sgorm

package
v1.1.26 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: MIT Imports: 5 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

Initializing the connection
    import "github.com/18721889353/sunshine/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
    gdb, 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/18721889353/sunshine/pkg/sgorm/postgresql"
        "github.com/18721889353/sunshine/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/18721889353/sunshine/pkg/sgorm/sqlite"

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

        dbFile: = "test.db"
        db, err := sgorm.Init(dbFile, opts...)
        if err != nil {
            panic("sgorm.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/18721889353/sunshine/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 User 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

Types

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

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