Documentation
¶
Overview ¶
Package db provides a SQLite database abstraction compatible with database/sql.
This package offers a simple interface for SQLite operations using modernc.org/sqlite driver. It exposes stdlib-compatible methods (QueryContext, QueryRowContext, ExecContext, BeginTx) along with generic scanning functions (Scan, ScanAll) for mapping rows to Go types.
Key features:
- stdlib-compatible API: QueryContext, QueryRowContext, ExecContext, BeginTx
- Generic Scan[T] for single row mapping
- Generic ScanAll[T] for multiple rows with iterator pattern
- Hybrid column mapping: explicit db tags or automatic snake_case conversion
- Support for SELECT * queries with any column order (ScanAll only)
- Iterator-based results with iter.Seq2[T, error] for proper error handling
- Database initialization from APP_NAME environment variable
Example usage:
close, err := db.Init()
if err != nil {
log.Fatal(err)
}
defer close()
// Single row query
row := db.QueryRowContext(ctx, "SELECT * FROM users WHERE id = ?", 1)
user, err := db.Scan[User](row)
if err != nil {
// handle error
}
// Multiple rows query
rows, err := db.QueryContext(ctx, "SELECT * FROM users ORDER BY id")
if err != nil {
// handle error
}
for user, err := range db.ScanAll[User](rows) {
if err != nil {
// handle error
}
// use user
}
// Transaction
tx, err := db.BeginTx(ctx, nil)
if err != nil {
// handle error
}
defer tx.Rollback()
// ... use tx
tx.Commit()
Index ¶
- func BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func Init() (func() error, error)
- func QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func Scan[T any](row *sql.Row) (T, error)
- func ScanAll[T any](rows *sql.Rows) iter.Seq2[T, error]
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BeginTx ¶
BeginTx starts a transaction. The default isolation level is dependent on the driver.
func ExecContext ¶
ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.
func QueryContext ¶
QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.
func QueryRowContext ¶
QueryRowContext executes a query that is expected to return at most one row. The args are for any placeholder parameters in the query.
func Scan ¶
Scan scans a single row into a value of type T. For scalar types (string, int, etc.), it scans directly. For struct types, it scans fields in declaration order with NULL handling. Pointer fields receive nil for NULL values, non-pointer primitives receive zero values.
Types ¶
This section is empty.