Files
semprini-data-product-templ…/canonical_data_product/ods/030_api.sql
T
2026-09-18 08:56:37 +12:00

32 lines
1.4 KiB
PL/PgSQL

-- {{product.name}}: API surface (runs on the ods service).
--
-- PostgREST connects as `authenticator` and switches to the platform's `anon` role, so the
-- GraphQL API sees exactly what `anon` is granted here. The lab has no authentication; a real
-- deployment would grant per-consumer roles and add row-level security policies.
GRANT USAGE ON SCHEMA {{product.schema}} TO anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {{product.schema}} TO anon;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA {{product.schema}} TO anon;
ALTER DEFAULT PRIVILEGES IN SCHEMA {{product.schema}} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO anon;
-- The product's GraphQL endpoint. PostgREST exposes api.<name> as POST /rpc/<name>.
-- pg_graphql reflects the schemas on the search_path, so the SET clause is what scopes this
-- endpoint to the product's tables and keeps other products out of its schema.
CREATE FUNCTION api.{{product.schema}}_graphql(
query text,
variables jsonb DEFAULT '{}'::jsonb,
"operationName" text DEFAULT NULL,
extensions jsonb DEFAULT NULL
) RETURNS jsonb
LANGUAGE sql
SECURITY INVOKER
SET search_path = {{product.schema}}, graphql
AS $$
SELECT graphql.resolve(query, variables, "operationName", extensions);
$$;
GRANT EXECUTE ON FUNCTION api.{{product.schema}}_graphql(text, jsonb, text, jsonb) TO anon;
-- PostgREST caches the API definition; ask it to pick up the new endpoint.
NOTIFY pgrst, 'reload schema';