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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(drizzle): enforce uniqueness on index names #8754

Merged
merged 2 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/db-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter>
findGlobalVersions,
findOne,
findVersions,
indexes: new Set<string>(),
init,
insert,
migrate,
Expand Down
1 change: 1 addition & 0 deletions packages/db-sqlite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {
findGlobalVersions,
findOne,
findVersions,
indexes: new Set<string>(),
init,
insert,
migrate,
Expand Down
21 changes: 13 additions & 8 deletions packages/db-sqlite/src/schema/build.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { DrizzleAdapter } from '@payloadcms/drizzle/types'
import type { Relation } from 'drizzle-orm'
import type {
AnySQLiteColumn,
Expand All @@ -9,7 +10,7 @@ import type {
} from 'drizzle-orm/sqlite-core'
import type { Field, SanitizedJoins } from 'payload'

import { createTableName } from '@payloadcms/drizzle'
import { buildIndexName, createTableName } from '@payloadcms/drizzle'
import { relations, sql } from 'drizzle-orm'
import {
foreignKey,
Expand Down Expand Up @@ -416,21 +417,25 @@ export const buildTable = ({
foreignColumns: [adapter.tables[formattedRelationTo].id],
}).onDelete('cascade')

const indexName = [colName]
const indexColumns = [colName]

const unique = !disableUnique && uniqueRelationships.has(relationTo)

if (unique) {
indexName.push('path')
indexColumns.push('path')
}
if (hasLocalizedRelationshipField) {
indexName.push('locale')
indexColumns.push('locale')
}

relationExtraConfig[`${relationTo}IdIdx`] = createIndex({
name: indexName,
columnName: `${formattedRelationTo}_id`,
tableName: relationshipsTableName,
const indexName = buildIndexName({
name: `${relationshipsTableName}_${formattedRelationTo}_id`,
adapter: adapter as unknown as DrizzleAdapter,
})

relationExtraConfig[indexName] = createIndex({
name: indexColumns,
indexName,
unique,
})
})
Expand Down
9 changes: 4 additions & 5 deletions packages/db-sqlite/src/schema/createIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import type { AnySQLiteColumn } from 'drizzle-orm/sqlite-core'
import { index, uniqueIndex } from 'drizzle-orm/sqlite-core'

type CreateIndexArgs = {
columnName: string
indexName: string
name: string | string[]
tableName: string
unique?: boolean
}

export const createIndex = ({ name, columnName, tableName, unique }: CreateIndexArgs) => {
export const createIndex = ({ name, indexName, unique }: CreateIndexArgs) => {
return (table: { [x: string]: AnySQLiteColumn }) => {
let columns
if (Array.isArray(name)) {
Expand All @@ -21,8 +20,8 @@ export const createIndex = ({ name, columnName, tableName, unique }: CreateIndex
columns = [table[name]]
}
if (unique) {
return uniqueIndex(`${tableName}_${columnName}_idx`).on(columns[0], ...columns.slice(1))
return uniqueIndex(indexName).on(columns[0], ...columns.slice(1))
}
return index(`${tableName}_${columnName}_idx`).on(columns[0], ...columns.slice(1))
return index(indexName).on(columns[0], ...columns.slice(1))
}
}
13 changes: 10 additions & 3 deletions packages/db-sqlite/src/schema/traverseFields.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { DrizzleAdapter } from '@payloadcms/drizzle/types'
import type { Relation } from 'drizzle-orm'
import type { IndexBuilder, SQLiteColumnBuilder } from 'drizzle-orm/sqlite-core'
import type { Field, SanitizedJoins, TabAsField } from 'payload'

import {
buildIndexName,
createTableName,
hasLocalesTable,
validateExistingBlockIsIdentical,
Expand Down Expand Up @@ -164,10 +166,15 @@ export const traverseFields = ({
}
adapter.fieldConstraints[rootTableName][`${columnName}_idx`] = constraintValue
}
targetIndexes[`${newTableName}_${field.name}Idx`] = createIndex({

const indexName = buildIndexName({
name: `${newTableName}_${columnName}`,
adapter: adapter as unknown as DrizzleAdapter,
})

targetIndexes[indexName] = createIndex({
name: field.localized ? [fieldName, '_locale'] : fieldName,
columnName,
tableName: newTableName,
indexName,
unique,
})
}
Expand Down
1 change: 1 addition & 0 deletions packages/db-vercel-postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export function vercelPostgresAdapter(args: Args = {}): DatabaseAdapterObj<Verce
fieldConstraints: {},
getMigrationTemplate,
idType: postgresIDType,
indexes: new Set<string>(),
initializing,
localesSuffix: args.localesSuffix || '_locales',
logger: args.logger,
Expand Down
1 change: 1 addition & 0 deletions packages/drizzle/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export { updateGlobal } from './updateGlobal.js'
export { updateGlobalVersion } from './updateGlobalVersion.js'
export { updateVersion } from './updateVersion.js'
export { upsertRow } from './upsertRow/index.js'
export { buildIndexName } from './utilities/buildIndexName.js'
export { executeSchemaHooks } from './utilities/executeSchemaHooks.js'
export { extendDrizzleTable } from './utilities/extendDrizzleTable.js'
export { hasLocalesTable } from './utilities/hasLocalesTable.js'
Expand Down
19 changes: 12 additions & 7 deletions packages/drizzle/src/postgres/schema/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type {
} from '../types.js'

import { createTableName } from '../../createTableName.js'
import { buildIndexName } from '../../utilities/buildIndexName.js'
import { createIndex } from './createIndex.js'
import { parentIDColumnMap } from './parentIDColumnMap.js'
import { setColumnID } from './setColumnID.js'
Expand Down Expand Up @@ -389,21 +390,25 @@ export const buildTable = ({
foreignColumns: [adapter.tables[formattedRelationTo].id],
}).onDelete('cascade')

const indexName = [colName]
const indexColumns = [colName]

const unique = !disableUnique && uniqueRelationships.has(relationTo)

if (unique) {
indexName.push('path')
indexColumns.push('path')
}
if (hasLocalizedRelationshipField) {
indexName.push('locale')
indexColumns.push('locale')
}

relationExtraConfig[`${relationTo}IdIdx`] = createIndex({
name: indexName,
columnName: `${formattedRelationTo}_id`,
tableName: relationshipsTableName,
const indexName = buildIndexName({
name: `${relationshipsTableName}_${formattedRelationTo}_id`,
adapter,
})

relationExtraConfig[indexName] = createIndex({
name: indexColumns,
indexName,
unique,
})
})
Expand Down
9 changes: 4 additions & 5 deletions packages/drizzle/src/postgres/schema/createIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import { index, uniqueIndex } from 'drizzle-orm/pg-core'
import type { GenericColumn } from '../types.js'

type CreateIndexArgs = {
columnName: string
indexName: string
name: string | string[]
tableName: string
unique?: boolean
}

export const createIndex = ({ name, columnName, tableName, unique }: CreateIndexArgs) => {
export const createIndex = ({ name, indexName, unique }: CreateIndexArgs) => {
return (table: { [x: string]: GenericColumn }) => {
let columns
if (Array.isArray(name)) {
Expand All @@ -21,8 +20,8 @@ export const createIndex = ({ name, columnName, tableName, unique }: CreateIndex
columns = [table[name]]
}
if (unique) {
return uniqueIndex(`${tableName}_${columnName}_idx`).on(columns[0], ...columns.slice(1))
return uniqueIndex(indexName).on(columns[0], ...columns.slice(1))
}
return index(`${tableName}_${columnName}_idx`).on(columns[0], ...columns.slice(1))
return index(indexName).on(columns[0], ...columns.slice(1))
}
}
9 changes: 6 additions & 3 deletions packages/drizzle/src/postgres/schema/traverseFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type {
} from '../types.js'

import { createTableName } from '../../createTableName.js'
import { buildIndexName } from '../../utilities/buildIndexName.js'
import { hasLocalesTable } from '../../utilities/hasLocalesTable.js'
import { validateExistingBlockIsIdentical } from '../../utilities/validateExistingBlockIsIdentical.js'
import { buildTable } from './build.js'
Expand Down Expand Up @@ -169,10 +170,12 @@ export const traverseFields = ({
}
adapter.fieldConstraints[rootTableName][`${columnName}_idx`] = constraintValue
}
targetIndexes[`${newTableName}_${field.name}Idx`] = createIndex({

const indexName = buildIndexName({ name: `${newTableName}_${columnName}`, adapter })

targetIndexes[indexName] = createIndex({
name: field.localized ? [fieldName, '_locale'] : fieldName,
columnName,
tableName: newTableName,
indexName,
unique,
})
}
Expand Down
1 change: 1 addition & 0 deletions packages/drizzle/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export interface DrizzleAdapter extends BaseDatabaseAdapter {
fieldConstraints: Record<string, Record<string, string>>
getMigrationTemplate: (args: MigrationTemplateArgs) => string
idType: 'serial' | 'uuid'
indexes: Set<string>
initializing: Promise<void>
insert: Insert
localesSuffix?: string
Expand Down
24 changes: 24 additions & 0 deletions packages/drizzle/src/utilities/buildIndexName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { DrizzleAdapter } from '../types.js'

export const buildIndexName = ({
name,
adapter,
number = 0,
}: {
adapter: DrizzleAdapter
name: string
number?: number
}): string => {
const indexName = `${name}${number ? `_${number}` : ''}_idx`

if (!adapter.indexes.has(indexName)) {
adapter.indexes.add(indexName)
return indexName
}

return buildIndexName({
name,
adapter,
number: number + 1,
})
}
17 changes: 17 additions & 0 deletions test/fields/collections/Indexed/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,23 @@ const IndexedFields: CollectionConfig = {
],
label: 'Collapsible',
},
{
type: 'text',
name: 'someText',
index: true,
},
{
type: 'array',
name: 'some',
index: true,
fields: [
{
type: 'text',
name: 'text',
index: true,
},
],
},
],
versions: true,
}
Expand Down
25 changes: 25 additions & 0 deletions test/fields/payload-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export interface Config {
'uploads-multi': UploadsMulti;
'uploads-poly': UploadsPoly;
'uploads-multi-poly': UploadsMultiPoly;
'uploads-restricted': UploadsRestricted;
'ui-fields': UiField;
'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference;
Expand Down Expand Up @@ -1061,6 +1062,13 @@ export interface IndexedField {
};
collapsibleLocalizedUnique?: string | null;
collapsibleTextUnique?: string | null;
someText?: string | null;
some?:
| {
text?: string | null;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
Expand Down Expand Up @@ -1619,6 +1627,19 @@ export interface UploadsMultiPoly {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "uploads-restricted".
*/
export interface UploadsRestricted {
id: string;
text?: string | null;
uploadWithoutRestriction?: (string | null) | Upload;
uploadWithAllowCreateFalse?: (string | null) | Upload;
uploadMultipleWithAllowCreateFalse?: (string | Upload)[] | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ui-fields".
Expand Down Expand Up @@ -1764,6 +1785,10 @@ export interface PayloadLockedDocument {
relationTo: 'uploads-multi-poly';
value: string | UploadsMultiPoly;
} | null)
| ({
relationTo: 'uploads-restricted';
value: string | UploadsRestricted;
} | null)
| ({
relationTo: 'ui-fields';
value: string | UiField;
Expand Down
Loading