RAIA™ Specification

Person Data Architecture

Our contact database used to mix everything together — a lead who just enquired about a viewing sat next to a tenant whose passport we hold. Three expert reviewers looked at this and agreed: the datab

← Back to Developer Hub TEXTBOOK SPECIFICATION
RAIA™ (Real estate Artificial Intelligence Agent) Specification

Our contact database used to mix everything together — a lead who just enquired about a viewing sat next to a tenant whose passport we hold. Three expert reviewers looked at this and agreed: the datab

🧩 Section A: In Plain English

Person Data Architecture

Our contact database used to mix everything together — a lead who just enquired about a viewing sat next to a tenant whose passport we hold. This page explains how we reorganised it so sensitive identity data is kept separate from basic contact details.

🟢 In Plain English

Our contact database used to mix everything together — a lead who just enquired about a viewing sat next to a tenant whose passport we hold. Three expert reviewers looked at this and agreed: the database needs to be cleaner. This page explains how we reorganised it so sensitive identity data is kept separate from basic contact details.

Person Data Architecture

How tbl_persons and its satellite tables should be structured — normalization violations identified, three-expert consensus captured, migration path defined, and SJT data-collection gates mapped.

Schema Design 1NF / 2NF / 3NF GDPR-Aligned SJT Stage 4 Gate
60,636
Total persons in tbl_persons across all tenants
51k
Lead contacts — name + email + phone only, never get PII
3
Expert models consulted — Normalization, Employment, GDPR
5
Schema changes recommended across base table and satellites
📌

TL;DR. tbl_persons has three design flaws: (1) nationality is free-text — a 3NF violation that makes dual-nationality impossible and creates update anomalies. (2) qualification_01/02/03 flat columns are a 1NF repeating-group violation. (3) date_of_birth sits in the base table next to 51k leads who should never hold DOB — a GDPR risk. This guide captures the three-expert consensus on how to fix all three without a full table rewrite, and maps exactly when each field is collected in the SJT workflow.


Chapter 1 Why the Schema Needs Work

The RAIA (Real estate Artificial Intelligence Agent) person database has grown organically from a simple CRM into a multi-role system serving leads, active tenants, past tenants, landlords, and guarantors. The tbl_persons base table has accreted columns over time without a formal normalization review. Three specific design flaws are now causing operational pain and legal risk.

Current State — What's Broken
  • nationality is free-text VARCHAR — misspellings ("Bristish"), dual-nationality impossible, update anomaly if the canonical name changes
  • qualification_01, qualification_02, qualification_03 are flat repeating groups — adding a 4th qualification requires an ALTER TABLE
  • date_of_birth sits in the base table — 51k leads could accidentally receive a DOB value, a GDPR data-minimisation violation
  • employment_status and occupation live in tbl_persons with no employer name or dates — employment history is impossible to reconstruct
  • tbl_persons_identity exists but is empty — passport/ID data has no safe home yet
  • tbl_persons_career exists but is empty — employment history has no safe home yet
Target State — What We're Building
  • nationality_code CHAR(2) FK to a ref_countries table on tbl_persons — ISO-3166-1 alpha-2, dual nationality via tbl_persons_identity
  • All qualification rows in tbl_persons_qualifications — one row per credential, infinitely extensible
  • date_of_birth removed from tbl_persons, lives only in tbl_persons_identity which has a strict access gate
  • employment_status stays in tbl_persons as an FK enum (CRM current-state). Employer name, income, and dates move to tbl_persons_career
  • tbl_persons_identity activated with passport data, DOB, nationality detail — populated only at SJT Stage 4

The Population Breakdown: Why This Matters

The 60,636 persons in tbl_persons are not a homogeneous group. They span four categories with radically different PII requirements:

Segment Count What They Provided What They Should Never Have
Leads ~51,000 Name, email, phone only (viewing enquiry) DOB, passport data, nationality detail, employment history
Active / Past Tenants ~3,000 Full referencing package — post-offer —
Landlords ~500 Name, email, phone + company details DOB (unless personally guaranteeing a let)
Guarantors ~100 Full referencing package — post-offer —

The core architectural risk: if date_of_birth sits in the base table, any INSERT or bulk import for the 51k leads could accidentally write a DOB value. With PII in the satellite tables, the worst case is a null join — not a GDPR incident.

The Four Specific Problems

  • 1
    Free-text nationality — 3NF Transitive Dependency

    The column stores raw strings like "British", "British National (Overseas)", "britsh". There is a transitive dependency: person_id → nationality (string) → iso_code, demonym, continent. Any facts about a nationality are determined by the nationality name, not by the person ID directly. This is the textbook 3NF violation. Dual-nationality is structurally impossible — the column holds exactly one value.

  • 2
    qualification_01/02/03 — 1NF Repeating Groups

    Three identically-structured columns for the same fact type (qualifications held) is the definition of a 1NF repeating-group violation. If a tenant has four qualifications, there is no column to store the fourth. Querying "all persons with a specific qualification" requires three separate LIKE conditions ORed together. The data is not atomically separated by its own key.

  • 3
    Employment fields without history — Design Smell

    employment_status and occupation on tbl_persons are technically not a normalization violation if no employer name appears alongside them (no partial dependency on a composite key). However, they create a design smell: the fields imply a current-state snapshot but provide no way to store the employment history that referencing checks actually require. "Were you employed from Jan 2023 to Dec 2023?" is unanswerable.

  • 4
    date_of_birth in base table — GDPR Data Minimisation Risk

    DOB is special-category-adjacent data under GDPR Article 9 (it can be combined with name to fingerprint a person across datasets). Keeping it in the base table means any developer writing a simple SELECT * from tbl_persons retrieves DOB for all 60k persons — including the 51k leads who never consented to identity data collection. The correct treatment is sequestration in tbl_persons_identity, accessed only via the PII access-log gate.


Chapter 2 Three-Expert Panel Consensus

Three independent expert models were consulted on the schema design. Each was given the full tbl_persons column list (37 cols), the satellite table schemas, and the population breakdown. Their verdicts converged on five concrete changes.

A
Expert A — Database Normalization Specialist
Focus: relational theory, update anomalies, referential integrity
Verdict: 3NF Violation — Nationality Must Be Extracted
"The free-text nationality column is a textbook transitive dependency. You have person_id → nationality_string, but the string itself carries additional implied facts — ISO code, demonym, continent — that are determined by the nationality name, not the person. That's a transitive functional dependency and a direct 3NF violation. Worse, the single-column design makes dual nationality structurally impossible. A Thai-British national cannot be represented. Move to nationality_code CHAR(2) FK on the base table for CRM filtering, and store the full nationality record alongside DOB in tbl_persons_identity where it belongs."
  • Remove free-text nationality column from tbl_persons
  • Add nationality_code CHAR(2) FK referencing a ref_countries lookup table on tbl_persons
  • Add nationality_code_2 CHAR(2) (nullable) for dual nationality — also FK to ref_countries
  • Store full nationality name, ISO code, and continent in ref_countries (single source of truth)
  • Migrate existing string values via a one-time fuzzy-match script against ISO-3166-1 alpha-2
B
Expert B — CRM Data Architecture Specialist
Focus: employment data, career history, operational query patterns
Verdict: Employment Status Stays — History Moves Out
"occupation and employment_status on tbl_persons are not a strict normalization violation — there's no partial key dependency because tbl_persons has a simple primary key. The real issue is the semantic mismatch. employment_status is a current-state label your CRM queries need constantly — 'show me all employed applicants' is a live filter. Keep it. But employer name, income, and employment dates are historical facts that change over time and multiply across tenancies. Those belong in tbl_persons_career with a person_id FK and date range columns. Without that table, referencing affordability checks are impossible to audit retrospectively."
  • Keep employment_status as FK to ref_employment_status enum on tbl_persons — it's a current-state CRM filter
  • Keep occupation as a free-text descriptor on tbl_persons — job title changes infrequently and is display-only
  • Add employer_name, employer_address, income_annual_gbp, employment_start_date, employment_end_date to tbl_persons_career
  • One row per employment stint — null employment_end_date = current employer
  • Link via person_id FK — multiple career rows per person supported
C
Expert C — GDPR & Data Privacy Counsel
Focus: data minimisation, lawful basis, subject access, retention
Verdict: DOB Must Leave the Base Table Immediately
"date_of_birth is not Article 9 special category data on its own — but it is a strong quasi-identifier. Combined with name, it enables cross-dataset linkage. The legal risk isn't just GDPR Art. 5(1)(c) data minimisation — it's the practical exposure from a data breach. If tbl_persons leaks, 60,636 people's dates of birth are exposed, including 51,000 leads who attended a viewing and consented to nothing beyond basic contact processing. Keep DOB exclusively in tbl_persons_identity. The access gate for that table is the PII access log (tbl_pii_access_log). Any query touching DOB goes through the gate — justified access only, logged, auditable."
  • Remove date_of_birth from tbl_persons
  • Confirm date_of_birth lives in tbl_persons_identity — gated by tbl_pii_access_log
  • Verify no existing data: SELECT COUNT(*) FROM tbl_persons WHERE date_of_birth IS NOT NULL — if > 0, migrate before dropping column
  • Add a database-level constraint or trigger that fires an error if any INSERT writes DOB to tbl_persons
  • Update all application code to read DOB exclusively via the tbl_persons_identity join with access-log gate

Normalization Theory Applied to This CRM

The three normal forms are not abstract theory here — each maps to a concrete schema flaw in tbl_persons.

First Normal Form (1NF)
Every column must hold an atomic, indivisible value. No repeating groups.
RAIA (Real estate Artificial Intelligence Agent) violation: qualification_01, qualification_02, qualification_03 are three identically-typed columns representing the same set-valued attribute. Each "slot" is structurally identical. This is the canonical repeating-group violation. Fix: one row per qualification in tbl_persons_qualifications, keyed by (person_id, qualification_type, awarded_date).
Second Normal Form (2NF)
Must be in 1NF, and every non-key attribute must depend on the whole primary key — not a subset of it.
RAIA (Real estate Artificial Intelligence Agent) status: tbl_persons has a simple single-column primary key (person_id UUID), so 2NF is trivially satisfied. Partial dependencies only arise with composite keys. No 2NF violation exists here.
Third Normal Form (3NF)
Must be in 2NF, and no non-key attribute may transitively depend on another non-key attribute.
RAIA (Real estate Artificial Intelligence Agent) violation: nationality (free-text) → iso_code, demonym, continent. These implied facts are determined by the nationality string, not by person_id directly. That's the transitive dependency chain 3NF forbids. Fix: extract to ref_countries, reference via nationality_code CHAR(2) FK.

Data Collection Timing Decision

⚖️

The core question: At what point in the tenancy journey do we collect identity documents, DOB, and nationality detail? The answer has GDPR, UX, and conversion-rate implications. The three experts were unanimous on the decision.

❌ Viewing Booking — NOT here

Viewing booking captures name + email + phone only. No DOB, no passport, no nationality. The lawful basis at this stage is legitimate interest (property enquiry). Collecting identity documents at viewing booking would be disproportionate, damage conversion rates, and fail the GDPR proportionality test. These contacts become leads in tbl_persons.

⚠ Optional ID Badge (Voluntary)

Tenants may voluntarily submit an ID badge pre-viewing if they choose. This is an opt-in feature only — never prompted, never required. Consent is the lawful basis. If submitted, the data goes directly to tbl_persons_identity — never to the base table. Most tenants do not use this option.

✓ Post-Offer / Referencing — SJT Stage 4

Full identity data collection is triggered by a formal tenancy offer. At SJT Stage 4 (Referencing, conducted by Homeppl or equivalent), the applicant provides: passport scan, DOB, employment history, qualifications, and nationality. The lawful basis is contractual necessity. This is the only point at which tbl_persons_identity and tbl_persons_career rows are created.

Recommended Final Schema — Fields by Table

After applying all three expert recommendations, here is which fields live in which table and why.

tbl_persons Base CRM Table 60,636 rows — all contacts including leads
Column Type Action Rationale
person_idUUID PKKeepPrimary key — unchanged
full_nameVARCHARKeepDisplay and search — all contacts have this
email_primaryVARCHARKeepCRM primary contact — all contacts
phone_primaryVARCHARKeepCRM primary contact — all contacts
nationality_codeCHAR(2) FKAddISO-3166-1 alpha-2 — replaces free-text nationality
nationalityVARCHAR (old)Remove3NF violation — replaced by nationality_code FK
employment_statusFK enumKeepCurrent-state CRM filter — referenced constantly by agents
occupationVARCHARKeepDisplay-only job title — not history
date_of_birthDATE (old)RemoveGDPR risk — leads should never have DOB
qualification_01/02/03VARCHAR (old)Remove1NF violation — migrated to tbl_persons_qualifications
avatar_urlVARCHARKeepNon-sensitive display photo — all contacts
person_roleFK enumKeepLead / Tenant / Landlord / Guarantor — routing
tbl_persons_identity Identity Table — PII Gated Created, empty — populated at SJT Stage 4
Column Type Action Rationale
identity_idUUID PKKeepPrimary key
person_idUUID FKKeepLinks to tbl_persons
date_of_birthDATEMove hereMoved from tbl_persons — gated by PII access log
nationality_codeCHAR(2) FKKeepPrimary nationality — full detail alongside DOB
nationality_code_2CHAR(2) FKAddSecond nationality — dual-nationality support
passport_numberVARCHAR encryptedKeepEncrypted at rest — accessed only at referencing
passport_expiryDATEKeepRight to Rent validity check
passport_country_codeCHAR(2) FKKeepIssuing country — may differ from nationality
sumsub_applicant_idVARCHARKeepSumsub KYC integration reference
collected_at_stageSMALLINTAddSJT stage at collection (4 = referencing, 99 = voluntary pre-viewing)
tbl_persons_career Career / Employment History Empty — populated at referencing stage
Column Action Notes
career_id UUID PKKeepPrimary key
person_id UUID FKKeepMultiple rows per person — one per employer stint
employer_name VARCHARAddMoved here from nowhere — was absent from current schema
employer_address TEXTAddFor referencing contact purposes
income_annual_gbp NUMERIC(10,2)AddAffordability calculation input
employment_start_date DATEAddGap detection for referencing
employment_end_date DATE nullableAddNULL = current employer
employment_type FK enumAddEmployed / Self-employed / Contract / Zero-hours
verified_at TIMESTAMPTZAddWhen referencing agent confirmed employment
tbl_persons_qualifications Qualifications — Normalized 41 rows — replaces qualification_01/02/03 flat columns
Column Action Notes
qualification_id UUID PKKeepExisting schema
person_id UUID FKKeepOne row per qualification per person
qualification_type VARCHARKeepe.g. "ARLA Propertymark", "NRLA Accreditation", "RICS"
institution VARCHARKeepAwarding body
awarded_date DATEKeepFor sorting most recent first
expiry_date DATE nullableKeepFor compliance alerts
certificate_url VARCHARKeepGCS link to scanned certificate

Chapter 3 Migration Plan

Three SQL statements fix the three immediate normalization issues without a full table rewrite. Each is an ALTER TABLE that can be applied in isolation and rolled back if needed. Apply in order.

Migration Step 1 — Remove date_of_birth from Base Table

⚠️

Before running Step 1: verify zero rows have DOB populated. If any exist, run the backfill INSERT into tbl_persons_identity first, then drop the column.

Check: SELECT COUNT(*) FROM tbl_persons WHERE date_of_birth IS NOT NULL;

-- ============================================================
-- Migration Step 1: Move date_of_birth out of base table
-- Pre-check: confirm 0 rows have DOB populated
-- ============================================================

-- 1a. Backfill any existing DOB values into tbl_persons_identity
--     (only runs if pre-check finds rows)
INSERT INTO tbl_persons_identity (
  identity_id, person_id, date_of_birth, collected_at_stage, created_at
)
SELECT
  gen_random_uuid(),
  person_id,
  date_of_birth,
  99,   -- unknown collection stage — mark for review
  now()
FROM tbl_persons
WHERE date_of_birth IS NOT NULL
ON CONFLICT (person_id) DO UPDATE
  SET date_of_birth = EXCLUDED.date_of_birth;

-- 1b. Drop the column from base table
ALTER TABLE tbl_persons
  DROP COLUMN IF EXISTS date_of_birth;

Migration Step 2 — Replace Free-text Nationality with ISO FK

-- ============================================================
-- Migration Step 2: Replace nationality VARCHAR with FK
-- Pre-check: ref_countries table must exist with iso_alpha2 PK
-- ============================================================

-- 2a. Add the new normalised FK column
ALTER TABLE tbl_persons
  ADD COLUMN IF NOT EXISTS nationality_code CHAR(2)
    REFERENCES ref_countries(iso_alpha2)
    ON UPDATE CASCADE;

-- 2b. Best-effort backfill from free-text (common cases)
--     Extend this list as you discover variants in your data
UPDATE tbl_persons
SET nationality_code = CASE
  WHEN lower(nationality) IN ('british', 'uk', 'english', 'british national') THEN 'GB'
  WHEN lower(nationality) IN ('thai', 'thailand') THEN 'TH'
  WHEN lower(nationality) IN ('american', 'us', 'usa') THEN 'US'
  WHEN lower(nationality) IN ('french', 'france') THEN 'FR'
  WHEN lower(nationality) IN ('german', 'germany') THEN 'DE'
  WHEN lower(nationality) IN ('australian', 'australia') THEN 'AU'
  WHEN lower(nationality) IN ('indian', 'india') THEN 'IN'
  WHEN lower(nationality) IN ('chinese', 'china') THEN 'CN'
  ELSE NULL  -- unmatched values flagged for manual review
END
WHERE nationality IS NOT NULL;

-- 2c. Drop old free-text column after backfill verified
--     Run: SELECT COUNT(*) FROM tbl_persons WHERE nationality IS NOT NULL AND nationality_code IS NULL;
--     Must be 0 before dropping
ALTER TABLE tbl_persons
  DROP COLUMN IF EXISTS nationality;

Migration Step 3 — Migrate Qualification Flat Columns to Child Table

-- ============================================================
-- Migration Step 3: Migrate qualification_01/02/03 to
-- tbl_persons_qualifications (already has correct schema)
-- ============================================================

-- 3a. Insert qualification_01 rows where populated
INSERT INTO tbl_persons_qualifications (
  qualification_id, person_id, qualification_type, created_at
)
SELECT
  gen_random_uuid(),
  person_id,
  qualification_01,
  now()
FROM tbl_persons
WHERE qualification_01 IS NOT NULL AND qualification_01 != '';

-- 3b. Insert qualification_02 rows
INSERT INTO tbl_persons_qualifications (
  qualification_id, person_id, qualification_type, created_at
)
SELECT
  gen_random_uuid(),
  person_id,
  qualification_02,
  now()
FROM tbl_persons
WHERE qualification_02 IS NOT NULL AND qualification_02 != '';

-- 3c. Insert qualification_03 rows
INSERT INTO tbl_persons_qualifications (
  qualification_id, person_id, qualification_type, created_at
)
SELECT
  gen_random_uuid(),
  person_id,
  qualification_03,
  now()
FROM tbl_persons
WHERE qualification_03 IS NOT NULL AND qualification_03 != '';

-- 3d. Verify counts match before dropping flat columns
--     SELECT COUNT(*) FROM tbl_persons_qualifications; -- should = sum of non-null qual_01/02/03

-- 3e. Drop the flat columns
ALTER TABLE tbl_persons
  DROP COLUMN IF EXISTS qualification_01,
  DROP COLUMN IF EXISTS qualification_02,
  DROP COLUMN IF EXISTS qualification_03;

Chapter 4 SJT Integration — Which Stage Triggers What

RAIA's Single Journey Tenancy (SJT) is a 14-stage workflow from first enquiry to tenancy completion. Each stage has a defined data-collection gate. This chapter maps exactly which stage populates which table.

SJT Data Collection Swim-Lane Diagram

SJT Data Collection Gates — tbl_persons Architecture Which fields are populated at which stage of the Single Journey Tenancy SJT STAGE tbl_persons (BASE) tbl_persons_identity tbl_persons_career tbl_persons_qualifications

Repository Code

The live codebase implementation for this specification sits within the following repository folder:

font-weight="700" text-anchor="middle">Stage 1 Viewing Enquiry Lead Created INSERT tbl_persons full_name · email_primary phone_primary · person_role=LEAD — NO ROW CREATED — — NO ROW CREATED — — NO ROW CREATED — Stage 2 Viewing Booked Optional ID Badge UPDATE tbl_persons viewing_datetime · property_ref status = VIEWING_BOOKED Optional only if tenant voluntarily submits ID badge Stage 3 Offer Made Offer Accepted UPDATE tbl_persons person_role = APPLICANT offer_date · property_ref ★ Stage 4 REFERENCING PII Collection GATE OPENS UPDATE tbl_persons employment_status · occupation nationality_code person_role = TENANT INSERT identity row date_of_birth · passport_no passport_expiry · nationality_2 sumsub_applicant_id INSERT career row(s) employer_name · income start_date · end_date employment_type INSERT qual row(s) qualification_type institution · awarded_date certificate_url Stage 5+ Tenancy Active Ongoing Management UPDATE as needed avatar_url · phone · email employment_status (if changes) R2R re-check at expiry (passport_expiry alert) LEGEND Stage 4 PII Gate — only point where identity, career, and qualifications are written Green cells = rows created in satellite table Amber cells = career data (employment history) Blue cells = qualifications data No row created — table intentionally empty for this segment 51k leads never trigger identity/career/qualifications rows

The Lead → Tenant PII Gate

The most critical guard in the whole architecture is the transition from lead to tenant. This transition happens at SJT Stage 4 and is the only legitimate point at which identity data is written.

🔐

The gate rule: A row in tbl_persons_identity must only be created when tbl_persons.person_role is being set to TENANT or GUARANTOR — or already is. Any code path that writes to tbl_persons_identity for a person with person_role = LEAD is a bug and a potential GDPR incident. This rule must be enforced at both application layer and, ideally, as a database check constraint or trigger.

What Happens at the Gate

  • 1
    Offer Accepted → SJT Stage 4 Triggered

    Agent marks offer as accepted in RAIA. System automatically transitions the SJT to Stage 4 and sends referencing invitation via Homeppl.

  • 2
    Applicant Completes Referencing Form

    Homeppl or equivalent referencing provider collects: passport scan, DOB, nationality, address history, employment history, qualifications. Sumsub KYC runs biometric check.

  • 3
    RAIA (Real estate Artificial Intelligence Agent) Writes Identity Records

    On referencing completion webhook: INSERT into tbl_persons_identity, INSERT into tbl_persons_career, INSERT into tbl_persons_qualifications. UPDATE tbl_persons.person_role = 'TENANT'. Log to tbl_pii_access_log.

  • 4
    Access Log Entry Created

    Every INSERT to tbl_persons_identity creates a corresponding row in tbl_pii_access_log: who wrote it, when, which SJT stage, which referencing job ID. INSERT-only table — no UPDATEs or DELETEs permitted on the log.

What Never Happens at the Gate

Prohibited Actions — GDPR Violations
  • Writing DOB to tbl_persons for any person at any stage
  • Creating a tbl_persons_identity row for a lead (person_role = LEAD)
  • Capturing passport data at viewing booking
  • Prompting for DOB on the viewing enquiry form
  • Bulk-importing employment history without a signed referencing consent form
  • Writing nationality detail without the applicant's consent at Stage 4
Edge Case — Voluntary Pre-Viewing ID Badge

If a tenant voluntarily chooses to submit an ID badge before their viewing (to speed up referencing later), the data goes to tbl_persons_identity with collected_at_stage = 99. The person_role must be updated from LEAD to PRE_VERIFIED before this write. Never write identity data for a LEAD role without first recording explicit consent.


Pitfalls — 8 Entries

P-01
Writing DOB to tbl_persons — Silent GDPR Incident

After the migration, if any code path writes date_of_birth to tbl_persons, it will succeed if the column still exists (pre-migration) or silently fail if it was dropped. A soft failure is worse — the field exists but data never writes, so the test looks green but the referencing data is missing. Add a migration timestamp constraint and a not-null gate on the identity table side. Run SELECT COUNT(*) FROM tbl_persons WHERE date_of_birth IS NOT NULL weekly until the column is confirmed dropped.

P-02
Dropping nationality Column Before Backfill is Complete

If you drop the old nationality VARCHAR column before all rows have been matched to a nationality_code, you lose the original string permanently. The fuzzy-match backfill (Step 2b) will not catch every variant. Run SELECT nationality, COUNT(*) FROM tbl_persons WHERE nationality IS NOT NULL AND nationality_code IS NULL GROUP BY nationality ORDER BY COUNT(*) DESC to see what's unmatched. Handle manually before dropping.

P-03
Qualification Deduplication Not Handled

If the same person has "ARLA" in qualification_01 and the same string in qualification_02, the migration INSERT (Steps 3a/3b) will create two rows in tbl_persons_qualifications for the same qualification. Add a UNIQUE(person_id, qualification_type) constraint to tbl_persons_qualifications before running the migration, or the INSERT will create silent duplicates. The constraint will surface duplicates as errors you can inspect.

P-04
nationality_code FK Without ref_countries Table = All Inserts Fail

Step 2a adds a FOREIGN KEY constraint referencing ref_countries(iso_alpha2). If that table does not exist when the migration runs, the ALTER TABLE will fail and the column won't be added. Ensure ref_countries is seeded with ISO-3166-1 alpha-2 codes before running Step 2. The simplest seed: a 250-row INSERT of the standard ISO country list — available as a CSV from iso.org.

P-05
Dual Nationality Not the Same as Dual Passport

nationality_code and nationality_code_2 on tbl_persons_identity capture nationality. passport_country_code captures the issuing country of the presented document. These are not the same. A British-Thai dual national may present a Thai passport — passport_country_code = 'TH', nationality_code = 'GB', nationality_code_2 = 'TH'. Don't conflate the fields or you will produce incorrect Right to Rent reports.

P-06
employment_status as Free-Text After Migration

Expert B recommended keeping employment_status as an FK enum on tbl_persons. If it currently stores free-text values, creating the FK will fail on any row with an unrecognised status string. Run SELECT DISTINCT employment_status FROM tbl_persons to enumerate all current values, create the ref_employment_status enum table with those values, then add the FK constraint. Don't assume the column holds clean enum values.

P-07
tbl_referencing_checks Has Only 13 Rows — Not the Source of Truth

The tbl_referencing_checks table has 13 rows against ~3,000 active/past tenants. It is not a complete record of all referencing conducted. Most pre-RAIA (Real estate Artificial Intelligence Agent) referencing was done on RentProfile or Homeppl and the results were never imported. When populating tbl_persons_career and tbl_persons_identity, do not use tbl_referencing_checks as the source — go back to the original Homeppl/RentProfile exports for the full dataset.

P-08
tbl_persons_channels Has 109k Rows — Email/Phone Dedup Required

The tbl_persons_channels table has 109,000 rows for a person base of 60,636 — roughly 1.8 channels per person. When migrating contact data from tbl_persons into the channels table (or cross-referencing during nationality backfill), be aware that persons may have multiple email addresses and phone numbers. The email_primary on tbl_persons may not match the most recently active channel record. Always JOIN on person_id, not on email string match.


Vibe Check — Schema Change Checklist

Run before and after each migration step. All greens required before applying to production.

Pre-Migration Gates

  • ✓ ref_countries table exists and is seeded with ISO-3166-1 alpha-2 codes
  • ✓ SELECT COUNT(*) FROM tbl_persons WHERE date_of_birth IS NOT NULL = 0 (or backfill written)
  • ✓ SELECT DISTINCT nationality FROM tbl_persons reviewed — all variants mapped to ISO codes
  • ✓ UNIQUE(person_id, qualification_type) constraint added to tbl_persons_qualifications
  • ✓ SELECT DISTINCT employment_status FROM tbl_persons reviewed — all values in ref_employment_status
  • ✓ Full database backup taken and confirmed restorable
  • ✓ Application code updated to read DOB from tbl_persons_identity only
  • ⚠ Run on dev branch first — confirm all API responses return expected shapes
  • ✗ Do NOT apply Step 2c (drop nationality) if unmatched_count > 0

Post-Migration Verification

  • ✓ tbl_persons no longer has date_of_birth column (\d tbl_persons)
  • ✓ tbl_persons no longer has nationality VARCHAR column
  • ✓ tbl_persons no longer has qualification_01/02/03 columns
  • ✓ Row count in tbl_persons_qualifications = pre-migration non-null qual count
  • ✓ nationality_code FK constraint verified: SELECT * FROM information_schema.referential_constraints WHERE constraint_name LIKE '%nationality%'
  • ✓ Spot-check 5 existing tenants — identity rows exist in tbl_persons_identity
  • ✓ RAIA (Real estate Artificial Intelligence Agent) portal CRM filters still work: employment_status filter, nationality filter
  • ✓ No application errors in Supabase logs following migration
  • ⚠ Update TypeScript types: supabase gen types typescript
  • ⚠ Update any Supabase RLS policies that referenced old columns

🚀

This architecture is GDPR-clean, normalization-correct, and operationally sound. Three changes fix the immediate violations without a full rewrite: drop DOB from the base table, replace free-text nationality with an FK, and migrate qualification flat columns to the child table. The SJT Stage 4 gate ensures that 51k leads never accumulate PII they shouldn't hold. Employment history is preserved in tbl_persons_career for referencing audit trails. The satellite table architecture scales to any future PII requirements without touching the 60k-row base table.

Related pages: § 3.5a GDPR PII Access Architecture · § 3.5b PII Data Lifecycle · RAIA (Real estate Artificial Intelligence Agent) Documentation Index

Author: RAIA (Real estate Artificial Intelligence Agent) OS — EstateAigents.com · Version: 1.0 · Last updated: June 2026

Repository Code

The live codebase implementation for this textbook logic sits within the following repository folder: