SQL CookbookRead this first

Read this first

There are two ways a query against a HiveCFM database goes wrong. The first is loud: you guessed a table or column name and Postgres tells you so. The second is silent: the query runs, returns rows, and the rows belong to somebody else’s tenant. This page covers both, in that order, because the loud failures teach you the habit that prevents the silent one — read the catalog, never the convention.

Everything below was reproduced against a live Postgres. The commands are copy-pasteable.

1. Connecting

Investigative work happens against one of two databases in the container hivecfm-postgres-t3060. They answer different questions and neither one substitutes for the other.

DatabaseSchemaRowsUse it to
devhub_refExactly origin/development — 47 tablesZeroSettle what a table or column is called, and EXPLAIN a query
hivecfmOlder migration-era schema1191 Survey, 70333 Contact, 1498 ResponseProve a query shape returns plausible rows
container  hivecfm-postgres-t3060   (pgvector/pgvector:pg17, PostgreSQL 17.10)
published  127.0.0.1:5460 -> 5432
user       postgres
databases  devhub_ref  hivecfm  hivecfm_hub  postgres  superset_app

Verify the container is up and the port is still mapped before you trust either:

docker ps --format '{{.Names}} {{.Ports}}'
# hivecfm-postgres-t3060 127.0.0.1:5460->5432/tcp

The identifiers you will need for the worked examples, read out of hivecfm:

PlaceholderValue in hivecfm
:environment_idcmr0o5ivu000clc01glv55m4p (1191 surveys) or cmr0o5ivf0006lc01atf3swul (0 surveys)
:organization_idcmr0o1t020001lc01y879434u

Recipes in this section are written with the psql variables :'environment_id' and :'organization_id'. Substitute an id from the database you are actually connected to — an id from a different deployment returns zero rows and looks like a broken recipe.

devhub_ref was built by pushing the origin/development schema into an empty database, holds nothing, and is disposable — the two recipes on this page that write (the RLS probe role in section 4, and the policy reproductions in section 5) are meant for it and nowhere else. hivecfm holds real migrated rows; treat it as read-only.

Those are real psql variables, so you can set them once and paste recipes unedited:

\set environment_id 'cmr0o5ivu000clc01glv55m4p'
SELECT count(*) FROM "Survey" WHERE "environmentId" = :'environment_id';
--  count
-- -------
--   1191

The quoting form matters. :'environment_id' interpolates a quoted literal, which is what a text cuid needs. Bare :environment_id interpolates a raw token and Postgres reads it as an identifier:

ERROR:  column "cmr0o5ivu000clc01glv55m4p" does not exist
LINE 1: ...CT count(*) FROM "Survey" WHERE "environmentId" = cmr0o5ivu0...

Piping SQL in: the Git Bash gotcha

The obvious invocation does not work from Git Bash on Windows:

docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref -f /tmp/probe.sql
# psql: error: C:/Users/AG-Dev/AppData/Local/Temp/probe.sql: No such file or directory

Two problems stack up. Git Bash’s MSYS layer rewrites the POSIX-looking argument /tmp/probe.sql into a Windows path before docker ever sees it, and -f is resolved by psql inside the container, which has its own filesystem and no such file either. Passing a real Windows path fails the same way for the second reason alone.

Pipe the file on stdin instead. psql reads the script from its own stdin, docker exec -i forwards it, and no path crosses the boundary:

docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref < probe.sql
#  ok
# ----
#   1

For a single statement, echo it:

echo 'SELECT 1 AS ok;' | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref

For a multi-statement script inline, use a quoted heredoc so the shell leaves $ and backticks alone:

docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref <<'SQL'
SELECT count(*) FROM "Survey";
SQL

The workspace default shell is PowerShell, where the equivalent is:

Get-Content .\probe.sql | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref

2. The table-naming trap

PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. emits a table name that matches the model name unless the model carries an @@map. Most models do not, so the table is quoted PascalCase. Unquoted identifiers are folded to lower case by Postgres, so the natural spelling fails:

ERROR:  relation "response" does not exist
LINE 1: SELECT count(*) FROM response;
                             ^
-- wrong
SELECT count(*) FROM response;
-- right
SELECT count(*) FROM "Response";

Exactly 12 of the 47 models at origin/development are @@map’d to snake_case. For these, the PascalCase spelling is the one that fails:

PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. modelSQL table
ResponseIntegrationLogresponse_integration_logs
ShortUrlshort_urls
ZendeskWebhookEventzendesk_webhook_event
Channelchannels
TenantQuotatenant_quota
TenantLicensetenant_license
OrganizationBrandingorganization_branding
AppSsoConfigapp_sso_config
TenantProvisioningLogtenant_provisioning_log
DashboardTemplatedashboard_template
WorkflowTemplateworkflow_template
AuditEventaudit_event

Channel is the one that bites hardest, because the mapped name is pluralised as well as re-cased, so neither half of the model name survives. FROM "Channel" fails; FROM channels works. Section 5 shows what that cost the RLS scripts.

Do not memorise the list. Ask the catalog:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
  AND table_name ILIKE '%channel%'
ORDER BY table_name;
--  table_name
-- ------------
--  channels

ILIKE matters: it is case-insensitive, so one query finds the table whichever casing it ended up with.

3. The column-naming trap

There is no convention to apply. 191 field-level @map directives across the schema mean camelCase and snake_case columns coexist inside a single table. "Response" at origin/development:

id, created_at, updated_at, finished, "surveyId", "contactId", "endingId",
data, variables, ttc, meta, "contactAttributes", "kpiScores", "singleUseId",
language, "displayId",
genesys_conversation_id, genesys_agent_id, genesys_agent_name,
genesys_queue_id, genesys_queue_name, genesys_handle_time, genesys_wrap_code,
genesys_direction, genesys_ani, genesys_dnis,
genesys_conversation_start, genesys_conversation_end,
survey_delivery_channel, survey_delivered_at,
is_negative_response, answered_questions_count, expired_at, expiry_source

created_at is snake and needs no quoting. "surveyId" is camel and does. Same table.

The contradictions repeat across tables, and there is no pattern that predicts which:

TableColumnCasing
"Survey""environmentId"camelCase, must be quoted
channelsenvironment_idsnake_case, no quoting
"Campaign"survey_id, segment_id, environment_identirely snake_case
"Account"created_atsnake_case
"ApiKey""createdAt"camelCase

"Survey" even carries both styles side by side: "environmentId" at ordinal 7 and channel_id at ordinal 8.

The columns you assume exist, do not

This is the failure mode that turns “read the catalog” from pedantry into a rule. The two databases in section 1 disagree about "Response", and they disagree in exactly the places a developer guesses.

hivecfm has per-KPI score columns. origin/development does not:

echo 'SELECT nps_score FROM "Response" LIMIT 1;' \
  | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref
# ERROR:  column "nps_score" does not exist

origin/development has the response-versus-invitation counter. hivecfm does not:

echo 'SELECT answered_questions_count FROM "Response" LIMIT 1;' \
  | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d hivecfm
# ERROR:  column "answered_questions_count" does not exist

So a query developed against the box with real rows will not port to the shipping schema, and vice versa. nps_score in particular is the column everybody reaches for first — it exists on the older database and not at origin/development, where scores live in "Response"."kpiScores" and answers are keyed by per-survey element cuid inside "Response".data. See Responses and answers for how to get a score out without a score column.

Ask the catalog, every time

Run this before writing the query, not after it errors:

SELECT ordinal_position AS pos, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
  AND table_name = 'channels'
ORDER BY ordinal_position;
 pos |  column_name   |          data_type          | is_nullable
-----+----------------+-----------------------------+-------------
   1 | id             | text                        | NO
   2 | created_at     | timestamp without time zone | NO
   3 | updated_at     | timestamp without time zone | NO
   4 | name           | text                        | NO
   5 | type           | USER-DEFINED                | NO
   6 | description    | text                        | YES
   7 | environment_id | text                        | NO
   8 | config         | jsonb                       | NO

Two things that output tells you which no schema summary would. channels scopes by environment_id and has no survey column at all — remember that for section 5. And type reports as USER-DEFINED, which is how information_schema renders an enum; the members are in pg_enum, and for channels.type they are the seven ChannelType values.

4. RLS and tenancy

HiveCFM is multi-tenant with row-level security, and the protection it gives you in a psql session is none. Understand why before you write a query whose output somebody will act on.

The GUC holds an organizationId

Tenant identity is carried in a session variable, set per transaction. From apps/web/lib/tenant/context.ts:11:

await tx.$executeRawUnsafe(`SET LOCAL app.current_tenant = '${organizationId}'`);

The parameter of withTenantContext() at line 9 is organizationId, so app.current_tenant is an organizationId — not an environmentId, and not a projectId. Every policy resolves to an organization id, by one of two routes: the 8 tables that carry an organizationId column compare it directly, and the other 12 reach it through a join. enable-rls.sql splits its own list along exactly that line, at :5 and :19. Setting an environmentId into that GUC matches nothing on either route, so you get zero rows and no error.

That line builds SQL by string interpolation. The value is session-derived rather than request-derived, so it is not a live injection path today, but it should be set_config('app.current_tenant', $1, true). Flagged here because you will read the line; do not treat it as a pattern to copy.

An unset GUC means every row is visible

Every policy in scripts/rls/create-policies.sql has the same shape — create-policies.sql:13-21, the Contact policy, is representative:

CREATE POLICY tenant_isolation_contact ON "Contact"
  USING (
    current_setting('app.current_tenant', true) IS NULL
    OR "environmentId" IN (
      SELECT e.id FROM "Environment" e
      JOIN "Project" p ON e."projectId" = p.id
      WHERE p."organizationId" = current_setting('app.current_tenant', true)
    )
  );

The leading IS NULL disjunct is the point. The file’s own header calls it “Backward-compatible: allows all rows when app.current_tenant is not set”. A psql session that never runs SET app.current_tenant satisfies the first branch on every row of every table that carries one of these policies, so the policy admits everything. The isolation is opt-in, and opting in is something the application does and you will not.

Policies are USING-only

All 20 CREATE POLICY statements in create-policies.sql specify USING and none specifies WITH CHECK. USING filters rows a statement can see; WITH CHECK constrains rows a statement can write. So RLS here restricts reads and never restricts writes — an INSERT or UPDATE naming another tenant’s key is not stopped by RLS. Treat any write against these databases as unguarded.

Superuser and owner bypass RLS entirely

⚠️

On every local box you will touch, RLS is not filtering anybody. The postgres role has rolsuper = t and rolbypassrls = t, and no table sets FORCE ROW LEVEL SECURITY — relforcerowsecurity = false on all 19 RLS-enabled tables, which also disables filtering for the table’s owner. So a query that “looks isolated” in psql proves nothing at all about isolation.

And turning FORCE on would not make the box representative: it subjects the table owner to policies and has no effect on a superuser, who bypasses RLS unconditionally. The only way to observe filtering is to connect as a role that is neither.

That is measurable, not inferred. As postgres, the plan for a scan of "Survey" carries no filter:

 Seq Scan on "Survey"  (cost=0.00..10.70 rows=70 width=32)

As a non-superuser, non-owner role with only SELECT, the same query gets the policy predicate grafted on:

 Seq Scan on "Survey"  (cost=20.86..31.91 rows=35 width=32)
   Filter: ((current_setting('app.current_tenant'::text, true) IS NULL) OR (ANY ("environmentId" = (hashed SubPlan 1).col1)))
   SubPlan 1
     ->  Nested Loop  (cost=4.33..20.85 rows=3 width=32)
           ->  Index Scan using "Project_organizationId_name_key" on "Project" p
                 Index Cond: ("organizationId" = current_setting('app.current_tenant'::text, true))
           ->  Bitmap Heap Scan on "Environment" e
                 Recheck Cond: ("projectId" = p.id)

Reproduce it yourself. SET ROLE does not need a login, so create the probe NOLOGIN and give it no password — there is nothing to leak and nothing to log in as. Keep the DROP ROLE inside the block; a stray role in a shared cluster is its own problem:

CREATE ROLE devhub_rls_probe NOLOGIN;
GRANT USAGE ON SCHEMA public TO devhub_rls_probe;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO devhub_rls_probe;
 
SET ROLE devhub_rls_probe;
EXPLAIN SELECT id FROM "Survey";
RESET ROLE;
 
REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM devhub_rls_probe;
REVOKE USAGE ON SCHEMA public FROM devhub_rls_probe;
DROP ROLE devhub_rls_probe;

One nuance from that experiment, worth internalising: the plan is byte-identical whether or not app.current_tenant is set. The IS NULL OR ... short-circuit is evaluated at runtime, not at plan time. EXPLAIN therefore proves a policy is attached. It does not prove the policy is filtering.

Resolving environmentId to organizationId

Most tables scope by "environmentId"; the GUC holds an organizationId. The bridge is two joins, and it is the same shape the 12 environmentId-scoped policies use:

"environmentId" IN (
  SELECT e.id
  FROM "Environment" e
  JOIN "Project" p ON e."projectId" = p.id
  WHERE p."organizationId" = :'organization_id'
)

Not every table has an environmentId to plug in there. "Response" and "Display" carry only "surveyId", so they need one extra hop through "Survey". channels scopes directly, but the column is spelled environment_id. Check which of the three cases you are in before writing the predicate:

SELECT table_name, string_agg(column_name, ', ' ORDER BY ordinal_position) AS scoping_cols
FROM information_schema.columns
WHERE table_schema = 'public'
  AND (column_name ILIKE '%environ%' OR column_name ILIKE '%survey%' OR column_name ILIKE '%organization%')
GROUP BY table_name
ORDER BY table_name;

The rule

Every recipe in this section carries an explicit tenant predicate, and so should yours. RLS is not a backstop you can lean on: unset GUC admits everything, USING-only leaves writes unconstrained, and superuser bypasses the whole mechanism. Isolation in an ad-hoc query is something you write, not something you inherit.

Two canonical predicates, with the plans EXPLAIN gives them on devhub_ref. Read the shape, not the numbers: that database is empty, so every row estimate below is Postgres’s default guess for a table it has no statistics for, not a measurement.

Filter by environment directly when you have an environmentId:

SELECT s.id, s.name, s.status
FROM "Survey" s
WHERE s."environmentId" = :'environment_id';
 Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s  (cost=0.14..8.16 rows=1 width=68)
   Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)

Filter by organization through the join when you have an organizationId — the whole tenant, every project, every environment:

SELECT s.id, s.name, s.status
FROM "Survey" s
JOIN "Environment" e ON e.id = s."environmentId"
JOIN "Project"     p ON p.id = e."projectId"
WHERE p."organizationId" = :'organization_id';
 Nested Loop  (cost=4.47..21.54 rows=1 width=68)
   ->  Nested Loop  (cost=4.33..20.84 rows=3 width=32)
         ->  Index Scan using "Project_organizationId_name_key" on "Project" p
               Index Cond: ("organizationId" = 'cmr0o1t020001lc01y879434u'::text)
         ->  Bitmap Heap Scan on "Environment" e
               Recheck Cond: ("projectId" = p.id)
               ->  Bitmap Index Scan on "Environment_projectId_idx"
                     Index Cond: ("projectId" = p.id)
   ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
         Index Cond: ("environmentId" = e.id)

Every access in both plans is index-driven — no sequential scan appears in either. That is a statement about the shape the planner can reach, not a benchmark.

Why you cannot test this on a dev box

⚠️

A single-tenant database cannot tell a correct tenant filter from a missing one. On hivecfm, the unfiltered count and the correctly filtered count are the same number:

SELECT (SELECT count(*) FROM "Survey")                                     AS no_tenant_filter,
       (SELECT count(*) FROM "Survey" WHERE "environmentId" = :'environment_id') AS correct_filter;
--  no_tenant_filter | correct_filter
-- ------------------+----------------
--              1191 |           1191

Every survey in that database lives in one environment. A broken filter, a filter on the wrong column, and no filter at all all return 1191 and all look right. You will find out in production, against a database with a second tenant in it.

5. Two verified defects in the RLS scripts

Both were reproduced by piping the scripts at origin/development into devhub_ref.

⚠️

Defect A — "ContactAttribute" ends up deny-all. enable-rls.sql:7 turns RLS on for the table and succeeds. create-policies.sql:25-34 then tries to create its policy and fails:

ERROR:  column "contactAttributeKeyId" does not exist

The real column is attributeKeyId. The result is the one combination that denies everything: RLS enabled, zero policies. For any role that does not bypass RLS, every contact attribute row is invisible — and since "Contact" has only four columns, that is every contact identity in the system.

The catalog settles which name is right, and it also shows why this table matters so much — value is the only payload column, so every contact’s email, phone and name is a row here rather than a column on "Contact":

     table_name      |                                       cols
---------------------+-----------------------------------------------------------------------------------
 ContactAttribute    | id, created_at, updated_at, attributeKeyId, contactId, value
 ContactAttributeKey | id, created_at, updated_at, isUnique, key, name, description, type, environmentId

The consequence is provable at plan level, with no rows needed. As the probe role from section 4:

SET ROLE devhub_rls_probe;
EXPLAIN SELECT id FROM "ContactAttribute";
--                 QUERY PLAN
-- ------------------------------------------
--  Result  (cost=0.00..0.00 rows=0 width=0)
--    One-Time Filter: false

One-Time Filter: false is Postgres saying the table cannot return a row.

⚠️

Defect B — Channel gets no RLS at all. Both scripts address the table as "Channel"; the @@map means it is channels. enable-rls.sql:14 and create-policies.sql:112 both fail:

ERROR:  relation "Channel" does not exist

channels therefore has RLS neither enabled nor policied — no tenant isolation whatsoever, on a table whose config jsonb column holds per-channel connector settings.

The name is not the only thing wrong with it. The policy body at create-policies.sql:113-121 scopes through "surveyId", and channels has no survey column — so renaming the target does not fix the statement:

CREATE POLICY tenant_isolation_channel_probe ON "channels"
  USING (
    current_setting('app.current_tenant', true) IS NULL
    OR "surveyId" IN (
      SELECT s.id FROM "Survey" s
      JOIN "Environment" e ON s."environmentId" = e.id
      JOIN "Project" p ON e."projectId" = p.id
      WHERE p."organizationId" = current_setting('app.current_tenant', true)
    )
  );
-- ERROR:  column "surveyId" does not exist

The predicate has to be rewritten to the environment_id shape, because the relationship runs the other way: "Survey".channel_id points at channels.id, not the reverse. Anyone filing the fix should know it is two changes, not one.

The meta-lesson: a green run proves nothing

Neither defect was caught, and the reason is the point of this whole page.

psql continues past a failed statement by default, and the noise around the error helps hide it. Each CREATE POLICY is preceded by a DROP POLICY IF EXISTS, and IF EXISTS covers a missing relation too — so the Channel block opens with a reassuring skip before it errors:

NOTICE:  relation "Channel" does not exist, skipping
DROP POLICY
ERROR:  relation "Channel" does not exist

And enable-rls.sql:29 ends with:

SELECT 'RLS enabled on all tenant-scoped tables' AS status;

create-policies.sql:227 closes with the matching SELECT 'RLS policies created for all tenant-scoped tables' AS status. Neither line is conditional on anything, so the operator sees a reassuring final row whether zero statements failed or five did — and the phrase both strings share, “all tenant-scoped tables”, was untrue the moment Channel was mapped. A check that passes against the wrong thing is worse than no check.

Verify the outcome instead of trusting the script. This is the query that actually answers “which tables are protected”:

SELECT c.relname             AS table_name,
       c.relrowsecurity      AS rls_enabled,
       c.relforcerowsecurity AS rls_forced,
       count(p.policyname)   AS policies
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_policies p
       ON p.schemaname = n.nspname AND p.tablename = c.relname
WHERE n.nspname = 'public'
  AND c.relkind = 'r'
  AND (c.relrowsecurity OR p.policyname IS NOT NULL)
GROUP BY 1, 2, 3
ORDER BY 4, 1;

Run against devhub_ref after both scripts, it returns 19 rows:

       table_name        | rls_enabled | rls_forced | policies
-------------------------+-------------+------------+----------
 ContactAttribute        | t           | f          |        0
 ActionClass             | t           | f          |        1
 ApiKey                  | t           | f          |        1
 Contact                 | t           | f          |        1
 ContactAttributeKey     | t           | f          |        1
 Display                 | t           | f          |        1
 Integration             | t           | f          |        1
 Invite                  | t           | f          |        1
 Membership              | t           | f          |        1
 Project                 | t           | f          |        1
 Response                | t           | f          |        1
 Segment                 | t           | f          |        1
 Survey                  | t           | f          |        1
 Tag                     | t           | f          |        1
 Team                    | t           | f          |        1
 Webhook                 | t           | f          |        1
 organization_branding   | t           | f          |        1
 tenant_provisioning_log | t           | f          |        1
 tenant_quota            | t           | f          |        1

Read it three ways. 18 tables got a policy — the scripts name 20, and the two missing are the two defects. ContactAttribute has policies = 0, which is Defect A. channels is absent from the output entirely, which is Defect B. And rls_forced is f on all 19, which is the superuser-bypass point from section 4 stated as data.

The anti-join isolates the deny-all class on its own, which is what you want in a CI check or a post-deploy assertion — it should return zero rows:

SELECT c.relname AS table_name
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
  AND c.relkind = 'r'
  AND c.relrowsecurity
  AND NOT EXISTS (
    SELECT 1 FROM pg_policies p
    WHERE p.schemaname = n.nspname AND p.tablename = c.relname
  )
ORDER BY 1;
--    table_name
-- ------------------
--  ContactAttribute
-- (1 row)

It returns one row today. Note what it does not catch: channels is not RLS-enabled, so it is not in the anti-join’s input at all. Detecting Defect B needs the complementary check — every table named in enable-rls.sql should appear in the 19-row listing above, and Channel never does.

Where to look in the code

  • packages/database/schema.prisma — the 47 models and all 191 field-level @map / 12 @@map directives. Read it at origin/development, not from a local checkout.
  • scripts/rls/enable-rls.sql — 20 ALTER TABLE ... ENABLE ROW LEVEL SECURITY statements plus the success line at :29.
  • scripts/rls/create-policies.sql — the 20 USING-only policies; :25-34 is Defect A, :112-121 is Defect B.
  • apps/web/lib/tenant/context.ts — withTenantContext() at :9, the SET LOCAL at :11.

HiveCFM Developer Hub — internal team guide