prostgles-types 4.0.113 → 4.0.115

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/lib/index.ts CHANGED
@@ -1,74 +1,84 @@
1
-
2
1
  import * as AuthTypes from "./auth";
3
2
  import { FileColumnConfig } from "./files";
4
3
  import { AnyObject, ComplexFilter, FullFilter, FullFilterBasic, ValueOf } from "./filters";
5
4
  import type { UpsertDataToPGCast } from "./insertUpdateUtils";
6
5
  import { JSONB } from "./jsonb";
7
6
  export const _PG_strings = [
8
- 'bpchar','char','varchar','text','citext','uuid','bytea', 'time','timetz','interval','name',
9
- 'cidr', 'inet', 'macaddr', 'macaddr8', "int4range", "int8range", "numrange",
10
- 'tsvector'
11
- ] as const;
12
- export const _PG_numbers_num = ['int2', 'int4', 'float4', 'float8', 'oid'] as const;
13
- export const _PG_numbers_str = ['int8', 'numeric', 'money'] as const;
14
- export const _PG_numbers = [
15
- ..._PG_numbers_num,
16
- ..._PG_numbers_str
17
- ] as const;
18
- export const _PG_json = ['json', 'jsonb'] as const;
19
- export const _PG_bool = ['bool'] as const;
20
- export const _PG_date = ['date', 'timestamp', 'timestamptz'] as const;
21
- export const _PG_interval = ['interval'] as const;
22
- export const _PG_postgis = ['geometry', 'geography'] as const;
23
- export const _PG_geometric = [
24
- "point",
25
- "line",
26
- "lseg",
27
- "box",
28
- "path",
29
- "polygon",
30
- "circle",
7
+ "bpchar",
8
+ "char",
9
+ "varchar",
10
+ "text",
11
+ "citext",
12
+ "uuid",
13
+ "bytea",
14
+ "time",
15
+ "timetz",
16
+ "interval",
17
+ "name",
18
+ "cidr",
19
+ "inet",
20
+ "macaddr",
21
+ "macaddr8",
22
+ "int4range",
23
+ "int8range",
24
+ "numrange",
25
+ "tsvector",
31
26
  ] as const;
27
+ export const _PG_numbers_num = ["int2", "int4", "float4", "float8", "oid"] as const;
28
+ export const _PG_numbers_str = ["int8", "numeric", "money"] as const;
29
+ export const _PG_numbers = [..._PG_numbers_num, ..._PG_numbers_str] as const;
30
+ export const _PG_json = ["json", "jsonb"] as const;
31
+ export const _PG_bool = ["bool"] as const;
32
+ export const _PG_date = ["date", "timestamp", "timestamptz"] as const;
33
+ export const _PG_interval = ["interval"] as const;
34
+ export const _PG_postgis = ["geometry", "geography"] as const;
35
+ export const _PG_geometric = ["point", "line", "lseg", "box", "path", "polygon", "circle"] as const;
36
+
37
+ export type PG_COLUMN_UDT_DATA_TYPE =
38
+ | (typeof _PG_strings)[number]
39
+ | (typeof _PG_numbers)[number]
40
+ | (typeof _PG_geometric)[number]
41
+ | (typeof _PG_json)[number]
42
+ | (typeof _PG_bool)[number]
43
+ | (typeof _PG_date)[number]
44
+ | (typeof _PG_interval)[number]
45
+ | (typeof _PG_postgis)[number];
32
46
 
33
- export type PG_COLUMN_UDT_DATA_TYPE =
34
- | typeof _PG_strings[number]
35
- | typeof _PG_numbers[number]
36
- | typeof _PG_geometric[number]
37
- | typeof _PG_json[number]
38
- | typeof _PG_bool[number]
39
- | typeof _PG_date[number]
40
- | typeof _PG_interval[number]
41
- | typeof _PG_postgis[number];
42
-
43
47
  const TS_PG_PRIMITIVES = {
44
- "string": [ ..._PG_strings, ..._PG_numbers_str, ..._PG_date, ..._PG_geometric, ..._PG_postgis, "lseg"],
45
- "number": _PG_numbers_num,
46
- "boolean": _PG_bool,
47
- "any": [..._PG_json, ..._PG_interval], // consider as any
48
-
49
- /** Timestamps are kept in original string format to avoid filters failing
48
+ string: [
49
+ ..._PG_strings,
50
+ ..._PG_numbers_str,
51
+ ..._PG_date,
52
+ ..._PG_geometric,
53
+ ..._PG_postgis,
54
+ "lseg",
55
+ ],
56
+ number: _PG_numbers_num,
57
+ boolean: _PG_bool,
58
+ any: [..._PG_json, ..._PG_interval], // consider as any
59
+
60
+ /** Timestamps are kept in original string format to avoid filters failing
50
61
  * TODO: cast to dates if udt_name date/timestamp(0 - 3)
51
- */
62
+ */
52
63
  // "Date": _PG_date,
53
64
  } as const;
54
65
 
55
66
  export const TS_PG_Types = {
56
67
  ...TS_PG_PRIMITIVES,
57
- "number[]": TS_PG_PRIMITIVES.number.map(s => `_${s}` as const),
58
- "boolean[]": TS_PG_PRIMITIVES.boolean.map(s => `_${s}` as const),
59
- "string[]": TS_PG_PRIMITIVES.string.map(s => `_${s}` as const),
60
- "any[]": TS_PG_PRIMITIVES.any.map(s => `_${s}` as const),
68
+ "number[]": TS_PG_PRIMITIVES.number.map((s) => `_${s}` as const),
69
+ "boolean[]": TS_PG_PRIMITIVES.boolean.map((s) => `_${s}` as const),
70
+ "string[]": TS_PG_PRIMITIVES.string.map((s) => `_${s}` as const),
71
+ "any[]": TS_PG_PRIMITIVES.any.map((s) => `_${s}` as const),
61
72
  // "Date[]": _PG_date.map(s => `_${s}` as const),
62
- // "any": [],
73
+ // "any": [],
63
74
  } as const;
64
75
  export type TS_COLUMN_DATA_TYPES = keyof typeof TS_PG_Types;
65
76
 
66
-
67
77
  /**
68
78
  * Generated Typescript schema for the tables and views in the database
69
79
  * Example:
70
- *
71
- *
80
+ *
81
+ *
72
82
  * type DBSchema = {
73
83
  * ..view_name: {
74
84
  * is_view: boolean;
@@ -90,19 +100,19 @@ export type DBTableSchema = {
90
100
  delete?: boolean;
91
101
  /**
92
102
  * Used in update, insertm select and filters
93
- * fields that are nullable or with a default value are be optional
103
+ * fields that are nullable or with a default value are be optional
94
104
  */
95
105
  columns: AnyObject;
96
- }
97
- export type DBSchema = {
98
- [tov_name: string]: DBTableSchema
99
- }
106
+ };
107
+ export type DBSchema = {
108
+ [tov_name: string]: DBTableSchema;
109
+ };
100
110
 
101
111
  export type ColumnInfo = {
102
112
  name: string;
103
113
 
104
114
  /**
105
- * Column display name. Will be first non empty value from i18n data, comment, name
115
+ * Column display name. Will be first non empty value from i18n data, comment, name
106
116
  */
107
117
  label: string;
108
118
 
@@ -154,7 +164,7 @@ export type ColumnInfo = {
154
164
  is_pkey: boolean;
155
165
 
156
166
  /**
157
- * Foreign key constraint
167
+ * Foreign key constraint
158
168
  * A column can reference multiple tables
159
169
  */
160
170
  references?: {
@@ -190,12 +200,9 @@ export type ColumnInfo = {
190
200
  * Used in SmartForm
191
201
  */
192
202
  file?: FileColumnConfig;
193
-
194
- }
195
-
203
+ };
196
204
 
197
205
  export type ValidatedColumnInfo = ColumnInfo & {
198
-
199
206
  /**
200
207
  * TypeScript data type
201
208
  */
@@ -230,8 +237,7 @@ export type ValidatedColumnInfo = ColumnInfo & {
230
237
  * Can be used in the delete filter
231
238
  */
232
239
  delete: boolean;
233
- }
234
-
240
+ };
235
241
 
236
242
  export type DBSchemaTable = {
237
243
  name: string;
@@ -242,7 +248,7 @@ export type DBSchemaTable = {
242
248
  /**
243
249
  * List of fields to include or exclude
244
250
  */
245
- export type FieldFilter<T extends AnyObject = AnyObject> = SelectTyped<T>
251
+ export type FieldFilter<T extends AnyObject = AnyObject> = SelectTyped<T>;
246
252
 
247
253
  export type AscOrDesc = 1 | -1 | boolean;
248
254
 
@@ -255,36 +261,41 @@ export type AscOrDesc = 1 | -1 | boolean;
255
261
  * Array order is maintained
256
262
  * if nullEmpty is true then empty text will be replaced to null (so nulls sorting takes effect on it)
257
263
  */
258
- export type _OrderBy<T extends AnyObject> =
264
+ export type _OrderBy<T extends AnyObject> =
259
265
  | { [K in keyof Partial<T>]: AscOrDesc }
260
266
  | { [K in keyof Partial<T>]: AscOrDesc }[]
261
- | { key: keyof T, asc?: AscOrDesc, nulls?: "last" | "first", nullEmpty?: boolean }[]
267
+ | { key: keyof T; asc?: AscOrDesc; nulls?: "last" | "first"; nullEmpty?: boolean }[]
262
268
  | Array<keyof T>
263
- | keyof T
264
- ;
265
-
266
- export type OrderBy<T extends AnyObject | void = void> = T extends AnyObject? _OrderBy<T> : _OrderBy<AnyObject>;
267
-
268
- type CommonSelect =
269
- | "*"
270
- | ""
271
- | { "*" : 1 }
272
-
273
- export type SelectTyped<T extends AnyObject> =
274
- | { [K in keyof Partial<T>]: 1 | true }
275
- | { [K in keyof Partial<T>]: 0 | false }
276
- | (keyof T)[]
277
- | CommonSelect
278
- ;
269
+ | keyof T;
279
270
 
271
+ export type OrderBy<T extends AnyObject | void = void> =
272
+ T extends AnyObject ? _OrderBy<T> : _OrderBy<AnyObject>;
280
273
 
281
- export const JOIN_KEYS = ["$innerJoin", "$leftJoin"] as const;
282
- export const JOIN_PARAMS = ["select", "filter", "$path", "$condition", "offset", "limit", "orderBy"] as const;
274
+ type CommonSelect = "*" | "" | { "*": 1 };
283
275
 
284
- export type JoinCondition = {
285
- column: string;
286
- rootColumn: string;
287
- } | ComplexFilter;
276
+ export type SelectTyped<T extends AnyObject> =
277
+ | { [K in keyof Partial<T>]: 1 | true }
278
+ | { [K in keyof Partial<T>]: 0 | false }
279
+ | (keyof T)[]
280
+ | CommonSelect;
281
+
282
+ export const JOIN_KEYS = ["$innerJoin", "$leftJoin"] as const;
283
+ export const JOIN_PARAMS = [
284
+ "select",
285
+ "filter",
286
+ "$path",
287
+ "$condition",
288
+ "offset",
289
+ "limit",
290
+ "orderBy",
291
+ ] as const;
292
+
293
+ export type JoinCondition =
294
+ | {
295
+ column: string;
296
+ rootColumn: string;
297
+ }
298
+ | ComplexFilter;
288
299
 
289
300
  export type JoinPath = {
290
301
  table: string;
@@ -295,9 +306,9 @@ export type JoinPath = {
295
306
  */
296
307
  on?: Record<string, string>[];
297
308
  };
298
- export type RawJoinPath = string | (JoinPath | string)[]
309
+ export type RawJoinPath = string | (JoinPath | string)[];
299
310
 
300
- export type DetailedJoinSelect = Partial<Record<typeof JOIN_KEYS[number], RawJoinPath>> & {
311
+ export type DetailedJoinSelect = Partial<Record<(typeof JOIN_KEYS)[number], RawJoinPath>> & {
301
312
  select: Select;
302
313
  filter?: FullFilter<void, void>;
303
314
  having?: FullFilter<void, void>;
@@ -305,26 +316,24 @@ export type DetailedJoinSelect = Partial<Record<typeof JOIN_KEYS[number], RawJoi
305
316
  limit?: number;
306
317
  orderBy?: OrderBy;
307
318
  } & (
308
- {
309
- $condition?: undefined;
310
- } | {
311
- /**
312
- * If present then will overwrite $path and any inferred joins
313
- */
314
- $condition?: JoinCondition[];
315
-
316
- }
317
- );
318
-
319
- export type SimpleJoinSelect =
320
- | "*"
321
- /** Aliased Shorthand join: table_name: { ...select } */
322
- | Record<string, 1 | "*" | true | FunctionSelect>
323
- | Record<string, 0 | false>
324
-
325
- export type JoinSelect =
326
- | SimpleJoinSelect
327
- | DetailedJoinSelect;
319
+ | {
320
+ $condition?: undefined;
321
+ }
322
+ | {
323
+ /**
324
+ * If present then will overwrite $path and any inferred joins
325
+ */
326
+ $condition?: JoinCondition[];
327
+ }
328
+ );
329
+
330
+ export type SimpleJoinSelect =
331
+ | "*"
332
+ /** Aliased Shorthand join: table_name: { ...select } */
333
+ | Record<string, 1 | "*" | true | FunctionSelect>
334
+ | Record<string, 0 | false>;
335
+
336
+ export type JoinSelect = SimpleJoinSelect | DetailedJoinSelect;
328
337
 
329
338
  type FunctionShorthand = string;
330
339
  type FunctionFull = Record<string, any[] | readonly any[] | FunctionShorthand>;
@@ -336,29 +345,30 @@ type FunctionAliasedSelect = Record<string, FunctionFull>;
336
345
 
337
346
  type InclusiveSelect = true | 1 | FunctionSelect | JoinSelect;
338
347
 
339
- type SelectFuncs<T extends AnyObject = AnyObject, IsTyped = false> = (
340
- | ({ [K in keyof Partial<T>]: InclusiveSelect } & Record<string, IsTyped extends true? FunctionFull : InclusiveSelect>)
348
+ type SelectFuncs<T extends AnyObject = AnyObject, IsTyped = false> =
349
+ | ({ [K in keyof Partial<T>]: InclusiveSelect } & Record<
350
+ string,
351
+ IsTyped extends true ? FunctionFull : InclusiveSelect
352
+ >)
341
353
  | FunctionAliasedSelect
342
354
  | { [K in keyof Partial<T>]: true | 1 | string }
343
355
  | { [K in keyof Partial<T>]: 0 | false }
344
356
  | CommonSelect
345
- | (keyof Partial<T>)[]
346
- );
357
+ | (keyof Partial<T>)[];
347
358
 
348
359
  /** S param is needed to ensure the non typed select works fine */
349
- export type Select<T extends AnyObject | void = void, S extends DBSchema | void = void> = { t: T, s: S } extends { t: AnyObject, s: DBSchema } ? SelectFuncs<T & { $rowhash: string }, true> : SelectFuncs<AnyObject & { $rowhash: string }, false>;
360
+ export type Select<T extends AnyObject | void = void, S extends DBSchema | void = void> =
361
+ {
362
+ t: T;
363
+ s: S;
364
+ } extends { t: AnyObject; s: DBSchema } ?
365
+ SelectFuncs<T & { $rowhash: string }, true>
366
+ : SelectFuncs<AnyObject & { $rowhash: string }, false>;
350
367
 
351
- export type SelectBasic =
352
- | { [key: string]: any }
353
- | {}
354
- | undefined
355
- | ""
356
- | "*"
357
- ;
368
+ export type SelectBasic = { [key: string]: any } | {} | undefined | "" | "*";
358
369
 
359
370
  /* Simpler types */
360
371
  type CommonSelectParams = {
361
-
362
372
  /**
363
373
  * Max number of rows to return
364
374
  * - If undefined then 1000 will be applied as the default
@@ -384,42 +394,41 @@ type CommonSelectParams = {
384
394
  * - statement-no-rls: sql statement without row level security
385
395
  * - statement-where: sql statement where condition
386
396
  */
387
- returnType?:
388
-
389
- /**
397
+ returnType?: /**
390
398
  * Will return the first row as an object. Will throw an error if more than a row is returned. Use limit: 1 to avoid error.
391
399
  */
392
400
  | "row"
393
401
 
394
- /**
395
- * Will return the first value from the selected field
396
- */
397
- | "value"
398
-
399
- /**
400
- * Will return an array of values from the selected field. Similar to array_agg(field).
401
- */
402
- | "values"
403
-
404
- /**
405
- * Will return the sql statement. Requires publishRawSQL privileges if called by client
406
- */
407
- | "statement"
402
+ /**
403
+ * Will return the first value from the selected field
404
+ */
405
+ | "value"
408
406
 
409
- /**
410
- * Will return the sql statement excluding the user header. Requires publishRawSQL privileges if called by client
411
- */
412
- | "statement-no-rls"
407
+ /**
408
+ * Will return an array of values from the selected field. Similar to array_agg(field).
409
+ */
410
+ | "values"
413
411
 
414
- /**
415
- * Will return the sql statement where condition. Requires publishRawSQL privileges if called by client
416
- */
417
- | "statement-where"
412
+ /**
413
+ * Will return the sql statement. Requires publishRawSQL privileges if called by client
414
+ */
415
+ | "statement"
418
416
 
419
- }
417
+ /**
418
+ * Will return the sql statement excluding the user header. Requires publishRawSQL privileges if called by client
419
+ */
420
+ | "statement-no-rls"
420
421
 
421
- export type SelectParams<T extends AnyObject | void = void, S extends DBSchema | void = void> = CommonSelectParams & {
422
+ /**
423
+ * Will return the sql statement where condition. Requires publishRawSQL privileges if called by client
424
+ */
425
+ | "statement-where";
426
+ };
422
427
 
428
+ export type SelectParams<
429
+ T extends AnyObject | void = void,
430
+ S extends DBSchema | void = void,
431
+ > = CommonSelectParams & {
423
432
  /**
424
433
  * Fields/expressions/linked data to select
425
434
  * - If empty then all fields will be selected
@@ -435,29 +444,31 @@ export type SelectParams<T extends AnyObject | void = void, S extends DBSchema |
435
444
  * Order by options
436
445
  * - If array then the order will be maintained
437
446
  */
438
- orderBy?: OrderBy<S extends DBSchema? T : void>;
447
+ orderBy?: OrderBy<S extends DBSchema ? T : void>;
439
448
 
440
449
  /**
441
450
  * Filter applied after any aggregations (group by)
442
451
  */
443
452
  having?: FullFilter<T, S>;
444
- }
445
- export type SubscribeParams<T extends AnyObject | void = void, S extends DBSchema | void = void> = SelectParams<T, S> & {
453
+ };
454
+ export type SubscribeParams<
455
+ T extends AnyObject | void = void,
456
+ S extends DBSchema | void = void,
457
+ > = SelectParams<T, S> & {
446
458
  /**
447
459
  * If true then the subscription will be throttled to the provided number of milliseconds
448
460
  */
449
461
  throttle?: number;
450
462
  throttleOpts?: {
451
- /**
452
- * False by default.
453
- * If true then the first value will be emitted at the end of the interval. Instant otherwise
463
+ /**
464
+ * False by default.
465
+ * If true then the first value will be emitted at the end of the interval. Instant otherwise
454
466
  * */
455
467
  skipFirst?: boolean;
456
468
  };
457
469
  };
458
470
 
459
471
  export type UpdateParams<T extends AnyObject | void = void, S extends DBSchema | void = void> = {
460
-
461
472
  /**
462
473
  * If defined will returns the specified fields of the updated record(s)
463
474
  */
@@ -470,11 +481,9 @@ export type UpdateParams<T extends AnyObject | void = void, S extends DBSchema |
470
481
 
471
482
  /* true by default. If false the update will fail if affecting more than one row */
472
483
  multi?: boolean;
473
-
474
484
  } & Pick<CommonSelectParams, "returnType">;
475
485
 
476
486
  export type InsertParams<T extends AnyObject | void = void, S extends DBSchema | void = void> = {
477
-
478
487
  /**
479
488
  * If defined will returns the specified fields of the updated record(s)
480
489
  */
@@ -501,7 +510,6 @@ export type DeleteParams<T extends AnyObject | void = void, S extends DBSchema |
501
510
  export type PartialLax<T = AnyObject> = Partial<T>;
502
511
 
503
512
  export type TableInfo = {
504
-
505
513
  /**
506
514
  * OID from the postgres database
507
515
  * Useful in handling renamed tables
@@ -517,14 +525,16 @@ export type TableInfo = {
517
525
  * Defined if this is the fileTable
518
526
  */
519
527
  isFileTable?: {
520
- /**
521
- * Defined if direct inserts are disabled.
528
+ /**
529
+ * Defined if direct inserts are disabled.
522
530
  * Only nested inserts through the specified tables/columns are allowed
523
531
  * */
524
- allowedNestedInserts?: {
525
- table: string;
526
- column: string;
527
- }[] | undefined;
532
+ allowedNestedInserts?:
533
+ | {
534
+ table: string;
535
+ column: string;
536
+ }[]
537
+ | undefined;
528
538
  };
529
539
 
530
540
  /**
@@ -545,214 +555,301 @@ export type TableInfo = {
545
555
  */
546
556
  dynamicRules?: {
547
557
  update?: boolean;
548
- }
558
+ };
549
559
 
550
560
  /**
551
561
  * Additional table info provided through TableConfig
552
562
  */
553
563
  info?: {
554
564
  label?: string;
555
- }
565
+ };
556
566
 
557
567
  /**
558
568
  * List of unique column indexes/constraints.
559
569
  * Column groups where at least a column is not allowed to be viewed (selected) are omitted.
560
570
  */
561
571
  uniqueColumnGroups: string[][] | undefined;
562
- }
572
+ };
563
573
 
564
574
  export type OnError = (err: any) => void;
565
575
 
566
576
  type JoinedSelect = Record<string, Select>;
567
577
  export type SelectFunction = Record<string, any[]>;
568
- type ParseSelect<Select extends SelectParams<TD>["select"], TD extends AnyObject> =
569
- (Select extends { "*": 1 }? Required<TD> : {})
570
- & {
571
- [Key in keyof Omit<Select, "*"> & string]: Select[Key] extends 1? Required<TD>[Key] :
572
- Select[Key] extends SelectFunction? any :
573
- Select[Key] extends JoinedSelect? any[] :
574
- any;
575
- }
576
-
577
- type GetSelectDataType<S extends DBSchema | void, O extends SelectParams<TD, S>, TD extends AnyObject> =
578
- O extends { returnType: "value" }? any :
579
- O extends { returnType: "values"; select: Record<string, 1> }? ValueOf<Pick<Required<TD>, keyof O["select"]>> :
580
- O extends { returnType: "values" }? any :
581
- O extends { select: "*" }? Required<TD> :
582
- O extends { select: "" }? Record<string, never> :
583
- O extends { select: Record<string, 0> }? Omit<Required<TD>, keyof O["select"]> :
584
- O extends { select: Record<string, any> }? ParseSelect<O["select"], Required<TD>> :
585
- Required<TD>;
586
-
587
- export type GetSelectReturnType<S extends DBSchema | void, O extends SelectParams<TD, S>, TD extends AnyObject, isMulti extends boolean> =
588
- O extends { returnType: "statement" }? string :
589
- isMulti extends true? GetSelectDataType<S, O, TD>[] :
590
- GetSelectDataType<S, O, TD>;
591
-
592
- type GetReturningReturnType<O extends UpdateParams<TD, S>, TD extends AnyObject, S extends DBSchema | void = void> =
593
- O extends { returning: "*" }? Required<TD> :
594
- O extends { returning: "" }? Record<string, never> :
595
- O extends { returning: Record<string, 1> }? Pick<Required<TD>, keyof O["returning"]> :
596
- O extends { returning: Record<string, 0> }? Omit<Required<TD>, keyof O["returning"]> :
597
- void;
598
-
599
- export type GetUpdateReturnType<O extends UpdateParams<TD, S>, TD extends AnyObject, S extends DBSchema | void = void> =
600
- O extends { multi: false }?
601
- GetReturningReturnType<O, TD, S> :
602
- GetReturningReturnType<O, TD, S>[];
603
-
604
- export type GetInsertReturnType<Data extends InsertData<AnyObject>, O extends UpdateParams<TD, S>, TD extends AnyObject, S extends DBSchema | void = void> =
605
- Data extends any[] | readonly any[]?
606
- GetReturningReturnType<O, TD, S>[] :
607
- GetReturningReturnType<O, TD, S>;
578
+ type ParseSelect<
579
+ Select extends SelectParams<TD>["select"],
580
+ TD extends AnyObject,
581
+ > = (Select extends { "*": 1 } ? Required<TD> : {}) & {
582
+ [Key in keyof Omit<Select, "*"> & string]: Select[Key] extends 1 ? Required<TD>[Key]
583
+ : Select[Key] extends SelectFunction ? any
584
+ : Select[Key] extends JoinedSelect ? any[]
585
+ : any;
586
+ };
587
+
588
+ type GetSelectDataType<
589
+ S extends DBSchema | void,
590
+ O extends SelectParams<TD, S>,
591
+ TD extends AnyObject,
592
+ > =
593
+ O extends { returnType: "value" } ? any
594
+ : O extends { returnType: "values"; select: Record<string, 1> } ?
595
+ ValueOf<Pick<Required<TD>, keyof O["select"]>>
596
+ : O extends { returnType: "values" } ? any
597
+ : O extends { select: "*" } ? Required<TD>
598
+ : O extends { select: "" } ? Record<string, never>
599
+ : O extends { select: Record<string, 0> } ? Omit<Required<TD>, keyof O["select"]>
600
+ : O extends { select: Record<string, any> } ? ParseSelect<O["select"], Required<TD>>
601
+ : Required<TD>;
602
+
603
+ export type GetSelectReturnType<
604
+ S extends DBSchema | void,
605
+ O extends SelectParams<TD, S>,
606
+ TD extends AnyObject,
607
+ isMulti extends boolean,
608
+ > =
609
+ O extends { returnType: "statement" } ? string
610
+ : isMulti extends true ? GetSelectDataType<S, O, TD>[]
611
+ : GetSelectDataType<S, O, TD>;
612
+
613
+ type GetReturningReturnType<
614
+ O extends UpdateParams<TD, S>,
615
+ TD extends AnyObject,
616
+ S extends DBSchema | void = void,
617
+ > =
618
+ O extends { returning: "*" } ? Required<TD>
619
+ : O extends { returning: "" } ? Record<string, never>
620
+ : O extends { returning: Record<string, 1> } ? Pick<Required<TD>, keyof O["returning"]>
621
+ : O extends { returning: Record<string, 0> } ? Omit<Required<TD>, keyof O["returning"]>
622
+ : void;
623
+
624
+ export type GetUpdateReturnType<
625
+ O extends UpdateParams<TD, S>,
626
+ TD extends AnyObject,
627
+ S extends DBSchema | void = void,
628
+ > =
629
+ O extends { multi: false } ? GetReturningReturnType<O, TD, S>
630
+ : GetReturningReturnType<O, TD, S>[];
631
+
632
+ export type GetInsertReturnType<
633
+ Data extends InsertData<AnyObject>,
634
+ O extends UpdateParams<TD, S>,
635
+ TD extends AnyObject,
636
+ S extends DBSchema | void = void,
637
+ > =
638
+ Data extends any[] | readonly any[] ? GetReturningReturnType<O, TD, S>[]
639
+ : GetReturningReturnType<O, TD, S>;
608
640
 
609
641
  export type SubscriptionHandler = {
610
642
  unsubscribe: () => Promise<any>;
611
643
  filter: FullFilter<void, void> | {};
612
- }
644
+ };
613
645
 
614
- type GetColumns = (lang?: string, params?: { rule: "update", data: AnyObject, filter: AnyObject }) => Promise<ValidatedColumnInfo[]>;
646
+ type GetColumns = (
647
+ lang?: string,
648
+ params?: { rule: "update"; data: AnyObject; filter: AnyObject }
649
+ ) => Promise<ValidatedColumnInfo[]>;
615
650
 
651
+ /**
652
+ * Methods for interacting with a view
653
+ * - On client-side some methods are restricted (and undefined) based on publish rules on the server
654
+ */
616
655
  export type ViewHandler<TD extends AnyObject = AnyObject, S extends DBSchema | void = void> = {
617
656
  /**
618
657
  * Retrieves the table/view info
619
658
  */
620
- getInfo?: (lang?: string) => Promise<TableInfo>;
659
+ getInfo: (lang?: string) => Promise<TableInfo>;
621
660
 
622
661
  /**
623
662
  * Retrieves columns metadata of the table/view
624
663
  */
625
- getColumns?: GetColumns;
664
+ getColumns: GetColumns;
626
665
 
627
666
  /**
628
- * Retrieves a list of records from the view/table
667
+ * Retrieves a list of matching records from the view/table
629
668
  */
630
- find: <P extends SelectParams<TD, S>>(filter?: FullFilter<TD, S>, selectParams?: P) => Promise<GetSelectReturnType<S, P, TD, true>>;
669
+ find: <P extends SelectParams<TD, S>>(
670
+ filter?: FullFilter<TD, S>,
671
+ selectParams?: P
672
+ ) => Promise<GetSelectReturnType<S, P, TD, true>>;
631
673
 
632
674
  /**
633
675
  * Retrieves a record from the view/table
634
676
  */
635
- findOne: <P extends SelectParams<TD, S>>(filter?: FullFilter<TD, S>, selectParams?: P) => Promise<undefined | GetSelectReturnType<S, P, TD, false>>;
677
+ findOne: <P extends SelectParams<TD, S>>(
678
+ filter?: FullFilter<TD, S>,
679
+ selectParams?: P
680
+ ) => Promise<undefined | GetSelectReturnType<S, P, TD, false>>;
636
681
 
637
682
  /**
638
- * Subscribes to changes in the view/table that match the filter
683
+ * Retrieves a list of matching records from the view/table and subscribes to changes
639
684
  */
640
685
  subscribe: <P extends SubscribeParams<TD, S>>(
641
- filter: FullFilter<TD, S>,
642
- params: P,
686
+ filter: FullFilter<TD, S>,
687
+ params: P,
643
688
  onData: (items: GetSelectReturnType<S, P, TD, true>) => any,
644
689
  onError?: OnError
645
690
  ) => Promise<SubscriptionHandler>;
646
691
 
692
+ /**
693
+ * Retrieves first matching record from the view/table and subscribes to changes
694
+ */
647
695
  subscribeOne: <P extends SubscribeParams<TD, S>>(
648
- filter: FullFilter<TD, S>,
649
- params: P,
650
- onData: (item: GetSelectReturnType<S, P, TD, false> | undefined) => any,
696
+ filter: FullFilter<TD, S>,
697
+ params: P,
698
+ onData: (item: GetSelectReturnType<S, P, TD, false> | undefined) => any,
651
699
  onError?: OnError
652
700
  ) => Promise<SubscriptionHandler>;
653
701
 
654
702
  /**
655
703
  * Returns the number of rows that match the filter
656
704
  */
657
- count: <P extends SelectParams<TD, S>>(filter?: FullFilter<TD, S>, selectParams?: P) => Promise<number>;
705
+ count: <P extends SelectParams<TD, S>>(
706
+ filter?: FullFilter<TD, S>,
707
+ selectParams?: P
708
+ ) => Promise<number>;
658
709
 
659
710
  /**
660
711
  * Returns result size in bits
661
712
  */
662
- size: <P extends SelectParams<TD, S>>(filter?: FullFilter<TD, S>, selectParams?: P) => Promise<string>;
663
- }
713
+ size: <P extends SelectParams<TD, S>>(
714
+ filter?: FullFilter<TD, S>,
715
+ selectParams?: P
716
+ ) => Promise<string>;
717
+ };
664
718
 
665
-
666
719
  type UpsertDataToPGCastLax<T extends AnyObject> = PartialLax<UpsertDataToPGCast<T>>;
667
- type InsertData<T extends AnyObject> = UpsertDataToPGCast<T> | UpsertDataToPGCast<T>[]
668
-
669
- export type TableHandler<TD extends AnyObject = AnyObject, S extends DBSchema | void = void> = ViewHandler<TD, S> & {
720
+ type InsertData<T extends AnyObject> = UpsertDataToPGCast<T> | UpsertDataToPGCast<T>[];
670
721
 
722
+ /**
723
+ * Methods for interacting with a table
724
+ * - On client-side some methods are restricted (and undefined) based on publish rules on the server
725
+ */
726
+ export type TableHandler<
727
+ TD extends AnyObject = AnyObject,
728
+ S extends DBSchema | void = void,
729
+ > = ViewHandler<TD, S> & {
671
730
  /**
672
731
  * Updates a record in the table based on the specified filter criteria
673
732
  * - Use { multi: false } to ensure no more than one row is updated
674
733
  */
675
- update: <P extends UpdateParams<TD, S>>(filter: FullFilter<TD, S>, newData: UpsertDataToPGCastLax<TD>, params?: P) => Promise<GetUpdateReturnType<P ,TD, S> | undefined>;
734
+ update: <P extends UpdateParams<TD, S>>(
735
+ filter: FullFilter<TD, S>,
736
+ newData: UpsertDataToPGCastLax<TD>,
737
+ params?: P
738
+ ) => Promise<GetUpdateReturnType<P, TD, S> | undefined>;
676
739
 
677
740
  /**
678
741
  * Updates multiple records in the table in a batch operation.
679
742
  * - Each item in the `data` array contains a filter and the corresponding data to update.
680
743
  */
681
- updateBatch: <P extends UpdateParams<TD, S>>(data: [FullFilter<TD, S>, UpsertDataToPGCastLax<TD>][], params?: P) => Promise<GetUpdateReturnType<P ,TD, S> | void>;
744
+ updateBatch: <P extends UpdateParams<TD, S>>(
745
+ data: [FullFilter<TD, S>, UpsertDataToPGCastLax<TD>][],
746
+ params?: P
747
+ ) => Promise<GetUpdateReturnType<P, TD, S> | void>;
682
748
 
683
749
  /**
684
750
  * Inserts a new record into the table.
685
751
  */
686
- insert: <P extends InsertParams<TD, S>, D extends InsertData<TD>>(data: D, params?: P) => Promise<GetInsertReturnType<D, P ,TD, S>>;
752
+ insert: <P extends InsertParams<TD, S>, D extends InsertData<TD>>(
753
+ data: D,
754
+ params?: P
755
+ ) => Promise<GetInsertReturnType<D, P, TD, S>>;
687
756
 
688
757
  /**
689
758
  * Inserts or updates a record in the table.
690
759
  * - If a record matching the `filter` exists, it updates the record.
691
760
  * - If no matching record exists, it inserts a new record.
692
761
  */
693
- upsert: <P extends UpdateParams<TD, S>>(filter: FullFilter<TD, S>, newData: UpsertDataToPGCastLax<TD>, params?: P) => Promise<GetUpdateReturnType<P ,TD, S>>;
762
+ upsert: <P extends UpdateParams<TD, S>>(
763
+ filter: FullFilter<TD, S>,
764
+ newData: UpsertDataToPGCastLax<TD>,
765
+ params?: P
766
+ ) => Promise<GetUpdateReturnType<P, TD, S>>;
694
767
 
695
768
  /**
696
769
  * Deletes records from the table based on the specified filter criteria.
697
770
  * - If no filter is provided, all records may be deleted (use with caution).
698
771
  */
699
- delete: <P extends DeleteParams<TD, S>>(filter?: FullFilter<TD, S>, params?: P) => Promise<GetUpdateReturnType<P ,TD, S> | undefined>;
700
- }
772
+ delete: <P extends DeleteParams<TD, S>>(
773
+ filter?: FullFilter<TD, S>,
774
+ params?: P
775
+ ) => Promise<GetUpdateReturnType<P, TD, S> | undefined>;
776
+ };
701
777
 
702
- export type JoinMakerOptions<TT extends AnyObject = AnyObject> = SelectParams<TT> & { path?: RawJoinPath };
703
- export type JoinMaker<TT extends AnyObject = AnyObject, S extends DBSchema | void = void> = (filter?: FullFilter<TT, S>, select?: Select<TT>, options?: JoinMakerOptions<TT> ) => any;
704
- export type JoinMakerBasic = (filter?: FullFilterBasic, select?: SelectBasic, options?: SelectParams & { path?: RawJoinPath }) => any;
778
+ export type JoinMakerOptions<TT extends AnyObject = AnyObject> = SelectParams<TT> & {
779
+ path?: RawJoinPath;
780
+ };
781
+ export type JoinMaker<TT extends AnyObject = AnyObject, S extends DBSchema | void = void> = (
782
+ filter?: FullFilter<TT, S>,
783
+ select?: Select<TT>,
784
+ options?: JoinMakerOptions<TT>
785
+ ) => any;
786
+ export type JoinMakerBasic = (
787
+ filter?: FullFilterBasic,
788
+ select?: SelectBasic,
789
+ options?: SelectParams & { path?: RawJoinPath }
790
+ ) => any;
705
791
 
706
792
  export type TableJoin = {
707
793
  [key: string]: JoinMaker;
708
- }
794
+ };
709
795
  export type TableJoinBasic = {
710
796
  [key: string]: JoinMakerBasic;
711
- }
797
+ };
712
798
 
713
799
  export type DbJoinMaker = {
714
800
  innerJoin: TableJoin;
715
801
  leftJoin: TableJoin;
716
802
  innerJoinOne: TableJoin;
717
803
  leftJoinOne: TableJoin;
718
- }
804
+ };
719
805
 
720
806
  export type SQLResultInfo = {
721
- command: "SELECT" | "UPDATE" | "DELETE" | "CREATE" | "ALTER" | "LISTEN" | "UNLISTEN" | "INSERT" | string;
807
+ command:
808
+ | "SELECT"
809
+ | "UPDATE"
810
+ | "DELETE"
811
+ | "CREATE"
812
+ | "ALTER"
813
+ | "LISTEN"
814
+ | "UNLISTEN"
815
+ | "INSERT"
816
+ | string;
722
817
  rowCount: number;
723
818
  duration: number;
724
- }
819
+ };
725
820
  export type SQLResult<T extends SQLOptions["returnType"]> = SQLResultInfo & {
726
- rows: (T extends "arrayMode"? any : AnyObject)[];
821
+ rows: (T extends "arrayMode" ? any : AnyObject)[];
727
822
  fields: {
728
823
  name: string;
729
824
  dataType: string;
730
825
  udt_name: PG_COLUMN_UDT_DATA_TYPE;
731
826
  tsDataType: TS_COLUMN_DATA_TYPES;
732
827
  tableID?: number;
733
- tableName?: string;
734
- tableSchema?: string;
828
+ tableName?: string;
829
+ tableSchema?: string;
735
830
  columnID?: number;
736
831
  columnName?: string;
737
832
  }[];
738
- }
833
+ };
739
834
  export type DBEventHandles = {
740
835
  socketChannel: string;
741
836
  socketUnsubChannel: string;
742
- addListener: (listener: (event: any) => void) => { removeListener: () => void; }
837
+ addListener: (listener: (event: any) => void) => { removeListener: () => void };
743
838
  };
744
839
 
745
- export type SocketSQLStreamPacket = {
746
- type: "data";
747
- fields?: any[];
748
- rows: any[];
749
- ended?: boolean;
750
- info?: SQLResultInfo;
751
- processId: number;
752
- } | {
753
- type: "error";
754
- error: any;
755
- };
840
+ export type SocketSQLStreamPacket =
841
+ | {
842
+ type: "data";
843
+ fields?: any[];
844
+ rows: any[];
845
+ ended?: boolean;
846
+ info?: SQLResultInfo;
847
+ processId: number;
848
+ }
849
+ | {
850
+ type: "error";
851
+ error: any;
852
+ };
756
853
  export type SocketSQLStreamServer = {
757
854
  channel: string;
758
855
  unsubChannel: string;
@@ -763,99 +860,124 @@ export type SocketSQLStreamHandlers = {
763
860
  stop: (terminate?: boolean) => Promise<void>;
764
861
  };
765
862
  export type SocketSQLStreamClient = SocketSQLStreamServer & {
766
- start: (listener: (packet: SocketSQLStreamPacket) => void) => Promise<SocketSQLStreamHandlers>
863
+ start: (listener: (packet: SocketSQLStreamPacket) => void) => Promise<SocketSQLStreamHandlers>;
767
864
  };
768
865
 
769
- export type CheckForListen<T, O extends SQLOptions> = O["allowListen"] extends true? (DBEventHandles | T) : T;
866
+ export type CheckForListen<T, O extends SQLOptions> =
867
+ O["allowListen"] extends true ? DBEventHandles | T : T;
770
868
 
771
869
  export type GetSQLReturnType<O extends SQLOptions> = CheckForListen<
772
- (
773
- O["returnType"] extends "row"? AnyObject | null :
774
- O["returnType"] extends "rows"? AnyObject[] :
775
- O["returnType"] extends "value"? any | null :
776
- O["returnType"] extends "values"? any[] :
777
- O["returnType"] extends "statement"? string :
778
- O["returnType"] extends "noticeSubscription"? DBEventHandles :
779
- O["returnType"] extends "stream"? SocketSQLStreamClient :
780
- SQLResult<O["returnType"]>
781
- )
782
- , O>;
783
-
784
- export type SQLHandler =
785
- /**
786
- *
787
- * @param query <string> query. e.g.: SELECT * FROM users;
788
- * @param params <any[] | object> query arguments to be escaped. e.g.: { name: 'dwadaw' }
789
- * @param options <object> { returnType: "statement" | "rows" | "noticeSubscription" }
790
- */
791
- <Opts extends SQLOptions>(
792
- query: string,
793
- args?: AnyObject | any[],
794
- options?: Opts,
795
- serverSideOptions?: {
796
- socket: any
797
- } | {
798
- httpReq: any;
799
- }
800
- ) => Promise<GetSQLReturnType<Opts>>
801
-
802
- type SelectMethods<T extends DBTableSchema> = T["select"] extends true? keyof Pick<TableHandler, "count" | "find" | "findOne" | "getColumns" | "getInfo" | "size" | "subscribe" | "subscribeOne"> : never;
803
- type UpdateMethods<T extends DBTableSchema> = T["update"] extends true? keyof Pick<TableHandler, "update" | "updateBatch"> : never;
804
- type InsertMethods<T extends DBTableSchema> = T["insert"] extends true? keyof Pick<TableHandler, "insert"> : never;
805
- type UpsertMethods<T extends DBTableSchema> = T["insert"] extends true? T["update"] extends true? keyof Pick<TableHandler, "upsert"> : never : never;
806
- type DeleteMethods<T extends DBTableSchema> = T["delete"] extends true? keyof Pick<TableHandler, "delete"> : never;
807
- // type SyncMethods<T extends DBTableSchema> = T["select"] extends true? T["is_view"] extends true? keyof Pick<TableHandler, "sync"> : never : never;
808
- export type ValidatedMethods<T extends DBTableSchema> =
809
- | SelectMethods<T>
810
- | UpdateMethods<T>
811
- | InsertMethods<T>
812
- | UpsertMethods<T>
813
- | DeleteMethods<T>
870
+ O["returnType"] extends "row" ? AnyObject | null
871
+ : O["returnType"] extends "rows" ? AnyObject[]
872
+ : O["returnType"] extends "value" ? any | null
873
+ : O["returnType"] extends "values" ? any[]
874
+ : O["returnType"] extends "statement" ? string
875
+ : O["returnType"] extends "noticeSubscription" ? DBEventHandles
876
+ : O["returnType"] extends "stream" ? SocketSQLStreamClient
877
+ : SQLResult<O["returnType"]>,
878
+ O
879
+ >;
880
+
881
+ export type SQLHandler =
882
+ /**
883
+ *
884
+ * @param query <string> query. e.g.: SELECT * FROM users;
885
+ * @param params <any[] | object> query arguments to be escaped. e.g.: { name: 'dwadaw' }
886
+ * @param options <object> { returnType: "statement" | "rows" | "noticeSubscription" }
887
+ */
888
+ <Opts extends SQLOptions>(
889
+ query: string,
890
+ args?: AnyObject | any[],
891
+ options?: Opts,
892
+ serverSideOptions?:
893
+ | {
894
+ socket: any;
895
+ }
896
+ | {
897
+ httpReq: any;
898
+ }
899
+ ) => Promise<GetSQLReturnType<Opts>>;
900
+
901
+ type SelectMethods<T extends DBTableSchema> =
902
+ T["select"] extends true ?
903
+ keyof Pick<
904
+ TableHandler,
905
+ | "count"
906
+ | "find"
907
+ | "findOne"
908
+ | "getColumns"
909
+ | "getInfo"
910
+ | "size"
911
+ | "subscribe"
912
+ | "subscribeOne"
913
+ >
914
+ : never;
915
+ type UpdateMethods<T extends DBTableSchema> =
916
+ T["update"] extends true ? keyof Pick<TableHandler, "update" | "updateBatch"> : never;
917
+ type InsertMethods<T extends DBTableSchema> =
918
+ T["insert"] extends true ? keyof Pick<TableHandler, "insert"> : never;
919
+ type UpsertMethods<T extends DBTableSchema> =
920
+ T["insert"] extends true ?
921
+ T["update"] extends true ?
922
+ keyof Pick<TableHandler, "upsert">
923
+ : never
924
+ : never;
925
+ type DeleteMethods<T extends DBTableSchema> =
926
+ T["delete"] extends true ? keyof Pick<TableHandler, "delete"> : never;
927
+
928
+ export type ValidatedMethods<T extends DBTableSchema> =
929
+ | SelectMethods<T>
930
+ | UpdateMethods<T>
931
+ | InsertMethods<T>
932
+ | UpsertMethods<T>
933
+ | DeleteMethods<T>;
814
934
  // | SyncMethods<T>
815
935
 
816
- export type DBHandler<S = void> = (S extends DBSchema? {
817
- [k in keyof S]: S[k]["is_view"] extends true ?
818
- ViewHandler<S[k]["columns"], S> :
819
- Pick<TableHandler<S[k]["columns"], S>, ValidatedMethods<S[k]>>
820
- } : {
821
- [key: string]: Partial<TableHandler>;
822
- }) & DbJoinMaker & {
823
- sql?: SQLHandler
824
- }
936
+ export type DBHandler<S = void> = (S extends DBSchema ?
937
+ {
938
+ [k in keyof S]: S[k]["is_view"] extends true ? ViewHandler<S[k]["columns"], S>
939
+ : Pick<TableHandler<S[k]["columns"], S>, ValidatedMethods<S[k]>>;
940
+ }
941
+ : {
942
+ [key: string]: Partial<TableHandler>;
943
+ }) &
944
+ DbJoinMaker & {
945
+ sql?: SQLHandler;
946
+ };
825
947
 
826
948
  export type DBNoticeConfig = {
827
949
  socketChannel: string;
828
950
  socketUnsubChannel: string;
829
- }
951
+ };
830
952
 
831
953
  export type DBNotifConfig = DBNoticeConfig & {
832
954
  notifChannel: string;
833
- }
834
-
955
+ };
835
956
 
836
957
  export type SQLOptions = {
837
958
  /**
838
959
  * Return type of the query
839
960
  */
840
- returnType?: Required<SelectParams>["returnType"]
961
+ returnType?:
962
+ | Required<SelectParams>["returnType"]
841
963
  | "default-with-rollback"
842
- | "statement"
843
- | "rows"
844
- | "noticeSubscription"
845
- | "arrayMode"
964
+ | "statement"
965
+ | "rows"
966
+ | "noticeSubscription"
967
+ | "arrayMode"
846
968
  | "stream";
847
-
969
+
848
970
  /**
849
971
  * If allowListen not specified and a LISTEN query is issued then expect error
850
972
  */
851
973
  allowListen?: boolean;
852
974
 
853
975
  /**
854
- * Positive integer that works only with returnType="stream".
855
- * If provided then the query will be cancelled when the specified number of rows have been streamed
976
+ * Positive integer that works only with returnType="stream".
977
+ * If provided then the query will be cancelled when the specified number of rows have been streamed
856
978
  */
857
979
  streamLimit?: number;
858
-
980
+
859
981
  /**
860
982
  * If true then the connection will be persisted and used for subsequent queries
861
983
  */
@@ -877,26 +999,25 @@ export type SQLOptions = {
877
999
  export type SQLRequest = {
878
1000
  query: string;
879
1001
  params?: any | any[];
880
- options?: SQLOptions
881
- }
1002
+ options?: SQLOptions;
1003
+ };
882
1004
 
883
1005
  export type NotifSubscription = {
884
1006
  socketChannel: string;
885
1007
  socketUnsubChannel: string;
886
1008
  notifChannel: string;
887
- }
1009
+ };
888
1010
 
889
1011
  export type NoticeSubscription = {
890
1012
  socketChannel: string;
891
1013
  socketUnsubChannel: string;
892
- }
1014
+ };
893
1015
 
894
1016
  const preffix = "_psqlWS_.";
895
1017
  export const CHANNELS = {
896
1018
  SCHEMA_CHANGED: preffix + "schema-changed",
897
1019
  SCHEMA: preffix + "schema",
898
1020
 
899
-
900
1021
  DEFAULT: preffix,
901
1022
  SQL: `${preffix}sql`,
902
1023
  SQL_STREAM: `${preffix}sql-stream`,
@@ -916,7 +1037,7 @@ export const CHANNELS = {
916
1037
  CONNECTION: `${preffix}connection`,
917
1038
 
918
1039
  _preffix: preffix,
919
- }
1040
+ };
920
1041
 
921
1042
  export type SubscriptionChannels = {
922
1043
  /** Used by server to emit data to client */
@@ -927,36 +1048,41 @@ export type SubscriptionChannels = {
927
1048
 
928
1049
  /** Used by client to stop subscription */
929
1050
  channelNameUnsubscribe: string;
930
- }
1051
+ };
931
1052
 
932
1053
  export type AuthGuardLocation = {
933
- href: string;
934
- origin: string;
1054
+ href: string;
1055
+ origin: string;
935
1056
  protocol: string;
936
- host: string;
1057
+ host: string;
937
1058
  hostname: string;
938
- port: string;
1059
+ port: string;
939
1060
  pathname: string;
940
- search: string;
941
- hash: string;
942
- }
1061
+ search: string;
1062
+ hash: string;
1063
+ };
943
1064
  export type AuthGuardLocationResponse = {
944
1065
  shouldReload: boolean;
945
- }
1066
+ };
946
1067
 
947
1068
  export const RULE_METHODS = {
948
- "getColumns": ["getColumns"],
949
- "getInfo": ["getInfo"],
950
- "insert": ["insert", "upsert"],
951
- "update": ["update", "upsert", "updateBatch"],
952
- "select": ["findOne", "find", "count", "size"],
953
- "delete": ["delete", "remove"],
954
- "sync": ["sync", "unsync"],
955
- "subscribe": ["unsubscribe", "subscribe", "subscribeOne"],
956
- } as const
957
-
958
- export type MethodKey = typeof RULE_METHODS[keyof typeof RULE_METHODS][number]
959
- export type TableSchemaForClient = Record<string, Partial<Record<MethodKey, (MethodKey extends "insert"? { allowedNestedInserts?: string[]; } : AnyObject)>>>;
1069
+ getColumns: ["getColumns"],
1070
+ getInfo: ["getInfo"],
1071
+ insert: ["insert", "upsert"],
1072
+ update: ["update", "upsert", "updateBatch"],
1073
+ select: ["findOne", "find", "count", "size"],
1074
+ delete: ["delete", "remove"],
1075
+ sync: ["sync", "unsync"],
1076
+ subscribe: ["unsubscribe", "subscribe", "subscribeOne"],
1077
+ } as const;
1078
+
1079
+ export type MethodKey = (typeof RULE_METHODS)[keyof typeof RULE_METHODS][number];
1080
+ export type TableSchemaForClient = Record<
1081
+ string,
1082
+ Partial<
1083
+ Record<MethodKey, MethodKey extends "insert" ? { allowedNestedInserts?: string[] } : AnyObject>
1084
+ >
1085
+ >;
960
1086
 
961
1087
  /* Schema */
962
1088
  export type TableSchema = {
@@ -974,26 +1100,29 @@ export type TableSchema = {
974
1100
  select: boolean;
975
1101
  update: boolean;
976
1102
  delete: boolean;
977
- }
978
- }
1103
+ };
1104
+ };
979
1105
 
980
- export type MethodFunction = (...args: any) => (any | Promise<any>);
1106
+ export type MethodFunction = (...args: any) => any | Promise<any>;
981
1107
  export type MethodFullDef = {
982
1108
  input: Record<string, JSONB.JSONBSchema>;
983
1109
  run: MethodFunction;
984
1110
  output?: Record<string, JSONB.JSONBSchema>;
985
- } & ({
986
- output?: undefined;
987
- outputTable?: string;
988
- } | {
989
- output?: Record<string, JSONB.JSONBSchema>;
990
- outputTable?: undefined;
991
- });
1111
+ } & (
1112
+ | {
1113
+ output?: undefined;
1114
+ outputTable?: string;
1115
+ }
1116
+ | {
1117
+ output?: Record<string, JSONB.JSONBSchema>;
1118
+ outputTable?: undefined;
1119
+ }
1120
+ );
992
1121
  export type Method = MethodFunction | MethodFullDef;
993
1122
 
994
1123
  export type MethodHandler = {
995
1124
  [method_name: string]: Method;
996
- }
1125
+ };
997
1126
 
998
1127
  export type TableSchemaErrors = {
999
1128
  [tableName: string]: {
@@ -1003,7 +1132,7 @@ export type TableSchemaErrors = {
1003
1132
  };
1004
1133
  };
1005
1134
 
1006
- export type ClientSchema = {
1135
+ export type ClientSchema = {
1007
1136
  rawSQL: boolean;
1008
1137
  joinTables: string[][];
1009
1138
  auth: AuthTypes.AuthSocketSchema | undefined;
@@ -1012,8 +1141,11 @@ export type ClientSchema = {
1012
1141
  tableSchemaErrors: TableSchemaErrors;
1013
1142
  tableSchema?: DBSchemaTable[];
1014
1143
  schema: TableSchemaForClient;
1015
- methods: (string | { name: string; description?: string; } & Pick<MethodFullDef, "input" | "output">)[];
1016
- }
1144
+ methods: (
1145
+ | string
1146
+ | ({ name: string; description?: string } & Pick<MethodFullDef, "input" | "output">)
1147
+ )[];
1148
+ };
1017
1149
 
1018
1150
  export type ProstglesError = {
1019
1151
  message: string;
@@ -1025,131 +1157,133 @@ export type ProstglesError = {
1025
1157
  code_info?: string;
1026
1158
  detail?: string;
1027
1159
  columns?: string[];
1028
- }
1029
-
1160
+ };
1030
1161
 
1031
1162
  /**
1032
1163
  * Type tests
1033
1164
  */
1034
- (( ) => {
1035
-
1036
- type Fields = { id: number; name: number; public: number; $rowhash: string; added_day: any }
1037
- const r:Fields = 1 as any
1038
- const sel1: Select = { id: 1, name: 1, public: 1, $rowhash: 1, added_day: { $day: [] } };
1039
- const sel2: Select<{ id: number; name: number; public: number; }> = { id: 1, name: 1, public: 1, $rowhash: 1, dsds: { d: [] } };
1040
- const sel3: Select<{ id: number; name: number; public: number; }> = ""
1041
- const sel4: Select<{ id: number; name: number; public: number; }> = "*"
1165
+ () => {
1166
+ type Fields = { id: number; name: number; public: number; $rowhash: string; added_day: any };
1167
+ const r: Fields = 1 as any;
1168
+ const sel1: Select = { id: 1, name: 1, public: 1, $rowhash: 1, added_day: { $day: [] } };
1169
+ const sel2: Select<{ id: number; name: number; public: number }> = {
1170
+ id: 1,
1171
+ name: 1,
1172
+ public: 1,
1173
+ $rowhash: 1,
1174
+ dsds: { d: [] },
1175
+ };
1176
+ const sel3: Select<{ id: number; name: number; public: number }> = "";
1177
+ const sel4: Select<{ id: number; name: number; public: number }> = "*";
1042
1178
  const sel12: Select = { id: 1, name: 1, public: 1, $rowhash: 1, dsds: { d: [] } };
1043
- const sel13: Select = ""
1179
+ const sel13: Select = "";
1044
1180
  const sel14: Select = "*";
1045
1181
 
1046
1182
  const fRow: FullFilter<Fields, {}> = {
1047
- $rowhash: { "$in": [""] }
1048
- };
1049
- const emptyFilter: FullFilter<Fields, {}> = {
1183
+ $rowhash: { $in: [""] },
1050
1184
  };
1185
+ const emptyFilter: FullFilter<Fields, {}> = {};
1051
1186
 
1052
1187
  const sel32: Select = {
1053
- dwa: 1
1054
- }
1055
-
1188
+ dwa: 1,
1189
+ };
1190
+
1056
1191
  const sel = {
1057
1192
  a: 1,
1058
1193
  $rowhash: 1,
1059
- dwadwA: { dwdwa: [5] }
1060
- } as const;
1061
-
1194
+ dwadwA: { dwdwa: [5] },
1195
+ } as const;
1196
+
1062
1197
  const sds: Select = sel;
1063
1198
  const sds01: Select = "";
1064
1199
  const sds02: Select = "*";
1065
1200
  const sds03: Select = {};
1066
- const sds2: Select<{a: number}> = sel;
1067
-
1068
- const s001: Select = {
1069
- h: { "$ts_headline_simple": ["name", { plainto_tsquery: "abc81" }] },
1070
- hh: { "$ts_headline": ["name", "abc81"] } ,
1201
+ const sds2: Select<{ a: number }> = sel;
1202
+
1203
+ const s001: Select = {
1204
+ h: { $ts_headline_simple: ["name", { plainto_tsquery: "abc81" }] },
1205
+ hh: { $ts_headline: ["name", "abc81"] },
1071
1206
  added: "$date_trunc_2hour",
1072
- addedY: { "$date_trunc_5minute": ["added"] },
1073
- }
1074
-
1207
+ addedY: { $date_trunc_5minute: ["added"] },
1208
+ };
1209
+
1075
1210
  //@ts-expect-error
1076
1211
  const badSel: Select = {
1077
1212
  a: 1,
1078
- b: 0
1213
+ b: 0,
1079
1214
  };
1080
-
1215
+
1081
1216
  //@ts-expect-error
1082
- const badSel1: Select<{a: number}, {}> = {
1217
+ const badSel1: Select<{ a: number }, {}> = {
1083
1218
  b: 1,
1084
- a: 1
1219
+ a: 1,
1085
1220
  };
1086
-
1087
- const sds3: Select<{a: number}> = {
1221
+
1222
+ const sds3: Select<{ a: number }> = {
1088
1223
  // "*": 1,
1089
1224
  // a: "$funcName",
1090
1225
  a: { dwda: [] },
1091
1226
  $rowhashD: { dwda: [] },
1092
1227
  // dwadwa: 1, //{ dwa: []}
1093
- }
1094
-
1228
+ };
1095
1229
 
1096
1230
  const sel1d: Select = {
1097
1231
  dwada: 1,
1098
1232
  $rowhash: 1,
1099
- dwawd: { funcName: [12] }
1100
- }
1233
+ dwawd: { funcName: [12] },
1234
+ };
1101
1235
 
1102
- const sel1d2: Select<AnyObject> = ["a"]
1236
+ const sel1d2: Select<AnyObject> = ["a"];
1103
1237
 
1104
1238
  const deletePar: DeleteParams = {
1105
- returning: { id: 1, name: 1, public: 1 , $rowhash: 1, added_day: { "$day": ["added"] } }
1106
- }
1107
- });
1239
+ returning: { id: 1, name: 1, public: 1, $rowhash: 1, added_day: { $day: ["added"] } },
1240
+ };
1241
+ };
1108
1242
 
1109
1243
  /** More Type tests */
1110
- (async () => {
1111
-
1244
+ async () => {
1112
1245
  type GSchema = {
1113
1246
  tbl1: {
1114
- is_view: false,
1247
+ is_view: false;
1115
1248
  columns: {
1116
- col1: string,
1117
- col2: string,
1118
- },
1119
- delete: true,
1120
- select: true,
1121
- insert: true,
1122
- update: true,
1123
- }
1249
+ col1: string;
1250
+ col2: string;
1251
+ };
1252
+ delete: true;
1253
+ select: true;
1254
+ insert: true;
1255
+ update: true;
1256
+ };
1124
1257
  };
1125
1258
 
1126
- type TableDef = { h: number; b?: number; c?: number; }
1127
- const tableHandler: TableHandler<TableDef> = undefined as any;
1128
- tableHandler.insert({ h: 1, c: 2, "b.$func": { dwa: [] } })
1129
-
1130
- type DBOFullyTyped<Schema = void> = Schema extends DBSchema ? {
1131
- [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true ?
1132
- ViewHandler<Schema[tov_name]["columns"], Schema> :
1133
- TableHandler<Schema[tov_name]["columns"], Schema>
1134
- } : Record<string, ViewHandler | TableHandler>;
1135
-
1136
-
1137
- type TypedFFilter = FullFilter<GSchema["tbl1"]["columns"], GSchema>
1259
+ type TableDef = { h: number; b?: number; c?: number };
1260
+ const tableHandler: TableHandler<TableDef> = undefined as any;
1261
+ tableHandler.insert({ h: 1, c: 2, "b.$func": { dwa: [] } });
1262
+
1263
+ type DBOFullyTyped<Schema = void> =
1264
+ Schema extends DBSchema ?
1265
+ {
1266
+ [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true ?
1267
+ ViewHandler<Schema[tov_name]["columns"], Schema>
1268
+ : TableHandler<Schema[tov_name]["columns"], Schema>;
1269
+ }
1270
+ : Record<string, ViewHandler | TableHandler>;
1271
+
1272
+ type TypedFFilter = FullFilter<GSchema["tbl1"]["columns"], GSchema>;
1138
1273
  const schemaFFilter: TypedFFilter = { "col1.$eq": "dd" };
1139
1274
  const fullFilter: FullFilter<void, void> = schemaFFilter;
1140
-
1275
+
1141
1276
  const ffFunc = (f: FullFilter<void, void>) => {};
1142
- ffFunc(schemaFFilter);
1143
-
1277
+ ffFunc(schemaFFilter);
1278
+
1144
1279
  const dbo: DBOFullyTyped<GSchema> = 1 as any;
1145
1280
  const funcData = { funcName: [] };
1146
1281
  const noRow = await dbo.tbl1.update({}, { col1: "" });
1147
- //@ts-expect-error
1282
+ //@ts-expect-error
1148
1283
  noRow.length;
1149
1284
  //@ts-expect-error
1150
1285
  noRow.col1;
1151
1286
 
1152
-
1153
1287
  const someData = await dbo.tbl1.find({}, { select: { col1: 1 }, orderBy: { col1: -1 } });
1154
1288
 
1155
1289
  const noRowFunc = await dbo.tbl1.update({}, { col1: "" });
@@ -1166,68 +1300,64 @@ export type ProstglesError = {
1166
1300
  manyRows?.col1;
1167
1301
  manyRows?.at(0)?.col1;
1168
1302
 
1169
-
1170
1303
  const noIRow = await dbo.tbl1.insert({ col1: "", col2: { $func: [] } });
1171
- //@ts-expect-error
1304
+ //@ts-expect-error
1172
1305
  noIRow.length;
1173
1306
  //@ts-expect-error
1174
1307
  noIRow.col1;
1175
-
1308
+
1176
1309
  const irow = await dbo.tbl1.insert({ col1: "", col2: funcData }, { returning: "*" });
1177
- //@ts-expect-error
1310
+ //@ts-expect-error
1178
1311
  irow.length;
1179
1312
  irow.col1;
1180
1313
 
1181
1314
  const irowFunc = await dbo.tbl1.insert({ col1: funcData, col2: "" }, { returning: "*" });
1182
1315
 
1183
1316
  const irows = await dbo.tbl1.insert([{ col1: "", col2: "" }], { returning: "*" });
1184
- //@ts-expect-error
1317
+ //@ts-expect-error
1185
1318
  irows.col1;
1186
1319
  irows.length;
1187
1320
 
1188
- const filter: FullFilter<GSchema["tbl1"]["columns"], GSchema> = { };
1189
-
1321
+ const filter: FullFilter<GSchema["tbl1"]["columns"], GSchema> = {};
1322
+
1190
1323
  const filterCheck = <F extends FullFilter<void, void> | undefined>(f: F) => {};
1191
1324
  filterCheck(filter);
1192
-
1325
+
1193
1326
  const t: UpsertDataToPGCast<GSchema["tbl1"]["columns"]> = {} as any;
1194
1327
  const d: UpsertDataToPGCast<AnyObject> = t;
1195
- const fup = (a: UpsertDataToPGCast<AnyObject>) => {}
1328
+ const fup = (a: UpsertDataToPGCast<AnyObject>) => {};
1196
1329
  fup(t);
1197
1330
 
1198
1331
  // const f = <A extends TableHandler["count"]>(a: A) => {};
1199
1332
  const f = (s: TableHandler) => {};
1200
- const th: TableHandler<GSchema["tbl1"]["columns"], GSchema> = { } as any;
1201
- // f(th)
1333
+ const th: TableHandler<GSchema["tbl1"]["columns"], GSchema> = {} as any;
1334
+ // f(th)
1202
1335
 
1203
1336
  const sp: SelectParams<GSchema["tbl1"]["columns"]> = { select: {} };
1204
- const sf = (sp: SelectParams) => {
1205
-
1206
- }
1337
+ const sf = (sp: SelectParams) => {};
1207
1338
  sf(sp);
1208
1339
  // const sub: TableHandler["count"] = dbo.tbl1.count
1209
-
1340
+
1210
1341
  /**
1211
1342
  * Upsert data funcs
1212
1343
  */
1213
- const gdw: InsertData<{ a: number; z: number }> = {
1214
- a: { dwa: [] },
1215
- z: { dwa: [] }
1216
- }
1217
- const gdwn: InsertData<{ a: number; z: number }> = {
1218
- a: 2,
1219
- z: { dwa: [] }
1220
- }
1221
- const gdw1: InsertData<{ a: number; z: number }> = { a: 1, z: 2 }
1222
- const gdw1Opt: InsertData<{ a: number; z?: number }> = { a: {}, z: 2 }
1223
- const gdw2: InsertData<{ a: number; z: number; }> = { a: { dwa: [] } , z: { dwa: [] } }
1344
+ const gdw: InsertData<{ a: number; z: number }> = {
1345
+ a: { dwa: [] },
1346
+ z: { dwa: [] },
1347
+ };
1348
+ const gdwn: InsertData<{ a: number; z: number }> = {
1349
+ a: 2,
1350
+ z: { dwa: [] },
1351
+ };
1352
+ const gdw1: InsertData<{ a: number; z: number }> = { a: 1, z: 2 };
1353
+ const gdw1Opt: InsertData<{ a: number; z?: number }> = { a: {}, z: 2 };
1354
+ const gdw2: InsertData<{ a: number; z: number }> = { a: { dwa: [] }, z: { dwa: [] } };
1224
1355
  //@ts-expect-error
1225
- const missingKey: InsertData<{ a: number; z: number; }> = { z: 1, z: { dwa: [] } }
1356
+ const missingKey: InsertData<{ a: number; z: number }> = { z: 1, z: { dwa: [] } };
1226
1357
  //@ts-expect-error
1227
- const missingKey2: InsertData<{ a: number; z: number; }> = { z: 1 };
1358
+ const missingKey2: InsertData<{ a: number; z: number }> = { z: 1 };
1228
1359
  // ra(schema);
1229
- })
1230
-
1360
+ };
1231
1361
 
1232
1362
  // import { md5 } from "./md5";
1233
1363
  // export { get, getTextPatch, unpatchText, isEmpty, WAL, WALConfig, asName } from "./util";
@@ -1236,6 +1366,14 @@ export { CONTENT_TYPE_TO_EXT } from "./files";
1236
1366
  export type { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, FileColumnConfig, FileType } from "./files";
1237
1367
  export * from "./filters";
1238
1368
  export * from "./jsonb";
1239
- export type { ClientExpressData, ClientSyncHandles, ClientSyncInfo, ClientSyncPullResponse, SyncBatchParams, SyncConfig, onUpdatesParams } from "./replication";
1369
+ export type {
1370
+ ClientExpressData,
1371
+ ClientSyncHandles,
1372
+ ClientSyncInfo,
1373
+ ClientSyncPullResponse,
1374
+ SyncBatchParams,
1375
+ SyncConfig,
1376
+ onUpdatesParams,
1377
+ } from "./replication";
1240
1378
  export * from "./util";
1241
- export * from "./auth";
1379
+ export * from "./auth";