## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# database

> Package database connects a Gas app to PostgreSQL, MySQL or SQLite and provides the connection as a gas.DatabaseProvider.

The Markdown of https://gasmod.dev/reference/database/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
import "github.com/gasmod/gas/database"
```

Package database connects a Gas app to PostgreSQL, MySQL or SQLite and
provides the connection as a gas.DatabaseProvider.

It runs in one of two modes:

- In [ModeSQL](#ModeSQL) it opens a database/sql handle with the dialect's
driver, or a connector given to [WithConnector](#WithConnector).
- In [ModePgx](#ModePgx) it opens a native pgxpool.Pool for PostgreSQL and
derives the database/sql handle from it.

[Service](#Service) implements gas.Service, gas.DatabaseProvider, gas.HealthReporter
and gas.ReadyReporter.

## Usage

In an app, the container builds the service from [New](#New) and calls its
Init. By hand, with a configuration given in code:

```go
cfg := database.DefaultConfig()
cfg.Database.Dialect = database.DialectSQLite
cfg.Database.DSN = "file:app.db"

svc, err := database.New(database.WithConfig(cfg))(nil, logger)
if err != nil {
	return err
}
if err := svc.Init(ctx); err != nil {
	return err
}
defer svc.Close(ctx)

err = svc.WithTx(ctx, nil, func(tx *sql.Tx) error {
	_, err := tx.ExecContext(ctx, "INSERT INTO notes (body) VALUES (?)", "hello")
	return err
})
```

The app imports modernc.org/sqlite for the `sqlite` driver. The insert
is committed, since the function returned nil, and svc.Driver() is
`sqlite`.

## Configuration

The settings live in the `database` section, in [Settings](#Settings):

- `database.mode`: [ModeSQL](#ModeSQL) or [ModePgx](#ModePgx). Default: [DefaultMode](#DefaultMode).
- `database.dialect`: [DialectPostgres](#DialectPostgres), [DialectMySQL](#DialectMySQL) or
[DialectSQLite](#DialectSQLite). It has no default, and is required unless a
connector is given.
- `database.dsn`: the connection string, in the format of the
dialect's driver, a gas.Secret, which fmt, encoding/json, YAML
encoders and log/slog write as `[redacted]`. It has no default, and
is required unless a connector is given.
- `database.maxopenconns`: the most open connections, 1 to 1000.
Default: [DefaultMaxOpenConns](#DefaultMaxOpenConns).
- `database.maxidleconns`: the most idle connections, 0 to
`maxopenconns`. Default: [DefaultMaxIdleConns](#DefaultMaxIdleConns). ModeSQL applies it;
ModePgx has no such setting and checks it without applying it.
- `database.connmaxlifetime`: the longest time a connection is
reused, 1s to 2h. Default: [DefaultConnMaxLifetime](#DefaultConnMaxLifetime).
- `database.connmaxidletime`: the longest time a connection stays
idle, 1s to 1h and at most `connmaxlifetime`. Default:
[DefaultConnMaxIdleTime](#DefaultConnMaxIdleTime).
- `database.connecttimeout`: the bound of each connect attempt, open
and ping, of each later ping, and of a pgx rollback, 1s to 1m.
Default: [DefaultConnectTimeout](#DefaultConnectTimeout).
- `database.connretries`: how many times a failed connect is retried,
0 to 10. Default: [DefaultConnRetries](#DefaultConnRetries).
- `database.connretryinterval`: the wait before the first retry,
100ms to [MaxConnRetryInterval](#MaxConnRetryInterval) (30s), checked only when
`connretries` is positive. Default: [DefaultConnRetryInterval](#DefaultConnRetryInterval).

Both modes apply every limit they have as configured; no zero stands
for a driver default. In ModePgx the settings replace the `pool_*`
parameters of the DSN that they match.

## Resolving the configuration

[Service.Init](#Service.Init) resolves the configuration each time it runs:

- Without [WithConfig](#WithConfig), it binds [DefaultConfig](#DefaultConfig) from the
gas.ConfigProvider, which checks the `validate` tags. A nil
ConfigProvider is the error [ErrNoConfigProvider](#ErrNoConfigProvider).
- With WithConfig, it takes a copy of the given Config, never changing
the caller's struct, and checks the same tags. A nil Config is the
error [ErrNilConfig](#ErrNilConfig).

Either way, these rules then run, in this order, and the first that
fails is the error:

1. With a connector: WithConnector was given one, with one of the
three dialects; the mode is ModeSQL; the dialect setting is empty
or the connector's; the DSN is empty.
2. Without a connector: the dialect is set; the DSN is set; ModePgx
has the dialect postgres.
3. `maxidleconns` is at most `maxopenconns`.
4. When `connretries` is positive, `connretryinterval` is in bounds.

A failure wraps [ErrInvalidConfig](#ErrInvalidConfig) and names the setting, never its
value.

[Service.Config](#Service.Config) returns a copy of the configuration the last
successful Init resolved, defaults included, with DSN still a
gas.Secret, or the zero Config before one. A failed Init and Close
leave it as it was.

It holds the settings as resolved:

- The DSN is without the busy timeout the dialect sqlite may add.
- With a connector, the Dialect setting is as given, which may be
empty; Driver reports the dialect in use.

## Modes

The mode picks what the service opens:

- ModeSQL opens a \*sql.DB and applies the four limits to it.
- ModePgx opens a \*pgxpool.Pool, with `maxopenconns` as its MaxConns
and the lifetime and idle time as its own. [Service.DB](#Service.DB) is then
derived from the pool with pgx's stdlib.OpenDBFromPool, keeps no
idle connections of its own, and borrows the pool's.

[Service.Pool](#Service.Pool) and [PoolFrom](#PoolFrom) return the pool in ModePgx, and nil in
ModeSQL. ModePgx requires the dialect postgres and takes no connector.

## Dialects

The dialect picks the driver in ModeSQL, and is what [Service.Driver](#Service.Driver)
returns, so that the services built on the database, such as migrate,
pick their SQL by it:

- postgres: pgx's database/sql adapter, on the DSN parsed by
pgx.ParseConfig. The module imports it; no registration is needed.
- mysql: github.com/go-sql-driver/mysql, on the DSN parsed by
mysql.ParseDSN. The module imports it. See MySQL.
- sqlite: the database/sql driver registered as `sqlite`, opened with
the DSN as it is, except for the busy timeout (see SQLite). The
module does not import one: the app imports modernc.org/sqlite, or
another driver registered under that name. Without one, Init fails
with [ErrDriverNotRegistered](#ErrDriverNotRegistered), naming the import.

## MySQL

The service sets up the mysql driver this way:

- ParseTime is always turned on, so DATETIME and TIMESTAMP columns
scan into time.Time.
- MultiStatements stays as the DSN sets it, off unless it says
`multiStatements=true`, since it widens what an injected statement
can do.
- The driver's own log by default writes its messages to stderr, with
network errors that name the server's address. It goes to the
service's logger instead, as one warn event
`mysql driver reported an error` per message, without the driver's
text. A connector given to WithConnector keeps its own logger.

## SQLite

Without a busy timeout, SQLite fails a statement that meets another
connection's lock at once, with SQLITE\_BUSY. So two connections of one
pool writing, or one reading while another commits, fail. With a busy
timeout the statement waits up to that long.

When the DSN sets no busy timeout, the service adds
[DefaultSQLiteBusyTimeout](#DefaultSQLiteBusyTimeout), 5 seconds, as modernc.org/sqlite reads it:
`_pragma=busy_timeout(5000)` is appended to the DSN's query.

- A DSN sets one with `_busy_timeout`, `_timeout`, or a `_pragma`
value starting with `busy_timeout`, such as
`_pragma=busy_timeout(0)`, which turns the wait off.
- A DSN whose query does not parse is left as it is, for the driver
to reject.
- Another driver registered as `sqlite` must accept that parameter.

## Connectors

[WithConnector](#WithConnector) gives ModeSQL a driver.Connector to open the handle
with, for what a DSN cannot express, such as a custom TLS setup or IAM
authentication. It also takes the dialect the connector speaks, which
Driver returns.

The connector is reused by every connect attempt and every Init, and
never closed by the service: closing the handle does not reach it. The
caller owns it.

## Connecting

Init first does what fails the same way every time, and retries neither:

- It parses the DSN. A DSN the driver cannot parse is [ErrInvalidDSN](#ErrInvalidDSN).
- It finds the driver. A missing driver is ErrDriverNotRegistered.

It then makes connect attempts. Each attempt opens the handle, or the
pool, and pings it, within Init's context and `connecttimeout`. When the
ping fails, the attempt closes what it opened.

A failed attempt is retried up to `connretries` times. Before each
retry, Init:

1. Logs `database connection failed, retrying` at warn level, with
`attempt` (from 1), `retries`, `wait` and `reason`.
2. Waits: `connretryinterval` before the first retry, then twice the
previous wait, up to [MaxConnRetryInterval](#MaxConnRetryInterval).

The wait ends early when Init's context ends, and Init then fails at
once.

## Connect failures

When the attempts run out, Init fails with an error wrapping
[ErrConnect](#ErrConnect), `connect: ` and a reason. When Init's context ended, the
error wraps the context's error too. The reason is the first of these
that holds for the driver's error:

- `authentication failed`: PostgreSQL's SQLSTATE 28P01 or 28000, or
MySQL's error 1045.
- `access denied`: MySQL's error 1044, the user denied the database.
MySQL reports it for a database that does not exist too, unless
the user has privileges on every database.
- `database does not exist`: PostgreSQL's 3D000, or MySQL's 1049.
- `timed out`: a deadline passed, in a context or on the network.
- `connection refused`: the server refused the TCP connection.
- `unreachable`: any other network error, such as a failed name
lookup.
- `failed`: anything else.

The driver's error itself is not kept: pgx's and MySQL's connect errors
can hold the user, the host, the database and, in pgx's
ParseConfigError and ConnectError, the password and the TLS
configuration. The reason and the database server's own logs are what
an operator diagnoses with.

## Connection failures after Init

The same holds after Init. The handle and the pool open connections
whenever they need one: after a server restart, a credential rotation,
or when `connmaxlifetime` ends one. The call that needed it gets the
failure.

So these calls replace a connection-level failure: Query, Exec,
BeginTx, BeginPgxTx, WithTx, WithPgxTx, their commit and rollback, and
Close. The replacement is `<op>: <reason>`, `<op>` as in the error's
usual text and the reason as above. It wraps ErrConnect and, when the
call's context ended, the context's error, never the driver's.

A failure is connection-level when:

- It comes from opening a connection with the dialect postgres or
mysql or with a connector (in pgx, a \*pgconn.ConnectError). A sqlite
driver's errors are not told apart that way.
- Unless a context ended the call, it is a network error (a
net.Error), driver.ErrBadConn, MySQL's mysql.ErrInvalidConn or pgx's
pgconn.ErrConnClosed.

Calls made on [Service.DB](#Service.DB) or [Service.Pool](#Service.Pool) directly get the driver's
errors as they are.

[Service.SafeError](#Service.SafeError) gives code that runs statements on DB itself, such
as migrate, the same replacement. It returns a connection-level failure
as `connection: ` and a reason, wrapping ErrConnect and not the
driver's error, and any other error unchanged. Having no context, it
wraps no context error. It works in any state of the service.

## Initializing

A successful Init publishes the handle and logs `service initialized` at
info level, with `mode` and `dialect`. Only then do the methods below
use it.

Init on an initialized service returns [ErrAlreadyInitialized](#ErrAlreadyInitialized) and
changes nothing: the running handle stays open. A failed Init closes
what it opened and leaves the service uninitialized.

Until Init succeeds, after a failed Init and after Close:

- DB and Pool return nil, PoolFrom returns nil and false, and Driver
returns an empty string.
- [Service.Ping](#Service.Ping), [Service.Query](#Service.Query), [Service.Exec](#Service.Exec), [Service.BeginTx](#Service.BeginTx),
[Service.WithTx](#Service.WithTx), [Service.BeginPgxTx](#Service.BeginPgxTx), [Service.WithPgxTx](#Service.WithPgxTx),
[Service.CheckHealth](#Service.CheckHealth) and [Service.CheckReady](#Service.CheckReady) return an error
wrapping [ErrNotInitialized](#ErrNotInitialized).

[New](#New)'s constructor fails with [ErrNilLogger](#ErrNilLogger) for a nil logger. A nil
ConfigProvider is accepted, and Init then requires WithConfig.

## Closing

[Service.Close](#Service.Close) runs these steps, in order:

1. It makes the service uninitialized.
2. It closes the handle and, in ModePgx, the pool, which waits for the
connections the caller holds, such as a transaction from
BeginPgxTx, to be released. The pool is closed even when closing
the handle fails, and that failure is returned.

When the closing finishes, Close returns, having logged `service closed`
at info level if it succeeded and nothing if it failed.

When Close's context ends first, Close returns an error wrapping
[ErrCloseTimeout](#ErrCloseTimeout) and the context's error, and the closing goes on. When
it finishes, it logs `service closed` at info level, or
`service close failed` at warn level with `reason`.

Close on a service that is not initialized returns nil and logs nothing.
After Close, even one that timed out, Init may run again, and resolves
the configuration afresh.

## Restarting

Restarting the service makes a new handle; the old one is closed. The
services that take [Service.DB](#Service.DB) in their own Init, such as migrate and
the auth stores, keep the old one. So restarting the database means
restarting them too.

## Transactions

[Service.WithTx](#Service.WithTx) begins a transaction on DB, runs the function with it,
and commits only when the function returned nil. When the function
returned an error, panicked or called runtime.Goexit, as t.FailNow does,
the transaction is rolled back:

- After an error return, WithTx returns the function's error
unchanged, joined with the rollback's error when the rollback
failed.
- After a panic or Goexit, the panic or Goexit goes on. A failed
rollback is logged at warn level as `transaction rollback failed`,
with `reason`, a reason as for a failed connect, and not the
driver's error.

A rollback that finds the transaction already ended is not a failure. A
function that commits or rolls back the transaction itself and returns
nil gets an error wrapping sql.ErrTxDone from the commit.

database/sql takes no context for a rollback, and rolls the transaction
back itself when the context of WithTx ends.

[Service.WithPgxTx](#Service.WithPgxTx) is the same for a pgx.Tx on the pool, in ModePgx
only; elsewhere it returns [ErrModeNotPgx](#ErrModeNotPgx):

- It commits with its context, so a context that has ended fails the
commit rather than persisting work the caller gave up on.
- It rolls back with that context without its cancellation, bounded by
`connecttimeout`, so the rollback runs when the context has ended
and cannot hang on a dead connection.
- A function that ends the transaction itself and returns nil gets an
error wrapping pgx.ErrTxClosed.

A nil function is [ErrNilFunc](#ErrNilFunc) for both, checked before the transaction
begins.

[Service.BeginTx](#Service.BeginTx) and [Service.BeginPgxTx](#Service.BeginPgxTx) begin a transaction that
the caller ends.

Errors from the driver in Query, Exec and the transaction methods that
describe the statement come back wrapped. Connection-level failures are
replaced, as described under Connection failures after Init.

## Health

[Service.CheckHealth](#Service.CheckHealth) does no I/O: it fails only when the service is
not initialized, which a restart fixes.

[Service.CheckReady](#Service.CheckReady) and [Service.Ping](#Service.Ping) ping the database, within their
context and `connecttimeout`. A failed ping wraps ErrConnect, after
`ping: `, with a reason as a failed connect has, and the context's error
when the caller's context ended.

## Concurrency

A Service is safe for concurrent use. Init and Close run one at a time:
a Close waits for a running Init, connect retries included, and then
closes what it opened. Close holds its lock only to make the service
uninitialized, so an Init can run while an earlier Close is still
closing.

Init swaps in what it opened at once, so the other methods, which take
no lock, use one Init's handle throughout a call. A call that runs
beside Close may find its handle closed and return the driver's error.

Close closes in a goroutine of its own, which outlives a Close whose
context ended until the closing finishes. The service starts no other
goroutines. In ModePgx, the pool runs pgx's health check, and opens
connections up to its minimum, until it is closed.

## Errors

The sentinel errors, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrNilLogger](#ErrNilLogger): New's constructor got a nil logger.
- [ErrNilConfig](#ErrNilConfig), [ErrNoConfigProvider](#ErrNoConfigProvider), [ErrInvalidConfig](#ErrInvalidConfig): Init
could not resolve a valid configuration. ErrInvalidConfig wraps the
binder's, the validator's or the rule's error.
- [ErrAlreadyInitialized](#ErrAlreadyInitialized): Init ran on an initialized service.
- [ErrDriverNotRegistered](#ErrDriverNotRegistered): no `sqlite` driver is registered.
- [ErrInvalidDSN](#ErrInvalidDSN): the dialect's driver could not parse the DSN.
- [ErrConnect](#ErrConnect): connecting or pinging failed, or a call after Init
failed at the connection level, or SafeError replaced such a
failure, as described under Connect failures and Connection
failures after Init.
- [ErrNotInitialized](#ErrNotInitialized): a method ran before Init succeeded, after a
failed Init, or after Close.
- [ErrModeNotPgx](#ErrModeNotPgx): a pgx transaction was asked for in ModeSQL.
- [ErrNilFunc](#ErrNilFunc): WithTx or WithPgxTx got a nil function.
- [ErrCloseTimeout](#ErrCloseTimeout): Close's context ended before the closing
finished. It wraps the context's error too.

Every error the package makes starts with [ServiceName](#ServiceName) and wraps its
sentinel. The errors that pass a statement's failure on wrap no
sentinel; they wrap the driver's error, after a prefix:

- Query: `gas/database: query: `.
- Exec: `gas/database: exec: `.
- BeginTx, BeginPgxTx, WithTx and WithPgxTx:
`gas/database: failed to begin transaction: `.
- WithTx and WithPgxTx:
`gas/database: failed to commit transaction: `.
- WithTx and WithPgxTx, after the function returned an error:
`gas/database: failed to roll back transaction: `, joined after
the function's error.
- Close: `gas/database: close: `.

When the function given to WithTx or WithPgxTx returns an error and the
rollback succeeds, they return that error unchanged: not wrapped, and
without the prefix.

No error the package makes and no log the service writes includes the
DSN, the password, the user, the host, the port, the database name or
TLS material; errors name the setting instead. The logs carry the
mode, the dialect, the retry `attempt`, `retries` and `wait`, and fixed
reasons.

The driver's errors that Query, Exec, the transaction methods and Close
pass on are the driver's own text. They describe the statement, and can
name what it touched, such as a table or, in an access error, a database
or the user.

A configuration that fails its tags gets the validator's error after
`gas/database: invalid config: validate config: `, such as:

```go
Key: 'Config.Database.Mode' Error:Field validation for 'Mode' failed on the 'oneof' tag
```

The other errors, as returned:

```go
gas/database: logger is nil
gas/database: config is nil
gas/database: no config provider
gas/database: invalid config: WithConnector requires a connector
gas/database: invalid config: WithConnector requires the dialect postgres, mysql or sqlite
gas/database: invalid config: a connector requires Database.Mode sql
gas/database: invalid config: with a connector, Database.Dialect must be empty or the connector's dialect
gas/database: invalid config: with a connector, Database.DSN must be empty
gas/database: invalid config: Database.Dialect is required without a connector
gas/database: invalid config: Database.DSN is required without a connector
gas/database: invalid config: Database.Mode pgx requires Database.Dialect postgres
gas/database: invalid config: Database.MaxIdleConns must not exceed Database.MaxOpenConns
gas/database: invalid config: Database.ConnRetryInterval must be 100ms to 30s when Database.ConnRetries is positive
gas/database: service already initialized
gas/database: driver not registered: dialect sqlite needs the import modernc.org/sqlite
gas/database: invalid DSN
gas/database: connect: authentication failed
gas/database: connect: access denied
gas/database: connect: database does not exist
gas/database: connect: timed out
gas/database: connect: connection refused
gas/database: connect: unreachable
gas/database: connect: failed
gas/database: connect: failed: context canceled
gas/database: ping: connection refused
gas/database: query: connection refused
gas/database: exec: connection refused
gas/database: failed to begin transaction: authentication failed
gas/database: failed to commit transaction: connection refused
gas/database: failed to roll back transaction: connection refused
gas/database: close: connection refused
gas/database: connection: connection refused
gas/database: close timed out: context deadline exceeded
gas/database: service not initialized
gas/database: mode is not pgx
gas/database: transaction function is nil
gas/database: failed to commit transaction: sql: transaction has already been committed or rolled back
```


## API reference

### Constants

<a id="DefaultMode"></a><a id="DefaultMaxOpenConns"></a><a id="DefaultMaxIdleConns"></a><a id="DefaultConnMaxLifetime"></a><a id="DefaultConnMaxIdleTime"></a><a id="DefaultConnectTimeout"></a><a id="DefaultConnRetries"></a><a id="DefaultConnRetryInterval"></a><a id="MaxConnRetryInterval"></a>

```go
const (
	// DefaultMode is the mode of DefaultConfig.
	DefaultMode = ModeSQL
	// DefaultMaxOpenConns is the open connection limit of DefaultConfig.
	DefaultMaxOpenConns int32 = 25
	// DefaultMaxIdleConns is the idle connection limit of DefaultConfig.
	DefaultMaxIdleConns = 5
	// DefaultConnMaxLifetime is the connection lifetime of DefaultConfig.
	DefaultConnMaxLifetime = 30 * time.Minute
	// DefaultConnMaxIdleTime is the connection idle time of DefaultConfig.
	DefaultConnMaxIdleTime = 5 * time.Minute
	// DefaultConnectTimeout is the per-attempt connect timeout of
	// DefaultConfig.
	DefaultConnectTimeout = 5 * time.Second
	// DefaultConnRetries is the number of connect retries of
	// DefaultConfig.
	DefaultConnRetries = 0
	// DefaultConnRetryInterval is the wait before the first connect retry
	// of DefaultConfig.
	DefaultConnRetryInterval = 2 * time.Second
	// MaxConnRetryInterval is the longest ConnRetryInterval, and caps
	// the doubling of the wait between connect retries.
	MaxConnRetryInterval = 30 * time.Second
)
```

<a id="DefaultSQLiteBusyTimeout"></a>

```go
const DefaultSQLiteBusyTimeout = 5 * time.Second
```

DefaultSQLiteBusyTimeout is the busy timeout the dialect sqlite adds to
a DSN that sets none, as described in the package documentation.

<a id="ServiceName"></a>

```go
const ServiceName = "gas/database"
```

ServiceName is the name of the database service, returned by
Service.Name and prefixed to every error the service returns.

### Variables

<a id="ErrNilLogger"></a><a id="ErrNilConfig"></a><a id="ErrNoConfigProvider"></a><a id="ErrInvalidConfig"></a><a id="ErrNotInitialized"></a><a id="ErrAlreadyInitialized"></a><a id="ErrDriverNotRegistered"></a><a id="ErrInvalidDSN"></a><a id="ErrConnect"></a><a id="ErrModeNotPgx"></a><a id="ErrNilFunc"></a><a id="ErrCloseTimeout"></a>

```go
var (
	// ErrNilLogger indicates that the constructor was given a nil logger.
	ErrNilLogger = errors.New("logger is nil")
	// ErrNilConfig indicates that WithConfig was given a nil
	// configuration.
	ErrNilConfig = errors.New("config is nil")
	// ErrNoConfigProvider indicates that there is neither a configuration
	// given to WithConfig nor a ConfigProvider to bind one from.
	ErrNoConfigProvider = errors.New("no config provider")
	// ErrInvalidConfig indicates that the configuration failed to bind,
	// failed its validate tags, or broke one of the package's rules.
	ErrInvalidConfig = errors.New("invalid config")
	// ErrNotInitialized indicates that a method was called before Init
	// succeeded, after a failed Init, or after Close.
	ErrNotInitialized = errors.New("service not initialized")
	// ErrAlreadyInitialized indicates that Init was called on a service
	// that is initialized.
	ErrAlreadyInitialized = errors.New("service already initialized")
	// ErrDriverNotRegistered indicates that the database/sql driver the
	// dialect needs is not registered.
	ErrDriverNotRegistered = errors.New("driver not registered")
	// ErrInvalidDSN indicates that the dialect's driver could not parse
	// Settings.DSN.
	ErrInvalidDSN = errors.New("invalid DSN")
	// ErrConnect indicates that connecting to the database, or pinging
	// it, failed.
	ErrConnect = errors.New("connect failed")
	// ErrModeNotPgx indicates that a pgx transaction was asked of a
	// service that is not in ModePgx.
	ErrModeNotPgx = errors.New("mode is not pgx")
	// ErrNilFunc indicates that WithTx or WithPgxTx was given a nil
	// function.
	ErrNilFunc = errors.New("transaction function is nil")
	// ErrCloseTimeout indicates that the context of Close ended before
	// closing finished. The service is uninitialized, and closing goes on.
	ErrCloseTimeout = errors.New("close timed out")
)
```

<a id="New"></a>

#### func New

```go
func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)
```

New returns the constructor of a Service with opts applied, in the shape
the gas container expects. The constructor returns an error wrapping
ErrNilLogger for a nil logger; a nil ConfigProvider is accepted, and
Init then requires WithConfig.

<a id="PoolFrom"></a>

#### func PoolFrom

```go
func PoolFrom(provider gas.DatabaseProvider) (*pgxpool.Pool, bool)
```

PoolFrom returns the native pool behind provider and true, when
provider has a Pool method that returns one. It returns nil and false
for any other provider, a Service in ModeSQL, and a Service that is not
initialized; callers then use DB.

<a id="Config"></a>

### type Config

```go
type Config struct {
	// Database holds the settings.
	Database Settings
}
```

Config holds the database service's configuration, read from the
`database` section.

<a id="DefaultConfig"></a>

#### func DefaultConfig

```go
func DefaultConfig() *Config
```

DefaultConfig returns the configuration a service starts from before
binding: DefaultMode, the Default limits and timeouts, no dialect and
no DSN.

<a id="Dialect"></a>

### type Dialect

```go
type Dialect string
```

Dialect names the SQL dialect of the database, as described in the
package documentation. Service.Driver returns it.

<a id="DialectPostgres"></a><a id="DialectMySQL"></a><a id="DialectSQLite"></a>

```go
const (
	// DialectPostgres is PostgreSQL, reached through pgx.
	DialectPostgres Dialect = "postgres"
	// DialectMySQL is MySQL, reached through go-sql-driver/mysql.
	DialectMySQL Dialect = "mysql"
	// DialectSQLite is SQLite, reached through the database/sql driver
	// registered as `sqlite`.
	DialectSQLite Dialect = "sqlite"
)
```

<a id="Mode"></a>

### type Mode

```go
type Mode string
```

Mode selects how the service connects, as described in the package
documentation.

<a id="ModeSQL"></a><a id="ModePgx"></a>

```go
const (
	// ModeSQL connects through database/sql, with the driver of the
	// dialect or the connector given to WithConnector.
	ModeSQL Mode = "sql"
	// ModePgx connects with a native pgxpool.Pool, for PostgreSQL only.
	// DB is derived from the pool.
	ModePgx Mode = "pgx"
)
```

<a id="Option"></a>

### type Option

```go
type Option func(*Service)
```

Option configures a Service. Options only record what they are given;
Init checks it.

<a id="WithConfig"></a>

#### func WithConfig

```go
func WithConfig(cfg *Config) Option
```

WithConfig makes Init use a copy of cfg instead of binding the
configuration from the ConfigProvider. Init copies \*cfg each time it
runs and never changes it; the copy is checked as a bound configuration
is. A nil cfg makes Init fail with ErrNilConfig.

Default: bind the `database` section from the ConfigProvider over
DefaultConfig.

<a id="WithConnector"></a>

#### func WithConnector

```go
func WithConnector(d Dialect, c driver.Connector) Option
```

WithConnector makes ModeSQL open the database through c instead of a
DSN, for drivers or connection setups the dialects do not cover, such
as custom TLS or IAM authentication. d is the dialect c speaks, which
Driver returns. With a connector, Settings.Dialect must be empty or d,
Settings.DSN must be empty, and Settings.Mode must be ModeSQL; Init
checks this, and that c is neither nil nor a typed nil. The service
never closes c.

Default: no connector; the dialect's driver opens Settings.DSN.

<a id="Service"></a>

### type Service

```go
type Service struct {
	// contains filtered or unexported fields
}
```

Service connects to a database and provides it to the app, as described
in the package documentation. It is safe for concurrent use.

<a id="Service.BeginPgxTx"></a>

#### func (*Service) BeginPgxTx

```go
func (s *Service) BeginPgxTx(ctx context.Context, opts *pgx.TxOptions) (pgx.Tx, error)
```

BeginPgxTx starts a native pgx transaction on the pool; nil opts are
pgx's defaults. The caller commits or rolls it back. Outside ModePgx it
returns ErrModeNotPgx. Its other errors are as BeginTx's.

<a id="Service.BeginTx"></a>

#### func (*Service) BeginTx

```go
func (s *Service) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
```

BeginTx starts a transaction on DB. The caller commits or rolls it
back. Its errors are as Query's, after `failed to begin transaction: `.

<a id="Service.CheckHealth"></a>

#### func (*Service) CheckHealth

```go
func (s *Service) CheckHealth(context.Context) error
```

CheckHealth reports liveness without I/O: an error wrapping
ErrNotInitialized when the service is not initialized, else nil.

<a id="Service.CheckReady"></a>

#### func (*Service) CheckReady

```go
func (s *Service) CheckReady(ctx context.Context) error
```

CheckReady reports readiness by pinging the database, as Ping does.

<a id="Service.Close"></a>

#### func (*Service) Close

```go
func (s *Service) Close(ctx context.Context) error
```

Close makes the service uninitialized and closes the database handle
and, in ModePgx, the pool, as described in the package documentation.
The pool is closed even when closing the handle fails. Close waits for
the closing until ctx ends, and then returns an error wrapping
ErrCloseTimeout and ctx's error while the closing goes on. Close on a
service that is not initialized returns nil.

<a id="Service.Config"></a>

#### func (*Service) Config

```go
func (s *Service) Config() Config
```

Config returns a copy of the configuration the last successful Init
resolved, defaults included, or the zero Config before one. A failed
Init and Close leave it as it was. Config holds no slice, map or
pointer, so the copy shares nothing with the service, and DSN stays a
gas.Secret.

<a id="Service.DB"></a>

#### func (*Service) DB

```go
func (s *Service) DB() *sql.DB
```

DB returns the database/sql handle, or nil when the service is not
initialized. In ModePgx it is derived from the pool.

<a id="Service.Driver"></a>

#### func (*Service) Driver

```go
func (s *Service) Driver() string
```

Driver returns the dialect, `postgres`, `mysql` or `sqlite`, as a
string, or an empty string when the service is not initialized. With a
connector it is the dialect given to WithConnector.

<a id="Service.Exec"></a>

#### func (*Service) Exec

```go
func (s *Service) Exec(ctx context.Context, query string, args ...any) (gas.Result, error)
```

Exec runs a statement that returns no rows, on DB. The gas.Result is
the sql.Result. Its errors are as Query's, after `exec: `.

<a id="Service.Init"></a>

#### func (*Service) Init

```go
func (s *Service) Init(ctx context.Context) error
```

Init resolves and checks the configuration, connects, and publishes the
connection, as described in the package documentation. On an
initialized service it returns ErrAlreadyInitialized and changes
nothing. A failed Init closes what it opened and leaves the service
uninitialized.

<a id="Service.Name"></a>

#### func (*Service) Name

```go
func (*Service) Name() string
```

Name returns ServiceName.

<a id="Service.Ping"></a>

#### func (*Service) Ping

```go
func (s *Service) Ping(ctx context.Context) error
```

Ping checks that the database answers, within ctx and
Settings.ConnectTimeout. A failure wraps ErrConnect and names a fixed
reason, as described in the package documentation.

<a id="Service.Pool"></a>

#### func (*Service) Pool

```go
func (s *Service) Pool() *pgxpool.Pool
```

Pool returns the native pool in ModePgx, or nil in ModeSQL and when the
service is not initialized. PoolFrom reaches it through a
gas.DatabaseProvider.

<a id="Service.Query"></a>

#### func (*Service) Query

```go
func (s *Service) Query(ctx context.Context, query string, args ...any) (gas.Rows, error)
```

Query runs a query that returns rows, on DB. The gas.Rows is the
\*sql.Rows, which the caller must close. A statement's error comes back
wrapped, after `query: `; a connection-level failure wraps ErrConnect,
as described in the package documentation.

<a id="Service.SafeError"></a>

#### func (*Service) SafeError

```go
func (*Service) SafeError(err error) error
```

SafeError returns err unchanged when it describes a statement, and, in
place of a connection-level failure, the error the service's own
methods return for one: `connection: ` and a fixed reason, wrapping
ErrConnect and not err, as described in the package documentation. A
nil err is nil. It is for code that runs statements on DB itself, such
as migrate, and works on a service in any state.

<a id="Service.WithPgxTx"></a>

#### func (*Service) WithPgxTx

```go
func (s *Service) WithPgxTx(ctx context.Context, opts *pgx.TxOptions, fn func(pgx.Tx) error) error
```

WithPgxTx runs fn in a native pgx transaction and commits it only when
fn returns nil, as WithTx does. The commit uses ctx; the rollback uses
ctx without its cancellation, bounded by Settings.ConnectTimeout.

<a id="Service.WithTx"></a>

#### func (*Service) WithTx

```go
func (s *Service) WithTx(ctx context.Context, opts *sql.TxOptions, fn func(*sql.Tx) error) error
```

WithTx runs fn in a transaction on DB and commits it only when fn
returns nil, as described in the package documentation. An error, a
panic or runtime.Goexit in fn rolls it back.

<a id="Settings"></a>

### type Settings

```go
type Settings struct {
	// Mode is ModeSQL or ModePgx.
	Mode Mode `validate:"oneof=sql pgx"`
	// Dialect is DialectPostgres, DialectMySQL or DialectSQLite. It may be
	// empty only with a connector.
	Dialect Dialect `validate:"omitempty,oneof=postgres mysql sqlite"`
	// DSN is the connection string, in the dialect's own format. It is
	// required without a connector and must be empty with one. It is a
	// gas.Secret, which prints, marshals and logs as `[redacted]`.
	DSN gas.Secret
	// ConnMaxLifetime is the longest time a connection is reused.
	ConnMaxLifetime time.Duration `validate:"min=1s,max=2h"`
	// ConnMaxIdleTime is the longest time a connection stays idle. It is
	// at most ConnMaxLifetime.
	ConnMaxIdleTime time.Duration `validate:"min=1s,max=1h,ltefield=ConnMaxLifetime"`
	// ConnectTimeout bounds each connect attempt, open and ping, each
	// later ping, and each pgx rollback.
	ConnectTimeout time.Duration `validate:"min=1s,max=1m"`
	// ConnRetryInterval is the wait before the first connect retry. It is
	// checked only when ConnRetries is positive.
	ConnRetryInterval time.Duration
	// MaxIdleConns is the most idle connections kept, at most
	// MaxOpenConns. ModeSQL applies it; ModePgx has no such setting.
	MaxIdleConns int `validate:"min=0"`
	// ConnRetries is how many times a failed connect is retried.
	ConnRetries int `validate:"min=0,max=10"`
	// MaxOpenConns is the most open connections.
	MaxOpenConns int32 `validate:"min=1,max=1000"`
}
```

Settings are the database service's settings, as described in the
package documentation.
