Skip to content

Commit ca73dd0

Browse files
fix(cache): improve unique constraint error detection
Create a database-agnostic utility function to detect unique constraint violations across PostgreSQL, MySQL, SQLite, and SQL Server. This improves the reliability of the cache upsert logic by properly handling database-specific error codes and numbers.
1 parent 4ba97d6 commit ca73dd0

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

server/src/services/cache.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import isEqual from "lodash/isEqual"
66

77
import type { PopulateParams } from "./populate"
88

9+
import { isUniqueConstraintError } from "../utils/isUniqueConstraintError"
910
import log from "../utils/log"
1011
import { majorMinorVersion } from "../utils/version"
1112
import { getConfig } from "./deep-populate/utils"
@@ -45,8 +46,8 @@ export default ({ strapi }: { strapi: Core.Strapi }) => ({
4546

4647
try {
4748
return await documentService.create({ data: { hash, params, populate, dependencies: dependencies.join(",") } })
48-
} catch (error) {
49-
if (error?.code?.includes("UNIQUE")) {
49+
} catch (error: unknown) {
50+
if (isUniqueConstraintError(error)) {
5051
const entry = await documentService.findFirst({ filters: { hash: { $eq: hash } } })
5152

5253
if (entry) {
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const UniqueConstraintErrorCodes = {
2+
// PostgreSQL
3+
POSTGRES_UNIQUE_VIOLATION: "23505",
4+
5+
// MySQL
6+
MYSQL_DUPLICATE_ENTRY: 1062,
7+
8+
// SQLite
9+
SQLITE_CONSTRAINT: 19,
10+
SQLITE_CONSTRAINT_UNIQUE: 2067,
11+
12+
// SQL Server
13+
SQLSERVER_DUPLICATE_KEY: 2601,
14+
SQLSERVER_UNIQUE_KEY_VIOLATION: 2627,
15+
} as const
16+
17+
export const isUniqueConstraintError = (error: unknown): boolean => {
18+
const err = error as { code?: string; errno?: number; number?: number }
19+
20+
return (
21+
Object.keys(UniqueConstraintErrorCodes).includes(err.code) ||
22+
err.code === UniqueConstraintErrorCodes.POSTGRES_UNIQUE_VIOLATION ||
23+
err.errno === UniqueConstraintErrorCodes.MYSQL_DUPLICATE_ENTRY ||
24+
err.errno === UniqueConstraintErrorCodes.SQLITE_CONSTRAINT ||
25+
err.errno === UniqueConstraintErrorCodes.SQLITE_CONSTRAINT_UNIQUE ||
26+
err.number === UniqueConstraintErrorCodes.SQLSERVER_DUPLICATE_KEY ||
27+
err.number === UniqueConstraintErrorCodes.SQLSERVER_UNIQUE_KEY_VIOLATION
28+
)
29+
}

0 commit comments

Comments
 (0)