async_postgres/pg_connection/dsn

DSN parsing for PostgreSQL connection strings.

Supports both libpq formats:

  • keyword=value: host=localhost port=5432 dbname=test
  • URI: postgresql://user:pass@host:port/db?param=value

Treat the DSN as trusted operator config, not end-user input: unknown keys become StartupMessage parameters and values such as options are forwarded verbatim. Sanitize before parseDsn if it is not under your control.

Only initConnConfig / parseDsn / validateConnConfig are re-exported through pg_connection.nim; the intermediate parsers stay here. Depends only on types.nim and conf_files.nim (does not touch PgConnection).

Internal module: not part of the public API. Import the pg_connection hub instead.

Procs

proc initConnConfig(host = DefaultHost; port = 5432; hostaddr = ""; user = "";
                    password = ""; database = ""; sslMode = sslPrefer;
                    sslRootCert = ""; sslCert = ""; sslKey = ""; sslSni = true;
                    channelBinding = cbPrefer; applicationName = "";
                    connectTimeout = ZeroDuration; keepAlive = true;
                    keepAliveIdle = 0; keepAliveInterval = 0;
                    keepAliveCount = 0; hosts: seq[HostEntry] = @[];
                    targetSessionAttrs = tsaAny; loadBalanceHosts = lbhDisable;
                    requireAuth: set[AuthMethod] = {};
                    extraParams: seq[(string, string)] = @[];
                    maxMessageSize = 0; maxScramIterations = 0;
                    sslNegotiation = sslnPostgres; passFile = "";
                    tcpUserTimeout = 0; sslRootCertSystem = false): ConnConfig {.
    ...raises: [PgConfigError], tags: [], forbids: [].}

Create a connection configuration with sensible defaults. For DSN-based configuration, use parseDsn instead. Unlike parseDsn, nothing comes from the environment: no password file unless passFile names one, and no OS user for an empty user.

Validates like DSN parsing; negative connectTimeout becomes ZeroDuration (no timeout). When hosts is non-empty, scalar host/hostaddr/port are overwritten from hosts[0] (same as DSN parsers). An empty host with no hostaddr is rejected, like an explicitly empty host in a DSN. sslRootCertSystem needs sslMode = sslVerifyFull passed too: the default sslPrefer is not raised as parseDsn raises an unset sslmode.

proc optionsTimeZone(options: string): Option[string] {....raises: [], tags: [],
    forbids: [].}
The TimeZone value a -c switch in options sets, if any. The last switch wins, as on the server.
proc parseDsn(dsn: string; environment = true): ConnConfig {.
    ...raises: [PgConfigError], tags: [RootEffect, ReadIOEffect], forbids: [].}

Parse a PostgreSQL connection string into a ConnConfig.

Supports two formats:

  • URI: postgresql://[user[:password]@][host[:port]][/database][?param=value&...]
  • keyword=value: host=localhost port=5432 dbname=test (libpq compatible)

Both postgresql:// and postgres:// schemes are accepted for URI format. A raw @ in user or password parses; a raw / or ? there must be percent-encoded, and a raw @ in the database, or in a query with no path, raises PgConfigError (h/db?user=a@b is fine).

As libpq does, a setting the string leaves out (or, in a URI, leaves empty) is taken from its service (PGSERVICE) in the connection service file, else from libpq's environment variable (PGHOST, PGUSER, PGPASSWORD, PGSSLMODE, ...; an empty one counts as unset). The service file is PGSERVICEFILE or ~/.pg_service.conf (%APPDATA%\postgresql\.pg_service.conf on Windows), then $PGSYSCONFDIR/pg_service.conf. An empty service in the string still outranks PGSERVICE and is not found, as in libpq. A missing user is the OS user, and ConnConfig.passFile defaults to ~/.pgpass.

From a variable or the service file, sslcert and sslkey are read only for an sslmode that sends them (prefer or stronger, and not with sslcertmode=disable) and sslrootcert only for one that checks it: verify-ca, verify-full, or require when the file is there (see ConnConfig.sslRootCert). As in libpq, a missing sslcert file there means no client certificate, and sslkey is read only along with one. What none of them names comes on the same terms from libpq's default files in ~/.postgresql (%APPDATA%\postgresql on Windows): root.crt, postgresql.crt and postgresql.key. A named file that is not there is not replaced by the default one, and a named sslkey goes with the default postgresql.crt, both as in libpq. None is read when every host is a Unix socket, where libpq starts no TLS. A root.crl there is a PgConfigError whenever a CA is checked: libpq checks revocation against it, which this client cannot. An empty sslrootcert, sslcert or sslkey means the default file, as in libpq. sslrootcert=system, wherever it is set, trusts the system's root certificates (ConnConfig.sslRootCertSystem) and reads neither root.crt nor root.crl; as in libpq, it makes the sslmode verify-full unless one is set anywhere, and any other sslmode is a PgConfigError. ./system names a file. client_encoding is ignored there and PGDATESTYLE keeps only its field order (DMY, ...): the session is UTF8 and ISO regardless.

A libpq keyword this client does not implement (gssencmode=disable, krbsrvname, ...) is ignored wherever it is set, unless it asks for a check or a limit this client would not apply (sslcrl, requirepeer, ssl_min_protocol_version=TLSv1.3, ...), which is a PgConfigError. So is a value libpq refuses too (an empty sslcertmode= in the string or the service file, ...). tcp_user_timeout is read only as libpq reads it, for a TCP host with keepalives on (a malformed value there is a PgConfigError), into ConnConfig.tcpUserTimeout; it is applied to the socket on Linux, as libpq applies it, and never sent to the server. fallback_application_name is the application_name when none is set. Application_Name in any case is read as application_name, the server setting it names. The deprecated requiressl is read as sslmode in the string and a URI (a value starting with 1 is require, anything else prefer), and a URI's ssl=true as sslmode=require; in the service file requiressl is a PgConfigError, as in libpq. A key set twice in the string keeps the last value; a keyword matches only in its own case (SSLMODE is a startup parameter, as libpq would refuse it). Integers follow libpq's strtol rules: surrounding spaces and a sign are taken, and a libpq keyword's value must fit a C int. sslsni is on only for a value starting with 1, as in libpq; a value that is not an integer is a PgConfigError. sslcertmode=disable is honored: no client certificate is sent, and one in the string with it is a PgConfigError unless sslmode is disable or allow, where the string's certificate and key are dropped unread (so is a key given without a certificate, in any mode). With environment = false only the string counts: no variable, no default file and no OS user; a service there then finds no file.

client_encoding is always UTF8: another value, directly or via -c in options, raises PgConfigError. Likewise DateStyle always uses the ISO output style: only its field order (DMY, ...) may be set. TimeZone is UTC unless set here; PGTZ is not read, since a session zone other than UTC shifts a DateTime parameter bound to timestamptz. Set TimeZone in the string, options or extraParams to change it (see ConnConfig.extraParams).

Security: the DSN is trusted configuration — unknown keys are forwarded as StartupMessage parameters, so a typo in a security-sensitive key (e.g. sslmde) is not detected. Do not pass end-user-controlled strings without sanitizing: a service with a password in its file sends it to whatever host the string names. Parse and validation failures report lengths and offsets only, never parameter values (a malformed DSN may place the password in any field), and name the variable or service file line a value came from; file I/O errors name the path for diagnosis. See ConnConfig for plaintext password handling.

proc validateConnConfig(config: var ConnConfig) {....raises: [PgConfigError],
    tags: [], forbids: [].}

Mirror DSN guards for initConnConfig and the connect chokepoint (DSN parsers validate inline; hand-built ConnConfig is re-checked at connect time so numeric / hostaddr faults become PgConfigError).

An empty host with no hostaddr is rejected rather than defaulted (matching the DSN parsers), so an unset template variable cannot hand the credentials to whatever listens on localhost. The scalar host/hostaddr/port are mirrored from hosts[0], which is what getHosts dials. Negative connectTimeout becomes ZeroDuration. A credentialsProvider alongside a non-empty password is rejected: which one is sent would not show.