feat(supabase): animals and relations M3 with RPCs, history and caps

Species rows (8 + other), animals with the D6b birth model, relations with
composite workspace keys, current/ended/voided states and a partial unique
index; definer RPCs for animals and relations (one lock order, shared write
budget, caps), invoker reads (search_animals, list_client_animals,
client_archive_preview) and search_clients with current_animal_count.
pgTAP 014 (254), parity test, sandbox suite, types from the isolated stack.
This commit is contained in:
bchanot committed 2026-10-26 00:52:22 +01:00
1 parent 2dc04bcfba
commit b54c8e5bd8
8 files changed
+3354 -11

No files matched your search

+111 -1
View File
@@ -1,16 +1,20 @@
/**
* D-R7 parity: the constants of src/field-limits.ts behave like the SQL CHECK
* constraints of public.clients, proven by inserting values at and past each
* constraints of public.clients, public.animals and
* public.animal_client_relations, proven by inserting values at and past each
* bound into the migrated PGlite schema (contract §12.2). The form may refuse
* more than SQL (never less): a value the TypeScript rule accepts must be
* accepted by SQL, and the listed samples must agree both ways.
*/
import type { PGlite } from '@electric-sql/pglite'
import {
ANIMAL_FIELD_LIMITS,
BIRTH_YEAR_MIN,
CLIENT_FIELD_LIMITS,
COUNTRY_CODE_PATTERN,
EMAIL_PATTERN,
PHONE_E164_PATTERN,
RECORD_DATE_MIN,
codePointLength,
isCleanText,
} from '../../src/field-limits'
@@ -73,6 +77,52 @@ const textFields: [Column, number][] = [
['city', CLIENT_FIELD_LIMITS.city],
]
/** One animal row in a rolled-back transaction: does the schema accept these columns? */
async function animalAccepts(
columns: Record<string, string>,
): Promise<boolean> {
const row = { name: 'Parity', species_id: 'equine', ...columns }
const names = Object.keys(row)
await db.exec('begin')
try {
await db.query(
`insert into public.animals (workspace_id, sex, create_request_id, create_request_digest, ${names.join(', ')})
values ($1, 'unknown', gen_random_uuid(), '\\x00', ${names.map((_, i) => `$${i + 2}`).join(', ')})`,
[workspaceId, ...Object.values(row)],
)
return true
} catch {
return false
} finally {
await db.exec('rollback')
}
}
/** One relation row (ended, so both dates are allowed) to a fresh animal and client. */
async function relationAccepts(
column: 'started_on' | 'ended_on',
value: string,
): Promise<boolean> {
await db.exec('begin')
try {
await db.query(
`with a as (insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
values ($1, 'Parity', 'equine', 'unknown', gen_random_uuid(), '\\x00') returning id),
c as (insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
values ($1, 'person', 'Parity', gen_random_uuid(), '\\x00') returning id)
insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, ${column},
create_request_id, create_request_digest)
select $1, a.id, c.id, 'owner', now(), $2, gen_random_uuid(), '\\x00' from a, c`,
[workspaceId, value],
)
return true
} catch {
return false
} finally {
await db.exec('rollback')
}
}
const tsEmail = (v: string) =>
isCleanText(v, CLIENT_FIELD_LIMITS.email) &&
v === v.toLowerCase() &&
@@ -167,4 +217,64 @@ describe('field limits match the SQL constraints (D-R7)', () => {
])
}
})
it.each([
['name', ANIMAL_FIELD_LIMITS.name],
['breed', ANIMAL_FIELD_LIMITS.breed],
] as const)(
'animals.%s: the text rule and its bound %i agree',
async (column, max) => {
for (const value of textSamples(max)) {
expect([
column,
JSON.stringify(value).slice(0, 24),
await animalAccepts({ [column]: value }),
]).toEqual([
column,
JSON.stringify(value).slice(0, 24),
isCleanText(value, max),
])
}
},
)
it('animals.species_detail: the text rule and its bound agree (with other)', async () => {
for (const value of textSamples(ANIMAL_FIELD_LIMITS.speciesDetail)) {
expect([
JSON.stringify(value).slice(0, 24),
await animalAccepts({ species_id: 'other', species_detail: value }),
]).toEqual([
JSON.stringify(value).slice(0, 24),
isCleanText(value, ANIMAL_FIELD_LIMITS.speciesDetail),
])
}
})
it('birth year: the floor agrees', async () => {
for (const year of [BIRTH_YEAR_MIN - 1, BIRTH_YEAR_MIN, 2015]) {
expect([year, await animalAccepts({ birth_year: String(year) })]).toEqual(
[year, year >= BIRTH_YEAR_MIN],
)
}
})
it('record dates: the floor agrees on birth and relation dates', async () => {
const before = '1899-12-31'
for (const value of [before, RECORD_DATE_MIN, '2015-04-12']) {
const expected = value >= RECORD_DATE_MIN
const year = value.slice(0, 4)
expect([
value,
await animalAccepts({ birth_year: year, birth_date: value }),
]).toEqual([value, expected])
expect([value, await relationAccepts('started_on', value)]).toEqual([
value,
expected,
])
expect([value, await relationAccepts('ended_on', value)]).toEqual([
value,
expected,
])
}
})
})
@@ -20,6 +20,41 @@ type ColumnMap = {
}
const expectedColumns = {
animal_client_relations: [
'animal_id',
'client_id',
'create_request_digest',
'create_request_id',
'created_at',
'ended_at',
'ended_on',
'id',
'relation_role',
'revision',
'started_on',
'updated_at',
'voided_at',
'workspace_id',
],
animals: [
'archived_at',
'birth_date',
'birth_year',
'breed',
'create_request_digest',
'create_request_id',
'created_at',
'id',
'name',
'name_key',
'revision',
'search_key',
'sex',
'species_detail',
'species_id',
'updated_at',
'workspace_id',
],
anatomical_sheet_assets: [
'byte_size',
'content_type',
@@ -158,9 +193,40 @@ const expectedFunctionArgs = {
claim_avatar_jobs: ['max_jobs'],
claim_purges: ['max_items'],
claim_quarantine_leftovers: ['max_items', 'older_than_seconds'],
client_archive_preview: ['client_id'],
complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'],
confirm_asset_upload: ['asset_id'],
confirm_sheet_asset_upload: ['asset_id'],
create_anatomical_sheet: [
'description',
'document',
'name',
'official',
'slug',
'species_id',
'visibility',
],
create_animal: [
'birth_date',
'birth_year',
'breed',
'client_id',
'create_request_id',
'name',
'relation_role',
'sex',
'species_detail',
'species_id',
'started_on',
'workspace_id',
],
create_animal_client_relation: [
'animal_id',
'client_id',
'create_request_id',
'relation_role',
'started_on',
],
create_client: [
'address_line1',
'address_line2',
@@ -174,23 +240,16 @@ const expectedFunctionArgs = {
'postal_code',
'workspace_id',
],
create_anatomical_sheet: [
'description',
'document',
'name',
'official',
'slug',
'species_id',
'visibility',
],
create_sheet_draft: ['change_note', 'from_version_id', 'sheet_id'],
delete_anatomical_sheet: ['sheet_id'],
delete_sheet_asset: ['asset_id'],
delete_sheet_version: ['version_id'],
deprecate_sheet_version: ['reason', 'version_id'],
end_animal_client_relation: ['ended_on', 'expected_revision', 'relation_id'],
expire_pending_uploads: ['max_age_seconds'],
fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'],
grant_platform_role: ['role', 'target_user_id'],
list_client_animals: ['after_id', 'after_sort', 'client_id', 'page_size'],
mark_quarantine_purged: ['asset_id'],
publish_sheet_version: ['version_id'],
register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'],
@@ -198,6 +257,15 @@ const expectedFunctionArgs = {
remove_avatar: [],
restore_anatomical_sheet: ['sheet_id'],
revoke_platform_role: ['reason', 'role', 'target_user_id'],
search_animals: [
'after_id',
'after_name_key',
'archived',
'page_size',
'query',
'species_filter',
'workspace_id',
],
search_clients: [
'after_id',
'after_name_key',
@@ -206,8 +274,26 @@ const expectedFunctionArgs = {
'query',
'workspace_id',
],
set_animal_archived: ['animal_id', 'archived'],
set_client_archived: ['archived', 'client_id'],
set_sheet_visibility: ['sheet_id', 'visibility'],
update_animal: [
'animal_id',
'birth_date',
'birth_year',
'breed',
'expected_revision',
'name',
'sex',
'species_detail',
'species_id',
],
update_animal_client_relation: [
'ended_on',
'expected_revision',
'relation_id',
'started_on',
],
update_client: [
'address_line1',
'address_line2',
@@ -221,6 +307,7 @@ const expectedFunctionArgs = {
'phone',
'postal_code',
],
void_animal_client_relation: ['expected_revision', 'relation_id'],
} as const satisfies FunctionArgs
// A function without arguments is generated as `Record<PropertyKey, never>`