SQL CookbookOperational queries

Operational Queries

Every other page in this cookbook answers a product question. This page answers deployment questions: what is in this database, is tenant isolation actually working, who did that, what migrations does this thing think it has applied, and why is it slow.

Table and column names follow no single convention — FROM "Response" is quoted PascalCase, FROM audit_event is bare snake_case, and "Response" mixes created_at with "surveyId" in the same row. Read this first has the full trap list; this page assumes you have.

Which of these are tenant-safe

Recipes on this page split into two kinds, and confusing them is how you end up reading another client’s data.

RecipeScopePredicate
1. Tenant inventoryOperator-wide by design, plus a single-org varianto.id = :'organization_id' on the variant
2. RLS verificationCatalog only — no tenant rows readnone needed
3. Audit trailTenant-scopedorganization_id = :'organization_id'
4. Migration ledger / driftCatalog and ledger onlynone needed
5. Orphan checksMixed — see each recipeenvironmentId where one exists
6. Table sizesDiagnostic, cross-tenantnone possible
7. Long-running / blockedDiagnostic, cross-tenantnone possible

Recipes 6 and 7 read pg_class and pg_stat_activity. They aggregate across every tenant in the database and there is no predicate that makes them tenant-safe. Do not paste their output into a client-facing channel.

Every query below was planned against devhub_ref (the origin/development schema, zero rows) — except the two _prisma_migrations queries in recipe 4, which cannot be planned there because that table does not exist on a db push’ed database; those were planned against hivecfm. Where a real-data figure is quoted, it came from hivecfm (1191 surveys, 70333 contacts, 1498 responses, 1476280 contact attributes).

1. Tenant inventory

The Organization to Project to Environment tree with row counts per environment. environmentId is the practical tenant boundary, so this is the query that tells you what a deployment actually contains.

Response has no environmentId — it reaches the tenant through "Survey". That join is the expensive part.

-- Operator-wide. Not tenant-scoped: returns every organization in the database.
SELECT o.id   AS organization_id,
       o.name AS organization_name,
       p.id   AS project_id,
       p.name AS project_name,
       e.id   AS environment_id,
       e.type AS environment_type,
       (SELECT count(*) FROM "Survey"  s WHERE s."environmentId" = e.id) AS surveys,
       (SELECT count(*) FROM "Contact" c WHERE c."environmentId" = e.id) AS contacts,
       (SELECT count(*) FROM "Response" r
          JOIN "Survey" s2 ON s2.id = r."surveyId"
         WHERE s2."environmentId" = e.id)                                AS responses
FROM "Organization" o
JOIN "Project"     p ON p."organizationId" = o.id
JOIN "Environment" e ON e."projectId"      = p.id
ORDER BY o.name, p.name, e.type;

Note p."organizationId" and e."projectId" are camelCase and quoted — Project and Environment carry no @map on those fields — while channels.environment_id and "Campaign".environment_id are snake_case. Same relationship, two spellings.

The single-tenant variant adds the predicate and is what you should reach for by default:

WHERE o.id = 'cmr0o1t020001lc01y879434u'   -- :'organization_id'

The plan, and what it costs. EXPLAIN on devhub_ref shows the three counts as SubPlan 1..3, re-executed once per Environment row:

  • surveys — Index Only Scan using "Survey_environmentId_updated_at_idx"
  • contacts — Bitmap Index Scan on "Contact_environmentId_idx"
  • responses — Nested Loop: the same survey index, then Index Only Scan using "Response_surveyId_singleUseId_key" per survey

So the cost is not one probe per environment, it is one pass over every row underneath every environment. Every response row gets touched. On hivecfm — two environments, one of them empty — the query measured between 180 ms and 690 ms across runs; the spread is buffer cache state, not query shape. Scale it by response count, not by environment count.

⚠️

On a database with millions of responses this query will sit there. Do not run it against a production primary during business hours to satisfy curiosity.

When the join is too slow, drop the tree and count per table. Cheap GROUP BY scans, joined by eye or in a spreadsheet:

SELECT "environmentId" AS environment_id, count(*) AS surveys
FROM "Survey"  GROUP BY 1 ORDER BY 2 DESC;
 
SELECT "environmentId" AS environment_id, count(*) AS contacts
FROM "Contact" GROUP BY 1 ORDER BY 2 DESC;

EXPLAIN on the survey form is a single HashAggregate over a Seq Scan — one pass, no per-environment re-execution. For responses, aggregate on "surveyId" and map surveys to environments separately, or accept reltuples from recipe 6 as an estimate.

2. Prove tenant isolation actually works

This is the recipe the page exists for, and it is the one most likely to lie to you.

A check that can pass against the wrong thing is worse than no check. The shipped isolation test, scripts/rls/test-rls.sql, is exactly that check: the zero it looks for is indistinguishable from an empty table, and it has no way to fail out loud either way.

First: is your test even capable of failing

Run this before any isolation test. Three independent mechanisms bypass RLS in PostgreSQLPostgreSQLThe open-source relational database HiveCFM runs on. Replaces SQL Server for this project., and all three are live in the default HiveCFM setup.

-- Am I a role that RLS applies to?
SELECT current_user, rolsuper, rolbypassrls
FROM pg_roles WHERE rolname = current_user;

On devhub_ref as the default connection role:

 current_user | rolsuper | rolbypassrls
--------------+----------+--------------
 postgres     | t        | t

rolsuper = t bypasses RLS. rolbypassrls = t bypasses RLS. Either one alone is enough.

-- Do I own the tables, and is FORCE set?
SELECT c.relname,
       pg_get_userbyid(c.relowner) AS owner,
       c.relrowsecurity            AS rls_enabled,
       c.relforcerowsecurity       AS rls_forced
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r'
  AND c.relname IN ('Response','Survey','ContactAttribute','channels');

Verified output on devhub_ref:

     relname      |  owner   | rls_enabled | rls_forced
------------------+----------+-------------+------------
 ContactAttribute | postgres | t           | f
 Response         | postgres | t           | f
 Survey           | postgres | t           | f
 channels         | postgres | f           | f

The third bypass is the subtle one: a table’s owner skips its own RLS policies even when that role is neither superuser nor BYPASSRLS, unless FORCE ROW LEVEL SECURITY is set on the table. relforcerowsecurity is f on every table in the schema. So “run as a non-superuser” is not sufficient advice — the role must also not own the tables.

🚫

The shipped test produces a false green. scripts/rls/test-rls.sql step 3 sets app.current_tenant to 'test-org-id-does-not-exist' and expects the counts to be 0. Run as postgres against devhub_ref it returns survey_count = 0 — but devhub_ref has zero rows, so 0 is what it would return with RLS switched off entirely. Run the same statements against hivecfm, which has 0 RLS-enabled tables and 0 policies, and "Survey" returns 1191 — the number that should stop a deployment. Either way the script ends with SELECT 'RLS test completed' and exits 0: there is no assertion anywhere in it, so psql just prints the count and moves on. The zero it asks for measures “are there rows”, not “is isolation enforced”, and nothing in the script notices when it does not get one.

To actually drop the bypass without creating anything, SET ROLE to a role that is neither superuser, BYPASSRLS, nor the table owner. It is session-local and mutates nothing:

SET ROLE some_constrained_role;
SET app.current_tenant = 'test-org-id-does-not-exist';
SELECT count(*) FROM "Survey";   -- must be 0
RESET ROLE;

Distinguish the two failure modes carefully. 0 means RLS filtered. ERROR: permission denied for table Survey means the role lacks a GRANT — you have proved a privilege problem, not an isolation property. On devhub_ref the only non-bypassing login roles are superset and superset_readonly, and both hit permission denied, so the positive case is not demonstrated on the reference database. It needs a role the operator grants SELECT to.

The catalog checks that do not depend on your role

These read pg_class and pg_policy only. They are honest regardless of who you connect as.

Which tables have RLS enabled:

SELECT c.relname AS table_name, c.relrowsecurity AS rls_enabled, c.relforcerowsecurity AS rls_forced
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relrowsecurity
ORDER BY 1;

19 rows on devhub_ref after both RLS scripts run.

Which tables have a policy, and whether it constrains writes:

SELECT tablename, policyname, cmd, permissive,
       (qual       IS NOT NULL) AS has_using,
       (with_check IS NOT NULL) AS has_with_check
FROM pg_policies WHERE schemaname = 'public'
ORDER BY tablename, policyname;

18 rows, all cmd = ALL, all has_using = t, all has_with_check = f. Policies are USING-only: RLS constrains reads and never constrains writes. A constrained role cannot see another tenant’s rows, but nothing at this layer stops it writing one.

The dangerous middle state — enabled, no policy:

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_policy p WHERE p.polrelid = c.oid)
ORDER BY 1;

Plans as a Hash Right Anti Join between pg_class and pg_policy. Returns exactly one row on devhub_ref:

    table_name
------------------
 ContactAttribute

RLS on with no policy means deny-all for any role RLS applies to. enable-rls.sql succeeds on "ContactAttribute"; create-policies.sql:28 then fails on it with ERROR: column "contactAttributeKeyId" does not exist, because the real column is attributeKeyId. psql continues past a failed statement, so the run still prints its success line and nothing looks wrong.

The opposite hole — tenant-columned tables with no RLS at all. The anti-join above cannot see a table where RLS was never enabled. This heuristic finds those:

SELECT c.relname AS table_name,
       string_agg(a.attname, ', ' ORDER BY a.attname) AS tenant_columns
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
WHERE n.nspname = 'public'
  AND c.relkind = 'r'
  AND NOT c.relrowsecurity
  AND a.attname IN ('environmentId','environment_id','organizationId','organization_id')
GROUP BY c.relname
ORDER BY 1;

Seven rows on devhub_ref: ApiKeyEnvironment, Campaign, audit_event, channels, response_integration_logs, tenant_license, zendesk_webhook_event. This is a candidate list, not a defect list — audit_event is deliberately unconstrained, and the others may be intentional.

But channels is a confirmed defect. Both scripts name "Channel" — enable-rls.sql:14 and create-policies.sql:111-112 — while the table is channels, because the model carries @@map("channels"). Both statements fail with ERROR: relation "Channel" does not exist and the table ends up with neither RLS nor a policy. channels.config is jsonb holding per-channel connector settings.

The reset trap

The policy body is an escape hatch plus a scope check. Verified from pg_policies.qual on "Survey":

(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)))

IS NULL means see-all. That is the documented backward-compatibility branch. What is not documented is that the GUC stops being NULL after the first time anything sets it:

SELECT current_setting('app.current_tenant', true) IS NULL AS unset_is_null;   -- t
 
BEGIN;
SET LOCAL app.current_tenant = 'org_abc';
SELECT current_setting('app.current_tenant', true);                            -- org_abc
COMMIT;
 
SELECT current_setting('app.current_tenant', true) IS NULL AS is_null_after_commit,
       current_setting('app.current_tenant', true) = ''    AS is_empty_string;
-- f, t

Verified on devhub_ref. After the transaction commits the GUC is the empty string, not NULL. RESET app.current_tenant produces the same ''.

🚫

Code contradicts comment. apps/web/lib/tenant/context.ts:7 says SET LOCAL “auto-resets when the transaction ends”. It reverts to '', not to unset. So on a pooled connection, once withTenantContext() has run once, the policy’s IS NULL branch is false for the life of that connection, and every later non-tenant query on it evaluates p."organizationId" = '' — matching nothing. That is deny-all, not see-all. It is invisible today only because the app connects as an owner/superuser that bypasses RLS; it becomes a live outage the moment somebody switches to a constrained role. The same empty-string reset also falsifies step 4 of scripts/rls/test-rls.sql, which does RESET app.current_tenant and then asserts in a comment that the count “should see all rows (backward compatibility)” — for a role RLS applies to, it would see none. A guard of coalesce(current_setting('app.current_tenant', true), '') = '' would survive both states.

Check for the poisoned state on any session before trusting its results:

SELECT current_user AS connected_as,
       current_setting('app.current_tenant', true) IS NULL AS guc_unset,
       current_setting('app.current_tenant', true) = ''    AS guc_empty_string,
       coalesce(current_setting('app.current_tenant', true), '<unset>') AS guc_value;

What a green run proves

Green on the catalog checks proves a policy row exists with the shape you expect. It does not prove that any real connection is constrained by it — that depends entirely on the role, and every role in the default setup bypasses. State both halves whenever you report on this.

3. Audit trail

AuditEvent is @@map’d to audit_event, so the table is bare snake_case and every column is snake_case — no quoting needed anywhere in this section. Columns verified with \d audit_event on devhub_ref.

Vocabulary, verified from apps/web/modules/ee/audit-logs/types/audit-log.ts:

ColumnValues
actor_typeuser, api, system
statussuccess, failure
action27 values including created, updated, deleted, merged, accessed, userSignedIn, authenticationSucceeded, validationFailed, bulkCreated, createdFromCSV
target_type28 values including survey, response, contact, apiKey, organization, project, channel, tenantLicense

ip_address can hold the literal string unknown (UNKNOWN_DATA in the same file), not just NULL.

Recent events for an organization:

SELECT created_at, actor_type, actor_id, actor_name,
       action, target_type, target_name, target_id,
       status, ip_address, http_method, http_status_code, error_message
FROM audit_event
WHERE organization_id = 'cmr0o1t020001lc01y879434u'   -- :'organization_id'
  AND created_at >= now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 100;

Plans as a clean Index Scan using audit_event_organization_id_created_at_idx with both predicates in the Index Cond.

Failed events:

SELECT created_at, actor_type, actor_id, actor_name,
       action, target_type, target_name,
       http_method, http_status_code, error_message, api_url
FROM audit_event
WHERE organization_id = 'cmr0o1t020001lc01y879434u'
  AND created_at >= now() - interval '7 days'
  AND status = 'failure'
ORDER BY created_at DESC
LIMIT 100;

Keep the created_at bound. There is no index on status — the plan shows Filter: (status = 'failure'::text) applied after the index scan, so the time bound is the only thing limiting how many rows get read.

Events by actor:

SELECT actor_type, actor_id, max(actor_name) AS actor_name,
       action, target_type,
       count(*)                                   AS events,
       count(*) FILTER (WHERE status = 'failure')  AS failures,
       max(created_at)                             AS last_seen
FROM audit_event
WHERE organization_id = 'cmr0o1t020001lc01y879434u'
  AND created_at >= now() - interval '30 days'
GROUP BY actor_type, actor_id, action, target_type
ORDER BY events DESC
LIMIT 50;

Plans as GroupAggregate over Index Scan using audit_event_organization_id_project_id_created_at_idx. actor_name and target_name are captured at write time so deletes and renames do not make old rows unreadable — that is why max(actor_name) is safe here rather than a join.

🚫

old_object, new_object, request_body and response_body are jsonb and contain personal data by design. Do not export them casually.

request_body and response_body pass through redactPIIForAudit, which uses AUDIT_SENSITIVE_KEYS (apps/web/lib/utils/logger-helpers.ts:53) — a credentials-only list: password, access_token, refresh_token, id_token, twofactorsecret, backupcodes, session_state, token, secret, hashedkey, apikey, pin. The comment above that list is explicit that name, email and contact attributes are deliberately not redacted, because that is the point of an audit trail. The broader SENSITIVE_KEYS list — which does cover email, name, phone, address, attributes — applies only to the stdout/Pino path, not to these columns.

old_object and new_object go through the same credentials-only list, but one layer up: buildAndLogAuditEvent applies redactPIIForAudit to both at handler.ts:155-156 before handing changes to logAuditEvent. The DB write itself redacts nothing — service.ts:42-49 lifts event.changes.oldObject / .newObject straight through to the single prisma.auditEvent.create at service.ts:51. handler.ts is the only non-test caller at the pinned ref, so in practice these two columns carry the same credentials-only redaction as the bodies, and the same unredacted names, emails and contact attributes.

Bodies are truncated at MAX_BODY_BYTES = 64 KiB and replaced by a _truncated / _originalBytes / preview object when over. Truncation is not redaction.

Select the named columns, as every query above does. SELECT * on audit_event is a data-export decision, not a debugging step.

4. Which migrations does this database think it has applied

There are two ledgers, and checking only one gives a wrong answer.

LedgerWritten byHolds
_prisma_migrationsprisma migrate deploy, invoked at migration-runner.ts:172schema migrations (migration.sql)
"DataMigration"raw INSERT / UPDATE at migration-runner.ts:87,100,117data migrations (migration.ts), status pending / applied / failed

_prisma_migrations is the standard PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. table — name confirmed on hivecfm (169 rows), columns id, checksum, finished_at, migration_name, logs, rolled_back_at, started_at, applied_steps_count.

It does not exist on devhub_ref. That reference database was built with prisma db push, which applies the schema without recording anything. The table’s absence is itself a diagnostic: a database with no _prisma_migrations was pushed, not migrated, and has no applied-migration history to compare against.

-- Schema migrations. Fails with 'relation "_prisma_migrations" does not exist' on a db push'ed database.
SELECT migration_name, started_at, finished_at, applied_steps_count, rolled_back_at
FROM _prisma_migrations
ORDER BY started_at DESC
LIMIT 20;
 
-- Anything that started and never finished, or was rolled back
SELECT migration_name, started_at, finished_at, rolled_back_at, logs
FROM _prisma_migrations
WHERE finished_at IS NULL OR rolled_back_at IS NOT NULL
ORDER BY started_at;
 
-- Data migrations — the other half
SELECT name, status, started_at, finished_at
FROM "DataMigration"
ORDER BY started_at DESC;
 
SELECT status, count(*) FROM "DataMigration" GROUP BY 1;

On hivecfm: 169 rows in _prisma_migrations, 14 rows in "DataMigration", all applied. A pending row in "DataMigration" blocks the nextNext.jsReact framework used by HiveCFM Core. Handles routing, server rendering, and API routes in one bundle. run — migration-runner.ts reads it as a lock and refuses to proceed.

The source-of-truth directory is packages/database/migration (singular, 200 migration directories plus migration_lock.toml, and the only one listed in the package’s files). packages/database/migrations (plural) is a staging area that migration-runner.ts:43 wipes with rm -rf on every run before copying in the one migration it is about to apply. Never count the plural directory to work out what should be applied.

The check that actually finds drift

The ledger tells you what a database believes. Comparing table and column lists tells you what is there. When those disagree, the ledger is the one that is wrong.

There is no cross-database join in plain psql, so dump both sides and diff. REF_URL points at a database holding the schema you expect; LIVE_URL at the one you are auditing.

REF_URL="postgresql://USER:PASSWORD@HOST:PORT/REF_DB"
LIVE_URL="postgresql://USER:PASSWORD@HOST:PORT/LIVE_DB"
 
Q="select table_name from information_schema.tables
   where table_schema='public' and table_type='BASE TABLE' order by 1;"
 
psql "$REF_URL"  -At -c "$Q" > ref.txt
psql "$LIVE_URL" -At -c "$Q" > live.txt
 
comm -23 ref.txt live.txt   # in the ref schema, MISSING from the live database
comm -13 ref.txt live.txt   # extra in the live database

Fill both URLs in from your own rig; never paste a live connection string into a shared channel. If you have no reference database, build one by pushing the pinned schema into an empty database (prisma db push), and read the Callout above about what that leaves out.

Real result, devhub_ref against hivecfm:

missing from live: app_sso_config  response_integration_logs  short_urls  zendesk_webhook_event

extra in live:     CustomerOrg Department Invitation LegacySurveyKind ResponseAnswer
                   SurveyChannel SurveyTouchpoint SurveyTouchpointType Touchpoint
                   TouchpointType _MigrationAuditLog _MigrationCheckpoint _MigrationVariant
                   _prisma_migrations merge_archive survey_merge_archive

What a difference means. A table in the ref schema and missing from the live database is an unapplied migration, and any code path touching it fails at runtime with relation "..." does not exist. A table only in the live database is either an older model since dropped upstream, or migration-era scaffolding — harmless to reads, but it means this database is not at the pinned ref. _prisma_migrations showing up as “extra” is noise from how the reference was built; recognise the diff’s own artefacts before chasing them.

Table-level is not enough. A table can be present with columns missing — that is the P2022 class of PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. failure, and it is much harder to spot:

Q="select table_name||'.'||column_name||' '||data_type from information_schema.columns c
   where table_schema='public'
     and exists (select 1 from information_schema.tables t
                 where t.table_schema='public' and t.table_name=c.table_name
                   and t.table_type='BASE TABLE')
   order by 1;"
 
psql "$REF_URL"  -At -c "$Q" > refc.txt
psql "$LIVE_URL" -At -c "$Q" > livec.txt
comm -23 refc.txt livec.txt

59 differences on that pair. Excluding the four wholly-absent tables, the ones that matter:

Project.integration_logs_config   Project.require_custom_domain_validation
Project.responses_export_config   Response.answered_questions_count
Response.expiry_source            Survey.allowAnonymous
Survey.custom_domain              Survey.enable_custom_domain
Survey.invalid_response_card      Survey.is_custom_domain_verified
Survey.survey_expiration_card     User.last_role_change_at
audit_event.project_id            tenant_license.customer_name
tenant_license.license_type       tenant_license.portal_payload
tenant_license.product_slug

Response.answered_questions_count is the one to notice. It exists at origin/development and does not exist on hivecfm. That column is the response-versus-invitation filter every response recipe in this cookbook depends on — so on that database those queries do not return wrong numbers, they fail outright. A drift check at table granularity would have called it clean.

5. Orphan and integrity checks

Most orphan queries you would think to write here cannot return a row, because a foreign key already forbids the state. Shipping one anyway is a check that can only ever pass. Enumerate the constraints first:

SELECT c.relname AS child, a.attname AS col, cf.relname AS parent,
       con.confdeltype AS on_delete   -- a=noAction c=cascade n=setNull r=restrict d=setDefault
FROM pg_constraint con
JOIN pg_class c  ON c.oid  = con.conrelid
JOIN pg_class cf ON cf.oid = con.confrelid
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = con.conkey[1]
WHERE con.contype = 'f' AND con.connamespace = 'public'::regnamespace
ORDER BY 1, 2;

61 foreign keys across the 47 tables on devhub_ref. Three of the four checks originally scoped for this page died on that list.

Proposed checkVerdict
Responses whose survey is goneDropped. Response.surveyId is NOT NULL with Response_surveyId_fkey ... ON DELETE CASCADE. Deleting a survey deletes its responses. Cannot return a row.
Surveys whose channel_id points at nothingDropped. Survey_channel_id_fkey ... ON DELETE SET NULL. Deleting a channel nulls the pointer. A dangling non-null channel_id is unreachable.
CampaignSend rows with no campaignDropped. CampaignSend_campaign_id_fkey ... ON DELETE CASCADE. Cannot return a row.
Contacts with no attributesKept. No constraint requires a Contact to have any ContactAttribute row.

Two more survive, found by asking which tables have no outbound foreign key at all:

SELECT c.relname AS table_with_no_outbound_fk
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r'
  AND NOT EXISTS (SELECT 1 FROM pg_constraint con
                  WHERE con.conrelid = c.oid AND con.contype = 'f')
ORDER BY 1;

Eight rows: DataMigration, Organization, User, app_sso_config, audit_event, dashboard_template, workflow_template, zendesk_webhook_event. Two of those carry HiveCFM ids with nothing enforcing them — audit_event and zendesk_webhook_event.

5a. Contacts with no attributes — tenant-scoped

"Contact" has four columns only: id, created_at, updated_at, "environmentId". Email, phone and name are EAV rows in "ContactAttribute". A contact with no attribute rows is a contact with no identity at all — usually a failed import.

SELECT c.id, c.created_at
FROM "Contact" c
WHERE c."environmentId" = 'cmr0o5ivu000clc01glv55m4p'   -- :'environment_id'
  AND NOT EXISTS (SELECT 1 FROM "ContactAttribute" ca WHERE ca."contactId" = c.id)
ORDER BY c.created_at DESC
LIMIT 100;

Zero rows on hivecfm, which is the healthy answer. The cost is not free. EXPLAIN (ANALYZE, BUFFERS) there measured between 0.43 s and 4.6 s across runs — that spread is buffer cache state, so treat the shape rather than the number as the finding. The shape is stable: the planner ignored Contact_environmentId_idx and sequential-scanned "Contact" — the predicate matches every row in a single-tenant database — then ran a Nested Loop Anti Join doing one Index Only Scan using "ContactAttribute_contactId_attributeKeyId_key" per contact, 70333 times, for roughly 212k buffer accesses. Scales linearly with contact count.

5b. Audit rows whose organization or project is gone — expected by design

audit_event has zero foreign keys, deliberately. schema.prisma:1465-1466: “No FK on purpose — audit rows are append-only and must survive project deletion.” So these are not integrity violations, they are the intended behaviour. The query is how you confirm a deletion actually happened, not how you find a bug.

-- Cross-tenant by nature: it looks for organization ids that no longer resolve.
SELECT ae.organization_id,
       count(*)           AS rows,
       min(ae.created_at) AS first_seen,
       max(ae.created_at) AS last_seen
FROM audit_event ae
WHERE NOT EXISTS (SELECT 1 FROM "Organization" o WHERE o.id = ae.organization_id)
GROUP BY 1
ORDER BY 2 DESC;
 
SELECT ae.project_id, count(*) AS rows, max(ae.created_at) AS last_seen
FROM audit_event ae
WHERE ae.project_id IS NOT NULL
  AND NOT EXISTS (SELECT 1 FROM "Project" p WHERE p.id = ae.project_id)
GROUP BY 1
ORDER BY 2 DESC;

Both plan as Hash Right Anti Join with a Seq Scan on audit_event — there is no index that helps an anti-join, so cost is linear in audit-table size. project_id is nullable and NULL means org-level or unattributable, so the IS NOT NULL guard is what stops every org-level event being reported as an orphan.

5c. Zendesk webhook events pointing at a missing survey — tenant-scoped

zendesk_webhook_event.environment_id and .survey_id are both NOT NULL with no foreign key, so a row can outlive its survey.

SELECT z.environment_id, z.survey_id,
       count(*) AS rows, max(z.created_at) AS last_seen
FROM zendesk_webhook_event z
WHERE z.environment_id = 'cmr0o5ivu000clc01glv55m4p'   -- :'environment_id'
  AND NOT EXISTS (SELECT 1 FROM "Survey" s WHERE s.id = z.survey_id)
GROUP BY 1, 2
ORDER BY 3 DESC;

Hash Right Anti Join, Seq Scan on zendesk_webhook_event — the table’s only indexes are on (survey_id, created_at) and (ticket_id), so the environment_id predicate is a filter, not an index condition.

⚠️

This query runs on devhub_ref and will fail on hivecfm — zendesk_webhook_event is one of the four tables missing there (recipe 4). Note also that zendesk_webhook_event holds payload (the full Zendesk request body) and requester_email. Same export caution as audit_event.

6. Table sizes and the biggest consumers

Diagnostic, cross-tenant. There is no tenant predicate for this query — pg_total_relation_size aggregates every tenant’s rows in the table.

SELECT c.relname                                     AS table_name,
       pg_size_pretty(pg_total_relation_size(c.oid))  AS total,
       pg_size_pretty(pg_relation_size(c.oid))        AS heap,
       pg_size_pretty(pg_indexes_size(c.oid))         AS indexes,
       c.reltuples::bigint                            AS est_rows
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r'
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 20;

Plans as a Sort over a Seq Scan on pg_class joined to pg_namespace — cheap, safe to run any time. Real top of the list on hivecfm:

    table_name    |  total  |  heap   | indexes | est_rows
------------------+---------+---------+---------+----------
 ContactAttribute | 482 MB  | 195 MB  | 287 MB  |  1464181
 Contact          | 17 MB   | 8040 kB | 9096 kB |    70333
 Survey           | 5224 kB | 2960 kB | 960 kB  |     1191
 Response         | 2472 kB | 1072 kB | 1344 kB |     1498

ContactAttribute is 94% of the public schema on that database (482 MB of 512 MB), and its indexes are larger than its heap. That is the direct cost of the EAV contact model: "Contact" has four columns, so every attribute of every contact is a row with its own index entries. When somebody asks where the storage went, this is the answer, and it is the reason contact queries in this cookbook are joins.

reltuples is an estimate maintained by ANALYZE, not a count. Three of the four rows above match the real count exactly; ContactAttribute reads 1464181 against an actual 1476280 — a 0.8% undercount from writes since the last analyze, on the one table where the number matters. On a table that has never been analyzed it is -1, which is what every row of devhub_ref returns. Use it for orders of magnitude; use recipe 1 when the number has to be right.

7. Long-running and blocked queries

Diagnostic, cross-tenant. pg_stat_activity shows every session on the instance, and query text can contain literal parameter values belonging to any tenant. Treat the output as sensitive.

SELECT pid, usename, application_name, client_addr, state,
       now() - xact_start  AS xact_age,
       now() - query_start AS query_age,
       wait_event_type, wait_event,
       left(query, 120) AS query
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid()
  AND state <> 'idle'
ORDER BY xact_start NULLS LAST;

The three predicates are what make this readable: datname drops other databases on the same instance, pg_backend_pid() drops your own session, state <> 'idle' drops the pool’s parked connections. Add AND now() - query_start > interval '30 seconds' when you only want the slow ones.

Watch for state = 'idle in transaction' with a large xact_age. Those hold locks and pin the vacuum horizon without running anything.

Who is blocking whom:

SELECT a.pid                   AS blocked_pid,
       a.usename               AS blocked_user,
       now() - a.query_start   AS blocked_for,
       left(a.query, 80)       AS blocked_query,
       pg_blocking_pids(a.pid) AS blocked_by,
       b.pid                   AS blocker_pid,
       left(b.query, 80)       AS blocker_query,
       b.state                 AS blocker_state
FROM pg_stat_activity a
LEFT JOIN pg_stat_activity b ON b.pid = ANY (pg_blocking_pids(a.pid))
WHERE cardinality(pg_blocking_pids(a.pid)) > 0
  AND a.datname = current_database();

Plans as nested loops over two pg_stat_get_activity function scans. pg_blocking_pids is evaluated per row, which is fine at connection-pool scale. An empty result means nothing is blocked right now — it says nothing about a minute ago, so this is a live-incident query, not a diagnosis.

Terminating a session is a decision, not a diagnostic. pg_cancel_backend(pid) cancels the current query; pg_terminate_backend(pid) drops the connection and rolls back its transaction. Neither belongs in a script that runs unattended.

Where to look in the code

  • hivecfm-core/scripts/rls/enable-rls.sql — ALTER TABLE ... ENABLE ROW LEVEL SECURITY per table; ends with an unconditional success SELECT.
  • hivecfm-core/scripts/rls/create-policies.sql — the tenant_isolation_* policies; USING-only, no WITH CHECK.
  • hivecfm-core/scripts/rls/test-rls.sql — the shipped isolation test that produces the false green described in recipe 2.
  • hivecfm-core/apps/web/lib/tenant/context.ts — withTenantContext(); line 7 is the comment the empty-string reset contradicts, line 11 sets the GUC.
  • hivecfm-core/packages/database/src/scripts/migration-runner.ts — both migration ledgers: prisma migrate deploy at line 172, "DataMigration" writes at lines 87, 100 and 117, and the plural-directory wipe at line 43.
  • hivecfm-core/packages/database/migration/ — the 200 git-tracked migration directories plus migration_lock.toml. Singular. The source of truth.
  • hivecfm-core/packages/database/schema.prisma — model AuditEvent at line 1460, including the deliberate no-FK comment at lines 1465-1466.
  • hivecfm-core/apps/web/modules/ee/audit-logs/types/audit-log.ts — ZAuditAction, ZAuditTarget, ZActor, ZAuditStatus, UNKNOWN_DATA.
  • hivecfm-core/apps/web/modules/ee/audit-logs/lib/service.ts — logAuditEvent(); the only prisma.auditEvent.create in the tree, at line 51, with old_object / new_object lifted from changes at lines 42-49 and no redaction of its own.
  • hivecfm-core/apps/web/modules/ee/audit-logs/lib/handler.ts — buildAndLogAuditEvent(); the sole non-test caller of logAuditEvent, and where redactPIIForAudit is applied to oldObject / newObject at lines 155-156.
  • hivecfm-core/apps/web/modules/ee/audit-logs/lib/http-capture.ts — captureRequestBody, captureResponseBody, MAX_BODY_BYTES.
  • hivecfm-core/apps/web/lib/utils/logger-helpers.ts — AUDIT_SENSITIVE_KEYS at line 53 and the comment explaining why it is narrower than SENSITIVE_KEYS.

HiveCFM Developer Hub — internal team guide