@event-driven-io/emmett-postgresql 0.18.0 → 0.19.0-alpha.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 +363 -0
- package/dist/index.cjs.map +1 -0
- package/dist/{index.d.mts → index.d.cts} +3 -7
- package/dist/index.d.ts +3 -7
- package/dist/index.js +16 -16
- package/dist/index.js.map +1 -1
- package/package.json +31 -10
- package/dist/index.mjs +0 -363
- package/dist/index.mjs.map +0 -1
package/dist/index.mjs
DELETED
|
@@ -1,363 +0,0 @@
|
|
|
1
|
-
import{dumbo as We}from"@event-driven-io/dumbo";import{v4 as Ke}from"uuid";import et from"async-retry";import{TransformStream as nt}from"web-streams-polyfill";var ue=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(ue||{}),ge=e=>typeof e=="number"&&e===e,Se=e=>typeof e=="string";var V=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,ye=class G extends Error{errorCode;constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:ge(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,G.prototype)}},fe=class W extends ye{constructor(t,n,o){super({errorCode:412,message:o??`Expected version ${n.toString()} does not match current ${t?.toString()}`}),this.current=t,this.expected=n,Object.setPrototypeOf(this,W.prototype)}};var D="STREAM_EXISTS",x="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK";var U=class z extends fe{constructor(t,n){super(t?.toString(),n?.toString()),Object.setPrototypeOf(this,z.prototype)}};var H=(e,t,n)=>({type:e,data:t,metadata:n});var k=e=>e;var Pe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(t?.map?t.map(e):e,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(e,t)=>{let n=JSON.parse(e,t?.reviver);if(t?.typeCheck&&!t?.typeCheck(n))throw new Pe(e);return t?.map?t.map(n):n}};var u=(e,t)=>{if(he(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((a,s)=>u(a,t[s]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in e)if(!(e[a]instanceof Function&&t[a]instanceof Function)&&!u(e[a],t[a]))return!1;return!0},he=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var y=class extends Error{constructor(e){super(e)}};var q=e=>{throw new y(e??"That should not ever happened, right?")};var Y=(e,t,n)=>{if(!u(e,t))throw new y(n??`subObj:
|
|
2
|
-
${P.stringify(t)}
|
|
3
|
-
is not equal to
|
|
4
|
-
${P.stringify(e)}`)};function T(e,t){if(!e)throw new y(t??"Condition is false")}function Ie(e,t){if(!e)throw new y(t??"Condition is not truthy")}function S(e,t,n){if(e!==t)throw new y(`${n??"Objects are not equal"}:
|
|
5
|
-
Expected: ${P.stringify(e)}
|
|
6
|
-
Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(n??`Objects are equal: ${P.stringify(e)}`)}function $(e){J(e,null),Ie(e)}var R=e=>({isEmpty:()=>S(e.length,0),isNotEmpty:()=>J(e.length,0),hasSize:t=>S(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrder:(...t)=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrderElementsOf:t=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyElementsOf:t=>{S(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{S(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(o=>u(o,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(o=>u(n,o))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});import"pg";import"@event-driven-io/dumbo";import"@event-driven-io/dumbo";import{pongoClient as Oe}from"@event-driven-io/pongo";var A=(e,t)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:s}=t;return n.withConnection(async p=>{let m=Oe(o,{connection:p});try{let E=m.db(a).collection(s);return e(E)}finally{await m.close()}})},K=e=>{let{_id:t,...n}=e;return n},Ne=(e,t)=>("_id"in t&&S(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),Y(K(e),K(t))),Re=(e,t)=>n=>A(async o=>{let a=await o.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);$(a),Ne(a,e)},{...t,...n}),Ae=(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e.length,a.length,"Different Documents Count than expected");for(let s=0;s<e.length;s++)R(a).contains(e[s])},{...t,...n}),Le=(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e,a.length,"Different Documents Count than expected")},{...t,...n}),Z=e=>t=>A(async n=>{let o=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);R(o).isNotEmpty()},{...e,...t}),ee=e=>t=>A(async n=>{let o=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);$(o)},{...e,...t}),dt={fromCollection:e=>({withId:t=>({toBeEqual:n=>Re(n,{withId:t,inCollection:e}),toExist:()=>Z({withId:t,inCollection:e}),notToExist:()=>ee({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>Ae(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>Le(n,{matchingFilter:t,inCollection:e}),toExist:()=>Z({matchingFilter:t,inCollection:e}),notToExist:()=>ee({matchingFilter:t,inCollection:e})})})};import{pongoClient as De}from"@event-driven-io/pongo";var xe=({handle:e,canHandle:t})=>j({canHandle:t,handle:async(n,o)=>{let{connectionString:a,client:s}=o,p=De(a,{client:s});await e(n,{...o,pongo:p})}}),Ce=e=>{let{collectionName:t,getDocumentId:n,canHandle:o}=e;return xe({handle:async(a,{pongo:s})=>{let p=s.db().collection(t);for(let m of a)await p.handle(n(m),async E=>"initialState"in e?await e.evolve(E??e.initialState(),m):await e.evolve(E,m))},canHandle:o})},vt=e=>Ce({...e,getDocumentId:t=>t.metadata.streamName});import{dumbo as te}from"@event-driven-io/dumbo";import{v4 as ne}from"uuid";var It={for:e=>{{let{projection:t,...n}=e,{connectionString:o}=n;return a=>({when:(s,p)=>{let m=[],E=async c=>{let l=0n,d=p?.numberOfTimes??1;for(let _ of[...a,...Array.from({length:d}).flatMap(()=>s)])m.push({..._,metadata:{globalPosition:++l,streamPosition:l,streamName:`test-${ne()}`,eventId:ne(),..._.metadata??{}}});await c.withTransaction(_=>C({events:m,projections:[t],connection:{connectionString:o,transaction:_}}))};return{then:async(c,l)=>{let d=te(n);try{await E(d);let _=await c({pool:d,connectionString:o});_!==void 0&&_===!1&&q(l??"Projection specification didn't match the criteria")}finally{await d.close()}},thenThrows:async(...c)=>{let l=te(n);try{throw await E(l),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!V(c[0])){T(c[0](d),`Error didn't match the error condition: ${d?.toString()}`);return}T(d instanceof c[0],`Caught error is not an instance of the expected type: ${d?.toString()}`),c[1]&&T(c[1](d),`Error didn't match the error condition: ${d?.toString()}`)}finally{await l.close()}}}}})}}},we=(e,t)=>({...t,metadata:{...t.metadata??{},streamName:t.metadata?.streamName??e}}),be=(e,t)=>t.map(n=>we(e,n)),Ot=be,Me=(e,t)=>async({pool:{execute:n}})=>{let o=await n.query(e);R(t).containsExactlyInAnyOrder(...o.rows)},Nt={query:e=>({resultRows:{toBeTheSame:t=>Me(e,t)}})};var C=async e=>{let{projections:t,events:n,connection:{transaction:o,connectionString:a}}=e,s=n.map(E=>E.type),p=t.filter(E=>E.canHandle.some(c=>s.includes(c))),m=await o.connection.open();for(let E of p)await E.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},j=e=>k(e),Fe=(e,...t)=>j({canHandle:t,handle:async(n,o)=>{let a=await e(n,o);await o.execute.batchCommand(a)}}),Dt=(e,...t)=>Fe(async(n,o)=>{let a=[];for(let s of n)a.push(await e(s,o));return a},...t);import"@event-driven-io/dumbo";import{rawSql as Ue,single as $e,sql as L}from"@event-driven-io/dumbo";import{v4 as je}from"uuid";var w="emt",v="global",N="emt:default",bt={module:`${w}:module:${v}`,tenant:`${w}:tenant:${v}`},b={partition:{name:"partition"},isArchived:{name:"is_archived"}},i={name:`${w}_streams`,columns:{partition:b.partition,isArchived:b.isArchived}},r={name:`${w}_events`,columns:{partition:b.partition,isArchived:b.isArchived}};var oe=Ue(`CREATE OR REPLACE FUNCTION emt_append_event(
|
|
7
|
-
v_event_ids text[],
|
|
8
|
-
v_events_data jsonb[],
|
|
9
|
-
v_events_metadata jsonb[],
|
|
10
|
-
v_event_schema_versions text[],
|
|
11
|
-
v_event_types text[],
|
|
12
|
-
v_stream_id text,
|
|
13
|
-
v_stream_type text,
|
|
14
|
-
v_expected_stream_position bigint DEFAULT NULL,
|
|
15
|
-
v_partition text DEFAULT emt_sanitize_name('default_partition')
|
|
16
|
-
) RETURNS TABLE (
|
|
17
|
-
success boolean,
|
|
18
|
-
next_stream_position bigint,
|
|
19
|
-
last_global_position bigint,
|
|
20
|
-
transaction_id xid8
|
|
21
|
-
) LANGUAGE plpgsql
|
|
22
|
-
AS $$
|
|
23
|
-
DECLARE
|
|
24
|
-
v_next_stream_position bigint;
|
|
25
|
-
v_position bigint;
|
|
26
|
-
v_updated_rows int;
|
|
27
|
-
v_transaction_id xid8;
|
|
28
|
-
v_last_global_position bigint;
|
|
29
|
-
BEGIN
|
|
30
|
-
IF v_expected_stream_position IS NULL THEN
|
|
31
|
-
SELECT COALESCE(max(stream_position), 0) INTO v_expected_stream_position
|
|
32
|
-
FROM ${i.name}
|
|
33
|
-
WHERE stream_id = v_stream_id AND partition = v_partition;
|
|
34
|
-
END IF;
|
|
35
|
-
|
|
36
|
-
v_next_stream_position := v_expected_stream_position + array_upper(v_events_data, 1);
|
|
37
|
-
v_transaction_id := pg_current_xact_id();
|
|
38
|
-
|
|
39
|
-
WITH ev AS (
|
|
40
|
-
SELECT row_number() OVER () + v_expected_stream_position AS stream_position,
|
|
41
|
-
event_data,
|
|
42
|
-
event_metadata,
|
|
43
|
-
schema_version,
|
|
44
|
-
event_id,
|
|
45
|
-
event_type
|
|
46
|
-
FROM (
|
|
47
|
-
SELECT *
|
|
48
|
-
FROM
|
|
49
|
-
unnest(v_event_ids, v_events_data, v_events_metadata, v_event_schema_versions, v_event_types)
|
|
50
|
-
AS event(event_id, event_data, event_metadata, schema_version, event_type)
|
|
51
|
-
) AS event
|
|
52
|
-
),
|
|
53
|
-
all_events_insert AS (
|
|
54
|
-
INSERT INTO ${r.name}
|
|
55
|
-
(stream_id, stream_position, partition, event_data, event_metadata, event_schema_version, event_type, event_id, transaction_id)
|
|
56
|
-
SELECT
|
|
57
|
-
v_stream_id, ev.stream_position, v_partition, ev.event_data, ev.event_metadata, ev.schema_version, ev.event_type, ev.event_id, v_transaction_id
|
|
58
|
-
FROM ev
|
|
59
|
-
RETURNING global_position
|
|
60
|
-
)
|
|
61
|
-
SELECT
|
|
62
|
-
max(global_position) INTO v_last_global_position
|
|
63
|
-
FROM
|
|
64
|
-
all_events_insert;
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
IF v_expected_stream_position = 0 THEN
|
|
68
|
-
INSERT INTO ${i.name}
|
|
69
|
-
(stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
|
|
70
|
-
VALUES
|
|
71
|
-
(v_stream_id, v_next_stream_position, v_partition, v_stream_type, '{}', FALSE);
|
|
72
|
-
ELSE
|
|
73
|
-
UPDATE ${i.name} as s
|
|
74
|
-
SET stream_position = v_next_stream_position
|
|
75
|
-
WHERE stream_id = v_stream_id AND stream_position = v_expected_stream_position AND partition = v_partition AND is_archived = FALSE;
|
|
76
|
-
|
|
77
|
-
get diagnostics v_updated_rows = row_count;
|
|
78
|
-
|
|
79
|
-
IF v_updated_rows = 0 THEN
|
|
80
|
-
RETURN QUERY SELECT FALSE, NULL::bigint, NULL::bigint, NULL::xid8;
|
|
81
|
-
RETURN;
|
|
82
|
-
END IF;
|
|
83
|
-
END IF;
|
|
84
|
-
|
|
85
|
-
RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
|
|
86
|
-
END;
|
|
87
|
-
$$;
|
|
88
|
-
`),ae=(e,t,n,o,a)=>e.withTransaction(async s=>{let{execute:p}=s;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let _=Qe(a?.expectedStreamVersion),h=o.map((I,f)=>({...I,metadata:{streamName:t,eventId:je(),streamPosition:BigInt(f),...I.metadata}}));m=await Xe(p,t,n,h,{expectedStreamVersion:_}),a?.preCommitHook&&await a.preCommitHook(h,{transaction:s})}catch(_){if(!Be(_))throw _;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:E,next_stream_position:c,last_global_position:l,transaction_id:d}=m;return{success:E,result:E&&c&&l&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(l),transactionId:d}:{success:!1}}}),Qe=e=>e===void 0||e===O||e==x||e==D?null:e,Be=e=>e instanceof Error&&"code"in e&&e.code==="23505",Xe=(e,t,n,o,a)=>$e(e.command(L(`SELECT * FROM emt_append_event(
|
|
89
|
-
ARRAY[%s]::text[],
|
|
90
|
-
ARRAY[%s]::jsonb[],
|
|
91
|
-
ARRAY[%s]::jsonb[],
|
|
92
|
-
ARRAY[%s]::text[],
|
|
93
|
-
ARRAY[%s]::text[],
|
|
94
|
-
%L::text,
|
|
95
|
-
%L::text,
|
|
96
|
-
%s::bigint,
|
|
97
|
-
%L::text
|
|
98
|
-
)`,o.map(s=>L("%L",s.metadata.eventId)).join(","),o.map(s=>L("%L",P.stringify(s.data))).join(","),o.map(s=>L("%L",P.stringify(s.metadata??{}))).join(","),o.map(()=>"'1'").join(","),o.map(s=>L("%L",s.type)).join(","),t,n,a?.expectedStreamVersion??"NULL",a?.partition??N)));import{rawSql as g}from"@event-driven-io/dumbo";var re=g(`CREATE TABLE IF NOT EXISTS ${i.name}(
|
|
99
|
-
stream_id TEXT NOT NULL,
|
|
100
|
-
stream_position BIGINT NOT NULL,
|
|
101
|
-
partition TEXT NOT NULL DEFAULT '${v}__${v}',
|
|
102
|
-
stream_type TEXT NOT NULL,
|
|
103
|
-
stream_metadata JSONB NOT NULL,
|
|
104
|
-
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
|
105
|
-
PRIMARY KEY (stream_id, stream_position, partition, is_archived),
|
|
106
|
-
UNIQUE (stream_id, partition, is_archived)
|
|
107
|
-
) PARTITION BY LIST (partition);`),ie=g(`
|
|
108
|
-
CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
|
|
109
|
-
|
|
110
|
-
CREATE TABLE IF NOT EXISTS ${r.name}(
|
|
111
|
-
stream_id TEXT NOT NULL,
|
|
112
|
-
stream_position BIGINT NOT NULL,
|
|
113
|
-
partition TEXT NOT NULL DEFAULT '${v}',
|
|
114
|
-
event_data JSONB NOT NULL,
|
|
115
|
-
event_metadata JSONB NOT NULL,
|
|
116
|
-
event_schema_version TEXT NOT NULL,
|
|
117
|
-
event_type TEXT NOT NULL,
|
|
118
|
-
event_id TEXT NOT NULL,
|
|
119
|
-
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
|
120
|
-
global_position BIGINT DEFAULT nextval('emt_global_event_position'),
|
|
121
|
-
transaction_id XID8 NOT NULL,
|
|
122
|
-
created TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
123
|
-
PRIMARY KEY (stream_id, stream_position, partition, is_archived)
|
|
124
|
-
) PARTITION BY LIST (partition);`),se=g(`
|
|
125
|
-
CREATE TABLE IF NOT EXISTS emt_subscriptions(
|
|
126
|
-
subscription_id TEXT NOT NULL PRIMARY KEY,
|
|
127
|
-
version INT NOT NULL DEFAULT 1,
|
|
128
|
-
module TEXT NULL,
|
|
129
|
-
tenant TEXT NULL,
|
|
130
|
-
last_processed_position BIGINT NOT NULL,
|
|
131
|
-
last_processed_transaction_id BIGINT NOT NULL
|
|
132
|
-
);
|
|
133
|
-
`),ce=g(`CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
|
|
134
|
-
BEGIN
|
|
135
|
-
RETURN REGEXP_REPLACE(input_name, '[^a-zA-Z0-9_]', '_', 'g');
|
|
136
|
-
END;
|
|
137
|
-
$$ LANGUAGE plpgsql;`),me=g(`
|
|
138
|
-
CREATE OR REPLACE FUNCTION emt_add_table_partition(tableName TEXT, partition_name TEXT) RETURNS void AS $$
|
|
139
|
-
DECLARE
|
|
140
|
-
v_main_partiton_name TEXT;
|
|
141
|
-
v_active_partiton_name TEXT;
|
|
142
|
-
v_archived_partiton_name TEXT;
|
|
143
|
-
BEGIN
|
|
144
|
-
v_main_partiton_name := emt_sanitize_name(tableName || '_' || partition_name);
|
|
145
|
-
v_active_partiton_name := emt_sanitize_name(v_main_partiton_name || '_active');
|
|
146
|
-
v_archived_partiton_name := emt_sanitize_name(v_main_partiton_name || '_archived');
|
|
147
|
-
|
|
148
|
-
-- create default events partition
|
|
149
|
-
EXECUTE format('
|
|
150
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
151
|
-
FOR VALUES IN (%L) PARTITION BY LIST (is_archived);',
|
|
152
|
-
v_main_partiton_name, tableName, partition_name
|
|
153
|
-
);
|
|
154
|
-
|
|
155
|
-
-- create default streams partition
|
|
156
|
-
EXECUTE format('
|
|
157
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
158
|
-
FOR VALUES IN (%L) PARTITION BY LIST (is_archived);',
|
|
159
|
-
v_main_partiton_name, tableName, partition_name
|
|
160
|
-
);
|
|
161
|
-
|
|
162
|
-
EXECUTE format('
|
|
163
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
164
|
-
FOR VALUES IN (FALSE);',
|
|
165
|
-
v_active_partiton_name, v_main_partiton_name
|
|
166
|
-
);
|
|
167
|
-
|
|
168
|
-
EXECUTE format('
|
|
169
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
170
|
-
FOR VALUES IN (TRUE);',
|
|
171
|
-
v_archived_partiton_name, v_main_partiton_name
|
|
172
|
-
);
|
|
173
|
-
END;
|
|
174
|
-
$$ LANGUAGE plpgsql;`),de=g(`
|
|
175
|
-
CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
|
|
176
|
-
BEGIN
|
|
177
|
-
PERFORM emt_add_table_partition('${r.name}', partition_name);
|
|
178
|
-
PERFORM emt_add_table_partition('${i.name}', partition_name);
|
|
179
|
-
END;
|
|
180
|
-
$$ LANGUAGE plpgsql;`),Ee=g(`
|
|
181
|
-
CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
|
|
182
|
-
BEGIN
|
|
183
|
-
-- For ${r.name} table
|
|
184
|
-
EXECUTE format('
|
|
185
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
186
|
-
FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
|
|
187
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || '${v}'), '${r.name}', new_module, '${v}'
|
|
188
|
-
);
|
|
189
|
-
|
|
190
|
-
EXECUTE format('
|
|
191
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
192
|
-
FOR VALUES IN (FALSE);',
|
|
193
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || '${v}' || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${v}')
|
|
194
|
-
);
|
|
195
|
-
|
|
196
|
-
EXECUTE format('
|
|
197
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
198
|
-
FOR VALUES IN (TRUE);',
|
|
199
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || '${v}' || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || '${v}')
|
|
200
|
-
);
|
|
201
|
-
|
|
202
|
-
-- For ${i.name} table
|
|
203
|
-
EXECUTE format('
|
|
204
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
205
|
-
FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
|
|
206
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || '${v}'), '${i.name}', new_module, '${v}'
|
|
207
|
-
);
|
|
208
|
-
|
|
209
|
-
EXECUTE format('
|
|
210
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
211
|
-
FOR VALUES IN (FALSE);',
|
|
212
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || '${v}' || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${v}')
|
|
213
|
-
);
|
|
214
|
-
|
|
215
|
-
EXECUTE format('
|
|
216
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
217
|
-
FOR VALUES IN (TRUE);',
|
|
218
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || '${v}' || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${v}')
|
|
219
|
-
);
|
|
220
|
-
END;
|
|
221
|
-
$$ LANGUAGE plpgsql;
|
|
222
|
-
`),le=g(`
|
|
223
|
-
CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
|
|
224
|
-
BEGIN
|
|
225
|
-
-- For ${r.name} table
|
|
226
|
-
EXECUTE format('
|
|
227
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
228
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
229
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant), '${r.name}', new_module, new_tenant
|
|
230
|
-
);
|
|
231
|
-
|
|
232
|
-
EXECUTE format('
|
|
233
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
234
|
-
FOR VALUES IN (FALSE);',
|
|
235
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
|
|
236
|
-
);
|
|
237
|
-
|
|
238
|
-
EXECUTE format('
|
|
239
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
240
|
-
FOR VALUES IN (TRUE);',
|
|
241
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || new_tenant)
|
|
242
|
-
);
|
|
243
|
-
|
|
244
|
-
-- For ${i.name} table
|
|
245
|
-
EXECUTE format('
|
|
246
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
247
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
248
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant), '${i.name}', new_module, new_tenant
|
|
249
|
-
);
|
|
250
|
-
|
|
251
|
-
EXECUTE format('
|
|
252
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
253
|
-
FOR VALUES IN (FALSE);',
|
|
254
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
|
|
255
|
-
);
|
|
256
|
-
|
|
257
|
-
EXECUTE format('
|
|
258
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
259
|
-
FOR VALUES IN (TRUE);',
|
|
260
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
|
|
261
|
-
);
|
|
262
|
-
END;
|
|
263
|
-
$$ LANGUAGE plpgsql;
|
|
264
|
-
`),pe=g(`
|
|
265
|
-
CREATE OR REPLACE FUNCTION add_module_for_all_tenants(new_module TEXT) RETURNS void AS $$
|
|
266
|
-
DECLARE
|
|
267
|
-
tenant_record RECORD;
|
|
268
|
-
BEGIN
|
|
269
|
-
PERFORM add_module(new_module);
|
|
270
|
-
|
|
271
|
-
FOR tenant_record IN SELECT DISTINCT tenant FROM ${r.name}
|
|
272
|
-
LOOP
|
|
273
|
-
-- For ${r.name} table
|
|
274
|
-
EXECUTE format('
|
|
275
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
276
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
277
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant), '${r.name}', new_module, tenant_record.tenant
|
|
278
|
-
);
|
|
279
|
-
|
|
280
|
-
EXECUTE format('
|
|
281
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
282
|
-
FOR VALUES IN (FALSE);',
|
|
283
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
|
|
284
|
-
);
|
|
285
|
-
|
|
286
|
-
EXECUTE format('
|
|
287
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
288
|
-
FOR VALUES IN (TRUE);',
|
|
289
|
-
emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${r.name}_' || new_module || '__' || tenant_record.tenant)
|
|
290
|
-
);
|
|
291
|
-
|
|
292
|
-
-- For ${i.name} table
|
|
293
|
-
EXECUTE format('
|
|
294
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
295
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
296
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant), '${i.name}', new_module, tenant_record.tenant
|
|
297
|
-
);
|
|
298
|
-
|
|
299
|
-
EXECUTE format('
|
|
300
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
301
|
-
FOR VALUES IN (FALSE);',
|
|
302
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
|
|
303
|
-
);
|
|
304
|
-
|
|
305
|
-
EXECUTE format('
|
|
306
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
307
|
-
FOR VALUES IN (TRUE);',
|
|
308
|
-
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
|
|
309
|
-
);
|
|
310
|
-
END LOOP;
|
|
311
|
-
END;
|
|
312
|
-
$$ LANGUAGE plpgsql;
|
|
313
|
-
`),_e=g(`
|
|
314
|
-
CREATE OR REPLACE FUNCTION add_tenant_for_all_modules(new_tenant TEXT) RETURNS void AS $$
|
|
315
|
-
DECLARE
|
|
316
|
-
module_record RECORD;
|
|
317
|
-
BEGIN
|
|
318
|
-
FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${r.name}'
|
|
319
|
-
LOOP
|
|
320
|
-
-- For ${r.name} table
|
|
321
|
-
EXECUTE format('
|
|
322
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
323
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
324
|
-
emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant), '${r.name}', module_record.partitionname, new_tenant
|
|
325
|
-
);
|
|
326
|
-
|
|
327
|
-
EXECUTE format('
|
|
328
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
329
|
-
FOR VALUES IN (FALSE);',
|
|
330
|
-
emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
331
|
-
);
|
|
332
|
-
|
|
333
|
-
EXECUTE format('
|
|
334
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
335
|
-
FOR VALUES IN (TRUE);',
|
|
336
|
-
emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${r.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
337
|
-
);
|
|
338
|
-
|
|
339
|
-
-- For ${i.name} table
|
|
340
|
-
EXECUTE format('
|
|
341
|
-
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
342
|
-
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
343
|
-
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant), '${i.name}', module_record.partitionname, new_tenant
|
|
344
|
-
);
|
|
345
|
-
|
|
346
|
-
EXECUTE format('
|
|
347
|
-
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
348
|
-
FOR VALUES IN (FALSE);',
|
|
349
|
-
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
350
|
-
);
|
|
351
|
-
|
|
352
|
-
EXECUTE format('
|
|
353
|
-
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
354
|
-
FOR VALUES IN (TRUE);',
|
|
355
|
-
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
356
|
-
);
|
|
357
|
-
END LOOP;
|
|
358
|
-
END;
|
|
359
|
-
$$ LANGUAGE plpgsql;
|
|
360
|
-
`),ve=g(`SELECT emt_add_partition('${N}');`);import{mapRows as Ve,sql as Ge}from"@event-driven-io/dumbo";var Te=async(e,t,n)=>{let o=n&&"from"in n?`AND stream_position >= ${n.from}`:"",a=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),s=isNaN(a)?"":`AND stream_position <= ${a}`,p=await Ve(e.query(Ge(`SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
|
|
361
|
-
FROM ${r.name}
|
|
362
|
-
WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${s}`,t,n?.partition??N)),m=>{let E=H(m.event_type,m.event_data,m.event_metadata);return{...E,metadata:{...E.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p}:null};var M=[re,ie,se,ce,me,de,Ee,le,pe,_e,oe,ve],Q=async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(M))};var ze=(n=>(n.None="None",n.CreateOrUpdate="CreateOrUpdate",n))(ze||{}),He={projections:[],schema:{autoMigration:"CreateOrUpdate"}},ke=(e,t=He)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},o="dumbo"in n?n.dumbo:We(n),a,s=t.schema?.autoMigration===void 0||t.schema?.autoMigration!=="None",p=()=>s?(a||(a=Q(o)),a):Promise.resolve(),m=(t.projections??[]).filter(({type:c})=>c==="inline").map(({projection:c})=>c),E=m.length>0?(c,{transaction:l})=>C({projections:m,connection:{connectionString:e,transaction:l},events:c}):void 0;return{schema:{sql:()=>M.join(""),print:()=>console.log(M.join("")),migrate:async()=>{await(a=Q(o))}},async aggregateStream(c,l){let{evolve:d,initialState:_,read:h}=l,I=h?.expectedStreamVersion,f=_(),F=await this.readStream(c,l.read);if(F===null)return null;let B=F.currentStreamVersion;Ye(B,I);for(let X of F.events)X&&(f=d(f,X));return{currentStreamVersion:B,state:f}},readStream:async(c,l)=>(await p(),Te(o.execute,c,l)),appendToStream:async(c,l,d)=>{await p();let[_,...h]=c.split("-"),I=_&&h.length>0?_:"emt:unknown",f=await ae(o,c,I,l,{...d,preCommitHook:E});if(!f.success)throw new U(-1n,d?.expectedStreamVersion??O);return{nextExpectedStreamVersion:f.nextStreamPosition}},close:()=>o.close(),async withSession(c){return await o.withConnection(async l=>{let d={...t,connectionOptions:{connection:l}},_=ke(e,d);return c({eventStore:_,close:()=>Promise.resolve()})})}}},qe=(e,t)=>t===O?!0:t==x?e===void 0:t==D?e!==void 0:e===t,Ye=(e,t)=>{if(t??=O,!qe(e,t))throw new U(e,t)};export{It as PostgreSQLProjectionSpec,ze as SchemaMigration,ve as addDefaultPartition,de as addEventsPartitions,pe as addModuleForAllTenantsSQL,Ee as addModuleSQL,me as addTablePartitions,_e as addTenantForAllModulesSQL,le as addTenantSQL,oe as appendEventsSQL,ae as appendToStream,Me as assertSQLQueryResultMatches,Q as createEventStoreSchema,He as defaultPostgreSQLOptions,N as defaultTag,ee as documentDoesNotExist,Re as documentExists,Z as documentMatchingExists,Ae as documentsAreTheSame,Le as documentsMatchingHaveCount,w as emmettPrefix,we as eventInStream,be as eventsInStream,r as eventsTable,ie as eventsTableSQL,dt as expectPongoDocuments,Nt as expectSQL,ke as getPostgreSQLEventStore,bt as globalNames,v as globalTag,C as handleProjections,Ot as newEventsInStream,Ce as pongoMultiStreamProjection,xe as pongoProjection,vt as pongoSingleStreamProjection,j as postgreSQLProjection,Fe as postgreSQLRawBatchSQLProjection,Dt as postgreSQLRawSQLProjection,Te as readStream,ce as sanitizeNameSQL,M as schemaSQL,i as streamsTable,re as streamsTableSQL,se as subscriptionsTableSQL};
|
|
363
|
-
//# sourceMappingURL=index.mjs.map
|