@event-driven-io/emmett-sqlite 0.42.0-rc.2 → 0.43.0-alpha.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.
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,7 +72,7 @@ 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
  };
@@ -430,10 +277,6 @@ var deepEquals = (left, right) => {
430
277
  var isEquatable = (left) => {
431
278
  return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
432
279
  };
433
- var toNormalizedString = (value) => value.toString().padStart(19, "0");
434
- var bigInt = {
435
- toNormalizedString
436
- };
437
280
  var ParseError = class extends Error {
438
281
  constructor(text) {
439
282
  super(`Cannot parse! ${text}`);
@@ -442,17 +285,17 @@ var ParseError = class extends Error {
442
285
  var JSONParser = {
443
286
  stringify: (value, options) => {
444
287
  return JSON.stringify(
445
- _optionalChain([options, 'optionalAccess', _14 => _14.map]) ? options.map(value) : value,
288
+ _optionalChain([options, 'optionalAccess', _8 => _8.map]) ? options.map(value) : value,
446
289
  //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
447
290
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
448
291
  (_, v) => typeof v === "bigint" ? v.toString() : v
449
292
  );
450
293
  },
451
294
  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)]))
295
+ const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _9 => _9.reviver]));
296
+ if (_optionalChain([options, 'optionalAccess', _10 => _10.typeCheck]) && !_optionalChain([options, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(parsed)]))
454
297
  throw new ParseError(text);
455
- return _optionalChain([options, 'optionalAccess', _19 => _19.map]) ? options.map(parsed) : parsed;
298
+ return _optionalChain([options, 'optionalAccess', _13 => _13.map]) ? options.map(parsed) : parsed;
456
299
  }
457
300
  };
458
301
  var textEncoder = new TextEncoder();
@@ -559,7 +402,7 @@ var assertThatArray = (array) => {
559
402
  };
560
403
  };
561
404
  var downcastRecordedMessage = (recordedMessage, options) => {
562
- if (!_optionalChain([options, 'optionalAccess', _20 => _20.downcast]))
405
+ if (!_optionalChain([options, 'optionalAccess', _14 => _14.downcast]))
563
406
  return recordedMessage;
564
407
  const downcasted = options.downcast(
565
408
  recordedMessage
@@ -577,14 +420,14 @@ var downcastRecordedMessage = (recordedMessage, options) => {
577
420
  };
578
421
  };
579
422
  var downcastRecordedMessages = (recordedMessages, options) => {
580
- if (!_optionalChain([options, 'optionalAccess', _21 => _21.downcast]))
423
+ if (!_optionalChain([options, 'optionalAccess', _15 => _15.downcast]))
581
424
  return recordedMessages;
582
425
  return recordedMessages.map(
583
426
  (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
584
427
  );
585
428
  };
586
429
  var upcastRecordedMessage = (recordedMessage, options) => {
587
- if (!_optionalChain([options, 'optionalAccess', _22 => _22.upcast]))
430
+ if (!_optionalChain([options, 'optionalAccess', _16 => _16.upcast]))
588
431
  return recordedMessage;
589
432
  const upcasted = options.upcast(
590
433
  recordedMessage
@@ -635,7 +478,7 @@ var sqliteRawBatchSQLProjection = (options) => sqliteProjection({
635
478
  canHandle: options.canHandle,
636
479
  handle: async (events, context) => {
637
480
  const sqls = await options.evolve(events, context);
638
- for (const sql2 of sqls) await context.connection.command(sql2);
481
+ for (const sql of sqls) await context.connection.execute.command(sql);
639
482
  },
640
483
  init: async (initOptions) => {
641
484
  if (options.init) {
@@ -643,8 +486,8 @@ var sqliteRawBatchSQLProjection = (options) => sqliteProjection({
643
486
  }
644
487
  if (options.initSQL) {
645
488
  const initSQLs = Array.isArray(options.initSQL) ? options.initSQL : [options.initSQL];
646
- for (const sql2 of initSQLs)
647
- await initOptions.context.connection.command(sql2);
489
+ for (const sql of initSQLs)
490
+ await initOptions.context.connection.execute.command(sql);
648
491
  }
649
492
  }
650
493
  });
@@ -670,41 +513,24 @@ var sqliteRawSQLProjection = (options) => {
670
513
  // src/eventStore/projections/sqliteProjectionSpec.ts
671
514
 
672
515
 
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
- ];
516
+ var _dumbo = require('@event-driven-io/dumbo');
517
+
518
+
519
+
520
+ var _sqlite3 = require('@event-driven-io/dumbo/sqlite3');
521
+
522
+
523
+ // src/eventStore/SQLiteEventStore.ts
524
+
525
+
526
+
527
+
528
+
529
+ // src/eventStore/consumers/messageBatchProcessing/index.ts
530
+
531
+
532
+ // src/eventStore/schema/readLastMessageGlobalPosition.ts
533
+
708
534
 
709
535
  // src/eventStore/schema/typing.ts
710
536
  var emmettPrefix2 = "emt";
@@ -741,196 +567,17 @@ var projectionsTable = {
741
567
  name: `${emmettPrefix2}_projections`
742
568
  };
743
569
 
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
570
  // 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
571
+ var { identifier } = _dumbo.SQL;
572
+ var readLastMessageGlobalPosition = async (execute, options) => {
573
+ const result = await _dumbo.singleOrNull.call(void 0,
574
+ execute.query(
575
+ _dumbo.SQL`
576
+ SELECT global_position
577
+ FROM ${identifier(messagesTable.name)}
578
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.partition]), () => ( defaultTag2))} AND is_archived = FALSE
930
579
  ORDER BY global_position
931
580
  LIMIT 1`
932
- ),
933
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _25 => _25.partition]), () => ( defaultTag2))]
934
581
  )
935
582
  );
936
583
  return {
@@ -939,22 +586,21 @@ var readLastMessageGlobalPosition = async (db, options) => {
939
586
  };
940
587
 
941
588
  // src/eventStore/schema/readMessagesBatch.ts
942
- var readMessagesBatch = async (db, options) => {
589
+
590
+ var { identifier: identifier2 } = _dumbo.SQL;
591
+ var readMessagesBatch = async (execute, options) => {
943
592
  const from = "from" in options ? options.from : "after" in options ? options.after + 1n : 0n;
944
593
  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}
594
+ const fromCondition = from !== -0n ? _dumbo.SQL`AND global_position >= ${from}` : "";
595
+ const toCondition = "to" in options ? _dumbo.SQL`AND global_position <= ${options.to}` : _dumbo.SQL.EMPTY;
596
+ const limitCondition = "batchSize" in options ? _dumbo.SQL`LIMIT ${options.batchSize}` : _dumbo.SQL.EMPTY;
597
+ const events = (await execute.query(
598
+ _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
599
+ FROM ${identifier2(messagesTable.name)}
600
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _18 => _18.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
953
601
  ORDER BY global_position
954
602
  ${limitCondition}`
955
- ),
956
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.partition]), () => ( defaultTag2))]
957
- )).map((row) => {
603
+ )).rows.map((row) => {
958
604
  const rawEvent = {
959
605
  type: row.message_type,
960
606
  data: JSONParser.parse(row.message_data),
@@ -997,7 +643,7 @@ var sqliteEventStoreMessageBatchPuller = ({
997
643
  let start;
998
644
  const pullMessages = async (options) => {
999
645
  const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await pool.withConnection(
1000
- async (connection) => readLastMessageGlobalPosition(connection)
646
+ async ({ execute }) => readLastMessageGlobalPosition(execute)
1001
647
  )).currentGlobalPosition, async () => ( 0n)) : options.startFrom.globalPosition;
1002
648
  const readMessagesOptions = {
1003
649
  after,
@@ -1006,7 +652,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1006
652
  let waitTime = 100;
1007
653
  do {
1008
654
  const { messages, currentGlobalPosition, areEventsLeft } = await pool.withConnection(
1009
- (connection) => readMessagesBatch(connection, readMessagesOptions)
655
+ ({ execute }) => readMessagesBatch(execute, readMessagesOptions)
1010
656
  );
1011
657
  if (messages.length > 0) {
1012
658
  const result = await eachBatch({ messages });
@@ -1050,12 +696,31 @@ var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
1050
696
  return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
1051
697
  };
1052
698
 
699
+ // src/eventStore/consumers/sqliteEventStoreConsumer.ts
700
+
701
+
702
+
703
+
704
+ // src/eventStore/consumers/sqliteProcessor.ts
705
+
706
+
707
+
708
+
709
+
1053
710
  // src/eventStore/schema/appendToStream.ts
1054
711
 
712
+
713
+
714
+
715
+
716
+
717
+
718
+
719
+ var { identifier: identifier3, merge } = _dumbo.SQL;
1055
720
  var appendToStream = async (connection, streamName, streamType, messages, options) => {
1056
721
  if (messages.length === 0) return { success: false };
1057
722
  const expectedStreamVersion = toExpectedVersion(
1058
- _optionalChain([options, 'optionalAccess', _27 => _27.expectedStreamVersion])
723
+ _optionalChain([options, 'optionalAccess', _19 => _19.expectedStreamVersion])
1059
724
  );
1060
725
  const messagesToAppend = messages.map(
1061
726
  (m, i) => ({
@@ -1069,21 +734,22 @@ var appendToStream = async (connection, streamName, streamType, messages, option
1069
734
  }
1070
735
  })
1071
736
  );
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
1081
- }
1082
- );
1083
- if (_optionalChain([options, 'optionalAccess', _30 => _30.onBeforeCommit]))
1084
- await options.onBeforeCommit(messagesToAppend, { connection });
1085
- return result;
1086
- });
737
+ return await connection.withTransaction(
738
+ async (transaction) => {
739
+ const result = await appendToStreamRaw(
740
+ transaction.execute,
741
+ streamName,
742
+ streamType,
743
+ downcastRecordedMessages(messagesToAppend, _optionalChain([options, 'optionalAccess', _20 => _20.schema, 'optionalAccess', _21 => _21.versioning])),
744
+ {
745
+ expectedStreamVersion
746
+ }
747
+ );
748
+ if (_optionalChain([options, 'optionalAccess', _22 => _22.onBeforeCommit]))
749
+ await options.onBeforeCommit(messagesToAppend, { connection });
750
+ return { success: true, result };
751
+ }
752
+ );
1087
753
  };
1088
754
  var toExpectedVersion = (expected) => {
1089
755
  if (expected === void 0) return null;
@@ -1092,54 +758,47 @@ var toExpectedVersion = (expected) => {
1092
758
  if (expected == STREAM_EXISTS) return null;
1093
759
  return expected;
1094
760
  };
1095
- var appendToStreamRaw = async (connection, streamId, streamType, messages, options) => {
761
+ var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
1096
762
  let streamPosition;
1097
763
  let globalPosition;
1098
764
  try {
1099
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _31 => _31.expectedStreamVersion]), () => ( null));
765
+ let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _23 => _23.expectedStreamVersion]), () => ( null));
1100
766
  if (expectedStreamVersion == null) {
1101
767
  expectedStreamVersion = await getLastStreamPosition(
1102
- connection,
768
+ execute,
1103
769
  streamId,
1104
770
  expectedStreamVersion
1105
771
  );
1106
772
  }
1107
773
  let position;
1108
774
  if (expectedStreamVersion === 0n) {
1109
- position = await connection.querySingle(
1110
- `INSERT INTO ${streamsTable.name}
775
+ position = await _dumbo.singleOrNull.call(void 0,
776
+ execute.query(
777
+ _dumbo.SQL`INSERT INTO ${identifier3(streamsTable.name)}
1111
778
  (stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
1112
779
  VALUES (
1113
- ?,
1114
- ?,
1115
- ?,
1116
- ?,
780
+ ${streamId},
781
+ ${messages.length},
782
+ ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _24 => _24.partition]), () => ( streamsTable.columns.partition))},
783
+ ${streamType},
1117
784
  '[]',
1118
785
  false
1119
786
  )
1120
787
  RETURNING stream_position;
1121
- `,
1122
- [
1123
- streamId,
1124
- messages.length,
1125
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _32 => _32.partition]), () => ( streamsTable.columns.partition)),
1126
- streamType
1127
- ]
788
+ `
789
+ )
1128
790
  );
1129
791
  } else {
1130
- position = await connection.querySingle(
1131
- `UPDATE ${streamsTable.name}
1132
- SET stream_position = stream_position + ?
1133
- WHERE stream_id = ?
1134
- AND partition = ?
792
+ position = await _dumbo.singleOrNull.call(void 0,
793
+ execute.query(
794
+ _dumbo.SQL`UPDATE ${identifier3(streamsTable.name)}
795
+ SET stream_position = stream_position + ${messages.length}
796
+ WHERE stream_id = ${streamId}
797
+ AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _25 => _25.partition]), () => ( streamsTable.columns.partition))}
1135
798
  AND is_archived = false
1136
799
  RETURNING stream_position;
1137
- `,
1138
- [
1139
- messages.length,
1140
- streamId,
1141
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _33 => _33.partition]), () => ( streamsTable.columns.partition))
1142
- ]
800
+ `
801
+ )
1143
802
  );
1144
803
  }
1145
804
  if (position == null) {
@@ -1154,21 +813,21 @@ var appendToStreamRaw = async (connection, streamId, streamType, messages, optio
1154
813
  };
1155
814
  }
1156
815
  }
1157
- const { sqlString, values } = buildMessageInsertQuery(
816
+ const insertSQL = buildMessageInsertQuery(
1158
817
  messages,
1159
818
  expectedStreamVersion,
1160
819
  streamId,
1161
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _34 => _34.partition, 'optionalAccess', _35 => _35.toString, 'call', _36 => _36()]), () => ( defaultTag2))
820
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.partition, 'optionalAccess', _27 => _27.toString, 'call', _28 => _28()]), () => ( defaultTag2))
1162
821
  );
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])) {
822
+ const { rows: returningIds } = await execute.query(insertSQL);
823
+ if (returningIds.length === 0 || !_optionalChain([returningIds, 'access', _29 => _29[returningIds.length - 1], 'optionalAccess', _30 => _30.global_position])) {
1165
824
  throw new Error("Could not find global position");
1166
825
  }
1167
826
  globalPosition = BigInt(
1168
827
  returningIds[returningIds.length - 1].global_position
1169
828
  );
1170
829
  } catch (err) {
1171
- if (isSQLiteError(err) && isOptimisticConcurrencyError(err)) {
830
+ if (_sqlite3.isSQLiteError.call(void 0, err) && isOptimisticConcurrencyError(err)) {
1172
831
  return {
1173
832
  success: false
1174
833
  };
@@ -1182,14 +841,15 @@ var appendToStreamRaw = async (connection, streamId, streamType, messages, optio
1182
841
  };
1183
842
  };
1184
843
  var isOptimisticConcurrencyError = (error) => {
1185
- return _optionalChain([error, 'optionalAccess', _39 => _39.errno]) !== void 0 && error.errno === 19;
844
+ return _optionalChain([error, 'optionalAccess', _31 => _31.errno]) !== void 0 && error.errno === 19;
1186
845
  };
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]
846
+ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
847
+ const result = await _dumbo.singleOrNull.call(void 0,
848
+ execute.query(
849
+ _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier3(streamsTable.name)} WHERE stream_id = ${streamId}`
850
+ )
1191
851
  );
1192
- if (_optionalChain([result, 'optionalAccess', _40 => _40.stream_position]) == null) {
852
+ if (_optionalChain([result, 'optionalAccess', _32 => _32.stream_position]) == null) {
1193
853
  expectedStreamVersion = 0n;
1194
854
  } else {
1195
855
  expectedStreamVersion = BigInt(result.stream_position);
@@ -1197,34 +857,15 @@ async function getLastStreamPosition(connection, streamId, expectedStreamVersion
1197
857
  return expectedStreamVersion;
1198
858
  }
1199
859
  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: []
860
+ const values = messages.map((message) => {
861
+ if (_optionalChain([message, 'access', _33 => _33.metadata, 'optionalAccess', _34 => _34.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
862
+ throw new Error("Stream position is required");
1224
863
  }
1225
- );
1226
- const sqlString = `
1227
- INSERT INTO ${messagesTable.name} (
864
+ const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
865
+ 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})`;
866
+ });
867
+ return _dumbo.SQL`
868
+ INSERT INTO ${identifier3(messagesTable.name)} (
1228
869
  stream_id,
1229
870
  stream_position,
1230
871
  partition,
@@ -1236,24 +877,22 @@ var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partit
1236
877
  message_id,
1237
878
  is_archived
1238
879
  )
1239
- VALUES ${query.parameterMarkers.join(", ")}
880
+ VALUES ${merge(values, ",")}
1240
881
  RETURNING
1241
882
  CAST(global_position as VARCHAR) AS global_position
1242
883
  `;
1243
- return { sqlString, values: query.values };
1244
884
  };
1245
885
 
1246
886
  // 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 = ?
887
+
888
+ var { identifier: identifier4 } = _dumbo.SQL;
889
+ var readProcessorCheckpoint = async (execute, options) => {
890
+ const result = await _dumbo.singleOrNull.call(void 0,
891
+ execute.query(
892
+ _dumbo.SQL`SELECT last_processed_checkpoint
893
+ FROM ${identifier4(processorsTable.name)}
894
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1254
895
  LIMIT 1`
1255
- ),
1256
- [_nullishCoalesce(_optionalChain([options, 'optionalAccess', _45 => _45.partition]), () => ( defaultTag2)), options.processorId]
1257
896
  )
1258
897
  );
1259
898
  return {
@@ -1262,18 +901,19 @@ var readProcessorCheckpoint = async (db, options) => {
1262
901
  };
1263
902
 
1264
903
  // 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}` : "";
904
+
905
+ var { identifier: identifier5 } = _dumbo.SQL;
906
+ var readStream = async (execute, streamId, options) => {
907
+ const fromCondition = _optionalChain([options, 'optionalAccess', _36 => _36.from]) ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
1267
908
  const to = Number(
1268
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _47 => _47.to]), () => ( (_optionalChain([options, 'optionalAccess', _48 => _48.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
909
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _37 => _37.to]), () => ( (_optionalChain([options, 'optionalAccess', _38 => _38.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
1269
910
  );
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))]
911
+ const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
912
+ const { rows: results } = await execute.query(
913
+ _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
914
+ FROM ${identifier5(messagesTable.name)}
915
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _39 => _39.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
916
+ ORDER BY stream_position ASC`
1277
917
  );
1278
918
  const messages = results.map((row) => {
1279
919
  const rawEvent = {
@@ -1293,7 +933,7 @@ var readStream = async (db, streamId, options) => {
1293
933
  kind: "Event",
1294
934
  metadata
1295
935
  };
1296
- return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _50 => _50.schema, 'optionalAccess', _51 => _51.versioning]));
936
+ return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _40 => _40.schema, 'optionalAccess', _41 => _41.versioning]));
1297
937
  });
1298
938
  return messages.length > 0 ? {
1299
939
  currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
@@ -1307,76 +947,60 @@ var readStream = async (db, streamId, options) => {
1307
947
  };
1308
948
 
1309
949
  // src/eventStore/schema/storeProcessorCheckpoint.ts
1310
- async function storeSubscriptionCheckpointSQLite(db, processorId, version, position, checkPosition, partition, processorInstanceId) {
950
+
951
+
952
+ var { identifier: identifier6 } = _dumbo.SQL;
953
+ async function storeSubscriptionCheckpointSQLite(execute, processorId, version, position, checkPosition, partition, processorInstanceId) {
1311
954
  processorInstanceId ??= unknownTag2;
1312
955
  if (checkPosition !== null) {
1313
- const updateResult = await db.command(
1314
- sql(`
1315
- UPDATE ${processorsTable.name}
956
+ const updateResult = await execute.command(
957
+ _dumbo.SQL`
958
+ UPDATE ${identifier6(processorsTable.name)}
1316
959
  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
- ]
960
+ last_processed_checkpoint = ${position},
961
+ processor_instance_id = ${processorInstanceId}
962
+ WHERE processor_id = ${processorId}
963
+ AND last_processed_checkpoint = ${checkPosition}
964
+ AND partition = ${partition}
965
+ `
1330
966
  );
1331
- if (updateResult.changes > 0) {
967
+ if (updateResult.rowCount && updateResult.rowCount > 0) {
1332
968
  return 1;
969
+ }
970
+ const current_position = await _dumbo.singleOrNull.call(void 0,
971
+ execute.query(
972
+ _dumbo.SQL`
973
+ SELECT last_processed_checkpoint FROM ${identifier6(processorsTable.name)}
974
+ WHERE processor_id = ${processorId} AND partition = ${partition}`
975
+ )
976
+ );
977
+ const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _42 => _42.last_processed_checkpoint]) !== null ? BigInt(current_position.last_processed_checkpoint) : null;
978
+ if (currentPosition === position) {
979
+ return 0;
980
+ } else if (position !== null && currentPosition !== null && currentPosition > position) {
981
+ return 2;
1333
982
  } 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
- }
983
+ return 2;
1351
984
  }
1352
985
  } else {
1353
986
  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
- ]
987
+ await execute.command(
988
+ _dumbo.SQL`INSERT INTO ${identifier6(processorsTable.name)} (processor_id, version, last_processed_checkpoint, partition, processor_instance_id)
989
+ VALUES (${processorId}, ${version}, ${position}, ${partition}, ${processorInstanceId})`
1365
990
  );
1366
991
  return 1;
1367
992
  } catch (err) {
1368
- if (!(isSQLiteError(err) && (err.errno === 19 || err.errno === 2067))) {
993
+ if (!(_sqlite3.isSQLiteError.call(void 0, err) && (err.errno === 19 || err.errno === 2067))) {
1369
994
  throw err;
1370
995
  }
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]
996
+ const current = await _dumbo.singleOrNull.call(void 0,
997
+ execute.query(
998
+ _dumbo.SQL`
999
+ SELECT last_processed_checkpoint FROM ${identifier6(processorsTable.name)}
1000
+ WHERE processor_id = ${processorId} AND partition = ${partition}`
1377
1001
  )
1378
1002
  );
1379
- const currentPosition = current && _optionalChain([current, 'optionalAccess', _53 => _53.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
1003
+ const currentPosition = current && _optionalChain([current, 'optionalAccess', _43 => _43.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
1380
1004
  if (currentPosition === position) {
1381
1005
  return 0;
1382
1006
  } else {
@@ -1385,10 +1009,10 @@ async function storeSubscriptionCheckpointSQLite(db, processorId, version, posit
1385
1009
  }
1386
1010
  }
1387
1011
  }
1388
- async function storeProcessorCheckpoint(db, options) {
1012
+ async function storeProcessorCheckpoint(execute, options) {
1389
1013
  try {
1390
1014
  const result = await storeSubscriptionCheckpointSQLite(
1391
- db,
1015
+ execute,
1392
1016
  options.processorId,
1393
1017
  _nullishCoalesce(options.version, () => ( 1)),
1394
1018
  options.newPosition,
@@ -1402,31 +1026,239 @@ async function storeProcessorCheckpoint(db, options) {
1402
1026
  }
1403
1027
  }
1404
1028
 
1029
+ // src/eventStore/schema/tables.ts
1030
+
1031
+
1032
+
1033
+ // src/eventStore/schema/migrations/0_41_0/0_41_0.snapshot.ts
1034
+
1035
+ var schema_0_41_0 = [
1036
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
1037
+ stream_id TEXT NOT NULL,
1038
+ stream_position BIGINT NOT NULL DEFAULT 0,
1039
+ partition TEXT NOT NULL DEFAULT 'global',
1040
+ stream_type TEXT NOT NULL,
1041
+ stream_metadata JSONB NOT NULL,
1042
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1043
+ PRIMARY KEY (stream_id, partition, is_archived),
1044
+ UNIQUE (stream_id, partition, is_archived)
1045
+ )`,
1046
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
1047
+ stream_id TEXT NOT NULL,
1048
+ stream_position BIGINT NOT NULL,
1049
+ partition TEXT NOT NULL DEFAULT 'global',
1050
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
1051
+ message_data JSONB NOT NULL,
1052
+ message_metadata JSONB NOT NULL,
1053
+ message_schema_version TEXT NOT NULL,
1054
+ message_type TEXT NOT NULL,
1055
+ message_id TEXT NOT NULL,
1056
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1057
+ global_position INTEGER PRIMARY KEY,
1058
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
1059
+ UNIQUE (stream_id, stream_position, partition, is_archived)
1060
+ )`,
1061
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_subscriptions(
1062
+ subscription_id TEXT NOT NULL,
1063
+ version INTEGER NOT NULL DEFAULT 1,
1064
+ partition TEXT NOT NULL DEFAULT 'global',
1065
+ last_processed_position BIGINT NOT NULL,
1066
+ PRIMARY KEY (subscription_id, partition, version)
1067
+ )`
1068
+ ];
1069
+
1070
+ // src/eventStore/schema/migrations/0_42_0/0_42_0.migration.ts
1071
+
1072
+ var { identifier: identifier7, plain } = _dumbo.SQL;
1073
+ var migration_0_42_0_SQLs = [
1074
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier7(processorsTable.name)}(
1075
+ processor_id TEXT NOT NULL,
1076
+ version INTEGER NOT NULL DEFAULT 1,
1077
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
1078
+ status TEXT NOT NULL DEFAULT 'stopped',
1079
+ last_processed_checkpoint TEXT NOT NULL,
1080
+ processor_instance_id TEXT DEFAULT 'emt:unknown',
1081
+ PRIMARY KEY (processor_id, partition, version)
1082
+ )`,
1083
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier7(projectionsTable.name)}(
1084
+ name TEXT NOT NULL,
1085
+ version INTEGER NOT NULL DEFAULT 1,
1086
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
1087
+ type CHAR(1) NOT NULL,
1088
+ kind TEXT NOT NULL,
1089
+ status TEXT NOT NULL,
1090
+ definition JSONB NOT NULL DEFAULT '{}',
1091
+ PRIMARY KEY (name, partition, version)
1092
+ )`,
1093
+ _dumbo.SQL`INSERT INTO ${identifier7(processorsTable.name)}
1094
+ (processor_id, version, partition, status, last_processed_checkpoint, processor_instance_id)
1095
+ SELECT
1096
+ subscription_id,
1097
+ version,
1098
+ partition,
1099
+ 'stopped',
1100
+ printf('%019d', last_processed_position),
1101
+ 'emt:unknown'
1102
+ FROM emt_subscriptions`,
1103
+ _dumbo.SQL`DROP TABLE emt_subscriptions`
1104
+ ];
1105
+ var migration_0_42_0_FromSubscriptionsToProcessors = async (execute) => {
1106
+ const tableExists = await _dumbo.singleOrNull.call(void 0,
1107
+ execute.query(
1108
+ _dumbo.SQL`SELECT name FROM sqlite_master WHERE type='table' AND name='emt_subscriptions'`
1109
+ )
1110
+ );
1111
+ if (!tableExists) {
1112
+ return;
1113
+ }
1114
+ await execute.batchCommand(migration_0_42_0_SQLs);
1115
+ };
1116
+
1117
+ // src/eventStore/schema/migrations/0_42_0/0_42_0.snapshot.ts
1118
+
1119
+ var schema_0_42_0 = [
1120
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
1121
+ stream_id TEXT NOT NULL,
1122
+ stream_position BIGINT NOT NULL DEFAULT 0,
1123
+ partition TEXT NOT NULL DEFAULT 'global',
1124
+ stream_type TEXT NOT NULL,
1125
+ stream_metadata JSONB NOT NULL,
1126
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1127
+ PRIMARY KEY (stream_id, partition, is_archived),
1128
+ UNIQUE (stream_id, partition, is_archived)
1129
+ )`,
1130
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
1131
+ stream_id TEXT NOT NULL,
1132
+ stream_position BIGINT NOT NULL,
1133
+ partition TEXT NOT NULL DEFAULT 'global',
1134
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
1135
+ message_data JSONB NOT NULL,
1136
+ message_metadata JSONB NOT NULL,
1137
+ message_schema_version TEXT NOT NULL,
1138
+ message_type TEXT NOT NULL,
1139
+ message_id TEXT NOT NULL,
1140
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1141
+ global_position INTEGER PRIMARY KEY,
1142
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
1143
+ UNIQUE (stream_id, stream_position, partition, is_archived)
1144
+ )`,
1145
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_processors(
1146
+ processor_id TEXT NOT NULL,
1147
+ version INTEGER NOT NULL DEFAULT 1,
1148
+ partition TEXT NOT NULL DEFAULT 'global',
1149
+ status TEXT NOT NULL DEFAULT 'stopped',
1150
+ last_processed_checkpoint TEXT NOT NULL,
1151
+ processor_instance_id TEXT DEFAULT 'emt:unknown',
1152
+ PRIMARY KEY (processor_id, partition, version)
1153
+ )`,
1154
+ _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_projections(
1155
+ name TEXT NOT NULL,
1156
+ version INTEGER NOT NULL DEFAULT 1,
1157
+ partition TEXT NOT NULL DEFAULT 'global',
1158
+ type CHAR(1) NOT NULL,
1159
+ kind TEXT NOT NULL,
1160
+ status TEXT NOT NULL,
1161
+ definition JSONB NOT NULL DEFAULT '{}',
1162
+ PRIMARY KEY (name, partition, version)
1163
+ )`
1164
+ ];
1165
+
1166
+ // src/eventStore/schema/tables.ts
1167
+ var { identifier: identifier8, plain: plain2 } = _dumbo.SQL;
1168
+ var streamsTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(streamsTable.name)}(
1169
+ stream_id TEXT NOT NULL,
1170
+ stream_position BIGINT NOT NULL DEFAULT 0,
1171
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1172
+ stream_type TEXT NOT NULL,
1173
+ stream_metadata JSONB NOT NULL,
1174
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1175
+ PRIMARY KEY (stream_id, partition, is_archived),
1176
+ UNIQUE (stream_id, partition, is_archived)
1177
+ );`;
1178
+ var messagesTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(messagesTable.name)}(
1179
+ stream_id TEXT NOT NULL,
1180
+ stream_position BIGINT NOT NULL,
1181
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1182
+ message_kind CHAR(1) NOT NULL DEFAULT 'E',
1183
+ message_data JSONB NOT NULL,
1184
+ message_metadata JSONB NOT NULL,
1185
+ message_schema_version TEXT NOT NULL,
1186
+ message_type TEXT NOT NULL,
1187
+ message_id TEXT NOT NULL,
1188
+ is_archived BOOLEAN NOT NULL DEFAULT FALSE,
1189
+ global_position INTEGER PRIMARY KEY,
1190
+ created DATETIME DEFAULT CURRENT_TIMESTAMP,
1191
+ UNIQUE (stream_id, stream_position, partition, is_archived)
1192
+ );
1193
+ `;
1194
+ var processorsTableSQL = _dumbo.SQL`
1195
+ CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(processorsTable.name)}(
1196
+ processor_id TEXT NOT NULL,
1197
+ version INTEGER NOT NULL DEFAULT 1,
1198
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1199
+ status TEXT NOT NULL DEFAULT 'stopped',
1200
+ last_processed_checkpoint TEXT NOT NULL,
1201
+ processor_instance_id TEXT DEFAULT '${plain2(unknownTag2)}',
1202
+ PRIMARY KEY (processor_id, partition, version)
1203
+ );
1204
+ `;
1205
+ var projectionsTableSQL = _dumbo.SQL`
1206
+ CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(projectionsTable.name)}(
1207
+ name TEXT NOT NULL,
1208
+ version INTEGER NOT NULL DEFAULT 1,
1209
+ partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1210
+ type CHAR(1) NOT NULL,
1211
+ kind TEXT NOT NULL,
1212
+ status TEXT NOT NULL,
1213
+ definition JSONB NOT NULL DEFAULT '{}',
1214
+ PRIMARY KEY (name, partition, version)
1215
+ );
1216
+ `;
1217
+ var schemaSQL = [
1218
+ streamsTableSQL,
1219
+ messagesTableSQL,
1220
+ processorsTableSQL,
1221
+ projectionsTableSQL
1222
+ ];
1223
+ var createEventStoreSchema = async (pool, hooks) => {
1224
+ await pool.withTransaction(async (tx) => {
1225
+ await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
1226
+ if (_optionalChain([hooks, 'optionalAccess', _44 => _44.onBeforeSchemaCreated])) {
1227
+ await hooks.onBeforeSchemaCreated({
1228
+ connection: tx.connection
1229
+ });
1230
+ }
1231
+ await tx.execute.batchCommand(schemaSQL);
1232
+ if (_optionalChain([hooks, 'optionalAccess', _45 => _45.onAfterSchemaCreated])) {
1233
+ await hooks.onAfterSchemaCreated();
1234
+ }
1235
+ });
1236
+ };
1237
+
1405
1238
  // src/eventStore/consumers/sqliteProcessor.ts
1406
1239
  var genericSQLiteProcessor = (options) => {
1407
1240
  const { eachMessage } = options;
1408
1241
  let isActive = true;
1409
1242
  const getDb = (context) => {
1410
- const fileName = _nullishCoalesce(context.fileName, () => ( _optionalChain([options, 'access', _54 => _54.connectionOptions, 'optionalAccess', _55 => _55.fileName])));
1243
+ const fileName = _nullishCoalesce(context.fileName, () => ( _optionalChain([options, 'access', _46 => _46.connectionOptions, 'optionalAccess', _47 => _47.fileName])));
1411
1244
  if (!fileName)
1412
1245
  throw new EmmettError(
1413
1246
  `SQLite processor '${options.processorId}' is missing file name. Ensure that you passed it through options`
1414
1247
  );
1415
- const connection = _nullishCoalesce(_nullishCoalesce(context.connection, () => ( _optionalChain([options, 'access', _56 => _56.connectionOptions, 'optionalAccess', _57 => _57.connection]))), () => ( sqliteConnection({ fileName })));
1248
+ const connection = _nullishCoalesce(_nullishCoalesce(context.connection, () => ( _optionalChain([options, 'access', _48 => _48.connectionOptions, 'optionalAccess', _49 => _49.connection]))), () => ( _sqlite3.sqlite3Connection.call(void 0, { fileName, serializer: _dumbo.JSONSerializer })));
1416
1249
  return { connection, fileName };
1417
1250
  };
1418
1251
  return {
1419
1252
  id: options.processorId,
1420
- start: async (connection) => {
1253
+ start: async ({
1254
+ execute
1255
+ }) => {
1421
1256
  isActive = true;
1422
1257
  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
- );
1258
+ const { lastProcessedPosition } = await readProcessorCheckpoint(execute, {
1259
+ processorId: options.processorId,
1260
+ partition: options.partition
1261
+ });
1430
1262
  if (lastProcessedPosition === null) return "BEGINNING";
1431
1263
  return { globalPosition: lastProcessedPosition };
1432
1264
  },
@@ -1436,17 +1268,17 @@ var genericSQLiteProcessor = (options) => {
1436
1268
  handle: async ({ messages }, context) => {
1437
1269
  if (!isActive) return;
1438
1270
  const { connection, fileName } = getDb(context);
1439
- return connection.withTransaction(async () => {
1271
+ return connection.withTransaction(async (tx) => {
1440
1272
  let result = void 0;
1441
1273
  let lastProcessedPosition = null;
1442
1274
  for (const message of messages) {
1443
1275
  const typedMessage = message;
1444
1276
  const messageProcessingResult = await eachMessage(typedMessage, {
1445
- connection,
1277
+ connection: tx.connection,
1446
1278
  fileName
1447
1279
  });
1448
1280
  const newPosition = getCheckpoint(typedMessage);
1449
- await storeProcessorCheckpoint(connection, {
1281
+ await storeProcessorCheckpoint(tx.execute, {
1450
1282
  processorId: options.processorId,
1451
1283
  version: options.version,
1452
1284
  lastProcessedPosition,
@@ -1497,7 +1329,10 @@ var sqliteEventStoreConsumer = (options) => {
1497
1329
  const processors = _nullishCoalesce(options.processors, () => ( []));
1498
1330
  let start;
1499
1331
  let currentMessagePuller;
1500
- const pool = _nullishCoalesce(options.pool, () => ( SQLiteConnectionPool(options)));
1332
+ const pool = _nullishCoalesce(options.pool, () => ( _sqlite3.sqlite3Pool.call(void 0, {
1333
+ transactionOptions: { allowNestedTransactions: true },
1334
+ ...options
1335
+ })));
1501
1336
  const eachBatch = (messagesBatch) => pool.withConnection(async (connection) => {
1502
1337
  const activeProcessors = processors.filter((s) => s.isActive);
1503
1338
  if (activeProcessors.length === 0)
@@ -1514,7 +1349,7 @@ var sqliteEventStoreConsumer = (options) => {
1514
1349
  })
1515
1350
  );
1516
1351
  return result.some(
1517
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _58 => _58.value, 'optionalAccess', _59 => _59.type]) !== "STOP"
1352
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _50 => _50.value, 'optionalAccess', _51 => _51.type]) !== "STOP"
1518
1353
  ) ? void 0 : {
1519
1354
  type: "STOP"
1520
1355
  };
@@ -1522,8 +1357,8 @@ var sqliteEventStoreConsumer = (options) => {
1522
1357
  const messagePooler = currentMessagePuller = sqliteEventStoreMessageBatchPuller({
1523
1358
  pool,
1524
1359
  eachBatch,
1525
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _60 => _60.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
1526
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _61 => _61.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs))
1360
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _52 => _52.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
1361
+ pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _53 => _53.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs))
1527
1362
  });
1528
1363
  const stop = async () => {
1529
1364
  if (!isRunning) return;
@@ -1573,33 +1408,39 @@ var sqliteEventStoreConsumer = (options) => {
1573
1408
  };
1574
1409
 
1575
1410
  // src/eventStore/schema/streamExists.ts
1576
- var streamExists = async (db, streamId, options) => {
1577
- const queryResult = await db.query(
1578
- `SELECT EXISTS (
1411
+
1412
+ var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
1413
+ execute.query(
1414
+ _dumbo.SQL`SELECT EXISTS (
1579
1415
  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
- };
1416
+ from ${_dumbo.SQL.identifier(streamsTable.name)}
1417
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _54 => _54.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
1418
+ `
1419
+ )
1420
+ );
1587
1421
 
1588
1422
  // src/eventStore/SQLiteEventStore.ts
1589
1423
  var SQLiteEventStoreDefaultStreamVersion = 0n;
1590
1424
  var getSQLiteEventStore = (options) => {
1591
1425
  let autoGenerateSchema = false;
1592
- const fileName = _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase));
1593
- const pool = _nullishCoalesce(options.pool, () => ( SQLiteConnectionPool(options)));
1426
+ const fileName = _nullishCoalesce(options.fileName, () => ( _sqlite3.InMemorySQLiteDatabase));
1427
+ const poolOptions = {
1428
+ fileName,
1429
+ transactionOptions: { allowNestedTransactions: true }
1430
+ };
1431
+ const pool = _nullishCoalesce(options.pool, () => ( _sqlite3.sqlite3Pool.call(void 0, {
1432
+ ...poolOptions,
1433
+ ...options.connectionOptions ? options.connectionOptions : {}
1434
+ })));
1594
1435
  let migrateSchema = void 0;
1595
1436
  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);
1437
+ const onBeforeCommitHook = _optionalChain([options, 'access', _55 => _55.hooks, 'optionalAccess', _56 => _56.onBeforeCommit]);
1438
+ const withConnection = async (handler) => pool.withConnection(async (connection) => {
1439
+ await ensureSchemaExists(connection);
1440
+ return await handler(connection);
1600
1441
  });
1601
1442
  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";
1443
+ autoGenerateSchema = _optionalChain([options, 'access', _57 => _57.schema, 'optionalAccess', _58 => _58.autoMigration]) === void 0 || _optionalChain([options, 'access', _59 => _59.schema, 'optionalAccess', _60 => _60.autoMigration]) !== "None";
1603
1444
  }
1604
1445
  const migrate = (connection) => {
1605
1446
  if (!migrateSchema) {
@@ -1615,11 +1456,11 @@ var getSQLiteEventStore = (options) => {
1615
1456
  });
1616
1457
  }
1617
1458
  }
1618
- if (_optionalChain([options, 'access', _71 => _71.hooks, 'optionalAccess', _72 => _72.onBeforeSchemaCreated])) {
1459
+ if (_optionalChain([options, 'access', _61 => _61.hooks, 'optionalAccess', _62 => _62.onBeforeSchemaCreated])) {
1619
1460
  await options.hooks.onBeforeSchemaCreated(context);
1620
1461
  }
1621
1462
  },
1622
- onAfterSchemaCreated: _optionalChain([options, 'access', _73 => _73.hooks, 'optionalAccess', _74 => _74.onAfterSchemaCreated])
1463
+ onAfterSchemaCreated: _optionalChain([options, 'access', _63 => _63.hooks, 'optionalAccess', _64 => _64.onAfterSchemaCreated])
1623
1464
  });
1624
1465
  }
1625
1466
  return migrateSchema;
@@ -1631,13 +1472,13 @@ var getSQLiteEventStore = (options) => {
1631
1472
  return {
1632
1473
  async aggregateStream(streamName, options2) {
1633
1474
  const { evolve, initialState, read } = options2;
1634
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _75 => _75.expectedStreamVersion]);
1475
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _65 => _65.expectedStreamVersion]);
1635
1476
  let state = initialState();
1636
1477
  if (typeof streamName !== "string") {
1637
1478
  throw new Error("Stream name is not string");
1638
1479
  }
1639
1480
  const result = await withConnection(
1640
- (connection) => readStream(connection, streamName, read)
1481
+ ({ execute }) => readStream(execute, streamName, read)
1641
1482
  );
1642
1483
  const currentStreamVersion = result.currentStreamVersion;
1643
1484
  assertExpectedVersionMatchesCurrent(
@@ -1656,11 +1497,7 @@ var getSQLiteEventStore = (options) => {
1656
1497
  };
1657
1498
  },
1658
1499
  readStream: async (streamName, options2) => withConnection(
1659
- (connection) => readStream(
1660
- connection,
1661
- streamName,
1662
- options2
1663
- )
1500
+ ({ execute }) => readStream(execute, streamName, options2)
1664
1501
  ),
1665
1502
  appendToStream: async (streamName, events, options2) => {
1666
1503
  const [firstPart, ...rest] = streamName.split("-");
@@ -1683,7 +1520,7 @@ var getSQLiteEventStore = (options) => {
1683
1520
  throw new ExpectedVersionConflictError(
1684
1521
  -1n,
1685
1522
  //TODO: Return actual version in case of error
1686
- _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _76 => _76.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1523
+ _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _66 => _66.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1687
1524
  );
1688
1525
  return {
1689
1526
  nextExpectedStreamVersion: appendResult.nextStreamPosition,
@@ -1693,7 +1530,7 @@ var getSQLiteEventStore = (options) => {
1693
1530
  },
1694
1531
  streamExists(streamName, options2) {
1695
1532
  return withConnection(
1696
- (connection) => streamExists(connection, streamName, options2)
1533
+ ({ execute }) => streamExists(execute, streamName, options2)
1697
1534
  );
1698
1535
  },
1699
1536
  consumer: (options2) => sqliteEventStoreConsumer({
@@ -1701,6 +1538,7 @@ var getSQLiteEventStore = (options) => {
1701
1538
  fileName,
1702
1539
  pool
1703
1540
  }),
1541
+ close: () => pool.close(),
1704
1542
  schema: {
1705
1543
  sql: () => schemaSQL.join(""),
1706
1544
  print: () => console.log(schemaSQL.join("")),
@@ -1713,8 +1551,9 @@ var getSQLiteEventStore = (options) => {
1713
1551
  var SQLiteProjectionSpec = {
1714
1552
  for: (options) => {
1715
1553
  {
1716
- const connection = _nullishCoalesce(options.connection, () => ( sqliteConnection({
1717
- fileName: _nullishCoalesce(options.fileName, () => ( InMemorySQLiteDatabase))
1554
+ const connection = _nullishCoalesce(options.connection, () => ( _sqlite3.sqlite3Connection.call(void 0, {
1555
+ fileName: _nullishCoalesce(options.fileName, () => ( _sqlite3.InMemorySQLiteDatabase)),
1556
+ serializer: _dumbo.JSONSerializer
1718
1557
  })));
1719
1558
  const projection2 = options.projection;
1720
1559
  let wasInitialized = false;
@@ -1724,7 +1563,7 @@ var SQLiteProjectionSpec = {
1724
1563
  const allEvents = [];
1725
1564
  const run = async (connection2) => {
1726
1565
  let globalPosition = 0n;
1727
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _77 => _77.numberOfTimes]), () => ( 1));
1566
+ const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _67 => _67.numberOfTimes]), () => ( 1));
1728
1567
  for (const event of [
1729
1568
  ...givenEvents,
1730
1569
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
@@ -1773,7 +1612,7 @@ var SQLiteProjectionSpec = {
1773
1612
  _nullishCoalesce(message, () => ( "Projection specification didn't match the criteria"))
1774
1613
  );
1775
1614
  } finally {
1776
- connection.close();
1615
+ await connection.close();
1777
1616
  }
1778
1617
  },
1779
1618
  thenThrows: async (...args) => {
@@ -1786,22 +1625,22 @@ var SQLiteProjectionSpec = {
1786
1625
  if (!isErrorConstructor(args[0])) {
1787
1626
  assertTrue(
1788
1627
  args[0](error),
1789
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _78 => _78.toString, 'call', _79 => _79()])}`
1628
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _68 => _68.toString, 'call', _69 => _69()])}`
1790
1629
  );
1791
1630
  return;
1792
1631
  }
1793
1632
  assertTrue(
1794
1633
  error instanceof args[0],
1795
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _80 => _80.toString, 'call', _81 => _81()])}`
1634
+ `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _70 => _70.toString, 'call', _71 => _71()])}`
1796
1635
  );
1797
1636
  if (args[1]) {
1798
1637
  assertTrue(
1799
1638
  args[1](error),
1800
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _82 => _82.toString, 'call', _83 => _83()])}`
1639
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _72 => _72.toString, 'call', _73 => _73()])}`
1801
1640
  );
1802
1641
  }
1803
1642
  } finally {
1804
- connection.close();
1643
+ await connection.close();
1805
1644
  }
1806
1645
  }
1807
1646
  };
@@ -1816,7 +1655,7 @@ var eventInStream = (streamName, event) => {
1816
1655
  ...event,
1817
1656
  metadata: {
1818
1657
  ..._nullishCoalesce(event.metadata, () => ( {})),
1819
- streamName: _nullishCoalesce(_optionalChain([event, 'access', _84 => _84.metadata, 'optionalAccess', _85 => _85.streamName]), () => ( streamName))
1658
+ streamName: _nullishCoalesce(_optionalChain([event, 'access', _74 => _74.metadata, 'optionalAccess', _75 => _75.streamName]), () => ( streamName))
1820
1659
  }
1821
1660
  };
1822
1661
  };
@@ -1824,14 +1663,16 @@ var eventsInStream = (streamName, events) => {
1824
1663
  return events.map((e) => eventInStream(streamName, e));
1825
1664
  };
1826
1665
  var newEventsInStream = eventsInStream;
1827
- var assertSQLQueryResultMatches = (sql2, rows) => async ({ connection }) => {
1828
- const result = await connection.query(sql2);
1829
- assertThatArray(rows).containsExactlyInAnyOrder(result);
1666
+ var assertSQLQueryResultMatches = (sql, rows) => async ({
1667
+ connection
1668
+ }) => {
1669
+ const result = await connection.execute.query(sql);
1670
+ assertThatArray(rows).containsExactlyInAnyOrder(result.rows);
1830
1671
  };
1831
1672
  var expectSQL = {
1832
- query: (sql2) => ({
1673
+ query: (sql) => ({
1833
1674
  resultRows: {
1834
- toBeTheSame: (rows) => assertSQLQueryResultMatches(sql2, rows)
1675
+ toBeTheSame: (rows) => assertSQLQueryResultMatches(sql, rows)
1835
1676
  }
1836
1677
  })
1837
1678
  };
@@ -1873,11 +1714,5 @@ var expectSQL = {
1873
1714
 
1874
1715
 
1875
1716
 
1876
-
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;
1717
+ 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.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
1883
1718
  //# sourceMappingURL=index.cjs.map