SQL CookbookOverview

SQL COOKBOOK · VERIFIED QUERIES

SQL Cookbook

Queries you can paste into psql, planned against a database built from the exact schema this section describes.

This section is a set of recipes: SQL that answers a specific question, with the naming trap that would have broken it called out beside it. It is deliberately not a schema reference. For structure — which tables exist, which columns they hold, how they relate — use Reference → Schema and the interactive Schema Viewer. This section adds queries, not structure — and when the two disagree, believe this section: the Schema Viewer is built from generated/, which is produced from a checkout 815 commits behind the ref described below.

The ref these recipes describe

Every recipe here was written against origin/development of hivecfm-core — 47 PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. models, which is 47 tables in public. That matters more than it sounds like it should: a recipe verified at one ref can be silently wrong at another, because tables get @@map’d, columns get renamed, and the column that defines a “response” — answered_questions_count — only landed on 2026-06-29 (08f6f87ea). A query that returns rows is not evidence it is asking the right question.

The check that you are looking at the same tree these recipes were written against:

cd hivecfm-core
git fetch origin
git rev-list --left-right --count origin/development...HEAD
# "0	0" means you are at the ref. Anything else, re-verify before trusting a recipe.

The git fetch is not optional. rev-list compares against your local origin/development ref, so without a fetch a stale tracking ref can report 0 0 while the real branch has moved — a green result against the wrong thing.

Two secondary tells, both measured:

  • grep -c surveyExpirationCard packages/database/schema.prisma returns 1 at this ref and 0 in the 815-behind hivecfm-core checkout, so it detects that checkout’s staleness — but it does not separate origin/development from a migrator feature branch (feat/6096-migrator-development-merge and feat/6096-schema-convergence both return 1), and a checkout stale but newer than the field’s introduction would also return 1.
  • What separates them is packages/migrator/, which does not exist at origin/development or at origin/main. If that directory is present, you are on a migrator branch and the schema has extra legacy_* columns that no recipe here uses.
⚠️

Do not source a schema fact from hivecfm-dev-hub/generated/. Those files are produced by pnpm run sync reading the sibling ../hivecfm-core/ working tree, which is 815 commits behind origin/development — two models present at the ref (ShortUrl, ZendeskWebhookEvent) are missing from it entirely. Source from git show origin/development:<path> instead.

How each recipe was verified

Two databases, both in the local container hivecfm-postgres-t3060, each doing one job.

DatabaseContentsWhat it proves
devhub_refThe exact origin/development schema, 47 tables, zero rowsThat every identifier resolves and the query plans. Schema authority.
hivecfmReal rows — 1191 Survey, 70333 Contact, 1498 Response, 2 EnvironmentThat the query returns plausible output against real data.

devhub_ref is not a shared deployment — it is a disposable database anyone can rebuild in about a second, and rebuilding it yourself is how you check that a recipe here still holds at a ref you care about. Point DATABASE_URL at an empty database and push the schema into it:

cd ../hivecfm-core
git show origin/development:packages/database/schema.prisma > ref-schema.prisma
docker exec hivecfm-postgres-t3060 psql -U postgres -c 'CREATE DATABASE devhub_ref'
docker exec hivecfm-postgres-t3060 psql -U postgres -d devhub_ref \
  -c 'CREATE EXTENSION IF NOT EXISTS vector'
DATABASE_URL="postgresql://postgres:postgres@127.0.0.1:5460/devhub_ref?schema=public" \
  node_modules/.bin/prisma db push --schema=ref-schema.prisma --skip-generate --accept-data-loss
# -> Your database is now in sync with your Prisma schema. Done in 540ms

Swap the ref in the git show to verify a recipe against a different branch. The schema needs no editing first — --skip-generate means the generator json block (prisma-json-types-generator) never runs. Keep the schema file out of a Git-Bash /tmp: prisma and node resolve /tmp/x as F:\tmp\x while the shell writes it to %LOCALAPPDATA%\Temp, so pass a path inside the repo or a Windows-style one.

A db push gives you the schema as Prisma renders it from schema.prisma — table- and column-exact, 47 of 47. It is not proof that applying the migration history in packages/database/migration/ produces the same result, and it creates no _prisma_migrations table and none of the Superset v_* views, because a push runs no migrations. For identifier and quoting questions that distinction does not matter; for anything about migration state it does.

Step one, always — EXPLAIN against the empty reference DB:

docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref <<'SQL'
\set environment_id 'cmr0o5ivu000clc01glv55m4p'
EXPLAIN SELECT r."surveyId", count(*) AS responses
FROM "Response" r JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id' GROUP BY 1;
SQL

Step two, where possible — run it against real rows:

docker exec -i hivecfm-postgres-t3060 psql -U postgres -d hivecfm <<'SQL'
\set environment_id 'cmr0o5ivu000clc01glv55m4p'
SELECT r."surveyId", count(*) AS responses
FROM "Response" r JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id' GROUP BY 1 ORDER BY 2 DESC LIMIT 3;
SQL

The \set line is what makes those blocks paste-and-run, and the quoting form is load-bearing: :'environment_id' interpolates a quoted literal, which a text cuid needs. A bare :environment_id is read as an identifier, and an unset psql variable is left in the statement verbatim — ERROR: syntax error at or near ":". Read this first lists the ids to substitute; the one above is the hivecfm production environment, which holds all 1191 surveys.

Both steps have limits, and the limits are the point.

EXPLAIN on an empty database proves resolution, not performance. With zero rows the planner estimates rows=1 and will happily pick an index-only scan on a unique key that real data would never choose. A clean plan means the table names, column names, and joins are all real. It says nothing about how the query behaves at 1498 responses, let alone at a million.

The real-rows database is an older schema, so not every recipe can be sample-run there. hivecfm has 59 tables against the reference DB’s 47: sixteen that do not exist at the ref — migration-era leftovers (Invitation, Department, SurveyTouchpoint, ResponseAnswer, Touchpoint, merge_archive, the three _Migration* bookkeeping tables, and others) plus PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma.’s own _prisma_migrations — and four tables that exist at origin/development but not there — app_sso_config, response_integration_logs, short_urls, zendesk_webhook_event. Column-level drift matters more: its "Response" table is missing answered_questions_count and expiry_source, and carries a nps_score column that does not exist at this ref. channels is one table that is not missing: it is present on hivecfm with 66 rows and the same eight columns as the reference DB (id, created_at, updated_at, name, type, description, environment_id, config), so channel recipes can be sample-run.

🚫

answered_questions_count is the column that separates a real response from an invitation — a session with answered_questions_count = 0 is an invitation, not a response. Because that column does not exist on hivecfm, any recipe that applies the response filter was EXPLAIN-verified only. The standard across this section is: EXPLAIN against devhub_ref always; sample-run against hivecfm only where every column the recipe touches exists on that older schema. Each recipe says which of the two it got.

Three traps that will bite you first

Stated once here, in full on Read this first.

  1. Table quoting. Most models have no @@map, so the table is quoted PascalCase — FROM "Response" works and FROM response fails outright with relation "response" does not exist; exactly 12 models are @@map’d to snake_case instead (Channel → channels, TenantQuota → tenant_quota, and ten more).

  2. Per-table column casing. There is no convention to apply — 191 @map directives mean camelCase and snake_case columns coexist inside a single table, so "Response" holds created_at, "surveyId", and answered_questions_count side by side, and "Survey"."environmentId" is camelCase while channels.environment_id is snake.

  3. RLS protects nobody in your psql session. Two independent reasons, both measured. With app.current_tenant unset every policy short-circuits to IS NULL OR … and you see every tenant’s rows. And the postgres role has rolsuper = t and rolbypassrls = t, so it bypasses the policies outright even when the GUC is set — setting FORCE ROW LEVEL SECURITY would not change that, because force only re-applies RLS to the table owner, never to a superuser or a BYPASSRLS role. (relforcerowsecurity is f on all 19 RLS-enabled tables, so the owner is unfiltered too.) That is why every recipe in this section carries an explicit tenant predicate in its WHERE clause rather than relying on RLS.

Pages

  • Read this first — “What is this table actually called, and what is this column actually called?” Quoting, the @@map list, the per-table casing catalog, and the tenant predicate every other page uses.
  • Responses & answers — “How do I read an answer out of Response.data when its keys are per-survey cuids, and what counts as a response rather than an invitation?”
  • Contacts & segments — “How many contacts have an email address?” "Contact" has four columns; every attribute is an EAV row, so this is a join and never a column read.
  • Channels & campaigns — “Which channel did this survey go out on, and what did a campaign actually deliver?”
  • Genesys & IVR — “Which agent, queue, and conversation produced this response?” The genesys_* columns on "Response" and how the IVR path fills them.
  • Operational queries — “Is anything stuck, oversized, or quietly failing?” Row counts, expiry, orphans, and integration logs.

Not covered here

HubHubThe Go service that owns background processing, integrations, and the admin API. Sibling to Core. (Go) queries. The Hub is a separate service with a separate database and its own migrations — plain SQL files in the hivecfm-hub repo under migrations/ (001_initial_schema.sql through 006_list_keyset_indexes.sql), not Prisma. Nothing in this section applies to it. See Hub (Go).

Superset semantics. HiveCFM ships a dedicated view layer for Superset — fifteen v_* views including v_csat_nps_summary, v_agent_performance, and v_kpi_dashboard — defined in scripts/superset/create-views.sql. They are not installed by a PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. migration: packages/database/migration/20260310000000_add_superset_views/migration.sql is deliberately empty (its whole body is SELECT 1;, with a comment saying so), and the views are applied instead by the container start script apps/web/scripts/docker/next-start.sh:81. devhub_ref was built by pushing the schema alone, so that script never ran against it and the views do not exist there — a view-based query cannot be verified by this section’s harness at all. Which datasets a given Superset dashboard is pointed at is configured inside Superset, not in this repo, so treat the view definitions as the source of truth for what a v_* metric computes, not as proof that no dashboard queries a base table.

The legacy MSSQL side of the migrator. packages/migrator/ does not exist at origin/development or origin/main — it lives only on feature branches such as feat/6096-migrator-development-merge. Its source-side queries run against SQL Server, not this schema, and its target-side writes land on a branch schema with legacy_id / legacy_extras columns that no recipe here references. Works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact. For how a migrated survey’s shape differs from one authored natively — page layout, Survey.type provenance, language consolidation — see Migrator.

Where to look in the code

  • hivecfm-core/packages/database/schema.prisma (at origin/development) — the 47 models, the 12 @@map table renames, and all 191 @map column renames.
  • hivecfm-core/scripts/rls/enable-rls.sql and hivecfm-core/scripts/rls/create-policies.sql — which tables get RLS and the exact current_setting('app.current_tenant', true) IS NULL OR … policy shape.
  • hivecfm-core/apps/web/lib/tenant/context.ts — where app.current_tenant is set, per transaction, and to what.
  • hivecfm-core/scripts/superset/create-views.sql — the fifteen v_* view definitions, applied at container start by apps/web/scripts/docker/next-start.sh:81.
  • hivecfm-hub/migrations/ — the Hub’s own schema, unrelated to everything above.

HiveCFM Developer Hub — internal team guide