Skip to main content

pylon_value/
lib.rs

1//
2// This source file is part of the Pylon open source project.
3//
4// Copyright (c) 2026 Jaldis B.V.
5//
6// Licensed under the MIT OR Apache-2.0 license (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10//     https://opensource.org/licenses/MIT
11//     https://www.apache.org/licenses/LICENSE-2.0
12//
13// Unless required by applicable law or agreed to in writing, software
14// distributed under the License is distributed on an "AS IS" BASIS,
15// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16// See the License for the specific language governing permissions and
17// limitations under the License.
18//
19
20//! A purpose-built, self-describing value tree for decoded Postgres rows.
21//!
22//! Not `serde_json::Value` (would blur int64 vs float64 vs decimal vs uuid —
23//! real distinctions PyQL's own type system preserves) and not raw
24//! serialization-of-arbitrary-PyObject (Rust has no way to serialize an
25//! arbitrary *registered* Python dataclass — those only exist Python-side).
26//! Instead, this sits at the same layer `pylon.query.deserialize()`'s
27//! `_decode()` consumes today: already decoded from Postgres wire format
28//! (never raw bytes), but still generic/positional, not yet hydrated into a
29//! user class.
30//!
31//! This is the shared decode target for both `pylon-cache` (stores it,
32//! serialized via `rkyv`) and `pylon-pgcon` (the Postgres driver — decodes
33//! wire bytes straight into this same representation) — the whole point
34//! being one decode path regardless of whether a result came fresh from
35//! Postgres or from the LMDB cache. Deliberately has no dependency on
36//! `pylon-core`, pyo3, or any I/O crate: it's just the value shape.
37//!
38//! Serialized with `rkyv` (zero-copy) rather than `bincode` — `bincode` is
39//! effectively unmaintained upstream (its 3.0.0 release is a deliberate
40//! `compile_error!` protest, forcing anyone pinned loosely onto the
41//! archived 2.x line).
42
43use rkyv::{Archive, Deserialize, Serialize};
44
45#[derive(Debug, Clone, PartialEq, Archive, Serialize, Deserialize)]
46#[rkyv(
47    compare(PartialEq),
48    derive(Debug),
49    serialize_bounds(__S: rkyv::ser::Writer + rkyv::ser::Allocator),
50    deserialize_bounds(__D::Error: rkyv::rancor::Source),
51    // Needed for the same reason as `omit_bounds` below, but on the
52    // validation side: when a *consumer* turns on rkyv's `bytecheck` feature
53    // (this crate does not), the derive also emits a `Verify` impl, and the
54    // recursive fields leave it without the context bound. Only parsed when
55    // that feature is on, so it costs nothing when it is off.
56    bytecheck(bounds(__C: rkyv::validation::ArchiveContext)),
57)]
58pub enum DecodedValue {
59    Null,
60    Bool(bool),
61    I64(i64),
62    F64(f64),
63    Str(String),
64    Bytes(Vec<u8>),
65    /// Raw 16-byte UUID, matching `QueryParam::Uuid`'s own convention in
66    /// `pylon-core`. Stored as raw bytes rather than a `uuid::Uuid` field
67    /// (every consuming crate already re-wraps this in its own richer type
68    /// on the way out — e.g. `pylon-client`'s `Value::Uuid(uuid::Uuid)` —
69    /// so there's no benefit to carrying that type this deep); `uuid` is
70    /// still a dependency of this crate, purely so `From<uuid::Uuid>` below
71    /// can convert into this variant without every caller writing
72    /// `.into_bytes()` by hand.
73    Uuid([u8; 16]),
74    /// Arbitrary-precision decimal, stored as its canonical string form
75    /// (matches how `_pg_decode_numeric` round-trips today) rather than a
76    /// lossy f64 or a bespoke bignum encoding.
77    Decimal(String),
78    /// A PostgreSQL `interval` — backs both Pylon's `std::duration` (months
79    /// always 0 by convention) and `cal::relative_duration` (months may be
80    /// nonzero). Kept as the three raw wire components rather than folded
81    /// into a single duration, since `months` (a calendar-relative unit —
82    /// "1 month" isn't a fixed number of days) can't be losslessly combined
83    /// with `days`/`microseconds` without a reference date.
84    Interval {
85        months: i32,
86        days: i32,
87        microseconds: i64,
88    },
89    /// PostgreSQL `date` — whole days since the PG epoch (2000-01-01),
90    /// exactly as the wire encodes it. Backs `cal::local_date`.
91    Date(i32),
92    /// PostgreSQL `time` (no timezone) — microseconds since midnight,
93    /// exactly as the wire encodes it. Backs `cal::local_time`.
94    Time(i64),
95    /// PostgreSQL `timestamp` (no timezone) — microseconds since the PG
96    /// epoch (2000-01-01T00:00:00), exactly as the wire encodes it. Backs
97    /// `cal::local_datetime`; decodes to a naive `datetime.datetime`.
98    Timestamp(i64),
99    /// PostgreSQL `timestamptz` — microseconds since the PG epoch
100    /// (2000-01-01T00:00:00 UTC; PostgreSQL always normalizes `timestamptz`
101    /// to UTC on the wire, regardless of session timezone), exactly as the
102    /// wire encodes it. Backs `std::datetime`; decodes to a UTC-aware
103    /// `datetime.datetime`. A distinct variant from `Timestamp` (not a
104    /// shared representation with a tag) so decode/encode can't mix up
105    /// naive vs. aware at the type level.
106    Timestamptz(i64),
107    // `omit_bounds` is required on self-referential fields: rkyv's derive
108    // otherwise adds a naive `FieldType: Archive` bound per field, which
109    // for a directly-recursive type like this overflows trait resolution
110    // (`DecodedValue: Archive` requires `Vec<DecodedValue>: Archive` requires
111    // `DecodedValue: Archive`, forever) — see rkyv's own docs on recursive
112    // types.
113    /// A genuine Postgres array (`text[]`, `int8[]`, ...) — reconstructed
114    /// Python-side as a `list`, matching what has always decoded a
115    /// Postgres array into. Do not use this for a composite/record's
116    /// positional fields; see `Composite`.
117    Array(#[rkyv(omit_bounds)] Vec<DecodedValue>),
118    /// A positional composite (`record` — a schema object's own field
119    /// tuple, or a nested `ROW(...)`), reconstructed Python-side as a
120    /// `tuple`, matching a record row's own behavior — critically,
121    /// `isinstance(a_tuple, (dict, list))` is `False`, the same as a real
122    /// a record row, which `pylon.query._decode()`'s `"named_tuple"`
123    /// case relies on to tell "this position holds a raw jsonb value"
124    /// apart from "this position holds a composite that needs `value[pos]`
125    /// indexing first." Using `Array` (→ `list`) here instead silently
126    /// breaks that check — a real bug caught by comparing decoded output
127    /// against the live driver path on real queries.
128    Composite(#[rkyv(omit_bounds)] Vec<DecodedValue>),
129    /// Field name + value pairs, in shape order (not a map — field order is
130    /// part of what `ShapeNode` positions describe, and duplicate names
131    /// can't happen for a single object's own pointers).
132    Object(#[rkyv(omit_bounds)] Vec<(String, DecodedValue)>),
133    /// A PostgreSQL range value (`int8range`, `numrange`, `tsrange`,
134    /// `tstzrange`, `daterange`, ...). `lower`/`upper` are `None` for an
135    /// unbounded side; `empty == true` means the whole range is empty
136    /// (`lower`/`upper` are meaningless in that case, not "both unbounded" —
137    /// PostgreSQL's own binary encoding distinguishes the two). A
138    /// `multirange<T>` decodes to a plain `Array` of these, not a separate
139    /// variant — it's just an ordered collection of ranges.
140    Range {
141        #[rkyv(omit_bounds)]
142        lower: Option<Box<DecodedValue>>,
143        #[rkyv(omit_bounds)]
144        upper: Option<Box<DecodedValue>>,
145        inc_lower: bool,
146        inc_upper: bool,
147        empty: bool,
148    },
149}
150
151// ── Native-type conversions ──────────────────────────────────────────────────
152//
153// Lets a caller write `"id".into()`/`some_uuid.into()` instead of spelling
154// out `DecodedValue::Uuid(...)` at every query-parameter call site — mirrors
155// `gel_protocol::value::Value`'s own `From<T>` impls (verified against
156// `gel-protocol` 0.9.2's `value.rs`), which exist for exactly this reason:
157// the wrapper enum itself isn't going away (a query parameter/result still
158// has to carry its own runtime type tag), but constructing one shouldn't
159// require spelling out the variant name by hand for the common cases.
160//
161// `i16`/`i32` and `f32` widen into this crate's single `I64`/`F64` variants
162// rather than getting their own — `DecodedValue` has never distinguished
163// integer/float width the way Postgres's own wire protocol does
164// (every integer column decodes to `I64`, every float column to `F64`
165// already, regardless of the underlying `int2`/`int4`/`int8` or
166// `float4`/`float8` column type), so these conversions just meet that
167// existing convention rather than introduce a new one.
168
169impl From<String> for DecodedValue {
170    fn from(value: String) -> Self {
171        DecodedValue::Str(value)
172    }
173}
174
175impl From<&str> for DecodedValue {
176    fn from(value: &str) -> Self {
177        DecodedValue::Str(value.to_string())
178    }
179}
180
181impl From<bool> for DecodedValue {
182    fn from(value: bool) -> Self {
183        DecodedValue::Bool(value)
184    }
185}
186
187impl From<i16> for DecodedValue {
188    fn from(value: i16) -> Self {
189        DecodedValue::I64(value.into())
190    }
191}
192
193impl From<i32> for DecodedValue {
194    fn from(value: i32) -> Self {
195        DecodedValue::I64(value.into())
196    }
197}
198
199impl From<i64> for DecodedValue {
200    fn from(value: i64) -> Self {
201        DecodedValue::I64(value)
202    }
203}
204
205impl From<f32> for DecodedValue {
206    fn from(value: f32) -> Self {
207        DecodedValue::F64(value.into())
208    }
209}
210
211impl From<f64> for DecodedValue {
212    fn from(value: f64) -> Self {
213        DecodedValue::F64(value)
214    }
215}
216
217impl From<Vec<u8>> for DecodedValue {
218    fn from(value: Vec<u8>) -> Self {
219        DecodedValue::Bytes(value)
220    }
221}
222
223impl From<uuid::Uuid> for DecodedValue {
224    fn from(value: uuid::Uuid) -> Self {
225        DecodedValue::Uuid(value.into_bytes())
226    }
227}
228
229/// One cache entry: the cached rows plus the tags a write to any of which
230/// must invalidate it — stored together so invalidation never needs a
231/// second lookup to find out what a key was tagged with.
232#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
233#[rkyv(derive(Debug))]
234pub struct CachedEntry {
235    pub rows: Vec<DecodedValue>,
236    pub tags: Vec<String>,
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use rkyv::rancor::Error;
243
244    #[test]
245    fn round_trips_every_variant() {
246        let value = DecodedValue::Object(vec![
247            ("id".into(), DecodedValue::Uuid([1; 16])),
248            ("name".into(), DecodedValue::Str("Alice".into())),
249            ("age".into(), DecodedValue::I64(30)),
250            ("score".into(), DecodedValue::F64(1.5)),
251            ("active".into(), DecodedValue::Bool(true)),
252            ("balance".into(), DecodedValue::Decimal("12.50".into())),
253            (
254                "tags".into(),
255                DecodedValue::Array(vec![DecodedValue::Str("a".into()), DecodedValue::Null]),
256            ),
257            ("avatar".into(), DecodedValue::Bytes(vec![1, 2, 3])),
258            (
259                "point".into(),
260                DecodedValue::Composite(vec![DecodedValue::F64(1.0), DecodedValue::F64(2.0)]),
261            ),
262            (
263                "span".into(),
264                DecodedValue::Interval {
265                    months: 1,
266                    days: 2,
267                    microseconds: 3_600_000_000,
268                },
269            ),
270            ("day".into(), DecodedValue::Date(9525)),
271            ("clock".into(), DecodedValue::Time(3_600_000_000)),
272            ("naive_ts".into(), DecodedValue::Timestamp(1_000_000_000)),
273            ("aware_ts".into(), DecodedValue::Timestamptz(1_000_000_000)),
274            (
275                "span_range".into(),
276                DecodedValue::Range {
277                    lower: Some(Box::new(DecodedValue::I64(1))),
278                    upper: Some(Box::new(DecodedValue::I64(10))),
279                    inc_lower: true,
280                    inc_upper: false,
281                    empty: false,
282                },
283            ),
284        ]);
285        let bytes = rkyv::to_bytes::<Error>(&value).unwrap();
286        // SAFETY: bytes were produced moments ago by `to_bytes` on this same
287        // type, in this same process — not untrusted external input, so the
288        // `bytecheck`-validated safe `access` API (which this crate opts out
289        // of entirely; see the `default-features = false` note in Cargo.toml)
290        // isn't needed here.
291        let archived = unsafe { rkyv::access_unchecked::<ArchivedDecodedValue>(&bytes) };
292        let decoded: DecodedValue = rkyv::deserialize::<DecodedValue, Error>(archived).unwrap();
293        assert_eq!(decoded, value);
294    }
295
296    #[test]
297    fn round_trips_cached_entry() {
298        let entry = CachedEntry {
299            rows: vec![DecodedValue::I64(1), DecodedValue::I64(2)],
300            tags: vec!["public.person".into()],
301        };
302        let bytes = rkyv::to_bytes::<Error>(&entry).unwrap();
303        // SAFETY: see the comment in `round_trips_every_variant` above.
304        let archived = unsafe { rkyv::access_unchecked::<ArchivedCachedEntry>(&bytes) };
305        let decoded: CachedEntry = rkyv::deserialize::<CachedEntry, Error>(archived).unwrap();
306        assert_eq!(decoded.rows, entry.rows);
307        assert_eq!(decoded.tags, entry.tags);
308    }
309
310    #[test]
311    fn from_native_string_types() {
312        assert_eq!(
313            DecodedValue::from("hello".to_string()),
314            DecodedValue::Str("hello".into())
315        );
316        assert_eq!(DecodedValue::from("hello"), DecodedValue::Str("hello".into()));
317    }
318
319    #[test]
320    fn from_native_bool() {
321        assert_eq!(DecodedValue::from(true), DecodedValue::Bool(true));
322    }
323
324    #[test]
325    fn from_native_integers_widen_into_i64() {
326        assert_eq!(DecodedValue::from(1i16), DecodedValue::I64(1));
327        assert_eq!(DecodedValue::from(2i32), DecodedValue::I64(2));
328        assert_eq!(DecodedValue::from(3i64), DecodedValue::I64(3));
329    }
330
331    #[test]
332    fn from_native_floats_widen_into_f64() {
333        assert_eq!(DecodedValue::from(1.5f32), DecodedValue::F64(1.5));
334        assert_eq!(DecodedValue::from(2.5f64), DecodedValue::F64(2.5));
335    }
336
337    #[test]
338    fn from_native_bytes() {
339        assert_eq!(DecodedValue::from(vec![1u8, 2, 3]), DecodedValue::Bytes(vec![1, 2, 3]));
340    }
341
342    #[test]
343    fn from_native_uuid() {
344        let u = uuid::Uuid::from_bytes([7; 16]);
345        assert_eq!(DecodedValue::from(u), DecodedValue::Uuid([7; 16]));
346    }
347
348    #[test]
349    fn into_conversion_works_at_a_query_param_style_call_site() {
350        // The motivating case: `&[(&str, DecodedValue)]`-shaped params
351        // accepting `.into()` instead of the explicit variant.
352        let params: Vec<(&str, DecodedValue)> =
353            vec![("name", "Ada".into()), ("age", 30i64.into()), ("active", true.into())];
354        assert_eq!(params[0].1, DecodedValue::Str("Ada".into()));
355        assert_eq!(params[1].1, DecodedValue::I64(30));
356        assert_eq!(params[2].1, DecodedValue::Bool(true));
357    }
358}