diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 42db1288..0a063c59 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -239,6 +239,149 @@ export type Database = { }, ] } + animal_client_relations: { + Row: { + animal_id: string + client_id: string + create_request_digest: string + create_request_id: string + created_at: string + ended_at: string | null + ended_on: string | null + id: string + relation_role: Database['public']['Enums']['animal_relation_role'] + revision: number + started_on: string | null + updated_at: string + voided_at: string | null + workspace_id: string + } + ComputedFields: never + Insert: { + animal_id: string + client_id: string + create_request_digest: string + create_request_id: string + created_at?: string + ended_at?: string | null + ended_on?: string | null + id?: string + relation_role: Database['public']['Enums']['animal_relation_role'] + revision?: number + started_on?: string | null + updated_at?: string + voided_at?: string | null + workspace_id: string + } + Update: { + animal_id?: string + client_id?: string + create_request_digest?: string + create_request_id?: string + created_at?: string + ended_at?: string | null + ended_on?: string | null + id?: string + relation_role?: Database['public']['Enums']['animal_relation_role'] + revision?: number + started_on?: string | null + updated_at?: string + voided_at?: string | null + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'animal_client_relations_animal_fk' + columns: ['workspace_id', 'animal_id'] + isOneToOne: false + referencedRelation: 'animals' + referencedColumns: ['workspace_id', 'id'] + }, + { + foreignKeyName: 'animal_client_relations_client_fk' + columns: ['workspace_id', 'client_id'] + isOneToOne: false + referencedRelation: 'clients' + referencedColumns: ['workspace_id', 'id'] + }, + ] + } + animals: { + Row: { + archived_at: string | null + birth_date: string | null + birth_year: number | null + breed: string | null + create_request_digest: string + create_request_id: string + created_at: string + id: string + name: string + name_key: string | null + revision: number + search_key: string | null + sex: Database['public']['Enums']['animal_sex'] + species_detail: string | null + species_id: string + updated_at: string + workspace_id: string + } + ComputedFields: never + Insert: { + archived_at?: string | null + birth_date?: string | null + birth_year?: number | null + breed?: string | null + create_request_digest: string + create_request_id: string + created_at?: string + id?: string + name: string + name_key?: never + revision?: number + search_key?: never + sex: Database['public']['Enums']['animal_sex'] + species_detail?: string | null + species_id: string + updated_at?: string + workspace_id: string + } + Update: { + archived_at?: string | null + birth_date?: string | null + birth_year?: number | null + breed?: string | null + create_request_digest?: string + create_request_id?: string + created_at?: string + id?: string + name?: string + name_key?: never + revision?: number + search_key?: never + sex?: Database['public']['Enums']['animal_sex'] + species_detail?: string | null + species_id?: string + updated_at?: string + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'animals_species_id_fkey' + columns: ['species_id'] + isOneToOne: false + referencedRelation: 'species' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'animals_workspace_id_fkey' + columns: ['workspace_id'] + isOneToOne: false + referencedRelation: 'workspaces' + referencedColumns: ['id'] + }, + ] + } assets: { Row: { attempts: number @@ -628,6 +771,7 @@ export type Database = { object_name: string }[] } + client_archive_preview: { Args: { client_id: string }; Returns: Json } complete_avatar_job: { Args: { asset_id: string @@ -654,6 +798,33 @@ export type Database = { } Returns: string } + create_animal: { + Args: { + birth_date?: string + birth_year?: string + breed?: string + client_id?: string + create_request_id: string + name: string + relation_role?: string + sex: string + species_detail?: string + species_id: string + started_on?: string + workspace_id: string + } + Returns: Json + } + create_animal_client_relation: { + Args: { + animal_id: string + client_id: string + create_request_id: string + relation_role: string + started_on?: string + } + Returns: Json + } create_client: { Args: { address_line1?: string @@ -685,6 +856,14 @@ export type Database = { Args: { reason?: string; version_id: string } Returns: string } + end_animal_client_relation: { + Args: { + ended_on?: string + expected_revision: number + relation_id: string + } + Returns: Json + } expire_pending_uploads: { Args: { max_age_seconds: number } Returns: number @@ -705,6 +884,31 @@ export type Database = { } Returns: string } + list_client_animals: { + Args: { + after_id?: string + after_sort?: string + client_id: string + page_size?: number + } + Returns: { + animal_archived_at: string + animal_id: string + animal_name: string + birth_year: number + breed: string + ended_on: string + is_current: boolean + relation_id: string + relation_revision: number + relation_role: Database['public']['Enums']['animal_relation_role'] + sex: Database['public']['Enums']['animal_sex'] + sort_key: string + species_detail: string + species_id: string + started_on: string + }[] + } mark_quarantine_purged: { Args: { asset_id: string }; Returns: undefined } publish_sheet_version: { Args: { version_id: string }; Returns: string } register_sheet_asset: { @@ -730,6 +934,30 @@ export type Database = { } Returns: string } + search_animals: { + Args: { + after_id?: string + after_name_key?: string + archived?: boolean + page_size?: number + query?: string + species_filter?: string + workspace_id: string + } + Returns: { + archived_at: string + birth_year: number + breed: string + current_owner_count: number + current_owners: Json + id: string + name: string + name_key: string + sex: Database['public']['Enums']['animal_sex'] + species_detail: string + species_id: string + }[] + } search_clients: { Args: { after_id?: string @@ -742,6 +970,7 @@ export type Database = { Returns: { archived_at: string city: string + current_animal_count: number display_name: string email: string id: string @@ -750,6 +979,10 @@ export type Database = { phone: string }[] } + set_animal_archived: { + Args: { animal_id: string; archived: boolean } + Returns: Json + } set_client_archived: { Args: { archived: boolean; client_id: string } Returns: Json @@ -761,6 +994,29 @@ export type Database = { } Returns: string } + update_animal: { + Args: { + animal_id: string + birth_date: string + birth_year: string + breed: string + expected_revision: number + name: string + sex: string + species_detail: string + species_id: string + } + Returns: Json + } + update_animal_client_relation: { + Args: { + ended_on: string + expected_revision: number + relation_id: string + started_on: string + } + Returns: Json + } update_client: { Args: { address_line1: string @@ -777,8 +1033,14 @@ export type Database = { } Returns: Json } + void_animal_client_relation: { + Args: { expected_revision: number; relation_id: string } + Returns: Json + } } Enums: { + animal_relation_role: 'owner' | 'keeper' | 'contact' + animal_sex: 'male' | 'female' | 'unknown' asset_status: | 'pending_upload' | 'uploaded' @@ -919,6 +1181,8 @@ export type CompositeTypes< export const Constants = { public: { Enums: { + animal_relation_role: ['owner', 'keeper', 'contact'], + animal_sex: ['male', 'female', 'unknown'], asset_status: [ 'pending_upload', 'uploaded', diff --git a/packages/supabase/src/field-limits.ts b/packages/supabase/src/field-limits.ts index 1ce77e1d..24133e90 100644 --- a/packages/supabase/src/field-limits.ts +++ b/packages/supabase/src/field-limits.ts @@ -16,6 +16,20 @@ export const CLIENT_FIELD_LIMITS = { city: 80, } as const +export const ANIMAL_FIELD_LIMITS = { + name: 80, + breed: 80, + speciesDetail: 80, +} as const + +/** + * Lower bounds of the SQL CHECKs on birth years and on every record date + * (birth, relation start and end). The upper bound is "not in the future": + * the form checks the device's local date, the RPCs tomorrow's UTC date. + */ +export const BIRTH_YEAR_MIN = 1900 +export const RECORD_DATE_MIN = '1900-01-01' + /** U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029 (the SQL literal starts at U+0001: text cannot hold U+0000). */ export const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u diff --git a/packages/supabase/tests/db/field-limits.test.ts b/packages/supabase/tests/db/field-limits.test.ts index b0fb0db6..badebf09 100644 --- a/packages/supabase/tests/db/field-limits.test.ts +++ b/packages/supabase/tests/db/field-limits.test.ts @@ -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, +): Promise { + 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 { + 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, + ]) + } + }) }) diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 287a82af..c003c198 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -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` diff --git a/packages/supabase/tests/sandbox/animals.sandbox.ts b/packages/supabase/tests/sandbox/animals.sandbox.ts new file mode 100644 index 00000000..8431695f --- /dev/null +++ b/packages/supabase/tests/sandbox/animals.sandbox.ts @@ -0,0 +1,832 @@ +/** + * V1-1.4 animals and relations (M3) on the real stack of `pnpm db:sandbox`: + * RPCs through PostgREST with real sessions per role, identical refusals, no + * lock taken outside the caller's workspace, then concurrent writes (replays, + * identical relations, end and void races, caps, the budget shared with the + * clients, relation creates against archives, a mixed burst across M2 and + * M3 without deadlock), the D9a guard through GoTrue admin, and timings. + * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.3, §7.1, §9, §10, §12. + */ +import { randomUUID } from 'node:crypto' +import { + adminDeleteUser, + confirmedAccount, + errorCode, + rest, + rpc, + sql, + stack, + type Account, + type RestResult, +} from './stack' + +const workspaceOf = (userId: string) => + sql(`select id from public.workspaces where personal_user_id = '${userId}'`) +const budgetOf = (ws: string) => + sql( + `select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`, + ) +const idOf = (result: RestResult) => (result.body as { id: string }).id +const messageOf = (result: RestResult) => + result.status === 200 ? 'ok' : (result.body as { message: string }).message +/** The error as the client sees it: status, code, message, details, hint. */ +const shape = (result: RestResult) => { + const body = result.body as Record + return [ + result.status, + body.code, + body.message, + body.details ?? null, + body.hint ?? null, + ] +} +const NOT_FOUND = [403, '42501', 'not_found', null, null] + +function createClient(account: Account, ws: string, displayName: string) { + return rpc( + 'create_client', + { + workspace_id: ws, + create_request_id: randomUUID(), + kind: 'person', + display_name: displayName, + }, + account.token, + ) +} +function createAnimal( + account: Account, + ws: string, + fields: Record, + requestId = randomUUID(), +) { + return rpc( + 'create_animal', + { + workspace_id: ws, + create_request_id: requestId, + species_id: 'equine', + sex: 'unknown', + ...fields, + }, + account.token, + ) +} +function link( + account: Account, + animalId: string, + clientId: string, + relationRole = 'owner', + requestId = randomUUID(), +) { + return rpc( + 'create_animal_client_relation', + { + animal_id: animalId, + client_id: clientId, + create_request_id: requestId, + relation_role: relationRole, + }, + account.token, + ) +} +const animalUpdate = (animalId: string, revision: number, name: string) => ({ + animal_id: animalId, + expected_revision: revision, + name, + species_id: 'equine', + sex: 'unknown', + species_detail: null, + breed: null, + birth_year: null, + birth_date: null, +}) + +describe('animals and relations through PostgREST, per role', () => { + let a: Account + let b: Account + let wA: string + let marie: string + let eclair: string + let relation: string + + beforeAll(async () => { + a = await confirmedAccount('an-a') + b = await confirmedAccount('an-b') + wA = await workspaceOf(a.id) + marie = idOf(await createClient(a, wA, 'Marie Dupont')) + const created = await createAnimal(a, wA, { + name: 'Éclair', + sex: 'male', + breed: 'Selle Français', + birth_year: '2015', + birth_date: '2015-04-12', + client_id: marie, + relation_role: 'owner', + started_on: '2020-01-01', + }) + expect(created.status).toBe(200) + eclair = idOf(created) + relation = (created.body as { relation_id: string }).relation_id + }) + + it('A creates, reads by id, searches, lists and changes a relation', async () => { + expect( + ( + await rest( + `/animals?select=id,name,species_id,sex,birth_year,birth_date,revision&id=eq.${eclair}`, + a.token, + ) + ).body, + ).toEqual([ + { + id: eclair, + name: 'Éclair', + species_id: 'equine', + sex: 'male', + birth_year: 2015, + birth_date: '2015-04-12', + revision: 1, + }, + ]) + expect( + ( + await rest( + `/animal_client_relations?select=client_id,relation_role,started_on,ended_at,voided_at&animal_id=eq.${eclair}`, + a.token, + ) + ).body, + ).toEqual([ + { + client_id: marie, + relation_role: 'owner', + started_on: '2020-01-01', + ended_at: null, + voided_at: null, + }, + ]) + const found = await rpc( + 'search_animals', + { workspace_id: wA, query: 'francais' }, + a.token, + ) + expect(found.body).toMatchObject([ + { + id: eclair, + current_owner_count: 1, + current_owners: [ + { client_id: marie, display_name: 'Marie Dupont', archived: false }, + ], + }, + ]) + expect( + ( + await rpc( + 'search_clients', + { workspace_id: wA, query: 'marie' }, + a.token, + ) + ).body, + ).toMatchObject([{ id: marie, current_animal_count: 1 }]) + expect( + (await rpc('list_client_animals', { client_id: marie }, a.token)).body, + ).toMatchObject([ + { relation_id: relation, animal_id: eclair, is_current: true }, + ]) + expect( + (await rpc('client_archive_preview', { client_id: marie }, a.token)).body, + ).toEqual({ count: 1, animals: [{ id: eclair, name: 'Éclair' }] }) + expect( + ( + await rpc( + 'end_animal_client_relation', + { relation_id: relation, expected_revision: 1, ended_on: null }, + a.token, + ) + ).body, + ).toEqual({ revision: 2 }) + expect( + ( + await rpc( + 'update_animal_client_relation', + { + relation_id: relation, + expected_revision: 2, + started_on: '2020-01-01', + ended_on: '2024-06-30', + }, + a.token, + ) + ).body, + ).toEqual({ revision: 3 }) + expect( + (await rpc('list_client_animals', { client_id: marie }, a.token)).body, + ).toMatchObject([{ relation_id: relation, is_current: false }]) + }) + + it('B gets nothing of A, and the same refusal as for an unknown id on every write', async () => { + expect( + (await rest(`/animals?select=id&id=eq.${eclair}`, b.token)).body, + ).toEqual([]) + const head = await rest( + `/animal_client_relations?select=id&workspace_id=eq.${wA}`, + b.token, + { method: 'HEAD', headers: { Prefer: 'count=exact' } }, + ) + expect(head.headers.get('content-range')).toBe('*/0') + for (const [fn, args] of [ + ['search_animals', { workspace_id: wA }], + ['list_client_animals', { client_id: marie }], + ] as const) { + expect((await rpc(fn, args, b.token)).body).toEqual([]) + } + expect( + (await rpc('client_archive_preview', { client_id: marie }, b.token)).body, + ).toEqual({ count: 0, animals: [] }) + const pairs: [string, Record, Record][] = + [ + [ + 'update_animal', + animalUpdate(eclair, 1, 'X'), + animalUpdate(randomUUID(), 1, 'X'), + ], + [ + 'set_animal_archived', + { animal_id: eclair, archived: true }, + { animal_id: randomUUID(), archived: true }, + ], + [ + 'end_animal_client_relation', + { relation_id: relation, expected_revision: 3, ended_on: null }, + { relation_id: randomUUID(), expected_revision: 3, ended_on: null }, + ], + [ + 'update_animal_client_relation', + { + relation_id: relation, + expected_revision: 3, + started_on: null, + ended_on: null, + }, + { + relation_id: randomUUID(), + expected_revision: 3, + started_on: null, + ended_on: null, + }, + ], + [ + 'void_animal_client_relation', + { relation_id: relation, expected_revision: 3 }, + { relation_id: randomUUID(), expected_revision: 3 }, + ], + [ + 'create_animal_client_relation', + { + animal_id: eclair, + client_id: marie, + create_request_id: randomUUID(), + relation_role: 'keeper', + }, + { + animal_id: randomUUID(), + client_id: marie, + create_request_id: randomUUID(), + relation_role: 'keeper', + }, + ], + ] + for (const [fn, foreign, unknown] of pairs) { + const x = await rpc(fn, foreign, b.token) + const y = await rpc(fn, unknown, b.token) + expect([fn, ...shape(x)]).toEqual([fn, ...shape(y)]) + expect([fn, ...shape(x)]).toEqual([fn, ...NOT_FOUND]) + } + const wB = await workspaceOf(b.id) + const bAnimal = idOf(await createAnimal(b, wB, { name: 'Animal B' })) + expect(shape(await link(b, bAnimal, marie))).toEqual(NOT_FOUND) + expect( + shape( + await createAnimal(b, wB, { + name: 'X', + client_id: marie, + relation_role: 'owner', + }), + ), + ).toEqual(NOT_FOUND) + expect(shape(await createAnimal(b, wA, { name: 'X' }))).toEqual(NOT_FOUND) + }) + + it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => { + const attempts: [string, string, RequestInit, number][] = [ + [ + '/animals', + a.token, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wA, + name: 'Direct', + species_id: 'equine', + sex: 'male', + }), + }, + 403, + ], + [ + `/animals?id=eq.${eclair}`, + a.token, + { method: 'PATCH', body: JSON.stringify({ workspace_id: wA }) }, + 403, + ], + [`/animals?id=eq.${eclair}`, a.token, { method: 'DELETE' }, 403], + [ + `/animal_client_relations?id=eq.${relation}`, + a.token, + { method: 'PATCH', body: JSON.stringify({ voided_at: null }) }, + 403, + ], + [ + `/animal_client_relations?id=eq.${relation}`, + a.token, + { method: 'DELETE' }, + 403, + ], + ['/animals?select=id', stack.anonKey, {}, 401], + [ + '/rpc/search_animals', + stack.anonKey, + { method: 'POST', body: JSON.stringify({ workspace_id: wA }) }, + 401, + ], + ['/animal_client_relations?select=id', stack.serviceKey, {}, 403], + [ + '/rpc/void_animal_client_relation', + stack.serviceKey, + { + method: 'POST', + body: JSON.stringify({ relation_id: relation, expected_revision: 3 }), + }, + 403, + ], + [ + '/rpc/lock_relation_for_write', + a.token, + { + method: 'POST', + body: JSON.stringify({ + p_relation_id: relation, + p_expected_revision: 3, + }), + }, + 404, + ], + ] + for (const [path, token, init, status] of attempts) { + const result = await rest(path, token, init) + expect([path, result.status]).toEqual([path, status]) + if (status !== 404) expect(errorCode(result)).toBe('42501') + expect(result.text).not.toContain('Éclair') + } + const invalid = await createAnimal(a, wA, { + name: 'Secret-Name-Value', + birth_year: '2015', + birth_date: '2015-02-30', + }) + expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null]) + expect(invalid.text).not.toMatch(/Secret-Name|2015-02-30/) + }) + + it('cuts a deactivated or unconfirmed account', async () => { + await sql(`update public.profiles set active = false where id = '${a.id}'`) + expect((await rest('/animals?select=id', a.token)).body).toEqual([]) + expect( + shape( + await rpc( + 'set_animal_archived', + { animal_id: eclair, archived: true }, + a.token, + ), + ), + ).toEqual(NOT_FOUND) + await sql(`update public.profiles set active = true where id = '${a.id}'`) + await sql( + `update auth.users set email_confirmed_at = null where id = '${a.id}'`, + ) + expect( + (await rest('/animal_client_relations?select=id', a.token)).body, + ).toEqual([]) + await sql( + `update auth.users set email_confirmed_at = now() where id = '${a.id}'`, + ) + expect((await rest('/animals?select=id', a.token)).body).toEqual([ + { id: eclair }, + ]) + }) + + it('a caller outside the workspace never waits on its locks', async () => { + const holder = sql(`begin; + select 1 from public.animals where id = '${eclair}' for update; + select 1 from public.animal_client_relations where id = '${relation}' for update; + select pg_sleep(2); commit;`) + await new Promise((resolve) => setTimeout(resolve, 300)) + const started = Date.now() + const results = await Promise.all([ + rpc('update_animal', animalUpdate(eclair, 1, 'X'), b.token), + rpc( + 'void_animal_client_relation', + { relation_id: relation, expected_revision: 3 }, + b.token, + ), + link(b, eclair, marie, 'contact'), + ]) + const elapsed = Date.now() - started + await holder + expect(results.map(shape)).toEqual([NOT_FOUND, NOT_FOUND, NOT_FOUND]) + expect(elapsed).toBeLessThan(1000) + console.log( + `[measure] A's animal and relation locked 2 s: B's three refusals answered in ${elapsed} ms`, + ) + }) + + it('hides animal and relation audit rows from the platform owner (N9)', async () => { + expect( + Number( + await sql( + `select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}')`, + ), + ), + ).toBe(4) + const ownerId = await sql( + `select id from auth.users where email = 'owner@faunosteo.local'`, + ) + const asOwner = await sql(`begin; set local role authenticated; + select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true); + select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}'); commit;`) + expect(asOwner.split('\n').pop()).toBe('0') + }) + + it('D9a: GoTrue admin cannot delete an account whose workspace holds an animal', async () => { + const g = await confirmedAccount('an-d9a') + const wG = await workspaceOf(g.id) + expect((await createAnimal(g, wG, { name: 'Seul' })).status).toBe(200) + expect(await adminDeleteUser(g.id)).not.toBe(200) + expect( + await sql( + `select (select count(*) from auth.users where id = '${g.id}') || '/' || + (select count(*) from public.profiles where id = '${g.id}') || '/' || + (select count(*) from public.animals where workspace_id = '${wG}')`, + ), + ).toBe('1/1/1') + }) +}) + +describe('concurrent writes', () => { + let a: Account + let wA: string + let clients: string[] + + beforeAll(async () => { + a = await confirmedAccount('an-race') + wA = await workspaceOf(a.id) + clients = [] + for (let i = 0; i < 24; i++) + clients.push(idOf(await createClient(a, wA, `Race client ${i}`))) + }) + + it('one create_animal request sent 8 times at once: one animal, one relation, two writes counted', async () => { + const before = Number((await budgetOf(wA)).split('/')[0]) + const requestId = randomUUID() + const results = await Promise.all( + Array.from({ length: 8 }, () => + createAnimal( + a, + wA, + { name: 'Replayed', client_id: clients[0], relation_role: 'owner' }, + requestId, + ), + ), + ) + expect(results.map((r) => r.status)).toEqual(Array(8).fill(200)) + expect(new Set(results.map((r) => JSON.stringify(r.body))).size).toBe(1) + expect( + await sql( + `select (select count(*) from public.animals where create_request_id = '${requestId}') || '/' || + (select count(*) from public.animal_client_relations where create_request_id = '${requestId}')`, + ), + ).toBe('1/1') + expect(Number((await budgetOf(wA)).split('/')[0])).toBe(before + 2) + }) + + it('two contents racing on one request id: one created, the other refused', async () => { + const requestId = randomUUID() + const results = await Promise.all([ + createAnimal(a, wA, { name: 'Racer X' }, requestId), + createAnimal(a, wA, { name: 'Racer Y' }, requestId), + ]) + expect(results.map(messageOf).sort()).toEqual(['ok', 'request_conflict']) + }) + + it('10 identical relations at once (distinct request ids): one row, nine duplicate_relation', async () => { + const animal = idOf(await createAnimal(a, wA, { name: 'Dup target' })) + const results = await Promise.all( + Array.from({ length: 10 }, () => link(a, animal, clients[1], 'keeper')), + ) + const messages = results.map(messageOf) + expect(messages.filter((m) => m === 'ok')).toHaveLength(1) + expect(messages.filter((m) => m === 'duplicate_relation')).toHaveLength(9) + expect( + await sql( + `select count(*) from public.animal_client_relations where animal_id = '${animal}'`, + ), + ).toBe('1') + }) + + it('end and void racing on one revision: exactly one applies, the relation is ended or voided, never both', async () => { + for (let round = 0; round < 6; round++) { + const animal = idOf( + await createAnimal(a, wA, { name: `End-void ${round}` }), + ) + const relation = idOf(await link(a, animal, clients[2])) + const results = await Promise.all([ + rpc( + 'end_animal_client_relation', + { relation_id: relation, expected_revision: 1, ended_on: null }, + a.token, + ), + rpc( + 'void_animal_client_relation', + { relation_id: relation, expected_revision: 1 }, + a.token, + ), + rpc( + 'end_animal_client_relation', + { relation_id: relation, expected_revision: 1, ended_on: null }, + a.token, + ), + ]) + const messages = results.map(messageOf) + expect(messages.filter((m) => m === 'ok')).toHaveLength(1) + expect(messages.filter((m) => m === 'conflict')).toHaveLength(2) + const state = await sql( + `select (ended_at is not null) || '/' || (voided_at is not null) || '/' || revision + from public.animal_client_relations where id = '${relation}'`, + ) + expect(['true/false/2', 'false/true/2']).toContain(state) + } + }) + + it('at 18 current relations, 6 concurrent links: exactly 2 pass', async () => { + const animal = idOf(await createAnimal(a, wA, { name: 'Crowded' })) + for (let i = 0; i < 18; i++) + expect((await link(a, animal, clients[i], 'contact')).status).toBe(200) + const results = await Promise.all( + clients.slice(18, 24).map((c) => link(a, animal, c, 'contact')), + ) + const messages = results.map(messageOf) + expect(messages.filter((m) => m === 'ok')).toHaveLength(2) + expect(messages.filter((m) => m === 'limit_reached')).toHaveLength(4) + expect( + await sql( + `select count(*) from public.animal_client_relations where animal_id = '${animal}' and ended_at is null and voided_at is null`, + ), + ).toBe('20') + }) + + it('a relation create racing the archive of its client: created before, or refused archived after', async () => { + const outcomes = new Set() + for (let round = 0; round < 10; round++) { + const client = idOf(await createClient(a, wA, `Archive race ${round}`)) + const animal = idOf( + await createAnimal(a, wA, { name: `Archive race ${round}` }), + ) + const [linked, archived] = await Promise.all([ + link(a, animal, client), + rpc( + 'set_client_archived', + { client_id: client, archived: true }, + a.token, + ), + ]) + expect(messageOf(archived)).toBe('ok') + expect(['ok', 'archived']).toContain(messageOf(linked)) + outcomes.add(messageOf(linked)) + const rows = await sql( + `select count(*) from public.animal_client_relations where animal_id = '${animal}'`, + ) + expect(rows).toBe(messageOf(linked) === 'ok' ? '1' : '0') + } + console.log( + `[measure] relation create vs client archive, 10 rounds: outcomes ${[...outcomes].join(', ')}`, + ) + }) + + it('the budget is one counter for clients, animals and relations: at 990, 30 mixed writes, exactly 10 pass', async () => { + const animals: string[] = [] + for (let i = 0; i < 10; i++) + animals.push(idOf(await createAnimal(a, wA, { name: `Budget ${i}` }))) + await sql( + `update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`, + ) + const results = await Promise.all( + Array.from({ length: 30 }, (_, i) => + i % 3 === 0 + ? createClient(a, wA, `Budget client ${i}`) + : i % 3 === 1 + ? createAnimal(a, wA, { name: `Budget new ${i}` }) + : link(a, animals[i % 10], clients[i % 24], 'contact'), + ), + ) + const messages = results.map(messageOf) + expect(messages.filter((m) => m === 'ok')).toHaveLength(10) + expect(messages.filter((m) => m === 'rate_limited')).toHaveLength(20) + expect((await budgetOf(wA)).split('/')[0]).toBe('1000') + await sql( + `update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`, + ) + }) + + it('caps of the workspace under concurrency: 20 000 animals and 100 000 relations', async () => { + const e = await confirmedAccount('an-caps') + const wE = await workspaceOf(e.id) + const client = idOf(await createClient(e, wE, 'Cap client')) + await sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) + select '${wE}', 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\\x00' from generate_series(1, 19998) g; + insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest) + select '${wE}', a.id, '${client}', 'contact', now(), gen_random_uuid(), '\\x00' + from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${wE}') a + cross join generate_series(1, 10) g where a.n <= 9999 or (a.n = 10000 and g <= 8); + analyze public.animals; analyze public.animal_client_relations;`) + const animals = await Promise.all( + Array.from({ length: 5 }, () => createAnimal(e, wE, { name: 'Over' })), + ) + expect(animals.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2) + expect( + animals.map(messageOf).filter((m) => m === 'limit_reached'), + ).toHaveLength(3) + const free = ( + await sql(`select id from public.animals a where workspace_id = '${wE}' + and not exists (select 1 from public.animal_client_relations r where r.animal_id = a.id) limit 5`) + ).split('\n') + const started = Date.now() + const links = await Promise.all(free.map((id) => link(e, id, client))) + const elapsed = Date.now() - started + expect(links.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2) + expect( + links.map(messageOf).filter((m) => m === 'limit_reached'), + ).toHaveLength(3) + expect( + await sql( + `select count(*) from public.animal_client_relations where workspace_id = '${wE}'`, + ), + ).toBe('100000') + console.log( + `[measure] 5 concurrent links next to 99 998 relations: ${elapsed} ms for the five (cap counted under the workspace lock)`, + ) + }) + + it('a mixed burst across clients, animals and relations raises no deadlock', async () => { + const animals: string[] = [] + const relations: string[] = [] + for (let i = 0; i < 6; i++) { + const animal = idOf(await createAnimal(a, wA, { name: `Burst ${i}` })) + animals.push(animal) + relations.push(idOf(await link(a, animal, clients[i], 'owner'))) + } + const started = Date.now() + const results = await Promise.all( + Array.from({ length: 96 }, (_, i) => { + const animal = animals[i % 6] + const client = clients[(i * 7) % 24] + switch (i % 8) { + case 0: + return link(a, animal, client, 'keeper') + case 1: + return rpc( + 'update_animal', + animalUpdate(animal, 1, `B${i}`), + a.token, + ) + case 2: + return rpc( + 'set_animal_archived', + { animal_id: animal, archived: i % 16 === 2 }, + a.token, + ) + case 3: + return rpc( + 'update_client', + { + client_id: client, + expected_revision: 1, + kind: 'person', + display_name: `Race client edit ${i}`, + email: null, + phone: null, + address_line1: null, + address_line2: null, + postal_code: null, + city: null, + country: null, + }, + a.token, + ) + case 4: + return rpc( + 'set_client_archived', + { client_id: client, archived: i % 16 === 4 }, + a.token, + ) + case 5: + return rpc( + 'end_animal_client_relation', + { + relation_id: relations[i % 6], + expected_revision: 1, + ended_on: null, + }, + a.token, + ) + case 6: + return createAnimal(a, wA, { + name: `Burst new ${i}`, + client_id: client, + relation_role: 'contact', + }) + default: + return rpc( + 'void_animal_client_relation', + { relation_id: relations[i % 6], expected_revision: 1 }, + a.token, + ) + } + }), + ) + const codes = results.map((r) => + r.status === 200 ? 'ok' : `${errorCode(r)}:${messageOf(r)}`, + ) + expect( + codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')), + ).toEqual([]) + const allowed = [ + 'ok', + 'P0001:conflict', + 'P0001:archived', + 'P0001:duplicate_relation', + 'P0001:already_ended', + 'P0001:invalid_input', + ] + expect(codes.filter((c) => !allowed.includes(c))).toEqual([]) + console.log( + `[measure] 96 mixed writes over M2 and M3 in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`, + ) + }) +}) + +describe('search on 20 000 animals', () => { + it('records the time of search_animals with owners (measurement, not a gate)', async () => { + const v = await confirmedAccount('an-volume') + const ws = await workspaceOf(v.id) + await sql(`insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + select '${ws}', 'person', 'Owner ' || g, gen_random_uuid(), '\\x00' from generate_series(1, 1000) g; + insert into public.animals (workspace_id, name, species_id, sex, breed, create_request_id, create_request_digest) + select '${ws}', 'Animal ' || g, case when g % 3 = 0 then 'canine' else 'equine' end, 'female', + 'Race ' || (g % 40), gen_random_uuid(), '\\x00' from generate_series(1, 20000) g; + insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest) + select '${ws}', a.id, c.id, 'owner', gen_random_uuid(), '\\x00' + from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${ws}') a + join (select id, row_number() over (order by id) as n from public.clients where workspace_id = '${ws}') c + on c.n = 1 + a.n % 1000; + analyze public.animals; analyze public.animal_client_relations; analyze public.clients;`) + const owner = await sql( + `select id from public.clients where workspace_id = '${ws}' limit 1`, + ) + const calls: [string, Record][] = [ + ['search_animals', { workspace_id: ws, query: 'animal 1999' }], + ['search_animals', { workspace_id: ws, query: 'race 7' }], + [ + 'search_animals', + { workspace_id: ws, query: '', species_filter: 'canine' }, + ], + ['search_animals', { workspace_id: ws, query: 'zzz-none' }], + ['search_animals', { workspace_id: ws, query: '', page_size: 100 }], + ['search_clients', { workspace_id: ws, query: 'owner', page_size: 100 }], + ['list_client_animals', { client_id: owner }], + ['client_archive_preview', { client_id: owner }], + ] + const times: number[] = [] + for (let round = 0; round < 3; round++) { + for (const [fn, args] of calls) { + const started = performance.now() + const result = await rpc(fn, args, v.token) + times.push(performance.now() - started) + expect([fn, result.status]).toEqual([fn, 200]) + } + } + times.sort((x, y) => x - y) + const p95 = times[Math.ceil(times.length * 0.95) - 1] + console.log( + `[measure] reads over 20 000 animals, 20 000 relations, 1 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`, + ) + }) +}) diff --git a/supabase/migrations/20261026100000_animals_relations.sql b/supabase/migrations/20261026100000_animals_relations.sql new file mode 100644 index 00000000..91e4b1b6 --- /dev/null +++ b/supabase/migrations/20261026100000_animals_relations.sql @@ -0,0 +1,1166 @@ +-- V1-1.4 Animals and relations (M3): the animals of a workspace and their +-- relations with its clients (owner, keeper, contact), written only through +-- RPCs, read through RLS and POST RPCs. Contract: +-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.2 (animal), +-- §5.3 (relation), §5.4 (species), §7.1 (archive), §8 (schema), §9 (helpers, +-- RLS, RPCs, failures), §10 (limits), §13.2 (N1, N4, N5, N6, N8, N9). +-- +-- Invariants pinned by supabase/tests/014_animals_relations.sql and the +-- sandbox suite: +-- * an animal belongs to one workspace; a relation joins an animal and a +-- client of the same workspace, enforced by composite foreign keys +-- whatever role writes; +-- * a relation is current (ended_at and voided_at null), ended (ended_at +-- set, ended_on when the date is known) or voided (entered by mistake, +-- voided_at set, frozen); at most one current relation per (animal, +-- client, role), enforced by a partial unique index; +-- * only a member with a write role of an active, confirmed account writes, +-- through the RPCs below; every foreign or unknown id gets the same 42501 +-- `not_found`; creates are idempotent by (workspace, create_request_id), +-- a divergent replay is refused (`request_conflict`); +-- * caps (20 000 animals and 100 000 relations per workspace, 20 current and +-- 200 relations per animal) and the write budget shared with the clients +-- are checked under locks taken in one order: workspace, animal, relation, +-- client, budget last; +-- * audit rows carry ids only, hidden from platform staff (M2's N9 filter +-- already names the animal and relation actions). + +-- --------------------------------------------------------------------------- +-- Species (contract §5.4, N1): the nine species of the contract and « Autre ». +-- Rows, not an enum; the existing `equine` row is kept unchanged. A species +-- row does not mean an anatomical sheet exists. +-- --------------------------------------------------------------------------- +insert into public.species (id, name_fr, name_en, sort_order) values + ('asinine', 'Âne', 'Donkey', 20), + ('canine', 'Chien', 'Dog', 30), + ('feline', 'Chat', 'Cat', 40), + ('bovine', 'Bovin', 'Cattle', 50), + ('caprine', 'Chèvre', 'Goat', 60), + ('ovine', 'Mouton', 'Sheep', 70), + ('porcine', 'Porc', 'Pig', 80), + ('leporine', 'Lapin', 'Rabbit', 90), + ('other', 'Autre', 'Other', 1000) +on conflict (id) do nothing; + +comment on table public.species is + 'Species of animals and of anatomical sheets. Reference data seeded by migrations; no API write path. A species row does not mean a sheet exists.'; + +-- --------------------------------------------------------------------------- +-- Dates and years sent as text (contract §9.3): parsed in the body, so a +-- malformed value is answered invalid_input without being echoed; "not in the +-- future" allows up to tomorrow's UTC date, so today in any time zone passes. +-- --------------------------------------------------------------------------- +create or replace function private.utc_tomorrow(p_now timestamptz) +returns date +language sql +stable +parallel safe +set search_path = '' +as $$ + select (p_now at time zone 'UTC')::date + 1; +$$; + +comment on function private.utc_tomorrow(timestamptz) is + 'Latest date a record may carry when written at p_now: the UTC date of tomorrow (contract §9.3).'; + +create or replace function private.parse_record_date(p_value text) +returns date +language plpgsql +stable +set search_path = '' +as $$ +declare + v_date date; +begin + if p_value is null then + return null; + end if; + if p_value !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + begin + v_date := p_value::date; + exception when data_exception then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + if v_date > private.utc_tomorrow(now()) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + return v_date; +end; +$$; + +comment on function private.parse_record_date(text) is + 'YYYY-MM-DD to a date no later than tomorrow UTC, else invalid_input; null stays null. The 1900 floor is a CHECK.'; + +create or replace function private.parse_birth_year(p_value text) +returns smallint +language plpgsql +stable +set search_path = '' +as $$ +begin + if p_value is null then + return null; + end if; + -- Two statements: SQL does not promise to test the pattern before the cast. + if p_value !~ '^[0-9]{4}$' then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + if p_value::integer > extract(year from private.utc_tomorrow(now()))::integer then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + return p_value::smallint; +end; +$$; + +comment on function private.parse_birth_year(text) is + 'Four digits to a year no later than the year of tomorrow UTC, else invalid_input; null stays null. The 1900 floor is a CHECK.'; + +-- --------------------------------------------------------------------------- +-- animals (contract §5.2: D6, D6b, N8) +-- --------------------------------------------------------------------------- +create type public.animal_sex as enum ('male', 'female', 'unknown'); + +create table public.animals ( + id uuid primary key default gen_random_uuid(), + -- restrict: an account whose workspace holds animals cannot be deleted (D9a). + workspace_id uuid not null references public.workspaces (id) on delete restrict, + name text not null + constraint animals_name_text check (private.is_clean_text(name, 80)), + species_id text not null references public.species (id) on delete restrict, + species_detail text + constraint animals_species_detail_text check (private.is_clean_text(species_detail, 80)), + -- No default: « inconnu » is chosen explicitly (N8). + sex public.animal_sex not null, + breed text + constraint animals_breed_text check (private.is_clean_text(breed, 80)), + birth_year smallint + constraint animals_birth_year_range check (birth_year between 1900 and 2100), + birth_date date + constraint animals_birth_date_range check (birth_date >= date '1900-01-01'), + name_key text collate "C" + generated always as (private.fold_text(name)) stored, + search_key text collate "C" + generated always as ( + private.fold_text(name || ' ' || coalesce(breed, '') || ' ' || coalesce(species_detail, '')) + ) stored, + create_request_id uuid not null, + create_request_digest bytea not null, + revision integer not null default 1 + constraint animals_revision_positive check (revision >= 1), + archived_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint animals_workspace_id_unique unique (workspace_id, id), + constraint animals_create_request_unique unique (workspace_id, create_request_id), + -- « Autre » needs its detail; any other species refuses one. + constraint animals_species_detail_iff_other check ((species_id = 'other') = (species_detail is not null)), + -- D6b: a full date carries its year again; a year never becomes a date. + constraint animals_birth_date_year check ( + birth_date is null + or (birth_year is not null and birth_year = extract(year from birth_date)::integer) + ) +); + +comment on table public.animals is + 'Animals of a workspace. Writes only through create_animal, update_animal, set_animal_archived; reads through RLS and search_animals.'; +comment on column public.animals.birth_year is + 'Year of birth when known; repeated from birth_date when the full date is known (D6b).'; + +create index animals_workspace_name_idx on public.animals (workspace_id, name_key, id); + +create trigger animals_set_updated_at + before update on public.animals + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- animal_client_relations (contract §5.3: D7, D7a, N4, N5) +-- --------------------------------------------------------------------------- +create type public.animal_relation_role as enum ('owner', 'keeper', 'contact'); + +create table public.animal_client_relations ( + id uuid primary key default gen_random_uuid(), + workspace_id uuid not null, + animal_id uuid not null, + client_id uuid not null, + relation_role public.animal_relation_role not null, + -- Real dates when known, never filled by default (N5). + started_on date + constraint animal_client_relations_started_on_range check (started_on >= date '1900-01-01'), + ended_on date + constraint animal_client_relations_ended_on_range check (ended_on >= date '1900-01-01'), + -- Technical time the end was recorded: null while current, never shown as the end date. + ended_at timestamptz, + -- Set once by void_animal_client_relation for a relation entered by mistake (N4). + voided_at timestamptz, + create_request_id uuid not null, + create_request_digest bytea not null, + revision integer not null default 1 + constraint animal_client_relations_revision_positive check (revision >= 1), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + -- Animal and client of one workspace, whatever writes the row (not deferrable). + constraint animal_client_relations_animal_fk foreign key (workspace_id, animal_id) + references public.animals (workspace_id, id) on delete restrict, + constraint animal_client_relations_client_fk foreign key (workspace_id, client_id) + references public.clients (workspace_id, id) on delete restrict, + constraint animal_client_relations_ended_on_needs_end check (ended_on is null or ended_at is not null), + constraint animal_client_relations_dates_order + check (started_on is null or ended_on is null or started_on <= ended_on), + constraint animal_client_relations_create_request_unique unique (workspace_id, create_request_id) +); + +comment on table public.animal_client_relations is + 'Relations between an animal and a client of one workspace, with their history. Writes only through the relation RPCs; never deleted (a mistake is voided).'; + +-- One current relation per (animal, client, role); ended and voided rows are history. +create unique index animal_client_relations_current_unique + on public.animal_client_relations (animal_id, client_id, relation_role) + where ended_at is null and voided_at is null; +create index animal_client_relations_animal_idx on public.animal_client_relations (workspace_id, animal_id); +create index animal_client_relations_client_idx on public.animal_client_relations (workspace_id, client_id); + +create trigger animal_client_relations_set_updated_at + before update on public.animal_client_relations + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Animal write RPCs (contract §9.3): authorise and lock in one statement, then +-- archived, revision, rules; the budget last; audit rows with ids only. +-- --------------------------------------------------------------------------- +create or replace function public.create_animal( + workspace_id uuid, + create_request_id uuid, + name text, + species_id text, + sex text, + species_detail text default null, + breed text default null, + birth_year text default null, + birth_date text default null, + client_id uuid default null, + relation_role text default null, + started_on text default null +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_sex public.animal_sex; + v_role public.animal_relation_role; + v_birth_year smallint; + v_birth_date date; + v_started_on date; + v_digest bytea; + v_existing_id uuid; + v_existing_revision integer; + v_existing_digest bytea; + v_client_archived_at timestamptz; + v_id uuid; + v_relation_id uuid; +begin + -- Serialises the creates of this workspace (replay check, caps, inserts). + perform 1 from public.workspaces w + where w.id = create_animal.workspace_id + and w.id in (select private.writable_workspace_ids()) + for no key update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + + begin + v_sex := create_animal.sex::public.animal_sex; + v_role := create_animal.relation_role::public.animal_relation_role; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + -- The initial relation is all or nothing: a client and a role, or neither. + if (create_animal.client_id is null) <> (v_role is null) + or (create_animal.client_id is null and create_animal.started_on is not null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + v_birth_year := private.parse_birth_year(create_animal.birth_year); + v_birth_date := private.parse_record_date(create_animal.birth_date); + v_started_on := private.parse_record_date(create_animal.started_on); + v_digest := sha256(convert_to(jsonb_build_array( + create_animal.name, create_animal.species_id, v_sex, create_animal.species_detail, + create_animal.breed, v_birth_year, v_birth_date, create_animal.client_id, v_role, v_started_on + )::text, 'UTF8')); + + select a.id, a.revision, a.create_request_digest + into v_existing_id, v_existing_revision, v_existing_digest + from public.animals a + where a.workspace_id = create_animal.workspace_id + and a.create_request_id = create_animal.create_request_id; + if found then + if v_existing_digest <> v_digest then + raise exception 'request_conflict' using errcode = 'P0001'; + end if; + -- The initial relation shares the request id of its animal. + select r.id into v_relation_id + from public.animal_client_relations r + where r.workspace_id = create_animal.workspace_id + and r.create_request_id = create_animal.create_request_id + and r.animal_id = v_existing_id; + return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision, 'relation_id', v_relation_id); + end if; + + if not exists (select 1 from public.species s where s.id = create_animal.species_id and s.active) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + if (select count(*) from public.animals a where a.workspace_id = create_animal.workspace_id) >= 20000 then + raise exception 'limit_reached' using errcode = 'P0001'; + end if; + if create_animal.client_id is not null then + select c.archived_at into v_client_archived_at + from public.clients c + where c.id = create_animal.client_id + and c.workspace_id = create_animal.workspace_id + for share; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if v_client_archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + -- A relation created by another call with this request id would collide. + if exists (select 1 from public.animal_client_relations r + where r.workspace_id = create_animal.workspace_id + and r.create_request_id = create_animal.create_request_id) then + raise exception 'request_conflict' using errcode = 'P0001'; + end if; + if (select count(*) from public.animal_client_relations r + where r.workspace_id = create_animal.workspace_id) >= 100000 then + raise exception 'limit_reached' using errcode = 'P0001'; + end if; + end if; + + -- Two audited writes when the relation comes along. + perform private.consume_write_budget(create_animal.workspace_id); + if create_animal.client_id is not null then + perform private.consume_write_budget(create_animal.workspace_id); + end if; + + begin + insert into public.animals ( + workspace_id, name, species_id, species_detail, sex, breed, birth_year, birth_date, + create_request_id, create_request_digest + ) + values ( + create_animal.workspace_id, create_animal.name, create_animal.species_id, create_animal.species_detail, + v_sex, create_animal.breed, v_birth_year, v_birth_date, create_animal.create_request_id, v_digest + ) + returning id into v_id; + if create_animal.client_id is not null then + insert into public.animal_client_relations ( + workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest + ) + values ( + create_animal.workspace_id, v_id, create_animal.client_id, v_role, v_started_on, + create_animal.create_request_id, + sha256(convert_to(jsonb_build_array(v_id, create_animal.client_id, v_role, v_started_on)::text, 'UTF8')) + ) + returning id into v_relation_id; + end if; + exception + when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + when foreign_key_violation then + raise exception 'not_found' using errcode = '42501'; + end; + + perform private.log_event( + auth.uid(), 'animal.created', 'animal', v_id, null, null, + jsonb_build_object('workspace_id', create_animal.workspace_id) + ); + if v_relation_id is not null then + perform private.log_event( + auth.uid(), 'animal_client_relation.created', 'animal_client_relation', v_relation_id, null, null, + jsonb_build_object('workspace_id', create_animal.workspace_id) + ); + end if; + return jsonb_build_object('id', v_id, 'revision', 1, 'relation_id', v_relation_id); +end; +$$; + +create or replace function public.update_animal( + animal_id uuid, + expected_revision integer, + name text, + species_id text, + sex text, + species_detail text, + breed text, + birth_year text, + birth_date text +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.animals; + v_sex public.animal_sex; + v_birth_year smallint; + v_birth_date date; +begin + select a.* into v_row + from public.animals a + where a.id = update_animal.animal_id + and a.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if v_row.archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + if update_animal.expected_revision is distinct from v_row.revision then + raise exception 'conflict' using errcode = 'P0001'; + end if; + + begin + v_sex := update_animal.sex::public.animal_sex; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + v_birth_year := private.parse_birth_year(update_animal.birth_year); + v_birth_date := private.parse_record_date(update_animal.birth_date); + -- A species may stay as it is; a new one must be active. + if update_animal.species_id is distinct from v_row.species_id + and not exists (select 1 from public.species s where s.id = update_animal.species_id and s.active) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + + -- No change: nothing written, nothing counted. + if (update_animal.name, update_animal.species_id, v_sex, update_animal.species_detail, update_animal.breed, + v_birth_year, v_birth_date) + is not distinct from + (v_row.name, v_row.species_id, v_row.sex, v_row.species_detail, v_row.breed, + v_row.birth_year, v_row.birth_date) then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + begin + update public.animals a + set name = update_animal.name, species_id = update_animal.species_id, sex = v_sex, + species_detail = update_animal.species_detail, breed = update_animal.breed, + birth_year = v_birth_year, birth_date = v_birth_date, + revision = a.revision + 1 + where a.id = v_row.id; + exception when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation or foreign_key_violation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'animal.updated', 'animal', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +create or replace function public.set_animal_archived( + animal_id uuid, + archived boolean +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.animals; +begin + select a.* into v_row + from public.animals a + where a.id = set_animal_archived.animal_id + and a.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if set_animal_archived.archived is null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + -- Already in that state: nothing written, nothing counted. The relations + -- stay as they are either way (§7.1). + if (v_row.archived_at is not null) = set_animal_archived.archived then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + update public.animals a + set archived_at = case when set_animal_archived.archived then now() end, + revision = a.revision + 1 + where a.id = v_row.id; + + perform private.log_event( + auth.uid(), + case when set_animal_archived.archived then 'animal.archived' else 'animal.restored' end, + 'animal', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +-- --------------------------------------------------------------------------- +-- Relation write RPCs. The animal's workspace is found among the caller's +-- writable ones without a lock, then the locks follow the one order: the +-- workspace (create only: the workspace cap), the animal, the relation, the +-- client (create only, shared), the budget last. +-- --------------------------------------------------------------------------- +create or replace function public.create_animal_client_relation( + animal_id uuid, + client_id uuid, + create_request_id uuid, + relation_role text, + started_on text default null +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_workspace_id uuid; + v_animal_archived_at timestamptz; + v_client_archived_at timestamptz; + v_role public.animal_relation_role; + v_started_on date; + v_digest bytea; + v_existing_id uuid; + v_existing_revision integer; + v_existing_digest bytea; + v_id uuid; +begin + select a.workspace_id into v_workspace_id + from public.animals a + where a.id = create_animal_client_relation.animal_id + and a.workspace_id in (select private.writable_workspace_ids()); + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + perform 1 from public.workspaces w where w.id = v_workspace_id for no key update; + select a.archived_at into v_animal_archived_at + from public.animals a + where a.id = create_animal_client_relation.animal_id + and a.workspace_id = v_workspace_id + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + -- The client must be of the animal's workspace: any other is unknown. + select c.archived_at into v_client_archived_at + from public.clients c + where c.id = create_animal_client_relation.client_id + and c.workspace_id = v_workspace_id + for share; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + + begin + v_role := create_animal_client_relation.relation_role::public.animal_relation_role; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + if v_role is null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + v_started_on := private.parse_record_date(create_animal_client_relation.started_on); + v_digest := sha256(convert_to(jsonb_build_array( + create_animal_client_relation.animal_id, create_animal_client_relation.client_id, v_role, v_started_on + )::text, 'UTF8')); + + -- A replay answers the relation it created, whatever happened since. + select r.id, r.revision, r.create_request_digest + into v_existing_id, v_existing_revision, v_existing_digest + from public.animal_client_relations r + where r.workspace_id = v_workspace_id + and r.create_request_id = create_animal_client_relation.create_request_id; + if found then + if v_existing_digest <> v_digest then + raise exception 'request_conflict' using errcode = 'P0001'; + end if; + return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision); + end if; + + if v_animal_archived_at is not null or v_client_archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + if exists (select 1 from public.animal_client_relations r + where r.animal_id = create_animal_client_relation.animal_id + and r.client_id = create_animal_client_relation.client_id + and r.relation_role = v_role + and r.ended_at is null and r.voided_at is null) then + raise exception 'duplicate_relation' using errcode = 'P0001'; + end if; + -- Current relations count against 20; every row, ended and voided included, + -- against 200 per animal and 100 000 per workspace (a create-and-void loop + -- cannot grow the table without bound). + if (select count(*) from public.animal_client_relations r + where r.workspace_id = v_workspace_id and r.animal_id = create_animal_client_relation.animal_id + and r.ended_at is null and r.voided_at is null) >= 20 + or (select count(*) from public.animal_client_relations r + where r.workspace_id = v_workspace_id and r.animal_id = create_animal_client_relation.animal_id) >= 200 + or (select count(*) from public.animal_client_relations r + where r.workspace_id = v_workspace_id) >= 100000 then + raise exception 'limit_reached' using errcode = 'P0001'; + end if; + + perform private.consume_write_budget(v_workspace_id); + begin + insert into public.animal_client_relations ( + workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest + ) + values ( + v_workspace_id, create_animal_client_relation.animal_id, create_animal_client_relation.client_id, + v_role, v_started_on, create_animal_client_relation.create_request_id, v_digest + ) + returning id into v_id; + exception + when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + when unique_violation then + raise exception 'duplicate_relation' using errcode = 'P0001'; + when foreign_key_violation then + raise exception 'not_found' using errcode = '42501'; + end; + + perform private.log_event( + auth.uid(), 'animal_client_relation.created', 'animal_client_relation', v_id, null, null, + jsonb_build_object('workspace_id', v_workspace_id) + ); + return jsonb_build_object('id', v_id, 'revision', 1); +end; +$$; + +-- Shared opening of the three RPCs that change an existing relation: find it +-- among the caller's writable workspaces, lock its animal then the relation, +-- refuse an archived animal, a stale revision and a voided relation. Returns +-- the locked relation row. +create or replace function private.lock_relation_for_write(p_relation_id uuid, p_expected_revision integer) +returns public.animal_client_relations +language plpgsql +volatile +security definer +set search_path = '' +as $$ +declare + v_workspace_id uuid; + v_animal_id uuid; + v_animal_archived_at timestamptz; + v_row public.animal_client_relations; +begin + select r.workspace_id, r.animal_id into v_workspace_id, v_animal_id + from public.animal_client_relations r + where r.id = p_relation_id + and r.workspace_id in (select private.writable_workspace_ids()); + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + select a.archived_at into v_animal_archived_at + from public.animals a + where a.id = v_animal_id and a.workspace_id = v_workspace_id + for update; + select r.* into v_row + from public.animal_client_relations r + where r.id = p_relation_id + for update; + -- The relations of an archived animal are frozen (§7.1). + if v_animal_archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + if p_expected_revision is distinct from v_row.revision then + raise exception 'conflict' using errcode = 'P0001'; + end if; + -- A voided relation keeps its state: no end, no date change, no un-voiding (N4). + if v_row.voided_at is not null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + return v_row; +end; +$$; + +comment on function private.lock_relation_for_write(uuid, integer) is + 'Authorises and locks (animal, then relation) a relation write; refuses not_found, archived, conflict, voided. For the relation RPCs only.'; + +create or replace function public.end_animal_client_relation( + relation_id uuid, + expected_revision integer, + ended_on text default null +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.animal_client_relations; + v_ended_on date; +begin + v_row := private.lock_relation_for_write(end_animal_client_relation.relation_id, + end_animal_client_relation.expected_revision); + if v_row.ended_at is not null then + raise exception 'already_ended' using errcode = 'P0001'; + end if; + v_ended_on := private.parse_record_date(end_animal_client_relation.ended_on); + + perform private.consume_write_budget(v_row.workspace_id); + begin + update public.animal_client_relations r + set ended_at = now(), ended_on = v_ended_on, revision = r.revision + 1 + where r.id = v_row.id; + exception when check_violation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'animal_client_relation.ended', 'animal_client_relation', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +create or replace function public.update_animal_client_relation( + relation_id uuid, + expected_revision integer, + started_on text, + ended_on text +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.animal_client_relations; + v_started_on date; + v_ended_on date; +begin + v_row := private.lock_relation_for_write(update_animal_client_relation.relation_id, + update_animal_client_relation.expected_revision); + v_started_on := private.parse_record_date(update_animal_client_relation.started_on); + v_ended_on := private.parse_record_date(update_animal_client_relation.ended_on); + -- An end date belongs to an ended relation only. + if v_row.ended_at is null and v_ended_on is not null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + if (v_started_on, v_ended_on) is not distinct from (v_row.started_on, v_row.ended_on) then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + begin + update public.animal_client_relations r + set started_on = v_started_on, ended_on = v_ended_on, revision = r.revision + 1 + where r.id = v_row.id; + exception when check_violation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'animal_client_relation.updated', 'animal_client_relation', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +create or replace function public.void_animal_client_relation( + relation_id uuid, + expected_revision integer +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.animal_client_relations; +begin + v_row := private.lock_relation_for_write(void_animal_client_relation.relation_id, + void_animal_client_relation.expected_revision); + + perform private.consume_write_budget(v_row.workspace_id); + -- Every value stays as entered; the row leaves the lists, the current + -- index, the derived values and the current cap (N4). + update public.animal_client_relations r + set voided_at = now(), revision = r.revision + 1 + where r.id = v_row.id; + + perform private.log_event( + auth.uid(), 'animal_client_relation.voided', 'animal_client_relation', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +-- --------------------------------------------------------------------------- +-- Reads (contract §9.3): security invoker, so RLS limits them to the caller's +-- workspaces; called with POST, so terms and cursors stay out of URLs. Voided +-- relations are left out of every list and derived value. +-- --------------------------------------------------------------------------- +-- The species filter is `species_filter`: a parameter cannot share the name +-- of the `species_id` output column. +create or replace function public.search_animals( + workspace_id uuid, + query text default '', + species_filter text default null, + archived boolean default false, + page_size integer default 25, + after_name_key text default null, + after_id uuid default null +) +returns table ( + id uuid, + name text, + species_id text, + species_detail text, + sex public.animal_sex, + breed text, + birth_year smallint, + archived_at timestamptz, + name_key text, + current_owners jsonb, + current_owner_count integer +) +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_term text := btrim(coalesce(search_animals.query, '')); + v_pattern text; +begin + if char_length(v_term) > 100 + or search_animals.archived is null + or search_animals.page_size is null + or search_animals.page_size not between 1 and 100 + or (search_animals.after_name_key is null) <> (search_animals.after_id is null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%'; + + return query + with page as ( + select a.id, a.workspace_id, a.name, a.species_id, a.species_detail, a.sex, a.breed, a.birth_year, + a.archived_at, a.name_key + from public.animals a + where a.workspace_id = search_animals.workspace_id + and (a.archived_at is not null) = search_animals.archived + and (search_animals.species_filter is null or a.species_id = search_animals.species_filter) + and (v_term = '' or a.search_key like v_pattern) + and (search_animals.after_name_key is null + or (a.name_key, a.id) > (search_animals.after_name_key collate "C", search_animals.after_id)) + order by a.name_key, a.id + limit search_animals.page_size + ) + select p.id, p.name, p.species_id, p.species_detail, p.sex, p.breed, p.birth_year, p.archived_at, p.name_key, + o.owners, o.owner_count + from page p + cross join lateral ( + select coalesce(jsonb_agg(jsonb_build_object('client_id', x.client_id, 'display_name', x.display_name, + 'archived', x.archived) + order by x.name_key, x.client_id) filter (where x.rank <= 3), '[]'::jsonb) as owners, + count(*)::integer as owner_count + from ( + select c.id as client_id, c.display_name, c.archived_at is not null as archived, c.name_key, + row_number() over (order by c.name_key, c.id) as rank + from public.animal_client_relations r + join public.clients c on c.workspace_id = r.workspace_id and c.id = r.client_id + where r.workspace_id = p.workspace_id and r.animal_id = p.id + and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null + ) x + ) o + order by p.name_key, p.id; +end; +$$; + +-- A client's relations with their animals: current first, then former, each +-- group in animal name order, then relation id. `sort_key` is the cursor: +-- '0' (current) or '1' (former) followed by the animal's name_key. +create or replace function public.list_client_animals( + client_id uuid, + page_size integer default 50, + after_sort text default null, + after_id uuid default null +) +returns table ( + relation_id uuid, + relation_role public.animal_relation_role, + started_on date, + ended_on date, + is_current boolean, + relation_revision integer, + animal_id uuid, + animal_name text, + species_id text, + species_detail text, + sex public.animal_sex, + breed text, + birth_year smallint, + animal_archived_at timestamptz, + sort_key text +) +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +begin + if list_client_animals.page_size is null + or list_client_animals.page_size not between 1 and 100 + or (list_client_animals.after_sort is null) <> (list_client_animals.after_id is null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + + return query + select s.relation_id, s.relation_role, s.started_on, s.ended_on, s.is_current, s.relation_revision, + s.animal_id, s.animal_name, s.species_id, s.species_detail, s.sex, s.breed, s.birth_year, + s.animal_archived_at, s.sort_key + from ( + select r.id as relation_id, r.relation_role, r.started_on, r.ended_on, r.ended_at is null as is_current, + r.revision as relation_revision, a.id as animal_id, a.name as animal_name, a.species_id, + a.species_detail, a.sex, a.breed, a.birth_year, a.archived_at as animal_archived_at, + ((case when r.ended_at is null then '0' else '1' end) || a.name_key) collate "C" as sort_key + from public.animal_client_relations r + join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id + where r.client_id = list_client_animals.client_id + and r.voided_at is null + ) s + where list_client_animals.after_sort is null + or (s.sort_key, s.relation_id) > (list_client_animals.after_sort collate "C", list_client_animals.after_id) + order by s.sort_key, s.relation_id + limit list_client_animals.page_size; +end; +$$; + +-- Before archiving a client: the active animals for which it holds the only +-- current owner relation (no other client, archived or not, has one). +create or replace function public.client_archive_preview(client_id uuid) +returns jsonb +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_count integer; + v_animals jsonb; +begin + with sole as ( + select a.id, a.name, a.name_key + from public.animal_client_relations r + join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id + where r.client_id = client_archive_preview.client_id + and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null + and a.archived_at is null + and not exists ( + select 1 from public.animal_client_relations o + where o.workspace_id = r.workspace_id and o.animal_id = r.animal_id + and o.relation_role = 'owner' and o.ended_at is null and o.voided_at is null + and o.client_id <> r.client_id + ) + ) + select (select count(*)::integer from sole), + coalesce((select jsonb_agg(jsonb_build_object('id', f.id, 'name', f.name) order by f.name_key, f.id) + from (select * from sole order by sole.name_key, sole.id limit 10) f), '[]'::jsonb) + into v_count, v_animals; + return jsonb_build_object('count', v_count, 'animals', v_animals); +end; +$$; + +-- search_clients gains current_animal_count (contract §9.3): a return type +-- change, so the function is dropped and created again with the same +-- parameters, rules and privileges. +drop function public.search_clients(uuid, text, boolean, integer, text, uuid); + +create function public.search_clients( + workspace_id uuid, + query text default '', + archived boolean default false, + page_size integer default 25, + after_name_key text default null, + after_id uuid default null +) +returns table ( + id uuid, + kind public.client_kind, + display_name text, + city text, + phone text, + email text, + archived_at timestamptz, + name_key text, + current_animal_count integer +) +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_term text := btrim(coalesce(search_clients.query, '')); + v_pattern text; + v_digits text; +begin + if char_length(v_term) > 100 + or search_clients.archived is null + or search_clients.page_size is null + or search_clients.page_size not between 1 and 100 + or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + + -- Folded term inside search_key; LIKE wildcards escaped, backslash first. + v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%'; + -- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits) + -- is also looked for in phone_digits, without one leading 0. + if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then + v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', ''); + end if; + + return query + with page as ( + select c.id, c.workspace_id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key + from public.clients c + where c.workspace_id = search_clients.workspace_id + and (c.archived_at is not null) = search_clients.archived + and (v_term = '' + or c.search_key like v_pattern + or (v_digits is not null and c.phone_digits like '%' || v_digits || '%')) + and (search_clients.after_name_key is null + or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id)) + order by c.name_key, c.id + limit search_clients.page_size + ) + -- Distinct animals of the current relations (any role, not voided), active animals only. + select p.id, p.kind, p.display_name, p.city, p.phone, p.email, p.archived_at, p.name_key, + (select count(distinct r.animal_id)::integer + from public.animal_client_relations r + join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id + where r.workspace_id = p.workspace_id and r.client_id = p.id + and r.ended_at is null and r.voided_at is null and a.archived_at is null) + from page p + order by p.name_key, p.id; +end; +$$; + +comment on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text) is + 'Creates an animal in a writable workspace, with an optional initial relation; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision, relation_id}.'; +comment on function public.update_animal(uuid, integer, text, text, text, text, text, text, text) is + 'Replaces the seven fields of an active animal at expected_revision. Returns {revision}.'; +comment on function public.set_animal_archived(uuid, boolean) is + 'Archives or restores an animal (same state: no write); its relations are kept. Returns {revision}.'; +comment on function public.create_animal_client_relation(uuid, uuid, uuid, text, text) is + 'Creates a current relation between an active animal and an active client of one workspace; idempotent by create_request_id. Returns {id, revision}.'; +comment on function public.end_animal_client_relation(uuid, integer, text) is + 'Ends a current relation (ended_at = now, optional ended_on). Returns {revision}.'; +comment on function public.update_animal_client_relation(uuid, integer, text, text) is + 'Corrects the dates of a relation that is not voided. Returns {revision}.'; +comment on function public.void_animal_client_relation(uuid, integer) is + 'Voids a relation entered by mistake (N4): kept, frozen, left out of lists and derived values. Returns {revision}.'; +comment on function public.search_animals(uuid, text, text, boolean, integer, text, uuid) is + 'Folded search (name, breed, species detail) in one workspace, optional species filter, keyset pages on (name_key, id), with the current owners.'; +comment on function public.list_client_animals(uuid, integer, text, uuid) is + 'A client''s relations with their animals, current then former, keyset on (sort_key, relation_id); 50 by default, 100 at most.'; +comment on function public.client_archive_preview(uuid) is + 'Active animals for which the client is the only current owner: {count, animals: first 10 by name}.'; +comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is + 'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most, with current_animal_count.'; + +-- --------------------------------------------------------------------------- +-- Privileges + RLS (N7: nothing for anon or service_role) +-- --------------------------------------------------------------------------- +revoke all on public.animals from public, anon, authenticated, service_role; +grant select ( + id, workspace_id, name, species_id, species_detail, sex, breed, birth_year, birth_date, + name_key, search_key, create_request_id, revision, archived_at, created_at, updated_at +) on public.animals to authenticated; + +revoke all on public.animal_client_relations from public, anon, authenticated, service_role; +grant select ( + id, workspace_id, animal_id, client_id, relation_role, started_on, ended_on, ended_at, voided_at, + create_request_id, revision, created_at, updated_at +) on public.animal_client_relations to authenticated; + +alter table public.animals enable row level security; +alter table public.animal_client_relations enable row level security; + +create policy animals_select_member + on public.animals + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +create policy animal_client_relations_select_member + on public.animal_client_relations + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +revoke all on function private.utc_tomorrow(timestamptz) from public, anon, authenticated, service_role; +revoke all on function private.parse_record_date(text) from public, anon, authenticated, service_role; +revoke all on function private.parse_birth_year(text) from public, anon, authenticated, service_role; +revoke all on function private.lock_relation_for_write(uuid, integer) from public, anon, authenticated, service_role; +revoke all on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.update_animal(uuid, integer, text, text, text, text, text, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.set_animal_archived(uuid, boolean) from public, anon, authenticated, service_role; +revoke all on function public.create_animal_client_relation(uuid, uuid, uuid, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.end_animal_client_relation(uuid, integer, text) from public, anon, authenticated, service_role; +revoke all on function public.update_animal_client_relation(uuid, integer, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.void_animal_client_relation(uuid, integer) from public, anon, authenticated, service_role; +revoke all on function public.search_animals(uuid, text, text, boolean, integer, text, uuid) + from public, anon, authenticated, service_role; +revoke all on function public.list_client_animals(uuid, integer, text, uuid) from public, anon, authenticated, service_role; +revoke all on function public.client_archive_preview(uuid) from public, anon, authenticated, service_role; +revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid) + from public, anon, authenticated, service_role; + +grant execute on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text) to authenticated; +grant execute on function public.update_animal(uuid, integer, text, text, text, text, text, text, text) to authenticated; +grant execute on function public.set_animal_archived(uuid, boolean) to authenticated; +grant execute on function public.create_animal_client_relation(uuid, uuid, uuid, text, text) to authenticated; +grant execute on function public.end_animal_client_relation(uuid, integer, text) to authenticated; +grant execute on function public.update_animal_client_relation(uuid, integer, text, text) to authenticated; +grant execute on function public.void_animal_client_relation(uuid, integer) to authenticated; +grant execute on function public.search_animals(uuid, text, text, boolean, integer, text, uuid) to authenticated; +grant execute on function public.list_client_animals(uuid, integer, text, uuid) to authenticated; +grant execute on function public.client_archive_preview(uuid) to authenticated; +grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated; diff --git a/supabase/tests/013_clients.sql b/supabase/tests/013_clients.sql index 38857966..92e6cbd2 100644 --- a/supabase/tests/013_clients.sql +++ b/supabase/tests/013_clients.sql @@ -231,7 +231,7 @@ create function pg_temp.names(p_query text, p_archived boolean default false, p_ as $$ select coalesce(string_agg(s.display_name, '|' order by s.ord), '') from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_query, p_archived, p_size, p_after_key, p_after_id) with ordinality s(id, kind, display_name, city, phone, email, - archived_at, name_key, ord) $$; + archived_at, name_key, current_animal_count, ord) $$; grant execute on function pg_temp.names(text, boolean, integer, text, uuid) to authenticated; select is(pg_temp.names(''), '100% Cheval|A_B Haras|Back\slash|Écurie du Lac|' || repeat('é', 120) || '|Mail|Marie Dupont', diff --git a/supabase/tests/014_animals_relations.sql b/supabase/tests/014_animals_relations.sql new file mode 100644 index 00000000..7501c0bb --- /dev/null +++ b/supabase/tests/014_animals_relations.sql @@ -0,0 +1,870 @@ +-- V1-1.4 Animals and relations (M3): species rows, animal fields and the +-- birth model, idempotent creates, revisions, archive, relations with their +-- history (current, ended, voided), derived values, searches, isolation +-- between workspaces, refusals for every other actor, caps and the write +-- budget shared with the clients, minimised audit, integrity under a +-- privileged writer, privileges and census. +-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.2-§5.4, §7.1, §9, §10, §12.1. +-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after +-- creating an animal; S a platform owner; E (per-animal caps, animal cap), +-- F (budget), H (workspace relation cap) and G (D9a) confirmed. +begin; +select plan(254); + +insert into auth.users (id, email, email_confirmed_at) values + ('70000000-0000-0000-0000-00000000000a', 'alice-an@test.local', now()), + ('70000000-0000-0000-0000-00000000000b', 'bob-an@test.local', now()), + ('70000000-0000-0000-0000-00000000000c', 'carol-an@test.local', null), + ('70000000-0000-0000-0000-00000000000d', 'dave-an@test.local', now()), + ('70000000-0000-0000-0000-000000000005', 'staff-an@test.local', now()), + ('70000000-0000-0000-0000-00000000000e', 'cap-an@test.local', now()), + ('70000000-0000-0000-0000-00000000000f', 'budget-an@test.local', now()), + ('70000000-0000-0000-0000-000000000011', 'wscap-an@test.local', now()), + ('70000000-0000-0000-0000-000000000012', 'd9a-an@test.local', now()); +select private.assign_platform_role(null, '70000000-0000-0000-0000-000000000005', 'owner'); +-- A species that is later switched off (« species active or unchanged »). +insert into public.species (id, name_fr, name_en, sort_order) values ('zz-retired', 'Retirée', 'Retired', 5000); + +create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer +as $$ select id from public.workspaces where personal_user_id = p_user $$; +create function pg_temp.wa() returns uuid language sql stable +as $$ select pg_temp.ws('70000000-0000-0000-0000-00000000000a') $$; +create function pg_temp.act_as(p_user uuid) returns text language sql +as $$ select set_config('request.jwt.claims', + json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$; +create table pg_temp.ids (key text primary key, id uuid not null); +create function pg_temp.id(p_key text) returns uuid language sql stable +as $$ select id from pg_temp.ids where key = p_key $$; +create function pg_temp.animal(p_id uuid) returns public.animals language sql stable security definer +as $$ select a from public.animals a where a.id = p_id $$; +create function pg_temp.relation(p_id uuid) returns public.animal_client_relations language sql stable security definer +as $$ select r from public.animal_client_relations r where r.id = p_id $$; +create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer +as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$; +create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer +as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$; +create function pg_temp.tomorrow() returns text language sql stable +as $$ select ((now() at time zone 'UTC')::date + 1)::text $$; +-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint. +create function pg_temp.err(p_sql text) returns text language plpgsql +as $$ +declare v_state text; v_msg text; v_detail text; v_hint text; +begin + execute p_sql; + return 'no error'; +exception when others then + get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text, + v_detail = pg_exception_detail, v_hint = pg_exception_hint; + return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, ''); +end; +$$; +-- SQLSTATE and message only: the real image appends a hint to table-privilege refusals. +create function pg_temp.denial(p_sql text) returns text language sql +as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$; +-- create_animal as the current caller in A's workspace, keyed for later use. +create function pg_temp.new_animal(p_key text, p_name text, p_species text, p_sex text, p_detail text default null, + p_breed text default null, p_year text default null, p_date text default null) returns uuid language sql +as $$ insert into pg_temp.ids values (p_key, (public.create_animal(pg_temp.wa(), gen_random_uuid(), p_name, p_species, p_sex, + p_detail, p_breed, p_year, p_date) ->> 'id')::uuid) returning id $$; +create function pg_temp.new_relation(p_key text, p_animal text, p_client text, p_role text, p_started text default null) + returns uuid language sql +as $$ insert into pg_temp.ids values (p_key, (public.create_animal_client_relation(pg_temp.id(p_animal), pg_temp.id(p_client), + gen_random_uuid(), p_role, p_started) ->> 'id')::uuid) returning id $$; +create function pg_temp.try_animal(p_name text, p_species text, p_sex text, p_detail text default null, + p_breed text default null, p_year text default null, p_date text default null) returns text language sql +as $$ select pg_temp.err(format('select public.create_animal(%L, gen_random_uuid(), %L, %L, %L, %L, %L, %L, %L)', + pg_temp.wa(), p_name, p_species, p_sex, p_detail, p_breed, p_year, p_date)) $$; +grant all on pg_temp.ids to authenticated, anon, service_role; +grant execute on all functions in schema pg_temp to authenticated, anon, service_role; + +-- --------------------------------------------------------------------------- +-- 1. Schema, species, privileges, census +-- --------------------------------------------------------------------------- +select has_table('public', 'animals', 'table public.animals exists'); +select has_table('public', 'animal_client_relations', 'table public.animal_client_relations exists'); +select ok((select bool_and(relrowsecurity) from pg_class + where oid in ('public.animals'::regclass, 'public.animal_client_relations'::regclass)), + 'RLS enabled on animals and animal_client_relations'); +select enum_has_labels('public', 'animal_sex', array['male', 'female', 'unknown'], 'animal_sex: male, female, unknown'); +select enum_has_labels('public', 'animal_relation_role', array['owner', 'keeper', 'contact'], + 'animal_relation_role: owner, keeper, contact'); +select results_eq( + $$ select id, name_fr, name_en, sort_order from public.species where id <> 'zz-retired' order by sort_order $$, + $$ values ('equine'::text, 'Cheval'::text, 'Horse'::text, 10), ('asinine', 'Âne', 'Donkey', 20), ('canine', 'Chien', 'Dog', 30), + ('feline', 'Chat', 'Cat', 40), ('bovine', 'Bovin', 'Cattle', 50), ('caprine', 'Chèvre', 'Goat', 60), + ('ovine', 'Mouton', 'Sheep', 70), ('porcine', 'Porc', 'Pig', 80), ('leporine', 'Lapin', 'Rabbit', 90), + ('other', 'Autre', 'Other', 1000) $$, + 'exactly the nine species of the contract and other, equine unchanged' +); +select ok((select bool_and(active) from public.species where id <> 'zz-retired'), 'every species row is active'); +select ok(obj_description('public.species'::regclass, 'pg_class') like 'Species of animals and of anatomical sheets.%', + 'the species table comment names animals'); +select is( + (select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C") from pg_tables + where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')), + 'animal_client_relations:postgres,animals:postgres', 'both tables belong to postgres' +); +select is( + (select count(*) from (values ('anon'), ('service_role')) r(role) + cross join (values ('animals'), ('animal_client_relations')) t(tbl) + cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege(r.role, 'public.' || t.tbl, p.priv)), + 0::bigint, 'anon and service_role hold no privilege on either table' +); +select is( + (select count(*) from (values ('animals'), ('animal_client_relations')) t(tbl) + cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege('authenticated', 'public.' || t.tbl, p.priv)), + 0::bigint, 'authenticated holds no write privilege on either table' +); +select ok(has_column_privilege('authenticated', 'public.animals', 'name', 'select') + and has_column_privilege('authenticated', 'public.animal_client_relations', 'voided_at', 'select') + and not has_column_privilege('authenticated', 'public.animals', 'create_request_digest', 'select') + and not has_column_privilege('authenticated', 'public.animal_client_relations', 'create_request_digest', 'select'), + 'authenticated reads the record columns, never the request digests'); +select is( + (select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',' order by tablename collate "C") + from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')), + 'animal_client_relations:animal_client_relations_select_member:SELECT:authenticated,animals:animals_select_member:SELECT:authenticated', + 'one SELECT policy per table, for authenticated' +); +select is( + (select count(*) from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations') + and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')), + 0::bigint, 'both policies go through caller_workspace_ids() and name no platform role' +); +select is( + (select string_agg(c.conname || '(' || (select string_agg(a.attname, ',' order by k.i) + from unnest(c.conkey) with ordinality k(n, i) join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.n) + || ')->' || c.confrelid::regclass::text || ':' || c.condeferrable, ';' order by c.conname collate "C") + from pg_constraint c where c.conrelid = 'public.animal_client_relations'::regclass and c.contype = 'f'), + 'animal_client_relations_animal_fk(workspace_id,animal_id)->animals:false;animal_client_relations_client_fk(workspace_id,client_id)->clients:false', + 'relations reference animal and client through (workspace_id, id), not deferrable' +); +select ok( + (select indisunique and pg_get_expr(indpred, indrelid) like '%ended_at IS NULL%voided_at IS NULL%' + from pg_index where indexrelid = 'public.animal_client_relations_current_unique'::regclass), + 'the current-relation index is unique on rows neither ended nor voided' +); +select is( + (select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation', + 'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals', + 'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date', + 'parse_birth_year', 'lock_relation_for_write') + and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'), + 'client_archive_preview:invoker,create_animal:definer,create_animal_client_relation:definer,end_animal_client_relation:definer,' + || 'list_client_animals:invoker,lock_relation_for_write:definer,parse_birth_year:invoker,parse_record_date:invoker,' + || 'search_animals:invoker,search_clients:invoker,set_animal_archived:definer,update_animal:definer,' + || 'update_animal_client_relation:definer,utc_tomorrow:invoker,void_animal_client_relation:definer', + 'definer and invoker as designed; search_path empty; owner postgres' +); +select is( + (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C") + from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role) + where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation', + 'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals', + 'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date', + 'parse_birth_year', 'lock_relation_for_write') + and has_function_privilege(r.role, p.oid, 'execute')), + 'authenticated:client_archive_preview,authenticated:create_animal,authenticated:create_animal_client_relation,' + || 'authenticated:end_animal_client_relation,authenticated:list_client_animals,authenticated:search_animals,' + || 'authenticated:search_clients,authenticated:set_animal_archived,authenticated:update_animal,' + || 'authenticated:update_animal_client_relation,authenticated:void_animal_client_relation', + 'EXECUTE: authenticated on the eleven RPCs; the private helpers for nobody; anon and service_role on none' +); +select is(private.utc_tomorrow('2026-12-31 23:30:00+00'), date '2027-01-01', + 'on 31 December UTC, 1 January is the latest accepted date'); +select is(private.utc_tomorrow('2026-12-31 23:30:00-05'), date '2027-01-02', + 'the UTC date decides, not the caller''s zone'); + +-- --------------------------------------------------------------------------- +-- 2. Animals: fields, species, the birth model (D6b), text rules +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000a'); +insert into pg_temp.ids values + ('marie', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Marie Dupont') ->> 'id')::uuid), + ('lac', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'organization', 'Écurie du Lac') ->> 'id')::uuid), + ('paul', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Paul Martin') ->> 'id')::uuid), + ('zoe', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Zoé Bernard') ->> 'id')::uuid), + ('ana', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Ana Petit') ->> 'id')::uuid); + +select is( + public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null, + 'Selle Français', '2015', '2015-04-12') - 'id', + '{"revision": 1, "relation_id": null}'::jsonb, 'create_animal answers revision 1 and no relation'); +insert into pg_temp.ids select 'eclair', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000001'; +select results_eq( + $$ select name, species_id, sex::text, breed, birth_year::integer, birth_date, revision, archived_at is null + from public.animals where id = pg_temp.id('eclair') $$, + $$ values ('Éclair'::text, 'equine'::text, 'male'::text, 'Selle Français'::text, 2015, date '2015-04-12', 1, true) $$, + 'A reads the created animal' +); +select is((pg_temp.animal(pg_temp.id('eclair'))).name_key, 'eclair', 'name_key folds accents and case'); +select is((pg_temp.animal(pg_temp.id('eclair'))).search_key, 'eclair selle francais ', 'search_key holds name, breed and detail'); +select lives_ok($$ select pg_temp.new_animal('bijou', 'Bijou', 'equine', 'female', null, null, '2016') $$, + 'year alone: born in 2016, day unknown'); +select is((pg_temp.animal(pg_temp.id('bijou'))).birth_date, null, 'no date is invented from a year'); +select lives_ok($$ select pg_temp.new_animal('sans', 'Sans Maître', 'equine', 'unknown') $$, + 'birth unknown and sex unknown, chosen explicitly'); +select lives_ok($$ select pg_temp.new_animal('furet', 'Pistache', 'other', 'unknown', 'Furet') $$, + 'other with its detail is accepted'); +select lives_ok($$ select pg_temp.new_animal('rex', 'Rex', 'canine', 'male') $$, 'a canine is accepted'); +select lives_ok($$ select pg_temp.new_animal('luna', 'Luna', 'feline', 'female') $$, 'a feline is accepted'); +select lives_ok($$ select pg_temp.new_animal('quatuor', 'Quatuor', 'equine', 'male') $$, 'another horse'); +select lives_ok($$ select pg_temp.new_animal('retired', 'Ancien', 'zz-retired', 'male') $$, 'an animal of a species still active'); + +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, null, '2015-04-12'), 'P0001|invalid_input||', + 'a date without its year is refused'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2016', '2015-04-12'), 'P0001|invalid_input||', + 'a date of another year is refused'); +select is(pg_temp.try_animal('Other', 'other', 'male'), 'P0001|invalid_input||', 'other without detail is refused'); +select is(pg_temp.try_animal('Detail', 'equine', 'male', 'Furet'), 'P0001|invalid_input||', 'a detail on another species is refused'); +select is(pg_temp.try_animal('Unicorn', 'unicorn', 'male'), 'P0001|invalid_input||', 'an unknown species is refused'); +select is(pg_temp.try_animal('Nothing', null, 'male'), 'P0001|invalid_input||', 'a missing species is refused'); +select is(pg_temp.try_animal('Sex', 'equine', null), 'P0001|invalid_input||', 'a missing sex is refused (no default)'); +select is(pg_temp.try_animal('Sex', 'equine', 'robot'), 'P0001|invalid_input||', 'an unknown sex is refused'); +select is(pg_temp.try_animal('', 'equine', 'male'), 'P0001|invalid_input||', 'an empty name is refused'); +select is(pg_temp.try_animal(' Lead', 'equine', 'male'), 'P0001|invalid_input||', 'a leading space is refused'); +select is(pg_temp.try_animal(e'Tab\there', 'equine', 'male'), 'P0001|invalid_input||', 'a control character is refused'); +select is(pg_temp.try_animal(repeat('é', 81), 'equine', 'male'), 'P0001|invalid_input||', '81 characters are refused'); +select is(pg_temp.try_animal(repeat('é', 80), 'equine', 'male'), 'no error', '80 accented characters are accepted'); +select is(pg_temp.try_animal('Breed', 'equine', 'male', null, repeat('b', 81)), 'P0001|invalid_input||', 'an 81-character breed is refused'); +select is(pg_temp.try_animal('Detail', 'other', 'male', repeat('d', 81)), 'P0001|invalid_input||', 'an 81-character detail is refused'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1899'), 'P0001|invalid_input||', 'birth year 1899 is refused'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1900'), 'no error', 'birth year 1900 is accepted'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4)), 'no error', + 'the year of tomorrow UTC is accepted'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, (left(pg_temp.tomorrow(), 4)::integer + 1)::text), + 'P0001|invalid_input||', 'a later year is refused'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '15'), 'P0001|invalid_input||', 'a two-digit year is refused'); +select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, 'abcd'), 'P0001|invalid_input||', 'a non-numeric year is refused'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '2015-02-30'), 'P0001|invalid_input||', + 'an impossible date is refused without echoing it'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '12/04/2015'), 'P0001|invalid_input||', + 'a date in another format is refused'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '1899', '1899-12-31'), 'P0001|invalid_input||', + 'a date before 1900 is refused'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4), pg_temp.tomorrow()), 'no error', + 'tomorrow UTC is accepted (today somewhere)'); +select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left((pg_temp.tomorrow()::date + 1)::text, 4), + (pg_temp.tomorrow()::date + 1)::text), 'P0001|invalid_input||', 'the day after tomorrow UTC is refused'); +select is((select count(*) from public.animals where workspace_id = pg_temp.wa()), 12::bigint, 'only the valid creates were written'); + +-- --------------------------------------------------------------------------- +-- 3. Idempotent create, update, revision, archive +-- --------------------------------------------------------------------------- +select is(pg_temp.budget(pg_temp.wa()), '17/17', 'five clients and twelve animals counted so far'); +select is( + (public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null, + 'Selle Français', '2015', '2015-04-12') ->> 'id')::uuid, + pg_temp.id('eclair'), 'a replay returns the first animal'); +select is(pg_temp.audit_count(pg_temp.id('eclair')), 1::bigint, 'the replay writes no audit row'); +select is(pg_temp.budget(pg_temp.wa()), '17/17', 'the replay consumes no budget'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', + 'female') $$), 'P0001|request_conflict||', 'the same request id with other content is refused'); + +select is(public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision', + '2', 'an update at the current revision gives revision 2'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou II', 'equine', 'female', null, null, null, null) $$), + 'P0001|conflict||', 'a stale revision is refused'); +select is((pg_temp.animal(pg_temp.id('bijou'))).breed, 'Pur-sang', 'the stale update overwrote nothing'); +select is(public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision', + '2', 'an update that changes nothing keeps the revision'); +select is(pg_temp.audit_count(pg_temp.id('bijou')), 2::bigint, 'and writes no audit row'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'other', 'female', null, null, '2016', null) $$), + 'P0001|invalid_input||', 'an update to other without detail is refused'); +reset role; +update public.species set active = false where id = 'zz-retired'; +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000a'); +select is(public.update_animal(pg_temp.id('retired'), 1, 'Ancien renommé', 'zz-retired', 'male', null, null, null, null) ->> 'revision', + '2', 'an animal keeps a species switched off since'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'zz-retired', 'female', null, null, '2016', null) $$), + 'P0001|invalid_input||', 'an animal cannot move to an inactive species'); +select is(pg_temp.try_animal('Retired', 'zz-retired', 'male'), 'P0001|invalid_input||', 'an inactive species is refused at creation'); + +-- --------------------------------------------------------------------------- +-- 4. Relations: owners, roles, history, voiding +-- --------------------------------------------------------------------------- +select isnt( + public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male', + client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id', + null, 'create_animal with an initial owner relation'); +insert into pg_temp.ids select 'tonnerre', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000002'; +insert into pg_temp.ids select 'r_tonnerre', id from public.animal_client_relations where animal_id = pg_temp.id('tonnerre'); +select results_eq( + $$ select client_id, relation_role::text, started_on, ended_at is null, voided_at is null, revision + from public.animal_client_relations where animal_id = pg_temp.id('tonnerre') $$, + $$ values (pg_temp.id('marie'), 'owner'::text, date '2020-01-01', true, true, 1) $$, + 'the initial relation is current, with its start date' +); +select is(pg_temp.budget(pg_temp.wa()), '21/21', 'animal and relation are two audited writes'); +select is( + public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male', + client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id', + pg_temp.id('r_tonnerre')::text, 'a replay returns the same relation'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male', + client_id => pg_temp.id('marie')) $$), 'P0001|invalid_input||', 'a client without a role is refused'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male', + relation_role => 'owner') $$), 'P0001|invalid_input||', 'a role without a client is refused'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male', + started_on => '2020-01-01') $$), 'P0001|invalid_input||', 'a start date without a client is refused'); + +select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_owner', 'eclair', 'marie', 'owner') $$, 'A links an owner'); +select lives_ok($$ select pg_temp.new_relation('r_eclair_paul_owner', 'eclair', 'paul', 'owner') $$, 'co-ownership: a second owner'); +select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_keeper', 'eclair', 'marie', 'keeper') $$, + 'the same client may also be the keeper'); +select lives_ok($$ select pg_temp.new_relation('r_eclair_lac_keeper', 'eclair', 'lac', 'keeper') $$, 'a stable as keeper'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$), + 'P0001|duplicate_relation||', 'a second current identical relation is refused'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), 'boss') $$), + 'P0001|invalid_input||', 'an unknown role is refused'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), null) $$), + 'P0001|invalid_input||', 'a missing role is refused'); +select is(pg_temp.err(format('select public.create_animal_client_relation(%L, %L, gen_random_uuid(), %L, %L)', + pg_temp.id('eclair'), pg_temp.id('ana'), 'contact', (pg_temp.tomorrow()::date + 1)::text)), + 'P0001|invalid_input||', 'a start date after tomorrow UTC is refused'); +select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('sans')), 0::bigint, + 'an animal may have no owner and no relation'); + +-- Ending, dates, successive relations. +select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_1', 'bijou', 'paul', 'owner', '2018-05-01') $$, 'Paul owns Bijou since 2018'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-01-01') $$), + 'P0001|invalid_input||', 'an end before the start is refused'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-02-30') $$), + 'P0001|invalid_input||', 'an impossible end date is refused'); +select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2018-05-01', '2021-06-30') $$), + 'P0001|invalid_input||', 'an end date on a current relation is refused'); +select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2021-06-30') ->> 'revision', '2', + 'ending the relation with its date gives revision 2'); +select ok((pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_at is not null + and (pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_on = date '2021-06-30', 'the ended relation keeps its row and dates'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2) $$), + 'P0001|already_ended||', 'ending an ended relation is refused'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1) $$), + 'P0001|conflict||', 'a stale revision is refused before the state'); +select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2, '2018-05-01', '2021-07-01') ->> 'revision', '3', + 'the dates of an ended relation can be corrected'); +select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2018-05-01', '2021-07-01') ->> 'revision', '3', + 'a correction that changes nothing keeps the revision'); +select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2022-01-01', '2021-07-01') $$), + 'P0001|invalid_input||', 'a start after the end is refused'); +select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_2', 'bijou', 'paul', 'owner', '2023-03-01') $$, + 'a successive relation of the same triple is accepted once the first has ended'); +select lives_ok($$ select pg_temp.new_relation('r_bijou_lac', 'bijou', 'lac', 'owner') $$, 'Écurie du Lac also owned Bijou'); +select is(public.end_animal_client_relation(pg_temp.id('r_bijou_lac'), 1) ->> 'revision', '2', 'an end with no known date'); +select ok((pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_at is not null and (pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_on is null, + 'ended, date unknown: ended_at set, ended_on null, distinct from a current relation'); + +-- Voiding (N4). +select lives_ok($$ select pg_temp.new_relation('r_rex_marie_wrong', 'rex', 'marie', 'owner', '2019-01-01') $$, 'a relation entered by mistake'); +select is(public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 1) ->> 'revision', '2', 'voiding gives revision 2'); +select results_eq( + $$ select client_id, relation_role::text, started_on, ended_on, ended_at is null, voided_at is not null + from public.animal_client_relations where id = pg_temp.id('r_rex_marie_wrong') $$, + $$ values (pg_temp.id('marie'), 'owner'::text, date '2019-01-01', null::date, true, true) $$, + 'a voided relation keeps every value as entered and gains voided_at, no end date invented' +); +select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$), + 'P0001|invalid_input||', 'voiding twice is refused'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$), + 'P0001|invalid_input||', 'a voided relation cannot be ended'); +select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2, null, null) $$), + 'P0001|invalid_input||', 'a voided relation cannot be corrected'); +select lives_ok($$ select pg_temp.new_relation('r_rex_marie', 'rex', 'marie', 'owner') $$, + 'a voided relation no longer holds the current-relation slot'); +select lives_ok($$ select pg_temp.new_relation('r_rex_lac_contact', 'rex', 'lac', 'contact') $$, 'a contact'); +select is(public.end_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 1, '2024-01-01') ->> 'revision', '2', 'the contact ends'); +select is(public.void_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 2) ->> 'revision', '3', + 'an ended relation recorded by mistake can be voided'); + +-- Four owners for the derived values; a keeper and an owner later archived. +select lives_ok($$ select pg_temp.new_relation('r_q_ana', 'quatuor', 'ana', 'owner'), pg_temp.new_relation('r_q_lac', 'quatuor', 'lac', 'owner'), + pg_temp.new_relation('r_q_marie', 'quatuor', 'marie', 'owner'), pg_temp.new_relation('r_q_paul', 'quatuor', 'paul', 'owner') $$, + 'four co-owners'); +select lives_ok($$ select pg_temp.new_relation('r_luna_lac', 'luna', 'lac', 'owner'), pg_temp.new_relation('r_luna_zoe', 'luna', 'zoe', 'owner'), + pg_temp.new_relation('r_rex_zoe_keeper', 'rex', 'zoe', 'keeper') $$, 'Luna owned by the stable and Zoé, Zoé keeps Rex'); + +-- --------------------------------------------------------------------------- +-- 5. Archive (§7.1): no cascade, frozen relations, archived client +-- --------------------------------------------------------------------------- +select is(public.client_archive_preview(pg_temp.id('paul')), + jsonb_build_object('count', 1, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('bijou'), 'name', 'Bijou'))), + 'preview: Paul is the only current owner of Bijou'); +select is(public.set_client_archived(pg_temp.id('zoe'), true) ->> 'revision', '2', 'Zoé is archived'); +select is((select count(*) from public.animals where id = pg_temp.id('luna') and archived_at is null), 1::bigint, + 'archiving a client archives none of its animals'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('luna'), pg_temp.id('zoe'), gen_random_uuid(), 'keeper') $$), + 'P0001|archived||', 'a new relation needs an active client'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male', + client_id => pg_temp.id('zoe'), relation_role => 'owner') $$), 'P0001|archived||', 'so does the initial relation'); +select is(public.end_animal_client_relation(pg_temp.id('r_rex_zoe_keeper'), 1) ->> 'revision', '2', + 'the relation of an archived client with an active animal can still be ended'); +select is(public.client_archive_preview(pg_temp.id('lac')), '{"count": 0, "animals": []}'::jsonb, + 'a co-owner, even archived, means the stable is not the only owner of Luna'); + +select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'Bijou is archived'); +select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'archiving again changes nothing'); +select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('bijou') + and ended_at is null and voided_at is null), 1::bigint, 'archiving an animal ends none of its relations'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('bijou'), pg_temp.id('ana'), gen_random_uuid(), 'keeper') $$), + 'P0001|archived||', 'no new relation on an archived animal'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 9) $$), + 'P0001|archived||', 'the relations of an archived animal are frozen (archived before conflict)'); +select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1, null, null) $$), + 'P0001|archived||', 'no date correction either'); +select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) $$), + 'P0001|archived||', 'no voiding either'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, null, null, null) $$), + 'P0001|archived||', 'an archived animal refuses edits, archived reported before the stale revision'); +select is(public.client_archive_preview(pg_temp.id('paul')), '{"count": 0, "animals": []}'::jsonb, + 'the preview lists active animals only'); +select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('bijou'), null) $$), 'P0001|invalid_input||', + 'a missing archive state is refused'); + +-- --------------------------------------------------------------------------- +-- 6. Reads: searches, derived values, a client's animals +-- --------------------------------------------------------------------------- +create function pg_temp.animals(p_query text, p_species text default null, p_archived boolean default false, + p_size integer default 25, p_after_key text default null, p_after_id uuid default null) returns text language sql +as $$ select coalesce(string_agg(s.name, '|' order by s.ord), '') + from public.search_animals(pg_temp.wa(), p_query, p_species, p_archived, p_size, p_after_key, p_after_id) + with ordinality s(id, name, species_id, species_detail, sex, breed, birth_year, archived_at, name_key, + current_owners, current_owner_count, ord) $$; +create function pg_temp.owners(p_key text) returns text language sql +as $$ select s.current_owner_count || ' ' || s.current_owners::text + from public.search_animals(pg_temp.wa(), (pg_temp.animal(pg_temp.id(p_key))).name, + null, (pg_temp.animal(pg_temp.id(p_key))).archived_at is not null) s + where s.id = pg_temp.id(p_key) $$; +create function pg_temp.client_count(p_key text) returns integer language sql +as $$ select s.current_animal_count from public.search_clients(pg_temp.wa(), '', true) s where s.id = pg_temp.id(p_key) + union all + select s.current_animal_count from public.search_clients(pg_temp.wa(), '', false) s where s.id = pg_temp.id(p_key) $$; +create function pg_temp.client_animals(p_key text, p_size integer default 50, p_after_sort text default null, + p_after_id uuid default null) returns text language sql +as $$ select coalesce(string_agg(s.animal_name || ':' || s.relation_role || ':' || case when s.is_current then 'current' else 'former' end, + '|' order by s.ord), '') + from public.list_client_animals(pg_temp.id(p_key), p_size, p_after_sort, p_after_id) + with ordinality s(relation_id, relation_role, started_on, ended_on, is_current, relation_revision, animal_id, + animal_name, species_id, species_detail, sex, breed, birth_year, animal_archived_at, sort_key, ord) $$; +grant execute on function pg_temp.animals(text, text, boolean, integer, text, uuid), pg_temp.owners(text), + pg_temp.client_count(text), pg_temp.client_animals(text, integer, text, uuid) to authenticated, anon, service_role; + +select is(pg_temp.animals(''), 'Ancien renommé|Date|Éclair|' || repeat('é', 80) || '|Luna|Pistache|Quatuor|Rex|Sans Maître|Tonnerre|Year|Year', + 'an empty term lists the active animals in name order (archived left out)'); +select is(pg_temp.animals('', null, true), 'Bijou', 'the archived filter lists the archived animal only'); +select is(pg_temp.animals('ECLA'), 'Éclair', 'search folds case and accents'); +select is(pg_temp.animals('francais'), 'Éclair', 'search reads the breed'); +select is(pg_temp.animals('furet'), 'Pistache', 'search reads the species detail'); +select is(pg_temp.animals('', 'canine'), 'Rex', 'the species filter keeps one species'); +select is(pg_temp.animals('', 'feline'), 'Luna', 'and excludes the others'); +select is(pg_temp.animals('', null, false, 3), 'Ancien renommé|Date|Éclair', 'page 1 of 3'); +select is(pg_temp.animals('', null, false, 3, (pg_temp.animal(pg_temp.id('eclair'))).name_key, pg_temp.id('eclair')), + repeat('é', 80) || '|Luna|Pistache', 'page 2 continues after the cursor, no gap, no repeat'); +select is(pg_temp.err($$ select pg_temp.animals(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused'); +select is(pg_temp.err($$ select pg_temp.animals('', null, false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused'); +select is(pg_temp.err($$ select pg_temp.animals('', null, false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused'); +select is(pg_temp.err($$ select pg_temp.animals('', null, null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused'); + +select is(pg_temp.owners('eclair'), + '2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false), + jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text, + 'current owners in client name order, keepers left out'); +select is(pg_temp.owners('quatuor'), + '4 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('ana'), 'display_name', 'Ana Petit', 'archived', false), + jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false), + jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text, + 'the first three owners, the count of all four'); +select is(pg_temp.owners('luna'), + '2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false), + jsonb_build_object('client_id', pg_temp.id('zoe'), 'display_name', 'Zoé Bernard', 'archived', true))::text, + 'an archived owner stays, flagged'); +select is(pg_temp.owners('rex'), + '1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text, + 'a voided owner relation is left out'); +select is(pg_temp.owners('sans'), '0 []', 'no owner: an empty list (« Propriétaire non renseigné »)'); +select is(pg_temp.owners('bijou'), + '1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text, + 'ended relations are left out'); + +select is(pg_temp.client_count('marie'), 4, 'Marie: Éclair (two roles, counted once), Quatuor, Rex, Tonnerre; the voided one left out'); +select is(pg_temp.client_count('paul'), 2, 'Paul: Éclair and Quatuor; Bijou archived is not counted'); +select is(pg_temp.client_count('lac'), 3, 'the stable: Éclair, Luna, Quatuor; ended and voided relations left out'); +select is(pg_temp.client_count('zoe'), 1, 'archived Zoé: Luna; her ended keeper relation left out'); + +select is(pg_temp.client_animals('lac'), 'Éclair:keeper:current|Luna:owner:current|Quatuor:owner:current|Bijou:owner:former', + 'a client''s animals: current first, then former, each by name; voided left out'); +select is(pg_temp.client_animals('paul'), 'Bijou:owner:current|Éclair:owner:current|Quatuor:owner:current|Bijou:owner:former', + 'successive relations of one animal appear as current and former'); +select is(pg_temp.client_animals('lac', 2), 'Éclair:keeper:current|Luna:owner:current', 'page 1 of 2'); +select is(pg_temp.client_animals('lac', 2, + (select s.sort_key from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1), + (select s.relation_id from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1)), + 'Quatuor:owner:current|Bijou:owner:former', 'page 2 continues after the cursor'); +select is(pg_temp.err($$ select pg_temp.client_animals('lac', 0) $$), 'P0001|invalid_input||', 'page size 0 is refused'); +select is(pg_temp.err($$ select pg_temp.client_animals('lac', 50, '0x') $$), 'P0001|invalid_input||', 'a cursor without its id is refused'); +select is(public.client_archive_preview(pg_temp.id('marie')), + jsonb_build_object('count', 2, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('rex'), 'name', 'Rex'), + jsonb_build_object('id', pg_temp.id('tonnerre'), 'name', 'Tonnerre'))), + 'preview: Marie is the only current owner of Rex and Tonnerre (co-owned animals left out)'); + +-- Restore: editable again. +select is(public.set_animal_archived(pg_temp.id('bijou'), false) ->> 'revision', '4', 'restoring adds one revision'); +select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) ->> 'revision', '2', 'its relations can change again'); + +-- D creates an animal while active (used after its deactivation). +select pg_temp.act_as('70000000-0000-0000-0000-00000000000d'); +insert into pg_temp.ids values ('dave', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000d'), + gen_random_uuid(), 'Cheval de Dave', 'equine', 'male') ->> 'id')::uuid); +-- B's own records, for the cross-workspace attempts. +select pg_temp.act_as('70000000-0000-0000-0000-00000000000b'); +insert into pg_temp.ids values + ('b_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'person', 'Client B') ->> 'id')::uuid), + ('b_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'Animal B', 'equine', 'male') ->> 'id')::uuid); +reset role; +update public.profiles set active = false where id = '70000000-0000-0000-0000-00000000000d'; + +-- --------------------------------------------------------------------------- +-- 7. Isolation: the same not_found for a foreign and an unknown id +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000b'); +select is((select count(*) from public.animals), 1::bigint, 'B reads its own animal only'); +select is((select count(*) from public.animal_client_relations), 0::bigint, 'B reads no relation of A'); +select is((select count(*) from public.animals where id = pg_temp.id('eclair')), 0::bigint, 'B naming an animal of A reads nothing'); +select is((select count(*) from public.search_animals(pg_temp.wa())), 0::bigint, 'B searching the workspace of A finds nothing'); +select is((select count(*) from public.list_client_animals(pg_temp.id('lac'))), 0::bigint, 'B listing a client of A finds nothing'); +select is(public.client_archive_preview(pg_temp.id('marie')), '{"count": 0, "animals": []}'::jsonb, 'B previews nothing of A'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male') $$), + pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$), + 'B creating in the workspace of A gets the error of an unknown workspace'); +select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$), + '42501|not_found||', 'that error is 42501 not_found, no detail, no hint'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, 'X', 'equine', 'male', null, null, null, null) $$), + pg_temp.err($$ select public.update_animal(gen_random_uuid(), 1, 'X', 'equine', 'male', null, null, null, null) $$), + 'B updating an animal of A gets the error of an unknown animal'); +select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, '', 'nope', 'robot', null, null, 'x', 'y') $$), + '42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)'); +select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('eclair'), true) $$), '42501|not_found||', + 'B archiving an animal of A gets not_found'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$), + pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), gen_random_uuid(), gen_random_uuid(), 'owner') $$), + 'B linking its animal to a client of A gets the error of an unknown client'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('b_client'), gen_random_uuid(), 'owner') $$), + '42501|not_found||', 'B linking an animal of A to its client gets not_found'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'X', 'equine', + 'male', client_id => pg_temp.id('marie'), relation_role => 'owner') $$), '42501|not_found||', + 'B creating an animal linked to a client of A gets not_found'); +select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$), + pg_temp.err($$ select public.end_animal_client_relation(gen_random_uuid(), 1) $$), + 'B ending a relation of A gets the error of an unknown relation'); +select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1, null, null) $$), + '42501|not_found||', 'B correcting a relation of A gets not_found'); +select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$), + '42501|not_found||', 'B voiding a relation of A gets not_found'); +select is(pg_temp.denial($$ insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) + values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), 'Direct', 'equine', 'male', gen_random_uuid(), '\x00') $$), + '42501|permission denied for table animals', 'a direct insert of an animal is refused by privilege'); +select is(pg_temp.denial($$ update public.animals set name = 'Direct' $$), + '42501|permission denied for table animals', 'a direct update of an animal is refused by privilege'); +select is(pg_temp.denial($$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') $$), + '42501|permission denied for table animals', 'moving an animal to another workspace is refused by privilege'); +select is(pg_temp.denial($$ delete from public.animals $$), + '42501|permission denied for table animals', 'a direct delete of an animal is refused by privilege'); +select is(pg_temp.denial($$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, + create_request_id, create_request_digest) values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('b_animal'), + pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$), + '42501|permission denied for table animal_client_relations', 'a direct insert of a relation is refused by privilege'); +select is(pg_temp.denial($$ update public.animal_client_relations set voided_at = null $$), + '42501|permission denied for table animal_client_relations', 'a direct update of a relation is refused by privilege'); +select is(pg_temp.denial($$ delete from public.animal_client_relations $$), + '42501|permission denied for table animal_client_relations', 'a direct delete of a relation is refused by privilege'); + +select pg_temp.act_as('70000000-0000-0000-0000-00000000000c'); +select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint, + 'C (unconfirmed) reads no animal and no relation'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'X', 'equine', 'male') $$), + '42501|not_found||', 'C cannot create, even in its own workspace'); + +select pg_temp.act_as('70000000-0000-0000-0000-00000000000d'); +select is((select count(*) from public.animals), 0::bigint, 'D (deactivated) no longer reads its own animal'); +select is((select count(*) from public.search_animals(pg_temp.ws('70000000-0000-0000-0000-00000000000d'))), 0::bigint, + 'D finds nothing through search'); +select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('dave'), true) $$), '42501|not_found||', + 'D cannot write its own animal'); + +select pg_temp.act_as('70000000-0000-0000-0000-000000000005'); +select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint, + 'S (platform owner) reads nothing: no platform-role branch'); +select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$), + '42501|not_found||', 'S cannot write a relation of A'); +reset role; + +set local role anon; +select is(pg_temp.denial($$ select id from public.animals $$), '42501|permission denied for table animals', 'anon cannot read animals'); +select is(pg_temp.denial($$ select id from public.animal_client_relations $$), '42501|permission denied for table animal_client_relations', + 'anon cannot read relations'); +select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$), + '42501|permission denied for function create_animal||', 'anon cannot execute create_animal'); +select is(pg_temp.err($$ select * from public.search_animals(gen_random_uuid()) $$), + '42501|permission denied for function search_animals||', 'anon cannot execute search_animals'); +reset role; +set local role service_role; +select is(pg_temp.denial($$ select id from public.animal_client_relations $$), + '42501|permission denied for table animal_client_relations', 'service_role cannot read relations despite BYPASSRLS'); +select is(pg_temp.err($$ select public.void_animal_client_relation(gen_random_uuid(), 1) $$), + '42501|permission denied for function void_animal_client_relation||', 'service_role cannot execute the relation RPCs'); +select is(pg_temp.err($$ select * from public.list_client_animals(gen_random_uuid()) $$), + '42501|permission denied for function list_client_animals||', 'service_role cannot execute the reads'); +reset role; +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000a'); +select is(pg_temp.err($$ select private.lock_relation_for_write(pg_temp.id('r_eclair_marie_owner'), 1) $$), + '42501|permission denied for function lock_relation_for_write||', 'A cannot call the relation lock directly'); +select is(pg_temp.err($$ select private.parse_record_date('2020-01-01') $$), + '42501|permission denied for function parse_record_date||', 'A cannot call the date parser directly'); +select is(pg_temp.err($$ select private.parse_birth_year('2020') $$), + '42501|permission denied for function parse_birth_year||', 'A cannot call the year parser directly'); +select is(pg_temp.err($$ select private.utc_tomorrow(now()) $$), + '42501|permission denied for function utc_tomorrow||', 'A cannot call the date bound directly'); +reset role; + +-- --------------------------------------------------------------------------- +-- 8. Write budget shared with the clients (one counter per workspace) +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000f'); +insert into pg_temp.ids values + ('f_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Client') ->> 'id')::uuid); +reset role; +update private.workspace_write_budgets set hour_count = 999, day_count = 999 +where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f'); +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000f'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'Two writes', + 'equine', 'male', client_id => pg_temp.id('f_client'), relation_role => 'owner') $$), + 'P0001|rate_limited||', 'an animal with its relation needs two writes: refused at 999 of 1 000'); +select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '999/999', 'the refused create consumed nothing'); +select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f')), 0::bigint, + 'and left no animal behind'); +insert into pg_temp.ids values ('f_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), + '72000000-0000-0000-0000-000000000001', 'Budget Animal', 'equine', 'male') ->> 'id')::uuid); +select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write (an animal) passes'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Late') $$), + 'P0001|rate_limited||', 'the next client write is refused: one budget for clients and animals'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('f_animal'), pg_temp.id('f_client'), gen_random_uuid(), 'owner') $$), + 'P0001|rate_limited||', 'so is a relation'); +select is((public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), '72000000-0000-0000-0000-000000000001', + 'Budget Animal', 'equine', 'male') ->> 'id')::uuid, pg_temp.id('f_animal'), 'a replay at the limit still answers'); +select is(public.update_animal(pg_temp.id('f_animal'), 1, 'Budget Animal', 'equine', 'male', null, null, null, null) ->> 'revision', + '1', 'a no-op at the limit still answers'); +select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'neither consumed anything'); +reset role; + +-- --------------------------------------------------------------------------- +-- 9. Caps: 20 current and 200 relations per animal, 20 000 animals and +-- 100 000 relations per workspace (rows inserted as postgres) +-- --------------------------------------------------------------------------- +insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'person', 'Cap client ' || g, gen_random_uuid(), '\x00' +from generate_series(1, 22) g; +insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Cap animal ' || g, 'equine', 'male', gen_random_uuid(), '\x00' +from generate_series(1, 2) g; +insert into pg_temp.ids select 'e_animal_' || substr(name, 12), id from public.animals +where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e'); +insert into pg_temp.ids select 'e_client_' || substr(display_name, 12), id from public.clients +where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e'); +-- Animal 1: 20 current relations with 20 clients. +insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_1'), pg_temp.id('e_client_' || g), 'contact', + gen_random_uuid(), '\x00' +from generate_series(1, 20) g; +-- Animal 2: 198 ended relations and one voided current one: 199 rows, none current. +insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, voided_at, + create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_2'), pg_temp.id('e_client_1'), 'contact', + case when g < 199 then now() end, case when g = 199 then now() end, gen_random_uuid(), '\x00' +from generate_series(1, 199) g; +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000e'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$), + 'P0001|limit_reached||', 'the 21st current relation of an animal is refused'); +reset role; +update public.animal_client_relations set voided_at = now() +where animal_id = pg_temp.id('e_animal_1') and client_id = pg_temp.id('e_client_20'); +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000e'); +select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$, + 'a voided relation frees a current slot'); +select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_2'), gen_random_uuid(), 'owner') $$, + 'the 200th relation of an animal is accepted (ended and voided rows count)'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_3'), gen_random_uuid(), 'owner') $$), + 'P0001|limit_reached||', 'the 201st is refused although only one is current'); +reset role; +insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\x00' +from generate_series(1, 19997) g; +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-00000000000e'); +select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001', + 'Cap last', 'equine', 'male') $$, 'the 20 000th animal is accepted'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'Cap over', + 'equine', 'male') $$), 'P0001|limit_reached||', 'the 20 001st animal is refused'); +select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001', + 'Cap last', 'equine', 'male') $$, 'a replay at the cap still answers'); +reset role; + +-- H: 99 999 relations (ended) in one workspace, then the 100 000th through the RPC. +insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) +values (pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'person', 'Bulk client', gen_random_uuid(), '\x00'); +insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'H ' || g, 'equine', 'male', gen_random_uuid(), '\x00' +from generate_series(1, 501) g; +-- Animals numbered 1 to 501 by name: 1 holds 199 rows, 2 to 500 hold 200, 501 none. +create table pg_temp.h_animals as + select id, substr(name, 3)::integer as n from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011'); +insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest) +select pg_temp.ws('70000000-0000-0000-0000-000000000011'), a.id, c.id, 'contact', now(), gen_random_uuid(), '\x00' +from pg_temp.h_animals a cross join generate_series(1, 200) g +cross join (select id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')) c +where a.n <= 500 and (a.n > 1 or g < 200); +select is((select count(*) from public.animal_client_relations where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')), + 99999::bigint, 'H holds 99 999 relations'); +insert into pg_temp.ids select 'h_client', id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011'); +insert into pg_temp.ids select 'h_1', id from pg_temp.h_animals where n = 1; +insert into pg_temp.ids select 'h_free', id from pg_temp.h_animals where n = 501; +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-000000000011'); +select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('h_1'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$, + 'the 100 000th relation of a workspace is accepted'); +select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('h_free'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$), + 'P0001|limit_reached||', 'the 100 001st is refused, on an animal without any relation'); +select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000011'), gen_random_uuid(), 'H new', + 'equine', 'male', client_id => pg_temp.id('h_client'), relation_role => 'owner') $$), + 'P0001|limit_reached||', 'an animal with an initial relation too'); +reset role; + +-- --------------------------------------------------------------------------- +-- 10. Audit: one row per write, ids only, hidden from platform staff (N9) +-- --------------------------------------------------------------------------- +select is( + (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_bijou_paul_1')), + 'animal_client_relation.created,animal_client_relation.ended,animal_client_relation.updated', + 'each write of a relation leaves one audit row' +); +select is( + (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs + where resource_id in (pg_temp.id('tonnerre'), pg_temp.id('r_tonnerre'))), + 'animal.created,animal_client_relation.created', 'create_animal with a relation leaves two rows' +); +select is( + (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_rex_marie_wrong')), + 'animal_client_relation.created,animal_client_relation.voided', 'voiding is audited as such' +); +select is( + (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('bijou')), + 'animal.archived,animal.created,animal.restored,animal.updated', 'archive and restore are audited' +); +select is( + (select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation') + and resource_id in (select id from pg_temp.ids) + and ((metadata - 'workspace_id') <> '{}'::jsonb + or (metadata ->> 'workspace_id')::uuid not in (select id from public.workspaces))), + 0::bigint, 'audit metadata is the workspace id only' +); +select is( + (select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation') + and (metadata::text ~* '(eclair|bijou|tonnerre|furet|selle|owner|keeper|contact|20[0-9]{2}-)' or correlation_id is not null)), + 0::bigint, 'no name, role, breed or date in the audit rows' +); +select is( + (select count(*) from audit.audit_logs where resource_id = pg_temp.id('eclair') + and actor_user_id is distinct from '70000000-0000-0000-0000-00000000000a'), + 0::bigint, 'the actor is the caller' +); +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-000000000005'); +select is((select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')), + 0::bigint, 'S reads no animal or relation audit row'); +reset role; + +-- --------------------------------------------------------------------------- +-- 11. Integrity without the RPCs: a privileged writer (postgres, past RLS) +-- still meets the constraints +-- --------------------------------------------------------------------------- +select throws_ok( + $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest) + values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$, + '23503', null, 'a relation to a client of another workspace is refused by the composite foreign key'); +select throws_ok( + $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest) + values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner', + gen_random_uuid(), '\x00') $$, + '23503', null, 'a relation claiming the other workspace is refused too (the animal is not there)'); +select throws_ok( + $$ update public.animal_client_relations set client_id = pg_temp.id('b_client') where id = pg_temp.id('r_eclair_marie_owner') $$, + '23503', null, 'repointing a relation to a client of another workspace is refused'); +select throws_ok( + $$ update public.animal_client_relations set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') + where id = pg_temp.id('r_eclair_marie_owner') $$, + '23503', null, 'moving a relation to another workspace is refused'); +select throws_ok( + $$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('eclair') $$, + '23503', null, 'moving an animal that has relations to another workspace is refused'); +select throws_ok( + $$ update public.clients set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('marie') $$, + '23503', null, 'moving a client that has relations to another workspace is refused'); +select throws_ok( + $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest) + values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('marie'), 'owner', gen_random_uuid(), '\x00') $$, + '23505', null, 'a second current identical relation is refused by the partial unique index'); +select throws_ok( + $$ update public.animal_client_relations set ended_on = '2020-01-01' where id = pg_temp.id('r_eclair_marie_owner') $$, + '23514', null, 'an end date without an end is refused'); +select throws_ok( + $$ update public.animal_client_relations set ended_at = now(), started_on = '2021-01-01', ended_on = '2020-01-01' + where id = pg_temp.id('r_eclair_marie_owner') $$, + '23514', null, 'an end before the start is refused'); +select throws_ok( + $$ update public.animal_client_relations set started_on = '1899-12-31' where id = pg_temp.id('r_eclair_marie_owner') $$, + '23514', null, 'a start before 1900 is refused'); +select throws_ok( + $$ update public.animals set birth_date = '2014-01-01' where id = pg_temp.id('eclair') $$, + '23514', null, 'a birth date out of its year is refused'); +select throws_ok( + $$ update public.animals set birth_year = null where id = pg_temp.id('eclair') $$, + '23514', null, 'a birth date without its year is refused'); +select throws_ok( + $$ update public.animals set species_detail = null where id = pg_temp.id('furet') $$, + '23514', null, 'other without detail is refused'); +select throws_ok( + $$ update public.animals set species_id = 'unicorn' where id = pg_temp.id('rex') $$, + '23503', null, 'an unknown species is refused by the foreign key'); +select throws_ok( + $$ delete from public.animals where id = pg_temp.id('eclair') $$, + '23503', null, 'an animal with relations cannot be deleted'); +select throws_ok( + $$ delete from public.clients where id = pg_temp.id('lac') $$, + '23503', null, 'a client with relations cannot be deleted'); + +-- --------------------------------------------------------------------------- +-- 12. Account deletion (D9a) +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('70000000-0000-0000-0000-000000000012'); +select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000012'), gen_random_uuid(), 'Seul', 'equine', 'male') $$, + 'G creates one animal and no client'); +reset role; +select throws_ok( + $$ delete from auth.users where id = '70000000-0000-0000-0000-000000000012' $$, + '23503', null, 'an account whose workspace holds an animal cannot be deleted (D9a)' +); +select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000012')), 1::bigint, + 'its animal is intact'); + +select * from finish(); +rollback;