Documentation ¶
Overview ¶
Package orm wraps the gorm to provide a simple ORM layer.
It contains a Model interface. All your models (for crud operations) should implement it. And there is a BasicModel struct implements Model. You can embed it into your model.
Call the ConnectDB() function to connect to the database. And call RegisterModel() to register your models.
Index ¶
Constants ¶
const ( DBDriverMySQL = "mysql" DBDriverSqlite = "sqlite" DBDriverPostgres = "postgres" )
available database drivers
Variables ¶
var DB *gorm.DB
DB is the global database instance
Functions ¶
func ConnectDB ¶
ConnectDB connects to the database and initializes the global crud.DB instance. The driver should be one of the following:
DBDriverMySQL, DBDriverSqlite, DBDriverPostgres
And the dsn is depends on the driver:
- DBDriverSqlite: gorm.db
- DBDriverMySQL: user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local
- DBDriverPostgres: host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai
See GORM docs for more information: - https://gorm.io/docs/connecting_to_the_database.html
func RegisterModel ¶
RegisterModel registers the given model to the database. Arguments should be pointers to model structs.
It calls gorm.AutoMigrate to migrate the database.
Types ¶
type BasicModel ¶
type BasicModel struct { ID uint `gorm:"primarykey"` CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` }
BasicModel implements Model interface with an auto increment primary key ID.
BasicModel is actually the gorm.Model struct which contains the following fields:
ID, CreatedAt, UpdatedAt, DeletedAt
It is a good idea to embed this struct as the base struct for all models:
type User struct { orm.BasicModel }
func (BasicModel) Identity ¶
func (m BasicModel) Identity() (fieldName string, value any)
type DBOpener ¶
DBOpener opens a gorm Dialector.
See:
- gorm.io/driver/mysql: https://github.com/go-gorm/mysql/blob/f46a79cf94a9d67edcc7d5f6f2606e21bf6525fe/mysql.go#L52
- gorm.io/driver/postgres: https://github.com/go-gorm/postgres/blob/c2cfceb161687324cb399c9f60ec775428335957/postgres.go#L31
- gorm.io/driver/sqlite: https://github.com/go-gorm/sqlite/blob/1d1e7723862758a6e6a860f90f3e7a3bea9cc94a/sqlite.go#L28
type Model ¶
type Model interface { // Identity returns the primary key field of the model. // A very common case is that the primary key field is ID. Identity() (fieldName string, value any) }
Model is the interface for all models. It only requires an Identity() method to return the primary key field name and value.