diff --git a/conformance/library_test.go b/conformance/library_test.go new file mode 100644 index 0000000..436369f --- /dev/null +++ b/conformance/library_test.go @@ -0,0 +1,302 @@ +package conformance + +import ( + "context" + "fmt" + "sort" + "strings" + "testing" + + expr "cel.dev/expr" + test "cel.dev/expr/conformance/test" + + "github.com/emfga/cel4postgres/internal/oracle" + "github.com/emfga/cel4postgres/internal/testdb" +) + +// The corpus calls a fraction of each extension library, and nothing +// in it calls what cel-go added after the pinned cel-spec release. +// These tests close that gap two ways: overload by overload against +// the oracle's declarations, and case by case for the functions the +// corpus never reaches. + +// knownMissing names every overload the oracle declares and the +// registry deliberately does not, with the reason. The list is +// printed on every run; an entry that gets implemented has to be +// removed, and an overload cel-go adds has to be implemented or +// named here, or TestLibraryOverloads fails. +var knownMissing = map[string]map[string]string{ + "standard": { + "__not_strictly_false__": "deprecated alias of " + + "not_strictly_false; no parser emits it", + }, + "bindings": { + "cel_block_list": "cel.@block is cel-go-internal " + + "(block_ext is skipped)", + }, + "encoders": { + "json_encode_dyn": jsonYAMLReason, + "json_parse_string": jsonYAMLReason, + "json_parse_string_type": jsonYAMLReason, + "yaml_encode_dyn": jsonYAMLReason, + "yaml_parse_string": jsonYAMLReason, + "yaml_parse_string_type": jsonYAMLReason, + }, +} + +const jsonYAMLReason = "json/yaml encoders not implemented " + + "(docs/CONFORMANCE.md)" + +func TestLibraryOverloads(t *testing.T) { + ctx := context.Background() + + conn, err := testdb.Connect(ctx) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + + standard, err := oracle.OverloadIDs("standard") + if err != nil { + t.Fatal(err) + } + + for _, name := range oracle.EnvNames() { + t.Run(name, func(t *testing.T) { + env := "standard," + name + if name == "standard" { + env = name + } + reference, err := oracle.OverloadIDs(env) + if err != nil { + t.Fatal(err) + } + + rows, err := conn.Query(ctx, + "SELECT ref FROM cel.env_item"+ + " WHERE env = $1 AND kind = 'overload'", + name) + if err != nil { + t.Fatal(err) + } + ours := map[string]bool{} + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + t.Fatal(err) + } + ours[id] = true + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + + known := knownMissing[name] + var missing, extra, stale []string + for id := range reference { + // An extension env is compared on what it adds. + if name != "standard" && standard[id] { + continue + } + if ours[id] { + if _, listed := known[id]; listed { + stale = append(stale, id) + } + continue + } + if _, listed := known[id]; !listed { + missing = append(missing, id) + } + } + for id := range ours { + if !reference[id] { + extra = append(extra, id) + } + } + for id := range known { + if !reference[id] { + stale = append(stale, id) + } + } + + for _, id := range sortedKeys(known) { + t.Logf("not implemented: %s %s -- %s", + name, id, known[id]) + } + report := func(what string, ids []string) { + if len(ids) > 0 { + sort.Strings(ids) + t.Errorf("%s: %s", what, strings.Join(ids, ", ")) + } + } + report("cel-go declares, registry lacks "+ + "(implement or add to knownMissing)", missing) + report("registry has, cel-go does not declare", extra) + report("knownMissing entries to remove", stale) + }) + } +} + +func sortedKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// libraryCase is one expression run through cel-go and cel4postgres +// under the same env; cel-go's outcome becomes the expectation. +// want says which outcome cel-go must produce, so a case can never +// pass because both sides rejected an undeclared function. +type libraryCase struct { + expr string + want outcome +} + +type outcome int + +const ( + value outcome = iota // evaluates to a value + evalError // checks, then errors at evaluation + checkError // rejected by the type checker +) + +// libraryCases are keyed by corpus file name, which selects the env +// exactly as it does for that file (EnvFor). +var libraryCases = map[string][]libraryCase{ + "lists_ext": { + {"[].hasOnly([1, 2])", value}, + {"[1, 1, 2].hasOnly([1, 2, 3])", value}, + {"[1, 2.0, 3u].hasOnly([1.0, 2u, 3])", value}, + {"[1, 4].hasOnly([1, 2, 3])", value}, + {"[1].hasOnly([])", value}, + {"[1, 2, 3].hasAny([3, 4])", value}, + {"[[1], [2, 3]].hasAny([[1, 2], [2, 3.0]])", value}, + {"[1, 2].hasAny([3, 4])", value}, + {"[1].hasAny([])", value}, + {"[].hasAny([])", value}, + {"[1, 2, 3].hasAll([])", value}, + {"[1, 2, 3, 4].hasAll([2, 3])", value}, + {"[1, 2.0, 3u].hasAll([1.0, 2u, 3])", value}, + {"[1, 2, 3].hasAll([2, 4])", value}, + {"[].hasExactly([])", value}, + {"[1].hasExactly([1, 1])", value}, + {"[1].hasExactly([1u, 1.0])", value}, + {"[1, 2, 3].hasExactly([3u, 2.0, 1])", value}, + {"[1, 2].hasExactly([1, 2, 3])", value}, + {"[{'a': 1}].hasAll([{'a': 1.0}])", checkError}, + {"[{'a': 1}].hasAll([dyn({'a': 1.0})])", value}, + {"['a', 'b'].hasOnly(['b', 'a', 'c'])", value}, + {"[1].hasAll(['a'])", checkError}, + {"[1].hasAny(1)", checkError}, + {"[1, 2][5] == 1 || [1].hasAll([1])", value}, + {"[1].hasAll([[1, 2][5]])", evalError}, + }, + "encoders_ext": { + {"base64.encodeUrl(b'hello')", value}, + {"base64.encodeUrl(b'\\xff\\xff\\xff')", value}, + {"base64.encodeUrl(b'\\xfb\\xff')", value}, + {"base64.encodeUrl(b'')", value}, + {"base64.decodeUrl('aGVsbG8=')", value}, + {"base64.decodeUrl('aGVsbG8')", value}, + {"base64.decodeUrl('____')", value}, + {"base64.decodeUrl('-_8')", value}, + {"base64.decodeUrl('')", value}, + {"base64.decodeUrl('////')", evalError}, + {"base64.decodeUrl('++++')", evalError}, + {"base64.decodeUrl('a')", evalError}, + {"base64.decodeUrl('!!!!')", evalError}, + {"base64.decodeUrl(base64.encodeUrl(b'\\x00\\xfe\\xff')) " + + "== b'\\x00\\xfe\\xff'", value}, + {"base64.encodeUrl('abc')", checkError}, + }, + "optionals": { + {"optional.of(42).hasValue(42)", value}, + {"optional.of(42).hasValue(21)", value}, + {"optional.none().hasValue(42)", value}, + {"optional.of(42).hasValue(42.0)", checkError}, + {"optional.of(dyn(42)).hasValue(42.0)", value}, + {"optional.of(optional.of(42)).hasValue(optional.of(42))", + value}, + {"optional.of(42).hasValue(dyn(optional.of(42)))", value}, + {"optional.of(42).hasValue(dyn(42))", value}, + {"optional.of([1, 2]).hasValue([1, 2])", value}, + {"{'a': 1}[?'a'].hasValue(1)", value}, + {"{'a': 1}[?'b'].hasValue(1)", value}, + {"[1, 2, 3].first().value()", value}, + {"[1, 2, 3].last().value()", value}, + {"[].first().hasValue()", value}, + {"[].last().hasValue()", value}, + {"[[1]].last().value()", value}, + {"optional.unwrap([optional.of(42), optional.none()])", value}, + {"[optional.of(42), optional.none()].unwrapOpt()", value}, + {"optional.unwrap([])", value}, + {"[optional.none(), optional.none()].unwrapOpt()", value}, + {"optional.unwrap([1])", checkError}, + {"optional.unwrap(dyn([1]))", evalError}, + {"optional.of(1 + 1).optMap(x, x * 2).value()", value}, + {"optional.none().optMap(x, x * 2).hasValue()", value}, + {"[1, 2][?0].optFlatMap(x, [x][?0]).value()", value}, + {"{'k': {}}.?k.optFlatMap(k, k.?sub).hasValue()", value}, + }, +} + +func TestLibraryCases(t *testing.T) { + ctx := context.Background() + + conn, err := testdb.Connect(ctx) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + + stages, err := InstalledStages(ctx, conn) + if err != nil { + t.Fatal(err) + } + + for _, file := range []string{ + "encoders_ext", "lists_ext", "optionals", + } { + for i, lc := range libraryCases[file] { + name := fmt.Sprintf("%s/%02d", file, i) + t.Run(name, func(t *testing.T) { + tc := &test.SimpleTest{Name: name, Expr: lc.expr} + + ref, err := oracle.RunCase(tc, EnvFor(file)) + if err != nil { + t.Fatal(err) + } + + switch { + case lc.want == value && ref.Err == nil: + tc.ResultMatcher = &test.SimpleTest_Value{ + Value: ref.Value, + } + case lc.want == evalError && ref.Err != nil && + ref.Type != nil: + tc.ResultMatcher = &test.SimpleTest_EvalError{ + EvalError: &expr.ErrorSet{}, + } + case lc.want == checkError && ref.Err != nil && + ref.Type == nil: + tc.ResultMatcher = &test.SimpleTest_EvalError{ + EvalError: &expr.ErrorSet{}, + } + tc.CheckOnly = true + default: + t.Fatalf("%s: cel-go outcome does not match the "+ + "case (value %v, type %v, err %v)", + lc.expr, ref.Value, ref.Type, ref.Err) + } + + result := RunCase(ctx, conn, stages, file, "library", tc) + if result.Status != Passed { + t.Fatalf("%s: %s", lc.expr, result.Detail) + } + }) + } + } +} diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d49ad80..fbdb1fa 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -201,6 +201,33 @@ its conformance harness does not run `network_ext` at all — so there is no reference position to weigh here, only the corpus, and the corpus is what cel4postgres implements. +## Library coverage beyond the corpus + +The corpus calls a fraction of each extension library, and nothing in +the pinned release calls what cel-go added since. Two tests close +that gap. `TestLibraryOverloads` compares every overload id the +reference declares in each environment with the registry's rows, +and fails on any it lacks that is not named as known-missing. +`TestLibraryCases` runs the functions the corpus never reaches — +`hasOnly` / `hasAny` / `hasAll` / `hasExactly`, `base64.encodeUrl` / +`decodeUrl`, `optional.hasValue(v)`, `first` / `last` / +`unwrapOpt`, and the single-evaluation `optMap` / `optFlatMap` — +through both implementations, cel-go's outcome as the expectation. + +The libraries run at cel-go's latest versions, with one exception: +**the JSON and YAML encoders are not implemented**, and the +reference holds `encoders` at version 2 so it cannot grow past what +was measured. Missing are `json.encode` (version 1) and `json.parse`, +`yaml.encode` and `yaml.parse` (version 2); both tests print them. +YAML needs a YAML 1.2 parser and emitter, which is not a reasonable +thing to write in PL/pgSQL. `json.parse(s, T)` converts by any CEL +type through cel-go's type provider, and `json.encode` reproduces Go +details — float formatting, HTML-safe escaping, integers quoted past +2^53, protobuf JSON for timestamps and durations — that a port would +match only partly. A half-faithful encoder is worse than an absent +one: a call that fails to type-check is visible, a subtly different +string is not. + ## Divergences the corpus does not cover Three behaviours differ from cel-go without a corpus case to record diff --git a/internal/oracle/options.go b/internal/oracle/options.go index 6f88063..dbaba34 100644 --- a/internal/oracle/options.go +++ b/internal/oracle/options.go @@ -2,6 +2,7 @@ package oracle import ( "fmt" + "sort" "strings" "cel.dev/cel-go/cel" @@ -24,27 +25,34 @@ var envOptions = map[string][]cel.EnvOption{ cel.CrossTypeNumericComparisons(true), cel.EnableErrorOnBadPresenceTest(true), }, - // Libraries whose latest version declares functions sql/ does - // not register are pinned to the version it implements: an - // unversioned library widens the reference env on every cel-go - // bump, and an oracle that knows overloads the evaluator lacks - // is configured differently from it. Lists 5 adds hasOnly / - // hasAny / hasAll / hasExactly; encoders 2 adds - // base64.encodeUrl / decodeUrl and json / yaml; optionals 3 - // adds optional.hasValue(v) and 4 re-expands optMap / - // optFlatMap (both cel-go v0.33.0). + // Every library runs at its latest version, as cel4postgres + // implements it, except encoders: its version 2 adds json.parse + // and yaml.encode / yaml.parse, which sql/ does not implement + // (docs/CONFORMANCE.md), so it is held at 2 rather than left to + // grow on the next cel-go bump. TestLibraryOverloads names what + // each env lacks against this configuration. "strings": {ext.Strings()}, "math": {ext.Math()}, - "lists": {ext.Lists(ext.ListsVersion(4))}, - "encoders": {ext.Encoders(ext.EncodersVersion(1))}, + "lists": {ext.Lists()}, + "encoders": {ext.Encoders(ext.EncodersVersion(2))}, "bindings": {ext.Bindings()}, "optionals": { - cel.OptionalTypes(cel.OptionalTypesVersion(2)), + cel.OptionalTypes(), }, "two_var_comprehensions": {ext.TwoVarComprehensions()}, "network": {ext.Network()}, } +// EnvNames returns every env name the oracle can configure, sorted. +func EnvNames() []string { + names := make([]string, 0, len(envOptions)) + for name := range envOptions { + names = append(names, name) + } + sort.Strings(names) + return names +} + // Options resolves a comma-separated env-name union -- the same string // cel.parse/check/eval take -- to cel-go options, so a disputed case // runs against the reference under the same environment composition @@ -62,3 +70,26 @@ func Options(env string) ([]cel.EnvOption, error) { } return options, nil } + +// OverloadIDs returns the overload ids a comma-separated env union +// declares in cel-go, so the registry can be checked against the +// reference overload for overload, not only case by case: the +// corpus exercises a fraction of each library, and a function it +// never calls would otherwise go missing unnoticed. +func OverloadIDs(env string) (map[string]bool, error) { + options, err := Options(env) + if err != nil { + return nil, err + } + celEnv, err := Env(options...) + if err != nil { + return nil, err + } + ids := map[string]bool{} + for _, fn := range celEnv.Functions() { + for _, o := range fn.OverloadDecls() { + ids[o.ID()] = true + } + } + return ids, nil +} diff --git a/scripts/upgrade-check.sh b/scripts/upgrade-check.sh index ba91425..5a6fd9e 100755 --- a/scripts/upgrade-check.sh +++ b/scripts/upgrade-check.sh @@ -162,4 +162,14 @@ expect "SELECT count(*) FROM cel.overload WHERE id = 'consumer_shout_string'" 1 expect "$probe" "$want" +# Nothing the upgrade did not ship into standard may end up there: +# not the consumer's overload, and not an extension's items. +expect "SELECT count(*) FROM cel.env_item + WHERE env = 'standard' AND ref = 'consumer_shout_string'" 0 +expect "SELECT count(*) FROM cel.env_item s + WHERE s.env = 'standard' AND EXISTS ( + SELECT FROM cel.env_item o + WHERE o.kind = s.kind AND o.ref = s.ref + AND o.env <> 'standard')" 0 + echo "upgraded $prev -> $head; consumer registration intact" diff --git a/sql/010_registry.sql b/sql/010_registry.sql index 3d091c4..5f179cc 100644 --- a/sql/010_registry.sql +++ b/sql/010_registry.sql @@ -157,6 +157,45 @@ AS $$ ); $$; +-- The core scripts put "everything registered so far" into the +-- standard env. On a fresh install that is exactly the core: the +-- extension scripts run later. Run again over an installed schema -- +-- which is what an upgrade is -- the same sweep would also catch +-- every extension row and every consumer row, enabling them in +-- standard. A row is only swept when no env claims it yet and, if it +-- has an implementation, that implementation lives in the cel +-- schema. +CREATE OR REPLACE FUNCTION cel._unclaimed(kind text, ref text, + impl regprocedure) +RETURNS boolean +LANGUAGE sql +STABLE +SET search_path = cel, pg_temp +AS $$ + SELECT NOT EXISTS ( + SELECT FROM cel.env_item i + WHERE i.kind = _unclaimed.kind AND i.ref = _unclaimed.ref + ) + AND (impl IS NULL + OR (SELECT pronamespace FROM pg_proc WHERE oid = impl) + = 'cel'::regnamespace); +$$; + +-- Repair for schemas reinstalled before that guard existed (0.0.2 +-- and earlier): drop from standard what a shipped extension env +-- also lists. On a fresh install nothing matches -- no shipped item +-- is in two envs. A consumer row swept the same way cannot be told +-- apart from one put in standard on purpose, so it stays. +DELETE FROM cel.env_item s +WHERE s.env = 'standard' + AND EXISTS ( + SELECT FROM cel.env_item o + WHERE o.kind = s.kind AND o.ref = s.ref + AND o.env IN ('strings', 'math', 'lists', 'encoders', + 'bindings', 'two_var_comprehensions', + 'optionals', 'network') + ); + -- The spec-conformant default environment. Its items are seeded by -- the scripts that create the functions they reference. The -- identifier-escape syntax (`a-b`) is part of standard parsing diff --git a/sql/030_parse.sql b/sql/030_parse.sql index 9e18dcd..a3c981c 100644 --- a/sql/030_parse.sql +++ b/sql/030_parse.sql @@ -2091,6 +2091,8 @@ ON CONFLICT (name, arity, member) DO UPDATE SET expander = excluded.expander; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'macro', format('%s/%s/%s', name, arity, member::int) FROM cel.macro +WHERE cel._unclaimed('macro', + format('%s/%s/%s', name, arity, member::int), expander) ON CONFLICT DO NOTHING; -- Parses CEL source under an environment. Returns the AST envelope, diff --git a/sql/060_stdlib.sql b/sql/060_stdlib.sql index 8e8715b..59352d3 100644 --- a/sql/060_stdlib.sql +++ b/sql/060_stdlib.sql @@ -790,10 +790,12 @@ ON CONFLICT (name) DO NOTHING; -- Everything above is visible in the standard env. INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'type', name FROM cel.type +WHERE cel._unclaimed('type', name, NULL) ON CONFLICT DO NOTHING; -- Part 2: type conversions and string functions. Conversion @@ -1270,4 +1272,5 @@ ON CONFLICT (id) DO UPDATE SET INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING; diff --git a/sql/070_wkt.sql b/sql/070_wkt.sql index e598a7e..19c89be 100644 --- a/sql/070_wkt.sql +++ b/sql/070_wkt.sql @@ -870,8 +870,10 @@ ON CONFLICT (id) DO UPDATE SET INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'type', name FROM cel.type WHERE name LIKE 'google.protobuf.%' + AND cel._unclaimed('type', name, NULL) ON CONFLICT DO NOTHING; INSERT INTO cel.env_item (env, kind, ref) SELECT 'standard', 'overload', id FROM cel.overload +WHERE cel._unclaimed('overload', id, impl) ON CONFLICT DO NOTHING; diff --git a/sql/110_ext_optionals.sql b/sql/110_ext_optionals.sql index 34a7763..ca6b56b 100644 --- a/sql/110_ext_optionals.sql +++ b/sql/110_ext_optionals.sql @@ -1,9 +1,9 @@ -- The optionals extension, part one: the optional_type opaque type -- and the optional.of / optional.ofNonZeroValue / optional.none / -- value / hasValue functions (cel-go cel/library.go optionals, pinned --- v0.32.0). Part two, further down, adds the optional-syntax sugar --- (x.?f, [?x], {?k: v}), or / orValue, and the optMap/optFlatMap --- macros. +-- v0.33.1, library version 4). Part two, further down, adds the +-- optional-syntax sugar (x.?f, [?x], {?k: v}), or / orValue, and the +-- optMap/optFlatMap macros. -- -- An optional value is the opaque -- {"@t": "opaque", "type": "optional_type", "v": @@ -151,6 +151,130 @@ INSERT INTO cel.env_item (env, kind, ref) VALUES ('optionals', 'overload', 'optional_hasValue') ON CONFLICT DO NOTHING; +-- opt.hasValue(v) (library version 3): whether the optional holds a +-- value equal to v, i.e. opt.hasValue() ? opt.value() == v : false. +-- v is compared as it is and never unwrapped, so +-- optional.of(42).hasValue(dyn(optional.of(42))) is false. +CREATE OR REPLACE FUNCTION cel._f_opt_has_value_value(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT cel._bool_val((args[1] -> 'v' ->> 'p')::boolean + AND cel._equal(args[1] -> 'v' -> 'v', args[2])); +$$; + +INSERT INTO cel.overload + (id, function, member, arg_types, result_type, impl, ordinal) +VALUES + ('optional_hasValue_value', 'hasValue', true, + '[{"kind": "opaque", "name": "optional_type", + "params": [{"kind": "param", "name": "V"}]}, + {"kind": "param", "name": "V"}]', + '{"kind": "bool"}', + 'cel._f_opt_has_value_value(jsonb[])', 20) +ON CONFLICT (id) DO UPDATE SET + function = excluded.function, + member = excluded.member, + arg_types = excluded.arg_types, + result_type = excluded.result_type, + impl = excluded.impl, + ordinal = excluded.ordinal; + +INSERT INTO cel.env_item (env, kind, ref) VALUES + ('optionals', 'overload', 'optional_hasValue_value') +ON CONFLICT DO NOTHING; + +-- List helpers (library version 2): first() / last() lift the end +-- elements of a list into optionals, and optional.unwrap(l) / +-- l.unwrapOpt() keep the values of the present optionals in l. +CREATE OR REPLACE FUNCTION cel._f_list_first(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT CASE WHEN jsonb_array_length(args[1] -> 'v') = 0 + THEN cel._opt_none() + ELSE cel._opt_of(args[1] -> 'v' -> 0) END; +$$; + +CREATE OR REPLACE FUNCTION cel._f_list_last(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT CASE WHEN jsonb_array_length(args[1] -> 'v') = 0 + THEN cel._opt_none() + ELSE cel._opt_of(args[1] -> 'v' -> -1) END; +$$; + +-- An element that is not an optional can only arrive through dyn; +-- it is an error, not something to skip. +CREATE OR REPLACE FUNCTION cel._f_opt_unwrap(args jsonb[]) +RETURNS jsonb +LANGUAGE plpgsql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ +DECLARE + e jsonb; + o jsonb := '[]'::jsonb; +BEGIN + FOR e IN SELECT x FROM jsonb_array_elements(args[1] -> 'v') x LOOP + IF e ->> '@t' <> 'opaque' OR e ->> 'type' <> 'optional_type' THEN + RETURN cel._err(format('value %s is not optional', e ->> 'v')); + END IF; + IF (e -> 'v' ->> 'p')::boolean THEN + o := o || jsonb_build_array(e -> 'v' -> 'v'); + END IF; + END LOOP; + RETURN jsonb_build_object('@t', 'list', 'v', o); +END; +$$; + +INSERT INTO cel.overload + (id, function, member, arg_types, result_type, impl, ordinal) +VALUES + ('list_last', 'last', true, + '[{"kind": "list", "params": [{"kind": "param", "name": "V"}]}]', + '{"kind": "opaque", "name": "optional_type", + "params": [{"kind": "param", "name": "V"}]}', + 'cel._f_list_last(jsonb[])', 10), + ('list_first', 'first', true, + '[{"kind": "list", "params": [{"kind": "param", "name": "V"}]}]', + '{"kind": "opaque", "name": "optional_type", + "params": [{"kind": "param", "name": "V"}]}', + 'cel._f_list_first(jsonb[])', 10), + ('optional_unwrap', 'optional.unwrap', false, + '[{"kind": "list", "params": [{"kind": "opaque", + "name": "optional_type", + "params": [{"kind": "param", "name": "V"}]}]}]', + '{"kind": "list", "params": [{"kind": "param", "name": "V"}]}', + 'cel._f_opt_unwrap(jsonb[])', 10), + ('optional_unwrapOpt', 'unwrapOpt', true, + '[{"kind": "list", "params": [{"kind": "opaque", + "name": "optional_type", + "params": [{"kind": "param", "name": "V"}]}]}]', + '{"kind": "list", "params": [{"kind": "param", "name": "V"}]}', + 'cel._f_opt_unwrap(jsonb[])', 10) +ON CONFLICT (id) DO UPDATE SET + function = excluded.function, + member = excluded.member, + arg_types = excluded.arg_types, + result_type = excluded.result_type, + impl = excluded.impl, + ordinal = excluded.ordinal; + +INSERT INTO cel.env_item (env, kind, ref) VALUES + ('optionals', 'overload', 'list_last'), + ('optionals', 'overload', 'list_first'), + ('optionals', 'overload', 'optional_unwrap'), + ('optionals', 'overload', 'optional_unwrapOpt') +ON CONFLICT DO NOTHING; + -- Part two: the optional-syntax operators, or/orValue, and the -- optMap/optFlatMap macros (cel/library.go optionals block, -- cel/library.go:430-560 at the pinned v0.32.0). @@ -264,7 +388,9 @@ AS $$ THEN args[1] -> 'v' -> 'v' ELSE args[2] END; $$; --- optMap / optFlatMap (cel/library.go optMap/optFlatMap): expand to +-- optMap / optFlatMap (cel/library.go optMapV2/optFlatMapV2, the +-- library-version-4 expansion that evaluates the target once): expand +-- to -- target.hasValue() -- ? (bind(v, target.value(), expr)) -- : optional.none() diff --git a/sql/140_ext_lists.sql b/sql/140_ext_lists.sql index b3e0c5d..1151405 100644 --- a/sql/140_ext_lists.sql +++ b/sql/140_ext_lists.sql @@ -1,6 +1,8 @@ --- The lists extension (cel-go ext/lists.go at the pinned v0.32.0): --- slice, flatten, sort, sortBy (macro over @sortByAssociatedKeys), --- lists.range, reverse, distinct. Registered under the 'lists' env. +-- The lists extension (cel-go ext/lists.go at the pinned v0.33.1, +-- library version 5): slice, flatten, sort, sortBy (macro over +-- @sortByAssociatedKeys), lists.range, reverse, distinct, and the +-- membership tests hasOnly / hasAny / hasAll / hasExactly. +-- Registered under the 'lists' env. CREATE OR REPLACE FUNCTION cel._list_val(elems jsonb) RETURNS jsonb @@ -406,3 +408,99 @@ ON CONFLICT DO NOTHING; INSERT INTO cel.env_item (env, kind, ref) VALUES ('lists', 'macro', 'sortBy/2/1') ON CONFLICT DO NOTHING; + +-- Membership tests (library version 5). Each compares elements with +-- CEL equality, so [1, 2.0, 3u].hasAll([1.0, 2u, 3]) holds, and +-- treats both lists as sets: duplicates and sizes do not matter. +-- +-- a.hasOnly(b) every element of a is in b (a subset of b) +-- a.hasAll(b) every element of b is in a (a superset of b) +-- a.hasAny(b) some element of a is in b (false if empty) +-- a.hasExactly(b) both of the above (set-equal) + +-- Whether every element of needles has an equal in haystack. +CREATE OR REPLACE FUNCTION cel._list_covers(haystack jsonb, + needles jsonb) +RETURNS boolean +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT NOT EXISTS ( + SELECT FROM jsonb_array_elements(needles) n + WHERE NOT EXISTS ( + SELECT FROM jsonb_array_elements(haystack) h + WHERE cel._equal(n, h) + ) + ); +$$; + +CREATE OR REPLACE FUNCTION cel._f_list_has_only(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT cel._bool_val(cel._list_covers(args[2] -> 'v', args[1] -> 'v')); +$$; + +CREATE OR REPLACE FUNCTION cel._f_list_has_all(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT cel._bool_val(cel._list_covers(args[1] -> 'v', args[2] -> 'v')); +$$; + +CREATE OR REPLACE FUNCTION cel._f_list_has_exactly(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT cel._bool_val( + cel._list_covers(args[1] -> 'v', args[2] -> 'v') + AND cel._list_covers(args[2] -> 'v', args[1] -> 'v')); +$$; + +CREATE OR REPLACE FUNCTION cel._f_list_has_any(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT cel._bool_val(EXISTS ( + SELECT FROM jsonb_array_elements(args[1] -> 'v') a, + jsonb_array_elements(args[2] -> 'v') b + WHERE cel._equal(a, b) + )); +$$; + +INSERT INTO cel.overload + (id, function, member, arg_types, result_type, impl, ordinal) +SELECT 'list_' || f || '_list', f, true, + '[{"kind": "list", "params": [{"kind": "param", "name": "T"}]}, + {"kind": "list", "params": [{"kind": "param", "name": "T"}]}]', + '{"kind": "bool"}', + impl::regprocedure, 10 +FROM (VALUES + ('hasOnly', 'cel._f_list_has_only(jsonb[])'), + ('hasAny', 'cel._f_list_has_any(jsonb[])'), + ('hasAll', 'cel._f_list_has_all(jsonb[])'), + ('hasExactly', 'cel._f_list_has_exactly(jsonb[])') +) v(f, impl) +ON CONFLICT (id) DO UPDATE SET + function = excluded.function, + member = excluded.member, + arg_types = excluded.arg_types, + result_type = excluded.result_type, + impl = excluded.impl, + ordinal = excluded.ordinal; + +INSERT INTO cel.env_item (env, kind, ref) VALUES + ('lists', 'overload', 'list_hasOnly_list'), + ('lists', 'overload', 'list_hasAny_list'), + ('lists', 'overload', 'list_hasAll_list'), + ('lists', 'overload', 'list_hasExactly_list') +ON CONFLICT DO NOTHING; diff --git a/sql/150_ext_encoders.sql b/sql/150_ext_encoders.sql index 0994608..6085146 100644 --- a/sql/150_ext_encoders.sql +++ b/sql/150_ext_encoders.sql @@ -1,6 +1,11 @@ -- The encoders extension (cel-go ext/encoders.go at the pinned --- v0.32.0): base64.encode / base64.decode. Registered under the --- 'encoders' env. +-- v0.33.1): base64.encode / base64.decode, and from library version +-- 2 their URL-safe twins base64.encodeUrl / base64.decodeUrl. +-- Registered under the 'encoders' env. +-- +-- Not implemented: json.encode (version 1) and json.parse, +-- yaml.encode, yaml.parse (version 2). docs/CONFORMANCE.md says why, +-- and conformance/library_test.go names them as known-missing. -- Go accepts both padded and raw (unpadded) standard base64 -- (encoders.go:143-150); Postgres decode requires padding, so pad @@ -37,6 +42,45 @@ AS $$ E'\n', '')); $$; +-- The URL-safe alphabet (RFC 4648 section 5) swaps '+' and '/' for +-- '-' and '_'. Postgres decode() knows only the standard alphabet, so +-- translate in both directions; a standard-only character in the +-- input is invalid here, as it is in Go's URLEncoding. Like +-- base64.decode, padded and unpadded input are both accepted. +CREATE OR REPLACE FUNCTION cel._f_base64_decode_url(args jsonb[]) +RETURNS jsonb +LANGUAGE plpgsql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ +DECLARE + s text := args[1] ->> 'v'; +BEGIN + IF s ~ '[+/]' THEN + RAISE 'not base64url'; + END IF; + s := translate(s, '-_', '+/'); + IF length(s) % 4 <> 0 THEN + s := rpad(s, length(s) + 4 - length(s) % 4, '='); + END IF; + RETURN jsonb_build_object('@t', 'bytes', 'v', + translate(encode(decode(s, 'base64'), 'base64'), E'\n', '')); +EXCEPTION WHEN OTHERS THEN + RETURN cel._err(format('illegal base64 data in %s', + quote_literal(args[1] ->> 'v'))); +END; +$$; + +CREATE OR REPLACE FUNCTION cel._f_base64_encode_url(args jsonb[]) +RETURNS jsonb +LANGUAGE sql +IMMUTABLE PARALLEL SAFE +SET search_path = cel, pg_temp +AS $$ + SELECT jsonb_build_object('@t', 'string', 'v', + translate(args[1] ->> 'v', '+/', '-_')); +$$; + INSERT INTO cel.overload (id, function, member, arg_types, result_type, impl, ordinal) VALUES @@ -45,7 +89,13 @@ VALUES 'cel._f_base64_decode(jsonb[])', 10), ('base64_encode_bytes', 'base64.encode', false, '[{"kind": "bytes"}]', '{"kind": "string"}', - 'cel._f_base64_encode(jsonb[])', 10) + 'cel._f_base64_encode(jsonb[])', 10), + ('base64_decode_url_string', 'base64.decodeUrl', false, + '[{"kind": "string"}]', '{"kind": "bytes"}', + 'cel._f_base64_decode_url(jsonb[])', 10), + ('base64_encode_url_bytes', 'base64.encodeUrl', false, + '[{"kind": "bytes"}]', '{"kind": "string"}', + 'cel._f_base64_encode_url(jsonb[])', 10) ON CONFLICT (id) DO UPDATE SET function = excluded.function, member = excluded.member, @@ -56,5 +106,7 @@ ON CONFLICT (id) DO UPDATE SET INSERT INTO cel.env_item (env, kind, ref) VALUES ('encoders', 'overload', 'base64_decode_string'), - ('encoders', 'overload', 'base64_encode_bytes') + ('encoders', 'overload', 'base64_encode_bytes'), + ('encoders', 'overload', 'base64_decode_url_string'), + ('encoders', 'overload', 'base64_encode_url_bytes') ON CONFLICT DO NOTHING;