database

package
v0.0.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSQLDB

func NewSQLDB(driver string, dsn string) (*sqlDB, error)

NewSQLDB creates a new instance of SQLDB and connects to the database using the provided driver and connection string.

Parameters:

  • driver: The database driver name.
  • dsn: The database connection string.

Returns:

  • *sqlDB: A new sqlDB instance.
  • error: An error if the connection fails.

func Query

func Query(
	ctx context.Context,
	preparer Preparer,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
) (Rows, Stmt, error)

Query prepares and executes a query that returns rows. The caller is responsible for closing both the returned rows and statement.

Parameters:

  • ctx: Context to use.
  • preparer: The preparer to use for the query.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.

Returns:

  • Rows: The rows of the query.
  • Stmt: The statement of the query.
  • error: An error if the query fails.

func QueryEntities

func QueryEntities[Entity Getter](
	ctx context.Context,
	preparer Preparer,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
	factoryFn func() Entity,
) ([]Entity, error)

QueryEntities executes a query and scans all entities of type T, handling statement and row closures internally.

Parameters:

  • ctx: Context to use.
  • preparer: The preparer to use for the query.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.
  • factoryFn: A function that returns a new instance of T.

Returns:

  • []T: A slice of entities scanned from the query.
  • error: An error if the query fails.

func QuerySingleEntity

func QuerySingleEntity[Entity Getter](
	ctx context.Context,
	preparer Preparer,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
	factoryFn func() Entity,
) (Entity, error)

QuerySingleEntity executes a query and scans a single entity of type T, handling statement and row closures internally.

Parameters:

  • ctx: Context to use.
  • preparer: The preparer to use for the query.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.
  • factoryFn: A function that returns a new instance of T.

Returns:

  • T: The entity scanned from the query.
  • error: An error if the query fails.

func QuerySingleValue

func QuerySingleValue[T any](
	ctx context.Context,
	preparer Preparer,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
	factoryFn func() T,
) (T, error)

QuerySingleValue executes a query that is expected to return a single scalar value. It prepares the query, executes it using QueryRow, scans the result using the provided factory function, and checks for errors.

Parameters:

  • ctx: Context to use.
  • preparer: The preparer to use for the query.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.
  • factoryFn: A function that returns a new instance of T (typically a pointer).

Returns:

  • T: The scanned scalar value.
  • error: An error if the query or scan fails.

func RowToAnyScalar

func RowToAnyScalar[T any](
	_ context.Context, row Row, factoryFn func() T,
) (T, error)

RowToAnyScalar scans a single row into a new scalar value of type T. It uses factoryFn to create an instance of T, scans the row into it, and then checks for any scanning errors.

Parameters:

  • ctx: Context to use.
  • row: The row to scan.
  • factoryFn: A function that returns a new instance of T (typically a pointer).

Returns:

  • T: The entity scanned from the row.
  • error: An error if scanning fails.

func RowToEntity

func RowToEntity[T Getter](
	_ context.Context, row Row, factoryFn func() T,
) (T, error)

RowToEntity scans a single row into a new entity.

Parameters:

  • ctx: Context to use.
  • row: The row to scan.
  • factoryFn: A function that returns a new instance of T.

Returns:

  • T: The entity scanned from the row.
  • error: An error if the scan fails.

func RowsToAnyScalars

func RowsToAnyScalars[T any](
	ctx context.Context, rows Rows, factoryFn func() T,
) ([]T, error)

RowsToAnyScalars scans all rows into a slice of scalar values of type T. It repeatedly calls RowToAny for each row returned by rows.

Parameters:

  • ctx: Context to use.
  • rows: The rows to scan.
  • factoryFn: A function that returns a new instance of T (typically a pointer).

Returns:

  • []T: A slice of entities scanned from the rows.
  • error: An error if scanning any row fails.

func RowsToEntities

func RowsToEntities[T Getter](
	_ context.Context, rows Rows, factoryFn func() T,
) ([]T, error)

RowsToEntities scans all rows into a slice of entities.

Parameters:

  • ctx: Context to use.
  • rows: The rows to scan.
  • factoryFn: A function that returns a new instance of T.

Returns:

  • []T: A slice of entities scanned from the rows.
  • error: An error if the scan fails.

func Transaction

func Transaction[Result any](
	ctx context.Context, tx Tx, txFn TxFn[Result],
) (result Result, txErr error)

Transaction executes a TxFn within a transaction. It recovers from panics, rolls back on errors, and commits if no error occurs.

Parameters:

  • ctx: The context for the transaction.
  • tx: The transaction to use.
  • txFn: The function to execute in a transaction.

Returns:

  • Result: The result of the transactional function.
  • error: An error if the transaction fails.

Types

type CRUDEntity

type CRUDEntity interface {
	Getter
	Mutator
}

CRUDEntity is a helper constraint for entities that can be both queried and altered.

type ConnOpenFn

type ConnOpenFn func(driver string, dsn string) (DB, error)

ConnOpenFn is a function that opens a database connection.

type ConnectConfig

type ConnectConfig struct {
	Driver          string        // Driver name. Required to connect.
	User            string        // Database user
	Password        string        // Database password
	Host            string        // Database host
	Port            int           // Database port
	Database        string        // Database name (e.g. "users")
	SocketDirectory string        // Unix socket directory
	SocketName      string        // Unix socket name
	Parameters      string        // Connection parameters
	ConnectionType  string        // Connection type
	ConnMaxLifetime time.Duration // Connection max lifetime
	ConnMaxIdleTime time.Duration // Connection max idle time
	MaxOpenConns    int           // Max open connections
	MaxIdleConns    int           // Max idle connections

	// DSNFormat is an optional format string (e.g. "%s:%s@tcp(%s:%d)/%s?%s").
	// If present (non-empty), it will be used to generate the DSN (with
	// fmt.Sprintf). You can embed placeholders for user, password, host,
	// port, database, and parameters. If left blank, the DSN() function
	// will fall back to a default per-driver build.
	DSNFormat string
}

ConnectConfig holds the configuration for the database connection.

type DB

type DB interface {
	Preparer
	UnderlyingDB() *sql.DB
	Ping() error
	SetConnMaxLifetime(d time.Duration)
	SetConnMaxIdleTime(d time.Duration)
	SetMaxOpenConns(n int)
	SetMaxIdleConns(n int)
	BeginTx(ctx context.Context, opts *sql.TxOptions) (Tx, error)
	Exec(query string, args ...any) (Result, error)
	Query(query string, args ...any) (Rows, error)
	QueryRow(query string, args ...any) Row
	Close() error
}

DB is an interface for core database operations and connection management.

func Connect

func Connect(
	cfg ConnectConfig,
	connOpenFn ConnOpenFn,
	dsn string,
) (DB, error)

Connect establishes a connection to the database using the provided configuration. It will automatically configure the connection based on the provided configuration and then attempt to ping the database.

Parameters:

  • cfg: The configuration for the database connection.
  • connOpenFn: The function to open the database connection.
  • dsn: The database connection string.

Returns:

  • DB: The database connection.
  • error: An error if the connection fails.

func NewSQLDBAdapter

func NewSQLDBAdapter(driver string, dsn string) (DB, error)

NewSQLDBAdapter creates a new instance of SQLDB and connects to the database using the provided driver and connection string. It adapts the NewSQLDB function to the DB interface.

Parameters:

  • driver: The database driver name.
  • dsn: The database connection string.

Returns:

  • DB: A new DB instance.
  • error: An error if the connection fails.

type ErrorChecker

type ErrorChecker interface {
	Check(err error) error
}

ErrorChecker translates database-specific errors into application errors.

type Getter

type Getter interface {
	TableNamer
	// ScanRow should populate the entity from the given Row.
	ScanRow(row Row) error
}

Getter can scan a database row into itself.

type Mutator

type Mutator interface {
	TableNamer
	// InsertedValues returns the column names and values for insertion.
	InsertedValues() ([]string, []any)
}

Mutator provides values for insert and update operations.

type Preparer

type Preparer interface {
	Prepare(query string) (Stmt, error)
}

Preparer is an interface for preparing SQL statements.

type RealResult

type RealResult struct {
	Result sql.Result
}

RealResult wraps sql.Result to implement the Result interface.

func (*RealResult) LastInsertId

func (r *RealResult) LastInsertId() (int64, error)

LastInsertId returns the last inserted id.

Returns:

  • int64: The last inserted id.
  • error: An error if the last inserted id cannot be retrieved.

func (*RealResult) RowsAffected

func (r *RealResult) RowsAffected() (int64, error)

RowsAffected returns the number of rows affected.

Returns:

  • int64: The number of rows affected.
  • error: An error if the number of rows affected cannot be retrieved.

type RealRow

type RealRow struct {
	*sql.Row
}

RealRow wraps *sql.Row to implement the Row interface.

func (*RealRow) Scan

func (r *RealRow) Scan(dest ...any) error

Scan scans the row into dest.

Parameters:

  • dest: The destination slice to scan into.

Returns:

  • error: An error if the row cannot be scanned.

type RealRows

type RealRows struct {
	*sql.Rows
}

RealRows wraps *sql.Rows to implement the Rows interface.

func (*RealRows) Close

func (r *RealRows) Close() error

Close closes the rows.

Returns:

  • error: An error if the rows cannot be closed.

func (*RealRows) Err

func (r *RealRows) Err() error

Err returns the error, if any, that was encountered during iteration.

Returns:

  • error: The error, if any, that was encountered during iteration.

func (*RealRows) Next

func (r *RealRows) Next() bool

Next advances the rows.

Returns:

  • bool: True if there are more rows, false otherwise.

func (*RealRows) Scan

func (r *RealRows) Scan(dest ...any) error

Scan scans the rows into dest.

Parameters:

  • dest: The destination slice to scan into.

Returns:

  • error: An error if the rows cannot be scanned.

type RealStmt

type RealStmt struct {
	*sql.Stmt
}

RealStmt wraps *sql.Stmt to implement the Stmt interface.

func (*RealStmt) Close

func (s *RealStmt) Close() error

Close closes the statement.

Returns:

  • error: An error if the statement cannot be closed.

func (*RealStmt) Exec

func (s *RealStmt) Exec(args ...any) (Result, error)

Exec executes a prepared statement with the given arguments.

Parameters:

  • args: The query parameters.

Returns:

  • Result: The result of the query.

func (*RealStmt) Query

func (s *RealStmt) Query(args ...any) (Rows, error)

Query executes a prepared query statement with the given arguments.

Parameters:

  • args: The query parameters.

Returns:

  • Rows: The rows of the query.

func (*RealStmt) QueryRow

func (s *RealStmt) QueryRow(args ...any) Row

QueryRow executes a prepared query statement with the given arguments.

Parameters:

  • args: The query parameters.

Returns:

  • Row: The row of the query.

type RealTx

type RealTx struct {
	*sql.Tx
}

RealTx wraps *sql.Tx to implement the Tx interface.

func (*RealTx) Commit

func (tx *RealTx) Commit() error

Prepare commits the transaction.

Returns:

  • error: An error if the transaction cannot be committed.

func (*RealTx) Exec

func (tx *RealTx) Exec(query string, args ...any) (Result, error)

Exec executes a query without returning rows.

Parameters:

  • query: The SQL query string to execute.
  • args: The query parameters.

Returns:

  • Result: The result of the query.
  • error: An error if the query cannot be executed.

func (*RealTx) Prepare

func (tx *RealTx) Prepare(query string) (Stmt, error)

Prepare prepares the statement.

Parameters:

  • query: The SQL query string to prepare.

Returns:

  • Stmt: The prepared statement.
  • error: An error if the statement cannot be prepared.

func (*RealTx) Rollback

func (tx *RealTx) Rollback() error

Rollback rollbacks the transaction.

Returns:

  • error: An error if the transaction cannot be rolled back.

type Result

type Result interface {
	LastInsertId() (int64, error)
	RowsAffected() (int64, error)
}

Result wraps *sql.Result for retrieving metadata of write operations.

func Exec

func Exec(
	ctx context.Context,
	preparer Preparer,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
) (Result, error)

Exec prepares and executes a query with parameters, returning the Result.

Parameters:

  • ctx: Context to use.
  • preparer: The preparer to use for the query.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.

Returns:

  • Result: The Result of the query.
  • error: An error if the query fails.

func ExecRaw

func ExecRaw(
	ctx context.Context,
	db DB,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
) (Result, error)

ExecRaw executes a query directly on the DB without explicit preparation.

Parameters:

  • ctx: Context to use.
  • db: The DB to execute the query on.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.

Returns:

  • Result: The Result of the query.
  • error: An error if the query fails.

type Row

type Row interface {
	// Scan scans the row into dest values.
	Scan(dest ...any) error
	Err() error
}

Row wraps *sql.Row for scanning a single result.

type Rows

type Rows interface {
	Next() bool
	// Scan scans the rows into dest values.
	Scan(dest ...any) error
	Close() error
	Err() error
}

Rows wraps *sql.Rows for scanning multiple results.

func QueryRaw

func QueryRaw(
	ctx context.Context,
	db DB,
	query string,
	parameters []any,
	errorChecker ErrorChecker,
) (Rows, error)

QueryRaw executes a query directly on the DB without preparation. The caller must close the returned rows.

Parameters:

  • ctx: Context to use.
  • db: The DB to execute the query on.
  • query: The SQL query to execute.
  • parameters: The query parameters.
  • errorChecker: An optional ErrorChecker to check for errors.

Returns:

  • Rows: The rows of the query.
  • error: An error if the query fails.

type Stmt

type Stmt interface {
	Close() error
	QueryRow(args ...any) Row
	Exec(args ...any) (Result, error)
	Query(args ...any) (Rows, error)
}

Stmt wraps *sql.Stmt methods for executing prepared statements.

type TableNamer

type TableNamer interface {
	TableName() string
}

TableNamer provides the table name for an entity.

type Tx

type Tx interface {
	Preparer
	Commit() error
	Rollback() error
	Exec(query string, args ...any) (Result, error)
}

Tx is an interface for transaction operations.

type TxFn

type TxFn[Result any] func(ctx context.Context, tx Tx) (Result, error)

TxFn is a function that takes in a transaction, and returns a result and an error.

Jump to

Keyboard shortcuts

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