@rsdk/db 2.5.1

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.
Files changed (149) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/README.md +3 -0
  3. package/db/dist/context.base.d.ts +30 -0
  4. package/db/dist/context.base.js +52 -0
  5. package/db/dist/context.base.js.map +1 -0
  6. package/db/dist/context.storage.d.ts +22 -0
  7. package/db/dist/context.storage.js +32 -0
  8. package/db/dist/context.storage.js.map +1 -0
  9. package/db/dist/exceptions.d.ts +10 -0
  10. package/db/dist/exceptions.js +25 -0
  11. package/db/dist/exceptions.js.map +1 -0
  12. package/db/dist/index.d.ts +6 -0
  13. package/db/dist/index.js +16 -0
  14. package/db/dist/index.js.map +1 -0
  15. package/db/dist/propagation.enum.d.ts +30 -0
  16. package/db/dist/propagation.enum.js +35 -0
  17. package/db/dist/propagation.enum.js.map +1 -0
  18. package/db/dist/transactional.runner.d.ts +29 -0
  19. package/db/dist/transactional.runner.js +119 -0
  20. package/db/dist/transactional.runner.js.map +1 -0
  21. package/db/dist/types.d.ts +10 -0
  22. package/db/dist/types.js +3 -0
  23. package/db/dist/types.js.map +1 -0
  24. package/db.knex/dist/index.d.ts +9 -0
  25. package/db.knex/dist/index.js +15 -0
  26. package/db.knex/dist/index.js.map +1 -0
  27. package/db.knex/dist/inject-knex.decorator.d.ts +2 -0
  28. package/db.knex/dist/inject-knex.decorator.js +8 -0
  29. package/db.knex/dist/inject-knex.decorator.js.map +1 -0
  30. package/db.knex/dist/internal/context.d.ts +78 -0
  31. package/db.knex/dist/internal/context.js +233 -0
  32. package/db.knex/dist/internal/context.js.map +1 -0
  33. package/db.knex/dist/internal/exceptions.d.ts +65 -0
  34. package/db.knex/dist/internal/exceptions.js +94 -0
  35. package/db.knex/dist/internal/exceptions.js.map +1 -0
  36. package/db.knex/dist/internal/initializer.d.ts +9 -0
  37. package/db.knex/dist/internal/initializer.js +48 -0
  38. package/db.knex/dist/internal/initializer.js.map +1 -0
  39. package/db.knex/dist/internal/strategy.d.ts +18 -0
  40. package/db.knex/dist/internal/strategy.js +75 -0
  41. package/db.knex/dist/internal/strategy.js.map +1 -0
  42. package/db.knex/dist/internal/test.e2e/strategy.test.d.ts +1 -0
  43. package/db.knex/dist/internal/test.e2e/strategy.test.js +762 -0
  44. package/db.knex/dist/internal/test.e2e/strategy.test.js.map +1 -0
  45. package/db.knex/dist/internal/test.e2e/utils.d.ts +17 -0
  46. package/db.knex/dist/internal/test.e2e/utils.js +21 -0
  47. package/db.knex/dist/internal/test.e2e/utils.js.map +1 -0
  48. package/db.knex/dist/knex.module.d.ts +5 -0
  49. package/db.knex/dist/knex.module.js +34 -0
  50. package/db.knex/dist/knex.module.js.map +1 -0
  51. package/db.knex/dist/knex.plugin.d.ts +10 -0
  52. package/db.knex/dist/knex.plugin.js +20 -0
  53. package/db.knex/dist/knex.plugin.js.map +1 -0
  54. package/db.knex/dist/providers/index.d.ts +4 -0
  55. package/db.knex/dist/providers/index.js +21 -0
  56. package/db.knex/dist/providers/index.js.map +1 -0
  57. package/db.knex/dist/providers/knex-logger.adapter.d.ts +10 -0
  58. package/db.knex/dist/providers/knex-logger.adapter.js +45 -0
  59. package/db.knex/dist/providers/knex-logger.adapter.js.map +1 -0
  60. package/db.knex/dist/providers/knex.config.d.ts +10 -0
  61. package/db.knex/dist/providers/knex.config.js +76 -0
  62. package/db.knex/dist/providers/knex.config.js.map +1 -0
  63. package/db.knex/dist/providers/knex.factory.d.ts +13 -0
  64. package/db.knex/dist/providers/knex.factory.js +96 -0
  65. package/db.knex/dist/providers/knex.factory.js.map +1 -0
  66. package/db.knex/dist/providers/knex.indicator.d.ts +8 -0
  67. package/db.knex/dist/providers/knex.indicator.js +41 -0
  68. package/db.knex/dist/providers/knex.indicator.js.map +1 -0
  69. package/db.knex/dist/types.d.ts +12 -0
  70. package/db.knex/dist/types.js +20 -0
  71. package/db.knex/dist/types.js.map +1 -0
  72. package/db.typeorm/dist/data-source-extractor.d.ts +20 -0
  73. package/db.typeorm/dist/data-source-extractor.js +43 -0
  74. package/db.typeorm/dist/data-source-extractor.js.map +1 -0
  75. package/db.typeorm/dist/index.d.ts +8 -0
  76. package/db.typeorm/dist/index.js +12 -0
  77. package/db.typeorm/dist/index.js.map +1 -0
  78. package/db.typeorm/dist/internal/context.d.ts +46 -0
  79. package/db.typeorm/dist/internal/context.js +123 -0
  80. package/db.typeorm/dist/internal/context.js.map +1 -0
  81. package/db.typeorm/dist/internal/exceptions.d.ts +67 -0
  82. package/db.typeorm/dist/internal/exceptions.js +99 -0
  83. package/db.typeorm/dist/internal/exceptions.js.map +1 -0
  84. package/db.typeorm/dist/internal/initializer.d.ts +15 -0
  85. package/db.typeorm/dist/internal/initializer.js +158 -0
  86. package/db.typeorm/dist/internal/initializer.js.map +1 -0
  87. package/db.typeorm/dist/internal/strategy.d.ts +54 -0
  88. package/db.typeorm/dist/internal/strategy.js +108 -0
  89. package/db.typeorm/dist/internal/strategy.js.map +1 -0
  90. package/db.typeorm/dist/internal/test/strategy.test.e2e.d.ts +5 -0
  91. package/db.typeorm/dist/internal/test/strategy.test.e2e.js +779 -0
  92. package/db.typeorm/dist/internal/test/strategy.test.e2e.js.map +1 -0
  93. package/db.typeorm/dist/internal/test/util.d.ts +22 -0
  94. package/db.typeorm/dist/internal/test/util.js +72 -0
  95. package/db.typeorm/dist/internal/test/util.js.map +1 -0
  96. package/db.typeorm/dist/modules/migration-checker.module.d.ts +9 -0
  97. package/db.typeorm/dist/modules/migration-checker.module.js +42 -0
  98. package/db.typeorm/dist/modules/migration-checker.module.js.map +1 -0
  99. package/db.typeorm/dist/providers/index.d.ts +3 -0
  100. package/db.typeorm/dist/providers/index.js +20 -0
  101. package/db.typeorm/dist/providers/index.js.map +1 -0
  102. package/db.typeorm/dist/providers/typeorm-logger.adapter.d.ts +13 -0
  103. package/db.typeorm/dist/providers/typeorm-logger.adapter.js +61 -0
  104. package/db.typeorm/dist/providers/typeorm-logger.adapter.js.map +1 -0
  105. package/db.typeorm/dist/providers/typeorm.config.d.ts +10 -0
  106. package/db.typeorm/dist/providers/typeorm.config.js +79 -0
  107. package/db.typeorm/dist/providers/typeorm.config.js.map +1 -0
  108. package/db.typeorm/dist/providers/typeorm.healthcheck.d.ts +8 -0
  109. package/db.typeorm/dist/providers/typeorm.healthcheck.js +36 -0
  110. package/db.typeorm/dist/providers/typeorm.healthcheck.js.map +1 -0
  111. package/db.typeorm/dist/typeorm.errors-transformer.d.ts +5 -0
  112. package/db.typeorm/dist/typeorm.errors-transformer.js +32 -0
  113. package/db.typeorm/dist/typeorm.errors-transformer.js.map +1 -0
  114. package/db.typeorm/dist/typeorm.plugin.d.ts +17 -0
  115. package/db.typeorm/dist/typeorm.plugin.js +81 -0
  116. package/db.typeorm/dist/typeorm.plugin.js.map +1 -0
  117. package/db.typeorm/dist/types.d.ts +14 -0
  118. package/db.typeorm/dist/types.js +18 -0
  119. package/db.typeorm/dist/types.js.map +1 -0
  120. package/dist/context.base.d.ts +30 -0
  121. package/dist/context.base.js +52 -0
  122. package/dist/context.base.js.map +1 -0
  123. package/dist/context.storage.d.ts +22 -0
  124. package/dist/context.storage.js +32 -0
  125. package/dist/context.storage.js.map +1 -0
  126. package/dist/exceptions.d.ts +10 -0
  127. package/dist/exceptions.js +25 -0
  128. package/dist/exceptions.js.map +1 -0
  129. package/dist/index.d.ts +6 -0
  130. package/dist/index.js +16 -0
  131. package/dist/index.js.map +1 -0
  132. package/dist/propagation.enum.d.ts +30 -0
  133. package/dist/propagation.enum.js +35 -0
  134. package/dist/propagation.enum.js.map +1 -0
  135. package/dist/transactional.runner.d.ts +29 -0
  136. package/dist/transactional.runner.js +119 -0
  137. package/dist/transactional.runner.js.map +1 -0
  138. package/dist/types.d.ts +10 -0
  139. package/dist/types.js +3 -0
  140. package/dist/types.js.map +1 -0
  141. package/package.json +21 -0
  142. package/src/context.base.ts +61 -0
  143. package/src/context.storage.ts +34 -0
  144. package/src/exceptions.ts +21 -0
  145. package/src/index.ts +10 -0
  146. package/src/propagation.enum.ts +36 -0
  147. package/src/transactional.runner.ts +222 -0
  148. package/src/types.ts +37 -0
  149. package/tsconfig.json +11 -0
@@ -0,0 +1,14 @@
1
+ import type { TypeOrmModuleOptions } from '@nestjs/typeorm';
2
+ export interface TypeOrmPluginOptions {
3
+ type: NonNullable<TypeOrmModuleOptions['type']>;
4
+ entities?: (string | any)[];
5
+ overrideConfig?: Partial<Omit<TypeOrmModuleOptions, 'type'>>;
6
+ }
7
+ export declare enum IsolationLevel {
8
+ READ_UNCOMMITTED = "READ UNCOMMITTED",
9
+ READ_COMMITTED = "READ COMMITTED",
10
+ REPEATABLE_READ = "REPEATABLE READ",
11
+ SERIALIZABLE = "SERIALIZABLE"
12
+ }
13
+ export declare const isolationLevels: readonly IsolationLevel[];
14
+ export declare const DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_UNCOMMITTED;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_ISOLATION_LEVEL = exports.isolationLevels = exports.IsolationLevel = void 0;
4
+ var IsolationLevel;
5
+ (function (IsolationLevel) {
6
+ IsolationLevel["READ_UNCOMMITTED"] = "READ UNCOMMITTED";
7
+ IsolationLevel["READ_COMMITTED"] = "READ COMMITTED";
8
+ IsolationLevel["REPEATABLE_READ"] = "REPEATABLE READ";
9
+ IsolationLevel["SERIALIZABLE"] = "SERIALIZABLE";
10
+ })(IsolationLevel || (exports.IsolationLevel = IsolationLevel = {}));
11
+ exports.isolationLevels = [
12
+ IsolationLevel.READ_UNCOMMITTED,
13
+ IsolationLevel.READ_COMMITTED,
14
+ IsolationLevel.REPEATABLE_READ,
15
+ IsolationLevel.SERIALIZABLE,
16
+ ];
17
+ exports.DEFAULT_ISOLATION_LEVEL = IsolationLevel.READ_UNCOMMITTED;
18
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAQA,IAAY,cAKX;AALD,WAAY,cAAc;IACxB,uDAAqC,CAAA;IACrC,mDAAiC,CAAA;IACjC,qDAAmC,CAAA;IACnC,+CAA6B,CAAA;AAC/B,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB;AAEY,QAAA,eAAe,GAA8B;IACxD,cAAc,CAAC,gBAAgB;IAC/B,cAAc,CAAC,cAAc;IAC7B,cAAc,CAAC,eAAe;IAC9B,cAAc,CAAC,YAAY;CAC5B,CAAC;AAEW,QAAA,uBAAuB,GAAG,cAAc,CAAC,gBAAgB,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `extendme` Базовый транзакционный контекст
3
+ */
4
+ export declare abstract class BaseContext<TIsolation> {
5
+ /**
6
+ * Указывает на то будут ли запросы к бд выполнены внутри транзакции
7
+ */
8
+ readonly suspended?: boolean;
9
+ /**
10
+ * Текущий уровень изоляции
11
+ */
12
+ readonly isolationLevel?: TIsolation;
13
+ /**
14
+ * Возможные уровни изоляции отсортированные по строгости
15
+ */
16
+ abstract readonly isolationLevels: readonly TIsolation[];
17
+ /**
18
+ * @param suspendedOrIsolationLevel будет ли создаваться/использовать транзакция в рамках этого контекста,
19
+ * это не значит что транзакцию нельзя будет создать, но если внешний контекст был задан с транзакцией,
20
+ * то внутри этого контекста будут отдаваться соединения без транзакции
21
+ * или уровень изоляции внутри этого контекста
22
+ * @protected
23
+ */
24
+ protected constructor(suspendedOrIsolationLevel: true | TIsolation);
25
+ /**
26
+ * Проверка на совместимость переданного уровня изоляции с тем который уже задан в контексте
27
+ * @param isolationLevel
28
+ */
29
+ assertIsolationCompatibility(isolationLevel?: TIsolation): void;
30
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseContext = void 0;
4
+ const core_1 = require("@rsdk/core");
5
+ const exceptions_1 = require("./exceptions");
6
+ /**
7
+ * `extendme` Базовый транзакционный контекст
8
+ */
9
+ class BaseContext {
10
+ /**
11
+ * Указывает на то будут ли запросы к бд выполнены внутри транзакции
12
+ */
13
+ suspended;
14
+ /**
15
+ * Текущий уровень изоляции
16
+ */
17
+ isolationLevel;
18
+ /**
19
+ * @param suspendedOrIsolationLevel будет ли создаваться/использовать транзакция в рамках этого контекста,
20
+ * это не значит что транзакцию нельзя будет создать, но если внешний контекст был задан с транзакцией,
21
+ * то внутри этого контекста будут отдаваться соединения без транзакции
22
+ * или уровень изоляции внутри этого контекста
23
+ * @protected
24
+ */
25
+ constructor(suspendedOrIsolationLevel) {
26
+ if (typeof suspendedOrIsolationLevel === 'boolean') {
27
+ this.suspended = suspendedOrIsolationLevel;
28
+ }
29
+ else {
30
+ this.isolationLevel = suspendedOrIsolationLevel;
31
+ }
32
+ }
33
+ /**
34
+ * Проверка на совместимость переданного уровня изоляции с тем который уже задан в контексте
35
+ * @param isolationLevel
36
+ */
37
+ assertIsolationCompatibility(isolationLevel) {
38
+ if (!isolationLevel) {
39
+ return;
40
+ }
41
+ if (this.isolationLevel === undefined) {
42
+ throw new core_1.InternalException('Isolation level not defined');
43
+ }
44
+ const currentIndex = this.isolationLevels.indexOf(this.isolationLevel);
45
+ const neededIndex = this.isolationLevels.indexOf(isolationLevel);
46
+ if (neededIndex > currentIndex) {
47
+ throw new exceptions_1.IncompatibleIsolationLevels(this.isolationLevel, isolationLevel);
48
+ }
49
+ }
50
+ }
51
+ exports.BaseContext = BaseContext;
52
+ //# sourceMappingURL=context.base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.base.js","sourceRoot":"","sources":["../src/context.base.ts"],"names":[],"mappings":";;;AAAA,qCAA+C;AAE/C,6CAA2D;AAE3D;;GAEG;AACH,MAAsB,WAAW;IAC/B;;OAEG;IACM,SAAS,CAAW;IAE7B;;OAEG;IACM,cAAc,CAAc;IAOrC;;;;;;OAMG;IACH,YAAsB,yBAA4C;QAChE,IAAI,OAAO,yBAAyB,KAAK,SAAS,EAAE;YAClD,IAAI,CAAC,SAAS,GAAG,yBAAyB,CAAC;SAC5C;aAAM;YACL,IAAI,CAAC,cAAc,GAAG,yBAAyB,CAAC;SACjD;IACH,CAAC;IAED;;;OAGG;IACH,4BAA4B,CAAC,cAA2B;QACtD,IAAI,CAAC,cAAc,EAAE;YACnB,OAAO;SACR;QAED,IAAI,IAAI,CAAC,cAAc,KAAK,SAAS,EAAE;YACrC,MAAM,IAAI,wBAAiB,CAAC,6BAA6B,CAAC,CAAC;SAC5D;QAED,MAAM,YAAY,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACvE,MAAM,WAAW,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QACjE,IAAI,WAAW,GAAG,YAAY,EAAE;YAC9B,MAAM,IAAI,wCAA2B,CACnC,IAAI,CAAC,cAAc,EACnB,cAAc,CACf,CAAC;SACH;IACH,CAAC;CACF;AArDD,kCAqDC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Обертка вокруг `AsyncLocalStorage`
3
+ * В теории можно запустить с пустым `payload`, для того чтобы добавлять
4
+ * значения в процессе
5
+ */
6
+ export declare class ContextStorage<P> {
7
+ private asyncLocalStorage;
8
+ /**
9
+ * Получает новое значение в контекст
10
+ */
11
+ getContext(): P | undefined;
12
+ /**
13
+ * Запускает переданную фунцию в контексте
14
+ * @template TResult
15
+ * @template TArgs
16
+ * @param context Контекст исполнения (данные)
17
+ * @param fn Функция для запуска
18
+ * @param args Аргументы функции
19
+ * @returns Результат выполнения функции
20
+ */
21
+ run<TResult, TArgs extends any[]>(context: P, fn: (...args: TArgs) => TResult, ...args: TArgs): TResult;
22
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContextStorage = void 0;
4
+ const node_async_hooks_1 = require("node:async_hooks");
5
+ /**
6
+ * Обертка вокруг `AsyncLocalStorage`
7
+ * В теории можно запустить с пустым `payload`, для того чтобы добавлять
8
+ * значения в процессе
9
+ */
10
+ class ContextStorage {
11
+ asyncLocalStorage = new node_async_hooks_1.AsyncLocalStorage();
12
+ /**
13
+ * Получает новое значение в контекст
14
+ */
15
+ getContext() {
16
+ return this.asyncLocalStorage.getStore()?.context;
17
+ }
18
+ /**
19
+ * Запускает переданную фунцию в контексте
20
+ * @template TResult
21
+ * @template TArgs
22
+ * @param context Контекст исполнения (данные)
23
+ * @param fn Функция для запуска
24
+ * @param args Аргументы функции
25
+ * @returns Результат выполнения функции
26
+ */
27
+ run(context, fn, ...args) {
28
+ return this.asyncLocalStorage.run({ context }, fn, ...args);
29
+ }
30
+ }
31
+ exports.ContextStorage = ContextStorage;
32
+ //# sourceMappingURL=context.storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.storage.js","sourceRoot":"","sources":["../src/context.storage.ts"],"names":[],"mappings":";;;AAAA,uDAAqD;AAErD;;;;GAIG;AACH,MAAa,cAAc;IACjB,iBAAiB,GAAG,IAAI,oCAAiB,EAAkB,CAAC;IAEpE;;OAEG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAC;IACpD,CAAC;IAED;;;;;;;;OAQG;IACH,GAAG,CACD,OAAU,EACV,EAA+B,EAC/B,GAAG,IAAW;QAEd,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;IAC9D,CAAC;CACF;AA1BD,wCA0BC"}
@@ -0,0 +1,10 @@
1
+ import { InternalException } from '@rsdk/core';
2
+ export declare class IncompatibleIsolationLevels<TIsolation> extends InternalException {
3
+ constructor(current: TIsolation, requested: TIsolation);
4
+ }
5
+ export declare class CallOutOfContextWithMandatory extends InternalException {
6
+ constructor();
7
+ }
8
+ export declare class NeverRunningInTransaction extends InternalException {
9
+ constructor();
10
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NeverRunningInTransaction = exports.CallOutOfContextWithMandatory = exports.IncompatibleIsolationLevels = void 0;
4
+ const core_1 = require("@rsdk/core");
5
+ class IncompatibleIsolationLevels extends core_1.InternalException {
6
+ constructor(current, requested) {
7
+ super('Incompatible isolation levels', {
8
+ details: { current, requested },
9
+ });
10
+ }
11
+ }
12
+ exports.IncompatibleIsolationLevels = IncompatibleIsolationLevels;
13
+ class CallOutOfContextWithMandatory extends core_1.InternalException {
14
+ constructor() {
15
+ super('Call out of context with mandatory');
16
+ }
17
+ }
18
+ exports.CallOutOfContextWithMandatory = CallOutOfContextWithMandatory;
19
+ class NeverRunningInTransaction extends core_1.InternalException {
20
+ constructor() {
21
+ super('Run in transaction, but propagation never');
22
+ }
23
+ }
24
+ exports.NeverRunningInTransaction = NeverRunningInTransaction;
25
+ //# sourceMappingURL=exceptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exceptions.js","sourceRoot":"","sources":["../src/exceptions.ts"],"names":[],"mappings":";;;AAAA,qCAA+C;AAE/C,MAAa,2BAAwC,SAAQ,wBAAiB;IAC5E,YAAY,OAAmB,EAAE,SAAqB;QACpD,KAAK,CAAC,+BAA+B,EAAE;YACrC,OAAO,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE;SAChC,CAAC,CAAC;IACL,CAAC;CACF;AAND,kEAMC;AAED,MAAa,6BAA8B,SAAQ,wBAAiB;IAClE;QACE,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC9C,CAAC;CACF;AAJD,sEAIC;AAED,MAAa,yBAA0B,SAAQ,wBAAiB;IAC9D;QACE,KAAK,CAAC,2CAA2C,CAAC,CAAC;IACrD,CAAC;CACF;AAJD,8DAIC"}
@@ -0,0 +1,6 @@
1
+ export { ContextStorage } from './context.storage';
2
+ export { BaseContext } from './context.base';
3
+ export { TransactionalStrategy, CallBack } from './types';
4
+ export { NeverRunningInTransaction, CallOutOfContextWithMandatory, IncompatibleIsolationLevels, } from './exceptions';
5
+ export { TransactionRunner } from './transactional.runner';
6
+ export { Propagation } from './propagation.enum';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Propagation = exports.TransactionRunner = exports.IncompatibleIsolationLevels = exports.CallOutOfContextWithMandatory = exports.NeverRunningInTransaction = exports.BaseContext = exports.ContextStorage = void 0;
4
+ var context_storage_1 = require("./context.storage");
5
+ Object.defineProperty(exports, "ContextStorage", { enumerable: true, get: function () { return context_storage_1.ContextStorage; } });
6
+ var context_base_1 = require("./context.base");
7
+ Object.defineProperty(exports, "BaseContext", { enumerable: true, get: function () { return context_base_1.BaseContext; } });
8
+ var exceptions_1 = require("./exceptions");
9
+ Object.defineProperty(exports, "NeverRunningInTransaction", { enumerable: true, get: function () { return exceptions_1.NeverRunningInTransaction; } });
10
+ Object.defineProperty(exports, "CallOutOfContextWithMandatory", { enumerable: true, get: function () { return exceptions_1.CallOutOfContextWithMandatory; } });
11
+ Object.defineProperty(exports, "IncompatibleIsolationLevels", { enumerable: true, get: function () { return exceptions_1.IncompatibleIsolationLevels; } });
12
+ var transactional_runner_1 = require("./transactional.runner");
13
+ Object.defineProperty(exports, "TransactionRunner", { enumerable: true, get: function () { return transactional_runner_1.TransactionRunner; } });
14
+ var propagation_enum_1 = require("./propagation.enum");
15
+ Object.defineProperty(exports, "Propagation", { enumerable: true, get: function () { return propagation_enum_1.Propagation; } });
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAmD;AAA1C,iHAAA,cAAc,OAAA;AACvB,+CAA6C;AAApC,2GAAA,WAAW,OAAA;AAEpB,2CAIsB;AAHpB,uHAAA,yBAAyB,OAAA;AACzB,2HAAA,6BAA6B,OAAA;AAC7B,yHAAA,2BAA2B,OAAA;AAE7B,+DAA2D;AAAlD,yHAAA,iBAAiB,OAAA;AAC1B,uDAAiD;AAAxC,+GAAA,WAAW,OAAA"}
@@ -0,0 +1,30 @@
1
+ export declare enum Propagation {
2
+ /**
3
+ * Support a current transaction, throw an exception if none exists.
4
+ */
5
+ MANDATORY = 0,
6
+ /**
7
+ * Execute within a nested transaction if a current transaction exists, behave like REQUIRED else.
8
+ */
9
+ NESTED = 1,
10
+ /**
11
+ * Execute non-transactionally, throw an exception if a transaction exists.
12
+ */
13
+ NEVER = 2,
14
+ /**
15
+ * Execute non-transactionally, suspend the current transaction if one exists.
16
+ */
17
+ NOT_SUPPORTED = 3,
18
+ /**
19
+ * (default behaviour) - Support a current transaction, create a new one if none exists.
20
+ */
21
+ REQUIRED = 4,
22
+ /**
23
+ * Create a new transaction, and suspend the current transaction if one exists.
24
+ */
25
+ REQUIRES_NEW = 5,
26
+ /**
27
+ * Support a current transaction, execute non-transactionally if none exists.
28
+ */
29
+ SUPPORTS = 6
30
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Propagation = void 0;
4
+ var Propagation;
5
+ (function (Propagation) {
6
+ /**
7
+ * Support a current transaction, throw an exception if none exists.
8
+ */
9
+ Propagation[Propagation["MANDATORY"] = 0] = "MANDATORY";
10
+ /**
11
+ * Execute within a nested transaction if a current transaction exists, behave like REQUIRED else.
12
+ */
13
+ Propagation[Propagation["NESTED"] = 1] = "NESTED";
14
+ /**
15
+ * Execute non-transactionally, throw an exception if a transaction exists.
16
+ */
17
+ Propagation[Propagation["NEVER"] = 2] = "NEVER";
18
+ /**
19
+ * Execute non-transactionally, suspend the current transaction if one exists.
20
+ */
21
+ Propagation[Propagation["NOT_SUPPORTED"] = 3] = "NOT_SUPPORTED";
22
+ /**
23
+ * (default behaviour) - Support a current transaction, create a new one if none exists.
24
+ */
25
+ Propagation[Propagation["REQUIRED"] = 4] = "REQUIRED";
26
+ /**
27
+ * Create a new transaction, and suspend the current transaction if one exists.
28
+ */
29
+ Propagation[Propagation["REQUIRES_NEW"] = 5] = "REQUIRES_NEW";
30
+ /**
31
+ * Support a current transaction, execute non-transactionally if none exists.
32
+ */
33
+ Propagation[Propagation["SUPPORTS"] = 6] = "SUPPORTS";
34
+ })(Propagation || (exports.Propagation = Propagation = {}));
35
+ //# sourceMappingURL=propagation.enum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"propagation.enum.js","sourceRoot":"","sources":["../src/propagation.enum.ts"],"names":[],"mappings":";;;AAAA,IAAY,WAmCX;AAnCD,WAAY,WAAW;IACrB;;OAEG;IACH,uDAAS,CAAA;IAET;;OAEG;IACH,iDAAM,CAAA;IAEN;;OAEG;IACH,+CAAK,CAAA;IAEL;;OAEG;IACH,+DAAa,CAAA;IAEb;;OAEG;IACH,qDAAQ,CAAA;IAER;;OAEG;IACH,6DAAY,CAAA;IAEZ;;OAEG;IACH,qDAAQ,CAAA;AACV,CAAC,EAnCW,WAAW,2BAAX,WAAW,QAmCtB"}
@@ -0,0 +1,29 @@
1
+ import type { BaseContext } from './context.base';
2
+ import { Propagation } from './propagation.enum';
3
+ import type { TransactionalStrategy } from './types';
4
+ export declare class TransactionRunner<TIsolation extends string, TContext extends BaseContext<TIsolation>> {
5
+ private readonly strategy;
6
+ private static defaultPropagation;
7
+ constructor(strategy: TransactionalStrategy<TIsolation, TContext>);
8
+ /**
9
+ * Вызовы метода будут обернуты в transactional context
10
+ */
11
+ Transactional(payload?: {
12
+ isolation?: TIsolation;
13
+ propagation?: Propagation;
14
+ }): MethodDecorator;
15
+ transactional<TResult>(...args: [fn: () => TResult]): Promise<TResult>;
16
+ transactional<TResult>(...args: [isolation: TIsolation, fn: () => TResult]): Promise<TResult>;
17
+ transactional<TResult>(...args: [fn: () => TResult] | [
18
+ runOptions: {
19
+ isolation: TIsolation;
20
+ propagation: Propagation;
21
+ },
22
+ fn: () => TResult
23
+ ]): Promise<TResult>;
24
+ /**
25
+ * Вернет функцию, которая вызовет переданный коллбек в transactional context
26
+ */
27
+ private bindTransactional;
28
+ private parseRunArgs;
29
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionRunner = void 0;
4
+ const common_1 = require("@rsdk/common");
5
+ const decorators_1 = require("@rsdk/decorators");
6
+ const exceptions_1 = require("./exceptions");
7
+ const propagation_enum_1 = require("./propagation.enum");
8
+ class TransactionRunner {
9
+ strategy;
10
+ static defaultPropagation = propagation_enum_1.Propagation.REQUIRED;
11
+ constructor(strategy) {
12
+ this.strategy = strategy;
13
+ }
14
+ /**
15
+ * Вызовы метода будут обернуты в transactional context
16
+ */
17
+ // eslint-disable-next-line @typescript-eslint/naming-convention
18
+ Transactional(payload) {
19
+ const { isolation, propagation = TransactionRunner.defaultPropagation } = payload ?? {};
20
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
21
+ const runner = this;
22
+ return function (_, __, descriptor) {
23
+ // eslint-disable-next-line @typescript-eslint/ban-types
24
+ const original = descriptor.value;
25
+ descriptor.value = function (...args) {
26
+ const bindedOriginal = original.bind(this, ...args);
27
+ return runner.bindTransactional(bindedOriginal, {
28
+ isolation: isolation,
29
+ propagation,
30
+ })();
31
+ };
32
+ Object.defineProperty(descriptor.value, 'name', {
33
+ value: original.name,
34
+ writable: false,
35
+ });
36
+ (0, decorators_1.redecorate)(original, descriptor.value);
37
+ };
38
+ }
39
+ transactional(...args) {
40
+ const { fn, isolation, propagation } = this.parseRunArgs(args);
41
+ return this.bindTransactional(fn, {
42
+ propagation,
43
+ isolation,
44
+ })();
45
+ }
46
+ /**
47
+ * Вернет функцию, которая вызовет переданный коллбек в transactional context
48
+ */
49
+ bindTransactional(fn, payload) {
50
+ const { propagation = TransactionRunner.defaultPropagation, isolation } = payload ?? {};
51
+ return async (...args) => {
52
+ const bindedFn = () => fn(...args);
53
+ const currentContext = this.strategy.getContext();
54
+ switch (propagation) {
55
+ case propagation_enum_1.Propagation.REQUIRES_NEW:
56
+ return this.strategy.runFromNewContext(isolation, fn, ...args);
57
+ case propagation_enum_1.Propagation.NEVER:
58
+ if (currentContext && !currentContext.suspended) {
59
+ throw new exceptions_1.NeverRunningInTransaction();
60
+ }
61
+ if (currentContext) {
62
+ return bindedFn();
63
+ }
64
+ return this.strategy.runOutTransactionalContext(fn, ...args);
65
+ case propagation_enum_1.Propagation.MANDATORY:
66
+ if (!currentContext || currentContext.suspended) {
67
+ throw new exceptions_1.CallOutOfContextWithMandatory();
68
+ }
69
+ currentContext.assertIsolationCompatibility(isolation);
70
+ return bindedFn();
71
+ case propagation_enum_1.Propagation.NESTED:
72
+ if (!currentContext || currentContext.suspended) {
73
+ return await this.strategy.runFromNewContext(isolation, fn, ...args);
74
+ }
75
+ return await this.strategy.nestedExecute(currentContext, isolation, fn, ...args);
76
+ case propagation_enum_1.Propagation.NOT_SUPPORTED:
77
+ if (currentContext?.suspended) {
78
+ return bindedFn();
79
+ }
80
+ return this.strategy.runOutTransactionalContext(fn, ...args);
81
+ case propagation_enum_1.Propagation.REQUIRED:
82
+ if (!currentContext || currentContext.suspended) {
83
+ return await this.strategy.runFromNewContext(isolation, fn, ...args);
84
+ }
85
+ currentContext.assertIsolationCompatibility(isolation);
86
+ return bindedFn();
87
+ case propagation_enum_1.Propagation.SUPPORTS:
88
+ return bindedFn();
89
+ default:
90
+ return (0, common_1.unreachable)(propagation);
91
+ }
92
+ };
93
+ }
94
+ parseRunArgs(args) {
95
+ if (args.length === 1) {
96
+ return {
97
+ fn: args[0],
98
+ propagation: TransactionRunner.defaultPropagation,
99
+ };
100
+ }
101
+ if (typeof args[0] === 'object' &&
102
+ args[0] !== null &&
103
+ 'isolation' in args[0] &&
104
+ 'propagation' in args[0]) {
105
+ return {
106
+ isolation: args[0].isolation,
107
+ fn: args[1],
108
+ propagation: args[0].propagation,
109
+ };
110
+ }
111
+ return {
112
+ isolation: args[0],
113
+ fn: args[1],
114
+ propagation: TransactionRunner.defaultPropagation,
115
+ };
116
+ }
117
+ }
118
+ exports.TransactionRunner = TransactionRunner;
119
+ //# sourceMappingURL=transactional.runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transactional.runner.js","sourceRoot":"","sources":["../src/transactional.runner.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,10 @@
1
+ import type { BaseContext } from './context.base';
2
+ export type CallBack<TArgs extends any[], TResult> = (...args: TArgs) => TResult;
3
+ export interface TransactionalStrategy<TIsolation extends string, TContext extends BaseContext<TIsolation>> {
4
+ bindContext<TResult, TArgs extends any[]>(fn: CallBack<TArgs, TResult>, options?: TIsolation): CallBack<TArgs, Promise<TResult>>;
5
+ isRunning(): boolean;
6
+ getContext(): TContext | undefined;
7
+ runFromNewContext<TArgs extends any[], TResult>(options: TIsolation | undefined, fn: (...args: TArgs) => TResult, ...args: any[]): Promise<TResult>;
8
+ runOutTransactionalContext<TArgs extends any[], TResult>(fn: (...args: TArgs) => TResult, ...args: any[]): Promise<TResult>;
9
+ nestedExecute<TArgs extends any[], TResult>(currentContext: TContext, options: TIsolation | undefined, fn: (...args: TArgs) => TResult, ...param4: any[]): Promise<TResult>;
10
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@rsdk/db",
3
+ "version": "2.5.1",
4
+ "description": "Common functionality and interfaces for relational database plugins",
5
+ "main": "dist/index.js",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "url": "https://github.com/R-Vision/rsdk"
11
+ },
12
+ "scripts": {
13
+ "prepublishOnly": "npm run build"
14
+ },
15
+ "peerDependencies": {
16
+ "@rsdk/common": "^2.4.2",
17
+ "@rsdk/core": "^2.5.1",
18
+ "@rsdk/decorators": "^2.5.1"
19
+ },
20
+ "gitHead": "8762f61fce4c854db863ef204d245d1f69d51655"
21
+ }
@@ -0,0 +1,61 @@
1
+ import { InternalException } from '@rsdk/core';
2
+
3
+ import { IncompatibleIsolationLevels } from './exceptions';
4
+
5
+ /**
6
+ * `extendme` Базовый транзакционный контекст
7
+ */
8
+ export abstract class BaseContext<TIsolation> {
9
+ /**
10
+ * Указывает на то будут ли запросы к бд выполнены внутри транзакции
11
+ */
12
+ readonly suspended?: boolean;
13
+
14
+ /**
15
+ * Текущий уровень изоляции
16
+ */
17
+ readonly isolationLevel?: TIsolation;
18
+
19
+ /**
20
+ * Возможные уровни изоляции отсортированные по строгости
21
+ */
22
+ abstract readonly isolationLevels: readonly TIsolation[];
23
+
24
+ /**
25
+ * @param suspendedOrIsolationLevel будет ли создаваться/использовать транзакция в рамках этого контекста,
26
+ * это не значит что транзакцию нельзя будет создать, но если внешний контекст был задан с транзакцией,
27
+ * то внутри этого контекста будут отдаваться соединения без транзакции
28
+ * или уровень изоляции внутри этого контекста
29
+ * @protected
30
+ */
31
+ protected constructor(suspendedOrIsolationLevel: true | TIsolation) {
32
+ if (typeof suspendedOrIsolationLevel === 'boolean') {
33
+ this.suspended = suspendedOrIsolationLevel;
34
+ } else {
35
+ this.isolationLevel = suspendedOrIsolationLevel;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Проверка на совместимость переданного уровня изоляции с тем который уже задан в контексте
41
+ * @param isolationLevel
42
+ */
43
+ assertIsolationCompatibility(isolationLevel?: TIsolation): void {
44
+ if (!isolationLevel) {
45
+ return;
46
+ }
47
+
48
+ if (this.isolationLevel === undefined) {
49
+ throw new InternalException('Isolation level not defined');
50
+ }
51
+
52
+ const currentIndex = this.isolationLevels.indexOf(this.isolationLevel);
53
+ const neededIndex = this.isolationLevels.indexOf(isolationLevel);
54
+ if (neededIndex > currentIndex) {
55
+ throw new IncompatibleIsolationLevels(
56
+ this.isolationLevel,
57
+ isolationLevel,
58
+ );
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,34 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ /**
4
+ * Обертка вокруг `AsyncLocalStorage`
5
+ * В теории можно запустить с пустым `payload`, для того чтобы добавлять
6
+ * значения в процессе
7
+ */
8
+ export class ContextStorage<P> {
9
+ private asyncLocalStorage = new AsyncLocalStorage<{ context: P }>();
10
+
11
+ /**
12
+ * Получает новое значение в контекст
13
+ */
14
+ getContext(): P | undefined {
15
+ return this.asyncLocalStorage.getStore()?.context;
16
+ }
17
+
18
+ /**
19
+ * Запускает переданную фунцию в контексте
20
+ * @template TResult
21
+ * @template TArgs
22
+ * @param context Контекст исполнения (данные)
23
+ * @param fn Функция для запуска
24
+ * @param args Аргументы функции
25
+ * @returns Результат выполнения функции
26
+ */
27
+ run<TResult, TArgs extends any[]>(
28
+ context: P,
29
+ fn: (...args: TArgs) => TResult,
30
+ ...args: TArgs
31
+ ): TResult {
32
+ return this.asyncLocalStorage.run({ context }, fn, ...args);
33
+ }
34
+ }
@@ -0,0 +1,21 @@
1
+ import { InternalException } from '@rsdk/core';
2
+
3
+ export class IncompatibleIsolationLevels<TIsolation> extends InternalException {
4
+ constructor(current: TIsolation, requested: TIsolation) {
5
+ super('Incompatible isolation levels', {
6
+ details: { current, requested },
7
+ });
8
+ }
9
+ }
10
+
11
+ export class CallOutOfContextWithMandatory extends InternalException {
12
+ constructor() {
13
+ super('Call out of context with mandatory');
14
+ }
15
+ }
16
+
17
+ export class NeverRunningInTransaction extends InternalException {
18
+ constructor() {
19
+ super('Run in transaction, but propagation never');
20
+ }
21
+ }