db

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 7 Imported by: 0

README

go-dbx

A lightweight Go database utility library that provides enhanced database operations with asynchronous support and automatic struct mapping.

Features

  • Asynchronous Operations: Execute database queries and transactions asynchronously
  • Generic Type Support: Type-safe query results with Go generics
  • Automatic Struct Mapping: Map query results to structs using reflection and db tags
  • Transaction Management: Simplified transaction handling with automatic commit/rollback
  • Lightweight: Minimal abstraction over Go's standard database/sql package
  • Context Support: Full context support for cancellation and timeouts

Installation

go get github.com/uoul/go-dbx

Requirements

  • Go 1.25.4 or higher
  • Dependencies: github.com/uoul/go-async v1.0.0

Core Interfaces

IDbSession

Basic database session interface for executing queries:

type IDbSession interface {
    QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}
IDbConnection

Extended interface that includes transaction support:

type IDbConnection interface {
    IDbSession
    BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

Usage Examples

Basic Queries
package main

import (
    "context"
    "database/sql"
    "fmt"
    "log"
    
    "github.com/uoul/go-dbx/db"
    _ "github.com/go-sql-driver/mysql"
)

type User struct {
    ID    int    `db:"id"`
    Name  string `db:"name"`
    Email string `db:"email"`
}

func main() {
    // Open database connection
    database, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
    if err != nil {
        log.Fatal(err)
    }
    defer database.Close()
    
    ctx := context.Background()
    
    // Execute synchronous query
    users, err := db.Query[User](ctx, database, "SELECT id, name, email FROM users WHERE active = ?", true)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Found %d users\n", len(users))
    for _, user := range users {
        fmt.Printf("User: %s (%s)\n", user.Name, user.Email)
    }
}
Asynchronous Queries
// Execute asynchronous query
result := db.QueryAsync[User](ctx, database, "SELECT id, name, email FROM users")

// Do other work...

// Get the result when ready
users := <-result
if users.Error != nil {
    log.Fatal(err)
}

fmt.Printf("Async query returned %d users\n", len(users.Value))
Struct Mapping with Tags

The library automatically maps database columns to struct fields using the db tag:

type UserProfile struct {
    UserID      int    `db:"user_id"`
    FirstName   string `db:"first_name"`
    LastName    string `db:"last_name"`
    Email       string `db:"email"`
    CreatedAt   string `db:"created_at"`
}

// The library will automatically map columns to struct fields
profiles, err := db.Query[UserProfile](ctx, database, 
    "SELECT user_id, first_name, last_name, email, created_at FROM user_profiles")
Nested Struct Support

The library supports nested structs with automatic field mapping:

type Address struct {
    Street string `db:"street"`
    City   string `db:"city"`
    State  string `db:"state"`
}

type UserWithAddress struct {
    ID      int     `db:"id"`
    Name    string  `db:"name"`
    Address Address `db:"address_"` // Prefix for nested fields
}

// Maps columns like: id, name, address_street, address_city, address_state

API Reference

Query Functions
Function Description
Query[T any](ctx context.Context, session IDbSession, query string, args ...any) ([]T, error) Execute SQL query synchronously and return typed results
QueryAsync[T any](ctx context.Context, session IDbSession, query string, args ...any) async.Result[[]T] Execute SQL query asynchronously
Transaction Functions
Function Description
ExecuteInTransaction(ctx context.Context, conn IDbConnection, opts *sql.TxOptions, fn TransactionScopeFunction) error Execute function within a database transaction with automatic commit/rollback
ExecuteInTransactionAsync(ctx context.Context, conn IDbConnection, opts *sql.TxOptions, fn TransactionScopeFunction) async.Result[any] Execute transaction asynchronously

Error Handling

The library provides comprehensive error handling:

  • Automatic transaction rollback on errors or panics
  • Context cancellation support
  • Proper resource cleanup

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

Acknowledgments

  • Built with Go's standard database/sql package
  • Utilizes the github.com/uoul/go-async library for asynchronous operations
  • Designed for simplicity and performance

Made with ❤️ for the Go community

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExecuteInTransaction

func ExecuteInTransaction[T any](ctx context.Context, db IDbConnection, tsf TransactionScopeFunction[T], opts ...sql.TxOptions) (T, error)

ExecuteInTransaction executes the provided function within a database transaction.

This function creates a new transaction using the provided database connection and executes the given TransactionScopeFunction within that transaction context. If the function completes successfully, the transaction is committed; otherwise, it is rolled back. The transaction is also rolled back if a panic occurs during execution (via deferred rollback).

Type parameter T represents the return type of the transaction function, allowing for flexible return values based on the specific business logic requirements.

Parameters:

  • ctx: Context for cancellation and timeout control, propagated to the transaction
  • db: Database connection to use for creating the transaction
  • tsf: Function to execute within the transaction scope
  • opts: Optional transaction options (isolation level, read-only mode, etc.). If not provided, default transaction options are used.

Returns:

  • T: The result returned by the transaction function
  • error: Non-nil if transaction creation, execution, or commit fails

func ExecuteInTransactionAsync

func ExecuteInTransactionAsync[T any](ctx context.Context, db IDbConnection, tsf TransactionScopeFunction[T], opts ...sql.TxOptions) async.Result[T]

ExecuteInTransactionAsync executes a database transaction asynchronously and returns the result.

This function wraps the synchronous ExecuteInTransaction function in an asynchronous execution context, allowing the transaction to run concurrently without blocking the caller. The result is returned as an async.Result that can be awaited or processed later.

The function leverages Go's concurrency model to execute the entire transaction lifecycle (begin, execute, commit/rollback) in a separate goroutine, making it suitable for scenarios where: - You want to execute multiple independent transactions in parallel - You need to avoid blocking the main execution flow while waiting for transaction completion - You're implementing non-blocking data persistence patterns - You want to improve throughput by overlapping transaction execution with other work

Type parameter T represents the return type of the transaction function, allowing for flexible return values based on the specific business logic requirements.

Parameters:

  • ctx: Context for cancellation and timeout control, propagated to the underlying transaction
  • db: Database connection to use for creating the transaction
  • tsf: Function to execute within the transaction scope
  • opts: Optional transaction options (isolation level, read-only mode, etc.). If not provided, default transaction options are used.

Returns:

  • async.Result[T]: An async result object containing either:
  • The result returned by the transaction function
  • An error if transaction creation, execution, or commit fails

func NewErrInvalidDataType added in v1.0.4

func NewErrInvalidDataType(format string, args ...any) error

func Query

func Query[T any](ctx context.Context, conn IDbSession, query string, args ...any) ([]T, error)

Query executes a SQL query and returns the results as a slice of type T.

The function performs the following operations: 1. Executes the provided SQL query with the given arguments using the database session 2. Parses the returned rows into a slice of the specified type T 3. Ensures proper resource cleanup by closing the rows

Type parameter T must be a type that can be populated from database rows. The actual mapping from database rows to type T is handled by parseDbResult.

Parameters:

  • ctx: Context for cancellation and timeout control
  • conn: Database session (connection or transaction) to execute the query on
  • query: SQL query string to execute
  • args: Variadic arguments to be used as query parameters (prevents SQL injection)

Returns:

  • []T: Slice of results parsed from the query, empty slice if no rows match
  • error: Non-nil if query execution or result parsing fails

func QueryAsync

func QueryAsync[T any](ctx context.Context, conn IDbSession, query string, args ...any) async.Result[[]T]

QueryAsync executes a SQL query asynchronously and returns the results as a slice of type T.

This function wraps the synchronous Query function in an asynchronous execution context, allowing the query to run concurrently without blocking the caller. The result is returned as an async.Result that can be awaited or processed later.

The function leverages Go's concurrency model to execute the database query in a separate goroutine, making it suitable for scenarios where you want to: - Execute multiple independent queries in parallel - Avoid blocking the main execution flow while waiting for database results - Implement non-blocking data fetching patterns

Types

type ErrInvalidDataType added in v1.0.4

type ErrInvalidDataType struct {
	Message string
}

---------------------------------------------------------------------- ErrInvalidDataType ----------------------------------------------------------------------

func (ErrInvalidDataType) Error added in v1.0.4

func (e ErrInvalidDataType) Error() string

Error implements error.

type IDbConnection

type IDbConnection interface {
	IDbSession
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

type IDbSession

type IDbSession interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

type TransactionScopeFunction

type TransactionScopeFunction[T any] func(ctx context.Context, tx *sql.Tx) (T, error)

TransactionScopeFunction is a function type that executes database operations within a transaction context.

This function type is designed to encapsulate business logic that requires transactional guarantees. It receives a context for cancellation/timeout control and a transaction object for executing database operations, and returns a result of type T along with any error that occurred.

Type parameter T represents the return type of the transaction function, allowing for flexible return values based on the specific use case.

Parameters:

  • ctx: Context for cancellation and timeout control during transaction execution
  • tx: Active database transaction to use for executing queries and commands

Returns:

  • T: Result of the transaction operations (type determined by caller)
  • error: Non-nil if any operation within the transaction fails

Jump to

Keyboard shortcuts

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