driver

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package driver defines the shared interface that all database drivers implement.

Index

Constants

This section is empty.

Variables

AllDrivers lists all supported driver names for error messages and help text.

View Source
var Registry = map[Driver]Info{
	DriverPG: {
		Driver: DriverPG, DisplayLabel: "PostgreSQL",
		Scheme: "postgres", DefaultPort: 5432, DefaultDB: "postgres",
		HostPort: true, Credential: CredentialUserPass,
	},
	DriverCockroachDB: {
		Driver: DriverCockroachDB, DisplayLabel: "CockroachDB",
		Scheme: "cockroachdb", DefaultPort: 26257, DefaultDB: "defaultdb",
		HostPort: true, Credential: CredentialUserPass,
	},
	DriverMySQL: {
		Driver: DriverMySQL, DisplayLabel: "MySQL",
		Scheme: "mysql", DefaultPort: 3306, DefaultDB: "mysql",
		HostPort: true, Credential: CredentialUserPass,
	},
	DriverMariaDB: {
		Driver: DriverMariaDB, DisplayLabel: "MariaDB",
		Scheme: "mariadb", DefaultPort: 3306, DefaultDB: "mysql",
		HostPort: true, Credential: CredentialUserPass,
	},
	DriverMSSQL: {
		Driver: DriverMSSQL, DisplayLabel: "MSSQL",
		Scheme: "mssql", DefaultPort: 1433,
		HostPort: true, Credential: CredentialUserPass,
	},
	DriverSQLite: {
		Driver: DriverSQLite, DisplayLabel: "SQLite",
		Scheme: "sqlite", Credential: CredentialNone,
	},
	DriverDuckDB: {
		Driver: DriverDuckDB, DisplayLabel: "DuckDB",
		Scheme: "duckdb", Credential: CredentialNone,
	},
	DriverSnowflake: {
		Driver: DriverSnowflake, DisplayLabel: "Snowflake",
		Scheme: "snowflake", Credential: CredentialToken,
	},
}

Registry is the single source of truth for per-driver metadata. Adding a driver: add one entry here plus the driver-package implementation. All other places that switch on driver name (config/display, resolve, error messages) read from this map.

View Source
var WriteCommands = []string{
	"INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP",
	"TRUNCATE", "MERGE", "GRANT", "REVOKE",
}

WriteCommands is the shared set of SQL write commands used by keyword guards.

Functions

func DetectCommand

func DetectCommand(sql string, commands []string) string

DetectCommand checks if SQL starts with a known write command. Returns the matched command (e.g. "INSERT") or empty string.

func GuardReadOnly

func GuardReadOnly(sql string) error

GuardReadOnly validates that a SQL statement is read-only using keyword matching. Used by PG, CockroachDB, and MSSQL drivers as defense-in-depth alongside server-side enforcement (BEGIN READ ONLY, db_datareader role, etc.).

func IsConnectionURL

func IsConnectionURL(value string) bool

IsConnectionURL returns true if the value looks like a database URL.

func IsFilePath

func IsFilePath(value string) bool

IsFilePath returns true if the value looks like a database file path.

func NormalizeValue

func NormalizeValue(v any) any

NormalizeValue converts database driver return types to JSON-friendly types. Drivers with additional type conversions (e.g., PG UUIDs) should use their own version.

func QuoteIdentDot

func QuoteIdentDot(name string) string

QuoteIdentDot quotes an identifier with dot-splitting for schema-qualified names. Uses double-quote style quoting (ANSI SQL).

func SplitSchemaTable

func SplitSchemaTable(name, defaultSchema string) (string, string)

SplitSchemaTable splits a potentially schema-qualified name into (schema, table). If the name contains no dot, defaultSchema is used.

Types

type ColumnInfo

type ColumnInfo struct {
	Name         string `json:"name"`
	Type         string `json:"type"`
	Nullable     bool   `json:"nullable"`
	DefaultValue string `json:"defaultValue,omitempty"`
	PrimaryKey   bool   `json:"primaryKey,omitempty"`
}

ColumnInfo describes a table column.

type ColumnMatch

type ColumnMatch struct {
	Table  string `json:"table"`
	Column string `json:"column"`
}

ColumnMatch is a column that matched a search pattern.

type Connection

type Connection interface {
	// Query executes a SQL statement and returns the result.
	Query(ctx context.Context, sql string, opts QueryOpts) (*QueryResult, error)

	// GetTables lists tables and views. When includeSystem is false, system tables are excluded.
	GetTables(ctx context.Context, includeSystem bool) ([]TableInfo, error)

	// DescribeTable returns column information for a table.
	DescribeTable(ctx context.Context, table string) ([]ColumnInfo, error)

	// GetIndexes returns indexes. If table is empty, returns indexes for all tables.
	GetIndexes(ctx context.Context, table string) ([]IndexInfo, error)

	// GetConstraints returns constraints. If table is empty, returns all constraints.
	GetConstraints(ctx context.Context, table string) ([]ConstraintInfo, error)

	// SearchSchema searches table and column names by pattern.
	SearchSchema(ctx context.Context, pattern string) (*SearchResult, error)

	// QuoteIdent quotes an identifier for safe use in SQL.
	QuoteIdent(name string) string

	// Close releases the connection resources.
	Close() error
}

Connection is the core driver interface. Every database driver implements this. All methods that perform I/O take context.Context for timeout and cancellation.

type ConstraintInfo

type ConstraintInfo struct {
	Name              string         `json:"name"`
	Table             string         `json:"table"`
	Schema            string         `json:"schema,omitempty"`
	Type              ConstraintType `json:"type"`
	Columns           []string       `json:"columns"`
	ReferencedTable   string         `json:"referencedTable,omitempty"`
	ReferencedColumns []string       `json:"referencedColumns,omitempty"`
	Definition        string         `json:"definition,omitempty"`
}

ConstraintInfo describes a database constraint.

type ConstraintType

type ConstraintType string

ConstraintType classifies a constraint.

const (
	ConstraintPrimaryKey ConstraintType = "primary_key"
	ConstraintForeignKey ConstraintType = "foreign_key"
	ConstraintUnique     ConstraintType = "unique"
	ConstraintCheck      ConstraintType = "check"
)

func MapConstraintType

func MapConstraintType(s string) ConstraintType

MapConstraintType maps database constraint type strings to ConstraintType. Returns empty string for unrecognized types.

type CredentialKind added in v1.6.0

type CredentialKind string

CredentialKind classifies what authentication shape a driver expects.

const (
	// CredentialNone means the driver does not authenticate
	// (file-backed drivers: sqlite, duckdb).
	CredentialNone CredentialKind = "none"
	// CredentialUserPass requires both username and password.
	CredentialUserPass CredentialKind = "userpass"
	// CredentialToken requires only a password (used as a bearer token /
	// PAT). Currently snowflake.
	CredentialToken CredentialKind = "token"
)

type DDLDumper added in v1.3.0

type DDLDumper interface {
	GetDDL(ctx context.Context, table string) (string, error)
}

DDLDumper is an optional interface for drivers that can produce CREATE TABLE DDL. Used by `schema dump --format sql`.

type Driver

type Driver string

Driver identifies a database driver type.

const (
	DriverPG          Driver = "pg"
	DriverCockroachDB Driver = "cockroachdb"
	DriverMySQL       Driver = "mysql"
	DriverMariaDB     Driver = "mariadb"
	DriverSQLite      Driver = "sqlite"
	DriverDuckDB      Driver = "duckdb"
	DriverSnowflake   Driver = "snowflake"
	DriverMSSQL       Driver = "mssql"
)

func DetectDriverFromURL

func DetectDriverFromURL(url string) Driver

DetectDriverFromURL detects the driver type from a URL or file path. Returns empty string if unrecognized.

type IndexInfo

type IndexInfo struct {
	Name    string   `json:"name"`
	Table   string   `json:"table"`
	Schema  string   `json:"schema,omitempty"`
	Columns []string `json:"columns"`
	Unique  bool     `json:"unique"`
}

IndexInfo describes a database index.

type Info added in v1.6.0

type Info struct {
	// Driver is the canonical short name ("pg", "mysql", ...).
	Driver Driver

	// DisplayLabel is the human-readable name used in error messages
	// ("PostgreSQL", "CockroachDB", "MSSQL").
	DisplayLabel string

	// Scheme is the prefix used when building a display URL for this
	// driver (e.g. "postgres" for pg, "sqlserver" — actually "mssql" --
	// for go-mssqldb-style URLs).
	Scheme string

	// DefaultPort is the connect-time default for host:port drivers.
	// Zero for non-host:port drivers (sqlite, duckdb, snowflake).
	DefaultPort int

	// DefaultDB is the database name used when none is configured.
	// Empty when the driver requires the user to specify one (mssql)
	// or when the concept doesn't apply (sqlite, duckdb).
	DefaultDB string

	// HostPort is true for drivers that connect to host:port (pg,
	// cockroachdb, mysql, mariadb, mssql) and false for the rest.
	// Drives display rendering: HostPort drivers get
	// "scheme://host:port/database" URLs.
	HostPort bool

	// Credential describes the authentication shape required for
	// stored connections of this driver.
	Credential CredentialKind
}

Info is the canonical metadata for a single driver. Centralizing this here means adding a driver is a single Registry entry plus the driver-package implementation; downstream consumers (display rendering, resolve dispatch, credential validation) read from this registry rather than maintaining parallel switches.

func Lookup added in v1.6.0

func Lookup(d Driver) Info

Lookup returns metadata for d, or zero Info if unknown.

type QueryOpts

type QueryOpts struct {
	Write bool
}

QueryOpts controls query execution behavior.

type QueryResult

type QueryResult struct {
	Columns      []string
	Rows         []map[string]any
	RowsAffected int64
	Command      string // e.g. "INSERT", empty for SELECT
}

QueryResult holds the result of a SQL query.

func Collect added in v1.2.0

func Collect(iter *RowIterator) (*QueryResult, error)

Collect drains a RowIterator into a QueryResult.

func ScanAllRows added in v1.2.0

func ScanAllRows(rows *sql.Rows, normalize func(any) any) (*QueryResult, error)

ScanAllRows scans all rows from *sql.Rows into a QueryResult. The normalize function is applied to each value if non-nil. Closes rows when done.

type RowIterator added in v1.2.0

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

RowIterator streams query results row by row. Follows the Go scanner pattern: call Next() in a loop, then check Err().

func NewRowIterator added in v1.2.0

func NewRowIterator(columns []string, next func() bool, scan func() (map[string]any, error), err func() error, close func() error) *RowIterator

NewRowIterator creates a RowIterator from function callbacks.

func SQLRowsIterator added in v1.2.0

func SQLRowsIterator(rows *sql.Rows, normalize func(any) any) (*RowIterator, error)

SQLRowsIterator wraps *sql.Rows into a RowIterator. Used by drivers backed by database/sql (SQLite, MySQL, MSSQL).

func SliceIterator added in v1.2.0

func SliceIterator(columns []string, rows []map[string]any) *RowIterator

SliceIterator wraps a pre-collected slice as a RowIterator (for non-streaming drivers).

func (*RowIterator) Close added in v1.2.0

func (r *RowIterator) Close() error

Close releases the underlying resources.

func (*RowIterator) Columns added in v1.2.0

func (r *RowIterator) Columns() []string

Columns returns the column names.

func (*RowIterator) Err added in v1.2.0

func (r *RowIterator) Err() error

Err returns any error from iteration.

func (*RowIterator) Next added in v1.2.0

func (r *RowIterator) Next() bool

Next advances to the next row. Returns false when done.

func (*RowIterator) Scan added in v1.2.0

func (r *RowIterator) Scan() (map[string]any, error)

Scan returns the current row as a map.

type SearchResult

type SearchResult struct {
	Tables  []TableInfo   `json:"tables"`
	Columns []ColumnMatch `json:"columns"`
}

SearchResult holds schema search results.

type StreamingQuerier added in v1.2.0

type StreamingQuerier interface {
	QueryStream(ctx context.Context, sql string, opts QueryOpts) (*StreamingResult, error)
}

StreamingQuerier is an optional interface for drivers that support streaming. The CLI prefers this over Query() for read operations.

type StreamingResult added in v1.2.0

type StreamingResult struct {
	Iterator     *RowIterator // nil for write results
	RowsAffected int64
	Command      string
}

StreamingResult holds either a streaming iterator or a write result.

type TableInfo

type TableInfo struct {
	Name   string `json:"name"`
	Schema string `json:"schema,omitempty"`
	Type   string `json:"type,omitempty"` // "table" or "view"
}

TableInfo describes a database table or view.

Directories

Path Synopsis
Package cockroachdb implements the CockroachDB driver as a thin wrapper over the PostgreSQL driver.
Package cockroachdb implements the CockroachDB driver as a thin wrapper over the PostgreSQL driver.
Package duckdb implements the DuckDB driver as a subprocess.
Package duckdb implements the DuckDB driver as a subprocess.
Package mariadb provides a thin wrapper over the MySQL driver with variant set to "mariadb".
Package mariadb provides a thin wrapper over the MySQL driver with variant set to "mariadb".
Package mssql implements the Microsoft SQL Server driver using database/sql.
Package mssql implements the Microsoft SQL Server driver using database/sql.
Package mysql implements the MySQL/MariaDB driver using go-sql-driver/mysql.
Package mysql implements the MySQL/MariaDB driver using go-sql-driver/mysql.
Package pg implements the PostgreSQL driver using pgx/v5 directly.
Package pg implements the PostgreSQL driver using pgx/v5 directly.
Package snowflake implements the Snowflake driver using the SQL REST API v2.
Package snowflake implements the Snowflake driver using the SQL REST API v2.
Package sqlite implements the SQLite driver using modernc.org/sqlite (pure Go).
Package sqlite implements the SQLite driver using modernc.org/sqlite (pure Go).

Jump to

Keyboard shortcuts

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