orm

package
v0.0.0-...-d5bc55e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 7, 2023 License: MIT Imports: 6 Imported by: 0

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

View Source
const (
	DBDriverMySQL    = "mysql"
	DBDriverSqlite   = "sqlite"
	DBDriverPostgres = "postgres"
)

available database drivers

Variables

View Source
var DB *gorm.DB

DB is the global database instance

Functions

func ConnectDB

func ConnectDB(driver DBDriver, dsn string) (*gorm.DB, error)

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

func RegisterModel(m ...any) error

RegisterModel registers the given model to the database. Arguments should be pointers to model structs.

It calls gorm.AutoMigrate to migrate the database.

func UseDB

func UseDB(db *gorm.DB)

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 DBDriver

type DBDriver string

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL