sgorm

package
v1.14.6 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2025 License: MIT Imports: 8 Imported by: 0

README

sgorm

sgorm is a library encapsulated on gorm, and added features such as tracer, paging queries, etc.

Support mysql, postgresql, sqlite.


Examples of use

Mysql

    import "github.com/go-dev-frame/sponge/pkg/sgorm/mysql"

    var dsn = "root:123456@(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"

    // case 1: connect to the database using the default settings
    db, err := mysql.Init(dsn)

    // case 2: customised settings to connect to the database
    db, err := mysql.Init(
        dsn,
        mysql.WithLogging(logger.Get()),  // print log
        mysql.WithLogRequestIDKey("request_id"),  // print request_id
        mysql.WithMaxIdleConns(5),
        mysql.WithMaxOpenConns(50),
        mysql.WithConnMaxLifetime(time.Minute*3),
        // mysql.WithSlowThreshold(time.Millisecond*100),  // only print logs that take longer than 100 milliseconds to execute
        // mysql.WithEnableTrace(),  // enable tracing
        // mysql.WithRWSeparation(SlavesDsn, MastersDsn...)  // read-write separation
        // mysql.WithGormPlugin(yourPlugin)  // custom gorm plugin
    )
    
    if err != nil {
        panic("mysql.Init error: " + err.Error())
    }

Postgresql

    import (
        "github.com/go-dev-frame/sponge/pkg/sgorm/postgresql"
        "github.com/go-dev-frame/sponge/pkg/utils"
    )

    func InitPostgresql() {
        opts := []postgresql.Option{
            postgresql.WithMaxIdleConns(10),
            postgresql.WithMaxOpenConns(100),
            postgresql.WithConnMaxLifetime(time.Duration(10) * time.Minute),
            postgresql.WithLogging(logger.Get()),
            postgresql.WithLogRequestIDKey("request_id"),
        }

        dsn := "root:123456@127.0.0.1:5432/test"  // or dsn := "host=127.0.0.1 user=root password=123456 dbname=account port=5432 sslmode=disable TimeZone=Asia/Shanghai"
        dsn = utils.AdaptivePostgresqlDsn(dsn)
        db, err := postgresql.Init(dsn, opts...)
        if err != nil {
            panic("postgresql.Init error: " + err.Error())
        }
    }

Tidb

Tidb is mysql compatible, just use mysql.Init.


Sqlite

    import "github.com/go-dev-frame/sponge/pkg/sgorm/sqlite"

    func InitSqlite() {
        opts := []sqlite.Option{
            sqlite.WithMaxIdleConns(10),
            sqlite.WithMaxOpenConns(100),
            sqlite.WithConnMaxLifetime(time.Duration(10) * time.Minute),
            sqlite.WithLogging(logger.Get()),
            sqlite.WithLogRequestIDKey("request_id"),
        }

        dbFile: = "test.db"
        db, err := sqlite.Init(dbFile, opts...)
        if err != nil {
            panic("sqlite.Init error: " + err.Error())
        }
    }

Transaction Example

    func createUser() error {
        // note that you should use tx as the database handle when you are in a transaction
        tx := db.Begin()
        defer func() {
            if err := recover(); err != nil { // rollback after a panic during transaction execution
                tx.Rollback()
                fmt.Printf("transaction failed, err = %v\n", err)
            }
        }()

        var err error
        if err = tx.Error; err != nil {
            return err
        }

        if err = tx.Where("id = ?", 1).First(table).Error; err != nil {
            tx.Rollback()
            return err
        }

        panic("mock panic")

        if err = tx.Create(&userExample{Name: "Mr Li", Age: table.Age + 2, Gender: "male"}).Error; err != nil {
            tx.Rollback()
            return err
        }

        return tx.Commit().Error
    }

Model Embedding Example

package model

import "github.com/go-dev-frame/sponge/pkg/sgorm"

// User object fields mapping table
type User struct {
    sgorm.Model `gorm:"embedded"`

    Name   string `gorm:"type:varchar(40);unique_index;not null" json:"name"`
    Age    int    `gorm:"not null" json:"age"`
    Gender string `gorm:"type:varchar(10);not null" json:"gender"`
}

// TableName get table name
func (table *User) TableName() string {
    return sgorm.GetTableName(table)
}

Gorm Guide

Documentation

Overview

Package sgorm is a library encapsulated on gorm.io/gorm

Index

Constants

View Source
const (
	// DBDriverMysql mysql driver
	DBDriverMysql = "mysql"
	// DBDriverPostgresql postgresql driver
	DBDriverPostgresql = "postgresql"
	// DBDriverTidb tidb driver
	DBDriverTidb = "tidb"
	// DBDriverSqlite sqlite driver
	DBDriverSqlite = "sqlite"
)

Variables

View Source
var ErrRecordNotFound = gorm.ErrRecordNotFound

Functions

func CloseDB

func CloseDB(db *gorm.DB) error

CloseDB close db

func GetTableName

func GetTableName(object interface{}) string

GetTableName get table name

func SetDriver added in v1.13.0

func SetDriver(driverName string)

SetDriver sets the name of the current database driver, such as "postgres" if you use postgres, you need to call SetDriver("postgres") after initializing gorm

Types

type BitBool added in v1.13.0

type BitBool = Bool

type Bool added in v1.12.2

type Bool bool

Bool is a custom type for MySQL bit(1) type and PostgreSQL boolean type.

func (*Bool) Scan added in v1.12.2

func (b *Bool) Scan(value interface{}) error

Scan implement Scanner interface to read values from database

func (Bool) Value added in v1.12.2

func (b Bool) Value() (driver.Value, error)

Value implement Valuer interface to write values to database

type DB

type DB = gorm.DB

type KV

type KV = map[string]interface{}

KV map type

type Model

type Model struct {
	ID        uint64         `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"`
	CreatedAt time.Time      `gorm:"column:created_at" json:"createdAt"`
	UpdatedAt time.Time      `gorm:"column:updated_at" json:"updatedAt"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"`
}

Model embedded structs, add `gorm: "embedded"` when defining table structs

type Model2

type Model2 struct {
	ID        uint64         `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"`
	CreatedAt time.Time      `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"`
}

Model2 embedded structs, json tag named is snake case

type TinyBool added in v1.13.0

type TinyBool bool

TinyBool is a custom type for MySQL tinyint(1) type

func (*TinyBool) Scan added in v1.13.0

func (b *TinyBool) Scan(value interface{}) error

Scan implement Scanner interface to read values from database

func (TinyBool) Value added in v1.13.0

func (b TinyBool) Value() (driver.Value, error)

Value implement Valuer interface to write values to database

Directories

Path Synopsis
Package dbclose provides a function to close gorm db.
Package dbclose provides a function to close gorm db.
Package glog provides a gorm logger implementation based on zap.
Package glog provides a gorm logger implementation based on zap.
Package mysql provides a gorm driver for mysql.
Package mysql provides a gorm driver for mysql.
Package postgresql provides a gorm driver for postgresql.
Package postgresql provides a gorm driver for postgresql.
Package query is a library of custom condition queries, support for complex conditional paging queries.
Package query is a library of custom condition queries, support for complex conditional paging queries.
Package sqlite provides a gorm driver for sqlite.
Package sqlite provides a gorm driver for sqlite.

Jump to

Keyboard shortcuts

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