sequelize-typescript-generator 12.0.1 → 13.0.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/.github/workflows/ci.yml +175 -150
- package/.vscode/launch.json +212 -0
- package/.vscode/tasks.json +95 -0
- package/CHANGELOG.md +17 -0
- package/CLAUDE.md +13 -0
- package/CONTEXT.md +67 -0
- package/README.md +827 -199
- package/build/bin/cli.js +65 -47
- package/build/bin/utils.d.ts +5 -2
- package/build/bin/utils.js +87 -104
- package/build/builders/Builder.d.ts +2 -2
- package/build/builders/Builder.js +3 -5
- package/build/builders/ModelBuilder.d.ts +43 -8
- package/build/builders/ModelBuilder.js +120 -122
- package/build/builders/NativeModelRenderer.d.ts +98 -0
- package/build/builders/NativeModelRenderer.js +353 -0
- package/build/builders/associationNaming.d.ts +9 -0
- package/build/builders/associationNaming.js +15 -0
- package/build/builders/decoratorsDependency.d.ts +27 -0
- package/build/builders/decoratorsDependency.js +45 -0
- package/build/builders/defaultValues.d.ts +40 -0
- package/build/builders/defaultValues.js +56 -0
- package/build/builders/generatedFile.d.ts +23 -0
- package/build/builders/generatedFile.js +31 -0
- package/build/builders/index.d.ts +1 -1
- package/build/builders/index.js +1 -5
- package/build/builders/nativeAssociations.d.ts +109 -0
- package/build/builders/nativeAssociations.js +308 -0
- package/build/builders/nativeAttributes.d.ts +96 -0
- package/build/builders/nativeAttributes.js +174 -0
- package/build/builders/nativeWiring.d.ts +51 -0
- package/build/builders/nativeWiring.js +108 -0
- package/build/builders/utils.d.ts +75 -0
- package/build/builders/utils.js +142 -48
- package/build/config/IConfig.d.ts +11 -2
- package/build/config/IConfig.js +4 -6
- package/build/config/format.d.ts +27 -0
- package/build/config/format.js +26 -0
- package/build/config/index.d.ts +1 -1
- package/build/config/index.js +1 -2
- package/build/connection/createConnection.d.ts +8 -1
- package/build/connection/createConnection.js +30 -7
- package/build/connection/index.d.ts +1 -1
- package/build/connection/index.js +1 -17
- package/build/dialects/AssociationsParser.d.ts +10 -2
- package/build/dialects/AssociationsParser.js +16 -19
- package/build/dialects/Dialect.d.ts +52 -9
- package/build/dialects/Dialect.js +93 -57
- package/build/dialects/DialectMSSQL.d.ts +22 -3
- package/build/dialects/DialectMSSQL.js +169 -75
- package/build/dialects/DialectMariaDB.d.ts +13 -3
- package/build/dialects/DialectMariaDB.js +98 -79
- package/build/dialects/DialectMySQL.d.ts +13 -3
- package/build/dialects/DialectMySQL.js +101 -83
- package/build/dialects/DialectPostgres.d.ts +14 -3
- package/build/dialects/DialectPostgres.js +129 -75
- package/build/dialects/DialectSQLite.d.ts +41 -3
- package/build/dialects/DialectSQLite.js +166 -24
- package/build/dialects/associationDiscovery.d.ts +64 -0
- package/build/dialects/associationDiscovery.js +275 -0
- package/build/dialects/associationsFileMerge.d.ts +21 -0
- package/build/dialects/associationsFileMerge.js +107 -0
- package/build/dialects/createDialect.d.ts +8 -0
- package/build/dialects/createDialect.js +24 -0
- package/build/dialects/dataTypes.d.ts +58 -0
- package/build/dialects/dataTypes.js +108 -0
- package/build/dialects/foreignKeys.d.ts +115 -0
- package/build/dialects/foreignKeys.js +198 -0
- package/build/dialects/index.d.ts +5 -5
- package/build/dialects/index.js +5 -13
- package/build/dialects/paranoid.d.ts +24 -0
- package/build/dialects/paranoid.js +29 -0
- package/build/dialects/utils.d.ts +2 -8
- package/build/dialects/utils.js +61 -58
- package/build/index.d.ts +11 -3
- package/build/index.js +5 -19
- package/build/lint/Linter.d.ts +14 -3
- package/build/lint/Linter.js +114 -14
- package/build/lint/eslintDefaultConfig.d.ts +2 -2
- package/build/lint/eslintDefaultConfig.js +28 -23
- package/build/lint/index.d.ts +1 -1
- package/build/lint/index.js +1 -5
- package/build/utils/errors.d.ts +6 -0
- package/build/utils/errors.js +6 -0
- package/docker-compose.yml +65 -0
- package/docs/adr/0001-esm-only-package.md +36 -0
- package/docs/adr/0002-native-default-output-format.md +41 -0
- package/docs/agents/domain.md +51 -0
- package/docs/agents/issue-tracker.md +45 -0
- package/docs/agents/triage-labels.md +15 -0
- package/docs/migration/12-to-13.md +248 -0
- package/docs/plans/v13-phase5-association-discovery.md +168 -0
- package/docs/plans/v13-phase6-native-emitter.md +537 -0
- package/docs/plans/v13-upgrade-plan.md +137 -0
- package/jest.config.cjs +31 -0
- package/package.json +44 -27
- package/scripts/check-no-sequelize-typescript.cjs +68 -0
- package/tsconfig.json +4 -3
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
# Phase 6 (issue #80) implementation plan: native output format emitter
|
|
2
|
+
|
|
3
|
+
Status: planned, not started
|
|
4
|
+
Implements: #80 (phase 6 of docs/plans/v13-upgrade-plan.md)
|
|
5
|
+
Depends on: phase 4 (#78, done on v13)
|
|
6
|
+
Depends on: phase 5 (#79)
|
|
7
|
+
|
|
8
|
+
Branch `v13`.
|
|
9
|
+
|
|
10
|
+
## Conventions
|
|
11
|
+
|
|
12
|
+
This plan follows the project conventions in the repository's CLAUDE.md files: no `any`, no type assertions (`as`, `as unknown as T`, non-null `!`), `satisfies` for checked literals, and `unknown` only at untyped boundaries then narrowed with a guard; library types first (sequelize's `ModelAttributeColumnOptions`, `InitOptions`, `BelongsToOptions`, ...), derived second, custom last; comments in English describing the code as it is now (no history or "phase" markers); names like `calculateTotalRevenue`, booleans `is/has/should`, constants `UPPER_SNAKE_CASE`; the CONTEXT.md vocabulary (Format, Native format, Decorators format, Wiring file, Strict mode); TDD at pure seams; the TypeScript compiler API (`ts.factory`) only, never string templates, for code emission; one commit per step with `v13 phase N: ...` subjects, with a separate agent creating the commits.
|
|
13
|
+
|
|
14
|
+
## 0. Facts that shape the design
|
|
15
|
+
|
|
16
|
+
This plan was written against the phase 4 state of `v13`.
|
|
17
|
+
|
|
18
|
+
- `ModelBuilder.build()` already returns after `console.warn("Couldn't find any table ...")` before mkdir/clean/write, so the zero-tables rule (nothing emitted, one warning) already holds. It writes one file per table plus `index.ts`, lints `outDir/*.ts`; rendering is `private static buildTableClassDeclaration(tableMetadata, dialect, strict)` plus `buildIndexExports`.
|
|
19
|
+
- `src/builders/utils.ts` `generateObjectLiteralDecorator` decides identifier-vs-string by sniffing `propValue.startsWith('DataType.') || propValue.startsWith('Sequelize.')` and prints single-line object literals (trailing-space artifacts in the decorators golden come from the ESLint fixer breaking those). `generateNamedImports` uses the deprecated boolean `createImportClause` overload; TypeScript 6 non-deprecated signature is `createImportClause(phaseModifier: SyntaxKind.TypeKeyword | SyntaxKind.DeferKeyword | undefined, name, namedBindings)`.
|
|
20
|
+
- `src/dialects/dataTypes.ts` has `DATA_TYPE_NAMESPACES.native = 'DataTypes'` and `renderDataTypeExpression` returns a string. `IColumnMetadata.sequelizeType` carries key + args, so the native renderer builds a real `ts.Expression`.
|
|
21
|
+
- Default values are decorators-spelled strings: MySQL/MariaDB `defaultValuesMap` yields `'DataType.NOW'`/`'DataType.UUIDV4'`; Postgres wraps every default as `Sequelize.literal("...")`; MySQL binary defaults come back as numbers. Native renderer normalises these.
|
|
22
|
+
- `dialect.mapDbTypeToJs` already returns `string` for Postgres `int8`/`numeric`/`money`, `object` for JSON/geometry, `string` for MySQL enum (#63 satisfied).
|
|
23
|
+
- **Pre-existing bug blocking native runtime tests:** `DialectSQLite.ts` `fetchColumnsMetadata` sets `allowNull: !!column.notnull` (inverted). Decorators output never emits `allowNull: false`, so nobody noticed. Native emits `allowNull: false`, so creates would fail on SQLite. Fix: `allowNull: !column.notnull`; changes decorators golden.
|
|
24
|
+
- `IConfig` has `strict?: boolean`, no `format`. `Format` lives only in `src/tests/integration/formats.ts`. CLI `-R/--no-strict` sets `strict: !(!!argv['no-strict'])`; yargs parses `--no-strict` as `strict: false` so only `-R` works (known follow-up).
|
|
25
|
+
- `src/lint/eslintDefaultConfig.ts` is stylistic only, format-neutral. But `@stylistic/padded-blocks: { blocks: 'always' }` pads every block statement including function bodies; native has `initModel`/`initModels` bodies. Recommendation: `{ blocks: 'never', classes: 'always', switches: 'always' }` (decorators output has no block statements so its golden is unaffected; README config block must be updated).
|
|
26
|
+
- `compileGeneratedModels.ts` hardcodes `experimentalDecorators`, `emitDecoratorMetadata`, `useDefineForClassFields: false`. `jest.config.cjs` also sets `useDefineForClassFields: false`; `declare` fields are unaffected by either.
|
|
27
|
+
- `TestRunner.ts` is decorators-bound at: `import { Sequelize } from 'sequelize-typescript'` and every `new Sequelize(...)`; `await import(indexDir)` + `connection!.addModels([...Object.values(models)])` under `// @ts-ignore` (Build, Data Types, Associations blocks); `connection!.addModels([ outDir ])` after `fs.unlink(indexDir)` (Tables/Skip tables/Skip views blocks); `compileGeneratedModels(outDir)`; `ITestMetadata.ts` types connections with sequelize-typescript's `Sequelize`. Golden dir is already `golden/${format}`. Phase 5 adds text assertions (`units.ts` has no `onDelete`, `@ForeignKey(() => races)`) that must become format-conditional.
|
|
28
|
+
- Prototype `origin/prototype/native-format:src/prototype-native/emitterFactory.ts` + `shared.ts` give reusable structure (descriptor layer + factory renderer). Do not carry over its `!` assertions or `references` emission (#69 emits no `references`).
|
|
29
|
+
- Spec conflict: #69 lists column `unique`; #73 rules it out (`--indices` carries it). Follow #73: no `unique` on columns.
|
|
30
|
+
- Sequelize facts: `Model.init` requires every non-`ForeignKey`-branded key of `InferAttributes<M>` in the attributes object (so `createdAt`/`updatedAt` must appear in `init` when `--timestamps`); `include: [Model]` works when exactly one association targets that model; `belongsToMany` deletes the auto `id` on a PK-less through model. Mixin accessor names come from `as`: to-one uses `upperFirst(as)`, to-many uses `upperFirst(as)` for plural forms and `upperFirst(singular(as))` for singular forms (Sequelize uses `inflection`; we use `pluralize`; runtime assertion covers divergence).
|
|
31
|
+
|
|
32
|
+
## 1. Expected native output (SQLite golden config: `indices: true`, associations CSV, no case, no timestamps, after the allowNull fix, discovery on)
|
|
33
|
+
|
|
34
|
+
Formatting: printer output is single-line imports and multi-line object literals (native passes `multiLine = true`), then default ESLint re-indents with tabs, breaks imports with >= 3 specifiers as `import {\n\t... \n}` (trailing space after last specifier, like decorators golden), blank line between class members, padded class bodies, function bodies NOT padded. Indexed access types print with double quotes (`races["race_id"]`).
|
|
35
|
+
|
|
36
|
+
Member order per class: column attributes (metadata order), timestamp attributes, then per association its mixins, then one `NonAttribute` field per association, `declare static associations`, `static initModel`. Column option key order: `type, primaryKey, autoIncrement, allowNull, defaultValue, comment, field`. `allowNull` omitted on primary keys, explicit (`true`/`false`) on every other column. Init option key order: `sequelize, tableName, freezeTableName, schema, timestamps, paranoid, deletedAt, hasTrigger, comment, indexes`. Indexes whose field set equals the PK column set are skipped (MySQL `PRIMARY`, Postgres `*_pkey`, MSSQL `PK__*`, SQLite `sqlite_autoindex_*_1`).
|
|
37
|
+
|
|
38
|
+
### `units.ts`
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import {
|
|
42
|
+
Association, BelongsToCreateAssociationMixin, BelongsToGetAssociationMixin, BelongsToSetAssociationMixin, CreationOptional, DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model, NonAttribute, Sequelize
|
|
43
|
+
} from "sequelize";
|
|
44
|
+
import type { races } from "./races";
|
|
45
|
+
|
|
46
|
+
export class units extends Model<InferAttributes<units>, InferCreationAttributes<units>> {
|
|
47
|
+
|
|
48
|
+
declare unit_id: CreationOptional<number>;
|
|
49
|
+
|
|
50
|
+
declare unit_name: string;
|
|
51
|
+
|
|
52
|
+
declare race_id: ForeignKey<races["race_id"]>;
|
|
53
|
+
|
|
54
|
+
declare getRace: BelongsToGetAssociationMixin<races>;
|
|
55
|
+
|
|
56
|
+
declare setRace: BelongsToSetAssociationMixin<races, races["race_id"]>;
|
|
57
|
+
|
|
58
|
+
declare createRace: BelongsToCreateAssociationMixin<races>;
|
|
59
|
+
|
|
60
|
+
declare race?: NonAttribute<races>;
|
|
61
|
+
|
|
62
|
+
declare static associations: {
|
|
63
|
+
race: Association<units, races>;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
static initModel(sequelize: Sequelize): typeof units {
|
|
67
|
+
units.init({
|
|
68
|
+
unit_id: {
|
|
69
|
+
type: DataTypes.INTEGER,
|
|
70
|
+
primaryKey: true,
|
|
71
|
+
autoIncrement: true
|
|
72
|
+
},
|
|
73
|
+
unit_name: {
|
|
74
|
+
type: DataTypes.STRING,
|
|
75
|
+
allowNull: false
|
|
76
|
+
},
|
|
77
|
+
race_id: {
|
|
78
|
+
type: DataTypes.INTEGER,
|
|
79
|
+
allowNull: false
|
|
80
|
+
}
|
|
81
|
+
}, {
|
|
82
|
+
sequelize,
|
|
83
|
+
tableName: "units",
|
|
84
|
+
freezeTableName: true,
|
|
85
|
+
timestamps: false
|
|
86
|
+
});
|
|
87
|
+
return units;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`indices.ts` init options example (exercises `--indices`):
|
|
94
|
+
```ts
|
|
95
|
+
}, {
|
|
96
|
+
sequelize,
|
|
97
|
+
tableName: "indices",
|
|
98
|
+
freezeTableName: true,
|
|
99
|
+
timestamps: false,
|
|
100
|
+
indexes: [
|
|
101
|
+
{
|
|
102
|
+
name: "indices_f_unique_uindex",
|
|
103
|
+
unique: true,
|
|
104
|
+
fields: ["f_unique"]
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
name: "indices_f_multi_1_f_multi_2_uindex",
|
|
108
|
+
unique: true,
|
|
109
|
+
fields: ["f_multi_1", "f_multi_2"]
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
name: "indices_f_not_unique_index",
|
|
113
|
+
unique: false,
|
|
114
|
+
fields: ["f_not_unique"]
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
(`using` added when `IIndexMetadata.using` set; fields are database column names in `seq` order; index order is first-seen while scanning columns.)
|
|
120
|
+
|
|
121
|
+
### `races.ts` (HasMany from CSV, alias = plural of target)
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import {
|
|
125
|
+
Association, CreationOptional, DataTypes, HasManyAddAssociationMixin, HasManyAddAssociationsMixin, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin, HasManyHasAssociationsMixin, HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, HasManySetAssociationsMixin, InferAttributes, InferCreationAttributes, Model, NonAttribute, Sequelize
|
|
126
|
+
} from "sequelize";
|
|
127
|
+
import type { units } from "./units";
|
|
128
|
+
|
|
129
|
+
export class races extends Model<InferAttributes<races>, InferCreationAttributes<races>> {
|
|
130
|
+
|
|
131
|
+
declare race_id: CreationOptional<number>;
|
|
132
|
+
|
|
133
|
+
declare race_name: string;
|
|
134
|
+
|
|
135
|
+
declare getUnits: HasManyGetAssociationsMixin<units>;
|
|
136
|
+
|
|
137
|
+
declare setUnits: HasManySetAssociationsMixin<units, units["unit_id"]>;
|
|
138
|
+
|
|
139
|
+
declare addUnit: HasManyAddAssociationMixin<units, units["unit_id"]>;
|
|
140
|
+
|
|
141
|
+
declare addUnits: HasManyAddAssociationsMixin<units, units["unit_id"]>;
|
|
142
|
+
|
|
143
|
+
declare removeUnit: HasManyRemoveAssociationMixin<units, units["unit_id"]>;
|
|
144
|
+
|
|
145
|
+
declare removeUnits: HasManyRemoveAssociationsMixin<units, units["unit_id"]>;
|
|
146
|
+
|
|
147
|
+
declare hasUnit: HasManyHasAssociationMixin<units, units["unit_id"]>;
|
|
148
|
+
|
|
149
|
+
declare hasUnits: HasManyHasAssociationsMixin<units, units["unit_id"]>;
|
|
150
|
+
|
|
151
|
+
declare countUnits: HasManyCountAssociationsMixin;
|
|
152
|
+
|
|
153
|
+
declare createUnit: HasManyCreateAssociationMixin<units, "race_id">;
|
|
154
|
+
|
|
155
|
+
declare units?: NonAttribute<units[]>;
|
|
156
|
+
|
|
157
|
+
declare static associations: {
|
|
158
|
+
units: Association<races, units>;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
static initModel(sequelize: Sequelize): typeof races {
|
|
162
|
+
races.init({
|
|
163
|
+
race_id: {
|
|
164
|
+
type: DataTypes.INTEGER,
|
|
165
|
+
primaryKey: true,
|
|
166
|
+
autoIncrement: true
|
|
167
|
+
},
|
|
168
|
+
race_name: {
|
|
169
|
+
type: DataTypes.STRING,
|
|
170
|
+
allowNull: false
|
|
171
|
+
}
|
|
172
|
+
}, {
|
|
173
|
+
sequelize,
|
|
174
|
+
tableName: "races",
|
|
175
|
+
freezeTableName: true,
|
|
176
|
+
timestamps: false
|
|
177
|
+
});
|
|
178
|
+
return races;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### `employees.ts` (self-ref BelongsTo `manager` + HasMany `managerEmployees`; no model import)
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import {
|
|
188
|
+
Association, BelongsToCreateAssociationMixin, BelongsToGetAssociationMixin, BelongsToSetAssociationMixin, CreationOptional, DataTypes, ForeignKey, HasManyAddAssociationMixin, HasManyAddAssociationsMixin, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin, HasManyHasAssociationsMixin, HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, HasManySetAssociationsMixin, InferAttributes, InferCreationAttributes, Model, NonAttribute, Sequelize
|
|
189
|
+
} from "sequelize";
|
|
190
|
+
|
|
191
|
+
export class employees extends Model<InferAttributes<employees>, InferCreationAttributes<employees>> {
|
|
192
|
+
|
|
193
|
+
declare employee_id: CreationOptional<number>;
|
|
194
|
+
|
|
195
|
+
declare name: string;
|
|
196
|
+
|
|
197
|
+
declare manager_id: ForeignKey<employees["employee_id"] | null>;
|
|
198
|
+
|
|
199
|
+
declare getManager: BelongsToGetAssociationMixin<employees>;
|
|
200
|
+
|
|
201
|
+
declare setManager: BelongsToSetAssociationMixin<employees, employees["employee_id"]>;
|
|
202
|
+
|
|
203
|
+
declare createManager: BelongsToCreateAssociationMixin<employees>;
|
|
204
|
+
|
|
205
|
+
declare getManagerEmployees: HasManyGetAssociationsMixin<employees>;
|
|
206
|
+
|
|
207
|
+
declare setManagerEmployees: HasManySetAssociationsMixin<employees, employees["employee_id"]>;
|
|
208
|
+
|
|
209
|
+
declare addManagerEmployee: HasManyAddAssociationMixin<employees, employees["employee_id"]>;
|
|
210
|
+
|
|
211
|
+
declare addManagerEmployees: HasManyAddAssociationsMixin<employees, employees["employee_id"]>;
|
|
212
|
+
|
|
213
|
+
declare removeManagerEmployee: HasManyRemoveAssociationMixin<employees, employees["employee_id"]>;
|
|
214
|
+
|
|
215
|
+
declare removeManagerEmployees: HasManyRemoveAssociationsMixin<employees, employees["employee_id"]>;
|
|
216
|
+
|
|
217
|
+
declare hasManagerEmployee: HasManyHasAssociationMixin<employees, employees["employee_id"]>;
|
|
218
|
+
|
|
219
|
+
declare hasManagerEmployees: HasManyHasAssociationsMixin<employees, employees["employee_id"]>;
|
|
220
|
+
|
|
221
|
+
declare countManagerEmployees: HasManyCountAssociationsMixin;
|
|
222
|
+
|
|
223
|
+
declare createManagerEmployee: HasManyCreateAssociationMixin<employees, "manager_id">;
|
|
224
|
+
|
|
225
|
+
declare manager?: NonAttribute<employees>;
|
|
226
|
+
|
|
227
|
+
declare managerEmployees?: NonAttribute<employees[]>;
|
|
228
|
+
|
|
229
|
+
declare static associations: {
|
|
230
|
+
manager: Association<employees, employees>;
|
|
231
|
+
managerEmployees: Association<employees, employees>;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
static initModel(sequelize: Sequelize): typeof employees {
|
|
235
|
+
employees.init({
|
|
236
|
+
employee_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
|
237
|
+
name: { type: DataTypes.STRING, allowNull: false },
|
|
238
|
+
manager_id: { type: DataTypes.INTEGER, allowNull: true }
|
|
239
|
+
}, {
|
|
240
|
+
sequelize,
|
|
241
|
+
tableName: "employees",
|
|
242
|
+
freezeTableName: true,
|
|
243
|
+
timestamps: false
|
|
244
|
+
});
|
|
245
|
+
return employees;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
(object literals shown compact here; actual output is multi-line as in units.ts)
|
|
251
|
+
|
|
252
|
+
### `profiles.ts` (unique FK -> person; unique autoindex kept under `--indices`, PK autoindex skipped)
|
|
253
|
+
|
|
254
|
+
Imports Association, BelongsTo* mixins, CreationOptional, DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model, NonAttribute, Sequelize; `import type { person } from "./person";`. Members: `declare profile_id: CreationOptional<number>; declare person_id: ForeignKey<person["person_id"]>; getPerson/setPerson/createPerson mixins; declare person?: NonAttribute<person>; declare static associations: { person: Association<profiles, person>; }`. Init options include `indexes: [{ name: "sqlite_autoindex_profiles_2", unique: true, fields: ["person_id"] }]`.
|
|
255
|
+
|
|
256
|
+
`person.ts` gains `declare profile?: NonAttribute<profiles>` plus HasOne mixins (`getProfile`, `setProfile`, `createProfile`) alongside the CSV `passport` HasOne, and `import type` for both.
|
|
257
|
+
|
|
258
|
+
### `authors_books.ts` (junction; both columns branded, no associations on the junction itself)
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
import {
|
|
262
|
+
DataTypes, ForeignKey, InferAttributes, InferCreationAttributes, Model, Sequelize
|
|
263
|
+
} from "sequelize";
|
|
264
|
+
import type { authors } from "./authors";
|
|
265
|
+
import type { books } from "./books";
|
|
266
|
+
|
|
267
|
+
export class authors_books extends Model<InferAttributes<authors_books>, InferCreationAttributes<authors_books>> {
|
|
268
|
+
|
|
269
|
+
declare author_id: ForeignKey<authors["author_id"]>;
|
|
270
|
+
|
|
271
|
+
declare book_id: ForeignKey<books["book_id"]>;
|
|
272
|
+
|
|
273
|
+
static initModel(sequelize: Sequelize): typeof authors_books {
|
|
274
|
+
authors_books.init({
|
|
275
|
+
author_id: { type: DataTypes.INTEGER, allowNull: false },
|
|
276
|
+
book_id: { type: DataTypes.INTEGER, allowNull: false }
|
|
277
|
+
}, {
|
|
278
|
+
sequelize,
|
|
279
|
+
tableName: "authors_books",
|
|
280
|
+
freezeTableName: true,
|
|
281
|
+
timestamps: false
|
|
282
|
+
});
|
|
283
|
+
return authors_books;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
`authors.ts` carries the ten `BelongsToMany*` mixins for alias `books` (`getBooks`, `setBooks`, `addBook`, `addBooks`, `removeBook`, `removeBooks`, `hasBook`, `hasBooks`, `countBooks`, `createBook: BelongsToManyCreateAssociationMixin<books>`), `declare books?: NonAttribute<books[]>`, `books: Association<authors, books>`, and `import type` of `books` only (junction referenced only in the wiring file).
|
|
289
|
+
|
|
290
|
+
### `data_types.ts` (every non-PK column nullable -> `T | null`; autoincrement PK -> `CreationOptional`)
|
|
291
|
+
|
|
292
|
+
`declare id: CreationOptional<number>; declare f_int: number | null; ... declare f_varchar: string | null; ... declare f_blob: Uint8Array | null;` and init entries `f_int: { type: DataTypes.INTEGER, allowNull: true }` etc. with the same `DataTypes.X` as the decorators golden.
|
|
293
|
+
|
|
294
|
+
Typing rules: base type from `dialect.mapDbTypeToJs(col.type)` mapped to a type node (`number`, `string`, `boolean`, `Date`, `Uint8Array`, `object`); unknown mapping -> `unknown` plus existing `warnUnknownMappingForDataType`. ENUM: when `sequelizeType.key === 'ENUM'` with args, attribute type is the string-literal union `"AA" | "BB"` paired with `DataTypes.ENUM("AA", "BB")`; otherwise `string`. JSON/JSONB, GEOMETRY/GEOGRAPHY: `object`. Nullable + default -> `CreationOptional<T | null>`. Defaults: MySQL `CURRENT_TIMESTAMP` -> `defaultValue: DataTypes.NOW`, `uuid()` -> `DataTypes.UUIDV4`, Postgres default -> `Sequelize.literal("...")`, numbers bare, other strings quoted.
|
|
295
|
+
|
|
296
|
+
### `soft_deletes.ts` with `--paranoid --timestamps` (unit test + paranoid integration block; not in golden)
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
export class soft_deletes extends Model<InferAttributes<soft_deletes>, InferCreationAttributes<soft_deletes>> {
|
|
300
|
+
|
|
301
|
+
declare id: CreationOptional<number>;
|
|
302
|
+
|
|
303
|
+
declare name: string;
|
|
304
|
+
|
|
305
|
+
declare deleted_at: CreationOptional<Date | null>;
|
|
306
|
+
|
|
307
|
+
declare createdAt: CreationOptional<Date>;
|
|
308
|
+
|
|
309
|
+
declare updatedAt: CreationOptional<Date>;
|
|
310
|
+
|
|
311
|
+
static initModel(sequelize: Sequelize): typeof soft_deletes {
|
|
312
|
+
soft_deletes.init({
|
|
313
|
+
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
|
314
|
+
name: { type: DataTypes.STRING, allowNull: false },
|
|
315
|
+
deleted_at: { type: DataTypes.DECIMAL, allowNull: true },
|
|
316
|
+
createdAt: DataTypes.DATE,
|
|
317
|
+
updatedAt: DataTypes.DATE
|
|
318
|
+
}, {
|
|
319
|
+
sequelize,
|
|
320
|
+
tableName: "soft_deletes",
|
|
321
|
+
freezeTableName: true,
|
|
322
|
+
timestamps: true,
|
|
323
|
+
paranoid: true,
|
|
324
|
+
deletedAt: "deleted_at"
|
|
325
|
+
});
|
|
326
|
+
return soft_deletes;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
}
|
|
330
|
+
```
|
|
331
|
+
Decisions: paranoid column typed `CreationOptional<Date | null>` regardless of dialect JS mapping; its `type` stays the dialect mapping. `createdAt`/`updatedAt` declared `CreationOptional<Date>` and listed in `init` with `DataTypes.DATE` shorthand (Model.init requires every non-FK attribute key); no `field`. Without `--timestamps`: `timestamps: false`. Under `--case CAMEL`: `declare deletedAt` with `field: "deleted_at"` and option `deletedAt: "deletedAt"`. Note: if the phase 4 paranoid step added created_at/updated_at columns to the soft_deletes fixture, check how the timestamps test maps them and adapt (physical created_at columns stay plain attributes per #69; Sequelize's own createdAt/updatedAt attributes are separate unless `--case` maps them — verify against the existing timestamps integration test).
|
|
332
|
+
|
|
333
|
+
### `initModels.ts` (tables in `tablesMetadata` key order; wiring in table order then association order)
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import { Sequelize } from "sequelize";
|
|
337
|
+
import { data_types } from "./data_types";
|
|
338
|
+
// ... one value import per model ...
|
|
339
|
+
|
|
340
|
+
export function initModels(sequelize: Sequelize) {
|
|
341
|
+
data_types.initModel(sequelize);
|
|
342
|
+
// ... every model ...
|
|
343
|
+
authors.belongsToMany(books, {
|
|
344
|
+
as: "books",
|
|
345
|
+
through: authors_books,
|
|
346
|
+
foreignKey: "author_id",
|
|
347
|
+
otherKey: "book_id"
|
|
348
|
+
});
|
|
349
|
+
books.belongsToMany(authors, { as: "authors", through: authors_books, foreignKey: "book_id", otherKey: "author_id" });
|
|
350
|
+
races.hasMany(units, { as: "units", foreignKey: "race_id", sourceKey: "race_id" });
|
|
351
|
+
units.belongsTo(races, { as: "race", foreignKey: "race_id", targetKey: "race_id" });
|
|
352
|
+
person.hasOne(passport, { as: "passport", foreignKey: "passport_id", sourceKey: "passport_id" });
|
|
353
|
+
person.hasOne(profiles, { as: "profile", foreignKey: "person_id", sourceKey: "person_id", onDelete: "CASCADE", onUpdate: "CASCADE" });
|
|
354
|
+
passport.belongsTo(person, { as: "person", foreignKey: "passport_id" });
|
|
355
|
+
employees.belongsTo(employees, { as: "manager", foreignKey: "manager_id", targetKey: "employee_id", onDelete: "SET NULL" });
|
|
356
|
+
employees.hasMany(employees, { as: "managerEmployees", foreignKey: "manager_id", sourceKey: "employee_id", onDelete: "SET NULL" });
|
|
357
|
+
profiles.belongsTo(person, { as: "person", foreignKey: "person_id", targetKey: "person_id", onDelete: "CASCADE", onUpdate: "CASCADE" });
|
|
358
|
+
return {
|
|
359
|
+
data_types,
|
|
360
|
+
// ... every model ...
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export type Models = ReturnType<typeof initModels>;
|
|
365
|
+
```
|
|
366
|
+
(object literals multi-line in real output)
|
|
367
|
+
|
|
368
|
+
Wiring decisions:
|
|
369
|
+
- Associations wired in `initModels`, never in `initModel` (#69: wiring file holds behaviour; model files stay free of value imports of other models).
|
|
370
|
+
- `as` always emitted; alias = `resolveAssociationPropertyName(association)` from phase 5 (discovered alias, else plural/singular of target). It keys `associations`, the `NonAttribute` property and mixin names.
|
|
371
|
+
- `foreignKey` always emitted. Discovered: `association.foreignKey`. CSV (no `foreignKey` on record): BelongsTo -> source table column whose `foreignKey.targetModel` equals the target; HasOne/HasMany -> target table column whose `foreignKey.targetModel` equals the source.
|
|
372
|
+
- `targetKey`/`sourceKey` when known (`association.targetKey`, else `column.foreignKey.targetKey`; `association.sourceKey`). `passport.belongsTo(person)` has neither, so omitted.
|
|
373
|
+
- `onDelete`/`onUpdate` only when present on the association.
|
|
374
|
+
- `belongsToMany`: `through` is the junction class identifier (value import in wiring file only); `foreignKey`/`otherKey` resolved from the junction's column `foreignKey.targetModel` records; omitted when unresolvable.
|
|
375
|
+
- Option key order: `as, through, foreignKey, otherKey, targetKey, sourceKey, onDelete, onUpdate`.
|
|
376
|
+
- `initModels` has no explicit return type: `Models = ReturnType<typeof initModels>`.
|
|
377
|
+
- `declare static associations: { race: Association<units, races> }` uses base `Association<S, T>`.
|
|
378
|
+
- Mixin `TModelPrimaryKey` arg is `Target["<pk attribute>"]` when target has exactly one PK column, else `number`; `HasManyCreateAssociationMixin<Target, "<fk attribute>">`, `HasOneCreateAssociationMixin<Target>`, `BelongsToCreateAssociationMixin<Target>`.
|
|
379
|
+
- Cross-model references in model files are `import type`; self-references import nothing. Extensionless specifiers.
|
|
380
|
+
- Excluded FK targets: column typed plain, no brand/association/import. Lookup by model **name** (post-case): build `Map<modelName, ITableMetadata>` once.
|
|
381
|
+
|
|
382
|
+
### `index.ts`
|
|
383
|
+
`export * from "./<model>";` per model, then `export * from "./initModels";` (reuse `generateIndexExport`).
|
|
384
|
+
|
|
385
|
+
## 2. Module layout and pure functions
|
|
386
|
+
|
|
387
|
+
### `src/config/IConfig.ts`
|
|
388
|
+
```ts
|
|
389
|
+
export const FORMATS = ['native', 'decorators'] as const;
|
|
390
|
+
export type Format = typeof FORMATS[number];
|
|
391
|
+
export const DEFAULT_FORMAT: Format = 'native';
|
|
392
|
+
export const isFormat = (value: unknown): value is Format => typeof value === 'string' && FORMATS.some(format => format === value);
|
|
393
|
+
export interface IConfig { connection; metadata?; output; lintOptions?; format?: Format; /* undefined means native */ strict?: boolean; /* decorators only; ignored with a notice in native */ }
|
|
394
|
+
```
|
|
395
|
+
### `src/config/format.ts`
|
|
396
|
+
```ts
|
|
397
|
+
export const resolveFormat = (config: IConfig): Format => config.format ?? DEFAULT_FORMAT;
|
|
398
|
+
export const shouldNoticeIgnoredStrict = (config: IConfig): boolean => resolveFormat(config) === 'native' && config.strict === false;
|
|
399
|
+
export const STRICT_IGNORED_NOTICE = 'Notice: strict mode applies to the decorators format only and is ignored with --format native, where attributes are typed with InferAttributes.';
|
|
400
|
+
```
|
|
401
|
+
### `src/builders/utils.ts` additions
|
|
402
|
+
```ts
|
|
403
|
+
export type PropertyValue = string | number | boolean | ts.Expression | PropertyValue[] | { [key: string]: PropertyValue };
|
|
404
|
+
export const isTsExpression = (value: unknown): value is ts.Expression => typeof value === 'object' && value !== null && 'kind' in value && ts.isExpression(value);
|
|
405
|
+
export const createPropertyValueExpression = (value: PropertyValue, isMultiLine: boolean): ts.Expression;
|
|
406
|
+
export const buildObjectLiteralExpression = (props: { [key: string]: PropertyValue }, isMultiLine: boolean): ts.ObjectLiteralExpression;
|
|
407
|
+
export const createTypeNodeFromName = (jsType: string): ts.TypeNode; // number|string|boolean keywords, Date/Uint8Array refs, object keyword, else unknown
|
|
408
|
+
export const createNullableTypeNode = (type: ts.TypeNode): ts.TypeNode;
|
|
409
|
+
export const createGenericTypeReference = (name: string, args: ts.TypeNode[]): ts.TypeNode;
|
|
410
|
+
export const createIndexedAccessTypeNode = (modelName: string, attribute: string): ts.TypeNode; // races["race_id"]
|
|
411
|
+
export const generateTypeOnlyImport = (importsSpecifier: string[], moduleSpecifier: string): ts.ImportDeclaration; // createImportClause(ts.SyntaxKind.TypeKeyword, ...)
|
|
412
|
+
export const buildDataTypeExpression = (dataType: ISequelizeDataType, namespace: DataTypeNamespace): ts.Expression;
|
|
413
|
+
```
|
|
414
|
+
`generateObjectLiteralDecorator(decoratorIdentifier, props)` becomes a wrapper mapping values through `resolveDecoratorPropertyValue(value)` (the `DataType.`/`Sequelize.` sniff kept only for decorators) then `buildObjectLiteralExpression(mapped, false)`. Native never passes strings for `type`/`defaultValue`. `generateNamedImports` moves to `createImportClause(undefined, ...)`. Unit test: `nodeToString(buildDataTypeExpression(t, 'DataTypes'))` vs `renderDataTypeExpression` modulo `, ` spacing (native uses printer spacing `DataTypes.DECIMAL(7, 2)`).
|
|
415
|
+
|
|
416
|
+
### `src/builders/defaultValues.ts`
|
|
417
|
+
```ts
|
|
418
|
+
export type DefaultValueDescriptor = { kind: 'dataTypeMember'; member: string } | { kind: 'sqlLiteral'; sql: string } | { kind: 'number'; value: number } | { kind: 'boolean'; value: boolean } | { kind: 'string'; value: string };
|
|
419
|
+
export const parseDefaultValue = (raw: unknown): DefaultValueDescriptor | undefined;
|
|
420
|
+
export const buildDefaultValueExpression = (descriptor: DefaultValueDescriptor, namespace: DataTypeNamespace): ts.Expression;
|
|
421
|
+
```
|
|
422
|
+
### `src/builders/nativeAttributes.ts`
|
|
423
|
+
```ts
|
|
424
|
+
export const ATTRIBUTE_KINDS = ['plain', 'nullable', 'creationOptional', 'creationOptionalNullable', 'foreignKey', 'foreignKeyNullable'] as const;
|
|
425
|
+
export type AttributeKind = typeof ATTRIBUTE_KINDS[number];
|
|
426
|
+
export const isParanoidColumn = (column, table): boolean; // table.paranoid && table.deletedAt === column.name
|
|
427
|
+
export const isCreationOptionalColumn = (column, table): boolean; // autoIncrement || defaultValue !== undefined || isParanoidColumn
|
|
428
|
+
export const classifyAttribute = (column, table, isForeignKeyTargetGenerated: boolean): AttributeKind;
|
|
429
|
+
export const resolvePrimaryKeyAttribute = (table): string | undefined; // exactly one primaryKey column
|
|
430
|
+
export const indexTablesByModelName = (tablesMetadata): ReadonlyMap<string, ITableMetadata>;
|
|
431
|
+
export const resolveForeignKeyTargetAttribute = (foreignKey: IColumnForeignKeyMetadata, target: ITableMetadata): string | undefined; // targetKey ?? single PK
|
|
432
|
+
export interface INativeIndex { name: string; isUnique: boolean; fields: string[]; using?: IndexMethod }
|
|
433
|
+
export const isPrimaryKeyIndex = (fields: readonly string[], primaryKeyColumns: readonly string[]): boolean;
|
|
434
|
+
export const collectTableIndexes = (table): INativeIndex[];
|
|
435
|
+
export const COLUMN_OPTION_KEYS = ['type', 'primaryKey', 'autoIncrement', 'allowNull', 'defaultValue', 'comment', 'field'] as const satisfies readonly (keyof ModelAttributeColumnOptions)[];
|
|
436
|
+
export const INIT_OPTION_KEYS = ['sequelize', 'tableName', 'freezeTableName', 'schema', 'timestamps', 'paranoid', 'deletedAt', 'hasTrigger', 'comment', 'indexes'] as const satisfies readonly (keyof InitOptions)[];
|
|
437
|
+
export const TIMESTAMP_ATTRIBUTES = ['createdAt', 'updatedAt'] as const;
|
|
438
|
+
```
|
|
439
|
+
### `src/builders/nativeAssociations.ts`
|
|
440
|
+
```ts
|
|
441
|
+
export const ASSOCIATION_METHODS = { HasOne: 'hasOne', HasMany: 'hasMany', BelongsTo: 'belongsTo', BelongsToMany: 'belongsToMany' } as const satisfies Record<IAssociationMetadata['associationName'], keyof typeof Model>;
|
|
442
|
+
export type AssociationWiringOptions = Partial<Pick<BelongsToOptions, 'as' | 'foreignKey' | 'targetKey' | 'onDelete' | 'onUpdate'>> & Partial<Pick<HasManyOptions, 'sourceKey'>> & Partial<Pick<BelongsToManyOptions, 'otherKey'>> & { throughModel?: string };
|
|
443
|
+
export interface INativeAssociationWiring { sourceModel: string; targetModel: string; method: ...; options: AssociationWiringOptions }
|
|
444
|
+
export const isToManyAssociation = (association): boolean;
|
|
445
|
+
export const resolveAssociationForeignKey = (source, association, tablesByModel): string | undefined;
|
|
446
|
+
export const resolveAssociationWiring = (source, association, tablesByModel): INativeAssociationWiring;
|
|
447
|
+
export interface IMixinDeclaration { propertyName: string; mixinTypeName: string; typeArguments: MixinTypeArgument[] }
|
|
448
|
+
export type MixinTypeArgument = { kind: 'model'; name: string } | { kind: 'attribute'; model: string; attribute: string } | { kind: 'literal'; value: string } | { kind: 'number' };
|
|
449
|
+
export const buildAssociationMixinDeclarations = (association, alias, targetPrimaryKeyAttribute, foreignKeyAttribute): IMixinDeclaration[];
|
|
450
|
+
export const collectSequelizeImports = (table, tablesByModel): string[]; // sorted, deterministic
|
|
451
|
+
export const collectModelTypeImports = (table, tablesByModel): string[]; // FK targets + association targets, minus self, minus non-generated
|
|
452
|
+
```
|
|
453
|
+
### `src/builders/NativeModelRenderer.ts`
|
|
454
|
+
`buildAttributeTypeNode`, `buildAttributeDeclaration`, `buildTimestampDeclarations`, `buildMixinDeclaration`, `buildIncludedAssociationDeclaration`, `buildStaticAssociationsDeclaration`, `buildColumnInitOptions`, `buildIndexLiteral`, `buildModelInitOptions`, `buildInitModelMethod`, `buildModelClassDeclaration`, `renderNativeModelFile(table, dialect, tablesByModel): string`, `renderNativeFiles(tablesMetadata, dialect): IGeneratedFile[]` (models + initModels.ts + index.ts).
|
|
455
|
+
### `src/builders/nativeWiring.ts`
|
|
456
|
+
`buildInitModelCall`, `buildAssociationCall`, `buildModelsReturn`, `buildInitModelsFunction`, `buildModelsTypeAlias`, `renderInitModelsFile`, `renderNativeIndexFile`.
|
|
457
|
+
### `src/builders/generatedFile.ts`
|
|
458
|
+
`export interface IGeneratedFile { fileName: string; content: string }`, `writeGeneratedFiles(outDir, files)`.
|
|
459
|
+
### `ModelBuilder.build()` dispatch (single entry, #82)
|
|
460
|
+
```ts
|
|
461
|
+
const format = resolveFormat(this.config);
|
|
462
|
+
if (shouldNoticeIgnoredStrict(this.config)) console.warn(STRICT_IGNORED_NOTICE);
|
|
463
|
+
// fetch metadata; zero tables -> warn and return (unchanged); ensure outDir; clean (unchanged)
|
|
464
|
+
const files = format === 'native' ? renderNativeFiles(tablesMetadata, this.dialect) : ModelBuilder.renderDecoratorsFiles(tablesMetadata, this.dialect, this.config.strict);
|
|
465
|
+
await writeGeneratedFiles(outDir, files);
|
|
466
|
+
// lint (unchanged)
|
|
467
|
+
if (format === 'decorators') warnWhenDecoratorsDependencyIsMissing(outDir);
|
|
468
|
+
```
|
|
469
|
+
`renderDecoratorsFiles` wraps existing `buildTableClassDeclaration` + `buildIndexExports` into `IGeneratedFile[]`; decorators node trees untouched. Replace `catch(err: any)` with `unknown` + `isErrnoException` guard.
|
|
470
|
+
|
|
471
|
+
## 3. Config and CLI
|
|
472
|
+
- `src/bin/utils.ts`: `aliasesMap.FORMAT: 'format'`; `buildConfig` adds `...(isFormat(argv[aliasesMap.FORMAT]) && { format: argv[aliasesMap.FORMAT] })`.
|
|
473
|
+
- `src/bin/cli.ts`: `.option('F', { alias: aliasesMap.FORMAT, string: true, choices: FORMATS, default: DEFAULT_FORMAT, describe: 'Output format:\n - native: plain Sequelize classes with declare fields, Model.init and an initModels wiring file (default)\n - decorators: sequelize-typescript decorators (requires sequelize-typescript in the target project)' })`; usage gains `-F [format]`. `-R` description: `Disable strict typescript class declaration (decorators format only; ignored in native format).`
|
|
474
|
+
- Notice printed once from `ModelBuilder.build()` when native and `strict === false`.
|
|
475
|
+
- `Builder` Postgres default schema unchanged.
|
|
476
|
+
- `src/index.ts`: export `FORMATS`, `DEFAULT_FORMAT`, `isFormat`, type `Format`.
|
|
477
|
+
- `src/tests/integration/formats.ts` re-exports from config.
|
|
478
|
+
|
|
479
|
+
## 4. Decorators dependency warning — `src/builders/decoratorsDependency.ts`
|
|
480
|
+
```ts
|
|
481
|
+
import { createRequire } from 'module';
|
|
482
|
+
export const DECORATORS_RUNTIME_PACKAGE = 'sequelize-typescript';
|
|
483
|
+
export const buildDecoratorsDependencyWarning = (outDir: string): string =>
|
|
484
|
+
`Warning: --format decorators emits models that import "sequelize-typescript", but it cannot be resolved from ${outDir}. ` +
|
|
485
|
+
`Install it in the target project: npm install sequelize-typescript reflect-metadata\n` +
|
|
486
|
+
`Or use --format native (the default), which depends on sequelize only.`;
|
|
487
|
+
export const isPackageResolvableFrom = (packageName: string, directory: string): boolean => { const require = createRequire(import.meta.url); try { require.resolve(packageName, { paths: [directory] }); return true; } catch (err: unknown) { return !(isErrnoException(err) && err.code === 'MODULE_NOT_FOUND'); } };
|
|
488
|
+
export const warnWhenDecoratorsDependencyIsMissing = (outDir: string): void => { if (!isPackageResolvableFrom(DECORATORS_RUNTIME_PACKAGE, outDir)) console.warn(buildDecoratorsDependencyWarning(outDir)); };
|
|
489
|
+
```
|
|
490
|
+
Verify wording against #69's agreed block (read the issue) and adjust if it differs. Called at end of `build()` for decorators only; never throws. Unit test with `fs.mkdtemp` dir lacking the package; repo root resolves true. Move `isErrnoException` to `src/utils/errors.ts`.
|
|
491
|
+
|
|
492
|
+
## 5. Zero tables
|
|
493
|
+
Guard stays before the format dispatch. Unit test with a stub `Dialect` subclass whose `buildTablesMetadata` resolves `{}`: both formats warn once, nothing written, no dependency warning.
|
|
494
|
+
|
|
495
|
+
## 6. Lint
|
|
496
|
+
Default config format-neutral. Change `padded-blocks` to `{ blocks: 'never', classes: 'always', switches: 'always' }`; update README config block. Native passes `multiLine = true` for object literals. `--lint-file` path unchanged.
|
|
497
|
+
|
|
498
|
+
## 7. Tests
|
|
499
|
+
Unit: `config.test.ts`, `cliConfig.test.ts` (format mapping, `-R`), `builders.test.ts` (new helpers; decorators text unchanged), `defaultValues.test.ts`, `nativeAttributes.test.ts`, `nativeAssociations.test.ts`, `nativeModelRenderer.test.ts` (nodeToString snapshots for units, races, employees, data types incl. ENUM union and unknown, timestamps on/off, paranoid, --case field/deletedAt, MSSQL schema+hasTrigger, indexes), `nativeWiring.test.ts`, `decoratorsDependency.test.ts`, `modelBuilder.test.ts` zero-tables stub. `readmeProgrammaticExample.test.ts` keeps passing with updated fixture.
|
|
500
|
+
|
|
501
|
+
Integration (`TestRunner.ts`, both formats):
|
|
502
|
+
- `formats.ts` -> `['native', 'decorators']` via config re-export.
|
|
503
|
+
- Replace `import { Sequelize } from 'sequelize-typescript'` with base `sequelize`; `createTestConnection(format, options)` returns the sequelize-typescript subclass for decorators (needed for `addModels`), base for native; declared type base `Sequelize`. `ITestMetadata.ts` and `initTestDatabase` use base type.
|
|
504
|
+
- `registerGeneratedModels(connection, outDir, format)`: decorators -> `import(indexDir)` + `addModels(Object.values(models))` behind a subclass guard (replaces `// @ts-ignore`); native -> `const wiring: unknown = await import(path.join(outDir, 'initModels.ts')); if (hasInitModels(wiring)) wiring.initModels(connection)`. Used in Build, Data Types, Associations, Tables/Skip tables/Skip views (unlink stays only on decorators branch).
|
|
505
|
+
- `compileGeneratedModels(outDir, format)`; native options: strict, noEmit, target ES2022, module ESNext, moduleResolution Bundler, esModuleInterop, skipLibCheck, useDefineForClassFields true, types ['node'], no decorator flags.
|
|
506
|
+
- Case block: for native also register + `connection.isDefined(transformer(tableName, MODEL))`.
|
|
507
|
+
- Associations block: same `include` assertions; native-only mixin check (`typeof race.getUnits === 'function'`, `await race.getUnits()` length, `Object.keys(unitsModel.associations)` equals `['race']`).
|
|
508
|
+
- Phase 4/5 blocks run unchanged after `registerGeneratedModels`; phase 5 text assertions branch on format (native: `initModels.ts` contains `foreignKey: "race_id"` and no `onDelete` for the CSV pair).
|
|
509
|
+
- Golden: `npm run test:golden:update`, commit `sqlite/golden/native/*`. Decorators golden changes only from the SQLite allowNull fix.
|
|
510
|
+
|
|
511
|
+
## 8. README
|
|
512
|
+
Options/usage: `-F, --format`; `-R` decorators-only. New "Output formats" section: native default with excerpts + consumer snippet (`const models = initModels(sequelize); await models.units.findAll({ include: models.races })`), `Models` type, native-only note for `initModels`/`Models`/`static initModel`; decorators subsection with dependency warning and `sequelize.addModels`. "Strict mode": decorators only, notice in native. "Programmatic usage": example gains `format: 'native'`, drops `strict: true`; update `src/tests/unit/fixtures/readmeProgrammaticExample.ts` identically. "Lint": new `padded-blocks` value. Short migration hints. Prerequisites: sequelize-typescript/reflect-metadata only for decorators.
|
|
513
|
+
|
|
514
|
+
## 9. Release `13.0.0-beta.3`
|
|
515
|
+
`npm version 13.0.0-beta.3 --no-git-tag-version`, commit `v13 phase 6: bump version to 13.0.0-beta.3`. Human: tag + push (CI publish job, needs NPM_TOKEN) or `npm publish --access public --tag next`.
|
|
516
|
+
|
|
517
|
+
## 10. Ordered steps (one worker each; baseline verification `npx tsc --noEmit && npm run test:unit`)
|
|
518
|
+
0. Fix SQLite nullability (`allowNull: !column.notnull`), regenerate decorators golden, review flips. Commit: `v13 phase 6: fix inverted allowNull in the SQLite dialect`.
|
|
519
|
+
1. Format option (IConfig, format.ts, bin/utils, cli, index.ts, formats.ts re-export; tests). Commit: `v13 phase 6: add the format option to the configuration and CLI`.
|
|
520
|
+
2. Compiler-API helpers (`builders/utils.ts`, `defaultValues.ts`; tests; decorators golden unchanged). Commit: `v13 phase 6: add compiler-API helpers for type nodes, type-only imports and object literals`.
|
|
521
|
+
3. Descriptor layer (`nativeAttributes.ts`, `nativeAssociations.ts`; tests). Commit: `v13 phase 6: derive native attribute kinds, indexes and association wiring from metadata`.
|
|
522
|
+
4. Model renderer (`NativeModelRenderer.ts`; tests). Commit: `v13 phase 6: render native model files with the TypeScript compiler API`.
|
|
523
|
+
5. Wiring renderer (`nativeWiring.ts`, `generatedFile.ts`, `renderNativeFiles`; tests). Commit: `v13 phase 6: render the initModels wiring file and barrel`.
|
|
524
|
+
6. Dispatch + notices + warning (`ModelBuilder.build()`, `decoratorsDependency.ts`, `utils/errors.ts`, lint `blocks: 'never'`; tests; `npm run test:sqlite` decorators golden unchanged apart from step 0). Commit: `v13 phase 6: dispatch ModelBuilder on the output format and warn on a missing decorators dependency`.
|
|
525
|
+
7. Integration harness (both formats; native golden committed; all five dialects). Commit: `v13 phase 6: run the integration harness for both output formats`.
|
|
526
|
+
8. README + fixture. Commit: `v13 phase 6: document the native format and the format option`.
|
|
527
|
+
9. Version bump `13.0.0-beta.3`.
|
|
528
|
+
|
|
529
|
+
## Risks
|
|
530
|
+
- SQLite allowNull inversion fix is mandatory before native runtime tests.
|
|
531
|
+
- Mixin naming: Sequelize singularises `as` with `inflection`; we use `pluralize`; runtime assertions guard divergence.
|
|
532
|
+
- `declare` fields emit nothing under either `useDefineForClassFields`; renderer must never emit a non-`declare` field (TS2612).
|
|
533
|
+
- Circular `import type` erased; only value-import graph is `initModels.ts` -> models; `through: authors_books` needs junction `initModel` before wiring (statement order).
|
|
534
|
+
- `Model.init` completeness: derive class attributes and init entries from the same column list plus `TIMESTAMP_ATTRIBUTES`.
|
|
535
|
+
- `--case`: `deletedAt` option is attribute name; `indexes.fields` are database column names; `ForeignKey<Races["raceId"]>` uses transformed target key; target lookup by model name.
|
|
536
|
+
- Postgres serial columns emit both `autoIncrement: true` and `defaultValue: Sequelize.literal("nextval(...)")`, as decorators do.
|
|
537
|
+
- MSSQL suite needs Node <= 23.
|