| @@ -13,10 +13,11 @@ |
| 13 | 13 | //! (its `now()`/`today()` read the transaction clock); `feel_eval_immutable` is the |
| 14 | 14 | //! deterministic subset for expression indexes — it rejects `now()`/`today()` and |
| 15 | 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). |
| 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 (`'symbols'`, |
| 20 | +//! the default, or `'quoted'` — backticks only, no per-row name checks). |
| 20 | 21 | //! |
| 21 | 22 | //! The JSON/jsonb boundary mapping lives here (not in `feel-core`), per the |
| 22 | 23 | //! project's boundary-mapping decision. It uses PostgreSQL's **binary** jsonb C |
| @@ -47,10 +48,7 @@ |
| 47 | 48 | use pgrx::prelude::*; |
| 48 | 49 | use pgrx::{pg_func_extra, PgBox}; |
| 49 | 50 | |
| 50 | | -use feel_core::{ |
| 51 | | - compile, compile_with_probe, name_run_candidates, CompiledExpr, Context, EvalEnv, |
| 52 | | - RustRegex, ScopeProbe, |
| 53 | | -}; |
| 51 | +use feel_core::{compile_with, CompiledExpr, Context, EvalEnv, NameResolution, ParseOptions, RustRegex}; |
| 54 | 52 | |
| 55 | 53 | mod jsonb; |
| 56 | 54 | use jsonb::PgJsonb; |
| @@ -71,13 +69,13 @@ |
| 71 | 69 | /// the usual case, e.g. one decision over many rows — it is parsed once per query |
| 72 | 70 | /// and only re-parsed if the text actually changes. No global/session cache. |
| 73 | 71 | /// |
| 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. |
| 72 | +/// The cached [`CompiledExpr`] is **scope-adaptive** (ADR-48): special-character |
| 73 | +/// runs (`a-b`, `x.y`, `applicant.first-name`) are checked against each row — |
| 74 | +/// one key lookup per candidate — and the row gets the parse for its scope, from |
| 75 | +/// a small per-call-site cache of parses keyed by those answers. A name and an |
| 76 | +/// arithmetic reading thus coexist across rows of one query at no per-row parse |
| 77 | +/// cost. `name_resolution => 'quoted'` (backticks only, Camunda semantics) skips |
| 78 | +/// the checks altogether; `'symbols'` is the default. |
| 81 | 79 | /// |
| 82 | 80 | /// Declared **STABLE** (not VOLATILE): the only non-argument input is the |
| 83 | 81 | /// transaction start timestamp behind `now()`/`today()`, constant within a |
| @@ -101,77 +99,60 @@ |
| 101 | 99 | expr: &str, |
| 102 | 100 | context: default!(PgJsonb, "'{}'::jsonb"), |
| 103 | 101 | strict: default!(bool, "false"), |
| 102 | + name_resolution: default!(&str, "'symbols'"), |
| 104 | 103 | fcinfo: pg_sys::FunctionCallInfo, |
| 105 | 104 | ) -> PgJsonb { |
| 105 | + let names = name_level(name_resolution, "feel_eval"); |
| 106 | 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; |
| 107 | + let compiled = unsafe { &*cached_compile(expr, names, fcinfo) }; |
| 109 | 108 | |
| 110 | 109 | // `now()`/`today()` read the transaction start (ADR-18) — constant per query, |
| 111 | 110 | // matching PostgreSQL's own `now()`/`transaction_timestamp()`. |
| 112 | 111 | let env = EvalEnv::new(&RustRegex, transaction_start()); |
| 113 | 112 | 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. |
| 113 | + eval_to_jsonb(compiled, &ctx, strict, &env) |
| 114 | +} |
| 115 | + |
| 116 | +/// The `name_resolution` argument as a level; an unknown spelling is an ERROR. |
| 117 | +fn name_level(arg: &str, func: &str) -> NameResolution { |
| 118 | + NameResolution::from_name(arg).unwrap_or_else(|| { |
| 119 | + error!("{func}: unknown name_resolution '{arg}' (expected 'symbols' or 'quoted')") |
| 120 | + }) |
| 121 | +} |
| 122 | + |
| 123 | +/// Parse `expr` at `names`, caching the [`CompiledExpr`] in the call site's |
| 124 | +/// `fn_extra` slot (allocated in `flinfo->fn_mcxt`, which lives for the whole |
| 125 | +/// query — never the per-row context), keyed on the text and the level. A query |
| 126 | +/// constant is thus parsed once and reused across rows; the compiled expression |
| 127 | +/// itself caches its few scope-specific parses (ADR-48). Returns a pointer into |
| 128 | +/// that cache, valid for the rest of the query. |
| 137 | 129 | /// |
| 138 | 130 | /// # Safety |
| 139 | 131 | /// `fcinfo` must be the genuine call info injected by the pgrx wrapper. The |
| 140 | 132 | /// returned pointer must not outlive the query (the `fn_mcxt`). |
| 141 | 133 | unsafe fn cached_compile( |
| 142 | 134 | expr: &str, |
| 135 | + names: NameResolution, |
| 143 | 136 | fcinfo: pg_sys::FunctionCallInfo, |
| 144 | | -) -> *const CachedParse { |
| 137 | +) -> *const CompiledExpr { |
| 145 | 138 | // `pg_func_extra` allocates the cache in `fn_mcxt` and registers a drop |
| 146 | 139 | // callback, so the owned `CompiledExpr` is freed on context teardown. |
| 147 | | - let mut cache: PgBox<Option<(String, CachedParse)>> = pg_func_extra(fcinfo, || None); |
| 140 | + let mut cache: PgBox<Option<(String, NameResolution, CompiledExpr)>> = |
| 141 | + pg_func_extra(fcinfo, || None); |
| 148 | 142 | let stale = match &*cache { |
| 149 | | - Some((cached, _)) => cached != expr, |
| 143 | + Some((cached, level, _)) => cached != expr || *level != names, |
| 150 | 144 | None => true, |
| 151 | 145 | }; |
| 152 | 146 | 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 | | - } |
| 147 | + match compile_with(expr, &ParseOptions::names(names)) { |
| 148 | + Ok(compiled) => *cache = Some((expr.to_owned(), names, compiled)), |
| 161 | 149 | Err(e) => error!("feel_eval failed: {e}"), |
| 162 | 150 | } |
| 163 | 151 | } |
| 164 | 152 | match &*cache { |
| 165 | | - Some((_, parsed)) => parsed as *const CachedParse, |
| 153 | + Some((_, _, compiled)) => compiled as *const CompiledExpr, |
| 166 | 154 | None => unreachable!("cache populated above"), |
| 167 | 155 | } |
| 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 | 156 | } |
| 176 | 157 | |
| 177 | 158 | /// Evaluate a FEEL expression as an **IMMUTABLE**, deterministic function — the |
| @@ -190,14 +171,14 @@ |
| 190 | 171 | /// `strict => true`): their UTC offset is read from the IANA tzdb, which can |
| 191 | 172 | /// change. Fixed offsets (`+02:00`) and `Z` are tzdb-independent and fully |
| 192 | 173 | /// 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`]. |
| 174 | +/// |
| 175 | +/// Special-character names resolve per row exactly as in [`feel_eval`] (ADR-48): |
| 176 | +/// a row binding `a-b` indexes the name, a row binding only `a` and `b` the |
| 177 | +/// difference — as §10.3.1.6 demands for each row. That is still IMMUTABLE: the |
| 178 | +/// parse is a pure function of the expression, the `name_resolution` argument and |
| 179 | +/// the row, so the result depends on the arguments alone. (Never a GUC: a session |
| 180 | +/// setting would break that.) `name_resolution => 'quoted'` gives one parse for |
| 181 | +/// every row. |
| 201 | 182 | /// |
| 202 | 183 | /// Math/regex builtins (`exp`/`log`/`sqrt`, `matches`/`replace`/`split`) are taken |
| 203 | 184 | /// as immutable; their results are stable except across a libc/`regex` upgrade — |
| @@ -215,29 +196,29 @@ |
| 215 | 196 | expr: &str, |
| 216 | 197 | context: default!(PgJsonb, "'{}'::jsonb"), |
| 217 | 198 | strict: default!(bool, "false"), |
| 199 | + name_resolution: default!(&str, "'symbols'"), |
| 218 | 200 | fcinfo: pg_sys::FunctionCallInfo, |
| 219 | 201 | ) -> PgJsonb { |
| 202 | + let names = name_level(name_resolution, "feel_eval_immutable"); |
| 220 | 203 | // 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>)>> = |
| 204 | + // verdict so the static check is paid once per query, never per row. |
| 205 | + let mut cache: PgBox<Option<(String, NameResolution, CompiledExpr, bool)>> = |
| 224 | 206 | unsafe { pg_func_extra(fcinfo, || None) }; |
| 225 | 207 | let stale = match &*cache { |
| 226 | | - Some((cached, _, _, _)) => cached != expr, |
| 208 | + Some((cached, level, _, _)) => cached != expr || *level != names, |
| 227 | 209 | None => true, |
| 228 | 210 | }; |
| 229 | 211 | if stale { |
| 230 | | - match compile(expr) { |
| 212 | + match compile_with(expr, &ParseOptions::names(names)) { |
| 231 | 213 | Ok(compiled) => { |
| 232 | 214 | let clock_free = compiled.is_clock_free(); |
| 233 | | - let candidates = name_run_candidates(expr); |
| 234 | | - *cache = Some((expr.to_owned(), compiled, clock_free, candidates)); |
| 215 | + *cache = Some((expr.to_owned(), names, compiled, clock_free)); |
| 235 | 216 | } |
| 236 | 217 | Err(e) => error!("feel_eval_immutable failed: {e}"), |
| 237 | 218 | } |
| 238 | 219 | } |
| 239 | | - let (compiled, clock_free, candidates) = match &*cache { |
| 240 | | - Some((_, compiled, clock_free, candidates)) => (compiled, *clock_free, candidates), |
| 220 | + let (compiled, clock_free) = match &*cache { |
| 221 | + Some((_, _, compiled, clock_free)) => (compiled, *clock_free), |
| 241 | 222 | None => unreachable!("cache populated above"), |
| 242 | 223 | }; |
| 243 | 224 | if !clock_free { |
| @@ -251,17 +232,6 @@ |
| 251 | 232 | // IMMUTABLE function should be. Named zones are vetted away (RD-10). |
| 252 | 233 | let env = EvalEnv::new(&RustRegex, fixed_instant()).forbidding_named_zones(); |
| 253 | 234 | 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 | 235 | eval_to_jsonb(compiled, &ctx, strict, &env) |
| 266 | 236 | } |
| 267 | 237 | |
| @@ -700,40 +670,87 @@ |
| 700 | 670 | } |
| 701 | 671 | |
| 702 | 672 | #[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>( |
| 673 | + fn special_char_name_parse_follows_each_row_at_one_call_site() { |
| 674 | + // ONE call site (one fn_extra cache) over several rows: rows binding |
| 675 | + // `a-b` read the NAME, rows binding only `a`/`b` the difference — the |
| 676 | + // adaptive CompiledExpr picks the parse per row (ADR-48). |
| 677 | + let matched = Spi::get_one::<bool>( |
| 678 | + r#"SELECT bool_and(feel_eval('a-b', c) = e) |
| 679 | + FROM (VALUES ('{"a-b": 5}'::jsonb, '5'::jsonb), |
| 680 | + ('{"a": 7, "b": 3}', '4'), |
| 681 | + ('{"a-b": 5, "a": 7, "b": 3}', '5'), |
| 682 | + ('{"a": 9, "b": 1}', '8')) t(c, e)"#, |
| 683 | + ) |
| 684 | + .expect("SPI query failed"); |
| 685 | + assert_eq!(matched, Some(true)); |
| 686 | + } |
| 687 | + |
| 688 | + #[pg_test] |
| 689 | + fn immutable_resolves_per_row_too() { |
| 690 | + // ADR-48 drops ADR-47's ERROR: the parse is a pure function of |
| 691 | + // (expr, name_resolution, row), so per-row names are still IMMUTABLE. |
| 692 | + let matched = Spi::get_one::<bool>( |
| 693 | + r#"SELECT bool_and(feel_eval_immutable('a-b', c) = e) |
| 694 | + FROM (VALUES ('{"a-b": 5}'::jsonb, '5'::jsonb), |
| 695 | + ('{"a": 7, "b": 3}', '4')) t(c, e)"#, |
| 696 | + ) |
| 697 | + .expect("SPI query failed"); |
| 698 | + assert_eq!(matched, Some(true)); |
| 699 | + let path = Spi::get_one::<bool>( |
| 723 | 700 | r#"SELECT feel_eval_immutable('x.y', '{"x": {"y": 42}}'::jsonb) = '42'::jsonb"#, |
| 724 | 701 | ) |
| 725 | 702 | .expect("SPI query failed"); |
| 703 | + assert_eq!(path, Some(true)); |
| 704 | + } |
| 705 | + |
| 706 | + #[pg_test] |
| 707 | + fn nested_jsonb_member_with_hyphen() { |
| 708 | + // The path-member probe navigates the lazy jsonb (ADR-48). |
| 709 | + let matched = Spi::get_one::<bool>( |
| 710 | + r#"SELECT feel_eval('applicant.first-name', |
| 711 | + '{"applicant": {"first-name": "Ada"}}'::jsonb) = '"Ada"'::jsonb |
| 712 | + AND feel_eval('orders.unit-price', |
| 713 | + '{"orders": [{"unit-price": 2}, {"unit-price": 3}]}'::jsonb) |
| 714 | + = '[2, 3]'::jsonb"#, |
| 715 | + ) |
| 716 | + .expect("SPI query failed"); |
| 717 | + assert_eq!(matched, Some(true)); |
| 718 | + } |
| 719 | + |
| 720 | + #[pg_test] |
| 721 | + fn path_selection_maps_over_a_jsonb_array() { |
| 722 | + // §10.3.2.5: selection on a list of contexts maps over it. A lazy jsonb |
| 723 | + // array used to answer every key with null. |
| 724 | + let matched = Spi::get_one::<bool>( |
| 725 | + r#"SELECT feel_eval('orders.x', '{"orders": [{"x": 1}, {"x": 2}, 3]}'::jsonb) |
| 726 | + = '[1, 2, null]'::jsonb |
| 727 | + AND feel_eval('o.items.x', '{"o": {"items": [{"x": 1}]}}'::jsonb) |
| 728 | + = '[1]'::jsonb"#, |
| 729 | + ) |
| 730 | + .expect("SPI query failed"); |
| 731 | + assert_eq!(matched, Some(true)); |
| 732 | + } |
| 733 | + |
| 734 | + #[pg_test] |
| 735 | + fn backticks_and_quoted_level() { |
| 736 | + // Backticks at every level; `'quoted'` never resolves unquoted runs. |
| 737 | + let matched = Spi::get_one::<bool>( |
| 738 | + r#"SELECT feel_eval('`Profit and loss`', '{"Profit and loss": 1}'::jsonb) = '1'::jsonb |
| 739 | + AND feel_eval('a-b', '{"a-b": 5, "a": 7, "b": 3}'::jsonb, |
| 740 | + name_resolution => 'quoted') = '4'::jsonb |
| 741 | + AND feel_eval('`a-b`', '{"a-b": 5}'::jsonb, |
| 742 | + name_resolution => 'quoted') = '5'::jsonb"#, |
| 743 | + ) |
| 744 | + .expect("SPI query failed"); |
| 726 | 745 | assert_eq!(matched, Some(true)); |
| 727 | 746 | } |
| 728 | 747 | |
| 729 | 748 | #[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" |
| 749 | + error = "feel_eval: unknown name_resolution 'full' (expected 'symbols' or 'quoted')" |
| 731 | 750 | )] |
| 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). |
| 751 | + fn unknown_name_resolution_is_an_error() { |
| 735 | 752 | let _ = Spi::get_one::<bool>( |
| 736 | | - r#"SELECT feel_eval_immutable('a-b', '{"a-b": 5}'::jsonb) IS NOT NULL"#, |
| 753 | + r#"SELECT feel_eval('1', '{}'::jsonb, name_resolution => 'full') IS NOT NULL"#, |
| 737 | 754 | ); |
| 738 | 755 | } |
| 739 | 756 | } |