Import path:
gitlab.soludian.com/soludian/fountain/libs/stored/fql
fql
import "gitlab.soludian.com/soludian/fountain/libs/stored/fql"Index
- Constants
- Variables
- func AddVersionMigrateQuery(dbName string, vers ...any)
- func CalculateValue[T any](client *Client, query string, args ...any) T
- func CalculateValues[I comparable, C any](client *Client, query string, args ...any) map[I]C
- func CreateDefaultCtx() (context.Context, context.CancelFunc)
- func CreateIndexNameFromQuery(query string) string
- func CreateNameFromQuery(query string) string
- func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, avars ...any) string
- func In(query string, args ...any) (string, []any, error)
- func InitVersionMigrate(dbName string)
- func MigrateCreateAlertEnumKey(enum, action, name string) string
- func MigrateCreateAlertTableKey(tblName, name string) string
- func MigrateCreateDeleteDataKey(tblName string, name string) string
- func MigrateCreateEnumKey(enum string) string
- func MigrateCreateIndexKey(tblName, idxName string) string
- func MigrateCreateInsertDataKey(tblName string, name string) string
- func MigrateCreateTableKey(tblName string) string
- func MigrateCreateUpdateDataKey(tblName string, name string) string
- func QueryDataParser[T any](client *Client, query string, fnAfterParse func(*T) error, args ...any) *T
- func QueryDataParserContext[T any](client *Client, ctx context.Context, query string, fnAfterParse func(*T) error, args ...any) *T
- func QueryListDataParser[T any](client *Client, query string, fnAfterParse func(*T) error, args ...any) []*T
- func QueryListDataParserContext[T any](client *Client, ctx context.Context, query string, fnAfterParse func(*T) error, args ...any) []*T
- func WithActive(active int) lib_3rd.Option[config]
- func WithConfig(conf *config) lib_3rd.Option[config]
- func WithDSN(dsn string) lib_3rd.Option[config]
- func WithDriver(driver string) lib_3rd.Option[config]
- func WithEnvironment(environment string) lib_3rd.Option[config]
- func WithIdle(idle int) lib_3rd.Option[config]
- func WithName(name string) lib_3rd.Option[config]
- func WithOnFail(onFail string) lib_3rd.Option[config]
- type BaseDAO
- func (dao *BaseDAO) CreateStatement(conditions ...clause.Expression) *statement
- func (dao *BaseDAO) CreateStatementWithTx(tx *sqlx.Tx, conditions ...clause.Expression) *statement
- func (dao *BaseDAO) GetSchema() *schema.Schema
- func (dao *BaseDAO) Insert(data any) error
- func (dao *BaseDAO) InsertIgnoreConflict(data any) error
- func (dao *BaseDAO) InsertResult(data any) (sql.Result, error)
- func (dao *BaseDAO) InsertReturn(data any) (any, error)
- func (dao *BaseDAO) InsertTx(tx *sqlx.Tx, data any) error
- func (dao *BaseDAO) InsertTxIgnoreConflict(tx *sqlx.Tx, data any) error
- func (dao *BaseDAO) InsertTxResult(tx *sqlx.Tx, data any) (sql.Result, error)
- func (dao *BaseDAO) InsertTxReturn(tx *sqlx.Tx, data any) (any, error)
- func (dao *BaseDAO) InsertWithContext(ctx context.Context, data any) error
- func (dao *BaseDAO) SetDefaultTimeout(timeout time.Duration) *BaseDAO
- func (dao *BaseDAO) SetSchema(sch *schema.Schema)
- func (dao *BaseDAO) Update(data any) error
- func (dao *BaseDAO) UpdateFields(data any, fields ...string) error
- func (dao *BaseDAO) UpdateIgnoreConflict(data any) error
- func (dao *BaseDAO) UpdateResult(data any) (sql.Result, error)
- func (dao *BaseDAO) UpdateResultVal(data any) (int64, error)
- func (dao *BaseDAO) UpdateTx(tx *sqlx.Tx, data any) error
- func (dao *BaseDAO) UpdateTxFields(tx *sqlx.Tx, data any, fields ...string) error
- func (dao *BaseDAO) UpdateTxResult(tx *sqlx.Tx, data any) (sql.Result, error)
- func (dao *BaseDAO) UpdateWithContext(ctx context.Context, data any) error
- type CanTableNameInf
- type Client
- func InitMocking(dbConn *sql.DB, slaveAmount int) *Client
- func (client *Client) AddAutoVersionMigrateQuery(mds ...any)
- func (c *Client) Begin() (*sql.Tx, error)
- func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (c *Client) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)
- func (c *Client) Beginx() (*sqlx.Tx, error)
- func (c *Client) Close() error
- func (c *Client) DriverName() string
- func (c *Client) Exec(query string, args ...any) (sql.Result, error)
- func (c *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Client) Get(dest any, query string, args ...any) error
- func (c *Client) GetContext(ctx context.Context, dest any, query string, args ...any) error
- func (c *Client) GetMaster(dest any, query string, args ...any) error
- func (c *Client) GetMasterContext(ctx context.Context, dest any, query string, args ...any) error
- func (c *Client) Master() *sqlx.DB
- func (c *Client) MustBegin() *sqlx.Tx
- func (c *Client) MustExec(query string, args ...any) sql.Result
- func (c *Client) MustExecContext(ctx context.Context, query string, args ...any) sql.Result
- func (c *Client) NamedExec(query string, args any) (sql.Result, error)
- func (c *Client) NamedExecContext(ctx context.Context, query string, args any) (sql.Result, error)
- func (c *Client) NamedQuery(query string, args any) (*sqlx.Rows, error)
- func (c *Client) NamedQueryContext(ctx context.Context, query string, args any) (*sqlx.Rows, error)
- func (client *Client) NewBaseDAO(md any) *BaseDAO
- func (c *Client) PingContext(ctx context.Context) error
- func (c *Client) Prepare(query string) (*Stmt, error)
- func (c *Client) PrepareContext(ctx context.Context, query string) (*Stmt, error)
- func (c *Client) Preparex(query string) (*Stmtx, error)
- func (c *Client) PreparexContext(ctx context.Context, query string) (*Stmtx, error)
- func (c *Client) Query(query string, args ...any) (*sql.Rows, error)
- func (c *Client) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (c *Client) QueryRow(query string, args ...any) *sql.Row
- func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (c *Client) QueryRowx(query string, args ...any) *sqlx.Row
- func (c *Client) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row
- func (c *Client) Queryx(query string, args ...any) (*sqlx.Rows, error)
- func (c *Client) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)
- func (c *Client) Rebind(query string) string
- func (c *Client) RebindMaster(query string) string
- func (c *Client) Select(dest any, query string, args ...any) error
- func (c *Client) SelectContext(ctx context.Context, dest any, query string, args ...any) error
- func (c *Client) SelectMaster(dest any, query string, args ...any) error
- func (c *Client) SelectMasterContext(ctx context.Context, dest any, query string, args ...any) error
- func (c *Client) SetConnMaxLifetime(d time.Duration)
- func (c *Client) SetMaxIdleConns(n int)
- func (c *Client) SetMaxOpenConnections(max int)
- func (c *Client) Slave() *sqlx.DB
- type DBStatus
- type DriverBuilderInf
- type ModelID
- type ModelUUID
- type NamedExecutorInf
- type SchemaModelInf
- type Stmt
- type Stmtx
- func (st *Stmtx) Close() error
- func (st *Stmtx) Exec(args ...any) (sql.Result, error)
- func (st *Stmtx) ExecContext(ctx context.Context, args ...any) (sql.Result, error)
- func (st *Stmtx) Get(dest any, args ...any) error
- func (st *Stmtx) GetContext(ctx context.Context, dest any, args ...any) error
- func (st *Stmtx) GetMaster(dest any, args ...any) error
- func (st *Stmtx) GetMasterContext(ctx context.Context, dest any, args ...any) error
- func (st *Stmtx) MustExec(args ...any) sql.Result
- func (st *Stmtx) MustExecContext(ctx context.Context, args ...any) sql.Result
- func (st *Stmtx) Query(args ...any) (*sql.Rows, error)
- func (st *Stmtx) QueryContext(ctx context.Context, args ...any) (*sql.Rows, error)
- func (st *Stmtx) QueryMaster(args ...any) (*sql.Rows, error)
- func (st *Stmtx) QueryMasterContext(ctx context.Context, args ...any) (*sql.Rows, error)
- func (st *Stmtx) QueryRow(args ...any) *sql.Row
- func (st *Stmtx) QueryRowContext(ctx context.Context, args ...any) *sql.Row
- func (st *Stmtx) QueryRowMaster(args ...any) *sql.Row
- func (st *Stmtx) QueryRowMasterContext(ctx context.Context, args ...any) *sql.Row
- func (st *Stmtx) QueryRowx(args ...any) *sqlx.Row
- func (st *Stmtx) QueryRowxContext(ctx context.Context, args ...any) *sqlx.Row
- func (st *Stmtx) QueryRowxMaster(args ...any) *sqlx.Row
- func (st *Stmtx) QueryRowxMasterContext(ctx context.Context, args ...any) *sqlx.Row
- func (st *Stmtx) Queryx(args ...any) (*sqlx.Rows, error)
- func (st *Stmtx) QueryxContext(ctx context.Context, args ...any) (*sqlx.Rows, error)
- func (st *Stmtx) Select(dest any, args ...any) error
- func (st *Stmtx) SelectContext(ctx context.Context, dest any, args ...any) error
- func (st *Stmtx) SelectMaster(dest any, args ...any) error
- func (st *Stmtx) SelectMasterContext(ctx context.Context, dest any, args ...any) error
- type TableModelInf
- type VersionMD
- type VersionsDAO
- func NewVersionsDAO(client *Client) *VersionsDAO
- func (dao *VersionsDAO) MigrateExec(dbNames ...string) error
- func (dao *VersionsDAO) NamedInsert(executor NamedExecutorInf, ctx context.Context, ver *VersionMD) error
- func (dao *VersionsDAO) QueryAllHashIsExisted() map[string]bool
- func (dao *VersionsDAO) QueryAllNameIsExisted() map[string]bool
Constants
DNS Examples mysqlDSN = "fql:fql@tcp(localhost:9910)/fql?charset=utf8&parseTime=True&loc=Local" tidbDSN = "root:@tcp(localhost:9940)/test?charset=utf8&parseTime=True&loc=Local" // TiDB and mySQL using same drive postgresDSN = "user=fql password=fql dbname=fql host=localhost port=9920 sslmode=disable TimeZone=Asia/Shanghai" sqlserverDSN = "sqlserver://fql:LoremIpsum86@localhost:9930?database=fql" sqliteDSN = "file:test.db?cache=shared&mode=memory"
const (
DatabaseMySQL = "mysql" // Using for mysql, mariadb, tidb
DatabasePostgres = "postgres"
DatabaseSQLite = "sqlite3"
DatabaseSQLServer = "sqlserver"
)const (
KDefaultTimeout = 30 * time.Second
// KDriverPostgres using postgres driver
KDriverPostgres string = "postgres"
// KDriverMySQL using mysql driver
KDriverMySQL string = "mysql"
)const (
AutoRandomTag = "auto_random()" // Treated as an auto_random field for tidb
)const KPackageName = "fql"Variables
var (
// ErrRecordNotFound record not found error
ErrRecordNotFound = fmt.Errorf("record not found")
// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidTransaction = fmt.Errorf("invalid transaction")
// ErrNotImplemented not implemented
ErrNotImplemented = fmt.Errorf("not implemented")
// ErrMissingWhereClause missing where clause
ErrMissingWhereClause = fmt.Errorf("WHERE conditions required")
// ErrUnsupportedRelation unsupported relations
ErrUnsupportedRelation = fmt.Errorf("unsupported relations")
// ErrPrimaryKeyRequired primary keys required
ErrPrimaryKeyRequired = fmt.Errorf("primary key required")
// ErrModelValueRequired model value required
ErrModelValueRequired = fmt.Errorf("model value required")
// ErrModelAccessibleFieldsRequired model accessible fields required
ErrModelAccessibleFieldsRequired = fmt.Errorf("model accessible fields required")
// ErrSubQueryRequired sub query required
ErrSubQueryRequired = fmt.Errorf("sub query required")
// ErrInvalidData unsupported data
ErrInvalidData = fmt.Errorf("unsupported data")
// ErrUnsupportedDriver unsupported driver
ErrUnsupportedDriver = fmt.Errorf("unsupported driver")
// ErrRegistered registered
ErrRegistered = fmt.Errorf("registered")
// ErrInvalidField invalid field
ErrInvalidField = fmt.Errorf("invalid field")
// ErrEmptySlice empty slice found
ErrEmptySlice = fmt.Errorf("empty slice found")
// ErrDryRunModeUnsupported dry run mode unsupported
ErrDryRunModeUnsupported = fmt.Errorf("dry run mode unsupported")
// ErrInvalidDB invalid db
ErrInvalidDB = fmt.Errorf("invalid db")
// ErrInvalidValue invalid value
ErrInvalidValue = fmt.Errorf("invalid value, should be pointer to struct or slice")
// ErrInvalidValueOfLength invalid values do not match length
ErrInvalidValueOfLength = fmt.Errorf("invalid association values, length doesn't match")
// ErrPreloadNotAllowed preload is not allowed when count is used
ErrPreloadNotAllowed = fmt.Errorf("preload is not allowed when count is used")
// ErrDuplicatedKey occurs when there is a unique key constraint violation
ErrDuplicatedKey = fmt.Errorf("duplicated key not allowed")
// ErrForeignKeyViolated occurs when there is a foreign key constraint violation
ErrForeignKeyViolated = fmt.Errorf("violates foreign key constraint")
// ErrCheckConstraintViolated occurs when there is a check constraint violation
ErrCheckConstraintViolated = fmt.Errorf("violates check constraint")
)var GetFountainInstance = Lib.GetFountainInstancevar GetFountainManager = Lib.GetFountainManagerSử dụng khi config instance ở dạng key:value; Nếu config instance ở dạng key:array thì sử dụng hàm InstallFountainInstances Nếu config ở dạng key:array thì sẽ chỉ install config phần tử đầu tiên mà thôi
Install with config format <key>:<value>; eg: fql:<value>
Usage:
config.yaml:
fql:
name: default_name
...
code.go
fql.InstallFountainInstance()
fql.WithConfigKey("fql").InstallFountainInstance()var InstallFountainInstance = Lib.InstallFountainInstanceSử dụng khi config instance ở dạng key:array<value>; Sẽ luôn cố gắng khởi tạo kể cả khi config ở dạng key:value
Install with config format <key>:array<value>; eg: fql:array<value>
Usage:
config.yaml:
fql:
- name: default_name
...
code.go
fql.InstallFountainInstances()
fql.WithConfigKey("fql").InstallFountainInstances()var InstallFountainInstances = Lib.InstallFountainInstancesTruy cập thẳng tới bộ quản lý thư viện
var Lib = lib_3rd.NewLib(newClient, lib_3rd.WithDefaultConfigFunc[config, Client](DefaultConfig))var WithConfigKey = Lib.WithConfigKeyfunc AddVersionMigrateQuery
func AddVersionMigrateQuery(dbName string, vers ...any)Tạo tên cho migrate query: Tự động bổ sung thêm Table, Hash và CreatedTime
Usage:
AddVersionMigrateQuery("db_name", &VersionMD{
Name: MigrateCreateIndexKey("versions", "version_time"),
Query: `CREATE INDEX CONCURRENTLY ` + MigrateCreateIndexKey("versions", "version_time") + ` ON versions (created_time desc)`,
})func CalculateValue
func CalculateValue[T any](client *Client, query string, args ...any) TCalculateValue query and calculate data with query and args
Usage:
query := "select count(1) from tables"
count := fql.CalculateValue[int](conn, query, nil)func CalculateValues
func CalculateValues[I comparable, C any](client *Client, query string, args ...any) map[I]CCalculateValues query and calculate data with query and args
Usage:
query := "select id, count(1) from tables group by id"
mCount := fql.CalculateValues[string, int](conn, query, nil)func CreateDefaultCtx
func CreateDefaultCtx() (context.Context, context.CancelFunc)func CreateIndexNameFromQuery
func CreateIndexNameFromQuery(query string) stringTrả về tên index
func CreateNameFromQuery
func CreateNameFromQuery(query string) stringfunc ExplainSQL
func ExplainSQL(sql string, numericPlaceholder *regexp.Regexp, escaper string, avars ...any) stringExplainSQL generate SQL string with given parameters, the generated SQL is expected to be used in logger, execute it might introduce a SQL injection vulnerability
func In
func In(query string, args ...any) (string, []any, error)func InitVersionMigrate
func InitVersionMigrate(dbName string)func MigrateCreateAlertEnumKey
func MigrateCreateAlertEnumKey(enum, action, name string) stringTạo tên cho enum key: MigrateCreateAlertEnumKey("status", "add", "new_status") MigrateCreateAlertEnumKey("status", "drop", "old_status")
Usage:
fql.MigrateCreateAlertEnumKey("status", "add", "new_status")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateAlertEnumKey("status", "add", "new_status"),
Query: `ALTER TYPE status ADD VALUE 'new_status';`,
})func MigrateCreateAlertTableKey
func MigrateCreateAlertTableKey(tblName, name string) stringTạo tên cho alert table: MigrateCreateAlertTableKey("tbl_users", "change_alert_table")
Usage:
fql.MigrateCreateAlertTableKey("tbl_users", "change_alert_table")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateAlertTableKey("tbl_users", "change_alert_table"),
Query: `ALTER TABLE tbl_users ADD COLUMN change_alert_table BOOLEAN DEFAULT FALSE;`,
})func MigrateCreateDeleteDataKey
func MigrateCreateDeleteDataKey(tblName string, name string) stringTạo tên cho delete data: MigrateCreateDeleteDataKey("tbl_users", "admin")
Usage:
fql.MigrateCreateDeleteDataKey("tbl_users", "admin")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateDeleteDataKey("tbl_users", "admin"),
Query: `DELETE FROM tbl_users WHERE name = 'admin';`,
})func MigrateCreateEnumKey
func MigrateCreateEnumKey(enum string) stringTạo tên cho enum: MigrateCreateEnumKey("status")
Usage:
fql.MigrateCreateEnumKey("status")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateEnumKey("status"),
Query: `CREATE TYPE status AS ENUM ('active', 'inactive', 'deleted');`,
})func MigrateCreateIndexKey
func MigrateCreateIndexKey(tblName, idxName string) stringTạo tên cho index: MigrateCreateIndexKey("versions", "create_time") MigrateCreateIndexKey("versions", "uniq_create_time")
Usage:
fql.MigrateCreateIndexKey("versions", "create_time")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateIndexKey("versions", "version_time"),
Query: `CREATE INDEX CONCURRENTLY ` + fql.MigrateCreateIndexKey("versions", "version_time") + ` ON versions (created_time desc)`,
})func MigrateCreateInsertDataKey
func MigrateCreateInsertDataKey(tblName string, name string) stringTạo tên cho insert data: MigrateCreateInsertDataKey("tbl_users", "admin")
Usage:
fql.MigrateCreateInsertDataKey("tbl_users", "admin")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateInsertDataKey("tbl_users", "admin"),
Query: `INSERT INTO tbl_users (name, age) VALUES ('admin', 30);`,
})func MigrateCreateTableKey
func MigrateCreateTableKey(tblName string) stringformat: <tbl>_<table_name>_<action>_<resource> Tạo tên cho bảng: MigrateCreateIndexKey("versions", "create_time") MigrateCreateIndexKey("versions", "uniq_create_time")
Usage:
fql.MigrateCreateIndexKey("versions", "create_time")
// Or
fql.AddVersionMigrateQuery("dbName", &VersionMD{
Name: MigrateCreateTableKey("versions"),
Query: `CREATE TABLE public.versions...`,
})func MigrateCreateUpdateDataKey
func MigrateCreateUpdateDataKey(tblName string, name string) stringTạo tên cho update data: MigrateCreateUpdateDataKey("tbl_users", "admin")
Usage:
fql.MigrateCreateUpdateDataKey("tbl_users", "admin")
// Or
fql.AddVersionMigrateQuery("db_name", &VersionMD{
Name: fql.MigrateCreateUpdateDataKey("tbl_users", "admin"),
Query: `UPDATE tbl_users SET age = 31 WHERE name = 'admin';`,
})func QueryDataParser
func QueryDataParser[T any](client *Client, query string, fnAfterParse func(*T) error, args ...any) *TQueryDataParserContext query and parser one data with query and args, using fnAfterParse for the record
Usage:
query := "select value from tables where id = $1"
md, err := fql.QueryDataParser[models.T](conn, query, func(t *models.T) error {t.ID = id; return nil}, id)func QueryDataParserContext
func QueryDataParserContext[T any](client *Client, ctx context.Context, query string, fnAfterParse func(*T) error, args ...any) *TQueryDataParserContext query and parser one data with query and args in context, using fnAfterParse for the record
Usage:
query := "select value from tables where id = $1"
md, err := fql.QueryDataParserContext[models.T](conn, context.Background(), query, func(t *models.T) error {t.ID = id; return nil}, id)func QueryListDataParser
func QueryListDataParser[T any](client *Client, query string, fnAfterParse func(*T) error, args ...any) []*TQueryListDataParser query and parser multi data with query and args, using fnAfterParse for every records
Usage:
query := "select * from tables"
mds, err := fql.QueryListDataParser[models.T](conn, query, nil)func QueryListDataParserContext
func QueryListDataParserContext[T any](client *Client, ctx context.Context, query string, fnAfterParse func(*T) error, args ...any) []*TQueryListDataParserContext query and parser multi data with query and args in context, using fnAfterParse for every records
Usage:
query := "select * from tables"
mds, err := fql.QueryListDataParserContext[models.T](conn, context.Background(), query, nil)func WithActive
func WithActive(active int) lib_3rd.Option[config]func WithConfig
func WithConfig(conf *config) lib_3rd.Option[config]func WithDSN
func WithDSN(dsn string) lib_3rd.Option[config]DNS Examples mysqlDSN = "fql:fql@tcp(localhost:9910)/fql?charset=utf8&parseTime=True&loc=Local" tidbDSN = "root:@tcp(localhost:9940)/test?charset=utf8&parseTime=True&loc=Local" // TiDB and mySQL using same drive postgresDSN = "user=fql password=fql dbname=fql host=localhost port=9920 sslmode=disable TimeZone=Asia/Shanghai" sqlserverDSN = "sqlserver://fql:LoremIpsum86@localhost:9930?database=fql" sqliteDSN = "file:test.db?cache=shared&mode=memory"
func WithDriver
func WithDriver(driver string) lib_3rd.Option[config]func WithEnvironment
func WithEnvironment(environment string) lib_3rd.Option[config]func WithIdle
func WithIdle(idle int) lib_3rd.Option[config]func WithName
func WithName(name string) lib_3rd.Option[config]func WithOnFail
func WithOnFail(onFail string) lib_3rd.Option[config]panic or error, default is panic if not found any connections are active
type BaseDAO
Schema
type BaseDAO struct {
*Client
Timeout time.Duration // timeout
// contains filtered or unexported fields
}func (*BaseDAO) CreateStatement
func (dao *BaseDAO) CreateStatement(conditions ...clause.Expression) *statementfunc (*BaseDAO) CreateStatementWithTx
func (dao *BaseDAO) CreateStatementWithTx(tx *sqlx.Tx, conditions ...clause.Expression) *statementCreateStatementWithTx tạo statement với transaction executor. Tx chỉ tồn tại trong scope của statement, không ảnh hưởng đến BaseDAO.
func (*BaseDAO) GetSchema
func (dao *BaseDAO) GetSchema() *schema.Schemafunc (*BaseDAO) Insert
func (dao *BaseDAO) Insert(data any) errorDùng hàm InsertResult hoặc InsertReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) InsertIgnoreConflict
func (dao *BaseDAO) InsertIgnoreConflict(data any) errorDùng hàm InsertResult hoặc InsertReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) InsertResult
func (dao *BaseDAO) InsertResult(data any) (sql.Result, error)data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng.
func (*BaseDAO) InsertReturn
func (dao *BaseDAO) InsertReturn(data any) (any, error)data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng. returning values sẽ có kiểu dữ liệu tương ứng data đầu vào
func (*BaseDAO) InsertTx
func (dao *BaseDAO) InsertTx(tx *sqlx.Tx, data any) errorInsertTx thực hiện insert trong transaction.
func (*BaseDAO) InsertTxIgnoreConflict
func (dao *BaseDAO) InsertTxIgnoreConflict(tx *sqlx.Tx, data any) errorInsertTxIgnoreConflict thực hiện insert trong transaction, bỏ qua conflict.
func (*BaseDAO) InsertTxResult
func (dao *BaseDAO) InsertTxResult(tx *sqlx.Tx, data any) (sql.Result, error)InsertTxResult thực hiện insert trong transaction và trả về sql.Result.
func (*BaseDAO) InsertTxReturn
func (dao *BaseDAO) InsertTxReturn(tx *sqlx.Tx, data any) (any, error)InsertTxReturn thực hiện insert trong transaction và trả về returning values.
func (*BaseDAO) InsertWithContext
func (dao *BaseDAO) InsertWithContext(ctx context.Context, data any) errorDùng hàm InsertResult hoặc InsertReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) SetDefaultTimeout
func (dao *BaseDAO) SetDefaultTimeout(timeout time.Duration) *BaseDAOfunc (*BaseDAO) SetSchema
func (dao *BaseDAO) SetSchema(sch *schema.Schema)func (*BaseDAO) Update
func (dao *BaseDAO) Update(data any) errorDùng hàm UpdateResult hoặc UpdateReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) UpdateFields
func (dao *BaseDAO) UpdateFields(data any, fields ...string) errorDùng hàm UpdateResult hoặc UpdateReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng fields: []string - Danh sách các trường cần update
func (*BaseDAO) UpdateIgnoreConflict
func (dao *BaseDAO) UpdateIgnoreConflict(data any) errorDùng hàm InsertResult hoặc InsertReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) UpdateResult
func (dao *BaseDAO) UpdateResult(data any) (sql.Result, error)data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) UpdateResultVal
func (dao *BaseDAO) UpdateResultVal(data any) (int64, error)data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
func (*BaseDAO) UpdateTx
func (dao *BaseDAO) UpdateTx(tx *sqlx.Tx, data any) errorUpdateTx thực hiện update trong transaction.
func (*BaseDAO) UpdateTxFields
func (dao *BaseDAO) UpdateTxFields(tx *sqlx.Tx, data any, fields ...string) errorUpdateTxFields thực hiện update các trường chỉ định trong transaction.
func (*BaseDAO) UpdateTxResult
func (dao *BaseDAO) UpdateTxResult(tx *sqlx.Tx, data any) (sql.Result, error)UpdateTxResult thực hiện update trong transaction và trả về sql.Result.
func (*BaseDAO) UpdateWithContext
func (dao *BaseDAO) UpdateWithContext(ctx context.Context, data any) errorDùng hàm InsertResult hoặc InsertReturn để lấy kết quả trả về data: any - Có thể là đối tượng, list đối tượng hoặc map đối tượng
type CanTableNameInf
type CanTableNameInf interface {
TableName() string
}type Client
type Client struct {
sync.Mutex // Locker for length
// contains filtered or unexported fields
}func InitMocking
func InitMocking(dbConn *sql.DB, slaveAmount int) *ClientInitMocking initialize the dbConnection mocking
func (*Client) AddAutoVersionMigrateQuery
func (client *Client) AddAutoVersionMigrateQuery(mds ...any)Tạo câu migrate query tự động từ đối tượng:
Usage:
fql.GetFountainInstance("db_name").AddVersionMigrateQuery(&VersionMD{})func (*Client) Begin
func (c *Client) Begin() (*sql.Tx, error)Begin sql transaction
func (*Client) BeginTx
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)BeginTx return sql.Tx
func (*Client) BeginTxx
func (c *Client) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)BeginTxx return sqlx.Tx
func (*Client) Beginx
func (c *Client) Beginx() (*sqlx.Tx, error)Beginx sqlx transaction
func (*Client) Close
func (c *Client) Close() errorClose closes all database connections
func (*Client) DriverName
func (c *Client) DriverName() stringTrả về tên driver đang sử dụng: mysql, postgres, sqlite3, sqlserver,..
func (*Client) Exec
func (c *Client) Exec(query string, args ...any) (sql.Result, error)Exec using master db
func (*Client) ExecContext
func (c *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)ExecContext using master db
func (*Client) Get
func (c *Client) Get(dest any, query string, args ...any) errorGet using slave.
func (*Client) GetContext
func (c *Client) GetContext(ctx context.Context, dest any, query string, args ...any) errorGetContext using slave.
func (*Client) GetMaster
func (c *Client) GetMaster(dest any, query string, args ...any) errorGetMaster using master.
func (*Client) GetMasterContext
func (c *Client) GetMasterContext(ctx context.Context, dest any, query string, args ...any) errorGetMasterContext using master.
func (*Client) Master
func (c *Client) Master() *sqlx.DBMaster return master database
func (*Client) MustBegin
func (c *Client) MustBegin() *sqlx.TxMustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead of an *sql.Tx.
func (*Client) MustExec
func (c *Client) MustExec(query string, args ...any) sql.ResultMustExec (panic) runs MustExec using master database.
func (*Client) MustExecContext
func (c *Client) MustExecContext(ctx context.Context, query string, args ...any) sql.ResultMustExecContext (panic) runs MustExec using master database.
func (*Client) NamedExec
func (c *Client) NamedExec(query string, args any) (sql.Result, error)Exec using master db
func (*Client) NamedExecContext
func (c *Client) NamedExecContext(ctx context.Context, query string, args any) (sql.Result, error)NamedExecContext using master db
func (*Client) NamedQuery
func (c *Client) NamedQuery(query string, args any) (*sqlx.Rows, error)Queryx queries the database and returns an *sqlx.Rows.
func (*Client) NamedQueryContext
func (c *Client) NamedQueryContext(ctx context.Context, query string, args any) (*sqlx.Rows, error)NamedQueryContext queries the database and returns an *sqlx.Rows.
func (*Client) NewBaseDAO
func (client *Client) NewBaseDAO(md any) *BaseDAOfunc (*Client) PingContext
func (c *Client) PingContext(ctx context.Context) errorPingContext database
func (*Client) Prepare
func (c *Client) Prepare(query string) (*Stmt, error)Prepare return sql stmt
func (*Client) PrepareContext
func (c *Client) PrepareContext(ctx context.Context, query string) (*Stmt, error)PrepareContext return sql stmt
func (*Client) Preparex
func (c *Client) Preparex(query string) (*Stmtx, error)Preparex sqlx stmt
func (*Client) PreparexContext
func (c *Client) PreparexContext(ctx context.Context, query string) (*Stmtx, error)PreparexContext sqlx stmt
func (*Client) Query
func (c *Client) Query(query string, args ...any) (*sql.Rows, error)Query queries the database and returns an *sql.Rows.
func (*Client) QueryContext
func (c *Client) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)QueryContext queries the database and returns an *sql.Rows.
func (*Client) QueryRow
func (c *Client) QueryRow(query string, args ...any) *sql.RowQueryRow queries the database and returns an *sqlx.Row.
func (*Client) QueryRowContext
func (c *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.RowQueryRowContext queries the database and returns an *sqlx.Row.
func (*Client) QueryRowx
func (c *Client) QueryRowx(query string, args ...any) *sqlx.RowQueryRowx queries the database and returns an *sqlx.Row.
func (*Client) QueryRowxContext
func (c *Client) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.RowQueryRowxContext queries the database and returns an *sqlx.Row.
func (*Client) Queryx
func (c *Client) Queryx(query string, args ...any) (*sqlx.Rows, error)Queryx queries the database and returns an *sqlx.Rows.
func (*Client) QueryxContext
func (c *Client) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)QueryxContext queries the database and returns an *sqlx.Rows.
func (*Client) Rebind
func (c *Client) Rebind(query string) stringRebind query
func (*Client) RebindMaster
func (c *Client) RebindMaster(query string) stringRebindMaster will rebind query for master
func (*Client) Select
func (c *Client) Select(dest any, query string, args ...any) errorSelect using slave db.
func (*Client) SelectContext
func (c *Client) SelectContext(ctx context.Context, dest any, query string, args ...any) errorSelectContext using slave db.
func (*Client) SelectMaster
func (c *Client) SelectMaster(dest any, query string, args ...any) errorSelectMaster using master db.
func (*Client) SelectMasterContext
func (c *Client) SelectMasterContext(ctx context.Context, dest any, query string, args ...any) errorSelectMasterContext using master db.
func (*Client) SetConnMaxLifetime
func (c *Client) SetConnMaxLifetime(d time.Duration)SetConnMaxLifetime sets the maximum amount of time a connection may be reused. Expired connections may be closed lazily before reuse. If d <= 0, connections are reused forever.
func (*Client) SetMaxIdleConns
func (c *Client) SetMaxIdleConns(n int)SetMaxIdleConns sets the maximum number of connections in the idle connection pool for all connections
func (*Client) SetMaxOpenConnections
func (c *Client) SetMaxOpenConnections(max int)SetMaxOpenConnections to set max connections
func (*Client) Slave
func (c *Client) Slave() *sqlx.DBSlave return slave database
type DBStatus
DBStatus for status response
type DBStatus struct {
Name string `json:"name"`
Connected bool `json:"connected"`
LastActive string `json:"last_active"`
Error any `json:"error"`
}type DriverBuilderInf
type DriverBuilderInf interface {
GetCreateTableClauses() []string // []string{"CREATE TABLE IF NOT EXISTS"}
GetCreateClauses() []string // []string{"INSERT", "VALUES", "ON CONFLICT", "RETURNING"}
GetQueryClauses() []string // []string{"SELECT", "FROM", "WHERE", "GROUP BY", "ORDER BY", "LIMIT", "FOR"}
GetUpdateClauses() []string // []string{"UPDATE", "SET", "WHERE"}
GetDeleteClauses() []string // []string{"DELETE", "FROM", "WHERE"}
DataTypeOf(field *schema.Field) string
DefaultValueOf(field *schema.Field) clause.Expression
BindVarTo(stmt *statement, v any)
QuoteTo(stmt *statement, s string)
Explain(sql string, vars ...any) string
}type ModelID
Model a basic GoLang struct which includes the following fields: ID, CreatedTime, UpdatedTime It may be embedded into your model or you may build your own model without it
type User struct {
fql.Model
}type ModelID struct {
ID string `fql:"primary_key"`
CreatedTime int32
UpdatedTime int32
}type ModelUUID
type ModelUUID struct {
UUID string `fql:"uuid"`
CreatedTime int32
UpdatedTime int32
}type NamedExecutorInf
type NamedExecutorInf interface {
NamedExecContext(ctx context.Context, query string, args any) (sql.Result, error)
}type SchemaModelInf
type SchemaModelInf interface {
SchemaName() string
}type Stmt
Stmt implement sql stmt
type Stmt struct {
// contains filtered or unexported fields
}func (*Stmt) Close
func (st *Stmt) Close() errorClose stmt
func (*Stmt) Exec
func (st *Stmt) Exec(args ...any) (sql.Result, error)Exec will always go to production
func (*Stmt) Query
func (st *Stmt) Query(args ...any) (*sql.Rows, error)Query will always go to slave
func (*Stmt) QueryMaster
func (st *Stmt) QueryMaster(args ...any) (*sql.Rows, error)QueryMaster will use master db
func (*Stmt) QueryRow
func (st *Stmt) QueryRow(args ...any) *sql.RowQueryRow will always go to slave
func (*Stmt) QueryRowMaster
func (st *Stmt) QueryRowMaster(args ...any) *sql.RowQueryRowMaster will use master db
type Stmtx
Stmtx implement sqlx stmt
type Stmtx struct {
// contains filtered or unexported fields
}func (*Stmtx) Close
func (st *Stmtx) Close() errorClose all dbs connection
func (*Stmtx) Exec
func (st *Stmtx) Exec(args ...any) (sql.Result, error)Exec will always go to production
func (*Stmtx) ExecContext
func (st *Stmtx) ExecContext(ctx context.Context, args ...any) (sql.Result, error)ExecContext will always go to production
func (*Stmtx) Get
func (st *Stmtx) Get(dest any, args ...any) errorGet will always go to slave
func (*Stmtx) GetContext
func (st *Stmtx) GetContext(ctx context.Context, dest any, args ...any) errorGetContext will always go to slave
func (*Stmtx) GetMaster
func (st *Stmtx) GetMaster(dest any, args ...any) errorGetMaster will always go to master
func (*Stmtx) GetMasterContext
func (st *Stmtx) GetMasterContext(ctx context.Context, dest any, args ...any) errorGetMasterContext will always go to master
func (*Stmtx) MustExec
func (st *Stmtx) MustExec(args ...any) sql.ResultMustExec using master database
func (*Stmtx) MustExecContext
func (st *Stmtx) MustExecContext(ctx context.Context, args ...any) sql.ResultMustExecContext using master database
func (*Stmtx) Query
func (st *Stmtx) Query(args ...any) (*sql.Rows, error)Query will always go to slave
func (*Stmtx) QueryContext
func (st *Stmtx) QueryContext(ctx context.Context, args ...any) (*sql.Rows, error)QueryContext will always go to slave
func (*Stmtx) QueryMaster
func (st *Stmtx) QueryMaster(args ...any) (*sql.Rows, error)QueryMaster will use master db
func (*Stmtx) QueryMasterContext
func (st *Stmtx) QueryMasterContext(ctx context.Context, args ...any) (*sql.Rows, error)QueryMasterContext will use master db
func (*Stmtx) QueryRow
func (st *Stmtx) QueryRow(args ...any) *sql.RowQueryRow will always go to slave
func (*Stmtx) QueryRowContext
func (st *Stmtx) QueryRowContext(ctx context.Context, args ...any) *sql.RowQueryRowContext will always go to slave
func (*Stmtx) QueryRowMaster
func (st *Stmtx) QueryRowMaster(args ...any) *sql.RowQueryRowMaster will use master db
func (*Stmtx) QueryRowMasterContext
func (st *Stmtx) QueryRowMasterContext(ctx context.Context, args ...any) *sql.RowQueryRowMasterContext will use master db
func (*Stmtx) QueryRowx
func (st *Stmtx) QueryRowx(args ...any) *sqlx.RowQueryRowx will always go to slave
func (*Stmtx) QueryRowxContext
func (st *Stmtx) QueryRowxContext(ctx context.Context, args ...any) *sqlx.RowQueryRowxContext will always go to slave
func (*Stmtx) QueryRowxMaster
func (st *Stmtx) QueryRowxMaster(args ...any) *sqlx.RowQueryRowxMaster will always go to master
func (*Stmtx) QueryRowxMasterContext
func (st *Stmtx) QueryRowxMasterContext(ctx context.Context, args ...any) *sqlx.RowQueryRowxMasterContext will always go to master
func (*Stmtx) Queryx
func (st *Stmtx) Queryx(args ...any) (*sqlx.Rows, error)Queryx will always go to slave
func (*Stmtx) QueryxContext
func (st *Stmtx) QueryxContext(ctx context.Context, args ...any) (*sqlx.Rows, error)QueryxContext will always go to slave
func (*Stmtx) Select
func (st *Stmtx) Select(dest any, args ...any) errorSelect will always go to slave
func (*Stmtx) SelectContext
func (st *Stmtx) SelectContext(ctx context.Context, dest any, args ...any) errorSelectContext will always go to slave
func (*Stmtx) SelectMaster
func (st *Stmtx) SelectMaster(dest any, args ...any) errorSelectMaster will always go to master
func (*Stmtx) SelectMasterContext
func (st *Stmtx) SelectMasterContext(ctx context.Context, dest any, args ...any) errorSelectMasterContext will always go to master
type TableModelInf
type TableModelInf interface {
TableName() string
}type VersionMD
type VersionMD struct {
ID int `db:"id" json:"id,omitempty"` // ID tự tăng
Name string `db:"name" json:"name,omitempty"` // Format: "<object_name>_<action/object>" eg: tbl_version_init, tbl_version_idx_create_time
Table string `db:"table_name" json:"table_name,omitempty"`
Query string `db:"query" json:"query,omitempty"`
Hash string `db:"hash" json:"hash,omitempty"` // Hash with sha256 -> 32byte ~ 64 characters
PreFunc func(tx *sqlx.Tx) error `db:"-" json:"-"` // Nếu Query mà rỗng thì query sẽ được gán bằng Name trước khi Action được thực thi, nếu Query khác rỗng, Name sẽ được bổ sung thêm hậu tố _call_pre_func
PostFunc func(dao *VersionsDAO) error `db:"-" json:"-"` // Nếu Query mà rỗng thì query sẽ được gán bằng Name sau khi Action được thực thi, nếu Query khác rỗng, Name sẽ được bổ sung thêm hậu tố _call_post_func
CreatedTime int32 `db:"created_time" json:"created_time,omitempty"`
CreatedAt string `db:"created_at" json:"created_at,omitempty"`
AvailableDB []string `db:"-" json:"available_db,omitempty"` // Available DB to run this query: mssql, mysql, postgresql, postgres, sqlite
}func (*VersionMD) AddAvailableDB
func (md *VersionMD) AddAvailableDB(driverName ...string) *VersionMDfunc (*VersionMD) HashQuery
func (md *VersionMD) HashQuery() *VersionMDfunc (*VersionMD) IsAvailableDB
func (md *VersionMD) IsAvailableDB(driverName string) boolNếu danh sách available db rỗng thì luôn trả về true
type VersionsDAO
type VersionsDAO struct {
*BaseDAO
}func NewVersionsDAO
func NewVersionsDAO(client *Client) *VersionsDAOfunc (*VersionsDAO) MigrateExec
func (dao *VersionsDAO) MigrateExec(dbNames ...string) errorfunc (*VersionsDAO) NamedInsert
func (dao *VersionsDAO) NamedInsert(executor NamedExecutorInf, ctx context.Context, ver *VersionMD) errorfunc (*VersionsDAO) QueryAllHashIsExisted
func (dao *VersionsDAO) QueryAllHashIsExisted() map[string]boolfunc (*VersionsDAO) QueryAllNameIsExisted
func (dao *VersionsDAO) QueryAllNameIsExisted() map[string]boolGenerated by gomarkdoc