@cossackframework/database 0.8.3 → 0.9.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 +6 -7
- package/agent-docs.json +90 -0
- package/dist/adapter/types.d.ts +14 -1
- package/dist/adapter/types.d.ts.map +1 -1
- package/dist/config.d.ts +10 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/cossack/cache-policy.d.ts +18 -0
- package/dist/cossack/cache-policy.d.ts.map +1 -0
- package/dist/cossack/cache-policy.js +64 -0
- package/dist/cossack/cache-policy.js.map +1 -0
- package/dist/cossack/index.d.ts +20 -3
- package/dist/cossack/index.d.ts.map +1 -1
- package/dist/cossack/index.js +105 -51
- package/dist/cossack/index.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/metadata/finalize.d.ts.map +1 -1
- package/dist/metadata/finalize.js +22 -5
- package/dist/metadata/finalize.js.map +1 -1
- package/dist/metadata/inspection.d.ts +51 -0
- package/dist/metadata/inspection.d.ts.map +1 -0
- package/dist/metadata/inspection.js +19 -0
- package/dist/metadata/inspection.js.map +1 -0
- package/dist/migration/plan.d.ts +13 -0
- package/dist/migration/plan.d.ts.map +1 -0
- package/dist/migration/plan.js +73 -0
- package/dist/migration/plan.js.map +1 -0
- package/dist/migration/runner.d.ts +13 -3
- package/dist/migration/runner.d.ts.map +1 -1
- package/dist/migration/runner.js +143 -11
- package/dist/migration/runner.js.map +1 -1
- package/dist/migration/types.d.ts +42 -2
- package/dist/migration/types.d.ts.map +1 -1
- package/dist/orm.d.ts +51 -0
- package/dist/orm.d.ts.map +1 -1
- package/dist/orm.js +44 -11
- package/dist/orm.js.map +1 -1
- package/dist/query/builder.d.ts +3 -2
- package/dist/query/builder.d.ts.map +1 -1
- package/dist/query/builder.js +63 -12
- package/dist/query/builder.js.map +1 -1
- package/dist/query/diagnostics.d.ts +3 -0
- package/dist/query/diagnostics.d.ts.map +1 -0
- package/dist/query/diagnostics.js +75 -0
- package/dist/query/diagnostics.js.map +1 -0
- package/dist/runtime/cloudflare-turso.d.ts +29 -0
- package/dist/runtime/cloudflare-turso.d.ts.map +1 -0
- package/dist/runtime/cloudflare-turso.js +47 -0
- package/dist/runtime/cloudflare-turso.js.map +1 -0
- package/dist/runtime/cloudflare.d.ts +1 -26
- package/dist/runtime/cloudflare.d.ts.map +1 -1
- package/dist/runtime/cloudflare.js +4 -45
- package/dist/runtime/cloudflare.js.map +1 -1
- package/dist/runtime/node.d.ts +2 -0
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +6 -1
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/turso.d.ts +5 -1
- package/dist/runtime/turso.d.ts.map +1 -1
- package/dist/runtime/turso.js +19 -5
- package/dist/runtime/turso.js.map +1 -1
- package/dist/runtime-capabilities.d.ts +25 -0
- package/dist/runtime-capabilities.d.ts.map +1 -0
- package/dist/runtime-capabilities.js +17 -0
- package/dist/runtime-capabilities.js.map +1 -0
- package/dist/schema/builder.d.ts.map +1 -1
- package/dist/schema/builder.js +6 -10
- package/dist/schema/builder.js.map +1 -1
- package/dist/schema/ddl.d.ts.map +1 -1
- package/dist/schema/ddl.js +29 -5
- package/dist/schema/ddl.js.map +1 -1
- package/dist/schema/introspection.d.ts +3 -1
- package/dist/schema/introspection.d.ts.map +1 -1
- package/dist/schema/introspection.js +9 -7
- package/dist/schema/introspection.js.map +1 -1
- package/dist/seeding/runner.d.ts +5 -1
- package/dist/seeding/runner.d.ts.map +1 -1
- package/dist/seeding/runner.js +66 -1
- package/dist/seeding/runner.js.map +1 -1
- package/dist/seeding/types.d.ts +15 -1
- package/dist/seeding/types.d.ts.map +1 -1
- package/dist/seeding/types.js.map +1 -1
- package/dist/sql/client.d.ts +1 -1
- package/dist/sql/client.d.ts.map +1 -1
- package/dist/sql/client.js +10 -51
- package/dist/sql/client.js.map +1 -1
- package/dist/sql/node-client.d.ts +7 -0
- package/dist/sql/node-client.d.ts.map +1 -0
- package/dist/sql/node-client.js +61 -0
- package/dist/sql/node-client.js.map +1 -0
- package/dist/tooling/cloudflare.d.ts +61 -0
- package/dist/tooling/cloudflare.d.ts.map +1 -0
- package/dist/tooling/cloudflare.js +130 -0
- package/dist/tooling/cloudflare.js.map +1 -0
- package/dist/tooling/generate.d.ts.map +1 -1
- package/dist/tooling/generate.js +5 -15
- package/dist/tooling/generate.js.map +1 -1
- package/dist/tooling/index.d.ts +6 -2
- package/dist/tooling/index.d.ts.map +1 -1
- package/dist/tooling/index.js +231 -64
- package/dist/tooling/index.js.map +1 -1
- package/dist/tooling/inspection.d.ts +40 -0
- package/dist/tooling/inspection.d.ts.map +1 -0
- package/dist/tooling/inspection.js +63 -0
- package/dist/tooling/inspection.js.map +1 -0
- package/dist/tooling/process-json.d.ts +4 -0
- package/dist/tooling/process-json.d.ts.map +1 -0
- package/dist/tooling/process-json.js +79 -0
- package/dist/tooling/process-json.js.map +1 -0
- package/docs/comparison.md +3 -3
- package/docs/inspection.md +50 -0
- package/docs/installation.md +0 -2
- package/docs/introduction.md +1 -1
- package/docs/migrations.md +90 -1
- package/docs/queries.md +18 -0
- package/docs/raw-queries.md +19 -4
- package/docs/relationships.md +11 -0
- package/docs/runtimes.md +77 -36
- package/docs/seeders.md +38 -0
- package/package.json +5 -4
- package/dist/runtime/deno.d.ts +0 -38
- package/dist/runtime/deno.d.ts.map +0 -1
- package/dist/runtime/deno.js +0 -57
- package/dist/runtime/deno.js.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { createORM } from '../orm.js';
|
|
3
|
+
import { inspectFinalizedMetadata } from '../metadata/inspection.js';
|
|
4
|
+
import { MigrationRunner } from '../migration/runner.js';
|
|
5
|
+
import { planTarget } from '../migration/plan.js';
|
|
6
|
+
import { ConfigurationError } from '../errors.js';
|
|
7
|
+
import { inspectProviderCapabilities } from '../runtime-capabilities.js';
|
|
8
|
+
import { dialectFor } from '../dialect/dialects.js';
|
|
9
|
+
export async function createORMFromConfig(config, context) {
|
|
10
|
+
const selected = context ?? { cwd: process.cwd(), configPath: resolve('orm.config.ts'), target: 'local', readOnly: false };
|
|
11
|
+
if (selected.target === 'remote' && typeof config.adapter !== 'function') {
|
|
12
|
+
throw new ConfigurationError('Remote tooling requires an adapter factory that accepts ORMToolingContext.');
|
|
13
|
+
}
|
|
14
|
+
const adapter = typeof config.adapter === 'function' ? await config.adapter(selected) : config.adapter;
|
|
15
|
+
try {
|
|
16
|
+
for (const [field, expected] of [['target', selected.target], ['environment', selected.environment]]) {
|
|
17
|
+
const descriptor = Object.getOwnPropertyDescriptor(adapter.tooling ?? {}, field);
|
|
18
|
+
if (expected && descriptor && 'value' in descriptor && typeof descriptor.value === 'string' && descriptor.value !== expected) {
|
|
19
|
+
throw new ConfigurationError('The adapter resolved a different database selection. Check its target and environment handling.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return createORM({ adapter, entities: config.entities,
|
|
23
|
+
...(config.namingStrategy === undefined ? {} : { namingStrategy: config.namingStrategy }),
|
|
24
|
+
...(config.logger === undefined ? {} : { logger: config.logger }) });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
await adapter.driver.close();
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function structuralSchema(schema) {
|
|
32
|
+
return { ...schema, entities: schema.entities.map(entity => ({ ...entity,
|
|
33
|
+
columns: entity.columns.map(({ default: _default, ...column }) => column) })) };
|
|
34
|
+
}
|
|
35
|
+
/** Inspect a borrowed connection. Its caller retains ownership and disposal. */
|
|
36
|
+
export async function inspectDatabase(orm, migrations = []) {
|
|
37
|
+
return orm.run(async () => {
|
|
38
|
+
const runner = new MigrationRunner(orm, migrations);
|
|
39
|
+
const target = Object.fromEntries(Object.entries(planTarget(orm)).filter(([key]) => key !== 'connectionId'));
|
|
40
|
+
const history = await runner.applied({ readOnly: true });
|
|
41
|
+
const statuses = await runner.status({ readOnly: true });
|
|
42
|
+
return {
|
|
43
|
+
schemaVersion: 1, defaultValues: 'omitted', dialect: orm.driver.dialect, target,
|
|
44
|
+
capabilities: { driver: { ...orm.driver.capabilities }, dialect: { ...dialectFor(orm.driver.dialect).capabilities } },
|
|
45
|
+
providerCapabilities: inspectProviderCapabilities(orm.driver, target.provider),
|
|
46
|
+
schema: structuralSchema(await orm.introspect()), models: structuralSchema(orm.schema()), entities: inspectFinalizedMetadata(orm.metadata),
|
|
47
|
+
migrations: statuses.map(({ migration, checksum, state, applied }) => ({ name: migration.name, checksum, state,
|
|
48
|
+
...(applied ? { appliedAt: applied.appliedAt.toISOString(), batch: applied.batch } : {}) })),
|
|
49
|
+
history: history.map(item => ({ name: item.name, checksum: item.checksum, appliedAt: item.appliedAt.toISOString(), batch: item.batch })),
|
|
50
|
+
};
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/** Own a temporary connection and always close it, including inspection failure. */
|
|
54
|
+
export async function inspectConfiguredDatabase(config, context) {
|
|
55
|
+
const orm = await createORMFromConfig(config, { ...context, readOnly: true });
|
|
56
|
+
try {
|
|
57
|
+
return await inspectDatabase(orm, config.migrations);
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await orm.close();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=inspection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inspection.js","sourceRoot":"","sources":["../../src/tooling/inspection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAY,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,wBAAwB,EAAyB,MAAM,2BAA2B,CAAC;AAC5F,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,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EAAE,CAAC,EAAE,CAAC,CAAC;YAC9F,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;SACzI,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,MAAiB,EAAE,OAA0B;IAC3F,MAAM,GAAG,GAAG,MAAM,mBAAmB,CAAC,MAAM,EAAE,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9E,IAAI,CAAC;QAAC,OAAO,MAAM,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IAAC,CAAC;YACrD,CAAC;QAAC,MAAM,GAAG,CAAC,KAAK,EAAE,CAAC;IAAC,CAAC;AAChC,CAAC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ORMCommandOptions } from "./index.js";
|
|
2
|
+
/** Execute configuration, adapters and callbacks with isolated stdout/stderr. */
|
|
3
|
+
export declare function runJSONORMCommand(moduleURL: string, argv: readonly string[], options: ORMCommandOptions): Promise<number>;
|
|
4
|
+
//# sourceMappingURL=process-json.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process-json.d.ts","sourceRoot":"","sources":["../../src/tooling/process-json.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA0CpD,iFAAiF;AACjF,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,iBAAiB,GACrE,OAAO,CAAC,MAAM,CAAC,CAqCjB"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
// Only repository-owned code is evaluated. Command arguments and options travel
|
|
5
|
+
// over IPC, so paths and values never become executable source or shell text.
|
|
6
|
+
const BOOTSTRAP = `
|
|
7
|
+
process.once("message", async ({ moduleURL, loaderURL, argv, options }) => {
|
|
8
|
+
try {
|
|
9
|
+
const { register } = await import(loaderURL);
|
|
10
|
+
const unregister = register();
|
|
11
|
+
const { runORMCommandInProcess } = await import(moduleURL);
|
|
12
|
+
let result;
|
|
13
|
+
const exitCode = await runORMCommandInProcess(argv, {
|
|
14
|
+
...options,
|
|
15
|
+
stdout: message => { result = JSON.parse(message); },
|
|
16
|
+
stderr: () => {},
|
|
17
|
+
});
|
|
18
|
+
await unregister();
|
|
19
|
+
process.send({ type: "orm-result", exitCode, result }, () => process.exit(exitCode));
|
|
20
|
+
} catch {
|
|
21
|
+
// Bootstrap failures may contain configuration values. The parent emits
|
|
22
|
+
// a stable diagnostic instead of forwarding this process's raw output.
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
`;
|
|
27
|
+
function isResult(message) {
|
|
28
|
+
if (!message || typeof message !== "object")
|
|
29
|
+
return false;
|
|
30
|
+
const value = message;
|
|
31
|
+
const result = value.result;
|
|
32
|
+
return value.type === "orm-result" && (value.exitCode === 0 || value.exitCode === 1) &&
|
|
33
|
+
!!result && result["schemaVersion"] === 1 && typeof result["command"] === "string" &&
|
|
34
|
+
typeof result["ok"] === "boolean" && Array.isArray(result["diagnostics"]) &&
|
|
35
|
+
result["ok"] === (value.exitCode === 0);
|
|
36
|
+
}
|
|
37
|
+
/** Execute configuration, adapters and callbacks with isolated stdout/stderr. */
|
|
38
|
+
export async function runJSONORMCommand(moduleURL, argv, options) {
|
|
39
|
+
const out = options.stdout ?? console.log;
|
|
40
|
+
let response;
|
|
41
|
+
let exitCode = null;
|
|
42
|
+
try {
|
|
43
|
+
const require = createRequire(import.meta.url);
|
|
44
|
+
const loaderURL = pathToFileURL(require.resolve("tsx/esm/api")).href;
|
|
45
|
+
exitCode = await new Promise((resolve) => {
|
|
46
|
+
// Keep eval in its default CommonJS mode. Miniflare's synchronous binding
|
|
47
|
+
// bridge starts a CommonJS eval Worker which inherits these Node flags.
|
|
48
|
+
// --input-type=module makes that Worker fail before it can notify the
|
|
49
|
+
// blocked parent thread, so local D1 commands never return.
|
|
50
|
+
const child = spawn(process.execPath, ["--eval", BOOTSTRAP], {
|
|
51
|
+
cwd: options.cwd ?? process.cwd(),
|
|
52
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
53
|
+
shell: false,
|
|
54
|
+
});
|
|
55
|
+
child.on("message", message => { if (isResult(message))
|
|
56
|
+
response = message; });
|
|
57
|
+
child.once("error", () => resolve(null));
|
|
58
|
+
child.once("close", code => resolve(code));
|
|
59
|
+
const { stdout: _stdout, stderr: _stderr, ...serializableOptions } = options;
|
|
60
|
+
child.send({ moduleURL, loaderURL, argv, options: serializableOptions }, error => {
|
|
61
|
+
if (error)
|
|
62
|
+
child.kill();
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// No configuration excerpts, connection logs, or child stack traces escape.
|
|
68
|
+
}
|
|
69
|
+
if (response && exitCode === response.exitCode) {
|
|
70
|
+
out(JSON.stringify(response.result));
|
|
71
|
+
return response.exitCode;
|
|
72
|
+
}
|
|
73
|
+
out(JSON.stringify({ schemaVersion: 1, command: argv[0]?.startsWith("-") ? "orm" : argv[0] ?? "orm",
|
|
74
|
+
action: argv[1]?.startsWith("-") ? null : argv[1] ?? null, ok: false, data: null,
|
|
75
|
+
diagnostics: [{ code: "COSSACK_ORM_PROCESS_FAILED", severity: "error",
|
|
76
|
+
message: "Database tooling exited before returning a result. Run without --json for tool diagnostics." }] }));
|
|
77
|
+
return 1;
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=process-json.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process-json.js","sourceRoot":"","sources":["../../src/tooling/process-json.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,gFAAgF;AAChF,8EAA8E;AAC9E,MAAM,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;CAoBjB,CAAC;AAQF,SAAS,QAAQ,CAAC,OAAgB;IAChC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC1D,MAAM,KAAK,GAAG,OAAiC,CAAC;IAChD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAC5B,OAAO,KAAK,CAAC,IAAI,KAAK,YAAY,IAAI,CAAC,KAAK,CAAC,QAAQ,KAAK,CAAC,IAAI,KAAK,CAAC,QAAQ,KAAK,CAAC,CAAC;QAClF,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,QAAQ;QAClF,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;QACzE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC;AAC5C,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,SAAiB,EAAE,IAAuB,EAAE,OAA0B;IAEtE,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,OAA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mBAAmB,EAAE,EAAE,KAAK,CAAC,EAAE;gBAC/E,IAAI,KAAK;oBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,4EAA4E;IAC9E,CAAC;IACD,IAAI,QAAQ,IAAI,QAAQ,KAAK,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC/C,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QACrC,OAAO,QAAQ,CAAC,QAAQ,CAAC;IAC3B,CAAC;IACD,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK;QACjG,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI;QAChF,WAAW,EAAE,CAAC,EAAE,IAAI,EAAE,4BAA4B,EAAE,QAAQ,EAAE,OAAO;gBACnE,OAAO,EAAE,6FAA6F,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAClH,OAAO,CAAC,CAAC;AACX,CAAC"}
|
package/docs/comparison.md
CHANGED
|
@@ -39,7 +39,7 @@ Last reviewed: July 2026.
|
|
|
39
39
|
| First-party seeding support | Ordered `SeederRunner` with transaction policy | `drizzle-seed` data generator | Application or community tooling | Application code | CLI seed command runs an application script |
|
|
40
40
|
| SQL database coverage | SQLite, PostgreSQL, MySQL; D1 and current Turso adapters | Broad PostgreSQL, MySQL, SQLite, SingleStore, MSSQL, and CockroachDB ecosystem | Broad SQL driver set | Official PostgreSQL, MySQL, MSSQL, SQLite, and PGlite dialects | PostgreSQL, MySQL/MariaDB, SQLite, SQL Server, and CockroachDB |
|
|
41
41
|
| MongoDB/NoSQL | No | No | MongoDB support | No | MongoDB support |
|
|
42
|
-
| Edge/serverless focus | First-class Bun, D1,
|
|
42
|
+
| Edge/serverless focus | First-class Bun, D1, and Hyperdrive entry points | Strong, with many serverless drivers | Driver-dependent | Runtime-neutral; dialect/driver-dependent | Supported through driver adapters and supported deployments |
|
|
43
43
|
| Multiple connections | Multiple isolated `ORM` instances | Multiple database instances | Multiple `DataSource` instances | Multiple `Kysely` instances | Separate schemas/generated clients |
|
|
44
44
|
| Cross-database relations or transactions | No | No general cross-database unit of work | Limited multi-database querying; no general distributed transaction | No | No general distributed transaction |
|
|
45
45
|
| Maturity and ecosystem | New v1 package | Established ecosystem | Long-established, feature-rich ORM | Established and deliberately focused | Long-established ecosystem and tooling |
|
|
@@ -60,7 +60,7 @@ Choose Cossack ORM when most of these are true:
|
|
|
60
60
|
current transaction.
|
|
61
61
|
- Relations should be requested explicitly and loaded in batches rather than
|
|
62
62
|
hidden behind lazy properties.
|
|
63
|
-
- The same model layer must run through isolated Node, Bun,
|
|
63
|
+
- The same model layer must run through isolated Node, Bun, or Cloudflare
|
|
64
64
|
adapters.
|
|
65
65
|
- Cossack Studio or other framework tooling needs serializable logical schema
|
|
66
66
|
metadata, including virtual relations.
|
|
@@ -178,7 +178,7 @@ The most important differences are not syntax:
|
|
|
178
178
|
startup synchronization.
|
|
179
179
|
- Automated integration coverage in this repository is currently strongest for
|
|
180
180
|
Node SQLite. The runtime adapters and public contracts exist, but PostgreSQL,
|
|
181
|
-
MySQL, Bun,
|
|
181
|
+
MySQL, Bun, and Hyperdrive do not yet have the same public integration
|
|
182
182
|
evidence as mature competitors.
|
|
183
183
|
- Cossack provides schema metadata for Studio integration, not a standalone
|
|
184
184
|
database GUI in this package.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Database inspection
|
|
3
|
+
description: Shared read-only schema, model, capability and migration facts for CLI and Studio.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Database inspection
|
|
7
|
+
|
|
8
|
+
Run `cossack schema inspect --json --env staging --target local` to inspect the
|
|
9
|
+
selected database. The result contains physical schema, declared model and
|
|
10
|
+
relationship metadata, provider capabilities, migration status and existing
|
|
11
|
+
history. Inspection does not create migration bookkeeping or apply migrations.
|
|
12
|
+
A named Cloudflare environment never falls back to top-level D1 bindings.
|
|
13
|
+
|
|
14
|
+
The database tooling entry exports the same service used by Studio:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { inspectConfiguredDatabase } from '@cossackframework/database/tooling';
|
|
18
|
+
import config from './orm.config.js';
|
|
19
|
+
|
|
20
|
+
const facts = await inspectConfiguredDatabase(config, {
|
|
21
|
+
cwd: process.cwd(),
|
|
22
|
+
configPath: 'orm.config.ts',
|
|
23
|
+
environment: 'staging',
|
|
24
|
+
target: 'local',
|
|
25
|
+
readOnly: true,
|
|
26
|
+
});
|
|
27
|
+
console.log(facts.migrations.map(item => ({ name: item.name, state: item.state })));
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
This service passes `readOnly: true` to the application adapter factory and closes
|
|
31
|
+
its temporary connection after success or failure. Factories must honor the
|
|
32
|
+
selected environment/target and avoid setup writes when read-only. If ORM model
|
|
33
|
+
validation fails after creating an adapter, the adapter is closed too.
|
|
34
|
+
`inspectDatabase(orm, migrations)` inspects an existing borrowed connection;
|
|
35
|
+
its owner remains responsible for closing it.
|
|
36
|
+
|
|
37
|
+
Resolved identity includes only bounded public fields. Connection URLs, credential
|
|
38
|
+
fields, getter properties and bound SQL values are excluded. Driver capabilities
|
|
39
|
+
are declarations of support, not a connectivity check or proof of server version.
|
|
40
|
+
Absent target metadata remains unspecified rather than guessing from a URL.
|
|
41
|
+
The `defaultValues: omitted` policy removes model and physical column default
|
|
42
|
+
values from shared inspection; entity metadata reports `hasDefault`. Use the
|
|
43
|
+
application-owned migration SQL when reviewing an explicit default change. Unknown historical migration names remain in `history` even
|
|
44
|
+
when their declarations are no longer loaded.
|
|
45
|
+
|
|
46
|
+
Studio displays these same facts under **Database capabilities and migrations**.
|
|
47
|
+
Its richer row editor still provides indexes, views and row locators. Those editor
|
|
48
|
+
details are separate from the shared versioned inspection result. Remote Studio
|
|
49
|
+
inspection loads the application's `orm.config.ts` and uses its remote adapter
|
|
50
|
+
factory; the selected binding must match an explicit `--database` request.
|
package/docs/installation.md
CHANGED
|
@@ -11,7 +11,6 @@ Cossack ORM is ESM-only and targets:
|
|
|
11
11
|
|
|
12
12
|
- Node.js 22 or newer
|
|
13
13
|
- A current stable Bun release
|
|
14
|
-
- A current stable Deno release
|
|
15
14
|
- Modern Cloudflare Workers compatibility dates
|
|
16
15
|
- TypeScript with decorator metadata enabled
|
|
17
16
|
|
|
@@ -64,7 +63,6 @@ for the runtime where the application executes:
|
|
|
64
63
|
| Runtime | Import | Available adapters |
|
|
65
64
|
| --- | --- | --- |
|
|
66
65
|
| Node.js | `@cossackframework/database/node` | `nodeSQLite`, `betterSQLite`, `postgres`, `mysql`, `turso` |
|
|
67
|
-
| Deno | `@cossackframework/database/deno` | `deno`, `denoSQLite`, `postgres`, `mysql`, `turso` |
|
|
68
66
|
| Bun | `@cossackframework/database/bun` | `bun` for SQLite, PostgreSQL, or MySQL |
|
|
69
67
|
| Cloudflare Workers | `@cossackframework/database/cloudflare` | `d1`, `hyperdrivePostgres`, `hyperdriveMySQL`, `turso` |
|
|
70
68
|
|
package/docs/introduction.md
CHANGED
|
@@ -6,7 +6,7 @@ description: Learn the design, core concepts, and first steps of Cossack ORM.
|
|
|
6
6
|
# Introduction
|
|
7
7
|
|
|
8
8
|
Cossack ORM is an ESM-only, serverless-first SQL ORM for Node.js, Bun,
|
|
9
|
-
Cloudflare Workers
|
|
9
|
+
and Cloudflare Workers. It combines decorated models, Active Record
|
|
10
10
|
methods, a typed query builder, safe SQL fragments, migrations, introspection,
|
|
11
11
|
and explicit runtime adapters.
|
|
12
12
|
|
package/docs/migrations.md
CHANGED
|
@@ -71,7 +71,7 @@ cossack-orm migration generate add_user_profiles \
|
|
|
71
71
|
Generation compares the committed model snapshot with current decorated model
|
|
72
72
|
metadata. It does not introspect the database. Adding or removing a `@Column()`,
|
|
73
73
|
entity, rename marker, or index produces deterministic TypeScript containing
|
|
74
|
-
reviewable `up
|
|
74
|
+
reviewable `operations.up` and inverse `operations.down` SQL. The snapshot advances only after the
|
|
75
75
|
migration file is written successfully. When the output is directly inside
|
|
76
76
|
`migrationDirectory` and its `index.ts` exports the standard `migrations` array,
|
|
77
77
|
the generator registers the new migration automatically; otherwise it prints a
|
|
@@ -143,6 +143,95 @@ Applied migrations are recorded in `_cossack_migrations` with their name,
|
|
|
143
143
|
SHA-256 checksum, batch, and application timestamp. Editing an applied migration
|
|
144
144
|
causes checksum validation to fail; create a new migration instead.
|
|
145
145
|
|
|
146
|
+
## Targets and plans
|
|
147
|
+
|
|
148
|
+
Select the environment and database target explicitly:
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
pnpm exec cossack migration plan --env staging --target remote --json
|
|
152
|
+
pnpm exec cossack migration up --env staging --target remote --dry-run --json
|
|
153
|
+
pnpm exec cossack migration up --env staging --target remote
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`--local` and `--remote` are aliases for `--target`. The default is local.
|
|
157
|
+
The selected environment also accepts `CLOUDFLARE_ENV`. Adapter factories
|
|
158
|
+
receive an `ORMToolingContext` with the project root, config path, environment,
|
|
159
|
+
target, and `readOnly` flag. A remote command requires a factory so the adapter
|
|
160
|
+
can honor that selection. See [D1 tooling](./runtimes.md#d1-tooling) for generated
|
|
161
|
+
Cloudflare projects.
|
|
162
|
+
|
|
163
|
+
`plan` reads migration history without creating its table and never executes
|
|
164
|
+
migration callbacks. Generated migrations declare authoritative `operations` for
|
|
165
|
+
`up` and `down`. Those same operations drive execution; callbacks cannot override
|
|
166
|
+
them. Each entry includes its direction, checksum, mode, ordered SQL, affected
|
|
167
|
+
objects, parameter counts, risk, target connection identity, atomicity and
|
|
168
|
+
provider limitations. Parameter values are omitted. Raw SQL object discovery and
|
|
169
|
+
risk classification are conservative; `affectedObjectsComplete: false` makes
|
|
170
|
+
that limit explicit. Review the SQL itself.
|
|
171
|
+
Use `--direction down` to preview the most recent reversal. A squash that
|
|
172
|
+
replaces fully applied migrations reports `mode: "consolidate"` without
|
|
173
|
+
replaying application SQL.
|
|
174
|
+
|
|
175
|
+
For a remote smoke test, first point a named Wrangler environment such as
|
|
176
|
+
`staging` at a dedicated disposable D1 database. Review its resolved target and
|
|
177
|
+
plan, then apply only the reviewed migration set:
|
|
178
|
+
|
|
179
|
+
```sh
|
|
180
|
+
pnpm exec cossack migration plan --env staging --target remote --json
|
|
181
|
+
pnpm exec cossack migration up --env staging --target remote --dry-run --json
|
|
182
|
+
pnpm exec cossack migration up --env staging --target remote
|
|
183
|
+
pnpm exec cossack migration check --env staging --target remote --json
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
This is an opt-in procedure and has not been run against a live account by the
|
|
187
|
+
release verification. Never point it at production for a smoke test. Remote
|
|
188
|
+
commands require `--target remote` (or `--remote`); an environment name alone
|
|
189
|
+
always uses local state.
|
|
190
|
+
|
|
191
|
+
Legacy callbacks remain executable through explicit `up()` and `down()`, but
|
|
192
|
+
planning reports them as incomplete without invoking them. This is an intentional
|
|
193
|
+
0.9 change: a disconnected ORM cannot stop a callback from writing files, calling
|
|
194
|
+
external services, or using another captured connection. Configuration module
|
|
195
|
+
loading is still trusted application code; this boundary does not sandbox imports.
|
|
196
|
+
|
|
197
|
+
For application-controlled review and apply in one process:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
const runner = new MigrationRunner(orm, migrations);
|
|
201
|
+
const plan = await runner.plan();
|
|
202
|
+
// Review plan, including incomplete entries and provider limitations.
|
|
203
|
+
await runner.applyPlan(plan);
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`applyPlan()` accepts only the exact plan returned by that live runner. It rejects
|
|
207
|
+
incomplete plans and rechecks all migration definitions, checksums, history and
|
|
208
|
+
target identity before writing. Its private SQL/parameter snapshot prevents later
|
|
209
|
+
application mutations from changing the approved batch. JSON reports are inspection
|
|
210
|
+
artifacts; they cannot be imported as executable approvals. Separate CLI invocations
|
|
211
|
+
must replan on their selected target. Concurrent external writers still need a
|
|
212
|
+
provider-specific deployment lock; history rechecks are not a distributed lock.
|
|
213
|
+
|
|
214
|
+
Bookkeeping SQL is reported separately, including squash consolidation deletes
|
|
215
|
+
and the replacement history insert. Missing declarative `down` operations mean a
|
|
216
|
+
reversal is unknown and cannot be applied from a plan. MySQL DDL can commit
|
|
217
|
+
implicitly; a transaction is not a guarantee of schema rollback. Providers with
|
|
218
|
+
neither transactions nor an atomic batch report possible partial application.
|
|
219
|
+
|
|
220
|
+
`--dry-run` also previews snapshot, generate, squash, and schema pull file
|
|
221
|
+
changes without writing them. `status` and `check` read history without
|
|
222
|
+
initializing bookkeeping. JSON commands emit one `schemaVersion: 1` envelope
|
|
223
|
+
with `ok`, target context, resolved adapter identity when available, results,
|
|
224
|
+
and diagnostics. Invalid flags, conflicting targets, and extra arguments fail
|
|
225
|
+
before opening the adapter.
|
|
226
|
+
|
|
227
|
+
JSON commands execute configuration and adapters in a child process. Console
|
|
228
|
+
messages, direct stdout/stderr writes, and inherited subprocess output are
|
|
229
|
+
suppressed; the structured result returns over IPC. This keeps Wrangler
|
|
230
|
+
connection logs out of JSON and prevents configuration code from changing the
|
|
231
|
+
calling process's environment. It is output isolation, not a sandbox for
|
|
232
|
+
application code. Unexpected child termination produces
|
|
233
|
+
`COSSACK_ORM_PROCESS_FAILED`; text mode retains raw diagnostics.
|
|
234
|
+
|
|
146
235
|
## Destructive changes
|
|
147
236
|
|
|
148
237
|
Dropping tables or columns and potentially narrowing column changes fail
|
package/docs/queries.md
CHANGED
|
@@ -259,3 +259,21 @@ console.log(result.meta.operation);
|
|
|
259
259
|
|
|
260
260
|
See [Raw queries](./raw-queries.md) when a query cannot be expressed cleanly by
|
|
261
261
|
the model APIs.
|
|
262
|
+
|
|
263
|
+
## Stable pagination
|
|
264
|
+
|
|
265
|
+
For an entity query with `limit()` or `offset()`, Cossack appends each primary
|
|
266
|
+
key field to the order. An explicit primary key order keeps its direction.
|
|
267
|
+
This makes ties in other sort fields deterministic. An entity without a primary
|
|
268
|
+
key cannot use this automatic order.
|
|
269
|
+
|
|
270
|
+
Joined, grouped, distinct, and projected pages require an explicit unique order.
|
|
271
|
+
Include all fields needed to distinguish result rows; Cossack cannot infer their
|
|
272
|
+
uniqueness. Offset pages can shift when concurrent writes insert or delete rows.
|
|
273
|
+
Use a transaction when the provider supports the consistency your application needs.
|
|
274
|
+
|
|
275
|
+
For keyset pagination, use the existing predicate and order APIs. For example,
|
|
276
|
+
query rows with `id > lastSeenId`, order by `id`, and apply a limit. Composite
|
|
277
|
+
orders need a matching lexicographic predicate. There is no opaque cursor API.
|
|
278
|
+
`count()` and aggregates operate on the full predicate, independent of pagination,
|
|
279
|
+
and restore the query's original window after execution.
|
package/docs/raw-queries.md
CHANGED
|
@@ -150,10 +150,10 @@ Within a scope, the global tag also exposes `execute()`, `transaction()`,
|
|
|
150
150
|
|
|
151
151
|
## Standalone SQL client
|
|
152
152
|
|
|
153
|
-
Use `SQL` when models and entity metadata are unnecessary:
|
|
153
|
+
Use the Node runtime's `SQL` client when models and entity metadata are unnecessary:
|
|
154
154
|
|
|
155
155
|
```ts
|
|
156
|
-
import { SQL } from "@cossackframework/database";
|
|
156
|
+
import { SQL } from "@cossackframework/database/node";
|
|
157
157
|
|
|
158
158
|
const client = new SQL("sqlite:app.db");
|
|
159
159
|
|
|
@@ -172,8 +172,9 @@ try {
|
|
|
172
172
|
```
|
|
173
173
|
|
|
174
174
|
In Node.js, URL or path inference supports PostgreSQL, MySQL, Turso HTTPS URLs, and
|
|
175
|
-
SQLite. Bun delegates to native Bun SQL.
|
|
176
|
-
|
|
175
|
+
SQLite. Bun delegates to native Bun SQL. The package root's `SQL` export accepts
|
|
176
|
+
explicit adapters and remains runtime neutral. Workers should use an
|
|
177
|
+
explicit adapter rather than URL guessing:
|
|
177
178
|
|
|
178
179
|
```ts
|
|
179
180
|
const client = new SQL({ adapter });
|
|
@@ -181,3 +182,17 @@ const client = new SQL({ adapter });
|
|
|
181
182
|
|
|
182
183
|
See [Runtimes](./runtimes.md) for adapter setup and
|
|
183
184
|
[Advanced usage](./advanced.md) for transactions and connection reservation.
|
|
185
|
+
|
|
186
|
+
## Query diagnostics
|
|
187
|
+
|
|
188
|
+
The ORM logger receives `sql`, parameter type markers, `durationMs`, `dialect`,
|
|
189
|
+
`provider`, `operation`, and `outcome`. A failed query includes only the fixed
|
|
190
|
+
code `COSSACK_DATABASE_QUERY_FAILED`; the event has no error object or message.
|
|
191
|
+
The SQL field is a bounded structural representation: literals and comments are
|
|
192
|
+
removed, and quoted identifiers are anonymous because some providers interpret
|
|
193
|
+
those tokens as values. It is diagnostic output, not executable SQL.
|
|
194
|
+
|
|
195
|
+
Parameter values are never included. Markers describe null, dates, binary size,
|
|
196
|
+
and JavaScript types. Logger exceptions are ignored so an observer cannot change
|
|
197
|
+
query or transaction results. Explicit callers still receive a `QueryError` and
|
|
198
|
+
must decide separately whether its private cause is safe to disclose.
|
package/docs/relationships.md
CHANGED
|
@@ -241,3 +241,14 @@ export const entities = [User, Post, Role, UserProfile] as const;
|
|
|
241
241
|
|
|
242
242
|
ORM creation validates missing targets, invalid inverse properties, and
|
|
243
243
|
unresolved join metadata.
|
|
244
|
+
|
|
245
|
+
## Inspect finalized relationships
|
|
246
|
+
|
|
247
|
+
`orm.inspectMetadata()` returns a detached, frozen description of registered
|
|
248
|
+
entities, columns, indexes, and resolved relationship fields. It includes both
|
|
249
|
+
ends of relations and physical join names, but excludes constructors, callbacks,
|
|
250
|
+
and default values. Use it for tooling without mutating ORM metadata.
|
|
251
|
+
|
|
252
|
+
Registration rejects missing referenced fields, missing inverse relations,
|
|
253
|
+
incompatible inverse relation kinds, and inverses that point at another entity.
|
|
254
|
+
These errors identify both entity and field names before database statements run.
|
package/docs/runtimes.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Runtimes
|
|
3
|
-
description: Configure runtime adapters, custom drivers, and multiple database connections across Node.js, Bun,
|
|
3
|
+
description: Configure runtime adapters, custom drivers, and multiple database connections across Node.js, Bun, and Workers.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Runtimes
|
|
@@ -10,11 +10,10 @@ eagerly include Node built-ins, native SQLite packages, or unused drivers.
|
|
|
10
10
|
|
|
11
11
|
| Runtime entry | Adapters |
|
|
12
12
|
| --- | --- |
|
|
13
|
-
| `@cossackframework/database/node` | Node SQLite, better-sqlite3, PostgreSQL, MySQL, Turso |
|
|
14
|
-
| `@cossackframework/database/deno` | Turso embedded SQLite, PostgreSQL, MySQL, remote Turso, or an injected driver |
|
|
13
|
+
| `@cossackframework/database/node` | Node SQLite, better-sqlite3, PostgreSQL, MySQL, Turso, automatic `SQL` client |
|
|
15
14
|
| `@cossackframework/database/bun` | Native Bun SQL for SQLite, PostgreSQL, MySQL |
|
|
16
15
|
| `@cossackframework/database/cloudflare` | D1 and Hyperdrive PostgreSQL/MySQL |
|
|
17
|
-
| `@cossackframework/database/
|
|
16
|
+
| `@cossackframework/database/cloudflare-turso` | Remote Turso for Workers |
|
|
18
17
|
| `@cossackframework/database/adapter` | Public contracts for custom adapters |
|
|
19
18
|
|
|
20
19
|
## Node.js
|
|
@@ -83,7 +82,7 @@ Turso (choose the client matching the connection):
|
|
|
83
82
|
|
|
84
83
|
```sh
|
|
85
84
|
pnpm add @tursodatabase/database # embedded SQLite / Desktop
|
|
86
|
-
pnpm add @tursodatabase/serverless # remote Turso
|
|
85
|
+
pnpm add @tursodatabase/serverless # remote Turso
|
|
87
86
|
```
|
|
88
87
|
|
|
89
88
|
```ts
|
|
@@ -97,6 +96,10 @@ const adapter = await turso({
|
|
|
97
96
|
});
|
|
98
97
|
```
|
|
99
98
|
|
|
99
|
+
Workers that use remote Turso should import `turso` from
|
|
100
|
+
`@cossackframework/database/cloudflare-turso`. Keeping that optional provider in
|
|
101
|
+
its own entry lets a D1-only Worker bundle without the Turso client installed.
|
|
102
|
+
|
|
100
103
|
Node adapters install `AsyncLocalStorage` request scopes automatically.
|
|
101
104
|
|
|
102
105
|
## Bun
|
|
@@ -135,16 +138,19 @@ by that client.
|
|
|
135
138
|
Create the adapter from a D1 binding:
|
|
136
139
|
|
|
137
140
|
```ts
|
|
141
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
138
142
|
import { createORM } from "@cossackframework/database";
|
|
139
143
|
import { d1 } from "@cossackframework/database/cloudflare";
|
|
144
|
+
import { createAsyncLocalScope } from "@cossackframework/database/adapter";
|
|
140
145
|
|
|
141
146
|
interface Env {
|
|
142
147
|
DB: D1Database;
|
|
143
148
|
}
|
|
144
149
|
|
|
145
150
|
export async function createRequestORM(env: Env) {
|
|
151
|
+
const adapter = await d1(env.DB);
|
|
146
152
|
return createORM({
|
|
147
|
-
adapter:
|
|
153
|
+
adapter: { ...adapter, scope: createAsyncLocalScope(new AsyncLocalStorage()) },
|
|
148
154
|
entities,
|
|
149
155
|
});
|
|
150
156
|
}
|
|
@@ -158,11 +164,46 @@ does not emulate them unsafely.
|
|
|
158
164
|
Migration schema operations and migration bookkeeping are submitted in one D1
|
|
159
165
|
batch. General callback-based transactions remain unsupported.
|
|
160
166
|
|
|
161
|
-
The
|
|
167
|
+
The application factory adds async-local request scoping through `node:async_hooks`.
|
|
168
|
+
Generated Cloudflare applications include this scope. Enable
|
|
162
169
|
the Workers compatibility support required by the deployment's compatibility
|
|
163
170
|
date, such as
|
|
164
171
|
[`nodejs_als`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/asynclocalstorage/).
|
|
165
172
|
|
|
173
|
+
`ormMiddleware()` owns databases created by its request factory. Component RPC
|
|
174
|
+
streams retain these databases until completion, failure, or cancellation. The
|
|
175
|
+
framework captures the SQL scope when it creates the response, so Active Record
|
|
176
|
+
and global `sql` calls can run between yielded values. Ordinary responses close
|
|
177
|
+
their owned ORM when middleware finishes. Caller-owned ORM instances remain
|
|
178
|
+
the caller's responsibility.
|
|
179
|
+
|
|
180
|
+
### D1 tooling
|
|
181
|
+
|
|
182
|
+
Keep tooling separate from the request adapter. Generated D1 applications use:
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
import type { ORMToolingContext } from "@cossackframework/database";
|
|
186
|
+
import { createD1ToolingAdapter } from "@cossackframework/database/tooling";
|
|
187
|
+
|
|
188
|
+
export function createToolingAdapter(context: ORMToolingContext) {
|
|
189
|
+
return createD1ToolingAdapter(context, { binding: "DB" });
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
The helper resolves Wrangler from the application and uses its configuration
|
|
194
|
+
parser. Local tooling disables remote bindings and shares the application's
|
|
195
|
+
`.wrangler/state/v3` storage used by Wrangler and the Cloudflare Vite plugin.
|
|
196
|
+
Remote tooling forces the selected D1 binding to use the remote resource,
|
|
197
|
+
requires a real `database_id`, and closes the proxy when the ORM closes. The
|
|
198
|
+
helper does not provision a remote database. JSON results include the selected
|
|
199
|
+
account ID, environment, binding and D1 identity when Wrangler provides them;
|
|
200
|
+
they never include credential values.
|
|
201
|
+
|
|
202
|
+
Named environments use their own binding declarations. Missing environments
|
|
203
|
+
fail instead of falling back to production. CLI and Studio share this binding
|
|
204
|
+
discovery through `readD1ToolingBindings()`. These exports are Node tooling;
|
|
205
|
+
Worker request code continues to import `d1()` from the Cloudflare entry.
|
|
206
|
+
|
|
166
207
|
## Cloudflare Hyperdrive
|
|
167
208
|
|
|
168
209
|
PostgreSQL through Hyperdrive:
|
|
@@ -198,35 +239,6 @@ clients and release them deterministically. Enable `nodejs_compat` for the
|
|
|
198
239
|
official `pg` and `mysql2` drivers. See Cloudflare's
|
|
199
240
|
[Hyperdrive driver guidance](https://developers.cloudflare.com/hyperdrive/).
|
|
200
241
|
|
|
201
|
-
## Deno
|
|
202
|
-
|
|
203
|
-
Deno accepts an injected driver rather than importing a specific database
|
|
204
|
-
library into the neutral package:
|
|
205
|
-
|
|
206
|
-
```ts
|
|
207
|
-
import { createORM } from "@cossackframework/database";
|
|
208
|
-
import {
|
|
209
|
-
deno,
|
|
210
|
-
type InjectedDenoDriver,
|
|
211
|
-
} from "@cossackframework/database/deno";
|
|
212
|
-
|
|
213
|
-
declare const driver: InjectedDenoDriver;
|
|
214
|
-
|
|
215
|
-
const orm = createORM({
|
|
216
|
-
adapter: deno(driver),
|
|
217
|
-
entities,
|
|
218
|
-
});
|
|
219
|
-
```
|
|
220
|
-
|
|
221
|
-
The injected driver declares its dialect, executes parameterized statements,
|
|
222
|
-
normalizes rows affected and insert IDs, and optionally supplies transactions.
|
|
223
|
-
An application can also inject a runtime-appropriate `ScopeStorage`.
|
|
224
|
-
|
|
225
|
-
Deno can connect through npm-compatible PostgreSQL/MySQL clients or an
|
|
226
|
-
application-provided SQLite driver. See Deno's
|
|
227
|
-
[database connection guide](https://docs.deno.com/examples/connecting_to_databases_tutorial/)
|
|
228
|
-
for runtime permissions and driver choices.
|
|
229
|
-
|
|
230
242
|
## Custom Runtime
|
|
231
243
|
|
|
232
244
|
Cossack ORM does not require runtime support to live in this package. A custom
|
|
@@ -424,3 +436,32 @@ if (orm.driver.capabilities.transactions) {
|
|
|
424
436
|
|
|
425
437
|
Capabilities include transactions, savepoints, returning clauses, batches,
|
|
426
438
|
connection reservation, cancellation, parameter limits, and batch limits.
|
|
439
|
+
|
|
440
|
+
## Provider capabilities
|
|
441
|
+
|
|
442
|
+
`orm.inspectCapabilities()` returns frozen driver declarations, including provider,
|
|
443
|
+
dialect, transaction modes, schema operations, generated values, returning support,
|
|
444
|
+
connection reservation, cancellation, and parameter/batch limits. These facts do
|
|
445
|
+
not establish remote connectivity or a server version. Custom drivers must declare
|
|
446
|
+
accurate limits and implement the advertised methods.
|
|
447
|
+
|
|
448
|
+
| Operation | SQLite / embedded Turso | PostgreSQL | MySQL | D1 |
|
|
449
|
+
| --- | --- | --- | --- | --- |
|
|
450
|
+
| Interactive transactions | Yes | Yes | Yes | No |
|
|
451
|
+
| Nested savepoints | Yes | Yes | Yes | No |
|
|
452
|
+
| Transactional DDL rollback | Yes | Yes | No | No |
|
|
453
|
+
| Generated increment key | Integer primary key | Identity column | AUTO_INCREMENT | Integer primary key |
|
|
454
|
+
| Explicit generated identity | No | Yes | No | No |
|
|
455
|
+
| Direct column type alteration | No | Yes | Yes | No |
|
|
456
|
+
|
|
457
|
+
UUID generation happens in the client. PostgreSQL and MySQL column alterations
|
|
458
|
+
support type changes only; changes to defaults or constraints need explicit SQL.
|
|
459
|
+
SQLite type changes need a table-rebuild migration. Schema queues compile every
|
|
460
|
+
operation before execution, so unsupported later operations cannot publish earlier
|
|
461
|
+
DDL. MySQL DDL can implicitly commit and must not be described as rollback-safe.
|
|
462
|
+
|
|
463
|
+
D1 supports its driver's atomic batch facility, not interactive callbacks or
|
|
464
|
+
nested transactions. Remote Turso and injected drivers use their own declared
|
|
465
|
+
capabilities. Unsupported interactive/nested operations reject before entering the
|
|
466
|
+
callback. Queries over the declared parameter limit reject before driver execution.
|
|
467
|
+
Unsupported generated identity and native array metadata reject during ORM setup.
|