prostgles-server 4.2.158 → 4.2.160

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 (145) hide show
  1. package/dist/Auth/AuthTypes.d.ts +4 -8
  2. package/dist/Auth/AuthTypes.d.ts.map +1 -1
  3. package/dist/Auth/setAuthProviders.d.ts.map +1 -1
  4. package/dist/Auth/setAuthProviders.js +4 -5
  5. package/dist/Auth/setAuthProviders.js.map +1 -1
  6. package/dist/Auth/setEmailProvider.js +3 -3
  7. package/dist/Auth/setEmailProvider.js.map +1 -1
  8. package/package.json +1 -1
  9. package/lib/Auth/AuthHandler.ts +0 -436
  10. package/lib/Auth/AuthTypes.ts +0 -285
  11. package/lib/Auth/getSafeReturnURL.ts +0 -35
  12. package/lib/Auth/sendEmail.ts +0 -83
  13. package/lib/Auth/setAuthProviders.ts +0 -129
  14. package/lib/Auth/setEmailProvider.ts +0 -85
  15. package/lib/Auth/setupAuthRoutes.ts +0 -161
  16. package/lib/DBEventsManager.ts +0 -178
  17. package/lib/DBSchemaBuilder.ts +0 -225
  18. package/lib/DboBuilder/DboBuilder.ts +0 -319
  19. package/lib/DboBuilder/DboBuilderTypes.ts +0 -361
  20. package/lib/DboBuilder/QueryBuilder/Functions.ts +0 -1153
  21. package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +0 -288
  22. package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +0 -263
  23. package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +0 -271
  24. package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +0 -136
  25. package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +0 -22
  26. package/lib/DboBuilder/QueryStreamer.ts +0 -250
  27. package/lib/DboBuilder/TableHandler/DataValidator.ts +0 -428
  28. package/lib/DboBuilder/TableHandler/TableHandler.ts +0 -205
  29. package/lib/DboBuilder/TableHandler/delete.ts +0 -115
  30. package/lib/DboBuilder/TableHandler/insert.ts +0 -183
  31. package/lib/DboBuilder/TableHandler/insertTest.ts +0 -78
  32. package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +0 -62
  33. package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +0 -134
  34. package/lib/DboBuilder/TableHandler/update.ts +0 -126
  35. package/lib/DboBuilder/TableHandler/updateBatch.ts +0 -49
  36. package/lib/DboBuilder/TableHandler/updateFile.ts +0 -48
  37. package/lib/DboBuilder/TableHandler/upsert.ts +0 -34
  38. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +0 -393
  39. package/lib/DboBuilder/ViewHandler/count.ts +0 -38
  40. package/lib/DboBuilder/ViewHandler/find.ts +0 -153
  41. package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +0 -73
  42. package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +0 -74
  43. package/lib/DboBuilder/ViewHandler/getInfo.ts +0 -32
  44. package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +0 -84
  45. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +0 -96
  46. package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +0 -105
  47. package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +0 -208
  48. package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +0 -163
  49. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +0 -90
  50. package/lib/DboBuilder/ViewHandler/size.ts +0 -37
  51. package/lib/DboBuilder/ViewHandler/subscribe.ts +0 -118
  52. package/lib/DboBuilder/ViewHandler/validateViewRules.ts +0 -70
  53. package/lib/DboBuilder/dboBuilderUtils.ts +0 -222
  54. package/lib/DboBuilder/getColumns.ts +0 -114
  55. package/lib/DboBuilder/getCondition.ts +0 -201
  56. package/lib/DboBuilder/getSubscribeRelatedTables.ts +0 -190
  57. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +0 -426
  58. package/lib/DboBuilder/insertNestedRecords.ts +0 -355
  59. package/lib/DboBuilder/parseUpdateRules.ts +0 -187
  60. package/lib/DboBuilder/prepareShortestJoinPaths.ts +0 -186
  61. package/lib/DboBuilder/runSQL.ts +0 -182
  62. package/lib/DboBuilder/runTransaction.ts +0 -50
  63. package/lib/DboBuilder/sqlErrCodeToMsg.ts +0 -254
  64. package/lib/DboBuilder/uploadFile.ts +0 -69
  65. package/lib/Event_Trigger_Tags.ts +0 -118
  66. package/lib/FileManager/FileManager.ts +0 -358
  67. package/lib/FileManager/getValidatedFileType.ts +0 -69
  68. package/lib/FileManager/initFileManager.ts +0 -187
  69. package/lib/FileManager/upload.ts +0 -62
  70. package/lib/FileManager/uploadStream.ts +0 -79
  71. package/lib/Filtering.ts +0 -463
  72. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +0 -502
  73. package/lib/JSONBValidation/validation.ts +0 -143
  74. package/lib/Logging.ts +0 -127
  75. package/lib/PostgresNotifListenManager.ts +0 -143
  76. package/lib/Prostgles.ts +0 -485
  77. package/lib/ProstglesTypes.ts +0 -196
  78. package/lib/PubSubManager/PubSubManager.ts +0 -609
  79. package/lib/PubSubManager/addSub.ts +0 -138
  80. package/lib/PubSubManager/addSync.ts +0 -141
  81. package/lib/PubSubManager/getCreatePubSubManagerError.ts +0 -72
  82. package/lib/PubSubManager/getPubSubManagerInitQuery.ts +0 -662
  83. package/lib/PubSubManager/initPubSubManager.ts +0 -79
  84. package/lib/PubSubManager/notifListener.ts +0 -173
  85. package/lib/PubSubManager/orphanTriggerCheck.ts +0 -70
  86. package/lib/PubSubManager/pushSubData.ts +0 -55
  87. package/lib/PublishParser/PublishParser.ts +0 -162
  88. package/lib/PublishParser/getFileTableRules.ts +0 -124
  89. package/lib/PublishParser/getSchemaFromPublish.ts +0 -141
  90. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +0 -177
  91. package/lib/PublishParser/publishTypesAndUtils.ts +0 -399
  92. package/lib/RestApi.ts +0 -127
  93. package/lib/SchemaWatch/SchemaWatch.ts +0 -90
  94. package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +0 -3
  95. package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +0 -45
  96. package/lib/SchemaWatch/getWatchSchemaTagList.ts +0 -27
  97. package/lib/SyncReplication.ts +0 -557
  98. package/lib/TableConfig/TableConfig.ts +0 -468
  99. package/lib/TableConfig/getColumnDefinitionQuery.ts +0 -111
  100. package/lib/TableConfig/getConstraintDefinitionQueries.ts +0 -95
  101. package/lib/TableConfig/getFutureTableSchema.ts +0 -64
  102. package/lib/TableConfig/getPGIndexes.ts +0 -53
  103. package/lib/TableConfig/getTableColumnQueries.ts +0 -129
  104. package/lib/TableConfig/initTableConfig.ts +0 -326
  105. package/lib/index.ts +0 -13
  106. package/lib/initProstgles.ts +0 -319
  107. package/lib/onSocketConnected.ts +0 -102
  108. package/lib/runClientRequest.ts +0 -129
  109. package/lib/shortestPath.ts +0 -122
  110. package/lib/typeTests/DBoGenerated.d.ts +0 -320
  111. package/lib/typeTests/dboTypeCheck.ts +0 -81
  112. package/lib/utils.ts +0 -15
  113. package/tests/client/hooks.spec.ts +0 -205
  114. package/tests/client/index.ts +0 -139
  115. package/tests/client/package-lock.json +0 -637
  116. package/tests/client/package.json +0 -26
  117. package/tests/client/renderReactHook.ts +0 -177
  118. package/tests/client/tsconfig.json +0 -15
  119. package/tests/client/useProstgles.spec.ts +0 -120
  120. package/tests/clientFileTests.spec.ts +0 -102
  121. package/tests/clientOnlyQueries.spec.ts +0 -667
  122. package/tests/clientRestApi.spec.ts +0 -82
  123. package/tests/config_test/DBoGenerated.d.ts +0 -407
  124. package/tests/config_test/index.html +0 -109
  125. package/tests/config_test/index.js +0 -86
  126. package/tests/config_test/index.js.map +0 -1
  127. package/tests/config_test/index.ts +0 -91
  128. package/tests/config_test/init.sql +0 -48
  129. package/tests/config_test/package.json +0 -29
  130. package/tests/config_test/tsconfig.json +0 -23
  131. package/tests/config_testDBoGenerated.d.ts +0 -407
  132. package/tests/isomorphicQueries.spec.ts +0 -1493
  133. package/tests/server/DBoGenerated.d.ts +0 -537
  134. package/tests/server/index.html +0 -73
  135. package/tests/server/index.ts +0 -289
  136. package/tests/server/init.sql +0 -224
  137. package/tests/server/package-lock.json +0 -2164
  138. package/tests/server/package.json +0 -25
  139. package/tests/server/publishTypeCheck.ts +0 -136
  140. package/tests/server/server.ts +0 -35
  141. package/tests/server/testPublish.ts +0 -147
  142. package/tests/server/testTableConfig.ts +0 -156
  143. package/tests/server/tsconfig.json +0 -22
  144. package/tests/serverOnlyQueries.spec.ts +0 -32
  145. package/tests/test.sh +0 -20
@@ -1,161 +0,0 @@
1
- import { RequestHandler } from "express";
2
- import { DBOFullyTyped } from "../DBSchemaBuilder";
3
- import { AUTH_ROUTES_AND_PARAMS, AuthHandler, getLoginClientInfo, HTTPCODES } from "./AuthHandler";
4
- import { AuthClientRequest, ExpressReq, ExpressRes, LoginParams } from "./AuthTypes";
5
- import { setAuthProviders, upsertNamedExpressMiddleware } from "./setAuthProviders";
6
-
7
- export async function setupAuthRoutes(this: AuthHandler) {
8
- if (!this.opts) return;
9
-
10
- const { login, getUser, expressConfig } = this.opts;
11
-
12
- if (!login) {
13
- throw "Invalid auth: Provide { sidKeyName: string } ";
14
- }
15
-
16
- if (this.sidKeyName === "sid") {
17
- throw "sidKeyName cannot be 'sid' due to collision with socket.io";
18
- }
19
-
20
- if (!getUser) throw "getUser missing from auth config";
21
-
22
- if (!expressConfig) {
23
- return
24
- }
25
- const { app, publicRoutes = [], onGetRequestOK, magicLinks, use } = expressConfig;
26
- if (publicRoutes.find(r => typeof r !== "string" || !r)) {
27
- throw "Invalid or empty string provided within publicRoutes "
28
- }
29
-
30
- await setAuthProviders.bind(this)(expressConfig);
31
-
32
- if(use){
33
- const prostglesUseMiddleware: RequestHandler = (req, res, next) => {
34
- use({
35
- req,
36
- res,
37
- next,
38
- getUser: () => this.getUser({ httpReq: req }) as any,
39
- dbo: this.dbo as DBOFullyTyped,
40
- db: this.db,
41
- })
42
- };
43
- upsertNamedExpressMiddleware(app, prostglesUseMiddleware, "prostglesUseMiddleware");
44
- }
45
-
46
- if (magicLinks) {
47
- const { check } = magicLinks;
48
- if (!check) {
49
- throw "Check must be defined for magicLinks";
50
- }
51
-
52
- app.get(AUTH_ROUTES_AND_PARAMS.magicLinksExpressRoute, async (req: ExpressReq, res: ExpressRes) => {
53
- const { id } = req.params ?? {};
54
-
55
- if (typeof id !== "string" || !id) {
56
- res.status(HTTPCODES.BAD_REQUEST).json({ msg: "Invalid magic-link id. Expecting a string" });
57
- } else {
58
- try {
59
- const session = await this.throttledFunc(async () => {
60
- return check(id, this.dbo as any, this.db, getLoginClientInfo({ httpReq: req }));
61
- });
62
- if (!session) {
63
- res.status(HTTPCODES.AUTH_ERROR).json({ msg: "Invalid magic-link" });
64
- } else {
65
- this.setCookieAndGoToReturnURLIFSet(session, { req, res });
66
- }
67
-
68
- } catch (e) {
69
- res.status(HTTPCODES.AUTH_ERROR).json({ msg: e });
70
- }
71
- }
72
- });
73
- }
74
-
75
- app.post(AUTH_ROUTES_AND_PARAMS.login, async (req: ExpressReq, res: ExpressRes) => {
76
- try {
77
- const loginParams: LoginParams = {
78
- type: "username",
79
- ...req.body,
80
- };
81
-
82
- await this.loginThrottledAndSetCookie(req, res, loginParams);
83
- } catch (err) {
84
- console.log(err)
85
- res.status(HTTPCODES.AUTH_ERROR).json({ err });
86
- }
87
-
88
- });
89
-
90
- const onLogout = async (req: ExpressReq, res: ExpressRes) => {
91
- const sid = this.validateSid(req?.cookies?.[this.sidKeyName]);
92
- if (sid) {
93
- try {
94
- await this.throttledFunc(() => {
95
- return this.opts?.logout?.(req?.cookies?.[this.sidKeyName], this.dbo as any, this.db);
96
- })
97
- } catch (err) {
98
- console.error(err);
99
- }
100
- }
101
- res.redirect("/")
102
- }
103
-
104
- /* Redirect if not logged in and requesting non public content */
105
- app.get(AUTH_ROUTES_AND_PARAMS.catchAll, async (req: ExpressReq, res: ExpressRes, next) => {
106
-
107
- const clientReq: AuthClientRequest = { httpReq: req };
108
- const getUser = this.getUser;
109
- if(this.prostgles.restApi){
110
- if(Object.values(this.prostgles.restApi.routes).some(restRoute => this.matchesRoute(restRoute.split("/:")[0], req.path))){
111
- next();
112
- return;
113
- }
114
- }
115
- try {
116
- const returnURL = this.getReturnUrl(req);
117
-
118
- if(this.matchesRoute(AUTH_ROUTES_AND_PARAMS.logoutGetPath, req.path)){
119
- await onLogout(req, res);
120
- return;
121
- }
122
-
123
- if(this.matchesRoute(AUTH_ROUTES_AND_PARAMS.loginWithProvider, req.path)){
124
- next();
125
- return;
126
- }
127
- /**
128
- * Requesting a User route
129
- */
130
- if (this.isUserRoute(req.path)) {
131
-
132
- /* Check auth. Redirect to login if unauthorized */
133
- const u = await getUser(clientReq);
134
- if (!u) {
135
- res.redirect(`${AUTH_ROUTES_AND_PARAMS.login}?returnURL=${encodeURIComponent(req.originalUrl)}`);
136
- return;
137
- }
138
-
139
- /* If authorized and going to returnUrl then redirect. Otherwise serve file */
140
- } else if (returnURL && (await getUser(clientReq))) {
141
-
142
- res.redirect(returnURL);
143
- return;
144
-
145
- /** If Logged in and requesting login then redirect to main page */
146
- } else if (this.matchesRoute(AUTH_ROUTES_AND_PARAMS.login, req.path) && (await getUser(clientReq))) {
147
-
148
- res.redirect("/");
149
- return;
150
- }
151
-
152
- onGetRequestOK?.(req, res, { getUser: () => getUser(clientReq), dbo: this.dbo as DBOFullyTyped, db: this.db })
153
-
154
- } catch (error) {
155
- console.error(error);
156
- const errorMessage = typeof error === "string" ? error : error instanceof Error ? error.message : "";
157
- res.status(HTTPCODES.AUTH_ERROR).json({ msg: "Something went wrong when processing your request" + (errorMessage? (": " + errorMessage) : "") });
158
- }
159
-
160
- });
161
- }
@@ -1,178 +0,0 @@
1
- import { PostgresNotifListenManager, PrglNotifListener } from "./PostgresNotifListenManager";
2
- import { DB, PGP } from "./Prostgles";
3
- import { getKeys, CHANNELS } from "prostgles-types";
4
- import { PRGLIOSocket } from "./DboBuilder/DboBuilder";
5
-
6
- export class DBEventsManager {
7
-
8
- notifies: {
9
- [key: string]: {
10
- socketChannel: string;
11
- sockets: any[];
12
- localFuncs: ((payload: string) => void)[];
13
- notifMgr: PostgresNotifListenManager;
14
- }
15
- } = {};
16
-
17
- notice: {
18
- socketChannel: string;
19
- socketUnsubChannel: string;
20
- sockets: any[];
21
- } = {
22
- socketChannel: CHANNELS.NOTICE_EV,
23
- socketUnsubChannel: CHANNELS.NOTICE_EV + "unsubscribe",
24
- sockets: []
25
- };
26
-
27
- notifManager?: PostgresNotifListenManager;
28
-
29
- db_pg: DB;
30
- pgp: PGP
31
- constructor(db_pg: DB, pgp: PGP){
32
- this.db_pg = db_pg;
33
- this.pgp = pgp;
34
- }
35
-
36
- private onNotif: PrglNotifListener = ({ channel, payload }) => {
37
-
38
- // console.log(36, { channel, payload }, Object.keys(this.notifies));
39
-
40
- getKeys(this.notifies)
41
- .filter(ch => ch === channel)
42
- .map(ch => {
43
- const sub = this.notifies[ch]!;
44
-
45
- sub.sockets.map(s => {
46
- s.emit(sub.socketChannel, payload)
47
- });
48
- sub.localFuncs.map(lf => {
49
- lf(payload);
50
- })
51
- });
52
- }
53
-
54
- onNotice = (notice: any) => {
55
- if(this.notice && this.notice.sockets.length){
56
- this.notice.sockets.map(s => {
57
- s.emit(this.notice.socketChannel, notice);
58
- })
59
- }
60
- }
61
-
62
- getNotifChannelName = async (channel: string) => {
63
- const c = await this.db_pg.one("SELECT quote_ident($1) as c", channel);
64
- return c.c;
65
- }
66
-
67
- async addNotify(query: string, socket?: PRGLIOSocket, func?: any): Promise<{
68
- socketChannel: string;
69
- socketUnsubChannel: string;
70
- notifChannel: string;
71
- unsubscribe?: () => void;
72
- }> {
73
- if(typeof query !== "string" || (!socket && !func)){
74
- throw "Expecting (query: string, socket?, localFunc?) But received: " + JSON.stringify({ query, socket, func });
75
- }
76
-
77
- /* Remove comments */
78
- let q = query.trim()
79
- .replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,'\n')
80
- .split("\n").map(v => v.trim()).filter(v => v && !v.startsWith("--"))
81
- .join("\n");
82
-
83
- /* Find the notify channel name */
84
- if(!q.toLowerCase().startsWith("listen")){
85
- throw "Expecting a LISTEN query but got: " + query;
86
- }
87
- q = q.slice(7).trim(); // Remove listen
88
- if(q.endsWith(";")) q = q.slice(0, -1);
89
-
90
- if(q.startsWith('"') && q.endsWith('"')) {
91
- q = q.slice(1, -1);
92
- } else {
93
- /* Replicate PG by lowercasing identifier if not quoted */
94
- q = q.toLowerCase();
95
- }
96
- q = q.replace(/""/g, `"`);
97
-
98
- const channel = q;
99
- let notifChannel = await this.getNotifChannelName(channel)
100
-
101
- notifChannel = notifChannel.replace(/""/g, `"`);
102
- if(notifChannel.startsWith('"')) notifChannel = notifChannel.slice(1, -1);
103
-
104
- const socketChannel = CHANNELS.LISTEN_EV + notifChannel,
105
- socketUnsubChannel = socketChannel + "unsubscribe";
106
-
107
- if(!this.notifies[notifChannel]){
108
- this.notifies[notifChannel] = {
109
- socketChannel,
110
- sockets: socket? [socket] : [],
111
- localFuncs: func? [func] : [],
112
- notifMgr: await PostgresNotifListenManager.create(this.db_pg, this.onNotif, channel)
113
- }
114
-
115
- } else {
116
- if(socket && !this.notifies[notifChannel]!.sockets.find(s => s.id === socket.id)) {
117
- this.notifies[notifChannel]!.sockets.push(socket);
118
-
119
- } else if(func) {
120
- this.notifies[notifChannel]!.localFuncs.push(func);
121
- }
122
- }
123
-
124
- if(socket){
125
- socket.removeAllListeners(socketUnsubChannel);
126
- socket.on(socketUnsubChannel, ()=>{
127
- this.removeNotify(notifChannel, socket);
128
- });
129
- }
130
-
131
- return {
132
- socketChannel,
133
- socketUnsubChannel,
134
- notifChannel,
135
- }
136
- }
137
-
138
- removeNotify(channel?: string, socket?: PRGLIOSocket, func?: any){
139
- const notifChannel = channel && this.notifies[channel]
140
- if(notifChannel){
141
- if(socket){
142
- notifChannel.sockets = notifChannel.sockets.filter(s => s.id !== socket.id);
143
- } else if(func){
144
- notifChannel.localFuncs = notifChannel.localFuncs.filter(f => f !== func);
145
- }
146
-
147
- /* UNLISTEN if no listeners ?? */
148
- }
149
-
150
- if(socket){
151
- getKeys(this.notifies).forEach(channel => {
152
- this.notifies[channel]!.sockets = this.notifies[channel]!.sockets.filter(s => s.id !== socket.id);
153
- })
154
- }
155
- }
156
-
157
- addNotice(socket: PRGLIOSocket){
158
- if(!socket || !socket.id) throw "Expecting a socket obj with id";
159
-
160
- if(!this.notice.sockets.find(s => s.id === socket.id)){
161
- this.notice.sockets.push(socket);
162
- }
163
-
164
- const { socketChannel, socketUnsubChannel } = this.notice;
165
-
166
- socket.removeAllListeners(socketUnsubChannel);
167
- socket.on(socketUnsubChannel, () => {
168
- this.removeNotice(socket);
169
- });
170
-
171
- return { socketChannel, socketUnsubChannel, }
172
- }
173
-
174
- removeNotice(socket: PRGLIOSocket){
175
- if(!socket || !socket.id) throw "Expecting a socket obj with id";
176
- this.notice.sockets = this.notice.sockets.filter(s => s.id !== socket.id)
177
- }
178
- }
@@ -1,225 +0,0 @@
1
- import { AnyObject, DbJoinMaker, DBSchema, isObject, JSONB, SQLHandler, TableHandler, ViewHandler } from "prostgles-types";
2
- import prostgles from ".";
3
- import { Auth } from "./Auth/AuthTypes";
4
- import { DboBuilder, escapeTSNames, postgresToTsType } from "./DboBuilder/DboBuilder";
5
- import { PublishAllOrNothing, PublishParams, PublishTableRule, PublishViewRule, } from "./PublishParser/PublishParser";
6
- import { getJSONBSchemaTSTypes } from "./JSONBValidation/validation";
7
- import { DBHandlerServer, TableSchemaColumn, TX } from "./DboBuilder/DboBuilderTypes";
8
-
9
-
10
- export const getDBSchema = (dboBuilder: DboBuilder): string => {
11
- const tables: string[] = [];
12
-
13
- const getColTypeForDBSchema = (udt_name: TableSchemaColumn["udt_name"]): string => {
14
- if(udt_name === "interval"){
15
- const units = [ "years", "months", "days", "hours", "minutes", "seconds", "milliseconds"];
16
-
17
- return `{ ${units.map(u => `${u}?: number;`).join(" ")} }`;
18
- }
19
-
20
- return postgresToTsType(udt_name);
21
- }
22
-
23
- /** Tables and columns are sorted to avoid infinite loops due to changing order */
24
- dboBuilder.tablesOrViews?.slice(0).sort((a, b) => a.name.localeCompare(b.name)).forEach(tov => {
25
- const cols = tov.columns.slice(0).sort((a, b) => a.name.localeCompare(b.name));
26
- const getColType = (c: typeof cols[number]) => {
27
-
28
- let type: string = (c.is_nullable? "null | " : "") + getColTypeForDBSchema(c.udt_name) + ";"
29
- const colConf = dboBuilder.prostgles.tableConfigurator?.getColumnConfig(tov.name, c.name);
30
- if(colConf){
31
- if(isObject(colConf) && (colConf.jsonbSchema || colConf.jsonbSchemaType)){
32
- const schema: JSONB.JSONBSchema = colConf.jsonbSchema || { ...colConf, type: colConf.jsonbSchemaType };
33
-
34
- type = getJSONBSchemaTSTypes(schema, { nullable: colConf.nullable }, " ", dboBuilder.tablesOrViews ?? []);
35
- } else if(isObject(colConf) && "enum" in colConf){
36
- if(!colConf.enum) throw "colConf.enum missing"
37
- const types = colConf.enum.map(t => typeof t === "number"? t : JSON.stringify(t));
38
- if(colConf.nullable){
39
- types.unshift("null")
40
- }
41
- type = types.join(" | ");
42
- }
43
- }
44
- /**
45
- * Columns that are nullable or have default values can be ommitted from an insert
46
- * Non nullable columns with default values cannot containt null values in an insert so they must contain a valid value or be omitted
47
- */
48
- return `${escapeTSNames(c.name)}${c.is_nullable || c.has_default? "?" : ""}: ${type}`
49
- }
50
- tables.push(`${escapeTSNames(tov.name)}: {
51
- is_view: ${tov.is_view};
52
- select: ${tov.privileges.select};
53
- insert: ${tov.privileges.insert};
54
- update: ${tov.privileges.update};
55
- delete: ${tov.privileges.delete};
56
- columns: {${cols.map(c => `
57
- ${getColType(c)}`).join("")}
58
- };
59
- };\n `)
60
- })
61
- return `
62
- export type DBSchemaGenerated = {
63
- ${tables.join("")}
64
- }
65
- `;
66
- }
67
-
68
- type ServerViewHandler<T extends AnyObject = AnyObject, Schema extends DBSchema | void = void> = ViewHandler<T, Schema> & { is_view: boolean; }
69
- type ServerTableHandler<T extends AnyObject = AnyObject, Schema extends DBSchema | void = void> = TableHandler<T, Schema> & { is_view: boolean; }
70
-
71
- export type DBTableHandlersFromSchema<Schema = void> = Schema extends DBSchema? {
72
- [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true?
73
- ServerViewHandler<Schema[tov_name]["columns"], Schema> :
74
- ServerTableHandler<Schema[tov_name]["columns"], Schema>
75
- } : Record<string, Partial<ServerTableHandler>>;
76
-
77
- export type DBHandlerServerExtra<TH = Record<string, Partial<ServerTableHandler>>, WithTransactions = true> = {
78
- sql: SQLHandler;
79
- } & Partial<DbJoinMaker> & (
80
- WithTransactions extends true? { tx: TX<TH> } :
81
- Record<string, never>
82
- );
83
- // export type DBOFullyTyped<Schema = void> = Schema extends DBSchema? (
84
- // DBTableHandlersFromSchema<Schema> & DBHandlerServerExtra<DBTableHandlersFromSchema<Schema>>
85
- // ) :
86
- // DBHandlerServer;
87
- export type DBOFullyTyped<Schema = void> = DBTableHandlersFromSchema<Schema> & DBHandlerServerExtra<DBTableHandlersFromSchema<Schema>>
88
-
89
- export type PublishFullyTyped<Schema = void> = Schema extends DBSchema? (
90
- | PublishAllOrNothing
91
- | {
92
- [tov_name in keyof Partial<Schema>]:
93
- | PublishAllOrNothing
94
- | (
95
- Schema[tov_name]["is_view"] extends true?
96
- PublishViewRule<Schema[tov_name]["columns"], Schema> :
97
- PublishTableRule<Schema[tov_name]["columns"], Schema>
98
- );
99
- }
100
- ) : (
101
- | PublishAllOrNothing
102
- | Record<string, PublishViewRule | PublishTableRule | PublishAllOrNothing>
103
- );
104
-
105
-
106
-
107
- /** Type checks */
108
- (() => {
109
-
110
- const ddb: DBOFullyTyped = 1 as any;
111
- ddb.dwad?.insert;
112
- ddb.dwad?.delete;
113
-
114
- const d: DBOFullyTyped<undefined> = 1 as any;
115
- d.dwad?.insert;
116
- d.dwad?.delete;
117
-
118
- const p: PublishParams = 1 as any;
119
- p.dbo.dwad?.insert;
120
- ddb.dwad?.delete;
121
-
122
- //@ts-ignore
123
- prostgles({
124
- dbConnection: 1 as any,
125
- publish: async (params) => {
126
- const _rows = await params.dbo.dwadwa?.find?.({});
127
-
128
- return "*" as const
129
- },
130
- transactions: true,
131
- onReady: ({ dbo }) => {
132
- dbo.tdwa?.find!();
133
- dbo.tx?.(t => {
134
- t.dwa?.find!();
135
- })
136
- }
137
- });
138
-
139
-
140
- const _auth: Auth = {
141
- sidKeyName: "sid_token",
142
- getUser: async (sid, db, _db) => {
143
- db.dwadaw?.find;
144
- return 1 as any;
145
- }
146
- }
147
-
148
-
149
- type S = {
150
- tbl1: {
151
- columns: {
152
- col1: number | null;
153
- col2: string;
154
- }
155
- },
156
- tbl2: {
157
- columns: {
158
- col1: number | null;
159
- col2: string;
160
- }
161
- }
162
- }
163
-
164
- /** Test the created schema */
165
- const c: S = 1 as any;
166
- const _test: DBSchema = c;
167
- const dbt: DBOFullyTyped<S> = 1 as any;
168
-
169
- dbt.tx!(t => {
170
- t.tbl1.delete();
171
- });
172
-
173
- const db: DBHandlerServer = 1 as any;
174
- db.tx!(t => {
175
- t.wadwa?.find!()
176
- });
177
-
178
- const _publish = (): PublishFullyTyped<S> => {
179
- const r = {
180
- tbl1: {
181
- select: {
182
- fields: "*" as const,
183
- forcedFilter: { col1: 32, col2: "" }
184
- },
185
- getColumns: true,
186
- getInfo: true,
187
- delete: {
188
- filterFields: {col1: 1}
189
- }
190
- },
191
- tbl2: {
192
- delete: {
193
- filterFields: "*" as const,
194
- forcedFilter: {col1: 2}
195
- }
196
- }
197
- }
198
- const res: PublishFullyTyped<S> = {
199
- tbl1: {
200
- select: {
201
- fields: "*",
202
- forcedFilter: { col1: 32, col2: "" }
203
- },
204
- getColumns: true,
205
- getInfo: true,
206
- delete: {
207
- filterFields: { col1: 1 }
208
- }
209
- },
210
- tbl2: {
211
- delete: {
212
- filterFields: "*" as const,
213
- forcedFilter: { col1: 2 }
214
- }
215
- }
216
- }
217
- const _res1: PublishFullyTyped = r
218
-
219
- const p: PublishParams<undefined> = 1 as any;
220
-
221
- p.dbo.dwadaw?.find?.();
222
-
223
- return res;
224
- }
225
- })