ggorm

package
v1.1.33 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: MIT Imports: 20 Imported by: 0

README

ggorm

ggorm library wrapped in gorm, with added features such as tracer, paging queries, etc.

Support mysql, postgresql, tidb, sqlite.


Examples of use

mysql

Initializing the connection
    import (
        "github.com/18721889353/sunshine/pkg/ggorm"
    )

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

    // (1) connect to the database using the default settings
    db, err := ggorm.InitMysql(dsn)

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

Model
package model

import (
	"github.com/18721889353/sunshine/pkg/ggorm"
)

// UserExample object fields mapping table
type UserExample struct {
	ggorm.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 *UserExample) TableName() string {
	return ggorm.GetTableName(table)
}

Transaction
    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
    }

Postgresql

import (
   "github.com/18721889353/sunshine/pkg/ggorm"
   "github.com/18721889353/sunshine/pkg/utils"
)

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

	dsn := "root:123456@127.0.0.1:5432/test"
	dsn = utils.AdaptivePostgresqlDsn(dsn)
	db, err := ggorm.InitPostgresql(dsn, opts...)
	if err != nil {
		panic("ggorm.InitPostgresql error: " + err.Error())
	}
}

Tidb

Tidb is mysql compatible, just use InitMysql.


Sqlite

import (
   "github.com/18721889353/sunshine/pkg/ggorm"
)

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

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

gorm User Guide

Documentation

Overview

Package ggorm is a library wrapped on top of gorm.io/gorm, with added features such as link tracing, paging queries, etc.

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

This section is empty.

Functions

func CloseDB

func CloseDB(db *gorm.DB) error

CloseDB close gorm db

func CloseSQLDB

func CloseSQLDB(db *gorm.DB)

CloseSQLDB close sql db

func GetTableName

func GetTableName(object interface{}) string

GetTableName get table name

func InitMysql

func InitMysql(dsn string, opts ...Option) (*gorm.DB, error)

InitMysql init mysql or tidb

func InitPostgresql

func InitPostgresql(dsn string, opts ...Option) (*gorm.DB, error)

InitPostgresql init postgresql

func InitSqlite

func InitSqlite(dbFile string, opts ...Option) (*gorm.DB, error)

InitSqlite init sqlite

func InitTidb

func InitTidb(dsn string, opts ...Option) (*gorm.DB, error)

InitTidb init tidb

func NewCustomGormLogger

func NewCustomGormLogger(o *options) logger.Interface

NewCustomGormLogger custom gorm logger

Types

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 Option

type Option func(*options)

Option set the mysql options.

func WithConnMaxLifetime

func WithConnMaxLifetime(t time.Duration) Option

WithConnMaxLifetime set conn max lifetime

func WithEnableForeignKey

func WithEnableForeignKey() Option

WithEnableForeignKey use foreign keys

func WithEnableTrace

func WithEnableTrace() Option

WithEnableTrace use trace

func WithGormPlugin

func WithGormPlugin(plugins ...gorm.Plugin) Option

WithGormPlugin setting gorm plugin

func WithLogRequestIDKey

func WithLogRequestIDKey(key string) Option

WithLogRequestIDKey log request id

func WithLogging

func WithLogging(l *zap.Logger, level ...logger.LogLevel) Option

WithLogging set log sql, If l=nil, the gorm log library will be used

func WithMaxIdleConns

func WithMaxIdleConns(size int) Option

WithMaxIdleConns set max idle conns

func WithMaxOpenConns

func WithMaxOpenConns(size int) Option

WithMaxOpenConns set max open conns

func WithRWSeparation

func WithRWSeparation(slavesDsn []string, mastersDsn ...string) Option

WithRWSeparation setting read-write separation

func WithSlowThreshold

func WithSlowThreshold(d time.Duration) Option

WithSlowThreshold Set sql values greater than the threshold

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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