prostgles-server 2.0.178 → 2.0.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/AuthHandler.d.ts +4 -4
  2. package/dist/AuthHandler.d.ts.map +1 -1
  3. package/dist/DBSchemaBuilder.d.ts +6 -6
  4. package/dist/DBSchemaBuilder.d.ts.map +1 -1
  5. package/dist/DBSchemaBuilder.js +25 -8
  6. package/dist/DBSchemaBuilder.js.map +1 -1
  7. package/dist/DboBuilder.d.ts +20 -21
  8. package/dist/DboBuilder.d.ts.map +1 -1
  9. package/dist/DboBuilder.js +1 -1
  10. package/dist/DboBuilder.js.map +1 -1
  11. package/dist/Prostgles.d.ts +8 -10
  12. package/dist/Prostgles.d.ts.map +1 -1
  13. package/dist/Prostgles.js.map +1 -1
  14. package/dist/PublishParser.d.ts +37 -37
  15. package/dist/PublishParser.d.ts.map +1 -1
  16. package/dist/PublishParser.js.map +1 -1
  17. package/dist/index.d.ts +2 -3
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/lib/AuthHandler.d.ts +148 -0
  21. package/lib/AuthHandler.d.ts.map +1 -0
  22. package/lib/AuthHandler.js +411 -0
  23. package/lib/AuthHandler.ts +3 -3
  24. package/lib/DBEventsManager.d.ts +38 -0
  25. package/lib/DBEventsManager.d.ts.map +1 -0
  26. package/lib/DBEventsManager.js +136 -0
  27. package/lib/DBSchemaBuilder.d.ts +11 -0
  28. package/lib/DBSchemaBuilder.d.ts.map +1 -0
  29. package/lib/DBSchemaBuilder.js +102 -0
  30. package/lib/DBSchemaBuilder.ts +62 -27
  31. package/lib/DboBuilder.d.ts +428 -0
  32. package/lib/DboBuilder.d.ts.map +1 -0
  33. package/lib/DboBuilder.js +3078 -0
  34. package/lib/DboBuilder.ts +25 -25
  35. package/lib/FileManager.d.ts +168 -0
  36. package/lib/FileManager.d.ts.map +1 -0
  37. package/lib/FileManager.js +474 -0
  38. package/lib/Filtering.d.ts +15 -0
  39. package/lib/Filtering.d.ts.map +1 -0
  40. package/lib/Filtering.js +299 -0
  41. package/lib/PostgresNotifListenManager.d.ts +27 -0
  42. package/lib/PostgresNotifListenManager.d.ts.map +1 -0
  43. package/lib/PostgresNotifListenManager.js +122 -0
  44. package/lib/Prostgles.d.ts +193 -0
  45. package/lib/Prostgles.d.ts.map +1 -0
  46. package/lib/Prostgles.js +579 -0
  47. package/lib/Prostgles.ts +6 -6
  48. package/lib/PubSubManager.d.ts +157 -0
  49. package/lib/PubSubManager.d.ts.map +1 -0
  50. package/lib/PubSubManager.js +1400 -0
  51. package/lib/PublishParser.d.ts +262 -0
  52. package/lib/PublishParser.d.ts.map +1 -0
  53. package/lib/PublishParser.js +390 -0
  54. package/lib/PublishParser.ts +39 -38
  55. package/lib/QueryBuilder.d.ts +124 -0
  56. package/lib/QueryBuilder.d.ts.map +1 -0
  57. package/lib/QueryBuilder.js +1349 -0
  58. package/lib/SyncReplication.d.ts +34 -0
  59. package/lib/SyncReplication.d.ts.map +1 -0
  60. package/lib/SyncReplication.js +411 -0
  61. package/lib/TableConfig.d.ts +175 -0
  62. package/lib/TableConfig.d.ts.map +1 -0
  63. package/lib/TableConfig.js +231 -0
  64. package/lib/index.d.ts +10 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +45 -0
  67. package/lib/index.ts +3 -4
  68. package/lib/shortestPath.d.ts +10 -0
  69. package/lib/shortestPath.d.ts.map +1 -0
  70. package/lib/shortestPath.js +111 -0
  71. package/lib/utils.d.ts +2 -0
  72. package/lib/utils.d.ts.map +1 -0
  73. package/lib/utils.js +5 -0
  74. package/package.json +3 -3
  75. package/tests/client/PID.txt +1 -1
  76. package/tests/client/index.d.ts +1 -1
  77. package/tests/client/index.d.ts.map +1 -1
  78. package/tests/client_only_queries.d.ts +4 -0
  79. package/tests/client_only_queries.d.ts.map +1 -0
  80. package/tests/isomorphic_queries.d.ts +6 -0
  81. package/tests/isomorphic_queries.d.ts.map +1 -0
  82. package/tests/server/DBoGenerated.d.ts +97 -193
  83. package/tests/server/dboTypeCheck.d.ts +2 -0
  84. package/tests/server/dboTypeCheck.d.ts.map +1 -0
  85. package/tests/server/dboTypeCheck.js +14 -0
  86. package/tests/server/dboTypeCheck.ts +17 -0
  87. package/tests/server/index.d.ts +2 -0
  88. package/tests/server/index.d.ts.map +1 -0
  89. package/tests/server/index.js +11 -11
  90. package/tests/server/index.ts +23 -16
  91. package/tests/server/package-lock.json +5 -5
  92. package/tests/server/publishTypeCheck.d.ts +2 -0
  93. package/tests/server/publishTypeCheck.d.ts.map +1 -0
  94. package/tests/server/publishTypeCheck.js +120 -0
  95. package/tests/server/publishTypeCheck.ts +129 -0
  96. package/tests/server/tsconfig.json +4 -5
  97. package/tests/server_only_queries.d.ts +2 -0
  98. package/tests/server_only_queries.d.ts.map +1 -0
@@ -0,0 +1,1400 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Stefan L. All rights reserved.
4
+ * Licensed under the MIT License. See LICENSE in the project root for license information.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || function (mod) {
23
+ if (mod && mod.__esModule) return mod;
24
+ var result = {};
25
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
26
+ __setModuleDefault(result, mod);
27
+ return result;
28
+ };
29
+ var _a;
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.pickKeys = exports.omitKeys = exports.PubSubManager = exports.log = exports.DEFAULT_SYNC_BATCH_SIZE = exports.asValue = void 0;
32
+ const PostgresNotifListenManager_1 = require("./PostgresNotifListenManager");
33
+ const utils_1 = require("./utils");
34
+ const Prostgles_1 = require("./Prostgles");
35
+ const Bluebird = __importStar(require("bluebird"));
36
+ const pgPromise = __importStar(require("pg-promise"));
37
+ const prostgles_types_1 = require("prostgles-types");
38
+ const SyncReplication_1 = require("./SyncReplication");
39
+ let pgp = pgPromise({
40
+ promiseLib: Bluebird
41
+ });
42
+ const asValue = (v) => pgp.as.format("$1", [v]);
43
+ exports.asValue = asValue;
44
+ exports.DEFAULT_SYNC_BATCH_SIZE = 50;
45
+ const log = (...args) => {
46
+ if (process.env.TEST_TYPE) {
47
+ console.log(...args);
48
+ }
49
+ };
50
+ exports.log = log;
51
+ class PubSubManager {
52
+ constructor(options) {
53
+ this.onSchemaChange = undefined;
54
+ this.NOTIF_TYPE = {
55
+ data: "data_has_changed",
56
+ schema: "schema_has_changed"
57
+ };
58
+ this.NOTIF_CHANNEL = {
59
+ preffix: 'prostgles_',
60
+ getFull: (appID) => {
61
+ if (!this.appID && !appID)
62
+ throw "No appID";
63
+ return this.NOTIF_CHANNEL.preffix + (appID || this.appID);
64
+ }
65
+ };
66
+ this.appCheckFrequencyMS = 10 * 1000;
67
+ this.destroyed = false;
68
+ this.destroy = () => {
69
+ this.destroyed = true;
70
+ if (this.appCheck) {
71
+ clearInterval(this.appCheck);
72
+ }
73
+ this.onSocketDisconnected();
74
+ // if(this.postgresNotifListenManager){
75
+ // this.postgresNotifListenManager.stopListening();
76
+ // }
77
+ if (!this.postgresNotifListenManager)
78
+ throw "this.postgresNotifListenManager missing";
79
+ this.postgresNotifListenManager.destroy();
80
+ };
81
+ this.canContinue = () => {
82
+ if (this.destroyed) {
83
+ console.trace("Could not start destroyed instance");
84
+ return false;
85
+ }
86
+ return true;
87
+ };
88
+ this.appChecking = false;
89
+ this.init = async () => {
90
+ if (!this.canContinue())
91
+ return undefined;
92
+ try {
93
+ const schema_version = 4;
94
+ const q = `
95
+ BEGIN; -- ISOLATION LEVEL SERIALIZABLE;-- TRANSACTION ISOLATION LEVEL SERIALIZABLE;
96
+
97
+ --SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
98
+
99
+ /*
100
+ * ${PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID}
101
+ */
102
+
103
+ DO
104
+ $do$
105
+ BEGIN
106
+
107
+ /* Reduce deadlocks */
108
+ PERFORM pg_sleep(random());
109
+
110
+ /* Drop older version */
111
+ IF EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'prostgles') THEN
112
+
113
+ IF
114
+ NOT EXISTS (
115
+ SELECT 1
116
+ FROM information_schema.tables
117
+ WHERE table_schema = 'prostgles'
118
+ AND table_name = 'versions'
119
+ )
120
+ THEN
121
+ DROP SCHEMA IF EXISTS prostgles CASCADE;
122
+ ELSE
123
+ IF NOT EXISTS(SELECT 1 FROM prostgles.versions WHERE version >= ${schema_version}) THEN
124
+ DROP SCHEMA IF EXISTS prostgles CASCADE;
125
+ END IF;
126
+ END IF;
127
+
128
+ END IF;
129
+
130
+
131
+ IF NOT EXISTS (SELECT 1 FROM information_schema.schemata WHERE schema_name = 'prostgles')
132
+ THEN
133
+ --RAISE NOTICE 'CREATE SCHEMA IF NOT EXISTS prostgles';
134
+
135
+ CREATE SCHEMA IF NOT EXISTS prostgles;
136
+
137
+ CREATE TABLE IF NOT EXISTS prostgles.versions(
138
+ version NUMERIC PRIMARY KEY
139
+ );
140
+ INSERT INTO prostgles.versions(version) VALUES(${schema_version}) ON CONFLICT DO NOTHING;
141
+
142
+ CREATE OR REPLACE FUNCTION prostgles.random_string(length INTEGER DEFAULT 33) RETURNS TEXT AS $$
143
+ DECLARE
144
+ chars TEXT[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
145
+ result TEXT := '';
146
+ i INTEGER := 0;
147
+ BEGIN
148
+ IF length < 0 THEN
149
+ RAISE exception 'Given length cannot be less than 0';
150
+ END IF;
151
+ FOR i IN 1..length LOOP
152
+ result := result || chars[1+random()*(array_length(chars, 1)-1)];
153
+ END LOOP;
154
+ RETURN result;
155
+ END;
156
+ $$ language plpgsql;
157
+ COMMENT ON FUNCTION prostgles.random_string IS 'UUIDs without installing pgcrypto';
158
+
159
+
160
+ CREATE OR REPLACE FUNCTION prostgles.debug(VARIADIC args TEXT[]) RETURNS VOID AS $$
161
+ BEGIN
162
+
163
+ --PERFORM pg_notify('debug', concat_ws(' ', args));
164
+ IF
165
+ NOT EXISTS (
166
+ SELECT 1
167
+ FROM information_schema.tables
168
+ WHERE table_schema = 'prostgles'
169
+ AND table_name = 'debug'
170
+ )
171
+ THEN
172
+ CREATE TABLE IF NOT EXISTS prostgles.debug(m TEXT);
173
+ END IF;
174
+
175
+ INSERT INTO prostgles.debug(m) VALUES(concat_ws(' ', args));
176
+
177
+ END;
178
+ $$ LANGUAGE plpgsql;
179
+ COMMENT ON FUNCTION prostgles.debug IS 'Used for internal debugging';
180
+
181
+
182
+ CREATE TABLE IF NOT EXISTS prostgles.apps (
183
+ id TEXT PRIMARY KEY DEFAULT prostgles.random_string(),
184
+ added TIMESTAMP DEFAULT NOW(),
185
+ application_name TEXT,
186
+ last_check TIMESTAMP NOT NULL DEFAULT NOW(),
187
+ last_check_ended TIMESTAMP NOT NULL DEFAULT NOW(),
188
+ watching_schema BOOLEAN DEFAULT FALSE,
189
+ check_frequency_ms INTEGER NOT NULL
190
+ );
191
+ COMMENT ON TABLE prostgles.apps IS 'Keep track of prostgles server apps connected to db to combine common triggers. Heartbeat used due to no logout triggers in postgres';
192
+
193
+ /*
194
+ CREATE TABLE IF NOT EXISTS prostgles.triggers (
195
+ table_name TEXT NOT NULL,
196
+ condition TEXT NOT NULL,
197
+ app_ids TEXT[] NOT NULL,
198
+ inserted TIMESTAMP NOT NULL DEFAULT NOW(),
199
+ last_used TIMESTAMP NOT NULL DEFAULT NOW(),
200
+ PRIMARY KEY (table_name, condition)
201
+ );
202
+ COMMENT ON TABLE prostgles.triggers IS 'Tables and conditions that are currently subscribed/synced';
203
+ */
204
+
205
+ CREATE TABLE IF NOT EXISTS prostgles.app_triggers (
206
+ app_id TEXT NOT NULL,
207
+ table_name TEXT NOT NULL,
208
+ condition TEXT NOT NULL,
209
+ inserted TIMESTAMP NOT NULL DEFAULT NOW(),
210
+ last_used TIMESTAMP NOT NULL DEFAULT NOW(),
211
+ PRIMARY KEY (app_id, table_name, condition)
212
+ );
213
+ COMMENT ON TABLE prostgles.app_triggers IS 'Tables and conditions that are currently subscribed/synced';
214
+
215
+
216
+ CREATE OR REPLACE VIEW prostgles.v_triggers AS
217
+ SELECT *
218
+ , (ROW_NUMBER() OVER( ORDER BY table_name, condition ))::text AS id
219
+ -- , concat_ws('-', table_name, condition) AS id
220
+ , ROW_NUMBER() OVER(PARTITION BY app_id, table_name ORDER BY table_name, condition ) - 1 AS c_id
221
+ FROM prostgles.app_triggers;
222
+ COMMENT ON VIEW prostgles.v_triggers IS 'Augment trigger table with natural IDs and per app IDs';
223
+
224
+
225
+ /*
226
+ CREATE OR REPLACE VIEW prostgles.v_triggers_unnested AS
227
+ SELECT *
228
+ , ROW_NUMBER() OVER(PARTITION BY app_id, table_name ORDER BY table_name, condition ) - 1 AS c_id
229
+ FROM (
230
+ SELECT *, unnest(app_ids) as app_id
231
+ FROM prostgles.v_triggers
232
+ ) t;
233
+
234
+ -- Force table into cache
235
+ IF EXISTS (select * from pg_extension where extname = 'pg_prewarm') THEN
236
+ CREATE EXTENSION IF NOT EXISTS pg_prewarm;
237
+ PERFORM pg_prewarm('prostgles.app_triggers');
238
+ END IF;
239
+ */
240
+
241
+
242
+ CREATE OR REPLACE FUNCTION ${this.DB_OBJ_NAMES.data_watch_func}() RETURNS TRIGGER
243
+ AS $$
244
+
245
+ DECLARE t_ids TEXT[];
246
+ DECLARE c_ids INTEGER[];
247
+ DECLARE err_c_ids INTEGER[];
248
+ DECLARE unions TEXT := '';
249
+ DECLARE query TEXT := '';
250
+ DECLARE nrw RECORD;
251
+ DECLARE erw RECORD;
252
+ DECLARE has_errors BOOLEAN := FALSE;
253
+
254
+ DECLARE err_text TEXT;
255
+ DECLARE err_detail TEXT;
256
+ DECLARE err_hint TEXT;
257
+
258
+ BEGIN
259
+
260
+ -- PERFORM pg_notify('debug', concat_ws(' ', 'TABLE', TG_TABLE_NAME, TG_OP));
261
+
262
+ SELECT string_agg(
263
+ concat_ws(
264
+ E' UNION \n ',
265
+ CASE WHEN (TG_OP = 'DELETE' OR TG_OP = 'UPDATE') THEN (p1 || ' old_table ' || p2) END,
266
+ CASE WHEN (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN (p1 || ' new_table ' || p2) END
267
+ ),
268
+ E' UNION \n '::text
269
+ )
270
+ INTO unions
271
+ FROM (
272
+ SELECT
273
+ $z$ SELECT CASE WHEN EXISTS( SELECT 1 FROM $z$ AS p1,
274
+ format(
275
+ $c$ as %I WHERE %s ) THEN %s::text END AS t_ids $c$
276
+ , table_name, condition, id
277
+ ) AS p2
278
+ FROM prostgles.v_triggers
279
+ WHERE table_name = TG_TABLE_NAME
280
+ ) t;
281
+
282
+ /*
283
+ PERFORM pg_notify(
284
+ ${(0, exports.asValue)(this.NOTIF_CHANNEL.preffix)} || (SELECT id FROM prostgles.apps LIMIT 1) ,
285
+ concat_ws(
286
+ ${(0, exports.asValue)(PubSubManager.DELIMITER)},
287
+
288
+ ${(0, exports.asValue)(this.NOTIF_TYPE.data)},
289
+ COALESCE(TG_TABLE_NAME, 'MISSING'),
290
+ COALESCE(TG_OP, 'MISSING'),
291
+ unions
292
+ )
293
+ );
294
+ RAISE 'unions: % , cids: %', unions, c_ids;
295
+ */
296
+
297
+ IF unions IS NOT NULL THEN
298
+ query = format(
299
+ $s$
300
+ SELECT ARRAY_AGG(DISTINCT t.t_ids)
301
+ FROM ( %s ) t
302
+ $s$,
303
+ unions
304
+ );
305
+
306
+ BEGIN
307
+ EXECUTE query INTO t_ids;
308
+
309
+ --RAISE NOTICE 'trigger fired ok';
310
+
311
+ EXCEPTION WHEN OTHERS THEN
312
+
313
+ has_errors := TRUE;
314
+
315
+ GET STACKED DIAGNOSTICS
316
+ err_text = MESSAGE_TEXT,
317
+ err_detail = PG_EXCEPTION_DETAIL,
318
+ err_hint = PG_EXCEPTION_HINT;
319
+
320
+
321
+ END;
322
+
323
+ --RAISE NOTICE 'has_errors: % ', has_errors;
324
+ --RAISE NOTICE 'unions: % , cids: %', unions, c_ids;
325
+
326
+ IF (t_ids IS NOT NULL OR has_errors) THEN
327
+
328
+ FOR nrw IN
329
+ SELECT app_id, string_agg(c_id::text, ',') as cids
330
+ FROM prostgles.v_triggers
331
+ WHERE id = ANY(t_ids)
332
+ OR has_errors
333
+ GROUP BY app_id
334
+ LOOP
335
+
336
+ PERFORM pg_notify(
337
+ ${(0, exports.asValue)(this.NOTIF_CHANNEL.preffix)} || nrw.app_id ,
338
+ concat_ws(
339
+ ${(0, exports.asValue)(PubSubManager.DELIMITER)},
340
+
341
+ ${(0, exports.asValue)(this.NOTIF_TYPE.data)},
342
+ COALESCE(TG_TABLE_NAME, 'MISSING'),
343
+ COALESCE(TG_OP, 'MISSING'),
344
+ CASE WHEN has_errors
345
+ THEN concat_ws('; ', 'error', err_text, err_detail, err_hint )
346
+ ELSE COALESCE(nrw.cids, '')
347
+ END
348
+ )
349
+ );
350
+ END LOOP;
351
+
352
+
353
+ IF has_errors THEN
354
+
355
+ DELETE FROM prostgles.app_triggers;
356
+ RAISE NOTICE 'trigger dropped due to exception: % % %', err_text, err_detail, err_hint;
357
+
358
+ END IF;
359
+
360
+
361
+ END IF;
362
+ END IF;
363
+
364
+
365
+ RETURN NULL;
366
+
367
+ /*
368
+ EXCEPTION WHEN OTHERS THEN
369
+ DELETE FROM prostgles.app_triggers; -- delete all or will need to loop through all conditions to find issue;
370
+ RAISE NOTICE 'trigger dropped due to exception';
371
+ ${"--EXCEPTION_WHEN_COLUMN_WAS_RENAMED_THEN_DROP_TRIGGER"};
372
+
373
+
374
+
375
+ RETURN NULL;
376
+ */
377
+ END;
378
+
379
+ --COMMIT;
380
+ $$ LANGUAGE plpgsql;
381
+ COMMENT ON FUNCTION ${this.DB_OBJ_NAMES.data_watch_func} IS 'Prostgles internal function used to notify when data in the table changed';
382
+
383
+
384
+
385
+ CREATE OR REPLACE FUNCTION ${this.DB_OBJ_NAMES.trigger_add_remove_func}() RETURNS TRIGGER
386
+ AS $$
387
+
388
+ DECLARE operations TEXT[] := ARRAY['insert', 'update', 'delete'];
389
+ DECLARE op TEXT;
390
+ DECLARE query TEXT;
391
+ DECLARE trw RECORD;
392
+
393
+ BEGIN
394
+
395
+
396
+ --RAISE NOTICE 'prostgles.app_triggers % ', TG_OP;
397
+
398
+ /* If no other listeners on table then DROP triggers */
399
+ IF TG_OP = 'DELETE' THEN
400
+
401
+ --RAISE NOTICE 'DELETE trigger_add_remove_func table: % ', ' ' || COALESCE((SELECT concat_ws(' ', string_agg(table_name, ' & '), count(*), min(inserted) ) FROM prostgles.app_triggers) , ' 0 ');
402
+ --RAISE NOTICE 'DELETE trigger_add_remove_func old_table: % ', '' || COALESCE((SELECT concat_ws(' ', string_agg(table_name, ' & '), count(*), min(inserted) ) FROM old_table), ' 0 ');
403
+
404
+
405
+ /* Drop actual triggers if needed */
406
+ FOR trw IN
407
+ SELECT DISTINCT table_name FROM old_table ot
408
+ WHERE NOT EXISTS (
409
+ SELECT 1 FROM prostgles.app_triggers t
410
+ WHERE t.table_name = ot.table_name
411
+ )
412
+ LOOP
413
+
414
+ FOREACH op IN ARRAY operations
415
+ LOOP
416
+ --RAISE NOTICE ' DROP DATA TRIGGER FOR: % ', trw.table_name;
417
+ EXECUTE format(' DROP TRIGGER IF EXISTS %I ON %I ;' , 'prostgles_triggers_' || trw.table_name || '_' || op, trw.table_name);
418
+ END LOOP;
419
+
420
+ END LOOP;
421
+
422
+ /* If newly added listeners on table then CREATE triggers */
423
+ ELSIF TG_OP = 'INSERT' THEN
424
+
425
+
426
+ --RAISE NOTICE 'INSERT trigger_add_remove_func table: % ', ' ' || COALESCE((SELECT concat_ws(' ', string_agg(table_name, ' & '), count(*), min(inserted) ) FROM prostgles.triggers) , ' 0 ');
427
+ --RAISE NOTICE 'INSERT trigger_add_remove_func new_table: % ', '' || COALESCE((SELECT concat_ws(' ', string_agg(table_name, ' & '), count(*), min(inserted) ) FROM new_table), ' 0 ');
428
+
429
+ /* Loop through newly added tables */
430
+ FOR trw IN
431
+
432
+ SELECT DISTINCT table_name
433
+ FROM new_table nt
434
+
435
+ /* Table did not exist prior to this insert */
436
+ WHERE NOT EXISTS (
437
+ SELECT 1
438
+ FROM prostgles.app_triggers t
439
+ WHERE t.table_name = nt.table_name
440
+ AND t.inserted < nt.inserted -- exclude current record (this is an after trigger). Turn into before trigger?
441
+ )
442
+
443
+ /* Table is valid */
444
+ AND EXISTS (
445
+ SELECT 1
446
+ FROM information_schema.tables
447
+ WHERE table_schema = 'public'
448
+ AND table_name = nt.table_name
449
+ )
450
+ LOOP
451
+
452
+ /*
453
+ RAISE NOTICE ' CREATE DATA TRIGGER FOR: % TABLE EXISTS?', trw.table_name, SELECT EXISTS (
454
+ SELECT 1
455
+ FROM information_schema.tables
456
+ WHERE table_schema = 'public'
457
+ AND table_name = nt.table_name
458
+ );
459
+ */
460
+
461
+ query := format(
462
+ $q$
463
+ DROP TRIGGER IF EXISTS %1$I ON %2$I;
464
+ CREATE TRIGGER %1$I
465
+ AFTER INSERT ON %2$I
466
+ REFERENCING NEW TABLE AS new_table
467
+ FOR EACH STATEMENT EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.data_watch_func}();
468
+ COMMENT ON TRIGGER %1$I ON %2$I IS 'Prostgles internal trigger used to notify when data in the table changed';
469
+ $q$,
470
+ 'prostgles_triggers_' || trw.table_name || '_insert', trw.table_name
471
+ ) || format(
472
+ $q$
473
+ DROP TRIGGER IF EXISTS %1$I ON %2$I;
474
+ CREATE TRIGGER %1$I
475
+ AFTER UPDATE ON %2$I
476
+ REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table
477
+ FOR EACH STATEMENT EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.data_watch_func}();
478
+ COMMENT ON TRIGGER %1$I ON %2$I IS 'Prostgles internal trigger used to notify when data in the table changed';
479
+ $q$,
480
+ 'prostgles_triggers_' || trw.table_name || '_update', trw.table_name
481
+ ) || format(
482
+ $q$
483
+ DROP TRIGGER IF EXISTS %1$I ON %2$I;
484
+ CREATE TRIGGER %1$I
485
+ AFTER DELETE ON %2$I
486
+ REFERENCING OLD TABLE AS old_table
487
+ FOR EACH STATEMENT EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.data_watch_func}();
488
+ COMMENT ON TRIGGER %1$I ON %2$I IS 'Prostgles internal trigger used to notify when data in the table changed';
489
+ $q$,
490
+ 'prostgles_triggers_' || trw.table_name || '_delete', trw.table_name
491
+ );
492
+
493
+ --RAISE NOTICE ' % ', query;
494
+
495
+
496
+ query := format(
497
+ $q$
498
+ DO $e$
499
+ BEGIN
500
+
501
+ IF EXISTS (
502
+ SELECT 1
503
+ FROM information_schema.tables
504
+ WHERE table_schema = 'public'
505
+ AND table_name = %L
506
+ ) THEN
507
+
508
+ %s
509
+
510
+ END IF;
511
+
512
+ END $e$;
513
+ $q$,
514
+ trw.table_name,
515
+ query
516
+ ) ;
517
+
518
+
519
+ EXECUTE query;
520
+
521
+ END LOOP;
522
+
523
+ END IF;
524
+
525
+
526
+ RETURN NULL;
527
+ END;
528
+
529
+ $$ LANGUAGE plpgsql;
530
+ COMMENT ON FUNCTION ${this.DB_OBJ_NAMES.trigger_add_remove_func} IS 'Used to add/remove table watch triggers concurrently ';
531
+
532
+ DROP TRIGGER IF EXISTS prostgles_triggers_insert ON prostgles.app_triggers;
533
+ CREATE TRIGGER prostgles_triggers_insert
534
+ AFTER INSERT ON prostgles.app_triggers
535
+ REFERENCING NEW TABLE AS new_table
536
+ FOR EACH STATEMENT EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.trigger_add_remove_func}();
537
+
538
+ DROP TRIGGER IF EXISTS prostgles_triggers_delete ON prostgles.app_triggers;
539
+ CREATE TRIGGER prostgles_triggers_delete
540
+ AFTER DELETE ON prostgles.app_triggers
541
+ REFERENCING OLD TABLE AS old_table
542
+ FOR EACH STATEMENT EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.trigger_add_remove_func}();
543
+
544
+
545
+ CREATE OR REPLACE FUNCTION ${this.DB_OBJ_NAMES.schema_watch_func}() RETURNS event_trigger AS $$
546
+
547
+ DECLARE curr_query TEXT := '';
548
+ DECLARE arw RECORD;
549
+
550
+ BEGIN
551
+
552
+ --RAISE NOTICE 'SCHEMA_WATCH: %', tg_tag;
553
+
554
+ IF
555
+ EXISTS (
556
+ SELECT 1
557
+ FROM information_schema.tables
558
+ WHERE table_schema = 'prostgles'
559
+ AND table_name = 'apps'
560
+ )
561
+ THEN
562
+
563
+ SELECT LEFT(COALESCE(current_query(), ''), 5000)
564
+ INTO curr_query;
565
+
566
+ FOR arw IN
567
+ SELECT * FROM prostgles.apps WHERE watching_schema IS TRUE
568
+
569
+ LOOP
570
+ PERFORM pg_notify(
571
+ ${(0, exports.asValue)(this.NOTIF_CHANNEL.preffix)} || arw.id,
572
+ concat_ws(
573
+ ${(0, exports.asValue)(PubSubManager.DELIMITER)},
574
+ ${(0, exports.asValue)(this.NOTIF_TYPE.schema)}, tg_tag , TG_event, curr_query
575
+ )
576
+ );
577
+ END LOOP;
578
+
579
+ END IF;
580
+
581
+ END;
582
+ $$ LANGUAGE plpgsql;
583
+ COMMENT ON FUNCTION ${this.DB_OBJ_NAMES.schema_watch_func} IS 'Prostgles internal function used to notify when schema has changed';
584
+
585
+ END IF;
586
+
587
+ END
588
+ $do$;
589
+
590
+
591
+ COMMIT;
592
+ `;
593
+ // const prgl_exists = await this.db.oneOrNone(`
594
+ // DROP SCHEMA IF EXISTS prostgles CASCADE;
595
+ // SELECT 1 FROM information_schema.schemata WHERE schema_name = 'prostgles'
596
+ // `);
597
+ // if(!prgl_exists){
598
+ // await this.db.any(q);
599
+ // }
600
+ await this.db.any(q);
601
+ if (!this.canContinue())
602
+ return;
603
+ /* Prepare App id */
604
+ if (!this.appID) {
605
+ const raw = await this.db.one("INSERT INTO prostgles.apps (check_frequency_ms, watching_schema, application_name) VALUES($1, $2, current_setting('application_name')) RETURNING *; ", [this.appCheckFrequencyMS, Boolean(this.onSchemaChange)]);
606
+ this.appID = raw.id;
607
+ if (!this.appCheck) {
608
+ this.appCheck = setInterval(async () => {
609
+ let appQ = "";
610
+ try { // drop owned by api
611
+ this.appChecking = true;
612
+ let trgUpdateLastUsed = "", listeners = this.getActiveListeners();
613
+ if (listeners.length) {
614
+ trgUpdateLastUsed = `
615
+ UPDATE prostgles.app_triggers
616
+ SET last_used = CASE WHEN (table_name, condition) IN (
617
+ ${listeners.map(l => ` ( ${(0, exports.asValue)(l.table_name)}, ${(0, exports.asValue)(l.condition)} ) `).join(", ")}
618
+ ) THEN NOW() ELSE last_used END
619
+ WHERE app_id = ${(0, exports.asValue)(this.appID)};
620
+ `;
621
+ }
622
+ appQ = `
623
+
624
+ DO $$
625
+ BEGIN
626
+
627
+ /* prostgles schema must exist */
628
+ IF
629
+ EXISTS (
630
+ SELECT 1
631
+ FROM information_schema.tables
632
+ WHERE table_schema = 'prostgles'
633
+ AND table_name = 'apps'
634
+ )
635
+ THEN
636
+
637
+
638
+ /* Concurrency control to avoid deadlock
639
+ IF NOT EXISTS (
640
+ SELECT 1 FROM prostgles.apps
641
+ WHERE last_check < last_check_ended
642
+ AND last_check_ended > NOW() - interval '5 minutes'
643
+ ) THEN
644
+ */
645
+ UPDATE prostgles.apps
646
+ SET last_check = NOW()
647
+ WHERE id = ${(0, exports.asValue)(this.appID)};
648
+
649
+
650
+
651
+ /* Delete unused triggers. Might deadlock */
652
+ IF EXISTS ( SELECT 1 FROM prostgles.app_triggers)
653
+
654
+ /* If this is the latest app then proceed
655
+ AND (
656
+ SELECT id = ${(0, exports.asValue)(this.appID)}
657
+ FROM prostgles.apps
658
+ ORDER BY last_check DESC
659
+ LIMIT 1
660
+ ) = TRUE
661
+ */
662
+
663
+ THEN
664
+
665
+ /* TODO: Fixed deadlocks */
666
+ --LOCK TABLE prostgles.app_triggers IN ACCESS EXCLUSIVE MODE;
667
+
668
+ /* UPDATE currently used triggers */
669
+ ${trgUpdateLastUsed}
670
+
671
+ /* DELETE stale triggers for current app. Other triggers will be deleted on app startup */
672
+ DELETE FROM prostgles.app_triggers
673
+ WHERE app_id = ${(0, exports.asValue)(this.appID)}
674
+ AND last_used < NOW() - 4 * ${(0, exports.asValue)(this.appCheckFrequencyMS)} * interval '1 millisecond';
675
+
676
+ END IF;
677
+
678
+
679
+
680
+ UPDATE prostgles.apps
681
+ SET last_check_ended = NOW()
682
+ WHERE id = ${(0, exports.asValue)(this.appID)};
683
+
684
+ /*
685
+ END IF;
686
+ */
687
+
688
+
689
+ END IF;
690
+
691
+ -- must not commit without a lock
692
+ --COMMIT;
693
+ END $$;
694
+ `;
695
+ await this.db.any(appQ);
696
+ (0, exports.log)("updated last_check");
697
+ }
698
+ catch (e) {
699
+ console.error("appCheck FAILED: \n", e, appQ);
700
+ }
701
+ this.appChecking = false;
702
+ }, 0.8 * this.appCheckFrequencyMS);
703
+ }
704
+ }
705
+ this.postgresNotifListenManager = new PostgresNotifListenManager_1.PostgresNotifListenManager(this.db, this.notifListener, this.NOTIF_CHANNEL.getFull());
706
+ await this.prepareTriggers();
707
+ return this;
708
+ }
709
+ catch (e) {
710
+ console.error("PubSubManager init failed: ", e);
711
+ }
712
+ };
713
+ this.DB_OBJ_NAMES = {
714
+ trigger_add_remove_func: "prostgles.trigger_add_remove_func",
715
+ data_watch_func: "prostgles.prostgles_trigger_function",
716
+ schema_watch_func: "prostgles.schema_watch_func",
717
+ schema_watch_trigger: "prostgles_schema_watch_trigger_new"
718
+ };
719
+ this.prepareTriggers = async () => {
720
+ // SELECT * FROM pg_catalog.pg_event_trigger WHERE evtname
721
+ if (!this.appID)
722
+ throw "prepareTriggers failed: this.appID missing";
723
+ if (this.dboBuilder.prostgles.opts.watchSchema && !(await (0, Prostgles_1.isSuperUser)(this.db))) {
724
+ console.warn("prostgles watchSchema requires superuser db user. Will not watch");
725
+ }
726
+ try {
727
+ await this.db.any(`
728
+ BEGIN;-- ISOLATION LEVEL SERIALIZABLE;
729
+
730
+ /** ${PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID}
731
+ * Drop stale triggers
732
+ * */
733
+ DO
734
+ $do$
735
+ DECLARE trg RECORD;
736
+ q TEXT;
737
+ ev_trg_needed BOOLEAN := FALSE;
738
+ ev_trg_exists BOOLEAN := FALSE;
739
+ is_super_user BOOLEAN := FALSE;
740
+ BEGIN
741
+ --SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
742
+
743
+ LOCK TABLE prostgles.app_triggers IN ACCESS EXCLUSIVE MODE;
744
+ EXECUTE format(
745
+ $q$
746
+
747
+ CREATE TEMP TABLE %1$I AS --ON COMMIT DROP AS
748
+ SELECT * FROM prostgles.app_triggers;
749
+
750
+ DELETE FROM prostgles.app_triggers;
751
+
752
+ INSERT INTO prostgles.app_triggers
753
+ SELECT * FROM %1$I;
754
+
755
+ DROP TABLE IF EXISTS %1$I;
756
+ $q$,
757
+ ${(0, exports.asValue)('triggers_' + this.appID)}
758
+ );
759
+
760
+ is_super_user := EXISTS (select 1 from pg_user where usename = CURRENT_USER AND usesuper IS TRUE);
761
+ /**
762
+ * Delete stale app records
763
+ * */
764
+
765
+ DELETE FROM prostgles.apps
766
+ WHERE last_check < NOW() - 8 * check_frequency_ms * interval '1 millisecond';
767
+
768
+ DELETE FROM prostgles.app_triggers
769
+ WHERE app_id NOT IN (SELECT id FROM prostgles.apps);
770
+
771
+ /* DROP the old buggy schema watch trigger */
772
+ IF EXISTS (
773
+ SELECT 1 FROM pg_catalog.pg_event_trigger
774
+ WHERE evtname = 'prostgles_schema_watch_trigger'
775
+ ) AND is_super_user IS TRUE
776
+ THEN
777
+ DROP EVENT TRIGGER IF EXISTS prostgles_schema_watch_trigger;
778
+ END IF;
779
+
780
+ ev_trg_needed := EXISTS (SELECT 1 FROM prostgles.apps WHERE watching_schema IS TRUE);
781
+ ev_trg_exists := EXISTS (
782
+ SELECT 1 FROM pg_catalog.pg_event_trigger
783
+ WHERE evtname = ${(0, exports.asValue)(this.DB_OBJ_NAMES.schema_watch_trigger)}
784
+ );
785
+
786
+ -- RAISE NOTICE ' ev_trg_needed %, ev_trg_exists %', ev_trg_needed, ev_trg_exists;
787
+
788
+ /**
789
+ * DROP stale event trigger
790
+ * */
791
+ IF is_super_user IS TRUE AND ev_trg_needed IS FALSE AND ev_trg_exists IS TRUE THEN
792
+
793
+ SELECT format(
794
+ $$ DROP EVENT TRIGGER IF EXISTS %I ; $$
795
+ , ${(0, exports.asValue)(this.DB_OBJ_NAMES.schema_watch_trigger)}
796
+ )
797
+ INTO q;
798
+
799
+ --RAISE NOTICE ' DROP EVENT TRIGGER %', q;
800
+
801
+ EXECUTE q;
802
+
803
+ /**
804
+ * CREATE event trigger
805
+ * */
806
+ ELSIF
807
+ is_super_user IS TRUE
808
+ AND ev_trg_needed IS TRUE
809
+ AND ev_trg_exists IS FALSE
810
+ THEN
811
+
812
+ DROP EVENT TRIGGER IF EXISTS ${this.DB_OBJ_NAMES.schema_watch_trigger};
813
+ CREATE EVENT TRIGGER ${this.DB_OBJ_NAMES.schema_watch_trigger} ON ddl_command_end
814
+ WHEN TAG IN ('CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'CREATE VIEW', 'DROP VIEW', 'ALTER VIEW', 'CREATE TABLE AS', 'SELECT INTO')
815
+ --WHEN TAG IN ('CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'CREATE TRIGGER', 'DROP TRIGGER')
816
+ EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.schema_watch_func}();
817
+
818
+ --RAISE NOTICE ' CREATED EVENT TRIGGER %', q;
819
+ END IF;
820
+
821
+
822
+ END
823
+ $do$;
824
+
825
+
826
+ COMMIT;
827
+ `).catch(e => {
828
+ console.error("prepareTriggers failed: ", e);
829
+ throw e;
830
+ });
831
+ return true;
832
+ }
833
+ catch (e) {
834
+ console.error("prepareTriggers failed: ", e);
835
+ throw e;
836
+ }
837
+ };
838
+ /* Relay relevant data to relevant subscriptions */
839
+ this.notifListener = async (data) => {
840
+ const str = data.payload;
841
+ if (!str) {
842
+ console.error("Empty notif?");
843
+ return;
844
+ }
845
+ const dataArr = str.split(PubSubManager.DELIMITER), notifType = dataArr[0];
846
+ (0, exports.log)(str);
847
+ if (notifType === this.NOTIF_TYPE.schema) {
848
+ if (this.onSchemaChange) {
849
+ const command = dataArr[1], event_type = dataArr[2], query = dataArr[3];
850
+ if (query) {
851
+ this.onSchemaChange({ command, query });
852
+ }
853
+ }
854
+ return;
855
+ }
856
+ if (notifType !== this.NOTIF_TYPE.data) {
857
+ console.error("Unexpected notif type: ", notifType);
858
+ return;
859
+ }
860
+ const table_name = dataArr[1], op_name = dataArr[2], condition_ids_str = dataArr[3];
861
+ // const triggers = await this.db.any("SELECT * FROM prostgles.triggers WHERE table_name = $1 AND id IN ($2:csv)", [table_name, condition_ids_str.split(",").map(v => +v)]);
862
+ // const conditions: string[] = triggers.map(t => t.condition);
863
+ (0, exports.log)("PG Trigger ->", dataArr.join("__"));
864
+ if (condition_ids_str && condition_ids_str.startsWith("error") &&
865
+ this._triggers && this._triggers[table_name] && this._triggers[table_name].length) {
866
+ const pref = "INTERNAL ERROR. Schema might have changed";
867
+ console.error(`${pref}: ${condition_ids_str}`);
868
+ this._triggers[table_name].map(c => {
869
+ const subs = this.getSubs(table_name, c);
870
+ subs.map(s => {
871
+ this.pushSubData(s, pref + ". Check server logs");
872
+ });
873
+ });
874
+ }
875
+ else if (condition_ids_str &&
876
+ condition_ids_str.split(",").length &&
877
+ !condition_ids_str.split(",").find((c) => !Number.isInteger(+c)) &&
878
+ this._triggers && this._triggers[table_name] && this._triggers[table_name].length) {
879
+ const idxs = condition_ids_str.split(",").map(v => +v);
880
+ const conditions = this._triggers[table_name].filter((c, i) => idxs.includes(i));
881
+ (0, exports.log)("PG Trigger -> ", { table_name, op_name, condition_ids_str, conditions }, this._triggers[table_name]);
882
+ conditions.map(condition => {
883
+ const subs = this.getSubs(table_name, condition);
884
+ const syncs = this.getSyncs(table_name, condition);
885
+ syncs.map((s) => {
886
+ this.syncData(s, undefined, "trigger");
887
+ });
888
+ if (!subs) {
889
+ // console.error(`sub missing for ${table_name} ${condition}`, this.triggers);
890
+ // console.log(this.subs)
891
+ return;
892
+ }
893
+ /* Throttle the subscriptions */
894
+ for (var i = 0; i < subs.length; i++) {
895
+ var sub = subs[i];
896
+ if (this.dbo[sub.table_name] &&
897
+ sub.is_ready &&
898
+ (sub.socket_id && this.sockets[sub.socket_id]) || sub.func) {
899
+ const throttle = sub.throttle || 0;
900
+ if (sub.last_throttled <= Date.now() - throttle) {
901
+ /* It is assumed the policy was checked before this point */
902
+ this.pushSubData(sub);
903
+ // sub.last_throttled = Date.now();
904
+ }
905
+ else if (!sub.is_throttling) {
906
+ (0, exports.log)("throttling sub");
907
+ sub.is_throttling = setTimeout(() => {
908
+ (0, exports.log)("throttling finished. pushSubData...");
909
+ sub.is_throttling = null;
910
+ this.pushSubData(sub);
911
+ }, throttle); // sub.throttle);
912
+ }
913
+ }
914
+ }
915
+ });
916
+ }
917
+ else {
918
+ // if(!this._triggers || !this._triggers[table_name] || !this._triggers[table_name].length){
919
+ // console.warn(190, "Trigger sub not found. DROPPING TRIGGER", table_name, condition_ids_str, this._triggers);
920
+ // this.dropTrigger(table_name);
921
+ // } else {
922
+ // }
923
+ console.warn(190, "Trigger sub issue: ", table_name, condition_ids_str, this._triggers);
924
+ }
925
+ };
926
+ this.parseCondition = (condition) => Boolean(condition && condition.trim().length) ? condition : "TRUE";
927
+ this.getActiveListeners = () => {
928
+ let result = [];
929
+ const upsert = (t, c) => {
930
+ if (!result.find(r => r.table_name === t && r.condition === c)) {
931
+ result.push({ table_name: t, condition: c });
932
+ }
933
+ };
934
+ (this.syncs || []).map(s => {
935
+ upsert(s.table_name, s.condition);
936
+ });
937
+ Object.keys(this.subs || {}).map(table_name => {
938
+ Object.keys(this.subs[table_name] || {}).map(condition => {
939
+ if (this.subs[table_name][condition].subs.length) {
940
+ upsert(table_name, condition);
941
+ }
942
+ });
943
+ });
944
+ return result;
945
+ };
946
+ this.checkIfTimescaleBug = async (table_name) => {
947
+ const schema = "_timescaledb_catalog", res = await this.db.oneOrNone("SELECT EXISTS( \
948
+ SELECT * \
949
+ FROM information_schema.tables \
950
+ WHERE 1 = 1 \
951
+ AND table_schema = ${schema} \
952
+ AND table_name = 'hypertable' \
953
+ );", { schema });
954
+ if (res.exists) {
955
+ let isHyperTable = await this.db.any("SELECT * FROM " + (0, prostgles_types_1.asName)(schema) + ".hypertable WHERE table_name = ${table_name};", { table_name, schema });
956
+ if (isHyperTable && isHyperTable.length) {
957
+ throw "Triggers do not work on timescaledb hypertables due to bug:\nhttps://github.com/timescale/timescaledb/issues/1084";
958
+ }
959
+ }
960
+ return true;
961
+ };
962
+ /*
963
+ A table will only have a trigger with all conditions (for different subs)
964
+ conditions = ["user_id = 1"]
965
+ fields = ["user_id"]
966
+ */
967
+ this.getMyTriggerQuery = async () => {
968
+ return pgp.as.format(`
969
+ SELECT * --, ROW_NUMBER() OVER(PARTITION BY table_name ORDER BY table_name, condition ) - 1 as id
970
+ FROM prostgles.v_triggers
971
+ WHERE app_id = $1
972
+ ORDER BY table_name, condition
973
+ `, [this.appID]);
974
+ };
975
+ this.addTriggerPool = undefined;
976
+ const { db, dbo, wsChannelNamePrefix, pgChannelName, onSchemaChange, dboBuilder } = options;
977
+ if (!db || !dbo) {
978
+ throw 'MISSING: db_pg, db';
979
+ }
980
+ this.db = db;
981
+ this.dbo = dbo;
982
+ this.onSchemaChange = onSchemaChange;
983
+ this.dboBuilder = dboBuilder;
984
+ this.sockets = {};
985
+ this.subs = {};
986
+ this.syncs = [];
987
+ this.socketChannelPreffix = wsChannelNamePrefix || "_psqlWS_";
988
+ (0, exports.log)("Created PubSubManager");
989
+ }
990
+ isReady() {
991
+ if (!this.postgresNotifListenManager)
992
+ throw "this.postgresNotifListenManager missing";
993
+ return this.postgresNotifListenManager.isListening();
994
+ }
995
+ getSubs(table_name, condition) {
996
+ return (0, utils_1.get)(this.subs, [table_name, condition, "subs"]);
997
+ }
998
+ getSyncs(table_name, condition) {
999
+ return (this.syncs || [])
1000
+ .filter((s) => s.table_name === table_name && s.condition === condition);
1001
+ }
1002
+ pushSubData(sub, err) {
1003
+ if (!sub)
1004
+ throw "pushSubData: invalid sub";
1005
+ const { table_name, filter, params, table_rules, socket_id, channel_name, func } = sub; //, subOne = false
1006
+ sub.last_throttled = Date.now();
1007
+ if (err) {
1008
+ if (socket_id) {
1009
+ this.sockets[socket_id].emit(channel_name, { err });
1010
+ }
1011
+ return true;
1012
+ }
1013
+ return new Promise(async (resolve, reject) => {
1014
+ /* TODO: Retire subOne -> it's redundant */
1015
+ // this.dbo[table_name][subOne? "findOne" : "find"](filter, params, null, table_rules)
1016
+ if (!this.dbo?.[table_name]?.find)
1017
+ throw "1107 this.dbo[table_name].find";
1018
+ this.dbo?.[table_name]?.find?.(filter, params, undefined, table_rules)
1019
+ .then(data => {
1020
+ if (socket_id && this.sockets[socket_id]) {
1021
+ (0, exports.log)("Pushed " + data.length + " records to sub");
1022
+ this.sockets[socket_id].emit(channel_name, { data }, () => {
1023
+ resolve(data);
1024
+ });
1025
+ /* TO DO: confirm receiving data or server will unsubscribe
1026
+ { data }, (cb)=> { console.log(cb) });
1027
+ */
1028
+ }
1029
+ else if (func) {
1030
+ func(data);
1031
+ resolve(data);
1032
+ }
1033
+ sub.last_throttled = Date.now();
1034
+ }).catch(err => {
1035
+ const errObj = { _err_msg: err.toString(), err };
1036
+ if (socket_id && this.sockets[socket_id]) {
1037
+ this.sockets[socket_id].emit(channel_name, { err: errObj });
1038
+ }
1039
+ else if (func) {
1040
+ func({ err: errObj });
1041
+ }
1042
+ reject(errObj);
1043
+ });
1044
+ });
1045
+ }
1046
+ upsertSocket(socket, channel_name) {
1047
+ if (socket && !this.sockets[socket.id]) {
1048
+ this.sockets[socket.id] = socket;
1049
+ socket.on("disconnect", () => this.onSocketDisconnected(socket));
1050
+ }
1051
+ }
1052
+ async syncData(sync, clientData, source) {
1053
+ return await (0, SyncReplication_1.syncData)(this, sync, clientData, source);
1054
+ }
1055
+ /**
1056
+ * Returns a sync channel
1057
+ * A sync channel is unique per socket for each filter
1058
+ */
1059
+ async addSync(syncParams) {
1060
+ const { socket = null, table_info = null, table_rules, synced_field = null, allow_delete = false, id_fields = [], filter = {}, params, condition = "", throttle = 0 } = syncParams || {};
1061
+ let conditionParsed = this.parseCondition(condition);
1062
+ if (!socket || !table_info)
1063
+ throw "socket or table_info missing";
1064
+ const { name: table_name } = table_info, channel_name = `${this.socketChannelPreffix}.${table_name}.${JSON.stringify(filter)}.sync`;
1065
+ if (!synced_field)
1066
+ throw "synced_field missing from table_rules";
1067
+ this.upsertSocket(socket, channel_name);
1068
+ const upsertSync = () => {
1069
+ let newSync = {
1070
+ channel_name,
1071
+ table_name,
1072
+ filter,
1073
+ condition: conditionParsed,
1074
+ synced_field,
1075
+ id_fields,
1076
+ allow_delete,
1077
+ table_rules,
1078
+ throttle: Math.max(throttle || 0, table_rules?.sync?.throttle || 0),
1079
+ batch_size: (0, utils_1.get)(table_rules, "sync.batch_size") || exports.DEFAULT_SYNC_BATCH_SIZE,
1080
+ last_throttled: 0,
1081
+ socket_id: socket.id,
1082
+ is_sync: true,
1083
+ last_synced: 0,
1084
+ lr: undefined,
1085
+ table_info,
1086
+ is_syncing: false,
1087
+ wal: undefined,
1088
+ socket,
1089
+ params
1090
+ };
1091
+ /* Only a sync per socket per table per condition allowed */
1092
+ this.syncs = this.syncs || [];
1093
+ let existing = this.syncs.find(s => s.socket_id === socket.id && s.channel_name === channel_name);
1094
+ if (!existing) {
1095
+ this.syncs.push(newSync);
1096
+ // console.log("Added SYNC");
1097
+ socket.removeAllListeners(channel_name + "unsync");
1098
+ socket.once(channel_name + "unsync", (_data, cb) => {
1099
+ this.onSocketDisconnected(socket, channel_name);
1100
+ cb(null, { res: "ok" });
1101
+ });
1102
+ socket.removeAllListeners(channel_name);
1103
+ socket.on(channel_name, (data, cb) => {
1104
+ if (!data) {
1105
+ cb({ err: "Unexpected request. Need data or onSyncRequest" });
1106
+ return;
1107
+ }
1108
+ /*
1109
+ */
1110
+ /* Server will:
1111
+ 1. Ask for last_synced emit(onSyncRequest)
1112
+ 2. Ask for data >= server_synced emit(onPullRequest)
1113
+ -> Upsert that data
1114
+ 2. Push data >= last_synced emit(data.data)
1115
+
1116
+ Client will:
1117
+ 1. Send last_synced on(onSyncRequest)
1118
+ 2. Send data >= server_synced on(onPullRequest)
1119
+ 3. Send data on CRUD emit(data.data | data.deleted)
1120
+ 4. Upsert data.data | deleted on(data.data | data.deleted)
1121
+ */
1122
+ // if(data.data){
1123
+ // console.error("THIS SHOUKD NEVER FIRE !! NEW DATA FROM SYNC");
1124
+ // this.upsertClientData(newSync, data.data);
1125
+ // } else
1126
+ if (data.onSyncRequest) {
1127
+ // console.log("syncData from socket")
1128
+ this.syncData(newSync, data.onSyncRequest, "client");
1129
+ // console.log("onSyncRequest ", socket._user)
1130
+ }
1131
+ else {
1132
+ console.error("Unexpected sync request data from client: ", data);
1133
+ }
1134
+ });
1135
+ // socket.emit(channel_name, { onSyncRequest: true }, (response) => {
1136
+ // console.log(response)
1137
+ // });
1138
+ }
1139
+ else {
1140
+ console.error("UNCLOSED DUPLICATE SYNC FOUND");
1141
+ }
1142
+ return newSync;
1143
+ };
1144
+ // const { min_id, max_id, count, max_synced } = params;
1145
+ let sync = upsertSync();
1146
+ await this.addTrigger({ table_name, condition: conditionParsed });
1147
+ return channel_name;
1148
+ }
1149
+ /* Must return a channel for socket */
1150
+ /* The distinct list of channel names must have a corresponding trigger in the database */
1151
+ async addSub(subscriptionParams) {
1152
+ const { socket, func = null, table_info = null, table_rules, filter = {}, params = {}, condition = "", throttle = 0 //subOne = false,
1153
+ } = subscriptionParams || {};
1154
+ let validated_throttle = subscriptionParams.throttle || 10;
1155
+ if ((!socket && !func) || !table_info)
1156
+ throw "socket/func or table_info missing";
1157
+ const pubThrottle = (0, utils_1.get)(table_rules, ["subscribe", "throttle"]) || 0;
1158
+ if (pubThrottle && Number.isInteger(pubThrottle) && pubThrottle > 0) {
1159
+ validated_throttle = pubThrottle;
1160
+ }
1161
+ if (throttle && Number.isInteger(throttle) && throttle >= pubThrottle) {
1162
+ validated_throttle = throttle;
1163
+ }
1164
+ let channel_name = `${this.socketChannelPreffix}.${table_info.name}.${JSON.stringify(filter)}.${JSON.stringify(params)}.${"m"}.sub`; //.${subOne? "o" : "m"}.sub`;
1165
+ this.upsertSocket(socket, channel_name);
1166
+ const upsertSub = (newSubData) => {
1167
+ const { table_name, condition: _cond, is_ready = false } = newSubData, condition = this.parseCondition(_cond), newSub = {
1168
+ socket,
1169
+ table_name: table_info.name,
1170
+ table_info,
1171
+ filter,
1172
+ params,
1173
+ table_rules,
1174
+ channel_name,
1175
+ func: func ? func : undefined,
1176
+ socket_id: socket?.id,
1177
+ throttle: validated_throttle,
1178
+ is_throttling: null,
1179
+ last_throttled: 0,
1180
+ is_ready,
1181
+ // subOne
1182
+ };
1183
+ this.subs[table_name] = this.subs[table_name] || {};
1184
+ this.subs[table_name][condition] = this.subs[table_name][condition] || { subs: [] };
1185
+ this.subs[table_name][condition].subs = this.subs[table_name][condition].subs || [];
1186
+ // console.log("1034 upsertSub", this.subs)
1187
+ const sub_idx = this.subs[table_name][condition].subs.findIndex(s => s.channel_name === channel_name &&
1188
+ (socket && s.socket_id === socket.id ||
1189
+ func && s.func === func));
1190
+ if (sub_idx < 0) {
1191
+ this.subs[table_name][condition].subs.push(newSub);
1192
+ if (socket) {
1193
+ const chnUnsub = channel_name + "unsubscribe";
1194
+ socket.removeAllListeners(chnUnsub);
1195
+ socket.once(chnUnsub, (_data, cb) => {
1196
+ const res = this.onSocketDisconnected(socket, channel_name);
1197
+ cb(null, { res });
1198
+ });
1199
+ }
1200
+ }
1201
+ else {
1202
+ this.subs[table_name][condition].subs[sub_idx] = newSub;
1203
+ }
1204
+ if (is_ready) {
1205
+ this.pushSubData(newSub);
1206
+ }
1207
+ };
1208
+ if (table_info.is_view && table_info.parent_tables) {
1209
+ if (table_info.parent_tables.length) {
1210
+ let _condition = "TRUE";
1211
+ table_info.parent_tables.map(async (table_name) => {
1212
+ upsertSub({
1213
+ table_name,
1214
+ condition: _condition,
1215
+ is_ready: true
1216
+ });
1217
+ await this.addTrigger({
1218
+ table_name,
1219
+ condition: _condition
1220
+ });
1221
+ upsertSub({
1222
+ table_name,
1223
+ condition: _condition,
1224
+ is_ready: true
1225
+ });
1226
+ });
1227
+ return channel_name;
1228
+ }
1229
+ else {
1230
+ throw "PubSubManager: view parent_tables missing";
1231
+ }
1232
+ /* */
1233
+ }
1234
+ else {
1235
+ /* Just a table, add table + condition trigger */
1236
+ // console.log(table_info, 202);
1237
+ upsertSub({
1238
+ table_name: table_info.name,
1239
+ condition: this.parseCondition(condition),
1240
+ is_ready: false
1241
+ });
1242
+ await this.addTrigger({
1243
+ table_name: table_info.name,
1244
+ condition: this.parseCondition(condition),
1245
+ });
1246
+ upsertSub({
1247
+ table_name: table_info.name,
1248
+ condition: this.parseCondition(condition),
1249
+ is_ready: true
1250
+ });
1251
+ return channel_name;
1252
+ }
1253
+ }
1254
+ removeLocalSub(table_name, condition, func) {
1255
+ let cond = this.parseCondition(condition);
1256
+ if ((0, utils_1.get)(this.subs, [table_name, cond, "subs"])) {
1257
+ this.subs[table_name][cond].subs.map((sub, i) => {
1258
+ if (sub.func && sub.func === func) {
1259
+ this.subs[table_name][cond].subs.splice(i, 1);
1260
+ }
1261
+ });
1262
+ }
1263
+ else {
1264
+ console.error("Could not unsubscribe. Subscription might not have initialised yet");
1265
+ }
1266
+ }
1267
+ onSocketDisconnected(socket, channel_name) {
1268
+ // process.on('warning', e => {
1269
+ // console.warn(e.stack)
1270
+ // });
1271
+ // console.log("onSocketDisconnected", channel_name, this.syncs)
1272
+ if (this.subs) {
1273
+ Object.keys(this.subs).map(table_name => {
1274
+ Object.keys(this.subs[table_name]).map(condition => {
1275
+ this.subs[table_name][condition].subs.map((sub, i) => {
1276
+ /**
1277
+ * If a channel name is specified then delete triggers
1278
+ */
1279
+ if ((socket && sub.socket_id === socket.id) &&
1280
+ (!channel_name || sub.channel_name === channel_name)) {
1281
+ this.subs[table_name][condition].subs.splice(i, 1);
1282
+ if (!this.subs[table_name][condition].subs.length) {
1283
+ delete this.subs[table_name][condition];
1284
+ if ((0, prostgles_types_1.isEmpty)(this.subs[table_name])) {
1285
+ delete this.subs[table_name];
1286
+ }
1287
+ }
1288
+ }
1289
+ });
1290
+ });
1291
+ });
1292
+ }
1293
+ if (this.syncs) {
1294
+ this.syncs = this.syncs.filter(s => {
1295
+ const matchesSocket = Boolean(socket && s.socket_id !== socket.id);
1296
+ if (channel_name) {
1297
+ return matchesSocket || s.channel_name !== channel_name;
1298
+ }
1299
+ return matchesSocket;
1300
+ });
1301
+ }
1302
+ if (!socket) {
1303
+ }
1304
+ else if (!channel_name) {
1305
+ delete this.sockets[socket.id];
1306
+ }
1307
+ else {
1308
+ socket.removeAllListeners(channel_name);
1309
+ socket.removeAllListeners(channel_name + "unsync");
1310
+ socket.removeAllListeners(channel_name + "unsubscribe");
1311
+ }
1312
+ return "ok";
1313
+ }
1314
+ async addTrigger(params) {
1315
+ try {
1316
+ let { table_name, condition } = { ...params };
1317
+ if (!table_name)
1318
+ throw "MISSING table_name";
1319
+ if (!this.appID)
1320
+ throw "MISSING appID";
1321
+ if (!condition || !condition.trim().length)
1322
+ condition = "TRUE";
1323
+ const app_id = this.appID;
1324
+ // console.log(1623, { app_id, addTrigger: { table_name, condition } });
1325
+ await this.checkIfTimescaleBug(table_name);
1326
+ const trgVals = {
1327
+ tbl: (0, exports.asValue)(table_name),
1328
+ cond: (0, exports.asValue)(condition),
1329
+ };
1330
+ await this.db.any(`
1331
+ BEGIN WORK;
1332
+ LOCK TABLE prostgles.app_triggers IN ACCESS EXCLUSIVE MODE;
1333
+
1334
+ INSERT INTO prostgles.app_triggers (table_name, condition, app_id)
1335
+ VALUES (${trgVals.tbl}, ${trgVals.cond}, ${(0, exports.asValue)(this.appID)})
1336
+ ON CONFLICT DO NOTHING;
1337
+
1338
+ COMMIT WORK;
1339
+ `);
1340
+ (0, exports.log)("addTrigger.. ", { table_name, condition });
1341
+ const triggers = await this.db.any(await this.getMyTriggerQuery());
1342
+ this._triggers = {};
1343
+ triggers.map(t => {
1344
+ this._triggers = this._triggers || {};
1345
+ this._triggers[t.table_name] = this._triggers[t.table_name] || [];
1346
+ if (!this._triggers[t.table_name].includes(t.condition)) {
1347
+ this._triggers[t.table_name].push(t.condition);
1348
+ }
1349
+ });
1350
+ (0, exports.log)("trigger added.. ", { table_name, condition });
1351
+ return true;
1352
+ // console.log("1612", JSON.stringify(triggers, null, 2))
1353
+ // console.log("1613",JSON.stringify(this._triggers, null, 2))
1354
+ }
1355
+ catch (e) {
1356
+ console.trace("Failed adding trigger", e);
1357
+ // throw e
1358
+ }
1359
+ }
1360
+ }
1361
+ exports.PubSubManager = PubSubManager;
1362
+ _a = PubSubManager;
1363
+ PubSubManager.DELIMITER = '|$prstgls$|';
1364
+ // ,datname
1365
+ // ,usename
1366
+ // ,client_hostname
1367
+ // ,client_port
1368
+ // ,backend_start
1369
+ // ,query_start
1370
+ // ,query
1371
+ // ,state
1372
+ // console.log(await _db.any(`
1373
+ // SELECT pid, application_name, state
1374
+ // FROM pg_stat_activity
1375
+ // WHERE application_name IS NOT NULL AND application_name != '' -- state = 'active';
1376
+ // `))
1377
+ PubSubManager.create = async (options) => {
1378
+ const res = new PubSubManager(options);
1379
+ return await res.init();
1380
+ };
1381
+ PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID = "prostgles internal query that should be excluded from ";
1382
+ function omitKeys(obj, exclude) {
1383
+ return pickKeys(obj, (0, prostgles_types_1.getKeys)(obj ?? []).filter(k => !exclude.includes(k)));
1384
+ }
1385
+ exports.omitKeys = omitKeys;
1386
+ function pickKeys(obj, include = []) {
1387
+ let keys = include;
1388
+ if (!keys.length) {
1389
+ return {};
1390
+ }
1391
+ if (obj && keys.length) {
1392
+ let res = {};
1393
+ keys.forEach(k => {
1394
+ res[k] = obj[k];
1395
+ });
1396
+ return res;
1397
+ }
1398
+ return obj;
1399
+ }
1400
+ exports.pickKeys = pickKeys;