Repository navigation
Expand file tree
/
Copy pathconnection.ts
More file actions
241 lines (154 loc) · 5.82 KB
/
Copy pathconnection.ts
File metadata and controls
241 lines (154 loc) · 5.82 KB
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
/**
* Connection worker — owns a Kysely instance and handles DB operations.
*
* Receives events via WorkerBridge and responds with correlation IDs.
* Uses the dialect factory directly to avoid observer/manager side effects
* that belong only in the main process.
*
* @example
* ```typescript
* const bridge = new WorkerBridge<ConnectionEvents>(CONNECTION_WORKER)
* await bridge.request('connect', { dialect: 'sqlite', connectionString: ':memory:' })
* const { rows } = await bridge.request('query', { sql: 'SELECT 1' })
* ```
*/
import { attempt } from '@logosdx/utils';
import { CompiledQuery, type Kysely } from 'kysely';
import { WorkerBridge } from '../core/worker-bridge/bridge.js';
import type { ConnectionEvents, Correlated } from '../core/worker-bridge/types.js';
import type { Dialect } from '../core/connection/types.js';
// === Declarations ===
const bridge = new WorkerBridge<ConnectionEvents>();
let db: Kysely<unknown> | null = null;
let destroyFn: (() => Promise<void>) | null = null;
// === Helpers ===
/**
* Create a Kysely instance from a dialect name and connection string.
*
* Bypasses the main-process factory to avoid observer emissions and
* connection-manager tracking that don't belong inside a worker.
*/
async function createDialectConnection(dialect: Dialect, connectionString: string) {
type DialectFactory = (config: { dialect: Dialect; database: string }) => {
db: Kysely<unknown>;
dialect: Dialect;
destroy: () => Promise<void>;
};
let createFn: DialectFactory;
if (dialect === 'sqlite') {
if (typeof (globalThis as Record<string, unknown>)['Bun'] !== 'undefined') {
const mod = await import('../core/connection/dialects/sqlite-bun.js');
createFn = mod.createBunSqliteConnection as unknown as DialectFactory;
}
else {
const mod = await import('../core/connection/dialects/sqlite.js');
createFn = mod.createSqliteConnection as unknown as DialectFactory;
}
}
else if (dialect === 'postgres') {
const mod = await import('../core/connection/dialects/postgres.js');
createFn = mod.createPostgresConnection as unknown as DialectFactory;
}
else if (dialect === 'mysql') {
const mod = await import('../core/connection/dialects/mysql.js');
createFn = mod.createMysqlConnection as unknown as DialectFactory;
}
else if (dialect === 'mssql') {
const mod = await import('../core/connection/dialects/mssql.js');
createFn = mod.createMssqlConnection as unknown as DialectFactory;
}
else {
throw new Error(`Unsupported dialect: ${dialect}`);
}
return createFn({ dialect, database: connectionString });
}
// === Event handlers ===
bridge.on('connect', async ({ data }) => {
const { dialect, connectionString, __cid } = data as Correlated<ConnectionEvents['connect']>;
if (db) {
await destroyFn?.();
db = null;
destroyFn = null;
}
const [conn, err] = await attempt(() =>
createDialectConnection(dialect as Dialect, connectionString),
);
if (err) {
bridge.emit(`connect:res:${__cid}`, { success: false, error: err.message });
return;
}
db = conn!.db;
destroyFn = conn!.destroy;
bridge.emit(`connect:res:${__cid}`, { success: true });
});
bridge.on('disconnect', async ({ data }) => {
const { __cid } = data as Correlated<ConnectionEvents['disconnect']>;
if (destroyFn) {
await destroyFn();
db = null;
destroyFn = null;
}
bridge.emit(`disconnect:res:${__cid}`, {});
});
bridge.on('query', async ({ data }) => {
const { sql, params, __cid } = data as Correlated<ConnectionEvents['query']>;
if (!db) {
bridge.emit(`query:res:${__cid}`, { rows: [], error: 'Not connected' });
return;
}
const [result, err] = await attempt(() =>
db!.executeQuery(CompiledQuery.raw(sql, params ?? [])),
);
if (err) {
bridge.emit(`query:res:${__cid}`, { rows: [], error: err.message });
return;
}
bridge.emit(`query:res:${__cid}`, { rows: result!.rows as unknown[] });
});
bridge.on('query:batch', async ({ data }) => {
const { sql, params, batchSize, offset, __cid } = data as Correlated<ConnectionEvents['query:batch']>;
if (!db) {
bridge.emit(`query:batch:res:${__cid}`, {
rows: [],
offset,
hasMore: false,
error: 'Not connected',
});
return;
}
const [result, err] = await attempt(() =>
db!.executeQuery(CompiledQuery.raw(sql, params ?? [])),
);
if (err) {
bridge.emit(`query:batch:res:${__cid}`, {
rows: [],
offset,
hasMore: false,
error: err.message,
});
return;
}
const allRows = result!.rows as unknown[];
const sliced = allRows.slice(offset, offset + batchSize);
const hasMore = offset + batchSize < allRows.length;
bridge.emit(`query:batch:res:${__cid}`, { rows: sliced, offset, hasMore });
});
bridge.on('execute', async ({ data }) => {
const { sql, params, __cid } = data as Correlated<ConnectionEvents['execute']>;
if (!db) {
bridge.emit(`execute:res:${__cid}`, { affectedRows: 0, error: 'Not connected' });
return;
}
const [result, err] = await attempt(() =>
db!.executeQuery(CompiledQuery.raw(sql, params ?? [])),
);
if (err) {
bridge.emit(`execute:res:${__cid}`, { affectedRows: 0, error: err.message });
return;
}
const numAffectedRows = result!.numAffectedRows ?? BigInt(0);
const affectedRows = typeof numAffectedRows === 'bigint'
? Number(numAffectedRows)
: numAffectedRows;
bridge.emit(`execute:res:${__cid}`, { affectedRows });
});