Documentation
¶
Index ¶
- Variables
- func Register(name string, factory DriverFactory)
- type ColumnTypeOptions
- type Config
- type Connection
- func (c *Connection) Close() error
- func (c *Connection) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (c *Connection) Location() *time.Location
- func (c *Connection) Now() time.Time
- func (c *Connection) Ping(ctx context.Context) error
- func (c *Connection) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (c *Connection) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (c *Connection) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (c *Connection) Transaction(ctx context.Context, fn func(tx *Tx) error) error
- func (c *Connection) TransactionWith(ctx context.Context, opts *sql.TxOptions, fn func(tx *Tx) error) (err error)
- type DriverFactory
- type Executor
- type Grammar
- type InsertIDStrategy
- type Manager
- func (m *Manager) Close() error
- func (m *Manager) Connection(name string) (*Connection, error)
- func (m *Manager) Default() (*Connection, error)
- func (m *Manager) Open(name string, cfg Config) (*Connection, error)
- func (m *Manager) Ping(ctx context.Context) error
- func (m *Manager) SetDefault(name string) error
- func (m *Manager) SetLogger(l *logger.Logger)
- func (m *Manager) Use(name string, conn *Connection)
- type Tx
Constants ¶
This section is empty.
Variables ¶
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.
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 ¶
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 ¶
QueryRowContext logs and forwards QueryRow.
func (*Connection) Transaction ¶
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 ¶
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) 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) SetDefault ¶
SetDefault selects which named connection is returned by Connection("").
func (*Manager) SetLogger ¶
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 ¶
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 ¶
RollbackTo rolls back to a previously created savepoint.