Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 3x 3x 3x 3x 15x 3x 15x 15x 15x 15x 15x 15x 7x 7x 2x 3x 3x 3x 3x 7x 5x 5x 5x 5x 5x 5x 5x 2x 2x 7x 7x 7x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 4x 1x 1x 1x 3x 4x 3x 3x 8x 1x 3x 4x 4x 1x 1x 3x 3x 3x 3x | /**
* In-Memory Database Adapter for Coherent.js
*
* @fileoverview In-memory adapter for development and testing purposes.
* Provides a simple, non-persistent storage solution.
*/
/**
* In-Memory Database Adapter
*
* @class MemoryAdapter
* @description Provides in-memory database operations with a simple key-value store.
*/
export class MemoryAdapter {
constructor() {
this.stores = new Map();
}
/**
* Create a new in-memory store
*
* @param {Object} config - Store configuration
* @returns {Promise<Object>} Store instance
*/
async createPool(config) {
const collections = new Map();
const schemas = new Map();
const store = {
config,
stats: {
created: Date.now(),
operations: 0,
collections: 0,
queries: 0
},
/**
* Get a collection by name
* @private
*/
_getCollection(name) {
if (!collections.has(name)) {
collections.set(name, new Map());
}
return collections.get(name);
},
/**
* Get schema for a collection
* @private
*/
_getSchema(collectionName) {
return schemas.get(collectionName) || {};
},
/**
* Execute a query
* @param {string} operation - Operation type
* @param {Object} params - Query parameters
* @returns {Promise<*>} Query result
*/
async query(operation, params = {}) {
this.stats.operations++;
this.stats.queries++;
const { table, where = {}, data, limit, offset, orderBy } = params;
const collection = this._getCollection(table);
switch (operation.toUpperCase()) {
case 'FIND': {
let results = Array.from(collection.values());
// Apply WHERE conditions
if (Object.keys(where).length > 0) {
results = results.filter(item =>
Object.entries(where).every(([key, value]) => {
Iif (value === undefined) return true;
Iif (value === null) return item[key] === null;
return JSON.stringify(item[key]) === JSON.stringify(value);
})
);
}
// Apply ORDER BY
if (orderBy) {
let field, direction;
Iif (Array.isArray(orderBy)) {
[field, direction = 'ASC'] = orderBy;
} else Iif (typeof orderBy === 'object') {
const entries = Object.entries(orderBy);
if (entries.length > 0) {
[field, direction] = entries[0];
}
} else {
field = orderBy;
direction = 'ASC';
}
Eif (field) {
const dir = direction.toLowerCase();
results.sort((a, b) => {
Iif (a[field] < b[field]) return dir === 'asc' ? -1 : 1;
Eif (a[field] > b[field]) return dir === 'asc' ? 1 : -1;
return 0;
});
}
}
// Apply OFFSET and LIMIT
Iif (offset) results = results.slice(offset);
Iif (limit) results = results.slice(0, limit);
return results;
}
case 'INSERT': {
Iif (!data) throw new Error('No data provided for insert');
const id = data.id || Date.now().toString(36) + Math.random().toString(36).substr(2);
const record = { ...data, id };
collection.set(id, record);
this.stats.collections = collections.size;
return { id };
}
case 'UPDATE': {
Iif (!data) throw new Error('No data provided for update');
const records = await this.query('FIND', { table, where });
const updated = [];
for (const record of records) {
const updatedRecord = { ...record, ...data };
collection.set(record.id, updatedRecord);
updated.push(updatedRecord);
}
return { affectedRows: updated.length };
}
case 'DELETE': {
const records = await this.query('FIND', { table, where });
const deleted = [];
for (const record of records) {
Eif (collection.delete(record.id)) {
deleted.push(record);
}
}
return { affectedRows: deleted.length };
}
case 'COUNT': {
const results = await this.query('FIND', { table, where });
return { count: results.length };
}
case 'CREATE_COLLECTION': {
const { name, schema } = params;
schemas.set(name, schema || {});
return { success: true };
}
case 'SET_SCHEMA': {
const { model, schema } = params;
schemas.set(model, schema);
return { success: true };
}
default:
throw new Error(`Unsupported operation: ${operation}`);
}
},
/**
* Get store statistics
* @returns {Object}
*/
getStats() {
return {
...this.stats,
uptime: Date.now() - this.stats.created,
collections: collections.size,
operations: this.stats.operations,
queries: this.stats.queries
};
},
/**
* Copy of every collection and schema, for rolling back a transaction
* @private
*/
_snapshot() {
const copy = new Map();
for (const [name, records] of collections) {
copy.set(name, new Map([...records].map(([id, record]) => [id, globalThis.structuredClone(record)])));
}
return { collections: copy, schemas: new Map(schemas) };
},
/**
* Restore a snapshot taken with _snapshot()
* @private
*/
_restore(snapshot) {
collections.clear();
for (const [name, records] of snapshot.collections) {
collections.set(name, records);
}
schemas.clear();
for (const [name, schema] of snapshot.schemas) {
schemas.set(name, schema);
}
},
/**
* Run a callback in a transaction: changes are undone if it throws.
*
* The store is shared, so changes made outside the callback while it runs are
* undone as well.
*
* @param {Function} callback - Transaction callback, receives `{ query }`
* @returns {Promise<*>} Result of the callback
*/
async transaction(callback) {
const snapshot = this._snapshot();
try {
return await callback({
query: (operation, params) => this.query(operation, params)
});
} catch (_error) {
this._restore(snapshot);
throw _error;
}
}
};
this.stores.set(config.name || 'default', store);
return store;
}
/**
* Get a store by name
*
* @param {string} name - Store name
* @returns {Object|undefined} Store instance or undefined if not found
*/
getStore(name = 'default') {
return this.stores.get(name);
}
/**
* Close all stores and clean up
*
* @returns {Promise<void>}
*/
async close() {
this.stores.clear();
}
/**
* Close the connection pool
* @param {Object} pool - The connection pool to close
* @returns {Promise<void>}
*/
async closePool(pool) {
// For in-memory adapter, we don't need to do anything special to close the pool
// Just clear any references to allow garbage collection
if (pool) {
// Clear any collections or other resources if needed
if (pool.collections) {
pool.collections.clear();
}
if (pool.schemas) {
pool.schemas.clear();
}
}
return Promise.resolve();
}
/**
* Start a transaction (the DatabaseManager contract), or run a callback in one.
*
* `transaction(store)` returns `{ query, commit, rollback, isCommitted, isRolledBack }`;
* rollback() restores the store as it was when the transaction started.
* `transaction(callback)` runs the callback on the default store and rolls back if it throws.
*
* @param {Object|Function} [storeOrCallback] - Store from createPool(), or a callback
* @returns {Promise<Object|*>} Transaction, or the callback's result
*/
async transaction(storeOrCallback) {
if (typeof storeOrCallback === 'function') {
const store = this.getStore();
Iif (!store) {
throw new Error('MemoryAdapter has no store: call createPool() first');
}
return store.transaction(storeOrCallback);
}
const store = storeOrCallback || this.getStore();
Iif (!store || typeof store._snapshot !== 'function') {
throw new Error('MemoryAdapter.transaction() needs a store created by createPool()');
}
const snapshot = store._snapshot();
const assertActive = () => {
if (tx.isCommitted || tx.isRolledBack) {
throw new Error('Transaction already completed');
}
};
const tx = {
isCommitted: false,
isRolledBack: false,
async query(operation, params) {
assertActive();
return store.query(operation, params);
},
async commit() {
assertActive();
tx.isCommitted = true;
},
async rollback() {
assertActive();
store._restore(snapshot);
tx.isRolledBack = true;
}
};
return tx;
}
}
|