@prisma-next/target-mongo 0.3.0 → 0.4.0-dev.2

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.
@@ -0,0 +1,277 @@
1
+ import type { MigrationOperationClass } from '@prisma-next/framework-components/control';
2
+ import {
3
+ type AnyMongoDdlCommand,
4
+ type AnyMongoInspectionCommand,
5
+ CollModCommand,
6
+ CreateCollectionCommand,
7
+ CreateIndexCommand,
8
+ DropCollectionCommand,
9
+ DropIndexCommand,
10
+ ListCollectionsCommand,
11
+ ListIndexesCommand,
12
+ MongoAndExpr,
13
+ MongoExistsExpr,
14
+ MongoFieldFilter,
15
+ type MongoFilterExpr,
16
+ type MongoMigrationCheck,
17
+ type MongoMigrationPlanOperation,
18
+ type MongoMigrationStep,
19
+ MongoNotExpr,
20
+ MongoOrExpr,
21
+ } from '@prisma-next/mongo-query-ast/control';
22
+ import { type } from 'arktype';
23
+
24
+ const IndexKeyDirection = type('1 | -1 | "text" | "2dsphere" | "2d" | "hashed"');
25
+ const IndexKeyJson = type({ field: 'string', direction: IndexKeyDirection });
26
+
27
+ const CreateIndexJson = type({
28
+ kind: '"createIndex"',
29
+ collection: 'string',
30
+ keys: IndexKeyJson.array().atLeastLength(1),
31
+ 'unique?': 'boolean',
32
+ 'sparse?': 'boolean',
33
+ 'expireAfterSeconds?': 'number',
34
+ 'partialFilterExpression?': 'Record<string, unknown>',
35
+ 'name?': 'string',
36
+ 'wildcardProjection?': 'Record<string, unknown>',
37
+ 'collation?': 'Record<string, unknown>',
38
+ 'weights?': 'Record<string, unknown>',
39
+ 'default_language?': 'string',
40
+ 'language_override?': 'string',
41
+ });
42
+
43
+ const DropIndexJson = type({
44
+ kind: '"dropIndex"',
45
+ collection: 'string',
46
+ name: 'string',
47
+ });
48
+
49
+ const CreateCollectionJson = type({
50
+ kind: '"createCollection"',
51
+ collection: 'string',
52
+ 'validator?': 'Record<string, unknown>',
53
+ 'validationLevel?': '"strict" | "moderate"',
54
+ 'validationAction?': '"error" | "warn"',
55
+ 'capped?': 'boolean',
56
+ 'size?': 'number',
57
+ 'max?': 'number',
58
+ 'timeseries?': 'Record<string, unknown>',
59
+ 'collation?': 'Record<string, unknown>',
60
+ 'changeStreamPreAndPostImages?': 'Record<string, unknown>',
61
+ 'clusteredIndex?': 'Record<string, unknown>',
62
+ });
63
+
64
+ const DropCollectionJson = type({
65
+ kind: '"dropCollection"',
66
+ collection: 'string',
67
+ });
68
+
69
+ const CollModJson = type({
70
+ kind: '"collMod"',
71
+ collection: 'string',
72
+ 'validator?': 'Record<string, unknown>',
73
+ 'validationLevel?': '"strict" | "moderate"',
74
+ 'validationAction?': '"error" | "warn"',
75
+ 'changeStreamPreAndPostImages?': 'Record<string, unknown>',
76
+ });
77
+
78
+ const ListIndexesJson = type({
79
+ kind: '"listIndexes"',
80
+ collection: 'string',
81
+ });
82
+
83
+ const ListCollectionsJson = type({
84
+ kind: '"listCollections"',
85
+ });
86
+
87
+ const FieldFilterJson = type({
88
+ kind: '"field"',
89
+ field: 'string',
90
+ op: 'string',
91
+ value: 'unknown',
92
+ });
93
+
94
+ const ExistsFilterJson = type({
95
+ kind: '"exists"',
96
+ field: 'string',
97
+ exists: 'boolean',
98
+ });
99
+
100
+ const CheckJson = type({
101
+ description: 'string',
102
+ source: 'Record<string, unknown>',
103
+ filter: 'Record<string, unknown>',
104
+ expect: '"exists" | "notExists"',
105
+ });
106
+
107
+ const StepJson = type({
108
+ description: 'string',
109
+ command: 'Record<string, unknown>',
110
+ });
111
+
112
+ const OperationJson = type({
113
+ id: 'string',
114
+ label: 'string',
115
+ operationClass: '"additive" | "widening" | "destructive"',
116
+ precheck: 'Record<string, unknown>[]',
117
+ execute: 'Record<string, unknown>[]',
118
+ postcheck: 'Record<string, unknown>[]',
119
+ });
120
+
121
+ function validate<T>(schema: { assert: (data: unknown) => T }, data: unknown, context: string): T {
122
+ try {
123
+ return schema.assert(data);
124
+ } catch (error) {
125
+ /* v8 ignore start -- assertion libraries always throw Error instances */
126
+ const message = error instanceof Error ? error.message : String(error);
127
+ /* v8 ignore stop */
128
+ throw new Error(`Invalid ${context}: ${message}`);
129
+ }
130
+ }
131
+
132
+ function deserializeFilterExpr(json: unknown): MongoFilterExpr {
133
+ const record = json as Record<string, unknown>;
134
+ const kind = record['kind'] as string;
135
+ switch (kind) {
136
+ case 'field': {
137
+ const data = validate(FieldFilterJson, json, 'field filter');
138
+ return MongoFieldFilter.of(data.field, data.op, data.value as never);
139
+ }
140
+ case 'and': {
141
+ const exprs = record['exprs'];
142
+ if (!Array.isArray(exprs)) throw new Error('Invalid and filter: missing exprs array');
143
+ return MongoAndExpr.of(exprs.map(deserializeFilterExpr));
144
+ }
145
+ case 'or': {
146
+ const exprs = record['exprs'];
147
+ if (!Array.isArray(exprs)) throw new Error('Invalid or filter: missing exprs array');
148
+ return MongoOrExpr.of(exprs.map(deserializeFilterExpr));
149
+ }
150
+ case 'not': {
151
+ const expr = record['expr'];
152
+ if (!expr || typeof expr !== 'object') throw new Error('Invalid not filter: missing expr');
153
+ return new MongoNotExpr(deserializeFilterExpr(expr));
154
+ }
155
+ case 'exists': {
156
+ const data = validate(ExistsFilterJson, json, 'exists filter');
157
+ return new MongoExistsExpr(data.field, data.exists);
158
+ }
159
+ default:
160
+ throw new Error(`Unknown filter expression kind: ${kind}`);
161
+ }
162
+ }
163
+
164
+ function deserializeDdlCommand(json: unknown): AnyMongoDdlCommand {
165
+ const record = json as Record<string, unknown>;
166
+ const kind = record['kind'] as string;
167
+ switch (kind) {
168
+ case 'createIndex': {
169
+ const data = validate(CreateIndexJson, json, 'createIndex command');
170
+ return new CreateIndexCommand(data.collection, data.keys, {
171
+ unique: data.unique,
172
+ sparse: data.sparse,
173
+ expireAfterSeconds: data.expireAfterSeconds,
174
+ partialFilterExpression: data.partialFilterExpression,
175
+ name: data.name,
176
+ wildcardProjection: data.wildcardProjection as Record<string, 0 | 1> | undefined,
177
+ collation: data.collation,
178
+ weights: data.weights as Record<string, number> | undefined,
179
+ default_language: data.default_language,
180
+ language_override: data.language_override,
181
+ });
182
+ }
183
+ case 'dropIndex': {
184
+ const data = validate(DropIndexJson, json, 'dropIndex command');
185
+ return new DropIndexCommand(data.collection, data.name);
186
+ }
187
+ case 'createCollection': {
188
+ const data = validate(CreateCollectionJson, json, 'createCollection command');
189
+ return new CreateCollectionCommand(data.collection, {
190
+ validator: data.validator,
191
+ validationLevel: data.validationLevel,
192
+ validationAction: data.validationAction,
193
+ capped: data.capped,
194
+ size: data.size,
195
+ max: data.max,
196
+ timeseries: data.timeseries as CreateCollectionCommand['timeseries'],
197
+ collation: data.collation,
198
+ changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as
199
+ | { enabled: boolean }
200
+ | undefined,
201
+ clusteredIndex: data.clusteredIndex as CreateCollectionCommand['clusteredIndex'],
202
+ });
203
+ }
204
+ case 'dropCollection': {
205
+ const data = validate(DropCollectionJson, json, 'dropCollection command');
206
+ return new DropCollectionCommand(data.collection);
207
+ }
208
+ case 'collMod': {
209
+ const data = validate(CollModJson, json, 'collMod command');
210
+ return new CollModCommand(data.collection, {
211
+ validator: data.validator,
212
+ validationLevel: data.validationLevel,
213
+ validationAction: data.validationAction,
214
+ changeStreamPreAndPostImages: data.changeStreamPreAndPostImages as
215
+ | { enabled: boolean }
216
+ | undefined,
217
+ });
218
+ }
219
+ default:
220
+ throw new Error(`Unknown DDL command kind: ${kind}`);
221
+ }
222
+ }
223
+
224
+ function deserializeInspectionCommand(json: unknown): AnyMongoInspectionCommand {
225
+ const record = json as Record<string, unknown>;
226
+ const kind = record['kind'] as string;
227
+ switch (kind) {
228
+ case 'listIndexes': {
229
+ const data = validate(ListIndexesJson, json, 'listIndexes command');
230
+ return new ListIndexesCommand(data.collection);
231
+ }
232
+ case 'listCollections': {
233
+ validate(ListCollectionsJson, json, 'listCollections command');
234
+ return new ListCollectionsCommand();
235
+ }
236
+ default:
237
+ throw new Error(`Unknown inspection command kind: ${kind}`);
238
+ }
239
+ }
240
+
241
+ function deserializeCheck(json: unknown): MongoMigrationCheck {
242
+ const data = validate(CheckJson, json, 'migration check');
243
+ return {
244
+ description: data.description,
245
+ source: deserializeInspectionCommand(data.source),
246
+ filter: deserializeFilterExpr(data.filter),
247
+ expect: data.expect,
248
+ };
249
+ }
250
+
251
+ function deserializeStep(json: unknown): MongoMigrationStep {
252
+ const data = validate(StepJson, json, 'migration step');
253
+ return {
254
+ description: data.description,
255
+ command: deserializeDdlCommand(data.command),
256
+ };
257
+ }
258
+
259
+ export function deserializeMongoOp(json: unknown): MongoMigrationPlanOperation {
260
+ const data = validate(OperationJson, json, 'migration operation');
261
+ return {
262
+ id: data.id,
263
+ label: data.label,
264
+ operationClass: data.operationClass as MigrationOperationClass,
265
+ precheck: data.precheck.map(deserializeCheck),
266
+ execute: data.execute.map(deserializeStep),
267
+ postcheck: data.postcheck.map(deserializeCheck),
268
+ };
269
+ }
270
+
271
+ export function deserializeMongoOps(json: readonly unknown[]): MongoMigrationPlanOperation[] {
272
+ return json.map(deserializeMongoOp);
273
+ }
274
+
275
+ export function serializeMongoOps(ops: readonly MongoMigrationPlanOperation[]): string {
276
+ return JSON.stringify(ops, null, 2);
277
+ }
@@ -0,0 +1,306 @@
1
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
2
+ import type {
3
+ MigrationOperationClass,
4
+ MigrationOperationPolicy,
5
+ MigrationPlanner,
6
+ MigrationPlannerConflict,
7
+ MigrationPlannerResult,
8
+ } from '@prisma-next/framework-components/control';
9
+ import type { MongoContract } from '@prisma-next/mongo-contract';
10
+ import type {
11
+ MongoSchemaCollection,
12
+ MongoSchemaCollectionOptions,
13
+ MongoSchemaIndex,
14
+ MongoSchemaIR,
15
+ MongoSchemaValidator,
16
+ } from '@prisma-next/mongo-schema-ir';
17
+ import { canonicalize, deepEqual } from '@prisma-next/mongo-schema-ir';
18
+ import { contractToMongoSchemaIR } from './contract-to-schema';
19
+ import type { OpFactoryCall } from './op-factory-call';
20
+ import {
21
+ CollModCall,
22
+ CreateCollectionCall,
23
+ CreateIndexCall,
24
+ DropCollectionCall,
25
+ DropIndexCall,
26
+ schemaCollectionToCreateCollectionOptions,
27
+ schemaIndexToCreateIndexOptions,
28
+ } from './op-factory-call';
29
+ import { renderOps } from './render-ops';
30
+
31
+ function buildIndexLookupKey(index: MongoSchemaIndex): string {
32
+ const keys = index.keys.map((k) => `${k.field}:${k.direction}`).join(',');
33
+ const opts = [
34
+ index.unique ? 'unique' : '',
35
+ index.sparse ? 'sparse' : '',
36
+ index.expireAfterSeconds != null ? `ttl:${index.expireAfterSeconds}` : '',
37
+ index.partialFilterExpression ? `pfe:${canonicalize(index.partialFilterExpression)}` : '',
38
+ index.wildcardProjection ? `wp:${canonicalize(index.wildcardProjection)}` : '',
39
+ index.collation ? `col:${canonicalize(index.collation)}` : '',
40
+ index.weights ? `wt:${canonicalize(index.weights)}` : '',
41
+ index.default_language ? `dl:${index.default_language}` : '',
42
+ index.language_override ? `lo:${index.language_override}` : '',
43
+ ]
44
+ .filter(Boolean)
45
+ .join(';');
46
+ return opts ? `${keys}|${opts}` : keys;
47
+ }
48
+
49
+ function validatorsEqual(
50
+ a: MongoSchemaValidator | undefined,
51
+ b: MongoSchemaValidator | undefined,
52
+ ): boolean {
53
+ if (!a && !b) return true;
54
+ if (!a || !b) return false;
55
+ return (
56
+ a.validationLevel === b.validationLevel &&
57
+ a.validationAction === b.validationAction &&
58
+ canonicalize(a.jsonSchema) === canonicalize(b.jsonSchema)
59
+ );
60
+ }
61
+
62
+ function classifyValidatorUpdate(
63
+ origin: MongoSchemaValidator,
64
+ dest: MongoSchemaValidator,
65
+ ): 'widening' | 'destructive' {
66
+ let hasDestructive = false;
67
+
68
+ if (canonicalize(origin.jsonSchema) !== canonicalize(dest.jsonSchema)) {
69
+ hasDestructive = true;
70
+ }
71
+
72
+ if (origin.validationAction !== dest.validationAction) {
73
+ if (dest.validationAction === 'error') hasDestructive = true;
74
+ }
75
+
76
+ if (origin.validationLevel !== dest.validationLevel) {
77
+ if (dest.validationLevel === 'strict') hasDestructive = true;
78
+ }
79
+
80
+ return hasDestructive ? 'destructive' : 'widening';
81
+ }
82
+
83
+ function hasImmutableOptionChange(
84
+ origin: MongoSchemaCollectionOptions | undefined,
85
+ dest: MongoSchemaCollectionOptions | undefined,
86
+ ): string | undefined {
87
+ if (canonicalize(origin?.capped) !== canonicalize(dest?.capped)) return 'capped';
88
+ if (canonicalize(origin?.timeseries) !== canonicalize(dest?.timeseries)) return 'timeseries';
89
+ if (canonicalize(origin?.collation) !== canonicalize(dest?.collation)) return 'collation';
90
+ if (canonicalize(origin?.clusteredIndex) !== canonicalize(dest?.clusteredIndex))
91
+ return 'clusteredIndex';
92
+ return undefined;
93
+ }
94
+
95
+ function collectionHasOptions(coll: MongoSchemaCollection): boolean {
96
+ return !!(coll.options || coll.validator);
97
+ }
98
+
99
+ export type PlanCallsResult =
100
+ | { readonly kind: 'success'; readonly calls: OpFactoryCall[] }
101
+ | { readonly kind: 'failure'; readonly conflicts: MigrationPlannerConflict[] };
102
+
103
+ export class MongoMigrationPlanner implements MigrationPlanner<'mongo', 'mongo'> {
104
+ planCalls(options: {
105
+ readonly contract: unknown;
106
+ readonly schema: unknown;
107
+ readonly policy: MigrationOperationPolicy;
108
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;
109
+ }): PlanCallsResult {
110
+ const contract = options.contract as MongoContract;
111
+ const originIR = options.schema as MongoSchemaIR;
112
+ const destinationIR = contractToMongoSchemaIR(contract);
113
+
114
+ const collCreates: OpFactoryCall[] = [];
115
+ const drops: OpFactoryCall[] = [];
116
+ const creates: OpFactoryCall[] = [];
117
+ const validatorOps: OpFactoryCall[] = [];
118
+ const mutableOptionOps: OpFactoryCall[] = [];
119
+ const collDrops: OpFactoryCall[] = [];
120
+ const conflicts: MigrationPlannerConflict[] = [];
121
+
122
+ const allCollectionNames = new Set([
123
+ ...originIR.collectionNames,
124
+ ...destinationIR.collectionNames,
125
+ ]);
126
+
127
+ for (const collName of [...allCollectionNames].sort()) {
128
+ const originColl = originIR.collection(collName);
129
+ const destColl = destinationIR.collection(collName);
130
+
131
+ if (!originColl) {
132
+ if (destColl && collectionHasOptions(destColl)) {
133
+ const opts = schemaCollectionToCreateCollectionOptions(destColl);
134
+ collCreates.push(new CreateCollectionCall(collName, opts));
135
+ }
136
+ } else if (!destColl) {
137
+ collDrops.push(new DropCollectionCall(collName));
138
+ } else {
139
+ const immutableChange = hasImmutableOptionChange(originColl.options, destColl.options);
140
+ if (immutableChange) {
141
+ conflicts.push({
142
+ kind: 'policy-violation',
143
+ summary: `Cannot change immutable collection option '${immutableChange}' on ${collName}`,
144
+ why: `MongoDB does not support modifying the '${immutableChange}' option after collection creation`,
145
+ });
146
+ }
147
+
148
+ const mutableCall = planMutableOptionsDiffCall(
149
+ collName,
150
+ originColl.options,
151
+ destColl.options,
152
+ );
153
+ if (mutableCall) mutableOptionOps.push(mutableCall);
154
+
155
+ const validatorCall = planValidatorDiffCall(
156
+ collName,
157
+ originColl.validator,
158
+ destColl.validator,
159
+ );
160
+ if (validatorCall) validatorOps.push(validatorCall);
161
+ }
162
+
163
+ const originLookup = new Map<string, MongoSchemaIndex>();
164
+ if (originColl) {
165
+ for (const idx of originColl.indexes) {
166
+ originLookup.set(buildIndexLookupKey(idx), idx);
167
+ }
168
+ }
169
+
170
+ const destLookup = new Map<string, MongoSchemaIndex>();
171
+ if (destColl) {
172
+ for (const idx of destColl.indexes) {
173
+ destLookup.set(buildIndexLookupKey(idx), idx);
174
+ }
175
+ }
176
+
177
+ for (const [lookupKey, idx] of originLookup) {
178
+ if (!destLookup.has(lookupKey)) {
179
+ drops.push(new DropIndexCall(collName, idx.keys));
180
+ }
181
+ }
182
+
183
+ for (const [lookupKey, idx] of destLookup) {
184
+ if (!originLookup.has(lookupKey)) {
185
+ creates.push(
186
+ new CreateIndexCall(collName, idx.keys, schemaIndexToCreateIndexOptions(idx)),
187
+ );
188
+ }
189
+ }
190
+ }
191
+
192
+ if (conflicts.length > 0) {
193
+ return { kind: 'failure', conflicts };
194
+ }
195
+
196
+ const allCalls = [
197
+ ...collCreates,
198
+ ...drops,
199
+ ...creates,
200
+ ...validatorOps,
201
+ ...mutableOptionOps,
202
+ ...collDrops,
203
+ ];
204
+
205
+ for (const call of allCalls) {
206
+ if (!options.policy.allowedOperationClasses.includes(call.operationClass)) {
207
+ conflicts.push({
208
+ kind: 'policy-violation',
209
+ summary: `${call.operationClass} operation disallowed: ${call.label}`,
210
+ why: `Policy does not allow '${call.operationClass}' operations`,
211
+ });
212
+ }
213
+ }
214
+
215
+ if (conflicts.length > 0) {
216
+ return { kind: 'failure', conflicts };
217
+ }
218
+
219
+ return { kind: 'success', calls: allCalls };
220
+ }
221
+
222
+ plan(options: {
223
+ readonly contract: unknown;
224
+ readonly schema: unknown;
225
+ readonly policy: MigrationOperationPolicy;
226
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'mongo', 'mongo'>>;
227
+ }): MigrationPlannerResult {
228
+ const contract = options.contract as MongoContract;
229
+ const result = this.planCalls(options);
230
+ if (result.kind === 'failure') return result;
231
+ return {
232
+ kind: 'success',
233
+ plan: {
234
+ targetId: 'mongo',
235
+ destination: {
236
+ storageHash: contract.storage.storageHash,
237
+ },
238
+ operations: renderOps(result.calls),
239
+ },
240
+ };
241
+ }
242
+ }
243
+
244
+ function planValidatorDiffCall(
245
+ collName: string,
246
+ originValidator: MongoSchemaValidator | undefined,
247
+ destValidator: MongoSchemaValidator | undefined,
248
+ ): OpFactoryCall | undefined {
249
+ if (validatorsEqual(originValidator, destValidator)) return undefined;
250
+
251
+ if (destValidator) {
252
+ const operationClass: MigrationOperationClass = originValidator
253
+ ? classifyValidatorUpdate(originValidator, destValidator)
254
+ : 'destructive';
255
+ return new CollModCall(
256
+ collName,
257
+ {
258
+ validator: { $jsonSchema: destValidator.jsonSchema },
259
+ validationLevel: destValidator.validationLevel,
260
+ validationAction: destValidator.validationAction,
261
+ },
262
+ {
263
+ id: `validator.${collName}.${originValidator ? 'update' : 'add'}`,
264
+ label: `${originValidator ? 'Update' : 'Add'} validator on ${collName}`,
265
+ operationClass,
266
+ },
267
+ );
268
+ }
269
+
270
+ return new CollModCall(
271
+ collName,
272
+ {
273
+ validator: {},
274
+ validationLevel: 'strict',
275
+ validationAction: 'error',
276
+ },
277
+ {
278
+ id: `validator.${collName}.remove`,
279
+ label: `Remove validator on ${collName}`,
280
+ operationClass: 'widening',
281
+ },
282
+ );
283
+ }
284
+
285
+ function planMutableOptionsDiffCall(
286
+ collName: string,
287
+ origin: MongoSchemaCollectionOptions | undefined,
288
+ dest: MongoSchemaCollectionOptions | undefined,
289
+ ): OpFactoryCall | undefined {
290
+ const originCSPPI = origin?.changeStreamPreAndPostImages;
291
+ const destCSPPI = dest?.changeStreamPreAndPostImages;
292
+ if (deepEqual(originCSPPI, destCSPPI)) return undefined;
293
+
294
+ const desiredCSPPI = destCSPPI ?? { enabled: false };
295
+ return new CollModCall(
296
+ collName,
297
+ {
298
+ changeStreamPreAndPostImages: desiredCSPPI,
299
+ },
300
+ {
301
+ id: `options.${collName}.update`,
302
+ label: `Update mutable options on ${collName}`,
303
+ operationClass: desiredCSPPI.enabled ? 'widening' : 'destructive',
304
+ },
305
+ );
306
+ }