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 · 33.6 KB · at 93b43c1c833b · raw

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