Hello,
i have following code:
package codelists
type MenuItemType struct {
ID int `json:"id" gorm:"primary_key"` // id
Code string `json:"code"` // code
Title string `json:"title"` // title
}
func (*MenuItemType) TableName() string {
return "menu_item_type"
}
and
package test
import (
"fmt"
"main/models/codelists"
"testing"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func TestSomething(t *testing.T) {
testDB, err := gorm.Open("postgres", "postgres://myUser:myPass@myURL:myPort/MyDB")
if err != nil {
fmt.Println(err)
}
menuItemType := codelists.MenuItemType{Code: "TEST", Title: "save_test"}
id := testDB.Save(&menuItemType)
fmt.Print(id)
}
and upon launching the test it writes following to the console output:
&{0xc0422362d0 pq: duplicate key value violates unique constraint "menu_item_type_code_key" 0 <nil> 0xc0421388f0 0xc042138840 0xc042136dc0 0 {0xc0420cbf40} <nil> false map[gorm:started_transaction0xc042068b900xc0421318c0:true] map[] false}PASS
ok test/dao 1.116s
I have tested this on multiple tables with multiple models and it happens everywhere (if there is no constraint it even inserts 2 rows with incremented id's).
I cannot see if I'm doing anyting wrong.
Is this possible bug?
Please help.
This means that you are trying to enter more than one record with an equality key. Test these two things
1 - make sure the database is empty
2 - try putting that sql: "auto_increment; primary_key; unique"
In the bank he created the int field but is inserting 0 every hour because there is no auto increment
Thanks. I will try as soon as i'm at home.
I'll write here how it ended.
It did not help, still getting double entries :(
Did you auto-migrate or changed the default value of field ID?
The sql flag is used for when you will create the database via script.
db.AutoMigrate(&MenuItemType{})
I'm not creating database from the code. I'm creating it with my own creation scripts.
I don't think it is a GORM problem, if it is, please create another issue with executable script like https://github.com/jinzhu/gorm/blob/master/CONTRIBUTING.md#executable-script-template