sq

package
v0.0.602 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CommentTrimmer = NewPreListener(fnTrimComments)
View Source
var ConverterBoolToBit = NewDBTypeConverter[bool, int64](func(v bool) (int64, error) {
	return langext.Conditional(v, int64(1), int64(0)), nil
}, func(v int64) (bool, error) {
	if v == 0 {
		return false, nil
	}
	if v == 1 {
		return true, nil
	}
	return false, errors.New(fmt.Sprintf("invalid valud for boolean: '%d'", v))
})
View Source
var ConverterExErrCategoryToString = NewDBTypeConverter[exerr.ErrorCategory, string](func(v exerr.ErrorCategory) (string, error) {
	return v.Category, nil
}, func(v string) (exerr.ErrorCategory, error) {
	for _, cat := range exerr.AllCategories {
		if cat.Category == v {
			return cat, nil
		}
	}
	return exerr.CatUser, errors.New("failed to convert '" + v + "' to exerr.ErrorCategory")
})
View Source
var ConverterExErrSeverityToString = NewDBTypeConverter[exerr.ErrorSeverity, string](func(v exerr.ErrorSeverity) (string, error) {
	return v.Severity, nil
}, func(v string) (exerr.ErrorSeverity, error) {
	for _, sev := range exerr.AllSeverities {
		if sev.Severity == v {
			return sev, nil
		}
	}
	return exerr.SevErr, errors.New("failed to convert '" + v + "' to exerr.ErrorSeverity")
})
View Source
var ConverterExErrTypeToString = NewDBTypeConverter[exerr.ErrorType, string](func(v exerr.ErrorType) (string, error) {
	return v.Key, nil
}, func(v string) (exerr.ErrorType, error) {
	for _, etp := range exerr.ListRegisteredTypes() {
		if etp.Key == v {
			return etp, nil
		}
	}

	return exerr.NewType(v, nil), nil
})
View Source
var ConverterJsonArrToString = NewAutoDBTypeConverter(JsonArr{})
View Source
var ConverterJsonObjToString = NewAutoDBTypeConverter(JsonObj{})
View Source
var ConverterRFC339NanoTimeToString = NewDBTypeConverter[rfctime.RFC3339NanoTime, string](func(v rfctime.RFC3339NanoTime) (string, error) {
	return v.Time().In(time.UTC).Format("2006-01-02 15:04:05.999999999"), nil
}, func(v string) (rfctime.RFC3339NanoTime, error) {
	t, err := time.ParseInLocation("2006-01-02 15:04:05.999999999", v, time.UTC)
	if err != nil {
		return rfctime.RFC3339NanoTime{}, err
	}
	return rfctime.NewRFC3339Nano(t), nil
})

ConverterRFC339NanoTimeToString Does not really use RFC339 - but sqlite does not understand timezones and the `T` delimiter

View Source
var ConverterRFC339TimeToString = NewDBTypeConverter[rfctime.RFC3339Time, string](func(v rfctime.RFC3339Time) (string, error) {
	return v.Time().In(time.UTC).Format("2006-01-02 15:04:05"), nil
}, func(v string) (rfctime.RFC3339Time, error) {
	t, err := time.Parse("2006-01-02 15:04:05", v)
	if err != nil {
		return rfctime.RFC3339Time{}, err
	}
	return rfctime.NewRFC3339(t), nil
})

ConverterRFC339TimeToString Does not really use RFC339 - but sqlite does not understand timezones and the `T` delimiter

View Source
var ConverterRFCDateToString = NewDBTypeConverter[rfctime.Date, string](func(v rfctime.Date) (string, error) {
	return fmt.Sprintf("%04d-%02d-%02d", v.Year, v.Month, v.Day), nil
}, func(v string) (rfctime.Date, error) {
	d := rfctime.Date{}
	if err := d.ParseString(v); err != nil {
		return rfctime.Date{}, err
	} else {
		return d, nil
	}
})
View Source
var ConverterRFCSecondsF64ToString = NewDBTypeConverter[rfctime.SecondsF64, float64](func(v rfctime.SecondsF64) (float64, error) {
	return v.Seconds(), nil
}, func(v float64) (rfctime.SecondsF64, error) {
	return rfctime.NewSecondsF64(timeext.FromSeconds(v)), nil
})
View Source
var ConverterRFCTimeToString = NewDBTypeConverter[rfctime.Time, string](func(v rfctime.Time) (string, error) {
	return v.SerializeShort(), nil
}, func(v string) (rfctime.Time, error) {
	res := rfctime.Time{}
	err := res.Deserialize(v)
	if err != nil {
		return rfctime.Time{}, err
	}
	return res, nil
})
View Source
var ConverterRFCUnixMilliTimeToUnixMillis = NewDBTypeConverter[rfctime.UnixMilliTime, int64](func(v rfctime.UnixMilliTime) (int64, error) {
	return v.UnixMilli(), nil
}, func(v int64) (rfctime.UnixMilliTime, error) {
	return rfctime.NewUnixMilli(time.UnixMilli(v)), nil
})
View Source
var ConverterRFCUnixNanoTimeToUnixNanos = NewDBTypeConverter[rfctime.UnixNanoTime, int64](func(v rfctime.UnixNanoTime) (int64, error) {
	return v.UnixNano(), nil
}, func(v int64) (rfctime.UnixNanoTime, error) {
	return rfctime.NewUnixNano(time.Unix(0, v)), nil
})
View Source
var ConverterRFCUnixTimeToUnixSeconds = NewDBTypeConverter[rfctime.UnixTime, int64](func(v rfctime.UnixTime) (int64, error) {
	return v.Unix(), nil
}, func(v int64) (rfctime.UnixTime, error) {
	return rfctime.NewUnix(time.Unix(v, 0)), nil
})
View Source
var ConverterTimeToUnixMillis = NewDBTypeConverter[time.Time, int64](func(v time.Time) (int64, error) {
	return v.UnixMilli(), nil
}, func(v int64) (time.Time, error) {
	return time.UnixMilli(v), nil
})

Functions

func Count

func Count(ctx context.Context, q Queryable, table string, filter PaginateFilter) (int, error)

func CreateSqliteDatabaseSchemaString

func CreateSqliteDatabaseSchemaString(ctx context.Context, db Queryable) (string, error)

func HashGoSqliteSchema

func HashGoSqliteSchema(ctx context.Context, schemaStr string) (string, error)

HashGoSqliteSchema use if mattn/go-sqlite3

func HashMattnSqliteSchema

func HashMattnSqliteSchema(ctx context.Context, schemaStr string) (string, error)

HashMattnSqliteSchema use if github.com/glebarez/go-sqlite

func HashSqliteDatabase

func HashSqliteDatabase(ctx context.Context, db Queryable) (string, error)

func InsertAndQuerySingle

func InsertAndQuerySingle[TData any](ctx context.Context, q Queryable, tableName string, v TData, idColumn string, mode StructScanMode, sec StructScanSafety) (TData, error)

func InsertMultiple

func InsertMultiple[TData any](ctx context.Context, q Queryable, tableName string, vArr []TData, maxBatch int) ([]sql.Result, error)

func InsertSingle

func InsertSingle[TData any](ctx context.Context, q Queryable, tableName string, v TData) (sql.Result, error)

func Iterate

func Iterate[TData any](ctx context.Context, q Queryable, table string, filter PaginateFilter, scanMode StructScanMode, scanSec StructScanSafety, page int, limit *int, consumer func(ctx context.Context, v TData) error) (int, error)

func IterateAll

func IterateAll[TData any](ctx context.Context, q Queryable, rows *sqlx.Rows, mode StructScanMode, sec StructScanSafety, close bool, consumer func(ctx context.Context, v TData) error) (int, error)

func PPID

func PPID() string

func Paginate

func Paginate[TData any](ctx context.Context, q Queryable, table string, filter PaginateFilter, scanMode StructScanMode, scanSec StructScanSafety, page int, limit *int) ([]TData, pag.Pagination, error)

func QueryAll

func QueryAll[TData any](ctx context.Context, q Queryable, sql string, pp PP, mode StructScanMode, sec StructScanSafety) ([]TData, error)

func QuerySingle

func QuerySingle[TData any](ctx context.Context, q Queryable, sql string, pp PP, mode StructScanMode, sec StructScanSafety) (TData, error)

func QuerySingleOpt

func QuerySingleOpt[TData any](ctx context.Context, q Queryable, sqlstr string, pp PP, mode StructScanMode, sec StructScanSafety) (*TData, error)

func ScanAll

func ScanAll[TData any](ctx context.Context, q Queryable, rows *sqlx.Rows, mode StructScanMode, sec StructScanSafety, close bool) ([]TData, error)

func ScanSingle

func ScanSingle[TData any](ctx context.Context, q Queryable, rows *sqlx.Rows, mode StructScanMode, sec StructScanSafety, close bool) (TData, error)

func UpdateAndQuerySingle

func UpdateAndQuerySingle[TData any](ctx context.Context, q Queryable, tableName string, v TData, idColumn string, mode StructScanMode, sec StructScanSafety) (TData, error)

func UpdateSingle

func UpdateSingle[TData any](ctx context.Context, q Queryable, tableName string, v TData, idColumn string) (sql.Result, error)

Types

type AutoJson

type AutoJson[T any] struct {
	Value T
}

func (AutoJson[T]) MarshalToDB

func (j AutoJson[T]) MarshalToDB(v AutoJson[T]) (string, error)

func (AutoJson[T]) UnmarshalToModel

func (j AutoJson[T]) UnmarshalToModel(v string) (AutoJson[T], error)

type DB

type DB interface {
	Queryable

	Ping(ctx context.Context) error
	BeginTransaction(ctx context.Context, iso sql.IsolationLevel) (Tx, error)
	AddListener(listener Listener)
	Exit() error
	RegisterConverter(DBTypeConverter)
}

func NewDB

func NewDB(db *sqlx.DB, opt DBOptions) DB

type DBDataConstraint

type DBDataConstraint interface {
	string | langext.NumberConstraint | []byte
}

type DBOptions

type DBOptions struct {
	RegisterDefaultConverter *bool
	RegisterCommentTrimmer   *bool
}

type DBTypeConverter

type DBTypeConverter interface {
	ModelTypeString() string
	DBTypeString() string
	ModelToDB(v any) (any, error)
	DBToModel(v any) (any, error)
}

func NewAutoDBTypeConverter

func NewAutoDBTypeConverter[TDBData DBDataConstraint, TModelData DatabaseConvertible[TModelData, TDBData]](obj TModelData) DBTypeConverter

func NewDBTypeConverter

func NewDBTypeConverter[TModelData any, TDBData DBDataConstraint](todb func(v TModelData) (TDBData, error), tomodel func(v TDBData) (TModelData, error)) DBTypeConverter

type DatabaseConvertible

type DatabaseConvertible[TModelData any, TDBData DBDataConstraint] interface {
	MarshalToDB(v TModelData) (TDBData, error)
	UnmarshalToModel(v TDBData) (TModelData, error)
}

type FilterSort

type FilterSort struct {
	Field     string
	Direction ct.SortDirection
}

type JsonArr

type JsonArr []any

func (JsonArr) MarshalToDB

func (j JsonArr) MarshalToDB(v JsonArr) (string, error)

func (JsonArr) UnmarshalToModel

func (j JsonArr) UnmarshalToModel(v string) (JsonArr, error)

type JsonObj

type JsonObj map[string]any

func (JsonObj) MarshalToDB

func (j JsonObj) MarshalToDB(v JsonObj) (string, error)

func (JsonObj) UnmarshalToModel

func (j JsonObj) UnmarshalToModel(v string) (JsonObj, error)

type Listener

type Listener interface {
	PrePing(ctx context.Context, meta PrePingMeta) error
	PreTxBegin(ctx context.Context, txid uint16, meta PreTxBeginMeta) error
	PreTxCommit(txid uint16, meta PreTxCommitMeta) error
	PreTxRollback(txid uint16, meta PreTxRollbackMeta) error
	PreQuery(ctx context.Context, txID *uint16, sql *string, params *PP, meta PreQueryMeta) error
	PreExec(ctx context.Context, txID *uint16, sql *string, params *PP, meta PreExecMeta) error

	PostPing(result error, meta PostPingMeta)
	PostTxBegin(txid uint16, result error, meta PostTxBeginMeta)
	PostTxCommit(txid uint16, result error, meta PostTxCommitMeta)
	PostTxRollback(txid uint16, result error, meta PostTxRollbackMeta)
	PostQuery(txID *uint16, sqlOriginal string, sqlReal string, params PP, result error, meta PostQueryMeta)
	PostExec(txID *uint16, sqlOriginal string, sqlReal string, params PP, result error, meta PostExecMeta)
}

func NewPostExecListener

func NewPostExecListener(f func(txID *uint16, sqlOriginal string, sqlReal string, params PP, result error, meta PostExecMeta)) Listener

func NewPostListener

func NewPostListener(f func(cmdtype string, txID *uint16, sqlOriginal string, sqlReal string, result error, params PP)) Listener

func NewPostPingListener

func NewPostPingListener(f func(result error, meta PostPingMeta)) Listener

func NewPostQueryListener

func NewPostQueryListener(f func(txID *uint16, sqlOriginal string, sqlReal string, params PP, result error, meta PostQueryMeta)) Listener

func NewPostTxBeginListener

func NewPostTxBeginListener(f func(txid uint16, result error, meta PostTxBeginMeta)) Listener

func NewPostTxCommitListener

func NewPostTxCommitListener(f func(txid uint16, result error, meta PostTxCommitMeta)) Listener

func NewPostTxRollbackListener

func NewPostTxRollbackListener(f func(txid uint16, result error, meta PostTxRollbackMeta)) Listener

func NewPreExecListener

func NewPreExecListener(f func(ctx context.Context, txID *uint16, sql *string, params *PP, meta PreExecMeta) error) Listener

func NewPreListener

func NewPreListener(f func(ctx context.Context, cmdtype string, txID *uint16, sql *string, params *PP) error) Listener

func NewPrePingListener

func NewPrePingListener(f func(ctx context.Context, meta PrePingMeta) error) Listener

func NewPreQueryListener

func NewPreQueryListener(f func(ctx context.Context, txID *uint16, sql *string, params *PP, meta PreQueryMeta) error) Listener

func NewPreTxBeginListener

func NewPreTxBeginListener(f func(ctx context.Context, txid uint16, meta PreTxBeginMeta) error) Listener

func NewPreTxCommitListener

func NewPreTxCommitListener(f func(txid uint16, meta PreTxCommitMeta) error) Listener

func NewPreTxRollbackListener

func NewPreTxRollbackListener(f func(txid uint16, meta PreTxRollbackMeta) error) Listener

type PP

type PP map[string]any

func BuildInsertMultipleStatement

func BuildInsertMultipleStatement[TData any](q Queryable, tableName string, vArr []TData) (string, PP, error)

func BuildInsertStatement

func BuildInsertStatement[TData any](q Queryable, tableName string, obj TData) (string, PP, error)

func BuildUpdateStatement

func BuildUpdateStatement[TData any](q Queryable, tableName string, obj TData, idColumn string) (string, PP, error)

func Join

func Join(pps ...PP) PP

func (*PP) Add

func (pp *PP) Add(v any) string

func (*PP) AddAll

func (pp *PP) AddAll(other PP)

type PaginateFilter

type PaginateFilter interface {
	SQL(params PP) (filterClause string, joinClause string, joinTables []string)
	Sort() []FilterSort
}

func NewEmptyPaginateFilter

func NewEmptyPaginateFilter() PaginateFilter

func NewPaginateFilter

func NewPaginateFilter(sql func(params PP) (filterClause string, joinClause string, joinTables []string), sort []FilterSort) PaginateFilter

func NewSimplePaginateFilter

func NewSimplePaginateFilter(filterClause string, filterParams PP, sort []FilterSort) PaginateFilter

type PostExecMeta

type PostExecMeta struct {
	Context                       context.Context
	TransactionConstructorContext context.Context
	Init                          time.Time
	Start                         time.Time
	End                           time.Time
}

type PostPingMeta

type PostPingMeta struct {
	Context context.Context
	Init    time.Time
	Start   time.Time
	End     time.Time
}

type PostQueryMeta

type PostQueryMeta struct {
	Context                       context.Context
	TransactionConstructorContext context.Context
	Init                          time.Time
	Start                         time.Time
	End                           time.Time
}

type PostTxBeginMeta

type PostTxBeginMeta struct {
	Context context.Context
	Init    time.Time
	Start   time.Time
	End     time.Time
}

type PostTxCommitMeta

type PostTxCommitMeta struct {
	ConstructorContext context.Context
	Init               time.Time
	Start              time.Time
	End                time.Time
	ExecCounter        int
	QueryCounter       int
}

type PostTxRollbackMeta

type PostTxRollbackMeta struct {
	ConstructorContext context.Context
	Init               time.Time
	Start              time.Time
	End                time.Time
	ExecCounter        int
	QueryCounter       int
}

type PreExecMeta

type PreExecMeta struct {
	Context                       context.Context
	TransactionConstructorContext context.Context
}

type PrePingMeta

type PrePingMeta struct {
	Context context.Context
}

type PreQueryMeta

type PreQueryMeta struct {
	Context                       context.Context
	TransactionConstructorContext context.Context
}

type PreTxBeginMeta

type PreTxBeginMeta struct {
	Context            context.Context
	ConstructorContext context.Context
}

type PreTxCommitMeta

type PreTxCommitMeta struct {
	ConstructorContext context.Context
}

type PreTxRollbackMeta

type PreTxRollbackMeta struct {
	ConstructorContext context.Context
}

type Queryable

type Queryable interface {
	Exec(ctx context.Context, sql string, prep PP) (sql.Result, error)
	Query(ctx context.Context, sql string, prep PP) (*sqlx.Rows, error)
	ListConverter() []DBTypeConverter
}

type StructScanMode

type StructScanMode string
const (
	SModeFast     StructScanMode = "FAST"     // Use default sq.Scan, does not work with joined/resolved types and/or custom value converter
	SModeExtended StructScanMode = "EXTENDED" // Fully featured perhaps (?) a tiny bit slower - default
)

type StructScanSafety

type StructScanSafety string
const (
	Safe   StructScanSafety = "SAFE"   // return error for missing fields
	Unsafe StructScanSafety = "UNSAFE" // ignore missing fields
)

type StructScanner

type StructScanner struct {
	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

func NewStructScanner

func NewStructScanner(rows *sqlx.Rows, unsafe bool) *StructScanner

func (*StructScanner) Start

func (r *StructScanner) Start(dest any) error

func (*StructScanner) StructScanBase

func (r *StructScanner) StructScanBase(dest any) error

StructScanBase forked from github.com/jmoiron/sqlx@v1.3.5/sqlx.go without (relevant) changes

func (*StructScanner) StructScanExt

func (r *StructScanner) StructScanExt(q Queryable, dest any) error

StructScanExt forked from github.com/jmoiron/sqlx@v1.3.5/sqlx.go does also work with nullabel structs (from LEFT JOIN's) does also work with custom value converters

type Tx

type Tx interface {
	Queryable

	Rollback() error
	Commit() error
	Status() TxStatus
}

type TxStatus

type TxStatus string
const (
	TxStatusInitial  TxStatus = "INITIAL"
	TxStatusActive   TxStatus = "ACTIVE"
	TxStatusComitted TxStatus = "COMMITTED"
	TxStatusRollback TxStatus = "ROLLBACK"
)

Jump to

Keyboard shortcuts

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