chore: fix imports postgres

This commit is contained in:
Dan Ribbens
2023-09-14 14:46:27 -04:00
parent 9575ec5319
commit 16d314ff49
44 changed files with 430 additions and 425 deletions

View File

@@ -6,6 +6,12 @@ module.exports = {
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/no-redundant-type-constituents': 'off',
},
},
],
parserOptions: {
project: ['./tsconfig.json'],

View File

@@ -1,21 +1,21 @@
import fs from 'fs';
import { v4 as uuid } from 'uuid';
import type { Connect } from 'payload/database';
import { generateDrizzleJson, pushSchema } from 'drizzle-kit/utils';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import type { Connect } from 'payload/dist/database/types';
import { Client, Pool } from 'pg';
import { generateDrizzleJson, pushSchema } from 'drizzle-kit/utils';
import { configToJSONSchema } from 'payload/dist/utilities/configToJSONSchema';
import prompts from 'prompts';
import { jsonb, numeric, pgTable, varchar } from 'drizzle-orm/pg-core';
import type { PostgresAdapter } from './types';
import { DrizzleDB } from './types';
import fs from 'fs';
import { configToJSONSchema } from 'payload/utilities';
import { Client, Pool } from 'pg';
import prompts from 'prompts';
import { v4 as uuid } from 'uuid';
import type { DrizzleDB, PostgresAdapter } from './types';
// Migration table def in order to use query using drizzle
const migrationsSchema = pgTable('payload_migrations', {
name: varchar('name'),
batch: numeric('batch'),
name: varchar('name'),
schema: jsonb('schema'),
});
@@ -67,13 +67,13 @@ export const connect: Connect = async function connect(
if (process.env.NODE_ENV === 'production') return;
// This will prompt if clarifications are needed for Drizzle to push new schema
const { hasDataLoss, warnings, statementsToExecute, apply } = await pushSchema(this.schema, this.db);
const { apply, hasDataLoss, statementsToExecute, warnings } = await pushSchema(this.schema, this.db);
this.payload.logger.debug({
msg: 'Schema push results',
hasDataLoss,
warnings,
msg: 'Schema push results',
statementsToExecute,
warnings,
});
if (warnings.length) {
@@ -90,10 +90,10 @@ export const connect: Connect = async function connect(
const { confirm: acceptWarnings } = await prompts(
{
type: 'confirm',
name: 'confirm',
message: 'Accept warnings and push schema to database?',
initial: false,
message: 'Accept warnings and push schema to database?',
name: 'confirm',
type: 'confirm',
},
{
onCancel: () => {
@@ -134,8 +134,8 @@ export const connect: Connect = async function connect(
if (!devPush.length) {
await this.db.insert(migrationsSchema).values({
name: 'dev',
batch: '-1',
name: 'dev',
schema: JSON.stringify(jsonSchema),
});
} else {

View File

@@ -1,5 +1,7 @@
import { Create } from 'payload/dist/database/types';
import type { Create } from 'payload/database';
import toSnakeCase from 'to-snake-case';
import { upsertRow } from '../upsertRow';
export const create: Create = async function create({

View File

@@ -1,12 +1,15 @@
import { PayloadRequest } from 'payload/types';
import type { CreateGlobal } from 'payload/database';
import type { PayloadRequest } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { CreateGlobal } from 'payload/dist/database/types';
import type { PostgresAdapter } from './types';
import { upsertRow } from './upsertRow';
import { PostgresAdapter } from './types';
export const createGlobal: CreateGlobal = async function createGlobal(
this: PostgresAdapter,
{ data, slug, req = {} as PayloadRequest },
{ data, req = {} as PayloadRequest, slug },
) {
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug);
@@ -14,7 +17,6 @@ export const createGlobal: CreateGlobal = async function createGlobal(
adapter: this,
data,
fields: globalConfig.fields,
locale: req.locale,
operation: 'create',
tableName: toSnakeCase(slug),
});

View File

@@ -1,18 +1,21 @@
import type { CreateVersion } from 'payload/dist/database/types';
import { buildVersionCollectionFields } from 'payload/dist/versions/buildCollectionFields';
import type { CreateVersion } from 'payload/database';
import { buildVersionCollectionFields } from 'payload/versions';
import toSnakeCase from 'to-snake-case';
import type { PostgresAdapter } from './types';
import { upsertRow } from './upsertRow';
export const createVersion: CreateVersion = async function createVersion(
this: PostgresAdapter,
{
collectionSlug,
parent,
versionData,
autosave,
collectionSlug,
createdAt,
parent,
updatedAt,
versionData,
},
) {
const collection = this.payload.collections[collectionSlug].config;
@@ -21,10 +24,10 @@ export const createVersion: CreateVersion = async function createVersion(
const result = await upsertRow({
adapter: this,
data: {
parent,
latest: true,
autosave,
createdAt,
latest: true,
parent,
updatedAt,
version: versionData,
},

View File

@@ -1,16 +1,19 @@
import { DeleteMany } from 'payload/dist/database/types';
import { PayloadRequest } from 'payload/dist/express/types';
import type { DeleteMany } from 'payload/database';
import type { PayloadRequest } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { PostgresAdapter } from './types';
import buildQuery from './queries/buildQuery';
import type { PostgresAdapter } from './types';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
export const deleteMany: DeleteMany = async function deleteMany(this: PostgresAdapter,
{
collection,
where: incomingWhere,
req = {} as PayloadRequest,
where: incomingWhere,
}) {
const collectionConfig = this.payload.collections[collection].config;
const tableName = toSnakeCase(collection);
@@ -18,8 +21,8 @@ export const deleteMany: DeleteMany = async function deleteMany(this: PostgresAd
const { where } = await buildQuery({
adapter: this,
fields: collectionConfig.fields,
where: incomingWhere,
tableName,
where: incomingWhere,
});
const findManyArgs = buildFindManyArgs({

View File

@@ -1,17 +1,20 @@
import { DeleteOne } from 'payload/dist/database/types';
import { PayloadRequest } from 'payload/dist/express/types';
import type { DeleteOne } from 'payload/database';
import type { PayloadRequest } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { PostgresAdapter } from './types';
import buildQuery from './queries/buildQuery';
import type { PostgresAdapter } from './types';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
export const deleteOne: DeleteOne = async function deleteOne(
this: PostgresAdapter,
{
collection,
where: incomingWhere,
req = {} as PayloadRequest,
where: incomingWhere,
},
) {
const collectionConfig = this.payload.collections[collection].config;

View File

@@ -1,23 +1,25 @@
import type { Find } from 'payload/database';
import type { PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload/types';
import { asc, desc, inArray, sql } from 'drizzle-orm';
import toSnakeCase from 'to-snake-case';
import type { Find } from 'payload/dist/database/types';
import type { PayloadRequest } from 'payload/dist/express/types';
import type { SanitizedCollectionConfig, TypeWithID } from 'payload/dist/collections/config/types';
import buildQuery from './queries/buildQuery';
import type { PostgresAdapter } from './types';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
import { PostgresAdapter } from './types';
export const find: Find = async function find(
this: PostgresAdapter, {
collection,
where: whereArg,
page = 1,
limit: limitArg,
sort: sortArg,
locale,
page = 1,
pagination,
req = {} as PayloadRequest,
sort: sortArg,
where: whereArg,
},
) {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config;
@@ -33,17 +35,17 @@ export const find: Find = async function find(
let selectDistinctResult;
const {
where,
orderBy,
joins,
orderBy,
selectFields,
where,
} = await buildQuery({
adapter: this,
fields: collectionConfig.fields,
locale,
where: whereArg,
sort,
tableName,
where: whereArg,
});
const orderedIDMap: Record<number | string, number> = {};
@@ -80,15 +82,15 @@ export const find: Find = async function find(
if (selectDistinctResult.length === 0) {
return {
docs: [],
totalDocs: 0,
hasNextPage: false,
hasPrevPage: false,
limit,
totalPages: 0,
nextPage: null,
page: 1,
pagingCounter: 0,
hasPrevPage: false,
hasNextPage: false,
prevPage: null,
nextPage: null,
totalDocs: 0,
totalPages: 0,
};
}
// set the id in an object for sorting later
@@ -157,14 +159,14 @@ export const find: Find = async function find(
return {
docs,
totalDocs,
hasNextPage,
hasPrevPage,
limit,
totalPages,
nextPage: hasNextPage ? page + 1 : null,
page,
pagingCounter,
hasPrevPage,
hasNextPage,
prevPage: hasPrevPage ? page - 1 : null,
nextPage: hasNextPage ? page + 1 : null,
totalDocs,
totalPages,
};
};

View File

@@ -1,7 +1,9 @@
import { ArrayField, Block, Field } from 'payload/types';
import { DBQueryConfig } from 'drizzle-orm';
import type { DBQueryConfig } from 'drizzle-orm';
import type { ArrayField, Block, Field } from 'payload/types';
import type { PostgresAdapter } from '../types';
import { traverseFields } from './traverseFields';
import { PostgresAdapter } from '../types';
type BuildFindQueryArgs = {
adapter: PostgresAdapter
@@ -26,18 +28,18 @@ export const buildFindManyArgs = ({
const _locales: Result = {
columns: {
id: false,
_parentID: false,
id: false,
},
};
if (adapter.tables[`${tableName}_relationships`]) {
result.with._relationships = {
orderBy: ({ order }, { asc: ASC }) => [ASC(order)],
columns: {
id: false,
parent: false,
},
orderBy: ({ order }, { asc: ASC }) => [ASC(order)],
};
}
@@ -49,12 +51,12 @@ export const buildFindManyArgs = ({
const locatedArrays: { [path: string]: ArrayField } = {};
traverseFields({
_locales,
adapter,
currentArgs: result,
currentTableName: tableName,
depth,
fields,
_locales,
locatedArrays,
locatedBlocks,
path: '',

View File

@@ -1,41 +0,0 @@
/* eslint-disable no-param-reassign */
import { SanitizedConfig } from 'payload/config';
import { buildFindManyArgs } from './buildFindManyArgs';
import { PostgresAdapter } from '../types';
type BuildWithFromDepthArgs = {
adapter: PostgresAdapter
config: SanitizedConfig
depth: number
fallbackLocale?: string | false
locale?: string
}
export const buildWithFromDepth = ({
adapter,
config,
depth,
fallbackLocale,
locale,
}: BuildWithFromDepthArgs): Record<string, unknown> | undefined => {
const result = config.collections.reduce((slugs, coll) => {
const { slug } = coll;
if (depth >= 1) {
const args = buildFindManyArgs({
adapter,
config,
collection: coll,
depth: depth - 1,
fallbackLocale,
locale,
});
slugs[`${slug}ID`] = args;
}
return slugs;
}, {});
return result;
};

View File

@@ -1,17 +1,19 @@
/* eslint-disable no-param-reassign */
import type { ArrayField, Block, Field } from 'payload/types';
import { fieldAffectsData } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { fieldAffectsData } from 'payload/dist/fields/config/types';
import { ArrayField, Block, Field } from 'payload/types';
import { Result } from './buildFindManyArgs';
import { PostgresAdapter } from '../types';
import type { PostgresAdapter } from '../tyfpes';
import type { Result } from './buildFindManyArgs';
type TraverseFieldArgs = {
_locales: Record<string, unknown>
adapter: PostgresAdapter
currentArgs: Record<string, unknown>,
currentTableName: string
depth?: number,
fields: Field[]
_locales: Record<string, unknown>
locatedArrays: { [path: string]: ArrayField },
locatedBlocks: Block[],
path: string,
@@ -20,12 +22,12 @@ type TraverseFieldArgs = {
}
export const traverseFields = ({
_locales,
adapter,
currentArgs,
currentTableName,
depth,
fields,
_locales,
locatedArrays,
locatedBlocks,
path,
@@ -37,11 +39,11 @@ export const traverseFields = ({
switch (field.type) {
case 'array': {
const withArray: Result = {
orderBy: ({ _order }, { asc }) => [asc(_order)],
columns: {
_parentID: false,
_order: false,
_parentID: false,
},
orderBy: ({ _order }, { asc }) => [asc(_order)],
with: {},
};
@@ -51,12 +53,12 @@ export const traverseFields = ({
currentArgs.with[`${path}${field.name}`] = withArray;
traverseFields({
_locales,
adapter,
currentArgs: withArray,
currentTableName: arrayTableName,
depth,
fields: field.fields,
_locales,
locatedArrays,
locatedBlocks,
path: '',
@@ -84,12 +86,12 @@ export const traverseFields = ({
topLevelArgs.with[blockKey] = withBlock;
traverseFields({
_locales,
adapter,
currentArgs: withBlock,
currentTableName,
depth,
fields: block.fields,
_locales,
locatedArrays,
locatedBlocks,
path,
@@ -103,12 +105,12 @@ export const traverseFields = ({
case 'group':
traverseFields({
_locales,
adapter,
currentArgs,
currentTableName,
depth,
fields: field.fields,
_locales,
locatedArrays,
locatedBlocks,
path: `${path}${field.name}_`,

View File

@@ -1,21 +1,25 @@
import type { FindGlobal } from 'payload/database';
import toSnakeCase from 'to-snake-case';
import type { FindGlobal } from 'payload/dist/database/types';
import buildQuery from './queries/buildQuery';
import type { PostgresAdapter } from './types';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
import { PostgresAdapter } from './types';
export const findGlobal: FindGlobal = async function findGlobal(
this: PostgresAdapter,
{ slug, locale, where },
{ locale, slug, where },
) {
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug);
const tableName = toSnakeCase(slug);
const query = await buildQuery({
adapter: this,
globalSlug: slug,
fields: globalConfig.fields,
locale,
tableName,
where,
});

View File

@@ -1,16 +1,17 @@
import type { FindOne } from 'payload/database';
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import type { FindOne } from 'payload/dist/database/types';
import type { PayloadRequest } from 'payload/dist/express/types';
import type { SanitizedCollectionConfig } from 'payload/dist/collections/config/types';
import buildQuery from './queries/buildQuery';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
export const findOne: FindOne = async function findOne({
collection,
where: incomingWhere,
locale,
req = {} as PayloadRequest,
where: incomingWhere,
}) {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config;
const tableName = toSnakeCase(collection);
@@ -18,8 +19,8 @@ export const findOne: FindOne = async function findOne({
const { where } = await buildQuery({
adapter: this,
fields: collectionConfig.fields,
tableName,
locale,
tableName,
where: incomingWhere,
});

View File

@@ -1,28 +1,30 @@
import type { Payload } from 'payload';
import { createDatabaseAdapter } from 'payload/dist/database/createAdapter';
import type { Args, PostgresAdapter, PostgresAdapterResult } from './types';
import { connect } from './connect';
import { init } from './init';
import { createMigration } from './createMigration';
import { webpack } from './webpack';
import { Args, PostgresAdapter, PostgresAdapterResult } from './types';
import { createGlobal } from './createGlobal';
import { createMigration } from './createMigration';
import { createVersion } from './createVersion';
import { beginTransaction } from './transactions/beginTransaction';
import { rollbackTransaction } from './transactions/rollbackTransaction';
import { commitTransaction } from './transactions/commitTransaction';
import { queryDrafts } from './queryDrafts';
import { find } from './find';
import { init } from './init';
import { queryDrafts } from './queryDrafts';
import { beginTransaction } from './transactions/beginTransaction';
import { commitTransaction } from './transactions/commitTransaction';
import { rollbackTransaction } from './transactions/rollbackTransaction';
import { webpack } from './webpack';
// import { findGlobalVersions } from './findGlobalVersions';
// import { findVersions } from './findVersions';
import { create } from './create';
// import { updateVersion } from './updateVersion';
import { deleteMany } from './deleteMany';
import { deleteOne } from './deleteOne';
// import { deleteVersions } from './deleteVersions';
import { findGlobal } from './findGlobal';
import { findOne } from './findOne';
import { updateGlobal } from './updateGlobal';
import { updateOne } from './update';
// import { updateVersion } from './updateVersion';
import { deleteMany } from './deleteMany';
import { updateGlobal } from './updateGlobal';
// import { destroy } from './destroy';
export function postgresAdapter(args: Args): PostgresAdapterResult {
@@ -31,33 +33,33 @@ export function postgresAdapter(args: Args): PostgresAdapterResult {
// @ts-expect-error
return createDatabaseAdapter<PostgresAdapter>({
...args,
sessions: {},
enums: {},
relations: {},
tables: {},
payload,
connect,
db: undefined,
// destroy,
init,
webpack,
createMigration,
beginTransaction,
rollbackTransaction,
commitTransaction,
queryDrafts,
findOne,
find,
connect,
create,
updateOne,
deleteOne,
deleteMany,
findGlobal,
createGlobal,
updateGlobal,
// findVersions,
createMigration,
// findGlobalVersions,
createVersion,
db: undefined,
deleteMany,
deleteOne,
enums: {},
find,
findGlobal,
findOne,
// destroy,
init,
payload,
queryDrafts,
relations: {},
rollbackTransaction,
sessions: {},
tables: {},
updateGlobal,
updateOne,
// findVersions,
webpack,
// updateVersion,
// deleteVersions,
});

View File

@@ -1,13 +1,15 @@
/* eslint-disable no-param-reassign */
import type { Init } from 'payload/database';
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 { SanitizedCollectionConfig } from 'payload/dist/collections/config/types';
import type { Init } from 'payload/dist/database/types';
import { buildVersionGlobalFields } from 'payload/dist/versions/buildGlobalFields';
import { buildVersionCollectionFields } from 'payload/dist/versions/buildCollectionFields';
import { buildTable } from './schema/build';
import type { PostgresAdapter } from './types';
import { buildTable } from './schema/build';
export const init: Init = async function init(this: PostgresAdapter) {
if (this.payload.config.localization) {
this.enums._locales = pgEnum(

View File

@@ -1,28 +1,29 @@
import { Where } from 'payload/types';
import { Field } from 'payload/dist/fields/config/types';
import { SQL } from 'drizzle-orm';
import type { SQL } from 'drizzle-orm';
import type { Field, Where } from 'payload/types';
import type { GenericColumn, PostgresAdapter } from '../types';
import type { BuildQueryJoins } from './buildQuery';
import { parseParams } from './parseParams';
import { GenericColumn, PostgresAdapter } from '../types';
import { BuildQueryJoins } from './buildQuery';
export async function buildAndOrConditions({
joins,
where,
adapter,
locale,
fields,
tableName,
joins,
locale,
selectFields,
tableName,
where,
}: {
joins: BuildQueryJoins,
where: Where[],
collectionSlug?: string,
globalSlug?: string,
adapter: PostgresAdapter
locale?: string,
collectionSlug?: string,
fields: Field[],
tableName: string,
globalSlug?: string,
joins: BuildQueryJoins,
locale?: string,
selectFields: Record<string, GenericColumn>
tableName: string,
where: Where[],
}): Promise<SQL[]> {
const completedConditions = [];
// Loop over all AND / OR operations and add them to the AND / OR query param
@@ -33,13 +34,13 @@ export async function buildAndOrConditions({
if (typeof condition === 'object') {
// eslint-disable-next-line no-await-in-loop
const result = await parseParams({
joins,
where: condition,
adapter,
locale,
fields,
tableName,
joins,
locale,
selectFields,
tableName,
where: condition,
});
if (result && Object.keys(result).length > 0) {
completedConditions.push(result);

View File

@@ -1,9 +1,12 @@
import { Where } from 'payload/dist/types';
import { Field } from 'payload/dist/fields/config/types';
import { asc, desc, SQL } from 'drizzle-orm';
import { parseParams } from './parseParams';
import { GenericColumn, PostgresAdapter } from '../types';
import type { SQL } from 'drizzle-orm';
import type { Field, Where } from 'payload/types';
import { asc, desc } from 'drizzle-orm';
import type { GenericColumn, PostgresAdapter } from '../types';
import { getTableColumnFromPath } from './getTableColumnFromPath';
import { parseParams } from './parseParams';
export type BuildQueryJoins = Record<string, SQL>
@@ -17,13 +20,13 @@ type BuildQueryArgs = {
}
type Result = {
where: SQL
joins: BuildQueryJoins
orderBy: {
column: GenericColumn
order: typeof asc | typeof desc
}
joins: BuildQueryJoins
selectFields: Record<string, GenericColumn>
where: SQL
}
const buildQuery = async function buildQuery({
adapter,
@@ -54,16 +57,16 @@ const buildQuery = async function buildQuery({
}
const {
table: sortTable,
columnName: sortTableColumnName,
table: sortTable,
} = getTableColumnFromPath({
adapter,
collectionPath: sortPath,
fields,
pathSegments: sortPath.split('.'),
joins,
selectFields,
locale,
pathSegments: sortPath.split('.'),
selectFields,
tableName,
});
@@ -82,17 +85,17 @@ const buildQuery = async function buildQuery({
fields,
joins,
locale,
selectFields,
tableName,
where: incomingWhere,
selectFields,
});
}
return {
joins,
orderBy,
where,
selectFields,
where,
};
};

View File

@@ -1,24 +1,28 @@
/* eslint-disable no-param-reassign */
import { Field, FieldAffectingData, fieldAffectsData, TabAsField, tabHasName } from 'payload/dist/fields/config/types';
import toSnakeCase from 'to-snake-case';
import { and, eq, SQL, sql } from 'drizzle-orm';
import type { SQL } from 'drizzle-orm';
import type { Field, FieldAffectingData, TabAsField } from 'payload/types';
import { and, eq, sql } from 'drizzle-orm';
import { APIError } from 'payload/errors';
import flattenFields from 'payload/dist/utilities/flattenTopLevelFields';
import { BuildQueryJoins } from './buildQuery';
import { GenericColumn, GenericTable, PostgresAdapter } from '../types';
import { fieldAffectsData, tabHasName } from 'payload/types';
import { flattenTopLevelFields } from 'payload/utilities';
import toSnakeCase from 'to-snake-case';
import type { GenericColumn, GenericTable, PostgresAdapter } from '../types';
import type { BuildQueryJoins } from './buildQuery';
type Constraint = {
table: GenericTable
columnName: string
table: GenericTable
value: unknown
}
type TableColumn = {
table: GenericTable
columnName?: string
constraints: Constraint[]
field: FieldAffectingData
rawColumn?: SQL
table: GenericTable
}
type Args = {
@@ -28,9 +32,9 @@ type Args = {
constraints?: Constraint[]
fields: (Field | TabAsField)[]
joins: BuildQueryJoins
selectFields: Record<string, GenericColumn>
locale?: string
pathSegments: string[]
selectFields: Record<string, GenericColumn>
tableName: string
}
/**
@@ -45,13 +49,13 @@ export const getTableColumnFromPath = ({
constraints = [],
fields,
joins,
selectFields,
locale,
pathSegments,
selectFields,
tableName,
}: Args): TableColumn => {
const fieldPath = pathSegments[0];
const field = flattenFields(fields as Field[])
const field = flattenTopLevelFields(fields as Field[])
.find((fieldToFind) => fieldAffectsData(fieldToFind) && fieldToFind.name === fieldPath) as Field | TabAsField;
let newTableName = tableName;
@@ -83,8 +87,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}
case 'tab': {
@@ -98,8 +102,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}
return getTableColumnFromPath({
@@ -111,8 +115,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}
@@ -130,8 +134,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}
@@ -153,8 +157,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}
@@ -185,19 +189,19 @@ export const getTableColumnFromPath = ({
joins[newTableName] = eq(adapter.tables[newTableName].id, adapter.tables[`${tableName}_relationships`][`${field.relationTo}ID`]);
if (newCollectionPath === '') {
return {
table: adapter.tables[relationTableName],
columnName: `${field.relationTo}ID`,
constraints,
field,
columnName: `${field.relationTo}ID`,
table: adapter.tables[relationTableName],
};
}
} else if (newCollectionPath === 'value') {
const tableColumnsNames = field.relationTo.map((relationTo) => `"${relationTableName}"."${toSnakeCase(relationTo)}_id"`);
return {
table: adapter.tables[relationTableName],
constraints,
field,
rawColumn: sql.raw(`COALESCE(${tableColumnsNames.join(', ')})`),
table: adapter.tables[relationTableName],
};
} else {
throw new APIError('Not supported');
@@ -211,8 +215,8 @@ export const getTableColumnFromPath = ({
joins,
locale,
pathSegments: pathSegments.slice(1),
tableName: newTableName,
selectFields,
tableName: newTableName,
});
}

View File

@@ -1,23 +1,22 @@
import { and, eq, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, ne, notInArray, or } from 'drizzle-orm';
export const operatorMap = {
greater_than_equal: gte,
less_than_equal: lte,
less_than: lt,
greater_than: gt,
in: inArray,
like: ilike,
// TODO:
// all: all,
not_in: notInArray,
not_equals: ne,
exists: isNotNull,
isNull, // handles exists: false
// intersects: intersects,
and,
equals: eq,
exists: isNotNull,
greater_than: gt,
greater_than_equal: gte,
in: inArray,
isNull, // handles exists: false
less_than: lt,
less_than_equal: lte,
like: ilike,
not_equals: ne,
// TODO: geojson queries
// near: near,
// within: within,
// intersects: intersects,
and,
// all: all,
not_in: notInArray,
or,
};

View File

@@ -1,34 +1,36 @@
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
import { Operator, Where } from 'payload/types';
import { Field } from 'payload/dist/fields/config/types';
import { validOperators } from 'payload/dist/types/constants';
import { and, SQL } from 'drizzle-orm';
import type { SQL } from 'drizzle-orm';
import type { Field, Operator, Where } from 'payload/types';
import { and } from 'drizzle-orm';
import { validOperators } from 'payload/types';
import type { GenericColumn, PostgresAdapter } from '../types';
import type { BuildQueryJoins } from './buildQuery';
import { buildAndOrConditions } from './buildAndOrConditions';
import { GenericColumn, PostgresAdapter } from '../types';
import { operatorMap } from './operatorMap';
import { BuildQueryJoins } from './buildQuery';
import { getTableColumnFromPath } from './getTableColumnFromPath';
import { operatorMap } from './operatorMap';
import { sanitizeQueryValue } from './sanitizeQueryValue';
type Args = {
joins: BuildQueryJoins
where: Where
adapter: PostgresAdapter
locale: string
tableName: string
fields: Field[]
joins: BuildQueryJoins
locale: string
selectFields: Record<string, GenericColumn>
tableName: string
where: Where
}
export async function parseParams({
joins,
where,
adapter,
locale,
fields,
tableName,
joins,
locale,
selectFields,
tableName,
where,
}: Args): Promise<SQL> {
let result: SQL;
const constraints: SQL[] = [];
@@ -46,13 +48,13 @@ export async function parseParams({
}
if (Array.isArray(condition)) {
const builtConditions = await buildAndOrConditions({
joins,
fields,
adapter,
fields,
joins,
locale,
selectFields,
tableName,
where: condition,
selectFields,
});
if (builtConditions.length > 0) {
if (result) {
@@ -70,11 +72,11 @@ export async function parseParams({
for (const operator of Object.keys(pathOperators)) {
if (validOperators.includes(operator as Operator)) {
const {
field,
table,
columnName,
constraints: queryConstraints,
field,
rawColumn,
table,
} = getTableColumnFromPath({
adapter,
collectionPath: relationOrPath,
@@ -82,8 +84,8 @@ export async function parseParams({
joins,
locale,
pathSegments: relationOrPath.split('.'),
tableName,
selectFields,
tableName,
});
const { operator: queryOperator, value: queryValue } = sanitizeQueryValue({
@@ -93,8 +95,8 @@ export async function parseParams({
});
queryConstraints.forEach(({
table: constraintTable,
columnName: col,
table: constraintTable,
value,
}) => {
constraints.push(operatorMap.equals(constraintTable[col], value));

View File

@@ -1,6 +1,7 @@
import { Field, TabAsField } from 'payload/dist/fields/config/types';
import { createArrayFromCommaDelineated } from 'payload/dist/utilities/createArrayFromCommaDelineated';
import type { Field, TabAsField } from 'payload/types';
import { APIError } from 'payload/errors';
import { createArrayFromCommaDelineated } from 'payload/utilities';
type SanitizeQueryValueArgs = {
field: Field | TabAsField
@@ -37,7 +38,7 @@ export const sanitizeQueryValue = ({ field, operator: operatorArg, val }: Saniti
if (val.toLowerCase() === 'false') formattedValue = false;
}
if (['all', 'not_in', 'in'].includes(operator) && typeof formattedValue === 'string') {
if (['all', 'in', 'not_in'].includes(operator) && typeof formattedValue === 'string') {
formattedValue = createArrayFromCommaDelineated(formattedValue);
if (field.type === 'number') {

View File

@@ -1,22 +1,23 @@
import type { QueryDrafts } from 'payload/database';
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types';
import { sql } from 'drizzle-orm';
import { buildVersionCollectionFields } from 'payload/versions';
import toSnakeCase from 'to-snake-case';
import type { QueryDrafts } from 'payload/dist/database/types';
import type { PayloadRequest } from 'payload/dist/express/types';
import type { SanitizedCollectionConfig } from 'payload/dist/collections/config/types';
import { buildVersionCollectionFields } from 'payload/dist/versions/buildCollectionFields';
import buildQuery from './queries/buildQuery';
import { buildFindManyArgs } from './find/buildFindManyArgs';
import buildQuery from './queries/buildQuery';
import { transform } from './transform/read';
export const queryDrafts: QueryDrafts = async function queryDrafts({
collection,
where,
page = 1,
limit: limitArg,
sort: sortArg,
locale,
page = 1,
pagination,
req = {} as PayloadRequest,
sort: sortArg,
where,
}) {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config;
const tableName = toSnakeCase(collection);
@@ -33,11 +34,12 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
let pagingCounter;
const query = await buildQuery({
collectionSlug: collection,
versionsFields: buildVersionCollectionFields(collectionConfig),
adapter: this,
fields: buildVersionCollectionFields(collectionConfig),
locale,
where,
sort,
tableName: versionsTableName,
where
});
if (pagination !== false) {
@@ -72,14 +74,14 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
return {
docs, // : T[]
totalDocs, // : number
hasNextPage, // : boolean
hasPrevPage, // : boolean
limit, // : number
totalPages, // : number
nextPage: hasNextPage ? page + 1 : null, // ?: number | null | undefined
page, // ?: number
pagingCounter, // : number
hasPrevPage, // : boolean
hasNextPage, // : boolean
prevPage: hasPrevPage ? page - 1 : null, // ?: number | null | undefined
nextPage: hasNextPage ? page + 1 : null, // ?: number | null | undefined
totalDocs, // : number
totalPages, // : number
};
};

View File

@@ -1,28 +1,21 @@
/* eslint-disable no-param-reassign */
import {
AnyPgColumnBuilder,
integer,
pgTable,
serial,
varchar,
index,
numeric,
timestamp,
IndexBuilder,
unique,
UniqueConstraintBuilder,
} from 'drizzle-orm/pg-core';
import { Field } from 'payload/types';
import type { Relation } from 'drizzle-orm';
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core';
import type { Field } from 'payload/types';
import { relations } from 'drizzle-orm';
import { index, integer, numeric, pgTable, serial, timestamp, unique, varchar, } from 'drizzle-orm/pg-core';
import { fieldAffectsData } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { Relation, relations } from 'drizzle-orm';
import { fieldAffectsData } from 'payload/dist/fields/config/types';
import { GenericColumns, GenericTable, PostgresAdapter } from '../types';
import { traverseFields } from './traverseFields';
import type { GenericColumns, GenericTable, PostgresAdapter } from '../types';
import { parentIDColumnMap } from './parentIDColumnMap';
import { traverseFields } from './traverseFields';
type Args = {
adapter: PostgresAdapter
baseColumns?: Record<string, AnyPgColumnBuilder>,
baseColumns?: Record<string, PgColumnBuilder>,
baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder>
buildRelationships?: boolean
fields: Field[]
@@ -43,12 +36,12 @@ export const buildTable = ({
tableName,
timestamps,
}: Args): Result => {
const columns: Record<string, AnyPgColumnBuilder> = baseColumns;
const columns: Record<string, PgColumnBuilder> = baseColumns;
const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {};
let hasLocalizedField = false;
let hasLocalizedRelationshipField = false;
const localesColumns: Record<string, AnyPgColumnBuilder> = {};
const localesColumns: Record<string, PgColumnBuilder> = {};
const localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {};
let localesTable: GenericTable;
@@ -136,11 +129,11 @@ export const buildTable = ({
if (buildRelationships) {
if (relationships.size) {
const relationshipColumns: Record<string, AnyPgColumnBuilder> = {
const relationshipColumns: Record<string, PgColumnBuilder> = {
id: serial('id').primaryKey(),
order: integer('order'),
parent: parentIDColumnMap[idColType]('parent_id').references(() => table.id, { onDelete: 'cascade' }).notNull(),
path: varchar('path').notNull(),
order: integer('order'),
};
if (hasLocalizedRelationshipField) {
@@ -177,9 +170,9 @@ export const buildTable = ({
const relationshipsTableRelations = relations(relationshipsTable, ({ one }) => {
const result: Record<string, Relation<string>> = {
parent: one(table, {
relationName: '_relationships',
fields: [relationshipsTable.parent],
references: [table.id],
relationName: '_relationships',
}),
};

View File

@@ -1,14 +1,15 @@
/* eslint-disable no-param-reassign */
import { uniqueIndex, index } from 'drizzle-orm/pg-core';
import { GenericColumn } from '../types';
import { index, uniqueIndex } from 'drizzle-orm/pg-core';
import type { GenericColumn } from '../types';
type CreateIndexArgs = {
name: string
columnName: string
name: string
unique?: boolean
}
export const createIndex = ({ name, columnName, unique }: CreateIndexArgs) => {
export const createIndex = ({ columnName, name, unique }: CreateIndexArgs) => {
return (table: { [x: string]: GenericColumn }) => {
if (unique) return uniqueIndex(`${columnName}_idx`).on(table[name]);
return index(`${columnName}_idx`).on(table[name]);

View File

@@ -2,6 +2,6 @@ import { integer, numeric, varchar } from 'drizzle-orm/pg-core';
export const parentIDColumnMap = {
integer,
varchar,
numeric,
varchar,
};

View File

@@ -1,38 +1,40 @@
/* eslint-disable no-param-reassign */
import type { Relation } from 'drizzle-orm';
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core';
import type { Field } from 'payload/types';
import { relations } from 'drizzle-orm';
import {
AnyPgColumnBuilder,
IndexBuilder,
PgNumericBuilder,
PgVarcharBuilder,
integer,
jsonb,
numeric,
PgNumericBuilder,
PgVarcharBuilder,
text,
unique,
UniqueConstraintBuilder,
varchar,
} from 'drizzle-orm/pg-core';
import { Field } from 'payload/types';
import { fieldAffectsData } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { fieldAffectsData } from 'payload/dist/fields/config/types';
import { Relation, relations } from 'drizzle-orm';
import { GenericColumns, PostgresAdapter } from '../types';
import { createIndex } from './createIndex';
import { buildTable } from './build';
import { parentIDColumnMap } from './parentIDColumnMap';
import type { GenericColumns, PostgresAdapter } from '../types';
import { hasLocalesTable } from '../utilities/hasLocalesTable';
import { buildTable } from './build';
import { createIndex } from './createIndex';
import { parentIDColumnMap } from './parentIDColumnMap';
type Args = {
adapter: PostgresAdapter
arrayBlockRelations: Map<string, string>
buildRelationships: boolean
columns: Record<string, AnyPgColumnBuilder>
columnPrefix?: string
columns: Record<string, PgColumnBuilder>
fieldPrefix?: string
fields: Field[]
forceLocalized?: boolean
indexes: Record<string, (cols: GenericColumns) => IndexBuilder>
localesColumns: Record<string, AnyPgColumnBuilder>
localesColumns: Record<string, PgColumnBuilder>
localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder>
newTableName: string
parentTableName: string
@@ -85,7 +87,7 @@ export const traverseFields = ({
targetIndexes = localesIndexes;
}
if ((field.unique || field.index) && !['array', 'blocks', 'relationship', 'upload', 'group'].includes(field.type)) {
if ((field.unique || field.index) && !['array', 'blocks', 'group', 'relationship', 'upload'].includes(field.type)) {
targetIndexes[`${field.name}Idx`] = createIndex({ columnName, name: field.name, unique: field.unique });
}
}
@@ -131,7 +133,7 @@ export const traverseFields = ({
}
case 'array': {
const baseColumns: Record<string, AnyPgColumnBuilder> = {
const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(),
_parentID: parentIDColumnMap[parentIDColType]('_parent_id').references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' }).notNull(),
};
@@ -185,10 +187,10 @@ export const traverseFields = ({
field.blocks.forEach((block) => {
const blockTableName = `${newTableName}_${toSnakeCase(block.slug)}`;
if (!adapter.tables[blockTableName]) {
const baseColumns: Record<string, AnyPgColumnBuilder> = {
const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(),
_path: text('_path').notNull(),
_parentID: parentIDColumnMap[parentIDColType]('_parent_id').references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' }).notNull(),
_path: text('_path').notNull(),
};
const baseExtraConfig: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder> = {};

View File

@@ -1,10 +1,12 @@
import type { BeginTransaction } from 'payload/dist/database/types';
import { PgTransactionConfig } from 'drizzle-orm/pg-core';
import { v4 as uuid } from 'uuid';
import { Client, Pool } from 'pg';
import { drizzle } from 'drizzle-orm/node-postgres';
import type { PgTransactionConfig } from 'drizzle-orm/pg-core';
import type { BeginTransaction } from 'payload/database';
import { sql } from 'drizzle-orm';
import { DrizzleDB } from '../types';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Client, Pool } from 'pg';
import { v4 as uuid } from 'uuid';
import type { DrizzleDB } from '../types';
export const beginTransaction: BeginTransaction = async function beginTransaction(
options: PgTransactionConfig = {},

View File

@@ -1,4 +1,5 @@
import { CommitTransaction } from 'payload/dist/database/types';
import type { CommitTransaction } from 'payload/database';
import { sql } from 'drizzle-orm';

View File

@@ -1,4 +1,5 @@
import { RollbackTransaction } from 'payload/dist/database/types';
import type { RollbackTransaction } from 'payload/database';
import { sql } from 'drizzle-orm';

View File

@@ -1,15 +1,15 @@
/* eslint-disable no-param-reassign */
import { Field } from 'payload/types';
import { TypeWithID } from 'payload/dist/collections/config/types';
import { SanitizedConfig } from 'payload/config';
import { traverseFields } from './traverseFields';
import { createRelationshipMap } from '../../utilities/createRelationshipMap';
import type { SanitizedConfig } from 'payload/config';
import type { Field, TypeWithID } from 'payload/types';
import { createBlocksMap } from '../../utilities/createBlocksMap';
import { createRelationshipMap } from '../../utilities/createRelationshipMap';
import { traverseFields } from './traverseFields';
type TransformArgs = {
config: SanitizedConfig
data: Record<string, unknown>
fallbackLocale?: string | false
fallbackLocale?: false | string
fields: Field[]
locale?: string
}

View File

@@ -1,8 +1,11 @@
/* eslint-disable no-param-reassign */
import { fieldAffectsData } from 'payload/dist/fields/config/types';
import { Field } from 'payload/types';
import { SanitizedConfig } from 'payload/config';
import { BlocksMap } from '../../utilities/createBlocksMap';
import type { SanitizedConfig } from 'payload/config';
import type { Field} from 'payload/types';
import { fieldAffectsData } from 'payload/types';
import type { BlocksMap } from '../../utilities/createBlocksMap';
import { transformRelationship } from './relationship';
type TraverseFieldsArgs = {
@@ -223,7 +226,7 @@ export const traverseFields = <T extends Record<string, unknown>>({
field.fields.forEach((subField) => {
if (fieldAffectsData(subField)) {
const subFieldKey = `${sanitizedPath.replace(/[.]/g, '_')}${field.name}_${subField.name}`;
const subFieldKey = `${sanitizedPath.replace(/\./g, '_')}${field.name}_${subField.name}`;
if (typeof locale === 'string') {
if (!ref[locale]) ref[locale] = {};

View File

@@ -1,6 +1,8 @@
/* eslint-disable no-param-reassign */
import { ArrayField } from 'payload/types';
import { ArrayRowToInsert, BlockRowToInsert } from './types';
import type { ArrayField } from 'payload/types';
import type { ArrayRowToInsert, BlockRowToInsert } from './types';
import { isArrayOfRows } from '../../utilities/isArrayOfRows';
import { traverseFields } from './traverseFields';

View File

@@ -1,7 +1,10 @@
/* eslint-disable no-param-reassign */
import { BlockField } from 'payload/types';
import type { BlockField } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { BlockRowToInsert } from './types';
import type { BlockRowToInsert } from './types';
import { traverseFields } from './traverseFields';
type Args = {
@@ -33,11 +36,11 @@ export const transformBlocks = ({
const newRow: BlockRowToInsert = {
arrays: {},
locales: {},
row: {
_order: i + 1,
_path: `${path}${field.name}`,
},
locales: {},
};
if (field.localized && locale) newRow.row._locale = locale;

View File

@@ -1,7 +1,10 @@
/* eslint-disable no-param-reassign */
import { Field } from 'payload/types';
import type { Field } from 'payload/types';
import type { RowToInsert } from './types';
import { traverseFields } from './traverseFields';
import { RowToInsert } from './types';
type Args = {
data: Record<string, unknown>
@@ -19,11 +22,11 @@ export const transformForWrite = ({
// Split out the incoming data into the corresponding:
// base row, locales, relationships, blocks, and arrays
const rowToInsert: RowToInsert = {
row: {},
arrays: {},
blocks: {},
locales: {},
relationships: [],
blocks: {},
arrays: {},
row: {},
};
// This function is responsible for building up the

View File

@@ -1,5 +1,6 @@
import { valueIsValueWithRelation } from 'payload/dist/fields/config/types';
import { RelationshipField, UploadField } from 'payload/types';
import type { RelationshipField, UploadField } from 'payload/types';
import { valueIsValueWithRelation } from 'payload/types';
type Args = {
baseRow: Record<string, unknown>

View File

@@ -1,8 +1,11 @@
/* eslint-disable no-param-reassign */
import { Field } from 'payload/types';
import type { Field } from 'payload/types';
import { fieldAffectsData } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { fieldAffectsData } from 'payload/dist/fields/config/types';
import { ArrayRowToInsert, BlockRowToInsert } from './types';
import type { ArrayRowToInsert, BlockRowToInsert } from './types';
import { isArrayOfRows } from '../../utilities/isArrayOfRows';
import { transformArray } from './array';
import { transformBlocks } from './blocks';
@@ -174,8 +177,8 @@ export const traverseFields = ({
Object.entries(fieldData).forEach(([localeKey, localeData]) => {
transformRelationship({
baseRow: {
path: relationshipPath,
locale: localeKey,
path: relationshipPath,
},
data: localeData,
field,
@@ -220,7 +223,7 @@ export const traverseFields = ({
ref = locales[forcedLocale];
}
valuesToTransform.push({ value: fieldData, ref });
valuesToTransform.push({ ref, value: fieldData });
}
valuesToTransform.forEach(({ localeKey, ref, value }) => {

View File

@@ -1,34 +1,34 @@
export type ArrayRowToInsert = {
columnName: string
row: Record<string, unknown>,
locales: {
[locale: string]: Record<string, unknown>
}
arrays: {
[tableName: string]: ArrayRowToInsert[]
}
columnName: string
locales: {
[locale: string]: Record<string, unknown>
}
row: Record<string, unknown>,
}
export type BlockRowToInsert = {
row: Record<string, unknown>,
locales: {
[locale: string]: Record<string, unknown>
}
arrays: {
[tableName: string]: ArrayRowToInsert[]
}
locales: {
[locale: string]: Record<string, unknown>
}
row: Record<string, unknown>,
}
export type RowToInsert = {
row: Record<string, unknown>,
arrays: {
[tableName: string]: ArrayRowToInsert[]
}
blocks: {
[blockType: string]: BlockRowToInsert[]
}
locales: {
[locale: string]: Record<string, unknown>
}
relationships: Record<string, unknown>[],
blocks: {
[blockType: string]: BlockRowToInsert[]
}
arrays: {
[tableName: string]: ArrayRowToInsert[]
}
row: Record<string, unknown>,
}

View File

@@ -1,9 +1,8 @@
import { ColumnBaseConfig, ColumnDataType, Relation, Relations } from 'drizzle-orm';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { PgColumn, PgEnum, PgTableWithColumns } from 'drizzle-orm/pg-core';
import { Payload } from 'payload';
import { DatabaseAdapter } from 'payload/dist/database/types';
import { ClientConfig, PoolConfig } from 'pg';
import type { ColumnBaseConfig, ColumnDataType, Relation, Relations } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type { PgColumn, PgEnum, PgTableWithColumns } from 'drizzle-orm/pg-core';
import type { DatabaseAdapter, Payload } from 'payload';
import type { ClientConfig, PoolConfig } from 'pg';
export type DrizzleDB = NodePgDatabase<Record<string, never>>
@@ -14,7 +13,7 @@ type BaseArgs = {
type ClientArgs = {
/** Client connection options for the Node package `pg` */
client?: ClientConfig | string | false
client?: ClientConfig | false | string
} & BaseArgs
type PoolArgs = {
@@ -31,7 +30,7 @@ export type GenericColumns = {
}
export type GenericTable = PgTableWithColumns<{
name: string, schema: undefined, columns: GenericColumns, dialect: string
columns: GenericColumns, dialect: string, name: string, schema: undefined
}>
export type GenericEnum = PgEnum<[string, ...string[]]>
@@ -40,11 +39,11 @@ export type GenericRelation = Relations<string, Record<string, Relation<string>>
export type PostgresAdapter = DatabaseAdapter & Args & {
db: DrizzleDB
sessions: Record<string, DrizzleDB>
enums: Record<string, GenericEnum>
relations: Record<string, GenericRelation>
schema: Record<string, GenericEnum | GenericRelation | GenericTable>
sessions: Record<string, DrizzleDB>
tables: Record<string, GenericTable>
schema: Record<string, GenericEnum | GenericTable | GenericRelation>
}
export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter

View File

@@ -1,6 +1,7 @@
import { UpdateOne } from 'payload/dist/database/types';
import type { UpdateOne } from 'payload/database';
import toSnakeCase from 'to-snake-case';
import { SQL } from 'drizzle-orm';
import buildQuery from '../queries/buildQuery';
import { upsertRow } from '../upsertRow';
@@ -15,7 +16,7 @@ export const updateOne: UpdateOne = async function updateOne({
}) {
const collection = this.payload.collections[collectionSlug].config;
let query: SQL<unknown>;
let query: Result;
if (where) {
query = await buildQuery({

View File

@@ -1,12 +1,15 @@
import { PayloadRequest } from 'payload/types';
import type { UpdateGlobal } from 'payload/database';
import type { PayloadRequest } from 'payload/types';
import toSnakeCase from 'to-snake-case';
import { UpdateGlobal } from 'payload/dist/database/types';
import type { PostgresAdapter } from './types';
import { upsertRow } from './upsertRow';
import { PostgresAdapter } from './types';
export const updateGlobal: UpdateGlobal = async function updateGlobal(
this: PostgresAdapter,
{ data, slug, req = {} as PayloadRequest },
{ data, req = {} as PayloadRequest, slug },
) {
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug);
const tableName = toSnakeCase(slug);
@@ -17,9 +20,8 @@ export const updateGlobal: UpdateGlobal = async function updateGlobal(
adapter: this,
data,
fields: globalConfig.fields,
locale: req.locale,
operation: 'update',
id: existingGlobal.id,
operation: 'update',
tableName: toSnakeCase(slug),
});

View File

@@ -1,6 +1,7 @@
import { Field } from 'payload/types';
import { SQL } from 'drizzle-orm';
import { GenericColumn, PostgresAdapter } from '../types';
import type { SQL } from 'drizzle-orm';
import type { Field } from 'payload/types';
import type { GenericColumn, PostgresAdapter } from '../types';
type BaseArgs = {
adapter: PostgresAdapter
@@ -11,17 +12,17 @@ type BaseArgs = {
}
type CreateArgs = BaseArgs & {
upsertTarget?: never
where?: never
id?: never
operation: 'create'
upsertTarget?: never
where?: never
}
type UpdateArgs = BaseArgs & {
upsertTarget?: GenericColumn
id?: number | string
operation: 'update'
upsertTarget?: GenericColumn
where?: SQL<unknown>
id?: string | number
}
export type Args = CreateArgs | UpdateArgs

View File

@@ -1,5 +1,6 @@
import { fieldAffectsData, fieldHasSubFields } from 'payload/dist/fields/config/types';
import { Field } from 'payload/types';
import type { Field} from 'payload/types';
import { fieldAffectsData, fieldHasSubFields } from 'payload/types';
export const hasLocalesTable = (fields: Field[]): boolean => {
return fields.some((field) => {

View File

@@ -1,5 +1,7 @@
export { i18nInit } from '../translations/init'
export { combineMerge } from '../utilities/combineMerge'
export { configToJSONSchema, entityToJSONSchema } from '../utilities/configToJSONSchema'
export { createArrayFromCommaDelineated } from '../utilities/createArrayFromCommaDelineated';
export { default as flattenTopLevelFields } from '../utilities/flattenTopLevelFields'

View File

@@ -1,21 +0,0 @@
import { Where, WhereField } from '../types';
/**
* Take a where query and flatten it to all top-level operators
*/
const flattenWhereToOperators = (query: Where): WhereField[] => Object.entries(query)
.reduce((flattenedConstraints, [key, val]) => {
if ((key === 'and' || key === 'or') && Array.isArray(val)) {
return [
...flattenedConstraints,
...val.map((subVal) => flattenWhereToOperators(subVal)),
];
}
return [
...flattenedConstraints,
{ [key]: val },
];
}, []);
export default flattenWhereToOperators;