| 1 | //! Binary jsonb boundary — direct access to PostgreSQL's jsonb C API, with no |
| 2 | //! `serde_json` round-trip. |
| 3 | //! |
| 4 | //! pgrx's stock [`pgrx::JsonB`] crosses the boundary as *text*: on input it calls |
| 5 | //! `jsonb_out` + `serde_json::from_str`, on output `serde_json::to_string` + |
| 6 | //! `jsonb_in` — two full text round-trips per call (see |
| 7 | //! `pgrx-0.18.1/src/datum/json.rs`). For `feel_eval` that boundary, not FEEL |
| 8 | //! evaluation, dominates the per-call cost (RD-11). This module replaces it with |
| 9 | //! the binary container API: |
| 10 | //! |
| 11 | //! * [`PgJsonb`] — the boundary newtype over `*mut pg_sys::Jsonb`. `FromDatum` |
| 12 | //! merely detoasts (no `jsonb_out`); `IntoDatum` is `JsonbPGetDatum`. The |
| 13 | //! `ArgAbi`/`BoxRet` impls mirror pgrx's own `JsonB` (the `argue_from_datum!` / |
| 14 | //! `impl_repackage_into_datum!` macro bodies) so it drops into `#[pg_extern]`. |
| 15 | //! * [`value_to_jsonb`] — builds the result jsonb straight from a [`Value`] with |
| 16 | //! `pushJsonbValue` + `JsonbValueToJsonb` (approach **C**). |
| 17 | //! * [`context_from_jsonb`] — walks the context jsonb into a [`Context`], either |
| 18 | //! **eagerly** (approach **B**) or **lazily** via [`JsonbForeign`] (approach |
| 19 | //! **A**, ADR-21): nested containers become `Value::Foreign` resolved only when |
| 20 | //! the FEEL dot navigates into them. |
| 21 | //! |
| 22 | //! ## Safety |
| 23 | //! |
| 24 | //! Every `pg_sys` jsonb function used here lives in pgrx's |
| 25 | //! `#[pg_guard] extern "C-unwind"` block: a Postgres `ereport`/`longjmp` (e.g. a |
| 26 | //! jsonb size-limit error from `JsonbValueToJsonb`) is caught at the FFI boundary |
| 27 | //! and re-raised as a Rust panic that unwinds *normally* — Rust destructors run, |
| 28 | //! no stack is corrupted, and the panic surfaces to the client as the original |
| 29 | //! Postgres ERROR. So no manual `PgTryBuilder` is needed for stack safety; we let |
| 30 | //! a genuine encoding error propagate as a real ERROR rather than masking it as a |
| 31 | //! null (RD-11). The read path (detoast, iterate, key lookup) does not `ereport` |
| 32 | //! for valid in-memory jsonb. `AnyNumeric`'s f64↔numeric conversions are themselves |
| 33 | //! guarded internally by pgrx. |
| 34 | //! |
| 35 | //! The lazy [`JsonbForeign`] holds a `*mut JsonbContainer` borrowed from the |
| 36 | //! detoasted argument; that pointer is valid **only for the duration of the call**. |
| 37 | //! The invariant (upheld by the callers in `lib.rs`) is that a `JsonbForeign` never |
| 38 | //! escapes the evaluation: it is created from the live argument, used during |
| 39 | //! `evaluate_with_env`, forced to owned jsonb on output, and dropped before return. |
| 40 | |
| 41 | use std::any::Any; |
| 42 | use std::ffi::{c_char, c_int}; |
| 43 | use std::ptr; |
| 44 | use std::sync::Arc; |
| 45 | |
| 46 | use pgrx::callconv::{Arg, ArgAbi, BoxRet, FcInfo}; |
| 47 | use pgrx::datum::Datum as FcxDatum; |
| 48 | use pgrx::nullable::Nullable; |
| 49 | use pgrx::pg_sys; |
| 50 | use pgrx::pgrx_sql_entity_graph::metadata::{ |
| 51 | ArgumentError, ReturnsError, ReturnsRef, SqlMappingRef, SqlTranslatable, TypeOrigin, |
| 52 | }; |
| 53 | use pgrx::{AnyNumeric, FromDatum, IntoDatum}; |
| 54 | |
| 55 | use feel_core::foreign::{Foreign, ForeignObject}; |
| 56 | use feel_core::{Context, Value}; |
| 57 | |
| 58 | /// The binary jsonb boundary type: a pointer to a (detoasted) `Jsonb` varlena. |
| 59 | /// |
| 60 | /// Used as both the `context` argument and the return type of the SQL functions |
| 61 | /// in place of pgrx's [`pgrx::JsonB`], avoiding its text round-trip. On the |
| 62 | /// argument side the pointer aliases the call's argument memory (valid for the |
| 63 | /// call); on the return side it points at freshly built jsonb in the current |
| 64 | /// memory context. |
| 65 | pub struct PgJsonb(pub *mut pg_sys::Jsonb); |
| 66 | |
| 67 | impl FromDatum for PgJsonb { |
| 68 | #[inline] |
| 69 | unsafe fn from_polymorphic_datum( |
| 70 | datum: pg_sys::Datum, |
| 71 | is_null: bool, |
| 72 | _typoid: pg_sys::Oid, |
| 73 | ) -> Option<PgJsonb> { |
| 74 | if is_null { |
| 75 | None |
| 76 | } else { |
| 77 | // `DatumGetJsonbP` fully detoasts (4-byte varlena header), which the |
| 78 | // binary container API requires; no `jsonb_out`/`serde` involved. |
| 79 | let jsonb = pg_sys::DatumGetJsonbP(datum); |
| 80 | Some(PgJsonb(jsonb)) |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl IntoDatum for PgJsonb { |
| 86 | #[inline] |
| 87 | fn into_datum(self) -> Option<pg_sys::Datum> { |
| 88 | if self.0.is_null() { |
| 89 | None |
| 90 | } else { |
| 91 | Some(unsafe { pg_sys::JsonbPGetDatum(self.0) }) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | #[inline] |
| 96 | fn type_oid() -> pg_sys::Oid { |
| 97 | pg_sys::JSONBOID |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // Mirror of pgrx's `argue_from_datum!` macro body for `JsonB` (callconv.rs): unbox |
| 102 | // the argument straight through `FromDatum` (which here is just a detoast). |
| 103 | unsafe impl<'fcx> ArgAbi<'fcx> for PgJsonb { |
| 104 | unsafe fn unbox_arg_unchecked(arg: Arg<'_, 'fcx>) -> Self { |
| 105 | let index = arg.index(); |
| 106 | unsafe { |
| 107 | arg.unbox_arg_using_from_datum() |
| 108 | .unwrap_or_else(|| panic!("argument {index} must not be null")) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | unsafe fn unbox_nullable_arg(arg: Arg<'_, 'fcx>) -> Nullable<Self> { |
| 113 | unsafe { arg.unbox_arg_using_from_datum().into() } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // Mirror of pgrx's `impl_repackage_into_datum!` macro body for `JsonB`. |
| 118 | unsafe impl BoxRet for PgJsonb { |
| 119 | unsafe fn box_into<'fcx>(self, fcinfo: &mut FcInfo<'fcx>) -> FcxDatum<'fcx> { |
| 120 | match self.into_datum() { |
| 121 | Some(datum) => unsafe { fcinfo.return_raw_datum(datum) }, |
| 122 | None => fcinfo.return_null(), |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // Copied verbatim from pgrx's `SqlTranslatable for JsonB`, with the `jsonb` |
| 128 | // literal mapping — so `#[pg_extern]` emits a `jsonb` argument/return in SQL. |
| 129 | unsafe impl SqlTranslatable for PgJsonb { |
| 130 | const TYPE_IDENT: &'static str = pgrx::pgrx_resolved_type!(PgJsonb); |
| 131 | const TYPE_ORIGIN: TypeOrigin = TypeOrigin::External; |
| 132 | const ARGUMENT_SQL: Result<SqlMappingRef, ArgumentError> = Ok(SqlMappingRef::literal("jsonb")); |
| 133 | const RETURN_SQL: Result<ReturnsRef, ReturnsError> = |
| 134 | Ok(ReturnsRef::One(SqlMappingRef::literal("jsonb"))); |
| 135 | } |
| 136 | |
| 137 | // --------------------------------------------------------------------------- |
| 138 | // Output (approach C): Value -> jsonb, built directly with the binary API. |
| 139 | // --------------------------------------------------------------------------- |
| 140 | |
| 141 | /// Map a `feel-core` [`Value`] to a binary `jsonb` value, reproducing exactly the |
| 142 | /// mapping the old `serde` path used (`value_to_json`/`number_to_json`): |
| 143 | /// |
| 144 | /// * integral finite numbers (`|n| < 2^53`) → a numeric from `i64`, else from |
| 145 | /// `f64`; non-finite (`NaN`/`±Inf`) → jsonb `null`; |
| 146 | /// * `List` → array, `Context` (key-ordered) → object, recursing; |
| 147 | /// * temporals → canonical ISO-8601 string (ADR-18); |
| 148 | /// * `Null`/`Error`/`Function` → jsonb `null` (the lenient boundary; strict mode is |
| 149 | /// checked on the `Value` upstream, ADR-14); |
| 150 | /// * `Foreign` (only reachable via the lazy input path A) is **forced** recursively |
| 151 | /// to jsonb — never nulled. |
| 152 | pub fn value_to_jsonb(value: &Value) -> *mut pg_sys::Jsonb { |
| 153 | // Owns every string and object key we emit, so their bytes stay alive until |
| 154 | // `JsonbValueToJsonb` copies them at the end. This is load-bearing for the lazy |
| 155 | // input path (A): a `Foreign` forced mid-stream yields a *temporary* sub-`Value` |
| 156 | // that is dropped before the final encode, so we must copy out of it eagerly |
| 157 | // rather than point at it. (Growing the Vec never moves a `String`'s heap |
| 158 | // buffer, so the raw pointers we hand to Postgres stay valid; numerics are |
| 159 | // palloc'd, booleans/null are inline — all outlive the temporary too.) |
| 160 | let mut arena: Vec<String> = Vec::new(); |
| 161 | unsafe { build_root(value, &mut arena) } |
| 162 | } |
| 163 | |
| 164 | unsafe fn build_root(value: &Value, arena: &mut Vec<String>) -> *mut pg_sys::Jsonb { |
| 165 | match value { |
| 166 | Value::List(_) | Value::Context(_) => { |
| 167 | let mut state: *mut pg_sys::JsonbParseState = ptr::null_mut(); |
| 168 | // The scalar token is unused for a container root. |
| 169 | let root = add_value( |
| 170 | &mut state, |
| 171 | pg_sys::JsonbIteratorToken::WJB_ELEM, |
| 172 | value, |
| 173 | arena, |
| 174 | ); |
| 175 | pg_sys::JsonbValueToJsonb(root) |
| 176 | } |
| 177 | Value::Foreign(f) => { |
| 178 | let forced = f.0.force(); |
| 179 | build_root(&forced, arena) |
| 180 | } |
| 181 | // A scalar root: `JsonbValueToJsonb` wraps a bare scalar itself. |
| 182 | _ => { |
| 183 | let mut jbv = scalar_jbv(value, arena); |
| 184 | pg_sys::JsonbValueToJsonb(&mut jbv) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Push `value` into the jsonb parse state. `scalar_token` (`WJB_VALUE`/`WJB_ELEM`) |
| 190 | /// is used only for scalar leaves; nested containers carry their own |
| 191 | /// `WJB_BEGIN_*`/`WJB_END_*` tokens, which Postgres resolves against the current |
| 192 | /// parse-state nesting. Returns the `JsonbValue` produced by the last push (used |
| 193 | /// only for the root). |
| 194 | unsafe fn add_value( |
| 195 | state: *mut *mut pg_sys::JsonbParseState, |
| 196 | scalar_token: pg_sys::JsonbIteratorToken::Type, |
| 197 | value: &Value, |
| 198 | arena: &mut Vec<String>, |
| 199 | ) -> *mut pg_sys::JsonbValue { |
| 200 | use pg_sys::JsonbIteratorToken::*; |
| 201 | match value { |
| 202 | Value::List(items) => { |
| 203 | pg_sys::pushJsonbValue(state, WJB_BEGIN_ARRAY, ptr::null_mut()); |
| 204 | for item in items { |
| 205 | add_value(state, WJB_ELEM, item, arena); |
| 206 | } |
| 207 | pg_sys::pushJsonbValue(state, WJB_END_ARRAY, ptr::null_mut()) |
| 208 | } |
| 209 | Value::Context(map) => { |
| 210 | pg_sys::pushJsonbValue(state, WJB_BEGIN_OBJECT, ptr::null_mut()); |
| 211 | for (key, val) in map { |
| 212 | let mut key_jbv = pg_sys::JsonbValue::default(); |
| 213 | set_string(&mut key_jbv, arena, key); |
| 214 | pg_sys::pushJsonbValue(state, WJB_KEY, &mut key_jbv); |
| 215 | add_value(state, WJB_VALUE, val, arena); |
| 216 | } |
| 217 | pg_sys::pushJsonbValue(state, WJB_END_OBJECT, ptr::null_mut()) |
| 218 | } |
| 219 | Value::Foreign(f) => { |
| 220 | let forced = f.0.force(); |
| 221 | add_value(state, scalar_token, &forced, arena) |
| 222 | } |
| 223 | _ => { |
| 224 | let mut jbv = scalar_jbv(value, arena); |
| 225 | pg_sys::pushJsonbValue(state, scalar_token, &mut jbv) |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// Build a scalar `JsonbValue` for a non-container `Value`. String bytes point into |
| 231 | /// the borrowed `Value` (for `String`) or into `arena` (for the ISO-8601 rendering |
| 232 | /// of a temporal), both of which outlive the enclosing `value_to_jsonb` call. |
| 233 | unsafe fn scalar_jbv(value: &Value, arena: &mut Vec<String>) -> pg_sys::JsonbValue { |
| 234 | let mut jbv = pg_sys::JsonbValue::default(); |
| 235 | match value { |
| 236 | Value::Boolean(b) => { |
| 237 | jbv.type_ = pg_sys::jbvType::jbvBool; |
| 238 | jbv.val.boolean = *b; |
| 239 | } |
| 240 | Value::Number(n) => set_number(&mut jbv, *n), |
| 241 | Value::String(s) => set_string(&mut jbv, arena, s), |
| 242 | Value::Date(_) |
| 243 | | Value::Time(_) |
| 244 | | Value::DateTime(_) |
| 245 | | Value::YearsMonthsDuration(_) |
| 246 | | Value::DaysTimeDuration(_) => match feel_core::temporal::to_iso(value) { |
| 247 | Some(iso) => set_string(&mut jbv, arena, &iso), |
| 248 | None => jbv.type_ = pg_sys::jbvType::jbvNull, |
| 249 | }, |
| 250 | // Null / Error / Function (and, defensively, containers) -> jsonb null. |
| 251 | _ => jbv.type_ = pg_sys::jbvType::jbvNull, |
| 252 | } |
| 253 | jbv |
| 254 | } |
| 255 | |
| 256 | /// Make `jbv` a `jbvString` over a copy of `s` owned by `arena`, so its bytes |
| 257 | /// outlive the eventual `JsonbValueToJsonb` even when `s` itself is borrowed from a |
| 258 | /// temporary (a forced `Foreign`). jsonb strings are length-counted, not |
| 259 | /// null-terminated. |
| 260 | unsafe fn set_string(jbv: &mut pg_sys::JsonbValue, arena: &mut Vec<String>, s: &str) { |
| 261 | arena.push(s.to_owned()); |
| 262 | let bytes = arena.last().unwrap().as_bytes(); |
| 263 | jbv.type_ = pg_sys::jbvType::jbvString; |
| 264 | jbv.val.string.len = bytes.len() as c_int; |
| 265 | jbv.val.string.val = bytes.as_ptr() as *mut c_char; |
| 266 | } |
| 267 | |
| 268 | /// Encode a FEEL number as a jsonb numeric, matching the old `number_to_json`: |
| 269 | /// integral and within `2^53` → from `i64` (so `1 + 1` is `2`, not `2.0`); else |
| 270 | /// from `f64`; `NaN`/`±Inf` → jsonb `null`. |
| 271 | unsafe fn set_number(jbv: &mut pg_sys::JsonbValue, n: f64) { |
| 272 | if !n.is_finite() { |
| 273 | jbv.type_ = pg_sys::jbvType::jbvNull; |
| 274 | return; |
| 275 | } |
| 276 | let numeric = if n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 { |
| 277 | AnyNumeric::from(n as i64) |
| 278 | } else { |
| 279 | match AnyNumeric::try_from(n) { |
| 280 | Ok(v) => v, |
| 281 | Err(_) => { |
| 282 | jbv.type_ = pg_sys::jbvType::jbvNull; |
| 283 | return; |
| 284 | } |
| 285 | } |
| 286 | }; |
| 287 | // `into_datum` palloc's the numeric into the current memory context, where it |
| 288 | // stays valid until `JsonbValueToJsonb`; the `AnyNumeric` is then dropped. |
| 289 | match numeric.into_datum() { |
| 290 | Some(d) => { |
| 291 | jbv.type_ = pg_sys::jbvType::jbvNumeric; |
| 292 | jbv.val.numeric = d.cast_mut_ptr::<pg_sys::NumericData>(); |
| 293 | } |
| 294 | None => jbv.type_ = pg_sys::jbvType::jbvNull, |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // --------------------------------------------------------------------------- |
| 299 | // Input (approaches B and A): jsonb -> Context. |
| 300 | // --------------------------------------------------------------------------- |
| 301 | |
| 302 | /// Build a [`Context`] from the context jsonb argument, **lazily** (approach A, |
| 303 | /// ADR-21 — the M4 benchmark's winner, RD-11): the top-level members are |
| 304 | /// materialised into the `Context` (where the evaluator looks up variables), but a |
| 305 | /// nested container becomes a [`Value::Foreign`] resolved only when the FEEL dot |
| 306 | /// navigates into it. A context whose deep structure is never touched is never |
| 307 | /// walked — the per-call win grows with context size and path selectivity. |
| 308 | /// |
| 309 | /// Mirrors the old serde `context_from_json`: a jsonb object → context; a jsonb |
| 310 | /// `null` → empty context; any other shape → `Err`. |
| 311 | /// |
| 312 | /// # Safety |
| 313 | /// `jsonb` must be a valid, fully detoasted `Jsonb` pointer that outlives the |
| 314 | /// returned `Context` and every `Foreign` derived from it (see the module note). |
| 315 | pub unsafe fn context_from_jsonb(jsonb: *mut pg_sys::Jsonb) -> Result<Context, String> { |
| 316 | let container = ptr::addr_of_mut!((*jsonb).root); |
| 317 | if (*container).header & pg_sys::JB_FOBJECT == 0 { |
| 318 | // Not an object: accept only a JSON null (-> empty context), like serde. |
| 319 | return match container_to_value(container) { |
| 320 | Value::Null => Ok(Context::new()), |
| 321 | _ => Err("expected a JSON object as the FEEL context".to_owned()), |
| 322 | }; |
| 323 | } |
| 324 | |
| 325 | let mut ctx = Context::new(); |
| 326 | let mut it = pg_sys::JsonbIteratorInit(container); |
| 327 | let mut v = pg_sys::JsonbValue::default(); |
| 328 | // WJB_BEGIN_OBJECT |
| 329 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 330 | loop { |
| 331 | let tok = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 332 | if tok == pg_sys::JsonbIteratorToken::WJB_END_OBJECT { |
| 333 | break; |
| 334 | } |
| 335 | // tok == WJB_KEY |
| 336 | let key = jbv_string(&v); |
| 337 | // WJB_VALUE (with skipNested, a nested container arrives as jbvBinary) |
| 338 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 339 | let val = jbv_to_value(&v); |
| 340 | ctx.insert(key, val); |
| 341 | } |
| 342 | Ok(ctx) |
| 343 | } |
| 344 | |
| 345 | /// Convert one `JsonbValue` to a *shallow* `feel-core` [`Value`]: scalars eagerly, a |
| 346 | /// nested container (`jbvBinary`) to a lazy [`Value::Foreign`] ([`JsonbForeign`]). |
| 347 | unsafe fn jbv_to_value(jbv: &pg_sys::JsonbValue) -> Value { |
| 348 | match jbv.type_ { |
| 349 | pg_sys::jbvType::jbvNull => Value::Null, |
| 350 | pg_sys::jbvType::jbvBool => Value::Boolean(jbv.val.boolean), |
| 351 | pg_sys::jbvType::jbvString => Value::String(jbv_string(jbv)), |
| 352 | pg_sys::jbvType::jbvNumeric => numeric_to_value(jbv.val.numeric), |
| 353 | pg_sys::jbvType::jbvBinary => { |
| 354 | // `JsonbForeign` is intentionally `!Send`/`!Sync` (it holds a raw |
| 355 | // container pointer valid only for this call), which is exactly ADR-21's |
| 356 | // model: a `Value` carrying a `Foreign` is `!Send`. The `Arc` is mandated |
| 357 | // by feel-core's `Foreign(Arc<dyn ForeignObject>)` and never crosses |
| 358 | // threads (evaluation is single-threaded per call). |
| 359 | #[allow(clippy::arc_with_non_send_sync)] |
| 360 | Value::Foreign(Foreign(Arc::new(JsonbForeign { |
| 361 | container: jbv.val.binary.data, |
| 362 | }))) |
| 363 | } |
| 364 | _ => Value::Null, |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// Walk a jsonb container **one level** into a `Value` (an object → `Context`, an |
| 369 | /// array → `List`, a raw-scalar pseudo-array → its scalar). Members are shallow |
| 370 | /// (nested containers stay lazy [`Value::Foreign`]s via [`jbv_to_value`]), so this |
| 371 | /// is both the top-level force of a [`JsonbForeign`] and the incremental step that |
| 372 | /// keeps laziness going. |
| 373 | unsafe fn container_to_value(container: *mut pg_sys::JsonbContainer) -> Value { |
| 374 | use pg_sys::JsonbIteratorToken::*; |
| 375 | let mut it = pg_sys::JsonbIteratorInit(container); |
| 376 | let mut v = pg_sys::JsonbValue::default(); |
| 377 | match pg_sys::JsonbIteratorNext(&mut it, &mut v, true) { |
| 378 | WJB_BEGIN_OBJECT => { |
| 379 | let mut map = std::collections::BTreeMap::new(); |
| 380 | loop { |
| 381 | let tok = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 382 | if tok == WJB_END_OBJECT { |
| 383 | break; |
| 384 | } |
| 385 | let key = jbv_string(&v); |
| 386 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 387 | map.insert(key, jbv_to_value(&v)); |
| 388 | } |
| 389 | Value::Context(map) |
| 390 | } |
| 391 | WJB_BEGIN_ARRAY => { |
| 392 | // A jsonb scalar is stored as a single-element raw-scalar array. |
| 393 | if v.val.array.rawScalar { |
| 394 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); // WJB_ELEM |
| 395 | let scalar = jbv_to_value(&v); |
| 396 | let _ = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); // WJB_END_ARRAY |
| 397 | scalar |
| 398 | } else { |
| 399 | let mut items = Vec::new(); |
| 400 | loop { |
| 401 | let tok = pg_sys::JsonbIteratorNext(&mut it, &mut v, true); |
| 402 | if tok == WJB_END_ARRAY { |
| 403 | break; |
| 404 | } |
| 405 | items.push(jbv_to_value(&v)); |
| 406 | } |
| 407 | Value::List(items) |
| 408 | } |
| 409 | } |
| 410 | _ => Value::Null, |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /// Copy a `jbvString`'s bytes into an owned `String` (lossy on invalid UTF-8, which |
| 415 | /// well-formed jsonb never contains). |
| 416 | unsafe fn jbv_string(jbv: &pg_sys::JsonbValue) -> String { |
| 417 | let s = jbv.val.string; |
| 418 | if s.val.is_null() || s.len <= 0 { |
| 419 | return String::new(); |
| 420 | } |
| 421 | let bytes = std::slice::from_raw_parts(s.val as *const u8, s.len as usize); |
| 422 | String::from_utf8_lossy(bytes).into_owned() |
| 423 | } |
| 424 | |
| 425 | /// Decode a jsonb numeric (a `*mut NumericData`) to a FEEL number. Out-of-`f64` |
| 426 | /// range → `Null` (FEEL numbers are `f64`). |
| 427 | unsafe fn numeric_to_value(numeric: pg_sys::Numeric) -> Value { |
| 428 | let datum = pg_sys::Datum::from(numeric); |
| 429 | match AnyNumeric::from_polymorphic_datum(datum, false, pg_sys::NUMERICOID) { |
| 430 | Some(n) => match f64::try_from(n) { |
| 431 | Ok(f) => Value::Number(f), |
| 432 | Err(_) => Value::Null, |
| 433 | }, |
| 434 | None => Value::Null, |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | // --------------------------------------------------------------------------- |
| 439 | // Lazy host object (approach A): a jsonb container behind ForeignObject (ADR-21). |
| 440 | // --------------------------------------------------------------------------- |
| 441 | |
| 442 | /// A jsonb container resolved lazily behind feel-core's [`ForeignObject`] seam: the |
| 443 | /// FEEL dot reads one member at a time via `getKeyJsonValueFromContainer`, so a |
| 444 | /// large context whose deep structure is never navigated is never walked. |
| 445 | /// |
| 446 | /// Holds a raw `*mut JsonbContainer` borrowed from the call's detoasted argument, |
| 447 | /// valid only for the duration of the call — see the module-level safety note. |
| 448 | #[derive(Debug)] |
| 449 | struct JsonbForeign { |
| 450 | container: *mut pg_sys::JsonbContainer, |
| 451 | } |
| 452 | |
| 453 | impl ForeignObject for JsonbForeign { |
| 454 | fn get(&self, key: &str) -> Value { |
| 455 | unsafe { |
| 456 | // Keyed access only makes sense for an object; an array member is an |
| 457 | // absent key (value-null), matching a missing context entry. |
| 458 | if (*self.container).header & pg_sys::JB_FOBJECT == 0 { |
| 459 | return Value::Null; |
| 460 | } |
| 461 | let mut res = pg_sys::JsonbValue::default(); |
| 462 | let found = pg_sys::getKeyJsonValueFromContainer( |
| 463 | self.container, |
| 464 | key.as_ptr() as *const c_char, |
| 465 | key.len() as c_int, |
| 466 | &mut res, |
| 467 | ); |
| 468 | if found.is_null() { |
| 469 | Value::Null |
| 470 | } else { |
| 471 | // Shallow: a nested container stays a Foreign. |
| 472 | jbv_to_value(&res) |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | fn force(&self) -> Value { |
| 478 | // One level: members are shallow, so nested containers stay lazy. |
| 479 | unsafe { container_to_value(self.container) } |
| 480 | } |
| 481 | |
| 482 | fn as_any(&self) -> &dyn Any { |
| 483 | self |
| 484 | } |
| 485 | } |