@anarchitects/nx-typeorm 0.2.0 → 0.3.0
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/README.md +32 -0
- package/dist/generators/bootstrap/files/lib/src/infrastructure-persistence/migrations/1700000000000_init_schema.ts__tmpl__ +7 -3
- package/dist/generators/migration-api/generator.d.ts +4 -0
- package/dist/generators/migration-api/generator.d.ts.map +1 -0
- package/dist/generators/migration-api/generator.js +1695 -0
- package/dist/generators/migration-api/schema.json +37 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.json +8 -0
- package/package.json +3 -4
|
@@ -0,0 +1,1695 @@
|
|
|
1
|
+
import { formatFiles, joinPathFragments, names, readProjectConfiguration, } from '@nx/devkit';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { basename, posix } from 'node:path';
|
|
4
|
+
import { Node, Project, SyntaxKind, } from 'ts-morph';
|
|
5
|
+
import { defaultMigrationsDirectory, normalizeName, } from '../../utils/shared.js';
|
|
6
|
+
const DEFAULT_ENTITY_GLOB = 'src/infrastructure-persistence/entities/**/*.ts';
|
|
7
|
+
const MANIFEST_FILENAME = '.nx-typeorm-migration-manifest.json';
|
|
8
|
+
const INIT_MIGRATION_FILENAME = '1700000000000_init_schema.ts';
|
|
9
|
+
const UP_START_MARKER = '// nx-typeorm:migration-api:up:start';
|
|
10
|
+
const UP_END_MARKER = '// nx-typeorm:migration-api:up:end';
|
|
11
|
+
const DOWN_START_MARKER = '// nx-typeorm:migration-api:down:start';
|
|
12
|
+
const DOWN_END_MARKER = '// nx-typeorm:migration-api:down:end';
|
|
13
|
+
const TYPEORM_CLASS_DECORATORS = new Set([
|
|
14
|
+
'Entity',
|
|
15
|
+
'Index',
|
|
16
|
+
'Unique',
|
|
17
|
+
'Check',
|
|
18
|
+
'Exclusion',
|
|
19
|
+
]);
|
|
20
|
+
const TYPEORM_PROPERTY_DECORATORS = new Set([
|
|
21
|
+
'PrimaryGeneratedColumn',
|
|
22
|
+
'PrimaryColumn',
|
|
23
|
+
'Column',
|
|
24
|
+
'CreateDateColumn',
|
|
25
|
+
'UpdateDateColumn',
|
|
26
|
+
'DeleteDateColumn',
|
|
27
|
+
'VersionColumn',
|
|
28
|
+
'Generated',
|
|
29
|
+
'Index',
|
|
30
|
+
'Unique',
|
|
31
|
+
'ManyToOne',
|
|
32
|
+
'OneToOne',
|
|
33
|
+
'OneToMany',
|
|
34
|
+
'JoinColumn',
|
|
35
|
+
'RelationId',
|
|
36
|
+
'RelationCount',
|
|
37
|
+
]);
|
|
38
|
+
const UNSUPPORTED_RELATION_DECORATORS = new Set(['ManyToMany', 'JoinTable']);
|
|
39
|
+
export default async function migrationApiGenerator(tree, options) {
|
|
40
|
+
const projectName = requireOption(options.project, 'project');
|
|
41
|
+
const project = readProjectConfiguration(tree, projectName);
|
|
42
|
+
if (project.projectType !== 'library') {
|
|
43
|
+
throw new Error('The migration-api generator only supports library projects.');
|
|
44
|
+
}
|
|
45
|
+
const fileMode = normalizeFileMode(options.fileMode);
|
|
46
|
+
const entityGlob = normalizeProjectRelative(options.entityGlob ?? DEFAULT_ENTITY_GLOB);
|
|
47
|
+
const metadata = readTypeormMetadata(project.metadata);
|
|
48
|
+
const migrationsDirectory = resolveMigrationsDirectory(project.root, project.projectType, metadata);
|
|
49
|
+
const manifestPath = joinPathFragments(migrationsDirectory, MANIFEST_FILENAME);
|
|
50
|
+
const initMigrationPath = joinPathFragments(migrationsDirectory, INIT_MIGRATION_FILENAME);
|
|
51
|
+
if (!tree.exists(migrationsDirectory)) {
|
|
52
|
+
throw new Error(`Migrations directory "${migrationsDirectory}" does not exist. Run bootstrap first.`);
|
|
53
|
+
}
|
|
54
|
+
const manifest = readManifest(tree, manifestPath);
|
|
55
|
+
const migrationFiles = listTypeScriptMigrationFiles(tree, migrationsDirectory);
|
|
56
|
+
validateMixedMigrations(migrationFiles, manifest, options.allowMixedMigrations ?? false);
|
|
57
|
+
if (fileMode === 'patch-init') {
|
|
58
|
+
if (!tree.exists(initMigrationPath)) {
|
|
59
|
+
throw new Error(`Patch mode requires the bootstrap init migration at "${initMigrationPath}".`);
|
|
60
|
+
}
|
|
61
|
+
const hasGeneratedDelta = (manifest?.migrations ?? []).some((entry) => entry.mode === 'new');
|
|
62
|
+
if (hasGeneratedDelta) {
|
|
63
|
+
throw new Error('Patch mode is allowed only before generating any delta migration files.');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const entityFiles = discoverEntityFiles(tree, project.root, entityGlob);
|
|
67
|
+
if (entityFiles.length === 0) {
|
|
68
|
+
throw new Error(`No entity files matched "${entityGlob}" under "${project.root}".`);
|
|
69
|
+
}
|
|
70
|
+
const snapshot = buildCanonicalSnapshot(tree, entityFiles, metadata.schema);
|
|
71
|
+
const previousSnapshot = manifest?.snapshot ?? emptySnapshot();
|
|
72
|
+
const diff = diffSnapshots(previousSnapshot, snapshot);
|
|
73
|
+
const nextManifest = {
|
|
74
|
+
schemaVersion: 1,
|
|
75
|
+
generatedBy: '@anarchitects/nx-typeorm:migration-api',
|
|
76
|
+
snapshot,
|
|
77
|
+
migrations: [...(manifest?.migrations ?? [])],
|
|
78
|
+
};
|
|
79
|
+
if (!diff.hasChanges) {
|
|
80
|
+
tree.write(manifestPath, `${JSON.stringify(nextManifest, null, 2)}\n`);
|
|
81
|
+
await formatFiles(tree);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const rendered = renderMigration(diff);
|
|
85
|
+
const migrationHash = sha256(JSON.stringify({
|
|
86
|
+
up: rendered.upStatements,
|
|
87
|
+
down: rendered.downStatements,
|
|
88
|
+
snapshotHash: snapshot.hash,
|
|
89
|
+
}));
|
|
90
|
+
if (fileMode === 'patch-init') {
|
|
91
|
+
patchInitMigration(tree, initMigrationPath, rendered);
|
|
92
|
+
nextManifest.migrations.push({
|
|
93
|
+
file: INIT_MIGRATION_FILENAME,
|
|
94
|
+
className: 'InitPatch',
|
|
95
|
+
timestamp: options.timestamp ?? Date.now(),
|
|
96
|
+
hash: migrationHash,
|
|
97
|
+
mode: 'patch-init',
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
const migrationName = normalizeName(requireOption(options.name, 'name'));
|
|
102
|
+
const timestamp = normalizeTimestamp(options.timestamp);
|
|
103
|
+
const migrationFile = `${timestamp}_${migrationName}.ts`;
|
|
104
|
+
const migrationPath = joinPathFragments(migrationsDirectory, migrationFile);
|
|
105
|
+
if (tree.exists(migrationPath)) {
|
|
106
|
+
throw new Error(`Migration file "${migrationPath}" already exists. Use a different timestamp or name.`);
|
|
107
|
+
}
|
|
108
|
+
const className = `${names(migrationName).className}${timestamp}`;
|
|
109
|
+
tree.write(migrationPath, renderMigrationFile({
|
|
110
|
+
className,
|
|
111
|
+
upStatements: rendered.upStatements,
|
|
112
|
+
downStatements: rendered.downStatements,
|
|
113
|
+
}));
|
|
114
|
+
nextManifest.migrations.push({
|
|
115
|
+
file: migrationFile,
|
|
116
|
+
className,
|
|
117
|
+
timestamp,
|
|
118
|
+
hash: migrationHash,
|
|
119
|
+
mode: 'new',
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
tree.write(manifestPath, `${JSON.stringify(nextManifest, null, 2)}\n`);
|
|
123
|
+
await formatFiles(tree);
|
|
124
|
+
}
|
|
125
|
+
function readTypeormMetadata(metadata) {
|
|
126
|
+
const root = metadata;
|
|
127
|
+
return {
|
|
128
|
+
schema: root?.typeorm?.schema,
|
|
129
|
+
migrationsDir: root?.typeorm?.migrationsDir,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function resolveMigrationsDirectory(projectRoot, projectType, metadata) {
|
|
133
|
+
const fallback = defaultMigrationsDirectory(projectRoot, projectType);
|
|
134
|
+
const configured = metadata.migrationsDir
|
|
135
|
+
? joinPathFragments(projectRoot, normalizeProjectRelative(metadata.migrationsDir))
|
|
136
|
+
: fallback;
|
|
137
|
+
return configured;
|
|
138
|
+
}
|
|
139
|
+
function normalizeFileMode(fileMode) {
|
|
140
|
+
const normalized = (fileMode ?? 'new').trim();
|
|
141
|
+
if (normalized === 'new' || normalized === 'patch-init') {
|
|
142
|
+
return normalized;
|
|
143
|
+
}
|
|
144
|
+
throw new Error('fileMode must be either "new" or "patch-init".');
|
|
145
|
+
}
|
|
146
|
+
function normalizeTimestamp(timestamp) {
|
|
147
|
+
if (typeof timestamp !== 'number') {
|
|
148
|
+
return Date.now();
|
|
149
|
+
}
|
|
150
|
+
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
|
151
|
+
throw new Error('timestamp must be a positive finite number when provided.');
|
|
152
|
+
}
|
|
153
|
+
return Math.floor(timestamp);
|
|
154
|
+
}
|
|
155
|
+
function requireOption(value, optionName) {
|
|
156
|
+
const trimmed = value?.trim();
|
|
157
|
+
if (!trimmed) {
|
|
158
|
+
throw new Error(`Provide a value for the ${optionName} option.`);
|
|
159
|
+
}
|
|
160
|
+
return trimmed;
|
|
161
|
+
}
|
|
162
|
+
function normalizeProjectRelative(pathValue) {
|
|
163
|
+
const normalized = pathValue.replace(/\\/g, '/').replace(/^\.\//, '').trim();
|
|
164
|
+
if (!normalized) {
|
|
165
|
+
throw new Error('Path options must not be empty.');
|
|
166
|
+
}
|
|
167
|
+
if (normalized.startsWith('/')) {
|
|
168
|
+
throw new Error(`Path "${pathValue}" must be relative to the project root.`);
|
|
169
|
+
}
|
|
170
|
+
const collapsed = posix.normalize(normalized);
|
|
171
|
+
if (collapsed === '.' || collapsed === '..' || collapsed.startsWith('../')) {
|
|
172
|
+
throw new Error(`Path "${pathValue}" must stay within the project root.`);
|
|
173
|
+
}
|
|
174
|
+
return collapsed;
|
|
175
|
+
}
|
|
176
|
+
function readManifest(tree, manifestPath) {
|
|
177
|
+
if (!tree.exists(manifestPath)) {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
const contents = tree.read(manifestPath, 'utf-8');
|
|
181
|
+
if (!contents) {
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const parsed = JSON.parse(contents);
|
|
186
|
+
if (parsed.schemaVersion !== 1 ||
|
|
187
|
+
parsed.generatedBy !== '@anarchitects/nx-typeorm:migration-api' ||
|
|
188
|
+
!Array.isArray(parsed.migrations)) {
|
|
189
|
+
throw new Error('Invalid manifest structure.');
|
|
190
|
+
}
|
|
191
|
+
return parsed;
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
throw new Error(`Failed to parse migration manifest "${manifestPath}": ${error instanceof Error ? error.message : String(error)}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function validateMixedMigrations(migrationFiles, manifest, allowMixedMigrations) {
|
|
198
|
+
const generatedFiles = new Set([
|
|
199
|
+
INIT_MIGRATION_FILENAME,
|
|
200
|
+
...(manifest?.migrations.map((entry) => entry.file) ?? []),
|
|
201
|
+
]);
|
|
202
|
+
const manualFiles = migrationFiles.filter((file) => !generatedFiles.has(file));
|
|
203
|
+
if (manualFiles.length > 0 && !allowMixedMigrations) {
|
|
204
|
+
throw new Error(`Detected non-tool migration files (${manualFiles.join(', ')}). Re-run with --allowMixedMigrations to opt in.`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function listTypeScriptMigrationFiles(tree, migrationsDirectory) {
|
|
208
|
+
return walkTreeFiles(tree, migrationsDirectory)
|
|
209
|
+
.map((filePath) => posix.relative(migrationsDirectory, filePath))
|
|
210
|
+
.filter((relativePath) => relativePath.endsWith('.ts') &&
|
|
211
|
+
!relativePath.endsWith('.d.ts') &&
|
|
212
|
+
basename(relativePath) !== MANIFEST_FILENAME)
|
|
213
|
+
.sort();
|
|
214
|
+
}
|
|
215
|
+
function discoverEntityFiles(tree, projectRoot, entityGlob) {
|
|
216
|
+
return walkTreeFiles(tree, projectRoot)
|
|
217
|
+
.filter((filePath) => filePath.endsWith('.ts') && !filePath.endsWith('.d.ts'))
|
|
218
|
+
.filter((filePath) => {
|
|
219
|
+
const relativePath = posix.relative(projectRoot, filePath);
|
|
220
|
+
return matchGlobPattern(relativePath, entityGlob);
|
|
221
|
+
})
|
|
222
|
+
.sort();
|
|
223
|
+
}
|
|
224
|
+
function walkTreeFiles(tree, rootPath) {
|
|
225
|
+
const normalizedRoot = rootPath.replace(/\\/g, '/');
|
|
226
|
+
if (!tree.exists(normalizedRoot)) {
|
|
227
|
+
return [];
|
|
228
|
+
}
|
|
229
|
+
if (tree.isFile(normalizedRoot)) {
|
|
230
|
+
return [normalizedRoot];
|
|
231
|
+
}
|
|
232
|
+
const files = [];
|
|
233
|
+
const stack = [normalizedRoot];
|
|
234
|
+
while (stack.length > 0) {
|
|
235
|
+
const current = stack.pop();
|
|
236
|
+
if (!current) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
for (const child of tree.children(current)) {
|
|
240
|
+
const childPath = joinPathFragments(current, child);
|
|
241
|
+
if (tree.isFile(childPath)) {
|
|
242
|
+
files.push(childPath);
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
stack.push(childPath);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return files;
|
|
250
|
+
}
|
|
251
|
+
function matchGlobPattern(pathValue, pattern) {
|
|
252
|
+
const pathSegments = pathValue
|
|
253
|
+
.split('/')
|
|
254
|
+
.filter((segment) => segment.length > 0);
|
|
255
|
+
const patternSegments = pattern
|
|
256
|
+
.split('/')
|
|
257
|
+
.filter((segment) => segment.length > 0);
|
|
258
|
+
return matchGlobSegments(pathSegments, patternSegments);
|
|
259
|
+
}
|
|
260
|
+
function matchGlobSegments(pathSegments, patternSegments) {
|
|
261
|
+
if (patternSegments.length === 0) {
|
|
262
|
+
return pathSegments.length === 0;
|
|
263
|
+
}
|
|
264
|
+
const [currentPattern, ...restPattern] = patternSegments;
|
|
265
|
+
if (currentPattern === '**') {
|
|
266
|
+
if (matchGlobSegments(pathSegments, restPattern)) {
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
if (pathSegments.length === 0) {
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
return matchGlobSegments(pathSegments.slice(1), patternSegments);
|
|
273
|
+
}
|
|
274
|
+
if (pathSegments.length === 0) {
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
if (!matchGlobSegment(pathSegments[0], currentPattern)) {
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
return matchGlobSegments(pathSegments.slice(1), restPattern);
|
|
281
|
+
}
|
|
282
|
+
function matchGlobSegment(pathSegment, patternSegment) {
|
|
283
|
+
const regexBody = patternSegment
|
|
284
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
285
|
+
.replace(/\*/g, '.*')
|
|
286
|
+
.replace(/\?/g, '.');
|
|
287
|
+
return new RegExp(`^${regexBody}$`).test(pathSegment);
|
|
288
|
+
}
|
|
289
|
+
function buildCanonicalSnapshot(tree, entityFiles, defaultSchema) {
|
|
290
|
+
const project = new Project({
|
|
291
|
+
useInMemoryFileSystem: true,
|
|
292
|
+
skipAddingFilesFromTsConfig: true,
|
|
293
|
+
});
|
|
294
|
+
for (const entityFile of entityFiles) {
|
|
295
|
+
const contents = tree.read(entityFile, 'utf-8');
|
|
296
|
+
if (!contents) {
|
|
297
|
+
throw new Error(`Unable to read entity file "${entityFile}".`);
|
|
298
|
+
}
|
|
299
|
+
project.createSourceFile(entityFile, contents, { overwrite: true });
|
|
300
|
+
}
|
|
301
|
+
const parsedEntities = [];
|
|
302
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
303
|
+
const aliases = readTypeormAliases(sourceFile);
|
|
304
|
+
for (const classDeclaration of sourceFile.getClasses()) {
|
|
305
|
+
const parsed = parseEntityClass(classDeclaration, aliases, defaultSchema);
|
|
306
|
+
if (parsed) {
|
|
307
|
+
parsedEntities.push(parsed);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (parsedEntities.length === 0) {
|
|
312
|
+
throw new Error('No @Entity classes were found in discovered entity files.');
|
|
313
|
+
}
|
|
314
|
+
resolvePendingRelations(parsedEntities);
|
|
315
|
+
const entities = parsedEntities
|
|
316
|
+
.map((entity) => {
|
|
317
|
+
return sortEntity({
|
|
318
|
+
key: entity.key,
|
|
319
|
+
className: entity.className,
|
|
320
|
+
tableName: entity.tableName,
|
|
321
|
+
schema: entity.schema,
|
|
322
|
+
columns: entity.columns,
|
|
323
|
+
uniques: entity.uniques,
|
|
324
|
+
indices: entity.indices,
|
|
325
|
+
checks: entity.checks,
|
|
326
|
+
exclusions: entity.exclusions,
|
|
327
|
+
foreignKeys: entity.foreignKeys,
|
|
328
|
+
});
|
|
329
|
+
})
|
|
330
|
+
.sort((left, right) => left.key.localeCompare(right.key));
|
|
331
|
+
const hash = sha256(JSON.stringify(entities));
|
|
332
|
+
return { entities, hash };
|
|
333
|
+
}
|
|
334
|
+
function parseEntityClass(classDeclaration, aliases, defaultSchema) {
|
|
335
|
+
const classDecorators = getTypeormDecorators(classDeclaration, aliases);
|
|
336
|
+
const entityDecorator = classDecorators.find((entry) => entry.canonicalName === 'Entity');
|
|
337
|
+
if (!entityDecorator) {
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
assertSupportedDecorators(classDecorators, TYPEORM_CLASS_DECORATORS, classDeclaration, 'class');
|
|
341
|
+
const className = classDeclaration.getName();
|
|
342
|
+
if (!className) {
|
|
343
|
+
throw new Error('Entity classes must be named exports.');
|
|
344
|
+
}
|
|
345
|
+
const tableInfo = parseEntityDecorator(entityDecorator.decorator, className);
|
|
346
|
+
const tableName = tableInfo.tableName;
|
|
347
|
+
const schema = tableInfo.schema ?? defaultSchema;
|
|
348
|
+
const entity = {
|
|
349
|
+
key: tableKey(schema, tableName),
|
|
350
|
+
className,
|
|
351
|
+
tableName,
|
|
352
|
+
schema,
|
|
353
|
+
columns: [],
|
|
354
|
+
uniques: [],
|
|
355
|
+
indices: [],
|
|
356
|
+
checks: [],
|
|
357
|
+
exclusions: [],
|
|
358
|
+
foreignKeys: [],
|
|
359
|
+
pendingRelations: [],
|
|
360
|
+
};
|
|
361
|
+
parseEntityLevelConstraints(entity, classDecorators, classDeclaration);
|
|
362
|
+
for (const property of classDeclaration.getProperties()) {
|
|
363
|
+
parseProperty(entity, property, aliases);
|
|
364
|
+
}
|
|
365
|
+
return sortParsedEntity(entity);
|
|
366
|
+
}
|
|
367
|
+
function readTypeormAliases(sourceFile) {
|
|
368
|
+
const aliases = new Map();
|
|
369
|
+
for (const declaration of sourceFile.getImportDeclarations()) {
|
|
370
|
+
if (declaration.getModuleSpecifierValue() !== 'typeorm') {
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
for (const namedImport of declaration.getNamedImports()) {
|
|
374
|
+
const canonicalName = namedImport.getName();
|
|
375
|
+
const localName = namedImport.getAliasNode()?.getText() ?? canonicalName;
|
|
376
|
+
aliases.set(localName, canonicalName);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return aliases;
|
|
380
|
+
}
|
|
381
|
+
function getTypeormDecorators(node, aliases) {
|
|
382
|
+
const result = [];
|
|
383
|
+
for (const decorator of node.getDecorators()) {
|
|
384
|
+
const localName = decorator.getName();
|
|
385
|
+
const canonicalName = aliases.get(localName);
|
|
386
|
+
if (!canonicalName) {
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
result.push({ canonicalName, decorator });
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
function assertSupportedDecorators(decorators, supported, node, nodeKind) {
|
|
394
|
+
for (const { canonicalName } of decorators) {
|
|
395
|
+
if (UNSUPPORTED_RELATION_DECORATORS.has(canonicalName)) {
|
|
396
|
+
throw new Error(`Unsupported TypeORM decorator @${canonicalName} on ${nodeKind} "${nodeKind === 'class'
|
|
397
|
+
? node.getName() ?? '<anonymous>'
|
|
398
|
+
: node.getName()}". Generate this migration manually.`);
|
|
399
|
+
}
|
|
400
|
+
if (!supported.has(canonicalName)) {
|
|
401
|
+
throw new Error(`Unsupported TypeORM decorator @${canonicalName} on ${nodeKind} "${nodeKind === 'class'
|
|
402
|
+
? node.getName() ?? '<anonymous>'
|
|
403
|
+
: node.getName()}".`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function parseEntityDecorator(decorator, className) {
|
|
408
|
+
const args = decorator.getArguments();
|
|
409
|
+
let tableName;
|
|
410
|
+
let schema;
|
|
411
|
+
for (const arg of args) {
|
|
412
|
+
if (Node.isStringLiteral(arg) ||
|
|
413
|
+
Node.isNoSubstitutionTemplateLiteral(arg)) {
|
|
414
|
+
tableName = arg.getLiteralText().trim();
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (Node.isObjectLiteralExpression(arg)) {
|
|
418
|
+
const nameValue = readStringProperty(arg, 'name');
|
|
419
|
+
if (nameValue) {
|
|
420
|
+
tableName = nameValue;
|
|
421
|
+
}
|
|
422
|
+
const schemaValue = readStringProperty(arg, 'schema');
|
|
423
|
+
if (schemaValue) {
|
|
424
|
+
schema = schemaValue;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (!tableName) {
|
|
429
|
+
throw new Error(`Entity "${className}" must declare an explicit table name in @Entity(...).`);
|
|
430
|
+
}
|
|
431
|
+
return { tableName, schema };
|
|
432
|
+
}
|
|
433
|
+
function parseEntityLevelConstraints(entity, decorators, classDeclaration) {
|
|
434
|
+
for (const { canonicalName, decorator } of decorators) {
|
|
435
|
+
if (canonicalName === 'Unique') {
|
|
436
|
+
const parsed = parseUniqueDecorator(decorator, classDeclaration.getName() ?? 'Entity');
|
|
437
|
+
entity.uniques.push(parsed);
|
|
438
|
+
}
|
|
439
|
+
if (canonicalName === 'Index') {
|
|
440
|
+
const parsed = parseIndexDecorator(decorator, classDeclaration.getName() ?? 'Entity');
|
|
441
|
+
entity.indices.push(parsed);
|
|
442
|
+
}
|
|
443
|
+
if (canonicalName === 'Check') {
|
|
444
|
+
entity.checks.push(parseNamedExpressionDecorator(decorator, 'Check', classDeclaration.getName() ?? 'Entity'));
|
|
445
|
+
}
|
|
446
|
+
if (canonicalName === 'Exclusion') {
|
|
447
|
+
entity.exclusions.push(parseNamedExpressionDecorator(decorator, 'Exclusion', classDeclaration.getName() ?? 'Entity'));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function parseProperty(entity, property, aliases) {
|
|
452
|
+
const decorators = getTypeormDecorators(property, aliases);
|
|
453
|
+
if (decorators.length === 0) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
assertSupportedDecorators(decorators, TYPEORM_PROPERTY_DECORATORS, property, 'property');
|
|
457
|
+
const propertyName = property.getName();
|
|
458
|
+
const decoratorMap = new Map();
|
|
459
|
+
for (const { canonicalName, decorator } of decorators) {
|
|
460
|
+
decoratorMap.set(canonicalName, decorator);
|
|
461
|
+
}
|
|
462
|
+
const columnDecorator = decoratorMap.get('PrimaryGeneratedColumn') ??
|
|
463
|
+
decoratorMap.get('PrimaryColumn') ??
|
|
464
|
+
decoratorMap.get('Column') ??
|
|
465
|
+
decoratorMap.get('CreateDateColumn') ??
|
|
466
|
+
decoratorMap.get('UpdateDateColumn') ??
|
|
467
|
+
decoratorMap.get('DeleteDateColumn') ??
|
|
468
|
+
decoratorMap.get('VersionColumn');
|
|
469
|
+
if (columnDecorator) {
|
|
470
|
+
const generatedDecorator = decoratorMap.get('Generated');
|
|
471
|
+
const column = parseColumn(property, columnDecorator, generatedDecorator);
|
|
472
|
+
upsertColumn(entity.columns, column);
|
|
473
|
+
}
|
|
474
|
+
const propertyUniqueDecorator = decoratorMap.get('Unique');
|
|
475
|
+
if (propertyUniqueDecorator) {
|
|
476
|
+
const unique = parseUniqueDecorator(propertyUniqueDecorator, propertyName, [
|
|
477
|
+
propertyName,
|
|
478
|
+
]);
|
|
479
|
+
entity.uniques.push(unique);
|
|
480
|
+
}
|
|
481
|
+
const propertyIndexDecorator = decoratorMap.get('Index');
|
|
482
|
+
if (propertyIndexDecorator) {
|
|
483
|
+
const index = parseIndexDecorator(propertyIndexDecorator, propertyName, [
|
|
484
|
+
propertyName,
|
|
485
|
+
]);
|
|
486
|
+
entity.indices.push(index);
|
|
487
|
+
}
|
|
488
|
+
const relationDecorator = decoratorMap.get('ManyToOne') ?? decoratorMap.get('OneToOne');
|
|
489
|
+
const joinColumnDecorator = decoratorMap.get('JoinColumn');
|
|
490
|
+
if (!relationDecorator) {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
const relationName = relationDecorator.getName();
|
|
494
|
+
if (relationName === 'ManyToOne' && !joinColumnDecorator) {
|
|
495
|
+
throw new Error(`Relation "${propertyName}" uses implicit join-column naming. Add @JoinColumn({ name: ..., referencedColumnName: ... }).`);
|
|
496
|
+
}
|
|
497
|
+
if (relationName === 'OneToOne' && !joinColumnDecorator) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (!joinColumnDecorator) {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const targetClassName = parseRelationTargetClassName(relationDecorator);
|
|
504
|
+
const relationOptions = parseRelationOptions(relationDecorator);
|
|
505
|
+
const joinColumn = parseJoinColumnDecorator(joinColumnDecorator, propertyName);
|
|
506
|
+
entity.pendingRelations.push({
|
|
507
|
+
sourceEntityKey: entity.key,
|
|
508
|
+
sourcePropertyName: propertyName,
|
|
509
|
+
targetClassName,
|
|
510
|
+
joinColumnName: joinColumn.name,
|
|
511
|
+
referencedColumnName: joinColumn.referencedColumnName,
|
|
512
|
+
foreignKeyConstraintName: joinColumn.foreignKeyConstraintName,
|
|
513
|
+
onDelete: relationOptions.onDelete,
|
|
514
|
+
onUpdate: relationOptions.onUpdate,
|
|
515
|
+
deferrable: relationOptions.deferrable,
|
|
516
|
+
nullable: relationOptions.nullable,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
function parseColumn(property, decorator, generatedDecorator) {
|
|
520
|
+
const propertyName = property.getName();
|
|
521
|
+
const decoratorName = decorator.getName();
|
|
522
|
+
const args = decorator.getArguments();
|
|
523
|
+
let strategy;
|
|
524
|
+
let typeHint;
|
|
525
|
+
let optionsLiteral;
|
|
526
|
+
if (decoratorName === 'PrimaryGeneratedColumn') {
|
|
527
|
+
if (args.length > 0 && isStringArgument(args[0])) {
|
|
528
|
+
strategy = getStringArgument(args[0]);
|
|
529
|
+
}
|
|
530
|
+
for (const arg of args) {
|
|
531
|
+
if (Node.isObjectLiteralExpression(arg)) {
|
|
532
|
+
optionsLiteral = arg;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
else {
|
|
537
|
+
if (args.length > 0 && !Node.isObjectLiteralExpression(args[0])) {
|
|
538
|
+
typeHint = parseColumnTypeExpression(args[0], propertyName);
|
|
539
|
+
}
|
|
540
|
+
for (const arg of args) {
|
|
541
|
+
if (Node.isObjectLiteralExpression(arg)) {
|
|
542
|
+
optionsLiteral = arg;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const options = readLiteralObjectOptions(optionsLiteral, propertyName);
|
|
547
|
+
if (decoratorName === 'PrimaryGeneratedColumn' && !strategy) {
|
|
548
|
+
strategy = optionString(options, 'strategy') ?? 'increment';
|
|
549
|
+
}
|
|
550
|
+
const generated = generatedDecorator
|
|
551
|
+
? parseGeneratedDecorator(generatedDecorator, propertyName)
|
|
552
|
+
: undefined;
|
|
553
|
+
const columnName = optionString(options, 'name') ?? propertyName;
|
|
554
|
+
const inferredType = optionString(options, 'type') ??
|
|
555
|
+
typeHint ??
|
|
556
|
+
typeFromSpecialDecorator(decoratorName) ??
|
|
557
|
+
inferTypeFromProperty(property);
|
|
558
|
+
const resolvedType = inferredType ?? typeFromGenerationStrategy(strategy ?? generated?.strategy);
|
|
559
|
+
if (!resolvedType) {
|
|
560
|
+
throw new Error(`Unable to resolve database type for column "${propertyName}". Provide an explicit type in the decorator options.`);
|
|
561
|
+
}
|
|
562
|
+
const isPrimary = decoratorName === 'PrimaryColumn' ||
|
|
563
|
+
decoratorName === 'PrimaryGeneratedColumn';
|
|
564
|
+
const isGenerated = decoratorName === 'PrimaryGeneratedColumn' || generated !== undefined;
|
|
565
|
+
return {
|
|
566
|
+
name: columnName,
|
|
567
|
+
type: resolvedType,
|
|
568
|
+
isPrimary,
|
|
569
|
+
isGenerated,
|
|
570
|
+
generationStrategy: strategy ?? generated?.strategy,
|
|
571
|
+
isNullable: optionBoolean(options, 'nullable') ?? false,
|
|
572
|
+
isUnique: optionBoolean(options, 'unique') ?? false,
|
|
573
|
+
isArray: optionBoolean(options, 'array') ?? false,
|
|
574
|
+
length: optionString(options, 'length'),
|
|
575
|
+
width: optionNumber(options, 'width'),
|
|
576
|
+
precision: optionNumber(options, 'precision'),
|
|
577
|
+
scale: optionNumber(options, 'scale'),
|
|
578
|
+
default: optionCode(options, 'default'),
|
|
579
|
+
onUpdate: optionString(options, 'onUpdate'),
|
|
580
|
+
charset: optionString(options, 'charset'),
|
|
581
|
+
collation: optionString(options, 'collation'),
|
|
582
|
+
enum: optionStringArray(options, 'enum'),
|
|
583
|
+
enumName: optionString(options, 'enumName'),
|
|
584
|
+
primaryKeyConstraintName: optionString(options, 'primaryKeyConstraintName'),
|
|
585
|
+
comment: optionString(options, 'comment'),
|
|
586
|
+
unsigned: optionBoolean(options, 'unsigned') ?? undefined,
|
|
587
|
+
zerofill: optionBoolean(options, 'zerofill') ?? undefined,
|
|
588
|
+
generatedType: optionString(options, 'generatedType'),
|
|
589
|
+
asExpression: optionCode(options, 'asExpression'),
|
|
590
|
+
generatedIdentity: optionString(options, 'generatedIdentity'),
|
|
591
|
+
spatialFeatureType: optionString(options, 'spatialFeatureType'),
|
|
592
|
+
srid: optionNumber(options, 'srid'),
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
function parseGeneratedDecorator(decorator, propertyName) {
|
|
596
|
+
const args = decorator.getArguments();
|
|
597
|
+
if (args.length === 0) {
|
|
598
|
+
return {};
|
|
599
|
+
}
|
|
600
|
+
if (!isStringArgument(args[0])) {
|
|
601
|
+
throw new Error(`Unsupported @Generated strategy for property "${propertyName}". Use a string literal strategy.`);
|
|
602
|
+
}
|
|
603
|
+
return { strategy: getStringArgument(args[0]) };
|
|
604
|
+
}
|
|
605
|
+
function parseRelationTargetClassName(decorator) {
|
|
606
|
+
const args = decorator.getArguments();
|
|
607
|
+
if (args.length === 0) {
|
|
608
|
+
throw new Error(`Decorator @${decorator.getName()} requires a target entity callback.`);
|
|
609
|
+
}
|
|
610
|
+
const first = args[0];
|
|
611
|
+
if (Node.isIdentifier(first)) {
|
|
612
|
+
return first.getText();
|
|
613
|
+
}
|
|
614
|
+
if (!Node.isArrowFunction(first) && !Node.isFunctionExpression(first)) {
|
|
615
|
+
throw new Error(`Unable to resolve relation target in @${decorator.getName()}. Use () => TargetEntity.`);
|
|
616
|
+
}
|
|
617
|
+
const body = first.getBody();
|
|
618
|
+
if (Node.isIdentifier(body)) {
|
|
619
|
+
return body.getText();
|
|
620
|
+
}
|
|
621
|
+
if (Node.isParenthesizedExpression(body) &&
|
|
622
|
+
Node.isIdentifier(body.getExpression())) {
|
|
623
|
+
return body.getExpression().getText();
|
|
624
|
+
}
|
|
625
|
+
if (Node.isBlock(body)) {
|
|
626
|
+
const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);
|
|
627
|
+
if (returns.length === 1) {
|
|
628
|
+
const expression = returns[0].getExpression();
|
|
629
|
+
if (expression && Node.isIdentifier(expression)) {
|
|
630
|
+
return expression.getText();
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
throw new Error(`Unable to resolve relation target in @${decorator.getName()}. Use () => TargetEntity.`);
|
|
635
|
+
}
|
|
636
|
+
function parseRelationOptions(decorator) {
|
|
637
|
+
const args = decorator.getArguments();
|
|
638
|
+
const optionsLiteral = args.find((arg) => Node.isObjectLiteralExpression(arg));
|
|
639
|
+
if (!optionsLiteral || !Node.isObjectLiteralExpression(optionsLiteral)) {
|
|
640
|
+
return {};
|
|
641
|
+
}
|
|
642
|
+
const options = readLiteralObjectOptions(optionsLiteral);
|
|
643
|
+
return {
|
|
644
|
+
onDelete: optionString(options, 'onDelete'),
|
|
645
|
+
onUpdate: optionString(options, 'onUpdate'),
|
|
646
|
+
deferrable: optionString(options, 'deferrable'),
|
|
647
|
+
nullable: optionBoolean(options, 'nullable'),
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function parseJoinColumnDecorator(decorator, propertyName) {
|
|
651
|
+
const args = decorator.getArguments();
|
|
652
|
+
const first = args[0];
|
|
653
|
+
if (!first) {
|
|
654
|
+
throw new Error(`Relation "${propertyName}" uses implicit join-column naming. Add @JoinColumn({ name: ..., referencedColumnName: ... }).`);
|
|
655
|
+
}
|
|
656
|
+
if (Node.isArrayLiteralExpression(first)) {
|
|
657
|
+
throw new Error(`Composite @JoinColumn arrays are not supported for relation "${propertyName}".`);
|
|
658
|
+
}
|
|
659
|
+
if (!Node.isObjectLiteralExpression(first)) {
|
|
660
|
+
throw new Error(`@JoinColumn for relation "${propertyName}" must use an object literal.`);
|
|
661
|
+
}
|
|
662
|
+
const name = readStringProperty(first, 'name');
|
|
663
|
+
if (!name) {
|
|
664
|
+
throw new Error(`Relation "${propertyName}" uses implicit join-column naming. Provide JoinColumn.name explicitly.`);
|
|
665
|
+
}
|
|
666
|
+
return {
|
|
667
|
+
name,
|
|
668
|
+
referencedColumnName: readStringProperty(first, 'referencedColumnName'),
|
|
669
|
+
foreignKeyConstraintName: readStringProperty(first, 'foreignKeyConstraintName'),
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function parseNamedExpressionDecorator(decorator, decoratorName, subjectName) {
|
|
673
|
+
const args = decorator.getArguments();
|
|
674
|
+
const name = args.find((arg) => isStringArgument(arg));
|
|
675
|
+
const expression = [...args].reverse().find((arg) => isStringArgument(arg));
|
|
676
|
+
if (!name || !expression) {
|
|
677
|
+
throw new Error(`@${decoratorName} on "${subjectName}" must declare explicit name and expression string literals.`);
|
|
678
|
+
}
|
|
679
|
+
return {
|
|
680
|
+
name: getStringArgument(name),
|
|
681
|
+
expression: getStringArgument(expression),
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
function parseUniqueDecorator(decorator, subjectName, fallbackColumnNames) {
|
|
685
|
+
const args = decorator.getArguments();
|
|
686
|
+
const nameArg = args.find((arg) => isStringArgument(arg));
|
|
687
|
+
const columnsArg = args.find((arg) => Node.isArrayLiteralExpression(arg));
|
|
688
|
+
if (!nameArg) {
|
|
689
|
+
throw new Error(`@Unique on "${subjectName}" must declare an explicit name to avoid implicit naming drift.`);
|
|
690
|
+
}
|
|
691
|
+
const columnNames = columnsArg
|
|
692
|
+
? parseStringArrayLiteral(columnsArg)
|
|
693
|
+
: fallbackColumnNames ?? [];
|
|
694
|
+
if (columnNames.length === 0) {
|
|
695
|
+
throw new Error(`@Unique "${getStringArgument(nameArg)}" on "${subjectName}" must declare columns explicitly.`);
|
|
696
|
+
}
|
|
697
|
+
const optionsArg = [...args]
|
|
698
|
+
.reverse()
|
|
699
|
+
.find((arg) => Node.isObjectLiteralExpression(arg));
|
|
700
|
+
const options = optionsArg && Node.isObjectLiteralExpression(optionsArg)
|
|
701
|
+
? readLiteralObjectOptions(optionsArg, subjectName)
|
|
702
|
+
: undefined;
|
|
703
|
+
return {
|
|
704
|
+
name: getStringArgument(nameArg),
|
|
705
|
+
columnNames: [...columnNames].sort(),
|
|
706
|
+
deferrable: optionString(options, 'deferrable'),
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function parseIndexDecorator(decorator, subjectName, fallbackColumnNames) {
|
|
710
|
+
const args = decorator.getArguments();
|
|
711
|
+
const nameArg = args.find((arg) => isStringArgument(arg));
|
|
712
|
+
const columnsArg = args.find((arg) => Node.isArrayLiteralExpression(arg));
|
|
713
|
+
if (!nameArg) {
|
|
714
|
+
throw new Error(`@Index on "${subjectName}" must declare an explicit index name to avoid implicit naming drift.`);
|
|
715
|
+
}
|
|
716
|
+
const columnNames = columnsArg
|
|
717
|
+
? parseStringArrayLiteral(columnsArg)
|
|
718
|
+
: fallbackColumnNames ?? [];
|
|
719
|
+
if (columnNames.length === 0) {
|
|
720
|
+
throw new Error(`@Index "${getStringArgument(nameArg)}" on "${subjectName}" must declare columns explicitly.`);
|
|
721
|
+
}
|
|
722
|
+
const optionsArg = [...args]
|
|
723
|
+
.reverse()
|
|
724
|
+
.find((arg) => Node.isObjectLiteralExpression(arg));
|
|
725
|
+
const options = optionsArg && Node.isObjectLiteralExpression(optionsArg)
|
|
726
|
+
? readLiteralObjectOptions(optionsArg, subjectName)
|
|
727
|
+
: undefined;
|
|
728
|
+
return {
|
|
729
|
+
name: getStringArgument(nameArg),
|
|
730
|
+
columnNames: [...columnNames].sort(),
|
|
731
|
+
isUnique: optionBoolean(options, 'unique') ?? false,
|
|
732
|
+
where: optionString(options, 'where'),
|
|
733
|
+
isSpatial: optionBoolean(options, 'spatial') ?? undefined,
|
|
734
|
+
isConcurrent: optionBoolean(options, 'concurrent') ?? undefined,
|
|
735
|
+
isFulltext: optionBoolean(options, 'fulltext') ?? undefined,
|
|
736
|
+
parser: optionString(options, 'parser'),
|
|
737
|
+
synchronize: optionBoolean(options, 'synchronize'),
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
function parseStringArrayLiteral(expression) {
|
|
741
|
+
if (!Node.isArrayLiteralExpression(expression)) {
|
|
742
|
+
throw new Error('Expected an array literal with string entries.');
|
|
743
|
+
}
|
|
744
|
+
const values = [];
|
|
745
|
+
for (const element of expression.getElements()) {
|
|
746
|
+
if (!isStringArgument(element)) {
|
|
747
|
+
throw new Error('Array literals must only contain string literals.');
|
|
748
|
+
}
|
|
749
|
+
values.push(getStringArgument(element));
|
|
750
|
+
}
|
|
751
|
+
return values;
|
|
752
|
+
}
|
|
753
|
+
function readLiteralObjectOptions(literal, subjectName) {
|
|
754
|
+
if (!literal) {
|
|
755
|
+
return undefined;
|
|
756
|
+
}
|
|
757
|
+
const options = new Map();
|
|
758
|
+
for (const property of literal.getProperties()) {
|
|
759
|
+
if (Node.isSpreadAssignment(property)) {
|
|
760
|
+
throw new Error(`Spread options are not supported${subjectName ? ` for "${subjectName}"` : ''}. Use explicit literal values.`);
|
|
761
|
+
}
|
|
762
|
+
if (Node.isShorthandPropertyAssignment(property)) {
|
|
763
|
+
throw new Error(`Shorthand options are not supported${subjectName ? ` for "${subjectName}"` : ''}. Use explicit literal values.`);
|
|
764
|
+
}
|
|
765
|
+
if (!Node.isPropertyAssignment(property)) {
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
const key = property
|
|
769
|
+
.getNameNode()
|
|
770
|
+
.getText()
|
|
771
|
+
.replace(/^['"]|['"]$/g, '');
|
|
772
|
+
const initializer = property.getInitializer();
|
|
773
|
+
if (!initializer) {
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
assertSerializableExpression(initializer, subjectName ?? key);
|
|
777
|
+
options.set(key, initializer.getText().trim());
|
|
778
|
+
}
|
|
779
|
+
return options;
|
|
780
|
+
}
|
|
781
|
+
function assertSerializableExpression(expression, subjectName) {
|
|
782
|
+
if (Node.isStringLiteral(expression) ||
|
|
783
|
+
Node.isNoSubstitutionTemplateLiteral(expression) ||
|
|
784
|
+
Node.isNumericLiteral(expression) ||
|
|
785
|
+
expression.getKind() === SyntaxKind.TrueKeyword ||
|
|
786
|
+
expression.getKind() === SyntaxKind.FalseKeyword ||
|
|
787
|
+
expression.getKind() === SyntaxKind.NullKeyword) {
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (Node.isPrefixUnaryExpression(expression)) {
|
|
791
|
+
assertSerializableExpression(expression.getOperand(), subjectName);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
if (Node.isArrayLiteralExpression(expression)) {
|
|
795
|
+
for (const element of expression.getElements()) {
|
|
796
|
+
if (!Node.isExpression(element)) {
|
|
797
|
+
throw new Error(`Unsupported non-expression value in array literal for "${subjectName}".`);
|
|
798
|
+
}
|
|
799
|
+
assertSerializableExpression(element, subjectName);
|
|
800
|
+
}
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (Node.isObjectLiteralExpression(expression)) {
|
|
804
|
+
for (const property of expression.getProperties()) {
|
|
805
|
+
if (!Node.isPropertyAssignment(property)) {
|
|
806
|
+
throw new Error(`Unsupported object literal option in "${subjectName}". Use plain property assignments.`);
|
|
807
|
+
}
|
|
808
|
+
const initializer = property.getInitializer();
|
|
809
|
+
if (!initializer) {
|
|
810
|
+
throw new Error(`Unsupported object literal option in "${subjectName}".`);
|
|
811
|
+
}
|
|
812
|
+
assertSerializableExpression(initializer, subjectName);
|
|
813
|
+
}
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
if (Node.isArrowFunction(expression) ||
|
|
817
|
+
Node.isFunctionExpression(expression)) {
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
throw new Error(`Unsupported expression "${expression.getText()}" in "${subjectName}". Use literal values or arrow functions only.`);
|
|
821
|
+
}
|
|
822
|
+
function parseColumnTypeExpression(expression, propertyName) {
|
|
823
|
+
if (isStringArgument(expression)) {
|
|
824
|
+
return getStringArgument(expression);
|
|
825
|
+
}
|
|
826
|
+
if (Node.isIdentifier(expression)) {
|
|
827
|
+
const text = expression.getText();
|
|
828
|
+
if (text === 'String') {
|
|
829
|
+
return 'varchar';
|
|
830
|
+
}
|
|
831
|
+
if (text === 'Number') {
|
|
832
|
+
return 'int';
|
|
833
|
+
}
|
|
834
|
+
if (text === 'Boolean') {
|
|
835
|
+
return 'boolean';
|
|
836
|
+
}
|
|
837
|
+
if (text === 'Date') {
|
|
838
|
+
return 'timestamp';
|
|
839
|
+
}
|
|
840
|
+
if (text === 'Buffer') {
|
|
841
|
+
return 'bytea';
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
throw new Error(`Unsupported column type expression "${expression.getText()}" for property "${propertyName}".`);
|
|
845
|
+
}
|
|
846
|
+
function inferTypeFromProperty(property) {
|
|
847
|
+
const typeNode = property.getTypeNode();
|
|
848
|
+
if (!typeNode) {
|
|
849
|
+
return undefined;
|
|
850
|
+
}
|
|
851
|
+
const text = typeNode.getText().trim();
|
|
852
|
+
if (text === 'string') {
|
|
853
|
+
return 'varchar';
|
|
854
|
+
}
|
|
855
|
+
if (text === 'number') {
|
|
856
|
+
return 'int';
|
|
857
|
+
}
|
|
858
|
+
if (text === 'boolean') {
|
|
859
|
+
return 'boolean';
|
|
860
|
+
}
|
|
861
|
+
if (text === 'Date') {
|
|
862
|
+
return 'timestamp';
|
|
863
|
+
}
|
|
864
|
+
if (text === 'Buffer' || text === 'Uint8Array') {
|
|
865
|
+
return 'bytea';
|
|
866
|
+
}
|
|
867
|
+
if (text === 'bigint') {
|
|
868
|
+
return 'bigint';
|
|
869
|
+
}
|
|
870
|
+
return undefined;
|
|
871
|
+
}
|
|
872
|
+
function typeFromSpecialDecorator(decoratorName) {
|
|
873
|
+
if (decoratorName === 'CreateDateColumn') {
|
|
874
|
+
return 'timestamp';
|
|
875
|
+
}
|
|
876
|
+
if (decoratorName === 'UpdateDateColumn') {
|
|
877
|
+
return 'timestamp';
|
|
878
|
+
}
|
|
879
|
+
if (decoratorName === 'DeleteDateColumn') {
|
|
880
|
+
return 'timestamp';
|
|
881
|
+
}
|
|
882
|
+
if (decoratorName === 'VersionColumn') {
|
|
883
|
+
return 'int';
|
|
884
|
+
}
|
|
885
|
+
return undefined;
|
|
886
|
+
}
|
|
887
|
+
function typeFromGenerationStrategy(strategy) {
|
|
888
|
+
if (!strategy) {
|
|
889
|
+
return undefined;
|
|
890
|
+
}
|
|
891
|
+
if (strategy === 'uuid') {
|
|
892
|
+
return 'uuid';
|
|
893
|
+
}
|
|
894
|
+
if (strategy === 'increment' ||
|
|
895
|
+
strategy === 'identity' ||
|
|
896
|
+
strategy === 'rowid') {
|
|
897
|
+
return 'int';
|
|
898
|
+
}
|
|
899
|
+
return undefined;
|
|
900
|
+
}
|
|
901
|
+
function optionCode(options, key) {
|
|
902
|
+
return options?.get(key);
|
|
903
|
+
}
|
|
904
|
+
function optionString(options, key) {
|
|
905
|
+
const value = options?.get(key);
|
|
906
|
+
if (!value) {
|
|
907
|
+
return undefined;
|
|
908
|
+
}
|
|
909
|
+
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
910
|
+
(value.startsWith("'") && value.endsWith("'"))) {
|
|
911
|
+
return value.slice(1, -1);
|
|
912
|
+
}
|
|
913
|
+
if (value.startsWith('`') && value.endsWith('`')) {
|
|
914
|
+
return value.slice(1, -1);
|
|
915
|
+
}
|
|
916
|
+
return undefined;
|
|
917
|
+
}
|
|
918
|
+
function optionNumber(options, key) {
|
|
919
|
+
const value = options?.get(key);
|
|
920
|
+
if (!value) {
|
|
921
|
+
return undefined;
|
|
922
|
+
}
|
|
923
|
+
const numeric = Number(value);
|
|
924
|
+
if (!Number.isFinite(numeric)) {
|
|
925
|
+
return undefined;
|
|
926
|
+
}
|
|
927
|
+
return numeric;
|
|
928
|
+
}
|
|
929
|
+
function optionBoolean(options, key) {
|
|
930
|
+
const value = options?.get(key);
|
|
931
|
+
if (value === 'true') {
|
|
932
|
+
return true;
|
|
933
|
+
}
|
|
934
|
+
if (value === 'false') {
|
|
935
|
+
return false;
|
|
936
|
+
}
|
|
937
|
+
return undefined;
|
|
938
|
+
}
|
|
939
|
+
function optionStringArray(options, key) {
|
|
940
|
+
const value = options?.get(key);
|
|
941
|
+
if (!value) {
|
|
942
|
+
return undefined;
|
|
943
|
+
}
|
|
944
|
+
if (!value.startsWith('[') || !value.endsWith(']')) {
|
|
945
|
+
return undefined;
|
|
946
|
+
}
|
|
947
|
+
try {
|
|
948
|
+
const parsed = JSON.parse(value.replace(/'/g, '"'));
|
|
949
|
+
if (!Array.isArray(parsed) ||
|
|
950
|
+
!parsed.every((entry) => typeof entry === 'string')) {
|
|
951
|
+
return undefined;
|
|
952
|
+
}
|
|
953
|
+
return parsed;
|
|
954
|
+
}
|
|
955
|
+
catch {
|
|
956
|
+
return undefined;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
function readStringProperty(objectLiteral, propertyName) {
|
|
960
|
+
const property = objectLiteral.getProperty(propertyName);
|
|
961
|
+
if (!property || !Node.isPropertyAssignment(property)) {
|
|
962
|
+
return undefined;
|
|
963
|
+
}
|
|
964
|
+
const initializer = property.getInitializer();
|
|
965
|
+
if (!initializer || !isStringArgument(initializer)) {
|
|
966
|
+
return undefined;
|
|
967
|
+
}
|
|
968
|
+
return getStringArgument(initializer).trim();
|
|
969
|
+
}
|
|
970
|
+
function isStringArgument(node) {
|
|
971
|
+
return (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node));
|
|
972
|
+
}
|
|
973
|
+
function getStringArgument(node) {
|
|
974
|
+
if (Node.isStringLiteral(node) ||
|
|
975
|
+
Node.isNoSubstitutionTemplateLiteral(node)) {
|
|
976
|
+
return node.getLiteralText();
|
|
977
|
+
}
|
|
978
|
+
throw new Error(`Expected a string literal, received "${node.getText()}".`);
|
|
979
|
+
}
|
|
980
|
+
function resolvePendingRelations(parsedEntities) {
|
|
981
|
+
const byKey = new Map();
|
|
982
|
+
const byClass = new Map();
|
|
983
|
+
for (const entity of parsedEntities) {
|
|
984
|
+
byKey.set(entity.key, entity);
|
|
985
|
+
const existing = byClass.get(entity.className);
|
|
986
|
+
if (existing) {
|
|
987
|
+
throw new Error(`Duplicate entity class name "${entity.className}" in "${existing.key}" and "${entity.key}".`);
|
|
988
|
+
}
|
|
989
|
+
byClass.set(entity.className, entity);
|
|
990
|
+
}
|
|
991
|
+
for (const entity of parsedEntities) {
|
|
992
|
+
for (const relation of entity.pendingRelations) {
|
|
993
|
+
const sourceEntity = byKey.get(relation.sourceEntityKey);
|
|
994
|
+
const targetEntity = byClass.get(relation.targetClassName);
|
|
995
|
+
if (!sourceEntity || !targetEntity) {
|
|
996
|
+
throw new Error(`Unable to resolve relation target "${relation.targetClassName}" for property "${relation.sourcePropertyName}".`);
|
|
997
|
+
}
|
|
998
|
+
const referencedColumn = resolveReferencedColumn(targetEntity, relation);
|
|
999
|
+
const sourceColumn = ensureJoinColumn(sourceEntity, relation, referencedColumn);
|
|
1000
|
+
const foreignKey = {
|
|
1001
|
+
name: relation.foreignKeyConstraintName,
|
|
1002
|
+
columnNames: [sourceColumn.name],
|
|
1003
|
+
referencedTableKey: targetEntity.key,
|
|
1004
|
+
referencedColumnNames: [referencedColumn.name],
|
|
1005
|
+
onDelete: relation.onDelete,
|
|
1006
|
+
onUpdate: relation.onUpdate,
|
|
1007
|
+
deferrable: relation.deferrable,
|
|
1008
|
+
};
|
|
1009
|
+
upsertForeignKey(sourceEntity.foreignKeys, foreignKey);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
function resolveReferencedColumn(targetEntity, relation) {
|
|
1014
|
+
if (relation.referencedColumnName) {
|
|
1015
|
+
const explicit = targetEntity.columns.find((column) => column.name === relation.referencedColumnName);
|
|
1016
|
+
if (!explicit) {
|
|
1017
|
+
throw new Error(`Referenced column "${relation.referencedColumnName}" does not exist on entity "${targetEntity.className}".`);
|
|
1018
|
+
}
|
|
1019
|
+
return explicit;
|
|
1020
|
+
}
|
|
1021
|
+
const primaryColumns = targetEntity.columns.filter((column) => column.isPrimary);
|
|
1022
|
+
if (primaryColumns.length !== 1) {
|
|
1023
|
+
throw new Error(`Relation "${relation.sourcePropertyName}" must declare JoinColumn.referencedColumnName when target entity "${targetEntity.className}" has ${primaryColumns.length} primary columns.`);
|
|
1024
|
+
}
|
|
1025
|
+
return primaryColumns[0];
|
|
1026
|
+
}
|
|
1027
|
+
function ensureJoinColumn(sourceEntity, relation, referencedColumn) {
|
|
1028
|
+
const existing = sourceEntity.columns.find((column) => column.name === relation.joinColumnName);
|
|
1029
|
+
if (existing) {
|
|
1030
|
+
if (existing.type !== referencedColumn.type) {
|
|
1031
|
+
throw new Error(`Join column "${relation.joinColumnName}" type "${existing.type}" does not match referenced column type "${referencedColumn.type}".`);
|
|
1032
|
+
}
|
|
1033
|
+
return existing;
|
|
1034
|
+
}
|
|
1035
|
+
const syntheticColumn = {
|
|
1036
|
+
name: relation.joinColumnName,
|
|
1037
|
+
type: referencedColumn.type,
|
|
1038
|
+
isPrimary: false,
|
|
1039
|
+
isGenerated: false,
|
|
1040
|
+
isNullable: relation.nullable ?? true,
|
|
1041
|
+
isUnique: false,
|
|
1042
|
+
isArray: false,
|
|
1043
|
+
};
|
|
1044
|
+
sourceEntity.columns.push(syntheticColumn);
|
|
1045
|
+
return syntheticColumn;
|
|
1046
|
+
}
|
|
1047
|
+
function upsertColumn(columns, column) {
|
|
1048
|
+
const index = columns.findIndex((entry) => entry.name === column.name);
|
|
1049
|
+
if (index === -1) {
|
|
1050
|
+
columns.push(column);
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
columns[index] = column;
|
|
1054
|
+
}
|
|
1055
|
+
function upsertForeignKey(foreignKeys, foreignKey) {
|
|
1056
|
+
const key = foreignKeyKey(foreignKey);
|
|
1057
|
+
const index = foreignKeys.findIndex((entry) => foreignKeyKey(entry) === key);
|
|
1058
|
+
if (index === -1) {
|
|
1059
|
+
foreignKeys.push(foreignKey);
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
foreignKeys[index] = foreignKey;
|
|
1063
|
+
}
|
|
1064
|
+
function sortParsedEntity(entity) {
|
|
1065
|
+
return {
|
|
1066
|
+
...entity,
|
|
1067
|
+
columns: [...entity.columns].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1068
|
+
uniques: [...entity.uniques].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1069
|
+
indices: [...entity.indices].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1070
|
+
checks: [...entity.checks].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1071
|
+
exclusions: [...entity.exclusions].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1072
|
+
foreignKeys: [...entity.foreignKeys].sort((left, right) => foreignKeyKey(left).localeCompare(foreignKeyKey(right))),
|
|
1073
|
+
pendingRelations: entity.pendingRelations,
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
function sortEntity(entity) {
|
|
1077
|
+
return {
|
|
1078
|
+
...entity,
|
|
1079
|
+
columns: [...entity.columns].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1080
|
+
uniques: [...entity.uniques].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1081
|
+
indices: [...entity.indices].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1082
|
+
checks: [...entity.checks].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1083
|
+
exclusions: [...entity.exclusions].sort((left, right) => left.name.localeCompare(right.name)),
|
|
1084
|
+
foreignKeys: [...entity.foreignKeys].sort((left, right) => foreignKeyKey(left).localeCompare(foreignKeyKey(right))),
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
function emptySnapshot() {
|
|
1088
|
+
return {
|
|
1089
|
+
entities: [],
|
|
1090
|
+
hash: sha256('[]'),
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function diffSnapshots(previous, current) {
|
|
1094
|
+
if (previous.hash === current.hash) {
|
|
1095
|
+
return {
|
|
1096
|
+
createTables: [],
|
|
1097
|
+
dropTables: [],
|
|
1098
|
+
alterTables: [],
|
|
1099
|
+
hasChanges: false,
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
const previousMap = toEntityMap(previous.entities);
|
|
1103
|
+
const currentMap = toEntityMap(current.entities);
|
|
1104
|
+
const createTables = [];
|
|
1105
|
+
const dropTables = [];
|
|
1106
|
+
const alterTables = [];
|
|
1107
|
+
for (const [key, entity] of currentMap.entries()) {
|
|
1108
|
+
if (!previousMap.has(key)) {
|
|
1109
|
+
createTables.push(entity);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
for (const [key, entity] of previousMap.entries()) {
|
|
1113
|
+
if (!currentMap.has(key)) {
|
|
1114
|
+
dropTables.push(entity);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
detectTableRenameLikeChanges(createTables, dropTables);
|
|
1118
|
+
for (const [key, before] of previousMap.entries()) {
|
|
1119
|
+
const after = currentMap.get(key);
|
|
1120
|
+
if (!after) {
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
const delta = diffTable(before, after);
|
|
1124
|
+
if (delta) {
|
|
1125
|
+
alterTables.push(delta);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
createTables.sort((left, right) => left.key.localeCompare(right.key));
|
|
1129
|
+
dropTables.sort((left, right) => left.key.localeCompare(right.key));
|
|
1130
|
+
alterTables.sort((left, right) => left.before.key.localeCompare(right.before.key));
|
|
1131
|
+
return {
|
|
1132
|
+
createTables,
|
|
1133
|
+
dropTables,
|
|
1134
|
+
alterTables,
|
|
1135
|
+
hasChanges: createTables.length > 0 ||
|
|
1136
|
+
dropTables.length > 0 ||
|
|
1137
|
+
alterTables.length > 0,
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
function toEntityMap(entities) {
|
|
1141
|
+
const map = new Map();
|
|
1142
|
+
for (const entity of entities) {
|
|
1143
|
+
map.set(entity.key, entity);
|
|
1144
|
+
}
|
|
1145
|
+
return map;
|
|
1146
|
+
}
|
|
1147
|
+
function detectTableRenameLikeChanges(createTables, dropTables) {
|
|
1148
|
+
const droppedSignatures = new Set(dropTables.map((entity) => tableRenameSignature(entity)));
|
|
1149
|
+
for (const created of createTables) {
|
|
1150
|
+
const signature = tableRenameSignature(created);
|
|
1151
|
+
if (droppedSignatures.has(signature)) {
|
|
1152
|
+
throw new Error(`Detected rename-like table change for "${created.tableName}". Create a manual rename migration instead of drop/create.`);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
function tableRenameSignature(entity) {
|
|
1157
|
+
return JSON.stringify({
|
|
1158
|
+
columns: entity.columns,
|
|
1159
|
+
uniques: entity.uniques,
|
|
1160
|
+
indices: entity.indices,
|
|
1161
|
+
checks: entity.checks,
|
|
1162
|
+
exclusions: entity.exclusions,
|
|
1163
|
+
foreignKeys: entity.foreignKeys,
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
function diffTable(before, after) {
|
|
1167
|
+
const beforeColumns = toNamedMap(before.columns, (column) => column.name);
|
|
1168
|
+
const afterColumns = toNamedMap(after.columns, (column) => column.name);
|
|
1169
|
+
const dropColumns = [];
|
|
1170
|
+
const addColumns = [];
|
|
1171
|
+
const changeColumns = [];
|
|
1172
|
+
for (const [name, column] of beforeColumns.entries()) {
|
|
1173
|
+
const next = afterColumns.get(name);
|
|
1174
|
+
if (!next) {
|
|
1175
|
+
dropColumns.push(column);
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1178
|
+
if (!deepEqual(column, next)) {
|
|
1179
|
+
changeColumns.push({ before: column, after: next });
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
for (const [name, column] of afterColumns.entries()) {
|
|
1183
|
+
if (!beforeColumns.has(name)) {
|
|
1184
|
+
addColumns.push(column);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
detectColumnRenameLikeChanges(before.key, addColumns, dropColumns);
|
|
1188
|
+
const uniqueDiff = diffNamedCollection(before.uniques, after.uniques, (item) => item.name);
|
|
1189
|
+
const indexDiff = diffNamedCollection(before.indices, after.indices, (item) => item.name);
|
|
1190
|
+
const checkDiff = diffNamedCollection(before.checks, after.checks, (item) => item.name);
|
|
1191
|
+
const exclusionDiff = diffNamedCollection(before.exclusions, after.exclusions, (item) => item.name);
|
|
1192
|
+
const foreignKeyDiff = diffNamedCollection(before.foreignKeys, after.foreignKeys, (item) => foreignKeyKey(item));
|
|
1193
|
+
const hasChanges = dropColumns.length > 0 ||
|
|
1194
|
+
addColumns.length > 0 ||
|
|
1195
|
+
changeColumns.length > 0 ||
|
|
1196
|
+
uniqueDiff.removed.length > 0 ||
|
|
1197
|
+
uniqueDiff.added.length > 0 ||
|
|
1198
|
+
indexDiff.removed.length > 0 ||
|
|
1199
|
+
indexDiff.added.length > 0 ||
|
|
1200
|
+
checkDiff.removed.length > 0 ||
|
|
1201
|
+
checkDiff.added.length > 0 ||
|
|
1202
|
+
exclusionDiff.removed.length > 0 ||
|
|
1203
|
+
exclusionDiff.added.length > 0 ||
|
|
1204
|
+
foreignKeyDiff.removed.length > 0 ||
|
|
1205
|
+
foreignKeyDiff.added.length > 0;
|
|
1206
|
+
if (!hasChanges) {
|
|
1207
|
+
return undefined;
|
|
1208
|
+
}
|
|
1209
|
+
return {
|
|
1210
|
+
before,
|
|
1211
|
+
after,
|
|
1212
|
+
dropColumns,
|
|
1213
|
+
addColumns,
|
|
1214
|
+
changeColumns,
|
|
1215
|
+
dropUniques: uniqueDiff.removed,
|
|
1216
|
+
addUniques: uniqueDiff.added,
|
|
1217
|
+
dropIndices: indexDiff.removed,
|
|
1218
|
+
addIndices: indexDiff.added,
|
|
1219
|
+
dropChecks: checkDiff.removed,
|
|
1220
|
+
addChecks: checkDiff.added,
|
|
1221
|
+
dropExclusions: exclusionDiff.removed,
|
|
1222
|
+
addExclusions: exclusionDiff.added,
|
|
1223
|
+
dropForeignKeys: foreignKeyDiff.removed,
|
|
1224
|
+
addForeignKeys: foreignKeyDiff.added,
|
|
1225
|
+
};
|
|
1226
|
+
}
|
|
1227
|
+
function detectColumnRenameLikeChanges(tableKeyValue, addColumns, dropColumns) {
|
|
1228
|
+
if (addColumns.length === 0 || dropColumns.length === 0) {
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
const dropped = new Set(dropColumns.map((column) => columnRenameSignature(column)));
|
|
1232
|
+
for (const column of addColumns) {
|
|
1233
|
+
if (dropped.has(columnRenameSignature(column))) {
|
|
1234
|
+
throw new Error(`Detected rename-like column change in table "${tableKeyValue}". Create a manual rename migration.`);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
function columnRenameSignature(column) {
|
|
1239
|
+
return JSON.stringify({
|
|
1240
|
+
...column,
|
|
1241
|
+
name: undefined,
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
function diffNamedCollection(before, after, keySelector) {
|
|
1245
|
+
const beforeMap = toNamedMap(before, keySelector);
|
|
1246
|
+
const afterMap = toNamedMap(after, keySelector);
|
|
1247
|
+
const removed = [];
|
|
1248
|
+
const added = [];
|
|
1249
|
+
for (const [key, item] of beforeMap.entries()) {
|
|
1250
|
+
const next = afterMap.get(key);
|
|
1251
|
+
if (!next) {
|
|
1252
|
+
removed.push(item);
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
if (!deepEqual(item, next)) {
|
|
1256
|
+
removed.push(item);
|
|
1257
|
+
added.push(next);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
for (const [key, item] of afterMap.entries()) {
|
|
1261
|
+
if (!beforeMap.has(key)) {
|
|
1262
|
+
added.push(item);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
return {
|
|
1266
|
+
removed: removed.sort((left, right) => keySelector(left).localeCompare(keySelector(right))),
|
|
1267
|
+
added: added.sort((left, right) => keySelector(left).localeCompare(keySelector(right))),
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
function toNamedMap(values, keySelector) {
|
|
1271
|
+
const map = new Map();
|
|
1272
|
+
for (const value of values) {
|
|
1273
|
+
map.set(keySelector(value), value);
|
|
1274
|
+
}
|
|
1275
|
+
return map;
|
|
1276
|
+
}
|
|
1277
|
+
function foreignKeyKey(foreignKey) {
|
|
1278
|
+
if (foreignKey.name) {
|
|
1279
|
+
return `name:${foreignKey.name}`;
|
|
1280
|
+
}
|
|
1281
|
+
return `sig:${foreignKey.columnNames.join(',')}->${foreignKey.referencedTableKey}:${foreignKey.referencedColumnNames.join(',')}:${foreignKey.onDelete ?? ''}:${foreignKey.onUpdate ?? ''}:${foreignKey.deferrable ?? ''}`;
|
|
1282
|
+
}
|
|
1283
|
+
function renderMigration(diff) {
|
|
1284
|
+
const upStatements = [];
|
|
1285
|
+
const downStatements = [];
|
|
1286
|
+
for (const table of diff.createTables) {
|
|
1287
|
+
upStatements.push(`await queryRunner.createTable(${renderTable(table)}, true, false, false);`);
|
|
1288
|
+
if (table.foreignKeys.length > 0) {
|
|
1289
|
+
upStatements.push(`await queryRunner.createForeignKeys(${renderStringLiteral(tablePath(table))}, [${table.foreignKeys
|
|
1290
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1291
|
+
.join(', ')}]);`);
|
|
1292
|
+
}
|
|
1293
|
+
if (table.foreignKeys.length > 0) {
|
|
1294
|
+
downStatements.push(`await queryRunner.dropForeignKeys(${renderStringLiteral(tablePath(table))}, [${table.foreignKeys
|
|
1295
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1296
|
+
.join(', ')}]);`);
|
|
1297
|
+
}
|
|
1298
|
+
downStatements.push(`await queryRunner.dropTable(${renderStringLiteral(tablePath(table))}, true, true, true);`);
|
|
1299
|
+
}
|
|
1300
|
+
for (const delta of diff.alterTables) {
|
|
1301
|
+
const tableRef = renderStringLiteral(tablePath(delta.after));
|
|
1302
|
+
if (delta.dropForeignKeys.length > 0) {
|
|
1303
|
+
upStatements.push(`await queryRunner.dropForeignKeys(${tableRef}, [${delta.dropForeignKeys
|
|
1304
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1305
|
+
.join(', ')}]);`);
|
|
1306
|
+
downStatements.unshift(`await queryRunner.createForeignKeys(${tableRef}, [${delta.dropForeignKeys
|
|
1307
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1308
|
+
.join(', ')}]);`);
|
|
1309
|
+
}
|
|
1310
|
+
if (delta.dropIndices.length > 0) {
|
|
1311
|
+
for (const index of delta.dropIndices) {
|
|
1312
|
+
upStatements.push(`await queryRunner.dropIndex(${tableRef}, ${renderStringLiteral(index.name)});`);
|
|
1313
|
+
downStatements.unshift(`await queryRunner.createIndex(${tableRef}, ${renderIndex(index)});`);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
if (delta.dropUniques.length > 0) {
|
|
1317
|
+
for (const unique of delta.dropUniques) {
|
|
1318
|
+
upStatements.push(`await queryRunner.dropUniqueConstraint(${tableRef}, ${renderStringLiteral(unique.name)});`);
|
|
1319
|
+
downStatements.unshift(`await queryRunner.createUniqueConstraint(${tableRef}, ${renderUnique(unique)});`);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
if (delta.dropChecks.length > 0) {
|
|
1323
|
+
for (const check of delta.dropChecks) {
|
|
1324
|
+
upStatements.push(`await queryRunner.dropCheckConstraint(${tableRef}, ${renderStringLiteral(check.name)});`);
|
|
1325
|
+
downStatements.unshift(`await queryRunner.createCheckConstraint(${tableRef}, ${renderCheck(check)});`);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
if (delta.dropExclusions.length > 0) {
|
|
1329
|
+
for (const exclusion of delta.dropExclusions) {
|
|
1330
|
+
upStatements.push(`await queryRunner.dropExclusionConstraint(${tableRef}, ${renderStringLiteral(exclusion.name)});`);
|
|
1331
|
+
downStatements.unshift(`await queryRunner.createExclusionConstraint(${tableRef}, ${renderExclusion(exclusion)});`);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
if (delta.dropColumns.length > 0) {
|
|
1335
|
+
upStatements.push(`await queryRunner.dropColumns(${tableRef}, [${delta.dropColumns
|
|
1336
|
+
.map((column) => renderStringLiteral(column.name))
|
|
1337
|
+
.join(', ')}]);`);
|
|
1338
|
+
downStatements.unshift(`await queryRunner.addColumns(${tableRef}, [${delta.dropColumns
|
|
1339
|
+
.map((column) => renderColumn(column))
|
|
1340
|
+
.join(', ')}]);`);
|
|
1341
|
+
}
|
|
1342
|
+
if (delta.addColumns.length > 0) {
|
|
1343
|
+
upStatements.push(`await queryRunner.addColumns(${tableRef}, [${delta.addColumns
|
|
1344
|
+
.map((column) => renderColumn(column))
|
|
1345
|
+
.join(', ')}]);`);
|
|
1346
|
+
downStatements.unshift(`await queryRunner.dropColumns(${tableRef}, [${delta.addColumns
|
|
1347
|
+
.map((column) => renderStringLiteral(column.name))
|
|
1348
|
+
.join(', ')}]);`);
|
|
1349
|
+
}
|
|
1350
|
+
if (delta.changeColumns.length > 0) {
|
|
1351
|
+
upStatements.push(`await queryRunner.changeColumns(${tableRef}, [${delta.changeColumns
|
|
1352
|
+
.map((change) => `{ oldColumn: ${renderColumn(change.before)}, newColumn: ${renderColumn(change.after)} }`)
|
|
1353
|
+
.join(', ')}]);`);
|
|
1354
|
+
downStatements.unshift(`await queryRunner.changeColumns(${tableRef}, [${delta.changeColumns
|
|
1355
|
+
.map((change) => `{ oldColumn: ${renderColumn(change.after)}, newColumn: ${renderColumn(change.before)} }`)
|
|
1356
|
+
.join(', ')}]);`);
|
|
1357
|
+
}
|
|
1358
|
+
if (delta.addUniques.length > 0) {
|
|
1359
|
+
upStatements.push(`await queryRunner.createUniqueConstraints(${tableRef}, [${delta.addUniques
|
|
1360
|
+
.map((unique) => renderUnique(unique))
|
|
1361
|
+
.join(', ')}]);`);
|
|
1362
|
+
downStatements.unshift(`await queryRunner.dropUniqueConstraints(${tableRef}, [${delta.addUniques
|
|
1363
|
+
.map((unique) => renderUnique(unique))
|
|
1364
|
+
.join(', ')}]);`);
|
|
1365
|
+
}
|
|
1366
|
+
if (delta.addChecks.length > 0) {
|
|
1367
|
+
upStatements.push(`await queryRunner.createCheckConstraints(${tableRef}, [${delta.addChecks
|
|
1368
|
+
.map((check) => renderCheck(check))
|
|
1369
|
+
.join(', ')}]);`);
|
|
1370
|
+
downStatements.unshift(`await queryRunner.dropCheckConstraints(${tableRef}, [${delta.addChecks
|
|
1371
|
+
.map((check) => renderCheck(check))
|
|
1372
|
+
.join(', ')}]);`);
|
|
1373
|
+
}
|
|
1374
|
+
if (delta.addExclusions.length > 0) {
|
|
1375
|
+
upStatements.push(`await queryRunner.createExclusionConstraints(${tableRef}, [${delta.addExclusions
|
|
1376
|
+
.map((exclusion) => renderExclusion(exclusion))
|
|
1377
|
+
.join(', ')}]);`);
|
|
1378
|
+
downStatements.unshift(`await queryRunner.dropExclusionConstraints(${tableRef}, [${delta.addExclusions
|
|
1379
|
+
.map((exclusion) => renderExclusion(exclusion))
|
|
1380
|
+
.join(', ')}]);`);
|
|
1381
|
+
}
|
|
1382
|
+
if (delta.addIndices.length > 0) {
|
|
1383
|
+
for (const index of delta.addIndices) {
|
|
1384
|
+
upStatements.push(`await queryRunner.createIndex(${tableRef}, ${renderIndex(index)});`);
|
|
1385
|
+
downStatements.unshift(`await queryRunner.dropIndex(${tableRef}, ${renderStringLiteral(index.name)});`);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (delta.addForeignKeys.length > 0) {
|
|
1389
|
+
upStatements.push(`await queryRunner.createForeignKeys(${tableRef}, [${delta.addForeignKeys
|
|
1390
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1391
|
+
.join(', ')}]);`);
|
|
1392
|
+
downStatements.unshift(`await queryRunner.dropForeignKeys(${tableRef}, [${delta.addForeignKeys
|
|
1393
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1394
|
+
.join(', ')}]);`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
for (const table of diff.dropTables) {
|
|
1398
|
+
upStatements.push(`await queryRunner.dropTable(${renderStringLiteral(tablePath(table))}, true, true, true);`);
|
|
1399
|
+
downStatements.unshift(`await queryRunner.createTable(${renderTable(table)}, true, false, false);`);
|
|
1400
|
+
if (table.foreignKeys.length > 0) {
|
|
1401
|
+
downStatements.unshift(`await queryRunner.createForeignKeys(${renderStringLiteral(tablePath(table))}, [${table.foreignKeys
|
|
1402
|
+
.map((foreignKey) => renderForeignKey(foreignKey))
|
|
1403
|
+
.join(', ')}]);`);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
return {
|
|
1407
|
+
upStatements,
|
|
1408
|
+
downStatements,
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
function renderMigrationFile(options) {
|
|
1412
|
+
const upBody = options.upStatements.length > 0
|
|
1413
|
+
? options.upStatements.map((line) => ` ${line}`).join('\n')
|
|
1414
|
+
: ' // No schema changes detected';
|
|
1415
|
+
const downBody = options.downStatements.length > 0
|
|
1416
|
+
? options.downStatements.map((line) => ` ${line}`).join('\n')
|
|
1417
|
+
: ' // No rollback operations';
|
|
1418
|
+
return `import { MigrationInterface, QueryRunner, Table, TableCheck, TableColumn, TableExclusion, TableForeignKey, TableIndex, TableUnique } from 'typeorm';
|
|
1419
|
+
|
|
1420
|
+
export class ${options.className} implements MigrationInterface {
|
|
1421
|
+
async up(queryRunner: QueryRunner): Promise<void> {
|
|
1422
|
+
${upBody}
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
async down(queryRunner: QueryRunner): Promise<void> {
|
|
1426
|
+
${downBody}
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
`;
|
|
1430
|
+
}
|
|
1431
|
+
function patchInitMigration(tree, migrationPath, rendered) {
|
|
1432
|
+
const source = tree.read(migrationPath, 'utf-8');
|
|
1433
|
+
if (!source) {
|
|
1434
|
+
throw new Error(`Unable to read init migration file "${migrationPath}".`);
|
|
1435
|
+
}
|
|
1436
|
+
const upBody = rendered.upStatements
|
|
1437
|
+
.map((statement) => ` ${statement}`)
|
|
1438
|
+
.join('\n');
|
|
1439
|
+
const downBody = rendered.downStatements
|
|
1440
|
+
.map((statement) => ` ${statement}`)
|
|
1441
|
+
.join('\n');
|
|
1442
|
+
let updated = source;
|
|
1443
|
+
if (source.includes(UP_START_MARKER) && source.includes(UP_END_MARKER)) {
|
|
1444
|
+
updated = replaceBetweenMarkers(updated, UP_START_MARKER, UP_END_MARKER, upBody);
|
|
1445
|
+
}
|
|
1446
|
+
else {
|
|
1447
|
+
updated = injectAfterSchemaEnsure(updated, upBody);
|
|
1448
|
+
}
|
|
1449
|
+
if (source.includes(DOWN_START_MARKER) && source.includes(DOWN_END_MARKER)) {
|
|
1450
|
+
updated = replaceBetweenMarkers(updated, DOWN_START_MARKER, DOWN_END_MARKER, downBody);
|
|
1451
|
+
}
|
|
1452
|
+
else {
|
|
1453
|
+
updated = injectBeforeSchemaComment(updated, downBody);
|
|
1454
|
+
}
|
|
1455
|
+
tree.write(migrationPath, updated);
|
|
1456
|
+
}
|
|
1457
|
+
function replaceBetweenMarkers(source, startMarker, endMarker, body) {
|
|
1458
|
+
const startIndex = source.indexOf(startMarker);
|
|
1459
|
+
const endIndex = source.indexOf(endMarker);
|
|
1460
|
+
if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {
|
|
1461
|
+
throw new Error(`Unable to patch migration; missing marker pair ${startMarker} / ${endMarker}.`);
|
|
1462
|
+
}
|
|
1463
|
+
const insertionStart = startIndex + startMarker.length;
|
|
1464
|
+
return `${source.slice(0, insertionStart)}\n${body}\n${source.slice(endIndex)}`;
|
|
1465
|
+
}
|
|
1466
|
+
function injectAfterSchemaEnsure(source, body) {
|
|
1467
|
+
const pattern = /await\s+\w+\.createSchema\(SCHEMA,\s*true\);/;
|
|
1468
|
+
const match = source.match(pattern);
|
|
1469
|
+
if (!match || match.index === undefined) {
|
|
1470
|
+
throw new Error('Unable to patch init migration up() body. Add markers or include createSchema(SCHEMA, true).');
|
|
1471
|
+
}
|
|
1472
|
+
const insertionIndex = match.index + match[0].length;
|
|
1473
|
+
return `${source.slice(0, insertionIndex)}\n${body}${source.slice(insertionIndex)}`;
|
|
1474
|
+
}
|
|
1475
|
+
function injectBeforeSchemaComment(source, body) {
|
|
1476
|
+
const marker = '// Schema intentionally kept';
|
|
1477
|
+
const markerIndex = source.indexOf(marker);
|
|
1478
|
+
if (markerIndex === -1) {
|
|
1479
|
+
throw new Error('Unable to patch init migration down() body. Add markers or include "Schema intentionally kept" comment.');
|
|
1480
|
+
}
|
|
1481
|
+
return `${source.slice(0, markerIndex)}${body}\n ${source.slice(markerIndex)}`;
|
|
1482
|
+
}
|
|
1483
|
+
function renderTable(entity) {
|
|
1484
|
+
const parts = [];
|
|
1485
|
+
parts.push(`name: ${renderStringLiteral(entity.tableName)}`);
|
|
1486
|
+
if (entity.schema) {
|
|
1487
|
+
parts.push(`schema: ${renderStringLiteral(entity.schema)}`);
|
|
1488
|
+
}
|
|
1489
|
+
parts.push(`columns: [${entity.columns
|
|
1490
|
+
.map((column) => renderColumn(column))
|
|
1491
|
+
.join(', ')}]`);
|
|
1492
|
+
if (entity.uniques.length > 0) {
|
|
1493
|
+
parts.push(`uniques: [${entity.uniques
|
|
1494
|
+
.map((unique) => renderUnique(unique))
|
|
1495
|
+
.join(', ')}]`);
|
|
1496
|
+
}
|
|
1497
|
+
if (entity.indices.length > 0) {
|
|
1498
|
+
parts.push(`indices: [${entity.indices
|
|
1499
|
+
.map((index) => renderIndex(index))
|
|
1500
|
+
.join(', ')}]`);
|
|
1501
|
+
}
|
|
1502
|
+
if (entity.checks.length > 0) {
|
|
1503
|
+
parts.push(`checks: [${entity.checks.map((check) => renderCheck(check)).join(', ')}]`);
|
|
1504
|
+
}
|
|
1505
|
+
if (entity.exclusions.length > 0) {
|
|
1506
|
+
parts.push(`exclusions: [${entity.exclusions
|
|
1507
|
+
.map((exclusion) => renderExclusion(exclusion))
|
|
1508
|
+
.join(', ')}]`);
|
|
1509
|
+
}
|
|
1510
|
+
return `new Table({ ${parts.join(', ')} })`;
|
|
1511
|
+
}
|
|
1512
|
+
function renderColumn(column) {
|
|
1513
|
+
const parts = [
|
|
1514
|
+
`name: ${renderStringLiteral(column.name)}`,
|
|
1515
|
+
`type: ${renderStringLiteral(column.type)}`,
|
|
1516
|
+
`isPrimary: ${column.isPrimary ? 'true' : 'false'}`,
|
|
1517
|
+
`isGenerated: ${column.isGenerated ? 'true' : 'false'}`,
|
|
1518
|
+
`isNullable: ${column.isNullable ? 'true' : 'false'}`,
|
|
1519
|
+
`isUnique: ${column.isUnique ? 'true' : 'false'}`,
|
|
1520
|
+
`isArray: ${column.isArray ? 'true' : 'false'}`,
|
|
1521
|
+
];
|
|
1522
|
+
if (column.generationStrategy) {
|
|
1523
|
+
parts.push(`generationStrategy: ${renderStringLiteral(column.generationStrategy)}`);
|
|
1524
|
+
}
|
|
1525
|
+
if (column.length) {
|
|
1526
|
+
parts.push(`length: ${renderStringLiteral(column.length)}`);
|
|
1527
|
+
}
|
|
1528
|
+
if (typeof column.width === 'number') {
|
|
1529
|
+
parts.push(`width: ${column.width}`);
|
|
1530
|
+
}
|
|
1531
|
+
if (typeof column.precision === 'number') {
|
|
1532
|
+
parts.push(`precision: ${column.precision}`);
|
|
1533
|
+
}
|
|
1534
|
+
if (typeof column.scale === 'number') {
|
|
1535
|
+
parts.push(`scale: ${column.scale}`);
|
|
1536
|
+
}
|
|
1537
|
+
if (column.default) {
|
|
1538
|
+
parts.push(`default: ${column.default}`);
|
|
1539
|
+
}
|
|
1540
|
+
if (column.onUpdate) {
|
|
1541
|
+
parts.push(`onUpdate: ${renderStringLiteral(column.onUpdate)}`);
|
|
1542
|
+
}
|
|
1543
|
+
if (column.charset) {
|
|
1544
|
+
parts.push(`charset: ${renderStringLiteral(column.charset)}`);
|
|
1545
|
+
}
|
|
1546
|
+
if (column.collation) {
|
|
1547
|
+
parts.push(`collation: ${renderStringLiteral(column.collation)}`);
|
|
1548
|
+
}
|
|
1549
|
+
if (column.enum && column.enum.length > 0) {
|
|
1550
|
+
parts.push(`enum: [${column.enum
|
|
1551
|
+
.map((entry) => renderStringLiteral(entry))
|
|
1552
|
+
.join(', ')}]`);
|
|
1553
|
+
}
|
|
1554
|
+
if (column.enumName) {
|
|
1555
|
+
parts.push(`enumName: ${renderStringLiteral(column.enumName)}`);
|
|
1556
|
+
}
|
|
1557
|
+
if (column.primaryKeyConstraintName) {
|
|
1558
|
+
parts.push(`primaryKeyConstraintName: ${renderStringLiteral(column.primaryKeyConstraintName)}`);
|
|
1559
|
+
}
|
|
1560
|
+
if (column.comment) {
|
|
1561
|
+
parts.push(`comment: ${renderStringLiteral(column.comment)}`);
|
|
1562
|
+
}
|
|
1563
|
+
if (column.unsigned) {
|
|
1564
|
+
parts.push('unsigned: true');
|
|
1565
|
+
}
|
|
1566
|
+
if (column.zerofill) {
|
|
1567
|
+
parts.push('zerofill: true');
|
|
1568
|
+
}
|
|
1569
|
+
if (column.generatedType) {
|
|
1570
|
+
parts.push(`generatedType: ${renderStringLiteral(column.generatedType)}`);
|
|
1571
|
+
}
|
|
1572
|
+
if (column.asExpression) {
|
|
1573
|
+
parts.push(`asExpression: ${column.asExpression}`);
|
|
1574
|
+
}
|
|
1575
|
+
if (column.generatedIdentity) {
|
|
1576
|
+
parts.push(`generatedIdentity: ${renderStringLiteral(column.generatedIdentity)}`);
|
|
1577
|
+
}
|
|
1578
|
+
if (column.spatialFeatureType) {
|
|
1579
|
+
parts.push(`spatialFeatureType: ${renderStringLiteral(column.spatialFeatureType)}`);
|
|
1580
|
+
}
|
|
1581
|
+
if (typeof column.srid === 'number') {
|
|
1582
|
+
parts.push(`srid: ${column.srid}`);
|
|
1583
|
+
}
|
|
1584
|
+
return `new TableColumn({ ${parts.join(', ')} })`;
|
|
1585
|
+
}
|
|
1586
|
+
function renderUnique(unique) {
|
|
1587
|
+
const parts = [
|
|
1588
|
+
`name: ${renderStringLiteral(unique.name)}`,
|
|
1589
|
+
`columnNames: [${unique.columnNames
|
|
1590
|
+
.map((column) => renderStringLiteral(column))
|
|
1591
|
+
.join(', ')}]`,
|
|
1592
|
+
];
|
|
1593
|
+
if (unique.deferrable) {
|
|
1594
|
+
parts.push(`deferrable: ${renderStringLiteral(unique.deferrable)}`);
|
|
1595
|
+
}
|
|
1596
|
+
return `new TableUnique({ ${parts.join(', ')} })`;
|
|
1597
|
+
}
|
|
1598
|
+
function renderIndex(index) {
|
|
1599
|
+
const parts = [
|
|
1600
|
+
`name: ${renderStringLiteral(index.name)}`,
|
|
1601
|
+
`columnNames: [${index.columnNames
|
|
1602
|
+
.map((column) => renderStringLiteral(column))
|
|
1603
|
+
.join(', ')}]`,
|
|
1604
|
+
];
|
|
1605
|
+
if (index.isUnique) {
|
|
1606
|
+
parts.push('isUnique: true');
|
|
1607
|
+
}
|
|
1608
|
+
if (index.where) {
|
|
1609
|
+
parts.push(`where: ${renderStringLiteral(index.where)}`);
|
|
1610
|
+
}
|
|
1611
|
+
if (index.isSpatial) {
|
|
1612
|
+
parts.push('isSpatial: true');
|
|
1613
|
+
}
|
|
1614
|
+
if (index.isConcurrent) {
|
|
1615
|
+
parts.push('isConcurrent: true');
|
|
1616
|
+
}
|
|
1617
|
+
if (index.isFulltext) {
|
|
1618
|
+
parts.push('isFulltext: true');
|
|
1619
|
+
}
|
|
1620
|
+
if (index.parser) {
|
|
1621
|
+
parts.push(`parser: ${renderStringLiteral(index.parser)}`);
|
|
1622
|
+
}
|
|
1623
|
+
if (typeof index.synchronize === 'boolean') {
|
|
1624
|
+
parts.push(`synchronize: ${index.synchronize ? 'true' : 'false'}`);
|
|
1625
|
+
}
|
|
1626
|
+
return `new TableIndex({ ${parts.join(', ')} })`;
|
|
1627
|
+
}
|
|
1628
|
+
function renderCheck(check) {
|
|
1629
|
+
return `new TableCheck({ name: ${renderStringLiteral(check.name)}, expression: ${renderStringLiteral(check.expression)} })`;
|
|
1630
|
+
}
|
|
1631
|
+
function renderExclusion(exclusion) {
|
|
1632
|
+
return `new TableExclusion({ name: ${renderStringLiteral(exclusion.name)}, expression: ${renderStringLiteral(exclusion.expression)} })`;
|
|
1633
|
+
}
|
|
1634
|
+
function renderForeignKey(foreignKey) {
|
|
1635
|
+
const referencedTable = foreignKey.referencedTableKey.includes(':')
|
|
1636
|
+
? foreignKey.referencedTableKey.split(':')[1]
|
|
1637
|
+
: foreignKey.referencedTableKey;
|
|
1638
|
+
const [referencedSchema, referencedTableName] = referencedTable.includes('.')
|
|
1639
|
+
? referencedTable.split('.', 2)
|
|
1640
|
+
: [undefined, referencedTable];
|
|
1641
|
+
const parts = [
|
|
1642
|
+
`columnNames: [${foreignKey.columnNames
|
|
1643
|
+
.map((column) => renderStringLiteral(column))
|
|
1644
|
+
.join(', ')}]`,
|
|
1645
|
+
`referencedTableName: ${renderStringLiteral(referencedTableName)}`,
|
|
1646
|
+
`referencedColumnNames: [${foreignKey.referencedColumnNames
|
|
1647
|
+
.map((column) => renderStringLiteral(column))
|
|
1648
|
+
.join(', ')}]`,
|
|
1649
|
+
];
|
|
1650
|
+
if (foreignKey.name) {
|
|
1651
|
+
parts.push(`name: ${renderStringLiteral(foreignKey.name)}`);
|
|
1652
|
+
}
|
|
1653
|
+
if (referencedSchema) {
|
|
1654
|
+
parts.push(`referencedSchema: ${renderStringLiteral(referencedSchema)}`);
|
|
1655
|
+
}
|
|
1656
|
+
if (foreignKey.onDelete) {
|
|
1657
|
+
parts.push(`onDelete: ${renderStringLiteral(foreignKey.onDelete)}`);
|
|
1658
|
+
}
|
|
1659
|
+
if (foreignKey.onUpdate) {
|
|
1660
|
+
parts.push(`onUpdate: ${renderStringLiteral(foreignKey.onUpdate)}`);
|
|
1661
|
+
}
|
|
1662
|
+
if (foreignKey.deferrable) {
|
|
1663
|
+
parts.push(`deferrable: ${renderStringLiteral(foreignKey.deferrable)}`);
|
|
1664
|
+
}
|
|
1665
|
+
return `new TableForeignKey({ ${parts.join(', ')} })`;
|
|
1666
|
+
}
|
|
1667
|
+
function renderStringLiteral(value) {
|
|
1668
|
+
return JSON.stringify(value);
|
|
1669
|
+
}
|
|
1670
|
+
function tablePath(entity) {
|
|
1671
|
+
if (!entity.schema) {
|
|
1672
|
+
return entity.tableName;
|
|
1673
|
+
}
|
|
1674
|
+
return `${entity.schema}.${entity.tableName}`;
|
|
1675
|
+
}
|
|
1676
|
+
function tableKey(schema, tableName) {
|
|
1677
|
+
return `${schema ?? ''}:${tablePath({
|
|
1678
|
+
key: '',
|
|
1679
|
+
className: '',
|
|
1680
|
+
tableName,
|
|
1681
|
+
schema,
|
|
1682
|
+
columns: [],
|
|
1683
|
+
uniques: [],
|
|
1684
|
+
indices: [],
|
|
1685
|
+
checks: [],
|
|
1686
|
+
exclusions: [],
|
|
1687
|
+
foreignKeys: [],
|
|
1688
|
+
})}`;
|
|
1689
|
+
}
|
|
1690
|
+
function deepEqual(left, right) {
|
|
1691
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
1692
|
+
}
|
|
1693
|
+
function sha256(value) {
|
|
1694
|
+
return createHash('sha256').update(value).digest('hex');
|
|
1695
|
+
}
|