durable-db 0.2.0 → 0.2.2

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.
Files changed (51) hide show
  1. package/dist/{arktypeConfig-zgI5p6zF.d.ts → arktypeConfig-AXvobTPL.d.ts} +0 -1
  2. package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
  3. package/dist/cli/bin.d.ts +1 -1
  4. package/dist/cli/bin.js +2 -10
  5. package/dist/cli/index.d.ts +27 -29
  6. package/dist/cli/index.js +4 -9
  7. package/dist/{cli-DnsOTcrH.js → cli-BUSZTS2D.js} +196 -19
  8. package/dist/context/index.d.ts +50 -2
  9. package/dist/context/index.js +119 -5
  10. package/dist/db/index.d.ts +4 -4
  11. package/dist/db/index.js +10 -12
  12. package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
  13. package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
  14. package/dist/{defineDatabase-DtkM6k1S.d.ts → defineDatabase-IUthY3Ex.d.ts} +5 -5
  15. package/dist/{discovery-DfimBbS_.d.ts → discovery-gHeLq8jk.d.ts} +1 -1
  16. package/dist/{index-BHLOQ7uV.d.ts → index-BdrcuAU7.d.ts} +4 -3
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +5 -8
  19. package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
  20. package/dist/migrations/generator.d.ts +14 -17
  21. package/dist/migrations/generator.js +202 -5
  22. package/dist/migrations/snapshot.d.ts +1 -1
  23. package/dist/migrations/snapshot.js +91 -3
  24. package/dist/{parser-BdV7Zqcv.js → parser-DR57GOjv.js} +21 -19
  25. package/dist/registry.d.ts +10 -11
  26. package/dist/registry.js +3 -5
  27. package/dist/schema.d.ts +5 -2
  28. package/dist/schema.js +6 -3
  29. package/dist/snapshot-CaG5xnE2.d.ts +48 -0
  30. package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
  31. package/dist/testing/index.d.ts +4 -5
  32. package/dist/testing/index.js +6 -10
  33. package/dist/transport/protocol.d.ts +7 -8
  34. package/dist/transport/protocol.js +34 -3
  35. package/dist/transport/websocket.d.ts +4 -5
  36. package/dist/transport/websocket.js +103 -3
  37. package/dist/vite/durableDb.d.ts +6 -7
  38. package/dist/vite/durableDb.js +23 -28
  39. package/package.json +12 -12
  40. package/dist/context-kIVZbhye.js +0 -121
  41. package/dist/generator-KHBZaOI1.js +0 -202
  42. package/dist/index-zzQS_psa.d.ts +0 -51
  43. package/dist/protocol-DEubbBbR.js +0 -35
  44. package/dist/push-BhrMZaQx.js +0 -190
  45. package/dist/push-cUJBpv5y.js +0 -8
  46. package/dist/schema-C2yy5KCT.d.ts +0 -6
  47. package/dist/schema-IFq7ovQq.js +0 -8
  48. package/dist/snapshot-DMW6j2Ix.js +0 -93
  49. package/dist/snapshot-DsSRYFe-.d.ts +0 -125
  50. package/dist/state-vav3VCId.js +0 -5
  51. package/dist/websocket-eao2rnHL.js +0 -104
@@ -1,202 +0,0 @@
1
- import { i as init_debug, n as debugMigrations } from "./debug-DmBrUmwe.js";
2
- import { i as generateSnapshotId, n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "./snapshot-DMW6j2Ix.js";
3
- import * as fs from "node:fs";
4
- import * as path$1 from "node:path";
5
- import * as os from "node:os";
6
- import { pathToFileURL } from "node:url";
7
-
8
- //#region src/migrations/generator.ts
9
- init_debug();
10
- /**
11
- * Snapshot file name
12
- */
13
- const SNAPSHOT_FILE = "_snapshot.json";
14
- /**
15
- * Load the previous snapshot from the migrations directory
16
- */
17
- function loadSnapshot(migrationsDir) {
18
- const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
19
- if (!fs.existsSync(snapshotPath)) return createEmptySnapshot();
20
- const content = fs.readFileSync(snapshotPath, "utf-8");
21
- try {
22
- return JSON.parse(content);
23
- } catch (e) {
24
- const message = e instanceof Error ? e.message : String(e);
25
- throw new Error(`[db] Failed to parse snapshot at ${snapshotPath}: ${message}. The file appears corrupt — restore from git, or delete it if you intend to re-derive migrations from scratch (only safe when the migration history matches an empty-starting-point schema).`);
26
- }
27
- }
28
- /**
29
- * Save a snapshot to the migrations directory
30
- */
31
- function saveSnapshot(migrationsDir, snapshot) {
32
- fs.mkdirSync(migrationsDir, { recursive: true });
33
- const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
34
- fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
35
- }
36
- /**
37
- * Generate a timestamp-based migration name
38
- */
39
- function generateMigrationName(suffix) {
40
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
41
- return suffix ? `${timestamp}_${suffix}` : timestamp;
42
- }
43
- /**
44
- * Generate a migration from schema changes
45
- *
46
- * This compares the current schema to the stored snapshot and generates
47
- * the necessary SQL statements to migrate the database.
48
- *
49
- * @example
50
- * ```ts
51
- * import { users, posts } from './schema';
52
- *
53
- * const result = await generateMigration({
54
- * migrationsDir: './migrations',
55
- * schema: { users, posts },
56
- * });
57
- *
58
- * if (result.hasChanges) {
59
- * console.log('Migration generated:', result.migrationName);
60
- * }
61
- * ```
62
- */
63
- async function generateMigration(options) {
64
- const { migrationsDir, schema, migrationName, write = true } = options;
65
- const previousSnapshot = loadSnapshot(migrationsDir);
66
- const newSnapshot = await generateSnapshotFromSchema(schema);
67
- newSnapshot.id = generateSnapshotId();
68
- newSnapshot.prevId = previousSnapshot.id;
69
- if (snapshotsEqual(previousSnapshot, newSnapshot)) return {
70
- hasChanges: false,
71
- statements: [],
72
- migrationName: null,
73
- snapshot: newSnapshot,
74
- previousSnapshot
75
- };
76
- const statements = await generateMigrationStatements(previousSnapshot, newSnapshot);
77
- const name = migrationName ?? generateMigrationName("auto");
78
- if (write && statements.length > 0) {
79
- fs.mkdirSync(migrationsDir, { recursive: true });
80
- const sqlPath = path$1.join(migrationsDir, `${name}.sql`);
81
- const sqlContent = statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
82
- fs.writeFileSync(sqlPath, sqlContent);
83
- saveSnapshot(migrationsDir, newSnapshot);
84
- debugMigrations("Generated migration: %s", name);
85
- debugMigrations("Statements: %d", statements.length);
86
- }
87
- return {
88
- hasChanges: true,
89
- statements,
90
- migrationName: name,
91
- snapshot: newSnapshot,
92
- previousSnapshot
93
- };
94
- }
95
- /**
96
- * Breakpoint marker in SQL files
97
- * Use: --> breakpoint
98
- */
99
- const BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
100
- /**
101
- * Parse SQL content into chunks (split by breakpoints) and statements
102
- *
103
- * @param content - Raw SQL file content
104
- * @returns Array of chunks, where each chunk is an array of SQL statements
105
- */
106
- function parseSqlMigration(content) {
107
- return content.split(BREAKPOINT_MARKER).map((chunk) => {
108
- return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
109
- }).filter((chunk) => chunk.length > 0);
110
- }
111
- /**
112
- * Load all migration SQL files from a directory
113
- * Returns migrations sorted by name (timestamp order) with breakpoint parsing
114
- */
115
- function loadMigrationFiles(migrationsDir) {
116
- const migrations = /* @__PURE__ */ new Map();
117
- if (!fs.existsSync(migrationsDir)) return migrations;
118
- const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
119
- for (const file of files) {
120
- const name = file.replace(".sql", "");
121
- const chunks = parseSqlMigration(fs.readFileSync(path$1.join(migrationsDir, file), "utf-8"));
122
- if (chunks.length > 0) migrations.set(name, chunks);
123
- }
124
- return migrations;
125
- }
126
- /**
127
- * Load a schema module using dynamic import
128
- * Works with both ESM and CJS modules
129
- */
130
- async function loadSchemaModule(schemaPath, tableNames) {
131
- const fileUrl = pathToFileURL(schemaPath).href;
132
- try {
133
- const module = await import(fileUrl);
134
- const schema = {};
135
- for (const name of tableNames) if (module[name]) schema[name] = module[name];
136
- else if (module.default?.[name]) schema[name] = module.default[name];
137
- return schema;
138
- } catch (error) {
139
- throw new Error(`Failed to load schema from ${schemaPath}: ${error}`);
140
- }
141
- }
142
- /**
143
- * Where to drop the transient transpiled-schema `.mjs`. We want a
144
- * directory that (a) is on the app's node_modules resolution chain
145
- * so the bundle's bare imports resolve, and (b) is NOT inside the
146
- * watched `src/` tree (so dev-server watchers don't react to it).
147
- * The app's `node_modules/.cache/durable-db/` satisfies both; if no
148
- * node_modules is found walking up from the schema, fall back to the
149
- * OS temp dir (the schema bundle's externals are usually resolvable
150
- * relative to cwd in that case too).
151
- */
152
- function resolveTempDir(schemaPath) {
153
- let dir = path$1.dirname(path$1.resolve(schemaPath));
154
- while (true) {
155
- if (fs.existsSync(path$1.join(dir, "node_modules"))) return path$1.join(dir, "node_modules", ".cache", "durable-db");
156
- const parent = path$1.dirname(dir);
157
- if (parent === dir) break;
158
- dir = parent;
159
- }
160
- return path$1.join(os.tmpdir(), "durable-db");
161
- }
162
- /**
163
- * Build schema module with esbuild and return the exports
164
- * This is useful when the schema is TypeScript and needs transpilation
165
- */
166
- async function buildAndLoadSchema(schemaPath, tableNames) {
167
- const result = await (await import("esbuild")).build({
168
- entryPoints: [schemaPath],
169
- bundle: true,
170
- write: false,
171
- format: "esm",
172
- platform: "node",
173
- packages: "external",
174
- target: "node18"
175
- });
176
- if (result.outputFiles?.length !== 1) throw new Error(`Unexpected esbuild output for ${schemaPath}`);
177
- const tempDir = resolveTempDir(schemaPath);
178
- fs.mkdirSync(tempDir, { recursive: true });
179
- const tempFile = path$1.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
180
- try {
181
- fs.writeFileSync(tempFile, result.outputFiles[0].text);
182
- const module = await import(pathToFileURL(tempFile).href);
183
- const schema = {};
184
- for (const name of tableNames) if (module[name]) schema[name] = module[name];
185
- else if (module.default?.[name]) schema[name] = module.default[name];
186
- return schema;
187
- } finally {
188
- try {
189
- fs.unlinkSync(tempFile);
190
- } catch {}
191
- }
192
- }
193
- /**
194
- * Generate SQL to create all tables from scratch
195
- * Useful for initial setup or testing
196
- */
197
- async function generateCreateTableSQL(schema) {
198
- return generateMigrationStatements(createEmptySnapshot(), await generateSnapshotFromSchema(schema));
199
- }
200
-
201
- //#endregion
202
- export { loadMigrationFiles as a, parseSqlMigration as c, generateMigrationName as i, saveSnapshot as l, generateCreateTableSQL as n, loadSchemaModule as o, generateMigration as r, loadSnapshot as s, buildAndLoadSchema as t };
@@ -1,51 +0,0 @@
1
- //#region src/context/index.d.ts
2
- /**
3
- * Configure a tenant ID resolver.
4
- *
5
- * The resolver is called at the moment a database operation needs the tenant ID —
6
- * by which point request middleware (auth, session, etc.) has already completed.
7
- *
8
- * @example
9
- * ```ts
10
- * import { setTenantIdResolver } from 'durable-db/context';
11
- * import { getRequestInfo } from 'rwsdk/worker';
12
- *
13
- * setTenantIdResolver(() => getRequestInfo().ctx.session!.shop);
14
- * ```
15
- */
16
- declare function setTenantIdResolver(resolver: (() => string) | null): void;
17
- declare function getTenantId(): string;
18
- /**
19
- * Check if a tenant ID resolver is configured (or a Durable Object context
20
- * can supply the tenant).
21
- */
22
- declare function hasTenantId(): boolean;
23
- /**
24
- * Get the dev epoch for instance key suffixing
25
- * Only used in development to allow database resets
26
- *
27
- * Returns null in production or if no dev state exists
28
- *
29
- * @deprecated The epoch is now baked into generated stubs at build time via
30
- * the `virtual:durable-db/__devEpoch` module — this function
31
- * cannot read the dev state inside workerd (no filesystem) and returns null
32
- * there. Import `devEpoch` / `applyDevEpoch` from the virtual module instead.
33
- */
34
- declare function getDevInstanceKeySuffix(): string | null;
35
- /**
36
- * Get a database instance key, optionally suffixed with dev epoch
37
- *
38
- * In development, this appends an epoch suffix to enable database resets.
39
- * In production, this returns the base key unchanged.
40
- *
41
- * @deprecated Generated stubs apply the epoch automatically via
42
- * `applyDevEpoch` from `virtual:durable-db/__devEpoch`. This
43
- * function only works in Node (it reads the dev state from disk) and is the
44
- * identity inside workerd — combining it with the generated stubs would
45
- * also double-suffix keys. Import from the virtual module instead.
46
- *
47
- * @param baseKey - The base instance key (e.g., tenant ID or 'global')
48
- */
49
- declare function getInstanceKey(baseKey: string): string;
50
- //#endregion
51
- export { setTenantIdResolver as a, hasTenantId as i, getInstanceKey as n, getTenantId as r, getDevInstanceKeySuffix as t };
@@ -1,35 +0,0 @@
1
- //#region src/transport/protocol.ts
2
- function encodeRequest(req) {
3
- return JSON.stringify(req);
4
- }
5
- function decodeRequest(data) {
6
- const parsed = JSON.parse(data);
7
- if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionRequest: expected object, got ${parsed === null ? "null" : typeof parsed}`);
8
- const obj = parsed;
9
- for (const field of [
10
- "id",
11
- "action",
12
- "instanceKey"
13
- ]) if (typeof obj[field] !== "string") throw new Error(`Invalid WsActionRequest: '${field}' must be a string, got ${describeType(obj[field])}`);
14
- return obj;
15
- }
16
- function encodeResponse(res) {
17
- return JSON.stringify(res);
18
- }
19
- function decodeResponse(data) {
20
- const parsed = JSON.parse(data);
21
- if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionResponse: expected object, got ${parsed === null ? "null" : typeof parsed}`);
22
- const obj = parsed;
23
- if (typeof obj.id !== "string") throw new Error(`Invalid WsActionResponse: 'id' must be a string, got ${describeType(obj.id)}`);
24
- if (typeof obj.ok !== "boolean") throw new Error(`Invalid WsActionResponse: 'ok' must be a boolean, got ${describeType(obj.ok)}`);
25
- if (!obj.ok && typeof obj.error !== "string") throw new Error(`Invalid WsActionResponse: 'error' must be a string when ok=false, got ${describeType(obj.error)}`);
26
- return obj;
27
- }
28
- function describeType(value) {
29
- if (value === null) return "null";
30
- if (Array.isArray(value)) return "array";
31
- return typeof value;
32
- }
33
-
34
- //#endregion
35
- export { encodeResponse as i, decodeResponse as n, encodeRequest as r, decodeRequest as t };
@@ -1,190 +0,0 @@
1
- import { i as init_debug, t as debugCli } from "./debug-DmBrUmwe.js";
2
- import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-DtZ70cBR.js";
3
- import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-DMW6j2Ix.js";
4
- import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-KHBZaOI1.js";
5
- import { a as discoverDatabaseFiles, c as loadViteAliases, n as parseDatabaseFile, o as readFile, s as resolveImportPath } from "./parser-BdV7Zqcv.js";
6
- import * as path$1 from "node:path";
7
- import * as crypto from "node:crypto";
8
-
9
- //#region src/cli/shared.ts
10
- init_debug();
11
- /**
12
- * Print a caught error to stderr. Always shows the message; when verbose
13
- * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
14
- * unexpected failures without patching the CLI.
15
- */
16
- function reportCliError(error, verbose = false) {
17
- const showStack = verbose || Boolean(process.env.DEBUG);
18
- if (error instanceof Error) {
19
- console.error("Error:", error.message);
20
- if (showStack && error.stack) console.error(error.stack);
21
- return;
22
- }
23
- console.error("Error:", error);
24
- }
25
- /**
26
- * Discover database files, parse them, and resolve migrationsDir.
27
- * Returns parsed DatabaseInfo[] with migrationsDir already set.
28
- */
29
- function discoverDatabases(opts) {
30
- const { projectRoot, databasesDir, migrationsDir, database } = opts;
31
- const files = discoverDatabaseFiles({
32
- projectRoot,
33
- databasesDir
34
- });
35
- const databases = [];
36
- for (const file of files) {
37
- const code = readFile(file.absolutePath);
38
- const parsed = parseDatabaseFile(file.absolutePath, code, { namePrefix: file.prefix });
39
- if (!parsed.database) continue;
40
- if (database && parsed.database.name !== database) continue;
41
- parsed.database.migrationsDir = path$1.resolve(projectRoot, migrationsDir, parsed.database.name);
42
- databases.push(parsed.database);
43
- }
44
- return databases;
45
- }
46
- /**
47
- * Load and validate schema for a database.
48
- *
49
- * Returns null only when the database genuinely declares no schema tables.
50
- * Every other failure mode (inline tables, unresolvable import, build error,
51
- * missing exports) throws — silently skipping a database is how a typo in
52
- * schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
53
- * a generated migration that DROPs tables that still exist in production.
54
- *
55
- * `projectRoot` enables alias resolution for non-relative schema imports
56
- * (e.g. `@/databases/schema`): the project's Vite `resolve.alias` is loaded
57
- * (cached) and used as the source of truth. Omit it to resolve relative
58
- * imports only.
59
- */
60
- async function loadSchema(db, projectRoot) {
61
- if (db.schemaTableNames.length === 0) {
62
- debugCli("Skipping %s: no schema defined", db.name);
63
- return null;
64
- }
65
- if (!db.schemaImport) throw new Error(`[db] Database '${db.name}' declares ${db.schemaTableNames.length} schema table(s) (${db.schemaTableNames.join(", ")}) but none of them are imported from a schema module. Tables defined inline in ${path$1.basename(db.filePath)} cannot be loaded for migration generation — move them to a schema file (e.g. src/databases/schema.ts) and import them.`);
66
- const aliases = projectRoot ? await loadViteAliases(projectRoot) : void 0;
67
- const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
68
- if (!schemaPath) throw new Error(`[db] Database '${db.name}': could not resolve schema import '${db.schemaImport}' from ${db.filePath}.` + (db.schemaImport.startsWith(".") ? "" : ` '${db.schemaImport}' looks like an alias — ensure it's defined in the project's Vite config (resolve.alias / tsconfig paths wired into Vite).`));
69
- let schema;
70
- try {
71
- schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
72
- } catch (error) {
73
- const message = error instanceof Error ? error.message : String(error);
74
- debugCli("Failed to load schema for %s: %O", db.name, error);
75
- throw new Error(`[db] Could not build schema for database '${db.name}' (${schemaPath}): ${message}`, { cause: error });
76
- }
77
- const missing = db.schemaTableNames.filter((name) => !(name in schema));
78
- if (missing.length > 0) throw new Error(`[db] Database '${db.name}': schema module ${schemaPath} does not export: ${missing.join(", ")}. Every table referenced in defineDatabase({ schema }) must be exported from the same schema module.`);
79
- return schema;
80
- }
81
- /**
82
- * Diff a schema against the production snapshot in migrationsDir.
83
- * Returns whether there are changes, the SQL statements, and both snapshots.
84
- */
85
- async function diffSchema(schema, migrationsDir) {
86
- const prodSnapshot = loadSnapshot(migrationsDir);
87
- const currentSnapshot = await generateSnapshotFromSchema(schema);
88
- if (snapshotsEqual(prodSnapshot, currentSnapshot)) return {
89
- hasChanges: false,
90
- statements: [],
91
- prodSnapshot,
92
- currentSnapshot
93
- };
94
- const statements = await generateMigrationStatements(prodSnapshot, currentSnapshot);
95
- return {
96
- hasChanges: statements.length > 0,
97
- statements,
98
- prodSnapshot,
99
- currentSnapshot
100
- };
101
- }
102
-
103
- //#endregion
104
- //#region src/cli/push.ts
105
- init_state();
106
- init_debug();
107
- /**
108
- * Push schema changes to dev migrations
109
- *
110
- * This command:
111
- * 1. Discovers all databases in the project
112
- * 2. For each database, diffs production snapshot against current schema
113
- * 3. If changes detected, generates a single squashed dev migration
114
- * 4. Uses content-hash naming so the same schema always produces the same
115
- * migration name — the DO skips it if already applied
116
- *
117
- * Dev migrations are stored in node_modules/.cache/durable-db/
118
- * and are ephemeral - they're cleared when running `db:generate` or `db:reset`
119
- */
120
- async function push(ctx = {}) {
121
- const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
122
- const results = [];
123
- const databases = discoverDatabases({
124
- projectRoot,
125
- databasesDir,
126
- migrationsDir
127
- });
128
- if (databases.length === 0) {
129
- debugCli("No databases found");
130
- return results;
131
- }
132
- for (const db of databases) {
133
- const result = await pushDatabase(projectRoot, db);
134
- results.push(result);
135
- }
136
- return results;
137
- }
138
- /**
139
- * Push a single database
140
- *
141
- * Always diffs from the production snapshot to the current schema,
142
- * producing a single squashed dev migration with a deterministic
143
- * content-hash name.
144
- */
145
- async function pushDatabase(projectRoot, db) {
146
- const result = {
147
- database: db.name,
148
- hasChanges: false,
149
- statements: [],
150
- migrationName: null
151
- };
152
- const schema = await loadSchema(db, projectRoot);
153
- if (!schema) return result;
154
- const diff = await diffSchema(schema, db.migrationsDir);
155
- if (!diff.hasChanges) {
156
- debugCli("No changes for %s", db.name);
157
- return result;
158
- }
159
- const safeStatements = diff.statements.map((s) => s.replace(/\bCREATE TABLE\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE TABLE IF NOT EXISTS").replace(/\bCREATE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE INDEX IF NOT EXISTS").replace(/\bCREATE UNIQUE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE UNIQUE INDEX IF NOT EXISTS"));
160
- const migrationName = `dev_${crypto.createHash("sha256").update(safeStatements.join("\n")).digest("hex").slice(0, 8)}`;
161
- if (loadDevMigrations(projectRoot, db.name).has(migrationName)) {
162
- debugCli("Migration %s already exists for %s, skipping", migrationName, db.name);
163
- return result;
164
- }
165
- clearDevMigrations(projectRoot, db.name);
166
- saveDevMigration(projectRoot, db.name, migrationName, safeStatements);
167
- result.hasChanges = true;
168
- result.statements = diff.statements;
169
- result.migrationName = migrationName;
170
- debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
171
- return result;
172
- }
173
- /**
174
- * Push a single database by name
175
- * Useful when you only want to push one specific database
176
- */
177
- async function pushOne(ctx = {}, dbName) {
178
- const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
179
- const databases = discoverDatabases({
180
- projectRoot,
181
- databasesDir,
182
- migrationsDir,
183
- database: dbName
184
- });
185
- if (databases.length === 0) return null;
186
- return await pushDatabase(projectRoot, databases[0]);
187
- }
188
-
189
- //#endregion
190
- export { loadSchema as a, discoverDatabases as i, pushOne as n, reportCliError as o, diffSchema as r, push as t };
@@ -1,8 +0,0 @@
1
- import "./debug-DmBrUmwe.js";
2
- import "./state-DtZ70cBR.js";
3
- import "./snapshot-DMW6j2Ix.js";
4
- import "./generator-KHBZaOI1.js";
5
- import "./parser-BdV7Zqcv.js";
6
- import { n as pushOne, t as push } from "./push-BhrMZaQx.js";
7
-
8
- export { push };
@@ -1,6 +0,0 @@
1
- import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
-
3
- //#region src/schema.d.ts
4
- declare const table: typeof sqliteTable;
5
- //#endregion
6
- export { integer as a, real as c, uniqueIndex as d, index as i, table as l, blob as n, numeric as o, foreignKey as r, primaryKey as s, AnySQLiteColumn as t, text as u };
@@ -1,8 +0,0 @@
1
- import { blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
- import { toSnakeCase } from "drizzle-orm/casing";
3
-
4
- //#region src/schema.ts
5
- const table = ((name, columns, extraConfig) => sqliteTable(toSnakeCase(name), columns, extraConfig));
6
-
7
- //#endregion
8
- export { numeric as a, table as c, integer as i, text as l, foreignKey as n, primaryKey as o, index as r, real as s, blob as t, uniqueIndex as u };
@@ -1,93 +0,0 @@
1
- import { createRequire } from "node:module";
2
-
3
- //#region src/migrations/snapshot.ts
4
- const { generateSQLiteDrizzleJson, generateSQLiteMigration } = createRequire(import.meta.url)("drizzle-kit/api");
5
- /**
6
- * Create an empty snapshot (for initial migration from nothing)
7
- */
8
- function createEmptySnapshot() {
9
- return {
10
- views: {},
11
- version: "6",
12
- dialect: "sqlite",
13
- id: "0000000000000",
14
- prevId: "",
15
- tables: {},
16
- enums: {},
17
- _meta: {
18
- tables: {},
19
- columns: {}
20
- }
21
- };
22
- }
23
- /**
24
- * Generate a unique snapshot ID based on timestamp
25
- */
26
- function generateSnapshotId() {
27
- return Date.now().toString(36).padStart(13, "0");
28
- }
29
- /**
30
- * Generate a snapshot from Drizzle schema objects
31
- *
32
- * @param schema - Object containing Drizzle table definitions
33
- * @returns Snapshot representing the current schema state
34
- *
35
- * @example
36
- * ```ts
37
- * import { users, posts } from './schema';
38
- * const snapshot = await generateSnapshotFromSchema({ users, posts });
39
- * ```
40
- */
41
- async function generateSnapshotFromSchema(schema) {
42
- return generateSQLiteDrizzleJson(schema, void 0, "snake_case");
43
- }
44
- /**
45
- * Generate SQL migration statements from two snapshots
46
- *
47
- * @param from - Previous schema state (or empty for initial migration)
48
- * @param to - Target schema state
49
- * @returns Array of SQL statements to migrate from `from` to `to`
50
- *
51
- * @example
52
- * ```ts
53
- * const statements = await generateMigrationStatements(prevSnapshot, newSnapshot);
54
- * // ['CREATE TABLE users (...)', 'CREATE INDEX ...']
55
- * ```
56
- */
57
- async function generateMigrationStatements(from, to) {
58
- return await generateSQLiteMigration(from, to);
59
- }
60
- /**
61
- * Serialize the schema-relevant parts of a snapshot for comparison/hashing.
62
- * Includes tables, views, and enums so that changes to any of them are
63
- * detected — previously only `tables` was considered.
64
- */
65
- function serializeSchemaShape(snapshot) {
66
- return JSON.stringify({
67
- tables: snapshot.tables ?? {},
68
- views: snapshot.views ?? {},
69
- enums: snapshot.enums ?? {}
70
- });
71
- }
72
- /**
73
- * Check if two snapshots are equivalent (no migration needed)
74
- */
75
- function snapshotsEqual(a, b) {
76
- return serializeSchemaShape(a) === serializeSchemaShape(b);
77
- }
78
- /**
79
- * Create a hash of a snapshot for quick comparison
80
- */
81
- function hashSnapshot(snapshot) {
82
- const content = serializeSchemaShape(snapshot);
83
- let hash = 0;
84
- for (let i = 0; i < content.length; i++) {
85
- const char = content.charCodeAt(i);
86
- hash = (hash << 5) - hash + char;
87
- hash = hash & hash;
88
- }
89
- return Math.abs(hash).toString(36);
90
- }
91
-
92
- //#endregion
93
- export { hashSnapshot as a, generateSnapshotId as i, generateMigrationStatements as n, snapshotsEqual as o, generateSnapshotFromSchema as r, createEmptySnapshot as t };