rds

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MPL-2.0 Imports: 9 Imported by: 0

Documentation

Overview

blocks/rds/block.go

blocks/rds/operations.go

blocks/rds/options.go

blocks/rds/types.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func QueryAll

func QueryAll[T any](ctx context.Context, b *Block, query string, args ...any) ([]T, error)

QueryAll executes a SELECT and scans all rows into a slice of T. T must be a struct whose fields carry `db:` or `json:` tags matching the column names.

users, err := rds.QueryAll[User](ctx, db,
    "SELECT id, name, email FROM users WHERE active = $1", true)

Types

type Block

type Block struct {
	// contains filtered or unexported fields
}

Block is an RDS integration block. It manages a *sql.DB connection pool and exposes typed query helpers for PostgreSQL, MySQL and Aurora.

The driver is selected via WithDriver; the connection string is built automatically from the individual options or supplied directly via WithDSN.

func New

func New(name string, opts ...Option) *Block

New creates a new RDS Block.

// PostgreSQL
db := rds.New("users-db",
    rds.WithDriver(rds.DriverPostgres),
    rds.WithHost("mydb.cluster-xyz.us-east-1.rds.amazonaws.com"),
    rds.WithPort(5432),
    rds.WithDatabase("myapp"),
    rds.WithUsername("app"),
    rds.WithPassword("secret"),
    rds.WithMaxOpenConns(20),
)

// Full DSN (e.g. secret fetched from Secrets Manager)
db := rds.New("users-db",
    rds.WithDriver(rds.DriverPostgres),
    rds.WithDSN(dsn),
)

func (*Block) DB

func (b *Block) DB() *sql.DB

DB returns the underlying *sql.DB for advanced use cases (transactions, COPY, raw driver features). Prefer the typed helpers for regular queries.

func (*Block) Exec

func (b *Block) Exec(ctx context.Context, query string, args ...any) (ExecResult, error)

Exec executes an INSERT, UPDATE, DELETE or DDL statement. Returns the number of affected rows and the last insert ID (MySQL only; PostgreSQL should use RETURNING instead).

result, err := db.Exec(ctx,
    "UPDATE users SET status = $1 WHERE id = $2",
    "inactive", userID)

func (*Block) Init

func (b *Block) Init(ctx context.Context) error

Init implements core.Block. It opens the connection pool and verifies connectivity with a Ping.

func (*Block) Name

func (b *Block) Name() string

Name implements core.Block.

func (*Block) Ping

func (b *Block) Ping(ctx context.Context) error

Ping verifies the database connection is still alive. Useful for health checks.

func (*Block) QueryOne

func (b *Block) QueryOne(ctx context.Context, dest any, query string, args ...any) error

QueryOne executes a SELECT and scans the first row into dest using json-roundtrip mapping (column name → json tag on struct fields). Returns sql.ErrNoRows (wrapped) when nothing is found.

var user User
err := db.QueryOne(ctx, &user,
    "SELECT id, name, email FROM users WHERE id = $1", userID)

func (*Block) QueryRows

func (b *Block) QueryRows(ctx context.Context, query string, args ...any) ([]Row, error)

QueryRows executes a SELECT and returns every row as a []Row (map of column name → value). Useful for dynamic queries where the schema is not known at compile time.

rows, err := db.QueryRows(ctx,
    "SELECT id, name, email FROM users WHERE status = $1",
    "active",
)

func (*Block) Shutdown

func (b *Block) Shutdown(_ context.Context) error

Shutdown implements core.Block. Closes all connections in the pool.

func (*Block) Tx

func (b *Block) Tx(ctx context.Context, fn func(*sql.Tx) error) error

Tx executes fn inside a database transaction. If fn returns an error the transaction is rolled back; otherwise it is committed.

err := db.Tx(ctx, func(tx *sql.Tx) error {
    _, err := tx.ExecContext(ctx, "INSERT INTO orders ...")
    if err != nil { return err }
    _, err = tx.ExecContext(ctx, "UPDATE inventory ...")
    return err
})

type Driver

type Driver string

Driver identifies the database engine.

const (
	// DriverPostgres targets PostgreSQL and Aurora PostgreSQL.
	// Uses github.com/lib/pq or pgx under the hood.
	DriverPostgres Driver = "postgres"

	// DriverMySQL targets MySQL and Aurora MySQL.
	// Uses github.com/go-sql-driver/mysql under the hood.
	DriverMySQL Driver = "mysql"
)

type ExecResult

type ExecResult struct {
	RowsAffected int64
	LastInsertID int64
}

ExecResult wraps sql.Result for convenience.

type Option

type Option func(*blockConfig)

Option configures an RDS Block.

func WithConnMaxIdleTime

func WithConnMaxIdleTime(d time.Duration) Option

WithConnMaxIdleTime sets the maximum time a connection may remain idle. Defaults to 1 minute.

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) Option

WithConnMaxLifetime sets the maximum time a connection may be reused. Defaults to 5 minutes.

func WithDSN

func WithDSN(dsn string) Option

WithDSN sets the full connection string, bypassing individual host/port/user options. Useful when the DSN is read from Secrets Manager or SSM at runtime.

// PostgreSQL
rds.WithDSN("postgres://user:pass@host:5432/dbname?sslmode=require")

// MySQL
rds.WithDSN("user:pass@tcp(host:3306)/dbname?parseTime=true")

func WithDatabase

func WithDatabase(db string) Option

WithDatabase sets the target database/schema name.

func WithDriver

func WithDriver(d Driver) Option

WithDriver sets the database engine. Must be DriverPostgres or DriverMySQL. Required unless WithDSN is used.

func WithHost

func WithHost(host string) Option

WithHost sets the database server hostname or IP. Defaults to "localhost".

func WithMaxIdleConns

func WithMaxIdleConns(n int) Option

WithMaxIdleConns sets the maximum number of idle connections kept in the pool. Defaults to 5.

func WithMaxOpenConns

func WithMaxOpenConns(n int) Option

WithMaxOpenConns sets the maximum number of open connections. Defaults to 10.

func WithPassword

func WithPassword(pass string) Option

WithPassword sets the login password.

func WithPort

func WithPort(port int) Option

WithPort sets the database server port. Defaults to 5432 for PostgreSQL and 3306 for MySQL.

func WithQueryTimeout

func WithQueryTimeout(d time.Duration) Option

WithQueryTimeout sets the default context timeout applied to every query that doesn't provide its own context deadline. Defaults to 30 seconds.

func WithSSLMode

func WithSSLMode(mode string) Option

WithSSLMode sets the PostgreSQL SSL mode. Accepted values: disable, require, verify-ca, verify-full. Defaults to "require" for production safety.

func WithUsername

func WithUsername(user string) Option

WithUsername sets the login username.

type Page

type Page[T any] struct {
	Items    []T
	Total    int64 // total rows matching the query (requires COUNT subquery)
	Page     int
	PageSize int
	HasMore  bool
}

Page is a paginated result set returned by QueryPage.

func QueryPage

func QueryPage[T any](ctx context.Context, b *Block, pageNum, pageSize int, query string, args ...any) (Page[T], error)

QueryPage executes a paginated SELECT and returns a Page[T]. The query must include LIMIT and OFFSET placeholders as the last two args.

page, err := rds.QueryPage[User](ctx, db, 1, 20,
    "SELECT id, name FROM users WHERE active = $1", true)

type Row

type Row map[string]any

Row is a single result row represented as a map of column name → value. Values are raw []byte from the driver; use the typed helpers or Scan[T] for structured results.

Jump to

Keyboard shortcuts

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