@payloadcms/drizzle 4.0.0-internal.b8e7c89 → 4.0.0-internal.bd1d413
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/exports/postgres.d.ts +4 -1
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +4 -1
- package/dist/exports/postgres.js.map +1 -1
- package/dist/exports/sqlite.d.ts +2 -1
- package/dist/exports/sqlite.d.ts.map +1 -1
- package/dist/exports/sqlite.js +2 -1
- package/dist/exports/sqlite.js.map +1 -1
- package/dist/find/buildPolymorphicJoinQuery.d.ts +39 -0
- package/dist/find/buildPolymorphicJoinQuery.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinQuery.js +146 -0
- package/dist/find/buildPolymorphicJoinQuery.js.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts +20 -0
- package/dist/find/buildPolymorphicJoinWhere.d.ts.map +1 -0
- package/dist/find/buildPolymorphicJoinWhere.js +301 -0
- package/dist/find/buildPolymorphicJoinWhere.js.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts +38 -0
- package/dist/find/createPolymorphicJoinWherePlan.d.ts.map +1 -0
- package/dist/find/createPolymorphicJoinWherePlan.js +200 -0
- package/dist/find/createPolymorphicJoinWherePlan.js.map +1 -0
- package/dist/find/traverseFields.d.ts.map +1 -1
- package/dist/find/traverseFields.js +20 -191
- package/dist/find/traverseFields.js.map +1 -1
- package/dist/index.d.ts +1 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -8
- package/dist/index.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +6 -2
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.d.ts.map +1 -1
- package/dist/migrateDown.js +5 -2
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +5 -2
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.d.ts.map +1 -1
- package/dist/migrateRefresh.js +6 -2
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.d.ts.map +1 -1
- package/dist/migrateReset.js +6 -2
- package/dist/migrateReset.js.map +1 -1
- package/dist/postgres/createJSONQuery/index.js +3 -3
- package/dist/postgres/createJSONQuery/index.js.map +1 -1
- package/dist/postgres/findDocumentLocks.d.ts +4 -0
- package/dist/postgres/findDocumentLocks.d.ts.map +1 -0
- package/dist/postgres/findDocumentLocks.js +22 -0
- package/dist/postgres/findDocumentLocks.js.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts +26 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js +61 -0
- package/dist/postgres/predefinedMigrations/localize-status/getGeneratedColumnType.js.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts +13 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js +17 -0
- package/dist/postgres/predefinedMigrations/localize-status/getMigrationDB.js.map +1 -0
- package/dist/postgres/predefinedMigrations/localize-status/index.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/localize-status/index.js +73 -10
- package/dist/postgres/predefinedMigrations/localize-status/index.js.map +1 -1
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
- package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
- package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/requireDrizzleKit.d.ts +4 -0
- package/dist/postgres/requireDrizzleKit.d.ts.map +1 -1
- package/dist/postgres/requireDrizzleKit.js +16 -10
- package/dist/postgres/requireDrizzleKit.js.map +1 -1
- package/dist/queries/buildOperatorConstraint.d.ts.map +1 -1
- package/dist/queries/buildOperatorConstraint.js +16 -0
- package/dist/queries/buildOperatorConstraint.js.map +1 -1
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +15 -1
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +59 -2
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
- package/dist/queries/sanitizeQueryValue.js +6 -2
- package/dist/queries/sanitizeQueryValue.js.map +1 -1
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +54 -5
- package/dist/schema/build.js.map +1 -1
- package/dist/schema/traverseFields.d.ts.map +1 -1
- package/dist/schema/traverseFields.js +71 -14
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js +3 -2
- package/dist/sqlite/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
- package/dist/sqlite/createJSONQuery/index.d.ts.map +1 -1
- package/dist/sqlite/createJSONQuery/index.js +6 -5
- package/dist/sqlite/createJSONQuery/index.js.map +1 -1
- package/dist/sqlite/createRequireDrizzleKit.d.ts +6 -0
- package/dist/sqlite/createRequireDrizzleKit.d.ts.map +1 -0
- package/dist/sqlite/createRequireDrizzleKit.js +15 -0
- package/dist/sqlite/createRequireDrizzleKit.js.map +1 -0
- package/dist/sqlite/execute.js.map +1 -1
- package/dist/sqlite/insert.d.ts.map +1 -1
- package/dist/sqlite/insert.js +4 -1
- package/dist/sqlite/insert.js.map +1 -1
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
- package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
- package/dist/transactions/beginTransaction.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.js +13 -5
- package/dist/transactions/beginTransaction.js.map +1 -1
- package/dist/transactions/commitTransaction.d.ts.map +1 -1
- package/dist/transactions/commitTransaction.js +2 -5
- package/dist/transactions/commitTransaction.js.map +1 -1
- package/dist/transform/read/traverseFields.d.ts.map +1 -1
- package/dist/transform/read/traverseFields.js +11 -3
- package/dist/transform/read/traverseFields.js.map +1 -1
- package/dist/transform/write/array.d.ts +3 -2
- package/dist/transform/write/array.d.ts.map +1 -1
- package/dist/transform/write/array.js +2 -1
- package/dist/transform/write/array.js.map +1 -1
- package/dist/transform/write/blocks.d.ts +3 -2
- package/dist/transform/write/blocks.d.ts.map +1 -1
- package/dist/transform/write/blocks.js +5 -2
- package/dist/transform/write/blocks.js.map +1 -1
- package/dist/transform/write/index.d.ts.map +1 -1
- package/dist/transform/write/index.js +5 -1
- package/dist/transform/write/index.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts +2 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +36 -16
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/transform/write/types.d.ts +10 -0
- package/dist/transform/write/types.d.ts.map +1 -1
- package/dist/transform/write/types.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +54 -1
- package/dist/updateOne.js.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts +6 -1
- package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
- package/dist/upsertRow/deleteExistingRowsByPath.js +21 -3
- package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
- package/dist/upsertRow/index.d.ts +1 -1
- package/dist/upsertRow/index.d.ts.map +1 -1
- package/dist/upsertRow/index.js +57 -13
- package/dist/upsertRow/index.js.map +1 -1
- package/dist/upsertRow/insertArrays.d.ts.map +1 -1
- package/dist/upsertRow/insertArrays.js +2 -3
- package/dist/upsertRow/insertArrays.js.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
- package/dist/utilities/blocksToJsonMigrator.js +7 -18
- package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
- package/dist/utilities/buildCreateMigration.js +1 -1
- package/dist/utilities/buildCreateMigration.js.map +1 -1
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
- package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +24 -13
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/executeSchemaHooks.js +1 -1
- package/dist/utilities/executeSchemaHooks.js.map +1 -1
- package/dist/utilities/fitIdentifierLength.d.ts +25 -0
- package/dist/utilities/fitIdentifierLength.d.ts.map +1 -0
- package/dist/utilities/fitIdentifierLength.js +35 -0
- package/dist/utilities/fitIdentifierLength.js.map +1 -0
- package/dist/utilities/formatGeneratedFile.d.ts +10 -0
- package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
- package/dist/utilities/formatGeneratedFile.js +58 -0
- package/dist/utilities/formatGeneratedFile.js.map +1 -0
- package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
- package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
- package/dist/utilities/getSizesToVariantsRenames.js +252 -0
- package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
- package/dist/utilities/getTransaction.js.map +1 -1
- package/dist/utilities/parseJSONPathSegment.d.ts +9 -0
- package/dist/utilities/parseJSONPathSegment.d.ts.map +1 -0
- package/dist/utilities/parseJSONPathSegment.js +17 -0
- package/dist/utilities/parseJSONPathSegment.js.map +1 -0
- package/dist/utilities/pushDevSchema.js +1 -1
- package/dist/utilities/pushDevSchema.js.map +1 -1
- package/package.json +17 -19
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js +0 -91
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js.map +0 -1
- package/dist/postgres/query/postgresUnaccent.spec.js +0 -71
- package/dist/postgres/query/postgresUnaccent.spec.js.map +0 -1
- package/dist/queries/buildOperatorConstraint.spec.js +0 -348
- package/dist/queries/buildOperatorConstraint.spec.js.map +0 -1
- package/dist/queries/validateOperatorHandlers.spec.js +0 -142
- package/dist/queries/validateOperatorHandlers.spec.js.map +0 -1
- package/dist/schema/buildRawSchema.spec.js +0 -290
- package/dist/schema/buildRawSchema.spec.js.map +0 -1
- package/dist/sqlite/requireDrizzleKit.d.ts +0 -3
- package/dist/sqlite/requireDrizzleKit.d.ts.map +0 -1
- package/dist/sqlite/requireDrizzleKit.js +0 -12
- package/dist/sqlite/requireDrizzleKit.js.map +0 -1
- package/dist/upsertRow/handleUpsertError.spec.js +0 -42
- package/dist/upsertRow/handleUpsertError.spec.js.map +0 -1
- package/dist/utilities/checkTruncatedIdentifiers.spec.js +0 -301
- package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +0 -1
- package/dist/utilities/isValidStringID.spec.js +0 -15
- package/dist/utilities/isValidStringID.spec.js.map +0 -1
- package/dist/utilities/validateIdentifierLength.spec.js +0 -19
- package/dist/utilities/validateIdentifierLength.spec.js.map +0 -1
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n Column,\n ColumnBaseConfig,\n ColumnDataType,\n DrizzleConfig,\n ExtractTablesWithRelations,\n Relation,\n Relations,\n SQL,\n TableRelationalConfig,\n} from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { NodePgDatabase, NodePgQueryResultHKT } from 'drizzle-orm/node-postgres'\nimport type {\n PgColumn,\n PgTable,\n PgTransaction,\n Precision,\n UpdateDeleteAction,\n} from 'drizzle-orm/pg-core'\nimport type { SQLiteColumn, SQLiteTable, SQLiteTransaction } from 'drizzle-orm/sqlite-core'\nimport type { Result } from 'drizzle-orm/sqlite-core/session'\nimport type {\n BaseDatabaseAdapter,\n FlattenedField,\n MigrationData,\n Operator,\n Payload,\n PayloadRequest,\n} from 'payload'\n\nimport type { BuildQueryJoinAliases } from './queries/buildQuery.js'\n\nexport { BuildQueryJoinAliases }\n\nimport type { ResultSet } from '@libsql/client'\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { SQLiteRaw } from 'drizzle-orm/sqlite-core/query-builders/raw'\nimport type { QueryResult } from 'pg'\n\nimport type { DrizzleResolvedOperator, Operators } from './queries/operatorMap.js'\n\nexport type PostgresDB = NodePgDatabase<Record<string, unknown>>\n\nexport type SQLiteDB = LibSQLDatabase<\n Record<string, GenericRelation | GenericTable> & Record<string, unknown>\n>\n\nexport type GenericPgColumn = PgColumn<\n ColumnBaseConfig<ColumnDataType, string>,\n Record<string, unknown>\n>\n\nexport type GenericColumns<T> = {\n [x: string]: T\n}\n\ntype GenericPgTable = PgTable<{\n columns: GenericColumns<GenericPgColumn>\n dialect: string\n name: string\n schema: undefined\n}>\n\ntype GenericSQLiteTable = SQLiteTable<{\n columns: GenericColumns<SQLiteColumn>\n dialect: string\n name: string\n schema: undefined\n}>\n\nexport type GenericColumn = GenericPgColumn | SQLiteColumn\n\nexport type GenericTable = GenericPgTable | GenericSQLiteTable\n\nexport type GenericRelation = Relations<string, Record<string, Relation<string>>>\n\nexport type TransactionSQLite = SQLiteTransaction<\n 'async',\n Result<'async', unknown>,\n Record<string, unknown>,\n { tsName: TableRelationalConfig }\n>\nexport type TransactionPg = PgTransaction<\n NodePgQueryResultHKT,\n Record<string, unknown>,\n ExtractTablesWithRelations<Record<string, unknown>>\n>\n\nexport type DrizzleTransaction = TransactionPg | TransactionSQLite\n\nexport type CountDistinct = (args: {\n column?: PgColumn<any> | SQLiteColumn<any>\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n joins: BuildQueryJoinAliases\n tableName: string\n where: SQL\n}) => Promise<number>\n\nexport type DeleteWhere = (args: {\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n tableName: string\n where: SQL\n}) => Promise<void>\n\nexport type DropDatabase = (args: { adapter: DrizzleAdapter }) => Promise<void>\n\nexport type Execute<T> = (args: {\n db?: DrizzleTransaction | LibSQLDatabase | PostgresDB\n drizzle?: LibSQLDatabase | PostgresDB\n raw?: string\n sql?: SQL<unknown>\n}) =>\n | Promise<QueryResult<Record<string, T>>>\n | SQLiteRaw<Promise<{ rows: T[] }>>\n | SQLiteRaw<ResultSet>\n\nexport type Insert = (args: {\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n onConflictDoUpdate?: unknown\n tableName: string\n values: Record<string, unknown> | Record<string, unknown>[]\n}) => Promise<Record<string, unknown>[]>\n\nexport type RequireDrizzleKit = () => {\n generateDrizzleJson: (\n args: Record<string, unknown>,\n ) => DrizzleSnapshotJSON | Promise<DrizzleSnapshotJSON>\n generateMigration: (prev: DrizzleSnapshotJSON, cur: DrizzleSnapshotJSON) => Promise<string[]>\n pushSchema: (\n schema: Record<string, unknown>,\n drizzle: DrizzleAdapter['drizzle'],\n filterSchema?: string[],\n tablesFilter?: string[],\n extensionsFilter?: string[],\n ) => Promise<{ apply; hasDataLoss; warnings }>\n upSnapshot?: (snapshot: Record<string, unknown>) => DrizzleSnapshotJSON\n}\n\nexport type Migration = {\n down: ({\n db,\n payload,\n req,\n }: {\n db?: DrizzleTransaction | LibSQLDatabase<Record<string, never>> | PostgresDB\n payload: Payload\n req: PayloadRequest\n }) => Promise<void>\n up: ({\n db,\n payload,\n req,\n }: {\n db?: DrizzleTransaction | LibSQLDatabase | PostgresDB\n payload: Payload\n req: PayloadRequest\n }) => Promise<void>\n} & MigrationData\n\nexport type CreateJSONQueryArgs = {\n column?: Column | string\n operator: string\n pathSegments: string[]\n rawColumn?: SQL<unknown>\n table?: string\n treatAsArray?: string[]\n treatRootAsArray?: boolean\n value: boolean | number | number[] | string | string[]\n}\n\n/**\n * Abstract relation link\n */\nexport type RawRelation =\n | {\n fields: { name: string; table: string }[]\n references: string[]\n relationName?: string\n to: string\n type: 'one'\n }\n | {\n relationName?: string\n to: string\n type: 'many'\n }\n\n/**\n * Abstract SQL table that later gets converted by database specific implementation to Drizzle\n */\nexport type RawTable = {\n columns: Record<string, RawColumn>\n foreignKeys?: Record<string, RawForeignKey>\n indexes?: Record<string, RawIndex>\n name: string\n}\n\n/**\n * Abstract SQL foreign key that later gets converted by database specific implementation to Drizzle\n */\nexport type RawForeignKey = {\n columns: string[]\n foreignColumns: { name: string; table: string }[]\n name: string\n onDelete?: UpdateDeleteAction\n onUpdate?: UpdateDeleteAction\n}\n\n/**\n * Abstract SQL index that later gets converted by database specific implementation to Drizzle\n */\nexport type RawIndex = {\n name: string\n on: string | string[]\n unique?: boolean\n}\n\n/**\n * Abstract SQL column that later gets converted by database specific implementation to Drizzle\n */\nexport type BaseRawColumn = {\n default?: any\n name: string\n notNull?: boolean\n primaryKey?: boolean\n reference?: {\n name: string\n onDelete: UpdateDeleteAction\n table: string\n }\n}\n\n/**\n * Postgres: native timestamp type\n * SQLite: text column, defaultNow achieved through strftime('%Y-%m-%dT%H:%M:%fZ', 'now'). withTimezone/precision have no any effect.\n */\nexport type TimestampRawColumn = {\n defaultNow?: boolean\n mode: 'date' | 'string'\n precision: Precision\n type: 'timestamp'\n withTimezone?: boolean\n} & BaseRawColumn\n\n/**\n * Postgres: native UUID type and db lavel defaultRandom\n * SQLite: text type and defaultRandom in the app level\n */\nexport type UUIDRawColumn = {\n defaultRandom?: boolean\n /** App-side UUID v7 default (Postgres & SQLite); mutually exclusive with defaultRandom in practice */\n defaultV7?: boolean\n type: 'uuid'\n} & BaseRawColumn\n\n/**\n * Accepts either `locale: true` to have options from locales or `options` string array\n * Postgres: native enums\n * SQLite: text column with checks.\n */\nexport type EnumRawColumn = (\n | {\n enumName: string\n options: string[]\n type: 'enum'\n }\n | {\n locale: true\n type: 'enum'\n }\n) &\n BaseRawColumn\n\nexport type IntegerRawColumn = {\n /**\n * SQLite only.\n * Enable [AUTOINCREMENT](https://www.sqlite.org/autoinc.html) for primary key to ensure that the same ID cannot be reused from previously deleted rows.\n */\n autoIncrement?: boolean\n type: 'integer'\n} & BaseRawColumn\n\nexport type VectorRawColumn = {\n dimensions?: number\n type: 'vector'\n} & BaseRawColumn\n\nexport type HalfVecRawColumn = {\n dimensions?: number\n type: 'halfvec'\n} & BaseRawColumn\n\nexport type SparseVecRawColumn = {\n dimensions?: number\n type: 'sparsevec'\n} & BaseRawColumn\n\nexport type BinaryVecRawColumn = {\n dimensions?: number\n type: 'bit'\n} & BaseRawColumn\n\nexport type RawColumn =\n | ({\n type: 'boolean' | 'geometry' | 'jsonb' | 'numeric' | 'serial' | 'text' | 'varchar'\n } & BaseRawColumn)\n | BinaryVecRawColumn\n | EnumRawColumn\n | HalfVecRawColumn\n | IntegerRawColumn\n | SparseVecRawColumn\n | TimestampRawColumn\n | UUIDRawColumn\n | VectorRawColumn\n\nexport type IDType = 'integer' | 'numeric' | 'text' | 'uuid' | 'varchar'\n\nexport type SetColumnID = (args: {\n adapter: DrizzleAdapter\n columns: Record<string, RawColumn>\n fields: FlattenedField[]\n}) => IDType\n\nexport type ColumnToCodeConverter = (args: {\n adapter: DrizzleAdapter\n addEnum: (name: string, options: string[]) => void\n addImport: (from: string, name: string) => void\n circularEdges?: Set<string>\n column: RawColumn\n locales?: string[]\n tableKey: string\n}) => string\n\nexport type BuildDrizzleTable<T extends DrizzleAdapter = DrizzleAdapter> = (args: {\n adapter: T\n locales: string[]\n rawTable: RawTable\n}) => void\n\nexport type BlocksToJsonBlockToMigrate = {\n data: Record<string, unknown> | Record<string, unknown>[]\n fieldAccessor: (number | string)[]\n}\n\nexport interface BaseBlocksToJsonEntityToMigrate {\n blocks: BlocksToJsonBlockToMigrate[]\n originalData: Record<string, any>\n}\n\nexport interface CollectionOrVersionBlocksToJsonEntityToMigrate\n extends BaseBlocksToJsonEntityToMigrate {\n id: number | string\n slug: string\n type: 'collection' | 'collectionVersion' | 'globalVersion'\n}\n\nexport interface GlobalBlocksToJsonEntityToMigrate extends BaseBlocksToJsonEntityToMigrate {\n slug: string\n type: 'global'\n}\n\nexport type BlocksToJsonEntityToMigrate =\n | CollectionOrVersionBlocksToJsonEntityToMigrate\n | GlobalBlocksToJsonEntityToMigrate\n\nexport interface BlocksToJsonMigrator {\n collectAndSaveEntitiesToBatches(\n req: PayloadRequest,\n options?: {\n batchSize?: number\n },\n ): Promise<void>\n getMigrationStatements(): Promise<{\n statements: string\n writeDrizzleSnapshot(filePath: string): void\n }>\n migrateEntitiesFromTempFolder(\n req: PayloadRequest,\n options?: {\n clearBatches?: boolean\n },\n ): Promise<void>\n setTempFolder(tempFolderPath: string): void\n updatePayloadConfigFile(): Promise<void>\n}\n\n/**\n * The information passed to a query-operator handler for one user-facing leaf comparison.\n */\nexport type DrizzleOperatorHandlerContext = {\n adapter: DrizzleAdapter\n column: Column | SQL\n field: FlattenedField\n locale?: string\n /** The operator supplied by the Payload query, before any adapter conversions. */\n originalOperator: Operator\n path: string\n /** The operator actually sent to the database after Payload's existing conversions. */\n resolvedOperator: DrizzleResolvedOperator\n storage: 'column'\n value: unknown\n}\n\n/**\n * Transforms the column and/or value of a matching operator before the default (or replacement)\n * comparison runs. Multiple matching transform handlers compose in configuration order.\n */\nexport type DrizzleOperandTransformHandler = {\n build?: never\n /** Restricts the handler to these Payload field types. Omit to match every field type. */\n fieldTypes?: FlattenedField['type'][]\n name: string\n operators: DrizzleResolvedOperator[]\n transformOperands: (context: DrizzleOperatorHandlerContext) => {\n column: Column | SQL\n value: unknown\n }\n}\n\n/**\n * Replaces the default comparison for a matching operator entirely. Runs after every matching\n * `transformOperands` handler has already run.\n */\nexport type DrizzleOperatorReplacementHandler = {\n build: (context: DrizzleOperatorHandlerContext) => SQL\n /** Restricts the handler to these Payload field types. Omit to match every field type. */\n fieldTypes?: FlattenedField['type'][]\n name: string\n operators: DrizzleResolvedOperator[]\n transformOperands?: never\n}\n\nexport type DrizzleOperatorHandler =\n | DrizzleOperandTransformHandler\n | DrizzleOperatorReplacementHandler\n\nexport type DrizzleQueryConfig = {\n operatorHandlers?: DrizzleOperatorHandler[]\n}\n\nexport interface DrizzleAdapter extends BaseDatabaseAdapter {\n blocksAsJSON?: boolean\n blocksToJsonMigrator?: BlocksToJsonMigrator\n convertPathToJSONTraversal?: (incomingSegments: string[]) => string\n countDistinct: CountDistinct\n createJSONQuery: (args: CreateJSONQueryArgs) => string\n defaultDrizzleSnapshot: Record<string, unknown>\n deleteWhere: DeleteWhere\n drizzle: LibSQLDatabase | PostgresDB\n dropDatabase: DropDatabase\n enums?: never | Record<string, unknown>\n execute: Execute<unknown>\n features: {\n json?: boolean\n }\n /**\n * 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\n * Used for returning properly formed errors from unique fields\n */\n fieldConstraints: Record<string, Record<string, string>>\n\n foreignKeys: Set<string>\n idType: 'serial' | 'uuid' | 'uuidv7'\n indexes: Set<string>\n initializing: Promise<void>\n insert: Insert\n /**\n * Timestamp (ms) of the last write operation. When read replicas are configured,\n * reads within `readReplicasAfterWriteInterval` ms of this timestamp are routed to the\n * primary to guarantee read-after-write consistency.\n */\n lastWriteTimestamp?: number\n limitedBoundParameters?: boolean\n localesSuffix?: string\n logger: DrizzleConfig['logger']\n operatorHandlers: DrizzleOperatorHandler[]\n operators: Operators\n /**\n * When read replicas are configured, holds the unwrapped primary drizzle instance\n * (before withReplicas wrapping). Used for reads that are part of write operations\n * to avoid replication lag.\n */\n primaryDrizzle?: PostgresDB\n push: boolean\n rawRelations: Record<string, Record<string, RawRelation>>\n rawTables: Record<string, RawTable>\n /**\n * How long (ms) after a write to route reads to the primary instead of a\n * read replica. Avoids stale reads caused by replication lag.\n * @default 2000\n */\n readReplicasAfterWriteInterval: number\n\n rejectInitializing: () => void\n relations: Record<string, GenericRelation>\n relationshipsSuffix?: string\n requireDrizzleKit: RequireDrizzleKit\n resolveInitializing: () => void\n\n schema: Record<string, unknown>\n\n schemaName?: string\n sessions: {\n [id: string]: {\n db: DrizzleTransaction\n reject: () => Promise<void>\n resolve: () => Promise<void>\n }\n }\n tableNameMap: Map<string, string>\n tables: Record<string, any>\n transactionOptions: unknown\n versionsSuffix?: string\n}\n\nexport type RelationMap = Map<\n string,\n {\n localized: boolean\n relationName?: string\n target: string\n type: 'many' | 'one'\n }\n>\n"],"names":[],"mappings":"AAogBA,WAQC"}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n Column,\n ColumnBaseConfig,\n ColumnDataType,\n DrizzleConfig,\n ExtractTablesWithRelations,\n Relation,\n Relations,\n SQL,\n TableRelationalConfig,\n} from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { NodePgDatabase, NodePgQueryResultHKT } from 'drizzle-orm/node-postgres'\nimport type {\n PgColumn,\n PgTable,\n PgTransaction,\n Precision,\n UpdateDeleteAction,\n} from 'drizzle-orm/pg-core'\nimport type { SQLiteColumn, SQLiteTable, SQLiteTransaction } from 'drizzle-orm/sqlite-core'\nimport type { Result } from 'drizzle-orm/sqlite-core/session'\nimport type {\n BaseDatabaseAdapter,\n FlattenedField,\n MigrationData,\n Operator,\n Payload,\n PayloadRequest,\n} from 'payload'\n\nimport type { BuildQueryJoinAliases } from './queries/buildQuery.js'\n\nexport { BuildQueryJoinAliases }\n\nimport type { ResultSet } from '@libsql/client'\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { SQLiteRaw } from 'drizzle-orm/sqlite-core/query-builders/raw'\nimport type { QueryResult } from 'pg'\n\nimport type { DrizzleResolvedOperator, Operators } from './queries/operatorMap.js'\n\nexport type PostgresDB = NodePgDatabase<Record<string, unknown>>\n\nexport type SQLiteDB = LibSQLDatabase<\n Record<string, GenericRelation | GenericTable> & Record<string, unknown>\n>\n\nexport type GenericPgColumn = PgColumn<\n ColumnBaseConfig<ColumnDataType, string>,\n Record<string, unknown>\n>\n\nexport type GenericColumns<T> = {\n [x: string]: T\n}\n\ntype GenericPgTable = PgTable<{\n columns: GenericColumns<GenericPgColumn>\n dialect: string\n name: string\n schema: undefined\n}>\n\ntype GenericSQLiteTable = SQLiteTable<{\n columns: GenericColumns<SQLiteColumn>\n dialect: string\n name: string\n schema: undefined\n}>\n\nexport type GenericColumn = GenericPgColumn | SQLiteColumn\n\nexport type GenericTable = GenericPgTable | GenericSQLiteTable\n\nexport type GenericRelation = Relations<string, Record<string, Relation<string>>>\n\nexport type TransactionSQLite = SQLiteTransaction<\n 'async',\n Result<'async', unknown>,\n Record<string, unknown>,\n { tsName: TableRelationalConfig }\n>\nexport type TransactionPg = PgTransaction<\n NodePgQueryResultHKT,\n Record<string, unknown>,\n ExtractTablesWithRelations<Record<string, unknown>>\n>\n\nexport type DrizzleTransaction = TransactionPg | TransactionSQLite\n\nexport type CountDistinct = (args: {\n column?: PgColumn<any> | SQLiteColumn<any>\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n joins: BuildQueryJoinAliases\n tableName: string\n where: SQL\n}) => Promise<number>\n\nexport type DeleteWhere = (args: {\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n tableName: string\n where: SQL\n}) => Promise<void>\n\nexport type DropDatabase = (args: { adapter: DrizzleAdapter }) => Promise<void>\n\nexport type Execute<T> = (args: {\n db?: DrizzleTransaction | LibSQLDatabase | PostgresDB\n drizzle?: LibSQLDatabase | PostgresDB\n raw?: string\n sql?: SQL<unknown>\n}) =>\n | Promise<QueryResult<Record<string, T>>>\n | SQLiteRaw<Promise<{ rows: T[] }>>\n | SQLiteRaw<ResultSet>\n\nexport type Insert = (args: {\n db: DrizzleTransaction | LibSQLDatabase | PostgresDB\n onConflictDoUpdate?: unknown\n tableName: string\n values: Record<string, unknown> | Record<string, unknown>[]\n}) => Promise<Record<string, unknown>[]>\n\nexport type RequireDrizzleKit = () => Promise<{\n generateDrizzleJson: (\n args: Record<string, unknown>,\n ) => DrizzleSnapshotJSON | Promise<DrizzleSnapshotJSON>\n generateMigration: (prev: DrizzleSnapshotJSON, cur: DrizzleSnapshotJSON) => Promise<string[]>\n pushSchema: (\n schema: Record<string, unknown>,\n drizzle: DrizzleAdapter['drizzle'],\n filterSchema?: string[],\n tablesFilter?: string[],\n extensionsFilter?: string[],\n ) => Promise<{ apply; hasDataLoss; warnings }>\n upSnapshot?: (snapshot: Record<string, unknown>) => DrizzleSnapshotJSON\n}>\n\nexport type Migration = {\n down: ({\n db,\n payload,\n req,\n }: {\n db?: DrizzleTransaction | LibSQLDatabase<Record<string, never>> | PostgresDB\n payload: Payload\n req: PayloadRequest\n }) => Promise<void>\n up: ({\n db,\n payload,\n req,\n }: {\n db?: DrizzleTransaction | LibSQLDatabase | PostgresDB\n payload: Payload\n req: PayloadRequest\n }) => Promise<void>\n} & MigrationData\n\nexport type CreateJSONQueryArgs = {\n column?: Column | string\n operator: string\n pathSegments: string[]\n rawColumn?: SQL<unknown>\n table?: string\n treatAsArray?: string[]\n treatRootAsArray?: boolean\n value: boolean | number | number[] | string | string[]\n}\n\n/**\n * Abstract relation link\n */\nexport type RawRelation =\n | {\n fields: { name: string; table: string }[]\n references: string[]\n relationName?: string\n to: string\n type: 'one'\n }\n | {\n relationName?: string\n to: string\n type: 'many'\n }\n\n/**\n * Abstract SQL table that later gets converted by database specific implementation to Drizzle\n */\nexport type RawTable = {\n columns: Record<string, RawColumn>\n foreignKeys?: Record<string, RawForeignKey>\n indexes?: Record<string, RawIndex>\n name: string\n}\n\n/**\n * Abstract SQL foreign key that later gets converted by database specific implementation to Drizzle\n */\nexport type RawForeignKey = {\n columns: string[]\n foreignColumns: { name: string; table: string }[]\n name: string\n onDelete?: UpdateDeleteAction\n onUpdate?: UpdateDeleteAction\n}\n\n/**\n * Abstract SQL index that later gets converted by database specific implementation to Drizzle\n */\nexport type RawIndex = {\n name: string\n on: string | string[]\n unique?: boolean\n}\n\n/**\n * Abstract SQL column that later gets converted by database specific implementation to Drizzle\n */\nexport type BaseRawColumn = {\n default?: any\n name: string\n notNull?: boolean\n primaryKey?: boolean\n reference?: {\n name: string\n onDelete: UpdateDeleteAction\n table: string\n }\n}\n\n/**\n * Postgres: native timestamp type\n * SQLite: text column, defaultNow achieved through strftime('%Y-%m-%dT%H:%M:%fZ', 'now'). withTimezone/precision have no any effect.\n */\nexport type TimestampRawColumn = {\n defaultNow?: boolean\n mode: 'date' | 'string'\n precision: Precision\n type: 'timestamp'\n withTimezone?: boolean\n} & BaseRawColumn\n\n/**\n * Postgres: native UUID type and db lavel defaultRandom\n * SQLite: text type and defaultRandom in the app level\n */\nexport type UUIDRawColumn = {\n defaultRandom?: boolean\n /** App-side UUID v7 default (Postgres & SQLite); mutually exclusive with defaultRandom in practice */\n defaultV7?: boolean\n type: 'uuid'\n} & BaseRawColumn\n\n/**\n * Accepts either `locale: true` to have options from locales or `options` string array\n * Postgres: native enums\n * SQLite: text column with checks.\n */\nexport type EnumRawColumn = (\n | {\n enumName: string\n options: string[]\n type: 'enum'\n }\n | {\n locale: true\n type: 'enum'\n }\n) &\n BaseRawColumn\n\nexport type IntegerRawColumn = {\n /**\n * SQLite only.\n * Enable [AUTOINCREMENT](https://www.sqlite.org/autoinc.html) for primary key to ensure that the same ID cannot be reused from previously deleted rows.\n */\n autoIncrement?: boolean\n type: 'integer'\n} & BaseRawColumn\n\nexport type VectorRawColumn = {\n dimensions?: number\n type: 'vector'\n} & BaseRawColumn\n\nexport type HalfVecRawColumn = {\n dimensions?: number\n type: 'halfvec'\n} & BaseRawColumn\n\nexport type SparseVecRawColumn = {\n dimensions?: number\n type: 'sparsevec'\n} & BaseRawColumn\n\nexport type BinaryVecRawColumn = {\n dimensions?: number\n type: 'bit'\n} & BaseRawColumn\n\nexport type RawColumn =\n | ({\n type: 'boolean' | 'geometry' | 'jsonb' | 'numeric' | 'serial' | 'text' | 'varchar'\n } & BaseRawColumn)\n | BinaryVecRawColumn\n | EnumRawColumn\n | HalfVecRawColumn\n | IntegerRawColumn\n | SparseVecRawColumn\n | TimestampRawColumn\n | UUIDRawColumn\n | VectorRawColumn\n\nexport type IDType = 'integer' | 'numeric' | 'text' | 'uuid' | 'varchar'\n\nexport type SetColumnID = (args: {\n adapter: DrizzleAdapter\n columns: Record<string, RawColumn>\n fields: FlattenedField[]\n}) => IDType\n\nexport type ColumnToCodeConverter = (args: {\n adapter: DrizzleAdapter\n addEnum: (name: string, options: string[]) => void\n addImport: (from: string, name: string) => void\n circularEdges?: Set<string>\n column: RawColumn\n locales?: string[]\n tableKey: string\n}) => string\n\nexport type BuildDrizzleTable<T extends DrizzleAdapter = DrizzleAdapter> = (args: {\n adapter: T\n locales: string[]\n rawTable: RawTable\n}) => void\n\nexport type BlocksToJsonBlockToMigrate = {\n data: Record<string, unknown> | Record<string, unknown>[]\n fieldAccessor: (number | string)[]\n}\n\nexport interface BaseBlocksToJsonEntityToMigrate {\n blocks: BlocksToJsonBlockToMigrate[]\n originalData: Record<string, any>\n}\n\nexport interface CollectionOrVersionBlocksToJsonEntityToMigrate extends BaseBlocksToJsonEntityToMigrate {\n id: number | string\n slug: string\n type: 'collection' | 'collectionVersion' | 'globalVersion'\n}\n\nexport interface GlobalBlocksToJsonEntityToMigrate extends BaseBlocksToJsonEntityToMigrate {\n slug: string\n type: 'global'\n}\n\nexport type BlocksToJsonEntityToMigrate =\n | CollectionOrVersionBlocksToJsonEntityToMigrate\n | GlobalBlocksToJsonEntityToMigrate\n\nexport interface BlocksToJsonMigrator {\n collectAndSaveEntitiesToBatches(\n req: PayloadRequest,\n options?: {\n batchSize?: number\n },\n ): Promise<void>\n getMigrationStatements(): Promise<{\n statements: string\n writeDrizzleSnapshot(filePath: string): void\n }>\n migrateEntitiesFromTempFolder(\n req: PayloadRequest,\n options?: {\n clearBatches?: boolean\n },\n ): Promise<void>\n setTempFolder(tempFolderPath: string): void\n updatePayloadConfigFile(): Promise<void>\n}\n\n/**\n * The information passed to a query-operator handler for one user-facing leaf comparison.\n */\nexport type DrizzleOperatorHandlerContext = {\n adapter: DrizzleAdapter\n column: Column | SQL\n field: FlattenedField\n locale?: string\n /** The operator supplied by the Payload query, before any adapter conversions. */\n originalOperator: Operator\n path: string\n /** The operator actually sent to the database after Payload's existing conversions. */\n resolvedOperator: DrizzleResolvedOperator\n storage: 'column'\n value: unknown\n}\n\n/**\n * Transforms the column and/or value of a matching operator before the default (or replacement)\n * comparison runs. Multiple matching transform handlers compose in configuration order.\n */\nexport type DrizzleOperandTransformHandler = {\n build?: never\n /** Restricts the handler to these Payload field types. Omit to match every field type. */\n fieldTypes?: FlattenedField['type'][]\n name: string\n operators: DrizzleResolvedOperator[]\n transformOperands: (context: DrizzleOperatorHandlerContext) => {\n column: Column | SQL\n value: unknown\n }\n}\n\n/**\n * Replaces the default comparison for a matching operator entirely. Runs after every matching\n * `transformOperands` handler has already run.\n */\nexport type DrizzleOperatorReplacementHandler = {\n build: (context: DrizzleOperatorHandlerContext) => SQL\n /** Restricts the handler to these Payload field types. Omit to match every field type. */\n fieldTypes?: FlattenedField['type'][]\n name: string\n operators: DrizzleResolvedOperator[]\n transformOperands?: never\n}\n\nexport type DrizzleOperatorHandler =\n | DrizzleOperandTransformHandler\n | DrizzleOperatorReplacementHandler\n\nexport type DrizzleQueryConfig = {\n operatorHandlers?: DrizzleOperatorHandler[]\n}\n\nexport interface DrizzleAdapter extends BaseDatabaseAdapter {\n blocksAsJSON?: boolean\n blocksToJsonMigrator?: BlocksToJsonMigrator\n convertPathToJSONTraversal?: (incomingSegments: string[]) => string\n countDistinct: CountDistinct\n createJSONQuery: (args: CreateJSONQueryArgs) => string\n defaultDrizzleSnapshot: Record<string, unknown>\n deleteWhere: DeleteWhere\n drizzle: LibSQLDatabase | PostgresDB\n dropDatabase: DropDatabase\n enums?: never | Record<string, unknown>\n execute: Execute<unknown>\n features: {\n json?: boolean\n }\n /**\n * 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\n * Used for returning properly formed errors from unique fields\n */\n fieldConstraints: Record<string, Record<string, string>>\n\n foreignKeys: Set<string>\n idType: 'serial' | 'uuid' | 'uuidv7'\n indexes: Set<string>\n initializing: Promise<void>\n insert: Insert\n /**\n * Timestamp (ms) of the last write operation. When read replicas are configured,\n * reads within `readReplicasAfterWriteInterval` ms of this timestamp are routed to the\n * primary to guarantee read-after-write consistency.\n */\n lastWriteTimestamp?: number\n limitedBoundParameters?: boolean\n localesSuffix?: string\n logger: DrizzleConfig['logger']\n operatorHandlers: DrizzleOperatorHandler[]\n operators: Operators\n /**\n * When read replicas are configured, holds the unwrapped primary drizzle instance\n * (before withReplicas wrapping). Used for reads that are part of write operations\n * to avoid replication lag.\n */\n primaryDrizzle?: PostgresDB\n push: boolean\n rawRelations: Record<string, Record<string, RawRelation>>\n rawTables: Record<string, RawTable>\n /**\n * How long (ms) after a write to route reads to the primary instead of a\n * read replica. Avoids stale reads caused by replication lag.\n * @default 2000\n */\n readReplicasAfterWriteInterval: number\n\n rejectInitializing: () => void\n relations: Record<string, GenericRelation>\n relationshipsSuffix?: string\n requireDrizzleKit: RequireDrizzleKit\n resolveInitializing: () => void\n\n schema: Record<string, unknown>\n\n schemaName?: string\n sessions: {\n [id: string]: {\n db: DrizzleTransaction\n reject: () => Promise<void>\n resolve: () => Promise<void>\n }\n }\n tableNameMap: Map<string, string>\n tables: Record<string, any>\n transactionOptions: unknown\n versionsSuffix?: string\n}\n\nexport type RelationMap = Map<\n string,\n {\n localized: boolean\n relationName?: string\n target: string\n type: 'many' | 'one'\n }\n>\n"],"names":[],"mappings":"AAmgBA,WAQC"}
|
package/dist/updateOne.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"updateOne.d.ts","sourceRoot":"","sources":["../src/updateOne.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"updateOne.d.ts","sourceRoot":"","sources":["../src/updateOne.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAiBxC,eAAO,MAAM,SAAS,EAAE,SAmJvB,CAAA"}
|
package/dist/updateOne.js
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
|
+
import { eq } from 'drizzle-orm';
|
|
1
2
|
import toSnakeCase from 'to-snake-case';
|
|
2
3
|
import { buildQuery } from './queries/buildQuery.js';
|
|
3
4
|
import { selectDistinct } from './queries/selectDistinct.js';
|
|
5
|
+
import { transform } from './transform/read/index.js';
|
|
6
|
+
import { transformForWrite } from './transform/write/index.js';
|
|
4
7
|
import { upsertRow } from './upsertRow/index.js';
|
|
8
|
+
import { shouldUseOptimizedUpsertRow } from './upsertRow/shouldUseOptimizedUpsertRow.js';
|
|
5
9
|
import { getPrimaryDb } from './utilities/getPrimaryDb.js';
|
|
6
10
|
import { getTransaction } from './utilities/getTransaction.js';
|
|
11
|
+
import { markWrite } from './utilities/readAfterWrite.js';
|
|
7
12
|
export const updateOne = async function updateOne({ id, collection: collectionSlug, data, joins: joinQuery, locale, options = {
|
|
8
13
|
upsert: false
|
|
9
14
|
}, req, returning, select, where: whereArg }) {
|
|
10
15
|
const collection = this.payload.collections[collectionSlug].config;
|
|
11
16
|
const tableName = this.tableNameMap.get(toSnakeCase(collection.slug));
|
|
12
17
|
let idToUpdate = id;
|
|
18
|
+
let whereToUpdate;
|
|
13
19
|
const db = getPrimaryDb(this, await getTransaction(this, req));
|
|
14
20
|
if (!idToUpdate) {
|
|
15
21
|
const { joins, selectFields, where } = buildQuery({
|
|
@@ -19,6 +25,52 @@ export const updateOne = async function updateOne({ id, collection: collectionSl
|
|
|
19
25
|
tableName,
|
|
20
26
|
where: whereArg
|
|
21
27
|
});
|
|
28
|
+
// A `where` that needs joins cannot be applied to the UPDATE statement itself, so those
|
|
29
|
+
// queries keep resolving a matching id first and then update that row unconditionally
|
|
30
|
+
whereToUpdate = joins.length === 0 ? where : undefined;
|
|
31
|
+
if (options.atomic === true) {
|
|
32
|
+
if (joins.length > 0) {
|
|
33
|
+
throw new Error('Atomic where updates do not support predicates that require joins');
|
|
34
|
+
}
|
|
35
|
+
if (!shouldUseOptimizedUpsertRow({
|
|
36
|
+
data,
|
|
37
|
+
fields: collection.flattenedFields
|
|
38
|
+
})) {
|
|
39
|
+
throw new Error('Atomic where updates only support fields stored on the main table');
|
|
40
|
+
}
|
|
41
|
+
const { arraysToPush, row } = transformForWrite({
|
|
42
|
+
adapter: this,
|
|
43
|
+
data,
|
|
44
|
+
enableAtomicWrites: true,
|
|
45
|
+
fields: collection.flattenedFields,
|
|
46
|
+
tableName
|
|
47
|
+
});
|
|
48
|
+
if (arraysToPush && Object.keys(arraysToPush).length) {
|
|
49
|
+
throw new Error('Atomic where updates do not support array operations');
|
|
50
|
+
}
|
|
51
|
+
const table = this.tables[tableName];
|
|
52
|
+
const matchingRowQuery = db.select({
|
|
53
|
+
id: table.id
|
|
54
|
+
}).from(table).where(where).limit(1);
|
|
55
|
+
// PostgreSQL must lock the candidate before applying LIMIT so a waiting caller can
|
|
56
|
+
// continue to another match if a concurrent update makes the first row ineligible.
|
|
57
|
+
// NO KEY UPDATE permits concurrent foreign-key checks on the candidate.
|
|
58
|
+
// SQLite serializes writers and does not support SELECT ... FOR UPDATE.
|
|
59
|
+
const matchingRow = this.name === 'postgres' ? matchingRowQuery.for('no key update') : matchingRowQuery;
|
|
60
|
+
markWrite(this);
|
|
61
|
+
const docs = await db.update(table).set(row).where(eq(table.id, matchingRow)).returning();
|
|
62
|
+
if (!docs[0]) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
return transform({
|
|
66
|
+
adapter: this,
|
|
67
|
+
config: this.payload.config,
|
|
68
|
+
data: docs[0],
|
|
69
|
+
fields: collection.flattenedFields,
|
|
70
|
+
joinQuery: false,
|
|
71
|
+
tableName
|
|
72
|
+
});
|
|
73
|
+
}
|
|
22
74
|
// selectDistinct will only return if there are joins
|
|
23
75
|
const selectDistinctResult = await selectDistinct({
|
|
24
76
|
adapter: this,
|
|
@@ -58,7 +110,8 @@ export const updateOne = async function updateOne({ id, collection: collectionSl
|
|
|
58
110
|
operation: 'update',
|
|
59
111
|
req,
|
|
60
112
|
select,
|
|
61
|
-
tableName
|
|
113
|
+
tableName,
|
|
114
|
+
where: whereToUpdate
|
|
62
115
|
});
|
|
63
116
|
if (returning === false) {
|
|
64
117
|
return null;
|
package/dist/updateOne.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/updateOne.ts"],"sourcesContent":["import type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { UpdateOne } from 'payload'\n\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter } from './types.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { upsertRow } from './upsertRow/index.js'\nimport { getPrimaryDb } from './utilities/getPrimaryDb.js'\nimport { getTransaction } from './utilities/getTransaction.js'\n\nexport const updateOne: UpdateOne = async function updateOne(\n this: DrizzleAdapter,\n {\n id,\n collection: collectionSlug,\n data,\n joins: joinQuery,\n locale,\n options = { upsert: false },\n req,\n returning,\n select,\n where: whereArg,\n },\n) {\n const collection = this.payload.collections[collectionSlug].config\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n let idToUpdate = id\n\n const db = getPrimaryDb(this, await getTransaction(this, req))\n\n if (!idToUpdate) {\n const { joins, selectFields, where } = buildQuery({\n adapter: this,\n fields: collection.flattenedFields,\n locale,\n tableName,\n where: whereArg,\n })\n\n // selectDistinct will only return if there are joins\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n db,\n joins,\n query: ({ query }) => query.limit(1),\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n idToUpdate = selectDistinctResult?.[0]?.id\n // If id wasn't passed but `where` without any joins, retrieve it with findFirst\n } else if (whereArg && !joins.length) {\n const table = this.tables[tableName]\n\n const docsToUpdate = await (db as LibSQLDatabase)\n .select({\n id: table.id,\n })\n .from(table)\n .where(where)\n .limit(1)\n idToUpdate = docsToUpdate?.[0]?.id\n }\n }\n\n if (!idToUpdate && !options.upsert) {\n // TODO: In 4.0, if returning === false, we should differentiate between:\n // - No document found to update\n // - Document found, but returning === false\n return null\n }\n\n const result = await upsertRow({\n id: idToUpdate,\n adapter: this,\n collectionSlug,\n data,\n db,\n fields: collection.flattenedFields,\n ignoreResult: returning === false,\n joinQuery,\n operation: 'update',\n req,\n select,\n tableName,\n })\n\n if (returning === false) {\n return null\n }\n\n return result\n}\n"],"names":["toSnakeCase","buildQuery","selectDistinct","upsertRow","getPrimaryDb","getTransaction","updateOne","id","collection","collectionSlug","data","joins","joinQuery","locale","options","upsert","req","returning","select","where","whereArg","payload","collections","config","tableName","tableNameMap","get","slug","idToUpdate","db","selectFields","adapter","fields","flattenedFields","
|
|
1
|
+
{"version":3,"sources":["../src/updateOne.ts"],"sourcesContent":["import type { SQL } from 'drizzle-orm'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { UpdateOne } from 'payload'\n\nimport { eq } from 'drizzle-orm'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { DrizzleAdapter, PostgresDB } from './types.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { transform } from './transform/read/index.js'\nimport { transformForWrite } from './transform/write/index.js'\nimport { upsertRow } from './upsertRow/index.js'\nimport { shouldUseOptimizedUpsertRow } from './upsertRow/shouldUseOptimizedUpsertRow.js'\nimport { getPrimaryDb } from './utilities/getPrimaryDb.js'\nimport { getTransaction } from './utilities/getTransaction.js'\nimport { markWrite } from './utilities/readAfterWrite.js'\n\nexport const updateOne: UpdateOne = async function updateOne(\n this: DrizzleAdapter,\n {\n id,\n collection: collectionSlug,\n data,\n joins: joinQuery,\n locale,\n options = { upsert: false },\n req,\n returning,\n select,\n where: whereArg,\n },\n) {\n const collection = this.payload.collections[collectionSlug].config\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n let idToUpdate = id\n let whereToUpdate: SQL<unknown> | undefined\n\n const db = getPrimaryDb(this, await getTransaction(this, req))\n\n if (!idToUpdate) {\n const { joins, selectFields, where } = buildQuery({\n adapter: this,\n fields: collection.flattenedFields,\n locale,\n tableName,\n where: whereArg,\n })\n // A `where` that needs joins cannot be applied to the UPDATE statement itself, so those\n // queries keep resolving a matching id first and then update that row unconditionally\n whereToUpdate = joins.length === 0 ? where : undefined\n\n if (options.atomic === true) {\n if (joins.length > 0) {\n throw new Error('Atomic where updates do not support predicates that require joins')\n }\n\n if (!shouldUseOptimizedUpsertRow({ data, fields: collection.flattenedFields })) {\n throw new Error('Atomic where updates only support fields stored on the main table')\n }\n\n const { arraysToPush, row } = transformForWrite({\n adapter: this,\n data,\n enableAtomicWrites: true,\n fields: collection.flattenedFields,\n tableName,\n })\n\n if (arraysToPush && Object.keys(arraysToPush).length) {\n throw new Error('Atomic where updates do not support array operations')\n }\n\n const table = this.tables[tableName]\n const matchingRowQuery = (db as PostgresDB)\n .select({ id: table.id })\n .from(table)\n .where(where)\n .limit(1)\n\n // PostgreSQL must lock the candidate before applying LIMIT so a waiting caller can\n // continue to another match if a concurrent update makes the first row ineligible.\n // NO KEY UPDATE permits concurrent foreign-key checks on the candidate.\n // SQLite serializes writers and does not support SELECT ... FOR UPDATE.\n const matchingRow =\n this.name === 'postgres' ? matchingRowQuery.for('no key update') : matchingRowQuery\n\n markWrite(this)\n\n const docs = await (db as LibSQLDatabase)\n .update(table)\n .set(row)\n .where(eq(table.id, matchingRow))\n .returning()\n\n if (!docs[0]) {\n return null\n }\n\n return transform({\n adapter: this,\n config: this.payload.config,\n data: docs[0],\n fields: collection.flattenedFields,\n joinQuery: false,\n tableName,\n })\n }\n\n // selectDistinct will only return if there are joins\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n db,\n joins,\n query: ({ query }) => query.limit(1),\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n idToUpdate = selectDistinctResult?.[0]?.id\n // If id wasn't passed but `where` without any joins, retrieve it with findFirst\n } else if (whereArg && !joins.length) {\n const table = this.tables[tableName]\n\n const docsToUpdate = await (db as LibSQLDatabase)\n .select({\n id: table.id,\n })\n .from(table)\n .where(where)\n .limit(1)\n idToUpdate = docsToUpdate?.[0]?.id\n }\n }\n\n if (!idToUpdate && !options.upsert) {\n // TODO: In 4.0, if returning === false, we should differentiate between:\n // - No document found to update\n // - Document found, but returning === false\n return null\n }\n\n const result = await upsertRow({\n id: idToUpdate,\n adapter: this,\n collectionSlug,\n data,\n db,\n fields: collection.flattenedFields,\n ignoreResult: returning === false,\n joinQuery,\n operation: 'update',\n req,\n select,\n tableName,\n where: whereToUpdate,\n })\n\n if (returning === false) {\n return null\n }\n\n return result\n}\n"],"names":["eq","toSnakeCase","buildQuery","selectDistinct","transform","transformForWrite","upsertRow","shouldUseOptimizedUpsertRow","getPrimaryDb","getTransaction","markWrite","updateOne","id","collection","collectionSlug","data","joins","joinQuery","locale","options","upsert","req","returning","select","where","whereArg","payload","collections","config","tableName","tableNameMap","get","slug","idToUpdate","whereToUpdate","db","selectFields","adapter","fields","flattenedFields","length","undefined","atomic","Error","arraysToPush","row","enableAtomicWrites","Object","keys","table","tables","matchingRowQuery","from","limit","matchingRow","name","for","docs","update","set","selectDistinctResult","query","docsToUpdate","result","ignoreResult","operation"],"mappings":"AAIA,SAASA,EAAE,QAAQ,cAAa;AAChC,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,SAAS,QAAQ,4BAA2B;AACrD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,2BAA2B,QAAQ,6CAA4C;AACxF,SAASC,YAAY,QAAQ,8BAA6B;AAC1D,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,SAAS,QAAQ,gCAA+B;AAEzD,OAAO,MAAMC,YAAuB,eAAeA,UAEjD,EACEC,EAAE,EACFC,YAAYC,cAAc,EAC1BC,IAAI,EACJC,OAAOC,SAAS,EAChBC,MAAM,EACNC,UAAU;IAAEC,QAAQ;AAAM,CAAC,EAC3BC,GAAG,EACHC,SAAS,EACTC,MAAM,EACNC,OAAOC,QAAQ,EAChB;IAED,MAAMZ,aAAa,IAAI,CAACa,OAAO,CAACC,WAAW,CAACb,eAAe,CAACc,MAAM;IAClE,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAC9B,YAAYY,WAAWmB,IAAI;IACnE,IAAIC,aAAarB;IACjB,IAAIsB;IAEJ,MAAMC,KAAK3B,aAAa,IAAI,EAAE,MAAMC,eAAe,IAAI,EAAEY;IAEzD,IAAI,CAACY,YAAY;QACf,MAAM,EAAEjB,KAAK,EAAEoB,YAAY,EAAEZ,KAAK,EAAE,GAAGtB,WAAW;YAChDmC,SAAS,IAAI;YACbC,QAAQzB,WAAW0B,eAAe;YAClCrB;YACAW;YACAL,OAAOC;QACT;QACA,wFAAwF;QACxF,sFAAsF;QACtFS,gBAAgBlB,MAAMwB,MAAM,KAAK,IAAIhB,QAAQiB;QAE7C,IAAItB,QAAQuB,MAAM,KAAK,MAAM;YAC3B,IAAI1B,MAAMwB,MAAM,GAAG,GAAG;gBACpB,MAAM,IAAIG,MAAM;YAClB;YAEA,IAAI,CAACpC,4BAA4B;gBAAEQ;gBAAMuB,QAAQzB,WAAW0B,eAAe;YAAC,IAAI;gBAC9E,MAAM,IAAII,MAAM;YAClB;YAEA,MAAM,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGxC,kBAAkB;gBAC9CgC,SAAS,IAAI;gBACbtB;gBACA+B,oBAAoB;gBACpBR,QAAQzB,WAAW0B,eAAe;gBAClCV;YACF;YAEA,IAAIe,gBAAgBG,OAAOC,IAAI,CAACJ,cAAcJ,MAAM,EAAE;gBACpD,MAAM,IAAIG,MAAM;YAClB;YAEA,MAAMM,QAAQ,IAAI,CAACC,MAAM,CAACrB,UAAU;YACpC,MAAMsB,mBAAmB,AAAChB,GACvBZ,MAAM,CAAC;gBAAEX,IAAIqC,MAAMrC,EAAE;YAAC,GACtBwC,IAAI,CAACH,OACLzB,KAAK,CAACA,OACN6B,KAAK,CAAC;YAET,mFAAmF;YACnF,mFAAmF;YACnF,wEAAwE;YACxE,wEAAwE;YACxE,MAAMC,cACJ,IAAI,CAACC,IAAI,KAAK,aAAaJ,iBAAiBK,GAAG,CAAC,mBAAmBL;YAErEzC,UAAU,IAAI;YAEd,MAAM+C,OAAO,MAAM,AAACtB,GACjBuB,MAAM,CAACT,OACPU,GAAG,CAACd,KACJrB,KAAK,CAACxB,GAAGiD,MAAMrC,EAAE,EAAE0C,cACnBhC,SAAS;YAEZ,IAAI,CAACmC,IAAI,CAAC,EAAE,EAAE;gBACZ,OAAO;YACT;YAEA,OAAOrD,UAAU;gBACfiC,SAAS,IAAI;gBACbT,QAAQ,IAAI,CAACF,OAAO,CAACE,MAAM;gBAC3Bb,MAAM0C,IAAI,CAAC,EAAE;gBACbnB,QAAQzB,WAAW0B,eAAe;gBAClCtB,WAAW;gBACXY;YACF;QACF;QAEA,qDAAqD;QACrD,MAAM+B,uBAAuB,MAAMzD,eAAe;YAChDkC,SAAS,IAAI;YACbF;YACAnB;YACA6C,OAAO,CAAC,EAAEA,KAAK,EAAE,GAAKA,MAAMR,KAAK,CAAC;YAClCjB;YACAP;YACAL;QACF;QAEA,IAAIoC,sBAAsB,CAAC,EAAE,EAAEhD,IAAI;YACjCqB,aAAa2B,sBAAsB,CAAC,EAAE,EAAEhD;QACxC,gFAAgF;QAClF,OAAO,IAAIa,YAAY,CAACT,MAAMwB,MAAM,EAAE;YACpC,MAAMS,QAAQ,IAAI,CAACC,MAAM,CAACrB,UAAU;YAEpC,MAAMiC,eAAe,MAAM,AAAC3B,GACzBZ,MAAM,CAAC;gBACNX,IAAIqC,MAAMrC,EAAE;YACd,GACCwC,IAAI,CAACH,OACLzB,KAAK,CAACA,OACN6B,KAAK,CAAC;YACTpB,aAAa6B,cAAc,CAAC,EAAE,EAAElD;QAClC;IACF;IAEA,IAAI,CAACqB,cAAc,CAACd,QAAQC,MAAM,EAAE;QAClC,yEAAyE;QACzE,gCAAgC;QAChC,4CAA4C;QAC5C,OAAO;IACT;IAEA,MAAM2C,SAAS,MAAMzD,UAAU;QAC7BM,IAAIqB;QACJI,SAAS,IAAI;QACbvB;QACAC;QACAoB;QACAG,QAAQzB,WAAW0B,eAAe;QAClCyB,cAAc1C,cAAc;QAC5BL;QACAgD,WAAW;QACX5C;QACAE;QACAM;QACAL,OAAOU;IACT;IAEA,IAAIZ,cAAc,OAAO;QACvB,OAAO;IACT;IAEA,OAAOyC;AACT,EAAC"}
|
|
@@ -6,9 +6,14 @@ type Args = {
|
|
|
6
6
|
parentColumnName?: string;
|
|
7
7
|
parentID: unknown;
|
|
8
8
|
pathColumnName?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Paths beginning with any of these prefixes are deleted, on top of the exact paths collected
|
|
11
|
+
* from `rows`. Used to clear rows left at array indexes the incoming data no longer occupies.
|
|
12
|
+
*/
|
|
13
|
+
pathPrefixesToDelete?: Set<string>;
|
|
9
14
|
rows: Record<string, unknown>[];
|
|
10
15
|
tableName: string;
|
|
11
16
|
};
|
|
12
|
-
export declare const deleteExistingRowsByPath: ({ adapter, db, localeColumnName, parentColumnName, parentID, pathColumnName, rows, tableName, }: Args) => Promise<void>;
|
|
17
|
+
export declare const deleteExistingRowsByPath: ({ adapter, db, localeColumnName, parentColumnName, parentID, pathColumnName, pathPrefixesToDelete, rows, tableName, }: Args) => Promise<void>;
|
|
13
18
|
export {};
|
|
14
19
|
//# sourceMappingURL=deleteExistingRowsByPath.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deleteExistingRowsByPath.d.ts","sourceRoot":"","sources":["../../src/upsertRow/deleteExistingRowsByPath.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAErE,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,cAAc,CAAA;IACvB,EAAE,EAAE,cAAc,CAAC,SAAS,CAAC,GAAG,kBAAkB,CAAA;IAClD,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IAC/B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;
|
|
1
|
+
{"version":3,"file":"deleteExistingRowsByPath.d.ts","sourceRoot":"","sources":["../../src/upsertRow/deleteExistingRowsByPath.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAErE,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,cAAc,CAAA;IACvB,EAAE,EAAE,cAAc,CAAC,SAAS,CAAC,GAAG,kBAAkB,CAAA;IAClD,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,OAAO,CAAA;IACjB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;;OAGG;IACH,oBAAoB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAClC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IAC/B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAQD,eAAO,MAAM,wBAAwB,0HAUlC,IAAI,KAAG,OAAO,CAAC,IAAI,CAiErB,CAAA"}
|
|
@@ -1,8 +1,16 @@
|
|
|
1
|
-
import { and, eq, inArray } from 'drizzle-orm';
|
|
2
|
-
|
|
1
|
+
import { and, eq, inArray, or, sql } from 'drizzle-orm';
|
|
2
|
+
/**
|
|
3
|
+
* `_` and `%` are `LIKE` wildcards, and both are legal characters in a Payload field name, so they
|
|
4
|
+
* have to be escaped to keep a prefix from matching sibling paths.
|
|
5
|
+
*/ const escapeLikePattern = (value)=>value.replace(/[\\%_]/g, '\\$&');
|
|
6
|
+
export const deleteExistingRowsByPath = async ({ adapter, db, localeColumnName = '_locale', parentColumnName = '_parentID', parentID, pathColumnName = '_path', pathPrefixesToDelete, rows, tableName })=>{
|
|
7
|
+
const table = adapter.tables[tableName];
|
|
8
|
+
// `_texts` / `_numbers` tables only exist when the schema has a hasMany text/number field
|
|
9
|
+
if (!table) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
3
12
|
const localizedPathsToDelete = new Set();
|
|
4
13
|
const pathsToDelete = new Set();
|
|
5
|
-
const table = adapter.tables[tableName];
|
|
6
14
|
rows.forEach((row)=>{
|
|
7
15
|
const path = row[pathColumnName];
|
|
8
16
|
const localeData = row[localeColumnName];
|
|
@@ -14,6 +22,16 @@ export const deleteExistingRowsByPath = async ({ adapter, db, localeColumnName =
|
|
|
14
22
|
}
|
|
15
23
|
}
|
|
16
24
|
});
|
|
25
|
+
// Deleted without a locale constraint on purpose - the array rows these belong to are themselves
|
|
26
|
+
// wiped for every locale by `deleteExistingArrayRows` and re-inserted from the incoming data.
|
|
27
|
+
if (pathPrefixesToDelete && pathPrefixesToDelete.size > 0) {
|
|
28
|
+
const prefixConstraints = Array.from(pathPrefixesToDelete, (prefix)=>sql`${table[pathColumnName]} like ${`${escapeLikePattern(prefix)}%`} escape '\\'`);
|
|
29
|
+
await adapter.deleteWhere({
|
|
30
|
+
db,
|
|
31
|
+
tableName,
|
|
32
|
+
where: and(eq(table[parentColumnName], parentID), or(...prefixConstraints))
|
|
33
|
+
});
|
|
34
|
+
}
|
|
17
35
|
if (localizedPathsToDelete.size > 0) {
|
|
18
36
|
const whereConstraints = [
|
|
19
37
|
eq(table[parentColumnName], parentID)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/upsertRow/deleteExistingRowsByPath.ts"],"sourcesContent":["import { and, eq, inArray } from 'drizzle-orm'\n\nimport type { DrizzleAdapter, DrizzleTransaction } from '../types.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n db: DrizzleAdapter['drizzle'] | DrizzleTransaction\n localeColumnName?: string\n parentColumnName?: string\n parentID: unknown\n pathColumnName?: string\n rows: Record<string, unknown>[]\n tableName: string\n}\n\nexport const deleteExistingRowsByPath = async ({\n adapter,\n db,\n localeColumnName = '_locale',\n parentColumnName = '_parentID',\n parentID,\n pathColumnName = '_path',\n rows,\n tableName,\n}: Args): Promise<void> => {\n const
|
|
1
|
+
{"version":3,"sources":["../../src/upsertRow/deleteExistingRowsByPath.ts"],"sourcesContent":["import { and, eq, inArray, or, sql } from 'drizzle-orm'\n\nimport type { DrizzleAdapter, DrizzleTransaction } from '../types.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n db: DrizzleAdapter['drizzle'] | DrizzleTransaction\n localeColumnName?: string\n parentColumnName?: string\n parentID: unknown\n pathColumnName?: string\n /**\n * Paths beginning with any of these prefixes are deleted, on top of the exact paths collected\n * from `rows`. Used to clear rows left at array indexes the incoming data no longer occupies.\n */\n pathPrefixesToDelete?: Set<string>\n rows: Record<string, unknown>[]\n tableName: string\n}\n\n/**\n * `_` and `%` are `LIKE` wildcards, and both are legal characters in a Payload field name, so they\n * have to be escaped to keep a prefix from matching sibling paths.\n */\nconst escapeLikePattern = (value: string): string => value.replace(/[\\\\%_]/g, '\\\\$&')\n\nexport const deleteExistingRowsByPath = async ({\n adapter,\n db,\n localeColumnName = '_locale',\n parentColumnName = '_parentID',\n parentID,\n pathColumnName = '_path',\n pathPrefixesToDelete,\n rows,\n tableName,\n}: Args): Promise<void> => {\n const table = adapter.tables[tableName]\n\n // `_texts` / `_numbers` tables only exist when the schema has a hasMany text/number field\n if (!table) {\n return\n }\n\n const localizedPathsToDelete = new Set<string>()\n const pathsToDelete = new Set<string>()\n\n rows.forEach((row) => {\n const path = row[pathColumnName]\n const localeData = row[localeColumnName]\n if (typeof path === 'string') {\n if (typeof localeData === 'string') {\n localizedPathsToDelete.add(path)\n } else {\n pathsToDelete.add(path)\n }\n }\n })\n\n // Deleted without a locale constraint on purpose - the array rows these belong to are themselves\n // wiped for every locale by `deleteExistingArrayRows` and re-inserted from the incoming data.\n if (pathPrefixesToDelete && pathPrefixesToDelete.size > 0) {\n const prefixConstraints = Array.from(\n pathPrefixesToDelete,\n (prefix) => sql`${table[pathColumnName]} like ${`${escapeLikePattern(prefix)}%`} escape '\\\\'`,\n )\n\n await adapter.deleteWhere({\n db,\n tableName,\n where: and(eq(table[parentColumnName], parentID), or(...prefixConstraints)),\n })\n }\n\n if (localizedPathsToDelete.size > 0) {\n const whereConstraints = [eq(table[parentColumnName], parentID)]\n\n if (pathColumnName) {\n whereConstraints.push(inArray(table[pathColumnName], Array.from(localizedPathsToDelete)))\n }\n\n await adapter.deleteWhere({\n db,\n tableName,\n where: and(...whereConstraints),\n })\n }\n\n if (pathsToDelete.size > 0) {\n const whereConstraints = [eq(table[parentColumnName], parentID)]\n\n if (pathColumnName) {\n whereConstraints.push(inArray(table[pathColumnName], Array.from(pathsToDelete)))\n }\n\n await adapter.deleteWhere({\n db,\n tableName,\n where: and(...whereConstraints),\n })\n }\n}\n"],"names":["and","eq","inArray","or","sql","escapeLikePattern","value","replace","deleteExistingRowsByPath","adapter","db","localeColumnName","parentColumnName","parentID","pathColumnName","pathPrefixesToDelete","rows","tableName","table","tables","localizedPathsToDelete","Set","pathsToDelete","forEach","row","path","localeData","add","size","prefixConstraints","Array","from","prefix","deleteWhere","where","whereConstraints","push"],"mappings":"AAAA,SAASA,GAAG,EAAEC,EAAE,EAAEC,OAAO,EAAEC,EAAE,EAAEC,GAAG,QAAQ,cAAa;AAoBvD;;;CAGC,GACD,MAAMC,oBAAoB,CAACC,QAA0BA,MAAMC,OAAO,CAAC,WAAW;AAE9E,OAAO,MAAMC,2BAA2B,OAAO,EAC7CC,OAAO,EACPC,EAAE,EACFC,mBAAmB,SAAS,EAC5BC,mBAAmB,WAAW,EAC9BC,QAAQ,EACRC,iBAAiB,OAAO,EACxBC,oBAAoB,EACpBC,IAAI,EACJC,SAAS,EACJ;IACL,MAAMC,QAAQT,QAAQU,MAAM,CAACF,UAAU;IAEvC,0FAA0F;IAC1F,IAAI,CAACC,OAAO;QACV;IACF;IAEA,MAAME,yBAAyB,IAAIC;IACnC,MAAMC,gBAAgB,IAAID;IAE1BL,KAAKO,OAAO,CAAC,CAACC;QACZ,MAAMC,OAAOD,GAAG,CAACV,eAAe;QAChC,MAAMY,aAAaF,GAAG,CAACb,iBAAiB;QACxC,IAAI,OAAOc,SAAS,UAAU;YAC5B,IAAI,OAAOC,eAAe,UAAU;gBAClCN,uBAAuBO,GAAG,CAACF;YAC7B,OAAO;gBACLH,cAAcK,GAAG,CAACF;YACpB;QACF;IACF;IAEA,iGAAiG;IACjG,8FAA8F;IAC9F,IAAIV,wBAAwBA,qBAAqBa,IAAI,GAAG,GAAG;QACzD,MAAMC,oBAAoBC,MAAMC,IAAI,CAClChB,sBACA,CAACiB,SAAW5B,GAAG,CAAC,EAAEc,KAAK,CAACJ,eAAe,CAAC,MAAM,EAAE,GAAGT,kBAAkB2B,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC;QAG/F,MAAMvB,QAAQwB,WAAW,CAAC;YACxBvB;YACAO;YACAiB,OAAOlC,IAAIC,GAAGiB,KAAK,CAACN,iBAAiB,EAAEC,WAAWV,MAAM0B;QAC1D;IACF;IAEA,IAAIT,uBAAuBQ,IAAI,GAAG,GAAG;QACnC,MAAMO,mBAAmB;YAAClC,GAAGiB,KAAK,CAACN,iBAAiB,EAAEC;SAAU;QAEhE,IAAIC,gBAAgB;YAClBqB,iBAAiBC,IAAI,CAAClC,QAAQgB,KAAK,CAACJ,eAAe,EAAEgB,MAAMC,IAAI,CAACX;QAClE;QAEA,MAAMX,QAAQwB,WAAW,CAAC;YACxBvB;YACAO;YACAiB,OAAOlC,OAAOmC;QAChB;IACF;IAEA,IAAIb,cAAcM,IAAI,GAAG,GAAG;QAC1B,MAAMO,mBAAmB;YAAClC,GAAGiB,KAAK,CAACN,iBAAiB,EAAEC;SAAU;QAEhE,IAAIC,gBAAgB;YAClBqB,iBAAiBC,IAAI,CAAClC,QAAQgB,KAAK,CAACJ,eAAe,EAAEgB,MAAMC,IAAI,CAACT;QAClE;QAEA,MAAMb,QAAQwB,WAAW,CAAC;YACxBvB;YACAO;YACAiB,OAAOlC,OAAOmC;QAChB;IACF;AACF,EAAC"}
|
|
@@ -7,5 +7,5 @@ import type { Args } from './types.js';
|
|
|
7
7
|
*
|
|
8
8
|
* adapter function replaces the entire row and does not support partial updates.
|
|
9
9
|
*/
|
|
10
|
-
export declare const upsertRow: <T extends Record<string, unknown> | TypeWithID>({ id, adapter, collectionSlug, data, db, fields, globalSlug, ignoreResult, customID, joinQuery: _joinQuery, operation, path, req, select, tableName, upsertTarget, where, }: Args) => Promise<T>;
|
|
10
|
+
export declare const upsertRow: <T extends Record<string, unknown> | TypeWithID>({ id, adapter, collectionSlug, data, db, fields, globalSlug, ignoreResult, customID, joinQuery: _joinQuery, operation, path, req, select, tableName, upsertTarget, where, }: Args) => Promise<null | T>;
|
|
11
11
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upsertRow/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/upsertRow/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAKzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAqBtC;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,+KAqB3E,IAAI,KAAG,OAAO,CAAC,IAAI,GAAG,CAAC,CA0uBzB,CAAA"}
|
package/dist/upsertRow/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { and, desc, eq, isNull, or } from 'drizzle-orm';
|
|
1
|
+
import { and, desc, eq, getTableColumns, isNull, or } from 'drizzle-orm';
|
|
2
2
|
import { buildFindManyArgs } from '../find/buildFindManyArgs.js';
|
|
3
3
|
import { transform } from '../transform/read/index.js';
|
|
4
4
|
import { transformForWrite } from '../transform/write/index.js';
|
|
@@ -40,6 +40,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
40
40
|
const { row } = transformedForWrite;
|
|
41
41
|
const { arraysToPush } = transformedForWrite;
|
|
42
42
|
const drizzle = db;
|
|
43
|
+
const updateWhere = where ? and(eq(adapter.tables[tableName].id, id), where) : eq(adapter.tables[tableName].id, id);
|
|
43
44
|
// First, handle $push arrays
|
|
44
45
|
if (arraysToPush && Object.keys(arraysToPush)?.length) {
|
|
45
46
|
await insertArrays({
|
|
@@ -65,7 +66,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
65
66
|
if (hasDataToUpdate) {
|
|
66
67
|
// Only update row if there is something to update.
|
|
67
68
|
// Example: if the data only consists of a single $push, calling insertArrays is enough - we don't need to update the row.
|
|
68
|
-
await drizzle.update(adapter.tables[tableName]).set(row).where(
|
|
69
|
+
await drizzle.update(adapter.tables[tableName]).set(row).where(updateWhere);
|
|
69
70
|
}
|
|
70
71
|
return ignoreResult === 'idOnly' ? {
|
|
71
72
|
id
|
|
@@ -83,8 +84,11 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
83
84
|
const hasOnlyColumns = Object.keys(findManyArgs.columns || {}).length > 0;
|
|
84
85
|
if (!hasDataToUpdate) {
|
|
85
86
|
// Nothing to update => just fetch current row and return
|
|
86
|
-
findManyArgs.where =
|
|
87
|
+
findManyArgs.where = updateWhere;
|
|
87
88
|
const doc = await db.query[tableName].findFirst(findManyArgs);
|
|
89
|
+
if (!doc) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
88
92
|
return transform({
|
|
89
93
|
adapter,
|
|
90
94
|
config: adapter.payload.config,
|
|
@@ -97,15 +101,14 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
97
101
|
if (findManyKeysLength === 0 || hasOnlyColumns) {
|
|
98
102
|
// Optimization - No need for joins => can simply use returning(). This is optimal for very simple collections
|
|
99
103
|
// without complex fields that live in separate tables like blocks, arrays, relationships, etc.
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
const returningFields = buildReturningFields({
|
|
105
|
+
findManyArgs,
|
|
106
|
+
table: adapter.tables[tableName]
|
|
107
|
+
});
|
|
108
|
+
const docs = await drizzle.update(adapter.tables[tableName]).set(row).where(updateWhere).returning(returningFields);
|
|
109
|
+
if (!docs[0]) {
|
|
110
|
+
return null;
|
|
107
111
|
}
|
|
108
|
-
const docs = await drizzle.update(adapter.tables[tableName]).set(row).where(eq(adapter.tables[tableName].id, id)).returning(Object.keys(selectedFields).length ? selectedFields : undefined);
|
|
109
112
|
return transform({
|
|
110
113
|
adapter,
|
|
111
114
|
config: adapter.payload.config,
|
|
@@ -116,7 +119,13 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
116
119
|
});
|
|
117
120
|
}
|
|
118
121
|
// DB Update that needs the result, potentially with joins => need to update first, then find. returning() does not work with joins.
|
|
119
|
-
await drizzle.update(adapter.tables[tableName]).set(row).where(
|
|
122
|
+
const docs = await drizzle.update(adapter.tables[tableName]).set(row).where(updateWhere).returning({
|
|
123
|
+
id: adapter.tables[tableName].id
|
|
124
|
+
});
|
|
125
|
+
if (!docs[0]) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
insertedRow = docs[0];
|
|
120
129
|
findManyArgs.where = eq(adapter.tables[tableName].id, insertedRow.id);
|
|
121
130
|
const doc = await db.query[tableName].findFirst(findManyArgs);
|
|
122
131
|
return transform({
|
|
@@ -168,7 +177,11 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
168
177
|
rowToInsert.row.id = id;
|
|
169
178
|
[insertedRow] = await adapter.insert({
|
|
170
179
|
db,
|
|
171
|
-
onConflictDoUpdate: {
|
|
180
|
+
onConflictDoUpdate: where ? {
|
|
181
|
+
set: rowToInsert.row,
|
|
182
|
+
target,
|
|
183
|
+
where
|
|
184
|
+
} : {
|
|
172
185
|
set: rowToInsert.row,
|
|
173
186
|
target
|
|
174
187
|
},
|
|
@@ -188,6 +201,9 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
188
201
|
values: rowToInsert.row
|
|
189
202
|
});
|
|
190
203
|
}
|
|
204
|
+
if (!insertedRow) {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
191
207
|
} else {
|
|
192
208
|
// No main row data to update, just use the existing ID
|
|
193
209
|
insertedRow = {
|
|
@@ -300,6 +316,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
300
316
|
parentColumnName: 'parent',
|
|
301
317
|
parentID: insertedRow.id,
|
|
302
318
|
pathColumnName: 'path',
|
|
319
|
+
pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,
|
|
303
320
|
rows: [
|
|
304
321
|
...relationsToInsert,
|
|
305
322
|
...generalRelationshipDeletes
|
|
@@ -472,6 +489,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
472
489
|
parentColumnName: 'parent',
|
|
473
490
|
parentID: insertedRow.id,
|
|
474
491
|
pathColumnName: 'path',
|
|
492
|
+
pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,
|
|
475
493
|
rows: [
|
|
476
494
|
...textsToInsert,
|
|
477
495
|
...rowToInsert.textsToDelete
|
|
@@ -498,6 +516,7 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
498
516
|
parentColumnName: 'parent',
|
|
499
517
|
parentID: insertedRow.id,
|
|
500
518
|
pathColumnName: 'path',
|
|
519
|
+
pathPrefixesToDelete: rowToInsert.pathPrefixesToDelete,
|
|
501
520
|
rows: [
|
|
502
521
|
...numbersToInsert,
|
|
503
522
|
...rowToInsert.numbersToDelete
|
|
@@ -667,5 +686,30 @@ customID, joinQuery: _joinQuery, operation, path = '', req, select, tableName, u
|
|
|
667
686
|
});
|
|
668
687
|
return result;
|
|
669
688
|
};
|
|
689
|
+
/**
|
|
690
|
+
* Builds the `RETURNING` selection for the single-query update path so it yields the same shape as
|
|
691
|
+
* `findFirst(findManyArgs)`: columns excluded by `findManyArgs.columns` are skipped and
|
|
692
|
+
* `findManyArgs.extras` are included. Point columns rely on this - they are excluded as raw
|
|
693
|
+
* columns and selected through an `ST_AsGeoJSON` extra instead.
|
|
694
|
+
*/ function buildReturningFields({ findManyArgs, table }) {
|
|
695
|
+
const columns = findManyArgs.columns ?? {};
|
|
696
|
+
const extras = findManyArgs.extras ?? {};
|
|
697
|
+
const hasIncludedColumns = Object.values(columns).some(Boolean);
|
|
698
|
+
const returningFields = {};
|
|
699
|
+
if (hasIncludedColumns) {
|
|
700
|
+
for (const [columnName, isIncluded] of Object.entries(columns)){
|
|
701
|
+
if (isIncluded) {
|
|
702
|
+
returningFields[columnName] = table[columnName];
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
} else {
|
|
706
|
+
for (const [columnName, column] of Object.entries(getTableColumns(table))){
|
|
707
|
+
if (columns[columnName] !== false) {
|
|
708
|
+
returningFields[columnName] = column;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return Object.assign(returningFields, extras);
|
|
713
|
+
}
|
|
670
714
|
|
|
671
715
|
//# sourceMappingURL=index.js.map
|