Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix primary key unique constraint error extraction for MySQL #22434

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slimy-jeans-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---

Check warning on line 1 in .changeset/slimy-jeans-shout.md

View workflow job for this annotation

GitHub Actions / Lint

File ignored by default.
'@directus/api': patch
---

Fixed error extraction for MySQL unique primary key constraints
5 changes: 5 additions & 0 deletions .changeset/twenty-seahorses-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---

Check warning on line 1 in .changeset/twenty-seahorses-drop.md

View workflow job for this annotation

GitHub Actions / Lint

File ignored by default.
'@directus/errors': patch
---

Added `primaryKey` flag in `RecordNotUniqueError` extensions
53 changes: 25 additions & 28 deletions api/src/database/errors/dialects/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,42 +48,39 @@ function uniqueViolation(error: MySQLError) {
/**
* MySQL's error doesn't return the field name in the error. In case the field is created through
* Directus (/ Knex), the key name will be `<collection>_<field>_unique` in which case we can pull
* the field name from the key name
* the field name from the key name.
* If the field is the primary key it instead will be `<collection>_PRIMARY` for MySQL 8+
* and `PRIMARY` for MySQL 5.7 and MariaDB.
*/

/** MySQL 8+ style error message */
if (matches[1]!.includes('.')) {
const collection = matches[1]!.slice(1, -1).split('.')[0]!;

let field = null;

const indexName = matches[1]?.slice(1, -1).split('.')[1];
let collection: string | null;
let indexName: string;
let field = null;

if (indexName?.startsWith(`${collection}_`) && indexName.endsWith('_unique')) {
field = indexName?.slice(collection.length + 1, -7);
}
if (matches[1]!.includes('.')) {
// MySQL 8+ style error message

return new RecordNotUniqueError({
collection,
field,
});
// In case of primary key matches[1] is `'<collection>.PRIMARY'`
// In case of other field matches[1] is `'<collection>.<collection>_<field>_unique'`
[collection, indexName] = matches[1]!.slice(1, -1).split('.') as [string, string];
} else {
/** MySQL 5.7 style error message */
const indexName = matches[1]!.slice(1, -1);

const collection = indexName.split('_')[0]!;

let field = null;
// MySQL 5.7 and MariaDB style error message

if (indexName?.startsWith(`${collection}_`) && indexName.endsWith('_unique')) {
field = indexName?.slice(collection.length + 1, -7);
}
// In case of primary key matches[1] is `'PRIMARY'`
// In case of other field matches[1] is `'<collection>_<field>_unique'`
indexName = matches[1]!.slice(1, -1);
collection = indexName.includes('_') ? indexName.split('_')[0]! : null;
}

return new RecordNotUniqueError({
collection,
field,
});
if (collection !== null && indexName.startsWith(`${collection}_`) && indexName.endsWith('_unique')) {
field = indexName?.slice(collection.length + 1, -7);
}

return new RecordNotUniqueError({
collection,
field,
primaryKey: indexName === 'PRIMARY', // propagate information about primary key violation
});
}

function numericValueOutOfRange(error: MySQLError) {
Expand Down
19 changes: 17 additions & 2 deletions api/src/services/items.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Action } from '@directus/constants';
import { useEnv } from '@directus/env';
import { ForbiddenError, InvalidPayloadError } from '@directus/errors';
import { ForbiddenError, InvalidPayloadError, ErrorCode, isDirectusError } from '@directus/errors';
import { isSystemCollection } from '@directus/system-data';
import type {
Accountability,
Expand Down Expand Up @@ -217,7 +217,22 @@ export class ItemsService<Item extends AnyItem = AnyItem> implements AbstractSer
primaryKey = primaryKey ?? returnedKey;
}
} catch (err: any) {
throw await translateDatabaseError(err);
const dbError = await translateDatabaseError(err);

if (isDirectusError(dbError, ErrorCode.RecordNotUnique) && dbError.extensions.primaryKey) {
// This is a MySQL specific thing we need to handle here, since MySQL does not return the field name
// if the unique constraint is the primary key
dbError.extensions.field = pkField?.field ?? null;

if (dbError.extensions.collection === null) {
// This is a special case for MySQL 5.7, where the collection is not returned for the primary key constraint
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not support MySQL 5.7 any more, I think this can be dropped.

dbError.extensions.collection = this.collection;
}

delete dbError.extensions.primaryKey;
}

throw dbError;
}

// Most database support returning, those who don't tend to return the PK anyways
Expand Down
1 change: 1 addition & 0 deletions packages/errors/src/errors/record-not-unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createError, ErrorCode } from '../index.js';
export interface RecordNotUniqueErrorExtensions {
collection: string | null;
field: string | null;
primaryKey?: boolean;
}

export const messageConstructor = ({ collection, field }: RecordNotUniqueErrorExtensions) => {
Expand Down