Setting PostgreSQL functions as default values for fields in GORM is typically used to automatically populate those fields during record insertion, such as timestamps or values calculated based on other fields. In GORM, you can achieve this by using the gorm:"default:..." tag in your model definition. The following are specific steps and an example:
Steps
- Define the model: First, define your data model in Go and specify the field attributes.
- Use the
defaulttag: Use thedefaulttag in the field tag of your model to specify a PostgreSQL function as the default value. - Migrate the database: Use GORM's migration tool to apply the model changes to the database.
Example
Suppose we have a User model, and we want to automatically set the created_at field's default value to the current time using PostgreSQL's now() function. The model definition is as follows:
gopackage main import ( "gorm.io/gorm" "gorm.io/driver/postgres" "log" ) type User struct { gorm.Model Name string CreatedAt time.Time `gorm:"default:now()"` } func main() { // Connect to the database dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { log.Fatal(err) } // Auto-migrate db.AutoMigrate(&User{}) // Insert example user user := User{Name: "张三"} db.Create(&user) }
In this example, when a new User is created and inserted into the database, the CreatedAt field will automatically be set to the current time using PostgreSQL's now() function, without manually setting it at the application level.
Notes
- Ensure that the PostgreSQL function is valid in the database; otherwise, it will cause errors.
- After migration, check the generated SQL to ensure the
defaultvalue is correctly set. - Using database functions as default values can reduce application-level code complexity, but ensure the logic meets business requirements.
By setting it up this way, you can leverage database-layer functionality to simplify application code and ensure data consistency and correctness.