database

package
v0.10.0-rc10 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is the package-level "not found" sentinel returned
	// by helpers in this package and matched (via errors.Is) by tests
	// that previously expected the sqlc-generated equivalent.
	ErrNotFound = errors.New("not found")

	// ErrUnsupportedDriver is returned when the database driver is not recognized.
	ErrUnsupportedDriver = errors.New("unsupported database driver")

	// ErrInvalidPostgresUnixURL is returned when a postgres+unix URL is invalid.
	ErrInvalidPostgresUnixURL = errors.New("invalid postgres+unix URL")

	// ErrInvalidMySQLUnixURL is returned when a mysql+unix URL is invalid.
	ErrInvalidMySQLUnixURL = errors.New("invalid mysql+unix URL")
)
View Source
var ErrNilDB = errors.New("database.NewClient: sdb is nil")

ErrNilDB is returned by NewClient when the caller passes a nil *sql.DB.

View Source
var ErrTransactionPanic = errors.New("transaction panicked")

ErrTransactionPanic wraps panics observed inside a WithTransaction callback. Callers can detect "this transaction died of a panic" via errors.Is without losing the original panic value (it is formatted into the error message via %v).

View Source
var ErrUnknownDialect = errors.New("database: unknown dialect")

ErrUnknownDialect is returned when a database.Type cannot be mapped to an ent dialect string. This is the single sentinel for unmapped dialects; pkg/database/migrate returns and matches this same value.

View Source
var SchemaCreateMu sync.Mutex

SchemaCreateMu serialises Ent's Schema.Create across the process. Ent mutates the package-level `migrate.Tables` slice during Schema.Create; without a global lock, concurrent goroutines race on that slice. Every code path that calls Schema.Create (fresh-install in pkg/database/migrate, schema-bootstrap helpers in tests) must acquire this mutex.

Functions

func EntDialectFor

func EntDialectFor(t Type) (string, error)

EntDialectFor maps ncps's database.Type to the corresponding ent dialect string. Exported and shared: pkg/database/migrate calls it when building its own ent driver for Schema.Create, so the mapping lives in exactly one place.

func IsAbortedTransactionError

func IsAbortedTransactionError(err error) bool

IsAbortedTransactionError returns true when err carries PostgreSQL SQLSTATE 25P02 ("in_failed_sql_transaction"). This state arises when a prior statement in the same transaction failed, leaving the transaction aborted. Subsequent statements on that connection will also fail until a ROLLBACK is issued. Detecting this lets callers clean up the connection before returning it to the pool.

func IsDeadlockError added in v0.8.0

func IsDeadlockError(err error) bool

IsDeadlockError checks if the error is a deadlock or a "database busy" error. Works across SQLite, PostgreSQL, and MySQL.

func IsDuplicateKeyError added in v0.6.0

func IsDuplicateKeyError(err error) bool

func IsNotFoundError added in v0.6.0

func IsNotFoundError(err error) bool

IsNotFoundError checks if the error indicates a row was not found. Accepts both the package-level ErrNotFound sentinel and Ent's *NotFoundError wrapper.

Types

type Client

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

Client is the post-migration database surface. It owns an Ent client (and the underlying *sql.DB) and exposes the lifecycle helpers callers need: Ent for fluent queries, DB for raw access (e.g. by goose), WithTransaction for atomic blocks, and Close for shutdown.

Per D11 of the migrate-to-ent-and-atlas openspec change, this type replaces the sqlc-generated `Querier` interface as the canonical dependency that callers (cache, server, ncps tooling) hold.

func NewClient

func NewClient(sdb *sql.DB, t Type) (*Client, error)

NewClient wraps an already-opened *sql.DB in an Ent client. The dialect must match the driver registered with sdb; mismatch will be caught at first query.

Callers should normally go through database.Open (introduced in §11) which constructs the *sql.DB and the *Client together with the correct otelsql instrumentation. NewClient is exposed for tests and for the migrate package, which already owns its *sql.DB lifecycle.

func Open

func Open(dbURL string, poolCfg *PoolConfig) (*Client, error)

Open opens a database connection and returns an Ent-backed *Client. The database type is determined from the URL scheme:

  • sqlite:// or sqlite3:// for SQLite
  • postgres:// or postgresql:// for PostgreSQL
  • mysql:// for MySQL/MariaDB

The poolCfg parameter is optional. If nil, sensible defaults are used based on the database type. SQLite uses MaxOpenConns=1, PostgreSQL and MySQL use higher values.

func (*Client) Close

func (c *Client) Close() error

Close closes the Ent client, which in turn closes the underlying *sql.DB. Safe to call once; subsequent calls return the *sql.DB "already closed" error.

func (*Client) DB

func (c *Client) DB() *sql.DB

DB returns the underlying *sql.DB. Used by goose (migrate package) and by code that still needs raw access during the §11 transition. Direct *sql.DB use is discouraged for new code — prefer the Ent API.

func (*Client) Ent

func (c *Client) Ent() *ent.Client

Ent returns the wrapped Ent client. Callers issue fluent queries against this client (e.g. `c.Ent().NarInfo.Create()...`).

func (*Client) Type

func (c *Client) Type() Type

Type returns the dialect this client was opened against.

func (*Client) WithTransaction

func (c *Client) WithTransaction(
	ctx context.Context,
	name string,
	fn func(tx *ent.Tx) error,
) (retErr error)

WithTransaction runs fn inside an Ent transaction. On success the transaction is committed; on error (including panic) it is rolled back. Lifecycle errors are wrapped with `name` so caller logs and telemetry can attribute failures to the originating operation — matching the behaviour of the legacy *Cache.executeTransaction helper this replaces.

Retry-on-deadlock is intentionally NOT handled here; that is a caller policy (see *Cache.withTransaction which wraps this).

type PoolConfig added in v0.6.0

type PoolConfig struct {
	// MaxOpenConns is the maximum number of open connections to the database.
	// If <= 0, defaults are used based on database type.
	MaxOpenConns int
	// MaxIdleConns is the maximum number of connections in the idle connection pool.
	// If <= 0, defaults are used based on database type.
	MaxIdleConns int
}

PoolConfig holds database connection pool settings.

type Type added in v0.6.0

type Type uint8
const (
	TypeUnknown Type = iota
	TypeMySQL
	TypePostgreSQL
	TypeSQLite
)

func DetectFromDatabaseURL added in v0.6.0

func DetectFromDatabaseURL(dbURL string) (Type, error)

DetectFromDatabaseURL detects the database type given a database url.

func (Type) String added in v0.6.0

func (t Type) String() string

String returns the string representation of a Type.

Directories

Path Synopsis
Package migrate implements the ncps schema-migration runtime: state detection, dbmate→goose adoption, fresh-install via Ent's Schema.Create, and the goose hand-off for incremental migrations.
Package migrate implements the ncps schema-migration runtime: state detection, dbmate→goose adoption, fresh-install via Ent's Schema.Create, and the goose hand-off for incremental migrations.

Jump to

Keyboard shortcuts

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