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.
Files changed (98) hide show
  1. package/.github/workflows/ci.yml +175 -150
  2. package/.vscode/launch.json +212 -0
  3. package/.vscode/tasks.json +95 -0
  4. package/CHANGELOG.md +17 -0
  5. package/CLAUDE.md +13 -0
  6. package/CONTEXT.md +67 -0
  7. package/README.md +827 -199
  8. package/build/bin/cli.js +65 -47
  9. package/build/bin/utils.d.ts +5 -2
  10. package/build/bin/utils.js +87 -104
  11. package/build/builders/Builder.d.ts +2 -2
  12. package/build/builders/Builder.js +3 -5
  13. package/build/builders/ModelBuilder.d.ts +43 -8
  14. package/build/builders/ModelBuilder.js +120 -122
  15. package/build/builders/NativeModelRenderer.d.ts +98 -0
  16. package/build/builders/NativeModelRenderer.js +353 -0
  17. package/build/builders/associationNaming.d.ts +9 -0
  18. package/build/builders/associationNaming.js +15 -0
  19. package/build/builders/decoratorsDependency.d.ts +27 -0
  20. package/build/builders/decoratorsDependency.js +45 -0
  21. package/build/builders/defaultValues.d.ts +40 -0
  22. package/build/builders/defaultValues.js +56 -0
  23. package/build/builders/generatedFile.d.ts +23 -0
  24. package/build/builders/generatedFile.js +31 -0
  25. package/build/builders/index.d.ts +1 -1
  26. package/build/builders/index.js +1 -5
  27. package/build/builders/nativeAssociations.d.ts +109 -0
  28. package/build/builders/nativeAssociations.js +308 -0
  29. package/build/builders/nativeAttributes.d.ts +96 -0
  30. package/build/builders/nativeAttributes.js +174 -0
  31. package/build/builders/nativeWiring.d.ts +51 -0
  32. package/build/builders/nativeWiring.js +108 -0
  33. package/build/builders/utils.d.ts +75 -0
  34. package/build/builders/utils.js +142 -48
  35. package/build/config/IConfig.d.ts +11 -2
  36. package/build/config/IConfig.js +4 -6
  37. package/build/config/format.d.ts +27 -0
  38. package/build/config/format.js +26 -0
  39. package/build/config/index.d.ts +1 -1
  40. package/build/config/index.js +1 -2
  41. package/build/connection/createConnection.d.ts +8 -1
  42. package/build/connection/createConnection.js +30 -7
  43. package/build/connection/index.d.ts +1 -1
  44. package/build/connection/index.js +1 -17
  45. package/build/dialects/AssociationsParser.d.ts +10 -2
  46. package/build/dialects/AssociationsParser.js +16 -19
  47. package/build/dialects/Dialect.d.ts +52 -9
  48. package/build/dialects/Dialect.js +93 -57
  49. package/build/dialects/DialectMSSQL.d.ts +22 -3
  50. package/build/dialects/DialectMSSQL.js +169 -75
  51. package/build/dialects/DialectMariaDB.d.ts +13 -3
  52. package/build/dialects/DialectMariaDB.js +98 -79
  53. package/build/dialects/DialectMySQL.d.ts +13 -3
  54. package/build/dialects/DialectMySQL.js +101 -83
  55. package/build/dialects/DialectPostgres.d.ts +14 -3
  56. package/build/dialects/DialectPostgres.js +129 -75
  57. package/build/dialects/DialectSQLite.d.ts +41 -3
  58. package/build/dialects/DialectSQLite.js +166 -24
  59. package/build/dialects/associationDiscovery.d.ts +64 -0
  60. package/build/dialects/associationDiscovery.js +275 -0
  61. package/build/dialects/associationsFileMerge.d.ts +21 -0
  62. package/build/dialects/associationsFileMerge.js +107 -0
  63. package/build/dialects/createDialect.d.ts +8 -0
  64. package/build/dialects/createDialect.js +24 -0
  65. package/build/dialects/dataTypes.d.ts +58 -0
  66. package/build/dialects/dataTypes.js +108 -0
  67. package/build/dialects/foreignKeys.d.ts +115 -0
  68. package/build/dialects/foreignKeys.js +198 -0
  69. package/build/dialects/index.d.ts +5 -5
  70. package/build/dialects/index.js +5 -13
  71. package/build/dialects/paranoid.d.ts +24 -0
  72. package/build/dialects/paranoid.js +29 -0
  73. package/build/dialects/utils.d.ts +2 -8
  74. package/build/dialects/utils.js +61 -58
  75. package/build/index.d.ts +11 -3
  76. package/build/index.js +5 -19
  77. package/build/lint/Linter.d.ts +14 -3
  78. package/build/lint/Linter.js +114 -14
  79. package/build/lint/eslintDefaultConfig.d.ts +2 -2
  80. package/build/lint/eslintDefaultConfig.js +28 -23
  81. package/build/lint/index.d.ts +1 -1
  82. package/build/lint/index.js +1 -5
  83. package/build/utils/errors.d.ts +6 -0
  84. package/build/utils/errors.js +6 -0
  85. package/docker-compose.yml +65 -0
  86. package/docs/adr/0001-esm-only-package.md +36 -0
  87. package/docs/adr/0002-native-default-output-format.md +41 -0
  88. package/docs/agents/domain.md +51 -0
  89. package/docs/agents/issue-tracker.md +45 -0
  90. package/docs/agents/triage-labels.md +15 -0
  91. package/docs/migration/12-to-13.md +248 -0
  92. package/docs/plans/v13-phase5-association-discovery.md +168 -0
  93. package/docs/plans/v13-phase6-native-emitter.md +537 -0
  94. package/docs/plans/v13-upgrade-plan.md +137 -0
  95. package/jest.config.cjs +31 -0
  96. package/package.json +44 -27
  97. package/scripts/check-no-sequelize-typescript.cjs +68 -0
  98. package/tsconfig.json +4 -3
@@ -0,0 +1,36 @@
1
+ # 0001. ESM-only package
2
+
3
+ - Status: Accepted
4
+ - Date: 2026-09-09
5
+
6
+ ## Context
7
+
8
+ The package previously shipped CommonJS. Version 13 moves the toolchain to
9
+ TypeScript 6 with `module: nodenext` and raises the runtime floor to Node
10
+ `>=22.13.0`. That Node version supports `require()` of ESM modules that have no
11
+ top-level await, so CommonJS consumers can still load an ESM-only package. The
12
+ surrounding ecosystem is ESM-first: yargs and the ESLint 10 flat-config stack
13
+ are shipped primarily as ES modules.
14
+
15
+ ## Decision
16
+
17
+ Ship the package as ESM only:
18
+
19
+ - `"type": "module"` in `package.json`.
20
+ - A single root `exports` entry plus `./package.json`; no other subpaths.
21
+ - A plain `tsc` build to `build/`, with no bundler and no dual CommonJS output.
22
+ - `.js` suffixes on relative imports, as `module: nodenext` requires.
23
+ - No top-level `await` in the shipped entry, so `require()` of the package from
24
+ CommonJS keeps working. A test loads the root entry with `require()` from a
25
+ CommonJS script to verify this.
26
+
27
+ ## Consequences
28
+
29
+ - Consumers on Node `<22.13` are unsupported.
30
+ - No dual build to maintain.
31
+ - Deep imports into `build/` are not supported; the `exports` map exposes the
32
+ root entry only.
33
+ - Generated model files are unchanged by this decision. Adding a `.js` suffix to
34
+ relative imports in generated code, for strict Node ESM consumers, is a
35
+ post-13 backlog item in the v13 upgrade plan
36
+ (`docs/plans/v13-upgrade-plan.md`).
@@ -0,0 +1,41 @@
1
+ # 0002. Native default output format
2
+
3
+ - Status: Accepted
4
+ - Date: 2026-09-10
5
+
6
+ ## Context
7
+
8
+ Every version before 13 emitted a single output style: `sequelize-typescript`
9
+ decorated classes, which require the consuming project to install
10
+ `sequelize-typescript` and `reflect-metadata`. Version 13 (issue #80) adds a
11
+ framework-free native emitter that produces plain `sequelize` classes: attributes
12
+ typed with `InferAttributes` / `InferCreationAttributes`, `declare`d fields wrapped
13
+ with `CreationOptional`, `ForeignKey` and `NonAttribute`, a `static initModel`
14
+ method per model, and an `initModels` wiring file plus an `index.ts` barrel. With
15
+ two formats available the generator needs a default.
16
+
17
+ ## Decision
18
+
19
+ Make the native format the default:
20
+
21
+ - `--format native` is the default; `--format decorators` is opt-in.
22
+ - The programmatic `IConfig.format` option defaults to `'native'` when unset.
23
+ - `strict` applies to the decorators format only. It is ignored under native, where
24
+ attributes are always typed with `InferAttributes`; combining `--no-strict` with
25
+ native prints a notice and does nothing else.
26
+
27
+ ## Consequences
28
+
29
+ - Breaking change for existing consumers: anyone relying on the previous decorators
30
+ output must now pass `--format decorators` (or set `format: 'decorators'`).
31
+ - Native models depend on `sequelize` alone; `sequelize-typescript` and
32
+ `reflect-metadata` are needed only for the decorators format. When the decorators
33
+ format is selected and `sequelize-typescript` cannot be resolved from the output
34
+ directory, a warning is emitted; the generator never throws for this.
35
+ - SQLite-specific quirk: SQLite reports `notnull=0` for an integer rowid primary
36
+ key, so native types such a primary key as `CreationOptional<number | null>`. The
37
+ init options stay correct (`primaryKey` and `autoIncrement` set, `allowNull`
38
+ omitted). Dialects that report `notnull=1` for their generated primary key emit
39
+ `CreationOptional<number>`.
40
+
41
+ See issue #80 and `docs/plans/v13-phase6-native-emitter.md`.
@@ -0,0 +1,51 @@
1
+ # Domain Docs
2
+
3
+ How the engineering skills should consume this repo's domain documentation when exploring the codebase.
4
+
5
+ ## Before exploring, read these
6
+
7
+ - **`CONTEXT.md`** at the repo root, or
8
+ - **`CONTEXT-MAP.md`** at the repo root if it exists: it points at one `CONTEXT.md` per context. Read each one relevant to the topic.
9
+ - **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
10
+
11
+ If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
12
+
13
+ ## File structure
14
+
15
+ Single-context repo (most repos):
16
+
17
+ ```
18
+ /
19
+ ├── CONTEXT.md
20
+ ├── docs/adr/
21
+ │ ├── 0001-event-sourced-orders.md
22
+ │ └── 0002-postgres-for-write-model.md
23
+ └── src/
24
+ ```
25
+
26
+ Multi-context repo (presence of `CONTEXT-MAP.md` at the root):
27
+
28
+ ```
29
+ /
30
+ ├── CONTEXT-MAP.md
31
+ ├── docs/adr/ ← system-wide decisions
32
+ └── src/
33
+ ├── ordering/
34
+ │ ├── CONTEXT.md
35
+ │ └── docs/adr/ ← context-specific decisions
36
+ └── billing/
37
+ ├── CONTEXT.md
38
+ └── docs/adr/
39
+ ```
40
+
41
+ ## Use the glossary's vocabulary
42
+
43
+ When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.
44
+
45
+ If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).
46
+
47
+ ## Flag ADR conflicts
48
+
49
+ If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
50
+
51
+ > _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
@@ -0,0 +1,45 @@
1
+ # Issue tracker: GitHub
2
+
3
+ Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations.
4
+
5
+ ## Conventions
6
+
7
+ - **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
8
+ - **Read an issue**: `gh issue view <number> --comments`, filtering comments by `jq` and also fetching labels.
9
+ - **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
10
+ - **Comment on an issue**: `gh issue comment <number> --body "..."`
11
+ - **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
12
+ - **Close**: `gh issue close <number> --comment "..."`
13
+
14
+ Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone.
15
+
16
+ ## Pull requests as a triage surface
17
+
18
+ **PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_
19
+
20
+ When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:
21
+
22
+ - **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff.
23
+ - **List external PRs for triage**: `gh pr list --state open --json number,title,body,labels,author,authorAssociation,comments` then keep only `authorAssociation` of `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, or `NONE` (drop `OWNER`/`MEMBER`/`COLLABORATOR`).
24
+ - **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.
25
+
26
+ GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`.
27
+
28
+ ## When a skill says "publish to the issue tracker"
29
+
30
+ Create a GitHub issue.
31
+
32
+ ## When a skill says "fetch the relevant ticket"
33
+
34
+ Run `gh issue view <number> --comments`.
35
+
36
+ ## Wayfinding operations
37
+
38
+ Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
39
+
40
+ - **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
41
+ - **Child ticket**: an issue linked to the map as a GitHub sub-issue (`gh api` on the sub-issues endpoint). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
42
+ - **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only, the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
43
+ - **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
44
+ - **Claim**: `gh issue edit <n> --add-assignee @me`, the session's first write.
45
+ - **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
@@ -0,0 +1,15 @@
1
+ # Triage Labels
2
+
3
+ The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
4
+
5
+ | Label in mattpocock/skills | Label in our tracker | Meaning |
6
+ | -------------------------- | -------------------- | ---------------------------------------- |
7
+ | `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
8
+ | `needs-info` | `needs-info` | Waiting on reporter for more information |
9
+ | `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
10
+ | `ready-for-human` | `ready-for-human` | Requires human implementation |
11
+ | `wontfix` | `wontfix` | Will not be actioned |
12
+
13
+ When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
14
+
15
+ Edit the right-hand column to match whatever vocabulary you actually use.
@@ -0,0 +1,248 @@
1
+ # Migrating from 12.x to 13.0.0
2
+
3
+ Version 13 is a substantial release. The package is now ESM-only, the generator
4
+ emits Sequelize's native output by default, foreign keys become associations
5
+ automatically, and the SQLite driver has changed. This guide walks through each
6
+ breaking change in the order you are likely to hit it while upgrading, with a
7
+ concrete before/after for each, then lists what is new in 13.
8
+
9
+ ## Breaking changes
10
+
11
+ ### 1. ESM-only package, Node `>=22.13.0`
12
+
13
+ The package now ships as ES modules only (`"type": "module"`, a single root
14
+ `exports` entry, no dual CommonJS build). The runtime floor is raised to Node
15
+ `>=22.13.0`, which is the first version able to `require()` an ESM module that
16
+ has no top-level await. CommonJS consumers can still load the package through
17
+ `require()`, but their TypeScript must resolve modules the modern way.
18
+
19
+ CommonJS/TypeScript consumers need `module: node20` (or `nodenext`) so that
20
+ `require()` of an ESM dependency is allowed:
21
+
22
+ Before (12.x), CommonJS with legacy module resolution worked:
23
+
24
+ ```jsonc
25
+ // tsconfig.json (12.x)
26
+ {
27
+ "compilerOptions": {
28
+ "module": "commonjs",
29
+ "moduleResolution": "node"
30
+ }
31
+ }
32
+ ```
33
+
34
+ After (13), use a Node-aware module setting:
35
+
36
+ ```jsonc
37
+ // tsconfig.json (13)
38
+ {
39
+ "compilerOptions": {
40
+ "module": "node20", // or "nodenext"
41
+ "moduleResolution": "nodenext"
42
+ }
43
+ }
44
+ ```
45
+
46
+ ```js
47
+ // CommonJS consumer (13) — require() of the ESM package works on Node >=22.13.0
48
+ const { SequelizeTypescriptGenerator } = require('sequelize-typescript-generator');
49
+ ```
50
+
51
+ Make sure the runtime is new enough:
52
+
53
+ ```bash
54
+ # Before (12.x): older Node was fine
55
+ node -v # v14+
56
+
57
+ # After (13): Node >=22.13.0 is required
58
+ node -v # v22.13.0 or newer
59
+ ```
60
+
61
+ Deep imports into `build/` are closed by the `exports` map as a consequence of
62
+ this change; see section 6.
63
+
64
+ ### 2. Native is the default output format
65
+
66
+ The generator now emits Sequelize's native output by default: plain `sequelize`
67
+ model classes with attributes typed via `InferAttributes` /
68
+ `InferCreationAttributes`, `declare`d fields, and a `static initModel` method per
69
+ model. The old `sequelize-typescript` decorator output is still available behind
70
+ the new `--format native|decorators` flag.
71
+
72
+ Native models depend on `sequelize` alone. The decorators format still requires
73
+ `sequelize-typescript` and `reflect-metadata` in the consuming project.
74
+
75
+ Before (12.x) — implicit decorators output:
76
+
77
+ ```bash
78
+ stg -D sqlite -s ./db.sqlite -o ./models
79
+ ```
80
+
81
+ ```ts
82
+ // models/person.ts (12.x, decorators)
83
+ @Table({ tableName: "person", timestamps: false })
84
+ export class person extends Model<personAttributes, personAttributes> {
85
+ @Column({ type: DataType.STRING })
86
+ name!: string;
87
+ }
88
+ ```
89
+
90
+ After (13) — the same command now emits native output:
91
+
92
+ ```ts
93
+ // models/person.ts (13, native — default)
94
+ export class person extends Model<InferAttributes<person>, InferCreationAttributes<person>> {
95
+ declare name: string;
96
+
97
+ static initModel(sequelize: Sequelize): typeof person {
98
+ person.init({
99
+ name: { type: DataTypes.STRING, allowNull: false }
100
+ }, { sequelize, tableName: "person", timestamps: false });
101
+ return person;
102
+ }
103
+ }
104
+ ```
105
+
106
+ To keep the old decorator output, opt in explicitly:
107
+
108
+ ```bash
109
+ stg -D sqlite -s ./db.sqlite -o ./models --format decorators
110
+ ```
111
+
112
+ ### 3. Associations discovered by default
113
+
114
+ Foreign keys are now turned into associations automatically. Where 12.x emitted
115
+ plain columns, 13 wires up the corresponding association mixins (and decorators,
116
+ under `--format decorators`). Pass `--no-associations` to restore the previous
117
+ behaviour of emitting foreign-key columns only.
118
+
119
+ Before (12.x) — a foreign key was just a column:
120
+
121
+ ```ts
122
+ // person.ts (12.x)
123
+ export interface personAttributes {
124
+ passport_id: number;
125
+ }
126
+ ```
127
+
128
+ After (13) — the relationship is materialised:
129
+
130
+ ```ts
131
+ // person.ts (13, native)
132
+ declare passport_id: number;
133
+ declare getPassport: HasOneGetAssociationMixin<passport>;
134
+ declare setPassport: HasOneSetAssociationMixin<passport, passport["passport_id"]>;
135
+ declare passport?: NonAttribute<passport>;
136
+ ```
137
+
138
+ Restore the old output:
139
+
140
+ ```bash
141
+ stg -D sqlite -s ./db.sqlite -o ./models --no-associations
142
+ ```
143
+
144
+ ### 4. SQLite driver is `@vscode/sqlite3`
145
+
146
+ The SQLite integration now uses `@vscode/sqlite3`. The old `sqlite3` package is
147
+ no longer supported.
148
+
149
+ Before (12.x):
150
+
151
+ ```bash
152
+ npm install sqlite3
153
+ ```
154
+
155
+ After (13):
156
+
157
+ ```bash
158
+ npm uninstall sqlite3
159
+ npm install @vscode/sqlite3
160
+ ```
161
+
162
+ ### 5. `--lint-file` is flat-config only
163
+
164
+ When you pass `--lint-file`, the generator now expects an ESLint flat config
165
+ (`eslint.config.js`). Legacy `.eslintrc*` files fail fast instead of being read.
166
+
167
+ Before (12.x) — a legacy config was accepted:
168
+
169
+ ```bash
170
+ stg -D sqlite -s ./db.sqlite -o ./models --lint-file .eslintrc.js
171
+ ```
172
+
173
+ ```js
174
+ // .eslintrc.js (12.x)
175
+ module.exports = {
176
+ rules: { semi: ["error", "always"] }
177
+ };
178
+ ```
179
+
180
+ After (13) — use a flat config:
181
+
182
+ ```bash
183
+ stg -D sqlite -s ./db.sqlite -o ./models --lint-file eslint.config.js
184
+ ```
185
+
186
+ ```js
187
+ // eslint.config.js (13)
188
+ export default [
189
+ { rules: { semi: ["error", "always"] } }
190
+ ];
191
+ ```
192
+
193
+ ### 6. `exports` map closes deep imports
194
+
195
+ The package `exports` map exposes only the root entry (plus `./package.json`).
196
+ Deep imports into `build/` no longer resolve. This follows from the ESM-only
197
+ change in section 1.
198
+
199
+ Before (12.x) — reaching into the build tree worked:
200
+
201
+ ```ts
202
+ import { SqliteDialect } from 'sequelize-typescript-generator/build/dialects/SqliteDialect';
203
+ ```
204
+
205
+ After (13) — import from the package root only:
206
+
207
+ ```ts
208
+ import { SqliteDialect } from 'sequelize-typescript-generator';
209
+ ```
210
+
211
+ ## New in 13
212
+
213
+ These are additive and do not require changes when upgrading.
214
+
215
+ ### `--paranoid`
216
+
217
+ Emit paranoid table options for tables that have a `deleted_at` / `deletedAt`
218
+ column. Requires `--timestamps`.
219
+
220
+ ```bash
221
+ stg -D sqlite -s ./db.sqlite -o ./models --timestamps --paranoid
222
+ ```
223
+
224
+ ```ts
225
+ // table option added when a deleted_at column is present
226
+ { sequelize, tableName: "person", timestamps: true, paranoid: true }
227
+ ```
228
+
229
+ ### `createDialect` factory
230
+
231
+ A `createDialect` factory is now exported from the package root, to build a
232
+ dialect instance programmatically.
233
+
234
+ ```ts
235
+ import { createDialect } from 'sequelize-typescript-generator';
236
+
237
+ const dialect = createDialect('sqlite');
238
+ ```
239
+
240
+ ### SQL Server `schema` and `hasTrigger`
241
+
242
+ For SQL Server, the generator now sets `schema` in the emitted table options and
243
+ detects `hasTrigger` on tables that have triggers.
244
+
245
+ ```ts
246
+ // table options (mssql)
247
+ { sequelize, tableName: "person", schema: "dbo", hasTrigger: true }
248
+ ```
@@ -0,0 +1,168 @@
1
+ # Phase 5 (issue #79) implementation plan: automatic association discovery
2
+
3
+ Status: planned, not started
4
+ Implements: #79 (phase 5 of docs/plans/v13-upgrade-plan.md)
5
+ Depends on: phase 4 (#78, done on v13)
6
+ Open judgment call: with no `--case`, singular/plural aliases keep the database spelling and only composed aliases are camelCased.
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; library types first, 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 (Association, Alias, Association discovery, Associations file, Junction table, Case); TDD at pure seams; the TypeScript compiler API 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
+ - Pipeline today (`src/dialects/Dialect.ts` `buildTablesMetadata`): fetch → filter → per-table columns/indices/FKs → `applyForeignKeyConstraintsToColumns` → CSV block **overwrites** `tablesMetadata[t].associations = association.associations` (would wipe discovered associations) and rewrites `columns[c].foreignKey` → `caseTransformer`.
17
+ - `caseTransformer` mutates association objects in place (`src/dialects/utils.ts`) and `AssociationsParser.parse` returns one static cached object regardless of path. Together: a second `buildTablesMetadata` with a different case double-transforms `targetModel`. Must be fixed in this phase (copy-on-transform + per-path cache returning copies).
18
+ - `IAssociationMetadata` already has optional `alias`, `foreignKey`, `targetKey`, `onDelete`, `onUpdate`; nothing reads them yet.
19
+ - Emission (`ModelBuilder.buildAssociationPropertyDecl`): property name is `pluralize.plural/singular(targetModel)`; only decorator option emitted is `sourceKey`; imports of target models and the self-import guard exist; decorator names are imported from the `associations` list.
20
+ - `generateArrowDecorator` (`src/builders/utils.ts`) renders object props as literals in insertion order, so option key order is controlled by the props object.
21
+ - `pluralize` and `change-case` are already dependencies.
22
+ - sequelize-typescript sets `options.as = propertyName` when `as` is absent.
23
+ - yargs 17: `.option('associations', { boolean: true, default: true })` yields `associations: false` for `--no-associations`. Side finding: existing `--no-views`/`--no-strict` long forms are parsed as `views: false` so only `-V`/`-R` work today; pre-existing bug, out of scope, file a follow-up issue.
24
+ - A composite primary key containing the FK column sets `primaryKey: true` on that column, so the "FK column is the PK" 1:1 rule must require a single-column PK.
25
+ - Fixtures in all five dialects: `units.race_id → races` (CASCADE/RESTRICT; MSSQL NO ACTION for update), `employees.manager_id → employees` (SET NULL; MSSQL may differ, check mssql test metadata), `profiles.person_id UNIQUE → person` (CASCADE/CASCADE), `shipments(order_id,line_no) → order_lines` composite; `person`/`passport` have no DB FK (CSV puts FK on `passport.passport_id → person`). Golden is generated WITH the CSV.
26
+
27
+ ## 1. Data model
28
+
29
+ Discovery **builds on** `applyForeignKeyConstraintsToColumns`; column-level `IColumnMetadata.foreignKey` stays as the `@ForeignKey`/`references` record. Extract the eligibility test into a shared classifier in `src/dialects/foreignKeys.ts`:
30
+
31
+ ```ts
32
+ export const FOREIGN_KEY_SKIP_REASONS = ['composite', 'cross-schema', 'excluded-target'] as const;
33
+ export type ForeignKeySkipReason = typeof FOREIGN_KEY_SKIP_REASONS[number];
34
+ export type ForeignKeyClassification = { isEligible: true } | { isEligible: false; reason: ForeignKeySkipReason };
35
+ /** Single-column, generated target, same schema -> eligible; otherwise the first failing rule. */
36
+ export const classifyForeignKeyConstraint = (constraint: IForeignKeyConstraintMetadata, sourceSchema: string | undefined, generatedTables: ReadonlySet<string>): ForeignKeyClassification;
37
+ ```
38
+ `applyForeignKeyConstraintsToColumns` uses the classifier with identical behaviour.
39
+
40
+ Discovered association for `units.race_id → races(race_id)` (pre-case, database names):
41
+
42
+ Source side (`units.associations`): `{ associationName: 'BelongsTo', targetModel: 'races', alias: 'race', foreignKey: 'race_id', targetKey: 'race_id', onDelete: 'CASCADE', onUpdate: 'RESTRICT' }`
43
+ Target side (`races.associations`): `{ associationName: 'HasMany', targetModel: 'units', alias: 'units', foreignKey: 'race_id', sourceKey: 'race_id', onDelete: 'CASCADE', onUpdate: 'RESTRICT' }`
44
+
45
+ - `HasOne` on target when `constraint.isSourceColumnUnique` or (`column.primaryKey` and the source table has exactly one PK column); `HasMany` otherwise. `BelongsTo` always on source.
46
+ - `foreignKey` on both sides; `targetKey` (BelongsTo) / `sourceKey` (Has*) = referenced column.
47
+ - `onDelete`/`onUpdate` set only when normalized rule is not `'NO ACTION'`, on both sides.
48
+ - CSV-derived associations keep `alias` undefined → emission falls back to today's plural/singular rule (golden compat).
49
+ - `IForeignKey` in AssociationsParser gains `isJunctionForeignKey: boolean` (true for N:N rows).
50
+
51
+ ## 2. Pure module `src/dialects/associationDiscovery.ts`
52
+
53
+ ```ts
54
+ export interface IAssociationDiscoveryResult { tablesMetadata: ITablesMetadata; /* new objects */ warnings: string[]; /* one per skipped constraint */ }
55
+ export const discoverAssociations = (tablesMetadata: ITablesMetadata): IAssociationDiscoveryResult;
56
+ export const FOREIGN_KEY_COLUMN_SUFFIXES = ['_id', '_fk', 'Id', 'Fk'] as const;
57
+ /** 'race_id' -> 'race'; undefined when no suffix matches or remainder is empty. */
58
+ export const stripForeignKeyColumnSuffix = (columnName: string): string | undefined;
59
+ export interface IAliasPair { belongsToAlias: string; hasAlias: string; }
60
+ export const resolveAssociationAliases = (input: { sourceModel: string; targetModel: string; foreignKeyColumn: string; isAmbiguous: boolean; isOneToOne: boolean; }): IAliasPair;
61
+ export const formatForeignKeySkipWarning = (constraint: IForeignKeyConstraintMetadata, sourceSchema: string | undefined, reason: ForeignKeySkipReason): string;
62
+ export const isAssociationDiscoveryEnabled = (metadata: IConfigMetadata | undefined): boolean => metadata?.associations !== false;
63
+ ```
64
+ No `console` inside. Input is post-filter, pre-case.
65
+
66
+ Algorithm, per table S in key order, per constraint in `foreignKeys` order:
67
+ 1. classify; not eligible → push warning, continue.
68
+ 2. `c = sourceColumns[0]`, `T = targetTable`, `k = targetColumns[0]`; find column by `originName === c` (skip silently if missing).
69
+ 3. `isOneToOne = constraint.isSourceColumnUnique || (column.primaryKey && S has a single PK column)`.
70
+ 4. `isAmbiguous = (#eligible constraints on S with targetTable === T) > 1 || S.originName === T`.
71
+ 5. Aliases:
72
+ - Unambiguous: `belongsToAlias = singular(T)`; `hasAlias = isOneToOne ? singular(S) : plural(S)`.
73
+ - Ambiguous: `stripped = stripForeignKeyColumnSuffix(c)`. If defined: `belongsToAlias = stripped`, `hasAlias = camelCase(`${stripped} ${isOneToOne ? singular(S) : plural(S)}`)`. Else: `belongsToAlias = camelCase(`${singular(T)} ${c}`)`, `hasAlias = camelCase(`${c} ${plural|singular(S)}`)`.
74
+ - Collision: each model keeps a Set of taken names seeded with its column field names and aliases already assigned. Candidates tried in order: primary, ambiguous form, fallback form, fallback + numeric suffix 2,3,... First free wins.
75
+ 6. Push BelongsTo onto S and Has* onto T (self-reference: both onto S, BelongsTo first).
76
+
77
+ Examples (no --case): `units.race` / `races.units`; `profiles.person` / `person.profile` (HasOne); `employees.manager` / `employees.managerEmployees`; hypothetical `books(author_id, editor_id) → authors`: `books.author`, `books.editor`, `authors.authorBooks`, `authors.editorBooks`.
78
+
79
+ `--case` on aliases: applied by `caseTransformer` with `TransformTarget.COLUMN`. With no `--case`, singular/plural aliases keep database spelling (12.x compatible) and only composed aliases are camelCased. This is the open judgment call surfaced in the header.
80
+
81
+ `caseTransformer` (`src/dialects/utils.ts`): build new association objects (`map` with spread), transforming `targetModel`/`joinModel` (MODEL) and `sourceKey`/`alias`/`foreignKey`/`targetKey` (COLUMN); rebuild `columns[x].foreignKey` without mutating the input.
82
+
83
+ ## 3. Associations file on top: `src/dialects/associationsFileMerge.ts` (pure)
84
+
85
+ ```ts
86
+ export interface IAssociationsFileMergeResult { tablesMetadata: ITablesMetadata; warnings: string[]; }
87
+ export const applyAssociationsFile = (tablesMetadata: ITablesMetadata, parsed: IAssociationsParsed): IAssociationsFileMergeResult;
88
+ ```
89
+ Replaces the inline CSV block in `Dialect.ts`; existing warning texts move into `warnings`.
90
+
91
+ Per parsed table S:
92
+ 1. Table missing → warning, continue.
93
+ 2. For each `foreignKeys` entry `{ name: c, targetModel: T, isJunctionForeignKey }`:
94
+ - If not junction: remove the discovered BelongsTo on S with `foreignKey === c` and its paired Has* on the discovered targetModel whose `targetModel === S && foreignKey === c`. Keyed on (source table, FK column) only.
95
+ - Junction row: remove nothing.
96
+ - Column missing → warning; else `columns[c].foreignKey = { ...(discovered?.targetModel === T ? discovered : {}), name: c, targetModel: T }`.
97
+ 3. **Append** `parsed[S].associations` to `tablesMetadata[S].associations` (instead of overwrite).
98
+ 4. Alias collision after merge: if a CSV association's effective property name (plural/singular of targetModel) equals a discovered `alias` on the same model, drop the discovered association with warning `Association alias '<x>' on table '<S>' is used by both a discovered association and the associations file; the associations file entry is kept`.
99
+
100
+ Fixture consequences (golden with CSV): `units.ts`/`races.ts` unchanged (CSV replaces discovered pair); `person.ts` gains `HasOne profiles` alias `profile` + import; `profiles.ts` gains BelongsTo; `employees.ts` gains BelongsTo + HasMany.
101
+
102
+ `AssociationsParser`: replace static cache with `Map<string, IAssociationsParsed>` keyed by path, return structural copies; set `isJunctionForeignKey`.
103
+
104
+ ## 4. `--no-associations`
105
+
106
+ - `IConfigMetadata.associations?: boolean; // Discover associations from foreign keys; undefined means enabled`.
107
+ - `src/bin/utils.ts`: `ASSOCIATIONS: 'associations'`; `buildConfig`: `...(argv[aliasesMap.ASSOCIATIONS] === false && { associations: false })`.
108
+ - `src/bin/cli.ts`: `.option(aliasesMap.ASSOCIATIONS, { boolean: true, default: true, describe: 'Discover one-to-one and one-to-many associations from foreign keys. Use --no-associations to disable.' })`, no short letter. Usage string gains `--no-associations`.
109
+ - With `associations: false`: skip `discoverAssociations` only; column `@ForeignKey` stays; associations file still works.
110
+
111
+ ## 5. Emission in `src/builders/ModelBuilder.ts`
112
+
113
+ Exported pure helpers:
114
+ ```ts
115
+ import type { BelongsToOptions, HasManyOptions, HasOneOptions } from 'sequelize';
116
+ export type AssociationDecoratorOptions = Partial<BelongsToOptions & HasManyOptions & HasOneOptions>;
117
+ /** Alias when discovered, otherwise plural/singular of the target model. */
118
+ export const resolveAssociationPropertyName = (association: IAssociationMetadata): string;
119
+ /** Options for @BelongsTo/@HasOne/@HasMany; undefined when empty. Key order: as, foreignKey, targetKey, sourceKey, onDelete, onUpdate. `as` is emitted only when alias is set (discovered associations). */
120
+ export const buildAssociationDecoratorProps = (association: IAssociationMetadata): AssociationDecoratorOptions | undefined;
121
+ ```
122
+ Discovered associations emit `as: alias` (issue #79 says "with foreignKey and as"); CSV associations without alias emit no `as` (golden compat). `@ForeignKey(() => T)` on the column unchanged. Imports already handled (self-import guard exists).
123
+
124
+ Expected golden after change (generated with CSV): `units.ts`, `races.ts` unchanged. `profiles.ts` gains
125
+ ```ts
126
+ @BelongsTo(() => person, { as: "person", foreignKey: "person_id", targetKey: "person_id", onDelete: "CASCADE", onUpdate: "CASCADE" })
127
+ person?: person;
128
+ ```
129
+ `person.ts` gains `import { profiles }` and `@HasOne(() => profiles, { as: "profile", foreignKey: "person_id", sourceKey: "person_id", onDelete: "CASCADE", onUpdate: "CASCADE" }) profile?: profiles;`
130
+ `employees.ts` gains `@BelongsTo(() => employees, { as: "manager", foreignKey: "manager_id", targetKey: "employee_id", onDelete: "SET NULL" }) manager?: employees;` and `@HasMany(() => employees, { as: "managerEmployees", foreignKey: "manager_id", sourceKey: "employee_id", onDelete: "SET NULL" }) managerEmployees?: employees[];` (linter formatting applies).
131
+
132
+ ## 6. Warnings (emitted once per constraint via `console.warn('[WARNING]', message)` in `buildTablesMetadata`)
133
+
134
+ - composite: `Foreign key constraint '<name>' on table '<table>' spans columns (<a>, <b>); Sequelize associations need a single column, so the columns are generated as plain attributes`
135
+ - cross-schema: `Foreign key constraint '<name>' on table '<schema>.<table>' references table '<targetSchema>.<target>' in another schema; the column is generated as a plain attribute`
136
+ - excluded target: `Foreign key constraint '<name>' on table '<table>' references table '<target>', which is not among the generated tables; the column is generated as a plain attribute`
137
+
138
+ `buildTablesMetadata` order after change: column FK copy inside the try; then (outside the fetch try) `if (isAssociationDiscoveryEnabled(config.metadata))` discover + warn; then `applyAssociationsFile` when `associationsFile` set (+ warn); then case transform.
139
+
140
+ ## 7. Tests
141
+
142
+ Unit: `associationDiscovery.test.ts` (cardinality incl. composite PK → HasMany; on-rules only when not NO ACTION; alias rule cases; collisions; three skip warnings with exact wording; no mutation; deterministic order), `associationsFileMerge.test.ts`, `foreignKeys.test.ts` (classifier), `caseTransformer.test.ts` (alias/foreignKey/targetKey; no compounding on repeat), `associationsParser.test.ts` (isJunctionForeignKey; per-path cache; copies), `builders.test.ts` (resolveAssociationPropertyName, buildAssociationDecoratorProps key order, nodeToString snapshot), `cliConfig.test.ts` (associations false mapping; isAssociationDiscoveryEnabled).
143
+
144
+ Integration (`TestRunner.ts`, new `describe('Association discovery')` after `Foreign keys`, per dialect, both formats): build WITHOUT associationsFile (`indices: true`), assert via `Model.associations` (`associationType`, `foreignKey`, `as`): 1:N units/races (+ include counts); 1:1 profiles/person (HasOne; include yields object); composite skip (shipments/order_lines associations empty; `console.warn` spy captured the constraint name); self-reference alias (`manager`, `managerEmployees`; include 'manager' works with seeded rows); referential actions (`units.associations.race.options.onDelete === 'CASCADE'`; onUpdate asserted only when expectedForeignKeys says not NO ACTION). CSV override (existing Associations block, build with CSV): `Object.keys(units.associations)` equals `['race']`, `races` → `['units']`, `person` → `['passport','profile']`, `units.ts` text has no `onDelete`. `--no-associations` build: all `associations` empty; `units.ts` still has `@ForeignKey(() => races)`. `--case CAMEL` build: file text contains `managerEmployees?: employees[]` and `foreignKey: "managerId"`. Golden update and review.
145
+
146
+ ## 8. README
147
+
148
+ Options block: `--associations ... [boolean] [default: true]` + usage line `--no-associations`. `## Associations` section rewrite: discovery default, cardinality rule, skipped FK kinds with warnings, N:N never inferred; "Alias rule" subsection; "Associations file precedence" paragraph; programmatic example shows `associations: false`. Check `src/tests/unit/readmeProgrammaticExample.test.ts` still passes.
149
+
150
+ ## 9. Release `13.0.0-beta.2` on `next`
151
+
152
+ State: package.json version `12.0.1`; no publishConfig; `.github/workflows/ci.yml` publish job runs on `v*` tags, `--tag next` when tag contains `-`, needs `secrets.NPM_TOKEN`; `13.0.0-beta.1` was never published (#84 open, ready-for-human, token missing). Agent-doable: `npm version 13.0.0-beta.2 --no-git-tag-version`, commit. Human: add NPM_TOKEN, `git tag v13.0.0-beta.2 && git push origin v13 v13.0.0-beta.2`; or `npm publish --access public --tag next` manually.
153
+
154
+ ## 10. Ordered steps
155
+
156
+ 1. Classifier + discovery module (+ unit tests). Commit: `v13 phase 5: derive associations and aliases from foreign key constraints`.
157
+ 2. Associations file merge + parser per-path cache/copies + caseTransformer copy-on-transform (+ unit tests). Commit: `v13 phase 5: apply the associations file on top of discovered associations`.
158
+ 3. Emission helpers in ModelBuilder (+ unit tests; golden unchanged at this step). Commit: `v13 phase 5: emit as, foreignKey, keys and referential actions on association decorators`.
159
+ 4. Config flag + CLI + pipeline wiring in Dialect.ts + golden update. Commit: `v13 phase 5: enable association discovery by default with --no-associations`.
160
+ 5. Integration harness block; run all five dialects. Commit: `v13 phase 5: cover association discovery in the integration harness`.
161
+ 6. README. Commit: `v13 phase 5: document association discovery and --no-associations`.
162
+ 7. Version bump to 13.0.0-beta.2. Commit: `v13 phase 5: bump version to 13.0.0-beta.2`. Comment on #79/#84; follow-up issue for `--no-views`/`--no-strict` long forms.
163
+
164
+ ## Risks
165
+ - Discovery on by default means every existing integration block emits associations; self-ref/1:1 emission bugs show up as compile failures everywhere.
166
+ - MSSQL reports `NO ACTION` for `ON UPDATE RESTRICT`; key onUpdate assertions off `expectedForeignKeys`.
167
+ - Composite-PK guard matters for junction tables with `PRIMARY KEY (a, b)`.
168
+ - Publishing depends on a human adding NPM_TOKEN.