From 43adca39b53c6226ee713a73c8552645a01d5a7e Mon Sep 17 00:00:00 2001 From: Mark Kalsbeek Date: Tue, 20 Oct 2026 21:39:01 +0200 Subject: [PATCH] smarm-pg 0.1.0: the Postgres client from the urus + smarm Conduit server Extracted from rust-urus-markk116 (db/wire.rs, db/types.rs). Changes on the way: - Config (was DbConfig) takes startup options; plan_cache_mode/jit are now the app's choice - PgConn::query for single statements - bool parameters and results; FromSql for time::OffsetDateTime (feature time) replaces the app-specific Timestamp - a parameter count mismatch is refused before sending and leaves the connection usable - lib denies unwrap/expect, as smarm does Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iFkM6QYfk9aJxpog3uuTj --- .gitignore | 1 + Cargo.lock | 598 +++++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 24 +++ LICENSE | 21 ++ README.md | 57 +++++ src/conn.rs | 562 +++++++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 40 ++++ src/lib.rs | 40 ++++ src/rows.rs | 98 +++++++++ src/stmt.rs | 49 +++++ src/types.rs | 191 ++++++++++++++++ 11 files changed, 1681 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/conn.rs create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 src/rows.rs create mode 100644 src/stmt.rs create mode 100644 src/types.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..24de67f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,598 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +dependencies = [ + "cmov", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "generator" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" +dependencies = [ + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows-link", + "windows-result", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loom" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64", + "byteorder", + "bytes", + "fallible-iterator", + "hmac", + "md-5", + "memchr", + "rand", + "sha2", + "stringprep", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "smarm" +version = "0.8.1" +source = "git+https://git.kalsbeek.dev/Markk116/smarm?tag=v0.8.1#095dead8b1bd789be2757bd56064e32343ed8adc" +dependencies = [ + "cc", + "libc", + "loom", +] + +[[package]] +name = "smarm-pg" +version = "0.1.0" +dependencies = [ + "bytes", + "libc", + "postgres-protocol", + "smarm", + "time", +] + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c65057d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "smarm-pg" +version = "0.1.0" +edition = "2021" +rust-version = "1.95" +description = "A small Postgres client for the smarm actor runtime: blocking calls that park on fd readiness" +license = "MIT" + +[dependencies] +smarm = { git = "https://git.kalsbeek.dev/Markk116/smarm", tag = "v0.8.1" } +postgres-protocol = "0.6" +bytes = "1" +libc = "0.2" +time = { version = "0.3", optional = true } + +[features] +default = ["time"] +# `FromSql` for `time::OffsetDateTime` (timestamptz). +time = ["dep:time"] + +[lints.clippy] +# As in smarm: library code doesn't hide panics behind unwrap/expect. +unwrap_used = "deny" +expect_used = "deny" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5730ea2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Mark Kalsbeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b21990e --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# smarm-pg + +A small Postgres client for the [smarm](https://git.kalsbeek.dev/Markk116/smarm) actor runtime. +Calls are plain blocking functions: the socket is read and written optimistically and the +calling actor parks on smarm's fd readiness only on `EAGAIN`. No async, no runtime of its own. + +Extracted from the urus + smarm Conduit server, where it replaced tokio-based drivers that +don't fit smarm. + +```rust +use smarm_pg::{oid, Config, PgConn, Stmt}; + +static ADD: Stmt = Stmt::read("SELECT $1::int8 + 1", &[oid::INT8]); + +smarm::run(|| { + let cfg = Config::parse("postgres://app:secret@127.0.0.1/app") + .unwrap() + .option("plan_cache_mode", "force_generic_plan"); + let mut conn = PgConn::connect(&cfg).unwrap(); + let rows = conn.query(&ADD, &[&41i64]).unwrap(); + assert_eq!(rows.first::().unwrap(), Some(42)); +}); +``` + +## What it does + +- **Extended protocol only.** Statements are `static` `Stmt`s. A connection prepares each one the + first time it runs it, under a name of its own, and reuses it afterwards. The Parse goes out in + the same write as the Bind/Execute, so a cold statement still costs one round trip. +- **Binary parameters and results.** +- **Pipelines.** `PgConn::pipeline` sends several statements behind one Sync: one round trip, one + implicit transaction. If one fails, the rest are skipped and none of them took effect. +- **Startup options.** `Config::option` puts session settings in the startup message. +- **Auth:** trust, cleartext, MD5, SCRAM-SHA-256 (no channel binding). +- **Failure:** a server error (`PgError::Db`) leaves the connection usable; anything else + (`PgError::fatal`) marks it broken for good (`is_healthy`), and the owner should drop it. + +## What it doesn't do (yet) + +- **Pooling.** One `PgConn` is one connection, used by one actor at a time. In smarm the natural + pool is an actor per connection under a supervisor, sending batches by message; the + application owns that, along with routing (`Stmt::writes` is there for read/write splitting). +- **Types:** `bool`, `int8` (int4 reads too), `text`, `text[]`, `timestamptz` (as + `time::OffsetDateTime`, feature `time`, on by default). Everything else is `Rows::raw`. +- No TLS, no COPY, no LISTEN/NOTIFY, no explicit transactions beyond a pipeline, no percent-decoding + in URLs, no Unix sockets. + +## Tests + +`TEST_DATABASE_URL=postgres://user:pw@127.0.0.1/db cargo test`. Without it, the tests that need a +server print a note and pass. They only create session-local temp tables. + +`cargo clippy --lib` must be clean: as in smarm, the library denies `unwrap`/`expect`. + +## License + +MIT diff --git a/src/conn.rs b/src/conn.rs new file mode 100644 index 0000000..73ed8bd --- /dev/null +++ b/src/conn.rs @@ -0,0 +1,562 @@ +//! One connection: blocking from the calling actor's point of view, parking on smarm's fd +//! readiness when the socket would block. + +use std::collections::HashMap; +use std::io::{self, Read as _, Write as _}; +use std::net::TcpStream; +use std::os::fd::{AsRawFd, RawFd}; + +use bytes::BytesMut; +use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256}; +use postgres_protocol::message::frontend; + +use crate::error::{PgError, PgResult}; +use crate::rows::{be_i32, Rows}; +use crate::stmt::{oid, Param, Step, Stmt}; +use crate::types::ToParam; + +/// Where to connect, as whom, and the session settings to start with. +#[derive(Clone, Debug)] +pub struct Config { + pub host: String, + pub port: u16, + pub user: String, + pub password: String, + pub dbname: String, + /// Run-time parameters sent in the startup message (`plan_cache_mode`, `jit`, …): in force + /// for the whole session, at no extra round trip. + pub options: Vec<(String, String)>, +} + +impl Config { + /// `postgres://user:pass@host:port/db` (or `postgresql://`). The query string is ignored + /// and nothing is percent-decoded. + pub fn parse(url: &str) -> Option { + let rest = url.strip_prefix("postgres://").or_else(|| url.strip_prefix("postgresql://"))?; + let (auth, hostdb) = rest.rsplit_once('@')?; + let (user, password) = auth.split_once(':').unwrap_or((auth, "")); + let (hostport, db) = hostdb.split_once('/')?; + let db = db.split('?').next()?; + let (host, port) = match hostport.rsplit_once(':') { + Some((h, p)) => (h, p.parse().ok()?), + None => (hostport, 5432), + }; + Some(Config { + host: host.to_string(), + port, + user: user.to_string(), + password: password.to_string(), + dbname: db.to_string(), + options: Vec::new(), + }) + } + + /// Add a session setting for the startup message. + pub fn option(mut self, name: &str, value: &str) -> Config { + self.options.push((name.to_string(), value.to_string())); + self + } +} + +pub struct PgConn { + _sock: TcpStream, + fd: RawFd, + rbuf: Vec, + rpos: usize, + wbuf: BytesMut, + /// Server-side name for each statement this connection has seen, by [`Stmt::key`], and + /// whether the server has confirmed preparing it (ParseComplete). + statements: HashMap, + broken: bool, +} + +impl PgConn { + /// Connects and authenticates (trust, cleartext, MD5 or SCRAM-SHA-256 without channel + /// binding). Startup runs on a blocking socket (it happens a handful of times per process); + /// the socket goes non-blocking afterwards. + pub fn connect(cfg: &Config) -> PgResult { + let mut sock = TcpStream::connect((cfg.host.as_str(), cfg.port))?; + sock.set_nodelay(true)?; + let mut buf = BytesMut::new(); + let params = [("user", cfg.user.as_str()), ("database", cfg.dbname.as_str()), ("client_encoding", "UTF8")] + .into_iter() + .chain(cfg.options.iter().map(|(k, v)| (k.as_str(), v.as_str()))); + frontend::startup_message(params, &mut buf)?; + sock.write_all(&buf)?; + buf.clear(); + + let mut scram: Option = None; + loop { + let (tag, body) = read_msg_blocking(&mut sock)?; + match tag { + b'R' => { + if body.len() < 4 { + return Err(PgError::Protocol("short authentication message")); + } + match be_i32(&body[0..4]) { + 0 => {} + 3 => frontend::password_message(cfg.password.as_bytes(), &mut buf)?, + 5 => { + let salt = body.get(4..8).ok_or(PgError::Protocol("short MD5 salt"))?; + let pw = postgres_protocol::authentication::md5_hash( + cfg.user.as_bytes(), + cfg.password.as_bytes(), + [salt[0], salt[1], salt[2], salt[3]], + ); + frontend::password_message(pw.as_bytes(), &mut buf)?; + } + 10 => { + let s = ScramSha256::new(cfg.password.as_bytes(), ChannelBinding::unsupported()); + frontend::sasl_initial_response("SCRAM-SHA-256", s.message(), &mut buf)?; + scram = Some(s); + } + 11 => { + let s = scram.as_mut().ok_or(PgError::Protocol("sasl continue without start"))?; + s.update(&body[4..])?; + frontend::sasl_response(s.message(), &mut buf)?; + } + 12 => { + let s = scram.as_mut().ok_or(PgError::Protocol("sasl final without start"))?; + s.finish(&body[4..])?; + } + _ => return Err(PgError::Protocol("unsupported auth method")), + } + if !buf.is_empty() { + sock.write_all(&buf)?; + buf.clear(); + } + } + b'E' => return Err(parse_error(&body)), + b'Z' => break, + _ => {} // ParameterStatus, BackendKeyData, NoticeResponse + } + } + sock.set_nonblocking(true)?; + let fd = sock.as_raw_fd(); + Ok(PgConn { + _sock: sock, + fd, + rbuf: Vec::with_capacity(16 * 1024), + rpos: 0, + wbuf: BytesMut::with_capacity(4096), + statements: HashMap::new(), + broken: false, + }) + } + + /// False once an IO or protocol error has left the connection unusable. + pub fn is_healthy(&self) -> bool { + !self.broken + } + + /// Run one statement. + pub fn query(&mut self, stmt: &'static Stmt, params: &[&dyn ToParam]) -> PgResult { + let step = Step { stmt, params: params.iter().map(|p| p.to_param()).collect() }; + let mut results = self.pipe(std::slice::from_ref(&step))?; + results.pop().ok_or(PgError::Protocol("result count mismatch")) + } + + /// [`pipeline`](Self::pipeline), failing on the first statement error (the batch is + /// all-or-nothing anyway). + pub fn pipe(&mut self, steps: &[Step]) -> PgResult> { + self.pipeline(steps)?.into_iter().collect() + } + + /// Run several statements behind one Sync: one round trip, one implicit transaction (an + /// error in any of them rolls all of them back). Per-statement results; statements after a + /// failed one are reported as skipped. + pub fn pipeline(&mut self, steps: &[Step]) -> PgResult>> { + if self.broken { + return Err(PgError::Protocol("connection broken")); + } + if steps.iter().any(|step| step.stmt.types.len() != step.params.len()) { + // Caught before anything is sent, so the connection stays usable. + return Err(PgError::Protocol("parameter count differs from the statement's types")); + } + let r = self.pipeline_inner(steps); + if let Err(e) = &r { + if e.fatal() { + self.broken = true; + } + } + r + } + + fn pipeline_inner(&mut self, steps: &[Step]) -> PgResult>> { + self.wbuf.clear(); + for step in steps { + self.encode(step.stmt, &step.params); + } + frontend::sync(&mut self.wbuf); + self.flush()?; + + let mut results: Vec> = Vec::with_capacity(steps.len()); + let mut cur = Rows::default(); + let mut idx = 0usize; + loop { + let (tag, start, end) = self.next_msg()?; + match tag { + b'1' => { + if let Some(entry) = steps.get(idx).and_then(|step| self.statements.get_mut(&step.stmt.key())) { + entry.1 = true; + } + } + b'2' | b'n' | b'I' | b's' => {} + b'D' => { + let body = &self.rbuf[start..end]; + let n = u16::from_be_bytes([body[0], body[1]]) as usize; + cur.ncols = n; + let mut p = 2; + for _ in 0..n { + let l = be_i32(&body[p..p + 4]); + p += 4; + let off = cur.data.len() as u32; + if l > 0 { + cur.data.extend_from_slice(&body[p..p + l as usize]); + p += l as usize; + } + cur.cols.push((off, l)); + } + } + b'C' => { + let body = &self.rbuf[start..end]; + let tagstr = std::str::from_utf8(&body[..body.len().saturating_sub(1)]).unwrap_or(""); + cur.affected = tagstr.rsplit(' ').next().and_then(|n| n.parse().ok()).unwrap_or(0); + results.push(Ok(std::mem::take(&mut cur))); + idx += 1; + } + b'E' => { + results.push(Err(parse_error(&self.rbuf[start..end]))); + idx += 1; + } + b'Z' => break, + b'N' | b'S' | b'A' => {} + _ => return Err(PgError::Protocol("unexpected message")), + } + } + // After an error the server skips the rest of the batch: report those as errors too. + while results.len() < steps.len() { + results.push(Err(PgError::Protocol("skipped after earlier error"))); + } + Ok(results) + } + + /// Parse (until the server has confirmed it once), Bind, Execute. + fn encode(&mut self, st: &'static Stmt, params: &[Param]) { + let next = self.statements.len(); + let (name, prepared) = self.statements.entry(st.key()).or_insert_with(|| (format!("s{next}"), false)); + let w = &mut self.wbuf; + if !*prepared { + let _ = frontend::parse(name, st.sql, st.types.iter().copied(), w); + } + // Bind: portal "", statement, 1 format code (binary for all), params, 1 result format (binary). + w.extend_from_slice(b"B"); + let len_at = w.len(); + w.extend_from_slice(&[0; 4]); + w.extend_from_slice(b"\0"); + w.extend_from_slice(name.as_bytes()); + w.extend_from_slice(b"\0"); + w.extend_from_slice(&1i16.to_be_bytes()); + w.extend_from_slice(&1i16.to_be_bytes()); + w.extend_from_slice(&(params.len() as i16).to_be_bytes()); + for p in params { + match p { + Param::Null => w.extend_from_slice(&(-1i32).to_be_bytes()), + Param::Bool(v) => { + w.extend_from_slice(&1i32.to_be_bytes()); + w.extend_from_slice(&[u8::from(*v)]); + } + Param::I8(v) => { + w.extend_from_slice(&8i32.to_be_bytes()); + w.extend_from_slice(&v.to_be_bytes()); + } + Param::Text(s) => { + w.extend_from_slice(&(s.len() as i32).to_be_bytes()); + w.extend_from_slice(s.as_bytes()); + } + Param::TextArr(items) => { + let start = w.len(); + w.extend_from_slice(&[0; 4]); + w.extend_from_slice(&1i32.to_be_bytes()); // ndim + w.extend_from_slice(&0i32.to_be_bytes()); // has nulls + w.extend_from_slice(&oid::TEXT.to_be_bytes()); + w.extend_from_slice(&(items.len() as i32).to_be_bytes()); + w.extend_from_slice(&1i32.to_be_bytes()); // lower bound + for it in items { + w.extend_from_slice(&(it.len() as i32).to_be_bytes()); + w.extend_from_slice(it.as_bytes()); + } + let l = (w.len() - start - 4) as i32; + w[start..start + 4].copy_from_slice(&l.to_be_bytes()); + } + } + } + w.extend_from_slice(&1i16.to_be_bytes()); + w.extend_from_slice(&1i16.to_be_bytes()); + let l = (w.len() - len_at) as i32; + w[len_at..len_at + 4].copy_from_slice(&l.to_be_bytes()); + let _ = frontend::execute("", 0, w); + } + + fn flush(&mut self) -> io::Result<()> { + let mut off = 0; + while off < self.wbuf.len() { + // SAFETY: the pointer and length describe the unwritten tail of wbuf. + let n = unsafe { libc::write(self.fd, self.wbuf[off..].as_ptr().cast(), self.wbuf.len() - off) }; + if n >= 0 { + off += n as usize; + continue; + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::WouldBlock => smarm::wait_writable(self.fd)?, + io::ErrorKind::Interrupted => {} + _ => return Err(e), + } + } + Ok(()) + } + + /// Next backend message: (tag, body start, body end) into rbuf. Reads optimistically and + /// only parks on epoll when the socket really has nothing. + fn next_msg(&mut self) -> PgResult<(u8, usize, usize)> { + loop { + let avail = self.rbuf.len() - self.rpos; + if avail >= 5 { + let len = be_i32(&self.rbuf[self.rpos + 1..self.rpos + 5]) as usize; + if avail > len { + let tag = self.rbuf[self.rpos]; + let start = self.rpos + 5; + let end = self.rpos + 1 + len; + self.rpos = end; + return Ok((tag, start, end)); + } + } + if self.rpos > 0 { + self.rbuf.drain(..self.rpos); + self.rpos = 0; + } + let have = self.rbuf.len(); + if self.rbuf.capacity() - have < 8192 { + self.rbuf.reserve(16 * 1024); + } + let cap = self.rbuf.capacity(); + // SAFETY: reads into rbuf's spare capacity; set_len only covers the bytes read. + let n = unsafe { libc::read(self.fd, self.rbuf.as_mut_ptr().add(have).cast(), cap - have) }; + if n > 0 { + unsafe { self.rbuf.set_len(have + n as usize) }; + continue; + } + if n == 0 { + return Err(PgError::Io(io::ErrorKind::UnexpectedEof.into())); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::WouldBlock => smarm::wait_readable(self.fd)?, + io::ErrorKind::Interrupted => {} + _ => return Err(e.into()), + } + } + } +} + +fn read_msg_blocking(sock: &mut TcpStream) -> io::Result<(u8, Vec)> { + let mut head = [0u8; 5]; + sock.read_exact(&mut head)?; + let len = be_i32(&head[1..5]) as usize; + let mut body = vec![0u8; len.saturating_sub(4)]; + sock.read_exact(&mut body)?; + Ok((head[0], body)) +} + +fn parse_error(body: &[u8]) -> PgError { + let mut code = String::new(); + let mut message = String::new(); + let mut p = 0; + while p < body.len() && body[p] != 0 { + let field = body[p]; + let end = body[p + 1..].iter().position(|&b| b == 0).map_or(body.len(), |i| p + 1 + i); + let val = String::from_utf8_lossy(&body[p + 1..end]).into_owned(); + match field { + b'C' => code = val, + b'M' => message = val, + _ => {} + } + p = end + 1; + } + PgError::Db { code, message } +} + +// Against a real Postgres at TEST_DATABASE_URL (skipped when unset). Only session-local temp +// tables are created, so any database the role can connect to will do. +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use crate::oid::{BOOL, INT8, TEXT, TEXT_ARR}; + + static SELECT_INT: Stmt = Stmt::read("SELECT $1::int8", &[INT8]); + static ECHO: Stmt = Stmt::read("SELECT $1::bool, $2::text, $3::text[]", &[BOOL, TEXT, TEXT_ARR]); + static DIV_ZERO: Stmt = Stmt::read("SELECT 1 / 0", &[]); + static MAKE_TEMP: Stmt = Stmt::write("CREATE TEMP TABLE IF NOT EXISTS t (k text PRIMARY KEY)", &[]); + static INSERT: Stmt = Stmt::write("INSERT INTO t VALUES ($1)", &[TEXT]); + static COUNT: Stmt = Stmt::read("SELECT count(*) FROM t", &[]); + static SHAPES: Stmt = Stmt::read( + "SELECT NULL::text, $1::text, ARRAY['b', 'a']::text[], ARRAY[]::text[], true, \ + '2025-04-01T12:00:00.1239Z'::timestamptz", + &[TEXT], + ); + static SETTING: Stmt = Stmt::read("SELECT current_setting('application_name')", &[]); + static DIE: Stmt = Stmt::read("SELECT pg_terminate_backend(pg_backend_pid())", &[]); + + fn step(stmt: &'static Stmt, params: &[Param]) -> Step { + Step { stmt, params: params.to_vec() } + } + + fn config() -> Option { + let cfg = std::env::var("TEST_DATABASE_URL").ok().and_then(|u| Config::parse(&u)); + if cfg.is_none() { + eprintln!("TEST_DATABASE_URL not set: skipping"); + } + cfg + } + + /// Run `f` with a fresh connection inside a smarm runtime (the client parks on epoll). + fn with_conn(f: impl FnOnce(&mut PgConn) + Send + 'static) { + let Some(cfg) = config() else { return }; + smarm::run(move || { + let mut c = PgConn::connect(&cfg).unwrap(); + f(&mut c); + }); + } + + #[test] + fn parses_urls() { + let c = Config::parse("postgresql://u:p:w@db.local:6543/app?sslmode=disable").unwrap(); + assert_eq!((c.user.as_str(), c.password.as_str()), ("u", "p:w")); + assert_eq!((c.host.as_str(), c.port, c.dbname.as_str()), ("db.local", 6543, "app")); + assert_eq!(Config::parse("postgres://u@h/db").unwrap().port, 5432); + assert!(Config::parse("mysql://u@h/db").is_none()); + } + + #[test] + fn statement_is_prepared_once_and_reused() { + with_conn(|c| { + for v in [7i64, 8] { + assert_eq!(c.query(&SELECT_INT, &[&v]).unwrap().i64(0, 0), v); + } + assert_eq!(c.statements.len(), 1); + assert!(c.statements[&SELECT_INT.key()].1); + }); + } + + #[test] + fn parameters_round_trip() { + with_conn(|c| { + let tags = vec!["x".to_string(), String::new(), "ü".to_string()]; + let r = c.query(&ECHO, &[&true, &"hi", &tags]).unwrap(); + assert!(r.bool(0, 0)); + assert_eq!(r.str(0, 1), "hi"); + assert_eq!(r.text_array(0, 2).collect::>(), ["x", "", "ü"]); + let r = c.query(&ECHO, &[&false, &None::, &Vec::::new()]).unwrap(); + assert!(!r.bool(0, 0)); + assert_eq!(r.opt_str(0, 1), None); + assert_eq!(r.text_array(0, 2).count(), 0); + }); + } + + #[test] + fn wrong_parameter_count_is_refused_before_sending() { + with_conn(|c| { + let e = c.pipe(&[step(&SELECT_INT, &[])]).err().unwrap(); + assert!(matches!(e, PgError::Protocol(_))); + assert!(c.is_healthy()); + assert_eq!(c.query(&SELECT_INT, &[&5i64]).unwrap().i64(0, 0), 5); + }); + } + + #[test] + fn startup_options_apply_to_the_session() { + let Some(cfg) = config() else { return }; + let cfg = cfg.option("application_name", "smarm-pg-test"); + smarm::run(move || { + let mut c = PgConn::connect(&cfg).unwrap(); + assert_eq!(c.query(&SETTING, &[]).unwrap().str(0, 0), "smarm-pg-test"); + }); + } + + #[test] + fn error_mid_batch_skips_the_rest_and_leaves_the_connection_usable() { + with_conn(|c| { + let one = [Param::I8(1)]; + let res = + c.pipeline(&[step(&SELECT_INT, &one), step(&DIV_ZERO, &[]), step(&SELECT_INT, &one)]).unwrap(); + assert!(res[0].is_ok()); + assert!(matches!(&res[1], Err(PgError::Db { code, .. }) if code == "22012")); + assert!(res[2].is_err()); + assert!(c.is_healthy()); + // The statement after the error never ran, but its Parse might have: either way + // the next use must work (a stale "prepared" flag would break it). + assert_eq!(c.query(&SELECT_INT, &[&3i64]).unwrap().i64(0, 0), 3); + // DIV_ZERO's Parse succeeded before it failed at execution; the rollback must not + // have taken the prepared statement with it (26000 would mean a stale flag). + let again = c.query(&DIV_ZERO, &[]).err().unwrap(); + assert!(matches!(&again, PgError::Db { code, .. } if code == "22012"), "{again}"); + }); + } + + #[test] + fn a_batch_is_one_transaction() { + with_conn(|c| { + c.query(&MAKE_TEMP, &[]).unwrap(); + let res = c.pipeline(&[step(&INSERT, &[Param::Text("x".into())]), step(&DIV_ZERO, &[])]).unwrap(); + assert!(res[0].is_ok() && res[1].is_err()); + assert_eq!(c.query(&COUNT, &[]).unwrap().i64(0, 0), 0, "insert rolled back"); + }); + } + + #[test] + fn unique_violation_is_recognised() { + with_conn(|c| { + c.query(&MAKE_TEMP, &[]).unwrap(); + c.query(&INSERT, &[&"dup"]).unwrap(); + let e = c.query(&INSERT, &[&"dup"]).err().unwrap(); + assert!(e.is_unique_violation()); + assert!(c.is_healthy()); + }); + } + + #[test] + fn decodes_nulls_text_arrays_bools_and_timestamps() { + with_conn(|c| { + let r = c.query(&SHAPES, &[&"héllo \"q\""]).unwrap(); + assert_eq!(r.opt_str(0, 0), None); + assert_eq!(r.str(0, 1), "héllo \"q\""); + assert_eq!(r.text_array(0, 2).collect::>(), ["b", "a"]); + assert_eq!(r.text_array(0, 3).count(), 0); + assert!(r.bool(0, 4)); + // timestamptz: µs since 2000-01-01Z + assert_eq!(r.i64(0, 5), 796_824_000_123_900); + }); + } + + #[cfg(feature = "time")] + #[test] + fn decodes_timestamptz_as_offset_date_time() { + with_conn(|c| { + let r = c.query(&SHAPES, &[&""]).unwrap(); + let t: time::OffsetDateTime = crate::FromSql::from_sql(&r, 0, 5).unwrap(); + assert_eq!(t.unix_timestamp_nanos(), 1_743_508_800_123_900_000); + }); + } + + #[test] + fn a_dead_backend_breaks_the_connection_for_good() { + with_conn(|c| { + let e = c.query(&DIE, &[]).err().unwrap(); + assert!(e.fatal(), "{e}"); + assert!(!c.is_healthy()); + assert!(c.query(&SELECT_INT, &[&1i64]).is_err()); + }); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..b4aa82b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,40 @@ +use std::io; + +#[derive(Debug)] +pub enum PgError { + Io(io::Error), + /// An error the server reported (an ErrorResponse): SQLSTATE and message. + Db { code: String, message: String }, + Protocol(&'static str), +} + +impl PgError { + pub fn is_unique_violation(&self) -> bool { + matches!(self, PgError::Db { code, .. } if code == "23505") + } + + /// Anything but a server-reported error leaves the connection in an unknown state. + pub fn fatal(&self) -> bool { + !matches!(self, PgError::Db { .. }) + } +} + +impl From for PgError { + fn from(e: io::Error) -> Self { + PgError::Io(e) + } +} + +impl std::fmt::Display for PgError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PgError::Io(e) => write!(f, "io: {e}"), + PgError::Db { code, message } => write!(f, "db {code}: {message}"), + PgError::Protocol(m) => write!(f, "protocol: {m}"), + } + } +} + +impl std::error::Error for PgError {} + +pub type PgResult = Result; diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..3308e23 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,40 @@ +//! A small Postgres client for [smarm](https://git.kalsbeek.dev/Markk116/smarm) actors. +//! +//! Calls block the calling actor, not the scheduler thread: socket reads and writes are tried +//! first and the actor only parks on smarm's fd readiness on `EAGAIN`. No async, no runtime of +//! its own. +//! +//! - Extended protocol only. Statements are `static` [`Stmt`]s; a connection prepares each one +//! the first time it runs it (the Parse goes out in the same write as the Bind/Execute, so a +//! cold statement still costs one round trip) and reuses it afterwards. +//! - Binary parameters and results. +//! - [`PgConn::pipeline`] sends several statements behind one Sync: one round trip, one +//! implicit transaction. +//! +//! One [`PgConn`] is one connection, used by one actor at a time. Pooling is left to the +//! application: in smarm the natural shape is an actor per connection under a supervisor. +//! +//! ```no_run +//! use smarm_pg::{oid, Config, PgConn, Stmt}; +//! +//! static ADD: Stmt = Stmt::read("SELECT $1::int8 + 1", &[oid::INT8]); +//! +//! smarm::run(|| { +//! let cfg = Config::parse("postgres://app:secret@127.0.0.1/app").unwrap(); +//! let mut conn = PgConn::connect(&cfg).unwrap(); +//! let rows = conn.query(&ADD, &[&41i64]).unwrap(); +//! assert_eq!(rows.first::().unwrap(), Some(42)); +//! }); +//! ``` + +mod conn; +mod error; +mod rows; +mod stmt; +mod types; + +pub use conn::{Config, PgConn}; +pub use error::{PgError, PgResult}; +pub use rows::{Rows, TextArrayIter}; +pub use stmt::{oid, Param, Step, Stmt}; +pub use types::{FromRow, FromSql, Row, ToParam}; diff --git a/src/rows.rs b/src/rows.rs new file mode 100644 index 0000000..aafce43 --- /dev/null +++ b/src/rows.rs @@ -0,0 +1,98 @@ +/// The result of one statement: all its DataRows in one buffer. +#[derive(Default)] +pub struct Rows { + pub(crate) data: Vec, + /// (start, len) per column, len -1 = NULL, row-major. + pub(crate) cols: Vec<(u32, i32)>, + pub(crate) ncols: usize, + /// Affected-row count from CommandComplete (INSERT/UPDATE/DELETE). + pub affected: u64, +} + +impl Rows { + pub fn len(&self) -> usize { + self.cols.len().checked_div(self.ncols).unwrap_or(0) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// The binary value at row `r`, column `c`; `None` for NULL. + #[inline] + pub fn raw(&self, r: usize, c: usize) -> Option<&[u8]> { + let (s, l) = self.cols[r * self.ncols + c]; + if l < 0 { + None + } else { + Some(&self.data[s as usize..s as usize + l as usize]) + } + } + + /// int8 or int4; also a timestamptz's microseconds since 2000-01-01Z. 0 for NULL. + pub fn i64(&self, r: usize, c: usize) -> i64 { + match self.raw(r, c) { + Some(b) if b.len() == 8 => i64::from_be_bytes(b.try_into().unwrap_or([0; 8])), + Some(b) if b.len() == 4 => i32::from_be_bytes(b.try_into().unwrap_or([0; 4])) as i64, + _ => 0, + } + } + + pub fn bool(&self, r: usize, c: usize) -> bool { + matches!(self.raw(r, c), Some([1])) + } + + /// Text; "" for NULL. + pub fn str(&self, r: usize, c: usize) -> &str { + self.opt_str(r, c).unwrap_or("") + } + + pub fn opt_str(&self, r: usize, c: usize) -> Option<&str> { + // Postgres guarantees valid UTF-8 for text in a UTF8 database. + self.raw(r, c).map(|b| std::str::from_utf8(b).unwrap_or("")) + } + + /// One-dimensional text[] (binary array format); empty for NULL. + pub fn text_array(&self, r: usize, c: usize) -> TextArrayIter<'_> { + let b = self.raw(r, c).unwrap_or(&[]); + if b.len() < 12 { + return TextArrayIter { b: &[], left: 0 }; + } + let ndim = be_i32(&b[0..4]); + if ndim == 0 { + return TextArrayIter { b: &[], left: 0 }; + } + let n = be_i32(&b[12..16]).max(0) as usize; + TextArrayIter { b: &b[12 + 8 * ndim as usize..], left: n } + } +} + +#[derive(Clone)] +pub struct TextArrayIter<'a> { + b: &'a [u8], + left: usize, +} + +impl<'a> Iterator for TextArrayIter<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + if self.left == 0 || self.b.len() < 4 { + return None; + } + self.left -= 1; + let l = be_i32(&self.b[..4]); + if l < 0 { + self.b = &self.b[4..]; + return Some(""); + } + let (s, rest) = self.b[4..].split_at(l as usize); + self.b = rest; + Some(std::str::from_utf8(s).unwrap_or("")) + } +} + +#[inline] +pub(crate) fn be_i32(b: &[u8]) -> i32 { + i32::from_be_bytes([b[0], b[1], b[2], b[3]]) +} diff --git a/src/stmt.rs b/src/stmt.rs new file mode 100644 index 0000000..712f7f2 --- /dev/null +++ b/src/stmt.rs @@ -0,0 +1,49 @@ +/// Type OIDs for [`Stmt`] parameter lists: the types [`Param`] can encode. +pub mod oid { + pub const BOOL: u32 = 16; + pub const INT8: u32 = 20; + pub const TEXT: u32 = 25; + pub const TEXT_ARR: u32 = 1009; +} + +/// A statement the application runs. Declare each one as a `static`: a connection prepares it +/// the first time it runs it and recognises it afterwards by its address. +pub struct Stmt { + pub sql: &'static str, + /// Parameter type OIDs, one per `$n` (see [`oid`]). + pub types: &'static [u32], + /// Whether it changes data. The client doesn't use this itself; it is there so a pool can + /// route writes, which wait for a WAL flush on commit, away from reads. + pub writes: bool, +} + +impl Stmt { + pub const fn read(sql: &'static str, types: &'static [u32]) -> Stmt { + Stmt { sql, types, writes: false } + } + + pub const fn write(sql: &'static str, types: &'static [u32]) -> Stmt { + Stmt { sql, types, writes: true } + } + + pub(crate) fn key(&'static self) -> usize { + std::ptr::from_ref(self) as usize + } +} + +/// A statement parameter, in the binary wire format of its declared type. Owned, so a batch +/// can be sent to the actor that holds the connection. +#[derive(Clone, Debug, PartialEq)] +pub enum Param { + Null, + Bool(bool), + I8(i64), + Text(String), + TextArr(Vec), +} + +/// One statement and its parameters. +pub struct Step { + pub stmt: &'static Stmt, + pub params: Vec, +} diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 0000000..0ba1a17 --- /dev/null +++ b/src/types.rs @@ -0,0 +1,191 @@ +//! Conversions between Rust values and statement parameters / result columns. + +use crate::error::{PgError, PgResult}; +use crate::rows::Rows; +use crate::stmt::Param; + +/// A value that can be passed as a statement parameter. +pub trait ToParam { + fn to_param(&self) -> Param; +} + +impl ToParam for bool { + fn to_param(&self) -> Param { + Param::Bool(*self) + } +} + +impl ToParam for i64 { + fn to_param(&self) -> Param { + Param::I8(*self) + } +} + +impl ToParam for str { + fn to_param(&self) -> Param { + Param::Text(self.to_owned()) + } +} + +impl ToParam for String { + fn to_param(&self) -> Param { + Param::Text(self.clone()) + } +} + +impl ToParam for Option { + fn to_param(&self) -> Param { + self.as_ref().map_or(Param::Null, ToParam::to_param) + } +} + +impl ToParam for [String] { + fn to_param(&self) -> Param { + Param::TextArr(self.to_vec()) + } +} + +impl ToParam for Vec { + fn to_param(&self) -> Param { + Param::TextArr(self.clone()) + } +} + +impl ToParam for &T { + fn to_param(&self) -> Param { + (**self).to_param() + } +} + +/// A value that can be read from one result column. +pub trait FromSql: Sized { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult; +} + +fn not_null(rows: &Rows, row: usize, col: usize) -> PgResult<()> { + match rows.raw(row, col) { + Some(_) => Ok(()), + None => Err(PgError::Protocol("unexpected NULL")), + } +} + +impl FromSql for i64 { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + not_null(rows, row, col)?; + Ok(rows.i64(row, col)) + } +} + +impl FromSql for bool { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + not_null(rows, row, col)?; + Ok(rows.bool(row, col)) + } +} + +impl FromSql for String { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + not_null(rows, row, col)?; + Ok(rows.str(row, col).to_owned()) + } +} + +impl FromSql for Option { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + Ok(rows.opt_str(row, col).map(str::to_owned)) + } +} + +/// text[]; NULL reads as empty. +impl FromSql for Vec { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + Ok(rows.text_array(row, col).map(str::to_owned).collect()) + } +} + +/// 2000-01-01T00:00:00Z, Postgres's timestamp epoch, in Unix microseconds. +#[cfg(feature = "time")] +const PG_EPOCH_UNIX_MICROS: i128 = 946_684_800_000_000; + +/// timestamptz, in UTC. +#[cfg(feature = "time")] +impl FromSql for time::OffsetDateTime { + fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult { + let pg_micros = i64::from_sql(rows, row, col)?; + let unix_nanos = (PG_EPOCH_UNIX_MICROS + i128::from(pg_micros)) * 1000; + time::OffsetDateTime::from_unix_timestamp_nanos(unix_nanos) + .map_err(|_| PgError::Protocol("timestamp out of range")) + } +} + +/// Reads the columns of one result row in order, so a [`FromRow`] impl lists its fields in the +/// same order as the SELECT list it reads. +pub struct Row<'a> { + rows: &'a Rows, + row: usize, + col: usize, +} + +impl Row<'_> { + /// The next column. + pub fn get(&mut self) -> PgResult { + let value = T::from_sql(self.rows, self.row, self.col)?; + self.col += 1; + Ok(value) + } +} + +/// A value built from one result row. +pub trait FromRow: Sized { + fn from_row(row: &mut Row) -> PgResult; +} + +impl FromRow for i64 { + fn from_row(row: &mut Row) -> PgResult { + row.get() + } +} + +impl FromRow for bool { + fn from_row(row: &mut Row) -> PgResult { + row.get() + } +} + +impl FromRow for String { + fn from_row(row: &mut Row) -> PgResult { + row.get() + } +} + +impl FromRow for (A, B) { + fn from_row(row: &mut Row) -> PgResult { + Ok((row.get()?, row.get()?)) + } +} + +impl FromRow for (A, B, C) { + fn from_row(row: &mut Row) -> PgResult { + Ok((row.get()?, row.get()?, row.get()?)) + } +} + +impl Rows { + /// Every row, decoded. + pub fn all(&self) -> PgResult> { + (0..self.len()).map(|row| self.decode(row)).collect() + } + + /// The first row, if there is one. + pub fn first(&self) -> PgResult> { + if self.is_empty() { + Ok(None) + } else { + self.decode(0).map(Some) + } + } + + fn decode(&self, row: usize) -> PgResult { + T::from_row(&mut Row { rows: self, row, col: 0 }) + } +}