Documentation
¶
Overview ¶
Package db @notice Opens the bun handle over a pgdriver pool that luima's resolvers query through.
@dev Connecting is the only part of the data layer that is the same in every application. Everything else is your models and the crud package. Connect is that sameness in one argument; ConnectWith is the same function with one more, for the configuration that has to be code rather than connection-string text.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Connect ¶
Connect @notice Opens the pool the resolvers query through and proves it works.
@dev pgdriver parses the connection string (parseDSN), and three things about how it does that decide what a DSN can say:
- Parameters. It reads host, sslmode, sslrootcert, sslcert, sslkey, application_name, timeout, dial_timeout, connect_timeout, read_timeout and write_timeout. Every other parameter becomes a Config.ConnParams entry, sent as SET name TO 'value' on every new connection. So ?statement_timeout=5s works, and a misspelled parameter is not a parse error: it fails the boot round trip instead — 42704 for an unknown name, 42601 for a key such as a-b — or, for a dotted name such as app.x, which Postgres takes as a custom setting, never fails at all. Two names are refused while parsing instead, password and sslpassword: sent as SET, their value would reach the server log in the statement Postgres rejects (see connector). sslcert and sslkey are read only alongside sslmode or sslrootcert; without either they are sent as SET and fail with 42704. ?host= is dialed as written, with no port added. A timeout written as an integer <= 0, which queryOptions.duration turns into -1ns — a deadline that has already passed — is read as unset, and keeps pgdriver's default, as 0.5.0 read ?connect_timeout=0.
- TLS. With sslmode absent, allow or prefer, the connection is TLS with InsecureSkipVerify: a managed Postgres connects with nothing to configure, and nothing is verified, sslrootcert or not. require is just as unverified, unless sslrootcert is given too, when it acts as verify-ca. verify-ca and verify-full both verify the certificate chain, against sslrootcert or the system roots, and the host name, against a ServerName pgdriver sets from the host in the URL's authority, without its port. That is 0.5.0's verify-ca, not libpq's: pgdriver checks verify-ca's chain alone, and connector hands it back to crypto/tls's full check. A host given only as ?host= leaves ServerName empty, and crypto/tls then refuses every verify-ca and verify-full handshake before sending it; set c.TLSConfig.ServerName in a ConnectWith tune for that, or a VerifyConnection of your own for a chain-only check. disable is plaintext. In every mode but disable a server that refuses TLS is an error, never a plaintext fallback, so a Postgres without TLS — a CI container, a unix socket — needs ?sslmode=disable.
- Defaults. A DSN with no host dials $PGHOST and $PGPORT, then localhost and 5432. A host name or IPv4 address with no port gets 5432, whatever $PGPORT says, but an IPv6 literal gets no port at all — parseDSN adds one only to a host without a colon — so [::1] fails to dial with "missing port in address" until it is written [::1]:5432. No user is $PGUSER, then postgres; no database is $PGDATABASE, then postgres, and that one is silent: a DSN that forgot its database connects to postgres. No password is $PGPASSWORD, which pgdriver does not read and connector does, as 0.5.0 did.
postgres://, postgresql:// and unix:///path/to/socket all parse.
Connect keeps pgdriver's socket timeouts — DialTimeout 5s, ReadTimeout 10s, WriteTimeout 5s (newDefaultConfig) — because they are the only bound on the I/O pgdriver does without the caller's context: the rows after a query's row description (rows.next reads with context.TODO()), the drain in rows.Close, COMMIT and ROLLBACK (tx.Commit and tx.Rollback run on context.Background()), and the whole startup of every connection that database/sql's connectionOpener dials in the background, on a context with no deadline. Zero them and a server that stops answering holds a connection forever — or the pool's one opener goroutine, which every later background dial queues behind. What they cost is a ceiling: a statement whose response takes longer than ReadTimeout fails client-side with an i/o timeout, whatever RequestTimeout allows. Raise it with ?read_timeout=60s, or with ConnectWith and func(c *pgdriver.Config) { c.ReadTimeout = 60 * time.Second }.
Query timeouts: server.Config.RequestTimeout puts a deadline on the resolver's context, and pgdriver makes the earlier of that deadline and now+WriteTimeout the socket deadline for writing each query, and the earlier of it and now+ReadTimeout the one for reading the reply ((*Conn).deadline) — all of it for an Exec (readQuery), and up to the row description for a query (readQueryData), whose rows are then read without the context. That stops the client waiting, and nothing else: pgdriver never asks Postgres to cancel a statement, so the statement runs on until it finishes. StatementTimeout, or ?statement_timeout= in the DSN, is the bound Postgres enforces itself.
The pool is database/sql's, sized by ConnectWith. Resize it on the returned handle: *bun.DB embeds *sql.DB through its state struct, so SetMaxOpenConns, SetMaxIdleConns, SetConnMaxIdleTime and Stats are promoted to it. Query hooks go on the handle as well: db.WithQueryHook(h) returns a copy over the same pool that runs h, so hand the copy to your resolvers (AddQueryHook is deprecated).
Connect takes a URL and nothing else, deliberately — a one-argument default that is correct is why this package is one call. What has to be code goes through ConnectWith, which is this function with one more parameter.
Unlike the server this was lifted from, Connect returns its error rather than calling log.Fatal, and takes the URL rather than reading os.Getenv: a library must not kill the caller's process, choose their logging, or read configuration behind their back. Write log.Fatal(err) at the call site if that is what you want. Connect's errors never contain the DSN or its password, so logging one does not leak the credential — a DSN whose user info an unescaped / ? or # cut short is refused before it can dial part of the password as a host or a port, and name it in the dial error (see connector) — and a DSN pgdriver would panic on comes back as an error too.
@param url a postgres:// or postgresql:// connection string @return *bun.DB the bun handle over a live pool, already proven with a round trip; nil on error @return error a parse failure, or the ping failure with the pool already closed
func ConnectWith ¶ added in v0.4.0
ConnectWith @notice Connect, plus the pgdriver.Config tuning that has to be code.
@dev A function rather than a struct of promoted fields: pgdriver.Config has sixteen of them and a struct would cover four, so every option luima did not think of would send the consumer back to re-implementing this function — which means re-implementing the parts of it that are easy to get wrong: a DSN that must neither panic nor reach a log, the pool sizing, and the bounded boot round trip.
tune is called with the *pgdriver.Config the connector dials with — (*Connector).Config returns the connector's own pointer, not a copy — after the DSN has been applied and before anything has dialed, the one point at which a change reaches every connection. So tune wins over the DSN, and it runs before the boot round trip reads DialTimeout, so raising DialTimeout raises that bound with it.
A DSN carries statement_timeout, read_timeout and application_name itself (see Connect). What is left for tune is what text cannot say: a *tls.Config with an in-memory CA pool or its own VerifyConnection, a Dialer, a ConnParams entry merged over whatever the DSN set — StatementTimeout is that case pre-written — or a value computed at startup, such as a password assigned as it is, with none of the percent-encoding a DSN needs. Raise ReadTimeout here for slow statements; do not zero it (see Connect).
Naming *pgdriver.Config costs a consumer an import line and nothing in their module graph: luima already requires pgdriver to connect at all.
@param url a postgres:// or postgresql:// connection string, as Connect takes @param tune called with the parsed config; nil is exactly Connect @return *bun.DB the bun handle over a live pool, already proven with a round trip; nil on error @return error a parse failure, or the ping failure with the pool already closed
func StatementTimeout ¶ added in v0.4.0
StatementTimeout @notice A tune func for ConnectWith that bounds every query server-side.
@dev A DSN can say ?statement_timeout=30s as well; this is the same bound for a duration that lives in Go rather than in the connection string, and it wins over the DSN's. pgdriver has no OnConnect hook. What it has is Config.ConnParams, which newConn sends as one SET per key on every connection it opens, before the connection is used. So this merges one key into that map rather than replacing it: a ?statement_timeout= in the DSN is overridden, and every other DSN parameter still goes out. To combine it with tuning of your own, call it inside your tune func: db.StatementTimeout(d)(c).
ms stays an int64 because the value is formatted into the statement, not bound: newConn sends "SET statement_timeout TO $1", and formatQuery's appendArg writes an int64 there bare — SET statement_timeout TO 1500, which Postgres reads as milliseconds. appendArg refuses every type it does not list, int and time.Duration among them, with "pgdriver: unexpected arg", and that would fail every dial.
This is the bound RequestTimeout cannot be. pgdriver never asks Postgres to cancel anything — it reads the backend key at startup and never uses it — so a context deadline stops only the client: (*Conn).deadline turns it into a socket deadline, the read fails, the connection is closed, and the statement runs on in Postgres until it finishes, holding its backend and its locks. statement_timeout is enforced by the server whether or not the client is still there. See SECURITY.md.
When it fires, Postgres answers SQLSTATE 57014, and pgdriver returns that error as it is — checkBadConn always returns the original — so luimaerr.SQLState reads it, provided the client is still reading. The read waiting for the answer has a socket deadline of its own, the earlier of ReadTimeout (10s unless raised) and the request context's deadline, so a d at or past either one still bounds the statement in Postgres, but the caller gets an i/o timeout with no SQLSTATE first, on a connection pgdriver then closes. Keep d under both, or raise them with it.
And the connection may not survive a 57014 that does arrive. checkBadConn counts 57014 as a bad connection and closes it, but it runs only in ExecContext and QueryContext: a 57014 read there — by an Exec, or by a query before its row description arrives — costs the pool that connection, and the next one pays a dial and the SETs again, while one read later, in rows.next, leaves the connection pooled. Inside a transaction, a closed connection fails every later statement, COMMIT included, with driver.ErrBadConn.
The round-up is not tidiness. Milliseconds truncates, so any d under 1ms would reach Postgres as "SET statement_timeout TO 0" — which is Postgres for *no timeout at all*, turning a bound into its own opposite silently. A zero or negative d still disables it, because that is what the caller asked for. The clamp to 0 is not tidiness either: Postgres accepts statement_timeout only in 0 ms .. 2147483647 ms, so an unclamped -1s would reach it as "SET statement_timeout TO -1000" and be refused with SQLSTATE 22023. newConn returns that error in place of the connection, and database/sql fails the query that asked for one with it — it retries only driver.ErrBadConn (DB.retry). Every new connection sends the SET, so every one would fail — ConnectWith's own boot ping first, which turns the documented way to disable the bound into a ConnectWith that can only return an error. Only the lower end is clamped: a d above 2147483647ms, about 24.8 days, is refused the same way.
@param d the bound; Postgres cancels a statement that exceeds it (SQLSTATE 57014, readable with luimaerr.SQLState while d is under ReadTimeout and the request deadline). Zero or negative disables it. @return func(*pgdriver.Config) a tune func for ConnectWith
Types ¶
This section is empty.