uql-codemod 0.53.0 → 0.55.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 CHANGED
@@ -25,13 +25,14 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
25
25
  ## What it rewrites
26
26
 
27
27
  - `virtual` to `computed` (on `@Field` and in `defineEntity`'s `fields`), a check's `expression` and a filter's `condition` to `where` (`@Entity`, `defineEntity`, `@Filter`), `raw('...')` to the `sql` tagged template, and a second argument onto `.as()`.
28
- - A column's options to its builder, last, after the rewrites above: `@Id()` and `@Field({ type: String, nullable: true, length: 80 })` to `@Field(f.number().id())` and `@Field(f.string().nullable().length(80))`, a NOT NULL column losing its `nullable: false`, `computed` to `@Computed((row) => f.string().as(...))` or `@Computed((row) => row.books.count())`, and a defined entity's `fields` likewise; its other options to the sections chained after it, and its `aggregates` to `.relations()`' second callback. A defined column's foreign key becomes a relation: its `references` is dropped where a relation joins on the column (by `(order) => order.customerId`, by `[{ local, foreign }]` pairs, or as the ORM infers the one column naming its target, written into it), its `onDelete` moved into that relation, and where none joins, a `manyToOne` named as the column less its `Id` is written for it: `customer: () => rel.manyToOne(Customer, { references: (order) => order.customerId })`. Then each index, check and trigger entry, in `@Entity` and `defineEntity`, goes to the helper its callback is handed: `(post, index) => [index([post.title], 'by_title')]`.
28
+ - A column's options to its builder, last, after the rewrites above: `@Id()` and `@Field({ type: String, nullable: true, length: 80 })` to `@Field(f.number().autoIncrement())` and `@Field(f.string().nullable().length(80))`, a NOT NULL column losing its `nullable: false`, `computed` to `@Computed((row) => f.string().as(...))` or `@Computed((row) => row.books.count())`, and a defined entity's `fields` likewise; its other options to the sections chained after it, and its `aggregates` to `.relations()`' second callback. A defined column's foreign key becomes a relation: its `references` is dropped where a relation joins on the column (by `(order) => order.customerId`, by `[{ local, foreign }]` pairs, or as the ORM infers the one column naming its target, written into it), its `onDelete` moved into that relation, and where none joins, a `manyToOne` named as the column less its `Id` is written for it: `customer: () => rel.manyToOne(Customer, { references: (order) => order.customerId })`. Then each index, check and trigger entry, in `@Entity` and `defineEntity`, goes to the helper its callback is handed: `(post, index) => [index([post.title], 'by_title')]`.
29
+ - A relation decorator's target first, as `defineEntity`'s `rel.*` take it: `@ManyToOne({ entity: () => User, references })` to `@ManyToOne(() => User, { references })`, and `@OneToMany({ entity: () => Post })` to `@OneToMany(() => Post)`, last, after the rewrites reading its options.
29
30
  - A migration's columns to the same methods: `table.string('email', { length: 80, nullable: true })` to `table.string('email').length(80).nullable()`, `.defaultValue()` to `.default()`, `.primaryKey()` to `.id()`, `.computed()` to `.as()`, and `.notNullable()` dropped.
30
31
  - `@Index`, `@Trigger` and `@Filter` into `@Entity`'s `indexes`, `triggers` and `filters`, each decorator's comments kept above its entry; a class with no `@Entity` becomes `@Entity({ abstract: true, ... })`, a base that is never a table.
31
32
  - Members named by string to callbacks: `mappedBy: 'author'` to `(post) => post.author`, and `include`, `references` and `@Entity`/`defineEntity`'s `indexes` and `hooks` likewise: `{ columns: (post) => [post.title] }`.
32
33
  - `references: (post) => post.authorId` on a to-one (`@ManyToOne`, `@OneToOne`, or in `defineEntity`) that names no foreign key, declaring `@Field({ references: () => User }) authorId` first on a decorated class that has no such column, typed as the key it points at.
33
34
  - A partial-index `where` string to `sql`, importing it, on entities and in the migration builder.
34
- - A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export type Post = InstanceType<typeof Post>`. The class is removed and a table it named kept as `table`; a field stating no `type` takes the one its property declares (`authorId?: number | null` is `f.number().nullable()`), each relation becomes `author: () => rel.manyToOne(User, { ... })`, a relation aggregate an aggregate field (`(post) => ({ total: () => post.comments.count() })`), a hook's method a function of the row (`this` read as the row), and the same class's `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are folded in.
35
+ - A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export interface Post extends InstanceType<typeof Post> {}`. The class is removed and a table it named kept as `table`; a field stating no `type` takes the one its property declares (`authorId?: number | null` is `f.number().nullable()`), each relation becomes `author: () => rel.manyToOne(User, { ... })`, a relation aggregate an aggregate field (`(post) => ({ total: () => post.comments.count() })`), a hook's method a function of the row (`this` read as the row), and the same class's `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are folded in.
35
36
  - A JSON index entry to the path read off the column's ref: `{ column: post.kind, jsonPath: { path: 'theme', type: Number } }` to `{ column: post.kind.theme, type: Number }`, and a `jsonArray`'s element type to `type: [String]`.
36
37
  - `col('cost')` to the ref it names, ``(product) => sql`${product.cost}` `` in a `computed` and `refs(Item).cost` in a statement, and `$lock: { wait: 'skip' }` to `{ $wait: 'skip' }`, or to `true` for `{}` and a `'block'` wait.
37
38
  - `$exclude` to a `$select` leaving its fields out: `$exclude: { password: true }` to `$select: { password: false }`, at every depth of `$populate`.
@@ -39,6 +40,7 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
39
40
  - An upsert's conflict keys to a query, `upsertOne(User, { email: true }, row)` to `upsertOne(User, { $conflict: { email: true } }, row)`, and its update, `{ update: X }` options or a fourth argument, to the query's `$update: X`, in `upsertOne`, `upsertMany` and a trigger's `upsertInto`; `const { id } = await upsertOne(...)` to `const id`.
40
41
  - Renamed exports, at the import and every use: `raw` to `sql`, `QueryWhereMap` to `QueryWhere`, `IndexColumnSchema` to `IndexEntry`, `IndexColumnModifiers` to `IndexEntryModifiers`, `RelationKeyMap` to `KeyMap`, `FilterCondition` to `FilterWhere`, `SqlMigrationModuleOptions` to `MigrationModuleOptions`, `buildSqlQuerierMigrationModule` to `buildMigrationModule`, `QueryDialect` to `SqlQueryDialect`, `EngineFeatures` to `DialectFeatures`, `KnownMigratorDialect` to `DialectName`, `QueryConflictPaths` to `QueryConflictKeys`, `D1Preparer`/`D1Database` to `D1Queryable`, and the removed driver classes to the one each extended: `PgDialect`/`NeonDialect`/`PgliteDialect` to `PostgresDialect`, `CrdbQuerier`/`NeonQuerier` to `PgQuerier`, `LibsqlQuerier`/`TursoQuerier` to `HranaQuerier`, `TursoLocalQuerier` to `SqliteQuerier` and `TursoDatabase` to `SqliteDatabase`, `MySql2Dialect` to `MySqlDialect`, `MongodbNativeDialect` to `MongoDialect`, `Sqlite3QuerierPool` to `SqliteQuerierPool`, the migration builder's `I`-prefixed types to the unprefixed name (`IColumnBuilder`/`IColumnFactory`, and `uql-orm/migrate`'s `ColumnBuilder`/`ColumnFactory`, to `TableColumnBuilder`/`TableColumnFactory`), moving the import to the entry that exports it; and `MongoQuerier`, `isMongoQuerier` and `MongoSchemaIntrospector` to `uql-orm/mongodb`.
41
42
  - Imports off `uql-orm/maria`, `uql-orm/mongo` and `uql-orm/bunSql` to `uql-orm/mariadb`, `uql-orm/mongodb` and `uql-orm/bun-sql`, and off `uql-orm/type`, `uql-orm/dialect`, `uql-orm/entity`, `uql-orm/querier` and `uql-orm/namingStrategy` to `uql-orm`.
43
+ - A sole numeric key to the generated one it was: `f.number().id()` to `f.number().autoIncrement()`, `f.bigint().id()` to `f.bigint().autoIncrement()`, and `.autoIncrement()` on `f.column('int').id()`. `.autoIncrement(false)` is dropped, a key no longer needing it, and a key a relation shares stays as it is. A class's `id!` stays too, which an insert then has to name until it is `id?` or listed in `[filledKey]`. On MongoDB, take `.autoIncrement()` off a numeric key: nothing generates one there. A subclass's `.autoIncrement()` on a column that is no key, its key inherited, stays and has to go by hand.
42
44
  - The `[idKey]?: '...'` brand, and its import, on a key not called `id`, `_id` or `uuid` and on every composite.
43
45
 
44
46
  ## What it leaves to you
@@ -63,7 +65,7 @@ Reported with what to do, never guessed:
63
65
  - A file that already names something the codemod would write (`sql`, `refs`, `idKey`, `f`, a renamed export): left unchanged and reported, since the new import would shadow it or be shadowed.
64
66
  - A property whose type maps to no column (`Json<T>`, a vector, a mixed union).
65
67
  - A column option it cannot write as a method: a `shape` a JSON column no longer takes, a migration column's options passed as a variable, or a flag such as `unique: isUnique` that no literal states.
66
- - A `@Field`/`@Id` with no `type`, and a relation with no `entity`: declare the column as a builder (`f.string()`) and name the target (`entity: () => Target`). A branded string id's column, `f.uuid()` or `f.string()`, is yours to pick.
68
+ - A `@Field`/`@Id` with no `type`, and a relation with no target: declare the column as a builder (`f.string()`) and pass the target first (`@ManyToOne(() => Target)`). A branded string id's column, `f.uuid()` or `f.string()`, is yours to pick.
67
69
  - `Relation<T>` imported from `uql-orm`, which no longer exports it: write the property's type without it, and drop the import.
68
70
 
69
71
  ## After it runs
@@ -263,7 +263,7 @@ function definedOf(name, cls, calls, entityCall, unit) {
263
263
  }
264
264
  const prefix = exported ? 'export ' : '';
265
265
  return {
266
- text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}type ${name} = InstanceType<typeof ${name}>;`,
266
+ text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}interface ${name} extends InstanceType<typeof ${name}> {}`,
267
267
  notes,
268
268
  };
269
269
  }
package/dist/edits.d.ts CHANGED
@@ -39,14 +39,15 @@ export declare function reparsedAgain(fileName: string, pass: Pass, edits: (sour
39
39
  */
40
40
  export declare function editedText(source: string, edits: readonly Edit[]): Pass;
41
41
  export declare function replaced(node: ts.Node, text: Replacement): Edit;
42
- export declare function inserted(node: ts.Node, text: string): Edit;
42
+ export declare function inserted(node: ts.Node, text: Replacement): Edit;
43
43
  export declare function appended(node: ts.Node, text: string): Edit;
44
44
  /** `node`'s text with each of `uses`, the nodes inside it, written as `text`. */
45
45
  export declare function replacingUses(node: ts.Node, uses: readonly ts.Node[], text: string): string;
46
46
  /**
47
47
  * Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
48
- * Each removed element takes the text up to the next item; the removed run at the end takes the separator before
49
- * it, so the ranges never overlap. `source` is passed because a tree from `ts.parseJsonText` has no `getStart()`.
48
+ * Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
49
+ * takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
50
+ * `ts.parseJsonText` has no `getStart()`.
50
51
  */
51
52
  export declare function removeFromList(items: readonly ts.Node[], removed: readonly ts.Node[], source: ts.SourceFile): readonly Edit[];
52
53
  /**
package/dist/edits.js CHANGED
@@ -92,15 +92,19 @@ export function replacingUses(node, uses, text) {
92
92
  }
93
93
  /**
94
94
  * Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
95
- * Each removed element takes the text up to the next item; the removed run at the end takes the separator before
96
- * it, so the ranges never overlap. `source` is passed because a tree from `ts.parseJsonText` has no `getStart()`.
95
+ * Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
96
+ * takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
97
+ * `ts.parseJsonText` has no `getStart()`.
97
98
  */
98
99
  export function removeFromList(items, removed, source) {
99
100
  const kept = items.map((item) => !removed.includes(item));
100
101
  const lastKept = kept.lastIndexOf(true);
102
+ const upTo = (item, next) => ts.getLeadingCommentRanges(source.text, next.pos)?.length
103
+ ? { start: item.pos, end: next.pos }
104
+ : { start: item.getStart(source), end: next.getStart(source) };
101
105
  const between = items
102
106
  .slice(0, lastKept + 1)
103
- .flatMap((item, at) => kept[at] ? [] : [{ start: item.getStart(source), end: items[at + 1].getStart(source), text: '' }]);
107
+ .flatMap((item, at) => (kept[at] ? [] : [{ ...upTo(item, items[at + 1]), text: '' }]));
104
108
  const trailing = items.slice(lastKept + 1);
105
109
  if (!trailing.length) {
106
110
  return between;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * States each generated key, which `.id()` no longer implies: a sole numeric key filled by nothing else and not
3
+ * shared with a row it references. Off the text the builders wrote, so it sees every column as one.
4
+ */
5
+ export declare function toGeneratedKeys(fileName: string, text: string): string;
@@ -0,0 +1,79 @@
1
+ import ts from 'typescript';
2
+ import { applyEdits } from './edits.js';
3
+ import { chainOf } from './syntax.js';
4
+ /** The columns a class's `@Field`s declare, by property. */
5
+ function classColumns(node) {
6
+ return node.members
7
+ .filter(ts.isPropertyDeclaration)
8
+ .flatMap((member) => (ts.getDecorators(member) ?? []).flatMap(({ expression }) => ts.isCallExpression(expression) && expression.expression.getText() === 'Field'
9
+ ? [{ name: member.name.getText(), column: expression.arguments[0] }]
10
+ : []));
11
+ }
12
+ /** The columns a `fields` object declares, by property. */
13
+ function fieldColumns(node) {
14
+ return node.properties
15
+ .filter(ts.isPropertyAssignment)
16
+ .map((property) => ({ name: property.name.getText(), column: property.initializer }));
17
+ }
18
+ /** The whole statement a `fields` object is in, whose chained `.relations()` may read its key. */
19
+ function statementOf(node) {
20
+ return ts.isStatement(node) || ts.isSourceFile(node.parent) ? node : statementOf(node.parent);
21
+ }
22
+ /** `method`, dot included, as `text`. */
23
+ function written({ receiver, call }, text) {
24
+ return { start: receiver.getEnd(), end: call.getEnd(), text };
25
+ }
26
+ /** The `.autoIncrement()` of a column no key, which generated nothing and would now make it one. */
27
+ function inertAutoIncrement(column) {
28
+ const { methods } = chainOf(column);
29
+ const inert = methods.find(({ name }) => name === 'autoIncrement');
30
+ return inert && !methods.some(({ name }) => name === 'id') ? [written(inert, '')] : [];
31
+ }
32
+ /** `.autoIncrement()` in place of `.id()` on the sole numeric key of `scope`, which the database no longer generates unasked. */
33
+ function stateKey(keys, scope) {
34
+ const ids = keys.filter(({ column }) => chainOf(column).methods.some(({ name }) => name === 'id'));
35
+ const inert = ids.length ? keys.flatMap(({ column }) => inertAutoIncrement(column)) : [];
36
+ if (ids.length !== 1)
37
+ return inert;
38
+ const [{ name: key, column }] = ids;
39
+ const { root, methods } = chainOf(column);
40
+ const names = methods.map(({ name }) => name);
41
+ const [type] = methods;
42
+ const numeric = ['number', 'bigint'].includes(type.name) ||
43
+ (type.name === 'column' && /\b(?:tiny|small|medium|big)?(?:int\d?|integer|serial)\b/i.test(type.call.getText()));
44
+ const shared = new RegExp(`references:\\s*\\(?\\w+\\)?\\s*=>\\s*\\w+\\.${key}\\b`).test(scope.getText());
45
+ const filled = ['references', 'onInsert', 'default'].some((method) => names.includes(method));
46
+ const declared = methods.some(({ name, call }) => name === 'autoIncrement' && call.arguments.length);
47
+ if (root.getText() !== 'f' || !numeric || filled || declared || shared)
48
+ return inert;
49
+ return [...inert, written(methods[names.indexOf('id')], names.includes('autoIncrement') ? '' : '.autoIncrement()')];
50
+ }
51
+ /**
52
+ * States each generated key, which `.id()` no longer implies: a sole numeric key filled by nothing else and not
53
+ * shared with a row it references. Off the text the builders wrote, so it sees every column as one.
54
+ */
55
+ export function toGeneratedKeys(fileName, text) {
56
+ if (!text.includes('.id()') && !text.includes('.autoIncrement(false)'))
57
+ return text;
58
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
59
+ const edits = [];
60
+ const visit = (node) => {
61
+ if (ts.isClassLike(node)) {
62
+ edits.push(...stateKey(classColumns(node), node));
63
+ }
64
+ if (ts.isPropertyAssignment(node) &&
65
+ node.name.getText() === 'fields' &&
66
+ ts.isObjectLiteralExpression(node.initializer)) {
67
+ edits.push(...stateKey(fieldColumns(node.initializer), statementOf(node)));
68
+ }
69
+ if (ts.isCallExpression(node) &&
70
+ ts.isPropertyAccessExpression(node.expression) &&
71
+ node.expression.name.text === 'autoIncrement' &&
72
+ node.arguments[0]?.getText() === 'false') {
73
+ edits.push({ start: node.expression.expression.getEnd(), end: node.getEnd(), text: '' });
74
+ }
75
+ ts.forEachChild(node, visit);
76
+ };
77
+ visit(source);
78
+ return applyEdits(text, edits);
79
+ }
@@ -0,0 +1,2 @@
1
+ /** Passes each relation decorator's target first, as `defineEntity`'s `rel.*` take it. Off the text the other passes wrote. */
2
+ export declare function toRelationTargets(fileName: string, text: string): string;
@@ -0,0 +1,31 @@
1
+ import ts from 'typescript';
2
+ import { applyEdits, inserted, original, removeFromList, replaced } from './edits.js';
3
+ import { decoratorName, namedProperty, RELATION_DECORATORS } from './syntax.js';
4
+ /** `@ManyToOne(() => User, { references })` from `@ManyToOne({ entity: () => User, references })`, the rest kept as written. */
5
+ function targetFirst(options) {
6
+ const entity = namedProperty(options, 'entity');
7
+ if (!entity)
8
+ return [];
9
+ const target = original(ts.isPropertyAssignment(entity) ? entity.initializer : entity.name);
10
+ if (options.properties.length === 1)
11
+ return [replaced(options, [target])];
12
+ return [inserted(options, [target, ', ']), ...removeFromList(options.properties, [entity], options.getSourceFile())];
13
+ }
14
+ /** Passes each relation decorator's target first, as `defineEntity`'s `rel.*` take it. Off the text the other passes wrote. */
15
+ export function toRelationTargets(fileName, text) {
16
+ if (!/@(?:OneToOne|ManyToOne|OneToMany|ManyToMany)\(\s*\{/.test(text))
17
+ return text;
18
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
19
+ const edits = [];
20
+ const visit = (node) => {
21
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression) && RELATION_DECORATORS.has(decoratorName(node))) {
22
+ const [options, ...rest] = node.expression.arguments;
23
+ if (options && !rest.length && ts.isObjectLiteralExpression(options)) {
24
+ edits.push(...targetFirst(options));
25
+ }
26
+ }
27
+ ts.forEachChild(node, visit);
28
+ };
29
+ visit(source);
30
+ return applyEdits(text, edits);
31
+ }
package/dist/syntax.d.ts CHANGED
@@ -74,6 +74,7 @@ export declare function decoratorsOf(node: ts.Node): readonly ts.Decorator[];
74
74
  export declare function decoratorName(node: ts.Decorator): string | undefined;
75
75
  /** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
76
76
  export declare const FIELD_DECORATORS: ReadonlySet<string | undefined>;
77
+ export declare const RELATION_DECORATORS: ReadonlySet<string | undefined>;
77
78
  /** Where the line holding offset `at` of `text` starts. */
78
79
  export declare function lineStartOf(text: string, at: number): number;
79
80
  /** The whitespace the line holding `node` starts with. */
package/dist/syntax.js CHANGED
@@ -183,6 +183,12 @@ export function decoratorName(node) {
183
183
  }
184
184
  /** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
185
185
  export const FIELD_DECORATORS = new Set(['Field', 'Id']);
186
+ export const RELATION_DECORATORS = new Set([
187
+ 'OneToOne',
188
+ 'ManyToOne',
189
+ 'OneToMany',
190
+ 'ManyToMany',
191
+ ]);
186
192
  /** Where the line holding offset `at` of `text` starts. */
187
193
  export function lineStartOf(text, at) {
188
194
  return text.lastIndexOf('\n', at - 1) + 1;
package/dist/transform.js CHANGED
@@ -8,14 +8,15 @@ import { nameClash } from './definedMessages.js';
8
8
  import { definerCall } from './definers.js';
9
9
  import { appended, editedText, followed, inserted, original, replaced, unedited, } from './edits.js';
10
10
  import { columnExpressions, handNamedColumns, sqlTag, sqlWhereEdit, templateOf } from './entitySql.js';
11
+ import { toGeneratedKeys } from './generatedKeys.js';
11
12
  import { clashingName, deadImportNames, foreignNames, LEGACY_SQL_TAG, reportRemovedExports, rewriteImports, SQL_TAG, sqlName, uqlExport, uqlImport, uqlImportDeclarations, } from './imports.js';
12
13
  import { rewriteBuilderIndexLengths, rewriteJsonIndexEntries } from './jsonIndex.js';
13
14
  import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByEdits, memberAccess, paramFor, quoted, referencesEdits, } from './keyMaps.js';
14
15
  import { toMigrationBuilders } from './migrationBuilders.js';
15
16
  import { relationTargetFor } from './relationTarget.js';
17
+ import { toRelationTargets } from './relationTargets.js';
16
18
  import { statementTemplate } from './statementSql.js';
17
- import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, } from './syntax.js';
18
- const RELATION_DECORATORS = new Set(['OneToOne', 'ManyToOne', 'OneToMany', 'ManyToMany']);
19
+ import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, } from './syntax.js';
19
20
  const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
20
21
  const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
21
22
  /**
@@ -633,24 +634,34 @@ function rewriteProperty(node, ctx) {
633
634
  renameSqlOption(options, 'virtual', 'computed', node, owner, ctx);
634
635
  }
635
636
  if (RELATION_DECORATORS.has(name)) {
636
- reportMissingOption(decorator, node, ctx, {
637
- option: 'entity',
638
- satisfiedBy: ['entity'],
639
- advice: 'name its target, `entity: () => Target`',
640
- });
641
- if (options.kind === 'literal') {
642
- const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
643
- rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
644
- }
645
- if (options.kind === 'literal' && TO_ONE_DECORATORS.has(name)) {
646
- addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
647
- }
637
+ rewriteRelation(decorator, name, node, owner, ctx);
648
638
  }
649
639
  }
650
640
  if (decorators.length) {
651
641
  dropDeclare(node, ctx);
652
642
  }
653
643
  }
644
+ /** A relation decorator holding its target as `entity`, which a later pass moves first; one passing it first is current. */
645
+ function rewriteRelation(decorator, name, node, owner, ctx) {
646
+ const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
647
+ if (first && isCallback(first)) {
648
+ return;
649
+ }
650
+ reportMissingOption(decorator, node, ctx, {
651
+ option: 'entity',
652
+ satisfiedBy: ['entity'],
653
+ advice: 'pass its target first, `@ManyToOne(() => Target)`',
654
+ });
655
+ const options = decoratorOptions(decorator);
656
+ if (options.kind !== 'literal') {
657
+ return;
658
+ }
659
+ const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
660
+ rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
661
+ if (TO_ONE_DECORATORS.has(name)) {
662
+ addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
663
+ }
664
+ }
654
665
  /** Whether a field decorator already declares its column with a builder, which states everything the rewrites add. */
655
666
  function writesBuilder(decorator) {
656
667
  const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
@@ -731,7 +742,9 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
731
742
  const legacy = rewriteLegacy(source, checker, options, taken);
732
743
  const located = (pass) => (at) => locationAt(source, pass.sourceOffset(at));
733
744
  const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
734
- const { text, unresolved } = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
745
+ const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
746
+ const { unresolved } = migrated;
747
+ const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, migrated.text));
735
748
  return {
736
749
  fileName: source.fileName,
737
750
  text,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "uql-codemod",
3
3
  "description": "Upgrade uql-orm across versions that introduce breaking changes",
4
4
  "license": "MIT",
5
- "version": "0.53.0",
5
+ "version": "0.55.0",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"