prostgles-server 4.2.160 → 4.2.162
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/AuthHandler.d.ts +4 -4
- package/dist/Auth/AuthHandler.d.ts.map +1 -1
- package/dist/Auth/AuthHandler.js.map +1 -1
- package/dist/Auth/setEmailProvider.d.ts.map +1 -1
- package/dist/Auth/setEmailProvider.js +5 -5
- package/dist/Auth/setEmailProvider.js.map +1 -1
- package/dist/Auth/setupAuthRoutes.d.ts.map +1 -1
- package/dist/Auth/setupAuthRoutes.js +5 -6
- package/dist/Auth/setupAuthRoutes.js.map +1 -1
- package/lib/Auth/AuthHandler.ts +436 -0
- package/lib/Auth/AuthTypes.ts +280 -0
- package/lib/Auth/getSafeReturnURL.ts +35 -0
- package/lib/Auth/sendEmail.ts +83 -0
- package/lib/Auth/setAuthProviders.ts +128 -0
- package/lib/Auth/setEmailProvider.ts +85 -0
- package/lib/Auth/setupAuthRoutes.ts +159 -0
- package/lib/DBEventsManager.ts +178 -0
- package/lib/DBSchemaBuilder.ts +225 -0
- package/lib/DboBuilder/DboBuilder.ts +319 -0
- package/lib/DboBuilder/DboBuilderTypes.ts +361 -0
- package/lib/DboBuilder/QueryBuilder/Functions.ts +1153 -0
- package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +288 -0
- package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +263 -0
- package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +271 -0
- package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +136 -0
- package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +22 -0
- package/lib/DboBuilder/QueryStreamer.ts +250 -0
- package/lib/DboBuilder/TableHandler/DataValidator.ts +428 -0
- package/lib/DboBuilder/TableHandler/TableHandler.ts +205 -0
- package/lib/DboBuilder/TableHandler/delete.ts +115 -0
- package/lib/DboBuilder/TableHandler/insert.ts +183 -0
- package/lib/DboBuilder/TableHandler/insertTest.ts +78 -0
- package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +62 -0
- package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +134 -0
- package/lib/DboBuilder/TableHandler/update.ts +126 -0
- package/lib/DboBuilder/TableHandler/updateBatch.ts +49 -0
- package/lib/DboBuilder/TableHandler/updateFile.ts +48 -0
- package/lib/DboBuilder/TableHandler/upsert.ts +34 -0
- package/lib/DboBuilder/ViewHandler/ViewHandler.ts +393 -0
- package/lib/DboBuilder/ViewHandler/count.ts +38 -0
- package/lib/DboBuilder/ViewHandler/find.ts +153 -0
- package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +73 -0
- package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +74 -0
- package/lib/DboBuilder/ViewHandler/getInfo.ts +32 -0
- package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +84 -0
- package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +96 -0
- package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +105 -0
- package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +208 -0
- package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +163 -0
- package/lib/DboBuilder/ViewHandler/prepareWhere.ts +90 -0
- package/lib/DboBuilder/ViewHandler/size.ts +37 -0
- package/lib/DboBuilder/ViewHandler/subscribe.ts +118 -0
- package/lib/DboBuilder/ViewHandler/validateViewRules.ts +70 -0
- package/lib/DboBuilder/dboBuilderUtils.ts +222 -0
- package/lib/DboBuilder/getColumns.ts +114 -0
- package/lib/DboBuilder/getCondition.ts +201 -0
- package/lib/DboBuilder/getSubscribeRelatedTables.ts +190 -0
- package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +426 -0
- package/lib/DboBuilder/insertNestedRecords.ts +355 -0
- package/lib/DboBuilder/parseUpdateRules.ts +187 -0
- package/lib/DboBuilder/prepareShortestJoinPaths.ts +186 -0
- package/lib/DboBuilder/runSQL.ts +182 -0
- package/lib/DboBuilder/runTransaction.ts +50 -0
- package/lib/DboBuilder/sqlErrCodeToMsg.ts +254 -0
- package/lib/DboBuilder/uploadFile.ts +69 -0
- package/lib/Event_Trigger_Tags.ts +118 -0
- package/lib/FileManager/FileManager.ts +358 -0
- package/lib/FileManager/getValidatedFileType.ts +69 -0
- package/lib/FileManager/initFileManager.ts +187 -0
- package/lib/FileManager/upload.ts +62 -0
- package/lib/FileManager/uploadStream.ts +79 -0
- package/lib/Filtering.ts +463 -0
- package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +502 -0
- package/lib/JSONBValidation/validation.ts +143 -0
- package/lib/Logging.ts +127 -0
- package/lib/PostgresNotifListenManager.ts +143 -0
- package/lib/Prostgles.ts +485 -0
- package/lib/ProstglesTypes.ts +196 -0
- package/lib/PubSubManager/PubSubManager.ts +609 -0
- package/lib/PubSubManager/addSub.ts +138 -0
- package/lib/PubSubManager/addSync.ts +141 -0
- package/lib/PubSubManager/getCreatePubSubManagerError.ts +72 -0
- package/lib/PubSubManager/getPubSubManagerInitQuery.ts +662 -0
- package/lib/PubSubManager/initPubSubManager.ts +79 -0
- package/lib/PubSubManager/notifListener.ts +173 -0
- package/lib/PubSubManager/orphanTriggerCheck.ts +70 -0
- package/lib/PubSubManager/pushSubData.ts +55 -0
- package/lib/PublishParser/PublishParser.ts +162 -0
- package/lib/PublishParser/getFileTableRules.ts +124 -0
- package/lib/PublishParser/getSchemaFromPublish.ts +141 -0
- package/lib/PublishParser/getTableRulesWithoutFileTable.ts +177 -0
- package/lib/PublishParser/publishTypesAndUtils.ts +399 -0
- package/lib/RestApi.ts +127 -0
- package/lib/SchemaWatch/SchemaWatch.ts +90 -0
- package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +3 -0
- package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +45 -0
- package/lib/SchemaWatch/getWatchSchemaTagList.ts +27 -0
- package/lib/SyncReplication.ts +557 -0
- package/lib/TableConfig/TableConfig.ts +468 -0
- package/lib/TableConfig/getColumnDefinitionQuery.ts +111 -0
- package/lib/TableConfig/getConstraintDefinitionQueries.ts +95 -0
- package/lib/TableConfig/getFutureTableSchema.ts +64 -0
- package/lib/TableConfig/getPGIndexes.ts +53 -0
- package/lib/TableConfig/getTableColumnQueries.ts +129 -0
- package/lib/TableConfig/initTableConfig.ts +326 -0
- package/lib/index.ts +13 -0
- package/lib/initProstgles.ts +319 -0
- package/lib/onSocketConnected.ts +102 -0
- package/lib/runClientRequest.ts +129 -0
- package/lib/shortestPath.ts +122 -0
- package/lib/typeTests/DBoGenerated.d.ts +320 -0
- package/lib/typeTests/dboTypeCheck.ts +81 -0
- package/lib/utils.ts +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { DetailedJoinSelect, JoinPath, JoinSelect, RawJoinPath, SelectParams, SimpleJoinSelect, getKeys, isEmpty, omitKeys } from "prostgles-types";
|
|
2
|
+
import { TableRule } from "../../PublishParser/PublishParser";
|
|
3
|
+
import { Filter, LocalParams, ValidatedTableRules } from "../DboBuilder";
|
|
4
|
+
import { ViewHandler } from "../ViewHandler/ViewHandler";
|
|
5
|
+
import { parseJoinPath } from "../ViewHandler/parseJoinPath";
|
|
6
|
+
import { prepareSortItems } from "../ViewHandler/prepareSortItems";
|
|
7
|
+
import { PrepareWhereParams } from "../ViewHandler/prepareWhere";
|
|
8
|
+
import { COMPUTED_FIELDS, FUNCTIONS } from "./Functions";
|
|
9
|
+
import { NewQuery, NewQueryJoin, SelectItemBuilder } from "./QueryBuilder";
|
|
10
|
+
|
|
11
|
+
const JOIN_KEYS = ["$innerJoin", "$leftJoin"] as const;
|
|
12
|
+
const JOIN_PARAM_KEYS = getKeys({
|
|
13
|
+
$condition: 1,
|
|
14
|
+
filter: 1,
|
|
15
|
+
having: 1,
|
|
16
|
+
limit: 1,
|
|
17
|
+
offset: 1,
|
|
18
|
+
orderBy: 1,
|
|
19
|
+
select: 1
|
|
20
|
+
} satisfies Record<keyof Omit<DetailedJoinSelect, typeof JOIN_KEYS[number]>, 1>);
|
|
21
|
+
|
|
22
|
+
type ParsedJoin =
|
|
23
|
+
| { type: "detailed"; params: DetailedJoinSelect & { table: DetailedJoinSelect["$leftJoin"]; path: RawJoinPath } }
|
|
24
|
+
| { type: "simple"; params: SimpleJoinSelect; }
|
|
25
|
+
| { type?: undefined; error: string; };
|
|
26
|
+
|
|
27
|
+
const parseJoinSelect = (joinParams: string | JoinSelect): ParsedJoin => {
|
|
28
|
+
if(!joinParams){
|
|
29
|
+
return {
|
|
30
|
+
error: "Empty join params"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if(typeof joinParams === "string"){
|
|
34
|
+
if(joinParams !== "*"){
|
|
35
|
+
throw "Join select can be * or { field: 1 }"
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
type: "simple",
|
|
39
|
+
params: joinParams
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const [joinKey, ...otherKeys] = getKeys(joinParams).filter(k => JOIN_KEYS.includes(k as any));
|
|
43
|
+
if(otherKeys.length) {
|
|
44
|
+
return {
|
|
45
|
+
error: "Cannot specify more than one join type ( $innerJoin OR $leftJoin )"
|
|
46
|
+
}
|
|
47
|
+
} else if(joinKey) {
|
|
48
|
+
|
|
49
|
+
/* Full option join { field_name: db.innerJoin.table_name(filter, select) } */
|
|
50
|
+
const invalidParams = Object.keys(joinParams).filter(k => ![ ...JOIN_PARAM_KEYS, ...JOIN_KEYS ].includes(k as any));
|
|
51
|
+
if(invalidParams.length) {
|
|
52
|
+
throw "Invalid join params: " + invalidParams.join(", ");
|
|
53
|
+
}
|
|
54
|
+
const path = joinParams[joinKey] as string | JoinPath[];
|
|
55
|
+
if(Array.isArray(path) && !path.length){
|
|
56
|
+
throw `Cannot have an empty join path/tableName ${joinKey}`
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
type: "detailed",
|
|
60
|
+
params: {
|
|
61
|
+
...(joinParams as DetailedJoinSelect),
|
|
62
|
+
path,
|
|
63
|
+
table: typeof path === "string"? path : path.at(-1)!.table,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
type: "simple",
|
|
70
|
+
params: joinParams as SimpleJoinSelect
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function getNewQuery(
|
|
75
|
+
_this: ViewHandler,
|
|
76
|
+
filter: Filter,
|
|
77
|
+
selectParams: (SelectParams & { alias?: string }) = {},
|
|
78
|
+
param3_unused = null,
|
|
79
|
+
tableRules: TableRule | undefined,
|
|
80
|
+
localParams: LocalParams | undefined,
|
|
81
|
+
): Promise<NewQuery> {
|
|
82
|
+
const { columns } = _this;
|
|
83
|
+
|
|
84
|
+
if(localParams?.isRemoteRequest && !tableRules?.select?.fields){
|
|
85
|
+
throw `INTERNAL ERROR: publish.${_this.name}.select.fields rule missing`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const allowedOrderByFields = !tableRules? _this.column_names.slice(0) : _this.parseFieldFilter(tableRules?.select?.orderByFields ?? tableRules?.select?.fields);
|
|
89
|
+
const allowedSelectFields = !tableRules? _this.column_names.slice(0) : _this.parseFieldFilter(tableRules?.select?.fields);
|
|
90
|
+
|
|
91
|
+
const joinQueries: NewQueryJoin[] = [];
|
|
92
|
+
|
|
93
|
+
const { select: userSelect = "*" } = selectParams,
|
|
94
|
+
sBuilder = new SelectItemBuilder({
|
|
95
|
+
allowedFields: allowedSelectFields,
|
|
96
|
+
allowedOrderByFields,
|
|
97
|
+
computedFields: COMPUTED_FIELDS,
|
|
98
|
+
isView: _this.is_view,
|
|
99
|
+
functions: FUNCTIONS,
|
|
100
|
+
allFields: _this.column_names.slice(0),
|
|
101
|
+
columns
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
await sBuilder.parseUserSelect(userSelect, async (fTable, _joinParams, throwErr) => {
|
|
106
|
+
|
|
107
|
+
const j_selectParams: SelectParams = {};
|
|
108
|
+
let j_filter: Filter = {},
|
|
109
|
+
j_isLeftJoin = true,
|
|
110
|
+
j_tableRules: TableRule | undefined;
|
|
111
|
+
const j_alias = fTable;
|
|
112
|
+
|
|
113
|
+
const parsedJoin = parseJoinSelect(_joinParams);
|
|
114
|
+
|
|
115
|
+
if(!parsedJoin.type){
|
|
116
|
+
throwErr(parsedJoin.error);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const j_path = parseJoinPath({
|
|
120
|
+
rawPath: parsedJoin.type === "simple"? fTable : parsedJoin.params.path,
|
|
121
|
+
rootTable: _this.name,
|
|
122
|
+
viewHandler: _this,
|
|
123
|
+
allowMultiOrJoin: true,
|
|
124
|
+
addShortestJoinIfMissing: true,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
if(parsedJoin.params === "*"){
|
|
128
|
+
j_selectParams.select = "*";
|
|
129
|
+
} else if(parsedJoin.type === "detailed") {
|
|
130
|
+
const joinParams = parsedJoin.params;
|
|
131
|
+
|
|
132
|
+
j_isLeftJoin = !!joinParams.$leftJoin;
|
|
133
|
+
|
|
134
|
+
j_selectParams.select = joinParams.select || "*";
|
|
135
|
+
j_filter = joinParams.filter || {};
|
|
136
|
+
j_selectParams.limit = joinParams.limit;
|
|
137
|
+
j_selectParams.offset = joinParams.offset;
|
|
138
|
+
j_selectParams.orderBy = joinParams.orderBy;
|
|
139
|
+
j_selectParams.having = joinParams.having;
|
|
140
|
+
} else {
|
|
141
|
+
j_selectParams.select = parsedJoin.params;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const jTable = parsedJoin.type === "simple"? fTable : (typeof j_path === "string"? j_path : j_path?.at(-1)?.table);
|
|
145
|
+
if(!jTable) {
|
|
146
|
+
throw "jTable missing";
|
|
147
|
+
}
|
|
148
|
+
const _thisJoinedTable: any = _this.dboBuilder.dbo[jTable];
|
|
149
|
+
if(!_thisJoinedTable) {
|
|
150
|
+
throw `Joined table ${JSON.stringify(jTable)} is disallowed or inexistent \nOr you've forgot to put the function arguments into an array`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
let isLocal = true;
|
|
154
|
+
if(localParams && (localParams.socket || localParams.httpReq)){
|
|
155
|
+
isLocal = false;
|
|
156
|
+
j_tableRules = await _this.dboBuilder.publishParser?.getValidatedRequestRuleWusr({ tableName: jTable, command: "find", localParams });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const isAllowedAccessToTable = isLocal || j_tableRules;
|
|
160
|
+
if(isAllowedAccessToTable){
|
|
161
|
+
|
|
162
|
+
const joinQuery: NewQuery = await getNewQuery(
|
|
163
|
+
_thisJoinedTable,
|
|
164
|
+
j_filter,
|
|
165
|
+
{ ...j_selectParams, alias: j_alias },
|
|
166
|
+
param3_unused,
|
|
167
|
+
j_tableRules,
|
|
168
|
+
localParams,
|
|
169
|
+
);
|
|
170
|
+
joinQuery.isLeftJoin = j_isLeftJoin;
|
|
171
|
+
joinQuery.tableAlias = j_alias;
|
|
172
|
+
joinQueries.push({
|
|
173
|
+
...joinQuery,
|
|
174
|
+
joinPath: j_path,
|
|
175
|
+
joinAlias: joinQuery.tableAlias ?? joinQuery.table,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Is this still needed?!!!
|
|
182
|
+
* Add non selected columns
|
|
183
|
+
* This ensures all fields are available for orderBy in case of nested select
|
|
184
|
+
* */
|
|
185
|
+
Array.from(new Set([...allowedSelectFields, ...allowedOrderByFields])).map(key => {
|
|
186
|
+
if(!sBuilder.select.find(s => s.alias === key && s.type === "column")){
|
|
187
|
+
sBuilder.addColumn(key, false);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
const select = sBuilder.select;
|
|
192
|
+
|
|
193
|
+
const tableAlias = selectParams.alias;
|
|
194
|
+
const commonWhereParams: PrepareWhereParams = {
|
|
195
|
+
filter,
|
|
196
|
+
select,
|
|
197
|
+
forcedFilter: tableRules?.select?.forcedFilter,
|
|
198
|
+
filterFields: tableRules?.select?.filterFields,
|
|
199
|
+
tableAlias,
|
|
200
|
+
localParams,
|
|
201
|
+
tableRule: tableRules,
|
|
202
|
+
isHaving: false,
|
|
203
|
+
}
|
|
204
|
+
const filterOpts = await _this.prepareWhere({
|
|
205
|
+
...commonWhereParams,
|
|
206
|
+
isHaving: false,
|
|
207
|
+
});
|
|
208
|
+
const havingOpts = !isEmpty(selectParams.having)? await _this.prepareWhere({
|
|
209
|
+
...omitKeys(commonWhereParams, ["forcedFilter"]),
|
|
210
|
+
filter: selectParams.having,
|
|
211
|
+
isHaving: true,
|
|
212
|
+
}) : undefined;
|
|
213
|
+
const where = filterOpts.where;
|
|
214
|
+
const validatedRules = _this.getValidatedRules(tableRules, localParams);
|
|
215
|
+
|
|
216
|
+
const resQuery: NewQuery = {
|
|
217
|
+
allFields: _this.column_names.slice(0),
|
|
218
|
+
select,
|
|
219
|
+
table: _this.name,
|
|
220
|
+
joins: joinQueries,
|
|
221
|
+
where,
|
|
222
|
+
whereOpts: filterOpts,
|
|
223
|
+
having: havingOpts?.condition ?? "",
|
|
224
|
+
isLeftJoin: false,
|
|
225
|
+
limit: prepareLimitQuery(selectParams.limit, validatedRules),
|
|
226
|
+
orderByItems: prepareSortItems(
|
|
227
|
+
selectParams.orderBy,
|
|
228
|
+
allowedOrderByFields,
|
|
229
|
+
selectParams.alias,
|
|
230
|
+
select,
|
|
231
|
+
joinQueries
|
|
232
|
+
),
|
|
233
|
+
offset: prepareOffsetQuery(selectParams.offset)
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
if(resQuery.select.some(s => s.type === "aggregation") && resQuery.joins?.length){
|
|
237
|
+
throw new Error(`Root query aggregation AND nested joins not allowed`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return resQuery;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const prepareOffsetQuery = (offset?: number) => {
|
|
244
|
+
if (Number.isInteger(offset)) {
|
|
245
|
+
return offset!;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return 0;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const prepareLimitQuery = (limit: number | null | undefined = null, p: ValidatedTableRules): number | null => {
|
|
252
|
+
|
|
253
|
+
if (limit !== undefined && limit !== null && !Number.isInteger(limit)) {
|
|
254
|
+
throw "Unexpected LIMIT. Must be null or an integer";
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let _limit = limit;
|
|
258
|
+
/* If no limit then set as the lesser of (100, maxLimit) */
|
|
259
|
+
if (_limit !== null && !Number.isInteger(_limit) && p.select.maxLimit !== null) {
|
|
260
|
+
_limit = [100, p.select.maxLimit].filter(Number.isInteger).sort((a, b) => a - b)[0]!;
|
|
261
|
+
} else {
|
|
262
|
+
|
|
263
|
+
/* If a limit higher than maxLimit specified throw error */
|
|
264
|
+
if (Number.isInteger(p.select.maxLimit) && _limit !== null && _limit > p.select.maxLimit!) {
|
|
265
|
+
throw `Unexpected LIMIT ${_limit}. Must be less than the published maxLimit: ` + p.select.maxLimit;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
return _limit;
|
|
271
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
|
|
2
|
+
import { prepareOrderByQuery } from "../DboBuilder";
|
|
3
|
+
import { isDefined, asName } from "prostgles-types";
|
|
4
|
+
import { NewQuery } from "./QueryBuilder";
|
|
5
|
+
import { ViewHandler } from "../ViewHandler/ViewHandler";
|
|
6
|
+
import { getJoinQuery } from "./getJoinQuery";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Used to prevent single row nested results in case of OR join conditions
|
|
10
|
+
*/
|
|
11
|
+
export const ROOT_TABLE_ROW_NUM_ID = "prostgles_root_table_row_id" as const;
|
|
12
|
+
export const ROOT_TABLE_ALIAS = 'prostgles_root_table_alias' as const;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Creating the text query from the NewQuery spec
|
|
16
|
+
* No validation/authorisation at this point
|
|
17
|
+
* */
|
|
18
|
+
export function getSelectQuery(
|
|
19
|
+
viewHandler: ViewHandler,
|
|
20
|
+
q: NewQuery,
|
|
21
|
+
depth = 0,
|
|
22
|
+
selectParamsGroupBy: boolean,
|
|
23
|
+
): string {
|
|
24
|
+
|
|
25
|
+
const rootSelect = q.select.filter(s => s.selected).map(s => [s.getQuery(ROOT_TABLE_ALIAS), " AS ", asName(s.alias)].join(""));
|
|
26
|
+
|
|
27
|
+
const parsedJoins = q.joins?.flatMap(q2 => {
|
|
28
|
+
const parsed = getJoinQuery(
|
|
29
|
+
viewHandler,
|
|
30
|
+
{
|
|
31
|
+
q1: { ...q, tableAlias: ROOT_TABLE_ALIAS },
|
|
32
|
+
q2: { ...q2 },
|
|
33
|
+
selectParamsGroupBy
|
|
34
|
+
}
|
|
35
|
+
);
|
|
36
|
+
return {
|
|
37
|
+
...q2,
|
|
38
|
+
...parsed
|
|
39
|
+
}
|
|
40
|
+
}) ?? [];
|
|
41
|
+
|
|
42
|
+
const selectItems = rootSelect.concat(
|
|
43
|
+
parsedJoins?.map(join => {
|
|
44
|
+
const { joinAlias } = join;
|
|
45
|
+
return `COALESCE(${asName(joinAlias)}.${join.resultAlias}, '[]') as ${asName(joinAlias)}`
|
|
46
|
+
}) ?? []);
|
|
47
|
+
|
|
48
|
+
/** OR joins cannot be easily aggregated to one-many with the root table. Must group by root table id */
|
|
49
|
+
const hasOrJoins = parsedJoins.some(j => j.isOrJoin)
|
|
50
|
+
|
|
51
|
+
let joinCtes = !parsedJoins.length? [] : [
|
|
52
|
+
...parsedJoins.flatMap((j, i) => {
|
|
53
|
+
const needsComma = parsedJoins.length > 1 && i < parsedJoins.length -1;
|
|
54
|
+
return j.cteLines.concat(needsComma? [","] : []);
|
|
55
|
+
})
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if(hasOrJoins){
|
|
60
|
+
const pkey = viewHandler.columns.find(c => c.is_pkey);
|
|
61
|
+
joinCtes = [
|
|
62
|
+
`${q.table} AS (`,
|
|
63
|
+
` SELECT *, ${pkey? asName(pkey.name): "ROW_NUMBER() OVER()"} as ${ROOT_TABLE_ROW_NUM_ID}`,
|
|
64
|
+
` FROM ${q.table}`,
|
|
65
|
+
`),`,
|
|
66
|
+
...joinCtes
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if(joinCtes.length){
|
|
71
|
+
joinCtes.unshift(`WITH `)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const query = [
|
|
75
|
+
...joinCtes,
|
|
76
|
+
`SELECT`
|
|
77
|
+
,...indentLines(selectItems, { appendCommas: true })
|
|
78
|
+
, `FROM ( `
|
|
79
|
+
, ` SELECT *`
|
|
80
|
+
, ` FROM ${q.table}`
|
|
81
|
+
, ...(q.where? [` ${q.where}`] : [])
|
|
82
|
+
, `) ${ROOT_TABLE_ALIAS}`
|
|
83
|
+
, ...parsedJoins.flatMap(j => j.joinLines)
|
|
84
|
+
, ...getRootGroupBy(q, selectParamsGroupBy)
|
|
85
|
+
, ...prepareOrderByQuery(q.orderByItems)
|
|
86
|
+
, ...(q.having ? [`HAVING ${q.having} `] : [])
|
|
87
|
+
, ...(depth || q.limit === null ? [] : [`LIMIT ${q.limit || 0}`])
|
|
88
|
+
, ...(q.offset? [`OFFSET ${q.offset || 0}`] : [])
|
|
89
|
+
];
|
|
90
|
+
|
|
91
|
+
return indentLinesToString(query);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const indentLine = (numberOfSpaces: number, str: string, indentStr = " "): string => new Array(numberOfSpaces).fill(indentStr).join("") + str;
|
|
95
|
+
type IndentLinesOpts = {
|
|
96
|
+
numberOfSpaces?: number;
|
|
97
|
+
indentStr?: string;
|
|
98
|
+
appendCommas?: boolean;
|
|
99
|
+
}
|
|
100
|
+
export const indentLines = (strArr: (string | undefined | null)[], { numberOfSpaces = 2, indentStr = " ", appendCommas = false }: IndentLinesOpts = {}): string[] => {
|
|
101
|
+
const nonEmptyLines = strArr
|
|
102
|
+
.filter(v => v);
|
|
103
|
+
|
|
104
|
+
return nonEmptyLines.map((str, idx) => {
|
|
105
|
+
const res = indentLine(numberOfSpaces, str as string, indentStr);
|
|
106
|
+
if(appendCommas && idx < nonEmptyLines.length - 1){
|
|
107
|
+
return `${res},`;
|
|
108
|
+
}
|
|
109
|
+
return res;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const indentLinesToString = (strArr: (string | undefined | null)[], numberOfSpaces = 0, separator = " \n ", indentStr = " ") => indentLines(strArr, { numberOfSpaces, indentStr }).join(separator);
|
|
113
|
+
const getTableAlias = (q: NewQuery) => !q.tableAlias ? q.table : `${q.tableAlias || ""}_${q.table}`;
|
|
114
|
+
export const getTableAliasAsName = (q: NewQuery) => asName(getTableAlias(q));
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
export const getRootGroupBy = (q: NewQuery, selectParamsGroupBy?: boolean) => {
|
|
118
|
+
|
|
119
|
+
const aggs = q.select.filter(s => s.selected && s.type === "aggregation");
|
|
120
|
+
const nonAggs = q.select.filter(s => s.selected && s.type !== "aggregation");
|
|
121
|
+
|
|
122
|
+
if ((selectParamsGroupBy || aggs.length) && nonAggs.length) {
|
|
123
|
+
|
|
124
|
+
/** Add ORDER BY items not included in root select */
|
|
125
|
+
const orderByItems: string[] = [];
|
|
126
|
+
// q.orderByItems.forEach(sortItem => {
|
|
127
|
+
// if (!sortItem.nested && "fieldQuery" in sortItem && !orderByItems.includes(sortItem.fieldQuery)) {
|
|
128
|
+
// orderByItems.push(sortItem.fieldQuery);
|
|
129
|
+
// }
|
|
130
|
+
// });
|
|
131
|
+
|
|
132
|
+
return [`GROUP BY ${q.select.map((s, i)=> s.selected && s.type !== "aggregation"? `${i+1}` : undefined).concat(orderByItems).filter(isDefined).join(", ")} `]
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return []
|
|
136
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isEmpty } from "prostgles-types";
|
|
2
|
+
import type { Filter } from "../DboBuilderTypes";
|
|
3
|
+
import type { SelectItemValidated } from "./QueryBuilder";
|
|
4
|
+
import { parseFilterItem } from "../../Filtering";
|
|
5
|
+
|
|
6
|
+
type Args = {
|
|
7
|
+
having: Filter | undefined;
|
|
8
|
+
select: SelectItemValidated[];
|
|
9
|
+
tableAlias: string | undefined;
|
|
10
|
+
filterFieldNames: string[];
|
|
11
|
+
}
|
|
12
|
+
export const prepareHaving = ({ having, select, tableAlias, filterFieldNames }: Args) => {
|
|
13
|
+
if(!having || isEmpty(having)) return "";
|
|
14
|
+
|
|
15
|
+
const havingStr = parseFilterItem({
|
|
16
|
+
filter: having,
|
|
17
|
+
select,
|
|
18
|
+
tableAlias,
|
|
19
|
+
allowedColumnNames: filterFieldNames,
|
|
20
|
+
});
|
|
21
|
+
return havingStr;
|
|
22
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import * as pg from "pg";
|
|
2
|
+
import CursorType from 'pg-cursor';
|
|
3
|
+
import { CHANNELS, SQLOptions, SocketSQLStreamPacket, SocketSQLStreamServer, omitKeys, pickKeys } from "prostgles-types";
|
|
4
|
+
import { BasicCallback } from "../PubSubManager/PubSubManager";
|
|
5
|
+
import { VoidFunction } from "../SchemaWatch/SchemaWatch";
|
|
6
|
+
import { DB } from "../initProstgles";
|
|
7
|
+
import { DboBuilder } from "./DboBuilder";
|
|
8
|
+
import { PRGLIOSocket } from "./DboBuilderTypes";
|
|
9
|
+
import { getErrorAsObject, getSerializedClientErrorFromPGError } from "./dboBuilderUtils";
|
|
10
|
+
import { getDetailedFieldInfo } from "./runSQL";
|
|
11
|
+
const Cursor: typeof CursorType = require('pg-cursor');
|
|
12
|
+
|
|
13
|
+
type ClientStreamedRequest = {
|
|
14
|
+
socket: PRGLIOSocket;
|
|
15
|
+
query: string;
|
|
16
|
+
options: SQLOptions | undefined;
|
|
17
|
+
persistConnection?: boolean;
|
|
18
|
+
}
|
|
19
|
+
type StreamedQuery = ClientStreamedRequest & {
|
|
20
|
+
cursor: CursorType | undefined;
|
|
21
|
+
client: pg.Client | undefined;
|
|
22
|
+
stop?: VoidFunction;
|
|
23
|
+
onError: ((error: any) => void);
|
|
24
|
+
}
|
|
25
|
+
type Info = {
|
|
26
|
+
command: string;
|
|
27
|
+
fields: any[];
|
|
28
|
+
rowCount: number;
|
|
29
|
+
duration: number;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const shortSocketIds: Record<string, number> = {};
|
|
33
|
+
const getSetShortSocketId = (socketId: string) => {
|
|
34
|
+
const shortId = socketId.slice(0, 3);
|
|
35
|
+
const currId = shortSocketIds[shortId] ?? 0;
|
|
36
|
+
const newId = currId + 1;
|
|
37
|
+
shortSocketIds[shortId] = newId;
|
|
38
|
+
return newId;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export class QueryStreamer {
|
|
42
|
+
db: DB;
|
|
43
|
+
dboBuilder: DboBuilder;
|
|
44
|
+
socketQueries: Record<string, Record<string, StreamedQuery>> = {};
|
|
45
|
+
adminClient: pg.Client;
|
|
46
|
+
constructor(dboBuilder: DboBuilder) {
|
|
47
|
+
this.dboBuilder = dboBuilder;
|
|
48
|
+
this.db = dboBuilder.db;
|
|
49
|
+
const setAdminClient = () => {
|
|
50
|
+
this.adminClient = this.getConnection(undefined, { keepAlive: true });
|
|
51
|
+
this.adminClient.connect();
|
|
52
|
+
}
|
|
53
|
+
this.adminClient = this.getConnection((error) => {
|
|
54
|
+
if(error.message?.includes("database") && error.message?.includes("does not exist")) return;
|
|
55
|
+
console.log("Admin client error. Reconnecting...", error);
|
|
56
|
+
setAdminClient();
|
|
57
|
+
}, { keepAlive: true });
|
|
58
|
+
this.adminClient.connect();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
getConnection = (onError: ((err: any) => void) | undefined, extraOptions?: pg.ClientConfig) => {
|
|
62
|
+
const connectionInfo = typeof this.db.$cn === "string"? { connectionString: this.db.$cn } : this.db.$cn as any;
|
|
63
|
+
const client = new pg.Client({ ...connectionInfo, ...extraOptions });
|
|
64
|
+
client.on("error", (err) => {
|
|
65
|
+
onError?.(err);
|
|
66
|
+
});
|
|
67
|
+
return client;
|
|
68
|
+
}
|
|
69
|
+
onDisconnect = (socketId: string) => {
|
|
70
|
+
const socketQueries = this.socketQueries[socketId];
|
|
71
|
+
if(!socketQueries) return;
|
|
72
|
+
Object.values(socketQueries).forEach(({ client, stop }) => {
|
|
73
|
+
stop?.();
|
|
74
|
+
/** end does not stop active query?! */
|
|
75
|
+
client?.end();
|
|
76
|
+
});
|
|
77
|
+
delete this.socketQueries[socketId];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
create = async (query: ClientStreamedRequest): Promise<SocketSQLStreamServer> => {
|
|
81
|
+
const { socket, persistConnection } = query;
|
|
82
|
+
const socketId = socket.id;
|
|
83
|
+
const id = getSetShortSocketId(socketId);
|
|
84
|
+
const channel = `${CHANNELS.SQL_STREAM}__${socketId}_${id}`;
|
|
85
|
+
const unsubChannel = `${channel}.unsubscribe`;
|
|
86
|
+
if(this.socketQueries[id] && !persistConnection){
|
|
87
|
+
throw `Must stop existing query ${id} first`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
this.socketQueries[socketId] ??= {};
|
|
91
|
+
let errored = false;
|
|
92
|
+
const socketQuery = {
|
|
93
|
+
...query,
|
|
94
|
+
id,
|
|
95
|
+
client: undefined,
|
|
96
|
+
cursor: undefined,
|
|
97
|
+
onError: (rawError: any) => {
|
|
98
|
+
if(errored) return;
|
|
99
|
+
errored = true;
|
|
100
|
+
|
|
101
|
+
const errorWithoutQuery = getSerializedClientErrorFromPGError(rawError, { type: "sql" });
|
|
102
|
+
// For some reason query is not present on the error object from sql stream mode
|
|
103
|
+
const error = { ...errorWithoutQuery, query: query.query };
|
|
104
|
+
socket.emit(channel, { type: "error", error } satisfies SocketSQLStreamPacket);
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
this.socketQueries[socketId]![id] ??= socketQuery;
|
|
108
|
+
let processID = -1;
|
|
109
|
+
let streamState: "started" | "ended" | "errored" | undefined;
|
|
110
|
+
|
|
111
|
+
const startStream = async (client: pg.Client | undefined, query: ClientStreamedRequest) => {
|
|
112
|
+
const socketQuery = this.socketQueries[socketId]?.[id];
|
|
113
|
+
if(!socketQuery){
|
|
114
|
+
throw "socket query not found";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Only send fields on first request */
|
|
118
|
+
let fieldsWereSent = false;
|
|
119
|
+
const emit = ({ reachedEnd, rows, info }: { reachedEnd: true; rows: any[]; info: Info } | { reachedEnd: false; rows: any[]; info: Omit<Info, "command"> }) => {
|
|
120
|
+
if(!info?.fields) throw "No fields";
|
|
121
|
+
const fields = getDetailedFieldInfo.bind(this.dboBuilder)(info.fields as any);
|
|
122
|
+
const packet: SocketSQLStreamPacket = { type: "data", rows, fields: fieldsWereSent? undefined : fields, info: reachedEnd? info : undefined, ended: reachedEnd, processId: processID };
|
|
123
|
+
socket.emit(channel, packet);
|
|
124
|
+
if(reachedEnd){
|
|
125
|
+
this.dboBuilder.prostgles.schemaWatch?.onSchemaChangeFallback?.({ command: info.command, query: query.query });
|
|
126
|
+
}
|
|
127
|
+
fieldsWereSent = true;
|
|
128
|
+
}
|
|
129
|
+
const currentClient = client ?? this.getConnection(err => {
|
|
130
|
+
socketQuery.onError(err);
|
|
131
|
+
currentClient.end();
|
|
132
|
+
});
|
|
133
|
+
this.socketQueries[socketId]![id]!.client = currentClient;
|
|
134
|
+
try {
|
|
135
|
+
if(!client){
|
|
136
|
+
await currentClient.connect();
|
|
137
|
+
}
|
|
138
|
+
processID = (currentClient as any).processID;
|
|
139
|
+
|
|
140
|
+
if(query.options?.streamLimit && (!Number.isInteger(query.options.streamLimit) || query.options.streamLimit < 0)){
|
|
141
|
+
throw "streamLimit must be a positive integer";
|
|
142
|
+
}
|
|
143
|
+
const batchSize = query.options?.streamLimit? Math.min(1e3, query.options?.streamLimit) : 1e3;
|
|
144
|
+
const cursor = currentClient.query(new Cursor(query.query, undefined, { rowMode: "array" }));
|
|
145
|
+
this.socketQueries[socketId]![id]!.cursor = cursor;
|
|
146
|
+
let streamLimitReached = false;
|
|
147
|
+
let reachedEnd = false;
|
|
148
|
+
(async () => {
|
|
149
|
+
try {
|
|
150
|
+
let rowChunk: any[] = [];
|
|
151
|
+
let rowsSent = 0;
|
|
152
|
+
do {
|
|
153
|
+
rowChunk = await cursor.read(batchSize);
|
|
154
|
+
const info = pickKeys((cursor as any)._result, ["fields", "rowCount", "command", "duration"]) as Info;
|
|
155
|
+
rowsSent += rowChunk.length;
|
|
156
|
+
streamLimitReached = Boolean(query.options?.streamLimit && rowsSent >= query.options.streamLimit);
|
|
157
|
+
reachedEnd = rowChunk.length < batchSize;
|
|
158
|
+
emit({ info, rows: rowChunk, reachedEnd: reachedEnd || streamLimitReached });
|
|
159
|
+
} while (!reachedEnd && !streamLimitReached);
|
|
160
|
+
|
|
161
|
+
streamState = "ended";
|
|
162
|
+
|
|
163
|
+
if(!query.options?.persistStreamConnection){
|
|
164
|
+
delete this.socketQueries[socketId]?.[id];
|
|
165
|
+
currentClient.end();
|
|
166
|
+
}
|
|
167
|
+
cursor.close();
|
|
168
|
+
} catch(error: any){
|
|
169
|
+
streamState = "errored";
|
|
170
|
+
if(error.message === "cannot insert multiple commands into a prepared statement") {
|
|
171
|
+
this.dboBuilder.dbo.sql!(query.query, {}, { returnType: "arrayMode", hasParams: false }).then(res => {
|
|
172
|
+
emit({ info: omitKeys(res, ["rows"]), reachedEnd: true, rows: res.rows});
|
|
173
|
+
}).catch(newError => {
|
|
174
|
+
socketQuery.onError(newError);
|
|
175
|
+
});
|
|
176
|
+
} else {
|
|
177
|
+
socketQuery.onError(error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
})()
|
|
181
|
+
} catch(err){
|
|
182
|
+
socketQuery.onError(err);
|
|
183
|
+
await currentClient.end();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const cleanup = () => {
|
|
188
|
+
socket.removeAllListeners(unsubChannel);
|
|
189
|
+
socket.removeAllListeners(channel);
|
|
190
|
+
delete this.socketQueries[socketId]?.[id];
|
|
191
|
+
}
|
|
192
|
+
const stop = async (opts: { terminate?: boolean; } | undefined, cb: BasicCallback) => {
|
|
193
|
+
const { client: queryClient } = this.socketQueries[socketId]?.[id] ?? {};
|
|
194
|
+
if(!queryClient) return;
|
|
195
|
+
if(opts?.terminate){
|
|
196
|
+
setTimeout(() => {
|
|
197
|
+
queryClient.end();
|
|
198
|
+
}, 4e3);
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const stopFunction = opts?.terminate? "pg_terminate_backend" : "pg_cancel_backend";
|
|
202
|
+
const rows = await this.adminClient.query(`SELECT ${stopFunction}(pid), pid, state, query FROM pg_stat_activity WHERE pid = $1`, [processID]);
|
|
203
|
+
cleanup();
|
|
204
|
+
cb({ processID, info: rows.rows[0] });
|
|
205
|
+
} catch (error){
|
|
206
|
+
cb(null, error);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
this.socketQueries[socketId]![id]!.stop = () => stop({ terminate: true }, () => { /* Empty */ });
|
|
210
|
+
|
|
211
|
+
socket.removeAllListeners(unsubChannel);
|
|
212
|
+
socket.once(unsubChannel, stop);
|
|
213
|
+
|
|
214
|
+
let runCount = 0;
|
|
215
|
+
socket.removeAllListeners(channel);
|
|
216
|
+
socket.on(channel, async (_data: { query: string; params: any } | undefined, cb: BasicCallback) => {
|
|
217
|
+
if(streamState === "started"){
|
|
218
|
+
return cb(processID, "Already started");
|
|
219
|
+
}
|
|
220
|
+
streamState = "started";
|
|
221
|
+
try {
|
|
222
|
+
/* Persisted connection query */
|
|
223
|
+
if(runCount){
|
|
224
|
+
const persistedClient = this.socketQueries[socketId]?.[id];
|
|
225
|
+
if(!persistedClient) throw "Persisted query client not found";
|
|
226
|
+
|
|
227
|
+
await startStream(persistedClient.client, { ...query, query: _data!.query! });
|
|
228
|
+
} else {
|
|
229
|
+
await startStream(undefined, query);
|
|
230
|
+
}
|
|
231
|
+
cb(processID);
|
|
232
|
+
} catch(err){
|
|
233
|
+
console.error(err)
|
|
234
|
+
cb(processID, getErrorAsObject(err) ?? "Something went wrong");
|
|
235
|
+
}
|
|
236
|
+
runCount++;
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
/** If not started within 5 seconds then assume it will never happen */
|
|
240
|
+
setTimeout(() => {
|
|
241
|
+
if(streamState) return;
|
|
242
|
+
cleanup();
|
|
243
|
+
}, 5e3);
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
channel,
|
|
247
|
+
unsubChannel,
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|