veko doc
Self-Contained API Reference • Gradual Types • Capabilities • Wasm Sandbox

db/postgres

lib/db/postgres.vk

lib/db/postgres.vk Pure-Veko PostgreSQL v3.0 binary wire protocol client over io/Stream. Implements StartupMessage, RFC 5802/7677 SCRAM-SHA-256 authentication, CleartextPassword fallback, Simple Query ('Q'), RowDescription ('T'), DataRow ('D'), CommandComplete ('C'), ReadyForQuery ('Z'), and ErrorResponse ('E'). Zero C FFI — works over TCP, TLS 1.3 (tls13/tls-stream), or io/mem-stream.

PgMsg struct
signature
PgMsg = struct { tag i64, body bytes }

Raw PostgreSQL v3 backend message (tag ASCII byte + body payload).

PgConn struct
signature
PgConn = struct { stream io/Stream, server_params map[str], backend_pid i64, backend_key i64, tx_status i64, transport_kind enum = ... }

Connected PostgreSQL session state over an io/Stream.

PgConfig struct
signature
PgConfig = struct { host str = ..., port i64 = ..., user str = ..., password str = ..., database str = ..., ssl_mode enum = ..., tls_opts map = ..., connect_timeout dur = ..., io_timeout dur = ... }

Connection & TLS 1.3 configuration for connect and new-pool.

PgPool struct
signature
PgPool = struct { cfg PgConfig, max_conns i64, acquire_timeout dur = ..., max_idle_ns i64 = ..., health_check_ns i64 = ..., sem_ch any, idle_ch any }

Thread-safe channel-backed PostgreSQL connection pool (stores closure-free transport slots across spawn workers).

PgResult struct
signature
PgResult = struct { columns block[str], rows block[block], command_tag str }

Query result containing column names, row data (str or .null), and command completion tag.

signature
ScramServerFirst = struct { nonce str, salt bytes, iters i64, raw str }

Parsed SCRAM-SHA-256 server-first challenge fields.

ScramProof struct
signature
ScramProof = struct { client_final str, expected_server bytes }

Computed SCRAM-SHA-256 client-final proof + expected server signature.

signature
encode-startup = fn [user str, database str] bytes

Encodes a PostgreSQL v3.0 StartupMessage (len(u32) || 196608(u32) || k\0v\0... || \0).

Executable Example
veko
use [pg = db/postgres]
m = pg/encode-startup 'veko' 'appdb'
if (bytes/get-u32-be m 0) != (len m) or (bytes/get-u32-be m 4) != 196608 [ err 'pg startup' ] else [ .ok ]
signature
encode-msg = fn [tag i64, payload bytes] bytes

Encodes a typed PostgreSQL frontend message (tag(u8) || len(u32) || payload).

signature
encode-query = fn [sql str] bytes

Encodes a Simple Query ('Q') message.

signature
encode-password = fn [password str] bytes

Encodes a PasswordMessage ('p') for cleartext auth.

signature
encode-sasl-initial = fn [mech str, client_first bytes] bytes

Encodes a SASLInitialResponse ('p') selecting mech (e.g. 'SCRAM-SHA-256').

signature
encode-sasl-response = fn [client_final bytes] bytes

Encodes a SASLResponse ('p') carrying client-final bytes.

signature
encode-terminate = fn [] bytes

Encodes a Terminate ('X') message.

signature
read-msg = fn [mut stream io/Stream] PgMsg

Reads one PostgreSQL backend message (tag(1B) || len(4B) || body) from stream.

signature
decode-row-description = fn [body bytes] block[str]

Decodes a RowDescription ('T') payload into a block of column names.

signature
decode-data-row = fn [body bytes] block

Decodes a DataRow ('D') payload into a block of strings (or .null for SQL NULL).

signature
decode-error-fields = fn [body bytes] map[str]

Decodes an ErrorResponse ('E') or NoticeResponse ('N') payload into a field map.

signature
scram-client-first = fn [user str, client_nonce str] str

Formats the SCRAM-SHA-256 client-first message ('n,,n=<user>,r=<nonce>').

signature
scram-parse-server-first = fn [msg str] ScramServerFirst

Parses a SCRAM-SHA-256 server-first message ('r=<nonce>,s=<b64salt>,i=<iters>').

signature
scram-compute-proof = fn [password str, client_first str, sf ScramServerFirst] ScramProof

Computes the RFC 7677 SCRAM-SHA-256 client-final message and expected server signature.

Executable Example
veko
use [pg = db/postgres]
cf = pg/scram-client-first 'user' 'rOprNGfwEbeRWgbNEkqO'
sf = pg/scram-parse-server-first 'r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096'
pr = pg/scram-compute-proof 'pencil' cf sf
if not (str/contains? pr.client_final 'p=dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ=') [
  err 'rfc7677 scram-sha-256 vector'
] else [ .ok ]
signature
scram-verify-server-final = fn [server_final str, expected_server bytes] bool

Verifies the server-final SCRAM-SHA-256 message ('v=<b64sig>') in constant time.

signature
md5-password-hash = fn [user str, password str, salt4 bytes] str

Computes PostgreSQL's md5 password authenticator ('md5' + hex(md5(hex(md5(password + user)) + salt4))).

signature
encode-ssl-request = fn [] bytes

Encodes PostgreSQL's 8-byte SSLRequest startup packet (len=8 || 80877103).

signature
connect-stream = fn [mut stream io/Stream, user str, password str, database str] PgConn

Performs the PostgreSQL v3.0 startup and authentication handshake over stream.

signature
query = fn [mut conn PgConn, sql str] PgResult

Executes a Simple Query ('Q') on conn and collects all returned rows until ReadyForQuery.

signature
close = fn [mut conn PgConn] enum

Sends a Terminate ('X') message and closes the underlying io/Stream.

connect fn caps: .net
signature
connect = fn [cfg PgConfig] PgConn

Connects to PostgreSQL over TCP with optional SSLRequest -> TLS 1.3 upgrade (ssl_mode in .disable, .prefer, .require).

signature
encode-parse = fn [stmt_name str, sql str] bytes

Encodes a Parse ('P') frontend message for $1, $2, ... parameterized SQL.

signature
encode-bind = fn [portal_name str, stmt_name str, params block] bytes

Encodes a Bind ('B') frontend message binding params (str, i64, f64, bool, bytes, or .null).

signature
encode-describe-portal = fn [portal_name str] bytes

Encodes a Describe ('D') message for portal portal_name.

signature
encode-execute = fn [portal_name str, max_rows i64] bytes

Encodes an Execute ('E') message (max_rows = 0 for all rows).

signature
encode-sync = fn [] bytes

Encodes a Sync ('S') message ending an Extended Query pipeline.

signature
query-params = fn [mut conn PgConn, sql str, params block] PgResult

Executes a SQL-injection-safe parameterized query ($1, $2, ...) using the Extended Query Protocol (Parse+Bind+Describe+Execute+Sync).

signature
prepare = fn [mut conn PgConn, stmt_name str, sql str] enum

Prepares a named server-side statement stmt_name for sql.

signature
query-prepared = fn [mut conn PgConn, stmt_name str, params block] PgResult

Executes a previously prepared statement stmt_name with params.

signature
rows-to-maps = fn [res PgResult] block[map]

Converts a PgResult into a block of maps keyed by res.columns.

signature
with-tx = fn [mut conn PgConn, work_fn any] any

Runs (work_fn mut conn) inside a BEGIN / COMMIT / ROLLBACK transaction (automatically using SAVEPOINT when nested!).

signature
new-pool = fn [cfg PgConfig, /max max_conns i64] PgPool

Creates a thread-safe PgPool bounded to max_conns concurrent connections (safe to share across spawn workers).

with-conn fn caps: .clocks
signature
with-conn = fn [pool PgPool, work_fn any] any

Borrows a healthy PgConn from pool (validating health & rolling back dirty transactions), runs (work_fn mut conn), and returns it.

signature
close-pool = fn [pool PgPool] i64

Drains and closes all idle connections in pool.