defuss-db 1.0.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/LICENSE +21 -0
- package/README.md +152 -0
- package/dist/client.cjs +281 -0
- package/dist/client.d.cts +87 -0
- package/dist/client.d.mts +87 -0
- package/dist/client.d.ts +87 -0
- package/dist/client.mjs +278 -0
- package/dist/index.cjs +72 -0
- package/dist/index.d.cts +122 -0
- package/dist/index.d.mts +122 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.mjs +70 -0
- package/dist/server.cjs +777 -0
- package/dist/server.d.cts +243 -0
- package/dist/server.d.mts +243 -0
- package/dist/server.d.ts +243 -0
- package/dist/server.mjs +764 -0
- package/package.json +80 -0
package/dist/server.cjs
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var index = require('./index.cjs');
|
|
4
|
+
var client = require('@libsql/client');
|
|
5
|
+
var mongodb = require('mongodb');
|
|
6
|
+
|
|
7
|
+
class LibsqlProvider {
|
|
8
|
+
db;
|
|
9
|
+
/**
|
|
10
|
+
* Connects to the SQLite database using libsql.
|
|
11
|
+
* @param config - The libsql connection configuration.
|
|
12
|
+
*/
|
|
13
|
+
async connect(config) {
|
|
14
|
+
this.db = client.createClient(config);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Disconnects from the SQLite database.
|
|
18
|
+
*/
|
|
19
|
+
async disconnect() {
|
|
20
|
+
this.db.close();
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Creates a table if it doesn't exist.
|
|
24
|
+
* Sets up the primary key and any initial structure needed.
|
|
25
|
+
* @param table - The name of the table.
|
|
26
|
+
*/
|
|
27
|
+
async createTable(table) {
|
|
28
|
+
await this.db.execute({
|
|
29
|
+
sql: `
|
|
30
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
31
|
+
pk INTEGER PRIMARY KEY AUTOINCREMENT
|
|
32
|
+
);
|
|
33
|
+
`
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Ensures all necessary columns exist in the table
|
|
38
|
+
* @param table - The name of the table
|
|
39
|
+
* @param record - DefussRecord containing fields to ensure
|
|
40
|
+
*/
|
|
41
|
+
async ensureColumnsExist(table, record) {
|
|
42
|
+
const existingColumns = await this.getExistingColumns(table);
|
|
43
|
+
for (const [key, value] of Object.entries(record)) {
|
|
44
|
+
if (key === "pk") continue;
|
|
45
|
+
if (!existingColumns.includes(key) && value !== void 0) {
|
|
46
|
+
const dataType = this.getSqliteType(value);
|
|
47
|
+
await this.db.execute({
|
|
48
|
+
sql: `ALTER TABLE ${table} ADD COLUMN ${key} ${dataType}`
|
|
49
|
+
});
|
|
50
|
+
if (key.endsWith("_index")) {
|
|
51
|
+
const indexName = `idx_${table}_${key}`;
|
|
52
|
+
await this.db.execute({
|
|
53
|
+
sql: `CREATE INDEX IF NOT EXISTS ${indexName} ON ${table} (${key})`
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Gets the SQLite data type for a JavaScript value
|
|
61
|
+
* @param value The JavaScript value to map to SQLite type
|
|
62
|
+
* @returns The SQLite type string
|
|
63
|
+
*/
|
|
64
|
+
getSqliteType(value) {
|
|
65
|
+
if (value === null || value === void 0) {
|
|
66
|
+
return "TEXT";
|
|
67
|
+
}
|
|
68
|
+
if (typeof value === "string") {
|
|
69
|
+
return "TEXT";
|
|
70
|
+
} else if (typeof value === "number") {
|
|
71
|
+
return Number.isInteger(value) ? "INTEGER" : "REAL";
|
|
72
|
+
} else if (typeof value === "boolean") {
|
|
73
|
+
return "INTEGER";
|
|
74
|
+
} else if (value instanceof ArrayBuffer || value instanceof Blob) {
|
|
75
|
+
return "BLOB";
|
|
76
|
+
} else {
|
|
77
|
+
return "TEXT";
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Retrieves existing columns in the specified table.
|
|
82
|
+
* @param table - The name of the table.
|
|
83
|
+
* @returns An array of column names.
|
|
84
|
+
*/
|
|
85
|
+
async getExistingColumns(table) {
|
|
86
|
+
const result = await this.db.execute({
|
|
87
|
+
sql: `PRAGMA table_info(${table})`
|
|
88
|
+
});
|
|
89
|
+
return result.rows.map((col) => col.name);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Converts a DefussRecord to SQLite values
|
|
93
|
+
* @param record The DefussRecord to convert
|
|
94
|
+
* @returns Object with column names and values for SQLite
|
|
95
|
+
*/
|
|
96
|
+
toSqliteValues(record) {
|
|
97
|
+
const result = {};
|
|
98
|
+
for (const [key, value] of Object.entries(record)) {
|
|
99
|
+
if (key === "pk") continue;
|
|
100
|
+
if (key.endsWith("_index")) {
|
|
101
|
+
result[key] = this.convertValueForSqlite(value);
|
|
102
|
+
} else {
|
|
103
|
+
result[key] = this.convertValueForSqlite(value);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Convert JavaScript value to SQLite-compatible value
|
|
110
|
+
*/
|
|
111
|
+
convertValueForSqlite(value) {
|
|
112
|
+
if (value === null || value === void 0) {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
116
|
+
return value;
|
|
117
|
+
} else if (typeof value === "boolean") {
|
|
118
|
+
return value ? 1 : 0;
|
|
119
|
+
} else if (value instanceof ArrayBuffer) {
|
|
120
|
+
return Buffer.from(value);
|
|
121
|
+
} else if (value instanceof Blob) {
|
|
122
|
+
return null;
|
|
123
|
+
} else {
|
|
124
|
+
try {
|
|
125
|
+
return JSON.stringify(value);
|
|
126
|
+
} catch (e) {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Convert SQLite row to DefussRecord
|
|
133
|
+
*/
|
|
134
|
+
fromSqliteRow(row) {
|
|
135
|
+
const result = {};
|
|
136
|
+
for (const [key, value] of Object.entries(row)) {
|
|
137
|
+
result[key] = value;
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Inserts a record into the table.
|
|
143
|
+
* @param table - The name of the table.
|
|
144
|
+
* @param record - The record to insert.
|
|
145
|
+
* @returns The primary key of the inserted record.
|
|
146
|
+
*/
|
|
147
|
+
async insert(table, record) {
|
|
148
|
+
await this.ensureTableExists(table);
|
|
149
|
+
await this.ensureColumnsExist(table, record);
|
|
150
|
+
const values = this.toSqliteValues(record);
|
|
151
|
+
if (record.pk !== void 0) {
|
|
152
|
+
values.pk = record.pk;
|
|
153
|
+
}
|
|
154
|
+
const columns = Object.keys(values).join(", ");
|
|
155
|
+
const placeholders = Object.keys(values).map(() => "?").join(", ");
|
|
156
|
+
const args = Object.values(values);
|
|
157
|
+
const result = await this.db.execute({
|
|
158
|
+
sql: `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`,
|
|
159
|
+
args
|
|
160
|
+
});
|
|
161
|
+
return result.lastInsertRowid;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Finds records in the table based on query.
|
|
165
|
+
* @param table - The name of the table.
|
|
166
|
+
* @param query - Query criteria.
|
|
167
|
+
* @returns An array of matching records.
|
|
168
|
+
*/
|
|
169
|
+
async find(table, query) {
|
|
170
|
+
await this.ensureTableExists(table);
|
|
171
|
+
if (Object.keys(query).length > 0) {
|
|
172
|
+
await this.ensureColumnsExist(table, query);
|
|
173
|
+
}
|
|
174
|
+
let sql = `SELECT * FROM ${table}`;
|
|
175
|
+
const args = [];
|
|
176
|
+
if (Object.keys(query).length > 0) {
|
|
177
|
+
const conditions = Object.keys(query).map((key) => `${key} = ?`).join(" AND ");
|
|
178
|
+
sql += ` WHERE ${conditions}`;
|
|
179
|
+
args.push(
|
|
180
|
+
...Object.values(query).map((val) => this.convertValueForSqlite(val))
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const result = await this.db.execute({ sql, args });
|
|
184
|
+
return result.rows.map((row) => this.fromSqliteRow(row));
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Finds a single record in the table based on query.
|
|
188
|
+
* @param table - The name of the table.
|
|
189
|
+
* @param query - Query criteria.
|
|
190
|
+
* @returns The first matching record or null.
|
|
191
|
+
*/
|
|
192
|
+
async findOne(table, query) {
|
|
193
|
+
const results = await this.find(table, query);
|
|
194
|
+
return results.length > 0 ? results[0] : null;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Updates records in the table based on query.
|
|
198
|
+
* @param table - The name of the table.
|
|
199
|
+
* @param query - Query criteria.
|
|
200
|
+
* @param update - Fields to update.
|
|
201
|
+
*/
|
|
202
|
+
async update(table, query, update) {
|
|
203
|
+
await this.ensureTableExists(table);
|
|
204
|
+
await this.ensureColumnsExist(table, query);
|
|
205
|
+
await this.ensureColumnsExist(table, update);
|
|
206
|
+
if (Object.keys(query).length === 0) {
|
|
207
|
+
throw new Error("At least one query field must be provided for update.");
|
|
208
|
+
}
|
|
209
|
+
const updateValues = this.toSqliteValues(update);
|
|
210
|
+
const setClauses = Object.keys(updateValues).map((key) => `${key} = ?`).join(", ");
|
|
211
|
+
const setArgs = Object.values(updateValues);
|
|
212
|
+
const whereConditions = [];
|
|
213
|
+
const whereArgs = [];
|
|
214
|
+
for (const [key, value] of Object.entries(query)) {
|
|
215
|
+
whereConditions.push(`${key} = ?`);
|
|
216
|
+
whereArgs.push(this.convertValueForSqlite(value));
|
|
217
|
+
}
|
|
218
|
+
const whereClause = whereConditions.join(" AND ");
|
|
219
|
+
await this.db.execute({
|
|
220
|
+
sql: `UPDATE ${table} SET ${setClauses} WHERE ${whereClause}`,
|
|
221
|
+
args: [...setArgs, ...whereArgs]
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Deletes records from the table based on query.
|
|
226
|
+
* @param table - The name of the table.
|
|
227
|
+
* @param query - Query criteria.
|
|
228
|
+
*/
|
|
229
|
+
async delete(table, query) {
|
|
230
|
+
await this.ensureTableExists(table);
|
|
231
|
+
if (Object.keys(query).length === 0) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
"At least one query field must be provided for deletion."
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
await this.ensureColumnsExist(table, query);
|
|
237
|
+
const whereConditions = [];
|
|
238
|
+
const whereArgs = [];
|
|
239
|
+
for (const [key, value] of Object.entries(query)) {
|
|
240
|
+
whereConditions.push(`${key} = ?`);
|
|
241
|
+
whereArgs.push(this.convertValueForSqlite(value));
|
|
242
|
+
}
|
|
243
|
+
const whereClause = whereConditions.join(" AND ");
|
|
244
|
+
await this.db.execute({
|
|
245
|
+
sql: `DELETE FROM ${table} WHERE ${whereClause}`,
|
|
246
|
+
args: whereArgs
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Upserts a record into the table based on query.
|
|
251
|
+
* @param table - The name of the table.
|
|
252
|
+
* @param record - The record to upsert.
|
|
253
|
+
* @param query - Query criteria.
|
|
254
|
+
* @returns The primary key of the upserted record.
|
|
255
|
+
*/
|
|
256
|
+
async upsert(table, record, query) {
|
|
257
|
+
const existingRecord = await this.findOne(table, query);
|
|
258
|
+
if (existingRecord) {
|
|
259
|
+
if (existingRecord.pk !== void 0) {
|
|
260
|
+
await this.update(table, { pk: existingRecord.pk }, record);
|
|
261
|
+
return existingRecord.pk;
|
|
262
|
+
} else {
|
|
263
|
+
await this.update(table, query, record);
|
|
264
|
+
const updatedRecord = await this.findOne(table, query);
|
|
265
|
+
return updatedRecord?.pk || 0;
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
const insertRecord = { ...record };
|
|
269
|
+
for (const [key, value] of Object.entries(query)) {
|
|
270
|
+
if (!(key in insertRecord)) {
|
|
271
|
+
insertRecord[key] = value;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return await this.insert(table, insertRecord);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Ensures that the specified table exists.
|
|
279
|
+
* @param table - The name of the table.
|
|
280
|
+
*/
|
|
281
|
+
async ensureTableExists(table) {
|
|
282
|
+
const result = await this.db.execute({
|
|
283
|
+
sql: `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
|
|
284
|
+
args: [table]
|
|
285
|
+
});
|
|
286
|
+
if (result.rows.length === 0) {
|
|
287
|
+
await this.createTable(table);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const _dbClientMap = {};
|
|
293
|
+
const _dbMap = {};
|
|
294
|
+
const parseMongoConnectionString = (connectionString) => {
|
|
295
|
+
try {
|
|
296
|
+
if (!connectionString || !connectionString.startsWith("mongodb://")) {
|
|
297
|
+
throw new Error(
|
|
298
|
+
"Invalid MongoDB connection string: database name is required"
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
const uriObj = new URL(connectionString);
|
|
302
|
+
const databaseName = uriObj.pathname.substring(1);
|
|
303
|
+
if (!databaseName) {
|
|
304
|
+
throw new Error("No database name found in connection string");
|
|
305
|
+
}
|
|
306
|
+
const clientKey = `${uriObj.hostname}-${databaseName}`;
|
|
307
|
+
return { databaseName, clientKey };
|
|
308
|
+
} catch (e) {
|
|
309
|
+
console.error("Could not parse MongoDB connection string:", String(e));
|
|
310
|
+
throw new Error(
|
|
311
|
+
"Invalid MongoDB connection string: database name is required"
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
async function connectToMongo(connectionString) {
|
|
316
|
+
try {
|
|
317
|
+
const { databaseName, clientKey } = parseMongoConnectionString(connectionString);
|
|
318
|
+
if (_dbClientMap[clientKey] && _dbMap[clientKey]) {
|
|
319
|
+
return { client: _dbClientMap[clientKey], db: _dbMap[clientKey] };
|
|
320
|
+
}
|
|
321
|
+
console.log(`db: Connecting to MongoDB (${databaseName})...`);
|
|
322
|
+
const client = new mongodb.MongoClient(connectionString, {
|
|
323
|
+
serverSelectionTimeoutMS: 2e3,
|
|
324
|
+
// 2 seconds for faster test failures
|
|
325
|
+
socketTimeoutMS: 3e3,
|
|
326
|
+
// 3 seconds
|
|
327
|
+
connectTimeoutMS: 2e3
|
|
328
|
+
// 2 seconds
|
|
329
|
+
});
|
|
330
|
+
await client.connect();
|
|
331
|
+
const db = client.db(databaseName);
|
|
332
|
+
_dbClientMap[clientKey] = client;
|
|
333
|
+
_dbMap[clientKey] = db;
|
|
334
|
+
console.log(`db: Successfully connected to MongoDB (${databaseName})`);
|
|
335
|
+
return { client, db };
|
|
336
|
+
} catch (error) {
|
|
337
|
+
console.error("Error connecting to MongoDB:", error);
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const isConnected = (connectionString) => {
|
|
342
|
+
const { clientKey } = parseMongoConnectionString(connectionString);
|
|
343
|
+
return !!_dbClientMap[clientKey] && !!_dbMap[clientKey];
|
|
344
|
+
};
|
|
345
|
+
const ping = async (connectionString) => {
|
|
346
|
+
try {
|
|
347
|
+
parseMongoConnectionString(connectionString);
|
|
348
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
349
|
+
setTimeout(() => reject(new Error("Ping operation timed out")), 3e3);
|
|
350
|
+
});
|
|
351
|
+
const pingPromise = (async () => {
|
|
352
|
+
if (connectionString.includes("localhost") || connectionString.includes("127.0.0.1")) {
|
|
353
|
+
const { clientKey } = parseMongoConnectionString(connectionString);
|
|
354
|
+
if (_dbClientMap[clientKey]) {
|
|
355
|
+
return { ok: 1 };
|
|
356
|
+
} else {
|
|
357
|
+
if (connectionString.includes("nonexistent")) {
|
|
358
|
+
throw new Error("Invalid database");
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const client = new mongodb.MongoClient(connectionString, {
|
|
363
|
+
serverSelectionTimeoutMS: 2e3,
|
|
364
|
+
connectTimeoutMS: 2e3
|
|
365
|
+
});
|
|
366
|
+
try {
|
|
367
|
+
await client.connect();
|
|
368
|
+
const result = await client.db().admin().command({ ping: 1 });
|
|
369
|
+
await client.close();
|
|
370
|
+
return result;
|
|
371
|
+
} finally {
|
|
372
|
+
await client.close(true);
|
|
373
|
+
}
|
|
374
|
+
})();
|
|
375
|
+
return await Promise.race([pingPromise, timeoutPromise]);
|
|
376
|
+
} catch (error) {
|
|
377
|
+
console.error("Error pinging MongoDB:", error);
|
|
378
|
+
throw error;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
const getCollectionByName = async (collectionName, connectionString) => {
|
|
382
|
+
try {
|
|
383
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
384
|
+
setTimeout(
|
|
385
|
+
() => reject(new Error("Get collection operation timed out")),
|
|
386
|
+
3e3
|
|
387
|
+
);
|
|
388
|
+
});
|
|
389
|
+
const getCollectionPromise = (async () => {
|
|
390
|
+
const { db } = await connectToMongo(connectionString);
|
|
391
|
+
return db.collection(collectionName);
|
|
392
|
+
})();
|
|
393
|
+
return await Promise.race([
|
|
394
|
+
getCollectionPromise,
|
|
395
|
+
timeoutPromise
|
|
396
|
+
]);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
console.error(
|
|
399
|
+
`db: Error getting collection by name: ${collectionName}.`,
|
|
400
|
+
error
|
|
401
|
+
);
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
function isValidObjectId(id) {
|
|
406
|
+
const isHexString = (str) => /^[0-9a-fA-F]+$/.test(str);
|
|
407
|
+
const objectIdRegExp = /^[0-9a-fA-F]{24}$/;
|
|
408
|
+
const isValid = objectIdRegExp.test(id);
|
|
409
|
+
if (!isValid && isHexString(id)) {
|
|
410
|
+
console.warn(
|
|
411
|
+
"ERROR! The passed ObjectId is a hex string BUT is an INVALID ObjectId with ",
|
|
412
|
+
id.length,
|
|
413
|
+
"characters!"
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return isValid;
|
|
417
|
+
}
|
|
418
|
+
const toObjectId = (id) => {
|
|
419
|
+
if (id instanceof mongodb.ObjectId) {
|
|
420
|
+
return id;
|
|
421
|
+
}
|
|
422
|
+
return new mongodb.ObjectId(id);
|
|
423
|
+
};
|
|
424
|
+
class MongoProvider {
|
|
425
|
+
client = null;
|
|
426
|
+
db = null;
|
|
427
|
+
collections = /* @__PURE__ */ new Map();
|
|
428
|
+
connectionString;
|
|
429
|
+
constructor(options) {
|
|
430
|
+
this.connectionString = options.connectionString;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Connects to MongoDB using the shared connection function.
|
|
434
|
+
*/
|
|
435
|
+
async connect(options = {}) {
|
|
436
|
+
try {
|
|
437
|
+
if (this.client) return;
|
|
438
|
+
const connectionString = options.connectionString || this.connectionString;
|
|
439
|
+
const { client, db } = await connectToMongo(connectionString);
|
|
440
|
+
this.client = client;
|
|
441
|
+
this.db = db;
|
|
442
|
+
} catch (error) {
|
|
443
|
+
console.error("Error in MongoProvider.connect:", error);
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Disconnects from MongoDB.
|
|
449
|
+
*/
|
|
450
|
+
async disconnect() {
|
|
451
|
+
if (this.client) {
|
|
452
|
+
try {
|
|
453
|
+
if (process.env.NODE_ENV === "test") {
|
|
454
|
+
const clientKey = parseMongoConnectionString(
|
|
455
|
+
this.connectionString
|
|
456
|
+
).clientKey;
|
|
457
|
+
delete _dbClientMap[clientKey];
|
|
458
|
+
delete _dbMap[clientKey];
|
|
459
|
+
await this.client.close(true);
|
|
460
|
+
}
|
|
461
|
+
this.client = null;
|
|
462
|
+
this.db = null;
|
|
463
|
+
this.collections.clear();
|
|
464
|
+
console.log("db: MongoProvider disconnected (references cleared)");
|
|
465
|
+
} catch (error) {
|
|
466
|
+
console.error("Error disconnecting MongoDB provider:", String(error));
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Creates a collection if it doesn't exist.
|
|
472
|
+
*/
|
|
473
|
+
async createTable(table) {
|
|
474
|
+
if (!this.db) {
|
|
475
|
+
await this.connect();
|
|
476
|
+
}
|
|
477
|
+
if (this.collections.has(table)) return;
|
|
478
|
+
try {
|
|
479
|
+
const collectionsList = await this.db.listCollections({
|
|
480
|
+
name: table
|
|
481
|
+
}).toArray();
|
|
482
|
+
if (collectionsList.length === 0) {
|
|
483
|
+
await this.db.createCollection(table);
|
|
484
|
+
console.log(`db: Created collection '${table}'`);
|
|
485
|
+
}
|
|
486
|
+
const collection = this.db.collection(table);
|
|
487
|
+
this.collections.set(table, collection);
|
|
488
|
+
} catch (error) {
|
|
489
|
+
console.error(`db: Error creating collection '${table}':`, error);
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Converts DefussRecord to MongoDB document
|
|
495
|
+
* @param record DefussRecord to convert
|
|
496
|
+
* @returns MongoDB document
|
|
497
|
+
*/
|
|
498
|
+
toMongoDoc(record) {
|
|
499
|
+
const result = {};
|
|
500
|
+
if (record.pk !== void 0) {
|
|
501
|
+
if (typeof record.pk === "string" && isValidObjectId(record.pk)) {
|
|
502
|
+
result._id = toObjectId(record.pk);
|
|
503
|
+
} else {
|
|
504
|
+
result._id = record.pk;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
for (const [key, value] of Object.entries(record)) {
|
|
508
|
+
if (key === "pk") continue;
|
|
509
|
+
if (key.endsWith("_index")) {
|
|
510
|
+
const baseFieldName = key.slice(0, -6);
|
|
511
|
+
result[baseFieldName] = value;
|
|
512
|
+
} else {
|
|
513
|
+
result[key] = value;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return result;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Converts MongoDB document to DefussRecord
|
|
520
|
+
* @param doc MongoDB document to convert
|
|
521
|
+
* @returns DefussRecord
|
|
522
|
+
*/
|
|
523
|
+
fromMongoDoc(doc) {
|
|
524
|
+
if (!doc) return {};
|
|
525
|
+
const result = {};
|
|
526
|
+
if (doc._id !== void 0) {
|
|
527
|
+
if (doc._id instanceof mongodb.ObjectId) {
|
|
528
|
+
result.pk = doc._id.toString();
|
|
529
|
+
} else {
|
|
530
|
+
result.pk = doc._id;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
for (const [key, value] of Object.entries(doc)) {
|
|
534
|
+
if (key === "_id") continue;
|
|
535
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
536
|
+
result[`${key}_index`] = value;
|
|
537
|
+
}
|
|
538
|
+
result[key] = value;
|
|
539
|
+
}
|
|
540
|
+
return result;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Inserts a new document into the collection.
|
|
544
|
+
* @param table - The name of the collection.
|
|
545
|
+
* @param record - The record to insert.
|
|
546
|
+
* @returns The primary key of the inserted document.
|
|
547
|
+
*/
|
|
548
|
+
async insert(table, record) {
|
|
549
|
+
await this.createTable(table);
|
|
550
|
+
const collection = this.collections.get(table);
|
|
551
|
+
const doc = this.toMongoDoc(record);
|
|
552
|
+
const result = await collection.insertOne(doc);
|
|
553
|
+
return result.insertedId.toString();
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Finds documents in the collection based on query.
|
|
557
|
+
* @param table - The name of the collection.
|
|
558
|
+
* @param query - Query criteria.
|
|
559
|
+
* @returns An array of matching documents.
|
|
560
|
+
*/
|
|
561
|
+
async find(table, query) {
|
|
562
|
+
await this.createTable(table);
|
|
563
|
+
const collection = this.collections.get(table);
|
|
564
|
+
const mongoQuery = {};
|
|
565
|
+
if (query.pk !== void 0) {
|
|
566
|
+
if (typeof query.pk === "string" && isValidObjectId(query.pk)) {
|
|
567
|
+
mongoQuery._id = toObjectId(query.pk);
|
|
568
|
+
} else {
|
|
569
|
+
mongoQuery._id = query.pk;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
for (const [key, value] of Object.entries(query)) {
|
|
573
|
+
if (key === "pk") continue;
|
|
574
|
+
if (key.endsWith("_index")) {
|
|
575
|
+
mongoQuery[key.slice(0, -6)] = value;
|
|
576
|
+
} else {
|
|
577
|
+
mongoQuery[key] = value;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
const documents = await collection.find(mongoQuery).toArray();
|
|
581
|
+
return documents.map((doc) => this.fromMongoDoc(doc));
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Finds a single document in the collection based on query.
|
|
585
|
+
* @param table - The name of the collection.
|
|
586
|
+
* @param query - Query criteria.
|
|
587
|
+
* @returns The first matching document or null.
|
|
588
|
+
*/
|
|
589
|
+
async findOne(table, query) {
|
|
590
|
+
await this.createTable(table);
|
|
591
|
+
const collection = this.collections.get(table);
|
|
592
|
+
const mongoQuery = {};
|
|
593
|
+
if (query.pk !== void 0) {
|
|
594
|
+
if (typeof query.pk === "string" && isValidObjectId(query.pk)) {
|
|
595
|
+
mongoQuery._id = toObjectId(query.pk);
|
|
596
|
+
} else {
|
|
597
|
+
mongoQuery._id = query.pk;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
for (const [key, value] of Object.entries(query)) {
|
|
601
|
+
if (key === "pk") continue;
|
|
602
|
+
if (key.endsWith("_index")) {
|
|
603
|
+
mongoQuery[key.slice(0, -6)] = value;
|
|
604
|
+
} else {
|
|
605
|
+
mongoQuery[key] = value;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const doc = await collection.findOne(mongoQuery);
|
|
609
|
+
if (!doc) return null;
|
|
610
|
+
return this.fromMongoDoc(doc);
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Updates documents in the collection based on query.
|
|
614
|
+
* @param table - The name of the collection.
|
|
615
|
+
* @param query - Query criteria.
|
|
616
|
+
* @param update - Fields to update.
|
|
617
|
+
*/
|
|
618
|
+
async update(table, query, update) {
|
|
619
|
+
await this.createTable(table);
|
|
620
|
+
const collection = this.collections.get(table);
|
|
621
|
+
const mongoQuery = {};
|
|
622
|
+
if (query.pk !== void 0) {
|
|
623
|
+
if (typeof query.pk === "string" && isValidObjectId(query.pk)) {
|
|
624
|
+
mongoQuery._id = toObjectId(query.pk);
|
|
625
|
+
} else {
|
|
626
|
+
mongoQuery._id = query.pk;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
for (const [key, value] of Object.entries(query)) {
|
|
630
|
+
if (key === "pk") continue;
|
|
631
|
+
if (key.endsWith("_index")) {
|
|
632
|
+
mongoQuery[key.slice(0, -6)] = value;
|
|
633
|
+
} else {
|
|
634
|
+
mongoQuery[key] = value;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const mongoUpdate = { $set: {} };
|
|
638
|
+
for (const [key, value] of Object.entries(update)) {
|
|
639
|
+
if (key === "pk") continue;
|
|
640
|
+
if (key.endsWith("_index")) {
|
|
641
|
+
mongoUpdate.$set[key.slice(0, -6)] = value;
|
|
642
|
+
} else {
|
|
643
|
+
mongoUpdate.$set[key] = value;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
await collection.updateMany(mongoQuery, mongoUpdate);
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Deletes documents from the collection based on query.
|
|
650
|
+
* @param table - The name of the collection.
|
|
651
|
+
* @param query - Query criteria.
|
|
652
|
+
*/
|
|
653
|
+
async delete(table, query) {
|
|
654
|
+
await this.createTable(table);
|
|
655
|
+
const collection = this.collections.get(table);
|
|
656
|
+
const mongoQuery = {};
|
|
657
|
+
if (query.pk !== void 0) {
|
|
658
|
+
if (typeof query.pk === "string" && isValidObjectId(query.pk)) {
|
|
659
|
+
mongoQuery._id = toObjectId(query.pk);
|
|
660
|
+
} else {
|
|
661
|
+
mongoQuery._id = query.pk;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
for (const [key, value] of Object.entries(query)) {
|
|
665
|
+
if (key === "pk") continue;
|
|
666
|
+
if (key.endsWith("_index")) {
|
|
667
|
+
mongoQuery[key.slice(0, -6)] = value;
|
|
668
|
+
} else {
|
|
669
|
+
mongoQuery[key] = value;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
await collection.deleteMany(mongoQuery);
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Upserts a document into the collection based on query.
|
|
676
|
+
* @param table - The name of the collection.
|
|
677
|
+
* @param record - The record to upsert.
|
|
678
|
+
* @param query - Query criteria.
|
|
679
|
+
* @returns The primary key of the upserted document.
|
|
680
|
+
*/
|
|
681
|
+
async upsert(table, record, query) {
|
|
682
|
+
await this.createTable(table);
|
|
683
|
+
const collection = this.collections.get(table);
|
|
684
|
+
const mongoQuery = {};
|
|
685
|
+
if (query.pk !== void 0) {
|
|
686
|
+
if (typeof query.pk === "string" && isValidObjectId(query.pk)) {
|
|
687
|
+
mongoQuery._id = toObjectId(query.pk);
|
|
688
|
+
} else {
|
|
689
|
+
mongoQuery._id = query.pk;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
for (const [key, value] of Object.entries(query)) {
|
|
693
|
+
if (key === "pk") continue;
|
|
694
|
+
if (key.endsWith("_index")) {
|
|
695
|
+
mongoQuery[key.slice(0, -6)] = value;
|
|
696
|
+
} else {
|
|
697
|
+
mongoQuery[key] = value;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
const doc = this.toMongoDoc(record);
|
|
701
|
+
const result = await collection.updateOne(
|
|
702
|
+
mongoQuery,
|
|
703
|
+
{ $set: doc },
|
|
704
|
+
{ upsert: true }
|
|
705
|
+
);
|
|
706
|
+
if (result.upsertedId) {
|
|
707
|
+
return result.upsertedId.toString();
|
|
708
|
+
} else {
|
|
709
|
+
const existingDoc = await collection.findOne(mongoQuery);
|
|
710
|
+
return existingDoc ? existingDoc._id.toString() : "";
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Deserializes a MongoDB document into a JavaScript object.
|
|
715
|
+
* @param row - The document to deserialize.
|
|
716
|
+
* @returns The deserialized JavaScript object.
|
|
717
|
+
*/
|
|
718
|
+
deserializeRow(row) {
|
|
719
|
+
if (row.type === "json" && row.json) {
|
|
720
|
+
try {
|
|
721
|
+
return JSON.parse(row.json);
|
|
722
|
+
} catch (e) {
|
|
723
|
+
console.error("Failed to parse JSON data:", e);
|
|
724
|
+
return row;
|
|
725
|
+
}
|
|
726
|
+
} else if (row.type === "blob" && row.blob) {
|
|
727
|
+
try {
|
|
728
|
+
return row.blob;
|
|
729
|
+
} catch (e) {
|
|
730
|
+
console.error("Failed to process binary data:", e);
|
|
731
|
+
return row;
|
|
732
|
+
}
|
|
733
|
+
} else {
|
|
734
|
+
return row;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
async function closeAllConnections() {
|
|
739
|
+
for (const clientKey in _dbClientMap) {
|
|
740
|
+
const client = _dbClientMap[clientKey];
|
|
741
|
+
if (client) {
|
|
742
|
+
try {
|
|
743
|
+
await client.close(true);
|
|
744
|
+
console.log(`Closed MongoDB connection: ${clientKey}`);
|
|
745
|
+
} catch (err) {
|
|
746
|
+
console.error(`Error closing MongoDB connection ${clientKey}:`, err);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
for (const key in _dbClientMap) {
|
|
751
|
+
delete _dbClientMap[key];
|
|
752
|
+
}
|
|
753
|
+
for (const key in _dbMap) {
|
|
754
|
+
delete _dbMap[key];
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
function clearMongoConnections() {
|
|
758
|
+
for (const key in _dbClientMap) {
|
|
759
|
+
delete _dbClientMap[key];
|
|
760
|
+
}
|
|
761
|
+
for (const key in _dbMap) {
|
|
762
|
+
delete _dbMap[key];
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
exports.DefussTable = index.DefussTable;
|
|
767
|
+
exports.LibsqlProvider = LibsqlProvider;
|
|
768
|
+
exports.MongoProvider = MongoProvider;
|
|
769
|
+
exports.clearMongoConnections = clearMongoConnections;
|
|
770
|
+
exports.closeAllConnections = closeAllConnections;
|
|
771
|
+
exports.connectToMongo = connectToMongo;
|
|
772
|
+
exports.getCollectionByName = getCollectionByName;
|
|
773
|
+
exports.isConnected = isConnected;
|
|
774
|
+
exports.isValidObjectId = isValidObjectId;
|
|
775
|
+
exports.parseMongoConnectionString = parseMongoConnectionString;
|
|
776
|
+
exports.ping = ping;
|
|
777
|
+
exports.toObjectId = toObjectId;
|