prostgles-server 4.0.57 → 4.0.59

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 (221) hide show
  1. package/dist/DboBuilder/getColumns.d.ts.map +1 -1
  2. package/dist/DboBuilder/getColumns.js +1 -13
  3. package/dist/DboBuilder/getColumns.js.map +1 -1
  4. package/dist/DboBuilder/runSQL.js +2 -2
  5. package/dist/DboBuilder/runSQL.js.map +1 -1
  6. package/dist/Prostgles.d.ts.map +1 -1
  7. package/dist/PubSubManager/PubSubManager.d.ts +1 -1
  8. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -1
  9. package/dist/PubSubManager/PubSubManager.js +14 -1
  10. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  11. package/lib/DboBuilder/getColumns.ts +1 -18
  12. package/lib/DboBuilder/runSQL.ts +2 -2
  13. package/lib/Prostgles.ts +3 -3
  14. package/lib/PubSubManager/PubSubManager.ts +14 -1
  15. package/package.json +2 -2
  16. package/tests/client/PID.txt +1 -1
  17. package/tests/client/package.json +2 -2
  18. package/tests/client/tsconfig.json +2 -1
  19. package/tests/isomorphic_queries.ts +11 -9
  20. package/tests/server/DBoGenerated.d.ts +1 -1
  21. package/tests/server/dboTypeCheck.ts +3 -3
  22. package/tests/server/index.ts +7 -6
  23. package/tests/server/package-lock.json +1 -1
  24. package/tests/server/package.json +3 -3
  25. package/tests/server/publishTypeCheck.ts +1 -1
  26. package/tests/server/tsconfig.json +3 -2
  27. package/tests/test.sh +2 -0
  28. package/dist/FileManager.d.ts +0 -143
  29. package/dist/FileManager.d.ts.map +0 -1
  30. package/dist/FileManager.js +0 -646
  31. package/dist/FileManager.js.map +0 -1
  32. package/dist/TableConfig.d.ts +0 -267
  33. package/dist/TableConfig.d.ts.map +0 -1
  34. package/dist/TableConfig.js +0 -463
  35. package/dist/TableConfig.js.map +0 -1
  36. package/dist/validation.d.ts +0 -126
  37. package/dist/validation.d.ts.map +0 -1
  38. package/dist/validation.js +0 -405
  39. package/dist/validation.js.map +0 -1
  40. package/lib/AuthHandler.d.ts +0 -187
  41. package/lib/AuthHandler.d.ts.map +0 -1
  42. package/lib/AuthHandler.js +0 -478
  43. package/lib/DBEventsManager.d.ts +0 -38
  44. package/lib/DBEventsManager.d.ts.map +0 -1
  45. package/lib/DBEventsManager.js +0 -140
  46. package/lib/DBSchemaBuilder.d.ts +0 -13
  47. package/lib/DBSchemaBuilder.d.ts.map +0 -1
  48. package/lib/DBSchemaBuilder.js +0 -145
  49. package/lib/DboBuilder/QueryBuilder/Functions.d.ts +0 -64
  50. package/lib/DboBuilder/QueryBuilder/Functions.d.ts.map +0 -1
  51. package/lib/DboBuilder/QueryBuilder/Functions.js +0 -984
  52. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts +0 -73
  53. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +0 -1
  54. package/lib/DboBuilder/QueryBuilder/QueryBuilder.js +0 -335
  55. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts +0 -8
  56. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts.map +0 -1
  57. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.js +0 -227
  58. package/lib/DboBuilder/TableHandler.d.ts +0 -37
  59. package/lib/DboBuilder/TableHandler.d.ts.map +0 -1
  60. package/lib/DboBuilder/TableHandler.js +0 -213
  61. package/lib/DboBuilder/ViewHandler.d.ts +0 -119
  62. package/lib/DboBuilder/ViewHandler.d.ts.map +0 -1
  63. package/lib/DboBuilder/ViewHandler.js +0 -1023
  64. package/lib/DboBuilder/delete.d.ts +0 -6
  65. package/lib/DboBuilder/delete.d.ts.map +0 -1
  66. package/lib/DboBuilder/delete.js +0 -128
  67. package/lib/DboBuilder/find.d.ts +0 -8
  68. package/lib/DboBuilder/find.d.ts.map +0 -1
  69. package/lib/DboBuilder/find.js +0 -91
  70. package/lib/DboBuilder/getColumns.d.ts +0 -12
  71. package/lib/DboBuilder/getColumns.d.ts.map +0 -1
  72. package/lib/DboBuilder/getColumns.js +0 -92
  73. package/lib/DboBuilder/getCondition.d.ts +0 -22
  74. package/lib/DboBuilder/getCondition.d.ts.map +0 -1
  75. package/lib/DboBuilder/getCondition.js +0 -236
  76. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts +0 -20
  77. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts.map +0 -1
  78. package/lib/DboBuilder/getSubscribeRelatedTables.js +0 -152
  79. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts +0 -3
  80. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts.map +0 -1
  81. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.js +0 -207
  82. package/lib/DboBuilder/insert.d.ts +0 -6
  83. package/lib/DboBuilder/insert.d.ts.map +0 -1
  84. package/lib/DboBuilder/insert.js +0 -180
  85. package/lib/DboBuilder/insertDataParse.d.ts +0 -12
  86. package/lib/DboBuilder/insertDataParse.d.ts.map +0 -1
  87. package/lib/DboBuilder/insertDataParse.js +0 -253
  88. package/lib/DboBuilder/parseUpdateRules.d.ts +0 -18
  89. package/lib/DboBuilder/parseUpdateRules.d.ts.map +0 -1
  90. package/lib/DboBuilder/parseUpdateRules.js +0 -123
  91. package/lib/DboBuilder/runSQL.d.ts +0 -7
  92. package/lib/DboBuilder/runSQL.d.ts.map +0 -1
  93. package/lib/DboBuilder/runSQL.js +0 -135
  94. package/lib/DboBuilder/subscribe.d.ts +0 -20
  95. package/lib/DboBuilder/subscribe.d.ts.map +0 -1
  96. package/lib/DboBuilder/subscribe.js +0 -90
  97. package/lib/DboBuilder/update.d.ts +0 -6
  98. package/lib/DboBuilder/update.d.ts.map +0 -1
  99. package/lib/DboBuilder/update.js +0 -151
  100. package/lib/DboBuilder/uploadFile.d.ts +0 -7
  101. package/lib/DboBuilder/uploadFile.d.ts.map +0 -1
  102. package/lib/DboBuilder/uploadFile.js +0 -53
  103. package/lib/DboBuilder.d.ts +0 -306
  104. package/lib/DboBuilder.d.ts.map +0 -1
  105. package/lib/DboBuilder.js +0 -745
  106. package/lib/Event_Trigger_Tags.d.ts +0 -4
  107. package/lib/Event_Trigger_Tags.d.ts.map +0 -1
  108. package/lib/Event_Trigger_Tags.js +0 -116
  109. package/lib/FileManager/FileManager.d.ts +0 -135
  110. package/lib/FileManager/FileManager.d.ts.map +0 -1
  111. package/lib/FileManager/FileManager.js +0 -303
  112. package/lib/FileManager/initFileManager.d.ts +0 -4
  113. package/lib/FileManager/initFileManager.d.ts.map +0 -1
  114. package/lib/FileManager/initFileManager.js +0 -231
  115. package/lib/FileManager/parseFile.d.ts +0 -15
  116. package/lib/FileManager/parseFile.d.ts.map +0 -1
  117. package/lib/FileManager/parseFile.js +0 -58
  118. package/lib/FileManager/upload.d.ts +0 -6
  119. package/lib/FileManager/upload.d.ts.map +0 -1
  120. package/lib/FileManager/upload.js +0 -98
  121. package/lib/FileManager/uploadStream.d.ts +0 -5
  122. package/lib/FileManager/uploadStream.d.ts.map +0 -1
  123. package/lib/FileManager/uploadStream.js +0 -92
  124. package/lib/Filtering.d.ts +0 -15
  125. package/lib/Filtering.d.ts.map +0 -1
  126. package/lib/Filtering.js +0 -336
  127. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts +0 -4
  128. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts.map +0 -1
  129. package/lib/JSONBValidation/validate_jsonb_schema_sql.js +0 -500
  130. package/lib/JSONBValidation/validation.d.ts +0 -9
  131. package/lib/JSONBValidation/validation.d.ts.map +0 -1
  132. package/lib/JSONBValidation/validation.js +0 -131
  133. package/lib/PostgresNotifListenManager.d.ts +0 -28
  134. package/lib/PostgresNotifListenManager.d.ts.map +0 -1
  135. package/lib/PostgresNotifListenManager.js +0 -134
  136. package/lib/Prostgles.d.ts +0 -289
  137. package/lib/Prostgles.d.ts.map +0 -1
  138. package/lib/Prostgles.js +0 -685
  139. package/lib/PubSubManager/PubSubManager.d.ts +0 -175
  140. package/lib/PubSubManager/PubSubManager.d.ts.map +0 -1
  141. package/lib/PubSubManager/PubSubManager.js +0 -452
  142. package/lib/PubSubManager/addSub.d.ts +0 -8
  143. package/lib/PubSubManager/addSub.d.ts.map +0 -1
  144. package/lib/PubSubManager/addSub.js +0 -166
  145. package/lib/PubSubManager/addSync.d.ts +0 -8
  146. package/lib/PubSubManager/addSync.d.ts.map +0 -1
  147. package/lib/PubSubManager/addSync.js +0 -109
  148. package/lib/PubSubManager/getInitQuery.d.ts +0 -9
  149. package/lib/PubSubManager/getInitQuery.d.ts.map +0 -1
  150. package/lib/PubSubManager/getInitQuery.js +0 -552
  151. package/lib/PubSubManager/initPubSubManager.d.ts +0 -3
  152. package/lib/PubSubManager/initPubSubManager.d.ts.map +0 -1
  153. package/lib/PubSubManager/initPubSubManager.js +0 -116
  154. package/lib/PubSubManager/notifListener.d.ts +0 -5
  155. package/lib/PubSubManager/notifListener.d.ts.map +0 -1
  156. package/lib/PubSubManager/notifListener.js +0 -100
  157. package/lib/PubSubManager/pushSubData.d.ts +0 -3
  158. package/lib/PubSubManager/pushSubData.d.ts.map +0 -1
  159. package/lib/PubSubManager/pushSubData.js +0 -51
  160. package/lib/PublishParser.d.ts +0 -284
  161. package/lib/PublishParser.d.ts.map +0 -1
  162. package/lib/PublishParser.js +0 -421
  163. package/lib/SchemaWatch.d.ts +0 -13
  164. package/lib/SchemaWatch.d.ts.map +0 -1
  165. package/lib/SchemaWatch.js +0 -35
  166. package/lib/SyncReplication.d.ts +0 -34
  167. package/lib/SyncReplication.d.ts.map +0 -1
  168. package/lib/SyncReplication.js +0 -412
  169. package/lib/TableConfig/TableConfig.d.ts +0 -284
  170. package/lib/TableConfig/TableConfig.d.ts.map +0 -1
  171. package/lib/TableConfig/TableConfig.js +0 -437
  172. package/lib/TableConfig/getColumnDefinitionQuery.d.ts +0 -27
  173. package/lib/TableConfig/getColumnDefinitionQuery.d.ts.map +0 -1
  174. package/lib/TableConfig/getColumnDefinitionQuery.js +0 -87
  175. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts +0 -34
  176. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts.map +0 -1
  177. package/lib/TableConfig/getConstraintDefinitionQueries.js +0 -65
  178. package/lib/TableConfig/getFutureTableSchema.d.ts +0 -15
  179. package/lib/TableConfig/getFutureTableSchema.d.ts.map +0 -1
  180. package/lib/TableConfig/getFutureTableSchema.js +0 -43
  181. package/lib/TableConfig/getTableColumnQueries.d.ts +0 -16
  182. package/lib/TableConfig/getTableColumnQueries.d.ts.map +0 -1
  183. package/lib/TableConfig/getTableColumnQueries.js +0 -107
  184. package/lib/index.d.ts +0 -5
  185. package/lib/index.d.ts.map +0 -1
  186. package/lib/index.js +0 -7
  187. package/lib/shortestPath.d.ts +0 -10
  188. package/lib/shortestPath.d.ts.map +0 -1
  189. package/lib/shortestPath.js +0 -111
  190. package/lib/utils.d.ts +0 -3
  191. package/lib/utils.d.ts.map +0 -1
  192. package/lib/utils.js +0 -12
  193. package/tests/client/index.d.ts +0 -2
  194. package/tests/client/index.d.ts.map +0 -1
  195. package/tests/client/index.js +0 -80
  196. package/tests/client/index.js.map +0 -1
  197. package/tests/client_only_queries.d.ts +0 -4
  198. package/tests/client_only_queries.d.ts.map +0 -1
  199. package/tests/client_only_queries.js +0 -282
  200. package/tests/config_test/DBoGenerated.d.ts +0 -388
  201. package/tests/config_test/index.js +0 -174
  202. package/tests/config_test/index.js.map +0 -1
  203. package/tests/isomorphic_queries.d.ts +0 -9
  204. package/tests/isomorphic_queries.d.ts.map +0 -1
  205. package/tests/isomorphic_queries.js +0 -773
  206. package/tests/manual_test/DBoGenerated.d.ts +0 -398
  207. package/tests/manual_test/index.d.ts +0 -2
  208. package/tests/manual_test/index.d.ts.map +0 -1
  209. package/tests/manual_test/index.js +0 -65
  210. package/tests/server/dboTypeCheck.d.ts +0 -2
  211. package/tests/server/dboTypeCheck.d.ts.map +0 -1
  212. package/tests/server/dboTypeCheck.js +0 -27
  213. package/tests/server/index.d.ts +0 -2
  214. package/tests/server/index.d.ts.map +0 -1
  215. package/tests/server/index.js +0 -507
  216. package/tests/server/publishTypeCheck.d.ts +0 -2
  217. package/tests/server/publishTypeCheck.d.ts.map +0 -1
  218. package/tests/server/publishTypeCheck.js +0 -130
  219. package/tests/server_only_queries.d.ts +0 -2
  220. package/tests/server_only_queries.d.ts.map +0 -1
  221. package/tests/server_only_queries.js +0 -19
package/lib/DboBuilder.js DELETED
@@ -1,745 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.withUserRLS = exports.canEXECUTE = exports.prepareSort = exports.postgresToTsType = exports.isPlainObject = exports.DboBuilder = exports.parseError = exports.makeErrorFromPGError = exports.escapeTSNames = exports.pgp = void 0;
31
- const Bluebird = __importStar(require("bluebird"));
32
- const pgPromise = __importStar(require("pg-promise"));
33
- const runSQL_1 = require("./DboBuilder/runSQL");
34
- const getTablesForSchemaPostgresSQL_1 = require("./DboBuilder/getTablesForSchemaPostgresSQL");
35
- const prostgles_types_1 = require("prostgles-types");
36
- const utils_1 = require("./utils");
37
- const PubSubManager_1 = require("./PubSubManager/PubSubManager");
38
- const ViewHandler_1 = require("./DboBuilder/ViewHandler");
39
- exports.pgp = pgPromise({
40
- promiseLib: Bluebird
41
- // ,query: function (e) { console.log({psql: e.query, params: e.params}); }
42
- });
43
- function snakify(str, capitalize = false) {
44
- return str.split("").map((c, i) => {
45
- if (!i) {
46
- if (capitalize)
47
- c = c.toUpperCase();
48
- if (c.match(/[^a-z_A-Z]/)) {
49
- return ((capitalize) ? "D_" : "_") + c.charCodeAt(0);
50
- }
51
- }
52
- else {
53
- if (c.match(/[^a-zA-Z_0-9]/)) {
54
- return "_" + c.charCodeAt(0);
55
- }
56
- }
57
- return c;
58
- }).join("");
59
- }
60
- function canBeUsedAsIsInTypescript(str) {
61
- if (!str)
62
- return false;
63
- const isAlphaNumericOrUnderline = str.match(/^[a-z0-9_]+$/i);
64
- const startsWithCharOrUnderscore = str[0]?.match(/^[a-z_]+$/i);
65
- return Boolean(isAlphaNumericOrUnderline && startsWithCharOrUnderscore);
66
- }
67
- function escapeTSNames(str, capitalize = false) {
68
- let res = str;
69
- res = (capitalize ? str[0]?.toUpperCase() : str[0]) + str.slice(1);
70
- if (canBeUsedAsIsInTypescript(res))
71
- return res;
72
- return JSON.stringify(res);
73
- }
74
- exports.escapeTSNames = escapeTSNames;
75
- const shortestPath_1 = require("./shortestPath");
76
- /* DEBUG CLIENT ERRORS HERE */
77
- function makeErrorFromPGError(err, localParams, view, allowedKeys) {
78
- // console.trace(err)
79
- if (process.env.TEST_TYPE || process.env.PRGL_DEBUG) {
80
- console.trace(err);
81
- }
82
- const errObject = {
83
- ...((!localParams || !localParams.socket) ? err : {}),
84
- ...(0, PubSubManager_1.pickKeys)(err, ["column", "code", "table", "constraint", "hint"]),
85
- ...(err && err.toString ? { txt: err.toString() } : {}),
86
- code_info: sqlErrCodeToMsg(err.code)
87
- };
88
- if (view?.dboBuilder?.constraints && errObject.constraint && !errObject.column) {
89
- const constraint = view.dboBuilder.constraints
90
- .find(c => c.conname === errObject.constraint && c.relname === view.name);
91
- if (constraint) {
92
- const cols = view.columns.filter(c => (!allowedKeys || allowedKeys.includes(c.name)) &&
93
- constraint.conkey.includes(c.ordinal_position));
94
- const [firstCol] = cols;
95
- if (firstCol) {
96
- errObject.column = firstCol.name;
97
- errObject.columns = cols.map(c => c.name);
98
- }
99
- }
100
- }
101
- return Promise.reject(errObject);
102
- }
103
- exports.makeErrorFromPGError = makeErrorFromPGError;
104
- /**
105
- * Ensure the error is an Object and has
106
- */
107
- function parseError(e, caller) {
108
- const errorObject = (0, prostgles_types_1.isObject)(e) ? e : undefined;
109
- const message = typeof e === "string" ? e : e instanceof Error ? e.message :
110
- (0, prostgles_types_1.isObject)(errorObject) ? (errorObject.message ?? errorObject.txt ?? JSON.stringify(errorObject) ?? "") : "";
111
- const stack = [
112
- ...(errorObject && Array.isArray(errorObject.stack) ? errorObject.stack : []),
113
- caller
114
- ];
115
- const result = {
116
- ...errorObject,
117
- message,
118
- stack,
119
- };
120
- return result;
121
- }
122
- exports.parseError = parseError;
123
- const Prostgles_1 = require("./Prostgles");
124
- const DBSchemaBuilder_1 = require("./DBSchemaBuilder");
125
- const TableHandler_1 = require("./DboBuilder/TableHandler");
126
- class DboBuilder {
127
- tablesOrViews; //TableSchema TableOrViewInfo
128
- /**
129
- * Used in obtaining column names for error messages
130
- */
131
- constraints;
132
- db;
133
- schema = "public";
134
- // dbo: DBHandlerServer | DBHandlerServerTX;
135
- dbo;
136
- _pubSubManager;
137
- /**
138
- * Used for db.sql field type details
139
- */
140
- DATA_TYPES;
141
- USER_TABLES;
142
- USER_TABLE_COLUMNS;
143
- getPubSubManager = async () => {
144
- if (!this._pubSubManager) {
145
- let onSchemaChange;
146
- const { isSuperUs } = await PubSubManager_1.PubSubManager.canCreate(this.db);
147
- if (!exports.canEXECUTE)
148
- throw "PubSubManager based subscriptions not possible: Cannot run EXECUTE statements on this connection";
149
- if (this.prostgles.opts.watchSchema && this.prostgles.opts.watchSchemaType === "DDL_trigger") {
150
- if (!isSuperUs) {
151
- console.warn(`watchSchemaType "${this.prostgles.opts.watchSchemaType}" cannot be used because db user is not a superuser. Will fallback to watchSchemaType "prostgles_queries" `);
152
- }
153
- else {
154
- onSchemaChange = (event) => {
155
- this.prostgles.onSchemaChange(event);
156
- };
157
- }
158
- }
159
- this._pubSubManager = await PubSubManager_1.PubSubManager.create({
160
- dboBuilder: this,
161
- onSchemaChange
162
- });
163
- }
164
- if (!this._pubSubManager) {
165
- console.trace("Could not create this._pubSubManager");
166
- throw "Could not create this._pubSubManager";
167
- }
168
- return this._pubSubManager;
169
- };
170
- pojoDefinitions;
171
- // dboDefinition?: string;
172
- tsTypesDefinition;
173
- joinGraph;
174
- joinPaths = [];
175
- prostgles;
176
- publishParser;
177
- onSchemaChange;
178
- constructor(prostgles) {
179
- this.prostgles = prostgles;
180
- if (!this.prostgles.db)
181
- throw "db missing";
182
- this.db = this.prostgles.db;
183
- this.schema = this.prostgles.opts.schema || "public";
184
- this.dbo = {};
185
- }
186
- init = async () => {
187
- /* If watchSchema then PubSubManager must be created (if possible) */
188
- await this.build();
189
- if (this.prostgles.opts.watchSchema &&
190
- (this.prostgles.opts.watchSchemaType === "DDL_trigger" || !this.prostgles.opts.watchSchemaType) &&
191
- this.prostgles.isSuperUser) {
192
- await this.getPubSubManager();
193
- }
194
- return this;
195
- };
196
- static create = async (prostgles) => {
197
- const res = new DboBuilder(prostgles);
198
- return await res.init();
199
- };
200
- destroy() {
201
- this._pubSubManager?.destroy();
202
- }
203
- _joins;
204
- get joins() {
205
- return (0, utils_1.clone)(this._joins ?? []).filter(j => j.tables[0] !== j.tables[1]);
206
- }
207
- set joins(j) {
208
- this._joins = (0, utils_1.clone)(j);
209
- }
210
- getJoinPaths() {
211
- return this.joinPaths;
212
- }
213
- async parseJoins() {
214
- if (this.prostgles.opts.joins) {
215
- let _joins = await this.prostgles.opts.joins;
216
- if (!this.tablesOrViews)
217
- throw new Error("Could not create join config. this.tablesOrViews missing");
218
- const inferredJoins = await getInferredJoins2(this.tablesOrViews);
219
- if (_joins === "inferred") {
220
- _joins = inferredJoins;
221
- /* If joins are specified then include inferred joins except the explicit tables */
222
- }
223
- else if (Array.isArray(_joins)) {
224
- const joinTables = _joins.map(j => j.tables).flat();
225
- _joins = _joins.concat(inferredJoins.filter(j => !j.tables.find(t => joinTables.includes(t))));
226
- }
227
- else if (_joins) {
228
- throw new Error("Unexpected joins init param. Expecting 'inferred' OR joinConfig but got: " + JSON.stringify(_joins));
229
- }
230
- const joins = JSON.parse(JSON.stringify(_joins));
231
- this.joins = joins;
232
- // Validate joins
233
- try {
234
- const tovNames = this.tablesOrViews.map(t => t.name);
235
- // 2 find incorrect tables
236
- const missing = joins.flatMap(j => j.tables).find(t => !tovNames.includes(t));
237
- if (missing) {
238
- throw "Table not found: " + missing;
239
- }
240
- // 3 find incorrect fields
241
- joins.map(({ tables, on }) => {
242
- const t1 = tables[0], t2 = tables[1];
243
- on.map(cond => {
244
- const f1s = Object.keys(cond), f2s = Object.values(cond);
245
- [[t1, f1s], [t2, f2s]].map(v => {
246
- const t = v[0], f = v[1];
247
- const tov = this.tablesOrViews.find(_t => _t.name === t);
248
- if (!tov)
249
- throw "Table not found: " + t;
250
- const m1 = f.filter(k => !tov.columns.map(c => c.name).includes(k));
251
- if (m1 && m1.length) {
252
- throw `Table ${t}(${tov.columns.map(c => c.name).join()}) has no fields named: ${m1.join()}`;
253
- }
254
- });
255
- });
256
- });
257
- // 4 find incorrect/missing join types
258
- const expected_types = " \n\n-> Expecting: " + Prostgles_1.JOIN_TYPES.map(t => JSON.stringify(t)).join(` | `);
259
- const mt = joins.find(j => !j.type);
260
- if (mt)
261
- throw "Join type missing for: " + JSON.stringify(mt, null, 2) + expected_types;
262
- const it = joins.find(j => !Prostgles_1.JOIN_TYPES.includes(j.type));
263
- if (it)
264
- throw "Incorrect join type for: " + JSON.stringify(it, null, 2) + expected_types;
265
- }
266
- catch (e) {
267
- console.error("JOINS VALIDATION ERROR \n-> ", e);
268
- }
269
- // Make joins graph
270
- this.joinGraph = {};
271
- this.joins.forEach(({ tables }) => {
272
- const _t = tables.slice().sort(), t1 = _t[0], t2 = _t[1];
273
- if (t1 === t2)
274
- return;
275
- this.joinGraph[t1] ??= {};
276
- this.joinGraph[t1][t2] = 1;
277
- this.joinGraph[t2] ??= {};
278
- this.joinGraph[t2][t1] = 1;
279
- });
280
- const tables = Array.from(new Set(this.joins.flatMap(t => t.tables)));
281
- this.joinPaths = [];
282
- tables.forEach((t1, i1) => {
283
- tables.forEach((t2, i2) => {
284
- /** Prevent recursion */
285
- if (t1 === t2 ||
286
- this.joinPaths.some(jp => {
287
- if (arrayValuesMatch([jp.t1, jp.t2], [t1, t2])) {
288
- const spath = (0, shortestPath_1.findShortestPath)(this.joinGraph, t1, t2);
289
- if (spath && arrayValuesMatch(spath.path, jp.path)) {
290
- return true;
291
- }
292
- }
293
- })) {
294
- return;
295
- }
296
- const spath = (0, shortestPath_1.findShortestPath)(this.joinGraph, t1, t2);
297
- if (!(spath && spath.distance < Infinity))
298
- return;
299
- const existing1 = this.joinPaths.find(j => j.t1 === t1 && j.t2 === t2);
300
- if (!existing1) {
301
- this.joinPaths.push({ t1, t2, path: spath.path.slice() });
302
- }
303
- const existing2 = this.joinPaths.find(j => j.t2 === t1 && j.t1 === t2);
304
- if (!existing2) {
305
- this.joinPaths.push({ t1: t2, t2: t1, path: spath.path.slice().reverse() });
306
- }
307
- });
308
- });
309
- }
310
- return this.joinPaths;
311
- }
312
- runSQL = async (query, params, options, localParams) => {
313
- return runSQL_1.runSQL.bind(this)(query, params, options, localParams);
314
- };
315
- async build() {
316
- this.tablesOrViews = await (0, getTablesForSchemaPostgresSQL_1.getTablesForSchemaPostgresSQL)(this);
317
- this.constraints = await getConstraints(this.db);
318
- await this.parseJoins();
319
- this.dbo = {};
320
- this.tablesOrViews.map(tov => {
321
- const columnsForTypes = tov.columns.slice(0).sort((a, b) => a.name.localeCompare(b.name));
322
- const filterKeywords = Object.values(this.prostgles.keywords);
323
- const $filterCol = columnsForTypes.find(c => filterKeywords.includes(c.name));
324
- if ($filterCol) {
325
- throw `DboBuilder init error: \n\nTable ${JSON.stringify(tov.name)} column ${JSON.stringify($filterCol.name)} is colliding with Prostgles filtering functionality ($filter keyword)
326
- Please provide a replacement keyword name using the $filter_keyName init option.
327
- Alternatively you can rename the table column\n`;
328
- }
329
- this.dbo[tov.name] = new (tov.is_view ? ViewHandler_1.ViewHandler : TableHandler_1.TableHandler)(this.db, tov, this, undefined, undefined, this.joinPaths);
330
- if (this.joinPaths && this.joinPaths.find(jp => [jp.t1, jp.t2].includes(tov.name))) {
331
- const table = tov.name;
332
- const makeJoin = (isLeft = true, filter, select, options) => {
333
- return {
334
- [isLeft ? "$leftJoin" : "$innerJoin"]: table,
335
- filter,
336
- select,
337
- ...options
338
- };
339
- };
340
- this.dbo.innerJoin = this.dbo.innerJoin || {};
341
- this.dbo.leftJoin = this.dbo.leftJoin || {};
342
- this.dbo.innerJoinOne = this.dbo.innerJoinOne || {};
343
- this.dbo.leftJoinOne = this.dbo.leftJoinOne || {};
344
- this.dbo.leftJoin[table] = (filter, select, options = {}) => {
345
- return makeJoin(true, filter, select, options);
346
- };
347
- this.dbo.innerJoin[table] = (filter, select, options = {}) => {
348
- return makeJoin(false, filter, select, options);
349
- };
350
- this.dbo.leftJoinOne[table] = (filter, select, options = {}) => {
351
- return makeJoin(true, filter, select, { ...options, limit: 1 });
352
- };
353
- this.dbo.innerJoinOne[table] = (filter, select, options = {}) => {
354
- return makeJoin(false, filter, select, { ...options, limit: 1 });
355
- };
356
- }
357
- });
358
- if (this.prostgles.opts.transactions) {
359
- let txKey = "tx";
360
- if (typeof this.prostgles.opts.transactions === "string")
361
- txKey = this.prostgles.opts.transactions;
362
- this.dbo[txKey] = (cb) => this.getTX(cb);
363
- }
364
- if (!this.dbo.sql) {
365
- this.dbo.sql = this.runSQL;
366
- }
367
- else {
368
- console.warn(`Could not create dbo.sql handler because there is already a table named "sql"`);
369
- }
370
- this.tsTypesDefinition = [
371
- `/* SCHEMA DEFINITON. Table names have been altered to work with Typescript */`,
372
- `/* DBO Definition */`,
373
- (0, DBSchemaBuilder_1.getDBSchema)(this)
374
- ].join("\n");
375
- return this.dbo;
376
- }
377
- getTX = (cb) => {
378
- return this.db.tx((t) => {
379
- const dbTX = {};
380
- this.tablesOrViews?.map(tov => {
381
- dbTX[tov.name] = new (tov.is_view ? ViewHandler_1.ViewHandler : TableHandler_1.TableHandler)(this.db, tov, this, t, dbTX, this.joinPaths);
382
- });
383
- if (!dbTX.sql) {
384
- dbTX.sql = this.runSQL;
385
- }
386
- (0, prostgles_types_1.getKeys)(dbTX).map(k => {
387
- dbTX[k].dbTX = dbTX;
388
- });
389
- dbTX.sql = (q, args, opts, localP) => this.runSQL(q, args, opts, { tx: { dbTX, t }, ...(localP ?? {}) });
390
- return cb(dbTX, t);
391
- });
392
- };
393
- }
394
- exports.DboBuilder = DboBuilder;
395
- async function getConstraints(db, schema = "public", filter) {
396
- return db.any(`
397
- SELECT rel.relname, con.conkey, con.conname, con.contype
398
- FROM pg_catalog.pg_constraint con
399
- INNER JOIN pg_catalog.pg_class rel
400
- ON rel.oid = con.conrelid
401
- INNER JOIN pg_catalog.pg_namespace nsp
402
- ON nsp.oid = connamespace
403
- WHERE nsp.nspname = ${(0, PubSubManager_1.asValue)(schema)}
404
- ${!filter ? "" : "AND rel.relname = ${} AND "}
405
- `);
406
- }
407
- function isPlainObject(o) {
408
- return Object(o) === o && Object.getPrototypeOf(o) === Object.prototype;
409
- }
410
- exports.isPlainObject = isPlainObject;
411
- function postgresToTsType(udt_data_type) {
412
- return (0, prostgles_types_1.getKeys)(prostgles_types_1.TS_PG_Types).find(k => {
413
- // @ts-ignore
414
- return prostgles_types_1.TS_PG_Types[k].includes(udt_data_type);
415
- }) ?? "any";
416
- }
417
- exports.postgresToTsType = postgresToTsType;
418
- function sqlErrCodeToMsg(code) {
419
- const errs = {
420
- "00000": "successful_completion",
421
- "01000": "warning",
422
- "0100C": "dynamic_result_sets_returned",
423
- "01008": "implicit_zero_bit_padding",
424
- "01003": "null_value_eliminated_in_set_function",
425
- "01007": "privilege_not_granted",
426
- "01006": "privilege_not_revoked",
427
- "01004": "string_data_right_truncation",
428
- "01P01": "deprecated_feature",
429
- "02000": "no_data",
430
- "02001": "no_additional_dynamic_result_sets_returned",
431
- "03000": "sql_statement_not_yet_complete",
432
- "08000": "connection_exception",
433
- "08003": "connection_does_not_exist",
434
- "08006": "connection_failure",
435
- "08001": "sqlclient_unable_to_establish_sqlconnection",
436
- "08004": "sqlserver_rejected_establishment_of_sqlconnection",
437
- "08007": "transaction_resolution_unknown",
438
- "08P01": "protocol_violation",
439
- "09000": "triggered_action_exception",
440
- "0A000": "feature_not_supported",
441
- "0B000": "invalid_transaction_initiation",
442
- "0F000": "locator_exception",
443
- "0F001": "invalid_locator_specification",
444
- "0L000": "invalid_grantor",
445
- "0LP01": "invalid_grant_operation",
446
- "0P000": "invalid_role_specification",
447
- "0Z000": "diagnostics_exception",
448
- "0Z002": "stacked_diagnostics_accessed_without_active_handler",
449
- "20000": "case_not_found",
450
- "21000": "cardinality_violation",
451
- "22000": "data_exception",
452
- "2202E": "array_subscript_error",
453
- "22021": "character_not_in_repertoire",
454
- "22008": "datetime_field_overflow",
455
- "22012": "division_by_zero",
456
- "22005": "error_in_assignment",
457
- "2200B": "escape_character_conflict",
458
- "22022": "indicator_overflow",
459
- "22015": "interval_field_overflow",
460
- "2201E": "invalid_argument_for_logarithm",
461
- "22014": "invalid_argument_for_ntile_function",
462
- "22016": "invalid_argument_for_nth_value_function",
463
- "2201F": "invalid_argument_for_power_function",
464
- "2201G": "invalid_argument_for_width_bucket_function",
465
- "22018": "invalid_character_value_for_cast",
466
- "22007": "invalid_datetime_format",
467
- "22019": "invalid_escape_character",
468
- "2200D": "invalid_escape_octet",
469
- "22025": "invalid_escape_sequence",
470
- "22P06": "nonstandard_use_of_escape_character",
471
- "22010": "invalid_indicator_parameter_value",
472
- "22023": "invalid_parameter_value",
473
- "2201B": "invalid_regular_expression",
474
- "2201W": "invalid_row_count_in_limit_clause",
475
- "2201X": "invalid_row_count_in_result_offset_clause",
476
- "2202H": "invalid_tablesample_argument",
477
- "2202G": "invalid_tablesample_repeat",
478
- "22009": "invalid_time_zone_displacement_value",
479
- "2200C": "invalid_use_of_escape_character",
480
- "2200G": "most_specific_type_mismatch",
481
- "22004": "null_value_not_allowed",
482
- "22002": "null_value_no_indicator_parameter",
483
- "22003": "numeric_value_out_of_range",
484
- "2200H": "sequence_generator_limit_exceeded",
485
- "22026": "string_data_length_mismatch",
486
- "22001": "string_data_right_truncation",
487
- "22011": "substring_error",
488
- "22027": "trim_error",
489
- "22024": "unterminated_c_string",
490
- "2200F": "zero_length_character_string",
491
- "22P01": "floating_point_exception",
492
- "22P02": "invalid_text_representation",
493
- "22P03": "invalid_binary_representation",
494
- "22P04": "bad_copy_file_format",
495
- "22P05": "untranslatable_character",
496
- "2200L": "not_an_xml_document",
497
- "2200M": "invalid_xml_document",
498
- "2200N": "invalid_xml_content",
499
- "2200S": "invalid_xml_comment",
500
- "2200T": "invalid_xml_processing_instruction",
501
- "23000": "integrity_constraint_violation",
502
- "23001": "restrict_violation",
503
- "23502": "not_null_violation",
504
- "23503": "foreign_key_violation",
505
- "23505": "unique_violation",
506
- "23514": "check_violation",
507
- "23P01": "exclusion_violation",
508
- "24000": "invalid_cursor_state",
509
- "25000": "invalid_transaction_state",
510
- "25001": "active_sql_transaction",
511
- "25002": "branch_transaction_already_active",
512
- "25008": "held_cursor_requires_same_isolation_level",
513
- "25003": "inappropriate_access_mode_for_branch_transaction",
514
- "25004": "inappropriate_isolation_level_for_branch_transaction",
515
- "25005": "no_active_sql_transaction_for_branch_transaction",
516
- "25006": "read_only_sql_transaction",
517
- "25007": "schema_and_data_statement_mixing_not_supported",
518
- "25P01": "no_active_sql_transaction",
519
- "25P02": "in_failed_sql_transaction",
520
- "25P03": "idle_in_transaction_session_timeout",
521
- "26000": "invalid_sql_statement_name",
522
- "27000": "triggered_data_change_violation",
523
- "28000": "invalid_authorization_specification",
524
- "28P01": "invalid_password",
525
- "2B000": "dependent_privilege_descriptors_still_exist",
526
- "2BP01": "dependent_objects_still_exist",
527
- "2D000": "invalid_transaction_termination",
528
- "2F000": "sql_routine_exception",
529
- "2F005": "function_executed_no_return_statement",
530
- "2F002": "modifying_sql_data_not_permitted",
531
- "2F003": "prohibited_sql_statement_attempted",
532
- "2F004": "reading_sql_data_not_permitted",
533
- "34000": "invalid_cursor_name",
534
- "38000": "external_routine_exception",
535
- "38001": "containing_sql_not_permitted",
536
- "38002": "modifying_sql_data_not_permitted",
537
- "38003": "prohibited_sql_statement_attempted",
538
- "38004": "reading_sql_data_not_permitted",
539
- "39000": "external_routine_invocation_exception",
540
- "39001": "invalid_sqlstate_returned",
541
- "39004": "null_value_not_allowed",
542
- "39P01": "trigger_protocol_violated",
543
- "39P02": "srf_protocol_violated",
544
- "39P03": "event_trigger_protocol_violated",
545
- "3B000": "savepoint_exception",
546
- "3B001": "invalid_savepoint_specification",
547
- "3D000": "invalid_catalog_name",
548
- "3F000": "invalid_schema_name",
549
- "40000": "transaction_rollback",
550
- "40002": "transaction_integrity_constraint_violation",
551
- "40001": "serialization_failure",
552
- "40003": "statement_completion_unknown",
553
- "40P01": "deadlock_detected",
554
- "42000": "syntax_error_or_access_rule_violation",
555
- "42601": "syntax_error",
556
- "42501": "insufficient_privilege",
557
- "42846": "cannot_coerce",
558
- "42803": "grouping_error",
559
- "42P20": "windowing_error",
560
- "42P19": "invalid_recursion",
561
- "42830": "invalid_foreign_key",
562
- "42602": "invalid_name",
563
- "42622": "name_too_long",
564
- "42939": "reserved_name",
565
- "42804": "datatype_mismatch",
566
- "42P18": "indeterminate_datatype",
567
- "42P21": "collation_mismatch",
568
- "42P22": "indeterminate_collation",
569
- "42809": "wrong_object_type",
570
- "428C9": "generated_always",
571
- "42703": "undefined_column",
572
- "42883": "undefined_function",
573
- "42P01": "undefined_table",
574
- "42P02": "undefined_parameter",
575
- "42704": "undefined_object",
576
- "42701": "duplicate_column",
577
- "42P03": "duplicate_cursor",
578
- "42P04": "duplicate_database",
579
- "42723": "duplicate_function",
580
- "42P05": "duplicate_prepared_statement",
581
- "42P06": "duplicate_schema",
582
- "42P07": "duplicate_table",
583
- "42712": "duplicate_alias",
584
- "42710": "duplicate_object",
585
- "42702": "ambiguous_column",
586
- "42725": "ambiguous_function",
587
- "42P08": "ambiguous_parameter",
588
- "42P09": "ambiguous_alias",
589
- "42P10": "invalid_column_reference",
590
- "42611": "invalid_column_definition",
591
- "42P11": "invalid_cursor_definition",
592
- "42P12": "invalid_database_definition",
593
- "42P13": "invalid_function_definition",
594
- "42P14": "invalid_prepared_statement_definition",
595
- "42P15": "invalid_schema_definition",
596
- "42P16": "invalid_table_definition",
597
- "42P17": "invalid_object_definition",
598
- "44000": "with_check_option_violation",
599
- "53000": "insufficient_resources",
600
- "53100": "disk_full",
601
- "53200": "out_of_memory",
602
- "53300": "too_many_connections",
603
- "53400": "configuration_limit_exceeded",
604
- "54000": "program_limit_exceeded",
605
- "54001": "statement_too_complex",
606
- "54011": "too_many_columns",
607
- "54023": "too_many_arguments",
608
- "55000": "object_not_in_prerequisite_state",
609
- "55006": "object_in_use",
610
- "55P02": "cant_change_runtime_param",
611
- "55P03": "lock_not_available",
612
- "57000": "operator_intervention",
613
- "57014": "query_canceled",
614
- "57P01": "admin_shutdown",
615
- "57P02": "crash_shutdown",
616
- "57P03": "cannot_connect_now",
617
- "57P04": "database_dropped",
618
- "58000": "system_error",
619
- "58030": "io_error",
620
- "58P01": "undefined_file",
621
- "58P02": "duplicate_file",
622
- "72000": "snapshot_too_old",
623
- "F0000": "config_file_error",
624
- "F0001": "lock_file_exists",
625
- "HV000": "fdw_error",
626
- "HV005": "fdw_column_name_not_found",
627
- "HV002": "fdw_dynamic_parameter_value_needed",
628
- "HV010": "fdw_function_sequence_error",
629
- "HV021": "fdw_inconsistent_descriptor_information",
630
- "HV024": "fdw_invalid_attribute_value",
631
- "HV007": "fdw_invalid_column_name",
632
- "HV008": "fdw_invalid_column_number",
633
- "HV004": "fdw_invalid_data_type",
634
- "HV006": "fdw_invalid_data_type_descriptors",
635
- "HV091": "fdw_invalid_descriptor_field_identifier",
636
- "HV00B": "fdw_invalid_handle",
637
- "HV00C": "fdw_invalid_option_index",
638
- "HV00D": "fdw_invalid_option_name",
639
- "HV090": "fdw_invalid_string_length_or_buffer_length",
640
- "HV00A": "fdw_invalid_string_format",
641
- "HV009": "fdw_invalid_use_of_null_pointer",
642
- "HV014": "fdw_too_many_handles",
643
- "HV001": "fdw_out_of_memory",
644
- "HV00P": "fdw_no_schemas",
645
- "HV00J": "fdw_option_name_not_found",
646
- "HV00K": "fdw_reply_handle",
647
- "HV00Q": "fdw_schema_not_found",
648
- "HV00R": "fdw_table_not_found",
649
- "HV00L": "fdw_unable_to_create_execution",
650
- "HV00M": "fdw_unable_to_create_reply",
651
- "HV00N": "fdw_unable_to_establish_connection",
652
- "P0000": "plpgsql_error",
653
- "P0001": "raise_exception",
654
- "P0002": "no_data_found",
655
- "P0003": "too_many_rows",
656
- "P0004": "assert_failure",
657
- "XX000": "internal_error",
658
- "XX001": "data_corrupted",
659
- "XX002": "index_corrupted"
660
- }, c2 = { "20000": "case_not_found", "21000": "cardinality_violation", "22000": "data_exception", "22001": "string_data_right_truncation", "22002": "null_value_no_indicator_parameter", "22003": "numeric_value_out_of_range", "22004": "null_value_not_allowed", "22005": "error_in_assignment", "22007": "invalid_datetime_format", "22008": "datetime_field_overflow", "22009": "invalid_time_zone_displacement_value", "22010": "invalid_indicator_parameter_value", "22011": "substring_error", "22012": "division_by_zero", "22013": "invalid_preceding_or_following_size", "22014": "invalid_argument_for_ntile_function", "22015": "interval_field_overflow", "22016": "invalid_argument_for_nth_value_function", "22018": "invalid_character_value_for_cast", "22019": "invalid_escape_character", "22021": "character_not_in_repertoire", "22022": "indicator_overflow", "22023": "invalid_parameter_value", "22024": "unterminated_c_string", "22025": "invalid_escape_sequence", "22026": "string_data_length_mismatch", "22027": "trim_error", "22030": "duplicate_json_object_key_value", "22031": "invalid_argument_for_sql_json_datetime_function", "22032": "invalid_json_text", "22033": "invalid_sql_json_subscript", "22034": "more_than_one_sql_json_item", "22035": "no_sql_json_item", "22036": "non_numeric_sql_json_item", "22037": "non_unique_keys_in_a_json_object", "22038": "singleton_sql_json_item_required", "22039": "sql_json_array_not_found", "23000": "integrity_constraint_violation", "23001": "restrict_violation", "23502": "not_null_violation", "23503": "foreign_key_violation", "23505": "unique_violation", "23514": "check_violation", "24000": "invalid_cursor_state", "25000": "invalid_transaction_state", "25001": "active_sql_transaction", "25002": "branch_transaction_already_active", "25003": "inappropriate_access_mode_for_branch_transaction", "25004": "inappropriate_isolation_level_for_branch_transaction", "25005": "no_active_sql_transaction_for_branch_transaction", "25006": "read_only_sql_transaction", "25007": "schema_and_data_statement_mixing_not_supported", "25008": "held_cursor_requires_same_isolation_level", "26000": "invalid_sql_statement_name", "27000": "triggered_data_change_violation", "28000": "invalid_authorization_specification", "34000": "invalid_cursor_name", "38000": "external_routine_exception", "38001": "containing_sql_not_permitted", "38002": "modifying_sql_data_not_permitted", "38003": "prohibited_sql_statement_attempted", "38004": "reading_sql_data_not_permitted", "39000": "external_routine_invocation_exception", "39001": "invalid_sqlstate_returned", "39004": "null_value_not_allowed", "40000": "transaction_rollback", "40001": "serialization_failure", "40002": "transaction_integrity_constraint_violation", "40003": "statement_completion_unknown", "42000": "syntax_error_or_access_rule_violation", "42501": "insufficient_privilege", "42601": "syntax_error", "42602": "invalid_name", "42611": "invalid_column_definition", "42622": "name_too_long", "42701": "duplicate_column", "42702": "ambiguous_column", "42703": "undefined_column", "42704": "undefined_object", "42710": "duplicate_object", "42712": "duplicate_alias", "42723": "duplicate_function", "42725": "ambiguous_function", "42803": "grouping_error", "42804": "datatype_mismatch", "42809": "wrong_object_type", "42830": "invalid_foreign_key", "42846": "cannot_coerce", "42883": "undefined_function", "42939": "reserved_name", "44000": "with_check_option_violation", "53000": "insufficient_resources", "53100": "disk_full", "53200": "out_of_memory", "53300": "too_many_connections", "53400": "configuration_limit_exceeded", "54000": "program_limit_exceeded", "54001": "statement_too_complex", "54011": "too_many_columns", "54023": "too_many_arguments", "55000": "object_not_in_prerequisite_state", "55006": "object_in_use", "57000": "operator_intervention", "57014": "query_canceled", "58000": "system_error", "58030": "io_error", "72000": "snapshot_too_old", "00000": "successful_completion", "01000": "warning", "0100C": "dynamic_result_sets_returned", "01008": "implicit_zero_bit_padding", "01003": "null_value_eliminated_in_set_function", "01007": "privilege_not_granted", "01006": "privilege_not_revoked", "01004": "string_data_right_truncation", "01P01": "deprecated_feature", "02000": "no_data", "02001": "no_additional_dynamic_result_sets_returned", "03000": "sql_statement_not_yet_complete", "08000": "connection_exception", "08003": "connection_does_not_exist", "08006": "connection_failure", "08001": "sqlclient_unable_to_establish_sqlconnection", "08004": "sqlserver_rejected_establishment_of_sqlconnection", "08007": "transaction_resolution_unknown", "08P01": "protocol_violation", "09000": "triggered_action_exception", "0A000": "feature_not_supported", "0B000": "invalid_transaction_initiation", "0F000": "locator_exception", "0F001": "invalid_locator_specification", "0L000": "invalid_grantor", "0LP01": "invalid_grant_operation", "0P000": "invalid_role_specification", "0Z000": "diagnostics_exception", "0Z002": "stacked_diagnostics_accessed_without_active_handler", "2202E": "array_subscript_error", "2200B": "escape_character_conflict", "2201E": "invalid_argument_for_logarithm", "2201F": "invalid_argument_for_power_function", "2201G": "invalid_argument_for_width_bucket_function", "2200D": "invalid_escape_octet", "22P06": "nonstandard_use_of_escape_character", "2201B": "invalid_regular_expression", "2201W": "invalid_row_count_in_limit_clause", "2201X": "invalid_row_count_in_result_offset_clause", "2202H": "invalid_tablesample_argument", "2202G": "invalid_tablesample_repeat", "2200C": "invalid_use_of_escape_character", "2200G": "most_specific_type_mismatch", "2200H": "sequence_generator_limit_exceeded", "2200F": "zero_length_character_string", "22P01": "floating_point_exception", "22P02": "invalid_text_representation", "22P03": "invalid_binary_representation", "22P04": "bad_copy_file_format", "22P05": "untranslatable_character", "2200L": "not_an_xml_document", "2200M": "invalid_xml_document", "2200N": "invalid_xml_content", "2200S": "invalid_xml_comment", "2200T": "invalid_xml_processing_instruction", "2203A": "sql_json_member_not_found", "2203B": "sql_json_number_not_found", "2203C": "sql_json_object_not_found", "2203D": "too_many_json_array_elements", "2203E": "too_many_json_object_members", "2203F": "sql_json_scalar_required", "23P01": "exclusion_violation", "25P01": "no_active_sql_transaction", "25P02": "in_failed_sql_transaction", "25P03": "idle_in_transaction_session_timeout", "28P01": "invalid_password", "2B000": "dependent_privilege_descriptors_still_exist", "2BP01": "dependent_objects_still_exist", "2D000": "invalid_transaction_termination", "2F000": "sql_routine_exception", "2F005": "function_executed_no_return_statement", "2F002": "modifying_sql_data_not_permitted", "2F003": "prohibited_sql_statement_attempted", "2F004": "reading_sql_data_not_permitted", "39P01": "trigger_protocol_violated", "39P02": "srf_protocol_violated", "39P03": "event_trigger_protocol_violated", "3B000": "savepoint_exception", "3B001": "invalid_savepoint_specification", "3D000": "invalid_catalog_name", "3F000": "invalid_schema_name", "40P01": "deadlock_detected", "42P20": "windowing_error", "42P19": "invalid_recursion", "42P18": "indeterminate_datatype", "42P21": "collation_mismatch", "42P22": "indeterminate_collation", "428C9": "generated_always", "42P01": "undefined_table", "42P02": "undefined_parameter", "42P03": "duplicate_cursor", "42P04": "duplicate_database", "42P05": "duplicate_prepared_statement", "42P06": "duplicate_schema", "42P07": "duplicate_table", "42P08": "ambiguous_parameter", "42P09": "ambiguous_alias", "42P10": "invalid_column_reference", "42P11": "invalid_cursor_definition", "42P12": "invalid_database_definition", "42P13": "invalid_function_definition", "42P14": "invalid_prepared_statement_definition", "42P15": "invalid_schema_definition", "42P16": "invalid_table_definition", "42P17": "invalid_object_definition", "55P02": "cant_change_runtime_param", "55P03": "lock_not_available", "55P04": "unsafe_new_enum_value_usage", "57P01": "admin_shutdown", "57P02": "crash_shutdown", "57P03": "cannot_connect_now", "57P04": "database_dropped", "58P01": "undefined_file", "58P02": "duplicate_file", "F0000": "config_file_error", "F0001": "lock_file_exists", "HV000": "fdw_error", "HV005": "fdw_column_name_not_found", "HV002": "fdw_dynamic_parameter_value_needed", "HV010": "fdw_function_sequence_error", "HV021": "fdw_inconsistent_descriptor_information", "HV024": "fdw_invalid_attribute_value", "HV007": "fdw_invalid_column_name", "HV008": "fdw_invalid_column_number", "HV004": "fdw_invalid_data_type", "HV006": "fdw_invalid_data_type_descriptors", "HV091": "fdw_invalid_descriptor_field_identifier", "HV00B": "fdw_invalid_handle", "HV00C": "fdw_invalid_option_index", "HV00D": "fdw_invalid_option_name", "HV090": "fdw_invalid_string_length_or_buffer_length", "HV00A": "fdw_invalid_string_format", "HV009": "fdw_invalid_use_of_null_pointer", "HV014": "fdw_too_many_handles", "HV001": "fdw_out_of_memory", "HV00P": "fdw_no_schemas", "HV00J": "fdw_option_name_not_found", "HV00K": "fdw_reply_handle", "HV00Q": "fdw_schema_not_found", "HV00R": "fdw_table_not_found", "HV00L": "fdw_unable_to_create_execution", "HV00M": "fdw_unable_to_create_reply", "HV00N": "fdw_unable_to_establish_connection", "P0000": "plpgsql_error", "P0001": "raise_exception", "P0002": "no_data_found", "P0003": "too_many_rows", "P0004": "assert_failure", "XX000": "internal_error", "XX001": "data_corrupted", "XX002": "index_corrupted" };
661
- //@ts-ignore
662
- return c2[code] || errs[code] || code;
663
- /*
664
- https://www.postgresql.org/docs/13/errcodes-appendix.html
665
- JSON.stringify([...THE_table_$0.rows].map(t => [...t.children].map(u => u.innerText)).filter((d, i) => i && d.length > 1).reduce((a, v)=>({ ...a, [v[0]]: v[1] }), {}))
666
- */
667
- }
668
- const arrayValuesMatch = (arr1, arr2) => {
669
- return arr1.slice().sort().join() === arr2.slice().sort().join();
670
- };
671
- async function getInferredJoins2(schema) {
672
- const joins = [];
673
- const upsertJoin = (t1, t2, cols, type) => {
674
- const existingIdx = joins.findIndex(j => arrayValuesMatch(j.tables.slice(0), [t1, t2]));
675
- const existing = joins[existingIdx];
676
- const normalCond = cols.reduce((a, v) => ({ ...a, [v.col1]: v.col2 }), {});
677
- const revertedCond = cols.reduce((a, v) => ({ ...a, [v.col2]: v.col1 }), {});
678
- if (existing) {
679
- const isLTR = existing.tables[0] === t1;
680
- const cond = isLTR ? normalCond : revertedCond;
681
- /** At some point we should add relationship type to EACH JOIN CONDITION GROUP */
682
- // const fixedType = isLTR? type : type.split("").reverse().join("") as Join["type"];
683
- /** Avoid duplicates */
684
- if (!existing.on.some(_cond => JSON.stringify(_cond) === JSON.stringify(cond))) {
685
- existing.on.push(cond);
686
- joins[existingIdx] = existing;
687
- }
688
- }
689
- else {
690
- joins.push({
691
- tables: [t1, t2],
692
- on: [normalCond],
693
- type
694
- });
695
- }
696
- };
697
- schema.map(tov => {
698
- tov.columns.map(col => {
699
- if (col.references) {
700
- col.references.forEach(r => {
701
- const joinCols = r.cols.map((c, i) => ({ col1: c, col2: r.fcols[i] }));
702
- let type = "one-many";
703
- const ftablePkeys = schema.find(_tov => _tov.name === r.ftable)?.columns.filter(fcol => fcol.is_pkey);
704
- if (ftablePkeys?.length && ftablePkeys.every(fkey => r.fcols.includes(fkey.name))) {
705
- type = "one-one";
706
- }
707
- upsertJoin(tov.name, r.ftable, joinCols, type);
708
- });
709
- }
710
- });
711
- });
712
- return joins;
713
- }
714
- const prepareSort = (items, excludeOrder = false) => {
715
- if (!items.length)
716
- return "";
717
- return (excludeOrder ? "" : " ORDER BY ") + items.map(d => {
718
- const orderType = d.asc ? " ASC " : " DESC ";
719
- const nullOrder = d.nulls ? ` NULLS ${d.nulls === "first" ? " FIRST " : " LAST "}` : "";
720
- const colKey = "fieldQuery" in d ? d.fieldQuery : d.fieldPosition;
721
- return `${colKey} ${orderType} ${nullOrder}`;
722
- }).join(", ");
723
- };
724
- exports.prepareSort = prepareSort;
725
- const canEXECUTE = async (db) => {
726
- try {
727
- await db.any(`DO $$ BEGIN EXECUTE 'select 1'; END $$;`);
728
- return true;
729
- }
730
- catch (error) {
731
- console.warn(error);
732
- }
733
- return false;
734
- };
735
- exports.canEXECUTE = canEXECUTE;
736
- const withUserRLS = (localParams, query) => {
737
- const user = localParams?.isRemoteRequest?.user;
738
- const queryPrefix = `SET SESSION "prostgles.user" \nTO`;
739
- let firstQuery = `${queryPrefix} '';`;
740
- if (user) {
741
- firstQuery = exports.pgp.as.format(`${queryPrefix} \${user};`, { user });
742
- }
743
- return [firstQuery, query].join("\n");
744
- };
745
- exports.withUserRLS = withUserRLS;