ts-grm-migrate 0.1.0-alpha.0 → 0.1.0-alpha.3

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 ADDED
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ English | [简体中文](docs/zh-CN/CHANGELOG.md)
4
+
5
+ ## 0.1.0-alpha.1 (pending publication)
6
+
7
+ - 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.
8
+ - Compare defaults by dialect and column type without numeric precision loss; abort on patch metadata errors; report all unproven CHECK differences.
9
+ - Repair isolated companion compatibility tests and add bilingual migration review, custom SQL, transaction recovery, and scope documentation.
10
+ - 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.
11
+ - Make CLI output concise and English by default, with `--detail` diagnostics, `--lang zh-CN` Chinese messages, and a configuration setting for the default language.
12
+ - Reduce default test output while retaining failure reasons and post-migration drift warnings.
13
+ - Remove the automatic GitHub Actions workflow; maintainers now run pre-release verification and publishing manually.
14
+ - Make English the primary documentation language and provide corresponding Simplified Chinese documents.
15
+
16
+ ## 0.1.0-alpha.0
17
+
18
+ - Add basic PostgreSQL and SQLite migrations and MySQL, SQL Server, and Oracle dialects.
19
+ - Add durable unfinished-migration state, transactional success recording, exclusive migration-file creation, and stable database locks.
20
+ - Add historical ts-grm compatibility checks, isolated package tests, and container database test scripts.
21
+ - Align the development toolchain with ts-grm, use MIT for original code, and retain third-party adaptation notices.
22
+
23
+ No stable version has been released. See the [README](README.md) for database support boundaries. Future releases will record breaking changes and recovery steps here.
@@ -0,0 +1,38 @@
1
+ # Contributing
2
+
3
+ English | [简体中文](docs/zh-CN/CONTRIBUTING.md)
4
+
5
+ This project is in alpha. When filing an issue, include a minimal model and the database, driver, Node, `@ts-grm/core`, and `@ts-grm/sql` versions. Remove credentials and application data.
6
+
7
+ ## Development and verification
8
+
9
+ The development toolchain follows ts-grm: Yarn 4.1.0, TypeScript 7, tsdown, Biome, and Vitest 4. Node `>=24.11.0` is required by the published upstream `using` syntax and the current tsdown runtime. Verify releases on Node 24.11 and the current Node 24 release. The upstream repository's Node >=18 declaration does not satisfy this project's build tools and SQLite driver.
10
+
11
+ ```sh
12
+ corepack enable
13
+ corepack yarn install --immutable
14
+ corepack yarn check
15
+ corepack yarn test:package 0.0.9
16
+ corepack yarn test:package 0.0.13
17
+ corepack yarn test:compat 0.0.9 0.0.13
18
+ corepack yarn test:postgres-mysql
19
+ corepack yarn test:servers
20
+ ```
21
+
22
+ `check` runs lint, type checking, the build, and local tests. Server tests are skipped when their database environment variables are absent, so this is not a complete database verification. The two container scripts use Podman by default; set `CONTAINER_RUNTIME=docker` to use Docker. They create temporary containers on random ports and clean up only their own resources. Allow space for the images and do not test against an application database.
23
+
24
+ `TS_GRM_TEST_VERSION=0.0.9 corepack yarn test:servers` installs that historical version in an isolated directory before running real database tests. Compatibility checks do not alter repository dependencies or the lockfile. See [compatibility](docs/compatibility.md) for the supported range and reproduction steps.
25
+
26
+ ## Changes
27
+
28
+ - A new dialect must cover model adaptation, introspection, DDL, execution, history, locking, and documentation.
29
+ - Verify the schema → SQL → introspection → diff cycle, including data preservation, failure recovery, and concurrency.
30
+ - Reject unsupported database structures explicitly instead of silently dropping them.
31
+ - Keep access to ts-grm internals in `src/vendor/ts-grm.ts`; verify candidate versions before changing the peer range.
32
+ - Keep the published package ESM and ts-grm external to the bundle so the host model registry is shared.
33
+ - Mark external implementation references with `@see` and retain applicable licenses and attribution for adopted code.
34
+ - Biome follows upstream formatting preferences. `yarn check` runs correctness lint without wholesale formatting of historical code.
35
+
36
+ Original contributions use MIT. See [third-party notices](THIRD_PARTY_NOTICES.md) for adapted code.
37
+
38
+ `yarn test:coverage` uses V8 to generate source coverage and LCOV, excluding test fixtures. Coverage from local tests alone does not represent coverage of every dialect; there is currently no global threshold based on a single coverage figure.
package/README.md CHANGED
@@ -1,50 +1,45 @@
1
1
  # ts-grm-migrate
2
2
 
3
- [ts-grm](https://github.com/babyfish-ct/ts-grm) 的数据库 schema 迁移工具 —— 像 Prisma Migrate 那样管理数据库版本,
4
- 但**模型就是你写的 ts-grm 代码**,不需要额外的 schema 文件,也没有代码生成步骤。
3
+ English | [简体中文](docs/zh-CN/README.md)
5
4
 
6
- ## 功能清单
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.
7
6
 
8
- - **增量迁移**:对比你的模型与数据库现状,生成可读的 SQL 迁移文件,并记录应用历史
9
- - **按序部署**:把所有未应用的迁移依次应用到目标库(部署 / CI 场景)
10
- - **快速同步**:快速执行迁移SQL,将数据库同步为model定义的形状
11
- - **迁移后对账**:应用完再核对数据库与模型,不一致就指出「哪个库、哪张表、差在哪」
12
- - **失败可恢复**:迁移中途失败会记入历史并阻止后续部署,用 `resolve` 修正状态后继续
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).
13
8
 
14
- ## 状态与安装
9
+ ## Features
15
10
 
16
- **Alpha / 尚未正式发布。** 当前仅承诺下表列出的验证范围;不保证任意数据库结构或历史版本兼容。
17
- 运行环境与当前 ts-grm 工具链一致:Node `>=24.11.0`、ESM。
18
- 开发使用 Yarn 4.1.0、TypeScript 7、tsdown、Biome 与 Vitest 4。
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.
14
+ - **Ordered deployment:** apply pending migration files in order, including in deployment pipelines.
15
+ - **Direct synchronization:** bring a database in line with the models without writing migration history.
16
+ - **Post-migration checks:** report schema differences that remain after applying changes.
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.
19
19
 
20
- 先在本仓库构建安装包:
20
+ ## Status and installation
21
21
 
22
- ```sh
23
- corepack yarn install --immutable
24
- corepack yarn check
25
- corepack yarn pack --out /tmp/ts-grm-migrate.tgz
26
- ```
22
+ **Alpha, published on [npm](https://www.npmjs.com/package/ts-grm-migrate).** The first release was `0.1.0-alpha.0`. Support is limited to the verified combinations and features below; arbitrary existing schemas and historical versions are not guaranteed to work.
23
+
24
+ Runtime requirements are Node `>=24.11.0` and ESM. Development uses Yarn 4.1.0, TypeScript 7, tsdown, Biome, and Vitest 4.
27
25
 
28
- 再在使用者项目中安装(以下示例使用 SQLite):
26
+ Install the migration CLI in your application. These commands match the PostgreSQL example below:
29
27
 
30
28
  ```sh
31
- npm install @ts-grm/core@0.0.13 @ts-grm/sql@0.0.13 better-sqlite3
32
- npm install -D /tmp/ts-grm-migrate.tgz
29
+ npm install @ts-grm/core@0.0.13 @ts-grm/sql@0.0.13 pg
30
+ npm install -D ts-grm-migrate@next
33
31
  ```
34
32
 
35
- - core/sql 是 peerDependencies,请使用**相同版本**;当前支持 `>=0.0.9 <0.0.14`。
36
- 这是已验证范围,不自动承诺未来版本;验证方法见 [兼容性](docs/compatibility.md)。
37
- - 数据库驱动按需安装,完整列表见下方支持表。
38
- - 安装后使用 `npx tgm`,或通过包管理器运行 `tgm` / `ts-grm-migrate`。
39
- - npm 发布步骤见 [发布](docs/releasing.md)。
33
+ - `@ts-grm/core` and `@ts-grm/sql` are peer dependencies and must use the **same version**. The verified range is `>=0.0.9 <0.0.14`; see [compatibility](docs/compatibility.md) before changing it.
34
+ - Install only the database driver you need; the supported drivers are listed below.
35
+ - `@next` follows prereleases. Pin an exact version when reproducibility matters, for example `ts-grm-migrate@0.1.0-alpha.0`.
36
+ - Run the installed CLI with `npx tgm`, or use `tgm` / `ts-grm-migrate` through your package manager.
40
37
 
41
- ## 快速开始
38
+ ## Quick start
42
39
 
43
- > **前置:项目需是 ESM** —— 给 `package.json` 加上 `"type": "module"`。
44
- > ts-grm 的模型注册表是**模块级单例**,migrate 必须与你的模型共用同一份 **ESM** 实例;
45
- > 若模型是 CommonJS,它会把模型注册到另一份实例上,migrate 看不到任何模型。
40
+ > **Your project must use ESM.** Set `"type": "module"` in `package.json`. The ts-grm model registry is a module-level singleton; the migration tool and your models must share the same ESM instance. CommonJS models may register with a separate instance and be invisible to the migration tool.
46
41
 
47
- 在项目根建一个配置文件:
42
+ Create a configuration file in your project root:
48
43
 
49
44
  ```ts
50
45
  // ts-grm-migrate.config.ts
@@ -53,50 +48,102 @@ import { defineConfig } from "ts-grm-migrate";
53
48
  export default defineConfig({
54
49
  dialect: "postgres",
55
50
  database: { host: "localhost", database: "app", user: "postgres" },
56
- models: ["./src/models"], // 交给 ts-grm 加载你的模型(.ts 或编译后的 .js)
51
+ models: ["./src/models"], // ts-grm loads these .ts files or compiled .js files
52
+ // language: "zh-CN", // Optional: use Chinese for this project's CLI output
57
53
  });
58
54
  ```
59
55
 
60
- 然后:
56
+ Then run:
61
57
 
62
58
  ```sh
63
- tgm dev -n init # 对比模型与数据库,生成并应用第一个迁移
64
- tgm dev # 不写名字也行:迁移只用时间戳命名
65
- tgm status # 看看应用了哪些、还剩哪些
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
63
+ npx tgm dev # Omit the name to use only a timestamp
64
+ npx tgm status # Inspect applied and pending migrations
65
+ ```
66
+
67
+ ### Configuration
68
+
69
+ - **`dialect`:** `postgres`, `sqlite`, `mysql`, `mssql`, or `oracle`; defaults to `postgres`. It selects the driver, schema introspection, SQL generation, and execution. See the support table below.
70
+ - **`database` (required):** connection settings; fields depend on the dialect.
71
+ - **`models` (required):** model files or directories relative to the project root, starting with `./` or `../`. They must be ESM: declare `"type": "module"` or point to compiled ESM `.js` files.
72
+ - `language`: project default for CLI output, `en` or `zh-CN`; defaults to `en`. `--lang` overrides it for one command.
73
+ - `migrationsDir`: migration file directory; defaults to `./src/ts-grm`.
74
+ - `schema`: target schema; defaults to `public` on PostgreSQL, `dbo` on SQL Server, and the login user's schema on Oracle.
75
+ - `lockPath`: process lock file; defaults to `./.ts-grm-migrate.lock`.
76
+
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"`.
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
+ );
66
108
  ```
67
109
 
68
- ### 配置项
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:
69
121
 
70
- - **`dialect`**:数据库方言,可选 `postgres`、`sqlite`、`mysql`、`mssql`、`oracle`,默认 `postgres`。
71
- 它决定使用哪个数据库驱动,以及结构读取、SQL 生成和迁移执行的具体实现;各方言的驱动依赖与支持范围见下表。
72
- - **`database`**(必填):数据库连接,字段含义随方言变化,见下文示例
73
- - **`models`**(必填):模型文件或目录,相对项目根,必须写成 `./xxx` 或 `../xxx`。
74
- **必须是 ESM** —— 项目声明 `"type": "module"`,或指向编译后的 ESM 产物(`.js`)
75
- - `migrationsDir`:迁移文件目录,默认 `./src/ts-grm`
76
- - `schema`:目标 schema,PostgreSQL 默认 `public`,SQL Server 默认 `dbo`,Oracle 默认登录用户
77
- - `lockPath`:进程锁文件,默认 `./.ts-grm-migrate.lock`
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`.
78
126
 
79
- 配置文件在项目根自动查找(`.ts` / `.mts` / `.mjs` / `.js`),也可以用 `--config <path>` 指定。
80
- `.ts` 的模块类型跟随项目:CommonJS 项目请用 `.mts`,或给 `package.json` 加 `"type": "module"`。
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.
81
128
 
82
- ## 数据库支持与配置
129
+ ## Databases and configuration
83
130
 
84
- | `dialect` | 驱动依赖 | 支持范围 |
131
+ | `dialect` | Driver dependency | Supported scope |
85
132
  | --- | --- | --- |
86
- | `postgres`(默认) | `pg` | PostgreSQL,schema 默认 `public` |
87
- | `sqlite` | `better-sqlite3` | 基础迁移;需要重建表的变更尚未实现 |
88
- | `mysql` | `mysql2` | MySQL 8.0.16+ / InnoDB,`lower_case_table_names=0` |
89
- | `mssql` | `mssql` | SQL Server 2016+,schema 默认 `dbo`;已验证 SQL Server 2022 |
90
- | `oracle` | `oracledb` | Oracle 19c+,schema 默认登录用户;已验证 Oracle Free 23 |
133
+ | `postgres` (default) | `pg` | PostgreSQL; default schema `public` |
134
+ | `sqlite` | `better-sqlite3` | Basic migrations; table rebuilds are not implemented |
135
+ | `mysql` | `mysql2` | MySQL 8.0.16+, InnoDB, `lower_case_table_names=0` |
136
+ | `mssql` | `mssql` | SQL Server 2016+; default schema `dbo`; tested on SQL Server 2022 |
137
+ | `oracle` | `oracledb` | Oracle 19c+; default schema is the login user; tested on Oracle Free 23 |
91
138
 
92
- SQL Server 示例:
139
+ SQL Server example:
93
140
 
94
141
  ```ts
95
142
  export default defineConfig({
96
143
  dialect: "mssql",
97
144
  database: {
98
145
  host: "localhost", port: 1433, database: "app", user: "app", password: process.env.DB_PASSWORD,
99
- // 本地自签名测试证书可启用;生产环境默认校验证书。
146
+ // Use only for local tests with self-signed certificates; production validates certificates by default.
100
147
  trustServerCertificate: true,
101
148
  },
102
149
  schema: "dbo",
@@ -104,7 +151,7 @@ export default defineConfig({
104
151
  });
105
152
  ```
106
153
 
107
- Oracle 示例(Thin mode,无需安装 Oracle Client):
154
+ Oracle example (Thin mode; no Oracle Client installation needed):
108
155
 
109
156
  ```ts
110
157
  export default defineConfig({
@@ -117,121 +164,99 @@ export default defineConfig({
117
164
  });
118
165
  ```
119
166
 
120
- Oracle `database.database` 表示 service name,也可用 `host` / `port` / `database` 代替
121
- `connectionString`。Oracle schema 必须已存在;SQL Server 会创建尚不存在的目标 schema。
122
- SQL Server 和 Oracle 的自动生成 DDL 与历史表均限定目标 schema,避免读写落在不同命名空间。
167
+ For Oracle, `database.database` is the service name. You can provide `host`, `port`, and `database` instead of `connectionString`. The Oracle schema must already exist; SQL Server creates a missing target schema. Generated DDL and migration history on both dialects are scoped to that schema.
123
168
 
124
- Oracle 用户需要 `CREATE SESSION`、`CREATE TABLE`、表空间配额;创建 identity 列还需要
125
- `CREATE SEQUENCE`。数据库锁使用 `DBMS_LOCK`,需由 DBA 授权:
169
+ The Oracle user needs `CREATE SESSION`, `CREATE TABLE`, and a tablespace quota. Identity columns also require `CREATE SEQUENCE`. A DBA must grant access to `DBMS_LOCK` for database locking:
126
170
 
127
171
  ```sql
128
172
  GRANT EXECUTE ON SYS.DBMS_LOCK TO APP;
129
173
  ```
130
174
 
131
- MySQL / Oracle 的 DDL 会隐式提交,失败可能留下部分改动。`resolve --rolled-back` 仅修改历史状态,
132
- **不会撤销 SQL**;应先手工恢复数据库再重试,或补完 SQL 后 `resolve --applied`。
133
- PostgreSQL、SQLite、SQL Server 在同一事务内执行迁移 SQL 并记录成功,记账失败也会回滚。
134
- 所有方言都会在执行前持久化未完成记录;进程中断、连接丢失或记账失败后会阻止自动重放,
135
- 需检查数据库实际状态,再使用 `resolve`。未完成记录在 `status` 中显示为 failed。
136
- `status` 仅将确认不存在的历史表视为空历史,连接和权限错误会向上传递;Oracle 跨 schema
137
- 的 ORA-00942 无法区分缺表与无权限,因此保留错误。
138
-
139
- 新迁移 ID 使用毫秒时间戳,并在本地锁内保证晚于已有生成时间戳;文件使用独占创建,
140
- 遇到已有同名文件会报错,不覆盖历史 SQL。PostgreSQL 数据库锁按数据库和当前 schema
141
- 限定固定资源名,不依赖 checkout 的本地路径。
142
-
143
- 当前边界:
144
-
145
- - SQL Server / Oracle 支持普通表、列、主键、唯一约束、外键、CHECK 和普通索引;
146
- 修改 identity 策略、自动重命名及复杂表重建不支持。
147
- - SQL Server 的计算/隐藏/稀疏列、temporal/memory-optimized 表、自定义聚集约束布局、
148
- 降序/INCLUDE/特殊索引会明确拒绝。
149
- - Oracle 的虚拟/隐藏列、IOT/嵌套/临时表、特殊/表达式/降序索引、延迟约束会明确拒绝。
150
- - 两者目前不支持跨 schema 外键及未启用/未验证的约束。CHECK 只做保守的格式归一化,
151
- 不承诺任意两种等价表达式都能匹配。
152
- - Oracle 迁移文件支持以分号分隔的 SQL,正确保留字符串、标识符、注释中的分号;
153
- PL/SQL、SQL*Plus 指令暂不支持,会在执行文件前拒绝。SQL Server 文件使用 SQL 批次,
154
- 不支持客户端的 `GO` 分隔符。
155
- - MySQL 暂不支持 MariaDB、生成列、隐藏列及特殊索引。
156
-
157
- ### 容器集成测试
175
+ MySQL and Oracle DDL commits implicitly and may leave partial changes after failure. `resolve --rolled-back` changes **history only**; it does not undo SQL. Restore the database manually before retrying, or complete the SQL and use `resolve --applied`.
176
+
177
+ PostgreSQL, SQLite, and SQL Server execute migration SQL and record success in one transaction, so a failure to record success rolls back the SQL. Every dialect persists an unfinished attempt before execution. A crash, lost connection, or history-write failure blocks automatic replay until you inspect the database and use `resolve`. `status` shows unfinished attempts as failed. It treats only a confirmed missing history table as empty history; connection and permission errors propagate. Oracle's ORA-00942 cannot reliably distinguish a missing table from lack of access across schemas, so that error is preserved.
178
+
179
+ New migration IDs use millisecond timestamps and advance past existing IDs while holding the local lock. Files are created exclusively; an existing filename causes an error instead of overwriting historical SQL. PostgreSQL uses a fixed database lock resource scoped to the database and current schema, independent of the checkout path.
180
+
181
+ Current limits:
182
+
183
+ - SQL Server and Oracle support ordinary tables, columns, primary keys, unique constraints, foreign keys, CHECK constraints, and ordinary indexes. Identity strategy changes, automatic renames, and complex table rebuilds are unsupported.
184
+ - SQL Server explicitly rejects computed, hidden, and sparse columns; temporal and memory-optimized tables; custom clustered constraint layouts; and descending, INCLUDE, or special indexes.
185
+ - Oracle explicitly rejects virtual and hidden columns; index-organized, nested, and temporary tables; special, expression, and descending indexes; and deferred constraints.
186
+ - Both reject cross-schema foreign keys and disabled or unvalidated constraints. CHECK expressions receive conservative normalization; equivalent expressions are not guaranteed to compare as equal.
187
+ - Oracle migration files may contain semicolon-separated SQL, including semicolons inside strings, identifiers, and comments. PL/SQL and SQL*Plus directives are rejected before execution. SQL Server files use SQL batches; the client-side `GO` separator is unsupported.
188
+ - MySQL support does not include MariaDB, generated or hidden columns, or special indexes.
189
+
190
+ ### Container integration tests
158
191
 
159
192
  ```sh
160
193
  corepack yarn install
161
194
  corepack yarn test:servers
162
195
  ```
163
196
 
164
- 脚本默认用 Podman 启动 SQL Server Developer 与 Oracle Free(`CONTAINER_RUNTIME=docker` 可切换 Docker),随机分配仅监听 `127.0.0.1` 的端口,
165
- 在独立 schema/用户中验证迁移、数据保留、锁、失败恢复与 CLI,完成后清理本次容器和数据卷。
166
- MySQL 集成测试始终创建随机专属数据库并清理,不使用 `MYSQL_DATABASE`;测试账号需要建库权限。
167
- 可通过 `MSSQL_TEST_IMAGE` / `ORACLE_TEST_IMAGE` 指定镜像。首次拉取镜像需要网络及足够磁盘空间。
168
- SQL Server Developer 的测试用途受其许可条款约束,脚本用 `ACCEPT_EULA=Y` 启动。
197
+ By default, the script starts SQL Server Developer and Oracle Free with Podman (`CONTAINER_RUNTIME=docker` selects Docker). It binds random ports to `127.0.0.1`, tests migrations, data preservation, locks, recovery, and the CLI in isolated schemas or users, then removes its containers and volumes. MySQL integration tests create and remove their own randomly named database rather than using `MYSQL_DATABASE`; the test account needs database-creation permission.
169
198
 
170
- 也可对专用测试实例设置 `MSSQL_HOST/PORT/USER/PASSWORD/DATABASE` 或
171
- `ORACLE_HOST/PORT/PASSWORD/DATABASE`,运行 `tests/server-integration.test.ts`。
172
- Oracle 测试使用 SYSTEM 创建临时用户,需要该账户拥有 `DBMS_LOCK` 的转授权权限;
173
- 这些权限仅供测试环境使用。未设置对应 `*_HOST` 时,集成测试会跳过。
199
+ Set `MSSQL_TEST_IMAGE` or `ORACLE_TEST_IMAGE` to select images. The first run needs network access and enough disk space. SQL Server Developer testing is subject to its license terms; the script starts it with `ACCEPT_EULA=Y`.
174
200
 
175
- ## 命令
201
+ You can also run `tests/server-integration.test.ts` against dedicated instances by setting `MSSQL_HOST/PORT/USER/PASSWORD/DATABASE` or `ORACLE_HOST/PORT/PASSWORD/DATABASE`. Oracle tests use SYSTEM to create temporary users, so SYSTEM needs permission to grant `DBMS_LOCK` to them. Those privileges are for test environments only. Integration tests skip when the corresponding `*_HOST` is unset.
176
202
 
177
- | 命令 | 用途 |
203
+ ## Commands
204
+
205
+ | Command | Purpose |
178
206
  | --- | --- |
179
- | `tgm dev [-n <名字>]` | 对比模型与数据库,生成并应用一个迁移(开发用;名字可省略,省略时只用时间戳命名) |
180
- | `tgm deploy` | 应用所有未应用的迁移(部署 / CI 用,无交互) |
181
- | `tgm push [--force]` | 直接同步成模型的样子,不写文件、不记历史 |
182
- | `tgm status` | 查看已应用 / 待应用的迁移 |
183
- | `tgm resolve --applied <id>` | 把迁移标记为已应用(SQL 已手工执行过) |
184
- | `tgm resolve --rolled-back <id>` | 清除失败记录,让它重新待应用 |
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 |
210
+ | `tgm deploy` | Apply pending migrations in order without interaction |
211
+ | `tgm push [--force]` | Sync the database to the models without a file or history record |
212
+ | `tgm status` | Show applied and pending migrations |
213
+ | `tgm resolve --applied <id>` | Mark SQL already executed manually as applied |
214
+ | `tgm resolve --rolled-back <id>` | Mark an attempt as rolled back so it becomes pending again |
185
215
 
186
- 选项:`--config <path>` 指定配置文件、`-n` / `--name <名字>` 给迁移命名、`--force` 破坏性变更不询问、`-h` 显示帮助。
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.
187
217
 
188
- ## 行为约定
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.
189
219
 
190
- - **迁移文件是人可读的 SQL**:`<migrationsDir>/<时间戳>_<名字>.sql`,可以手工编辑。
191
- 但**已应用的迁移不能再改** —— 内容一旦变动,后续 `deploy` 会因 checksum 不匹配而拒绝继续
192
- - **破坏性变更会先问**:删表 / 删列 / 改列类型默认交互确认;非交互环境(CI)需显式加 `--force`
193
- - **迁移后自动对账**:`dev` / `deploy` / `push` 完成后会再读一次数据库与模型比对,
194
- 仍有差异就报出具体位置,例如:
220
+ ### Output language
195
221
 
196
- ```
197
- ⚠ 对账发现数据库与模型不一致(库 app,schema public):
198
- - 表 AUTHOR:多出列 LEGACY
199
- 这通常意味着迁移未完整生效,或数据库被手工改动过。
200
- ```
222
+ The CLI defaults to English and does not switch based on the system's `LANG`. Set `language: "zh-CN"` in `defineConfig({...})` to make Chinese the project default. To use Chinese for a single command:
201
223
 
202
- - **并发防护**:同一项目上的多个 migrate 实例由进程锁文件挡住;多机部署时再由数据库的
203
- advisory lock 兜底
204
- - **`schema` 是全局生效的**:同时作用于结构读取与 DDL 执行(PostgreSQL `search_path`,SQL Server / Oracle 限定表名),
205
- 不会出现「读了 A schema、却往 B schema 写」的情况
224
+ ```sh
225
+ npx tgm --help --lang zh-CN
226
+ npx tgm deploy --lang zh-CN
227
+ npx tgm status --lang zh-CN --detail
228
+ ```
206
229
 
207
- ## 为什么是 peer 依赖
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. Low-level diagnostics and database-driver errors remain in English or their original language.
208
231
 
209
- migrate 是 ts-grm 的插件,必须与你项目里的 ts-grm **共用同一份实例**:ts-grm 的模型注册表是
210
- 模块级单例,若 migrate 自带一份 `@ts-grm/core`,它看到的是空注册表,拿不到你定义的任何模型。
232
+ ## Behavior
211
233
 
212
- 因此 `@ts-grm/core` / `@ts-grm/sql` 声明为 peerDependencies,由你的项目提供。
234
+ - **History validation:** `dev` and `deploy` reject changed or missing applied files. `dev` refuses to generate while pending files exist; apply them with `deploy` first.
235
+ - **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.
236
+ - **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.
237
+ - **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.
238
+ - **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:
213
239
 
214
- ## 开发与协作
240
+ ```text
241
+ Warning: postgres/app/public differs from the model:
242
+ - Table AUTHOR: Extra column LEGACY
243
+ Check for a partial migration or manual database changes.
244
+ ```
215
245
 
216
- ```sh
217
- corepack yarn check
218
- corepack yarn test:compat 0.0.9 0.0.13
219
- corepack yarn test:package 0.0.9
220
- corepack yarn test:postgres-mysql
221
- corepack yarn test:servers
222
- ```
246
+ - **Concurrency protection:** a process lock prevents parallel migrations in one project; a database lock protects deployments across machines.
247
+ - **Target schema applies to reads and writes:** PostgreSQL uses `search_path`, while SQL Server and Oracle qualify target tables. This prevents introspection and DDL from targeting different schemas.
223
248
 
224
- GitHub CI 分别运行本地检查、历史依赖/安装包测试、真实数据库测试;本地缺少数据库环境变量时
225
- 相关测试会跳过,因此不能仅凭 `yarn test` 绿色判断全部数据库通过。
249
+ ## License
226
250
 
227
- - [贡献指南](CONTRIBUTING.md)
228
- - [安全报告](SECURITY.md)
229
- - [变更记录](CHANGELOG.md)
230
- - [设计](docs/design.md):代码分层、差分规则与失败恢复
231
- - [兼容性](docs/compatibility.md):ts-grm 版本范围及复现命令
232
- - [发布](docs/releasing.md):npm 发布前检查
251
+ Original code uses [MIT](LICENSE). ts-grm uses Apache-2.0; adapted upstream structure types retain their license and attribution. See [third-party notices](THIRD_PARTY_NOTICES.md).
233
252
 
234
- ## 许可证
253
+ ## More documentation
235
254
 
236
- 原创代码采用 [MIT](LICENSE)。ts-grm 使用 Apache-2.0;本项目改写的上游结构类型保留其许可与署名,
237
- 见[第三方声明](THIRD_PARTY_NOTICES.md)。
255
+ - [Review, custom SQL, transaction rollback, and recovery](docs/migrations.md)
256
+ - [Compatibility and supported ts-grm versions](docs/compatibility.md)
257
+ - [Design and migration internals](docs/design.md)
258
+ - [Contributing](CONTRIBUTING.md)
259
+ - [Security and support](SECURITY.md)
260
+ - [Release process](docs/releasing.md)
261
+ - [Changelog](CHANGELOG.md)
262
+ - [Third-party notices](THIRD_PARTY_NOTICES.md)
package/SECURITY.md ADDED
@@ -0,0 +1,9 @@
1
+ # Security and support
2
+
3
+ English | [简体中文](docs/zh-CN/SECURITY.md)
4
+
5
+ This project is in alpha. Only the current development branch is maintained, and no production support lifecycle is promised. Database migrations change schema and data; review generated SQL and verify it in a recoverable environment before release.
6
+
7
+ To report a vulnerability, use the repository's private GitHub Security reporting option once it is enabled. Do not post credentials, application data, or directly exploitable details in a public issue. Until a private channel is available, file only a non-sensitive request to contact the maintainers so they can establish one.
8
+
9
+ Maintainers should enable Private vulnerability reporting on GitHub and configure branch protection according to their collaboration model. Repository files cannot replace GitHub account settings. No response time is currently promised.
@@ -1,17 +1,15 @@
1
1
  # Third-party notices
2
2
 
3
- 本项目原创代码使用 MIT,见 [LICENSE](LICENSE)。依赖和适配部分保留其各自许可证。
3
+ English | [简体中文](docs/zh-CN/THIRD_PARTY_NOTICES.md)
4
+
5
+ Original code in this project is under the [MIT license](LICENSE). Dependencies and adapted portions retain their respective licenses.
4
6
 
5
7
  ## ts-grm
6
8
 
7
- `src/vendor/ts-grm.ts` 中的 `TableDef`、`ColumnDef` 和约束类型声明改写自 ts-grm 的
8
- `schema_def.ts`:保留迁移器需要的字段,调整类型名称和引用,并添加本项目的适配接口及实现。
9
- 上游文件署名为陈涛 (Chen Tao),上游包标记为 Apache-2.0。改写部分保留其许可与署名;
10
- 本项目其余原创代码使用 MIT。
9
+ The `TableDef`, `ColumnDef`, and constraint type declarations in `src/vendor/ts-grm.ts` were adapted from ts-grm's `schema_def.ts`. They retain the fields needed by the migrator, change type names and references, and add this project's adapter interfaces and implementation. The upstream file credits Chen Tao, and the upstream package is licensed under Apache-2.0. The adapted portion retains that license and attribution; the project's other original code uses MIT.
11
10
 
12
11
  - @see https://github.com/babyfish-ct/ts-grm/blob/fe78eb6c323bf335ff23650a414856eb36bfbce7/packages/sql/src/impl/schema_def.ts
13
12
  - @see https://github.com/babyfish-ct/ts-grm/blob/fe78eb6c323bf335ff23650a414856eb36bfbce7/packages/sql/package.json
14
- - [Apache-2.0 全文](LICENSES/Apache-2.0.txt)
13
+ - [Full Apache-2.0 license](LICENSES/Apache-2.0.txt)
15
14
 
16
- 发布包将 `@ts-grm/core` 和 `@ts-grm/sql` 保留为外部 peerDependencies,不嵌入上游实现。
17
- 其他数据库驱动也为外部依赖,其许可证由各自包提供。
15
+ The published package keeps `@ts-grm/core` and `@ts-grm/sql` as external peer dependencies; it does not bundle upstream implementations. Database drivers are external dependencies with their own licenses.
package/dist/bin.mjs CHANGED
@@ -1,16 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { n as run, v as MigrationAbortedError } from "./cli-C-KYDbI_.mjs";
2
+ import { n as run, r as messages, t as parseArgs, y as MigrationAbortedError } from "./cli-CMBM5t1z.mjs";
3
3
  //#region src/bin.ts
4
4
  async function main() {
5
+ const argv = process.argv.slice(2);
6
+ let language = parseArgs(argv).flags.get("lang") === "zh-CN" ? "zh-CN" : "en";
5
7
  try {
6
- process.exitCode = await run(process.argv.slice(2), process.cwd());
8
+ process.exitCode = await run(argv, process.cwd(), { onLanguage: (selected) => {
9
+ language = selected;
10
+ } });
7
11
  } catch (e) {
12
+ const m = messages(language);
8
13
  if (e instanceof MigrationAbortedError) {
9
- console.log("已取消。");
14
+ console.log(m.cancelled);
10
15
  process.exitCode = 0;
11
16
  return;
12
17
  }
13
- console.error(`错误:${e.message}`);
18
+ console.error(`${m.error}: ${e.message}`);
14
19
  process.exitCode = 1;
15
20
  }
16
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 { run } from \"./cli.js\";\nimport { MigrationAbortedError } from \"./migrator.js\";\n\nasync function main(): Promise<void> {\n try {\n process.exitCode = await run(process.argv.slice(2), process.cwd());\n } catch (e) {\n if (e instanceof MigrationAbortedError) {\n console.log(\"已取消。\");\n process.exitCode = 0;\n return;\n }\n console.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":";;;AAIA,eAAe,OAAsB;CACnC,IAAI;EACF,QAAQ,WAAW,MAAM,IAAI,QAAQ,KAAK,MAAM,CAAC,GAAG,QAAQ,IAAI,CAAC;CACnE,SAAS,GAAG;EACV,IAAI,aAAa,uBAAuB;GACtC,QAAQ,IAAI,MAAM;GAClB,QAAQ,WAAW;GACnB;EACF;EACA,QAAQ,MAAM,MAAO,EAAY,SAAS;EAC1C,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\";\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"}