dbx

package module
v0.0.0-...-14686a8 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2026 License: BSD-3-Clause Imports: 19 Imported by: 0

README

dbx

dbx (Database Eextensions) is a small toolkit of common and reusable database helpers built around the Jet SQL builder. Provides an app.Module.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoRows is returned when a query returns no rows.
	ErrNoRows = qrm.ErrNoRows

	// ErrValueIsZero is returned when an expected value is missing.
	ErrValueIsZero = errors.New("value is zero-value for type")
)

Functions

func ApplyComplexPtr

func ApplyComplexPtr[
	Existing constraints.Float | constraints.Integer,
	New constraints.Float | constraints.Integer,
](
	existing *Existing,
	newVal *New,
	updatedColumns *mysql.ColumnList,
	targetColumn mysql.Column,
) *Existing

ApplyComplexPtr compares the existing value with a new value and returns the updated value if they differ. The new value may be of a different type (e.g. existing is uint16 and new is uint64), but it will be converted to match the current type resulting in potential loss of data. If the new value is nil, the existing value is retained. If the new value is a zero-value, the existing value is NOT retained, it will be set to nil. If the value is changed, targetColumn is pushed to updatedColumns.

func ApplyInterfacePtr

func ApplyInterfacePtr[T ApplyInterface[T]](
	existing *T,
	newVal *T,
	updatedColumns *mysql.ColumnList,
	targetColumn mysql.Column,
) *T

ApplyInterfacePtr compares the existing value with a new value and returns the updated value if they differ. Comparable types must have IsZero and Equal methods. If the new value is nil, the existing value is retained. If the new value is a zero-value, the existing value is NOT retained, it will be set to nil. If the value is changed, targetColumn is pushed to updatedColumns.

func ApplyPtr

func ApplyPtr[T constraints.Float | constraints.Integer | string | bool](
	existing *T,
	newVal *T,
	updatedColumns *mysql.ColumnList,
	targetColumn mysql.Column,
) *T

ApplyPtr compares the existing value with a new value and returns the updated value if they differ. If the new value is nil, the existing value is retained. If the new value is a zero-value, the existing value is NOT retained, it will be set to nil. If the value is changed, targetColumn is pushed to updatedColumns.

func ApplyVal

func ApplyVal[T constraints.Float | constraints.Integer | string | bool](
	existing T,
	newVal *T,
	updatedColumns *mysql.ColumnList,
	targetColumn mysql.Column,
) T

ApplyVal compares the existing value with a pointer to a new value and returns the updated value if they differ. If the new value is nil, the existing value is retained. If the value is changed, targetColumn is pushed to updatedColumns

func DestName

func DestName(destTypeStruct any, path ...string) string

DestName returns the name of the type passed as `destTypeStruct` as a string, normalized for compatibility with the Jet QRM.

func ExprStringers

func ExprStringers(values []fmt.Stringer) []mysql.Expression

ExprStringers converts a list of fmt.Stringers to a list of mysql.Expression values.

func ExprValues

func ExprValues[T any](values []T, f func(T) mysql.Expression) []mysql.Expression

ExprValues converts a list of values to a list of mysql.Expression values using function f to transform the values (mysql.String for strings, mysql.Uint64, etc).

func Fetch

func Fetch[T any](sqlo Queryable, stmt Statement) ([]*T, error)

Fetch queries the database and returns the result as a slice. If the query returns no rows, it returns an empty slice and no error.

func FetchOne

func FetchOne[T any](sqlo Queryable, stmt Statement) (*T, error)

FetchOne queries the database and returns a single result. If the query returns no rows, it returns nil and no error.

func Insert

func Insert(sqlo Executable, stmt Statement) (uint64, error)

Insert executes an insert statement, returning the last inserted ID or an error if the insert fails.

func InsertReturning

func InsertReturning[T any](sqlo Queryable, stmt Statement) (*T, error)

InsertReturning executes an insert statement that returns the inserted row. The statement MUST be a Jet InsertStatement with a RETURNING clause. Returns the inserted row object T or an error if the insert fails or no rows are returned.

func IsZero

func IsZero[T any](ptr *T) error

IsZero checks if a pointer references the zero value of a given type and returns an error if this condition is met, otherwise returns nil if the pointer is nil or the value is not zero.

func ModuleDB

func ModuleDB(dialect Dialect, config *DBConfig, forceDebugLog bool) *app.Module

ModuleDB returns the database module with the provided configuration. dialect specifies the SQL dialect to use (e.g., DialectPostgres, DialectMySQL). config specifies the database connection configuration. forceDebugLog forces debug logging to be enabled regardless of the config setting.

func MustFetch

func MustFetch[T any](sqlo Queryable, stmt Statement, notFoundErr error) ([]*T, error)

MustFetch queries the database and returns the result as a slice. If the query returns no rows, it returns an empty slice and the desired error.

func MustFetchOne

func MustFetchOne[T any](sqlo Queryable, stmt Statement, notFoundErr error) (*T, error)

MustFetchOne queries the database and returns a single result. If the query returns no rows, it returns nil and the desired error.

func NormalCols

func NormalCols[CL ColumnList](cols ...Column) CL

NormalCols processes a list of columns and strips out any that implement any of ColumnTimestamp, ColumnTime, or ColumnDate.

func NowPtr

func NowPtr() *time.Time

NowPtr returns a pointer to the current time.

func Ptr

func Ptr[T any](val T) *T

Ptr returns a pointer to the given value of any scalar type. Returns nil if the value is a zero value.

func SQLO

func SQLO() *sql.DB

SQLO returns the current SQL database handle.

func StringToFilter

func StringToFilter(str string) string

StringToFilter processes a string to be used as a filter in an SQL LIKE statement. It replaces all spaces with % and adds % to the beginning and end of the string.

func TrimPtr

func TrimPtr(s *string) *string

TrimPtr trims the whitespace from a pointer to a string and returns nil only if the pointer is nil.

func TrimPtrToNil

func TrimPtrToNil(s *string) *string

TrimPtrToNil trims the whitespace from a pointer to a string and returns nil if the resulting string is empty or if the pointer is nil.

func Update

func Update(sqlo Executable, stmt Statement) error

Update executes an update statement, returning an error if the update fails.

func UpdateAffected

func UpdateAffected(sqlo Executable, stmt Statement) (int64, error)

UpdateAffected executes an update statement and returns the number of rows affected and an error if any.

func UpdateReturning

func UpdateReturning[T any](sqlo Queryable, stmt Statement) (*T, error)

UpdateReturning executes an update statement that returns the updated row. The statement MUST be a Jet UpdateStatement with a RETURNING clause. Returns the updated row object T or an error if the update fails or no rows are returned.

func Val

func Val[T any](ptr *T) T

Val returns the value of the pointer to a scalar type, or the zero value if the pointer is nil.

Types

type ApplyInterface

type ApplyInterface[T any] interface {
	Equal(T) bool
	IsZero() bool
}

type BoolExpression

type BoolExpression interface {
	mysql.BoolExpression
	postgres.BoolExpression
}

BoolExpression is a union type for mysql.BoolExpression and postgres.BoolExpression

type Column

type Column interface {
	mysql.Column
	postgres.Column
}

Column is a union type for mysql.Column and postgres.Column

type ColumnList

type ColumnList interface {
	mysql.ColumnList
	postgres.ColumnList
}

ColumnList is a union type for mysql.ColumnList and postgres.ColumnList

type DBConfig

type DBConfig struct {
	User        string `validate:"required"`
	Password    string `validate:"required"`
	URI         string `validate:"hostname_port,required"`
	Name        string `validate:"required"`
	MaxConn     int    `validate:"min=1,max=1000"`
	AutoMigrate bool
	DebugLog    bool
}

DBConfig provides a template for database connection configuration compatible with go-toolkit/config. If used as a field in a struct, remember to include the `validate:"dive"` tag to ensure that the validator checks sub-fields.

func (*DBConfig) ConnectionString

func (cfg *DBConfig) ConnectionString(dialect Dialect) string

ConnectionString returns a connection string compatible with the given SQL dialect.

func (*DBConfig) Host

func (cfg *DBConfig) Host() (string, error)

Host returns the host portion of the database URI.

func (*DBConfig) Port

func (cfg *DBConfig) Port() (int, error)

Port returns the port portion of the database URI.

type Dialect

type Dialect string

Dialect is the SQL dialect used by the database connection.

const (
	// ModuleDBName is the name of the database module.
	ModuleDBName = "database"

	// DialectPostgres is the PostgreSQL dialect.
	DialectPostgres Dialect = "postgres"
	// DialectMySQL is the MySQL dialect.
	DialectMySQL Dialect = "mysql"
)

func (Dialect) String

func (d Dialect) String() string

String implements the Stringer interface for Dialect.

type Executable

type Executable interface {
	qrm.Executable
	Exec(string, ...any) (sql.Result, error)
}

Executable interface is an SQL driver object that can execute SQL statements for Jet.

type ExecutableTx

type ExecutableTx interface {
	Executable
	Begin() (*sql.Tx, error)
}

ExecutableTx interface is an SQL driver object that implements the Executable interface and can also begin a transaction.

type JSONB

type JSONB map[string]any

JSONB is a type that represents a JSON object stored in the database. It is a map[string]any and implements sql.Scanner, driver.Valuer, and Stringer.

func NewJSONB

func NewJSONB(data map[string]any) JSONB

NewJSONB creates a new JSONB value from a map[string]any.

func (*JSONB) Scan

func (j *JSONB) Scan(src any) error

Scan implements the sql.Scanner interface. It supports converting from string, []byte, or nil into a JSONB value. Attempting to convert from any other type will return an error.

func (JSONB) String

func (j JSONB) String() string

func (JSONB) ToMap

func (j JSONB) ToMap() map[string]any

ToMap converts the JSONB value to a map[string]any.

func (JSONB) Value

func (j JSONB) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It converts the JSONB value into a SQL driver value which can be used to directly use the JSONB as a parameter to a SQL query.

type QueryExec

type QueryExec interface {
	Queryable
	Executable
}

QueryExec interface is an SQL driver object that can execute SQL statements for Jet and query results.

type QueryExecTx

type QueryExecTx interface {
	Queryable
	ExecutableTx
}

QueryExecTx interface is an SQL driver object that can execute SQL statements for Jet, query results, and begin a transaction.

type Queryable

type Queryable interface {
	qrm.Queryable
	Query(string, ...any) (*sql.Rows, error)
}

Queryable interface is an SQL driver object that can execute SQL statements for Jet.

type SQLOFunc

type SQLOFunc = func() *sql.DB

SQLOFunc is a function that returns a *sql.DB pointer.

type Statement

type Statement interface {
	Query(db qrm.Queryable, destination any) error
	QueryContext(ctx context.Context, db qrm.Queryable, destination any) error
	Exec(db qrm.Executable) (sql.Result, error)
	ExecContext(ctx context.Context, db qrm.Executable) (sql.Result, error)
}

Statement is a common Jet statement for all SQL operations.

type UUID

type UUID struct {
	ksuid.KSUID
}

UUID is a wrapper around ksuid.KSUID that implements the graphql.Unmarshaler and graphql.Marshaler interfaces for use in GraphQL APIs. It also provides additional convenience functions such as ParseUUID and NewUUID.

func NewUUID

func NewUUID() UUID

Generates a new, wrapped KSUID. In the strange case that random bytes can't be read, it will panic.

func ParseUUID

func ParseUUID(s string) (UUID, error)

ParseUUID parses a UUID from a string. If the string is not a valid UUID, it will return an error.

func (UUID) MarshalGQL

func (u UUID) MarshalGQL(w io.Writer)

MarshalGQL implements the graphql.Marshaler interface

func (*UUID) UnmarshalGQL

func (u *UUID) UnmarshalGQL(value interface{}) error

UnmarshalGQL implements the graphql.Unmarshaler interface

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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