ts-grm-migrate 0.1.0-alpha.5 → 0.1.0-alpha.6

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,6 +2,11 @@
2
2
 
3
3
  English | [简体中文](docs/zh-CN/CHANGELOG.md)
4
4
 
5
+ ## 0.1.0-alpha.6 (pending publication)
6
+
7
+ - Add explicit `tgm seed` with executable/argument configuration, literal argument forwarding after `--`, local binary lookup, inherited environment and terminal I/O, exit-code propagation and interruption handling.
8
+ - Keep seeding independent of migration runtime, schema changes and history; add bilingual examples and subprocess/SQLite integration tests.
9
+
5
10
  ## 0.1.0-alpha.4 (pending publication)
6
11
 
7
12
  - Localize configuration, history, locking, DDL, transaction and drift explanations throughout the CLI; preserve technical identifiers and expose original external diagnostics with `--detail`.
package/README.md CHANGED
@@ -81,9 +81,58 @@ npx tgm status # Inspect applied and pending migrations
81
81
  - `migrationsDir`: migration file directory; defaults to `./src/ts-grm`.
82
82
  - `schema`: target schema; defaults to `public` on PostgreSQL, `dbo` on SQL Server, and the login user's schema on Oracle.
83
83
  - `lockPath`: process lock file; defaults to `./.ts-grm-migrate.lock`.
84
+ - `seed`: optional `{ command: string, args?: string[] }` executable for `tgm seed`; see below.
84
85
 
85
86
  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"`.
86
87
 
88
+ ## Database seeding
89
+
90
+ Add an optional `seed` executable and argument array to your existing configuration:
91
+
92
+ ```ts
93
+ seed: {
94
+ command: "node",
95
+ args: ["./src/ts-grm/seed.ts"],
96
+ },
97
+ ```
98
+
99
+ Run it explicitly after deploying the schema:
100
+
101
+ ```sh
102
+ npx tgm deploy && npx tgm seed
103
+ npx tgm seed -- --environment development
104
+ ```
105
+
106
+ The script can use your application's ts-grm client factory or a database driver. Reuse the same connection settings and target schema as the application. For example, with the PostgreSQL quick-start configuration and an `app_role(code, label)` table created by a migration in `public`:
107
+
108
+ ```ts
109
+ // src/ts-grm/seed.ts
110
+ import { Pool } from "pg";
111
+ import config from "../../ts-grm-migrate.config.ts";
112
+
113
+ const pool = new Pool(config.database);
114
+ try {
115
+ await pool.query(
116
+ `insert into app_role(code, label) values ($1, $2)
117
+ on conflict(code) do update set label = excluded.label`,
118
+ ["reader", "Reader"],
119
+ );
120
+ } finally {
121
+ await pool.end();
122
+ }
123
+ ```
124
+
125
+ - `command` is an executable, not a shell command string. Put each argument in `args`; quotes, spaces and shell characters are passed literally. Local `node_modules/.bin` directories in the project and its ancestors are searched before the inherited PATH. On Windows, use a native executable such as `node` with the runner's JavaScript entry point rather than a `.cmd`/`.bat` wrapper.
126
+ - All relative paths use the CLI working directory, including when `--config` selects a file elsewhere. The script inherits environment variables and terminal input/output. The CLI does not load `.env` automatically; load it in the configuration/script or launch with your environment configured.
127
+ - Node runs TypeScript supported by native type stripping; use a compiled ESM script or your installed TypeScript runner when additional transformations or path aliases are needed.
128
+ - Arguments after `--` are appended verbatim to the configured arguments. The script chooses how to parse them, including environment or dataset selection.
129
+ - Every invocation runs the script. Migration commands do not seed automatically; seed creates no migration history or locks. The script owns connection cleanup, transactions, dependency order and idempotency. Concurrent seed runs and runs overlapping migrations must be coordinated by the application or deployment workflow.
130
+ - A missing seed configuration, startup error or interruption fails the command. Numeric script exit codes are retained; SIGINT/SIGTERM return 130/143. On POSIX, these signals reach the seed process group; a process that does not exit is killed after five seconds. On Windows, interruption terminates the immediate seed process; descendant cleanup depends on the runner.
131
+
132
+ Use migration SQL for one-time data changes tied to a schema version. Use seed for repeatable initialization. This separation follows [Prisma's explicit seeding workflow](https://docs.prisma.io/docs/orm/v7/prisma-migrate/workflows/seeding).
133
+
134
+ Programmatic callers can use `runSeed(seed, cwd, args?)`, which returns the exit code, inherits process I/O and temporarily handles SIGINT/SIGTERM. It does not create a migration runtime.
135
+
87
136
  ## Defaults and auto-increment (optional)
88
137
 
89
138
  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:
package/dist/bin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { K as formatError, n as run, r as messages, t as parseArgs, y as MigrationAbortedError } from "./cli-Cfr6e9vX.mjs";
2
+ import { b as MigrationAbortedError, n as run, q as formatError, r as messages, t as parseArgs } from "./cli-BlCk2tT8.mjs";
3
3
  //#region src/bin.ts
4
4
  async function main() {
5
5
  const argv = process.argv.slice(2);
@@ -6,9 +6,19 @@ import { pathToFileURL } from "node:url";
6
6
  import { MySqlDriver, OracleDriver, OraclePool, PostgresDriver, SqlServerDriver, SqlServerPool, SqliteDriver, newSqlClient } from "@ts-grm/sql";
7
7
  import { EntityManager } from "@ts-grm/core";
8
8
  import { createInterface } from "node:readline/promises";
9
+ import { spawn } from "node:child_process";
10
+ import { constants } from "node:os";
9
11
  //#region src/diagnostics/catalog.ts
10
12
  /** Paired diagnostic templates. Values such as paths, SQL and identifiers are not translated. */
11
13
  const diagnostics = {
14
+ seed_config: {
15
+ en: "Invalid seed configuration. Expected { command: \"node\", args: [\"./src/ts-grm/seed.ts\"] }: command must be non-empty and args must be strings without null bytes.",
16
+ "zh-CN": "seed 配置无效。应为 { command: \"node\", args: [\"./src/ts-grm/seed.ts\"] }:command 必须为非空字符串,args 必须为字符串数组,且不能包含空字符。"
17
+ },
18
+ seed_start: {
19
+ en: "Cannot start seed executable \"{0}\": {1}. Check the executable, working directory and installed dependencies.",
20
+ "zh-CN": "无法启动 seed 可执行文件 \"{0}\":{1}。请检查可执行文件、工作目录及已安装的依赖。"
21
+ },
12
22
  lock_lost: {
13
23
  en: "Migration lease ownership changed: {0}. The replacement lease was not removed.",
14
24
  "zh-CN": "迁移租约所有权已改变:{0}。未删除替代租约。"
@@ -1094,22 +1104,6 @@ function checkKey(expression, dialect, types) {
1094
1104
  }
1095
1105
  return JSON.stringify(tokens.map((t) => t.startsWith("'") ? t : t.startsWith("\"") ? `id:${identifier(t, dialect)}` : /^[A-Za-z_$][\w$]*$/.test(t) ? /^(?:and|or|not|in|is|null|true|false|any|array|case|when|then|else|end|collate)$/i.test(t) ? `keyword:${t.toLowerCase()}` : `id:${identifier(t, dialect)}` : t));
1096
1106
  }
1097
- /** Extract CHECK bodies with balanced tokens, including nested expressions and quoted delimiters. */
1098
- function sqliteChecks(sql) {
1099
- const tokens = sqlTokens(sql), result = [];
1100
- for (let i = 0; i < tokens.length; i++) {
1101
- if (tokens[i]?.toLowerCase() !== "check" || tokens[i + 1] !== "(") continue;
1102
- let depth = 1, end = i + 2;
1103
- for (; end < tokens.length && depth; end++) {
1104
- if (tokens[end] === "(") depth++;
1105
- if (tokens[end] === ")") depth--;
1106
- }
1107
- if (depth) throw diagnostic("sqlite_check_parse");
1108
- result.push(tokens.slice(i + 2, end - 1).join(" "));
1109
- i = end - 1;
1110
- }
1111
- return result;
1112
- }
1113
1107
  //#endregion
1114
1108
  //#region src/schema/defaults.ts
1115
1109
  /** Compare catalog forms conservatively: casts inside expressions retain their semantics. */
@@ -2030,9 +2024,7 @@ var SqliteIntrospector = class {
2030
2024
  const tables = [];
2031
2025
  for (const row of tableRows.rows) {
2032
2026
  const name = asString$1(row["name"]);
2033
- const definitionTokens = sqlTokens(asString$1(row["sql"])).filter((token) => token !== ";");
2034
- if (definitionTokens.some((token, i) => token.toLowerCase() === "deferrable" && definitionTokens[i - 1]?.toLowerCase() !== "not" || token.toLowerCase() === "collate" || token.toLowerCase() === "virtual" && definitionTokens[i + 1]?.toLowerCase() === "table") || definitionTokens.slice(-2).join(" ").toLowerCase() === "without rowid" || definitionTokens.at(-1)?.toLowerCase() === "strict") throw diagnostic("unsupported_structure", name, diagnostic("structure_table"));
2035
- const autoIncrement = definitionTokens.some((token) => token.toLowerCase() === "autoincrement");
2027
+ const autoIncrement = /\bautoincrement\b/i.test(asString$1(row["sql"] ?? ""));
2036
2028
  const { columns, primaryKey } = await this._columns(name, autoIncrement);
2037
2029
  const foreignKeys = await this._foreignKeys(name);
2038
2030
  const { uniques, indexes } = await this._indexes(name);
@@ -2042,14 +2034,7 @@ var SqliteIntrospector = class {
2042
2034
  constraints: [
2043
2035
  ...primaryKey,
2044
2036
  ...uniques,
2045
- ...foreignKeys,
2046
- ...sqliteChecks(asString$1(row["sql"])).map((expression) => ({
2047
- kind: "CHECK",
2048
- name: void 0,
2049
- expression,
2050
- values: [],
2051
- implicit: void 0
2052
- }))
2037
+ ...foreignKeys
2053
2038
  ],
2054
2039
  indexes
2055
2040
  });
@@ -2065,8 +2050,7 @@ var SqliteIntrospector = class {
2065
2050
  * 据此还原主键并保持列序。
2066
2051
  */
2067
2052
  async _columns(table, autoIncrement) {
2068
- const { rows } = await this._options.query.query(`pragma table_xinfo(${quoteForPragma(table)})`);
2069
- if (rows.some((row) => Number(row["hidden"] ?? 0) !== 0)) throw diagnostic("unsupported_structure", table, diagnostic("structure_column"));
2053
+ const { rows } = await this._options.query.query(`pragma table_info(${quoteForPragma(table)})`);
2070
2054
  const pkColumns = [];
2071
2055
  const columns = rows.map((row) => {
2072
2056
  const name = asString$1(row["name"]);
@@ -2111,19 +2095,12 @@ var SqliteIntrospector = class {
2111
2095
  for (const group of byId.values()) {
2112
2096
  const ordered = [...group].sort((a, b) => Number(a["seq"]) - Number(b["seq"]));
2113
2097
  const onDelete = toOnDelete(asString$1(ordered[0]["on_delete"]));
2114
- if (asString$1(ordered[0]["on_update"]).toUpperCase() !== "NO ACTION") throw diagnostic("unsupported_structure", table, diagnostic("structure_constraint"));
2115
- let referencedColumns = ordered.map((r) => asString$1(r["to"]));
2116
- if (ordered.every((r) => r["to"] == null)) {
2117
- const parent = asString$1(ordered[0]["table"]);
2118
- referencedColumns = (await this._options.query.query(`pragma table_xinfo(${quoteForPragma(parent)})`)).rows.filter((r) => Number(r["pk"]) > 0).sort((a, b) => Number(a["pk"]) - Number(b["pk"])).map((r) => asString$1(r["name"]));
2119
- if (referencedColumns.length !== ordered.length) throw diagnostic("unsupported_structure", table, diagnostic("structure_missing_key"));
2120
- }
2121
2098
  result.push({
2122
2099
  kind: "FOREIGN_KEY",
2123
2100
  name: void 0,
2124
2101
  columns: ordered.map((r) => asString$1(r["from"])),
2125
2102
  referencedTable: asString$1(ordered[0]["table"]),
2126
- referencedColumns,
2103
+ referencedColumns: ordered.map((r) => asString$1(r["to"])),
2127
2104
  onDelete,
2128
2105
  deferrable: false,
2129
2106
  cascade: toCascade(onDelete),
@@ -2147,28 +2124,19 @@ var SqliteIntrospector = class {
2147
2124
  for (const row of rows) {
2148
2125
  const name = asString$1(row["name"]);
2149
2126
  const origin = asString$1(row["origin"]);
2150
- if (origin === "pk") {
2151
- if ((await this._options.query.query(`pragma index_xinfo(${quoteForPragma(name)})`)).rows.some((r) => Number(r["key"]) === 1 && (Number(r["desc"]) !== 0 || asString$1(r["coll"]).toUpperCase() !== "BINARY"))) throw diagnostic("unsupported_structure", table, diagnostic("structure_constraint"));
2152
- continue;
2153
- }
2127
+ if (origin === "pk") continue;
2154
2128
  const columns = await this._indexColumns(name);
2155
- const tokens = sqlTokens(asString$1((await this._options.query.query(`select sql from sqlite_master where type = 'index' and name = ${"'" + name.replaceAll("'", "''") + "'"}`)).rows[0]?.["sql"]));
2156
- const unsupported = (await this._options.query.query(`pragma index_xinfo(${quoteForPragma(name)})`)).rows.some((r) => Number(r["key"]) === 1 && (Number(r["cid"]) < 0 || Number(r["desc"]) !== 0 || asString$1(r["coll"]).toUpperCase() !== "BINARY"));
2157
- const where = tokens.findIndex((t) => t.toLowerCase() === "where");
2158
- if (origin === "u") {
2159
- if (unsupported) throw diagnostic("unsupported_structure", `${table}.${name}`, diagnostic("structure_constraint"));
2160
- uniques.push({
2161
- kind: "UNIQUE",
2162
- name: void 0,
2163
- columns,
2164
- implicit: void 0
2165
- });
2166
- } else indexes.push({
2129
+ if (origin === "u") uniques.push({
2130
+ kind: "UNIQUE",
2131
+ name: void 0,
2132
+ columns,
2133
+ implicit: void 0
2134
+ });
2135
+ else indexes.push({
2167
2136
  name,
2168
- ...unsupported ? { unsupported: "SQLITE_SPECIAL_INDEX" } : {},
2169
2137
  columns,
2170
2138
  unique: Number(row["unique"]) === 1,
2171
- predicate: where < 0 ? void 0 : tokens.slice(where + 1).join(" ")
2139
+ predicate: void 0
2172
2140
  });
2173
2141
  }
2174
2142
  return {
@@ -2199,7 +2167,7 @@ function normalizeSqliteType(raw) {
2199
2167
  if (t.includes("char") || t.includes("clob") || t.includes("text")) return "text";
2200
2168
  if (t.includes("blob")) return "blob";
2201
2169
  if (t.includes("real") || t.includes("floa") || t.includes("doub")) return "real";
2202
- return "numeric";
2170
+ return "real";
2203
2171
  }
2204
2172
  /** SQLite 的 on_delete 文本 → migrate 的 OnDelete */
2205
2173
  function toOnDelete(raw) {
@@ -3080,6 +3048,11 @@ function failureLogs(file, message, language, rolledBack) {
3080
3048
  *
3081
3049
  * 模型文件可以是 `.ts`(Node 22.18+ / 23.6+ 原生类型剥离)或编译后的 `.js`。
3082
3050
  */
3051
+ function validateSeedConfig(value) {
3052
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw diagnostic("seed_config");
3053
+ const seed = value;
3054
+ if (typeof seed.command !== "string" || seed.command.trim() === "" || seed.command.includes("\0") || seed.args !== void 0 && (!Array.isArray(seed.args) || seed.args.some((arg) => typeof arg !== "string" || arg.includes("\0")))) throw diagnostic("seed_config");
3055
+ }
3083
3056
  /** 配置辅助函数:仅用于类型提示与自动补全 */
3084
3057
  function defineConfig(config) {
3085
3058
  return config;
@@ -3137,6 +3110,7 @@ function validateConfig(value, file) {
3137
3110
  if (typeof config.database !== "object" || config.database === null) throw diagnostic("config_4", file);
3138
3111
  if (!Array.isArray(config.models) || config.models.length === 0) throw diagnostic("config_5", file);
3139
3112
  if (config.language != null && config.language !== "en" && config.language !== "zh-CN") throw diagnostic("config_6", file, String(config.language));
3113
+ if (config.seed !== void 0) validateSeedConfig(config.seed);
3140
3114
  if (config.dialect != null) dialectInfo(config.dialect);
3141
3115
  return config;
3142
3116
  }
@@ -4517,6 +4491,73 @@ async function openSqlite(config, cwd, readOnly) {
4517
4491
  } : void 0);
4518
4492
  }
4519
4493
  //#endregion
4494
+ //#region src/seed.ts
4495
+ /** Run a user-owned seed process without creating a migration runtime.
4496
+ * The script owns its connections, transactions and idempotency. Output is inherited.
4497
+ */
4498
+ async function runSeed(seed, cwd, args = []) {
4499
+ validateSeedConfig(seed);
4500
+ const root = path.resolve(cwd);
4501
+ const bins = [];
4502
+ for (let dir = root;; dir = path.dirname(dir)) {
4503
+ bins.push(path.join(dir, "node_modules", ".bin"));
4504
+ if (path.dirname(dir) === dir) break;
4505
+ }
4506
+ const env = { ...process.env };
4507
+ const pathKey = Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
4508
+ env[pathKey] = [...bins, env[pathKey] ?? ""].join(path.delimiter);
4509
+ return new Promise((resolve, reject) => {
4510
+ const grouped = process.platform !== "win32";
4511
+ const child = spawn(seed.command, [...seed.args ?? [], ...args], {
4512
+ cwd: root,
4513
+ env,
4514
+ stdio: "inherit",
4515
+ shell: false,
4516
+ detached: grouped
4517
+ });
4518
+ let interrupted;
4519
+ let escalation;
4520
+ const terminate = (signal) => {
4521
+ if (child.pid === void 0) return;
4522
+ try {
4523
+ if (grouped) process.kill(-child.pid, signal);
4524
+ else child.kill(signal);
4525
+ } catch (error) {
4526
+ if (error.code !== "ESRCH") child.kill(signal);
4527
+ }
4528
+ };
4529
+ const forward = (signal) => {
4530
+ if (interrupted) {
4531
+ terminate("SIGKILL");
4532
+ return;
4533
+ }
4534
+ interrupted = signal;
4535
+ terminate(signal);
4536
+ escalation = setTimeout(() => terminate("SIGKILL"), 5e3);
4537
+ escalation.unref();
4538
+ };
4539
+ const onInterrupt = () => forward("SIGINT");
4540
+ const onTerminate = () => forward("SIGTERM");
4541
+ const cleanup = () => {
4542
+ process.off("SIGINT", onInterrupt);
4543
+ process.off("SIGTERM", onTerminate);
4544
+ if (escalation) clearTimeout(escalation);
4545
+ };
4546
+ process.on("SIGINT", onInterrupt);
4547
+ process.on("SIGTERM", onTerminate);
4548
+ child.once("error", (error) => {
4549
+ cleanup();
4550
+ reject(diagnostic("seed_start", seed.command, asError(error)));
4551
+ });
4552
+ child.once("close", (code, signal) => {
4553
+ if (interrupted && grouped) terminate("SIGKILL");
4554
+ cleanup();
4555
+ const termination = interrupted ?? signal;
4556
+ resolve(termination ? 128 + (constants.signals[termination] ?? 1) : code ?? 1);
4557
+ });
4558
+ });
4559
+ }
4560
+ //#endregion
4520
4561
  //#region src/cli/messages.ts
4521
4562
  const CATALOG = {
4522
4563
  en: {
@@ -4526,6 +4567,7 @@ Usage: tgm <command> [options]
4526
4567
 
4527
4568
  Commands:
4528
4569
  dev [-n <name>] Generate and apply a migration
4570
+ seed [-- <args...>] Run the configured seed script
4529
4571
  deploy Apply pending migrations
4530
4572
  push Sync the database without migration history
4531
4573
  status Show migration status
@@ -4546,6 +4588,11 @@ Options:
4546
4588
  Configuration files:
4547
4589
  ${CONFIG_FILENAMES.join("\n ")}
4548
4590
  `,
4591
+ seedMissing: "No seed configured. Add seed: { command: \"node\", args: [\"./src/ts-grm/seed.ts\"] } to your configuration.",
4592
+ seedOption: (flag) => `Unsupported seed option --${flag}. Pass script arguments after --.`,
4593
+ seedStarted: "Running seed script...",
4594
+ seedCompleted: "Seed completed.",
4595
+ seedFailed: (code) => `Seed failed (exit code ${code}).`,
4549
4596
  dataCondition: (table) => `Existing data in ${table} must satisfy the new NOT NULL, key or CHECK constraints. SQL may fail; non-transactional DDL may partially apply.`,
4550
4597
  dryRunPush: "Option --dry-run is only supported by push.",
4551
4598
  invalidLanguage: (value) => `Unsupported language "${value}". Use en or zh-CN.`,
@@ -4594,6 +4641,11 @@ Configuration files:
4594
4641
  detailSkipped: (count) => `Skipped ${count} already applied migrations.`
4595
4642
  },
4596
4643
  "zh-CN": {
4644
+ seedMissing: "未配置 seed。请在配置中添加 seed: { command: \"node\", args: [\"./src/ts-grm/seed.ts\"] }。",
4645
+ seedOption: (flag) => `seed 不支持选项 --${flag}。脚本参数请放在 -- 之后。`,
4646
+ seedStarted: "正在运行 seed 脚本……",
4647
+ seedCompleted: "Seed 执行完成。",
4648
+ seedFailed: (code) => `Seed 执行失败(退出码 ${code})。`,
4597
4649
  dataCondition: (table) => `${table} 的已有数据必须满足新的非空、键或 CHECK 约束。SQL 可能失败;非事务型 DDL 可能部分生效。`,
4598
4650
  dryRunPush: "--dry-run 仅支持 push。",
4599
4651
  usage: `ts-grm-migrate — ts-grm 的数据库迁移工具
@@ -4602,6 +4654,7 @@ Configuration files:
4602
4654
 
4603
4655
  命令:
4604
4656
  dev [-n <name>] 生成并应用迁移
4657
+ seed [-- <参数...>] 运行配置的 seed 脚本
4605
4658
  deploy 应用待处理迁移
4606
4659
  push 同步数据库,不记录迁移历史
4607
4660
  status 查看迁移状态
@@ -4701,8 +4754,13 @@ const SHORT_FLAG_ALIASES = { n: "name" };
4701
4754
  function parseArgs(argv) {
4702
4755
  const flags = /* @__PURE__ */ new Map();
4703
4756
  let command;
4757
+ let passthrough = [];
4704
4758
  for (let i = 0; i < argv.length; i++) {
4705
4759
  const arg = argv[i];
4760
+ if (arg === "--") {
4761
+ passthrough = argv.slice(i + 1);
4762
+ break;
4763
+ }
4706
4764
  if (arg.startsWith("--")) {
4707
4765
  const eq = arg.indexOf("=");
4708
4766
  if (eq >= 0) {
@@ -4733,7 +4791,8 @@ function parseArgs(argv) {
4733
4791
  }
4734
4792
  return {
4735
4793
  command,
4736
- flags
4794
+ flags,
4795
+ passthrough
4737
4796
  };
4738
4797
  }
4739
4798
  /**
@@ -4744,7 +4803,7 @@ function parseArgs(argv) {
4744
4803
  async function run(argv, cwd, options = {}) {
4745
4804
  const log = options.log ?? ((message) => console.log(message));
4746
4805
  const errorLog = options.errorLog ?? ((message) => console.error(message));
4747
- const { command, flags } = parseArgs(argv);
4806
+ const { command, flags, passthrough } = parseArgs(argv);
4748
4807
  const lang = flags.get("lang");
4749
4808
  let m = messages(lang === "zh-CN" ? "zh-CN" : "en");
4750
4809
  if (lang != null && lang !== "en" && lang !== "zh-CN") {
@@ -4761,7 +4820,8 @@ async function run(argv, cwd, options = {}) {
4761
4820
  "push",
4762
4821
  "status",
4763
4822
  "resolve",
4764
- "check"
4823
+ "check",
4824
+ "seed"
4765
4825
  ].includes(command)) {
4766
4826
  errorLog(m.unknownCommand(command));
4767
4827
  log(m.usage);
@@ -4794,6 +4854,26 @@ async function run(argv, cwd, options = {}) {
4794
4854
  errorLog(m.dryRunPush);
4795
4855
  return 1;
4796
4856
  }
4857
+ if (command === "seed") {
4858
+ for (const flag of flags.keys()) if (![
4859
+ "config",
4860
+ "lang",
4861
+ "detail"
4862
+ ].includes(flag)) {
4863
+ errorLog(m.seedOption(flag));
4864
+ return 1;
4865
+ }
4866
+ if (config.seed === void 0) {
4867
+ errorLog(m.seedMissing);
4868
+ return 1;
4869
+ }
4870
+ if (detail) log(m.config(configFile));
4871
+ log(m.seedStarted);
4872
+ const code = await runSeed(config.seed, cwd, passthrough);
4873
+ if (code === 0) log(m.seedCompleted);
4874
+ else errorLog(m.seedFailed(code));
4875
+ return code;
4876
+ }
4797
4877
  const runtime = await createRuntime(config, cwd, {
4798
4878
  confirm: options.confirm ?? makeConfirm(flags.has("force"), errorLog, m),
4799
4879
  driftLanguage: language,
@@ -4995,6 +5075,6 @@ function printDestructive(changes, errorLog, m) {
4995
5075
  }
4996
5076
  }
4997
5077
  //#endregion
4998
- export { SqliteDdlGenerator as A, PostgresSqlExecutor as B, abnormalDrift as C, FileMigrationStore as D, DatabaseMigrationHistoryStore as E, DIALECTS as F, diagnostic as G, tableDefsToSchema as H, DIALECT_NAMES as I, formatError as K, IMPLEMENTED_DIALECT_NAMES as L, SqliteSqlExecutor as M, PostgresDdlGenerator as N, checksumOf as O, PostgresIntrospector as P, dialectInfo as R, toSqlFile as S, DEFAULT_HISTORY_TABLE as T, ServerSql as U, SchemaDiffer as V, asError as W, defineConfig as _, DEFAULT_MIGRATIONS_DIR as a, Migrator as b, SqlServerIntrospector as c, OracleSqlExecutor as d, SqlServerSqlExecutor as f, CONFIG_FILENAMES as g, MysqlDdlGenerator as h, DEFAULT_LOCK_PATH as i, SqliteIntrospector as j, ServerMigrationHistoryStore as k, OracleIntrospector as l, MysqlSqlExecutor as m, run as n, createRuntime as o, SqlServerDdlGenerator as p, messages as r, MysqlIntrospector as s, parseArgs as t, OracleDdlGenerator as u, loadConfig as v, describeDiff as w, generateMigrationId as x, MigrationAbortedError as y, acquireProcessLock as z };
5078
+ export { ServerMigrationHistoryStore as A, acquireProcessLock as B, toSqlFile as C, DatabaseMigrationHistoryStore as D, DEFAULT_HISTORY_TABLE as E, PostgresIntrospector as F, asError as G, SchemaDiffer as H, DIALECTS as I, diagnostic as K, DIALECT_NAMES as L, SqliteIntrospector as M, SqliteSqlExecutor as N, FileMigrationStore as O, PostgresDdlGenerator as P, IMPLEMENTED_DIALECT_NAMES as R, generateMigrationId as S, describeDiff as T, tableDefsToSchema as U, PostgresSqlExecutor as V, ServerSql as W, CONFIG_FILENAMES as _, DEFAULT_LOCK_PATH as a, MigrationAbortedError as b, MysqlIntrospector as c, OracleDdlGenerator as d, OracleSqlExecutor as f, MysqlDdlGenerator as g, MysqlSqlExecutor as h, runSeed as i, SqliteDdlGenerator as j, checksumOf as k, SqlServerIntrospector as l, SqlServerDdlGenerator as m, run as n, DEFAULT_MIGRATIONS_DIR as o, SqlServerSqlExecutor as p, formatError as q, messages as r, createRuntime as s, parseArgs as t, OracleIntrospector as u, defineConfig as v, abnormalDrift as w, Migrator as x, loadConfig as y, dialectInfo as z };
4999
5079
 
5000
- //# sourceMappingURL=cli-Cfr6e9vX.mjs.map
5080
+ //# sourceMappingURL=cli-BlCk2tT8.mjs.map