@event-driven-io/emmett-sqlite 0.42.0-rc.2 → 0.43.0-apha.2

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/dist/index.cjs CHANGED
@@ -1,157 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/connection/sqliteConnection.ts
2
- var _sqlite3 = require('sqlite3'); var _sqlite32 = _interopRequireDefault(_sqlite3);
3
- var isSQLiteError = (error) => {
4
- if (error instanceof Error && "code" in error) {
5
- return true;
6
- }
7
- return false;
8
- };
9
- var InMemorySharedCacheSQLiteDatabase = "file::memory:?cache=shared";
10
- var InMemorySQLiteDatabase = ":memory:";
11
- var sqliteConnection = (options) => {
12
- const fileName = _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase));
13
- let db;
14
- if (fileName.startsWith("file:")) {
15
- db = new _sqlite32.default.Database(
16
- fileName,
17
- _sqlite32.default.OPEN_URI | _sqlite32.default.OPEN_READWRITE | _sqlite32.default.OPEN_CREATE
18
- );
19
- } else {
20
- db = new _sqlite32.default.Database(fileName);
21
- }
22
- db.run("PRAGMA journal_mode = WAL;");
23
- let transactionNesting = 0;
24
- return {
25
- close: () => db.close(),
26
- command: (sql2, params) => new Promise((resolve, reject) => {
27
- db.run(
28
- sql2,
29
- _nullishCoalesce(params, () => ( [])),
30
- function(err) {
31
- if (err) {
32
- reject(err);
33
- return;
34
- }
35
- resolve(this);
36
- }
37
- );
38
- }),
39
- batchCommand: async (sqls) => {
40
- for (const sql2 of sqls) {
41
- await new Promise((resolve, reject) => {
42
- db.run(sql2, [], (err) => {
43
- if (err) {
44
- reject(err);
45
- return;
46
- }
47
- resolve();
48
- });
49
- });
50
- }
51
- },
52
- query: (sql2, params) => new Promise((resolve, reject) => {
53
- db.all(sql2, _nullishCoalesce(params, () => ( [])), (err, result) => {
54
- if (err) {
55
- reject(err);
56
- return;
57
- }
58
- resolve(result);
59
- });
60
- }),
61
- querySingle: (sql2, params) => new Promise((resolve, reject) => {
62
- db.get(sql2, _nullishCoalesce(params, () => ( [])), (err, result) => {
63
- if (err) {
64
- reject(err);
65
- return;
66
- }
67
- resolve(result);
68
- });
69
- }),
70
- withTransaction: async (fn) => {
71
- try {
72
- if (transactionNesting++ == 0) {
73
- await beginTransaction(db);
74
- }
75
- const result = await fn();
76
- if (transactionNesting === 1) await commitTransaction(db);
77
- transactionNesting--;
78
- return result;
79
- } catch (err) {
80
- console.log(err);
81
- if (--transactionNesting === 0) await rollbackTransaction(db);
82
- throw err;
83
- }
84
- }
85
- };
86
- };
87
- var beginTransaction = (db) => new Promise((resolve, reject) => {
88
- db.run("BEGIN IMMEDIATE TRANSACTION", (err) => {
89
- if (err) {
90
- reject(err);
91
- return;
92
- }
93
- resolve();
94
- });
95
- });
96
- var commitTransaction = (db) => new Promise((resolve, reject) => {
97
- db.run("COMMIT", (err) => {
98
- if (err) {
99
- reject(err);
100
- return;
101
- }
102
- resolve();
103
- });
104
- });
105
- var rollbackTransaction = (db) => new Promise((resolve, reject) => {
106
- db.run("ROLLBACK", (err) => {
107
- if (err) {
108
- reject(err);
109
- return;
110
- }
111
- resolve();
112
- });
113
- });
114
-
115
- // src/connection/sqliteConnectionPool.ts
116
- var SQLiteConnectionPool = (options) => {
117
- const fileName = _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase));
118
- const isInMemory = fileName === InMemorySQLiteDatabase || fileName === InMemorySharedCacheSQLiteDatabase;
119
- const singletonConnection = _nullishCoalesce(_optionalChain([options, 'access', _2 => _2.connectionOptions, 'optionalAccess', _3 => _3.connection]), () => ( (isInMemory ? sqliteConnection({
120
- fileName
121
- }) : null)));
122
- const isAmbientConnection = _optionalChain([options, 'access', _4 => _4.connectionOptions, 'optionalAccess', _5 => _5.singleton]) === true && _optionalChain([options, 'access', _6 => _6.connectionOptions, 'optionalAccess', _7 => _7.connection]) !== void 0;
123
- const createConnection = () => {
124
- return _nullishCoalesce(singletonConnection, () => ( sqliteConnection({
125
- fileName
126
- })));
127
- };
128
- const closeConnection = (connection) => {
129
- if (isInMemory || isAmbientConnection) {
130
- return;
131
- }
132
- connection.close();
133
- };
134
- const withConnection = async (handler) => {
135
- const connection = _nullishCoalesce(singletonConnection, () => ( createConnection()));
136
- try {
137
- return await handler(connection);
138
- } finally {
139
- closeConnection(connection);
140
- }
141
- };
142
- return {
143
- connection: () => Promise.resolve(createConnection()),
144
- withConnection,
145
- close: () => {
146
- if (singletonConnection && !isAmbientConnection) {
147
- closeConnection(singletonConnection);
148
- }
149
- return Promise.resolve();
150
- }
151
- };
152
- };
153
-
154
- // ../emmett/dist/chunk-AZDDB5SF.js
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// ../emmett/dist/chunk-AZDDB5SF.js
155
2
  var isNumber = (val) => typeof val === "number" && val === val;
156
3
  var isBigint = (val) => typeof val === "bigint" && val === val;
157
4
  var isString = (val) => typeof val === "string";
@@ -192,7 +39,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
192
39
  constructor(current, expected, message) {
193
40
  super({
194
41
  errorCode: EmmettError.Codes.ConcurrencyError,
195
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _8 => _8.toString, 'call', _9 => _9()])}`))
42
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))
196
43
  });
197
44
  this.current = current;
198
45
  this.expected = expected;
@@ -225,10 +72,14 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
225
72
  };
226
73
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
227
74
  constructor(current, expected) {
228
- super(_optionalChain([current, 'optionalAccess', _10 => _10.toString, 'call', _11 => _11()]), _optionalChain([expected, 'optionalAccess', _12 => _12.toString, 'call', _13 => _13()]));
75
+ super(_optionalChain([current, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]), _optionalChain([expected, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]));
229
76
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
230
77
  }
231
78
  };
79
+ var isExpectedVersionConflictError = (error2) => error2 instanceof ExpectedVersionConflictError || EmmettError.isInstanceOf(
80
+ error2,
81
+ ExpectedVersionConflictError.Codes.ConcurrencyError
82
+ );
232
83
  var isPrimitive = (value) => {
233
84
  const type = typeof value;
234
85
  return value === null || value === void 0 || type === "boolean" || type === "number" || type === "string" || type === "symbol" || type === "bigint";
@@ -430,10 +281,6 @@ var deepEquals = (left, right) => {
430
281
  var isEquatable = (left) => {
431
282
  return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
432
283
  };
433
- var toNormalizedString = (value) => value.toString().padStart(19, "0");
434
- var bigInt = {
435
- toNormalizedString
436
- };
437
284
  var ParseError = class extends Error {
438
285
  constructor(text) {
439
286
  super(`Cannot parse! ${text}`);
@@ -442,17 +289,17 @@ var ParseError = class extends Error {
442
289
  var JSONParser = {
443
290
  stringify: (value, options) => {
444
291
  return JSON.stringify(
445
- _optionalChain([options, 'optionalAccess', _14 => _14.map]) ? options.map(value) : value,
292
+ _optionalChain([options, 'optionalAccess', _8 => _8.map]) ? options.map(value) : value,
446
293
  //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
447
294
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
448
295
  (_, v) => typeof v === "bigint" ? v.toString() : v
449
296
  );
450
297
  },
451
298
  parse: (text, options) => {
452
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _15 => _15.reviver]));
453
- if (_optionalChain([options, 'optionalAccess', _16 => _16.typeCheck]) && !_optionalChain([options, 'optionalAccess', _17 => _17.typeCheck, 'call', _18 => _18(parsed)]))
299
+ const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _9 => _9.reviver]));
300
+ if (_optionalChain([options, 'optionalAccess', _10 => _10.typeCheck]) && !_optionalChain([options, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(parsed)]))
454
301
  throw new ParseError(text);
455
- return _optionalChain([options, 'optionalAccess', _19 => _19.map]) ? options.map(parsed) : parsed;
302
+ return _optionalChain([options, 'optionalAccess', _13 => _13.map]) ? options.map(parsed) : parsed;
456
303
  }
457
304
  };
458
305
  var textEncoder = new TextEncoder();
@@ -559,7 +406,7 @@ var assertThatArray = (array) => {
559
406
  };
560
407
  };
561
408
  var downcastRecordedMessage = (recordedMessage, options) => {
562
- if (!_optionalChain([options, 'optionalAccess', _20 => _20.downcast]))
409
+ if (!_optionalChain([options, 'optionalAccess', _14 => _14.downcast]))
563
410
  return recordedMessage;
564
411
  const downcasted = options.downcast(
565
412
  recordedMessage
@@ -577,14 +424,14 @@ var downcastRecordedMessage = (recordedMessage, options) => {
577
424
  };
578
425
  };
579
426
  var downcastRecordedMessages = (recordedMessages, options) => {
580
- if (!_optionalChain([options, 'optionalAccess', _21 => _21.downcast]))
427
+ if (!_optionalChain([options, 'optionalAccess', _15 => _15.downcast]))
581
428
  return recordedMessages;
582
429
  return recordedMessages.map(
583
430
  (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
584
431
  );
585
432
  };
586
433
  var upcastRecordedMessage = (recordedMessage, options) => {
587
- if (!_optionalChain([options, 'optionalAccess', _22 => _22.upcast]))
434
+ if (!_optionalChain([options, 'optionalAccess', _16 => _16.upcast]))
588
435
  return recordedMessage;
589
436
  const upcasted = options.upcast(
590
437
  recordedMessage
@@ -635,7 +482,7 @@ var sqliteRawBatchSQLProjection = (options) => sqliteProjection({
635
482
  canHandle: options.canHandle,
636
483
  handle: async (events, context) => {
637
484
  const sqls = await options.evolve(events, context);
638
- for (const sql2 of sqls) await context.connection.command(sql2);
485
+ for (const sql of sqls) await context.connection.execute.command(sql);
639
486
  },
640
487
  init: async (initOptions) => {
641
488
  if (options.init) {
@@ -643,8 +490,8 @@ var sqliteRawBatchSQLProjection = (options) => sqliteProjection({
643
490
  }
644
491
  if (options.initSQL) {
645
492
  const initSQLs = Array.isArray(options.initSQL) ? options.initSQL : [options.initSQL];
646
- for (const sql2 of initSQLs)
647
- await initOptions.context.connection.command(sql2);
493
+ for (const sql of initSQLs)
494
+ await initOptions.context.connection.execute.command(sql);
648
495
  }
649
496
  }
650
497
  });
@@ -670,41 +517,18 @@ var sqliteRawSQLProjection = (options) => {
670
517
  // src/eventStore/projections/sqliteProjectionSpec.ts
671
518
 
672
519
 
673
- // src/eventStore/schema/migrations/0_41_0/0_41_0.snapshot.ts
674
- var schema_0_41_0 = [
675
- `CREATE TABLE IF NOT EXISTS emt_streams(
676
- stream_id TEXT NOT NULL,
677
- stream_position BIGINT NOT NULL DEFAULT 0,
678
- partition TEXT NOT NULL DEFAULT 'global',
679
- stream_type TEXT NOT NULL,
680
- stream_metadata JSONB NOT NULL,
681
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
682
- PRIMARY KEY (stream_id, partition, is_archived),
683
- UNIQUE (stream_id, partition, is_archived)
684
- )`,
685
- `CREATE TABLE IF NOT EXISTS emt_messages(
686
- stream_id TEXT NOT NULL,
687
- stream_position BIGINT NOT NULL,
688
- partition TEXT NOT NULL DEFAULT 'global',
689
- message_kind CHAR(1) NOT NULL DEFAULT 'E',
690
- message_data JSONB NOT NULL,
691
- message_metadata JSONB NOT NULL,
692
- message_schema_version TEXT NOT NULL,
693
- message_type TEXT NOT NULL,
694
- message_id TEXT NOT NULL,
695
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
696
- global_position INTEGER PRIMARY KEY,
697
- created DATETIME DEFAULT CURRENT_TIMESTAMP,
698
- UNIQUE (stream_id, stream_position, partition, is_archived)
699
- )`,
700
- `CREATE TABLE IF NOT EXISTS emt_subscriptions(
701
- subscription_id TEXT NOT NULL,
702
- version INTEGER NOT NULL DEFAULT 1,
703
- partition TEXT NOT NULL DEFAULT 'global',
704
- last_processed_position BIGINT NOT NULL,
705
- PRIMARY KEY (subscription_id, partition, version)
706
- )`
707
- ];
520
+ var _dumbo = require('@event-driven-io/dumbo');
521
+ require('@event-driven-io/dumbo/sqlite');
522
+
523
+
524
+ // src/eventStore/SQLiteEventStore.ts
525
+
526
+
527
+
528
+
529
+
530
+ // src/eventStore/schema/readLastMessageGlobalPosition.ts
531
+
708
532
 
709
533
  // src/eventStore/schema/typing.ts
710
534
  var emmettPrefix2 = "emt";
@@ -741,196 +565,17 @@ var projectionsTable = {
741
565
  name: `${emmettPrefix2}_projections`
742
566
  };
743
567
 
744
- // src/eventStore/schema/migrations/0_42_0/0_42_0.migration.ts
745
- var migration_0_42_0_SQLs = [
746
- `CREATE TABLE IF NOT EXISTS ${processorsTable.name}(
747
- processor_id TEXT NOT NULL,
748
- version INTEGER NOT NULL DEFAULT 1,
749
- partition TEXT NOT NULL DEFAULT '${globalTag}',
750
- status TEXT NOT NULL DEFAULT 'stopped',
751
- last_processed_checkpoint TEXT NOT NULL,
752
- processor_instance_id TEXT DEFAULT 'emt:unknown',
753
- PRIMARY KEY (processor_id, partition, version)
754
- )`,
755
- `CREATE TABLE IF NOT EXISTS ${projectionsTable.name}(
756
- name TEXT NOT NULL,
757
- version INTEGER NOT NULL DEFAULT 1,
758
- partition TEXT NOT NULL DEFAULT '${globalTag}',
759
- type CHAR(1) NOT NULL,
760
- kind TEXT NOT NULL,
761
- status TEXT NOT NULL,
762
- definition JSONB NOT NULL DEFAULT '{}',
763
- PRIMARY KEY (name, partition, version)
764
- )`,
765
- `INSERT INTO ${processorsTable.name}
766
- (processor_id, version, partition, status, last_processed_checkpoint, processor_instance_id)
767
- SELECT
768
- subscription_id,
769
- version,
770
- partition,
771
- 'stopped',
772
- printf('%019d', last_processed_position),
773
- 'emt:unknown'
774
- FROM emt_subscriptions`,
775
- `DROP TABLE emt_subscriptions`
776
- ];
777
- var migration_0_42_0_FromSubscriptionsToProcessors = async (connection) => {
778
- await connection.withTransaction(async () => {
779
- const tableExists = await connection.querySingle(
780
- "SELECT name FROM sqlite_master WHERE type='table' AND name='emt_subscriptions'"
781
- );
782
- if (!tableExists) {
783
- return;
784
- }
785
- await connection.batchCommand(migration_0_42_0_SQLs);
786
- });
787
- };
788
-
789
- // src/eventStore/schema/migrations/0_42_0/0_42_0.snapshot.ts
790
- var schema_0_42_0 = [
791
- `CREATE TABLE IF NOT EXISTS emt_streams(
792
- stream_id TEXT NOT NULL,
793
- stream_position BIGINT NOT NULL DEFAULT 0,
794
- partition TEXT NOT NULL DEFAULT 'global',
795
- stream_type TEXT NOT NULL,
796
- stream_metadata JSONB NOT NULL,
797
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
798
- PRIMARY KEY (stream_id, partition, is_archived),
799
- UNIQUE (stream_id, partition, is_archived)
800
- )`,
801
- `CREATE TABLE IF NOT EXISTS emt_messages(
802
- stream_id TEXT NOT NULL,
803
- stream_position BIGINT NOT NULL,
804
- partition TEXT NOT NULL DEFAULT 'global',
805
- message_kind CHAR(1) NOT NULL DEFAULT 'E',
806
- message_data JSONB NOT NULL,
807
- message_metadata JSONB NOT NULL,
808
- message_schema_version TEXT NOT NULL,
809
- message_type TEXT NOT NULL,
810
- message_id TEXT NOT NULL,
811
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
812
- global_position INTEGER PRIMARY KEY,
813
- created DATETIME DEFAULT CURRENT_TIMESTAMP,
814
- UNIQUE (stream_id, stream_position, partition, is_archived)
815
- )`,
816
- `CREATE TABLE IF NOT EXISTS emt_processors(
817
- processor_id TEXT NOT NULL,
818
- version INTEGER NOT NULL DEFAULT 1,
819
- partition TEXT NOT NULL DEFAULT 'global',
820
- status TEXT NOT NULL DEFAULT 'stopped',
821
- last_processed_checkpoint TEXT NOT NULL,
822
- processor_instance_id TEXT DEFAULT 'emt:unknown',
823
- PRIMARY KEY (processor_id, partition, version)
824
- )`,
825
- `CREATE TABLE IF NOT EXISTS emt_projections(
826
- name TEXT NOT NULL,
827
- version INTEGER NOT NULL DEFAULT 1,
828
- partition TEXT NOT NULL DEFAULT 'global',
829
- type CHAR(1) NOT NULL,
830
- kind TEXT NOT NULL,
831
- status TEXT NOT NULL,
832
- definition JSONB NOT NULL DEFAULT '{}',
833
- PRIMARY KEY (name, partition, version)
834
- )`
835
- ];
836
-
837
- // src/eventStore/schema/tables.ts
838
- var sql = (sql2) => sql2;
839
- var streamsTableSQL = sql(
840
- `CREATE TABLE IF NOT EXISTS ${streamsTable.name}(
841
- stream_id TEXT NOT NULL,
842
- stream_position BIGINT NOT NULL DEFAULT 0,
843
- partition TEXT NOT NULL DEFAULT '${globalTag}',
844
- stream_type TEXT NOT NULL,
845
- stream_metadata JSONB NOT NULL,
846
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
847
- PRIMARY KEY (stream_id, partition, is_archived),
848
- UNIQUE (stream_id, partition, is_archived)
849
- );`
850
- );
851
- var messagesTableSQL = sql(
852
- `CREATE TABLE IF NOT EXISTS ${messagesTable.name}(
853
- stream_id TEXT NOT NULL,
854
- stream_position BIGINT NOT NULL,
855
- partition TEXT NOT NULL DEFAULT '${globalTag}',
856
- message_kind CHAR(1) NOT NULL DEFAULT 'E',
857
- message_data JSONB NOT NULL,
858
- message_metadata JSONB NOT NULL,
859
- message_schema_version TEXT NOT NULL,
860
- message_type TEXT NOT NULL,
861
- message_id TEXT NOT NULL,
862
- is_archived BOOLEAN NOT NULL DEFAULT FALSE,
863
- global_position INTEGER PRIMARY KEY,
864
- created DATETIME DEFAULT CURRENT_TIMESTAMP,
865
- UNIQUE (stream_id, stream_position, partition, is_archived)
866
- );
867
- `
868
- );
869
- var processorsTableSQL = sql(
870
- `
871
- CREATE TABLE IF NOT EXISTS ${processorsTable.name}(
872
- processor_id TEXT NOT NULL,
873
- version INTEGER NOT NULL DEFAULT 1,
874
- partition TEXT NOT NULL DEFAULT '${globalTag}',
875
- status TEXT NOT NULL DEFAULT 'stopped',
876
- last_processed_checkpoint TEXT NOT NULL,
877
- processor_instance_id TEXT DEFAULT '${unknownTag2}',
878
- PRIMARY KEY (processor_id, partition, version)
879
- );
880
- `
881
- );
882
- var projectionsTableSQL = sql(
883
- `
884
- CREATE TABLE IF NOT EXISTS ${projectionsTable.name}(
885
- name TEXT NOT NULL,
886
- version INTEGER NOT NULL DEFAULT 1,
887
- partition TEXT NOT NULL DEFAULT '${globalTag}',
888
- type CHAR(1) NOT NULL,
889
- kind TEXT NOT NULL,
890
- status TEXT NOT NULL,
891
- definition JSONB NOT NULL DEFAULT '{}',
892
- PRIMARY KEY (name, partition, version)
893
- );
894
- `
895
- );
896
- var schemaSQL = [
897
- streamsTableSQL,
898
- messagesTableSQL,
899
- processorsTableSQL,
900
- projectionsTableSQL
901
- ];
902
- var createEventStoreSchema = async (connection, hooks) => {
903
- await connection.withTransaction(async () => {
904
- await migration_0_42_0_FromSubscriptionsToProcessors(connection);
905
- if (_optionalChain([hooks, 'optionalAccess', _23 => _23.onBeforeSchemaCreated])) {
906
- await hooks.onBeforeSchemaCreated({ connection });
907
- }
908
- await connection.batchCommand(schemaSQL);
909
- });
910
- if (_optionalChain([hooks, 'optionalAccess', _24 => _24.onAfterSchemaCreated])) {
911
- await hooks.onAfterSchemaCreated();
912
- }
913
- };
914
-
915
- // src/eventStore/schema/utils.ts
916
- var singleOrNull = async (getResult) => {
917
- const result = await getResult;
918
- if (result.length > 1) throw new Error("Query had more than one result");
919
- return result.length > 0 ? _nullishCoalesce(result[0], () => ( null)) : null;
920
- };
921
-
922
568
  // src/eventStore/schema/readLastMessageGlobalPosition.ts
923
- var readLastMessageGlobalPosition = async (db, options) => {
924
- const result = await singleOrNull(
925
- db.query(
926
- sql(
927
- `SELECT global_position
928
- FROM ${messagesTable.name}
929
- WHERE partition = ? AND is_archived = FALSE
569
+ var { identifier } = _dumbo.SQL;
570
+ var readLastMessageGlobalPosition = async (execute, options) => {
571
+ const result = await _dumbo.singleOrNull.call(void 0,
572
+ execute.query(
573
+ _dumbo.SQL`
574
+ SELECT global_position
575
+ FROM ${identifier(messagesTable.name)}
576
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.partition]), () => ( defaultTag2))} AND is_archived = FALSE
930
577
  ORDER BY global_position
931
578
  LIMIT 1`
932
- ),
933
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _25 => _25.partition]), () => ( defaultTag2))]
934
579
  )
935
580
  );
936
581
  return {
@@ -939,22 +584,21 @@ var readLastMessageGlobalPosition = async (db, options) => {
939
584
  };
940
585
 
941
586
  // src/eventStore/schema/readMessagesBatch.ts
942
- var readMessagesBatch = async (db, options) => {
587
+
588
+ var { identifier: identifier2 } = _dumbo.SQL;
589
+ var readMessagesBatch = async (execute, options) => {
943
590
  const from = "from" in options ? options.from : "after" in options ? options.after + 1n : 0n;
944
591
  const batchSize = options && "batchSize" in options ? options.batchSize : options.to - options.from;
945
- const fromCondition = from !== -0n ? `AND global_position >= ${from}` : "";
946
- const toCondition = "to" in options ? `AND global_position <= ${options.to}` : "";
947
- const limitCondition = "batchSize" in options ? `LIMIT ${options.batchSize}` : "";
948
- const events = (await db.query(
949
- sql(
950
- `SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
951
- FROM ${messagesTable.name}
952
- WHERE partition = ? AND is_archived = FALSE ${fromCondition} ${toCondition}
592
+ const fromCondition = from !== -0n ? _dumbo.SQL`AND global_position >= ${from}` : "";
593
+ const toCondition = "to" in options ? _dumbo.SQL`AND global_position <= ${options.to}` : _dumbo.SQL.EMPTY;
594
+ const limitCondition = "batchSize" in options ? _dumbo.SQL`LIMIT ${options.batchSize}` : _dumbo.SQL.EMPTY;
595
+ const events = (await execute.query(
596
+ _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
597
+ FROM ${identifier2(messagesTable.name)}
598
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _18 => _18.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
953
599
  ORDER BY global_position
954
600
  ${limitCondition}`
955
- ),
956
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.partition]), () => ( defaultTag2))]
957
- )).map((row) => {
601
+ )).rows.map((row) => {
958
602
  const rawEvent = {
959
603
  type: row.message_type,
960
604
  data: JSONParser.parse(row.message_data),
@@ -997,7 +641,7 @@ var sqliteEventStoreMessageBatchPuller = ({
997
641
  let start;
998
642
  const pullMessages = async (options) => {
999
643
  const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await pool.withConnection(
1000
- async (connection) => readLastMessageGlobalPosition(connection)
644
+ async ({ execute }) => readLastMessageGlobalPosition(execute)
1001
645
  )).currentGlobalPosition, async () => ( 0n)) : options.startFrom.globalPosition;
1002
646
  const readMessagesOptions = {
1003
647
  after,
@@ -1006,7 +650,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1006
650
  let waitTime = 100;
1007
651
  do {
1008
652
  const { messages, currentGlobalPosition, areEventsLeft } = await pool.withConnection(
1009
- (connection) => readMessagesBatch(connection, readMessagesOptions)
653
+ ({ execute }) => readMessagesBatch(execute, readMessagesOptions)
1010
654
  );
1011
655
  if (messages.length > 0) {
1012
656
  const result = await eachBatch({ messages });
@@ -1050,12 +694,29 @@ var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
1050
694
  return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
1051
695
  };
1052
696
 
697
+ // src/eventStore/consumers/sqliteEventStoreConsumer.ts
698
+
699
+
700
+
701
+
702
+ // src/eventStore/consumers/sqliteProcessor.ts
703
+
704
+
1053
705
  // src/eventStore/schema/appendToStream.ts
1054
706
 
707
+
708
+
709
+
710
+
711
+
712
+
713
+
714
+
715
+ var { identifier: identifier3, merge } = _dumbo.SQL;
1055
716
  var appendToStream = async (connection, streamName, streamType, messages, options) => {
1056
717
  if (messages.length === 0) return { success: false };
1057
718
  const expectedStreamVersion = toExpectedVersion(
1058
- _optionalChain([options, 'optionalAccess', _27 => _27.expectedStreamVersion])
719
+ _optionalChain([options, 'optionalAccess', _19 => _19.expectedStreamVersion])
1059
720
  );
1060
721
  const messagesToAppend = messages.map(
1061
722
  (m, i) => ({
@@ -1069,21 +730,36 @@ var appendToStream = async (connection, streamName, streamType, messages, option
1069
730
  }
1070
731
  })
1071
732
  );
1072
- let result;
1073
- return await connection.withTransaction(async () => {
1074
- result = await appendToStreamRaw(
1075
- connection,
1076
- streamName,
1077
- streamType,
1078
- downcastRecordedMessages(messagesToAppend, _optionalChain([options, 'optionalAccess', _28 => _28.schema, 'optionalAccess', _29 => _29.versioning])),
1079
- {
1080
- expectedStreamVersion
733
+ try {
734
+ return await connection.withTransaction(
735
+ async (transaction) => {
736
+ const result = await appendToStreamRaw(
737
+ transaction.execute,
738
+ streamName,
739
+ streamType,
740
+ downcastRecordedMessages(
741
+ messagesToAppend,
742
+ _optionalChain([options, 'optionalAccess', _20 => _20.schema, 'optionalAccess', _21 => _21.versioning])
743
+ ),
744
+ {
745
+ expectedStreamVersion
746
+ }
747
+ );
748
+ if (_optionalChain([options, 'optionalAccess', _22 => _22.onBeforeCommit]))
749
+ await options.onBeforeCommit(messagesToAppend, { connection });
750
+ return { success: true, result };
1081
751
  }
1082
752
  );
1083
- if (_optionalChain([options, 'optionalAccess', _30 => _30.onBeforeCommit]))
1084
- await options.onBeforeCommit(messagesToAppend, { connection });
1085
- return result;
1086
- });
753
+ } catch (err) {
754
+ if (isExpectedVersionConflictError(err) || _dumbo.DumboError.isInstanceOf(err, {
755
+ errorType: _dumbo.UniqueConstraintError.ErrorType
756
+ }) || _dumbo.DumboError.isInstanceOf(err, {
757
+ errorType: _dumbo.BatchCommandNoChangesError.ErrorType
758
+ })) {
759
+ return { success: false };
760
+ }
761
+ throw err;
762
+ }
1087
763
  };
1088
764
  var toExpectedVersion = (expected) => {
1089
765
  if (expected === void 0) return null;
@@ -1092,104 +768,65 @@ var toExpectedVersion = (expected) => {
1092
768
  if (expected == STREAM_EXISTS) return null;
1093
769
  return expected;
1094
770
  };
1095
- var appendToStreamRaw = async (connection, streamId, streamType, messages, options) => {
1096
- let streamPosition;
1097
- let globalPosition;
1098
- try {
1099
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _31 => _31.expectedStreamVersion]), () => ( null));
1100
- if (expectedStreamVersion == null) {
1101
- expectedStreamVersion = await getLastStreamPosition(
1102
- connection,
1103
- streamId,
1104
- expectedStreamVersion
1105
- );
1106
- }
1107
- let position;
1108
- if (expectedStreamVersion === 0n) {
1109
- position = await connection.querySingle(
1110
- `INSERT INTO ${streamsTable.name}
771
+ var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
772
+ let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _23 => _23.expectedStreamVersion]), () => ( null));
773
+ const currentStreamVersion = await getLastStreamPosition(
774
+ execute,
775
+ streamId,
776
+ expectedStreamVersion
777
+ );
778
+ expectedStreamVersion ??= _nullishCoalesce(currentStreamVersion, () => ( 0n));
779
+ if (expectedStreamVersion !== currentStreamVersion) {
780
+ throw new ExpectedVersionConflictError(
781
+ currentStreamVersion,
782
+ expectedStreamVersion
783
+ );
784
+ }
785
+ const streamSQL = expectedStreamVersion === 0n ? _dumbo.SQL`INSERT INTO ${identifier3(streamsTable.name)}
1111
786
  (stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
1112
787
  VALUES (
1113
- ?,
1114
- ?,
1115
- ?,
1116
- ?,
788
+ ${streamId},
789
+ ${messages.length},
790
+ ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _24 => _24.partition]), () => ( streamsTable.columns.partition))},
791
+ ${streamType},
1117
792
  '[]',
1118
793
  false
1119
794
  )
1120
795
  RETURNING stream_position;
1121
- `,
1122
- [
1123
- streamId,
1124
- messages.length,
1125
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _32 => _32.partition]), () => ( streamsTable.columns.partition)),
1126
- streamType
1127
- ]
1128
- );
1129
- } else {
1130
- position = await connection.querySingle(
1131
- `UPDATE ${streamsTable.name}
1132
- SET stream_position = stream_position + ?
1133
- WHERE stream_id = ?
1134
- AND partition = ?
796
+ ` : _dumbo.SQL`UPDATE ${identifier3(streamsTable.name)}
797
+ SET stream_position = stream_position + ${messages.length}
798
+ WHERE stream_id = ${streamId}
799
+ AND stream_position = ${expectedStreamVersion}
800
+ AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _25 => _25.partition]), () => ( streamsTable.columns.partition))}
1135
801
  AND is_archived = false
1136
802
  RETURNING stream_position;
1137
- `,
1138
- [
1139
- messages.length,
1140
- streamId,
1141
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _33 => _33.partition]), () => ( streamsTable.columns.partition))
1142
- ]
1143
- );
1144
- }
1145
- if (position == null) {
1146
- throw new Error("Could not find stream position");
1147
- }
1148
- streamPosition = BigInt(position.stream_position);
1149
- if (expectedStreamVersion != null) {
1150
- const expectedStreamPositionAfterSave = BigInt(expectedStreamVersion) + BigInt(messages.length);
1151
- if (streamPosition !== expectedStreamPositionAfterSave) {
1152
- return {
1153
- success: false
1154
- };
1155
- }
1156
- }
1157
- const { sqlString, values } = buildMessageInsertQuery(
1158
- messages,
1159
- expectedStreamVersion,
1160
- streamId,
1161
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _34 => _34.partition, 'optionalAccess', _35 => _35.toString, 'call', _36 => _36()]), () => ( defaultTag2))
1162
- );
1163
- const returningIds = await connection.query(sqlString, values);
1164
- if (returningIds.length === 0 || !_optionalChain([returningIds, 'access', _37 => _37[returningIds.length - 1], 'optionalAccess', _38 => _38.global_position])) {
1165
- throw new Error("Could not find global position");
1166
- }
1167
- globalPosition = BigInt(
1168
- returningIds[returningIds.length - 1].global_position
1169
- );
1170
- } catch (err) {
1171
- if (isSQLiteError(err) && isOptimisticConcurrencyError(err)) {
1172
- return {
1173
- success: false
1174
- };
1175
- }
1176
- throw err;
1177
- }
803
+ `;
804
+ const insertSQL = buildMessageInsertQuery(
805
+ messages,
806
+ expectedStreamVersion,
807
+ streamId,
808
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.partition, 'optionalAccess', _27 => _27.toString, 'call', _28 => _28()]), () => ( defaultTag2))
809
+ );
810
+ const results = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
811
+ const [streamResult, messagesResult] = results;
812
+ const streamPosition = _optionalChain([streamResult, 'optionalAccess', _29 => _29.rows, 'access', _30 => _30[0], 'optionalAccess', _31 => _31.stream_position]);
813
+ const globalPosition = _optionalChain([messagesResult, 'optionalAccess', _32 => _32.rows, 'access', _33 => _33.at, 'call', _34 => _34(-1), 'optionalAccess', _35 => _35.global_position]);
814
+ if (!streamPosition)
815
+ throw new ExpectedVersionConflictError(0n, _nullishCoalesce(expectedStreamVersion, () => ( 0n)));
816
+ if (!globalPosition) throw new Error("Could not find global position");
1178
817
  return {
1179
818
  success: true,
1180
- nextStreamPosition: streamPosition,
1181
- lastGlobalPosition: globalPosition
819
+ nextStreamPosition: BigInt(streamPosition),
820
+ lastGlobalPosition: BigInt(globalPosition)
1182
821
  };
1183
822
  };
1184
- var isOptimisticConcurrencyError = (error) => {
1185
- return _optionalChain([error, 'optionalAccess', _39 => _39.errno]) !== void 0 && error.errno === 19;
1186
- };
1187
- async function getLastStreamPosition(connection, streamId, expectedStreamVersion) {
1188
- const result = await connection.querySingle(
1189
- `SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${streamsTable.name} WHERE stream_id = ?`,
1190
- [streamId]
823
+ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
824
+ const result = await _dumbo.singleOrNull.call(void 0,
825
+ execute.query(
826
+ _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier3(streamsTable.name)} WHERE stream_id = ${streamId}`
827
+ )
1191
828
  );
1192
- if (_optionalChain([result, 'optionalAccess', _40 => _40.stream_position]) == null) {
829
+ if (_optionalChain([result, 'optionalAccess', _36 => _36.stream_position]) == null) {
1193
830
  expectedStreamVersion = 0n;
1194
831
  } else {
1195
832
  expectedStreamVersion = BigInt(result.stream_position);
@@ -1197,34 +834,15 @@ async function getLastStreamPosition(connection, streamId, expectedStreamVersion
1197
834
  return expectedStreamVersion;
1198
835
  }
1199
836
  var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
1200
- const query = messages.reduce(
1201
- (queryBuilder, message) => {
1202
- if (_optionalChain([message, 'access', _41 => _41.metadata, 'optionalAccess', _42 => _42.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1203
- throw new Error("Stream position is required");
1204
- }
1205
- const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
1206
- queryBuilder.parameterMarkers.push(`(?,?,?,?,?,?,?,?,?,?)`);
1207
- queryBuilder.values.push(
1208
- streamId,
1209
- _nullishCoalesce(streamPosition.toString(), () => ( 0)),
1210
- _nullishCoalesce(partition, () => ( defaultTag2)),
1211
- message.kind === "Event" ? "E" : "C",
1212
- JSONParser.stringify(message.data),
1213
- JSONParser.stringify(message.metadata),
1214
- _nullishCoalesce(_optionalChain([expectedStreamVersion, 'optionalAccess', _43 => _43.toString, 'call', _44 => _44()]), () => ( 0)),
1215
- message.type,
1216
- message.metadata.messageId,
1217
- false
1218
- );
1219
- return queryBuilder;
1220
- },
1221
- {
1222
- parameterMarkers: [],
1223
- values: []
837
+ const values = messages.map((message) => {
838
+ if (_optionalChain([message, 'access', _37 => _37.metadata, 'optionalAccess', _38 => _38.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
839
+ throw new Error("Stream position is required");
1224
840
  }
1225
- );
1226
- const sqlString = `
1227
- INSERT INTO ${messagesTable.name} (
841
+ const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
842
+ return _dumbo.SQL`(${streamId},${_nullishCoalesce(streamPosition, () => ( 0n))},${_nullishCoalesce(partition, () => ( defaultTag2))},${message.kind === "Event" ? "E" : "C"},${message.data},${message.metadata},${_nullishCoalesce(expectedStreamVersion, () => ( 0n))},${message.type},${message.metadata.messageId},${false})`;
843
+ });
844
+ return _dumbo.SQL`
845
+ INSERT INTO ${identifier3(messagesTable.name)} (
1228
846
  stream_id,
1229
847
  stream_position,
1230
848
  partition,
@@ -1236,24 +854,155 @@ var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partit
1236
854
  message_id,
1237
855
  is_archived
1238
856
  )
1239
- VALUES ${query.parameterMarkers.join(", ")}
857
+ VALUES ${merge(values, ",")}
1240
858
  RETURNING
1241
859
  CAST(global_position as VARCHAR) AS global_position
1242
860
  `;
1243
- return { sqlString, values: query.values };
1244
861
  };
1245
862
 
863
+ // src/eventStore/schema/migrations/0_41_0/0_41_0.snapshot.ts
864
+
865
+ var schema_0_41_0 = [
866
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
867
+ stream_id TEXT NOT NULL,
868
+ stream_position BIGINT NOT NULL DEFAULT 0,
869
+ partition TEXT NOT NULL DEFAULT 'global',
870
+ stream_type TEXT NOT NULL,
871
+ stream_metadata JSONB NOT NULL,
872
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
873
+ PRIMARY KEY (stream_id, partition, is_archived),
874
+ UNIQUE (stream_id, partition, is_archived)
875
+ )`,
876
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
877
+ stream_id TEXT NOT NULL,
878
+ stream_position BIGINT NOT NULL,
879
+ partition TEXT NOT NULL DEFAULT 'global',
880
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
881
+ message_data JSONB NOT NULL,
882
+ message_metadata JSONB NOT NULL,
883
+ message_schema_version TEXT NOT NULL,
884
+ message_type TEXT NOT NULL,
885
+ message_id TEXT NOT NULL,
886
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
887
+ global_position INTEGER PRIMARY KEY,
888
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
889
+ UNIQUE (stream_id, stream_position, partition, is_archived)
890
+ )`,
891
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_subscriptions(
892
+ subscription_id TEXT NOT NULL,
893
+ version INTEGER NOT NULL DEFAULT 1,
894
+ partition TEXT NOT NULL DEFAULT 'global',
895
+ last_processed_position BIGINT NOT NULL,
896
+ PRIMARY KEY (subscription_id, partition, version)
897
+ )`
898
+ ];
899
+
900
+ // src/eventStore/schema/migrations/0_42_0/0_42_0.migration.ts
901
+
902
+ var { identifier: identifier4, plain } = _dumbo.SQL;
903
+ var migration_0_42_0_SQLs = [
904
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier4(processorsTable.name)}(
905
+ processor_id TEXT NOT NULL,
906
+ version INTEGER NOT NULL DEFAULT 1,
907
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
908
+ status TEXT NOT NULL DEFAULT 'stopped',
909
+ last_processed_checkpoint TEXT NOT NULL,
910
+ processor_instance_id TEXT DEFAULT 'emt:unknown',
911
+ PRIMARY KEY (processor_id, partition, version)
912
+ )`,
913
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier4(projectionsTable.name)}(
914
+ name TEXT NOT NULL,
915
+ version INTEGER NOT NULL DEFAULT 1,
916
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
917
+ type CHAR(1) NOT NULL,
918
+ kind TEXT NOT NULL,
919
+ status TEXT NOT NULL,
920
+ definition JSONB NOT NULL DEFAULT '{}',
921
+ PRIMARY KEY (name, partition, version)
922
+ )`,
923
+ _dumbo.SQL`INSERT INTO ${identifier4(processorsTable.name)}
924
+ (processor_id, version, partition, status, last_processed_checkpoint, processor_instance_id)
925
+ SELECT
926
+ subscription_id,
927
+ version,
928
+ partition,
929
+ 'stopped',
930
+ printf('%019d', last_processed_position),
931
+ 'emt:unknown'
932
+ FROM emt_subscriptions`,
933
+ _dumbo.SQL`DROP TABLE emt_subscriptions`
934
+ ];
935
+ var migration_0_42_0_FromSubscriptionsToProcessors = async (execute) => {
936
+ const tableExists = await _dumbo.singleOrNull.call(void 0,
937
+ execute.query(
938
+ _dumbo.SQL`SELECT name FROM sqlite_master WHERE type='table' AND name='emt_subscriptions'`
939
+ )
940
+ );
941
+ if (!tableExists) {
942
+ return;
943
+ }
944
+ await execute.batchCommand(migration_0_42_0_SQLs);
945
+ };
946
+
947
+ // src/eventStore/schema/migrations/0_42_0/0_42_0.snapshot.ts
948
+
949
+ var schema_0_42_0 = [
950
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
951
+ stream_id TEXT NOT NULL,
952
+ stream_position BIGINT NOT NULL DEFAULT 0,
953
+ partition TEXT NOT NULL DEFAULT 'global',
954
+ stream_type TEXT NOT NULL,
955
+ stream_metadata JSONB NOT NULL,
956
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
957
+ PRIMARY KEY (stream_id, partition, is_archived),
958
+ UNIQUE (stream_id, partition, is_archived)
959
+ )`,
960
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
961
+ stream_id TEXT NOT NULL,
962
+ stream_position BIGINT NOT NULL,
963
+ partition TEXT NOT NULL DEFAULT 'global',
964
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
965
+ message_data JSONB NOT NULL,
966
+ message_metadata JSONB NOT NULL,
967
+ message_schema_version TEXT NOT NULL,
968
+ message_type TEXT NOT NULL,
969
+ message_id TEXT NOT NULL,
970
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
971
+ global_position INTEGER PRIMARY KEY,
972
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
973
+ UNIQUE (stream_id, stream_position, partition, is_archived)
974
+ )`,
975
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_processors(
976
+ processor_id TEXT NOT NULL,
977
+ version INTEGER NOT NULL DEFAULT 1,
978
+ partition TEXT NOT NULL DEFAULT 'global',
979
+ status TEXT NOT NULL DEFAULT 'stopped',
980
+ last_processed_checkpoint TEXT NOT NULL,
981
+ processor_instance_id TEXT DEFAULT 'emt:unknown',
982
+ PRIMARY KEY (processor_id, partition, version)
983
+ )`,
984
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_projections(
985
+ name TEXT NOT NULL,
986
+ version INTEGER NOT NULL DEFAULT 1,
987
+ partition TEXT NOT NULL DEFAULT 'global',
988
+ type CHAR(1) NOT NULL,
989
+ kind TEXT NOT NULL,
990
+ status TEXT NOT NULL,
991
+ definition JSONB NOT NULL DEFAULT '{}',
992
+ PRIMARY KEY (name, partition, version)
993
+ )`
994
+ ];
995
+
1246
996
  // src/eventStore/schema/readProcessorCheckpoint.ts
1247
- var readProcessorCheckpoint = async (db, options) => {
1248
- const result = await singleOrNull(
1249
- db.query(
1250
- sql(
1251
- `SELECT last_processed_checkpoint
1252
- FROM ${processorsTable.name}
1253
- WHERE partition = ? AND processor_id = ?
997
+
998
+ var { identifier: identifier5 } = _dumbo.SQL;
999
+ var readProcessorCheckpoint = async (execute, options) => {
1000
+ const result = await _dumbo.singleOrNull.call(void 0,
1001
+ execute.query(
1002
+ _dumbo.SQL`SELECT last_processed_checkpoint
1003
+ FROM ${identifier5(processorsTable.name)}
1004
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _39 => _39.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1254
1005
  LIMIT 1`
1255
- ),
1256
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _45 => _45.partition]), () => ( defaultTag2)), options.processorId]
1257
1006
  )
1258
1007
  );
1259
1008
  return {
@@ -1262,18 +1011,19 @@ var readProcessorCheckpoint = async (db, options) => {
1262
1011
  };
1263
1012
 
1264
1013
  // src/eventStore/schema/readStream.ts
1265
- var readStream = async (db, streamId, options) => {
1266
- const fromCondition = _optionalChain([options, 'optionalAccess', _46 => _46.from]) ? `AND stream_position >= ${options.from}` : "";
1014
+
1015
+ var { identifier: identifier6 } = _dumbo.SQL;
1016
+ var readStream = async (execute, streamId, options) => {
1017
+ const fromCondition = _optionalChain([options, 'optionalAccess', _40 => _40.from]) ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
1267
1018
  const to = Number(
1268
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _47 => _47.to]), () => ( (_optionalChain([options, 'optionalAccess', _48 => _48.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
1019
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _41 => _41.to]), () => ( (_optionalChain([options, 'optionalAccess', _42 => _42.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
1269
1020
  );
1270
- const toCondition = !isNaN(to) ? `AND stream_position <= ${to}` : "";
1271
- const results = await db.query(
1272
- `SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1273
- FROM ${messagesTable.name}
1274
- WHERE stream_id = ? AND partition = ? AND is_archived = FALSE ${fromCondition} ${toCondition}
1275
- ORDER BY stream_position ASC`,
1276
- [streamId, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _49 => _49.partition]), () => ( defaultTag2))]
1021
+ const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
1022
+ const { rows: results } = await execute.query(
1023
+ _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1024
+ FROM ${identifier6(messagesTable.name)}
1025
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _43 => _43.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1026
+ ORDER BY stream_position ASC`
1277
1027
  );
1278
1028
  const messages = results.map((row) => {
1279
1029
  const rawEvent = {
@@ -1293,7 +1043,7 @@ var readStream = async (db, streamId, options) => {
1293
1043
  kind: "Event",
1294
1044
  metadata
1295
1045
  };
1296
- return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _50 => _50.schema, 'optionalAccess', _51 => _51.versioning]));
1046
+ return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _44 => _44.schema, 'optionalAccess', _45 => _45.versioning]));
1297
1047
  });
1298
1048
  return messages.length > 0 ? {
1299
1049
  currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
@@ -1307,76 +1057,66 @@ var readStream = async (db, streamId, options) => {
1307
1057
  };
1308
1058
 
1309
1059
  // src/eventStore/schema/storeProcessorCheckpoint.ts
1310
- async function storeSubscriptionCheckpointSQLite(db, processorId, version, position, checkPosition, partition, processorInstanceId) {
1060
+
1061
+
1062
+
1063
+
1064
+
1065
+
1066
+ var { identifier: identifier7 } = _dumbo.SQL;
1067
+ async function storeSubscriptionCheckpointSQLite(execute, processorId, version, position, checkPosition, partition, processorInstanceId) {
1311
1068
  processorInstanceId ??= unknownTag2;
1312
1069
  if (checkPosition !== null) {
1313
- const updateResult = await db.command(
1314
- sql(`
1315
- UPDATE ${processorsTable.name}
1070
+ const updateResult = await execute.command(
1071
+ _dumbo.SQL`
1072
+ UPDATE ${identifier7(processorsTable.name)}
1316
1073
  SET
1317
- last_processed_checkpoint = ?,
1318
- processor_instance_id = ?
1319
- WHERE processor_id = ?
1320
- AND last_processed_checkpoint = ?
1321
- AND partition = ?
1322
- `),
1323
- [
1324
- bigInt.toNormalizedString(position),
1325
- processorInstanceId,
1326
- processorId,
1327
- bigInt.toNormalizedString(checkPosition),
1328
- partition
1329
- ]
1074
+ last_processed_checkpoint = ${position},
1075
+ processor_instance_id = ${processorInstanceId}
1076
+ WHERE processor_id = ${processorId}
1077
+ AND last_processed_checkpoint = ${checkPosition}
1078
+ AND partition = ${partition}
1079
+ `
1330
1080
  );
1331
- if (updateResult.changes > 0) {
1081
+ if (updateResult.rowCount && updateResult.rowCount > 0) {
1332
1082
  return 1;
1083
+ }
1084
+ const current_position = await _dumbo.singleOrNull.call(void 0,
1085
+ execute.query(
1086
+ _dumbo.SQL`
1087
+ SELECT last_processed_checkpoint FROM ${identifier7(processorsTable.name)}
1088
+ WHERE processor_id = ${processorId} AND partition = ${partition}`
1089
+ )
1090
+ );
1091
+ const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _46 => _46.last_processed_checkpoint]) !== null ? BigInt(current_position.last_processed_checkpoint) : null;
1092
+ if (currentPosition === position) {
1093
+ return 0;
1094
+ } else if (position !== null && currentPosition !== null && currentPosition > position) {
1095
+ return 2;
1333
1096
  } else {
1334
- const current_position = await singleOrNull(
1335
- db.query(
1336
- sql(
1337
- `SELECT last_processed_checkpoint FROM ${processorsTable.name}
1338
- WHERE processor_id = ? AND partition = ?`
1339
- ),
1340
- [processorId, partition]
1341
- )
1342
- );
1343
- const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _52 => _52.last_processed_checkpoint]) !== null ? BigInt(current_position.last_processed_checkpoint) : null;
1344
- if (currentPosition === position) {
1345
- return 0;
1346
- } else if (position !== null && currentPosition !== null && currentPosition > position) {
1347
- return 2;
1348
- } else {
1349
- return 2;
1350
- }
1097
+ return 2;
1351
1098
  }
1352
1099
  } else {
1353
1100
  try {
1354
- await db.command(
1355
- sql(
1356
- `INSERT INTO ${processorsTable.name} (processor_id, version, last_processed_checkpoint, partition, processor_instance_id) VALUES (?, ?, ?, ?, ?)`
1357
- ),
1358
- [
1359
- processorId,
1360
- version,
1361
- bigInt.toNormalizedString(position),
1362
- partition,
1363
- processorInstanceId
1364
- ]
1101
+ await execute.command(
1102
+ _dumbo.SQL`INSERT INTO ${identifier7(processorsTable.name)} (processor_id, version, last_processed_checkpoint, partition, processor_instance_id)
1103
+ VALUES (${processorId}, ${version}, ${position}, ${partition}, ${processorInstanceId})`
1365
1104
  );
1366
1105
  return 1;
1367
1106
  } catch (err) {
1368
- if (!(isSQLiteError(err) && (err.errno === 19 || err.errno === 2067))) {
1107
+ if (!_dumbo.DumboError.isInstanceOf(err, {
1108
+ errorType: _dumbo.UniqueConstraintError.ErrorType
1109
+ })) {
1369
1110
  throw err;
1370
1111
  }
1371
- const current = await singleOrNull(
1372
- db.query(
1373
- sql(
1374
- `SELECT last_processed_checkpoint FROM ${processorsTable.name} WHERE processor_id = ? AND partition = ?`
1375
- ),
1376
- [processorId, partition]
1112
+ const current = await _dumbo.singleOrNull.call(void 0,
1113
+ execute.query(
1114
+ _dumbo.SQL`
1115
+ SELECT last_processed_checkpoint FROM ${identifier7(processorsTable.name)}
1116
+ WHERE processor_id = ${processorId} AND partition = ${partition}`
1377
1117
  )
1378
1118
  );
1379
- const currentPosition = current && _optionalChain([current, 'optionalAccess', _53 => _53.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
1119
+ const currentPosition = current && _optionalChain([current, 'optionalAccess', _47 => _47.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
1380
1120
  if (currentPosition === position) {
1381
1121
  return 0;
1382
1122
  } else {
@@ -1385,10 +1125,10 @@ async function storeSubscriptionCheckpointSQLite(db, processorId, version, posit
1385
1125
  }
1386
1126
  }
1387
1127
  }
1388
- async function storeProcessorCheckpoint(db, options) {
1128
+ async function storeProcessorCheckpoint(execute, options) {
1389
1129
  try {
1390
1130
  const result = await storeSubscriptionCheckpointSQLite(
1391
- db,
1131
+ execute,
1392
1132
  options.processorId,
1393
1133
  _nullishCoalesce(options.version, () => ( 1)),
1394
1134
  options.newPosition,
@@ -1402,31 +1142,113 @@ async function storeProcessorCheckpoint(db, options) {
1402
1142
  }
1403
1143
  }
1404
1144
 
1145
+ // src/eventStore/schema/streamExists.ts
1146
+
1147
+ var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
1148
+ execute.query(
1149
+ _dumbo.SQL`SELECT EXISTS (
1150
+ SELECT 1
1151
+ from ${_dumbo.SQL.identifier(streamsTable.name)}
1152
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _48 => _48.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
1153
+ `
1154
+ )
1155
+ );
1156
+
1157
+ // src/eventStore/schema/tables.ts
1158
+
1159
+
1160
+ var { identifier: identifier8, plain: plain2 } = _dumbo.SQL;
1161
+ var streamsTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(streamsTable.name)}(
1162
+ stream_id TEXT NOT NULL,
1163
+ stream_position BIGINT NOT NULL DEFAULT 0,
1164
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1165
+ stream_type TEXT NOT NULL,
1166
+ stream_metadata JSONB NOT NULL,
1167
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1168
+ PRIMARY KEY (stream_id, partition, is_archived),
1169
+ UNIQUE (stream_id, partition, is_archived)
1170
+ );`;
1171
+ var messagesTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(messagesTable.name)}(
1172
+ stream_id TEXT NOT NULL,
1173
+ stream_position BIGINT NOT NULL,
1174
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1175
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
1176
+ message_data JSONB NOT NULL,
1177
+ message_metadata JSONB NOT NULL,
1178
+ message_schema_version TEXT NOT NULL,
1179
+ message_type TEXT NOT NULL,
1180
+ message_id TEXT NOT NULL,
1181
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1182
+ global_position INTEGER PRIMARY KEY,
1183
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
1184
+ UNIQUE (stream_id, stream_position, partition, is_archived)
1185
+ );
1186
+ `;
1187
+ var processorsTableSQL = _dumbo.SQL`
1188
+ CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(processorsTable.name)}(
1189
+ processor_id TEXT NOT NULL,
1190
+ version INTEGER NOT NULL DEFAULT 1,
1191
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1192
+ status TEXT NOT NULL DEFAULT 'stopped',
1193
+ last_processed_checkpoint TEXT NOT NULL,
1194
+ processor_instance_id TEXT DEFAULT '${plain2(unknownTag2)}',
1195
+ PRIMARY KEY (processor_id, partition, version)
1196
+ );
1197
+ `;
1198
+ var projectionsTableSQL = _dumbo.SQL`
1199
+ CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(projectionsTable.name)}(
1200
+ name TEXT NOT NULL,
1201
+ version INTEGER NOT NULL DEFAULT 1,
1202
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1203
+ type CHAR(1) NOT NULL,
1204
+ kind TEXT NOT NULL,
1205
+ status TEXT NOT NULL,
1206
+ definition JSONB NOT NULL DEFAULT '{}',
1207
+ PRIMARY KEY (name, partition, version)
1208
+ );
1209
+ `;
1210
+ var schemaSQL = [
1211
+ streamsTableSQL,
1212
+ messagesTableSQL,
1213
+ processorsTableSQL,
1214
+ projectionsTableSQL
1215
+ ];
1216
+ var createEventStoreSchema = async (pool, hooks) => {
1217
+ await pool.withTransaction(async (tx) => {
1218
+ await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
1219
+ if (_optionalChain([hooks, 'optionalAccess', _49 => _49.onBeforeSchemaCreated])) {
1220
+ await hooks.onBeforeSchemaCreated({
1221
+ connection: tx.connection
1222
+ });
1223
+ }
1224
+ await tx.execute.batchCommand(schemaSQL);
1225
+ if (_optionalChain([hooks, 'optionalAccess', _50 => _50.onAfterSchemaCreated])) {
1226
+ await hooks.onAfterSchemaCreated();
1227
+ }
1228
+ });
1229
+ };
1230
+
1405
1231
  // src/eventStore/consumers/sqliteProcessor.ts
1406
1232
  var genericSQLiteProcessor = (options) => {
1407
1233
  const { eachMessage } = options;
1408
1234
  let isActive = true;
1409
- const getDb = (context) => {
1410
- const fileName = _nullishCoalesce(context.fileName, () => ( _optionalChain([options, 'access', _54 => _54.connectionOptions, 'optionalAccess', _55 => _55.fileName])));
1411
- if (!fileName)
1412
- throw new EmmettError(
1413
- `SQLite processor '${options.processorId}' is missing file name. Ensure that you passed it through options`
1414
- );
1415
- const connection = _nullishCoalesce(_nullishCoalesce(context.connection, () => ( _optionalChain([options, 'access', _56 => _56.connectionOptions, 'optionalAccess', _57 => _57.connection]))), () => ( sqliteConnection({ fileName })));
1416
- return { connection, fileName };
1235
+ const mapToContext = (context) => {
1236
+ const connection = _nullishCoalesce(context.connection, () => ( _optionalChain([options, 'access', _51 => _51.connectionOptions, 'optionalAccess', _52 => _52.connection])));
1237
+ if (!connection)
1238
+ throw new Error("Connection is required in context or options");
1239
+ return { connection };
1417
1240
  };
1418
1241
  return {
1419
1242
  id: options.processorId,
1420
- start: async (connection) => {
1243
+ start: async ({
1244
+ execute
1245
+ }) => {
1421
1246
  isActive = true;
1422
1247
  if (options.startFrom !== "CURRENT") return options.startFrom;
1423
- const { lastProcessedPosition } = await readProcessorCheckpoint(
1424
- connection,
1425
- {
1426
- processorId: options.processorId,
1427
- partition: options.partition
1428
- }
1429
- );
1248
+ const { lastProcessedPosition } = await readProcessorCheckpoint(execute, {
1249
+ processorId: options.processorId,
1250
+ partition: options.partition
1251
+ });
1430
1252
  if (lastProcessedPosition === null) return "BEGINNING";
1431
1253
  return { globalPosition: lastProcessedPosition };
1432
1254
  },
@@ -1435,18 +1257,17 @@ var genericSQLiteProcessor = (options) => {
1435
1257
  },
1436
1258
  handle: async ({ messages }, context) => {
1437
1259
  if (!isActive) return;
1438
- const { connection, fileName } = getDb(context);
1439
- return connection.withTransaction(async () => {
1260
+ const { connection } = mapToContext(context);
1261
+ return connection.withTransaction(async (tx) => {
1440
1262
  let result = void 0;
1441
1263
  let lastProcessedPosition = null;
1442
1264
  for (const message of messages) {
1443
1265
  const typedMessage = message;
1444
1266
  const messageProcessingResult = await eachMessage(typedMessage, {
1445
- connection,
1446
- fileName
1267
+ connection: tx.connection
1447
1268
  });
1448
1269
  const newPosition = getCheckpoint(typedMessage);
1449
- await storeProcessorCheckpoint(connection, {
1270
+ await storeProcessorCheckpoint(tx.execute, {
1450
1271
  processorId: options.processorId,
1451
1272
  version: options.version,
1452
1273
  lastProcessedPosition,
@@ -1497,7 +1318,13 @@ var sqliteEventStoreConsumer = (options) => {
1497
1318
  const processors = _nullishCoalesce(options.processors, () => ( []));
1498
1319
  let start;
1499
1320
  let currentMessagePuller;
1500
- const pool = _nullishCoalesce(options.pool, () => ( SQLiteConnectionPool(options)));
1321
+ const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1322
+ transactionOptions: {
1323
+ allowNestedTransactions: true,
1324
+ mode: "session_based"
1325
+ },
1326
+ ...options
1327
+ })));
1501
1328
  const eachBatch = (messagesBatch) => pool.withConnection(async (connection) => {
1502
1329
  const activeProcessors = processors.filter((s) => s.isActive);
1503
1330
  if (activeProcessors.length === 0)
@@ -1508,13 +1335,12 @@ var sqliteEventStoreConsumer = (options) => {
1508
1335
  const result = await Promise.allSettled(
1509
1336
  activeProcessors.map((s) => {
1510
1337
  return s.handle(messagesBatch, {
1511
- connection,
1512
- fileName: options.fileName
1338
+ connection
1513
1339
  });
1514
1340
  })
1515
1341
  );
1516
1342
  return result.some(
1517
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _58 => _58.value, 'optionalAccess', _59 => _59.type]) !== "STOP"
1343
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _53 => _53.value, 'optionalAccess', _54 => _54.type]) !== "STOP"
1518
1344
  ) ? void 0 : {
1519
1345
  type: "STOP"
1520
1346
  };
@@ -1522,8 +1348,8 @@ var sqliteEventStoreConsumer = (options) => {
1522
1348
  const messagePooler = currentMessagePuller = sqliteEventStoreMessageBatchPuller({
1523
1349
  pool,
1524
1350
  eachBatch,
1525
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _60 => _60.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
1526
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _61 => _61.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs))
1351
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _55 => _55.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
1352
+ pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _56 => _56.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs))
1527
1353
  });
1528
1354
  const stop = async () => {
1529
1355
  if (!isRunning) return;
@@ -1572,34 +1398,26 @@ var sqliteEventStoreConsumer = (options) => {
1572
1398
  };
1573
1399
  };
1574
1400
 
1575
- // src/eventStore/schema/streamExists.ts
1576
- var streamExists = async (db, streamId, options) => {
1577
- const queryResult = await db.query(
1578
- `SELECT EXISTS (
1579
- SELECT 1
1580
- from ${streamsTable.name}
1581
- WHERE stream_id = ? AND partition = ? AND is_archived = FALSE)
1582
- `,
1583
- [streamId, _nullishCoalesce(_optionalChain([options, 'optionalAccess', _62 => _62.partition]), () => ( defaultTag2))]
1584
- );
1585
- return _nullishCoalesce(_optionalChain([queryResult, 'access', _63 => _63[0], 'optionalAccess', _64 => _64.exists]), () => ( false));
1586
- };
1587
-
1588
1401
  // src/eventStore/SQLiteEventStore.ts
1589
1402
  var SQLiteEventStoreDefaultStreamVersion = 0n;
1590
1403
  var getSQLiteEventStore = (options) => {
1591
1404
  let autoGenerateSchema = false;
1592
- const fileName = _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase));
1593
- const pool = _nullishCoalesce(options.pool, () => ( SQLiteConnectionPool(options)));
1405
+ const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1406
+ transactionOptions: {
1407
+ allowNestedTransactions: true,
1408
+ mode: "session_based"
1409
+ },
1410
+ ...options
1411
+ })));
1594
1412
  let migrateSchema = void 0;
1595
1413
  const inlineProjections = (_nullishCoalesce(options.projections, () => ( []))).filter(({ type }) => type === "inline").map(({ projection: projection2 }) => projection2);
1596
- const onBeforeCommitHook = _optionalChain([options, 'access', _65 => _65.hooks, 'optionalAccess', _66 => _66.onBeforeCommit]);
1597
- const withConnection = async (handler) => pool.withConnection(async (database) => {
1598
- await ensureSchemaExists(database);
1599
- return await handler(database);
1414
+ const onBeforeCommitHook = _optionalChain([options, 'access', _57 => _57.hooks, 'optionalAccess', _58 => _58.onBeforeCommit]);
1415
+ const withConnection = async (handler) => pool.withConnection(async (connection) => {
1416
+ await ensureSchemaExists(connection);
1417
+ return await handler(connection);
1600
1418
  });
1601
1419
  if (options) {
1602
- autoGenerateSchema = _optionalChain([options, 'access', _67 => _67.schema, 'optionalAccess', _68 => _68.autoMigration]) === void 0 || _optionalChain([options, 'access', _69 => _69.schema, 'optionalAccess', _70 => _70.autoMigration]) !== "None";
1420
+ autoGenerateSchema = _optionalChain([options, 'access', _59 => _59.schema, 'optionalAccess', _60 => _60.autoMigration]) === void 0 || _optionalChain([options, 'access', _61 => _61.schema, 'optionalAccess', _62 => _62.autoMigration]) !== "None";
1603
1421
  }
1604
1422
  const migrate = (connection) => {
1605
1423
  if (!migrateSchema) {
@@ -1615,11 +1433,11 @@ var getSQLiteEventStore = (options) => {
1615
1433
  });
1616
1434
  }
1617
1435
  }
1618
- if (_optionalChain([options, 'access', _71 => _71.hooks, 'optionalAccess', _72 => _72.onBeforeSchemaCreated])) {
1436
+ if (_optionalChain([options, 'access', _63 => _63.hooks, 'optionalAccess', _64 => _64.onBeforeSchemaCreated])) {
1619
1437
  await options.hooks.onBeforeSchemaCreated(context);
1620
1438
  }
1621
1439
  },
1622
- onAfterSchemaCreated: _optionalChain([options, 'access', _73 => _73.hooks, 'optionalAccess', _74 => _74.onAfterSchemaCreated])
1440
+ onAfterSchemaCreated: _optionalChain([options, 'access', _65 => _65.hooks, 'optionalAccess', _66 => _66.onAfterSchemaCreated])
1623
1441
  });
1624
1442
  }
1625
1443
  return migrateSchema;
@@ -1631,13 +1449,13 @@ var getSQLiteEventStore = (options) => {
1631
1449
  return {
1632
1450
  async aggregateStream(streamName, options2) {
1633
1451
  const { evolve, initialState, read } = options2;
1634
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _75 => _75.expectedStreamVersion]);
1452
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _67 => _67.expectedStreamVersion]);
1635
1453
  let state = initialState();
1636
1454
  if (typeof streamName !== "string") {
1637
1455
  throw new Error("Stream name is not string");
1638
1456
  }
1639
1457
  const result = await withConnection(
1640
- (connection) => readStream(connection, streamName, read)
1458
+ ({ execute }) => readStream(execute, streamName, read)
1641
1459
  );
1642
1460
  const currentStreamVersion = result.currentStreamVersion;
1643
1461
  assertExpectedVersionMatchesCurrent(
@@ -1656,11 +1474,7 @@ var getSQLiteEventStore = (options) => {
1656
1474
  };
1657
1475
  },
1658
1476
  readStream: async (streamName, options2) => withConnection(
1659
- (connection) => readStream(
1660
- connection,
1661
- streamName,
1662
- options2
1663
- )
1477
+ ({ execute }) => readStream(execute, streamName, options2)
1664
1478
  ),
1665
1479
  appendToStream: async (streamName, events, options2) => {
1666
1480
  const [firstPart, ...rest] = streamName.split("-");
@@ -1683,7 +1497,7 @@ var getSQLiteEventStore = (options) => {
1683
1497
  throw new ExpectedVersionConflictError(
1684
1498
  -1n,
1685
1499
  //TODO: Return actual version in case of error
1686
- _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _76 => _76.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1500
+ _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _68 => _68.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1687
1501
  );
1688
1502
  return {
1689
1503
  nextExpectedStreamVersion: appendResult.nextStreamPosition,
@@ -1693,14 +1507,15 @@ var getSQLiteEventStore = (options) => {
1693
1507
  },
1694
1508
  streamExists(streamName, options2) {
1695
1509
  return withConnection(
1696
- (connection) => streamExists(connection, streamName, options2)
1510
+ ({ execute }) => streamExists(execute, streamName, options2)
1697
1511
  );
1698
1512
  },
1699
- consumer: (options2) => sqliteEventStoreConsumer({
1700
- ..._nullishCoalesce(options2, () => ( {})),
1701
- fileName,
1513
+ consumer: (consumerOptions) => sqliteEventStoreConsumer({
1514
+ ..._nullishCoalesce(options, () => ( {})),
1515
+ ..._nullishCoalesce(consumerOptions, () => ( {})),
1702
1516
  pool
1703
1517
  }),
1518
+ close: () => pool.close(),
1704
1519
  schema: {
1705
1520
  sql: () => schemaSQL.join(""),
1706
1521
  print: () => console.log(schemaSQL.join("")),
@@ -1713,8 +1528,12 @@ var getSQLiteEventStore = (options) => {
1713
1528
  var SQLiteProjectionSpec = {
1714
1529
  for: (options) => {
1715
1530
  {
1716
- const connection = _nullishCoalesce(options.connection, () => ( sqliteConnection({
1717
- fileName: _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase))
1531
+ const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1532
+ transactionOptions: {
1533
+ allowNestedTransactions: true,
1534
+ mode: "session_based"
1535
+ },
1536
+ ...options
1718
1537
  })));
1719
1538
  const projection2 = options.projection;
1720
1539
  let wasInitialized = false;
@@ -1722,9 +1541,9 @@ var SQLiteProjectionSpec = {
1722
1541
  return {
1723
1542
  when: (events, options2) => {
1724
1543
  const allEvents = [];
1725
- const run = async (connection2) => {
1544
+ const run = async (connection) => {
1726
1545
  let globalPosition = 0n;
1727
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _77 => _77.numberOfTimes]), () => ( 1));
1546
+ const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _69 => _69.numberOfTimes]), () => ( 1));
1728
1547
  for (const event of [
1729
1548
  ...givenEvents,
1730
1549
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
@@ -1748,62 +1567,58 @@ var SQLiteProjectionSpec = {
1748
1567
  await projection2.init({
1749
1568
  registrationType: "async",
1750
1569
  status: "active",
1751
- context: { connection: connection2 },
1570
+ context: { connection },
1752
1571
  version: _nullishCoalesce(projection2.version, () => ( 1))
1753
1572
  });
1754
1573
  wasInitialized = true;
1755
1574
  }
1756
- await connection2.withTransaction(
1575
+ await connection.withTransaction(
1757
1576
  () => handleProjections({
1758
1577
  events: allEvents,
1759
1578
  projections: [projection2],
1760
- connection: connection2
1579
+ connection
1761
1580
  })
1762
1581
  );
1763
1582
  };
1764
1583
  return {
1765
- then: async (assert, message) => {
1766
- try {
1767
- await run(connection);
1768
- const succeeded = await assert({
1769
- connection
1770
- });
1771
- if (succeeded !== void 0 && succeeded === false)
1772
- assertFails(
1773
- _nullishCoalesce(message, () => ( "Projection specification didn't match the criteria"))
1774
- );
1775
- } finally {
1776
- connection.close();
1777
- }
1778
- },
1779
- thenThrows: async (...args) => {
1584
+ then: (assert, message) => pool.withConnection(async (connection) => {
1585
+ await run(connection);
1586
+ const succeeded = await assert({
1587
+ connection
1588
+ });
1589
+ if (succeeded !== void 0 && succeeded === false)
1590
+ assertFails(
1591
+ _nullishCoalesce(message, () => ( "Projection specification didn't match the criteria"))
1592
+ );
1593
+ }),
1594
+ thenThrows: (...args) => pool.withConnection(async (connection) => {
1780
1595
  try {
1781
1596
  await run(connection);
1782
- throw new AssertionError("Handler did not fail as expected");
1597
+ throw new AssertionError(
1598
+ "Handler did not fail as expected"
1599
+ );
1783
1600
  } catch (error) {
1784
1601
  if (error instanceof AssertionError) throw error;
1785
1602
  if (args.length === 0) return;
1786
1603
  if (!isErrorConstructor(args[0])) {
1787
1604
  assertTrue(
1788
1605
  args[0](error),
1789
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _78 => _78.toString, 'call', _79 => _79()])}`
1606
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _70 => _70.toString, 'call', _71 => _71()])}`
1790
1607
  );
1791
1608
  return;
1792
1609
  }
1793
1610
  assertTrue(
1794
1611
  error instanceof args[0],
1795
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _80 => _80.toString, 'call', _81 => _81()])}`
1612
+ `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _72 => _72.toString, 'call', _73 => _73()])}`
1796
1613
  );
1797
1614
  if (args[1]) {
1798
1615
  assertTrue(
1799
1616
  args[1](error),
1800
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _82 => _82.toString, 'call', _83 => _83()])}`
1617
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _74 => _74.toString, 'call', _75 => _75()])}`
1801
1618
  );
1802
1619
  }
1803
- } finally {
1804
- connection.close();
1805
1620
  }
1806
- }
1621
+ })
1807
1622
  };
1808
1623
  }
1809
1624
  };
@@ -1816,7 +1631,7 @@ var eventInStream = (streamName, event) => {
1816
1631
  ...event,
1817
1632
  metadata: {
1818
1633
  ..._nullishCoalesce(event.metadata, () => ( {})),
1819
- streamName: _nullishCoalesce(_optionalChain([event, 'access', _84 => _84.metadata, 'optionalAccess', _85 => _85.streamName]), () => ( streamName))
1634
+ streamName: _nullishCoalesce(_optionalChain([event, 'access', _76 => _76.metadata, 'optionalAccess', _77 => _77.streamName]), () => ( streamName))
1820
1635
  }
1821
1636
  };
1822
1637
  };
@@ -1824,14 +1639,16 @@ var eventsInStream = (streamName, events) => {
1824
1639
  return events.map((e) => eventInStream(streamName, e));
1825
1640
  };
1826
1641
  var newEventsInStream = eventsInStream;
1827
- var assertSQLQueryResultMatches = (sql2, rows) => async ({ connection }) => {
1828
- const result = await connection.query(sql2);
1829
- assertThatArray(rows).containsExactlyInAnyOrder(result);
1642
+ var assertSQLQueryResultMatches = (sql, rows) => async ({
1643
+ connection
1644
+ }) => {
1645
+ const result = await connection.execute.query(sql);
1646
+ assertThatArray(rows).containsExactlyInAnyOrder(result.rows);
1830
1647
  };
1831
1648
  var expectSQL = {
1832
- query: (sql2) => ({
1649
+ query: (sql) => ({
1833
1650
  resultRows: {
1834
- toBeTheSame: (rows) => assertSQLQueryResultMatches(sql2, rows)
1651
+ toBeTheSame: (rows) => assertSQLQueryResultMatches(sql, rows)
1835
1652
  }
1836
1653
  })
1837
1654
  };
@@ -1874,10 +1691,5 @@ var expectSQL = {
1874
1691
 
1875
1692
 
1876
1693
 
1877
-
1878
-
1879
-
1880
-
1881
-
1882
- exports.InMemorySQLiteDatabase = InMemorySQLiteDatabase; exports.InMemorySharedCacheSQLiteDatabase = InMemorySharedCacheSQLiteDatabase; exports.SQLiteConnectionPool = SQLiteConnectionPool; exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion; exports.SQLiteProjectionSpec = SQLiteProjectionSpec; exports.appendToStream = appendToStream; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.createEventStoreSchema = createEventStoreSchema; exports.defaultTag = defaultTag2; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventsInStream = eventsInStream; exports.expectSQL = expectSQL; exports.getSQLiteEventStore = getSQLiteEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.isSQLiteError = isSQLiteError; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors; exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs; exports.newEventsInStream = newEventsInStream; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readStream = readStream; exports.schemaSQL = schemaSQL; exports.schema_0_41_0 = schema_0_41_0; exports.schema_0_42_0 = schema_0_42_0; exports.sql = sql; exports.sqliteConnection = sqliteConnection; exports.sqliteProjection = sqliteProjection; exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection; exports.sqliteRawSQLProjection = sqliteRawSQLProjection; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
1694
+ exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion; exports.SQLiteProjectionSpec = SQLiteProjectionSpec; exports.appendToStream = appendToStream; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.createEventStoreSchema = createEventStoreSchema; exports.defaultTag = defaultTag2; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventsInStream = eventsInStream; exports.expectSQL = expectSQL; exports.getSQLiteEventStore = getSQLiteEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors; exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs; exports.newEventsInStream = newEventsInStream; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readStream = readStream; exports.schemaSQL = schemaSQL; exports.schema_0_41_0 = schema_0_41_0; exports.schema_0_42_0 = schema_0_42_0; exports.sqliteProjection = sqliteProjection; exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection; exports.sqliteRawSQLProjection = sqliteRawSQLProjection; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
1883
1695
  //# sourceMappingURL=index.cjs.map