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 · 35.4 KB · at da382279c66c · raw

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