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