From 608fd976c4a9cbad05681d5dc6b4602be30c8fec Mon Sep 17 00:00:00 2001 From: Christophe de Vienne Date: Mon, 20 Jun 2016 15:00:19 +0200 Subject: [PATCH] Fix auto_increment on postgres database. --- create_test.go | 12 ++++++++++++ migration_test.go | 1 + model_struct.go | 4 ++++ 3 files changed, 17 insertions(+) diff --git a/create_test.go b/create_test.go index dc82de50..28a049f4 100644 --- a/create_test.go +++ b/create_test.go @@ -57,6 +57,18 @@ func TestCreate(t *testing.T) { } } +func TestCreateWithAutoIncrement(t *testing.T) { + user1 := User{} + user2 := User{} + + DB.Create(&user1) + DB.Create(&user2) + + if user2.Sequence-user1.Sequence != 1 { + t.Errorf("Auto increment should apply on Sequence") + } +} + func TestCreateWithNoGORMPrimayKey(t *testing.T) { if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" { t.Skip("Skipping this because MSSQL will return identity only if the table has an Id column") diff --git a/migration_test.go b/migration_test.go index 592dadb7..ec33efc1 100644 --- a/migration_test.go +++ b/migration_test.go @@ -33,6 +33,7 @@ type User struct { Company Company Role PasswordHash []byte + Sequence uint `gorm:"AUTO_INCREMENT"` IgnoreMe int64 `sql:"-"` IgnoreStringSlice []string `sql:"-"` Ignored struct{ Name string } `sql:"-"` diff --git a/model_struct.go b/model_struct.go index eb3762f4..d8f9ed1b 100644 --- a/model_struct.go +++ b/model_struct.go @@ -175,6 +175,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct { field.HasDefaultValue = true } + if _, ok := field.TagSettings["AUTO_INCREMENT"]; ok { + field.HasDefaultValue = true + } + indirectType := fieldStruct.Type for indirectType.Kind() == reflect.Ptr { indirectType = indirectType.Elem()