uql-codemod 0.52.1 → 0.54.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 +2 -1
- package/dist/generatedKeys.d.ts +5 -0
- package/dist/generatedKeys.js +79 -0
- package/dist/transform.js +4 -1
- package/dist/tsconfig.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ 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().
|
|
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
29
|
- 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
30
|
- `@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
31
|
- 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] }`.
|
|
@@ -39,6 +39,7 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
|
|
|
39
39
|
- 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
40
|
- 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
41
|
- 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`.
|
|
42
|
+
- 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
43
|
- The `[idKey]?: '...'` brand, and its import, on a key not called `id`, `_id` or `uuid` and on every composite.
|
|
43
44
|
|
|
44
45
|
## What it leaves to you
|
|
@@ -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
|
+
}
|
package/dist/transform.js
CHANGED
|
@@ -8,6 +8,7 @@ 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';
|
|
@@ -731,7 +732,9 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
|
|
|
731
732
|
const legacy = rewriteLegacy(source, checker, options, taken);
|
|
732
733
|
const located = (pass) => (at) => locationAt(source, pass.sourceOffset(at));
|
|
733
734
|
const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
|
|
734
|
-
const
|
|
735
|
+
const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
|
|
736
|
+
const { unresolved } = migrated;
|
|
737
|
+
const text = toGeneratedKeys(source.fileName, migrated.text);
|
|
735
738
|
return {
|
|
736
739
|
fileName: source.fileName,
|
|
737
740
|
text,
|
package/dist/tsconfig.js
CHANGED
|
@@ -25,7 +25,7 @@ export function checkTsconfig(fileName, text) {
|
|
|
25
25
|
const target = options && propertyValue(options, 'target');
|
|
26
26
|
if (target && ts.isStringLiteral(target) && target.text.toLowerCase() === 'esnext') {
|
|
27
27
|
unresolved.push(`${fileName}: 'target' is 'esnext', the one target that emits decorator syntax untransformed. ` +
|
|
28
|
-
'Change it to any dated target, such as `
|
|
28
|
+
'Change it to any dated target, such as `es2022`.');
|
|
29
29
|
}
|
|
30
30
|
// A value the file inherits cannot be edited here, and silence would read as "there was none".
|
|
31
31
|
if (propertyValue(root, 'extends') && !legacy.length) {
|