@wxn0brp/db-core 0.12.2 → 0.12.4-alpha.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.
@@ -1,7 +1,9 @@
1
1
  import { ActionsBaseInterface } from "../types/action.js";
2
2
  import { DataInternal } from "../types/data.js";
3
+ import { Id } from "../types/Id.js";
3
4
  import { AdapterOpts } from "../types/options.js";
4
5
  import { VQueryT } from "../types/query.js";
6
+ import { TransactionHandle } from "../types/transaction.js";
5
7
  export declare abstract class ActionsBase implements ActionsBaseInterface {
6
8
  _inited: boolean;
7
9
  adapterOpts: AdapterOpts;
@@ -20,6 +22,9 @@ export declare abstract class ActionsBase implements ActionsBaseInterface {
20
22
  abstract updateOne(config: VQueryT.Update): Promise<DataInternal | null>;
21
23
  abstract remove(config: VQueryT.Remove): Promise<DataInternal[]>;
22
24
  abstract removeOne(config: VQueryT.Remove): Promise<DataInternal | null>;
25
+ beginTransaction(id: Id): Promise<TransactionHandle>;
26
+ commitTransaction(handle: TransactionHandle): Promise<void>;
27
+ rollbackTransaction(handle: TransactionHandle): Promise<void>;
23
28
  updateOneOrAdd(config: VQueryT.UpdateOneOrAdd): Promise<VQueryT.UpdateOneOrAddResult<DataInternal>>;
24
29
  toggleOne(config: VQueryT.ToggleOne): Promise<VQueryT.ToggleOneResult<DataInternal>>;
25
30
  }
@@ -10,6 +10,15 @@ export class ActionsBase {
10
10
  version = "ActionsBase-core-" + version;
11
11
  async init(...args) { }
12
12
  async close(...args) { }
13
+ async beginTransaction(id) {
14
+ throw new Error("Transactions are not supported for ActionsBase");
15
+ }
16
+ async commitTransaction(handle) {
17
+ throw new Error("Transactions are not supported for ActionsBase");
18
+ }
19
+ async rollbackTransaction(handle) {
20
+ throw new Error("Transactions are not supported for ActionsBase");
21
+ }
13
22
  async updateOneOrAdd(config) {
14
23
  const res = await this.updateOne(config);
15
24
  if (res)
@@ -1,5 +1,6 @@
1
1
  import { ActionsBase } from "../base/actions.js";
2
2
  import { VQueryT } from "../types/query.js";
3
+ import { TransactionHandle } from "../types/transaction.js";
3
4
  export declare class MultiBackend extends ActionsBase {
4
5
  backends: ActionsBase[];
5
6
  primaryBackend: ActionsBase;
@@ -17,4 +18,7 @@ export declare class MultiBackend extends ActionsBase {
17
18
  issetCollection(collection: string): Promise<boolean>;
18
19
  removeCollection(collection: string): Promise<boolean>;
19
20
  getCollections(): Promise<string[]>;
21
+ beginTransaction(): Promise<TransactionHandle>;
22
+ commitTransaction(): Promise<void>;
23
+ rollbackTransaction(): Promise<void>;
20
24
  }
@@ -100,4 +100,13 @@ export class MultiBackend extends ActionsBase {
100
100
  });
101
101
  return Array.from(uniqueCollections);
102
102
  }
103
+ async beginTransaction() {
104
+ throw new Error("Transactions are not supported for MultiBackend");
105
+ }
106
+ async commitTransaction() {
107
+ throw new Error("Transactions are not supported for MultiBackend");
108
+ }
109
+ async rollbackTransaction() {
110
+ throw new Error("Transactions are not supported for MultiBackend");
111
+ }
103
112
  }
@@ -1,5 +1,6 @@
1
1
  import { ActionsBase } from "../base/actions.js";
2
2
  import { VQueryT, VQuery } from "../types/query.js";
3
+ import { TransactionHandle } from "../types/transaction.js";
3
4
  export type MatchRule = string | RegExp | ((config: VQuery) => boolean);
4
5
  export interface RouteEntry {
5
6
  match: MatchRule;
@@ -25,4 +26,7 @@ export declare class RoutedStorage extends ActionsBase {
25
26
  issetCollection(collection: string): Promise<boolean>;
26
27
  removeCollection(collection: string): Promise<boolean>;
27
28
  getCollections(): Promise<string[]>;
29
+ beginTransaction(): Promise<TransactionHandle>;
30
+ commitTransaction(): Promise<void>;
31
+ rollbackTransaction(): Promise<void>;
28
32
  }
@@ -96,4 +96,13 @@ export class RoutedStorage extends ActionsBase {
96
96
  const merged = new Set(all.flat());
97
97
  return Array.from(merged);
98
98
  }
99
+ async beginTransaction() {
100
+ throw new Error("Transactions are not supported for RoutedStorage");
101
+ }
102
+ async commitTransaction() {
103
+ throw new Error("Transactions are not supported for RoutedStorage");
104
+ }
105
+ async rollbackTransaction() {
106
+ throw new Error("Transactions are not supported for RoutedStorage");
107
+ }
99
108
  }
@@ -6,6 +6,7 @@ import { Data } from "../types/data.js";
6
6
  import { DbOpts } from "../types/options.js";
7
7
  import { ValtheraPlugin } from "../types/plugin.js";
8
8
  import { VQuery, VQueryT } from "../types/query.js";
9
+ import { TransactionHandle } from "../types/transaction.js";
9
10
  import { ValtheraCompatible } from "../types/valthera.js";
10
11
  /**
11
12
  * Represents a database management class for performing CRUD operations.
@@ -23,6 +24,7 @@ export declare class ValtheraClass implements ValtheraCompatible {
23
24
  version: string;
24
25
  _plugins: ValtheraPlugin[];
25
26
  _collections: Map<string, Collection<any>>;
27
+ _activeTx: TransactionHandle | null;
26
28
  plugin(p: ValtheraPlugin): () => void;
27
29
  constructor(options: DbOpts);
28
30
  init(...args: any[]): Promise<any>;
@@ -84,4 +86,17 @@ export declare class ValtheraClass implements ValtheraCompatible {
84
86
  * Removes a database collection from the database.
85
87
  */
86
88
  removeCollection(collection: string): Promise<boolean>;
89
+ /**
90
+ * @experimental
91
+ *
92
+ * Executes operations within a transaction. Automatically rolls back on error.
93
+ *
94
+ * This feature is highly experimental and may change or be removed at any time.
95
+ *
96
+ * - Requires `executorAware: false` in ValtheraClass options.
97
+ * - Transaction support depends on the executor implementation.
98
+ * - Nested transactions are not supported.
99
+ * - Transactions lock the whole database for the duration of the transaction.
100
+ */
101
+ transaction<T>(fn: (handle: TransactionHandle) => Promise<T>): Promise<T>;
87
102
  }
@@ -1,6 +1,7 @@
1
1
  import { VEE } from "@wxn0brp/event-emitter";
2
2
  import { Collection } from "../helpers/collection.js";
3
3
  import { SmartExecutor } from "../helpers/executor.js";
4
+ import { genId } from "../helpers/gen.js";
4
5
  import { version } from "../version.js";
5
6
  /**
6
7
  * Represents a database management class for performing CRUD operations.
@@ -14,6 +15,7 @@ export class ValtheraClass {
14
15
  version = version;
15
16
  _plugins = [];
16
17
  _collections = new Map();
18
+ _activeTx = null;
17
19
  plugin(p) {
18
20
  p.init?.(this);
19
21
  this._plugins.push(p);
@@ -34,6 +36,7 @@ export class ValtheraClass {
34
36
  this.adapter.adapterOpts = options.adapterOpts;
35
37
  }
36
38
  }
39
+ options.executorAware ??= true;
37
40
  }
38
41
  async init(...args) {
39
42
  if (this.adapter?._inited)
@@ -46,6 +49,7 @@ export class ValtheraClass {
46
49
  self.adapter = await self.options.adapter();
47
50
  // if the executor is not set, and the action wants a smart executor
48
51
  if (!self.options.executor &&
52
+ self.options.executorAware &&
49
53
  self.adapter.smartExecutor &&
50
54
  self.executor instanceof SmartExecutor)
51
55
  self.executor.aware = true;
@@ -72,6 +76,10 @@ export class ValtheraClass {
72
76
  }
73
77
  async execute(name, query) {
74
78
  await this.init();
79
+ const isTransaction = this._activeTx && typeof query !== "string";
80
+ if (isTransaction) {
81
+ query.transaction = this._activeTx;
82
+ }
75
83
  const plugins = this._plugins;
76
84
  const self = this;
77
85
  let idx = 0;
@@ -81,6 +89,8 @@ export class ValtheraClass {
81
89
  next: async () => {
82
90
  if (idx < plugins.length)
83
91
  return plugins[idx++].execute(ctx);
92
+ if (isTransaction)
93
+ return self.adapter[name](query);
84
94
  return self.executor.addOp(self.adapter[ctx.op].bind(self.adapter), ctx.query, typeof ctx.query === "string" ? ctx.query : ctx.query.collection);
85
95
  },
86
96
  };
@@ -202,4 +212,52 @@ export class ValtheraClass {
202
212
  this._collections.delete(collection);
203
213
  return this.execute("removeCollection", collection);
204
214
  }
215
+ /**
216
+ * @experimental
217
+ *
218
+ * Executes operations within a transaction. Automatically rolls back on error.
219
+ *
220
+ * This feature is highly experimental and may change or be removed at any time.
221
+ *
222
+ * - Requires `executorAware: false` in ValtheraClass options.
223
+ * - Transaction support depends on the executor implementation.
224
+ * - Nested transactions are not supported.
225
+ * - Transactions lock the whole database for the duration of the transaction.
226
+ */
227
+ async transaction(fn) {
228
+ await this.init();
229
+ if ("aware" in this.executor && this.executor.aware) {
230
+ throw new Error("Transactions are not supported when using a smart executor. " +
231
+ "Please use options.executorAware = false when creating the Valthera instance.");
232
+ }
233
+ if (this._activeTx)
234
+ throw new Error("Nested transactions are not supported");
235
+ const self = this;
236
+ return this.executor.addOp(async () => {
237
+ if (self._activeTx)
238
+ throw new Error("Nested transactions are not supported");
239
+ const handle = await self.adapter.beginTransaction(genId());
240
+ self._activeTx = handle;
241
+ try {
242
+ const result = await fn(handle);
243
+ await self.adapter.commitTransaction(handle);
244
+ return result;
245
+ }
246
+ catch (err) {
247
+ try {
248
+ await self.adapter.rollbackTransaction(handle);
249
+ }
250
+ catch (rollbackErr) {
251
+ throw new AggregateError([
252
+ err,
253
+ rollbackErr,
254
+ ], "Transaction failed and rollback failed");
255
+ }
256
+ throw err;
257
+ }
258
+ finally {
259
+ self._activeTx = null;
260
+ }
261
+ });
262
+ }
205
263
  }
@@ -67,6 +67,8 @@ export async function processRelations(dbs, cfg, data, parentList = null) {
67
67
  : [
68
68
  data,
69
69
  ];
70
+ if (targets.length === 0)
71
+ return;
70
72
  for (const key in cfg) {
71
73
  if (!Object.hasOwn(cfg, key))
72
74
  continue;
@@ -158,29 +160,83 @@ export async function processRelations(dbs, cfg, data, parentList = null) {
158
160
  else if (type === "nm") {
159
161
  if (!through || !through.table || !through.pk || !through.fk)
160
162
  throw new Error(`Relation type "nm" requires a defined "through" in "${key}"`);
161
- for (const item of targets) {
162
- const pivotDb = dbs[through.db || dbKey];
163
- const pivots = await pivotDb.find({
164
- collection: through.table,
165
- search: {
166
- [through.pk]: item[pk],
163
+ const allSourceIds = targets.map(i => i[pk]);
164
+ const pivotDb = dbs[through.db || dbKey];
165
+ const allPivots = await pivotDb.find({
166
+ collection: through.table,
167
+ search: {
168
+ $in: {
169
+ [through.pk]: allSourceIds,
167
170
  },
168
- });
169
- const ids = pivots.map(p => p[through.fk]);
170
- const related = await db.find({
171
+ },
172
+ });
173
+ const pivotMap = new Map();
174
+ for (const p of allPivots) {
175
+ const srcId = p[through.pk];
176
+ const arr = pivotMap.get(srcId) || [];
177
+ arr.push(p[through.fk]);
178
+ pivotMap.set(srcId, arr);
179
+ }
180
+ const allTargetIds = [
181
+ ...new Set(allPivots.map(p => p[through.fk])),
182
+ ];
183
+ const allRelated = await db.find({
184
+ collection,
185
+ search: {
186
+ $in: {
187
+ [fk]: allTargetIds,
188
+ },
189
+ },
190
+ findOpts: {
191
+ select,
192
+ },
193
+ });
194
+ const targetMap = new Map(allRelated.map(r => [
195
+ r[fk],
196
+ r,
197
+ ]));
198
+ for (const item of targets) {
199
+ const targetIds = pivotMap.get(item[pk]) || [];
200
+ const related = targetIds.map(id => targetMap.get(id)).filter(Boolean);
201
+ item[as] = related;
202
+ if (rel.relations && related.length > 0) {
203
+ await Promise.all(related.map(row => processRelations(dbs, rel.relations, row)));
204
+ }
205
+ }
206
+ }
207
+ else if (type === "n1") {
208
+ const allFkIds = [
209
+ ...new Set(targets.flatMap(i => i[pk] || [])),
210
+ ];
211
+ if (allFkIds.length === 0) {
212
+ for (const item of targets)
213
+ item[as] = null;
214
+ }
215
+ else {
216
+ const [selectSafe, deleteSelect] = autoSelect(rel, fk);
217
+ const results = await db.find({
171
218
  collection,
172
219
  search: {
173
220
  $in: {
174
- [fk]: ids,
221
+ [fk]: allFkIds,
175
222
  },
176
223
  },
177
224
  findOpts: {
178
- select,
225
+ select: selectSafe,
179
226
  },
180
227
  });
181
- item[as] = related;
182
- if (rel.relations) {
183
- await Promise.all(related.map(row => processRelations(dbs, rel.relations, row)));
228
+ const map = new Map(results.map(row => [
229
+ row[fk],
230
+ row,
231
+ ]));
232
+ for (const item of targets) {
233
+ const fks = item[pk] || [];
234
+ const result = map.get(fks[0]) || null;
235
+ if (result && rel.relations)
236
+ await processRelations(dbs, rel.relations, result);
237
+ if (deleteSelect && result)
238
+ delete result[fk];
239
+ item[as] = result;
184
240
  }
185
241
  }
186
242
  }
@@ -1,6 +1,8 @@
1
1
  import { DataInternal } from "./data.js";
2
+ import { Id } from "./Id.js";
2
3
  import { AdapterOpts } from "./options.js";
3
4
  import { VQueryT } from "./query.js";
5
+ import { TransactionHandle } from "./transaction.js";
4
6
  export interface ActionsBaseInterface {
5
7
  _inited: boolean;
6
8
  adapterOpts: AdapterOpts;
@@ -20,4 +22,7 @@ export interface ActionsBaseInterface {
20
22
  removeOne(query: VQueryT.Remove): Promise<DataInternal | null>;
21
23
  updateOneOrAdd(query: VQueryT.UpdateOneOrAdd): Promise<VQueryT.UpdateOneOrAddResult<DataInternal>>;
22
24
  toggleOne(query: VQueryT.ToggleOne): Promise<VQueryT.ToggleOneResult<DataInternal>>;
25
+ beginTransaction(id: Id): Promise<TransactionHandle>;
26
+ commitTransaction(handle: TransactionHandle): Promise<void>;
27
+ rollbackTransaction(handle: TransactionHandle): Promise<void>;
23
28
  }
@@ -5,6 +5,7 @@ export type AdapterValue = ActionsBase | (() => Promise<ActionsBase>);
5
5
  export interface DbOpts {
6
6
  adapter: AdapterValue;
7
7
  executor?: Executor;
8
+ executorAware?: boolean;
8
9
  adapterOpts?: AdapterOpts;
9
10
  }
10
11
  export interface AdapterOpts {
@@ -1,6 +1,7 @@
1
1
  import { Arg, Search, Updater } from "./arg.js";
2
2
  import { Data } from "./data.js";
3
3
  import { DbFindOpts, FindOpts } from "./options.js";
4
+ import { TransactionHandle } from "./transaction.js";
4
5
  import { VContext } from "./types.js";
5
6
  /**
6
7
  * To extend via adapters
@@ -25,6 +26,7 @@ export interface VQuery<T = Data, AllowFn extends boolean = true> {
25
26
  add_arg?: Arg<T>;
26
27
  updater?: Updater<T, AllowFn>;
27
28
  control?: VQuery_Control;
29
+ transaction?: TransactionHandle;
28
30
  }
29
31
  export declare namespace VQueryT {
30
32
  type QueryBase<T = Data> = {
@@ -19,7 +19,7 @@ export declare namespace RelationTypes {
19
19
  as?: string;
20
20
  select?: string[];
21
21
  dbFindOpts?: DbFindOpts;
22
- type?: "1" | "11" | "1n" | "nm";
22
+ type?: "1" | "11" | "1n" | "nm" | "n1";
23
23
  relations?: Relation;
24
24
  through?: {
25
25
  table: string;
@@ -0,0 +1,4 @@
1
+ export interface TransactionHandle {
2
+ id: string;
3
+ _adapterData?: unknown;
4
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "0.12.2";
1
+ export declare const version = "0.12.4-alpha.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const version = "0.12.2";
1
+ export const version = "0.12.4-alpha.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxn0brp/db-core",
3
- "version": "0.12.2",
3
+ "version": "0.12.4-alpha.0",
4
4
  "types": "dist/index.d.ts",
5
5
  "main": "dist/index.js",
6
6
  "author": "wxn0brP",
@@ -17,7 +17,6 @@
17
17
  },
18
18
  "devDependencies": {
19
19
  "@types/bun": "*",
20
- "@types/node": "*",
21
20
  "fast-check": "^4",
22
21
  "tsc-alias": "^1",
23
22
  "typescript": "^7"