ts-grm-migrate 0.1.0-alpha.1 → 0.1.0-alpha.4

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/CHANGELOG.md CHANGED
@@ -2,8 +2,17 @@
2
2
 
3
3
  English | [简体中文](docs/zh-CN/CHANGELOG.md)
4
4
 
5
+ ## 0.1.0-alpha.4 (pending publication)
6
+
7
+ - Localize configuration, history, locking, DDL, transaction and drift explanations throughout the CLI; preserve technical identifiers and expose original external diagnostics with `--detail`.
8
+ - Explain model naming errors in the selected language and restrict ESM troubleshooting hints to module-format failures.
9
+
5
10
  ## 0.1.0-alpha.1 (pending publication)
6
11
 
12
+ - Add `dev --create-only` and read-only `check`, validate history before development generation, preserve unmanaged indexes, order PostgreSQL dependencies, and handle MySQL identity/default changes together.
13
+ - Compare defaults by dialect and column type without numeric precision loss; abort on patch metadata errors; report all unproven CHECK differences.
14
+ - Repair isolated companion compatibility tests and add bilingual migration review, custom SQL, transaction recovery, and scope documentation.
15
+ - Support column-level `default` and `autoIncrement` declared through the optional [`ts-grm-patches`](https://www.npmjs.com/package/ts-grm-patches) package, including the matching DDL for PostgreSQL, MySQL, SQLite, SQL Server, and Oracle, and normalize catalog default forms (`::type` casts, parentheses, `N` prefixes, numeric quoting) so migrations are not regenerated.
7
16
  - Make CLI output concise and English by default, with `--detail` diagnostics, `--lang zh-CN` Chinese messages, and a configuration setting for the default language.
8
17
  - Reduce default test output while retaining failure reasons and post-migration drift warnings.
9
18
  - Remove the automatic GitHub Actions workflow; maintainers now run pre-release verification and publishing manually.
package/README.md CHANGED
@@ -4,13 +4,18 @@ English | [简体中文](docs/zh-CN/README.md)
4
4
 
5
5
  Database schema migrations for [ts-grm](https://github.com/babyfish-ct/ts-grm). Manage database versions with SQL migration files while keeping your ts-grm models as the source of truth. No separate schema file or code generation is required.
6
6
 
7
+ The current scope is **new ts-grm applications and subsequent model evolution**. Start with an empty database. Adopting existing application databases and baselining pre-existing tables are not supported. A shadow database is deliberately omitted; see [migration workflows and design tradeoffs](docs/migrations.md).
8
+
7
9
  ## Features
8
10
 
9
11
  - **Incremental migrations:** compare models with the database, generate readable SQL files, and record applied history.
12
+ - **SQL review:** `dev --create-only` generates a pending file for review and editing before deployment.
13
+ - **Strict checks:** `check` reports model/database drift with a nonzero exit code.
10
14
  - **Ordered deployment:** apply pending migration files in order, including in deployment pipelines.
11
15
  - **Direct synchronization:** bring a database in line with the models without writing migration history.
12
16
  - **Post-migration checks:** report schema differences that remain after applying changes.
13
17
  - **Failure recovery:** record failed or interrupted attempts and require an explicit `resolve` before retrying.
18
+ - **Column defaults and auto-increment:** with the optional [`ts-grm-patches`](https://www.npmjs.com/package/ts-grm-patches) package installed, models can declare `default(...)` and `autoIncrement()` and migrations create the matching database features.
14
19
 
15
20
  ## Status and installation
16
21
 
@@ -51,7 +56,10 @@ export default defineConfig({
51
56
  Then run:
52
57
 
53
58
  ```sh
54
- npx tgm dev -n init # Generate and apply the first migration
59
+ npx tgm dev --create-only -n init # Generate SQL for review
60
+ # Review the generated SQL file, then:
61
+ npx tgm deploy # Apply the first migration
62
+ npx tgm check # Check that the model matches
55
63
  npx tgm dev # Omit the name to use only a timestamp
56
64
  npx tgm status # Inspect applied and pending migrations
57
65
  ```
@@ -68,6 +76,56 @@ npx tgm status # Inspect applied and pending migrations
68
76
 
69
77
  The CLI searches the project root for a `.ts`, `.mts`, `.mjs`, or `.js` configuration file. Use `--config <path>` to choose one explicitly. A `.ts` file follows the project's module type; in a CommonJS project, use `.mts` or set `"type": "module"`.
70
78
 
79
+ ## Defaults and auto-increment (optional)
80
+
81
+ Upstream ts-grm column metadata expresses neither column defaults nor auto-increment, so a model cannot declare `serial` / `identity` / `auto_increment` or a `DEFAULT` value on its own. As of this release that capability comes from a companion package, [ts-grm-patches](https://www.npmjs.com/package/ts-grm-patches); install it alongside the CLI:
82
+
83
+ ```sh
84
+ npm install -D ts-grm-patches@0.1.0
85
+ ```
86
+
87
+ `ts-grm-patches@0.1.0` requires both ts-grm peers at `0.0.13`. The broader `0.0.9`–`0.0.13` range applies to the migrator without the companion package.
88
+
89
+ Then install the patch once, **before any `model(...)` definition**:
90
+
91
+ ```ts
92
+ // ts-grm-migrate.config.ts (or any module your models import first)
93
+ import { applyPatches } from "ts-grm-patches";
94
+
95
+ applyPatches();
96
+ ```
97
+
98
+ ```ts
99
+ const User = model(
100
+ "User",
101
+ "id",
102
+ class {
103
+ id = prop.i32().autoIncrement(); // serial / identity / auto_increment
104
+ status = prop.str(20).default("active"); // literal
105
+ createdAt = prop.dt().default(dsl.native.date`now()`); // SQL expression
106
+ },
107
+ );
108
+ ```
109
+
110
+ No migrate-side configuration is needed: the model adapter detects the patch and manages both attributes. `ts-grm-patches` only declares them and carries the metadata; turning them into DDL is this tool's job.
111
+
112
+ What changes once the patch is installed:
113
+
114
+ - **The model becomes authoritative for these two attributes.** A column without `default(...)` is diffed as "no default", so a default that exists only in the database is dropped (`alter column ... drop default`). Without the patch, migrate leaves existing defaults and auto-increment untouched.
115
+ - `autoIncrement()` and `default(...)` are mutually exclusive on one column; declaring both is rejected.
116
+ - **On PostgreSQL, SQL Server, Oracle, and SQLite, switching auto-increment on or off for an existing column requires a manual SQL migration** (see [workflow](docs/migrations.md#custom-sql-and-unsupported-automatic-changes)): PostgreSQL, SQL Server, and Oracle cannot do it in place safely, and SQLite cannot alter tables at all. MySQL supports switching existing columns and updates their defaults together. Creating a table with `autoIncrement()` is supported on all dialects; adding such a column is supported except on SQLite.
117
+ - Expression defaults accept `dsl.native.*` expressions (for example `` dsl.native.str`uuid_generate_v4()` ``); other ts-grm expression nodes are rejected rather than rendered as questionable SQL. Literals accept the column's value type.
118
+ - If `applyPatches()` runs after a model was defined, that model's columns are not affected.
119
+
120
+ Per-dialect rendering:
121
+
122
+ - **PostgreSQL:** `generated by default as identity` for `autoIncrement()`.
123
+ - **MySQL:** `auto_increment`.
124
+ - **SQLite:** `INTEGER PRIMARY KEY AUTOINCREMENT` (the column must be the single-column, integer primary key; adding one to an existing table is rejected) and `default (expr)` for expressions.
125
+ - **SQL Server / Oracle:** `identity(1,1)` / `generated by default as identity`.
126
+
127
+ Catalog forms differ from what the model writes: PostgreSQL adds type casts (`'active'::character varying`), SQL Server wraps expressions in parentheses and prefixes unicode literals with `N`, and MySQL quotes numeric defaults. The differ normalizes whole-literal casts compatible with the target type, catalog parentheses, and dialect-specific prefixes. Textual digits remain text, numbers are compared without floating-point precision loss, and casts inside expressions are preserved. Unproven expression equivalence may still appear as a difference. Metadata getter failures abort migration rather than requesting deletion.
128
+
71
129
  ## Databases and configuration
72
130
 
73
131
  | `dialect` | Driver dependency | Supported scope |
@@ -147,13 +205,15 @@ You can also run `tests/server-integration.test.ts` against dedicated instances
147
205
  | Command | Purpose |
148
206
  | --- | --- |
149
207
  | `tgm dev [-n <name>]` | Compare models with the database, then generate and apply a migration (the name is optional) |
208
+ | `tgm dev --create-only [-n <name>]` | Generate a pending SQL file for review without applying it |
209
+ | `tgm check` | Read-only model/database comparison; exit 1 for drift or an error |
150
210
  | `tgm deploy` | Apply pending migrations in order without interaction |
151
211
  | `tgm push [--force]` | Sync the database to the models without a file or history record |
152
212
  | `tgm status` | Show applied and pending migrations |
153
213
  | `tgm resolve --applied <id>` | Mark SQL already executed manually as applied |
154
214
  | `tgm resolve --rolled-back <id>` | Mark an attempt as rolled back so it becomes pending again |
155
215
 
156
- Options: `--config <path>` selects a configuration file; `-n` / `--name <name>` names a migration; `--force` skips destructive-change confirmation; `--detail` shows execution steps, SQL, and locks; `--lang <en|zh-CN>` selects the language for this command; `-h` shows help.
216
+ Options: `--create-only` generates without applying (`dev` only); `--config <path>` selects a configuration file; `-n` / `--name <name>` names a migration; `--force` skips destructive-change confirmation; `--detail` shows execution steps, SQL, and locks; `--lang <en|zh-CN>` selects the language for this command; `-h` shows help.
157
217
 
158
218
  Normal commands report the target, migration count or ID, and result. `status` intentionally lists migrations because it is an inspection command. For example, `tgm deploy` may print `Applied 2 migrations to postgres/app/public.` The SQL shown with `--detail` may contain business data: take care when saving or sharing logs. Diagnostic events do not print connection passwords.
159
219
 
@@ -167,13 +227,25 @@ npx tgm deploy --lang zh-CN
167
227
  npx tgm status --lang zh-CN --detail
168
228
  ```
169
229
 
170
- The precedence is **`--lang` > configuration `language` > `en`**. For example, `tgm deploy --lang en` uses English once in a project configured for Chinese. `--help` and unknown commands do not load the project configuration, so add `--lang zh-CN` explicitly for Chinese help or errors in those paths. `--detail` works with either language. Low-level diagnostics and database-driver errors remain in English or their original language.
230
+ The precedence is **`--lang` > configuration `language` > `en`**. For example, `tgm deploy --lang en` uses English once in a project configured for Chinese. `--help` and unknown commands do not load the project configuration, so add `--lang zh-CN` explicitly for Chinese help or errors in those paths. `--detail` works with either language. All tool-authored explanations follow the selected language, including configuration validation, history checks, DDL limitations, locks, transaction failures and drift descriptions. SQL, identifiers, paths, commands and error codes retain their original spelling. Known upstream model errors and common driver error codes receive localized explanations. Unrecognized external errors receive a localized summary; use `--detail` to include the original diagnostic text for troubleshooting.
231
+
232
+ Model names use PascalCase, for example `model("SysUser", ...)`; a table-style name such as `sys_user` is not a valid model name. Upstream 0.0.13 accidentally prints the lowercase property-name regex in this error, although model validation requires an uppercase first letter. Model validation errors do not receive an ESM hint; only module-format failures do. Missing files or dependencies receive a path/install hint instead.
233
+
234
+ To retain the database table name `sys_user`, configure it in the fourth argument:
235
+
236
+ ```ts
237
+ export const SYS_USER = model("SysUser", "id", class {
238
+ id = prop.i64();
239
+ }, (ctx) => ctx.table("sys_user"));
240
+ ```
171
241
 
172
242
  ## Behavior
173
243
 
244
+ - **History validation:** `dev` and `deploy` reject changed or missing applied files. `dev` refuses to generate while pending files exist; apply them with `deploy` first.
245
+ - **Independent indexes and comments are not managed by models:** custom migration indexes are preserved while their columns remain. Explicit programmatic schemas may manage indexes; removing a unique index is flagged as destructive.
174
246
  - **Migration files are readable SQL:** `<migrationsDir>/<timestamp>_<name>.sql` can be edited before application. **Do not edit an applied migration.** `deploy` rejects a changed checksum; make a new migration instead.
175
- - **Destructive changes require confirmation:** dropping tables or columns and changing column types prompts by default. Non-interactive environments require `--force`.
176
- - **Post-migration checks:** `dev`, `deploy`, and `push` reread the schema and report remaining differences, for example:
247
+ - **Destructive changes require confirmation:** dropping tables or columns, changing column types, and explicit unique-index removal prompt during model synchronization; non-interactive synchronization requires `--force`. `deploy` applies reviewed SQL files without confirmation.
248
+ - **Post-migration checks:** `dev`, `deploy`, and `push` reread the schema and warn about remaining differences while retaining a successful execution exit code. `check` returns 1 for differences, including CHECK constraints whose equivalence cannot be proven. For example:
177
249
 
178
250
  ```text
179
251
  Warning: postgres/app/public differs from the model:
@@ -190,6 +262,7 @@ Original code uses [MIT](LICENSE). ts-grm uses Apache-2.0; adapted upstream stru
190
262
 
191
263
  ## More documentation
192
264
 
265
+ - [Review, custom SQL, transaction rollback, and recovery](docs/migrations.md)
193
266
  - [Compatibility and supported ts-grm versions](docs/compatibility.md)
194
267
  - [Design and migration internals](docs/design.md)
195
268
  - [Contributing](CONTRIBUTING.md)
package/dist/bin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as run, r as messages, t as parseArgs, y as MigrationAbortedError } from "./cli-hSh1xp10.mjs";
2
+ import { W as formatError, n as run, r as messages, t as parseArgs, y as MigrationAbortedError } from "./cli-vcn3DTDJ.mjs";
3
3
  //#region src/bin.ts
4
4
  async function main() {
5
5
  const argv = process.argv.slice(2);
@@ -15,7 +15,7 @@ async function main() {
15
15
  process.exitCode = 0;
16
16
  return;
17
17
  }
18
- console.error(`${m.error}: ${e.message}`);
18
+ console.error(`${m.error}: ${formatError(e, language, parseArgs(argv).flags.has("detail"))}`);
19
19
  process.exitCode = 1;
20
20
  }
21
21
  }
package/dist/bin.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.mjs","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { parseArgs, run } from \"./cli.js\";\nimport { messages, type CliLanguage } from \"./cli/messages.js\";\nimport { MigrationAbortedError } from \"./migrator.js\";\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n let language: CliLanguage = parseArgs(argv).flags.get(\"lang\") === \"zh-CN\" ? \"zh-CN\" : \"en\";\n try {\n process.exitCode = await run(argv, process.cwd(), { onLanguage: (selected) => { language = selected; } });\n } catch (e) {\n const m = messages(language);\n if (e instanceof MigrationAbortedError) {\n console.log(m.cancelled);\n process.exitCode = 0;\n return;\n }\n console.error(`${m.error}: ${(e as Error).message}`);\n process.exitCode = 1;\n }\n}\n\n// Keep the executable separate from library exports; no config/import cycle.\nvoid main();\n"],"mappings":";;;AAKA,eAAe,OAAsB;CACnC,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;CACjC,IAAI,WAAwB,UAAU,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,MAAM,UAAU,UAAU;CACtF,IAAI;EACF,QAAQ,WAAW,MAAM,IAAI,MAAM,QAAQ,IAAI,GAAG,EAAE,aAAa,aAAa;GAAE,WAAW;EAAU,EAAE,CAAC;CAC1G,SAAS,GAAG;EACV,MAAM,IAAI,SAAS,QAAQ;EAC3B,IAAI,aAAa,uBAAuB;GACtC,QAAQ,IAAI,EAAE,SAAS;GACvB,QAAQ,WAAW;GACnB;EACF;EACA,QAAQ,MAAM,GAAG,EAAE,MAAM,IAAK,EAAY,SAAS;EACnD,QAAQ,WAAW;CACrB;AACF;AAGK,KAAK"}
1
+ {"version":3,"file":"bin.mjs","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { parseArgs, run } from \"./cli.js\";\nimport { messages, type CliLanguage } from \"./cli/messages.js\";\nimport { MigrationAbortedError } from \"./migrator.js\";\nimport { formatError } from \"./diagnostics/error.js\";\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n let language: CliLanguage = parseArgs(argv).flags.get(\"lang\") === \"zh-CN\" ? \"zh-CN\" : \"en\";\n try {\n process.exitCode = await run(argv, process.cwd(), { onLanguage: (selected) => { language = selected; } });\n } catch (e) {\n const m = messages(language);\n if (e instanceof MigrationAbortedError) {\n console.log(m.cancelled);\n process.exitCode = 0;\n return;\n }\n console.error(`${m.error}: ${formatError(e, language, parseArgs(argv).flags.has(\"detail\"))}`);\n process.exitCode = 1;\n }\n}\n\n// Keep the executable separate from library exports; no config/import cycle.\nvoid main();\n"],"mappings":";;;AAMA,eAAe,OAAsB;CACnC,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;CACjC,IAAI,WAAwB,UAAU,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,MAAM,UAAU,UAAU;CACtF,IAAI;EACF,QAAQ,WAAW,MAAM,IAAI,MAAM,QAAQ,IAAI,GAAG,EAAE,aAAa,aAAa;GAAE,WAAW;EAAU,EAAE,CAAC;CAC1G,SAAS,GAAG;EACV,MAAM,IAAI,SAAS,QAAQ;EAC3B,IAAI,aAAa,uBAAuB;GACtC,QAAQ,IAAI,EAAE,SAAS;GACvB,QAAQ,WAAW;GACnB;EACF;EACA,QAAQ,MAAM,GAAG,EAAE,MAAM,IAAI,YAAY,GAAG,UAAU,UAAU,IAAI,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,GAAG;EAC5F,QAAQ,WAAW;CACrB;AACF;AAGK,KAAK"}