From 1d8292c5abd112ddd66381a80d7e18b7700027f3 Mon Sep 17 00:00:00 2001 From: Vibhav Sreekanti Date: Sun, 20 Sep 2015 10:58:12 -0700 Subject: [PATCH] Support the AUTOINCREMENT keyword on SQLite. Omit the "PRIMARY KEY" clause at the end of the create statement if any column's SQL tags already contains the PRIMARY KEY constraint. --- scope_private.go | 11 ++++++++++- sqlite3.go | 5 ++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scope_private.go b/scope_private.go index f47c8433..fbcbc1fe 100644 --- a/scope_private.go +++ b/scope_private.go @@ -512,9 +512,18 @@ func (scope *Scope) createJoinTable(field *StructField) { func (scope *Scope) createTable() *Scope { var tags []string var primaryKeys []string + var primaryKeyInColumnType bool = false for _, field := range scope.GetStructFields() { if field.IsNormal { sqlTag := scope.generateSqlTag(field) + + // Check if the primary key constraint was specified as + // part of the column type. If so, we can only support + // one column as the primary key. + if strings.Contains(strings.ToLower(sqlTag), "primary key") { + primaryKeyInColumnType = true + } + tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag) } @@ -525,7 +534,7 @@ func (scope *Scope) createTable() *Scope { } var primaryKeyStr string - if len(primaryKeys) > 0 { + if len(primaryKeys) > 0 && !primaryKeyInColumnType { primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ",")) } scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v) %s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec() diff --git a/sqlite3.go b/sqlite3.go index 4584642e..96d798a0 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -15,10 +15,13 @@ func (sqlite3) SqlTag(value reflect.Value, size int, autoIncrease bool) string { case reflect.Bool: return "bool" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr: + if autoIncrease { + return "integer primary key autoincrement" + } return "integer" case reflect.Int64, reflect.Uint64: if autoIncrease { - return "integer" + return "integer primary key autoincrement" } return "bigint" case reflect.Float32, reflect.Float64: