-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmagicDB.js
More file actions
525 lines (423 loc) · 14.6 KB
/
magicDB.js
File metadata and controls
525 lines (423 loc) · 14.6 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
"use strict";
/// <reference types="./dexie/dexie.d.ts" />
import Dexie from "./dexie/dexie.js";
import { magicQueryAsync, magicQueryYield } from "./magicLinqToIndexedDb.js";
import {debugLog} from "./utilities/utilityHelpers.js";
/**
* @typedef {Object} DatabasesItem
* @property {string} name
* @property {Dexie} db
*/
/**
* @type {Array.<DatabasesItem>}
*/
//export async function initializeMagicMigration() {
// const { MagicMigration } = await import('/magicMigration.js'); // Dynamically import it
// const magicMigration = new MagicMigration(db); // Pass only Dexie.js
// magicMigration.Initialize(); // Call method (optional)
//}
let databases = new Map(); // Change array to a Map
export async function openDb(dbName) {
if (!dbName || typeof dbName !== "string") {
throw new Error("openDb: Invalid database name.");
}
if (databases.has(dbName)) {
const existingDb = databases.get(dbName);
if (!existingDb.isOpen()) {
await existingDb.open(); // Re-open if it was closed
}
return existingDb;
}
const db = new Dexie(dbName);
await db.open();
databases.set(dbName, db);
return db;
}
export async function closeDb(dbName) {
const db = databases.get(dbName);
if (db?.isOpen()) db.close();
databases.delete(dbName);
}
export function isDbOpen(dbName) {
if (!dbName || typeof dbName !== "string") {
console.error("isDbOpen: Invalid database name.");
return false;
}
const db = databases.get(dbName);
if (!db) {
// Not cached = definitely not open
return false;
}
if (typeof db.isOpen === "function") {
return db.isOpen(); // Dexie provides this
}
// Fallback just in case
return false;
}
export function listOpenDatabases() {
return Array.from(databases.entries())
.filter(([_, db]) => db.isOpen?.())
.map(([name]) => name);
}
export function createDb(dbStore) {
debugLog("Received dbStore in createDb", dbStore);
if (!dbStore || !dbStore.name) {
console.error("Blazor.IndexedDB.Framework - Invalid dbStore provided");
return;
}
const dbName = dbStore.name;
if (isDbOpen(dbName)) {
return;
}
const db = new Dexie(dbName);
const stores = {};
for (let i = 0; i < dbStore.storeSchemas.length; i++) {
const schema = dbStore.storeSchemas[i];
if (!schema || !schema.tableName) {
console.error(`Invalid schema at index ${i}:`, schema);
continue;
}
let def = "";
// **Handle Primary Key (Single or Compound)**
if (Array.isArray(schema.columnNamesInCompoundKey) && schema.columnNamesInCompoundKey.length > 0) {
if (schema.columnNamesInCompoundKey.length === 1) {
// Single primary key
if (schema.primaryKeyAuto) def += "++"; // Auto increment
def += schema.columnNamesInCompoundKey[0]; // Primary key column
} else {
// Compound primary key
def += `[${schema.columnNamesInCompoundKey.join('+')}]`;
}
}
// **Handle Unique Indexes**
if (Array.isArray(schema.uniqueIndexes)) {
for (let j = 0; j < schema.uniqueIndexes.length; j++) {
def += `,&${schema.uniqueIndexes[j]}`;
}
}
// **Handle Standard Indexes**
if (Array.isArray(schema.indexes)) {
for (let j = 0; j < schema.indexes.length; j++) {
def += `,${schema.indexes[j]}`;
}
}
// **Handle Compound Indexes**
if (Array.isArray(schema.columnNamesInCompoundIndex)) {
for (let j = 0; j < schema.columnNamesInCompoundIndex.length; j++) {
let compoundIndex = schema.columnNamesInCompoundIndex[j];
if (compoundIndex.length > 0) {
def += `,[${compoundIndex.join('+')}]`; // Correct format for compound indexes
}
}
}
stores[schema.tableName] = def;
}
debugLog("Dexie Store Definition:", stores);
db.version(dbStore.version).stores(stores);
// Store the database in the Map (overwriting if it already exists)
databases.set(dbName, db);
db.open().catch(error => {
console.error(`Failed to open IndexedDB for "${dbName}":`, error);
});
}
/**
* Creates multiple databases based on an array of dbStores.
* @param {Array.<{ name: string, storeSchemas: StoreSchema[] }>} dbStores - List of database configurations.
*/
export function createDatabases(dbStores) {
dbStores.forEach(dbStore => createDb(dbStore.name, dbStore.storeSchemas));
}
export async function countTable(dbName, storeName) {
const table = await getTable(dbName, storeName);
return await table.count();
}
/**
* Closes all open databases.
*/
export function closeAll() {
databases.forEach((entry, dbName) => {
entry.db.close();
entry.isOpen = false;
debugLog(`Database ${dbName} closed.`);
});
}
/**
* Deletes a specific database.
*/
export async function deleteDb(dbName) {
if (!dbName || typeof dbName !== "string") {
console.error("deleteDb: Invalid database name.");
return;
}
try {
const db = new Dexie(dbName);
try {
await db.open();
if (db.isOpen()) {
db.close();
}
} catch (openErr) {
console.warn(`deleteDb: Couldn't open DB '${dbName}' before deletion. Proceeding anyway.`, openErr);
// Still proceed � might be locked or unopened in current context
}
await Dexie.delete(dbName);
debugLog(`Database '${dbName}' deleted.`);
} catch (deleteErr) {
console.error(`deleteDb: Failed to delete DB '${dbName}'`, deleteErr);
}
}
export async function doesDbExist(dbName) {
if (!dbName || typeof dbName !== "string") {
console.error("doesDbExist: Invalid database name.");
return false;
}
// Fast path: Chromium
if (isChromium()) {
try {
const dbs = await indexedDB.databases();
return dbs.some(db => db.name === dbName);
} catch (err) {
console.warn("doesDbExist (Chromium): Failed to list databases. Falling back.", err);
// Fall through to bulletproof fallback
}
}
// Bulletproof fallback (works in all browsers)
return new Promise((resolve) => {
let resolved = false;
const request = indexedDB.open(dbName);
request.onupgradeneeded = function () {
request.transaction.abort(); // Prevent creating the DB
if (!resolved) {
resolved = true;
resolve(false);
}
};
request.onsuccess = function () {
request.result.close();
if (!resolved) {
resolved = true;
resolve(true);
}
};
request.onerror = function (event) {
const err = event.target.error;
if (!resolved) {
resolved = true;
if (err?.name === "NotFoundError") {
resolve(false);
} else {
console.warn("doesDbExist: Unexpected error during fallback check", err);
resolve(false);
}
}
};
// Just in case nothing fires (paranoia safety)
setTimeout(() => {
if (!resolved) {
resolved = true;
resolve(false);
}
}, 1000);
});
}
function isChromium() {
try {
// Modern detection via userAgentData
if (navigator.userAgentData?.brands?.some(b => b.brand.includes("Chromium"))) {
return true;
}
// Legacy fallback detection
return /Chrome/.test(navigator.userAgent) &&
!!window.chrome &&
typeof indexedDB.databases === "function";
} catch (err) {
console.warn("isChromium: Detection failed due to unexpected error.", err);
return false;
}
}
/**
* Deletes all databases.
*/
export async function deleteAllDatabases() {
for (const dbName of databases.keys()) {
await deleteDb(dbName);
}
debugLog("All databases deleted.");
}
const keyCache = new Map(); // Caches key structures for each (db, storeName) combination
/**
* Retrieves the primary key structure for a given table.
* Caches the key structure to avoid redundant lookups.
*/
async function getPrimaryKey(dbName, storeName) {
const cacheKey = `${dbName}.${storeName}`;
if (keyCache.has(cacheKey)) {
return keyCache.get(cacheKey);
}
const table = await getTable(dbName, storeName);
const primaryKey = table.schema.primKey; // Retrieve the primary key metadata
let keyStructure;
if (Array.isArray(primaryKey.keyPath)) {
keyStructure = { isCompound: true, keys: primaryKey.keyPath };
} else {
keyStructure = { isCompound: false, keys: [primaryKey.keyPath] };
}
keyCache.set(cacheKey, keyStructure);
return keyStructure;
}
/**
* Formats keys correctly based on the table's primary key structure.
*/
async function formatKey(dbName, storeName, keyData) {
const keyInfo = await getPrimaryKey(dbName, storeName);
if (!keyInfo.isCompound) {
return keyData[keyInfo.keys[0]]; // Extract the single primary key
}
return keyInfo.keys.map(pk => keyData[pk]); // Extract multiple keys for compound key
}
/**
* Adds a single item, dynamically determining primary key structure.
*/
export async function addItem(item) {
const table = await getTable(item.dbName, item.storeName);
const key = await formatKey(item.dbName, item.storeName, item.record);
return await table.add({
...item.record,
id: key
});
}
/**
* Bulk adds multiple items.
*/
export async function bulkAddItem(dbName, storeName, items) {
const table = await getTable(dbName, storeName);
const formattedItems = await Promise.all(items.map(async item => ({
...item,
id: await formatKey(dbName, storeName, item)
})));
return await table.bulkAdd(formattedItems);
}
/**
* Inserts or updates a single item.
*/
export async function putItem(item) {
const table = await getTable(item.dbName, item.storeName);
const key = await formatKey(item.dbName, item.storeName, item.record);
return await table.put({
...item.record,
id: key
});
}
// Bulk put function for Dexie.js
export async function bulkPutItems(items) {
if (!items.length) return;
const { dbName, storeName } = items[0];
const table = await getTable(dbName, storeName);
const formattedItems = await Promise.all(items.map(async item => {
const key = await formatKey(item.dbName, item.storeName, item.record);
return {
...item.record,
id: key
};
}));
return await table.bulkPut(formattedItems);
}
/**
* Updates an item using the correct primary key format.
*/
export async function updateItem(item) {
const table = await getTable(item.dbName, item.storeName);
const key = await formatKey(item.dbName, item.storeName, item.record);
return await table.update(key, item.record);
}
/**
* Bulk updates items, ensuring keys are properly formatted.
*/
export async function bulkUpdateItem(items) {
const table = await getTable(items[0].dbName, items[0].storeName);
try {
const formattedItems = await Promise.all(items.map(async item => ({
...item.record,
id: await formatKey(item.dbName, item.storeName, item.record)
})));
await table.bulkPut(formattedItems);
return items.length;
} catch (e) {
console.error(e);
throw new Error('Some items could not be updated');
}
}
async function getKeyArrayForDelete(dbName, storeName, keyData) {
const keyInfo = await getPrimaryKey(dbName, storeName);
if (!keyInfo.isCompound) {
return keyData.find(k => k.JsName === keyInfo.keys[0])?.Value;
}
return keyInfo.keys.map(pk => {
const part = keyData.find(k => k.JsName === pk);
if (!part) throw new Error(`Missing key part: ${pk}`);
return part.Value;
});
}
/**
* Deletes multiple items, supporting single and compound keys.
*/
export async function bulkDelete(dbName, storeName, items) {
const table = await getTable(dbName, storeName);
try {
const formattedKeys = await Promise.all(
items.map(item => getKeyArrayForDelete(dbName, storeName, item))
);
debugLog('Keys to delete:', formattedKeys);
await table.bulkDelete(formattedKeys);
return items.length;
} catch (e) {
console.error('bulkDelete error:', e);
throw new Error('Some items could not be deleted');
}
}
/**
* Deletes a single item.
*/
export async function deleteItem(item) {
const table = await getTable(item.dbName, item.storeName);
const key = await formatKey(item.dbName, item.storeName, item.record);
await table.delete(key);
}
export async function clear(dbName, storeName) {
const table = await getTable(dbName, storeName);
await table.clear();
}
export async function findItem(dbName, storeName, keyValue) {
const table = await getTable(dbName, storeName);
return await table.get(keyValue);
}
export async function toArray(dbName, storeName) {
const table = await getTable(dbName, storeName);
return await table.toArray();
}
export function getStorageEstimate() {
return navigator.storage.estimate();
}
async function getTable(dbName, storeName) {
let db = await openDb(dbName);
let table = db.table(storeName);
return table;
}
/**
* Wrapper method for magicQueryAsync.
* Automatically retrieves the Dexie instance from your manager using dbName.
*/
export async function wrapperMagicQueryAsync(dbName, storeName, nestedOrFilter, queryAdditions, forceCursor = false) {
const db = await openDb(dbName); // Get the Dexie instance from your manager
let table = db.table(storeName);
return await magicQueryAsync(db, table, nestedOrFilter, queryAdditions, forceCursor);
}
/**
* Wrapper method for magicQueryYield.
* Automatically retrieves the Dexie instance from your manager using dbName.
*/
export async function* wrapperMagicQueryYield(dbName, storeName, nestedOrFilter, queryAdditions = [], forceCursor = false) {
const db = await openDb(dbName); // Get the Dexie instance from your manager
let table = db.table(storeName);
yield* magicQueryYield(db, table, nestedOrFilter, queryAdditions, forceCursor);
}