database

package
v2.41.1 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: CC0-1.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ActionInsert     = "insert"
	ActionUpdate     = "update"
	ActionUpsert     = "upsert"
	ActionDelete     = "delete"
	ActionBulkInsert = "bulk_insert"
	ActionBulkUpdate = "bulk_update"
	ActionUpdateById = "update_by_id"
	ActionDeleteById = "delete_by_id"

	MySQLEngine      = "mysql"
	NRMySQLEngine    = "nrmysql"
	PostgresEngine   = "postgres"
	NRPostgresEngine = "nrpostgres"

	LockShare  = "share"
	LockUpdate = "update"

	NewRelicAttributeQuery  = "query"
	NewRelicAttributeParams = "params"
)

Variables

This section is empty.

Functions

func EvictReadStmt added in v2.41.0

func EvictReadStmt(query string)

EvictReadStmt is the exported version for use by action package fast paths.

func EvictWriteStmt added in v2.41.0

func EvictWriteStmt(query string)

EvictWriteStmt removes a cached prepared statement (called on execution failure). Exported for use by action package fast paths.

func GenerateAddOnQuery

func GenerateAddOnQuery(ctx context.Context, reqData *TableRequest) (string, []interface{}, error)

func MySQLEngineGroupActive added in v2.41.0

func MySQLEngineGroupActive(engine string) (bool, bool)

MySQLEngineGroupActive returns whether the given engine is a MySQL variant.

func PutCUDConstructData added in v2.41.0

func PutCUDConstructData(d *CUDConstructData)

PutCUDConstructData returns a *CUDConstructData to the pool after resetting it.

func PutCUDResponse added in v2.41.0

func PutCUDResponse(c *CUDResponse)

PutCUDResponse returns a *CUDResponse to the pool after resetting it.

func PutQueryOpts added in v2.41.0

func PutQueryOpts(o *QueryOpts)

PutQueryOpts returns a *QueryOpts to the pool after resetting it.

func PutSelectResponse added in v2.41.0

func PutSelectResponse(s *SelectResponse)

PutSelectResponse returns a *SelectResponse to the pool after resetting it.

func PutTableRequest added in v2.41.0

func PutTableRequest(tr *TableRequest)

PutTableRequest returns a *TableRequest to the pool after resetting it.

Types

type BaseColumn

type BaseColumn[T string | int | int64] struct {
	Id T `json:"id" db:"id"`
	TimeCol
}

type CUDConstructData

type CUDConstructData struct {
	Cols       []string      `json:"cols"`
	Values     []interface{} `json:"values"`
	ColsInsert string
	BulkValues string
	BulkQuery  string
	Action     string
	TableName  string
}

func GetCUDConstructData added in v2.41.0

func GetCUDConstructData() *CUDConstructData

GetCUDConstructData retrieves a *CUDConstructData from the pool with all fields reset.

func (*CUDConstructData) SetValues

func (d *CUDConstructData) SetValues(value interface{})

type CUDResponse

type CUDResponse struct {
	Status       bool   `json:"status"`
	RowsAffected int64  `json:"rows_affected"`
	LastInsertID int64  `json:"last_insert_id"`
	Message      string `json:"message,omitempty"`
	// contains filtered or unexported fields
}

func GetCUDResponse added in v2.41.0

func GetCUDResponse() *CUDResponse

GetCUDResponse retrieves a *CUDResponse from the pool with all fields reset.

func (*CUDResponse) GetGeneratedQuery

func (e *CUDResponse) GetGeneratedQuery() map[string][]interface{}

GetGeneratedQuery - return query + params with format map[<query>]<params>

type Follower

type Follower interface {
	// Get from follower database
	Get(dest interface{}, query string, args ...interface{}) error

	// Select from follower database
	Select(dest interface{}, query string, args ...interface{}) error

	// Query from follower database
	Query(query string, args ...interface{}) (*sql.Rows, error)

	// NamedQuery do named query on follower DB
	NamedQuery(query string, arg interface{}) (*sqlx.Rows, error)

	// GetContext from sql database
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

	// SelectContext from sql database
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

	// QueryContext from sql database
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

	// QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.
	QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)

	// QueryRowxContext queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.
	QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row

	// NamedQueryContext do named query on follower DB
	NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error)
	// contains filtered or unexported methods
}

Follower defines operation that will be executed to follower DB

type ISQL added in v2.13.0

type ISQL interface {
	Master
	Follower
	GetTransaction() Transactions
	Read(ctx context.Context, opts *QueryOpts, additionalParams ...interface{}) error
	Write(ctx context.Context, opts *QueryOpts, isSoftDelete ...bool) (*CUDResponse, error)
	CachedRebind(query string) string
}

type Master

type Master interface {
	Exec(query string, args ...interface{}) (sql.Result, error)

	// ExecContext use master database to exec query
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

	// Begin transaction on master DB
	Begin() (*sql.Tx, error)
	// Begin transaction on master DB
	Beginx() (*sqlx.Tx, error)

	// BeginTx begins transaction on master DB
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

	// NamedExec do named exec on master DB
	NamedExec(query string, arg interface{}) (sql.Result, error)

	// NamedExecContext do named exec on master DB
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

	// BindNamed do BindNamed on master DB
	BindNamed(query string, arg interface{}) (string, []interface{}, error)

	Follower
}

type QueryOpts

type QueryOpts struct {
	BaseQuery         string
	Conditions        func(ctx context.Context) `json:"-"`
	ExcludeColumns    string
	Columns           string
	OptionalTableName string // for view name
	SelectRequest     *TableRequest
	CUDRequest        *CUDConstructData
	Result            interface{}
	IsList            bool
	UpsertInsertId    int64
	Trx               *sqlx.Tx
	LockingType       string
	UseMaster         bool
	// contains filtered or unexported fields
}

func GetQueryOpts added in v2.41.0

func GetQueryOpts() *QueryOpts

GetQueryOpts retrieves a *QueryOpts from the pool with all fields reset.

func (*QueryOpts) GetGeneratedQuery

func (e *QueryOpts) GetGeneratedQuery() map[string][]interface{}

GetGeneratedQuery - return query + params with format map[<query>]<params>

type ResponseMetaData

type ResponseMetaData struct {
	RequestParam  interface{} `json:"request_param"`
	TotalData     int64       `json:"total_data"`
	TotalFiltered int64       `json:"total_filtered"`
}

type SQL

type SQL struct {
	Master
	Follower
	// contains filtered or unexported fields
}

func Connect

func Connect() (*SQL, error)

func (*SQL) CachedRebind added in v2.41.0

func (this *SQL) CachedRebind(query string) string

CachedRebind returns the cached Rebind result for the given query string, computing and caching it on first access.

func (*SQL) CheckSQLWarning added in v2.41.0

func (this *SQL) CheckSQLWarning(ctx context.Context, query string, start time.Time, params ...interface{})

CheckSQLWarning is the exported version of checkSQLWarning for use by action package fast paths.

func (*SQL) Engine added in v2.41.0

func (this *SQL) Engine() string

Engine returns the database engine string (e.g. "mysql", "postgres", "nrmysql").

func (*SQL) Get added in v2.29.0

func (this *SQL) Get(dest interface{}, query string, args ...interface{}) error

func (*SQL) GetContext added in v2.29.0

func (this *SQL) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

func (*SQL) GetTransaction added in v2.13.0

func (this *SQL) GetTransaction() Transactions

func (*SQL) GetWriteStmt added in v2.41.0

func (this *SQL) GetWriteStmt(ctx context.Context, query string) (*sql.Stmt, error)

GetWriteStmt is the exported version of getWriteStmt for use by action package fast paths that bypass Write() entirely.

func (*SQL) IsPostgres added in v2.41.0

func (this *SQL) IsPostgres() bool

IsPostgres returns true if the engine is a PostgreSQL variant.

func (*SQL) NamedQuery added in v2.29.0

func (this *SQL) NamedQuery(query string, arg interface{}) (*sqlx.Rows, error)

func (*SQL) NamedQueryContext added in v2.29.0

func (this *SQL) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error)

NamedQueryContext do named query on follower DB

func (*SQL) Query added in v2.29.0

func (this *SQL) Query(query string, args ...interface{}) (*sql.Rows, error)

Query from follower database

func (*SQL) QueryContext added in v2.29.0

func (this *SQL) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

QueryContext from sql database

func (*SQL) QueryRow added in v2.13.1

func (this *SQL) QueryRow(query string, args ...interface{}) *sql.Row

func (*SQL) QueryRowContext added in v2.13.1

func (this *SQL) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*SQL) QueryRowx added in v2.28.0

func (this *SQL) QueryRowx(query string, args ...interface{}) *sqlx.Row

func (*SQL) QueryRowxContext added in v2.28.0

func (this *SQL) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row

func (*SQL) QueryxContext added in v2.29.0

func (this *SQL) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*SQL) Read

func (this *SQL) Read(ctx context.Context, opts *QueryOpts, additionalParams ...interface{}) error

func (*SQL) Rebind added in v2.13.1

func (this *SQL) Rebind(sql string) string

func (*SQL) Select added in v2.29.0

func (this *SQL) Select(dest interface{}, query string, args ...interface{}) error

Select from follower database

func (*SQL) SelectContext added in v2.29.0

func (this *SQL) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext from sql database

func (*SQL) SetEngine added in v2.41.0

func (this *SQL) SetEngine(engine string)

SetEngine sets the database engine (e.g. "mysql", "postgres", "nrmysql", "nrpostgres"). This is useful for testing and benchmarking where a SQL instance is created programmatically rather than via Connect().

func (*SQL) SetSlowQueryThreshold added in v2.41.0

func (this *SQL) SetSlowQueryThreshold(threshold float64)

SetSlowQueryThreshold sets the threshold in seconds above which queries are logged as slow. Set to a high value to effectively disable slow query logging during benchmarks.

func (*SQL) Write

func (this *SQL) Write(ctx context.Context, opts *QueryOpts, isSoftDelete ...bool) (*CUDResponse, error)

type SQLConfig

type SQLConfig struct {
	Username        string `yaml:"username"`
	Password        string `yaml:"password"`
	Host            string `yaml:"host"`
	Port            string `yaml:"port"`
	Engine          string `yaml:"engine"`
	DBName          string `yaml:"db_name"`
	Timeout         int    `yaml:"timeout"`
	MaxConnLifetime int    `yaml:"max_conn_lifetime"`
	MaxIdleTime     int    `yaml:"max_idle_time"`
	MaxOpenConn     int    `yaml:"max_open_conn"`
	MaxIdleConn     int    `yaml:"max_idle_conn"`
	ConnString      string `yaml:"conn_string"`
}

type SQLs

type SQLs struct {
	Master             SQLConfig `yaml:"master"`
	Follower           SQLConfig `yaml:"follower"`
	Timeout            int       `yaml:"timeout"`
	SlowQueryThreshold float64   `yaml:"slow_query_threshold"`
	EncryptionKey      string    `yaml:"encryption_key"`
}

type SelectResponse

type SelectResponse struct {
	Data interface{} `json:"data"`
	*ResponseMetaData
}

func GetSelectResponse added in v2.41.0

func GetSelectResponse() *SelectResponse

GetSelectResponse retrieves a *SelectResponse from the pool with all fields reset.

type TableRequest

type TableRequest struct {
	Keyword               string        `json:"keyword,omitempty" schema:"keyword"`
	SearchColsStr         string        `json:"search_cols,omitempty" schema:"search_cols"`
	SearchCols            []string      `json:"-"`
	Page                  int           `json:"page,omitempty" schema:"page"`
	Limit                 int           `json:"limit,omitempty" schema:"limit"`
	OrderBy               string        `json:"order_by,omitempty" schema:"order_by"`
	GroupBy               string        `json:"group_by,omitempty" schema:"group_by"`
	CreatedStart          string        `json:"date_start,omitempty" schema:"date_start"`
	CreatedEnd            string        `json:"date_end,omitempty" schema:"date_end"`
	CustomDateColFilter   string        `json:"-"` // specify this field manually at each of usecase services
	InitiateWhere         []string      `json:"-"` // will be defined manually at each of usecase services
	InitiateWhereValues   []interface{} `json:"-"` // will be defined manually at each of usecase services
	IncludeDeleted        bool          `json:"-"`
	NotContainsDeletedCol bool          `json:"-"`
	MainTableAlias        string        `json:"-"`
	IsDeleted             string        `json:"is_deleted,omitempty" schema:"is_deleted"`
	// contains filtered or unexported fields
}

func GetTableRequest added in v2.41.0

func GetTableRequest() *TableRequest

GetTableRequest retrieves a *TableRequest from the pool with all fields reset.

func (*TableRequest) SetWhereCondition

func (req *TableRequest) SetWhereCondition(condition string, value ...interface{})

type TimeCol

type TimeCol struct {
	CreatedAt string      `json:"created_at" db:"created_at"`
	UpdatedAt null.String `json:"updated_at" db:"updated_at"`
	DeletedAt null.String `json:"deleted_at" db:"deleted_at"`
}

type Transaction

type Transaction struct {
	// contains filtered or unexported fields
}

func NewTransaction

func NewTransaction(db Master) *Transaction

func (*Transaction) Begin

func (t *Transaction) Begin() (*sqlx.Tx, error)

func (*Transaction) Finish

func (t *Transaction) Finish(tx *sqlx.Tx, errTransaction error)

type Transactions

type Transactions interface {
	Begin() (*sqlx.Tx, error)
	Finish(tx *sqlx.Tx, errTransaction error)
}

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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