From 9c179e47a16c8449e492d9d3f9f5131751ff7e31 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 1 Jun 2017 09:57:33 +0800 Subject: [PATCH] fix insert single pk column table failed (#603) --- session_insert.go | 26 ++++++++++++++++++-------- session_pk_test.go | 12 ++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/session_insert.go b/session_insert.go index 1b3f7fb9..93168c2e 100644 --- a/session_insert.go +++ b/session_insert.go @@ -343,15 +343,26 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) { if len(exprColVals) > 0 { colPlaces = colPlaces + strings.Join(exprColVals, ", ") } else { - colPlaces = colPlaces[0 : len(colPlaces)-2] + if len(colPlaces) > 0 { + colPlaces = colPlaces[0 : len(colPlaces)-2] + } } - sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)", - session.Engine.Quote(session.Statement.TableName()), - session.Engine.QuoteStr(), - strings.Join(colNames, session.Engine.Quote(", ")), - session.Engine.QuoteStr(), - colPlaces) + var sqlStr string + if len(colPlaces) > 0 { + sqlStr = fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)", + session.Engine.Quote(session.Statement.TableName()), + session.Engine.QuoteStr(), + strings.Join(colNames, session.Engine.Quote(", ")), + session.Engine.QuoteStr(), + colPlaces) + } else { + if session.Engine.dialect.DBType() == core.SQLITE || session.Engine.dialect.DBType() == core.POSTGRES { + sqlStr = fmt.Sprintf("INSERT INTO %s DEFAULT VALUES", session.Engine.Quote(session.Statement.TableName())) + } else { + sqlStr = fmt.Sprintf("INSERT INTO %s VALUES ()", session.Engine.Quote(session.Statement.TableName())) + } + } handleAfterInsertProcessorFunc := func(bean interface{}) { if session.IsAutoCommit { @@ -384,7 +395,6 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) { // for postgres, many of them didn't implement lastInsertId, so we should // implemented it ourself. if session.Engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 { - //assert table.AutoIncrement != "" res, err := session.query("select seq_atable.currval from dual", args...) if err != nil { return 0, err diff --git a/session_pk_test.go b/session_pk_test.go index 44ffb300..b9c70321 100644 --- a/session_pk_test.go +++ b/session_pk_test.go @@ -1105,3 +1105,15 @@ func TestMyStringId(t *testing.T) { panic(err) } } + +func TestSingleAutoIncrColumn(t *testing.T) { + type Account struct { + Id int64 `xorm:"pk autoincr"` + } + + assert.NoError(t, prepareEngine()) + assertSync(t, new(Account)) + + _, err := testEngine.Insert(&Account{}) + assert.NoError(t, err) +}