Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feel / crates / feel-pg / src / lib.rs · 27.7 KB · at 90f493059be5 · raw

Outline: 41 definitions
1
//! PostgreSQL wrapper for `feel-core`, built with pgrx.
2
//!
3
//! Exposes two SQL functions:
4
//!
5
//! ```sql
6
//! feel_eval(expr text, context jsonb DEFAULT '{}', strict bool DEFAULT false)
7
//!   RETURNS jsonb                                       -- STABLE PARALLEL SAFE
8
//! feel_eval_immutable(expr text, context jsonb DEFAULT '{}', strict bool DEFAULT false)
9
//!   RETURNS jsonb                                       -- IMMUTABLE PARALLEL SAFE
10
//! ```
11
//!
12
//! Both evaluate a FEEL expression against a jsonb context. `feel_eval` is STABLE
13
//! (its `now()`/`today()` read the transaction clock); `feel_eval_immutable` is the
14
//! deterministic subset for expression indexes — it rejects `now()`/`today()` and
15
//! named time zones, leaving the result a pure function of `(expr, context)` (RD-10).
16
//!
17
//! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the
18
//! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C
19
//! API directly — no `serde_json` round-trip — and reads the context **lazily**
20
//! (nested objects navigated on demand, ADR-21); see the [`jsonb`] module and
21
//! RD-11.
22
//!
23
//! Regex dialect: this wrapper keeps feel-core's default `RustRegex` provider, so
24
//! `matches`/`replace`/`split` use the Rust regex dialect (ADR-15/ADR-16). A
25
//! future `PgRegex` provider could route them through Postgres' own POSIX ARE
26
//! engine (e.g. `DirectFunctionCall` to `textregexreplace` /
27
//! `regexp_split_to_array`) and be passed via `CompiledExpr::evaluate_with_env`, so
28
//! the *host* dialect applies server-side too — deferred, not done here.
29
//!
30
//! Temporal values (ADR-18) cross the boundary as canonical ISO-8601 jsonb
31
//! strings, so converting to a native PostgreSQL type is a plain cast — and the
32
//! cast's error path stays in SQL, never `ereport`-ing through Rust frames:
33
//!
34
//! ```sql
35
//! (feel_eval('date(2017, 8, 3)')              #>> '{}')::date          -- 2017-08-03
36
//! (feel_eval('date and time("2017-08-10T...")') #>> '{}')::timestamptz
37
//! (feel_eval('duration("P1Y2M")')             #>> '{}')::interval      -- 1 year 2 mons
38
//! ```
39
//!
40
//! `now()`/`today()` read the transaction start timestamp, so they are constant
41
//! across rows of a query and agree with PostgreSQL's own `now()`.
42
43
use pgrx::prelude::*;
44
use pgrx::{pg_func_extra, PgBox};
45
46
use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex};
47
48
mod jsonb;
49
use jsonb::PgJsonb;
50
51
::pgrx::pg_module_magic!();
52
53
/// Evaluate a FEEL expression and return the result as jsonb.
54
///
55
/// Raises a Postgres ERROR if the expression cannot be parsed. By default the
56
/// boundary is *lenient*: a null arising from a type/domain error is returned as
57
/// jsonb `null`. Pass `strict => true` to instead raise an ERROR when the result
58
/// is, or contains, such an error-null, so the error does not pass silently
59
/// (ADR-14).
60
///
61
/// The parsed expression is cached in the call site's `fn_extra` slot (allocated
62
/// in `flinfo->fn_mcxt`, which lives for the whole query — never the per-row
63
/// context), keyed on the expression text. So when `expr` is a query constant —
64
/// the usual case, e.g. one decision over many rows — it is parsed once per query
65
/// and only re-parsed if the text actually changes. No global/session cache.
66
///
67
/// Declared **STABLE** (not VOLATILE): the only non-argument input is the
68
/// transaction start timestamp behind `now()`/`today()`, constant within a
69
/// transaction — exactly why PostgreSQL's own `transaction_timestamp()` is STABLE.
70
/// **PARALLEL SAFE**: evaluation has no global mutable state, I/O or randomness,
71
/// and a parallel worker is a separate process with its own `fn_extra` cache.
72
/// `COST 100`: a parse-cached eval of a low-to-medium expression over a small
73
/// context measures ~2.3 µs/call on pg18 — ≈ 95× a baseline `procost`-1 C call (one
74
/// `cpu_operator_cost` ≈ 24 ns here), rounded to PostgreSQL's own PL/pgSQL default
75
/// of 100, which feel_eval is now roughly on par with (RD-11). The earlier `COST
76
/// 500` reflected the pgrx `JsonB` text↔`serde_json` boundary (~13.5 µs); the binary
77
/// jsonb boundary (RD-11) removed that, so the planner can now schedule feel_eval
78
/// more like an ordinary function. The function is STRICT (pgrx default for non-`Option`
79
/// args): a SQL `NULL` `expr` or `context` returns `NULL` unevaluated; the `context`
80
/// `DEFAULT '{}'` keeps `feel_eval('1 + 1')` working — only an *explicit* `NULL`
81
/// context short-circuits. It is *not* IMMUTABLE (`now()` varies across
82
/// transactions) — see [`feel_eval_immutable`] for the deterministic subset usable
83
/// in expression indexes (RD-10).
84
#[pg_extern(stable, parallel_safe, cost = 100)]
85
fn feel_eval(
86
    expr: &str,
87
    context: default!(PgJsonb, "'{}'::jsonb"),
88
    strict: default!(bool, "false"),
89
    fcinfo: pg_sys::FunctionCallInfo,
90
) -> PgJsonb {
91
    // SAFETY: see [`cached_compile`] — the returned pointer is valid for the query.
92
    let compiled = unsafe { &*cached_compile(expr, fcinfo) };
93
94
    // `now()`/`today()` read the transaction start (ADR-18) — constant per query,
95
    // matching PostgreSQL's own `now()`/`transaction_timestamp()`.
96
    let env = EvalEnv::new(&RustRegex, transaction_start());
97
    let ctx = build_context(&context);
98
    eval_to_jsonb(compiled, &ctx, strict, &env)
99
}
100
101
/// Parse `expr`, caching the [`CompiledExpr`] in the call site's `fn_extra` slot
102
/// (allocated in `flinfo->fn_mcxt`, which lives for the whole query — never the
103
/// per-row context), keyed on the text. A query constant is thus parsed once and
104
/// reused across rows; the text only re-parses if it actually changes. Returns a
105
/// pointer into that cache, valid for the rest of the query.
106
///
107
/// # Safety
108
/// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The
109
/// returned pointer must not outlive the query (the `fn_mcxt`).
110
unsafe fn cached_compile(expr: &str, fcinfo: pg_sys::FunctionCallInfo) -> *const CompiledExpr {
111
    // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop
112
    // callback, so the owned `CompiledExpr` is freed on context teardown.
113
    let mut cache: PgBox<Option<(String, CompiledExpr)>> = pg_func_extra(fcinfo, || None);
114
    let stale = match &*cache {
115
        Some((cached, _)) => cached != expr,
116
        None => true,
117
    };
118
    if stale {
119
        match compile(expr) {
120
            Ok(compiled) => *cache = Some((expr.to_owned(), compiled)),
121
            Err(e) => error!("feel_eval failed: {e}"),
122
        }
123
    }
124
    match &*cache {
125
        Some((_, compiled)) => compiled as *const CompiledExpr,
126
        None => unreachable!("cache populated above"),
127
    }
128
}
129
130
/// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the
131
/// subset safe in expression indexes, generated columns, and constant folding
132
/// (RD-10).
133
///
134
/// Same arguments and jsonb boundary as [`feel_eval`], with two restrictions that
135
/// make the result depend only on `(expr, context)` and never on time or the
136
/// (updatable) IANA tzdb:
137
///
138
/// - `now()`/`today()` are **rejected** with an ERROR: they vary across
139
///   transactions, so can never be IMMUTABLE — use [`feel_eval`] for those. The
140
///   check is static ([`CompiledExpr::is_clock_free`]) and cached per call site,
141
///   so it costs nothing per row.
142
/// - *Named* time zones (`@Europe/Berlin`) become null (or ERROR under
143
///   `strict => true`): their UTC offset is read from the IANA tzdb, which can
144
///   change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully
145
///   supported — all an index needs.
146
///
147
/// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken
148
/// as immutable; their results are stable except across a libc/`regex` upgrade —
149
/// the same pragmatic stance PostgreSQL takes for its own such functions, after
150
/// which an index may need a one-off `REINDEX` (RD-10). `PARALLEL SAFE` and
151
/// `COST 100` for the same reasons as [`feel_eval`].
152
///
153
/// ```sql
154
/// -- Index a FEEL predicate over a jsonb column:
155
/// CREATE INDEX ON applications
156
///   ((feel_eval_immutable('applicant.age >= 18 and applicant.income > 50000', data)));
157
/// ```
158
#[pg_extern(immutable, parallel_safe, cost = 100)]
159
fn feel_eval_immutable(
160
    expr: &str,
161
    context: default!(PgJsonb, "'{}'::jsonb"),
162
    strict: default!(bool, "false"),
163
    fcinfo: pg_sys::FunctionCallInfo,
164
) -> PgJsonb {
165
    // Same per-call-site parse cache as `feel_eval`, plus the cached clock-free
166
    // verdict so the static check is paid once per query, never per row.
167
    let mut cache: PgBox<Option<(String, CompiledExpr, bool)>> =
168
        unsafe { pg_func_extra(fcinfo, || None) };
169
    let stale = match &*cache {
170
        Some((cached, _, _)) => cached != expr,
171
        None => true,
172
    };
173
    if stale {
174
        match compile(expr) {
175
            Ok(compiled) => {
176
                let clock_free = compiled.is_clock_free();
177
                *cache = Some((expr.to_owned(), compiled, clock_free));
178
            }
179
            Err(e) => error!("feel_eval_immutable failed: {e}"),
180
        }
181
    }
182
    let (compiled, clock_free) = match &*cache {
183
        Some((_, compiled, clock_free)) => (compiled, *clock_free),
184
        None => unreachable!("cache populated above"),
185
    };
186
    if !clock_free {
187
        error!(
188
            "feel_eval_immutable: expression calls now()/today(), which are not \
189
             IMMUTABLE; use feel_eval instead"
190
        );
191
    }
192
    // The clock is never read (now()/today() are rejected above), so the instant
193
    // is a fixed sentinel — keeping this function free of any ambient read, as an
194
    // IMMUTABLE function should be. Named zones are vetted away (RD-10).
195
    let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones();
196
    let ctx = build_context(&context);
197
    eval_to_jsonb(compiled, &ctx, strict, &env)
198
}
199
200
/// Build the evaluation [`Context`] from the binary jsonb argument, lazily (approach
201
/// A, ADR-21) — the M4 benchmark's clear winner over the eager and serde walks
202
/// (RD-11): a nested context is navigated on demand, so an expression that reads one
203
/// deep path out of a large context pays almost nothing.
204
fn build_context(context: &PgJsonb) -> Context {
205
    // SAFETY: `context.0` is the live, detoasted argument jsonb, valid for the whole
206
    // call; any lazy `Foreign` derived from it is confined to this call — the output
207
    // path forces it to owned jsonb, so it never escapes.
208
    unsafe { jsonb::context_from_jsonb(context.0) }
209
        .unwrap_or_else(|e| error!("invalid feel context: {e}"))
210
}
211
212
/// The eval-and-map-to-jsonb tail shared by [`feel_eval`] and
213
/// [`feel_eval_immutable`]: run the compiled expression against the prebuilt
214
/// [`Context`] under `env`, and apply the strict/lenient boundary (ADR-14), then
215
/// build the result jsonb directly (approach C). The volatility difference lives
216
/// entirely in the `env`, and the input strategy in how `ctx` was built.
217
fn eval_to_jsonb(compiled: &CompiledExpr, ctx: &Context, strict: bool, env: &EvalEnv) -> PgJsonb {
218
    match compiled.evaluate_with_env(ctx, env) {
219
        Ok(value) if strict && value.contains_error() => {
220
            error!("feel_eval: result is null from a type or domain error (strict mode)")
221
        }
222
        Ok(value) => PgJsonb(jsonb::value_to_jsonb(&value)),
223
        Err(e) => error!("feel_eval failed: {e}"),
224
    }
225
}
226
227
/// A fixed, arbitrary instant (the Unix epoch, UTC) for [`feel_eval_immutable`]'s
228
/// `EvalEnv`. `now()`/`today()` are rejected before evaluation there, so it is
229
/// never read; using a constant — not the transaction clock — keeps the function
230
/// free of any ambient read.
231
fn fixed_instant() -> jiff::Zoned {
232
    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
233
    jiff::Timestamp::from_microsecond(0)
234
        .map(|ts| ts.to_zoned(utc))
235
        .unwrap_or_else(|_| jiff::Zoned::now())
236
}
237
238
/// The current transaction's start time as a `jiff::Zoned` (UTC), for `now()`/
239
/// `today()`. PostgreSQL's `TimestampTz` is microseconds since 2000-01-01 UTC.
240
fn transaction_start() -> jiff::Zoned {
241
    // SAFETY: a plain read of the transaction timestamp; never `ereport`s.
242
    let pg_micros = unsafe { pg_sys::GetCurrentTransactionStartTimestamp() };
243
    const PG_EPOCH_UNIX_SECS: i64 = 946_684_800; // 2000-01-01 minus 1970-01-01
244
    let unix_micros = pg_micros + PG_EPOCH_UNIX_SECS * 1_000_000;
245
    // A fixed-offset (not named) UTC zone, so `now()` serialises as `…+00:00`,
246
    // which casts straight to `timestamptz` (a named `@UTC` would not).
247
    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
248
    jiff::Timestamp::from_microsecond(unix_micros)
249
        .map(|ts| ts.to_zoned(utc))
250
        .unwrap_or_else(|_| jiff::Zoned::now())
251
}
252
253
#[cfg(any(test, feature = "pg_test"))]
254
#[pg_schema]
255
mod tests {
256
    use pgrx::prelude::*;
257
258
    #[pg_test]
259
    fn addition_returns_two() {
260
        let matched = Spi::get_one::<bool>("SELECT feel_eval('1 + 1', '{}'::jsonb) = '2'::jsonb")
261
            .expect("SPI query failed");
262
        assert_eq!(matched, Some(true));
263
    }
264
265
    #[pg_test]
266
    fn range_membership_is_true() {
267
        let matched =
268
            Spi::get_one::<bool>("SELECT feel_eval('5 in [1..10]', '{}'::jsonb) = 'true'::jsonb")
269
                .expect("SPI query failed");
270
        assert_eq!(matched, Some(true));
271
    }
272
273
    #[pg_test]
274
    fn default_context_argument() {
275
        // The `context` argument defaults to '{}'::jsonb.
276
        let matched = Spi::get_one::<bool>("SELECT feel_eval('1 + 1') = '2'::jsonb")
277
            .expect("SPI query failed");
278
        assert_eq!(matched, Some(true));
279
    }
280
281
    #[pg_test]
282
    fn if_then_else_branches() {
283
        let matched =
284
            Spi::get_one::<bool>("SELECT feel_eval('if 1 < 2 then 10 else 20') = '10'::jsonb")
285
                .expect("SPI query failed");
286
        assert_eq!(matched, Some(true));
287
    }
288
289
    #[pg_test]
290
    fn for_loop_returns_jsonb_array() {
291
        let matched = Spi::get_one::<bool>(
292
            "SELECT feel_eval('for i in [1,2,3] return i + 1') = '[2,3,4]'::jsonb",
293
        )
294
        .expect("SPI query failed");
295
        assert_eq!(matched, Some(true));
296
    }
297
298
    #[pg_test]
299
    fn type_error_is_lenient_null_by_default() {
300
        // A type error -> jsonb null (lenient boundary).
301
        let matched = Spi::get_one::<bool>("SELECT feel_eval('1 + true') = 'null'::jsonb")
302
            .expect("SPI query failed");
303
        assert_eq!(matched, Some(true));
304
    }
305
306
    #[pg_test(error = "feel_eval: result is null from a type or domain error (strict mode)")]
307
    fn strict_mode_raises_on_error_null() {
308
        // strict => true escalates the error-null to an ERROR (this query raises).
309
        let _ = Spi::get_one::<bool>("SELECT feel_eval('1 + true', '{}'::jsonb, true) IS NOT NULL");
310
    }
311
312
    #[pg_test]
313
    fn strict_mode_passes_plain_null() {
314
        // A genuine value-null is fine even in strict mode.
315
        let matched =
316
            Spi::get_one::<bool>("SELECT feel_eval('null', '{}'::jsonb, true) = 'null'::jsonb")
317
                .expect("SPI query failed");
318
        assert_eq!(matched, Some(true));
319
    }
320
321
    #[pg_test]
322
    fn same_expression_over_many_contexts() {
323
        // One constant expression evaluated against many per-row jsonb contexts:
324
        // exercises the fn_extra parse-once reuse path; each row must still be
325
        // correct. `a + 1` over a generated series of contexts.
326
        let matched = Spi::get_one::<bool>(
327
            r#"SELECT bool_and(feel_eval('a + 1', jsonb_build_object('a', g)) = to_jsonb(g + 1))
328
               FROM generate_series(1, 100) AS g"#,
329
        )
330
        .expect("SPI query failed");
331
        assert_eq!(matched, Some(true));
332
    }
333
334
    #[pg_test]
335
    fn path_access_reads_nested_context() {
336
        // A nested jsonb object is bound as a FEEL context; `p.age` reads it.
337
        let matched = Spi::get_one::<bool>(
338
            r#"SELECT feel_eval('p.age', '{"p": {"age": 42}}'::jsonb) = '42'::jsonb"#,
339
        )
340
        .expect("SPI query failed");
341
        assert_eq!(matched, Some(true));
342
    }
343
344
    #[pg_test]
345
    fn context_literal_returns_jsonb_object() {
346
        let matched = Spi::get_one::<bool>(
347
            r#"SELECT feel_eval('{a: 1, b: a + 1}') = '{"a": 1, "b": 2}'::jsonb"#,
348
        )
349
        .expect("SPI query failed");
350
        assert_eq!(matched, Some(true));
351
    }
352
353
    #[pg_test]
354
    fn string_comparison_is_lexicographic() {
355
        let matched =
356
            Spi::get_one::<bool>(r#"SELECT feel_eval('"apple" < "banana"') = 'true'::jsonb"#)
357
                .expect("SPI query failed");
358
        assert_eq!(matched, Some(true));
359
    }
360
361
    #[pg_test]
362
    fn temporal_date_is_iso_string() {
363
        // A temporal result crosses as a canonical ISO-8601 jsonb string (ADR-18).
364
        let matched =
365
            Spi::get_one::<bool>(r#"SELECT feel_eval('date(2017, 8, 3)') = '"2017-08-03"'::jsonb"#)
366
                .expect("SPI query failed");
367
        assert_eq!(matched, Some(true));
368
    }
369
370
    #[pg_test]
371
    fn temporal_duration_casts_to_interval() {
372
        // ISO-8601 means converting to a native PostgreSQL type is a plain cast,
373
        // satisfying ADR-5's interval mapping (the cast errors stay in SQL).
374
        let matched = Spi::get_one::<bool>(
375
            r#"SELECT (feel_eval('duration("P1Y2M")') #>> '{}')::interval
376
                      = interval '1 year 2 months'"#,
377
        )
378
        .expect("SPI query failed");
379
        assert_eq!(matched, Some(true));
380
    }
381
382
    #[pg_test]
383
    fn now_is_transaction_stable() {
384
        // now() reads the transaction start, so it is constant across rows and
385
        // equals PostgreSQL's own transaction_timestamp() (ADR-18).
386
        let matched = Spi::get_one::<bool>(
387
            r#"SELECT bool_and((feel_eval('now()') #>> '{}')::timestamptz = transaction_timestamp())
388
               FROM generate_series(1, 5)"#,
389
        )
390
        .expect("SPI query failed");
391
        assert_eq!(matched, Some(true));
392
    }
393
394
    #[pg_test]
395
    fn immutable_evaluates_like_feel_eval() {
396
        let matched = Spi::get_one::<bool>("SELECT feel_eval_immutable('1 + 1') = '2'::jsonb")
397
            .expect("SPI query failed");
398
        assert_eq!(matched, Some(true));
399
    }
400
401
    #[pg_test]
402
    fn immutable_parses_once_over_many_rows() {
403
        // The fn_extra cache (parse + clock-free verdict) is reused per row.
404
        let matched = Spi::get_one::<bool>(
405
            r#"SELECT bool_and(feel_eval_immutable('a + 1', jsonb_build_object('a', g)) = to_jsonb(g + 1))
406
               FROM generate_series(1, 100) AS g"#,
407
        )
408
        .expect("SPI query failed");
409
        assert_eq!(matched, Some(true));
410
    }
411
412
    #[pg_test(
413
        error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead"
414
    )]
415
    fn immutable_rejects_now() {
416
        // now() can never be IMMUTABLE -> hard ERROR (not a silent null).
417
        let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('now()') IS NOT NULL");
418
    }
419
420
    #[pg_test(
421
        error = "feel_eval_immutable: expression calls now()/today(), which are not IMMUTABLE; use feel_eval instead"
422
    )]
423
    fn immutable_rejects_today() {
424
        let _ = Spi::get_one::<bool>("SELECT feel_eval_immutable('today() = today()') IS NOT NULL");
425
    }
426
427
    #[pg_test]
428
    fn immutable_allows_offset_zones() {
429
        // Fixed offsets and Z are tzdb-independent -> fully supported.
430
        let matched = Spi::get_one::<bool>(
431
            r#"SELECT feel_eval_immutable('time("12:00:00+02:00")') = '"12:00:00+02:00"'::jsonb"#,
432
        )
433
        .expect("SPI query failed");
434
        assert_eq!(matched, Some(true));
435
    }
436
437
    #[pg_test]
438
    fn immutable_named_zone_is_null_by_default() {
439
        // A named zone (tzdb-dependent) is vetted to jsonb null at the lenient boundary.
440
        let matched = Spi::get_one::<bool>(
441
            r#"SELECT feel_eval_immutable('time("12:00:00@Europe/Berlin")') = 'null'::jsonb"#,
442
        )
443
        .expect("SPI query failed");
444
        assert_eq!(matched, Some(true));
445
    }
446
447
    #[pg_test(error = "feel_eval: result is null from a type or domain error (strict mode)")]
448
    fn immutable_named_zone_raises_in_strict_mode() {
449
        // strict => true escalates the vetted named-zone error-null to an ERROR.
450
        let _ = Spi::get_one::<bool>(
451
            r#"SELECT feel_eval_immutable('time("12:00:00@Europe/Berlin")', '{}', true) IS NOT NULL"#,
452
        );
453
    }
454
455
    #[pg_test]
456
    fn immutable_is_usable_in_an_expression_index() {
457
        // The payoff: PostgreSQL only accepts IMMUTABLE functions in an index
458
        // expression, so this DDL succeeding *is* the proof of the marker.
459
        Spi::run(
460
            "CREATE TEMP TABLE feel_idx_ok (data jsonb);
461
             CREATE INDEX ON feel_idx_ok ((feel_eval_immutable('applicant.age >= 18', data)));",
462
        )
463
        .expect("an expression index over feel_eval_immutable should be allowed");
464
    }
465
466
    #[pg_test]
467
    fn lazy_binary_input_reads_every_shape() {
468
        // The lazy binary input walk (approach A, ADR-21 — RD-11's chosen default)
469
        // must read every context shape correctly: scalar reads, deep path
470
        // navigation through nested objects, list builtins over a context list,
471
        // for-loops, absent keys (-> null), and — crucially — returning a whole
472
        // sub-object or sub-list, which exercises the output path forcing a lazy
473
        // `Foreign` recursively back to jsonb.
474
        let all_match = Spi::get_one::<bool>(
475
            r#"
476
            SELECT bool_and(feel_eval(expr, ctx) IS NOT DISTINCT FROM expected)
477
            FROM (VALUES
478
                ('a + 1',            '{"a": 41}'::jsonb,                              '42'::jsonb),
479
                ('p.address.city',   '{"p": {"address": {"city": "Berlin"}}}'::jsonb, '"Berlin"'::jsonb),
480
                ('sum(xs)',          '{"xs": [1, 2, 3, 4]}'::jsonb,                   '10'::jsonb),
481
                ('count(p.tags)',    '{"p": {"tags": ["x", "y", "z"]}}'::jsonb,       '3'::jsonb),
482
                ('for x in xs return x * 2', '{"xs": [10, 20, 30]}'::jsonb,           '[20, 40, 60]'::jsonb),
483
                -- return a whole nested sub-object: forces the lazy Foreign back out
484
                ('p',  '{"p": {"a": 1, "b": [2, {"c": 3}], "d": null}}'::jsonb,
485
                       '{"a": 1, "b": [2, {"c": 3}], "d": null}'::jsonb),
486
                ('p.tags',           '{"p": {"tags": ["x", "y"]}}'::jsonb,            '["x", "y"]'::jsonb),
487
                ('missing.key',      '{"present": 1}'::jsonb,                         'null'::jsonb),
488
                ('flag and 1 < 2',   '{"flag": true}'::jsonb,                         'true'::jsonb)
489
            ) AS t(expr, ctx, expected)
490
            "#,
491
        )
492
        .expect("SPI query failed");
493
        assert_eq!(all_match, Some(true));
494
    }
495
496
    #[pg_test]
497
    fn binary_output_matches_expected_jsonb_across_shapes() {
498
        // The approach-C GATE (RD-11): the binary jsonb output path must reproduce
499
        // the exact value the old serde path did, across the shapes that stress an
500
        // ad-hoc encoder — deep/mixed nesting, empty containers, integer-vs-float
501
        // and the 2^53 integral boundary, unicode, and null/error-null. jsonb `=` is
502
        // semantic (normalised), so key order is irrelevant.
503
        let all_match = Spi::get_one::<bool>(
504
            r#"
505
            SELECT bool_and(feel_eval(expr) IS NOT DISTINCT FROM expected)
506
            FROM (VALUES
507
                -- scalars
508
                ('1 + 1',            '2'::jsonb),
509
                ('-42',              '-42'::jsonb),
510
                ('2.5',              '2.5'::jsonb),
511
                ('true',             'true'::jsonb),
512
                ('false',            'false'::jsonb),
513
                ('null',             'null'::jsonb),
514
                ('1 + true',         'null'::jsonb),          -- error-null -> null
515
                ('"héllo ☃ 日本"',   '"héllo ☃ 日本"'::jsonb), -- unicode
516
                ('""',               '""'::jsonb),            -- empty string
517
                -- integral boundary: 2^53 - 1 stays an integer
518
                ('9007199254740991', '9007199254740991'::jsonb),
519
                -- containers
520
                ('[]',               '[]'::jsonb),
521
                ('[1, 2, 3]',        '[1, 2, 3]'::jsonb),
522
                ('{a: 1, b: 2}',     '{"a": 1, "b": 2}'::jsonb),
523
                ('for i in [1,2,3] return i * i', '[1, 4, 9]'::jsonb),
524
                -- deep + mixed nesting
525
                ('{a: {b: [1, {c: 2}]}, list: [[1, 2], []]}',
526
                 '{"a": {"b": [1, {"c": 2}]}, "list": [[1, 2], []]}'::jsonb),
527
                ('[{x: [true, null, "s"]}, {y: 1.5}]',
528
                 '[{"x": [true, null, "s"]}, {"y": 1.5}]'::jsonb)
529
            ) AS t(expr, expected)
530
            "#,
531
        )
532
        .expect("SPI query failed");
533
        assert_eq!(all_match, Some(true));
534
    }
535
536
    #[pg_test]
537
    fn binary_output_temporals_are_iso_strings() {
538
        // Temporals cross as canonical ISO-8601 jsonb strings (ADR-18); check each
539
        // type both for the exact string and for castability to its native type.
540
        let all_match = Spi::get_one::<bool>(
541
            r#"
542
            SELECT
543
                feel_eval('date(2017, 8, 3)')                       = '"2017-08-03"'::jsonb
544
            AND feel_eval('time("12:34:56")')                       = '"12:34:56"'::jsonb
545
            AND (feel_eval('date and time("2017-08-10T11:22:33")') #>> '{}')::timestamp
546
                    = timestamp '2017-08-10 11:22:33'
547
            AND (feel_eval('duration("P1Y2M")')   #>> '{}')::interval = interval '1 year 2 months'
548
            AND (feel_eval('duration("P1DT2H30M")')#>> '{}')::interval = interval '1 day 2 hours 30 minutes'
549
            "#,
550
        )
551
        .expect("SPI query failed");
552
        assert_eq!(all_match, Some(true));
553
    }
554
555
    #[pg_test]
556
    fn binary_output_handles_non_finite_number_as_null() {
557
        // NaN/±Inf have no jsonb representation -> null (matching number_to_json).
558
        // `log(0)` underflows to -Infinity in the FEEL math builtins.
559
        let matched = Spi::get_one::<bool>("SELECT feel_eval('log(0)') = 'null'::jsonb")
560
            .expect("SPI query failed");
561
        assert_eq!(matched, Some(true));
562
    }
563
564
    #[pg_test(error = "functions in index expression must be marked IMMUTABLE")]
565
    fn stable_feel_eval_is_rejected_in_an_index() {
566
        // The flip side: feel_eval is STABLE, so PostgreSQL refuses it in an index.
567
        Spi::run(
568
            "CREATE TEMP TABLE feel_idx_bad (data jsonb);
569
             CREATE INDEX ON feel_idx_bad ((feel_eval('applicant.age >= 18', data)));",
570
        )
571
        .expect("DDL should raise before this unwrap");
572
    }
573
574
    // Descendant `e ... name` (DMN 10.3.2.7, grammar rule 68). jsonb is a serialized
575
    // value tree, so the reachable JsonbForeign sub-graph is definitionally acyclic
576
    // — feel-pg is EXEMPT from the cycle-guard question (no identity() override and
577
    // no cycle test, because a cycle cannot be constructed in jsonb).
578
    #[pg_test]
579
    fn descendant_spec_example() {
580
        let matched = Spi::get_one::<bool>(
581
            r#"SELECT feel_eval('{a: {b: {b: 1}}} ... b') = '[{"b": 1}, 1]'::jsonb"#,
582
        )
583
        .expect("SPI query failed");
584
        assert_eq!(matched, Some(true));
585
    }
586
587
    #[pg_test]
588
    fn descendant_collects_across_a_list_of_contexts() {
589
        let matched = Spi::get_one::<bool>(
590
            r#"SELECT feel_eval('[{x:1},{x:2}] ... x') = '[1, 2]'::jsonb"#,
591
        )
592
        .expect("SPI query failed");
593
        assert_eq!(matched, Some(true));
594
    }
595
596
    #[pg_test]
597
    fn descendant_no_match_is_empty_list() {
598
        let matched =
599
            Spi::get_one::<bool>(r#"SELECT feel_eval('{a:1} ... z') = '[]'::jsonb"#)
600
                .expect("SPI query failed");
601
        assert_eq!(matched, Some(true));
602
    }
603
604
    #[pg_test]
605
    fn descendant_descends_into_nested_jsonb() {
606
        let matched = Spi::get_one::<bool>(
607
            r#"SELECT feel_eval('o ... name', '{"o": {"customer": {"name": "Ada"}}}'::jsonb)
608
                       = '["Ada"]'::jsonb"#,
609
        )
610
        .expect("SPI query failed");
611
        assert_eq!(matched, Some(true));
612
    }
613
}
614
615
/// Required pgrx test harness hooks.
616
#[cfg(test)]
617
pub mod pg_test {
618
    pub fn setup(_options: Vec<&str>) {}
619
620
    pub fn postgresql_conf_options() -> Vec<&'static str> {
621
        vec![]
622
    }
623
}