File size: 6,732 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// src/lib/db/adapters/libsqlAdapter.ts
import { Worker, MessageChannel, receiveMessageOnPort } from "node:worker_threads";
import type { SqliteAdapter, PreparedStatement, RunResult } from "./types";

const workerCode = `
const { parentPort } = require('worker_threads');
const { createClient } = require('@libsql/client');

let client;

parentPort.on('message', async (msg) => {
  if (msg.type === 'init') {
    try {
      client = createClient({
        url: msg.url,
        syncUrl: msg.syncUrl,
        authToken: msg.authToken,
        syncInterval: msg.syncInterval,
      });
      if (msg.syncUrl) {
        await client.sync();
      }
      parentPort.postMessage({ type: 'init_done' });
    } catch (err) {
      parentPort.postMessage({ type: 'init_failed', error: err.message });
    }
    return;
  }

  const { type, sql, params, sharedBuffer, port } = msg;
  const sharedArray = new Int32Array(sharedBuffer);

  try {
    if (type === 'sync') {
      if (client.sync) {
        await client.sync();
      }
      port.postMessage({ success: true });
    } else if (type === 'exec') {
      await client.execute(sql);
      port.postMessage({ success: true });
    } else if (type === 'close') {
      if (client.close) {
        client.close();
      }
      port.postMessage({ success: true });
    } else {
      const rs = await client.execute({ sql, args: params || [] });
      if (type === 'run') {
        const result = {
          changes: rs.rowsAffected || 0,
          lastInsertRowid: rs.lastInsertRowid !== undefined ? String(rs.lastInsertRowid) : 0
        };
        port.postMessage({ success: true, result });
      } else {
        const rows = rs.rows.map(row => {
          const obj = {};
          for (const col of rs.columns) {
            obj[col] = row[col];
          }
          return obj;
        });
        if (type === 'get') {
          port.postMessage({ success: true, result: rows[0] });
        } else {
          port.postMessage({ success: true, result: rows });
        }
      }
    }
  } catch (err) {
    port.postMessage({ success: false, error: err.message });
  } finally {
    Atomics.store(sharedArray, 0, 1);
    Atomics.notify(sharedArray, 0);
  }
});
`;

export function createLibsqlAdapter(
  filePath: string,
  options?: { url?: string; syncUrl?: string; authToken?: string; syncInterval?: number }
): SqliteAdapter {
  const worker = new Worker(workerCode, { eval: true });

  const url = options?.url || `file:${filePath}`;
  const syncUrl = options?.syncUrl;
  const authToken = options?.authToken;
  const syncInterval = options?.syncInterval || 30000;

  // Initialize the worker synchronously (block until done)
  const sharedBuffer = new SharedArrayBuffer(4);
  const sharedArray = new Int32Array(sharedBuffer);
  sharedArray[0] = 0;

  let initError: string | null = null;
  let initDone = false;

  worker.on("message", (msg) => {
    if (msg.type === "init_done") {
      initDone = true;
      Atomics.store(sharedArray, 0, 1);
      Atomics.notify(sharedArray, 0);
    } else if (msg.type === "init_failed") {
      initError = msg.error;
      Atomics.store(sharedArray, 0, 1);
      Atomics.notify(sharedArray, 0);
    }
  });

  worker.postMessage({
    type: "init",
    url,
    syncUrl,
    authToken,
    syncInterval,
  });

  // Block until initialized
  Atomics.wait(sharedArray, 0, 0);

  if (initError) {
    worker.terminate();
    throw new Error(`[DB] LibSQL initialization failed: ${initError}`);
  }

  let _isOpen = true;

  function querySync(type: string, sql: string, params?: unknown[]): any {
    if (!_isOpen) {
      throw new Error("[DB] Database is closed");
    }

    const channel = new MessageChannel();
    const queryBuffer = new SharedArrayBuffer(4);
    const queryArray = new Int32Array(queryBuffer);
    queryArray[0] = 0;

    worker.postMessage(
      {
        type,
        sql,
        params,
        sharedBuffer: queryBuffer,
        port: channel.port2,
      },
      [channel.port2]
    );

    // Block main thread
    Atomics.wait(queryArray, 0, 0);

    const msg = receiveMessageOnPort(channel.port1);
    if (!msg) {
      throw new Error("[DB] LibSQL worker did not return a response");
    }

    const { success, result, error } = msg.message;
    if (!success) {
      throw new Error(`[DB] LibSQL Query Error: ${error}`);
    }

    return result;
  }

  function runSavepoint<T>(fn: (...args: unknown[]) => T, ...args: unknown[]): T {
    const sp = `sp_${Math.random().toString(36).slice(2)}`;
    querySync("exec", `SAVEPOINT "${sp}"`);
    try {
      const result = fn(...args);
      querySync("exec", `RELEASE "${sp}"`);
      return result;
    } catch (err) {
      try {
        querySync("exec", `ROLLBACK TO "${sp}"`);
        querySync("exec", `RELEASE "${sp}"`);
      } catch {}
      throw err;
    }
  }

  return {
    driver: "libsql" as any,

    get open() {
      return _isOpen;
    },

    get name() {
      return filePath;
    },

    prepare(sql: string): PreparedStatement {
      return {
        run(...params: unknown[]): RunResult {
          const r = querySync("run", sql, params);
          return {
            changes: Number(r.changes ?? 0),
            lastInsertRowid: typeof r.lastInsertRowid === "string" ? BigInt(r.lastInsertRowid) : BigInt(r.lastInsertRowid ?? 0),
          };
        },
        get(...params: unknown[]): unknown {
          return querySync("get", sql, params);
        },
        all(...params: unknown[]): unknown[] {
          return querySync("all", sql, params);
        },
      };
    },

    exec(sql: string): void {
      querySync("exec", sql);
    },

    pragma(pragmaStr: string, options?: { simple?: boolean }): unknown {
      const sql = `PRAGMA ${pragmaStr}`;
      if (options?.simple) {
        const row = querySync("get", sql) as Record<string, unknown> | undefined;
        if (!row) return null;
        return Object.values(row)[0] ?? null;
      }
      return querySync("all", sql);
    },

    transaction<T>(fn: (...args: unknown[]) => T): (...args: unknown[]) => T {
      return (...args: unknown[]) => runSavepoint(fn, ...args);
    },

    immediate(fn: () => void): void {
      runSavepoint(() => fn());
    },

    async backup(destination: string): Promise<void> {
      // For remote or replica, we trigger a manual sync
      querySync("sync", "");
    },

    checkpoint(mode = "TRUNCATE"): void {
      // WAL checkpoints are managed on Turso side
    },

    close(): void {
      if (_isOpen) {
        try {
          querySync("close", "");
        } catch {}
        worker.terminate();
        _isOpen = false;
      }
    },

    get raw() {
      return null;
    },
  };
}