gsql

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 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 build Update struct into sql update map

💡 HINT:

⚠️ WARNING: fields of update must be pointers

🚀 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.
    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 build Where model struct into query & args in SQL

💡 HINT:

⚠️ WARNING:

🚀 example:

// model table
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 to be updated
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 need use FieldExpr type

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