@forestfuture/active-record 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/config-schema.json +56 -0
- package/dist/{adapter-BSvFhTDf.d.mts → adapter-AGKp6wfO.d.mts} +42 -9
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.mjs +4 -3
- package/dist/{batch-DBeYk5wx.mjs → batch-BS_WseLf.mjs} +128 -44
- package/dist/cli.d.mts +176 -28
- package/dist/cli.mjs +3 -2
- package/dist/command.mjs +746 -432
- package/dist/d1.d.mts +68 -0
- package/dist/d1.mjs +0 -0
- package/dist/for-adapters-Ch6CoHD4.mjs +240 -0
- package/dist/for-adapters-D_Iu0gS_.mjs +33 -0
- package/dist/for-adapters-t3-LukJQ.d.mts +21 -0
- package/dist/{generated-model-CfDggoVN.mjs → generated-model-Cnt0Ot9q.mjs} +4 -0
- package/dist/index-CyCJuM96.d.mts +149 -0
- package/dist/index.d.mts +3 -143
- package/dist/index.mjs +3 -2
- package/dist/plugin-Cyoej7qV.mjs +600 -0
- package/dist/plugin-XOHYndhP.mjs +939 -0
- package/dist/postgresql.d.mts +72 -0
- package/dist/postgresql.mjs +588 -0
- package/dist/src-la_KkjCS.mjs +1 -0
- package/dist/storage-override-CpbkdIqE.mjs +187 -0
- package/llms-full.txt +837 -201
- package/package.json +25 -2
- package/skills/active-record/SKILL.md +4 -4
- package/dist/storage-override-BYBYP8Mj.mjs +0 -91
package/dist/command.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { J as tableize, Y as ancestors, i as isBase } from "./generated-model-
|
|
2
|
+
import { J as tableize, Y as ancestors, i as isBase } from "./generated-model-Cnt0Ot9q.mjs";
|
|
3
3
|
import { a as underscore, i as camelize, n as pluralize, r as singularize } from "./epoch-storage-o2aoOH7H.mjs";
|
|
4
|
-
import { a as isIdentifier,
|
|
5
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
|
|
4
|
+
import { _ as shown$1, a as isIdentifier, f as byVersion, g as importPath, h as migrationsOf, l as parseJsonc, m as leadingNumber, o as listed, p as hasNestedMigrations, r as classify, s as moduleName, t as storageOverride, u as projectDatabases, v as slashed } from "./storage-override-CpbkdIqE.mjs";
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
|
|
6
6
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
7
7
|
import { inspect, parseArgs, types } from "node:util";
|
|
8
8
|
import { WriteStream } from "node:tty";
|
|
9
|
-
import { createJiti } from "jiti";
|
|
10
9
|
import { createInterface } from "node:readline";
|
|
10
|
+
import { createJiti } from "jiti";
|
|
11
11
|
import { Console } from "node:console";
|
|
12
12
|
import { PassThrough, Readable, Writable } from "node:stream";
|
|
13
13
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -16,7 +16,6 @@ import { createHash } from "node:crypto";
|
|
|
16
16
|
//#region cli/subcommand.ts
|
|
17
17
|
/** The flags every subcommand takes. */
|
|
18
18
|
const sharedOptions = {
|
|
19
|
-
adapter: { type: "string" },
|
|
20
19
|
config: { type: "string" },
|
|
21
20
|
help: {
|
|
22
21
|
type: "boolean",
|
|
@@ -25,8 +24,7 @@ const sharedOptions = {
|
|
|
25
24
|
};
|
|
26
25
|
/** The help for the shared flags, after every subcommand's own. */
|
|
27
26
|
const sharedFlagHelp = `Options for every command:
|
|
28
|
-
--
|
|
29
|
-
--config <file> Use this Wrangler config
|
|
27
|
+
--config <file> Use this config file, in place of active-record.jsonc
|
|
30
28
|
-h, --help Show this help`;
|
|
31
29
|
/** A subcommand from its spec: its `action` gets the command line parsed, or `fail` says why it can't be. */
|
|
32
30
|
function defineSubcommand(spec) {
|
|
@@ -66,203 +64,68 @@ function helpFor(subcommands) {
|
|
|
66
64
|
].join("\n\n");
|
|
67
65
|
}
|
|
68
66
|
//#endregion
|
|
69
|
-
//#region cli/project/targets.ts
|
|
70
|
-
/**
|
|
71
|
-
* A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
|
|
72
|
-
* per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
|
|
73
|
-
*/
|
|
74
|
-
function baseFor(modelsDir, binding, several) {
|
|
75
|
-
if (!several) return {
|
|
76
|
-
path: join(modelsDir, "application-record.ts"),
|
|
77
|
-
className: "ApplicationRecord"
|
|
78
|
-
};
|
|
79
|
-
const className = `${classify(binding.toLowerCase())}Record`;
|
|
80
|
-
return {
|
|
81
|
-
path: join(modelsDir, `${moduleName(className)}.ts`),
|
|
82
|
-
className
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
/** Where Models and their base class go without `--models`. */
|
|
86
|
-
const defaultModels = "src/models";
|
|
87
|
-
/** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
|
|
88
|
-
function oneModelsFile(models) {
|
|
89
|
-
return models.endsWith(".ts");
|
|
90
|
-
}
|
|
91
|
-
/** The folder Models and their base class live in: `--models`, or `src/models`. */
|
|
92
|
-
function modelsDirOf(cwd, models = defaultModels) {
|
|
93
|
-
const path = resolve(cwd, models);
|
|
94
|
-
return oneModelsFile(models) ? dirname(path) : path;
|
|
95
|
-
}
|
|
96
|
-
/** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
|
|
97
|
-
function modelsFolders(cwd, models = defaultModels) {
|
|
98
|
-
const folder = modelsDirOf(cwd, models);
|
|
99
|
-
return existsSync(folder) ? [folder] : [];
|
|
100
|
-
}
|
|
101
|
-
/** Bindings whose base classes would be the same (`DB` and `db` → `DbRecord`), as an error. */
|
|
102
|
-
function sharedBase(targets) {
|
|
103
|
-
const seen = /* @__PURE__ */ new Map();
|
|
104
|
-
for (const { database, base } of targets) {
|
|
105
|
-
const other = seen.get(base.className);
|
|
106
|
-
if (other !== void 0) return `The bindings ${other} and ${database.binding} would share the base class ${base.className}; rename one`;
|
|
107
|
-
seen.set(base.className, database.binding);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
/** The databases to generate, from the adapter's config and the options; or why there are none. */
|
|
111
|
-
function targetsOf(adapter, cwd, options) {
|
|
112
|
-
const config = adapter.databases(cwd, options.config);
|
|
113
|
-
if (!config.ok) return config.error;
|
|
114
|
-
const { databases, dir } = config;
|
|
115
|
-
if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
|
|
116
|
-
const targets = databases.map((database) => {
|
|
117
|
-
const migrationsDir = resolve(cwd, options.migrations ?? join(dir, database.migrationsDir));
|
|
118
|
-
const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
|
|
119
|
-
const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
|
|
120
|
-
return {
|
|
121
|
-
database,
|
|
122
|
-
configDir: dir,
|
|
123
|
-
migrationsDir,
|
|
124
|
-
out,
|
|
125
|
-
base
|
|
126
|
-
};
|
|
127
|
-
});
|
|
128
|
-
return sharedBase(targets) ?? targets;
|
|
129
|
-
}
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region cli/project/load.ts
|
|
132
|
-
/**
|
|
133
|
-
* A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
|
|
134
|
-
* paths, and resolves the library (`@forestfuture/active-record` and `@forestfuture/d1-record`)
|
|
135
|
-
* from the project's `node_modules`, so the Models and the command share a single copy of it.
|
|
136
|
-
*/
|
|
137
|
-
function projectJiti(cwd) {
|
|
138
|
-
return createJiti(`${cwd}/`, {
|
|
139
|
-
tsconfigPaths: true,
|
|
140
|
-
fsCache: false,
|
|
141
|
-
moduleCache: true
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
/** The Model files: the folder's `.ts` files, or the one file `--models` names. */
|
|
145
|
-
function modelFiles(cwd, models) {
|
|
146
|
-
const path = resolve(cwd, models);
|
|
147
|
-
if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
|
|
148
|
-
if (oneModelsFile(models) || statSync(path).isFile()) return [path];
|
|
149
|
-
return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
|
|
150
|
-
}
|
|
151
|
-
/** The core, which every command loads from the project, beside the adapter some need. */
|
|
152
|
-
const corePackage = "@forestfuture/active-record";
|
|
153
|
-
/** Whether `error` is the loader failing to find `name` itself, not something it imports. */
|
|
154
|
-
function isMissing(error, name) {
|
|
155
|
-
const { code, message } = error;
|
|
156
|
-
return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).startsWith(`Cannot find module '${name}'`);
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* The project's own copies of `packages` (the core, and the adapter when a command needs it), as
|
|
160
|
-
* one module, or why one can't be loaded, naming it. Each is imported from a file in the project,
|
|
161
|
-
* as its Models import it, because only imports made inside a file follow a `tsconfig.json` path
|
|
162
|
-
* (a workspace link), and so the Models and the command get one copy.
|
|
163
|
-
*/
|
|
164
|
-
async function loadLibrary(cwd, jiti, { command, packages }) {
|
|
165
|
-
const filename = join(cwd, `active-record-${command}.ts`);
|
|
166
|
-
let library = {};
|
|
167
|
-
for (const name of packages) try {
|
|
168
|
-
const source = `export * from "${name}";`;
|
|
169
|
-
const loaded = await jiti.evalModule(source, {
|
|
170
|
-
filename,
|
|
171
|
-
async: true
|
|
172
|
-
});
|
|
173
|
-
library = {
|
|
174
|
-
...library,
|
|
175
|
-
...loaded
|
|
176
|
-
};
|
|
177
|
-
} catch (error) {
|
|
178
|
-
if (isMissing(error, name)) return `${name} isn't installed here (install it, then run active-record ${command} again)`;
|
|
179
|
-
return `Couldn't load ${name}: ${error.message}`;
|
|
180
|
-
}
|
|
181
|
-
return library;
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Forgets the project's own modules, so they are read again. Its dependencies stay as they are,
|
|
185
|
-
* and so do `keep` (the library's files, which may sit under the project's folder).
|
|
186
|
-
*/
|
|
187
|
-
function forgetProjectFiles(cwd, jiti, keep) {
|
|
188
|
-
const folder = `${slashed(resolve(cwd))}/`;
|
|
189
|
-
for (const file of Object.keys(jiti.cache)) {
|
|
190
|
-
const name = slashed(file);
|
|
191
|
-
if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
//#endregion
|
|
195
67
|
//#region cli/project/adapters.ts
|
|
196
|
-
/** Each adapter
|
|
68
|
+
/** Each adapter a database's `adapter` names. Its plugin ships with the command, loaded when it's used. */
|
|
197
69
|
const adapters = {
|
|
198
|
-
d1:
|
|
199
|
-
|
|
70
|
+
d1: {
|
|
71
|
+
entry: "@forestfuture/active-record/d1",
|
|
72
|
+
plugin: async () => (await import("./plugin-Cyoej7qV.mjs")).cli
|
|
73
|
+
},
|
|
74
|
+
postgresql: {
|
|
75
|
+
entry: "@forestfuture/active-record/postgresql",
|
|
76
|
+
plugin: async () => (await import("./plugin-XOHYndhP.mjs")).cli
|
|
77
|
+
}
|
|
200
78
|
};
|
|
201
|
-
/** The
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
79
|
+
/** The adapters' names, in the registry's order. */
|
|
80
|
+
const adapterNames = Object.keys(adapters);
|
|
81
|
+
/** The entry an adapter's factory and `connect` are imported from, as the registry names it. */
|
|
82
|
+
function adapterEntry(adapter) {
|
|
83
|
+
return adapters[adapter.name]?.entry ?? adapter.name;
|
|
84
|
+
}
|
|
85
|
+
/** What's wrong with a database's `adapter`, if anything. */
|
|
86
|
+
function adapterError(binding, adapter) {
|
|
87
|
+
if (adapter === void 0) {
|
|
88
|
+
const quoted = adapterNames.map((name) => JSON.stringify(name));
|
|
89
|
+
return `databases.${binding} has no adapter (add "adapter": ${listed(quoted)})`;
|
|
209
90
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
for (
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
if (found.length > 0) return found;
|
|
221
|
-
if (dirname(dir) === dir) return [];
|
|
91
|
+
if (typeof adapter === "string" && Object.hasOwn(adapters, adapter)) return void 0;
|
|
92
|
+
return `databases.${binding} has the adapter ${JSON.stringify(adapter)}, which isn't ${listed(adapterNames)}`;
|
|
93
|
+
}
|
|
94
|
+
/** The one adapter the project's databases name, or why there isn't one (#305). */
|
|
95
|
+
function adapterNamed(project) {
|
|
96
|
+
const file = basename(project.file);
|
|
97
|
+
const entries = Object.entries(project.databases);
|
|
98
|
+
for (const [binding, entry] of entries) {
|
|
99
|
+
const error = adapterError(binding, entry.adapter);
|
|
100
|
+
if (error !== void 0) return `${file}: ${error}`;
|
|
222
101
|
}
|
|
102
|
+
const named = new Set(entries.map(([, entry]) => entry.adapter));
|
|
103
|
+
if (named.size === 1) return { name: [...named][0] };
|
|
104
|
+
return `${file} names more than one adapter (${entries.map(([binding, entry]) => `${String(entry.adapter)} for ${binding}`).join(", ")}); a project uses one, for now`;
|
|
223
105
|
}
|
|
224
|
-
/**
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
async function pluginOf(cwd, name) {
|
|
229
|
-
const entry = `${adapters[name]}/cli`;
|
|
230
|
-
try {
|
|
231
|
-
const source = `export { cli } from "${entry}";`;
|
|
232
|
-
const filename = join(cwd, "active-record-adapter.ts");
|
|
233
|
-
return (await projectJiti(cwd).evalModule(source, {
|
|
234
|
-
filename,
|
|
235
|
-
async: true
|
|
236
|
-
})).cli;
|
|
237
|
-
} catch (error) {
|
|
238
|
-
if (isMissing(error, entry) || isMissing(error, adapters[name])) return void 0;
|
|
239
|
-
return `Couldn't load ${entry}: ${error.message}`;
|
|
240
|
-
}
|
|
106
|
+
/** The notes the project's adapter has about its databases, as the command prints them. */
|
|
107
|
+
function configNotes(adapter) {
|
|
108
|
+
const config = adapter.databases();
|
|
109
|
+
return config.ok ? (config.notes ?? []).map((note) => `Note: ${note}`) : [];
|
|
241
110
|
}
|
|
242
|
-
/** The
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
const found = [];
|
|
246
|
-
for (const name of listedHere.length > 0 ? listedHere : Object.keys(adapters)) {
|
|
247
|
-
const plugin = await pluginOf(cwd, name);
|
|
248
|
-
if (typeof plugin === "string") return plugin;
|
|
249
|
-
if (plugin !== void 0) found.push(plugin);
|
|
250
|
-
}
|
|
251
|
-
return found;
|
|
111
|
+
/** The plugin of the adapter `name`. */
|
|
112
|
+
function pluginOf(name) {
|
|
113
|
+
return adapters[name].plugin();
|
|
252
114
|
}
|
|
253
115
|
/**
|
|
254
|
-
* The project's adapter
|
|
255
|
-
*
|
|
256
|
-
* none, is a message saying what to do.
|
|
116
|
+
* The project's adapter, as its `active-record.jsonc` (or the file `configPath` names) names it, with
|
|
117
|
+
* its plugin reading the databases there; or a message saying what to do.
|
|
257
118
|
*/
|
|
258
|
-
async function loadAdapter(cwd,
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
if (
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
119
|
+
async function loadAdapter(cwd, configPath) {
|
|
120
|
+
const project = projectDatabases(cwd, configPath);
|
|
121
|
+
if (typeof project === "string") return project;
|
|
122
|
+
const named = adapterNamed(project);
|
|
123
|
+
if (typeof named === "string") return named;
|
|
124
|
+
const plugin = await pluginOf(named.name);
|
|
125
|
+
return plugin.unsupported?.() ?? {
|
|
126
|
+
...plugin,
|
|
127
|
+
databases: () => plugin.databases(project)
|
|
128
|
+
};
|
|
266
129
|
}
|
|
267
130
|
//#endregion
|
|
268
131
|
//#region cli/project/databases.ts
|
|
@@ -280,18 +143,17 @@ function chooseDatabase(databases, named) {
|
|
|
280
143
|
}
|
|
281
144
|
/** The database for `--database` (and `--config`), with its config file, or why there isn't one. */
|
|
282
145
|
function chosenDatabase(adapter, cwd, options) {
|
|
283
|
-
const config = adapter.databases(
|
|
146
|
+
const config = adapter.databases();
|
|
284
147
|
if (!config.ok) return config.error;
|
|
285
148
|
const chosen = chooseDatabase(config.databases, options.database);
|
|
286
149
|
if (typeof chosen === "string") return chosen;
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
accountId: config.accountId
|
|
150
|
+
const { binding, entry } = chosen;
|
|
151
|
+
const migrationsDir = resolve(config.dir, chosen.migrationsDir);
|
|
152
|
+
return {
|
|
153
|
+
binding,
|
|
154
|
+
entry,
|
|
155
|
+
configFile: config.file,
|
|
156
|
+
migrationsDir
|
|
295
157
|
};
|
|
296
158
|
}
|
|
297
159
|
//#endregion
|
|
@@ -389,6 +251,133 @@ async function confirmRemote({ input, output, target, consequence = "What you ch
|
|
|
389
251
|
};
|
|
390
252
|
}
|
|
391
253
|
//#endregion
|
|
254
|
+
//#region cli/project/targets.ts
|
|
255
|
+
/**
|
|
256
|
+
* A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
|
|
257
|
+
* per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
|
|
258
|
+
*/
|
|
259
|
+
function baseFor(modelsDir, binding, several) {
|
|
260
|
+
if (!several) return {
|
|
261
|
+
path: join(modelsDir, "application-record.ts"),
|
|
262
|
+
className: "ApplicationRecord"
|
|
263
|
+
};
|
|
264
|
+
const className = `${classify(binding.toLowerCase())}Record`;
|
|
265
|
+
return {
|
|
266
|
+
path: join(modelsDir, `${moduleName(className)}.ts`),
|
|
267
|
+
className
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
/** Where Models and their base class go without `--models`. */
|
|
271
|
+
const defaultModels = "src/models";
|
|
272
|
+
/** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
|
|
273
|
+
function oneModelsFile(models) {
|
|
274
|
+
return models.endsWith(".ts");
|
|
275
|
+
}
|
|
276
|
+
/** The folder Models and their base class live in: `--models`, or `src/models`. */
|
|
277
|
+
function modelsDirOf(cwd, models = defaultModels) {
|
|
278
|
+
const path = resolve(cwd, models);
|
|
279
|
+
return oneModelsFile(models) ? dirname(path) : path;
|
|
280
|
+
}
|
|
281
|
+
/** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
|
|
282
|
+
function modelsFolders(cwd, models = defaultModels) {
|
|
283
|
+
const folder = modelsDirOf(cwd, models);
|
|
284
|
+
return existsSync(folder) ? [folder] : [];
|
|
285
|
+
}
|
|
286
|
+
/** Bindings whose base classes would be the same (`DB` and `db` → `DbRecord`), as an error. */
|
|
287
|
+
function sharedBase(targets) {
|
|
288
|
+
const seen = /* @__PURE__ */ new Map();
|
|
289
|
+
for (const { database, base } of targets) {
|
|
290
|
+
const other = seen.get(base.className);
|
|
291
|
+
if (other !== void 0) return `The bindings ${other} and ${database.binding} would share the base class ${base.className}; rename one`;
|
|
292
|
+
seen.set(base.className, database.binding);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** The databases to generate, from the adapter's config and the options; or why there are none. */
|
|
296
|
+
function targetsOf(adapter, cwd, options) {
|
|
297
|
+
const config = adapter.databases();
|
|
298
|
+
if (!config.ok) return config.error;
|
|
299
|
+
const { databases, dir, file } = config;
|
|
300
|
+
if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
|
|
301
|
+
const targets = databases.map((database) => {
|
|
302
|
+
const migrationsDir = resolve(cwd, options.migrations ?? join(dir, database.migrationsDir));
|
|
303
|
+
const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
|
|
304
|
+
const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
|
|
305
|
+
return {
|
|
306
|
+
database,
|
|
307
|
+
configFile: file,
|
|
308
|
+
configDir: dir,
|
|
309
|
+
migrationsDir,
|
|
310
|
+
out,
|
|
311
|
+
base
|
|
312
|
+
};
|
|
313
|
+
});
|
|
314
|
+
return sharedBase(targets) ?? targets;
|
|
315
|
+
}
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region cli/project/load.ts
|
|
318
|
+
/**
|
|
319
|
+
* A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
|
|
320
|
+
* paths, and resolves the library (`@forestfuture/active-record` and its adapter's package)
|
|
321
|
+
* from the project's `node_modules`, so the Models and the command share a single copy of it.
|
|
322
|
+
*/
|
|
323
|
+
function projectJiti(cwd) {
|
|
324
|
+
return createJiti(`${cwd}/`, {
|
|
325
|
+
tsconfigPaths: true,
|
|
326
|
+
fsCache: false,
|
|
327
|
+
moduleCache: true
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
/** The Model files: the folder's `.ts` files, or the one file `--models` names. */
|
|
331
|
+
function modelFiles(cwd, models) {
|
|
332
|
+
const path = resolve(cwd, models);
|
|
333
|
+
if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
|
|
334
|
+
if (oneModelsFile(models) || statSync(path).isFile()) return [path];
|
|
335
|
+
return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
|
|
336
|
+
}
|
|
337
|
+
/** The core, which every command loads from the project, beside the adapter some need. */
|
|
338
|
+
const corePackage = "@forestfuture/active-record";
|
|
339
|
+
/** Whether `error` is the loader failing to find `name` itself, not something it imports. */
|
|
340
|
+
function isMissing(error, name) {
|
|
341
|
+
const { code, message } = error;
|
|
342
|
+
return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).startsWith(`Cannot find module '${name}'`);
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* The project's own copies of `packages` (the core, and the adapter when a command needs it), as
|
|
346
|
+
* one module, or why one can't be loaded, naming it. Each is imported from a file in the project,
|
|
347
|
+
* as its Models import it, because only imports made inside a file follow a `tsconfig.json` path
|
|
348
|
+
* (a workspace link), and so the Models and the command get one copy.
|
|
349
|
+
*/
|
|
350
|
+
async function loadLibrary(cwd, jiti, { command, packages }) {
|
|
351
|
+
const filename = join(cwd, `active-record-${command}.ts`);
|
|
352
|
+
let library = {};
|
|
353
|
+
for (const name of packages) try {
|
|
354
|
+
const source = `export * from "${name}";`;
|
|
355
|
+
const loaded = await jiti.evalModule(source, {
|
|
356
|
+
filename,
|
|
357
|
+
async: true
|
|
358
|
+
});
|
|
359
|
+
library = {
|
|
360
|
+
...library,
|
|
361
|
+
...loaded
|
|
362
|
+
};
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (isMissing(error, name)) return `${name} isn't installed here (install it, then run active-record ${command} again)`;
|
|
365
|
+
return `Couldn't load ${name}: ${error.message}`;
|
|
366
|
+
}
|
|
367
|
+
return library;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Forgets the project's own modules, so they are read again. Its dependencies stay as they are,
|
|
371
|
+
* and so do `keep` (the library's files, which may sit under the project's folder).
|
|
372
|
+
*/
|
|
373
|
+
function forgetProjectFiles(cwd, jiti, keep) {
|
|
374
|
+
const folder = `${slashed(resolve(cwd))}/`;
|
|
375
|
+
for (const file of Object.keys(jiti.cache)) {
|
|
376
|
+
const name = slashed(file);
|
|
377
|
+
if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
//#endregion
|
|
392
381
|
//#region cli/console/project.ts
|
|
393
382
|
/** The Model classes the files export, by name; or the file that couldn't be loaded. */
|
|
394
383
|
async function loadModels(cwd, jiti, files, library) {
|
|
@@ -723,12 +712,12 @@ function standardIo$1() {
|
|
|
723
712
|
};
|
|
724
713
|
}
|
|
725
714
|
/**
|
|
726
|
-
* Where the history is kept:
|
|
727
|
-
* remote session has a file of its own, so a line typed against the real database is
|
|
728
|
-
* offered, with the up arrow, to a local session (or the other way round).
|
|
715
|
+
* Where the history is kept: in the adapter's folder for local files, which the project already
|
|
716
|
+
* ignores. A remote session has a file of its own, so a line typed against the real database is
|
|
717
|
+
* never offered, with the up arrow, to a local session (or the other way round).
|
|
729
718
|
*/
|
|
730
|
-
function historyFileFor(
|
|
731
|
-
return join(
|
|
719
|
+
function historyFileFor(stateFolder, remote) {
|
|
720
|
+
return join(stateFolder, `active-record-history${remote ? "-remote" : ""}`);
|
|
732
721
|
}
|
|
733
722
|
/** Says why the console can't open; 1. */
|
|
734
723
|
function refused$1(print, problem) {
|
|
@@ -783,24 +772,26 @@ function runOnce(code, opened, io, errors) {
|
|
|
783
772
|
/** Everything that has to be true before a session starts, or why it isn't. */
|
|
784
773
|
async function prepare(options, io) {
|
|
785
774
|
const cwd = options.cwd ?? process.cwd();
|
|
786
|
-
const adapter = await loadAdapter(cwd, options.
|
|
775
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
787
776
|
if (typeof adapter === "string") return adapter;
|
|
788
777
|
const chosen = chosenDatabase(adapter, cwd, options);
|
|
789
778
|
if (typeof chosen === "string") return chosen;
|
|
790
|
-
const project = await loadProject(
|
|
779
|
+
const project = await loadProject(adapterEntry(adapter), cwd, options.models);
|
|
791
780
|
if (typeof project === "string") return project;
|
|
792
781
|
const opened = await (options.remote === true ? openRemote(adapter, {
|
|
793
782
|
cwd,
|
|
794
783
|
chosen
|
|
795
784
|
}, options, io) : adapter.open(cwd, chosen, { remote: false }));
|
|
796
|
-
|
|
797
|
-
|
|
785
|
+
if (typeof opened === "string") return opened;
|
|
786
|
+
return {
|
|
787
|
+
stateFolder: adapter.stateFolder(chosen),
|
|
788
|
+
notes: configNotes(adapter),
|
|
798
789
|
project,
|
|
799
790
|
opened
|
|
800
791
|
};
|
|
801
792
|
}
|
|
802
793
|
/** The session, or the one piece of code, on the open database; the exit code. */
|
|
803
|
-
async function converse(options, {
|
|
794
|
+
async function converse(options, { stateFolder, notes, project, opened }, { io, say, errors }) {
|
|
804
795
|
const scripted = options.eval !== void 0;
|
|
805
796
|
const remote = options.remote === true;
|
|
806
797
|
const { library, models } = project;
|
|
@@ -812,6 +803,7 @@ async function converse(options, { chosen, project, opened }, { io, say, errors
|
|
|
812
803
|
const database = library.connect(opened.binding, { onQuery });
|
|
813
804
|
say(opened.description);
|
|
814
805
|
say(`Models: ${Object.keys(models).join(", ")}`);
|
|
806
|
+
for (const note of notes) say(note);
|
|
815
807
|
const inside = {
|
|
816
808
|
scope: {
|
|
817
809
|
...models,
|
|
@@ -825,7 +817,7 @@ async function converse(options, { chosen, project, opened }, { io, say, errors
|
|
|
825
817
|
...io,
|
|
826
818
|
...inside,
|
|
827
819
|
prompt: promptFor(remote, io.terminal === true),
|
|
828
|
-
historyFile: options.history ?? !remote ? historyFileFor(
|
|
820
|
+
historyFile: options.history ?? !remote ? historyFileFor(stateFolder, remote) : void 0
|
|
829
821
|
}).closed;
|
|
830
822
|
return {
|
|
831
823
|
exitCode: 0,
|
|
@@ -894,14 +886,14 @@ function consoleChoices(values) {
|
|
|
894
886
|
/** `active-record console`: opens the project's database (local, or remote) and its Models in a REPL. */
|
|
895
887
|
const consoleSubcommand = defineSubcommand({
|
|
896
888
|
options,
|
|
897
|
-
usage: ` active-record console (or c) Open a console on your
|
|
889
|
+
usage: ` active-record console (or c) Open a console on your database, with your Models`,
|
|
898
890
|
flagHelp: `Options for console:
|
|
899
|
-
--database <name> The
|
|
891
|
+
--database <name> The database to open, when the config has several
|
|
900
892
|
--models <path> Where the Models are: a folder (src/models) or one file (src/models.ts)
|
|
901
893
|
--remote Open your remote database instead, after asking you to type its name
|
|
902
894
|
--yes Don't ask first (with --remote); also how to open it without a terminal
|
|
903
895
|
--history Keep what you type, which a remote session doesn't unless asked
|
|
904
|
-
--no-history Don't keep what you type
|
|
896
|
+
--no-history Don't keep what you type
|
|
905
897
|
--verbose Print each statement a line runs (.verbose toggles it while it runs)
|
|
906
898
|
-e, --eval <code> Run this code, print its result, and exit (only the result goes to stdout)`,
|
|
907
899
|
action({ values, positionals }, print, fail) {
|
|
@@ -1040,7 +1032,7 @@ function databaseSnapshot(target, toolsFound) {
|
|
|
1040
1032
|
};
|
|
1041
1033
|
}
|
|
1042
1034
|
/**
|
|
1043
|
-
* Reads a project's databases from its
|
|
1035
|
+
* Reads a project's databases from its config, and the other `files` a command needs
|
|
1044
1036
|
* (a Model file, for `g model`); or why it can't, such as a missing config.
|
|
1045
1037
|
*/
|
|
1046
1038
|
function readProject(adapter, cwd, options, files = []) {
|
|
@@ -1073,9 +1065,9 @@ const stringLiteralPattern = String.raw`"(?:[^"\\]|\\.)*"`;
|
|
|
1073
1065
|
//#region cli/schema/render.ts
|
|
1074
1066
|
/**
|
|
1075
1067
|
* The generated file's format. Bump it when the output changes, so `--check` reports files an
|
|
1076
|
-
* older
|
|
1068
|
+
* older version of the command wrote (its fingerprint covers the format as well as the schema).
|
|
1077
1069
|
*/
|
|
1078
|
-
const format =
|
|
1070
|
+
const format = 6;
|
|
1079
1071
|
/**
|
|
1080
1072
|
* An object key: bare when it's an identifier, quoted otherwise (`"first name"`). `__proto__` is
|
|
1081
1073
|
* computed, since in an object literal a bare or quoted one sets the prototype and the key is
|
|
@@ -1120,10 +1112,11 @@ ${attributes}
|
|
|
1120
1112
|
} as const;`;
|
|
1121
1113
|
}
|
|
1122
1114
|
/** A short hash of the schema itself, so `--check` ignores how the file is formatted. */
|
|
1123
|
-
function fingerprintOf({ tables, binding, models }) {
|
|
1115
|
+
function fingerprintOf({ adapter, tables, binding, models }) {
|
|
1124
1116
|
const listed = byName(models, (model) => model.className);
|
|
1125
1117
|
return createHash("sha256").update(JSON.stringify({
|
|
1126
1118
|
format,
|
|
1119
|
+
adapter,
|
|
1127
1120
|
tables,
|
|
1128
1121
|
binding,
|
|
1129
1122
|
models: listed
|
|
@@ -1140,7 +1133,7 @@ function modelsSource(entries) {
|
|
|
1140
1133
|
return `{\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
|
|
1141
1134
|
}
|
|
1142
1135
|
/** The `schema` value: its adapter and binding, every table by name, and every Model's table by class. */
|
|
1143
|
-
function schemaValueSource({ tables, binding, models }) {
|
|
1136
|
+
function schemaValueSource({ adapter, tables, binding, models }) {
|
|
1144
1137
|
const entries = tables.map((table) => {
|
|
1145
1138
|
const primaryKey = JSON.stringify(table.primaryKey);
|
|
1146
1139
|
return ` ${keySource(table.name)}: { attributes: ${table.exportName}, primaryKey: ${primaryKey} },`;
|
|
@@ -1148,7 +1141,7 @@ function schemaValueSource({ tables, binding, models }) {
|
|
|
1148
1141
|
const listed = byName(models, (model) => model.className).map((model) => `${keySource(model.className)}: ${JSON.stringify(model.table)}`);
|
|
1149
1142
|
return `/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
|
|
1150
1143
|
export const schema = {
|
|
1151
|
-
adapter:
|
|
1144
|
+
adapter: ${adapter.factory}({ binding: ${stringLiteral(binding)} }),
|
|
1152
1145
|
tables: {
|
|
1153
1146
|
${entries}
|
|
1154
1147
|
},
|
|
@@ -1179,7 +1172,7 @@ function declarationsSource({ tables, models }) {
|
|
|
1179
1172
|
*/
|
|
1180
1173
|
function renderSchema(schema, source) {
|
|
1181
1174
|
const hasModels = schema.models.length > 0;
|
|
1182
|
-
const imports = (hasModels ? "import type { TableAttributes } from \"@forestfuture/active-record\";\n" : "") +
|
|
1175
|
+
const imports = (hasModels ? "import type { TableAttributes } from \"@forestfuture/active-record\";\n" : "") + `import { ${schema.adapter.factory} } from ${stringLiteral(schema.adapter.from)};\n\n`;
|
|
1183
1176
|
const declarations = hasModels ? `\n\n${declarationsSource(schema)}` : "";
|
|
1184
1177
|
return `// Generated by \`active-record schema\` from ${source} — don't edit.
|
|
1185
1178
|
// schema: ${fingerprintOf(schema)}
|
|
@@ -1190,63 +1183,181 @@ ${schemaValueSource(schema)}${declarations}
|
|
|
1190
1183
|
`;
|
|
1191
1184
|
}
|
|
1192
1185
|
/**
|
|
1193
|
-
* The app's base class for a database's Models, written once and then the app's own, as Rails'
|
|
1194
|
-
* `ApplicationRecord` is: `class Product extends ApplicationRecord {}`.
|
|
1186
|
+
* The app's base class for a database's Models, written once and then the app's own, as Rails'
|
|
1187
|
+
* `ApplicationRecord` is: `class Product extends ApplicationRecord {}`.
|
|
1188
|
+
*/
|
|
1189
|
+
function renderBase(className, schemaImport) {
|
|
1190
|
+
return `import { Model } from "@forestfuture/active-record";
|
|
1191
|
+
import { schema } from ${stringLiteral(schemaImport)};
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* The base class for this app's Models: \`class Product extends ${className} {}\`. Methods,
|
|
1195
|
+
* callbacks and scopes written here are shared by every Model, as in Rails' ApplicationRecord.
|
|
1196
|
+
* It's abstract: it has no table of its own.
|
|
1197
|
+
*/
|
|
1198
|
+
export abstract class ${className} extends Model {
|
|
1199
|
+
// The generated schema: each Model's attributes, from its table, and the binding Models
|
|
1200
|
+
// query (Product.find(id)), from your project's config.
|
|
1201
|
+
static override schema = schema;
|
|
1202
|
+
|
|
1203
|
+
// A method every record has:
|
|
1204
|
+
// label() {
|
|
1205
|
+
// return \`\${this.constructor.name} \${JSON.stringify(this.attributes())}\`;
|
|
1206
|
+
// }
|
|
1207
|
+
|
|
1208
|
+
// A scope every Model has, in SQL since it runs on each Model's own table (import sql too):
|
|
1209
|
+
// static newest = this.scope((q) => q.order(sql\`created_at DESC\`));
|
|
1210
|
+
|
|
1211
|
+
// Log every query, from every Model, in production too (import type QueryListener too; the
|
|
1212
|
+
// guide's Connecting page shows development-only logging, and one request's queries):
|
|
1213
|
+
// static override onQuery: QueryListener = ({ model, sql, durationMs }) =>
|
|
1214
|
+
// console.log(\`\${model} \${durationMs.toFixed(1)}ms \${sql}\`);
|
|
1215
|
+
|
|
1216
|
+
// Values of attributes named like these show as "[FILTERED]" to onQuery and in errors. These
|
|
1217
|
+
// are Rails' defaults (passwords, tokens, keys, emails…); add yours, or leave one out:
|
|
1218
|
+
// static override filterAttributes = [...Model.filterAttributes, "iban"];
|
|
1219
|
+
|
|
1220
|
+
// Attributes toJSON() leaves out, so Response.json(record) never sends them (exact names;
|
|
1221
|
+
// attributes() still has them):
|
|
1222
|
+
// static override hiddenAttributes = ["passwordDigest"];
|
|
1223
|
+
|
|
1224
|
+
// How new TEXT keys are made (a UUID by default), e.g. time-ordered ones from a
|
|
1225
|
+
// library you choose:
|
|
1226
|
+
// static override generateId = () => uuidv7();
|
|
1227
|
+
|
|
1228
|
+
static {
|
|
1229
|
+
// A callback that runs for every Model, before each Model's own:
|
|
1230
|
+
// this.beforeSave((record) => {
|
|
1231
|
+
// console.log(\`Saving \${record.constructor.name}\`);
|
|
1232
|
+
// });
|
|
1233
|
+
// Error messages in place of the built-in English, for every Model (a Model can declare
|
|
1234
|
+
// its own, and attributes: { email: { … } } is for one attribute):
|
|
1235
|
+
// this.errorMessages({ blank: "is required" });
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
`;
|
|
1239
|
+
}
|
|
1240
|
+
/** The fingerprint a generated file was made from, read from its header. */
|
|
1241
|
+
function fingerprintIn(source) {
|
|
1242
|
+
return /^\/\/ schema: ([0-9a-f]{12})$/m.exec(source)?.[1];
|
|
1243
|
+
}
|
|
1244
|
+
//#endregion
|
|
1245
|
+
//#region cli/schema/origin.ts
|
|
1246
|
+
const issue = "https://github.com/forestfuture/active-record/issues/73";
|
|
1247
|
+
/** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
|
|
1248
|
+
const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
|
|
1249
|
+
/**
|
|
1250
|
+
* The hint for migrations in folders, when `hasNestedMigrations` found them: the pattern to set,
|
|
1251
|
+
* when the adapter reads one (`setting`), or that they aren't read.
|
|
1252
|
+
*/
|
|
1253
|
+
function layoutNote(cwd, target, setting) {
|
|
1254
|
+
const dir = target.migrationsDir;
|
|
1255
|
+
const found = `${shown$1(cwd, dir)}/ has its migrations in folders, as Drizzle writes them`;
|
|
1256
|
+
if (setting === void 0) return `${found}, which aren't read`;
|
|
1257
|
+
return `${found}; set ${setting} to "${`${shown$1(target.configDir, dir)}/*/migration.sql`}" in ${shown$1(cwd, target.configFile)}, so they're read`;
|
|
1258
|
+
}
|
|
1259
|
+
/** The columns worth checking, in a schema from `tool`'s migrations. */
|
|
1260
|
+
function columnNotes(tool, tables) {
|
|
1261
|
+
const notes = [];
|
|
1262
|
+
for (const table of tables) for (const [attribute, spec] of Object.entries(table.attributes)) {
|
|
1263
|
+
const column = spec.column ?? underscore(attribute);
|
|
1264
|
+
const words = underscore(column);
|
|
1265
|
+
const where = `${table.name}.${column}`;
|
|
1266
|
+
if (spec.type === "integer" && words.endsWith("_at")) notes.push(`${where}: read as an integer; if it holds a Unix timestamp, override it in its Model as ` + storageOverride(tool === "Drizzle"));
|
|
1267
|
+
else if (spec.type === "string" && jsonish.test(words)) notes.push(`${where}: read as a string; if it holds JSON, override it as "json" in its Model`);
|
|
1268
|
+
}
|
|
1269
|
+
return notes;
|
|
1270
|
+
}
|
|
1271
|
+
/** A note for a datetime whose default writes the database's own date text, which sorts apart from ISO (#143). */
|
|
1272
|
+
function textDateNote(where) {
|
|
1273
|
+
return `${where}: its default writes the database's own date text (2026-10-12 06:38:30), where active-record writes ISO text (2026-10-12T06:38:30.000Z), and the two sort apart as text, so range conditions can misplace values within a day (see Existing databases in the guide)`;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Notes for a schema generated from another tool's migrations: the tool, then the columns to
|
|
1277
|
+
* check, and `textDates`, the datetime columns whose default is the database's own date text.
|
|
1278
|
+
*/
|
|
1279
|
+
function originNotes(tool, tables, textDates) {
|
|
1280
|
+
if (tool === void 0) return [];
|
|
1281
|
+
return [
|
|
1282
|
+
`these migrations look like ${tool}'s. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (${issue})`,
|
|
1283
|
+
...columnNotes(tool, tables),
|
|
1284
|
+
...textDates.map(textDateNote)
|
|
1285
|
+
];
|
|
1286
|
+
}
|
|
1287
|
+
//#endregion
|
|
1288
|
+
//#region cli/schema/writes.ts
|
|
1289
|
+
/** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
|
|
1290
|
+
function baseWrites(cwd, db) {
|
|
1291
|
+
const { target } = db;
|
|
1292
|
+
if (db.hasBase) return [];
|
|
1293
|
+
const { path, className } = target.base;
|
|
1294
|
+
return [written({
|
|
1295
|
+
path,
|
|
1296
|
+
source: renderBase(className, importPath(dirname(path), target.out))
|
|
1297
|
+
}, `Wrote ${shown$1(cwd, path)}`)];
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* Why the schema can't be written where it's going, if it can't: a file the command didn't write
|
|
1301
|
+
* (a Drizzle schema, say) is never replaced, and a file next to a folder of the same name would
|
|
1302
|
+
* take over that folder's imports (`@/db/schema` finds `schema.ts` before `schema/index.ts`).
|
|
1303
|
+
*/
|
|
1304
|
+
function schemaRefusal(cwd, db) {
|
|
1305
|
+
const out = shown$1(cwd, db.target.out);
|
|
1306
|
+
const folder = db.target.out.replace(/\.ts$/, "");
|
|
1307
|
+
const suggestion = "choose another file with --out, such as --out src/db/active-record.ts";
|
|
1308
|
+
if (db.schemaFolder) return `${out} would take over imports of the folder ${shown$1(cwd, folder)}/ (an import of ${basename(folder)} finds the file first), so it isn't written; ${suggestion}`;
|
|
1309
|
+
if (db.schema !== void 0 && fingerprintIn(db.schema) === void 0) return `${out} wasn't written by active-record schema (it has no "Generated by" header), so it's left as it is; ${suggestion}`;
|
|
1310
|
+
}
|
|
1311
|
+
/** The adapter a schema imports: the plugin's name is its factory's, from the adapter's package. */
|
|
1312
|
+
function schemaAdapterOf(adapter) {
|
|
1313
|
+
return {
|
|
1314
|
+
factory: adapter.name,
|
|
1315
|
+
from: adapterEntry(adapter)
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
/** What a database's schema is rendered from: its adapter, tables and binding, and the Models found. */
|
|
1319
|
+
function schemaSourceOf(project, db, tables) {
|
|
1320
|
+
const { target } = db;
|
|
1321
|
+
const models = db.models.map(({ className, table, file }) => ({
|
|
1322
|
+
className,
|
|
1323
|
+
table,
|
|
1324
|
+
module: importPath(dirname(target.out), file)
|
|
1325
|
+
}));
|
|
1326
|
+
return {
|
|
1327
|
+
adapter: schemaAdapterOf(project.adapter),
|
|
1328
|
+
tables,
|
|
1329
|
+
binding: target.database.binding,
|
|
1330
|
+
models
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* What writing a database's schema takes, once its tables are known: the schema file (unless
|
|
1335
|
+
* it's unchanged), the base class when it's missing, and the notes.
|
|
1195
1336
|
*/
|
|
1196
|
-
function
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
// static override onQuery: QueryListener = ({ model, sql, durationMs }) =>
|
|
1221
|
-
// console.log(\`\${model} \${durationMs.toFixed(1)}ms \${sql}\`);
|
|
1222
|
-
|
|
1223
|
-
// Values of attributes named like these show as "[FILTERED]" to onQuery and in errors. These
|
|
1224
|
-
// are Rails' defaults (passwords, tokens, keys, emails…); add yours, or leave one out:
|
|
1225
|
-
// static override filterAttributes = [...Model.filterAttributes, "iban"];
|
|
1226
|
-
|
|
1227
|
-
// Attributes toJSON() leaves out, so Response.json(record) never sends them (exact names;
|
|
1228
|
-
// attributes() still has them):
|
|
1229
|
-
// static override hiddenAttributes = ["passwordDigest"];
|
|
1230
|
-
|
|
1231
|
-
// How new TEXT keys are made (a UUID by default), e.g. time-ordered ones from a
|
|
1232
|
-
// library you choose:
|
|
1233
|
-
// static override generateId = () => uuidv7();
|
|
1234
|
-
|
|
1235
|
-
static {
|
|
1236
|
-
// A callback that runs for every Model, before each Model's own:
|
|
1237
|
-
// this.beforeSave((record) => {
|
|
1238
|
-
// console.log(\`Saving \${record.constructor.name}\`);
|
|
1239
|
-
// });
|
|
1240
|
-
// Error messages in place of the built-in English, for every Model (a Model can declare
|
|
1241
|
-
// its own, and attributes: { email: { … } } is for one attribute):
|
|
1242
|
-
// this.errorMessages({ blank: "is required" });
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
`;
|
|
1246
|
-
}
|
|
1247
|
-
/** The fingerprint a generated file was made from, read from its header. */
|
|
1248
|
-
function fingerprintIn(source) {
|
|
1249
|
-
return /^\/\/ schema: ([0-9a-f]{12})$/m.exec(source)?.[1];
|
|
1337
|
+
function schemaWrites(project, db, result) {
|
|
1338
|
+
const { cwd } = project;
|
|
1339
|
+
const { target } = db;
|
|
1340
|
+
const out = shown$1(cwd, target.out);
|
|
1341
|
+
const source = `${shown$1(cwd, target.migrationsDir)}/`;
|
|
1342
|
+
const rendered = renderSchema(schemaSourceOf(project, db, result.tables), source);
|
|
1343
|
+
const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
|
|
1344
|
+
const setting = project.adapter.patternSetting;
|
|
1345
|
+
const notes = db.nestedMigrations ? [layoutNote(cwd, target, setting)] : [];
|
|
1346
|
+
const steps = [];
|
|
1347
|
+
if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
|
|
1348
|
+
else {
|
|
1349
|
+
steps.push(written({
|
|
1350
|
+
path: target.out,
|
|
1351
|
+
source: rendered
|
|
1352
|
+
}, `Wrote ${out} (${count}) from ${source}`));
|
|
1353
|
+
const tool = migrationTool(db.toolsFound, db.migrations ?? []);
|
|
1354
|
+
notes.unshift(...result.notes, ...originNotes(tool, result.tables, result.textDates));
|
|
1355
|
+
}
|
|
1356
|
+
steps.push(...baseWrites(cwd, db), ...notes.map((note) => ({ line: `Note: ${note}` })));
|
|
1357
|
+
return {
|
|
1358
|
+
steps,
|
|
1359
|
+
code: 0
|
|
1360
|
+
};
|
|
1250
1361
|
}
|
|
1251
1362
|
//#endregion
|
|
1252
1363
|
//#region cli/schema/models.ts
|
|
@@ -1268,10 +1379,14 @@ async function freshSchemas(jiti, project, placeholders) {
|
|
|
1268
1379
|
const schemas = /* @__PURE__ */ new Map();
|
|
1269
1380
|
for (const db of project.databases) {
|
|
1270
1381
|
const { database, out } = db.target;
|
|
1271
|
-
const migrationsTable = database
|
|
1272
|
-
const result = project.adapter.readSchema(db.migrations ?? [], {
|
|
1382
|
+
const { migrationsTable, entry } = database;
|
|
1383
|
+
const result = await project.adapter.readSchema(db.migrations ?? [], {
|
|
1384
|
+
migrationsTable,
|
|
1385
|
+
entry
|
|
1386
|
+
});
|
|
1273
1387
|
if (db.migrations === void 0 || !result.ok) continue;
|
|
1274
1388
|
const source = renderSchema({
|
|
1389
|
+
adapter: schemaAdapterOf(project.adapter),
|
|
1275
1390
|
tables: result.tables,
|
|
1276
1391
|
binding: database.binding,
|
|
1277
1392
|
models: []
|
|
@@ -1394,110 +1509,6 @@ async function withModels(project, { models = defaultModels, check = false } = {
|
|
|
1394
1509
|
}
|
|
1395
1510
|
}
|
|
1396
1511
|
//#endregion
|
|
1397
|
-
//#region cli/schema/origin.ts
|
|
1398
|
-
const issue = "https://github.com/forestfuture/active-record/issues/73";
|
|
1399
|
-
/** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
|
|
1400
|
-
const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
|
|
1401
|
-
/** Wrangler's hint for migrations in folders, when `hasNestedMigrations` found them. */
|
|
1402
|
-
function layoutNote(cwd, target) {
|
|
1403
|
-
const dir = target.migrationsDir;
|
|
1404
|
-
const pattern = `${shown$1(target.configDir, dir)}/*/migration.sql`;
|
|
1405
|
-
return `${shown$1(cwd, dir)}/ has its migrations in folders, as Drizzle writes them; set migrations_pattern to "${pattern}" in your Wrangler config, so Wrangler and d1-record read them`;
|
|
1406
|
-
}
|
|
1407
|
-
/** The columns worth checking, in a schema from `tool`'s migrations. */
|
|
1408
|
-
function columnNotes(tool, tables) {
|
|
1409
|
-
const notes = [];
|
|
1410
|
-
for (const table of tables) for (const [attribute, spec] of Object.entries(table.attributes)) {
|
|
1411
|
-
const column = spec.column ?? underscore(attribute);
|
|
1412
|
-
const words = underscore(column);
|
|
1413
|
-
const where = `${table.name}.${column}`;
|
|
1414
|
-
if (spec.type === "integer" && words.endsWith("_at")) notes.push(`${where}: read as an integer; if it holds a Unix timestamp, override it in its Model as ` + storageOverride(tool === "Drizzle"));
|
|
1415
|
-
else if (spec.type === "string" && jsonish.test(words)) notes.push(`${where}: read as a string; if it holds JSON, override it as "json" in its Model`);
|
|
1416
|
-
}
|
|
1417
|
-
return notes;
|
|
1418
|
-
}
|
|
1419
|
-
/** A note for a datetime whose default writes SQLite's date text, which sorts apart from ISO (#143). */
|
|
1420
|
-
function textDateNote(where) {
|
|
1421
|
-
return `${where}: its default writes SQLite's date text (2026-10-12 06:38:30), where d1-record writes ISO text (2026-10-12T06:38:30.000Z), and the two sort apart as text, so range conditions can misplace values within a day (see Existing databases in the guide)`;
|
|
1422
|
-
}
|
|
1423
|
-
/**
|
|
1424
|
-
* Notes for a schema generated from another tool's migrations: the tool, then the columns to
|
|
1425
|
-
* check, and `textDates`, the datetime columns whose default is SQLite's own date text.
|
|
1426
|
-
*/
|
|
1427
|
-
function originNotes(tool, tables, textDates) {
|
|
1428
|
-
if (tool === void 0) return [];
|
|
1429
|
-
return [
|
|
1430
|
-
`these migrations look like ${tool}'s. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (${issue})`,
|
|
1431
|
-
...columnNotes(tool, tables),
|
|
1432
|
-
...textDates.map(textDateNote)
|
|
1433
|
-
];
|
|
1434
|
-
}
|
|
1435
|
-
//#endregion
|
|
1436
|
-
//#region cli/schema/writes.ts
|
|
1437
|
-
/** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
|
|
1438
|
-
function baseWrites(cwd, db) {
|
|
1439
|
-
const { target } = db;
|
|
1440
|
-
if (db.hasBase) return [];
|
|
1441
|
-
const { path, className } = target.base;
|
|
1442
|
-
return [written({
|
|
1443
|
-
path,
|
|
1444
|
-
source: renderBase(className, importPath(dirname(path), target.out))
|
|
1445
|
-
}, `Wrote ${shown$1(cwd, path)}`)];
|
|
1446
|
-
}
|
|
1447
|
-
/**
|
|
1448
|
-
* Why the schema can't be written where it's going, if it can't: a file d1-record didn't write
|
|
1449
|
-
* (a Drizzle schema, say) is never replaced, and a file next to a folder of the same name would
|
|
1450
|
-
* take over that folder's imports (`@/db/schema` finds `schema.ts` before `schema/index.ts`).
|
|
1451
|
-
*/
|
|
1452
|
-
function schemaRefusal(cwd, db) {
|
|
1453
|
-
const out = shown$1(cwd, db.target.out);
|
|
1454
|
-
const folder = db.target.out.replace(/\.ts$/, "");
|
|
1455
|
-
const suggestion = "choose another file with --out, such as --out src/db/d1-record.ts";
|
|
1456
|
-
if (db.schemaFolder) return `${out} would take over imports of the folder ${shown$1(cwd, folder)}/ (an import of ${basename(folder)} finds the file first), so it isn't written; ${suggestion}`;
|
|
1457
|
-
if (db.schema !== void 0 && fingerprintIn(db.schema) === void 0) return `${out} wasn't written by active-record schema (it has no "Generated by" header), so it's left as it is; ${suggestion}`;
|
|
1458
|
-
}
|
|
1459
|
-
/** What a database's schema is rendered from: its tables, its binding, and the Models found. */
|
|
1460
|
-
function schemaSourceOf(db, tables) {
|
|
1461
|
-
const { target } = db;
|
|
1462
|
-
const models = db.models.map(({ className, table, file }) => ({
|
|
1463
|
-
className,
|
|
1464
|
-
table,
|
|
1465
|
-
module: importPath(dirname(target.out), file)
|
|
1466
|
-
}));
|
|
1467
|
-
return {
|
|
1468
|
-
tables,
|
|
1469
|
-
binding: target.database.binding,
|
|
1470
|
-
models
|
|
1471
|
-
};
|
|
1472
|
-
}
|
|
1473
|
-
/**
|
|
1474
|
-
* What writing a database's schema takes, once its tables are known: the schema file (unless
|
|
1475
|
-
* it's unchanged), the base class when it's missing, and the notes.
|
|
1476
|
-
*/
|
|
1477
|
-
function schemaWrites(cwd, db, result) {
|
|
1478
|
-
const { target } = db;
|
|
1479
|
-
const out = shown$1(cwd, target.out);
|
|
1480
|
-
const source = `${shown$1(cwd, target.migrationsDir)}/`;
|
|
1481
|
-
const rendered = renderSchema(schemaSourceOf(db, result.tables), source);
|
|
1482
|
-
const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
|
|
1483
|
-
const notes = db.nestedMigrations ? [layoutNote(cwd, target)] : [];
|
|
1484
|
-
const steps = [];
|
|
1485
|
-
if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
|
|
1486
|
-
else {
|
|
1487
|
-
steps.push(written({
|
|
1488
|
-
path: target.out,
|
|
1489
|
-
source: rendered
|
|
1490
|
-
}, `Wrote ${out} (${count}) from ${source}`));
|
|
1491
|
-
const tool = migrationTool(db.toolsFound, db.migrations ?? []);
|
|
1492
|
-
notes.unshift(...result.notes, ...originNotes(tool, result.tables, result.textDates));
|
|
1493
|
-
}
|
|
1494
|
-
steps.push(...baseWrites(cwd, db), ...notes.map((note) => ({ line: `Note: ${note}` })));
|
|
1495
|
-
return {
|
|
1496
|
-
steps,
|
|
1497
|
-
code: 0
|
|
1498
|
-
};
|
|
1499
|
-
}
|
|
1500
|
-
//#endregion
|
|
1501
1512
|
//#region cli/generate/columns.ts
|
|
1502
1513
|
const types$1 = [
|
|
1503
1514
|
"string",
|
|
@@ -1664,6 +1675,22 @@ function appendModel(existing, model) {
|
|
|
1664
1675
|
};
|
|
1665
1676
|
}
|
|
1666
1677
|
//#endregion
|
|
1678
|
+
//#region cli/generate/migration-file.ts
|
|
1679
|
+
/** `20261108090503`: the UTC second, as 14 digits. */
|
|
1680
|
+
function stamp(now) {
|
|
1681
|
+
return Number(now.toISOString().slice(0, 19).replaceAll(/\D/g, ""));
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* The next migration's file name: the current UTC second as its version, or one past the highest
|
|
1685
|
+
* version there when that's later, as Rails numbers them, so two written in one second stay in
|
|
1686
|
+
* order. Files numbered `0001_…` sort before it, on every adapter.
|
|
1687
|
+
*/
|
|
1688
|
+
function migrationFileName(existing, name, now) {
|
|
1689
|
+
const highest = Math.max(0, ...existing.map(leadingNumber).filter(Number.isFinite));
|
|
1690
|
+
const version = Math.max(stamp(now), highest + 1);
|
|
1691
|
+
return `${String(version).padStart(14, "0")}_${underscore(name)}.sql`;
|
|
1692
|
+
}
|
|
1693
|
+
//#endregion
|
|
1667
1694
|
//#region cli/generate/names.ts
|
|
1668
1695
|
/** A name the generators accept: letters, digits and `_`, starting with a letter. */
|
|
1669
1696
|
const allowed$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
@@ -1713,19 +1740,22 @@ function databaseFor(project, options) {
|
|
|
1713
1740
|
if (typeof chosen === "string") return chosen;
|
|
1714
1741
|
return project.databases.find((db) => db.target.database === chosen);
|
|
1715
1742
|
}
|
|
1716
|
-
/**
|
|
1743
|
+
/** Only migrations a database's pattern matches are applied, so refuse any other file. */
|
|
1717
1744
|
function patternRefusal({ project, db }, path) {
|
|
1718
1745
|
const { target } = db;
|
|
1719
1746
|
const pattern = target.database.migrationsPattern;
|
|
1720
1747
|
const relativePath = slashed(relative(target.configDir, path));
|
|
1721
1748
|
if (pattern === void 0 || process.getBuiltinModule("node:path").matchesGlob(relativePath, pattern)) return;
|
|
1722
|
-
return `${shown$1(project.cwd, path)} wouldn't match
|
|
1749
|
+
return `${shown$1(project.cwd, path)} wouldn't match ${project.adapter.patternSetting ?? "the pattern"} (${pattern}) in ${shown$1(project.cwd, target.configFile)}, so it wouldn't be applied; write the migration with your migration tool instead`;
|
|
1723
1750
|
}
|
|
1724
|
-
/**
|
|
1751
|
+
/**
|
|
1752
|
+
* Each table's key column's type, for the columns that reference it: as the adapter read it, or
|
|
1753
|
+
* else by its attribute's type.
|
|
1754
|
+
*/
|
|
1725
1755
|
function keyTypes(tables) {
|
|
1726
1756
|
return new Map(tables.map((table) => {
|
|
1727
1757
|
const spec = table.attributes[table.primaryKey];
|
|
1728
|
-
return [table.name, spec.type === "integer" ? "INTEGER" : "TEXT"];
|
|
1758
|
+
return [table.name, table.keyType ?? (spec.type === "integer" ? "INTEGER" : "TEXT")];
|
|
1729
1759
|
}));
|
|
1730
1760
|
}
|
|
1731
1761
|
/** Where `g model` writes a Model: its own file, or the one file Models are appended to. */
|
|
@@ -1766,17 +1796,16 @@ function modelFile(request) {
|
|
|
1766
1796
|
source: appended.source
|
|
1767
1797
|
} : refused(`${shown$1(cwd, path)}: ${appended.error}`);
|
|
1768
1798
|
}
|
|
1769
|
-
/** Notes for references to tables the migrations don't make yet: their key type is a guess. */
|
|
1770
|
-
function referenceNotes(columns, keys) {
|
|
1771
|
-
return columns.filter((column) => column.type === "references" && !keys.has(column.references)).map((column) => `${column.references} isn't in the migrations yet, so ${column.name} is TEXT`);
|
|
1772
|
-
}
|
|
1773
1799
|
/** The migration, checked by applying it after the others in memory; or why it was refused. */
|
|
1774
|
-
function checkedMigration(request, existing) {
|
|
1800
|
+
async function checkedMigration(request, existing) {
|
|
1775
1801
|
const { project, db, options, columns } = request;
|
|
1776
1802
|
const { adapter } = project;
|
|
1777
1803
|
const { target } = db;
|
|
1778
|
-
const migrationsTable = target.database
|
|
1779
|
-
const current = adapter.readSchema(existing, {
|
|
1804
|
+
const { migrationsTable, entry } = target.database;
|
|
1805
|
+
const current = await adapter.readSchema(existing, {
|
|
1806
|
+
migrationsTable,
|
|
1807
|
+
entry
|
|
1808
|
+
});
|
|
1780
1809
|
if (!current.ok) return refused(...current.errors);
|
|
1781
1810
|
const keys = keyTypes(current.tables);
|
|
1782
1811
|
const stem = request.className === void 0 ? options.name : `create_${tableize(request.className)}`;
|
|
@@ -1784,16 +1813,18 @@ function checkedMigration(request, existing) {
|
|
|
1784
1813
|
name: stem,
|
|
1785
1814
|
columns,
|
|
1786
1815
|
keys,
|
|
1787
|
-
existing: existing.map((each) => each.name),
|
|
1788
1816
|
options
|
|
1789
1817
|
});
|
|
1790
1818
|
if (!result.ok) return refused(result.error);
|
|
1791
|
-
const name =
|
|
1819
|
+
const name = migrationFileName(existing.map((each) => each.name), stem, /* @__PURE__ */ new Date());
|
|
1792
1820
|
const after = [...existing, {
|
|
1793
1821
|
name,
|
|
1794
1822
|
sql: result.sql
|
|
1795
|
-
}].sort((a, b) =>
|
|
1796
|
-
const checked = adapter.readSchema(after, {
|
|
1823
|
+
}].sort((a, b) => byVersion(a.name, b.name));
|
|
1824
|
+
const checked = await adapter.readSchema(after, {
|
|
1825
|
+
migrationsTable,
|
|
1826
|
+
entry
|
|
1827
|
+
});
|
|
1797
1828
|
if (!checked.ok) return refused(...checked.errors);
|
|
1798
1829
|
return {
|
|
1799
1830
|
migration: {
|
|
@@ -1802,7 +1833,7 @@ function checkedMigration(request, existing) {
|
|
|
1802
1833
|
},
|
|
1803
1834
|
after,
|
|
1804
1835
|
schema: checked,
|
|
1805
|
-
notes:
|
|
1836
|
+
notes: result.notes ?? []
|
|
1806
1837
|
};
|
|
1807
1838
|
}
|
|
1808
1839
|
/** The request: the database, the columns and the names, each checked. */
|
|
@@ -1838,12 +1869,12 @@ function withModel(models, added) {
|
|
|
1838
1869
|
return [...models.filter((each) => each.className !== added.className), added];
|
|
1839
1870
|
}
|
|
1840
1871
|
/** Checks everything a generator would write, before anything is written. */
|
|
1841
|
-
function checkedFor(project, options) {
|
|
1872
|
+
async function checkedFor(project, options) {
|
|
1842
1873
|
const request = requestFor(project, options);
|
|
1843
1874
|
if (isPlan(request)) return request;
|
|
1844
1875
|
const model = request.className === void 0 ? void 0 : modelFile(request);
|
|
1845
1876
|
if (model !== void 0 && isPlan(model)) return model;
|
|
1846
|
-
const checked = checkedMigration(request, request.db.migrations ?? []);
|
|
1877
|
+
const checked = await checkedMigration(request, request.db.migrations ?? []);
|
|
1847
1878
|
if (isPlan(checked)) return checked;
|
|
1848
1879
|
const refusal = patternRefusal(request, checked.migration.path);
|
|
1849
1880
|
if (refusal !== void 0) return unusable(refusal);
|
|
@@ -1869,13 +1900,13 @@ function checkedFor(project, options) {
|
|
|
1869
1900
|
* What `g model` or `g migration` writes and prints for a project: a migration (and a Model),
|
|
1870
1901
|
* checked against the existing migrations, then the schema regenerated with it.
|
|
1871
1902
|
*/
|
|
1872
|
-
function planGenerate(project, options) {
|
|
1873
|
-
const checked = checkedFor(project, options);
|
|
1903
|
+
async function planGenerate(project, options) {
|
|
1904
|
+
const checked = await checkedFor(project, options);
|
|
1874
1905
|
if (isPlan(checked)) return checked;
|
|
1875
1906
|
const { db, migration, model, notes } = checked;
|
|
1876
1907
|
const { cwd } = project;
|
|
1877
1908
|
const own = model === void 0 ? [migration] : [migration, model];
|
|
1878
|
-
const schema = schemaWrites(
|
|
1909
|
+
const schema = schemaWrites(project, db, checked.schema);
|
|
1879
1910
|
const named = project.databases.length > 1 ? ` --database ${db.target.database.binding}` : "";
|
|
1880
1911
|
return {
|
|
1881
1912
|
steps: [
|
|
@@ -1895,11 +1926,12 @@ function planGenerate(project, options) {
|
|
|
1895
1926
|
async function runGenerate(options, print) {
|
|
1896
1927
|
const cwd = resolve(options.cwd ?? process.cwd());
|
|
1897
1928
|
const { config, models, out } = options;
|
|
1898
|
-
const adapter = await loadAdapter(cwd, options.
|
|
1929
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
1899
1930
|
if (typeof adapter === "string") {
|
|
1900
1931
|
print(adapter);
|
|
1901
1932
|
return 1;
|
|
1902
1933
|
}
|
|
1934
|
+
for (const note of configNotes(adapter)) print(note);
|
|
1903
1935
|
const model = options.kind === "model" ? modelName(options.name) : void 0;
|
|
1904
1936
|
const files = model?.ok === true ? [modelPathOf(cwd, options, model.className)] : [];
|
|
1905
1937
|
const read = readProject(adapter, cwd, {
|
|
@@ -1911,7 +1943,7 @@ async function runGenerate(options, print) {
|
|
|
1911
1943
|
print(read);
|
|
1912
1944
|
return 1;
|
|
1913
1945
|
}
|
|
1914
|
-
return apply(planGenerate(await withModels(read, { models }), options), cwd, print);
|
|
1946
|
+
return apply(await planGenerate(await withModels(read, { models }), options), cwd, print);
|
|
1915
1947
|
}
|
|
1916
1948
|
//#endregion
|
|
1917
1949
|
//#region cli/generate/flags.ts
|
|
@@ -1930,11 +1962,11 @@ const generateSubcommand = defineSubcommand({
|
|
|
1930
1962
|
datetime, json or references; then ! for NOT NULL, =value for a default, and :unique or
|
|
1931
1963
|
:index for an index. For example: email:string!:unique active:boolean!=false user:references`,
|
|
1932
1964
|
flagHelp: `Options for g:
|
|
1933
|
-
--id integer Give the table an
|
|
1965
|
+
--id integer Give the table an integer key the database generates (a key made in code by default)
|
|
1934
1966
|
--no-timestamps Leave out created_at and updated_at
|
|
1935
1967
|
--models <path> Write Models here (src/models), or append them to one file (src/models.ts);
|
|
1936
1968
|
ApplicationRecord is imported from the same folder
|
|
1937
|
-
--database <name> The
|
|
1969
|
+
--database <name> The database to use, when the config has several
|
|
1938
1970
|
--out <file> The schema file to regenerate, when it isn't src/db/schema.ts`,
|
|
1939
1971
|
action({ values, positionals }, print, fail) {
|
|
1940
1972
|
const [kind, name, ...columns] = positionals;
|
|
@@ -1953,6 +1985,260 @@ datetime, json or references; then ! for NOT NULL, =value for a default, and :un
|
|
|
1953
1985
|
}
|
|
1954
1986
|
});
|
|
1955
1987
|
//#endregion
|
|
1988
|
+
//#region cli/init/insert.ts
|
|
1989
|
+
/** Just past the comment starting at `index`, or `index` when none starts there. */
|
|
1990
|
+
function pastComment(text, index) {
|
|
1991
|
+
if (text.startsWith("//", index)) {
|
|
1992
|
+
const end = text.indexOf("\n", index);
|
|
1993
|
+
return end < 0 ? text.length : end;
|
|
1994
|
+
}
|
|
1995
|
+
if (text.startsWith("/*", index)) {
|
|
1996
|
+
const end = text.indexOf("*/", index + 2);
|
|
1997
|
+
return end < 0 ? text.length : end + 2;
|
|
1998
|
+
}
|
|
1999
|
+
return index;
|
|
2000
|
+
}
|
|
2001
|
+
/** Just past the string starting at `start`. */
|
|
2002
|
+
function pastString(text, start) {
|
|
2003
|
+
let index = start + 1;
|
|
2004
|
+
while (index < text.length && text[index] !== "\"") index += text[index] === "\\" ? 2 : 1;
|
|
2005
|
+
return index + 1;
|
|
2006
|
+
}
|
|
2007
|
+
/** The text's tokens, in order: strings, and each other character that isn't space or a comment. */
|
|
2008
|
+
function tokensOf(text) {
|
|
2009
|
+
const tokens = [];
|
|
2010
|
+
let index = 0;
|
|
2011
|
+
while (index < text.length) {
|
|
2012
|
+
const comment = pastComment(text, index);
|
|
2013
|
+
if (comment > index) index = comment;
|
|
2014
|
+
else if (/\s/.test(text[index])) index += 1;
|
|
2015
|
+
else if (text[index] === "\"") {
|
|
2016
|
+
const end = pastString(text, index);
|
|
2017
|
+
tokens.push({
|
|
2018
|
+
start: index,
|
|
2019
|
+
end,
|
|
2020
|
+
value: JSON.parse(text.slice(index, end)),
|
|
2021
|
+
string: true
|
|
2022
|
+
});
|
|
2023
|
+
index = end;
|
|
2024
|
+
} else {
|
|
2025
|
+
tokens.push({
|
|
2026
|
+
start: index,
|
|
2027
|
+
end: index + 1,
|
|
2028
|
+
value: text[index],
|
|
2029
|
+
string: false
|
|
2030
|
+
});
|
|
2031
|
+
index += 1;
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
return tokens;
|
|
2035
|
+
}
|
|
2036
|
+
/** How a token changes the depth of nesting: an opening bracket 1, a closing one -1. */
|
|
2037
|
+
function depthChange({ value, string }) {
|
|
2038
|
+
if (string) return 0;
|
|
2039
|
+
if (value === "{" || value === "[") return 1;
|
|
2040
|
+
return value === "}" || value === "]" ? -1 : 0;
|
|
2041
|
+
}
|
|
2042
|
+
/** The index of the token that closes the object or array opened at `open`. */
|
|
2043
|
+
function closing(tokens, open) {
|
|
2044
|
+
let depth = 0;
|
|
2045
|
+
for (let index = open; index < tokens.length; index++) {
|
|
2046
|
+
depth += depthChange(tokens[index]);
|
|
2047
|
+
if (depth === 0) return index;
|
|
2048
|
+
}
|
|
2049
|
+
return tokens.length - 1;
|
|
2050
|
+
}
|
|
2051
|
+
/** Whether the tokens at `index` are the key `databases`, then `:` and an object's `{`. */
|
|
2052
|
+
function isDatabasesKey(tokens, index) {
|
|
2053
|
+
const key = tokens[index];
|
|
2054
|
+
return key.string && key.value === "databases" && tokens[index + 1]?.value === ":" && tokens[index + 2]?.value === "{";
|
|
2055
|
+
}
|
|
2056
|
+
/**
|
|
2057
|
+
* The indexes of the top-level `databases` object's `{` and `}`, if the text has one: the last,
|
|
2058
|
+
* when it has two, as JSON.parse (and so the command) reads it.
|
|
2059
|
+
*/
|
|
2060
|
+
function databasesObject(tokens) {
|
|
2061
|
+
let depth = 0;
|
|
2062
|
+
let found;
|
|
2063
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
2064
|
+
depth += depthChange(tokens[index]);
|
|
2065
|
+
if (depth === 1 && isDatabasesKey(tokens, index)) found = {
|
|
2066
|
+
open: index + 2,
|
|
2067
|
+
close: closing(tokens, index + 2)
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
return found;
|
|
2071
|
+
}
|
|
2072
|
+
/** The whitespace a line starts with, for the line holding `at`. */
|
|
2073
|
+
function indentAt(text, at) {
|
|
2074
|
+
const lineStart = text.lastIndexOf("\n", at - 1) + 1;
|
|
2075
|
+
return /^[ \t]*/.exec(text.slice(lineStart))[0];
|
|
2076
|
+
}
|
|
2077
|
+
/** The end of `at`'s line, before any `\r`, when only space and comments follow it there, or `at`. */
|
|
2078
|
+
function endOfLine(text, at) {
|
|
2079
|
+
const found = text.indexOf("\n", at);
|
|
2080
|
+
const end = found < 0 ? text.length : found;
|
|
2081
|
+
const lineEnd = text[end - 1] === "\r" ? end - 1 : end;
|
|
2082
|
+
for (let index = at; index < lineEnd;) {
|
|
2083
|
+
if (text.startsWith("//", index)) return lineEnd;
|
|
2084
|
+
const past = pastComment(text, index);
|
|
2085
|
+
if (past > lineEnd) return at;
|
|
2086
|
+
if (past > index) index = past;
|
|
2087
|
+
else if (text[index] === " " || text[index] === " ") index += 1;
|
|
2088
|
+
else return at;
|
|
2089
|
+
}
|
|
2090
|
+
return lineEnd;
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* The text with `entries` added at the end of its top-level `databases` object, each on a line of
|
|
2094
|
+
* its own (with the file's line endings), as the entries before it are indented, with a trailing
|
|
2095
|
+
* comma if the last one had one;
|
|
2096
|
+
* undefined when the text has no such object with an entry in it.
|
|
2097
|
+
*/
|
|
2098
|
+
function withEntries(text, entries) {
|
|
2099
|
+
const tokens = tokensOf(text);
|
|
2100
|
+
const object = databasesObject(tokens);
|
|
2101
|
+
if (object === void 0 || object.close - object.open < 2) return void 0;
|
|
2102
|
+
const last = tokens[object.close - 1];
|
|
2103
|
+
const trailing = last.value === "," && !last.string;
|
|
2104
|
+
const indent = indentAt(text, tokens[object.open + 1].start);
|
|
2105
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
2106
|
+
const lines = entries.map(([key, value]) => {
|
|
2107
|
+
const fields = Object.entries(value).map(([name, field]) => `${JSON.stringify(name)}: ${JSON.stringify(field)}`);
|
|
2108
|
+
return `${eol}${indent}${JSON.stringify(key)}: { ${fields.join(", ")} }`;
|
|
2109
|
+
});
|
|
2110
|
+
const after = endOfLine(text, last.end);
|
|
2111
|
+
const added = trailing ? lines.map((line) => `${line},`).join("") : lines.join(",");
|
|
2112
|
+
return `${text.slice(0, last.end)}${trailing ? "" : ","}${text.slice(last.end, after)}${added}${text.slice(after)}`;
|
|
2113
|
+
}
|
|
2114
|
+
//#endregion
|
|
2115
|
+
//#region cli/init/command.ts
|
|
2116
|
+
/** The JSON Schema the package ships for the file, which editors complete its keys from. */
|
|
2117
|
+
const schemaFile = "config-schema.json";
|
|
2118
|
+
/** The core package as the nearest `node_modules` holds it, or as the project's own will. */
|
|
2119
|
+
function installedCore(cwd, dir) {
|
|
2120
|
+
for (let at = dir;; at = dirname(at)) {
|
|
2121
|
+
const here = join(at, "node_modules", corePackage);
|
|
2122
|
+
if (existsSync(here)) return here;
|
|
2123
|
+
if (dirname(at) === at) return join(cwd, "node_modules", corePackage);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
/** The `$schema` link, from the file's folder to the schema in the installed package. */
|
|
2127
|
+
function schemaLink(cwd, dir) {
|
|
2128
|
+
const link = slashed(relative(dir, join(installedCore(cwd, dir), schemaFile)));
|
|
2129
|
+
return link.startsWith("../") ? link : `./${link}`;
|
|
2130
|
+
}
|
|
2131
|
+
/** The plugin `name`'s entries, chosen with `--adapter`, or why there are none. */
|
|
2132
|
+
async function chosenEntries(dir, name) {
|
|
2133
|
+
if (!adapterNames.includes(name)) return `--adapter takes ${listed(adapterNames)}, not ${name}`;
|
|
2134
|
+
const result = (await pluginOf(name)).init(dir, true);
|
|
2135
|
+
if (result === void 0) return `Nothing here declares a database for ${name}`;
|
|
2136
|
+
return typeof result === "string" ? result : {
|
|
2137
|
+
name,
|
|
2138
|
+
result
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
/** The entries of the one adapter something in the project points to, or why there isn't one. */
|
|
2142
|
+
async function foundEntries(dir) {
|
|
2143
|
+
const found = [];
|
|
2144
|
+
for (const name of adapterNames) {
|
|
2145
|
+
const result = (await pluginOf(name)).init(dir, false);
|
|
2146
|
+
if (typeof result === "string") return result;
|
|
2147
|
+
if (result !== void 0) found.push({
|
|
2148
|
+
name,
|
|
2149
|
+
result
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
if (found.length === 1) return found[0];
|
|
2153
|
+
if (found.length === 0) return `Nothing here says which database the project uses; choose ${listed(adapterNames)} with --adapter`;
|
|
2154
|
+
return `This project could use ${listed(found.map((each) => each.name))}; choose one with --adapter`;
|
|
2155
|
+
}
|
|
2156
|
+
/** The file's text: the schema link, then each database with its adapter first. */
|
|
2157
|
+
function source(link, { name, result }) {
|
|
2158
|
+
const databases = Object.fromEntries(Object.entries(result.databases).map(([binding, entry]) => [binding, {
|
|
2159
|
+
adapter: name,
|
|
2160
|
+
...entry
|
|
2161
|
+
}]));
|
|
2162
|
+
return `${JSON.stringify({
|
|
2163
|
+
$schema: link,
|
|
2164
|
+
databases
|
|
2165
|
+
}, null, 2)}\n`;
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* What `init` does when the file is there: add each database the adapter the file names finds and
|
|
2169
|
+
* the file doesn't name, keeping the rest of the text as written; or say why it can't.
|
|
2170
|
+
*/
|
|
2171
|
+
async function planAdding(cwd, path, options) {
|
|
2172
|
+
const name = shown$1(cwd, path);
|
|
2173
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
2174
|
+
if (typeof adapter === "string") return printing([adapter], 1);
|
|
2175
|
+
if (options.adapter !== void 0 && options.adapter !== adapter.name) return printing([`${name} names ${adapter.name}; a project uses one adapter, for now, so --adapter ${options.adapter} adds nothing`], 1);
|
|
2176
|
+
const found = adapter.init(dirname(path), false);
|
|
2177
|
+
if (typeof found === "string") return printing([found], 1);
|
|
2178
|
+
const text = readFileSync(path, "utf8");
|
|
2179
|
+
const named = parseJsonc(text).databases;
|
|
2180
|
+
const missing = Object.entries(found?.databases ?? {}).filter(([key]) => !Object.hasOwn(named, key));
|
|
2181
|
+
if (missing.length === 0) return printing([`${name} names every database init finds; it wrote nothing`]);
|
|
2182
|
+
const source = withEntries(text, missing.map(([key, entry]) => [key, {
|
|
2183
|
+
adapter: adapter.name,
|
|
2184
|
+
...entry
|
|
2185
|
+
}]));
|
|
2186
|
+
if (source === void 0) return printing([`${name}'s databases couldn't be found to add to`], 1);
|
|
2187
|
+
const bindings = missing.map(([key]) => key);
|
|
2188
|
+
const notes = bindings.flatMap((key) => found?.notes?.[key] ?? []).map((note) => printed(`Note: ${note}`));
|
|
2189
|
+
const added = `Added ${listed(bindings, "and")} to ${name} (on ${adapter.name})`;
|
|
2190
|
+
return {
|
|
2191
|
+
steps: [written({
|
|
2192
|
+
path,
|
|
2193
|
+
source
|
|
2194
|
+
}, added), ...notes],
|
|
2195
|
+
code: 0
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
/** What `init` does: write the file, and say what's next; or say why it can't. */
|
|
2199
|
+
async function planInit(options) {
|
|
2200
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
2201
|
+
const path = resolve(cwd, options.config ?? "active-record.jsonc");
|
|
2202
|
+
const name = shown$1(cwd, path);
|
|
2203
|
+
const there = lstatSync(path, { throwIfNoEntry: false });
|
|
2204
|
+
if (there?.isSymbolicLink() === true) return printing([`${name} is a link; init writes nothing through it`], 1);
|
|
2205
|
+
if (there !== void 0) return planAdding(cwd, path, options);
|
|
2206
|
+
const dir = dirname(path);
|
|
2207
|
+
const found = options.adapter === void 0 ? await foundEntries(dir) : await chosenEntries(dir, options.adapter);
|
|
2208
|
+
if (typeof found === "string") return printing([found], 1);
|
|
2209
|
+
const bindings = listed(Object.keys(found.result.databases), "and");
|
|
2210
|
+
const notes = Object.values(found.result.notes ?? {}).map((note) => printed(`Note: ${note}`));
|
|
2211
|
+
return {
|
|
2212
|
+
steps: [
|
|
2213
|
+
written({
|
|
2214
|
+
path,
|
|
2215
|
+
source: source(schemaLink(cwd, dir), found)
|
|
2216
|
+
}, `Wrote ${name} (${bindings}, on ${found.name})`),
|
|
2217
|
+
...notes,
|
|
2218
|
+
printed("Next: npx active-record schema")
|
|
2219
|
+
],
|
|
2220
|
+
code: 0
|
|
2221
|
+
};
|
|
2222
|
+
}
|
|
2223
|
+
/** `active-record init`: resolves to the exit code. */
|
|
2224
|
+
async function runInit(options, print) {
|
|
2225
|
+
return apply(await planInit(options), resolve(options.cwd ?? process.cwd()), print);
|
|
2226
|
+
}
|
|
2227
|
+
//#endregion
|
|
2228
|
+
//#region cli/init/flags.ts
|
|
2229
|
+
/** `active-record init`: writes the project's active-record.jsonc. */
|
|
2230
|
+
const initSubcommand = defineSubcommand({
|
|
2231
|
+
options: { adapter: { type: "string" } },
|
|
2232
|
+
usage: ` active-record init Write active-record.jsonc, which names your databases`,
|
|
2233
|
+
flagHelp: `Options for init:
|
|
2234
|
+
--adapter <name> The adapter, when the project could use several, or nothing says which`,
|
|
2235
|
+
action({ values, positionals }, print, fail) {
|
|
2236
|
+
if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
|
|
2237
|
+
const { help: _, ...options } = values;
|
|
2238
|
+
return runInit(options, print);
|
|
2239
|
+
}
|
|
2240
|
+
});
|
|
2241
|
+
//#endregion
|
|
1956
2242
|
//#region cli/migrate/command.ts
|
|
1957
2243
|
const standardIo = () => ({
|
|
1958
2244
|
input: process.stdin,
|
|
@@ -1975,11 +2261,12 @@ async function allowed(target, options, io) {
|
|
|
1975
2261
|
/** `active-record migrate`: resolves to the exit code, the adapter's own when it ran. */
|
|
1976
2262
|
async function runMigrate(options, print, io = standardIo()) {
|
|
1977
2263
|
const cwd = options.cwd ?? process.cwd();
|
|
1978
|
-
const adapter = await loadAdapter(cwd, options.
|
|
2264
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
1979
2265
|
if (typeof adapter === "string") {
|
|
1980
2266
|
print(adapter);
|
|
1981
2267
|
return 1;
|
|
1982
2268
|
}
|
|
2269
|
+
for (const note of configNotes(adapter)) print(note);
|
|
1983
2270
|
const chosen = chosenDatabase(adapter, cwd, options);
|
|
1984
2271
|
if (typeof chosen === "string") {
|
|
1985
2272
|
print(chosen);
|
|
@@ -2026,40 +2313,44 @@ function failed(errors, cwd, db) {
|
|
|
2026
2313
|
return printing([...errors, kept], 1);
|
|
2027
2314
|
}
|
|
2028
2315
|
/** `--check`: whether the file on disk was generated from these tables (its fingerprint, not its format). */
|
|
2029
|
-
function checkPlan(
|
|
2030
|
-
const out = shown$1(cwd, db.target.out);
|
|
2031
|
-
const schema = schemaSourceOf(db, tables);
|
|
2316
|
+
function checkPlan(project, db, tables) {
|
|
2317
|
+
const out = shown$1(project.cwd, db.target.out);
|
|
2318
|
+
const schema = schemaSourceOf(project, db, tables);
|
|
2032
2319
|
const current = db.schema !== void 0 && fingerprintIn(db.schema) === fingerprintOf(schema);
|
|
2033
2320
|
return printing([current ? `${out} is up to date` : `${out} is out of date: run \`active-record schema\``], current ? 0 : 1);
|
|
2034
2321
|
}
|
|
2035
2322
|
/** One database's schema, generated (or, with `check`, checked). */
|
|
2036
|
-
function planDatabase(project, db, check) {
|
|
2323
|
+
async function planDatabase(project, db, check) {
|
|
2037
2324
|
const { adapter, cwd } = project;
|
|
2038
2325
|
if (db.migrations === void 0) return failed([`No migrations folder at ${shown$1(cwd, db.target.migrationsDir)}/`], cwd, db);
|
|
2039
2326
|
const refusal = check ? void 0 : schemaRefusal(cwd, db);
|
|
2040
2327
|
if (refusal !== void 0) return failed([refusal], cwd, db);
|
|
2041
2328
|
if (db.modelErrors.length > 0) return failed(db.modelErrors, cwd, db);
|
|
2042
|
-
const migrationsTable = db.target.database
|
|
2043
|
-
const result = adapter.readSchema(db.migrations, {
|
|
2329
|
+
const { migrationsTable, entry } = db.target.database;
|
|
2330
|
+
const result = await adapter.readSchema(db.migrations, {
|
|
2331
|
+
migrationsTable,
|
|
2332
|
+
entry
|
|
2333
|
+
});
|
|
2044
2334
|
if (!result.ok) return failed(result.errors, cwd, db);
|
|
2045
|
-
return check ? checkPlan(
|
|
2335
|
+
return check ? checkPlan(project, db, result.tables) : schemaWrites(project, db, result);
|
|
2046
2336
|
}
|
|
2047
2337
|
/** What `active-record schema` writes and prints for a project (or, with `check`, only prints). */
|
|
2048
|
-
function planSchema(project, check) {
|
|
2049
|
-
return combined(project.databases.map((db) => planDatabase(project, db, check)));
|
|
2338
|
+
async function planSchema(project, check) {
|
|
2339
|
+
return combined(await Promise.all(project.databases.map((db) => planDatabase(project, db, check))));
|
|
2050
2340
|
}
|
|
2051
2341
|
/**
|
|
2052
|
-
* `active-record schema`: generates each
|
|
2342
|
+
* `active-record schema`: generates each database's `schema.ts` from its migrations and the Models
|
|
2053
2343
|
* built on it (#66, #68, #232). Resolves to the exit code: 0, or 1 when anything failed or, with
|
|
2054
2344
|
* `check`, is out of date.
|
|
2055
2345
|
*/
|
|
2056
2346
|
async function runSchema(options, print) {
|
|
2057
2347
|
const cwd = resolve(options.cwd ?? process.cwd());
|
|
2058
|
-
const adapter = await loadAdapter(cwd, options.
|
|
2348
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
2059
2349
|
if (typeof adapter === "string") {
|
|
2060
2350
|
print(adapter);
|
|
2061
2351
|
return 1;
|
|
2062
2352
|
}
|
|
2353
|
+
for (const note of configNotes(adapter)) print(note);
|
|
2063
2354
|
const read = readProject(adapter, cwd, options);
|
|
2064
2355
|
if (typeof read === "string") {
|
|
2065
2356
|
print(read);
|
|
@@ -2069,7 +2360,21 @@ async function runSchema(options, print) {
|
|
|
2069
2360
|
models: options.models,
|
|
2070
2361
|
check: options.check
|
|
2071
2362
|
});
|
|
2072
|
-
return apply(planSchema(project, options.check === true), project.cwd, print);
|
|
2363
|
+
return apply(await planSchema(project, options.check === true), project.cwd, print);
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* `active-record schema --watch` from the command line: watching, once its adapter loads; or, when
|
|
2367
|
+
* it can't (none installed, or a Node it can't run on), 1, having said why, as a run without
|
|
2368
|
+
* `--watch` would.
|
|
2369
|
+
*/
|
|
2370
|
+
async function watchFromCommandLine(options, print) {
|
|
2371
|
+
const adapter = await loadAdapter(resolve(options.cwd ?? process.cwd()), options.config);
|
|
2372
|
+
if (typeof adapter === "string") {
|
|
2373
|
+
print(adapter);
|
|
2374
|
+
return 1;
|
|
2375
|
+
}
|
|
2376
|
+
watchSchema(options, print);
|
|
2377
|
+
return "watching";
|
|
2073
2378
|
}
|
|
2074
2379
|
/**
|
|
2075
2380
|
* `active-record schema --watch`: generates, then again whenever a migration or a Model file changes,
|
|
@@ -2078,7 +2383,7 @@ async function runSchema(options, print) {
|
|
|
2078
2383
|
async function watchSchema(options, print) {
|
|
2079
2384
|
let running = runSchema(options, print);
|
|
2080
2385
|
const cwd = resolve(options.cwd ?? process.cwd());
|
|
2081
|
-
const adapter = await loadAdapter(cwd, options.
|
|
2386
|
+
const adapter = await loadAdapter(cwd, options.config);
|
|
2082
2387
|
if (typeof adapter === "string") return () => {};
|
|
2083
2388
|
const project = readProject(adapter, cwd, options);
|
|
2084
2389
|
if (typeof project === "string") return () => {};
|
|
@@ -2099,6 +2404,7 @@ async function watchSchema(options, print) {
|
|
|
2099
2404
|
//#region cli/main.ts
|
|
2100
2405
|
/** Each subcommand by the names it answers to. */
|
|
2101
2406
|
const subcommands = {
|
|
2407
|
+
init: initSubcommand,
|
|
2102
2408
|
schema: defineSubcommand({
|
|
2103
2409
|
options: {
|
|
2104
2410
|
check: { type: "boolean" },
|
|
@@ -2107,7 +2413,7 @@ const subcommands = {
|
|
|
2107
2413
|
migrations: { type: "string" },
|
|
2108
2414
|
models: { type: "string" }
|
|
2109
2415
|
},
|
|
2110
|
-
usage: ` active-record schema [options] Generate src/db/schema.ts from your
|
|
2416
|
+
usage: ` active-record schema [options] Generate src/db/schema.ts from your migrations`,
|
|
2111
2417
|
flagHelp: `Options for schema:
|
|
2112
2418
|
--check Fail if the generated schema is out of date (for CI)
|
|
2113
2419
|
--watch Regenerate whenever a migration changes
|
|
@@ -2117,9 +2423,7 @@ const subcommands = {
|
|
|
2117
2423
|
action({ values, positionals }, print, fail) {
|
|
2118
2424
|
const { watch, help: _, ...options } = values;
|
|
2119
2425
|
if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
|
|
2120
|
-
|
|
2121
|
-
watchSchema(options, print);
|
|
2122
|
-
return "watching";
|
|
2426
|
+
return watch ? watchFromCommandLine(options, print) : runSchema(options, print);
|
|
2123
2427
|
}
|
|
2124
2428
|
}),
|
|
2125
2429
|
g: generateSubcommand,
|
|
@@ -2134,7 +2438,17 @@ function usage(print, problem) {
|
|
|
2134
2438
|
print(`${problem}\n\n${help}`);
|
|
2135
2439
|
return 1;
|
|
2136
2440
|
}
|
|
2137
|
-
/**
|
|
2441
|
+
/**
|
|
2442
|
+
* Whether this Node has what the command itself uses: `process.getBuiltinModule`, `fs.globSync`
|
|
2443
|
+
* and `path.matchesGlob` (Node 22.5; Node 20 has only the first and last). A plugin says what
|
|
2444
|
+
* it needs itself, with `unsupported`.
|
|
2445
|
+
*/
|
|
2446
|
+
function isSupportedNode() {
|
|
2447
|
+
if (typeof process.getBuiltinModule !== "function") return false;
|
|
2448
|
+
const { globSync } = process.getBuiltinModule("node:fs");
|
|
2449
|
+
return globSync !== void 0 && process.getBuiltinModule("node:path").matchesGlob !== void 0;
|
|
2450
|
+
}
|
|
2451
|
+
/** Runs the command line: the exit code, or "watching" while `schema --watch` runs on. */
|
|
2138
2452
|
function main(argv, print = console.log) {
|
|
2139
2453
|
const [command = "", ...rest] = argv;
|
|
2140
2454
|
const subcommand = Object.hasOwn(subcommands, command) ? subcommands[command] : void 0;
|
|
@@ -2143,8 +2457,8 @@ function main(argv, print = console.log) {
|
|
|
2143
2457
|
print(help);
|
|
2144
2458
|
return asked ? 0 : 1;
|
|
2145
2459
|
}
|
|
2146
|
-
if (
|
|
2147
|
-
print(`active-record ${command} needs Node 22.
|
|
2460
|
+
if (!isSupportedNode()) {
|
|
2461
|
+
print(`active-record ${command} needs Node 22.5 or later (this is Node ${process.versions.node})`);
|
|
2148
2462
|
return 1;
|
|
2149
2463
|
}
|
|
2150
2464
|
return subcommand.run(rest, print, (problem) => usage(print, problem));
|