gsql

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildSQLUpdate

func BuildSQLUpdate(update any) (map[string]any, error)

BuildSQLUpdate

@Description: build Update struct into sql update map

@param update: Update struct

@return m: map of sql update

@return err:

@example:

    // model of table_abc
    type TableAbc struct {
        ID   int64  `gorm:"column:id"`
        Name string `gorm:"column:name"`
        Age  int    `gorm:"column:p_age"`
    }

    func (TableAbc) TableName() string {
    	return "table_abc"
    }

    // fields need to update. ⚠️  WARNING: must be pointers
    type TableAbcUpdate struct {
        Name *string `sql_field:"name"`
        Age  *int    `sql_field:"p_age"`
    }

    var name = "byte-er"
    attrs = TableAbcUpdate{
        Name: &name
    }

    // SQL: update table_abc set name="byte-er" where id = 1
	attrs, err := BuildSQLUpdate(attrs)
    if err != nil{
        // do something
    }
    if err := db.Model(TableAbc{}).Where("id = ?", id).Updates(attrs).Error; err != nil {
        logs.Error("update table abc failed: %s", err)
    }

func BuildSQLWhere

func BuildSQLWhere(where any) (query string, args []any, err error)

BuildSQLWhere

@Description: 将 Where model struct 编译为 sql 语句中 query 和 args

@param where: Where model

@return query:

@return args:

@return err:

@example

// model 表
type TableAbc struct {
	ID   int64  `gorm:"column:id"`
	Name string `gorm:"column:name"`
	Age  int    `gorm:"column:p_age"`
}

func (TableAbc) TableName() string {
	return "table_abc"
}

// 需要更新的字段
type TableAbcWhere struct {
	Name *string `sql_field:"name" sql_operator:"like"`
	Age  *int    `sql_field:"p_age"`
}

func example() {
	var name = "name%"
	var age = 20
	attrs := TableAbcWhere{
		Name: &name,
		Age:  &age,
	}

	query, args, err := BuildSQLWhere(attrs)
	if err != nil {
		// handle error
	}

	// 下面即 sql: update table_abc set name="byte-er" where id = 1
	if err := db.Find(&pos).Where(query, args...).Error; err != nil {
		logs.Error("fins table abc failed: %s", err)
	}
}

Types

type FieldExpr

type FieldExpr string // sql: field_1 > field_2, name field_2 需要使用 FieldExpr 类型

type Operator

type Operator func(data any) (operator string, placeholder string, arg any)

func GetOperatorMap

func GetOperatorMap(operatorKey string, data any) (Operator, error)

type OperatorFilter

type OperatorFilter func(data any) bool

type SQLUpdater

type SQLUpdater func(field string, data any) clause.Expr

SQLUpdater update SQL generator

Jump to

Keyboard shortcuts

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