database

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Global = NewManager()

Global is a process-wide manager. Applications typically use this; tests and library code should construct their own Manager.

Functions

func Register

func Register(name string, factory DriverFactory)

Register installs a driver factory under name. Drivers should call this in their package init. Re-registration overwrites silently.

Types

type ColumnTypeOptions

type ColumnTypeOptions struct {
	Length        int
	Precision     int
	Scale         int
	Unsigned      bool
	AutoIncrement bool
	Allowed       []string // for ENUM/SET
}

ColumnTypeOptions carries portable options understood by Grammar.CompileType.

type Config

type Config struct {
	// Driver is the name of a registered driver: "postgres", "mysql", "sqlite".
	Driver string `json:"driver"`
	// DSN is a fully-formed connection string. If non-empty it takes precedence
	// over the field-based options below.
	DSN string `json:"dsn,omitempty"`

	Host     string            `json:"host,omitempty"`
	Port     int               `json:"port,omitempty"`
	Username string            `json:"username,omitempty"`
	Password string            `json:"password,omitempty"`
	Database string            `json:"database,omitempty"`
	Schema   string            `json:"schema,omitempty"`
	SSLMode  string            `json:"ssl_mode,omitempty"`
	TimeZone string            `json:"timezone,omitempty"`
	Params   map[string]string `json:"params,omitempty"`

	// Pool settings.
	MaxOpenConns    int           `json:"max_open_conns,omitempty"`
	MaxIdleConns    int           `json:"max_idle_conns,omitempty"`
	ConnMaxIdleTime time.Duration `json:"conn_max_idle_time,omitempty"`
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime,omitempty"`

	// Logging.
	LogQueries      bool          `json:"log_queries,omitempty"`
	SlowQuery       time.Duration `json:"slow_query,omitempty"`
	TablePrefix     string        `json:"table_prefix,omitempty"`
	MigrationsTable string        `json:"migrations_table,omitempty"`
}

Config describes one named database connection.

func (Config) BuildDSN

func (c Config) BuildDSN() (string, error)

BuildDSN returns the DSN derived from the structured fields. Drivers may override this through their own grammar; this is the framework's default behavior and is safe for the common case.

type Connection

type Connection struct {
	Name    string
	DB      *sql.DB
	Grammar Grammar
	Config  Config
	Log     *logger.Logger
	// Loc is the active *time.Location resolved from Config.TimeZone. The
	// ORM uses it for CreatedAt/UpdatedAt timestamps so values written to
	// the database honor the application's selected time zone.
	Loc *time.Location
	// contains filtered or unexported fields
}

Connection wraps *sql.DB together with the dialect grammar and connection metadata. It is goroutine-safe and the canonical handle passed across the framework.

func (*Connection) Close

func (c *Connection) Close() error

Close terminates the underlying pool. Subsequent calls are no-ops.

func (*Connection) ExecContext

func (c *Connection) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext logs (if enabled) and forwards Exec to the pool.

func (*Connection) Location added in v0.2.0

func (c *Connection) Location() *time.Location

Location returns the active *time.Location (always non-nil; defaults to time.UTC). Use this to format or convert times consistently across the app: `t.In(conn.Location())`.

func (*Connection) Now added in v0.2.0

func (c *Connection) Now() time.Time

Now returns the current time in the connection's configured location. The ORM uses this when populating CreatedAt/UpdatedAt.

func (*Connection) Ping

func (c *Connection) Ping(ctx context.Context) error

Ping verifies the connection is alive.

func (*Connection) PrepareContext

func (c *Connection) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

PrepareContext prepares a statement.

func (*Connection) QueryContext

func (c *Connection) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext logs and forwards Query.

func (*Connection) QueryRowContext

func (c *Connection) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext logs and forwards QueryRow.

func (*Connection) Transaction

func (c *Connection) Transaction(ctx context.Context, fn func(tx *Tx) error) error

Transaction runs fn inside a transaction, committing on success or rolling back on error / panic. fn receives a *Tx that satisfies Executor.

func (*Connection) TransactionWith

func (c *Connection) TransactionWith(ctx context.Context, opts *sql.TxOptions, fn func(tx *Tx) error) (err error)

TransactionWith allows setting transaction options.

type DriverFactory

type DriverFactory func(dsn string) (*sql.DB, Grammar, error)

DriverFactory opens a database/sql.DB for the given DSN.

type Executor

type Executor 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
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

Executor is the minimal interface that every query target satisfies — both raw *sql.DB and *sql.Tx implement it. ORM/query code accepts an Executor so the same calls work transparently inside or outside a transaction.

type Grammar

type Grammar interface {
	// Name returns the driver name, e.g. "postgres".
	Name() string
	// Quote wraps an identifier (table or column) in dialect quotes.
	Quote(ident string) string
	// Placeholder returns the placeholder for the n-th positional argument
	// (1-indexed). "?" for MySQL/SQLite, "$1", "$2", … for Postgres.
	Placeholder(n int) string
	// CompileType maps a portable column kind + options to a dialect-specific
	// SQL fragment. See schema.CompileType for full options.
	CompileType(kind string, opts ColumnTypeOptions) string
	// SupportsReturning indicates whether INSERT … RETURNING is supported.
	SupportsReturning() bool
	// LastInsertIDStrategy describes how a driver returns IDs from inserts.
	LastInsertIDStrategy() InsertIDStrategy
}

Grammar is implemented by drivers to provide SQL dialect-specific rendering. Schema/migration/query packages depend on this interface rather than on a concrete driver.

type InsertIDStrategy

type InsertIDStrategy int

InsertIDStrategy enumerates how a driver returns the last-inserted ID.

const (
	// InsertIDFromResult uses sql.Result.LastInsertId() (MySQL, SQLite).
	InsertIDFromResult InsertIDStrategy = iota
	// InsertIDViaReturning appends RETURNING <pk> to inserts (Postgres).
	InsertIDViaReturning
)

type Manager

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

Manager holds a set of named connections.

func NewManager

func NewManager() *Manager

NewManager creates an empty connection manager. The default logger is a silent logger; call SetLogger to wire SQL logging.

func (*Manager) Close

func (m *Manager) Close() error

Close terminates all connections in the manager.

func (*Manager) Connection

func (m *Manager) Connection(name string) (*Connection, error)

Connection returns a named connection, or the default if name == "".

func (*Manager) Default

func (m *Manager) Default() (*Connection, error)

Default returns the default connection.

func (*Manager) Open

func (m *Manager) Open(name string, cfg Config) (*Connection, error)

Open creates a connection with the given name and config and registers it.

func (*Manager) Ping

func (m *Manager) Ping(ctx context.Context) error

Ping pings every connection.

func (*Manager) SetDefault

func (m *Manager) SetDefault(name string) error

SetDefault selects which named connection is returned by Connection("").

func (*Manager) SetLogger

func (m *Manager) SetLogger(l *logger.Logger)

SetLogger replaces the manager's logger and applies it to any existing connections.

func (*Manager) Use

func (m *Manager) Use(name string, conn *Connection)

Use registers an externally-built connection. Useful when the host application owns the *sql.DB lifecycle.

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Tx wraps *sql.Tx with the parent Connection, satisfying Executor.

func (*Tx) Connection

func (t *Tx) Connection() *Connection

Connection returns the parent connection (provides Grammar etc.).

func (*Tx) RollbackTo

func (t *Tx) RollbackTo(ctx context.Context, name string) error

RollbackTo rolls back to a previously created savepoint.

func (*Tx) Savepoint

func (t *Tx) Savepoint(ctx context.Context, name string) error

Savepoint creates a SQL savepoint within this transaction.

Jump to

Keyboard shortcuts

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