diff --git a/.changeset/33213-duplicate-refusal-locale.md b/.changeset/33213-duplicate-refusal-locale.md new file mode 100644 index 00000000000..ab1d04b7687 --- /dev/null +++ b/.changeset/33213-duplicate-refusal-locale.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': patch +'@objectstack/types': patch +'@objectstack/objectql': patch +--- + +fix(objectql): the duplicate refusal (`409 UNIQUE_VIOLATION`) now reads in the writer's language and names the fields of a composite unique index + +Clause-②: yes (widening) +Metadata-protocol: none + +A write refused by a unique constraint used to answer the fixed English sentence "A record with this value already exists" as the 409 body's `error`, whatever the request's `Accept-Language`, and never named the fields of a unique index over several columns, so the user could not tell which combination collided. The engine now composes that sentence in the writer's locale from the platform's operation message catalog, the catalog the `DELETE_RESTRICTED` refusal already uses, so a `zh-CN` request reads `已存在「工厂」、「牌号」、「成本周次」均相同的记录` where it read English. A composite key is named only when the columns the database reported match, as a set, a unique index the object declares, and only when every one of those fields has a label; otherwise the sentence names nothing, because a wrong field name is worse than none. The wire shape does not change: `code` stays `UNIQUE_VIOLATION`, the status stays 409, and `field` still names one column only when the database named exactly one. An English deployment reads the same sentences as before for a single field or none. + +Three additions ride along. `BUILTIN_OPERATION_MESSAGES` (`@objectstack/spec/system`) gains `duplicate_record`, `duplicate_record_field` and `duplicate_record_fields` in every platform locale, so a deployment can override them with an `errors.duplicate_record*` translation. `@objectstack/types` exports `uniqueViolationColumns(error)`, the columns of a composite unique key the driver named, with the organization part set aside. `DuplicateRecordError` carries the composed sentence as `endUserMessage`. A MySQL refusal names an index and not its columns, so it still names no field. diff --git a/packages/objectql/src/duplicate-record-error.ts b/packages/objectql/src/duplicate-record-error.ts index 3fc2f8f0005..55cc4074390 100644 --- a/packages/objectql/src/duplicate-record-error.ts +++ b/packages/objectql/src/duplicate-record-error.ts @@ -1,6 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { isUniqueViolationError, uniqueViolationField } from '@objectstack/types'; +import { renderOperationMessage } from '@objectstack/spec/system'; +import { isUniqueViolationError, uniqueViolationColumns, uniqueViolationField } from '@objectstack/types'; import { objectDisplayLabel } from './engine-validation-messages.js'; import { resolveFieldLabel, type ValidationMessageContext } from './validation/record-validator.js'; @@ -97,6 +98,32 @@ import { resolveFieldLabel, type ValidationMessageContext } from './validation/r * a write made in `zh-CN` against a translated object reads its labels in * `zh-CN`. With no message context (a bare-kernel caller) they are the * declared labels, exactly as before. + * - **`endUserMessage`** — the end user's sentence, composed in the writer's + * locale from the platform's operation catalog (`duplicate_record*`, + * `renderOperationMessage` in `@objectstack/spec/system`, the catalog the + * `DELETE_RESTRICTED` refusal renders from), so a deployment's + * `errors.duplicate_record*` translation overrides it. The HTTP doors ship + * it as the 409 body's `error`; before, they composed a fixed English + * sentence there, so a `zh-CN` writer read English beside a Chinese + * object label. It names the conflicting field by label (one field), the + * fields of a composite unique index by their labels (see `uniqueFields` + * below), or nothing. ⛔ It is deliberately NOT spelled `userMessage`: + * that name is the ApiError contract's producer-marked channel, which every + * boundary promotes to a wire key of its own (`withDeclaredUserMessage`), + * and whether this refusal joins that channel is a contract decision this + * sentence does not make. The wire shape is unchanged: only the text of + * `error` moves. + * - **The fields of a composite unique index** — named in `endUserMessage` + * and in `message` ONLY when the columns the store named + * (`uniqueViolationColumns`, organization part set aside) match, as a set, + * the `fields` of a unique index the object DECLARES. Driver text alone is evidence, not a verdict: a + * `tenancy.tenantField` column prints beside the authored ones and cannot + * be told from them, so anything short of a declared match names nothing — + * the rule `field` follows, for the reason it does. `field` itself keeps + * its single-column contract and stays absent for a composite; the + * composite's API names open `developerMessage`. And the user's sentence + * names them only when every one has a label — never an API name, the + * rule `field_edit_denied` set for its list of fields. * * ## ⛔ What this deliberately does NOT do * @@ -111,8 +138,24 @@ export const DUPLICATE_RECORD_CODE = 'DUPLICATE_RECORD' as const; /** The conflict status the engine's sibling 409 refusals declare. */ const DUPLICATE_RECORD_STATUS = 409 as const; -/** The declared labels of the refused write's object and conflicting field. */ -type DuplicateRecordLabels = { readonly object?: string; readonly field?: string }; +/** + * What the user-facing sentences name: the display labels of the refused + * write's object and conflicting field, the composite unique index's fields + * when one was matched, and the writer's locale to render the end user's + * sentence in. + */ +type DuplicateRecordLabels = { + readonly object?: string; + readonly field?: string; + /** + * The fields of the declared unique index the store's composite key matched, + * in the index's declared order, each with its display label (absent where + * the field has none). Absent when no declared index matched. + */ + readonly uniqueFields?: ReadonlyArray<{ readonly name: string; readonly label?: string }>; + /** The writer's locale and the deployment's translation hook; absent ⇒ `en`. */ + readonly messages?: Pick; +}; export class DuplicateRecordError extends Error { readonly code = DUPLICATE_RECORD_CODE; @@ -137,6 +180,12 @@ export class DuplicateRecordError extends Error { * See the module header. */ readonly fieldLabel?: string; + /** + * The end user's sentence, in the writer's locale, from the platform's + * operation catalog — what the HTTP doors ship as the 409 body's `error`. + * See the module header, and on why it is not `userMessage`. + */ + readonly endUserMessage: string; constructor( /** The object the refused write targeted. */ @@ -147,13 +196,21 @@ export class DuplicateRecordError extends Error { /** The display labels the user-facing `message` names them by; absent ⇒ the API name. */ labels?: DuplicateRecordLabels, ) { - super(buildDuplicateMessage(labels?.object || object, field && (labels?.field || field))); + const uniqueFields = field ? undefined : labels?.uniqueFields; + super( + buildDuplicateMessage( + labels?.object || object, + field ? [labels?.field || field] : uniqueFields?.map((f) => f.label || f.name), + ), + ); this.name = 'DuplicateRecordError'; this.cause = cause; if (field && labels?.field) this.fieldLabel = labels.field; + this.endUserMessage = buildEndUserMessage(field ? labels?.field : undefined, uniqueFields, labels?.messages); this.developerMessage = `Duplicate record refused on object '${object}'` + (field ? `, field '${field}'` : '') + + (uniqueFields ? `, unique index fields ${uniqueFields.map((f) => `'${f.name}'`).join(', ')}` : '') + `. The driver refused this write as a unique-constraint violation. Its own error is attached ` + `as \`cause\`. Branch on the platform code (ADR-0112), never on a dialect's code or message, ` + `so the handling survives a change of store: over the HTTP API this refusal is reported as ` + @@ -173,16 +230,45 @@ export class DuplicateRecordError extends Error { * message opening "Insert on 'x' …" would be thrown away by a guard written * against leaked driver statements. Measured, not guessed. */ -function buildDuplicateMessage(object: string, field?: string): string { +function buildDuplicateMessage(object: string, fields?: readonly string[]): string { return ( `Duplicate record refused on '${object}': ` + - (field - ? `a unique constraint on '${field}' already holds this value. ` - : 'a unique constraint already holds these values. ') + + (fields?.length === 1 + ? `a unique constraint on '${fields[0]}' already holds this value. ` + : fields && fields.length > 1 + ? `a unique constraint on ${fields.map((f) => `'${f}'`).join(', ')} already holds these values. ` + : 'a unique constraint already holds these values. ') + 'No record was written.' ); } +/** + * The end user's sentence, rendered from the operation catalog in the writer's + * locale: the one field's label, the composite index's labels as a list + * spelled by the locale's `field_label_quoted` / `field_label_list_separator` + * rules, or nothing named. A composite is named only when EVERY field has a + * label — never an API name in this sentence. + */ +function buildEndUserMessage( + fieldLabel: string | undefined, + uniqueFields: DuplicateRecordLabels['uniqueFields'], + messages: DuplicateRecordLabels['messages'], +): string { + const opts = { locale: messages?.locale, translate: messages?.translate }; + if (fieldLabel) { + return renderOperationMessage({ messageKey: 'duplicate_record_field', params: { field: fieldLabel } }, opts); + } + const labels = uniqueFields?.map((f) => f.label); + if (labels && labels.length > 1 && labels.every((l): l is string => typeof l === 'string' && l.length > 0)) { + const separator = renderOperationMessage({ messageKey: 'field_label_list_separator' }, opts); + const list = labels + .map((label) => renderOperationMessage({ messageKey: 'field_label_quoted', params: { label } }, opts)) + .join(separator); + return renderOperationMessage({ messageKey: 'duplicate_record_fields', params: { fields: list } }, opts); + } + return renderOperationMessage({ messageKey: 'duplicate_record' }, opts); +} + /** * A write door's driver-error exit — `insert` (#14095) and `update` (commit 9d7f7259f), * by-id and predicate alike: the platform envelope for a unique violation, or @@ -210,7 +296,61 @@ export function envelopeUniqueViolation( if (error instanceof DuplicateRecordError) return error; if (!isUniqueViolationError(error)) return error; const field = uniqueViolationField(error); - return new DuplicateRecordError(object, error, field, displayLabels(schema, object, field, messages)); + const uniqueFields = field ? undefined : declaredCompositeIndex(schema, uniqueViolationColumns(error)); + return new DuplicateRecordError(object, error, field, { + ...displayLabels(schema, object, field, messages), + ...(uniqueFields ? { uniqueFields: uniqueFields.map((name) => ({ name, label: fieldDisplayLabel(schema, object, name, messages) })) } : {}), + ...(messages ? { messages: { locale: messages.locale, translate: messages.translate } } : {}), + }); +} + +/** + * The `fields` of the unique index the object DECLARES whose field set equals + * the composite key the store named — in the index's declared order — or + * `undefined` when none matches exactly. The store's side arrives with the + * organization key part already set aside (`uniqueViolationColumns`), which + * is what a `unique: 'organization'` index lists: only its authored fields. + * The declared side is compared as written, so a legacy hand-written global + * index that lists the organization column itself matches nothing and names + * nothing — the conservative answer. A non-unique index never matches: it + * refuses nothing. + */ +function declaredCompositeIndex(schema: unknown, columns: readonly string[] | undefined): readonly string[] | undefined { + if (!columns || columns.length < 2) return undefined; + const indexes = (schema as { indexes?: unknown } | undefined)?.indexes; + if (!Array.isArray(indexes)) return undefined; + const wanted = new Set(columns); + if (wanted.size !== columns.length) return undefined; + for (const raw of indexes) { + const index = raw as { fields?: unknown; unique?: unknown } | null; + if (!index || typeof index !== 'object') continue; + if (index.unique !== 'global' && index.unique !== 'organization') continue; + if (!Array.isArray(index.fields) || !index.fields.every((f): f is string => typeof f === 'string')) continue; + const declared = index.fields; + if (declared.length === wanted.size && new Set(declared).size === declared.length && declared.every((f) => wanted.has(f))) { + return declared; + } + } + return undefined; +} + +/** + * One field's display label in the writer's locale — a translation, else its + * declared `label` — or `undefined` when it has neither (the API name is never + * returned as a label). The ladder {@link displayLabels} climbs for `field`. + */ +function fieldDisplayLabel( + schema: unknown, + object: string, + field: string, + messages: ValidationMessageContext | undefined, +): string | undefined { + const s = schema as { fields?: Record } | undefined; + const declared = typeof s?.fields?.[field]?.label === 'string' && (s.fields[field]!.label as string).trim() !== '' + ? (s.fields[field]!.label as string).trim() + : undefined; + const label = resolveFieldLabel(field, { label: declared }, messages && { ...messages, objectName: object }); + return label === field && declared === undefined ? undefined : label; } /** diff --git a/packages/objectql/src/engine-duplicate-record-label-sentence.test.ts b/packages/objectql/src/engine-duplicate-record-label-sentence.test.ts index 67dfcdcbfbe..b5fac64813a 100644 --- a/packages/objectql/src/engine-duplicate-record-label-sentence.test.ts +++ b/packages/objectql/src/engine-duplicate-record-label-sentence.test.ts @@ -239,7 +239,8 @@ describe('a unique refusal names the object and field by label (#24951)', () => 'No record was written.', ); const answer = mapDataError(failure, 'crm_account'); - expect(answer.body.error).toBe('A record with this 客户名称 already exists'); + // The sentence itself is in the writer's locale too, not only the label in it. + expect(answer.body.error).toBe('已存在相同客户名称的记录'); expect(answer.body.field).toBe('name'); }); @@ -307,7 +308,7 @@ describe('an organization-scoped unique field names the field, by label', () => const failure = await refusalOf(() => write(engine, { context: { locale: 'zh-CN' } })); expect(failure.fieldLabel).toBe('客户名称'); - expect(mapDataError(failure, 'crm_account').body.error).toBe('A record with this 客户名称 already exists'); + expect(mapDataError(failure, 'crm_account').body.error).toBe('已存在相同客户名称的记录'); }); it('two authored columns beside the organization part: no field, the unnamed sentence', async () => { @@ -326,3 +327,176 @@ describe('an organization-scoped unique field names the field, by label', () => }); }); }); + +/** + * The duplicate refusal's end-user sentence is composed in the writer's + * locale from the platform operation catalog (`duplicate_record*`), and a + * composite unique index the object DECLARES is named by its fields' labels. + * The wire shape does not move: `code` stays `UNIQUE_VIOLATION`, the status + * 409, and `field` keeps its single-column contract (absent for a composite). + */ +describe('the duplicate refusal speaks the writer\'s locale, and names a declared composite unique index', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + const WEEKLY = { + name: 'crm_weekly_cost', + label: 'Weekly Cost', + fields: { + plant: { type: 'text', label: 'Plant' }, + carbon_grade: { type: 'text', label: 'Carbon Grade' }, + cost_week: { type: 'text', label: 'Cost Week' }, + }, + indexes: [{ fields: ['plant', 'carbon_grade', 'cost_week'], unique: 'organization' }], + }; + const WEEKLY_ZH: Record = { + 'objects.crm_weekly_cost.label': '周成本', + 'objects.crm_weekly_cost.fields.plant.label': '工厂', + 'objects.crm_weekly_cost.fields.carbon_grade.label': '牌号', + 'objects.crm_weekly_cost.fields.cost_week.label': '成本周次', + }; + const weeklyI18n = (overrides: Record = {}) => ({ + t: (key: string, locale: string) => overrides[key] ?? ((locale === 'zh-CN' && WEEKLY_ZH[key]) || key), + getLocales: () => ['en', 'zh-CN'], + }); + + /** better-sqlite3 on the `unique: 'organization'` index: the organization part, then the three authored columns. */ + const sqliteComposite = () => + Object.assign( + new Error( + 'UNIQUE constraint failed: crm_weekly_cost.organization_id, crm_weekly_cost.plant, ' + + 'crm_weekly_cost.carbon_grade, crm_weekly_cost.cost_week', + ), + { code: 'SQLITE_CONSTRAINT_UNIQUE' }, + ); + /** node-postgres: the columns ride `error.detail`, the message names the constraint. */ + const postgresComposite = () => + Object.assign(new Error('duplicate key value violates unique constraint "uniq_crm_weekly_cost_plant"'), { + code: '23505', + detail: 'Key (organization_id, plant, carbon_grade, cost_week)=(org_a, p1, g1, 2026-W45) already exists.', + }); + const mysqlIndexOnly = () => + Object.assign(new Error("Duplicate entry 'p1-g1-2026-W45' for key 'idx_weekly'"), { code: 'ER_DUP_ENTRY', errno: 1062 }); + + const WEEKLY_DOORS: Array<[string, (engine: ObjectQL, ctx?: Ctx) => Promise]> = [ + ['insert', (engine, ctx = {}) => engine.insert('crm_weekly_cost', { plant: 'p1' }, ctx as any)], + ['update by id', (engine, ctx = {}) => engine.update('crm_weekly_cost', { id: 'r1', plant: 'p1' }, ctx as any)], + ]; + + const EN_NAMED = 'A record with the same “Plant”, “Carbon Grade”, “Cost Week” already exists'; + const ZH_NAMED = '已存在「工厂」、「牌号」、「成本周次」均相同的记录'; + + describe.each(WEEKLY_DOORS)('on %s', (_door, write) => { + it('en: the declared index\'s fields by label; no `field`, the wire code and status unchanged', async () => { + const engine = makeRig(WEEKLY, sqliteComposite); + await engine.init(); + + const failure = await refusalOf(() => write(engine)); + + expect(failure).toBeInstanceOf(DuplicateRecordError); + expect(failure.field).toBeUndefined(); + expect(failure).not.toHaveProperty('fieldLabel'); + expect(failure.endUserMessage).toBe(EN_NAMED); + expect(failure.message).toBe( + "Duplicate record refused on 'Weekly Cost': a unique constraint on 'Plant', 'Carbon Grade', 'Cost Week' " + + 'already holds these values. No record was written.', + ); + expect(failure.developerMessage).toMatch( + /^Duplicate record refused on object 'crm_weekly_cost', unique index fields 'plant', 'carbon_grade', 'cost_week'\. /, + ); + const answer = mapDataError(failure, 'crm_weekly_cost'); + expect(answer.status).toBe(409); + expect(answer.body.code).toBe('UNIQUE_VIOLATION'); + expect(answer.body).not.toHaveProperty('field'); + expect(answer.body).not.toHaveProperty('userMessage'); + expect(answer.body.error).toBe(EN_NAMED); + }); + + it('zh-CN: the sentence and the labels both in the writer\'s locale', async () => { + const engine = makeRig(WEEKLY, sqliteComposite); + engine.setI18nService(weeklyI18n() as any); + await engine.init(); + + const failure = await refusalOf(() => write(engine, { context: { locale: 'zh-CN' } })); + + const answer = mapDataError(failure, 'crm_weekly_cost'); + expect(answer.status).toBe(409); + expect(answer.body.code).toBe('UNIQUE_VIOLATION'); + expect(answer.body).not.toHaveProperty('field'); + expect(answer.body.error).toBe(ZH_NAMED); + }); + + it('the Postgres DETAIL shape matches the same declared index', async () => { + const engine = makeRig(WEEKLY, postgresComposite); + engine.setI18nService(weeklyI18n() as any); + await engine.init(); + + const failure = await refusalOf(() => write(engine, { context: { locale: 'zh-CN' } })); + + expect(mapDataError(failure, 'crm_weekly_cost').body.error).toBe(ZH_NAMED); + }); + + it('fallback: a locale the catalog does not carry reads the en sentence, with the declared labels', async () => { + const engine = makeRig(WEEKLY, sqliteComposite); + engine.setI18nService(weeklyI18n() as any); + await engine.init(); + + const failure = await refusalOf(() => write(engine, { context: { locale: 'de-DE' } })); + + expect(mapDataError(failure, 'crm_weekly_cost').body.error).toBe(EN_NAMED); + }); + + it('a deployment\'s `errors.duplicate_record_fields` translation overrides the built-in sentence', async () => { + const engine = makeRig(WEEKLY, sqliteComposite); + engine.setI18nService(weeklyI18n({ 'errors.duplicate_record_fields': '{{fields}}组合重复。' }) as any); + await engine.init(); + + const failure = await refusalOf(() => write(engine, { context: { locale: 'zh-CN' } })); + + expect(mapDataError(failure, 'crm_weekly_cost').body.error).toBe('「工厂」、「牌号」、「成本周次」组合重复。'); + }); + }); + + // Controls: nothing short of a declared unique index with exactly the named + // columns, every one of them labelled, names a field — a wrong field name is + // worse than none. Each still answers in the writer's locale. + const UNTRANSLATED_COST_WEEK = { 'objects.crm_weekly_cost.fields.cost_week.label': 'objects.crm_weekly_cost.fields.cost_week.label' }; + const CONTROLS: Array<[string, unknown, () => unknown, Record]> = [ + ['no declared index matches the columns', { ...WEEKLY, indexes: [{ fields: ['plant', 'cost_week'], unique: 'organization' }] }, sqliteComposite, {}], + ['the matching declared index is not unique', { ...WEEKLY, indexes: [{ fields: ['plant', 'carbon_grade', 'cost_week'], unique: false }] }, sqliteComposite, {}], + ['the object declares no index', { ...WEEKLY, indexes: undefined }, sqliteComposite, {}], + // The bundle echoes the key for `cost_week`, so no translation rescues the missing label. + ['one field of the index has no label', { ...WEEKLY, fields: { ...WEEKLY.fields, cost_week: { type: 'text' } } }, sqliteComposite, UNTRANSLATED_COST_WEEK], + ['the store named an index, not columns (MySQL)', WEEKLY, mysqlIndexOnly, {}], + ]; + + it.each(CONTROLS)('%s: the unnamed sentence, in zh-CN and en', async (_label, schema, refuse, overrides) => { + const engine = makeRig(schema, refuse); + engine.setI18nService(weeklyI18n(overrides) as any); + await engine.init(); + + const zh = await refusalOf(() => engine.insert('crm_weekly_cost', { plant: 'p1' }, { context: { locale: 'zh-CN' } } as any)); + const zhAnswer = mapDataError(zh, 'crm_weekly_cost'); + expect(zhAnswer.status).toBe(409); + expect(zhAnswer.body.code).toBe('UNIQUE_VIOLATION'); + expect(zhAnswer.body).not.toHaveProperty('field'); + expect(zhAnswer.body.error).toBe('已存在相同值的记录'); + + const en = await refusalOf(() => engine.insert('crm_weekly_cost', { plant: 'p1' })); + expect(mapDataError(en, 'crm_weekly_cost').body.error).toBe('A record with this value already exists'); + }); + + it('a single field with no label in zh-CN: the unnamed sentence in Chinese, `field` still the API key', async () => { + const engine = makeRig(UNLABELLED, namedColumn); + // A bundle that translates nothing: the field has no label in any locale. + engine.setI18nService({ t: (key: string) => key, getLocales: () => ['en', 'zh-CN'] } as any); + await engine.init(); + + const failure = await refusalOf(() => engine.insert('crm_account', { name: 'Acme' }, { context: { locale: 'zh-CN' } } as any)); + + const answer = mapDataError(failure, 'crm_account'); + expect(answer.body.field).toBe('name'); + expect(answer.body.error).toBe('已存在相同值的记录'); + }); +}); diff --git a/packages/rest/src/rest-duplicate-record-arm.test.ts b/packages/rest/src/rest-duplicate-record-arm.test.ts index 37d2b9b5d59..87643b8a364 100644 --- a/packages/rest/src/rest-duplicate-record-arm.test.ts +++ b/packages/rest/src/rest-duplicate-record-arm.test.ts @@ -527,3 +527,54 @@ describe('#14389 §5 — a producer that merely SPEAKS `DUPLICATE_RECORD` is not expect(r.body).not.toHaveProperty('field'); }); }); + +/* -------------------------------------------------------------------------- + * A declared composite unique index, named by its fields' labels in the + * writer's locale — the same real engine on real better-sqlite3 as §2, so the + * driver's composite text is the one SQLite actually prints, not a fixture. + * ----------------------------------------------------------------------- */ + +describe('a declared composite unique index: its fields named by label, in the writer\'s locale (real driver)', () => { + const DECLARED = { + ...COMPOSITE, + name: 'duly_pair_declared', + indexes: [{ name: 'idx_duly_pair_declared', fields: ['tenant', 'email'], unique: 'global' }], + }; + + async function conflictIn(locale?: string) { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + engine.registry.registerObject(DECLARED as any); + await engine.syncSchemas(); + const row = { tenant: 'acme', email: VALUE }; + await engine.insert(DECLARED.name, { id: 'r1', ...row }); + return refusalOf(() => + engine.insert(DECLARED.name, { id: 'r2', ...row }, (locale ? { context: { locale } } : {}) as any), + ); + } + + it.each([ + ['en (no locale named)', undefined, 'A record with the same “Tenant”, “Email” already exists'], + ['zh-CN', 'zh-CN', '已存在「Tenant」、「Email」均相同的记录'], + ])('%s: 409 UNIQUE_VIOLATION, the fields named, still NO `field` key and no value', async (_label, locale, sentence) => { + const env = await conflictIn(locale); + + expect(env).toBeInstanceOf(DuplicateRecordError); + expect(env.field).toBeUndefined(); + const r = mapDataError(env, 'duly_pair_declared'); + expect(r.status).toBe(409); + expect(r.body).toEqual({ + error: sentence, + code: 'UNIQUE_VIOLATION', + developerMessage: env.message, + object: 'duly_pair_declared', + }); + expect(JSON.stringify(r.body)).not.toContain(VALUE); + expect(JSON.stringify(r.body)).not.toContain('acme'); + }, 60_000); +}); diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index ca90b388978..10126e95fad 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -500,3 +500,52 @@ describe('operation message catalog — the field-label list rules', () => { .toBe(' / '); }); }); + +/** + * The unique-constraint refusal's three sentences — one wire code + * (`UNIQUE_VIOLATION`), named as far as the engine can name honestly. The call + * site is pinned in `packages/objectql/src/engine-duplicate-record-label-sentence.test.ts`, + * through the real write doors and `mapDataError`. + */ +describe('operation message catalog — the duplicate refusal', () => { + const KEYS = { + duplicate_record: [], + duplicate_record_field: ['{{field}}'], + duplicate_record_fields: ['{{fields}}'], + } as const; + + it('every locale defines all three, each with exactly its own placeholder', () => { + const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); + // Guard the guard: a catalog that lost its locales would make the loop vacuous. + expect(locales.length).toBeGreaterThanOrEqual(4); + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const [key, placeholders] of Object.entries(KEYS)) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([...placeholders]); + } + } + }); + + it('the English sentences keep the wording the HTTP doors answered before they were localized', () => { + expect(renderOperationMessage({ messageKey: 'duplicate_record' }, { locale: 'en' })) + .toBe('A record with this value already exists'); + expect(renderOperationMessage({ messageKey: 'duplicate_record_field', params: { field: 'Global SKU' } }, { locale: 'en' })) + .toBe('A record with this Global SKU already exists'); + }); + + it('renders the caller locale, and falls back to en for a locale the catalog does not carry', () => { + expect(renderOperationMessage({ messageKey: 'duplicate_record' }, { locale: 'zh-CN' })).toBe('已存在相同值的记录'); + expect(renderOperationMessage({ messageKey: 'duplicate_record_field', params: { field: '客户名称' } }, { locale: 'zh' })) + .toBe('已存在相同客户名称的记录'); + expect(renderOperationMessage({ messageKey: 'duplicate_record' }, { locale: 'de-DE' })) + .toBe('A record with this value already exists'); + }); + + it('a deployment translation override wins, under the shared `errors.` address', () => { + for (const key of Object.keys(KEYS)) { + expect(operationMessageTranslationKey(key)).toBe(`errors.${key}`); + const translate = (k: string) => (k === `errors.${key}` ? '部署自定义文案。' : k); + expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN', translate })).toBe('部署自定义文案。'); + } + }); +}); diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index f00823948ca..ee68ac270dc 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -14,7 +14,8 @@ * the sharing middleware's by-id write denial (`record_write_denied`; emitter * conversion is #12260's half) and plugin-approvals' non-submitter recall * refusal (`approval_recall_not_submitter`; emitter conversion is #11993's - * half). The catalog is the seat for the rest of the family as they are + * half) — and the unique-constraint refusal (`409 UNIQUE_VIOLATION` on the + * wire, the engine's `DuplicateRecordError`). The catalog is the seat for the rest of the family as they are * localized — a second mechanism for the second producer is exactly what this * module exists to prevent. * @@ -238,6 +239,26 @@ export function operationMessageTranslationKey(messageKey: string): string { * carries its list rules in the same edit — the every-locale-defines-every-key * test refuses a locale that omits them — and so they resolve by the same * ladder as the sentence, a deployment's `errors.` override included. + * + * The three `duplicate_record*` keys are the end user's sentence of a + * unique-constraint refusal — one wire code (`UNIQUE_VIOLATION`), three + * sentences, chosen by how much of the key the engine can name honestly: + * + * - `duplicate_record_field` takes `{{field}}`, the one conflicting field's + * LABEL in the caller's locale, named only when the store determinably + * named that column and the field has a label (a translation, else its + * declared `label`; never the API name); + * - `duplicate_record_fields` takes `{{fields}}`, the labels of a composite + * unique index's fields spelled by `field_label_quoted` and + * `field_label_list_separator`, named only when the columns the store + * named match a unique index the object declares and every one of those + * fields has a label; + * - `duplicate_record` names nothing — every other case, because a wrong + * field name is worse than none. + * + * The English sentences are byte-identical to the fixed text the HTTP doors + * answered before they were localized, so an English deployment reads no + * change for a single field or none. */ export const BUILTIN_OPERATION_MESSAGES: Record> = { en: { @@ -275,6 +296,9 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This {{object}} is still referenced by {{dependentObject}} record(s) through “{{field}}”. Delete or reassign them first.', delete_restricted_required_opaque: 'This {{object}} is still referenced by {{dependentObject}} record(s) through “{{field}}”, which is required and cannot be cleared. Delete or reassign them first.', + duplicate_record: 'A record with this value already exists', + duplicate_record_field: 'A record with this {{field}} already exists', + duplicate_record_fields: 'A record with the same {{fields}} already exists', }, 'zh-CN': { permission_denied: '您没有执行此操作的权限,如需访问请联系管理员。', @@ -299,6 +323,9 @@ export const BUILTIN_OPERATION_MESSAGES: Record> '该{{object}}正被{{dependentObject}}记录通过「{{field}}」引用,请先删除或改派这些记录。', delete_restricted_required_opaque: '该{{object}}正被{{dependentObject}}记录通过「{{field}}」引用,且该字段为必填、无法清空,请先删除或改派这些记录。', + duplicate_record: '已存在相同值的记录', + duplicate_record_field: '已存在相同{{field}}的记录', + duplicate_record_fields: '已存在{{fields}}均相同的记录', }, 'ja-JP': { permission_denied: 'この操作を実行する権限がありません。アクセスが必要な場合は管理者にお問い合わせください。', @@ -334,6 +361,9 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'この{{object}}は{{dependentObject}}レコードから「{{field}}」で参照されています。先にそれらを削除するか、参照先を変更してください。', delete_restricted_required_opaque: 'この{{object}}は{{dependentObject}}レコードから「{{field}}」で参照されています。この項目は必須のため空にできません。先にそれらを削除するか、参照先を変更してください。', + duplicate_record: '同じ値のレコードがすでに存在します', + duplicate_record_field: '同じ{{field}}のレコードがすでに存在します', + duplicate_record_fields: '{{fields}}がすべて同じレコードがすでに存在します', }, 'es-ES': { permission_denied: @@ -370,6 +400,9 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Todavía hay registros de {{dependentObject}} que hacen referencia a este {{object}} mediante «{{field}}». Elimínelos o reasígnelos primero.', delete_restricted_required_opaque: 'Todavía hay registros de {{dependentObject}} que hacen referencia a este {{object}} mediante «{{field}}», un campo obligatorio que no puede vaciarse. Elimínelos o reasígnelos primero.', + duplicate_record: 'Ya existe un registro con este valor', + duplicate_record_field: 'Ya existe un registro con el mismo valor de {{field}}', + duplicate_record_fields: 'Ya existe un registro con los mismos valores de {{fields}}', }, }; diff --git a/packages/types/src/data-error-classification.ts b/packages/types/src/data-error-classification.ts index a74ea41a804..7b7c8d7799f 100644 --- a/packages/types/src/data-error-classification.ts +++ b/packages/types/src/data-error-classification.ts @@ -1065,8 +1065,12 @@ function structuredCodeAnswer( // codes parse as `ErrorCode` — the reason) and §1 (`not.toHaveProperty`). // // **Two sentences — the `DELETE_RESTRICTED` split above.** `error` is the - // curated end-user sentence: fixed text plus, at most, the field's display - // name the ENGINE resolved — [#26867] its `fieldLabel`, the translation in + // curated end-user sentence. The engine composes it (`endUserMessage`) in + // the writer's locale from the platform operation catalog, so a `zh-CN` + // writer reads Chinese and a composite unique index the object declares + // is named by its fields' labels; what follows describes the field naming + // that sentence carries. Before that it was fixed English plus, at most, + // the field's display name the ENGINE resolved — [#26867] its `fieldLabel`, the translation in // the writer's locale or the declared `label`, the same one `message` names // it by. It used to interpolate the API key (`field`), so the end user read // `gsku` while `developerMessage` read `Global SKU`. A field with no label @@ -1106,12 +1110,21 @@ function structuredCodeAnswer( const label = field && typeof error?.fieldLabel === 'string' && error.fieldLabel.trim().length > 0 ? error.fieldLabel : undefined; + // The engine's end-user sentence, composed in the WRITER's locale from + // the platform operation catalog (`duplicate_record*`), naming the one + // field or a declared composite index's fields by label. This module + // holds neither a locale nor a schema, so it relays the producer's + // sentence; the fixed English below is only for an envelope that + // carries none (one built before the engine composed it). + const sentence = typeof error?.endUserMessage === 'string' && error.endUserMessage.trim().length > 0 + ? error.endUserMessage + : undefined; return { status: 409, body: { - error: label + error: sentence ?? (label ? `A record with this ${label} already exists` - : 'A record with this value already exists', + : 'A record with this value already exists'), code: 'UNIQUE_VIOLATION', ...(typeof error?.message === 'string' && error.message.length > 0 ? { developerMessage: error.message } diff --git a/packages/types/src/unique-violation.test.ts b/packages/types/src/unique-violation.test.ts index 962ed88b754..010f6596d5a 100644 --- a/packages/types/src/unique-violation.test.ts +++ b/packages/types/src/unique-violation.test.ts @@ -20,7 +20,7 @@ */ import { describe, it, expect } from 'vitest'; -import { isUniqueViolationError, uniqueViolationColumn, uniqueViolationField } from './unique-violation.js'; +import { isUniqueViolationError, uniqueViolationColumn, uniqueViolationColumns, uniqueViolationField } from './unique-violation.js'; describe('isUniqueViolationError — input shapes', () => { it('accepts a bare string, for callers that already unwrapped `err.message`', () => { @@ -335,3 +335,51 @@ describe('uniqueViolationField — the implied organization key part is set asid expect(uniqueViolationField(error)).toBeUndefined(); }); }); + +describe('uniqueViolationColumns — the composite key the store named', () => { + /** + * The reading `uniqueViolationField` refuses to reduce to one field: the + * columns of a composite key, organization part set aside, for a caller + * that matches them against a unique index the object declares before it + * names any of them. The Postgres DETAIL is the shape node-postgres hands + * back on `error.detail`. + */ + it.each([ + ['SQLite, organization + three authored', { message: 'UNIQUE constraint failed: t.organization_id, t.plant, t.carbon_grade, t.cost_week' }], + ['SQLite, three authored', { message: 'UNIQUE constraint failed: t.plant, t.carbon_grade, t.cost_week' }], + [ + 'Postgres DETAIL, organization + three authored', + { + message: 'duplicate key value violates unique constraint "uniq_t_plant"', + code: '23505', + detail: 'Key (organization_id, plant, carbon_grade, cost_week)=(org_a, p, g, w) already exists.', + }, + ], + ])('reads the authored columns, in the driver\'s order, for %s', (_label, error) => { + expect(uniqueViolationColumns(error)).toEqual(['plant', 'carbon_grade', 'cost_week']); + // …and never overlaps the single-field answer. + expect(uniqueViolationField(error)).toBeUndefined(); + }); + + it('a key that reduces to one field is `uniqueViolationField`\'s answer, not this one\'s', () => { + expect(uniqueViolationColumns('UNIQUE constraint failed: t.organization_id, t.invoice_no')).toBeUndefined(); + expect(uniqueViolationColumns('UNIQUE constraint failed: sys_user.email')).toBeUndefined(); + expect(uniqueViolationColumns('UNIQUE constraint failed: t.organization_id')).toBeUndefined(); + }); + + it.each([ + ['a MySQL index name', { message: "Duplicate entry 'a-b' for key 'idx_plant_week'", code: 'ER_DUP_ENTRY', errno: 1062 }], + ["SQLite's index form", { message: "UNIQUE constraint failed: index 'idx_plant_week'", code: 'SQLITE_CONSTRAINT_UNIQUE' }], + [ + 'an expression part', + { + message: 'duplicate key value violates unique constraint "uniq_t"', + code: '23505', + detail: "Key (COALESCE(organization_id, '__global__'::text), plant, cost_week)=(o, p, w) already exists.", + }, + ], + ['a NOT NULL refusal (gated on the predicate)', { message: 'NOT NULL constraint failed: t.plant' }], + ])('names no columns for %s', (_label, error) => { + expect(uniqueViolationColumns(error)).toBeUndefined(); + }); +}); diff --git a/packages/types/src/unique-violation.ts b/packages/types/src/unique-violation.ts index 197125a1e41..1e959eefdab 100644 --- a/packages/types/src/unique-violation.ts +++ b/packages/types/src/unique-violation.ts @@ -305,6 +305,26 @@ function bareIdentifier(raw: string): string { */ const IMPLIED_ORGANIZATION_KEY_PART = 'organization_id'; +/** + * One dialect's list of constraint targets as the key's column names, or + * `undefined` when any part is not determinably a column (an expression part, + * a quoted oddity). + * + * `setAsideOrganization` is {@link uniqueViolationField}'s question: the + * implied organization key part is dropped first, so + * `(organization_id, invoice_no)` answers `['invoice_no']`, and a key whose + * ONLY part is `organization_id` still answers that column. + */ +function keyColumns(targets: string, setAsideOrganization: boolean): string[] | undefined { + const names = targets.split(',').map(bareIdentifier); + const counted = + setAsideOrganization && names.length > 1 + ? names.filter((name) => name !== IMPLIED_ORGANIZATION_KEY_PART) + : names; + if (counted.length === 0 || !counted.every((name) => PLAIN_IDENTIFIER.test(name))) return undefined; + return counted; +} + /** * Reduce one dialect's list of constraint targets to THE conflicting column, * or `undefined` when there is not exactly one that is determinably a column. @@ -314,33 +334,38 @@ const IMPLIED_ORGANIZATION_KEY_PART = 'organization_id'; * returning an index name — it points a form at `tenant_id` when what the user * typed twice was `email`. * - * `setAsideOrganization` is {@link uniqueViolationField}'s question: the - * implied organization key part is dropped before counting, so - * `(organization_id, invoice_no)` answers `invoice_no`, while - * `(organization_id, department, code)` still answers `undefined` and a key - * whose ONLY part is `organization_id` still answers that column. + * With `setAsideOrganization`, `(organization_id, invoice_no)` answers + * `invoice_no`, while `(organization_id, department, code)` still answers + * `undefined` — see {@link keyColumns}. */ function soleColumn(targets: string, setAsideOrganization: boolean): string | undefined { - const names = targets.split(',').map(bareIdentifier); - const counted = - setAsideOrganization && names.length > 1 - ? names.filter((name) => name !== IMPLIED_ORGANIZATION_KEY_PART) - : names; - if (counted.length !== 1) return undefined; - const [name] = counted; - return PLAIN_IDENTIFIER.test(name) ? name : undefined; + const columns = keyColumns(targets, setAsideOrganization); + return columns !== undefined && columns.length === 1 ? columns[0] : undefined; } -function columnFromText(text: string, setAsideOrganization: boolean): string | undefined { +/** + * The composite reading of one dialect's targets: the key's columns when there + * are AT LEAST TWO and every one is determinably a column, else `undefined`. + * A single column is {@link soleColumn}'s answer, never this one's. + */ +function compositeColumns(targets: string, setAsideOrganization: boolean): readonly string[] | undefined { + const columns = keyColumns(targets, setAsideOrganization); + return columns !== undefined && columns.length > 1 ? columns : undefined; +} + +/** The reading a text's constraint targets are reduced by — {@link soleColumn} or {@link compositeColumns}. */ +type TargetReading = (targets: string, setAsideOrganization: boolean) => T | undefined; + +function columnFromText(text: string, setAsideOrganization: boolean, read: TargetReading): T | undefined { const sqlite = SQLITE_TARGETS.exec(text); if (sqlite) { const targets = sqlite[1].trim(); // `index 'idx_email_unique'` is an index name, not a column. Refuse. - return SQLITE_INDEX_FORM.test(targets) ? undefined : soleColumn(targets, setAsideOrganization); + return SQLITE_INDEX_FORM.test(targets) ? undefined : read(targets, setAsideOrganization); } const postgres = POSTGRES_DETAIL_TARGETS.exec(text); - if (postgres) return soleColumn(postgres[1], setAsideOrganization); + if (postgres) return read(postgres[1], setAsideOrganization); // MySQL deliberately has no limb here — see the doc comment on // `uniqueViolationColumn`. `Duplicate entry 'x' for key 'i'` names `i`, @@ -348,26 +373,31 @@ function columnFromText(text: string, setAsideOrganization: boolean): string | u return undefined; } -function findUniqueViolationColumn(error: unknown, depth: number, setAsideOrganization: boolean): string | undefined { +function findUniqueViolationColumn( + error: unknown, + depth: number, + setAsideOrganization: boolean, + read: TargetReading, +): T | undefined { if (error === null || error === undefined || depth > MAX_CAUSE_DEPTH) return undefined; - if (typeof error === 'string') return columnFromText(error, setAsideOrganization); + if (typeof error === 'string') return columnFromText(error, setAsideOrganization, read); if (typeof error !== 'object') return undefined; const err = error as { message?: unknown; detail?: unknown; cause?: unknown }; if (typeof err.message === 'string') { - const fromMessage = columnFromText(err.message, setAsideOrganization); + const fromMessage = columnFromText(err.message, setAsideOrganization, read); if (fromMessage !== undefined) return fromMessage; } // node-postgres keeps the `DETAIL:` line off the message and on its own // field, so for the driver we actually ship this is where the column is. if (typeof err.detail === 'string') { - const fromDetail = columnFromText(err.detail, setAsideOrganization); + const fromDetail = columnFromText(err.detail, setAsideOrganization, read); if (fromDetail !== undefined) return fromDetail; } - return findUniqueViolationColumn(err.cause, depth + 1, setAsideOrganization); + return findUniqueViolationColumn(err.cause, depth + 1, setAsideOrganization, read); } /** @@ -439,7 +469,7 @@ function findUniqueViolationColumn(error: unknown, depth: number, setAsideOrgani */ export function uniqueViolationColumn(error: unknown): string | undefined { if (!isUniqueViolationError(error)) return undefined; - return findUniqueViolationColumn(error, 0, false); + return findUniqueViolationColumn(error, 0, false, soleColumn); } /** @@ -490,5 +520,36 @@ export function uniqueViolationColumn(error: unknown): string | undefined { */ export function uniqueViolationField(error: unknown): string | undefined { if (!isUniqueViolationError(error)) return undefined; - return findUniqueViolationColumn(error, 0, true); + return findUniqueViolationColumn(error, 0, true, soleColumn); +} + +/** + * The columns of a COMPOSITE unique key the driver named, organization part + * set aside exactly as {@link uniqueViolationField} sets it aside — or + * `undefined` when the refusal is not determinably a composite of columns. + * + * This is the reading {@link uniqueViolationField} refuses to reduce to one + * field: SQLite's `UNIQUE constraint failed: t.organization_id, t.plant, + * t.cost_week` and Postgres' `Key (organization_id, plant, cost_week)=(…)` + * both answer `['plant', 'cost_week']`. It answers only where every part is a + * plain column name and at least two remain, so it never overlaps + * {@link uniqueViolationField}: a key that reduces to one field is that + * function's answer, and this one's `undefined`. + * + * ⛔ **Driver text is evidence, not a verdict.** The columns are what the store + * printed, and a column is not yet a field the writer can be told about: an + * object keyed on a `tenancy.tenantField` other than `organization_id` prints + * that column beside the authored ones, and the text cannot tell them apart. + * So a caller names these to a writer ONLY after matching the whole set to a + * unique index the object DECLARES (the engine's `DuplicateRecordError` does + * exactly that) — never by printing them as they come. Index names (MySQL, + * SQLite's `index 'x'`, a Postgres constraint name) and expression parts name + * nothing here either, for the reason {@link uniqueViolationColumn} gives. + * + * @param error - the thrown value, of any shape. + * @returns the composite key's columns in the driver's order, or `undefined`. + */ +export function uniqueViolationColumns(error: unknown): readonly string[] | undefined { + if (!isUniqueViolationError(error)) return undefined; + return findUniqueViolationColumn(error, 0, true, compositeColumns); }