File a_day_learn.go
package main
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Product struct {
ID uint `gorm:"primaryKey;default:auto_random()"`
Code string
Price uint
}
func main() {
dsn := "host=172.16.4.184 user=postgres password=itsasecret dbname=vy port=5432 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
fmt.Println(db, err)
db.AutoMigrate(&Product{})
insertProduct := &Product{Code: "D42", Price: 100}
db.Create(insertProduct)
fmt.Printf("insert ID: %d, Code: %s, Prict: %d\n",
insertProduct.ID, insertProduct.Code, insertProduct.Price)
readProduct := &Product{}
db.First(&readProduct, "code = ?", "D42") // find product with code D42
fmt.Printf("read ID: %d, Code: %s, Prict: %d\n",
readProduct.ID, readProduct.Code, readProduct.Price)
}
log
GOROOT=D:\Program Files\Go #gosetup
GOPATH=D:\vygopath;C:\Users\admin\go #gosetup
"D:\Program Files\Go\bin\go.exe" build -o C:\Users\admin\AppData\Local\Temp\GoLand\___1go_build_a_day_learn_go.exe C:\Users\admin\GolandProjects\awesomeProject1\a_day_learn.go #gosetup
C:\Users\admin\AppData\Local\Temp\GoLand\___1go_build_a_day_learn_go.exe
&{0xc0000f2510 <nil> 0 0xc0001b2000 1} <nil>
2023/02/23 16:22:50 C:/Users/admin/GolandProjects/awesomeProject1/a_day_learn.go:25 ERROR: multiple default values specified for column "id" of table "products" (SQLSTATE 42601)
[1.592ms] [rows:0] CREATE TABLE "products" ("id" bigserial DEFAULT auto_random(),"code" text,"price" bigint,PRIMARY KEY ("id"))
2023/02/23 16:22:50 C:/Users/admin/GolandProjects/awesomeProject1/a_day_learn.go:29 ERROR: relation "products" does not exist (SQLSTATE 42P01)
[3.108ms] [rows:0] INSERT INTO "products" ("code","price") VALUES ('D42',100) RETURNING "id"
insert ID: 0, Code: D42, Prict: 100
2023/02/23 16:22:50 C:/Users/admin/GolandProjects/awesomeProject1/a_day_learn.go:34 ERROR: relation "products" does not exist (SQLSTATE 42P01)
[1.051ms] [rows:0] SELECT * FROM "products" WHERE code = 'D42' ORDER BY "products"."id" LIMIT 1
read ID: 0, Code: , Prict: 0
Process finished with the exit code 0
Please guide me https://stackoverflow.com/questions/75542876/gorm-postgres-15-how-to-work-with-schema
Comment From: a631807682
I don’t know what is on your picture. In fact, we connect to the database through dsn and execute the sql to create the table. It is the same as you use psql. You can also use psql to execute query statements to verify it.
You can also view the migration log by
db.Logger = db.Logger.LogMode(logger.Info)