sql

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package sql contains types and providers for connecting to and migrating SQL databases.

DSNs for this package are URI's with the driver as the scheme, eg. `postgres://...`.

To avoid bloating end-user binaries, drivers are excluded by default by build tags. To include a driver, add `--tags=<driver>` to Zero and your Go tools, or preferably set GOFLAGS='-tags=<driver>'. The latter will be picked up automatically

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckMigrations added in v0.7.0

func CheckMigrations(ctx context.Context, dsn string, db *sql.DB, migrations Migrations) error

CheckMigrations returns an error if there are missing migrations.

func CreateDatabase added in v0.9.0

func CreateDatabase(ctx context.Context, dsn string) error

CreateDatabase creates or recreates a database.

func Migrate added in v0.7.0

func Migrate(ctx context.Context, logger *slog.Logger, dsn string, db *sql.DB, migrations Migrations) error

Migrate applies all pending migrations to the database.

func New

func New(ctx context.Context, config Config, logger *slog.Logger, migrations Migrations) (db *sql.DB, err error)

New creates a new SQL database connection, applying migrations or verifying migrations have been applied.

func Open added in v0.9.0

func Open(dsn string) (db *sql.DB, err error)

Open a database connection.

func Register added in v0.9.0

func Register(scheme string, driver Driver)

Register a driver with the registry.

Types

type Config

type Config struct {
	Create  bool   `help:"Create (or recreate) the database."`
	Migrate bool   `help:"Apply migrations during connection establishment."`
	DSN     string `default:"${sqldsn}" required:"" help:"DSN for the SQL connection."`
}

type Driver added in v0.9.0

type Driver interface {
	// Open connection to the database.
	Open(dsn string) (*sql.DB, error)
	// Denormalise a query that uses ? placeholders to its native format.
	Denormalise(query string) string
	// RecreateDatabase optionally drops, then creates a database.
	RecreateDatabase(ctx context.Context, dsn string) error
}

Driver abstracts driver-specific functionality for supporting migrations and local development.

type Migrations added in v0.7.0

type Migrations []fs.FS

Migrations represents a set of SQL migrations.

Create a provider that returns an fs.FS with your .sql migrations at the root of the FS. eg.

//go:embed migrations/*.sql
var migrations embed.FS

//zero:provider multi
func Migrations() Migrations {
	sub, _ := fs.Sub(migrations, "migrations")
	return []fs.FS{sub}
}

Jump to

Keyboard shortcuts

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