@decocms/runtime 1.0.0-alpha.2 → 1.0.0-alpha.20

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/src/drizzle.ts DELETED
@@ -1,201 +0,0 @@
1
- import type { DrizzleConfig } from "drizzle-orm";
2
- import {
3
- drizzle as drizzleProxy,
4
- type SqliteRemoteDatabase,
5
- } from "drizzle-orm/sqlite-proxy";
6
- import { QueryResult } from "./mcp.ts";
7
- export * from "drizzle-orm/sqlite-core";
8
- export * as orm from "drizzle-orm";
9
- import { sql } from "drizzle-orm";
10
- import { DefaultEnv } from "./index.ts";
11
-
12
- const mapGetResult = ({ result: [page] }: { result: QueryResult[] }) => {
13
- return page.results ?? [];
14
- };
15
-
16
- const mapPostResult = ({ result }: { result: QueryResult[] }) => {
17
- return (
18
- result
19
- .map((page) => page.results ?? [])
20
- .flat()
21
- // @ts-expect-error - this is ok, result comes as unknown
22
- .map(Object.values)
23
- );
24
- };
25
-
26
- export function drizzle<
27
- TSchema extends Record<string, unknown> = Record<string, never>,
28
- >(
29
- { DECO_WORKSPACE_DB }: Pick<DefaultEnv, "DECO_WORKSPACE_DB">,
30
- config?: DrizzleConfig<TSchema>,
31
- ) {
32
- return drizzleProxy((sql, params, method) => {
33
- // https://orm.drizzle.team/docs/connect-drizzle-proxy says
34
- // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.
35
- // When the method is get, you should return a value as {rows: string[]}.
36
- // Otherwise, you should return {rows: string[][]}.
37
- const asRows = method === "get" ? mapGetResult : mapPostResult;
38
- return DECO_WORKSPACE_DB.query({
39
- sql,
40
- params,
41
- }).then((result) => ({ rows: asRows(result) }));
42
- }, config);
43
- }
44
-
45
- /**
46
- * The following code is a custom migration system tweaked
47
- * from the durable-sqlite original migrator.
48
- *
49
- * @see https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/durable-sqlite/migrator.ts
50
- *
51
- * It applies the migrations without transactions, as a workaround
52
- * while we don't have remote transactions support on the
53
- * workspace database durable object. Not ideal and we should
54
- * look into implementing some way of doing transactions soon.
55
- */
56
-
57
- export interface MigrationMeta {
58
- sql: string[];
59
- folderMillis: number;
60
- hash: string;
61
- bps: boolean;
62
- }
63
-
64
- export interface MigrationConfig {
65
- journal: {
66
- entries: { idx: number; when: number; tag: string; breakpoints: boolean }[];
67
- };
68
- migrations: Record<string, string>;
69
- debug?: boolean;
70
- }
71
-
72
- function readMigrationFiles({
73
- journal,
74
- migrations,
75
- }: MigrationConfig): MigrationMeta[] {
76
- const migrationQueries: MigrationMeta[] = [];
77
-
78
- for (const journalEntry of journal.entries) {
79
- const query =
80
- migrations[`m${journalEntry.idx.toString().padStart(4, "0")}`];
81
-
82
- if (!query) {
83
- throw new Error(`Missing migration: ${journalEntry.tag}`);
84
- }
85
-
86
- try {
87
- const result = query.split("--> statement-breakpoint").map((it) => {
88
- return it;
89
- });
90
-
91
- migrationQueries.push({
92
- sql: result,
93
- bps: journalEntry.breakpoints,
94
- folderMillis: journalEntry.when,
95
- hash: "",
96
- });
97
- } catch {
98
- throw new Error(`Failed to parse migration: ${journalEntry.tag}`);
99
- }
100
- }
101
-
102
- return migrationQueries;
103
- }
104
-
105
- export async function migrateWithoutTransaction(
106
- db: SqliteRemoteDatabase,
107
- config: MigrationConfig,
108
- ): Promise<void> {
109
- const debug = config.debug ?? false;
110
-
111
- if (debug) console.log("Migrating database");
112
- const migrations = readMigrationFiles(config);
113
- if (debug) console.log("Migrations", migrations);
114
-
115
- try {
116
- if (debug) console.log("Setting up migrations table");
117
- const migrationsTable = "__drizzle_migrations";
118
-
119
- // Create migrations table if it doesn't exist
120
- // Note: Changed from SERIAL to INTEGER PRIMARY KEY AUTOINCREMENT for SQLite compatibility
121
- const migrationTableCreate = sql`
122
- CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
123
- id INTEGER PRIMARY KEY AUTOINCREMENT,
124
- hash text NOT NULL,
125
- created_at numeric
126
- )
127
- `;
128
- await db.run(migrationTableCreate);
129
-
130
- // Get the last applied migration
131
- const dbMigrations = await db.values<[number, string, string]>(
132
- sql`SELECT id, hash, created_at FROM ${sql.identifier(
133
- migrationsTable,
134
- )} ORDER BY created_at DESC LIMIT 1`,
135
- );
136
-
137
- const lastDbMigration = dbMigrations[0] ?? undefined;
138
- if (debug) console.log("Last applied migration:", lastDbMigration);
139
-
140
- // Apply pending migrations sequentially (without transaction wrapper)
141
- for (const migration of migrations) {
142
- const hasNoMigrations =
143
- lastDbMigration === undefined || !lastDbMigration.length;
144
- if (
145
- hasNoMigrations ||
146
- Number(lastDbMigration[2])! < migration.folderMillis
147
- ) {
148
- if (debug) console.log(`Applying migration: ${migration.folderMillis}`);
149
-
150
- try {
151
- // Execute all statements in the migration
152
- for (const stmt of migration.sql) {
153
- if (stmt.trim()) {
154
- // Skip empty statements
155
- if (debug) {
156
- console.log("Executing:", stmt.substring(0, 100) + "...");
157
- }
158
- await db.run(sql.raw(stmt));
159
- }
160
- }
161
-
162
- // Record successful migration
163
- await db.run(
164
- sql`INSERT INTO ${sql.identifier(
165
- migrationsTable,
166
- )} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`,
167
- );
168
-
169
- if (debug) {
170
- console.log(
171
- `✅ Migration ${migration.folderMillis} applied successfully`,
172
- );
173
- }
174
- } catch (migrationError: unknown) {
175
- console.error(
176
- `❌ Migration ${migration.folderMillis} failed:`,
177
- migrationError,
178
- );
179
- throw new Error(
180
- `Migration failed at ${migration.folderMillis}: ${
181
- migrationError instanceof Error
182
- ? migrationError.message
183
- : String(migrationError)
184
- }`,
185
- );
186
- }
187
- } else {
188
- if (debug) {
189
- console.log(
190
- `⏭️ Skipping already applied migration: ${migration.folderMillis}`,
191
- );
192
- }
193
- }
194
- }
195
-
196
- if (debug) console.log("✅ All migrations completed successfully");
197
- } catch (error: unknown) {
198
- console.error("❌ Migration process failed:", error);
199
- throw error;
200
- }
201
- }