prostgles-server 4.2.159 → 4.2.161

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 (107) hide show
  1. package/dist/Auth/setEmailProvider.js +2 -2
  2. package/dist/Auth/setEmailProvider.js.map +1 -1
  3. package/lib/Auth/AuthHandler.ts +436 -0
  4. package/lib/Auth/AuthTypes.ts +280 -0
  5. package/lib/Auth/getSafeReturnURL.ts +35 -0
  6. package/lib/Auth/sendEmail.ts +83 -0
  7. package/lib/Auth/setAuthProviders.ts +128 -0
  8. package/lib/Auth/setEmailProvider.ts +85 -0
  9. package/lib/Auth/setupAuthRoutes.ts +161 -0
  10. package/lib/DBEventsManager.ts +178 -0
  11. package/lib/DBSchemaBuilder.ts +225 -0
  12. package/lib/DboBuilder/DboBuilder.ts +319 -0
  13. package/lib/DboBuilder/DboBuilderTypes.ts +361 -0
  14. package/lib/DboBuilder/QueryBuilder/Functions.ts +1153 -0
  15. package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +288 -0
  16. package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +263 -0
  17. package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +271 -0
  18. package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +136 -0
  19. package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +22 -0
  20. package/lib/DboBuilder/QueryStreamer.ts +250 -0
  21. package/lib/DboBuilder/TableHandler/DataValidator.ts +428 -0
  22. package/lib/DboBuilder/TableHandler/TableHandler.ts +205 -0
  23. package/lib/DboBuilder/TableHandler/delete.ts +115 -0
  24. package/lib/DboBuilder/TableHandler/insert.ts +183 -0
  25. package/lib/DboBuilder/TableHandler/insertTest.ts +78 -0
  26. package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +62 -0
  27. package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +134 -0
  28. package/lib/DboBuilder/TableHandler/update.ts +126 -0
  29. package/lib/DboBuilder/TableHandler/updateBatch.ts +49 -0
  30. package/lib/DboBuilder/TableHandler/updateFile.ts +48 -0
  31. package/lib/DboBuilder/TableHandler/upsert.ts +34 -0
  32. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +393 -0
  33. package/lib/DboBuilder/ViewHandler/count.ts +38 -0
  34. package/lib/DboBuilder/ViewHandler/find.ts +153 -0
  35. package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +73 -0
  36. package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +74 -0
  37. package/lib/DboBuilder/ViewHandler/getInfo.ts +32 -0
  38. package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +84 -0
  39. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +96 -0
  40. package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +105 -0
  41. package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +208 -0
  42. package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +163 -0
  43. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +90 -0
  44. package/lib/DboBuilder/ViewHandler/size.ts +37 -0
  45. package/lib/DboBuilder/ViewHandler/subscribe.ts +118 -0
  46. package/lib/DboBuilder/ViewHandler/validateViewRules.ts +70 -0
  47. package/lib/DboBuilder/dboBuilderUtils.ts +222 -0
  48. package/lib/DboBuilder/getColumns.ts +114 -0
  49. package/lib/DboBuilder/getCondition.ts +201 -0
  50. package/lib/DboBuilder/getSubscribeRelatedTables.ts +190 -0
  51. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +426 -0
  52. package/lib/DboBuilder/insertNestedRecords.ts +355 -0
  53. package/lib/DboBuilder/parseUpdateRules.ts +187 -0
  54. package/lib/DboBuilder/prepareShortestJoinPaths.ts +186 -0
  55. package/lib/DboBuilder/runSQL.ts +182 -0
  56. package/lib/DboBuilder/runTransaction.ts +50 -0
  57. package/lib/DboBuilder/sqlErrCodeToMsg.ts +254 -0
  58. package/lib/DboBuilder/uploadFile.ts +69 -0
  59. package/lib/Event_Trigger_Tags.ts +118 -0
  60. package/lib/FileManager/FileManager.ts +358 -0
  61. package/lib/FileManager/getValidatedFileType.ts +69 -0
  62. package/lib/FileManager/initFileManager.ts +187 -0
  63. package/lib/FileManager/upload.ts +62 -0
  64. package/lib/FileManager/uploadStream.ts +79 -0
  65. package/lib/Filtering.ts +463 -0
  66. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +502 -0
  67. package/lib/JSONBValidation/validation.ts +143 -0
  68. package/lib/Logging.ts +127 -0
  69. package/lib/PostgresNotifListenManager.ts +143 -0
  70. package/lib/Prostgles.ts +485 -0
  71. package/lib/ProstglesTypes.ts +196 -0
  72. package/lib/PubSubManager/PubSubManager.ts +609 -0
  73. package/lib/PubSubManager/addSub.ts +138 -0
  74. package/lib/PubSubManager/addSync.ts +141 -0
  75. package/lib/PubSubManager/getCreatePubSubManagerError.ts +72 -0
  76. package/lib/PubSubManager/getPubSubManagerInitQuery.ts +662 -0
  77. package/lib/PubSubManager/initPubSubManager.ts +79 -0
  78. package/lib/PubSubManager/notifListener.ts +173 -0
  79. package/lib/PubSubManager/orphanTriggerCheck.ts +70 -0
  80. package/lib/PubSubManager/pushSubData.ts +55 -0
  81. package/lib/PublishParser/PublishParser.ts +162 -0
  82. package/lib/PublishParser/getFileTableRules.ts +124 -0
  83. package/lib/PublishParser/getSchemaFromPublish.ts +141 -0
  84. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +177 -0
  85. package/lib/PublishParser/publishTypesAndUtils.ts +399 -0
  86. package/lib/RestApi.ts +127 -0
  87. package/lib/SchemaWatch/SchemaWatch.ts +90 -0
  88. package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +3 -0
  89. package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +45 -0
  90. package/lib/SchemaWatch/getWatchSchemaTagList.ts +27 -0
  91. package/lib/SyncReplication.ts +557 -0
  92. package/lib/TableConfig/TableConfig.ts +468 -0
  93. package/lib/TableConfig/getColumnDefinitionQuery.ts +111 -0
  94. package/lib/TableConfig/getConstraintDefinitionQueries.ts +95 -0
  95. package/lib/TableConfig/getFutureTableSchema.ts +64 -0
  96. package/lib/TableConfig/getPGIndexes.ts +53 -0
  97. package/lib/TableConfig/getTableColumnQueries.ts +129 -0
  98. package/lib/TableConfig/initTableConfig.ts +326 -0
  99. package/lib/index.ts +13 -0
  100. package/lib/initProstgles.ts +319 -0
  101. package/lib/onSocketConnected.ts +102 -0
  102. package/lib/runClientRequest.ts +129 -0
  103. package/lib/shortestPath.ts +122 -0
  104. package/lib/typeTests/DBoGenerated.d.ts +320 -0
  105. package/lib/typeTests/dboTypeCheck.ts +81 -0
  106. package/lib/utils.ts +15 -0
  107. package/package.json +1 -1
@@ -0,0 +1,138 @@
1
+ import { SubscriptionChannels } from "prostgles-types";
2
+ import { BasicCallback, parseCondition, PubSubManager, Subscription, SubscriptionParams } from "./PubSubManager";
3
+ import { VoidFunction } from "../SchemaWatch/SchemaWatch";
4
+
5
+ type AddSubscriptionParams = SubscriptionParams & {
6
+ condition: string;
7
+ }
8
+
9
+ type AddSubResult = SubscriptionChannels & { sendFirstData: VoidFunction | undefined }
10
+
11
+ /* Must return a channel for socket */
12
+ /* The distinct list of {table_name, condition} must have a corresponding trigger in the database */
13
+ export async function addSub(this: PubSubManager, subscriptionParams: Omit<AddSubscriptionParams, "channel_name" | "parentSubParams">): Promise<AddSubResult> {
14
+ const {
15
+ socket, localFuncs, table_rules, filter = {},
16
+ params = {}, condition = "", throttle = 0, //subOne = false,
17
+ viewOptions, table_info, throttleOpts,
18
+ } = subscriptionParams || {};
19
+ const table_name = table_info.name;
20
+
21
+ if (!socket && !localFuncs) {
22
+ throw "socket AND func missing";
23
+ }
24
+ if (socket && localFuncs) {
25
+ throw "addSub: cannot have socket AND func";
26
+ }
27
+
28
+ let validated_throttle = subscriptionParams.throttle || 10;
29
+ const pubThrottle = table_rules?.subscribe?.throttle || 0;
30
+ if (pubThrottle && Number.isInteger(pubThrottle) && pubThrottle > 0) {
31
+ validated_throttle = pubThrottle;
32
+ }
33
+ if (throttle && Number.isInteger(throttle) && throttle >= pubThrottle) {
34
+ validated_throttle = throttle;
35
+ }
36
+
37
+ const channel_name = `${this.socketChannelPreffix}.${table_name}.${JSON.stringify(filter)}.${JSON.stringify(params)}.${"m"}.sub`;
38
+ const mainTrigger = {
39
+ table_name: table_name,
40
+ condition: parseCondition(condition),
41
+ is_related: false,
42
+ } as const;
43
+
44
+ const newSub: Subscription = {
45
+ channel_name,
46
+ filter,
47
+ localFuncs,
48
+ params,
49
+ last_throttled: 0,
50
+ socket,
51
+ throttleOpts,
52
+ table_info,
53
+ is_ready: true,
54
+ is_throttling: false,
55
+ socket_id: socket?.id,
56
+ table_rules,
57
+ throttle: validated_throttle,
58
+ triggers: [
59
+ mainTrigger
60
+ ]
61
+ }
62
+
63
+ const result: AddSubResult = {
64
+ channelName: channel_name,
65
+ channelNameReady: channel_name + ".ready",
66
+ channelNameUnsubscribe: channel_name + ".unsubscribe",
67
+ sendFirstData: undefined,
68
+ }
69
+
70
+ const [matchingSub] = this.getClientSubs(newSub);
71
+ if(matchingSub){
72
+ console.error("Trying to add a duplicate sub for: ", channel_name);
73
+ return result;
74
+ }
75
+
76
+ this.upsertSocket(socket);
77
+
78
+ if(viewOptions){
79
+ for await(const relatedTable of viewOptions.relatedTables){
80
+ const relatedSub = {
81
+ table_name: relatedTable.tableName,
82
+ condition: parseCondition(relatedTable.condition),
83
+ is_related: true,
84
+ } as const;
85
+
86
+ newSub.triggers.push(relatedSub)
87
+
88
+ await this.addTrigger(relatedSub, viewOptions, socket);
89
+ }
90
+
91
+ }
92
+
93
+
94
+ if(localFuncs){
95
+ /**
96
+ * Must ensure sub will start sending data after all triggers are set up.
97
+ * Socket clients are not affected as they need to confirm they are ready to receive data
98
+ */
99
+ result.sendFirstData = () => {
100
+ this.pushSubData(newSub);
101
+ }
102
+
103
+ } else if (socket) {
104
+ const removeListeners = () => {
105
+ socket.removeAllListeners(channel_name);
106
+ socket.removeAllListeners(result.channelNameReady);
107
+ socket.removeAllListeners(result.channelNameUnsubscribe);
108
+ }
109
+ removeListeners();
110
+
111
+ socket.once(result.channelNameReady, () => {
112
+ this.pushSubData(newSub);
113
+ });
114
+ socket.once(result.channelNameUnsubscribe, (_data: any, cb: BasicCallback) => {
115
+ const res = "ok";
116
+ this.subs = this.subs.filter(s => {
117
+ const isMatch = s.socket?.id === socket.id && s.channel_name === channel_name;
118
+ return !isMatch;
119
+ });
120
+ removeListeners();
121
+ cb(null, { res });
122
+ });
123
+ }
124
+
125
+ this.subs.push(newSub);
126
+
127
+ /** A view does not have triggers. Only related triggers */
128
+ if (table_info.is_view) {
129
+ if (!viewOptions?.relatedTables.length) {
130
+ throw "PubSubManager: view parent_tables missing";
131
+ }
132
+
133
+ } else {
134
+ await this.addTrigger(mainTrigger, undefined, socket);
135
+ }
136
+
137
+ return result;
138
+ }
@@ -0,0 +1,141 @@
1
+ import { find, tryCatch } from "prostgles-types/dist/util";
2
+ import { AddSyncParams, BasicCallback, DEFAULT_SYNC_BATCH_SIZE, PubSubManager, parseCondition } from "./PubSubManager";
3
+
4
+ /**
5
+ * Returns a sync channel
6
+ * A sync channel is unique per socket for each filter
7
+ */
8
+ export async function addSync(this: PubSubManager, syncParams: AddSyncParams) {
9
+
10
+ const sid = this.dboBuilder.prostgles.authHandler?.getSIDNoError({ socket: syncParams.socket });
11
+ const res = await tryCatch(async () => {
12
+
13
+ const {
14
+ socket = null, table_info = null, table_rules, synced_field = null,
15
+ allow_delete = false, id_fields = [], filter = {},
16
+ params, condition = "", throttle = 0
17
+ } = syncParams || {} as AddSyncParams;
18
+ const conditionParsed = parseCondition(condition);
19
+ if (!socket || !table_info) throw "socket or table_info missing";
20
+
21
+ const { name: table_name } = table_info;
22
+ const channel_name = `${this.socketChannelPreffix}.${table_name}.${JSON.stringify(filter)}.sync`;
23
+
24
+ if (!synced_field) throw "synced_field missing from table_rules";
25
+
26
+ this.upsertSocket(socket);
27
+
28
+ const upsertSync = () => {
29
+ const newSync = {
30
+ channel_name,
31
+ table_name,
32
+ filter,
33
+ condition: conditionParsed,
34
+ synced_field,
35
+ sid,
36
+ id_fields,
37
+ allow_delete,
38
+ table_rules,
39
+ throttle: Math.max(throttle || 0, table_rules?.sync?.throttle || 0),
40
+ batch_size: table_rules?.sync?.batch_size || DEFAULT_SYNC_BATCH_SIZE,
41
+ socket_id: socket.id,
42
+ is_sync: true,
43
+ last_synced: 0,
44
+ lr: undefined,
45
+ table_info,
46
+ is_syncing: false,
47
+ wal: undefined,
48
+ socket,
49
+ params
50
+ };
51
+
52
+ /* Only a sync per socket per table per condition allowed */
53
+ this.syncs ??= [];
54
+ const existing = find(this.syncs, { socket_id: socket.id, channel_name });
55
+ if (!existing) {
56
+ this.syncs.push(newSync);
57
+
58
+ const unsyncChn = channel_name + "unsync";
59
+ socket.removeAllListeners(unsyncChn);
60
+ socket.once(unsyncChn, (_data: any, cb: BasicCallback) => {
61
+ this._log({
62
+ type: "sync",
63
+ command: "unsync",
64
+ socketId: socket.id,
65
+ tableName: table_name,
66
+ condition,
67
+ sid,
68
+ connectedSocketIds: this.connectedSocketIds,
69
+ duration: -1,
70
+ });
71
+ socket.removeAllListeners(channel_name);
72
+ socket.removeAllListeners(unsyncChn);
73
+ this.syncs = this.syncs.filter(s => {
74
+ const isMatch = s.socket_id && s.socket_id === socket.id && s.channel_name === channel_name;
75
+ return !isMatch;
76
+ });
77
+ cb(null, { res: "ok" });
78
+ });
79
+
80
+ socket.removeAllListeners(channel_name);
81
+ socket.on(channel_name, (data: any, cb: BasicCallback) => {
82
+
83
+ if (!data) {
84
+ cb({ err: "Unexpected request. Need data or onSyncRequest" });
85
+ return;
86
+ }
87
+
88
+ /*
89
+ */
90
+
91
+ /* Server will:
92
+ 1. Ask for last_synced emit(onSyncRequest)
93
+ 2. Ask for data >= server_synced emit(onPullRequest)
94
+ -> Upsert that data
95
+ 2. Push data >= last_synced emit(data.data)
96
+
97
+ Client will:
98
+ 1. Send last_synced on(onSyncRequest)
99
+ 2. Send data >= server_synced on(onPullRequest)
100
+ 3. Send data on CRUD emit(data.data | data.deleted)
101
+ 4. Upsert data.data | deleted on(data.data | data.deleted)
102
+ */
103
+
104
+ if (data.onSyncRequest) {
105
+ this.syncData(newSync, data.onSyncRequest, "client");
106
+
107
+ } else {
108
+ console.error("Unexpected sync request data from client: ", data)
109
+ }
110
+ });
111
+
112
+ } else {
113
+ console.warn("UNCLOSED DUPLICATE SYNC FOUND", existing.channel_name);
114
+ }
115
+
116
+ return newSync;
117
+ };
118
+
119
+ upsertSync();
120
+
121
+ await this.addTrigger({ table_name, condition: conditionParsed }, undefined, socket);
122
+
123
+ return { result: channel_name };
124
+ });
125
+
126
+ await this._log({
127
+ type: "sync",
128
+ command: "addSync",
129
+ tableName: syncParams.table_info.name,
130
+ condition: syncParams.condition,
131
+ socketId: syncParams.socket.id,
132
+ connectedSocketIds: this.connectedSocketIds,
133
+ duration: res.duration,
134
+ error: res.error,
135
+ sid,
136
+ });
137
+
138
+ if(res.error !== undefined) throw res.error;
139
+
140
+ return res.result;
141
+ }
@@ -0,0 +1,72 @@
1
+ import { tryCatch } from "prostgles-types";
2
+ import { getPubSubManagerInitQuery } from "./getPubSubManagerInitQuery";
3
+ import { getCanExecute } from "../DboBuilder/dboBuilderUtils";
4
+ import { DboBuilder } from "../DboBuilder/DboBuilder";
5
+
6
+ export const getCreatePubSubManagerError = async (dboBuilder: DboBuilder): Promise<string | undefined> => {
7
+ const db = dboBuilder.db;
8
+
9
+ const canExecute = await getCanExecute(db)
10
+ if (!canExecute) return "Cannot run EXECUTE statements on this connection";
11
+
12
+ /** Check if prostgles schema exists */
13
+ const prglSchema = await db.any(`
14
+ SELECT *
15
+ FROM pg_catalog.pg_namespace
16
+ WHERE nspname = 'prostgles'
17
+ `);
18
+
19
+ const checkIfCanCreateProstglesSchema = () => tryCatch(async () => {
20
+ const allGood = await db.task(async t => {
21
+ try {
22
+ await t.none(`
23
+ BEGIN;
24
+ DROP SCHEMA IF EXISTS prostgles CASCADE;
25
+ CREATE SCHEMA IF NOT EXISTS prostgles;
26
+ ROLLBACK;
27
+ `);
28
+ } catch (e) {
29
+ await t.none(`ROLLBACK`);
30
+ return false;
31
+ }
32
+
33
+ return true;
34
+ });
35
+
36
+ return allGood;
37
+ });
38
+
39
+ if (!prglSchema.length) {
40
+ const canCreate = await checkIfCanCreateProstglesSchema();
41
+ if (!canCreate) {
42
+ const dbName = await db.one(`SELECT current_database()`);
43
+ const user = await db.one(`SELECT current_user`);
44
+ return `Not allowed to create prostgles schema. GRANT CREATE ON DATABASE ${dbName} TO ${user}`;
45
+ }
46
+ return undefined;
47
+ } else {
48
+ const canCheckVersion = await tryCatch(async () => {
49
+ await db.any(`
50
+ SELECT * FROM prostgles.versions
51
+ `);
52
+ return { ok: true };
53
+ });
54
+
55
+ if(!canCheckVersion.ok){
56
+ console.error("prostgles schema exists but cannot check version. Check logs", canCheckVersion.error);
57
+ return "prostgles schema exists but cannot check version. Check logs";
58
+ }
59
+ }
60
+
61
+ const initQuery = await tryCatch(async () => ({ query: await getPubSubManagerInitQuery.bind(dboBuilder)() }));
62
+ if(initQuery.hasError){
63
+ console.error(initQuery.error);
64
+ return "Could not get initQuery. Check logs";
65
+ }
66
+
67
+ if(!initQuery.query){
68
+ return undefined;
69
+ }
70
+
71
+ return undefined;
72
+ }