SQL CookbookContacts & segments

Contacts & Segments

"Contact" has four columns: id, created_at, updated_at, "environmentId". No email. No phone. No name. No userId.

Everything a contact is lives in "ContactAttribute" — one row per ("contactId", "attributeKeyId") pair holding a text value — pointing at a definition row in "ContactAttributeKey". That single design choice is why “contacts with an email” is a join and not a WHERE, why “show me a contact table” is a pivot, and why “how many contacts do we have” and “how many contacts can we email” are two different queries with two different answers.

Two databases are referenced below, both described in Read this first: devhub_ref carries the exact origin/development schema and zero rows (every query here was planned against it), and hivecfm carries real rows on an older migration-era schema (every count below labelled “measured” came from it, and is a property of that dataset, not of the product).

1. Prove it for yourself

Do not take the four columns on trust. The catalog is the only authority that cannot drift:

SELECT ordinal_position, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
  AND table_name = 'Contact'
ORDER BY ordinal_position;
 ordinal_position | 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 | environmentId | text                        | NO

That is the whole table. Widen it to the trio to see where the data actually is:

SELECT table_name, ordinal_position, column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'public'
  AND table_name IN ('Contact', 'ContactAttribute', 'ContactAttributeKey')
ORDER BY table_name, ordinal_position;

"ContactAttribute" returns id, created_at, updated_at, attributeKeyId, contactId, value. "ContactAttributeKey" returns id, created_at, updated_at, isUnique, key, name, description, type, environmentId.

Two things in that output surprise people:

  • ContactAttributeKey.type reports data_type = USER-DEFINED. Nothing is broken — it is the ContactAttributeType enum, whose only members are default and custom.
  • ContactAttribute.value is text, always. There is no numeric or boolean attribute storage. A rating of 7 is the string '7'; a flag is the string 'true'. Every comparison you write against it is a text comparison unless you cast.

These two queries carry no tenant predicate, because information_schema has no tenant dimension — it describes the schema, not anybody’s rows. The same is true of the pg_class check in section 7. Every query on this page that reads a tenant’s rows carries an explicit :'environment_id'.

Scoping: the one table with no environmentId

"Contact", "ContactAttributeKey" and "Segment" each carry "environmentId". "ContactAttribute" does not. pg_constraint lists exactly three entries for it — a primary key on id, and two foreign keys:

ContactAttribute_attributeKeyId_fkey  FOREIGN KEY ("attributeKeyId") REFERENCES "ContactAttributeKey"(id) ON UPDATE CASCADE ON DELETE CASCADE
ContactAttribute_contactId_fkey       FOREIGN KEY ("contactId")      REFERENCES "Contact"(id)            ON UPDATE CASCADE ON DELETE CASCADE

The @@unique([contactId, attributeKeyId]) from the PrismaPrismaThe TypeScript ORM HiveCFM uses to talk to Postgres. The schema lives at packages/database/schema.prisma. schema is not in that list, because Postgres enforces it as a unique index — ContactAttribute_contactId_attributeKeyId_key, visible in pg_indexes and not in pg_constraint. Check the wrong catalog and you will conclude the table has no uniqueness at all; it does, and sections 3 and 4 below rely on it.

So an attribute row must be scoped through one of its two parents, and which one you pick is a performance decision, not a correctness one:

You areScope throughBecause
Filtering by a known attribute key"ContactAttributeKey"."environmentId"ContactAttributeKey_key_environmentId_key resolves key + tenant in a single unique-index lookup
Enumerating or paging contacts"Contact"."environmentId"Contact_environmentId_idx gives you the tenant’s contact set directly
Auditingbothsee below
⚠️

Nothing in the database forces a contact and its attribute key into the same environment. Two foreign keys, no check constraint, no trigger. The invariant is maintained by application code only. On the migration-era hivecfm dataset it does hold — the audit below returned 0 — but a query scoped through only one parent is trusting convention, not the schema.

SELECT count(*) AS attribute_rows_keyed_outside_this_environment
FROM "Contact" c
JOIN "ContactAttribute"     a ON a."contactId" = c.id
JOIN "ContactAttributeKey"  k ON k.id = a."attributeKeyId"
WHERE c."environmentId" = :'environment_id'
  AND k."environmentId" <> c."environmentId";

Measured on hivecfm: 0. Run it after any bulk import or migration; a non-zero result means some tenant’s attribute values are hanging off another tenant’s key definitions, and every key-scoped query in this page will then leak.

2. What data do we actually have?

This is the first query to run against any environment you have not seen before. It answers “which attributes exist” and “how many contacts actually have one” in a single pass, and it is the query that tells you whether the rest of your plan is possible.

SELECT k.key,
       k.name,
       k.type,
       k."isUnique",
       count(a.id)                                AS contacts_with_value,
       count(*) FILTER (WHERE btrim(a.value) <> '') AS contacts_with_nonblank
FROM "ContactAttributeKey" k
LEFT JOIN "ContactAttribute" a ON a."attributeKeyId" = k.id
WHERE k."environmentId" = :'environment_id'
GROUP BY k.id, k.key, k.name, k.type, k."isUnique"
ORDER BY contacts_with_value DESC, k.key;

The LEFT JOIN is deliberate: a key with zero attribute rows is a defined-but-unused attribute, and it must appear with 0 rather than vanish. count(a.id) counts matched rows only; the FILTER separates “has a row” from “has something in it”.

Measured on hivecfm, production environment (migration-era dataset, 70,333 contacts, 136 attribute keys — 18 real attributes and 118 list_* migration artifacts). First eleven rows exactly as returned:

     key     |      name       |  type   | isUnique | contacts_with_value | contacts_with_nonblank
-------------+-----------------+---------+----------+---------------------+------------------------
 firstName   | First Name      | default | f        |               70333 |                  70333
 gender      | Gender          | custom  | f        |               70333 |                  70333
 isAnonymous | Anonymous       | custom  | f        |               70333 |                  70333
 name        | Full Name       | custom  | f        |               70333 |                  70333
 birthDate   | Birth Date      | custom  | f        |               70330 |                  70330
 email       | Email           | default | t        |               70198 |                  70198
 phoneNumber | Phone Number    | default | f        |               70050 |                  70050
 userCIC     | User CIC        | custom  | f        |               70026 |                  70026
 language    | Language        | custom  | f        |               65336 |                  65336
 lastName    | Last Name       | default | f        |               64875 |                  64875
 list_1171   | test fatma 0308 | custom  | f        |               59670 |                  59670

Three things worth knowing before you read a list like that:

The default keys are seeded per environment, not global. createEnvironment writes eight of them on the spot — userId, firstName, lastName, email, phoneNumber, facebookId, instagramId, twitterId, all with type = 'default', and only userId and email with isUnique = true (apps/web/lib/environment/service.ts:138-190). Two later migrations backfill phoneNumber and the three social keys into environments that predate them (20260423000000_add_phone_default_attribute, 20260713000000_add_social_default_attributes).

The phone key is phoneNumber, not phone. WHERE k.key = 'phone' returns nothing, silently, forever. Its display name has drifted — the code and the phone migration both write 'Phone', the migration-era dataset above shows 'Phone Number' — which is exactly why you match on key and never on name.

list_* keys are a migration artifact. In the migrated dataset, legacy audience lists arrived as keys named list_<legacyId> whose value is the string 'true' for members and absent for everyone else — a boolean smuggled through a text column. They are not part of the origin/development model; do not build a recipe that assumes they exist.

3. Contacts with an email

There is no email column, so this is a join — and the number it returns is not the contact count.

SELECT (SELECT count(*) FROM "Contact" WHERE "environmentId" = :'environment_id') AS contacts_total,
       count(*)                                      AS contacts_with_email_row,
       count(*) FILTER (WHERE btrim(a.value) <> '')  AS contacts_with_nonblank_email,
       count(*) FILTER (WHERE a.value LIKE '%@%.%')  AS contacts_with_at_sign
FROM "ContactAttribute" a
JOIN "ContactAttributeKey" k ON k.id = a."attributeKeyId"
WHERE k."environmentId" = :'environment_id'
  AND k.key = 'email';

Measured on hivecfm (migration-era):

 contacts_total | contacts_with_email_row | contacts_with_nonblank_email | contacts_with_at_sign
----------------+-------------------------+------------------------------+-----------------------
          70333 |                   70198 |                        70198 |                 70193

135 contacts have no email row at all, and 5 more hold something in the email field that does not even contain an @ and a .. Note also that the @@unique([contactId, attributeKeyId]) index guarantees count(*) here equals a distinct contact count — one email row per contact, maximum — so no DISTINCT is needed.

⚠️

“We have N contacts” and “we can email N contacts” are different numbers, and the gap can be the whole dataset. A prior internal audit of one client’s SMS-only source data found 102 of 252,000 contacts had an email at all. That figure is carried over from that audit and was not re-measured here; treat it as an illustration of the size of the gap, not as a number about this schema. Before you promise an email campaign, run the query above for that environment. A contact count is not a reachable-audience count, and no amount of "Contact" row counting will tell you the difference.

The listing form, when you need the addresses themselves:

SELECT c.id AS contact_id, c.created_at, a.value AS email
FROM "Contact" c
JOIN "ContactAttribute"    a ON a."contactId" = c.id
JOIN "ContactAttributeKey" k ON k.id = a."attributeKeyId"
                             AND k."environmentId" = c."environmentId"
WHERE c."environmentId" = :'environment_id'
  AND k.key = 'email'
  AND btrim(a.value) <> ''
ORDER BY c.created_at DESC
LIMIT 100;

4. Pivot attributes into columns

Why the naive join is wrong

Join the trio without aggregating and you get one row per attribute, not per contact:

SELECT c.id AS contact_id, k.key, a.value
FROM "Contact" c
JOIN "ContactAttribute"    a ON a."contactId" = c.id
JOIN "ContactAttributeKey" k ON k.id = a."attributeKeyId"
WHERE c."environmentId" = :'environment_id'
ORDER BY c.id, k.key
LIMIT 25;

Measured on hivecfm: 70,333 contacts produce 1,476,280 rows — 21.0 rows per contact. Any count(*), sum(), avg() or LIMIT layered on top of that shape is answering a question about attribute rows while appearing to answer one about people.

The pivot

Filtered aggregates collapse it back to one row per contact. Page the contacts first, then fan out — otherwise the GROUP BY has to aggregate the entire environment before the LIMIT can discard it:

WITH page AS (
    SELECT c.id, c.created_at
    FROM "Contact" c
    WHERE c."environmentId" = :'environment_id'
    ORDER BY c.created_at DESC
    LIMIT 50
),
wanted AS (
    SELECT k.id, k.key
    FROM "ContactAttributeKey" k
    WHERE k."environmentId" = :'environment_id'
      AND k.key IN ('email', 'firstName', 'lastName', 'phoneNumber', 'language')
)
SELECT p.id AS contact_id,
       p.created_at,
       max(a.value) FILTER (WHERE w.key = 'email')       AS email,
       max(a.value) FILTER (WHERE w.key = 'firstName')   AS first_name,
       max(a.value) FILTER (WHERE w.key = 'lastName')    AS last_name,
       max(a.value) FILTER (WHERE w.key = 'phoneNumber') AS phone_number,
       max(a.value) FILTER (WHERE w.key = 'language')    AS language
FROM page p
LEFT JOIN "ContactAttribute" a ON a."contactId" = p.id
LEFT JOIN wanted             w ON w.id = a."attributeKeyId"
GROUP BY p.id, p.created_at
ORDER BY p.created_at DESC;

Run against hivecfm (migration-era): a 50-contact page goes in and 50 rows come out — one row per contact, with the five columns populated.

Notes on the shape:

  • max() is not a real aggregate here — @@unique([contactId, attributeKeyId]) means at most one value can match each FILTER, so max() is just “the value, or NULL”. Do not read it as “the largest”.
  • Both LEFT JOINs matter. A contact with none of the five wanted attributes still returns a row of NULLs; a contact’s rows for keys outside wanted join with w.key IS NULL and are filtered out of every column.
  • The key list is scoped to the environment inside wanted, so a same-named key in another tenant cannot bleed in.
  • Every output column is text. Cast at the point of use, and defensively: NULLIF(btrim(value), '')::numeric still throws on 'N/A'. If you need arithmetic on an attribute, filter to rows matching '^-?\d+(\.\d+)?$' first.

5. Duplicate contacts, and what isUnique does not do

SELECT lower(btrim(a.value))                          AS normalized_value,
       count(*)                                       AS contact_count,
       count(DISTINCT a.value)                        AS distinct_raw_spellings,
       array_agg(a."contactId" ORDER BY a."contactId") AS contact_ids
FROM "ContactAttribute" a
JOIN "ContactAttributeKey" k ON k.id = a."attributeKeyId"
WHERE k."environmentId" = :'environment_id'
  AND k.key = 'email'
  AND btrim(a.value) <> ''
GROUP BY lower(btrim(a.value))
HAVING count(*) > 1
ORDER BY count(*) DESC, normalized_value
LIMIT 25;

Swap 'email' for any key. Grouping on lower(btrim(...)) catches the case and whitespace variants that an exact-value grouping misses; distinct_raw_spellings tells you which of the two you are looking at.

Measured on hivecfm, email key. The query above returns the offending addresses, which are contact PII, so what is reported here is a count wrapped around it — the same grouping, aggregated one level further:

 duplicated_email_values | contacts_involved
-------------------------+-------------------
                      22 |                72

Identical under both exact and normalized grouping in this dataset, so these are true collisions rather than casing artifacts.

🚫

That email key has isUnique = true. 22 duplicated values across 72 contacts, on a key the schema comment describes as “Whether the attribute must have unique values across contacts” (packages/database/schema.prisma:121). The comment describes an intention that no code implements.

Verified at origin/development: the only @@unique on "ContactAttribute" is ([contactId, attributeKeyId]) — one value per key per contact, which is a different guarantee entirely (schema.prisma:108). Outside tests, seeds and OpenAPI samples, isUnique is read in exactly two places, and both are about the key definition, not the values: the v2 management route refuses to PUT or DELETE a key whose isUnique is true (apps/web/modules/api/v2/management/contact-attribute-keys/[contactAttributeKeyId]/route.ts:93 and :166). No write path reads it at all — isUnique does not appear in a single non-test file under apps/web/modules/ee/contacts/, which is where the upsert, bulk and CSV-import paths live. Nothing can enforce a flag nothing reads.

Treat isUnique as a UI hint and an immutability flag. If you need uniqueness, deduplicate with the query above and enforce it yourself.

Contact matching, incidentally, does not use isUnique either — the bulk endpoint hard-codes const emailAttributeKey = "email" and falls back to email matching when no explicit identifier is supplied (apps/web/modules/ee/contacts/api/v2/management/contacts/bulk/lib/contact.ts:16-28).

6. Segments

The type behind the jsonb

"Segment".filters is jsonb NOT NULL DEFAULT '[]'::jsonb. The schema annotates it with a /// [SegmentFilter] comment, which prisma-json-types-generator resolves through a global namespace — so the real type is a three-hop chase:

So the top-level jsonb is an array of filter groups, each { id, connector: "and" | "or" | null, resource }, where resource is either a leaf filter or a nested TBaseFilters array. A leaf has four discriminated root.type values — attribute (with root.contactAttributeKey), person (root.personIdentifier), segment (root.segmentId), device (root.deviceType) — plus value and qualifier.operator (packages/types/segment.ts:62-116).

Note the name drift: the annotation says SegmentFilter, which in the types package is the name of a leaf (TSegmentFilter), but the column actually holds TBaseFilters. Chase the alias, not the label.

List the segments in an environment

SELECT s.id,
       s.title,
       s."isPrivate",
       jsonb_typeof(s.filters) AS filters_kind,
       CASE WHEN jsonb_typeof(s.filters) = 'array'
            THEN jsonb_array_length(s.filters) END AS top_level_groups,
       s.created_at
FROM "Segment" s
WHERE s."environmentId" = :'environment_id'
ORDER BY s.title;

The jsonb_typeof guard is not paranoia — jsonb_array_length raises on a non-array, so one malformed row would abort the whole listing. Uses Segment_environmentId_title_key.

Measured on hivecfm (migration-era): 1,177 segments, of which 1,036 have filters = '[]' and 1,058 are private.

A Segment row is not necessarily an audience. Creating an app survey creates a private segment alongside it, titled with the survey’s own id and with empty filters (apps/web/lib/survey/service.ts:782-793 on create, and a connectOrCreate on environmentId_title at :549-566 when a survey is switched to app). All 1,058 private segments in the dataset above are titled after an existing "Survey".id — verified by joining "Segment".title to "Survey".id, 1058 of 1058. Filter to NOT "isPrivate" when you want the segments a human actually built: 119 of 1,177 here.

Inspect one segment’s filters

SELECT g->>'id'                                      AS group_id,
       g->>'connector'                               AS connector,
       jsonb_typeof(g->'resource')                   AS resource_kind,
       g->'resource'->'root'->>'type'                AS root_type,
       coalesce(g->'resource'->'root'->>'contactAttributeKey',
                g->'resource'->'root'->>'personIdentifier',
                g->'resource'->'root'->>'deviceType',
                g->'resource'->'root'->>'segmentId') AS root_target,
       g->'resource'->'qualifier'->>'operator'       AS operator,
       g->'resource'->>'value'                       AS value
FROM "Segment" s
CROSS JOIN LATERAL jsonb_array_elements(s.filters) AS g
WHERE s."environmentId" = :'environment_id'
  AND s.id = :'segment_id';

resource_kind is the discriminator you need: object is a leaf filter and every other column is populated; array is a nested group and root_type onward come back NULL — recurse into g->'resource' for those.

Measured on hivecfm, one real segment:

 group_id                 | connector | resource_kind | root_type | root_target | operator | value
--------------------------+-----------+---------------+-----------+-------------+----------+-------
 tksw60puwh3xov4hmqey9ttq |           | object        | attribute | name        | contains | fa

Across every segment in that environment the distribution was attribute/equals (119) and attribute/contains (22) — no person, device or nested segment filters at all, and no nested groups. A dataset with no nested segments does not prove nesting is unused in general; it only means this dataset cannot exercise your recursion.

Membership: there are two evaluators, and they disagree

origin/development contains two independent implementations of segment semantics.

Compiles to SQLEvaluates in JS
Entry pointsegmentFilterToPrismaQueryevaluateSegment
Fileapps/web/modules/ee/contacts/segments/lib/filter/prisma-query.ts:253apps/web/modules/ee/contacts/segments/lib/segments.ts:483
OutputPrisma.ContactWhereInput, executed by Postgresa boolean, per contact, in Node
Called fromcontact listing (modules/ee/contacts/lib/contacts.ts:30), personal-link generation (modules/api/v2/management/surveys/[surveyId]/contact-links/segments/[segmentId]/lib/contact.ts:46)two app-survey targeting paths: getPersonSegmentIds (modules/ee/contacts/api/v1/client/[environmentId]/user/lib/segments.ts:61) and the app sync filter (app/api/v1/client/[environmentId]/app/sync/lib/survey.ts:118)

So evaluation is pushed to SQL — for the paths that list contacts. App-survey targeting takes the other path and never touches SQL. And the two do not agree.

🚫

Observed divergence — case sensitivity. The translator asks for a case-insensitive contains (prisma-query.ts:72, { contains: String(value), mode: "insensitive" }). The JS evaluator uses String.prototype.includes, which is case-sensitive (segments.ts:465-466).

The real segment shown above (attribute name contains 'fa') measured on hivecfm: 1,215 contacts case-insensitively, 374 case-sensitively. One segment definition, two answers, 3.2× apart. The two evaluators cannot both be right about this segment.

A second divergence is visible in the code but was not exercised by this dataset, which contained only equals and contains filters — read it as a code-level finding, not a measurement. ZSegmentFilter refuses an arithmetic operator whose value is not a number (packages/types/segment.ts:119-140), so greaterThan filters always carry a JS number. The JS evaluator then compares numerically ((a as number) > (b as number), segments.ts:458). The translator stringifies it instead — { gt: String(value) }, prisma-query.ts:84 — against a text column, which makes it a collation-ordered text comparison. In devhub_ref (collation en_US.utf8):

SELECT '100' > '20' AS text_comparison, 100 > 20 AS numeric_comparison;
--  text_comparison | numeric_comparison
-- -----------------+--------------------
--  f               | t

An attribute value of '100' therefore satisfies greaterThan 20 in the JS evaluator and fails it in the SQL one.

Mirroring a simple segment in SQL

For a single flat attribute filter you can reproduce the SQL-side evaluator faithfully. This is the mirror of the name contains 'fa' segment:

SELECT count(*) AS contacts_matching
FROM "Contact" c
WHERE c."environmentId" = :'environment_id'
  AND EXISTS (
        SELECT 1
        FROM "ContactAttribute"    a
        JOIN "ContactAttributeKey" k ON k.id = a."attributeKeyId"
        WHERE a."contactId"     = c.id
          AND k."environmentId" = c."environmentId"
          AND k.key             = :'attribute_key'
          AND a.value ILIKE '%' || :'value' || '%'
      );

EXISTS rather than a join, so a contact is counted once regardless of how many attribute rows it has. k."environmentId" = c."environmentId" constrains both parents, per the scoping warning above. Uses ContactAttributeKey_key_environmentId_key then ContactAttribute_attributeKeyId_value_idx.

To mirror a different operator, swap the value predicate — and keep the case-insensitivity the translator asks for, because that is part of the semantics:

  • equals → a.value ILIKE :'value'. prisma-query.ts:66 requests mode: "insensitive", so a plain = :'value' is a different query.
  • startsWith → a.value ILIKE :'value' || '%' (prisma-query.ts:78). endsWith → a.value ILIKE '%' || :'value' (:81).
  • isSet / isNotSet change the shape, not the predicate. The translator drops the value test entirely (prisma-query.ts:41-49), so isSet is the block above with the a.value line removed, and isNotSet is that same reduced block under NOT EXISTS. Negating the block as written would mean “has no matching value”, which is not what isNotSet compiles to.
⚠️

Do not generalise that mirror. Three specific things break it:

  1. Nested segment roots. buildSegmentFilterWhereClause (prisma-query.ts:153) resolves a referenced segment with an await getSegment(segmentId) — an application-code database read, recursive, with its own cycle guard. There is no SQL you can write that follows it without re-implementing that loop.
  2. Connector handling. processFilters (prisma-query.ts:207) reads filters[1].connector when it processes element 0 (:235), i.e. the first group’s AND/OR placement depends on its successor. Reproducing multi-group logic means reproducing that, not reading the connectors left to right.
  3. There is no single membership to mirror. Given the divergence above, “the contacts in segment X” has two different answers inside HiveCFM itself, depending on which code path asked. A SQL mirror can match one of them. It cannot be authoritative about both.

Use SQL to inspect a segment definition and to sanity-check a simple one. For an authoritative membership list, call the application path that the feature you care about actually uses.

7. Contact attributes and RLS: the confusing failure mode

"ContactAttribute" is the one table in the schema with row-level security enabled and no policy. On devhub_ref, after running the origin/development RLS scripts:

SELECT c.relname            AS table_name,
       c.relrowsecurity     AS rls_enabled,
       count(p.policyname)  AS policies
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = 'public'
LEFT JOIN pg_policies p ON p.schemaname = 'public' AND p.tablename = c.relname
WHERE c.relname IN ('Contact', 'ContactAttribute', 'ContactAttributeKey', 'Segment')
GROUP BY 1, 2
ORDER BY 1;
     table_name      | rls_enabled | policies
---------------------+-------------+----------
 Contact             | t           |        1
 ContactAttribute    | t           |        0
 ContactAttributeKey | t           |        1
 Segment             | t           |        1

The cause is a one-word typo. scripts/rls/enable-rls.sql turns RLS on for "ContactAttribute" and succeeds; scripts/rls/create-policies.sql then fails on that table with ERROR: column "contactAttributeKeyId" does not exist. The real column is attributeKeyId. Because psql -f continues past a failed statement and the script ends by selecting a success message, the run reports success either way.

🚫

What this looks like when it bites you. In Postgres, a table with RLS enabled and no policy denies every row — it is not “no restriction”, it is “no permission”. Verified in an isolated scratch database: a non-bypassing role reading a table with RLS plus a permissive policy saw 1 row; reading a table with RLS and zero policies it saw 0; the superuser saw 1 in both.

So on a hardened database — one where the application connects as a non-owner, non-superuser role — every query on this page that joins "ContactAttribute" returns zero rows, while SELECT * FROM "Contact" keeps returning rows normally. Contacts exist and have no attributes. Nobody has an email. Every segment is empty. Nothing errors.

Locally this is invisible: the dev stack connects as postgres, which bypasses RLS entirely unless FORCE ROW LEVEL SECURITY is set. Run the pg_class query above before you conclude the data is missing. Full RLS model, the second defect (Channel / channels), and why a green script run proves nothing: Read this first.

One more thing RLS will not do for you: the policies at origin/development are USING-only, with no WITH CHECK, and the app.current_tenant GUC left unset means every row of every tenant is visible. That is why every recipe on this page carries an explicit :'environment_id'. Do not drop it because “RLS handles it”.

Where to look in the code

  • hivecfm-core/packages/database/schema.prisma:98-164 — ContactAttribute, ContactAttributeKey (isUnique at :130), and Contact. The @@unique([contactId, attributeKeyId]) at :108 is the only uniqueness the database enforces on attribute values.
  • hivecfm-core/packages/database/schema.prisma:1255-1271 — Segment, with the /// [SegmentFilter] annotation at :1262.
  • hivecfm-core/packages/database/json-types.ts:71 — PrismaJson.SegmentFilter = TBaseFilters, the middle hop of the type chase.
  • hivecfm-core/packages/types/segment.ts — TBaseFilter/TBaseFilters at :173-179, the four leaf filter shapes at :62-116, the operator lists at :4-52, and the refine that forces arithmetic values to be numbers at :119-140.
  • hivecfm-core/apps/web/modules/ee/contacts/segments/lib/filter/prisma-query.ts — the SQL-side evaluator. Operator mapping at :64-97, nested-segment recursion at :153, connector logic at :207-248, entry point at :253.
  • hivecfm-core/apps/web/modules/ee/contacts/segments/lib/segments.ts — the JS-side evaluator. compareValues at :443-476, evaluateSegment at :483.
  • hivecfm-core/apps/web/modules/ee/contacts/api/v1/client/[environmentId]/user/lib/segments.ts — getPersonSegmentIds, the app-survey targeting path that uses the JS evaluator.
  • hivecfm-core/apps/web/lib/environment/service.ts:138-190 — the eight default ContactAttributeKey rows every new environment gets.
  • hivecfm-core/apps/web/modules/api/v2/management/contact-attribute-keys/[contactAttributeKeyId]/route.ts:93,166 — the only two places isUnique changes behaviour, both about the key definition rather than the values.
  • hivecfm-core/apps/web/modules/ee/contacts/api/v2/management/contacts/bulk/lib/contact.ts — bulk contact matching, including the hard-coded email fallback key.
  • hivecfm-core/apps/web/lib/survey/service.ts:549-566,782-793 — where the private per-survey Segment rows come from.
  • hivecfm-core/scripts/rls/enable-rls.sql and scripts/rls/create-policies.sql — the RLS scripts, and the contactAttributeKeyId typo that leaves ContactAttribute deny-all.
  • Read this first — table and column naming traps, the RLS model, and which database to run what against.
  • Responses & answers — Response.data is keyed by survey element id, and responses are separated from invitations by a column.
  • Channels & campaigns — where a Segment becomes an actual send.
  • Schema Viewer — the interactive ERD for the trio described here.

HiveCFM Developer Hub — internal team guide