xdb

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	XERR_NONE   xerrors.ErrorCode = ""
	XERR_PKGCTX xerrors.ErrorCode = "ERR_XDB"

	// XERR_CONNECTION_FAILED targets failures when establishing physical channel lines or initial driver handshakes.
	// Format expects: TARGET, DETAILS
	XERR_CONNECTION_FAILED xerrors.ErrorCode = "E1001"

	// XERR_ENGINE_CONFIG_FAILED targets syntax or logic failures when applying internal engine runtime configurations (e.g. PRAGMAs).
	// Format expects: TARGET, DETAILS
	XERR_ENGINE_CONFIG_FAILED xerrors.ErrorCode = "E1002"

	// XERR_MIGRATION_EXECUTION_FAILED targets processing sequences where valid SQL structures fail state transmission or command limits.
	// Format expects: TARGET, DETAILS
	XERR_MIGRATION_EXECUTION_FAILED xerrors.ErrorCode = "E1003"

	XERR_REPO_INSERT_WITH_UNEXPECTED_NUMERIC_PK xerrors.ErrorCode = "E2001"
	XERR_REPO_INSERT_WITH_UNEXPECTED_STRING_PK  xerrors.ErrorCode = "E2002"
	XERR_REPO_INSERT_WITH_UNEXPECTED_EMPTY_PK   xerrors.ErrorCode = "E2003"
	XERR_REPO_INSERT_WITH_UNEXPECTED_NIL_PK     xerrors.ErrorCode = "E2004"
	XERR_REPO_INSERT_EXECUTION_FAILED           xerrors.ErrorCode = "E2005"
	XERR_REPO_INSERT_FETCH_ID_FAILED            xerrors.ErrorCode = "E2006"

	XERR_REPO_UPDATE_INVALID_NUMERICAL_PK xerrors.ErrorCode = "E3001"
	XERR_REPO_UPDATE_EMPTY_STRING_PK      xerrors.ErrorCode = "E3002"
	XERR_REPO_UPDATE_PK_NIL               xerrors.ErrorCode = "E3003"
	XERR_REPO_UPDATE_UNKNOWN_PK_TYPE      xerrors.ErrorCode = "E3004"
	XERR_REPO_UPDATE_NO_COLUMNS_DEFINED   xerrors.ErrorCode = "E3005"
	XERR_REPO_UPDATE_EXEC_FAILED          xerrors.ErrorCode = "E3006"
	XERR_REPO_UPDATE_VERIFY_ROWS_FAILED   xerrors.ErrorCode = "E3007"
	XERR_REPO_UPDATE_RECORD_NOT_FOUND     xerrors.ErrorCode = "E3008"

	XERR_REPO_DELETE_EXEC_FAILED        xerrors.ErrorCode = "E4001"
	XERR_REPO_DELETE_VERIFY_ROWS_FAILED xerrors.ErrorCode = "E4002"
	XERR_REPO_DELETE_RECORD_NOT_FOUND   xerrors.ErrorCode = "E4003"

	XERR_REPO_GET_BY_ID_EXEC_FAILED      xerrors.ErrorCode = "E5001"
	XERR_REPO_GET_BY_ID_RECORD_NOT_FOUND xerrors.ErrorCode = "E5002"
	XERR_REPO_GET_BY_ID_SCAN_FAILED      xerrors.ErrorCode = "E5003"
	XERR_REPO_GET_ALL_EXEC_FAILED        xerrors.ErrorCode = "E5004"
	XERR_REPO_GET_ALL_SCAN_FAILED        xerrors.ErrorCode = "E5005"
	XERR_REPO_GET_ALL_ITERATION_FAILED   xerrors.ErrorCode = "E5006"
	XERR_REPO_GET_BY_FIELD_EXEC_FAILED   xerrors.ErrorCode = "E5007"
	XERR_REPO_GET_BY_FIELD_SCAN_FAILED   xerrors.ErrorCode = "E5008"
	XERR_REPO_GET_WHERE_ARGS_MISMATCH    xerrors.ErrorCode = "E5009"
	XERR_REPO_GET_WHERE_EXEC_FAILED      xerrors.ErrorCode = "E5010"
	XERR_REPO_GET_WHERE_SCAN_FAILED      xerrors.ErrorCode = "E5011"

	XERR_REPO_QUERY_RAW_EXEC_FAILED xerrors.ErrorCode = "E6001"
	XERR_REPO_QUERY_RAW_SCAN_FAILED xerrors.ErrorCode = "E6002"
)

Variables

This section is empty.

Functions

func ContextWithForcedIdempotency

func ContextWithForcedIdempotency(ctx context.Context) context.Context

ContextWithForcedIdempotency wraps the provided context to guarantee that down-stream update and delete actions run idempotently.

func ContextWithProhibitedIdempotency

func ContextWithProhibitedIdempotency(ctx context.Context) context.Context

ContextWithProhibitedIdempotency wraps the provided context to strictly block idempotent behavior on down-stream data modifications.

func QueryRaw

func QueryRaw[R any](
	ctx context.Context,
	db *sql.DB,
	cq CustomQuery[R],
) ([]R, xerrors.ErrorCode)

QueryRaw coordinates the isolation, manual execution, and custom collection scan mapping of arbitrary database commands.

func RetrieveDbType

func RetrieveDbType(db *sql.DB) string

retrieveDbType inspects the underlying driver of an active sql.DB instance safely to identify the target dialect.

Types

type CustomQuery

type CustomQuery[R any] struct {
	SQL     string
	Args    []any
	Scanner RowScanner[R]
}

CustomQuery decouples raw SQL execution from rigid models by bundling the query statement, its runtime parameters, and its mapping logic.

type DBConfig

type DBConfig struct {
	Driver                string        `json:"driver"`
	DSN                   string        `json:"dsn"`
	MigrationsDirPath     string        `json:"migrationsDirPath"`
	MaxOpenConnections    int           `json:"maxOpenConnections"`
	MaxIdleConnections    int           `json:"maxIdleConnections"`
	ConnectionMaxLifetime time.Duration `json:"connectionMaxLifetime"`
	SQLite                SQLiteConfig  `json:"sqlite"`

	DB *sql.DB
}

DBConfig manages database driver options, connection pool life cycles, and engine-specific options.

func NewDBConfig

func NewDBConfig(
	driver string,
	dsn string,
	migrationsDirPath string,
	sqliteMode string,
	sqliteDir string,
	sqliteFileName string,
	sqliteQuerystring string,
) DBConfig

NewDBConfig instantiates a baseline operational configuration setup with optimized defaults for embedded deployments.

func (*DBConfig) CheckConfiguration

func (o *DBConfig) CheckConfiguration() error

CheckConfiguration verifies structural parameters to maintain setup layout consistency before initializing adapters.

func (*DBConfig) InitDataBaseConnection

func (o *DBConfig) InitDataBaseConnection(ctx context.Context) error

InitDataBaseConnection activates database interface structures and applies custom engine tuning options safely.

func (*DBConfig) RunMigrations

func (o *DBConfig) RunMigrations(ctx context.Context) error

RunMigrations processes organized script collections chronologically against target database environments.

type DBGeneric

type DBGeneric[T any, PT interface {
	*T
	Entity
}] struct {
	// contains filtered or unexported fields
}

DBGeneric implements a type-safe, generic repository pattern dedicated to a specific domain entity model.

func NewDBGeneric

func NewDBGeneric[T any, PT interface {
	*T
	Entity
}](db *sql.DB) *DBGeneric[T, PT]

NewDBGeneric initializes and yields a new operational instance of the generic repository interface.

func (*DBGeneric[T, PT]) Delete

func (r *DBGeneric[T, PT]) Delete(ctx context.Context, entity PT) xerrors.ErrorCode

Delete drops target records based on explicit key mapping evaluations.

func (*DBGeneric[T, PT]) GetAll

func (r *DBGeneric[T, PT]) GetAll(ctx context.Context) ([]*T, xerrors.ErrorCode)

GetAll extracts every existing collection sequence context from the entity schema targets.

func (*DBGeneric[T, PT]) GetByField

func (r *DBGeneric[T, PT]) GetByField(ctx context.Context, field string, value any) ([]*T, xerrors.ErrorCode)

GetByField searches for matching dataset groups filtered by a specific column variable signature.

func (*DBGeneric[T, PT]) GetByID

func (r *DBGeneric[T, PT]) GetByID(ctx context.Context, id any) (*T, xerrors.ErrorCode)

GetByID performs a target row execution based on primary key mappings to fetch a singular type-safe entry instance.

func (*DBGeneric[T, PT]) GetSQLExecutor

func (r *DBGeneric[T, PT]) GetSQLExecutor() SQLExecutor

GetSQLExecutor evaluates whether to pipeline execution states through an active transaction isolation or the global connection pool.

func (*DBGeneric[T, PT]) GetWhere

func (r *DBGeneric[T, PT]) GetWhere(ctx context.Context, queryFragment string, args ...any) ([]*T, xerrors.ErrorCode)

GetWhere parses complex conditional dynamic parameters to retrieve subset target collections.

func (*DBGeneric[T, PT]) Insert

func (r *DBGeneric[T, PT]) Insert(ctx context.Context, entity PT) xerrors.ErrorCode

Insert validates model states, produces identifiers when applicable, and stores records securely.

func (*DBGeneric[T, PT]) SetIdempotentDelete

func (r *DBGeneric[T, PT]) SetIdempotentDelete(enabled bool) *DBGeneric[T, PT]

SetIdempotentDelete overrides instance delete settings to silently tolerate non-existent entities during removal attempts.

func (*DBGeneric[T, PT]) SetIdempotentUpdate

func (r *DBGeneric[T, PT]) SetIdempotentUpdate(enabled bool) *DBGeneric[T, PT]

SetIdempotentUpdate overrides instance update settings to prevent throwing missing record validation errors on missing datasets.

func (*DBGeneric[T, PT]) Update

func (r *DBGeneric[T, PT]) Update(ctx context.Context, entity PT) xerrors.ErrorCode

Update coordinates column updates while enforcing primary key validations and idempotency rules.

func (*DBGeneric[T, PT]) WithTx

func (r *DBGeneric[T, PT]) WithTx(tx *sql.Tx) *DBGeneric[T, PT]

WithTx returns a contextual shallow clone of the repository bound to an active database transaction lifecycle.

type Entity

type Entity interface {
	// TableName returns the exact database table identifier linked to this entity.
	TableName() string

	// PKColumnName returns the physical database primary key column
	// identifier (e.g., "id" or "key").
	PKColumnName() string

	// PKSetValue allows the repository engine to inject database-generated
	// or application-generated identifiers back into the instance memory
	// pointer.
	PKSetValue(id any)

	// PKGetValue returns the current snapshot value of the primary key
	// field (e.g., an int64 ID or a string UUID).
	PKGetValue() any

	// PKGenerateValue creates an application-side unique identifier,
	// returning nil if the key lifecycle is delegated to the database
	// engine.
	PKGenerateValue() any

	// PKExternal indicates whether the entity's primary key comes from
	// an external identifier provided by the system context, rather
	// than from the database itself (This value is commonly 'false').
	PKExternal() bool

	// Columns yields the sequence of table columns targeted for
	// INSERT/UPDATE actions, strictly excluding database-managed values.
	Columns() []string

	// Values yields the field records mapped in the exact corresponding
	// sequence order specified by Columns().
	Values() []any

	// ScanRow hydrats the entire entity fields from an active database
	// query cursor row result, mapping all table columns sequentially.
	ScanRow(rows *sql.Rows) error

	// Normalize cleanses and standardizes internal field values before
	// processing (e.g., trimming whitespace or altering casing).
	Normalize()

	// Validate performs fail-fast domain business rules checking,
	// returning false and a distinct status code upon failure.
	Validate() (bool, xerrors.ErrorCode)
}

Entity establishes the mandatory domain lifecycle methods required for automatic CRUD operations.

type RowScanner

type RowScanner[R any] func(rows *sql.Rows) (R, error)

RowScanner defines the function signature required to map database columns into a structured type.

type SQLExecutor

type SQLExecutor interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

SQLExecutor unifies common database operations available on both *sql.DB and *sql.Tx connections.

type SQLiteConfig

type SQLiteConfig struct {
	Mode        string            `json:"mode"`
	Dir         string            `json:"dir"`
	FileName    string            `json:"fileName"`
	QueryString string            `json:"querystring"`
	Pragma      map[string]string `json:"pragma"`
}

SQLiteConfig aggregates dedicated attributes and behavior modifiers needed to shape SQLite behavior.

Jump to

Keyboard shortcuts

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