Compare commits

...

18 Commits

Author SHA1 Message Date
Dan Ribbens
1557735030 merge main 2024-01-24 10:20:38 -05:00
Dan Ribbens
83eb468ac8 chore: reverted file 2024-01-08 17:14:30 -05:00
Dan Ribbens
ea6879a786 merge main 2024-01-08 17:04:00 -05:00
Dan Ribbens
033c894b38 test: database schema mongodb ignored 2023-12-20 17:10:36 -05:00
Dan Ribbens
b7861e2a65 test: database tableName and enum checks 2023-12-20 15:52:31 -05:00
Dan Ribbens
0016691975 chore: merge conflict 2023-12-20 08:59:00 -05:00
Dan Ribbens
77b4fb1b48 merge main 2023-12-19 16:35:13 -05:00
Ritsu
76d196a608 chore: made enumName and tableName types declarable by postgres adapter 2023-12-18 00:11:50 +02:00
Ritsu
79ba286814 chore: getTableName move prefer to options 2023-12-17 01:44:37 +02:00
Ritsu
05a9d9e507 fix: add tableName property for select with hasMany: true 2023-12-17 01:28:37 +02:00
Ritsu
da77d406f5 docs: replace 'the' with 'this' in radio/select config 2023-12-17 00:21:34 +02:00
Ritsu
c089eb4bc9 docs: add documentation for the feature 2023-12-17 00:07:26 +02:00
Ritsu
8a34be6946 chore: simplify getTableName 2023-12-16 23:52:17 +02:00
Ritsu
14ce4bdcf1 enumName instead of tableName for radio and select 2023-12-16 23:48:48 +02:00
Ritsu
18edcff410 fix: find with query to multi relationship field to collections with custom table names 2023-12-16 23:36:24 +02:00
Ritsu
3b571bf6a7 remove tableName from "blocks", keep only in block 2023-12-16 05:56:52 +02:00
Ritsu
c517bfb5e5 localization test revert 2023-12-16 05:43:07 +02:00
Ritsu
5f8a0950f5 feat(db-postgres): allow for custom table names 2023-12-16 05:30:03 +02:00
40 changed files with 348 additions and 90 deletions

View File

@@ -30,6 +30,7 @@ It's often best practice to write your Collections in separate files and then im
| **`typescript`** | An object with property `interface` as the text used in schema generation. Auto-generated from slug if not defined. |
| **`defaultSort`** | Pass a top-level field to sort by default in the collection List view. Prefix the name of the field with a minus symbol ("-") to sort in descending order. |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`tableName`** | Custom table name for this collection when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from slug if not defined.
_\* An asterisk denotes that a property is required._

View File

@@ -26,6 +26,7 @@ As with Collection configs, it's often best practice to write your Globals in se
| **`graphQL.name`** | Text used in schema generation. Auto-generated from slug if not defined. |
| **`typescript`** | An object with property `interface` as the text used in schema generation. Auto-generated from slug if not defined. |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`tableName`** | Custom table name for this global when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from slug if not defined.
_\* An asterisk denotes that a property is required._

View File

@@ -45,6 +45,7 @@ keywords: array, fields, config, configuration, documentation, Content Managemen
| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`interfaceName`** | Create a top level, reusable [Typescript interface](/docs/typescript/generating-types#custom-field-interfaces) & [GraphQL type](/docs/graphql/graphql-schema#custom-field-schemas). |
| **`tableName`** | Custom table name for the field when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from name if not defined.
_\* An asterisk denotes that a property is required._

View File

@@ -72,7 +72,7 @@ Blocks are defined as separate configs of their own.
</Banner>
| Option | Description |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|----------------------------| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`slug`** \* | Identifier for this block type. Will be saved on each block as the `blockType` property. |
| **`fields`** \* | Array of fields to be stored in this block. |
| **`labels`** | Customize the block labels that appear in the Admin dashboard. Auto-generated from slug if not defined. |
@@ -80,7 +80,8 @@ Blocks are defined as separate configs of their own.
| **`imageAltText`** | Customize this block's image thumbnail alt text. |
| **`interfaceName`** | Create a top level, reusable [Typescript interface](/docs/typescript/generating-types#custom-field-interfaces) & [GraphQL type](/docs/graphql/graphql-schema#custom-field-schemas). |
| **`graphQL.singularName`** | Text to use for the GraphQL schema name. Auto-generated from slug if not defined. NOTE: this is set for deprecation, prefer `interfaceName`. |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`tableName`** | Custom table name for this block type when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from slug if not defined.
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
#### Auto-generated data per block

View File

@@ -36,6 +36,7 @@ keywords: radio, fields, config, configuration, documentation, Content Managemen
| **`required`** | Require this field to have a value. |
| **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`enumName`** | Custom enum name for this field when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from name if not defined.
_\* An asterisk denotes that a property is required._

View File

@@ -38,6 +38,8 @@ keywords: select, multi-select, fields, config, configuration, documentation, Co
| **`required`** | Require this field to have a value. |
| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. |
| **`custom`** | Extension point for adding custom data (e.g. for plugins) |
| **`enumName`** | Custom enum name for this field when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from name if not defined.
| **`tableName`** | Custom table name (if `hasMany` set to `true`) for this field when using SQL database adapter ([Postgres](/docs/database/postgres)). Auto-generated from name if not defined.
_\* An asterisk denotes that a property is required._

View File

@@ -1,10 +1,9 @@
import type { Create } from 'payload/database'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export const create: Create = async function create(
this: PostgresAdapter,
@@ -19,8 +18,8 @@ export const create: Create = async function create(
db,
fields: collection.fields,
operation: 'create',
tableName: toSnakeCase(collectionSlug),
req,
tableName: getTableName(collection),
})
return result

View File

@@ -1,11 +1,10 @@
import type { CreateGlobalArgs } from 'payload/database'
import type { PayloadRequest, TypeWithID } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function createGlobal<T extends TypeWithID>(
this: PostgresAdapter,
@@ -20,8 +19,8 @@ export async function createGlobal<T extends TypeWithID>(
db,
fields: globalConfig.fields,
operation: 'create',
tableName: toSnakeCase(slug),
req,
tableName: getTableName(globalConfig),
})
return result

View File

@@ -1,14 +1,14 @@
import type { TypeWithVersion } from 'payload/database'
import { type CreateGlobalVersionArgs } from 'payload/database'
import type { PayloadRequest, TypeWithID } from 'payload/types'
import { sql } from 'drizzle-orm'
import { type CreateGlobalVersionArgs } from 'payload/database'
import { buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function createGlobalVersion<T extends TypeWithID>(
this: PostgresAdapter,
@@ -16,7 +16,7 @@ export async function createGlobalVersion<T extends TypeWithID>(
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)
const globalTableName = toSnakeCase(globalSlug)
const globalTableName = getTableName(global)
const tableName = `_${globalTableName}_v`
const result = await upsertRow<TypeWithVersion<T>>({
@@ -29,8 +29,8 @@ export async function createGlobalVersion<T extends TypeWithID>(
db,
fields: buildVersionGlobalFields(global),
operation: 'create',
tableName,
req,
tableName,
})
const table = this.tables[tableName]

View File

@@ -3,11 +3,11 @@ import type { PayloadRequest, TypeWithID } from 'payload/types'
import { sql } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function createVersion<T extends TypeWithID>(
this: PostgresAdapter,
@@ -21,7 +21,7 @@ export async function createVersion<T extends TypeWithID>(
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collection = this.payload.collections[collectionSlug].config
const collectionTableName = toSnakeCase(collectionSlug)
const collectionTableName = getTableName(collection)
const tableName = `_${collectionTableName}_v`
const result = await upsertRow<TypeWithVersion<T>>({
@@ -35,8 +35,8 @@ export async function createVersion<T extends TypeWithID>(
db,
fields: buildVersionCollectionFields(collection),
operation: 'create',
tableName,
req,
tableName,
})
const table = this.tables[tableName]

View File

@@ -2,11 +2,11 @@ import type { DeleteMany } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import { inArray } from 'drizzle-orm'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const deleteMany: DeleteMany = async function deleteMany(
this: PostgresAdapter,
@@ -14,7 +14,7 @@ export const deleteMany: DeleteMany = async function deleteMany(
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig = this.payload.collections[collection].config
const tableName = toSnakeCase(collection)
const tableName = getTableName(collectionConfig)
const result = await findMany({
adapter: this,

View File

@@ -1,13 +1,12 @@
import type { DeleteOne } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'
import { getTableName } from './utilities/getTableName'
export const deleteOne: DeleteOne = async function deleteOne(
this: PostgresAdapter,
@@ -15,7 +14,7 @@ export const deleteOne: DeleteOne = async function deleteOne(
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig = this.payload.collections[collection].config
const tableName = toSnakeCase(collection)
const tableName = getTableName(collectionConfig)
const { where } = await buildQuery({
adapter: this,

View File

@@ -3,11 +3,11 @@ import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import { inArray } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const deleteVersions: DeleteVersions = async function deleteVersion(
this: PostgresAdapter,
@@ -16,7 +16,7 @@ export const deleteVersions: DeleteVersions = async function deleteVersion(
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = `_${toSnakeCase(collection)}_v`
const tableName = `_${getTableName(collectionConfig)}_v`
const fields = buildVersionCollectionFields(collectionConfig)
const { docs } = await findMany({

View File

@@ -1,11 +1,10 @@
import type { Find } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const find: Find = async function find(
this: PostgresAdapter,
@@ -32,7 +31,7 @@ export const find: Find = async function find(
pagination,
req,
sort,
tableName: toSnakeCase(collection),
tableName: getTableName(collectionConfig),
where: whereArg,
})
}

View File

@@ -7,6 +7,8 @@ import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from '../types'
import type { Result } from './buildFindManyArgs'
import { getTableName } from '../utilities/getTableName'
type TraverseFieldArgs = {
_locales: Record<string, unknown>
adapter: PostgresAdapter
@@ -78,7 +80,7 @@ export const traverseFields = ({
with: {},
}
const arrayTableName = `${currentTableName}_${toSnakeCase(field.name)}`
const arrayTableName = `${currentTableName}_${getTableName(field)}`
if (adapter.tables[`${arrayTableName}_locales`]) withArray.with._locales = _locales
currentArgs.with[`${path}${field.name}`] = withArray
@@ -128,7 +130,7 @@ export const traverseFields = ({
with: {},
}
const tableName = `${topLevelTableName}_blocks_${toSnakeCase(block.slug)}`
const tableName = `${topLevelTableName}_blocks_${getTableName(block)}`
if (adapter.tables[`${tableName}_locales`]) withBlock.with._locales = _locales
topLevelArgs.with[blockKey] = withBlock

View File

@@ -1,17 +1,16 @@
import type { FindGlobal } from 'payload/database'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const findGlobal: FindGlobal = async function findGlobal(
this: PostgresAdapter,
{ locale, req, slug, where },
) {
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)
const tableName = toSnakeCase(slug)
const tableName = getTableName(globalConfig)
const {
docs: [doc],

View File

@@ -2,11 +2,11 @@ import type { FindGlobalVersions } from 'payload/database'
import type { PayloadRequest, SanitizedGlobalConfig } from 'payload/types'
import { buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions(
this: PostgresAdapter,
@@ -27,7 +27,7 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV
)
const sort = typeof sortArg === 'string' ? sortArg : '-createdAt'
const tableName = `_${toSnakeCase(global)}_v`
const tableName = `_${getTableName(globalConfig)}_v`
const fields = buildVersionGlobalFields(globalConfig)
return findMany({

View File

@@ -1,17 +1,17 @@
import type { FindOneArgs } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export async function findOne<T extends TypeWithID>(
this: PostgresAdapter,
{ collection, locale, req = {} as PayloadRequest, where: incomingWhere }: FindOneArgs,
): Promise<T> {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = getTableName(collectionConfig)
const { docs } = await findMany({
adapter: this,
@@ -22,7 +22,7 @@ export async function findOne<T extends TypeWithID>(
pagination: false,
req,
sort: undefined,
tableName: toSnakeCase(collection),
tableName,
where: incomingWhere,
})

View File

@@ -2,11 +2,11 @@ import type { FindVersions } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const findVersions: FindVersions = async function findVersions(
this: PostgresAdapter,
@@ -25,7 +25,7 @@ export const findVersions: FindVersions = async function findVersions(
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const sort = typeof sortArg === 'string' ? sortArg : collectionConfig.defaultSort
const tableName = `_${toSnakeCase(collection)}_v`
const tableName = `_${getTableName(collectionConfig)}_v`
const fields = buildVersionCollectionFields(collectionConfig)
return findMany({

View File

@@ -4,12 +4,12 @@ import type { SanitizedCollectionConfig } from 'payload/types'
import { pgEnum } from 'drizzle-orm/pg-core'
import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { buildTable } from './schema/build'
import { getConfigIDType } from './schema/getConfigIDType'
import { getTableName } from './utilities/getTableName'
export const init: Init = async function init(this: PostgresAdapter) {
if (this.payload.config.localization) {
@@ -20,7 +20,7 @@ export const init: Init = async function init(this: PostgresAdapter) {
}
this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {
const tableName = toSnakeCase(collection.slug)
const tableName = getTableName(collection)
buildTable({
adapter: this,
@@ -55,7 +55,7 @@ export const init: Init = async function init(this: PostgresAdapter) {
})
this.payload.config.globals.forEach((global) => {
const tableName = toSnakeCase(global.slug)
const tableName = getTableName(global)
buildTable({
adapter: this,

View File

@@ -13,6 +13,8 @@ import { v4 as uuid } from 'uuid'
import type { GenericColumn, GenericTable, PostgresAdapter } from '../types'
import type { BuildQueryJoinAliases, BuildQueryJoins } from './buildQuery'
import { getTableName } from '../utilities/getTableName'
type Constraint = {
columnName: string
table: GenericTable
@@ -199,7 +201,7 @@ export const getTableColumnFromPath = ({
}
case 'array': {
newTableName = `${tableName}_${toSnakeCase(field.name)}`
newTableName = `${tableName}_${getTableName(field)}`
constraintPath = `${constraintPath}${field.name}.%.`
if (locale && field.localized && adapter.payload.config.localization) {
joins[newTableName] = and(
@@ -239,7 +241,7 @@ export const getTableColumnFromPath = ({
let blockTableColumn: TableColumn
let newTableName: string
const hasBlockField = field.blocks.some((block) => {
newTableName = `${tableName}_blocks_${toSnakeCase(block.slug)}`
newTableName = `${tableName}_blocks_${getTableName(block)}`
constraintPath = `${constraintPath}${field.name}.%.`
let result
const blockConstraints = []
@@ -329,9 +331,10 @@ export const getTableColumnFromPath = ({
let newAliasTable
if (typeof field.relationTo === 'string') {
newTableName = `${toSnakeCase(field.relationTo)}`
const relationshipConfig = adapter.payload.collections[field.relationTo].config
newTableName = getTableName(relationshipConfig)
// parent to relationship join table
relationshipFields = adapter.payload.collections[field.relationTo].config.fields
relationshipFields = relationshipConfig.fields
newAliasTable = alias(adapter.tables[newTableName], toSnakeCase(uuid()))
@@ -350,7 +353,10 @@ export const getTableColumnFromPath = ({
}
} else if (newCollectionPath === 'value') {
const tableColumnsNames = field.relationTo.map(
(relationTo) => `"${aliasRelationshipTableName}"."${toSnakeCase(relationTo)}_id"`,
(relationTo) =>
`"${aliasRelationshipTableName}"."${getTableName(
adapter.payload.collections[relationTo].config,
)}_id"`,
)
return {
constraints,

View File

@@ -2,9 +2,9 @@ import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import { type QueryDrafts, combineQueries } from 'payload/database'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import { findMany } from './find/findMany'
import { getTableName } from './utilities/getTableName'
export const queryDrafts: QueryDrafts = async function queryDrafts({
collection,
@@ -17,7 +17,7 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
where,
}) {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = `_${toSnakeCase(collection)}_v`
const tableName = `_${getTableName(collectionConfig)}_v`
const fields = buildVersionCollectionFields(collectionConfig)
const combinedWhere = combineQueries({ latest: { equals: true } }, where)

View File

@@ -15,10 +15,10 @@ import {
varchar,
} from 'drizzle-orm/pg-core'
import { fieldAffectsData } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { GenericColumns, GenericTable, PostgresAdapter } from '../types'
import { getTableName } from '../utilities/getTableName'
import { getConfigIDType } from './getConfigIDType'
import { parentIDColumnMap } from './parentIDColumnMap'
import { traverseFields } from './traverseFields'
@@ -296,11 +296,12 @@ export const buildTable = ({
}
relationships.forEach((relationTo) => {
const formattedRelationTo = toSnakeCase(relationTo)
const relationshipConfig = adapter.payload.collections[relationTo].config
const formattedRelationTo = getTableName(relationshipConfig)
let colType = 'integer'
const relatedCollectionCustomID = adapter.payload.collections[
relationTo
].config.fields.find((field) => fieldAffectsData(field) && field.name === 'id')
const relatedCollectionCustomID = relationshipConfig.fields.find(
(field) => fieldAffectsData(field) && field.name === 'id',
)
if (relatedCollectionCustomID?.type === 'number') colType = 'numeric'
if (relatedCollectionCustomID?.type === 'text') colType = 'varchar'
@@ -337,7 +338,7 @@ export const buildTable = ({
}
relationships.forEach((relationTo) => {
const relatedTableName = toSnakeCase(relationTo)
const relatedTableName = getTableName(adapter.payload.collections[relationTo].config)
const idColumnName = `${relationTo}ID`
result[idColumnName] = one(adapter.tables[relatedTableName], {
fields: [relationshipsTable[idColumnName]],

View File

@@ -23,6 +23,7 @@ import toSnakeCase from 'to-snake-case'
import type { GenericColumns, PostgresAdapter } from '../types'
import { getTableName } from '../utilities/getTableName'
import { hasLocalesTable } from '../utilities/hasLocalesTable'
import { buildTable } from './build'
import { createIndex } from './createIndex'
@@ -214,7 +215,7 @@ export const traverseFields = ({
case 'radio':
case 'select': {
const enumName = `enum_${newTableName}_${toSnakeCase(field.name)}`
const enumName = `enum_${newTableName}_${getTableName(field, { prefer: 'enumName' })}`
adapter.enums[enumName] = pgEnum(
enumName,
@@ -228,7 +229,7 @@ export const traverseFields = ({
)
if (field.type === 'select' && field.hasMany) {
const selectTableName = `${newTableName}_${toSnakeCase(field.name)}`
const selectTableName = `${newTableName}_${getTableName(field, { prefer: 'tableName' })}`
const baseColumns: Record<string, PgColumnBuilder> = {
order: integer('order').notNull(),
parent: parentIDColumnMap[parentIDColType]('parent_id')
@@ -292,7 +293,7 @@ export const traverseFields = ({
case 'array': {
const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull
const arrayTableName = `${newTableName}_${toSnakeCase(field.name)}`
const arrayTableName = `${newTableName}_${getTableName(field)}`
const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(),
_parentID: parentIDColumnMap[parentIDColType]('_parent_id')
@@ -370,7 +371,7 @@ export const traverseFields = ({
const disableNotNullFromHere = Boolean(field.admin?.condition) || disableNotNull
field.blocks.forEach((block) => {
const blockTableName = `${rootTableName}_blocks_${toSnakeCase(block.slug)}`
const blockTableName = `${rootTableName}_blocks_${getTableName(block)}`
if (!adapter.tables[blockTableName]) {
const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(),

View File

@@ -1,11 +1,10 @@
/* eslint-disable no-param-reassign */
import type { BlockField } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from '../../types'
import type { BlockRowToInsert, RelationshipToDelete } from './types'
import { getTableName } from '../../utilities/getTableName'
import { traverseFields } from './traverseFields'
type Args = {
@@ -46,7 +45,7 @@ export const transformBlocks = ({
if (typeof blockRow.blockType !== 'string') return
const matchedBlock = field.blocks.find(({ slug }) => slug === blockRow.blockType)
if (!matchedBlock) return
const blockType = toSnakeCase(blockRow.blockType)
const blockType = getTableName(matchedBlock)
if (!blocks[blockType]) blocks[blockType] = []

View File

@@ -7,6 +7,7 @@ import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from '../../types'
import type { ArrayRowToInsert, BlockRowToInsert, RelationshipToDelete } from './types'
import { getTableName } from '../../utilities/getTableName'
import { isArrayOfRows } from '../../utilities/isArrayOfRows'
import { transformArray } from './array'
import { transformBlocks } from './blocks'
@@ -88,7 +89,7 @@ export const traverseFields = ({
let fieldData: unknown
if (fieldAffectsData(field)) {
columnName = `${columnPrefix || ''}${toSnakeCase(field.name)}`
columnName = `${columnPrefix || ''}${getTableName(field)}`
fieldName = `${fieldPrefix || ''}${field.name}`
fieldData = data[field.name]
}
@@ -147,8 +148,8 @@ export const traverseFields = ({
}
if (field.type === 'blocks') {
field.blocks.forEach(({ slug }) => {
blocksToDelete.add(toSnakeCase(slug))
field.blocks.forEach((block) => {
blocksToDelete.add(getTableName(block))
})
if (field.localized) {

View File

@@ -10,6 +10,14 @@ import type { NodePgDatabase, NodePgQueryResultHKT } from 'drizzle-orm/node-post
import type { PgColumn, PgEnum, PgTableWithColumns, PgTransaction } from 'drizzle-orm/pg-core'
import type { Payload } from 'payload'
import type { BaseDatabaseAdapter } from 'payload/database'
import type { BaseCollectionConfig } from 'payload/dist/collections/config/types'
import type {
BaseArrayField,
BaseBlock,
BaseRadioField,
BaseSelectField,
} from 'payload/dist/fields/config/types'
import type { BaseGlobalConfig } from 'payload/dist/globals/config/types'
import type { Pool, PoolConfig } from 'pg'
export type DrizzleDB = NodePgDatabase<Record<string, unknown>>
@@ -51,6 +59,11 @@ export type PostgresAdapter = BaseDatabaseAdapter & {
drizzle: DrizzleDB
logger: DrizzleConfig['logger']
enums: Record<string, GenericEnum>
/**
* An object keyed on each table, with a key value pair where the constraint name is the key, followed by the dot-notation field name
* Used for returning properly formed errors from unique fields
*/
fieldConstraints: Record<string, Record<string, string>>
pool: Pool
poolOptions: Args['pool']
push: boolean
@@ -64,11 +77,6 @@ export type PostgresAdapter = BaseDatabaseAdapter & {
}
}
tables: Record<string, GenericTable>
/**
* An object keyed on each table, with a key value pair where the constraint name is the key, followed by the dot-notation field name
* Used for returning properly formed errors from unique fields
*/
fieldConstraints: Record<string, Record<string, string>>
}
export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter
@@ -82,6 +90,7 @@ declare module 'payload' {
BaseDatabaseAdapter {
drizzle: DrizzleDB
enums: Record<string, GenericEnum>
fieldConstraints: Record<string, Record<string, string>>
pool: Pool
push: boolean
relations: Record<string, GenericRelation>
@@ -94,6 +103,53 @@ declare module 'payload' {
}
}
tables: Record<string, GenericTable>
fieldConstraints: Record<string, Record<string, string>>
}
}
declare module 'payload/types' {
export interface CollectionConfig extends BaseCollectionConfig {
/**
* Customize the SQL table name
*/
tableName?: string
}
export interface GlobalConfig extends BaseGlobalConfig {
/**
* Customize the SQL table name
*/
tableName?: string
}
export interface ArrayField extends BaseArrayField {
/**
* Customize the SQL table name
*/
tableName?: string
}
export interface RadioField extends BaseRadioField {
/**
* Customize the SQL enum name
*/
enumName?: string
}
export interface Block extends BaseBlock {
/**
* Customize the SQL table name
*/
tableName?: string
}
export interface SelectField extends BaseSelectField {
/**
* Customize the SQL enum name
*/
enumName?: string
/**
* Customize the SQL table name when using `hasMany: true`
*/
tableName?: string
}
}

View File

@@ -1,12 +1,12 @@
import type { UpdateOne } from 'payload/database'
import toSnakeCase from 'to-snake-case'
import type { ChainedMethods } from './find/chainMethods'
import { chainMethods } from './find/chainMethods'
import type { PostgresAdapter } from './types'
import { chainMethods } from './find/chainMethods'
import buildQuery from './queries/buildQuery'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export const updateOne: UpdateOne = async function updateOne(
this: PostgresAdapter,
@@ -14,7 +14,7 @@ export const updateOne: UpdateOne = async function updateOne(
) {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collection = this.payload.collections[collectionSlug].config
const tableName = toSnakeCase(collectionSlug)
const tableName = getTableName(collection)
const whereToUse = whereArg || { id: { equals: id } }
const { joinAliases, joins, selectFields, where } = await buildQuery({
@@ -70,8 +70,8 @@ export const updateOne: UpdateOne = async function updateOne(
db,
fields: collection.fields,
operation: 'update',
tableName: toSnakeCase(collectionSlug),
req,
tableName,
})
return result

View File

@@ -1,11 +1,10 @@
import type { UpdateGlobalArgs } from 'payload/database'
import type { PayloadRequest, TypeWithID } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function updateGlobal<T extends TypeWithID>(
this: PostgresAdapter,
@@ -13,7 +12,7 @@ export async function updateGlobal<T extends TypeWithID>(
): Promise<T> {
const db = this.sessions[req.transactionID]?.db || this.drizzle
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)
const tableName = toSnakeCase(slug)
const tableName = getTableName(globalConfig)
const existingGlobal = await db.query[tableName].findFirst({})
@@ -23,8 +22,8 @@ export async function updateGlobal<T extends TypeWithID>(
data,
db,
fields: globalConfig.fields,
tableName,
req,
tableName,
})
return result

View File

@@ -2,12 +2,12 @@ import type { TypeWithVersion, UpdateGlobalVersionArgs } from 'payload/database'
import type { PayloadRequest, SanitizedGlobalConfig, TypeWithID } from 'payload/types'
import { buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import buildQuery from './queries/buildQuery'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function updateGlobalVersion<T extends TypeWithID>(
this: PostgresAdapter,
@@ -25,7 +25,7 @@ export async function updateGlobalVersion<T extends TypeWithID>(
({ slug }) => slug === global,
)
const whereToUse = whereArg || { id: { equals: id } }
const tableName = `_${toSnakeCase(global)}_v`
const tableName = `_${getTableName(globalConfig)}_v`
const fields = buildVersionGlobalFields(globalConfig)
const { where } = await buildQuery({
@@ -43,9 +43,9 @@ export async function updateGlobalVersion<T extends TypeWithID>(
db,
fields,
operation: 'update',
req,
tableName,
where,
req,
})
return result

View File

@@ -2,12 +2,12 @@ import type { TypeWithVersion, UpdateVersionArgs } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload/types'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'
import buildQuery from './queries/buildQuery'
import { upsertRow } from './upsertRow'
import { getTableName } from './utilities/getTableName'
export async function updateVersion<T extends TypeWithID>(
this: PostgresAdapter,
@@ -23,7 +23,7 @@ export async function updateVersion<T extends TypeWithID>(
const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const whereToUse = whereArg || { id: { equals: id } }
const tableName = `_${toSnakeCase(collection)}_v`
const tableName = `_${getTableName(collectionConfig)}_v`
const fields = buildVersionCollectionFields(collectionConfig)
const { where } = await buildQuery({
@@ -41,9 +41,9 @@ export async function updateVersion<T extends TypeWithID>(
db,
fields,
operation: 'update',
req,
tableName,
where,
req,
})
return result

View File

@@ -0,0 +1,21 @@
import toSnakeCase from 'to-snake-case'
type Options = {
prefer: 'enumName' | 'tableName'
}
type EntityConfig = {
enumName?: string
name?: string
slug?: string
tableName?: string
}
export const getTableName = (
{ name, enumName, slug, tableName }: EntityConfig,
{ prefer }: Options = { prefer: 'tableName' },
) => {
const generated = toSnakeCase(name ?? slug)
const custom = prefer === 'tableName' ? tableName ?? enumName : enumName ?? tableName
return custom ?? generated
}

View File

@@ -159,6 +159,7 @@ const collectionSchema = joi.object().keys({
.try(joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
}),
slug: joi.string().required(),
tableName: joi.string(),
timestamps: joi.boolean(),
typescript: joi.object().keys({
interface: joi.string(),

View File

@@ -332,8 +332,7 @@ export type CollectionAdminOptions = {
useAsTitle?: string
}
/** Manage all aspects of a data collection */
export type CollectionConfig = {
export type BaseCollectionConfig = {
/**
* Access control
*/
@@ -426,6 +425,7 @@ export type CollectionConfig = {
* @default false // disable uploads
*/
upload?: IncomingUploadType | boolean
/**
* Customize the handling of incoming file uploads
*
@@ -434,6 +434,9 @@ export type CollectionConfig = {
versions?: IncomingCollectionVersions | boolean
}
/** Manage all aspects of a data collection */
export type CollectionConfig = BaseCollectionConfig
export interface SanitizedCollectionConfig
extends Omit<
DeepRequired<CollectionConfig>,

View File

@@ -196,6 +196,7 @@ export const select = baseField.keys({
defaultValue: joi
.alternatives()
.try(joi.string().allow(''), joi.array().items(joi.string().allow('')), joi.func()),
enumName: joi.string(),
hasMany: joi.boolean().default(false),
options: joi
.array()
@@ -212,6 +213,7 @@ export const select = baseField.keys({
),
)
.required(),
tableName: joi.string(),
type: joi.string().valid('select').required(),
})
@@ -225,6 +227,7 @@ export const radio = baseField.keys({
layout: joi.string().valid('vertical', 'horizontal'),
}),
defaultValue: joi.alternatives().try(joi.string().allow(''), joi.func()),
enumName: joi.string(),
options: joi
.array()
.min(1)
@@ -315,6 +318,7 @@ export const array = baseField.keys({
}),
maxRows: joi.number(),
minRows: joi.number(),
tableName: joi.string(),
type: joi.string().valid('array').required(),
})
@@ -416,6 +420,7 @@ export const blocks = baseField.keys({
.try(joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
}),
slug: joi.string().required(),
tableName: joi.string(),
custom: joi.object().pattern(joi.string(), joi.any()),
}),
)

View File

@@ -433,7 +433,7 @@ export type JSONField = Omit<FieldBase, 'admin'> & {
type: 'json'
}
export type SelectField = FieldBase & {
export type BaseSelectField = FieldBase & {
admin?: Admin & {
components?: {
Error?: React.ComponentType<ErrorProps>
@@ -447,6 +447,8 @@ export type SelectField = FieldBase & {
type: 'select'
}
export type SelectField = BaseSelectField
type SharedRelationshipProperties = FieldBase & {
filterOptions?: FilterOptions
hasMany?: boolean
@@ -528,7 +530,7 @@ export type RichTextField<
type: 'richText'
} & ExtraProperties
export type ArrayField = FieldBase & {
export type BaseArrayField = FieldBase & {
admin?: Admin & {
components?: {
RowLabel?: RowLabel
@@ -549,7 +551,9 @@ export type ArrayField = FieldBase & {
type: 'array'
}
export type RadioField = FieldBase & {
export type ArrayField = BaseArrayField
export type BaseRadioField = FieldBase & {
admin?: Admin & {
components?: {
Error?: React.ComponentType<ErrorProps>
@@ -561,6 +565,27 @@ export type RadioField = FieldBase & {
type: 'radio'
}
export type RadioField = BaseRadioField
export type BaseBlock = {
fields: Field[]
/** @deprecated - please migrate to the interfaceName property instead. */
graphQL?: {
singularName?: string
}
imageAltText?: string
imageURL?: string
/** Customize generated GraphQL and Typescript schema names.
* The slug is used by default.
*
* This is useful if you would like to generate a top level type to share amongst collections/fields.
* **Note**: Top level types can collide, ensure they are unique among collections, arrays, groups, blocks, tabs.
*/
interfaceName?: string
labels?: Labels
slug: string
}
export type Block = {
fields: Field[]
/** @deprecated - please migrate to the interfaceName property instead. */

View File

@@ -65,6 +65,7 @@ const globalSchema = joi
}),
label: joi.alternatives().try(joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
slug: joi.string().required(),
tableName: joi.string(),
typescript: joi.object().keys({
interface: joi.string(),
}),

View File

@@ -160,7 +160,7 @@ export type GlobalAdminOptions = {
preview?: GeneratePreviewURL
}
export type GlobalConfig = {
export type BaseGlobalConfig = {
access?: {
read?: Access
readDrafts?: Access
@@ -198,6 +198,8 @@ export type GlobalConfig = {
versions?: IncomingGlobalVersions | boolean
}
export type GlobalConfig = BaseGlobalConfig
export interface SanitizedGlobalConfig
extends Omit<DeepRequired<GlobalConfig>, 'endpoints' | 'fields' | 'versions'> {
endpoints: Omit<Endpoint, 'root'>[] | false

View File

@@ -63,7 +63,95 @@ export default buildConfigWithDefaults({
},
slug: 'relation-b',
},
{
fields: [
{
name: 'text',
type: 'text',
},
{
name: 'localizedText',
localized: true,
type: 'text',
},
{
name: 'relationship',
hasMany: true,
relationTo: 'relation-a',
type: 'relationship',
},
{
name: 'select',
enumName: 'selectEnum',
hasMany: true,
options: ['a', 'b', 'c'],
tableName: 'customSelect',
type: 'select',
},
{
name: 'radio',
enumName: 'radioEnum',
options: ['a', 'b', 'c'],
type: 'select',
},
{
name: 'array',
fields: [
{
name: 'text',
type: 'text',
},
{
name: 'localizedText',
localized: true,
type: 'text',
},
],
tableName: 'customArrays',
type: 'array',
},
{
name: 'blocks',
blocks: [
{
fields: [
{
name: 'text',
type: 'text',
},
{
name: 'localizedText',
localized: true,
type: 'text',
},
],
slug: 'block',
tableName: 'customBlocks',
},
],
type: 'blocks',
},
],
slug: 'custom-schema',
tableName: 'customs',
},
],
globals: [
{
fields: [
{
name: 'text',
type: 'text',
},
],
slug: 'global',
tableName: 'customGlobal',
},
],
localization: {
defaultLocale: 'en',
locales: ['en', 'es'],
},
onInit: async (payload) => {
await payload.create({
collection: 'users',

View File

@@ -1,5 +1,6 @@
import { GraphQLClient } from 'graphql-request'
import type { PostgresAdapter } from '../../packages/db-postgres/src/types'
import type { TypeWithID } from '../../packages/payload/src/collections/config/types'
import type { PayloadRequest } from '../../packages/payload/src/express/types'
@@ -16,12 +17,16 @@ describe('database', () => {
const collection = 'posts'
const title = 'title'
let user: TypeWithID & Record<string, unknown>
let checkSchema = true
beforeAll(async () => {
const init = await initPayloadTest({ __dirname, init: { local: false } })
serverURL = init.serverURL
const url = `${serverURL}/api/graphql`
client = new GraphQLClient(url)
if (payload.db.name === 'mongoose') {
checkSchema = false
}
const loginResult = await payload.login({
collection: 'users',
@@ -35,6 +40,46 @@ describe('database', () => {
user = loginResult.user
})
describe('schema', () => {
it('should use custom tableNames', () => {
const db: PostgresAdapter = payload.db
expect(db).toBeDefined()
if (checkSchema) {
// collection
expect(db.tables['customs']).toBeDefined()
// collection relationships
expect(db.tables.customs_rels).toBeDefined()
// collection localized
expect(db.tables.customs_locales).toBeDefined()
// global
expect(db.tables.customGlobal).toBeDefined()
// select
expect(db.tables.customs_customSelect).toBeDefined()
// array
expect(db.tables.customs_customArrays).toBeDefined()
// array localized
expect(db.tables.customs_customArrays_locales).toBeDefined()
// blocks
expect(db.tables.customs_blocks_customBlocks).toBeDefined()
// localized blocks
expect(db.tables.customs_blocks_customBlocks_locales).toBeDefined()
// enum names
expect(db.enums.enum_customs_selectEnum).toBeDefined()
expect(db.enums.enum_customs_radioEnum).toBeDefined()
}
})
})
describe('transactions', () => {
describe('local api', () => {
it('should commit multiple operations in isolation', async () => {