xdb

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 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 = "E0002"
	XERR_REPO_INSERT_WITH_UNEXPECTED_STRING_PK  xerrors.ErrorCode = "E0003"
	XERR_REPO_INSERT_WITH_UNEXPECTED_EMPTY_PK   xerrors.ErrorCode = "E0004"
	XERR_REPO_INSERT_WITH_UNEXPECTED_NIL_PK     xerrors.ErrorCode = "E0005"
	XERR_REPO_INSERT_EXECUTION_FAILED           xerrors.ErrorCode = "E0006"
	XERR_REPO_INSERT_FETCH_ID_FAILED            xerrors.ErrorCode = "E0007"
	XERR_REPO_UPDATE_INVALID_NUMERICAL_PK       xerrors.ErrorCode = "E0008"
	XERR_REPO_UPDATE_EMPTY_STRING_PK            xerrors.ErrorCode = "E0009"
	XERR_REPO_UPDATE_PK_NIL                     xerrors.ErrorCode = "E0010"
	XERR_REPO_UPDATE_UNKNOWN_PK_TYPE            xerrors.ErrorCode = "E0011"
	XERR_REPO_UPDATE_NO_COLUMNS_DEFINED         xerrors.ErrorCode = "E0012"
	XERR_REPO_UPDATE_EXEC_FAILED                xerrors.ErrorCode = "E0013"
	XERR_REPO_UPDATE_VERIFY_ROWS_FAILED         xerrors.ErrorCode = "E0014"
	XERR_REPO_UPDATE_RECORD_NOT_FOUND           xerrors.ErrorCode = "E0015"
	XERR_REPO_DELETE_EXEC_FAILED                xerrors.ErrorCode = "E0016"
	XERR_REPO_DELETE_VERIFY_ROWS_FAILED         xerrors.ErrorCode = "E0017"
	XERR_REPO_DELETE_RECORD_NOT_FOUND           xerrors.ErrorCode = "E0018"
	XERR_REPO_INTERFACE_ASSERTION_FAILED        xerrors.ErrorCode = "E0019"
	XERR_REPO_GET_BY_ID_EXEC_FAILED             xerrors.ErrorCode = "E0020"
	XERR_REPO_GET_BY_ID_RECORD_NOT_FOUND        xerrors.ErrorCode = "E0021"
	XERR_REPO_GET_BY_ID_SCAN_FAILED             xerrors.ErrorCode = "E0022"
	XERR_REPO_GET_ALL_EXEC_FAILED               xerrors.ErrorCode = "E0023"
	XERR_REPO_GET_ALL_SCAN_FAILED               xerrors.ErrorCode = "E0024"
	XERR_REPO_GET_ALL_ITERATION_FAILED          xerrors.ErrorCode = "E0025"
	XERR_REPO_GET_BY_FIELD_EXEC_FAILED          xerrors.ErrorCode = "E0026"
	XERR_REPO_GET_BY_FIELD_SCAN_FAILED          xerrors.ErrorCode = "E0027"
	XERR_REPO_GET_WHERE_ARGS_MISMATCH           xerrors.ErrorCode = "E0028"
	XERR_REPO_GET_WHERE_EXEC_FAILED             xerrors.ErrorCode = "E0029"
	XERR_REPO_GET_WHERE_SCAN_FAILED             xerrors.ErrorCode = "E0030"
	XERR_REPO_QUERY_RAW_EXEC_FAILED             xerrors.ErrorCode = "E0031"
	XERR_REPO_QUERY_RAW_SCAN_FAILED             xerrors.ErrorCode = "E0032"
)

Variables

View Source
var ErrorMessages = map[xerrors.ErrorCode]string{
	XERR_REPO_INSERT_WITH_UNEXPECTED_NUMERIC_PK: "cannot insert entity with an existing numerical ID",
	XERR_REPO_INSERT_WITH_UNEXPECTED_STRING_PK:  "cannot insert entity with an existing primary key string",
	XERR_REPO_INSERT_WITH_UNEXPECTED_EMPTY_PK:   "cannot insert entity: natural primary key string cannot be empty",
	XERR_REPO_INSERT_WITH_UNEXPECTED_NIL_PK:     "cannot insert entity: natural primary key cannot be nil",
	XERR_REPO_INSERT_EXECUTION_FAILED:           "failed to execute insert statement in the database",
	XERR_REPO_INSERT_FETCH_ID_FAILED:            "failed to retrieve last inserted numerical ID from database",
	XERR_REPO_UPDATE_INVALID_NUMERICAL_PK:       "cannot update entity with invalid numerical ID (must be > 0)",
	XERR_REPO_UPDATE_EMPTY_STRING_PK:            "cannot update entity with empty string key",
	XERR_REPO_UPDATE_PK_NIL:                     "cannot update entity without a primary key",
	XERR_REPO_UPDATE_UNKNOWN_PK_TYPE:            "unknown primary key type format",
	XERR_REPO_UPDATE_NO_COLUMNS_DEFINED:         "no columns defined for update operation in this table",
	XERR_REPO_UPDATE_EXEC_FAILED:                "failed to execute update statement in the database",
	XERR_REPO_UPDATE_VERIFY_ROWS_FAILED:         "failed to verify affected rows during update operation",
	XERR_REPO_UPDATE_RECORD_NOT_FOUND:           "target record not found in database for update operation",
	XERR_REPO_DELETE_EXEC_FAILED:                "failed to execute delete statement in the database",
	XERR_REPO_DELETE_VERIFY_ROWS_FAILED:         "failed to verify affected rows during delete operation",
	XERR_REPO_DELETE_RECORD_NOT_FOUND:           "target record not found in database for delete operation",
	XERR_REPO_INTERFACE_ASSERTION_FAILED:        "internal error: entity type does not implement database dao interface",
	XERR_REPO_GET_BY_ID_EXEC_FAILED:             "failed to execute select single record query",
	XERR_REPO_GET_BY_ID_RECORD_NOT_FOUND:        "requested record not found in the database table",
	XERR_REPO_GET_BY_ID_SCAN_FAILED:             "failed to scan database columns into entity memory pointers",
	XERR_REPO_GET_ALL_EXEC_FAILED:               "failed to execute select collection list query",
	XERR_REPO_GET_ALL_SCAN_FAILED:               "failed to scan row iteration into entity memory pointers",
	XERR_REPO_GET_ALL_ITERATION_FAILED:          "database cursor failure during rows iteration process",
	XERR_REPO_GET_BY_FIELD_EXEC_FAILED:          "failed to execute field query statement in the database",
	XERR_REPO_GET_BY_FIELD_SCAN_FAILED:          "failed to scan database row into the entity fields",
	XERR_REPO_GET_WHERE_ARGS_MISMATCH:           "query parameters count does not match the provided arguments length",
	XERR_REPO_GET_WHERE_EXEC_FAILED:             "failed to execute conditional query statement in the database",
	XERR_REPO_GET_WHERE_SCAN_FAILED:             "failed to scan conditional database row into the entity fields",
	XERR_REPO_QUERY_RAW_EXEC_FAILED:             "failed to execute raw sql query statement in the database",
	XERR_REPO_QUERY_RAW_SCAN_FAILED:             "failed to scan database row into the raw query destination structure",
}

ErrorMessages acts as a centralized English translation catalog for core repository errors.

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 {
	// 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)

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

	// 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

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

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

	// PKValue returns the current snapshot value of the primary key field (e.g., an int64 ID or a string UUID).
	PKValue() 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

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

	// IsNaturalPK indicates whether the entity primary key is a natural identifier supplied from an external context outside the system.
	IsNaturalPK() bool
}

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