-- Copyright 2026 Manuel Reyes Bravo -- SPDX-License-Identifier: Apache-2.0 -- pg_grammar_guard 0.4.10 -> 0.5.0 -- -- * Whitespace between tokens is bounded the way llama.cpp's own JSON -- grammar bounds it (grammars/json.gbnf): nothing, one space, or a newline -- and up to 20 spaces or tabs. `ws ::= [ \t\n]*` let a model emit spaces -- until it ran out of budget, every one of them legal. Only the grammar -- text changes; fingerprints are taken over the spec, so no watch reads -- broken. -- * USAGE on the grammar_guard schema is granted to PUBLIC. Every function -- was already executable by PUBLIC, but a role nobody had granted USAGE -- got "permission denied for schema grammar_guard". The functions read -- only the catalog; watch() still needs rights on living_assertions. -- * A new install script, pg_grammar_guard--0.5.0.sql, with the comments -- rewritten: shorter, saying what and why, without figures that have no -- record. This script replaces every function and comment with that -- text, so an upgraded installation is identical to a fresh one. Apart -- from the whitespace, the functions do what they did in 0.4.10. -- * The comment on the extension says what problem it solves. \echo Use "ALTER EXTENSION pg_grammar_guard UPDATE TO '0.5.0'" to load this file. \quit GRANT USAGE ON SCHEMA grammar_guard TO PUBLIC; CREATE OR REPLACE FUNCTION grammar_guard.catalog_tables(p_schemas text[] DEFAULT NULL) RETURNS text[] LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$ -- Quoted, so "Customers" is not read back as customers. Ordered, so the -- same tables are the same list. Temporary schemas are left out: another -- session's temporary table is not part of the database a model writes -- against. SELECT coalesce(array_agg(format('%I.%I', n.nspname, c.relname) ORDER BY n.nspname, c.relname), '{}') FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f') AND n.nspname <> ALL (ARRAY['pg_catalog', 'information_schema']) AND n.nspname NOT LIKE 'pg\_toast%' AND n.nspname NOT LIKE 'pg\_temp\_%' AND (p_schemas IS NULL OR n.nspname = ANY (p_schemas)); $$; CREATE OR REPLACE FUNCTION grammar_guard.catalog_columns(p_table regclass) RETURNS text[] LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$ -- attname is a name; PostgreSQL 12 and older will not return a name[] -- where text[] is declared, hence the cast. SELECT coalesce(array_agg(a.attname::text ORDER BY a.attnum), '{}') FROM pg_attribute a WHERE a.attrelid = p_table AND a.attnum > 0 AND NOT a.attisdropped; $$; CREATE OR REPLACE FUNCTION grammar_guard.catalog_enum(p_type regtype) RETURNS text[] LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$ SELECT coalesce(array_agg(e.enumlabel::text ORDER BY e.enumsortorder), '{}') FROM pg_enum e WHERE e.enumtypid = p_type; $$; CREATE OR REPLACE FUNCTION grammar_guard.gbnf_literal(p_value text) RETURNS text LANGUAGE sql IMMUTABLE STRICT SET search_path = pg_catalog, pg_temp AS $$ -- Backslashes first: escaping the quotes first would double the -- backslashes added for them. SELECT '"' || replace(replace(p_value, '\', '\\'), '"', '\"') || '"'; $$; CREATE OR REPLACE FUNCTION grammar_guard.json_string_literal(p_value text) RETURNS text LANGUAGE sql IMMUTABLE STRICT SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ -- to_json quotes the value as JSON, control characters included; -- gbnf_literal then quotes that for GBNF. SELECT gbnf_literal(to_json(p_value)::text); $$; CREATE OR REPLACE FUNCTION grammar_guard.rule_name(p_field text, p_ordinal int) RETURNS text LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$ -- GBNF rule names take letters, digits and dashes. The ordinal keeps -- "a.b" and "a-b" from becoming one rule with one set of values. SELECT 'f' || p_ordinal::text || '-' || coalesce(nullif(regexp_replace(lower(p_field), '[^a-z0-9]+', '-', 'g'), ''), 'x'); $$; CREATE OR REPLACE FUNCTION grammar_guard.grammar_for_json(p_fields grammar_guard.grammar_field[], p_dialect text DEFAULT 'gbnf') RETURNS text LANGUAGE plpgsql STABLE SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ DECLARE f grammar_field; i int := 0; n_required int := 0; rname text; body text := ''; rules text := ''; alts text; v text; needs_scalar boolean := false; props jsonb := '{}'::jsonb; req jsonb := '[]'::jsonb; BEGIN IF p_fields IS NULL OR cardinality(p_fields) = 0 THEN RAISE EXCEPTION 'no fields given' USING HINT = 'grammar_for_json needs at least one field to constrain.'; END IF; IF p_dialect IS NULL OR p_dialect NOT IN ('gbnf', 'json_schema') THEN RAISE EXCEPTION 'unknown dialect: %', p_dialect USING HINT = 'Supported dialects are gbnf (llama.cpp) and json_schema.'; END IF; FOREACH f IN ARRAY p_fields LOOP IF f.name IS NULL OR f.name = '' THEN RAISE EXCEPTION 'a field has no name'; END IF; IF f.kind IS NULL OR f.kind NOT IN ('enum', 'string', 'integer', 'number', 'boolean') THEN RAISE EXCEPTION 'field %: unknown kind %', f.name, coalesce(f.kind, ''); END IF; -- A rule with no alternatives matches nothing: the model could not -- finish the object. IF f.kind = 'enum' AND (f.values IS NULL OR cardinality(f.values) = 0) THEN RAISE EXCEPTION 'field %: enum with no values', f.name USING HINT = 'The query that fills this enum returned no rows. ' 'An empty enum cannot be satisfied.'; END IF; -- A NULL value would make the whole grammar NULL, which a client -- reads as "no constraint". IF f.kind = 'enum' AND array_position(f.values, NULL) IS NOT NULL THEN RAISE EXCEPTION 'field %: an enum value is NULL', f.name; END IF; IF coalesce(f.required, false) THEN n_required := n_required + 1; END IF; END LOOP; IF (SELECT count(DISTINCT x.name) FROM unnest(p_fields) x) < cardinality(p_fields) THEN RAISE EXCEPTION 'two fields with the same name' USING HINT = 'A JSON object with a key twice is read as the last one.'; END IF; IF p_dialect = 'gbnf' THEN -- With every field optional, each one may or may not need a leading -- comma; a required field gives the commas a fixed place. IF n_required = 0 THEN RAISE EXCEPTION 'every field is optional' USING HINT = 'GBNF needs at least one required field to anchor ' 'the commas. Mark the field you always want as required.'; END IF; -- Required fields first, in the given order, then the optional ones: -- the key order is fixed. body := '"{" ws'; FOR i IN 1 .. cardinality(p_fields) LOOP f := p_fields[i]; CONTINUE WHEN NOT coalesce(f.required, false); rname := rule_name(f.name, i); IF body <> '"{" ws' THEN body := body || ' "," ws'; END IF; body := body || ' ' || gbnf_literal(to_json(f.name)::text) || ' ws ":" ws ' || rname || ' ws'; END LOOP; FOR i IN 1 .. cardinality(p_fields) LOOP f := p_fields[i]; CONTINUE WHEN coalesce(f.required, false); rname := rule_name(f.name, i); body := body || ' ( "," ws ' || gbnf_literal(to_json(f.name)::text) || ' ws ":" ws ' || rname || ' ws )?'; END LOOP; body := body || ' "}"'; FOR i IN 1 .. cardinality(p_fields) LOOP f := p_fields[i]; rname := rule_name(f.name, i); IF f.kind = 'enum' THEN SELECT string_agg(json_string_literal(x), ' | ' ORDER BY o) INTO alts FROM unnest(f.values) WITH ORDINALITY AS t(x, o); rules := rules || rname || ' ::= ' || alts || E'\n'; ELSE needs_scalar := true; rules := rules || rname || ' ::= ' || f.kind || E'\n'; END IF; END LOOP; rules := 'root ::= ' || body || E'\n' || rules; IF needs_scalar THEN rules := rules || E'string ::= "\\"" char* "\\""\n' || E'char ::= [^"\\\\\\x00-\\x1F] | "\\\\" (["\\\\/bfnrt] | "u" hex hex hex hex)\n' || E'hex ::= [0-9a-fA-F]\n' || E'integer ::= "-"? ("0" | [1-9] [0-9]*)\n' || E'number ::= integer ("." [0-9]+)? ([eE] [-+]? [0-9]+)?\n' || E'boolean ::= "true" | "false"\n'; END IF; -- Bounded as in llama.cpp's grammars/json.gbnf: unbounded whitespace -- lets a model emit spaces until it runs out of budget. rules := rules || E'ws ::= | " " | "\\n" [ \\t]{0,20}\n'; RETURN rules; END IF; -- json_schema: the same values, but checked by a validator after the -- model has written them, not while it writes. FOR i IN 1 .. cardinality(p_fields) LOOP f := p_fields[i]; IF f.kind = 'enum' THEN props := props || jsonb_build_object(f.name, jsonb_build_object('type', 'string', 'enum', to_jsonb(f.values))); ELSIF f.kind = 'integer' THEN props := props || jsonb_build_object(f.name, jsonb_build_object('type', 'integer')); ELSIF f.kind = 'number' THEN props := props || jsonb_build_object(f.name, jsonb_build_object('type', 'number')); ELSIF f.kind = 'boolean' THEN props := props || jsonb_build_object(f.name, jsonb_build_object('type', 'boolean')); ELSE props := props || jsonb_build_object(f.name, jsonb_build_object('type', 'string')); END IF; IF coalesce(f.required, false) THEN req := req || to_jsonb(f.name); END IF; END LOOP; RETURN jsonb_pretty(jsonb_build_object( 'type', 'object', 'properties', props, 'required', req, 'additionalProperties', false)); END; $$; CREATE OR REPLACE FUNCTION grammar_guard.grammar_fingerprint(p_fields grammar_guard.grammar_field[]) RETURNS text LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$ -- Over the fields, not the generated text, so both dialects of the same -- fields share a fingerprint. Over their JSON, not a concatenation, so a -- separator inside a value or a NULL cannot make two lists collide. -- Enum values count in their order; a NULL required counts as false. SELECT md5(to_jsonb(ARRAY( SELECT ROW(f.name, f.kind, f.values, coalesce(f.required, false)) FROM unnest(p_fields) WITH ORDINALITY AS f(name, kind, values, required, ord) ORDER BY f.ord))::text); $$; CREATE OR REPLACE FUNCTION grammar_guard._rules(p_field jsonb, p_id text) RETURNS text LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ DECLARE kind text := p_field ->> 'kind'; field_name text := coalesce(p_field ->> 'name', '?'); rules text := ''; alts text := ''; body text := ''; v text; sub jsonb; rid text; i int := 0; n_req int := 0; item_max int; item_min int; pivot int; BEGIN IF kind IS NULL THEN RAISE EXCEPTION 'field %: no kind', field_name; END IF; IF kind = 'enum' THEN -- A rule with no alternatives matches nothing: the model could not -- finish the object. IF p_field -> 'values' IS NULL OR jsonb_typeof(p_field -> 'values') <> 'array' OR jsonb_array_length(p_field -> 'values') = 0 THEN RAISE EXCEPTION 'field %: enum with no values', field_name USING HINT = 'The query that fills this enum returned no rows.'; END IF; -- A NULL would make the whole grammar NULL, which a client reads as -- "no constraint"; a number would be quoted as if it were a string. IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_field -> 'values') x WHERE jsonb_typeof(x) <> 'string') THEN RAISE EXCEPTION 'field %: enum values must be strings, and none NULL', field_name; END IF; SELECT string_agg(json_string_literal(x), ' | ' ORDER BY o) INTO alts FROM jsonb_array_elements_text(p_field -> 'values') WITH ORDINALITY AS t(x, o); RETURN p_id || ' ::= ' || alts || E'\n'; END IF; -- Arrays always have an upper bound: without one a model can repeat a -- legal item until it runs out of budget. 32 by default, at most 1000. -- min_items defaults to 1; 0 allows the empty list. IF kind = 'array' THEN sub := p_field -> 'items'; IF sub IS NULL THEN RAISE EXCEPTION 'field %: array without items', field_name USING HINT = 'Give items a kind, e.g. {"kind": "enum", "values": [...]}.'; END IF; IF (p_field ->> 'max_items') !~ '^[0-9]+$' OR (p_field ->> 'min_items') !~ '^[0-9]+$' THEN RAISE EXCEPTION 'field %: max_items and min_items must be whole numbers', field_name; END IF; item_max := coalesce((p_field ->> 'max_items')::int, 32); IF item_max < 1 OR item_max > 1000 THEN RAISE EXCEPTION 'field %: max_items must be between 1 and 1000', field_name; END IF; item_min := coalesce((p_field ->> 'min_items')::int, 1); IF item_min < 0 OR item_min > item_max THEN RAISE EXCEPTION 'field %: min_items must be between 0 and max_items', field_name; END IF; rid := p_id || '-i'; IF item_min = 0 THEN rules := p_id || ' ::= "[" ws ( ' || rid || ' (ws "," ws ' || rid || '){0,' || (item_max - 1)::text || '} ws )? "]"' || E'\n'; ELSE rules := p_id || ' ::= "[" ws ' || rid || ' (ws "," ws ' || rid || '){' || (item_min - 1)::text || ',' || (item_max - 1)::text || '} ws "]"' || E'\n'; END IF; RETURN rules || _rules(sub, rid); END IF; -- An object compiles its fields the way the root does: the root is an -- object too. IF kind = 'object' THEN IF p_field -> 'fields' IS NULL OR jsonb_array_length(p_field -> 'fields') = 0 THEN RAISE EXCEPTION 'field %: object with no fields', field_name; END IF; -- A key twice is read as the last one; a field without a name would -- make the grammar NULL. IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_field -> 'fields') f WHERE jsonb_typeof(f -> 'name') IS DISTINCT FROM 'string' OR f ->> 'name' = '') THEN RAISE EXCEPTION 'field %: every subfield needs a non-empty name', field_name; END IF; IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_field -> 'fields') f GROUP BY f ->> 'name' HAVING count(*) > 1) THEN RAISE EXCEPTION 'field %: two subfields with the same name', field_name; END IF; IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_field -> 'fields') f WHERE f ? 'required' AND jsonb_typeof(f -> 'required') <> 'boolean') THEN RAISE EXCEPTION 'field %: required must be true or false', field_name; END IF; -- A field with dependents is a pivot: the values of the dependents -- depend on the value chosen for it (see _correlated). Two pivots -- would need one alternative per combination of their values. FOR i IN 0 .. jsonb_array_length(p_field -> 'fields') - 1 LOOP IF (p_field -> 'fields' -> i) ? 'dependents' THEN IF pivot IS NOT NULL THEN RAISE EXCEPTION 'field %: two correlated fields in one object', field_name USING HINT = 'Only one field per object may carry dependents.'; END IF; pivot := i; END IF; END LOOP; IF pivot IS NOT NULL THEN RETURN _correlated(p_field, p_id, pivot); END IF; -- With every field optional, each one may or may not need a leading -- comma; a required field gives the commas a fixed place. FOR i IN 0 .. jsonb_array_length(p_field -> 'fields') - 1 LOOP IF coalesce(((p_field -> 'fields' -> i) ->> 'required')::boolean, false) THEN n_req := n_req + 1; END IF; END LOOP; IF n_req = 0 THEN RAISE EXCEPTION 'field %: every subfield is optional', field_name USING HINT = 'GBNF needs one required field to anchor the commas.'; END IF; -- Required fields first, then the optional ones: the key order is -- fixed. body := '"{" ws'; FOR i IN 0 .. jsonb_array_length(p_field -> 'fields') - 1 LOOP sub := p_field -> 'fields' -> i; CONTINUE WHEN NOT coalesce((sub ->> 'required')::boolean, false); rid := p_id || '-' || i::text; IF body <> '"{" ws' THEN body := body || ' "," ws'; END IF; body := body || ' ' || gbnf_literal(to_json(sub ->> 'name')::text) || ' ws ":" ws ' || rid || ' ws'; rules := rules || _rules(sub, rid); END LOOP; FOR i IN 0 .. jsonb_array_length(p_field -> 'fields') - 1 LOOP sub := p_field -> 'fields' -> i; CONTINUE WHEN coalesce((sub ->> 'required')::boolean, false); rid := p_id || '-' || i::text; body := body || ' ( "," ws ' || gbnf_literal(to_json(sub ->> 'name')::text) || ' ws ":" ws ' || rid || ' ws )?'; rules := rules || _rules(sub, rid); END LOOP; RETURN p_id || ' ::= ' || body || ' "}"' || E'\n' || rules; END IF; IF kind IN ('string', 'integer', 'number', 'boolean') THEN RETURN p_id || ' ::= ' || kind || E'\n'; END IF; RAISE EXCEPTION 'field %: unknown kind %', field_name, kind; END; $$; CREATE OR REPLACE FUNCTION grammar_guard._correlated(p_field jsonb, p_id text, p_pivot int) RETURNS text LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ DECLARE field_list jsonb := p_field -> 'fields'; pivot jsonb := p_field -> 'fields' -> p_pivot; deps jsonb := (p_field -> 'fields' -> p_pivot) -> 'dependents'; dependent_names text[]; branches text := ''; rules text := ''; body text; dep jsonb; dep_values text[]; v text; rid text; i int; j int; k int; is_first boolean; BEGIN -- An optional pivot would need every branch twice, with and without it. IF NOT coalesce((pivot ->> 'required')::boolean, false) THEN RAISE EXCEPTION 'field %: a correlated field must be required', pivot ->> 'name'; END IF; IF jsonb_typeof(pivot -> 'values') IS DISTINCT FROM 'array' OR jsonb_array_length(pivot -> 'values') = 0 THEN RAISE EXCEPTION 'field %: enum with no values', pivot ->> 'name' USING HINT = 'The query that fills this enum returned no rows.'; END IF; IF EXISTS (SELECT 1 FROM jsonb_array_elements(pivot -> 'values') x WHERE jsonb_typeof(x) <> 'string') THEN RAISE EXCEPTION 'field %: enum values must be strings, and none NULL', pivot ->> 'name'; END IF; IF jsonb_typeof(deps) <> 'array' OR jsonb_array_length(deps) = 0 THEN RAISE EXCEPTION 'field %: dependents must be a non-empty array', pivot ->> 'name'; END IF; SELECT array_agg(d ->> 'name') INTO dependent_names FROM jsonb_array_elements(deps) d; -- One alternative of the object per value of the pivot. In each, the -- pivot is that value as a literal and its dependents follow it at once, -- limited to what by_value lists for that value. FOR k IN 0 .. jsonb_array_length(pivot -> 'values') - 1 LOOP v := pivot -> 'values' ->> k; body := '"{" ws'; is_first := true; FOR i IN 0 .. jsonb_array_length(field_list) - 1 LOOP CONTINUE WHEN NOT coalesce( ((field_list -> i) ->> 'required')::boolean, false); IF NOT is_first THEN body := body || ' "," ws'; END IF; is_first := false; body := body || ' ' || gbnf_literal(to_json((field_list -> i) ->> 'name')::text) || ' ws ":" ws '; -- A dependent is declared once, inside dependents with its -- by_value; declared again in fields there would be two -- definitions to keep in step. IF ((field_list -> i) ->> 'name') = ANY (dependent_names) THEN RAISE EXCEPTION 'field %: a dependent is declared inside dependents, ' 'not again in fields', (field_list -> i) ->> 'name'; END IF; IF i = p_pivot THEN body := body || json_string_literal(v) || ' ws'; FOR j IN 0 .. jsonb_array_length(deps) - 1 LOOP dep := deps -> j; IF EXISTS (SELECT 1 FROM jsonb_array_elements( coalesce(dep -> 'by_value' -> v, '[]'::jsonb)) x WHERE jsonb_typeof(x) <> 'string') THEN RAISE EXCEPTION 'field %: values must be strings, and none NULL', dep ->> 'name'; END IF; SELECT array_agg(x) INTO dep_values FROM jsonb_array_elements_text( coalesce(dep -> 'by_value' -> v, '[]'::jsonb)) x; -- A value of the pivot with no values for a dependent -- would be a branch the model can enter and not finish. IF dep_values IS NULL OR cardinality(dep_values) = 0 THEN RAISE EXCEPTION 'field %: no values for % = %', dep ->> 'name', pivot ->> 'name', v USING HINT = 'Every value of the pivot needs at least one ' 'value for each dependent, or drop it from the pivot.'; END IF; rid := p_id || '-v' || k::text || '-d' || j::text; body := body || ' "," ws ' || gbnf_literal(to_json(dep ->> 'name')::text) || ' ws ":" ws ' || rid || ' ws'; rules := rules || _rules( jsonb_build_object('kind', 'enum', 'name', dep ->> 'name', 'values', to_jsonb(dep_values)), rid); END LOOP; ELSE -- The other fields are the same in every branch: their rules -- are written once. rid := p_id || '-' || i::text; body := body || rid || ' ws'; IF k = 0 THEN rules := rules || _rules(field_list -> i, rid); END IF; END IF; END LOOP; FOR i IN 0 .. jsonb_array_length(field_list) - 1 LOOP CONTINUE WHEN coalesce(((field_list -> i) ->> 'required')::boolean, false); IF ((field_list -> i) ->> 'name') = ANY (dependent_names) THEN RAISE EXCEPTION 'field %: a dependent is declared inside dependents, ' 'not again in fields', (field_list -> i) ->> 'name'; END IF; rid := p_id || '-' || i::text; body := body || ' ( "," ws ' || gbnf_literal(to_json((field_list -> i) ->> 'name')::text) || ' ws ":" ws ' || rid || ' ws )?'; IF k = 0 THEN rules := rules || _rules(field_list -> i, rid); END IF; END LOOP; IF branches <> '' THEN branches := branches || ' | '; END IF; branches := branches || body || ' "}"'; END LOOP; -- In GBNF a rule ends at the end of the line, so the alternatives stay -- on one. RETURN p_id || ' ::= ' || branches || E'\n' || rules; END; $$; CREATE OR REPLACE FUNCTION grammar_guard.grammar_for(p_fields jsonb, p_dialect text DEFAULT 'gbnf') RETURNS text LANGUAGE plpgsql STABLE SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ DECLARE rules text; BEGIN IF p_fields IS NULL OR jsonb_typeof(p_fields) <> 'array' OR jsonb_array_length(p_fields) = 0 THEN RAISE EXCEPTION 'no fields given' USING HINT = 'grammar_for takes a JSON array of field objects.'; END IF; -- A JSON Schema cannot tie a column to the table chosen before it, so -- the nested and correlated cases are GBNF only. IF p_dialect IS DISTINCT FROM 'gbnf' THEN RAISE EXCEPTION 'unknown dialect: %', p_dialect USING HINT = 'grammar_for emits gbnf. For json_schema use the flat ' 'grammar_for_json(grammar_field[], ''json_schema'').'; END IF; rules := _rules(jsonb_build_object('kind', 'object', 'name', 'root', 'fields', p_fields), 'root'); -- A client that is handed NULL generates with no constraint at all. IF rules IS NULL THEN RAISE EXCEPTION 'the grammar came out NULL: a field is missing a name, a kind or a value'; END IF; -- The scalar rules go in whether or not a field uses them; an unused -- GBNF rule costs nothing. Whitespace is bounded as in llama.cpp's -- grammars/json.gbnf. RETURN rules || E'string ::= "\\"" char* "\\""\n' || E'char ::= [^"\\\\\\x00-\\x1F] | "\\\\" (["\\\\/bfnrt] | "u" hex hex hex hex)\n' || E'hex ::= [0-9a-fA-F]\n' || E'integer ::= "-"? ("0" | [1-9] [0-9]*)\n' || E'number ::= integer ("." [0-9]+)? ([eE] [-+]? [0-9]+)?\n' || E'boolean ::= "true" | "false"\n' || E'ws ::= | " " | "\\n" [ \\t]{0,20}\n'; END; $$; CREATE OR REPLACE FUNCTION grammar_guard.catalog_correlated(p_tables text[], p_pivot text DEFAULT 'table', p_dependent text DEFAULT 'column') RETURNS jsonb LANGUAGE sql STABLE SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ -- A list of tables, not a schema: the grammar grows with every (table, -- column) pair, so pass the tables a request could touch. SELECT jsonb_build_object( 'name', p_pivot, 'kind', 'enum', 'required', true, 'values', to_jsonb(p_tables), 'dependents', jsonb_build_array(jsonb_build_object( 'name', p_dependent, 'kind', 'enum', 'required', true, 'by_value', (SELECT coalesce(jsonb_object_agg(t, cols), '{}'::jsonb) FROM (SELECT t, to_jsonb(catalog_columns(t::regclass)) AS cols FROM unnest(p_tables) t) _ WHERE jsonb_array_length(cols) > 0)))); $$; CREATE OR REPLACE FUNCTION grammar_guard.grammar_fingerprint(p_fields jsonb) RETURNS text LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$ -- jsonb keeps neither whitespace nor the order of keys, so the same -- spec written two ways has one fingerprint. SELECT md5(p_fields::text); $$; CREATE OR REPLACE FUNCTION grammar_guard.watch(p_name text, p_spec_sql text, p_note text DEFAULT NULL) RETURNS bigint LANGUAGE sql AS $$ SELECT living_assertions.declare_unchanged( pg_catalog.concat('grammar:', p_name), pg_catalog.concat( CASE WHEN p_note IS NULL THEN '' ELSE pg_catalog.concat(p_note, ' -- ') END, 'the approved grammar still describes the live catalog'), pg_catalog.format( 'select grammar_guard.grammar_fingerprint((%s)::jsonb)', p_spec_sql)); $$; CREATE OR REPLACE FUNCTION grammar_guard.check_grammar(p_name text) RETURNS text LANGUAGE sql SET search_path = pg_catalog, grammar_guard, pg_temp AS $$ SELECT (living_assertions.run('grammar:' || p_name)).state; $$; COMMENT ON TYPE grammar_guard.grammar_field IS 'One field of a flat JSON object. kind = enum is what the catalog adds: ' 'its values are the only ones the grammar permits.'; COMMENT ON FUNCTION grammar_guard.catalog_tables(text[]) IS 'Tables, partitioned tables, views, materialized views and foreign ' 'tables, schema-qualified and quoted, ordered by schema and name. The ' 'catalogs do not filter by privilege: the list includes relations the ' 'current role cannot read.'; COMMENT ON FUNCTION grammar_guard.catalog_columns(regclass) IS 'The columns of a table in attnum order, so a column dropped and added ' 'again counts as a change.'; COMMENT ON FUNCTION grammar_guard.catalog_enum(regtype) IS 'The labels of an enum type in their sort order. Empty for a type that ' 'is not an enum.'; COMMENT ON FUNCTION grammar_guard.gbnf_literal(text) IS 'A GBNF string literal that matches exactly the given text.'; COMMENT ON FUNCTION grammar_guard.json_string_literal(text) IS 'A GBNF literal that matches the value written as a JSON string.'; COMMENT ON FUNCTION grammar_guard.rule_name(text, int) IS 'The GBNF rule name of a field of grammar_for_json.'; COMMENT ON FUNCTION grammar_guard.grammar_for_json(grammar_guard.grammar_field[], text) IS 'Compiles a flat list of fields into a grammar for one JSON object. With ' 'gbnf the sampler cannot produce a value outside the enums; with ' 'json_schema a validator rejects it afterwards. Keys come out in a fixed ' 'order: required fields first, then optional ones.'; COMMENT ON FUNCTION grammar_guard.grammar_fingerprint(grammar_guard.grammar_field[]) IS 'Identifies a list of fields: two lists with the same fingerprint compile ' 'to the same grammar.'; COMMENT ON FUNCTION grammar_guard._rules(jsonb, text) IS 'Internal. The GBNF rules of one field of grammar_for and of everything ' 'inside it.'; COMMENT ON FUNCTION grammar_guard._correlated(jsonb, text, int) IS 'Internal. Compiles an object with a pivot field into one alternative per ' 'value of the pivot, so a dependent can only take the values listed for ' 'the pivot value already written.'; COMMENT ON FUNCTION grammar_guard.grammar_for(jsonb, text) IS 'Compiles a JSON array of fields into GBNF. A field is {name, kind, ' 'required} plus values for kind enum, items for array, fields for ' 'object, and dependents for a field whose choice limits others. Keys come ' 'out in a fixed order: required fields first, then optional ones.'; COMMENT ON FUNCTION grammar_guard.catalog_correlated(text[], text, text) IS 'A field for grammar_for whose value is a table and whose dependent is a ' 'column of that table. A table with no columns is left out of by_value, ' 'and grammar_for refuses it.'; COMMENT ON FUNCTION grammar_guard.grammar_fingerprint(jsonb) IS 'Identifies a grammar_for spec. The same fields given to ' 'grammar_for_json as a grammar_field[] have a different fingerprint.'; COMMENT ON FUNCTION grammar_guard.watch(text, text, text) IS 'Approves the grammar spec that a query returns now, as the living ' 'assertion grammar:. It stores the query, not the spec, so each ' 'check builds the spec again from the catalog.'; COMMENT ON FUNCTION grammar_guard.check_grammar(text) IS 'Checks a watched grammar now and returns its state: holds, broken, ' 'unknown or erroring.'; COMMENT ON EXTENSION pg_grammar_guard IS 'Stop a language model from naming tables and columns your database does not have';