-
-
Notifications
You must be signed in to change notification settings - Fork 612
Expand file tree
/
Copy pathdatasource.ts
More file actions
1512 lines (1415 loc) · 44.5 KB
/
datasource.ts
File metadata and controls
1512 lines (1415 loc) · 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import chalk from "chalk";
import type { GrafastValuesList, ObjectStep } from "grafast";
import {
__ValueStep,
arraysMatch,
constant,
ExecutableStep,
exportAs,
partitionByIndex,
} from "grafast";
import type { SQL } from "pg-sql2";
import sql from "pg-sql2";
import type {
_AnyPgCodecAttribute,
GenericPgCodecAttribute,
PgCodecAttributeName,
PgCodecAttributeVia,
PgCodecAttributeViaExplicit,
} from "./codecs.js";
import { TYPES } from "./codecs.js";
import type {
PgClientResult,
PgExecutor,
PgExecutorContextPlans,
PgExecutorInput,
PgExecutorMutationOptions,
PgExecutorOptions,
} from "./executor.js";
import { inspect } from "./inspect.js";
import type {
_AnyPgCodec,
_AnyPgCodecRelationConfig,
_AnyPgRegistry,
_AnyPgRegistryConfig,
_AnyScalarPgCodec,
Expand,
GenericPgCodec,
GenericPgCodecRelationConfig,
GetPgRegistryCodecRelationConfigs,
GetPgRegistryCodecRelations,
GetPgRegistryCodecs,
PgCodecAttributes,
PgCodecName,
PgCodecRelationConfig,
PgCodecRelationConfigName,
PgRefDefinition,
PgRegistry,
PgRegistryConfig,
PgRegistryConfigCodecs,
PgRegistryConfigRelationConfigs,
PgRegistryConfigResourceOptions,
PlanByUniques,
} from "./interfaces.js";
import type { PgClassExpressionStep } from "./steps/pgClassExpression.js";
import type {
PgSelectArgumentDigest,
PgSelectArgumentSpec,
PgSelectIdentifierSpec,
PgSelectMode,
PgSelectStep,
} from "./steps/pgSelect.js";
import { pgSelect } from "./steps/pgSelect.js";
import type {
PgSelectSinglePlanOptions,
PgSelectSingleStep,
} from "./steps/pgSelectSingle.js";
export function EXPORTABLE<T, TScope extends any[]>(
factory: (...args: TScope) => T,
args: [...TScope],
): T {
const fn: T = factory(...args);
if (
(typeof fn === "function" || (typeof fn === "object" && fn !== null)) &&
!("$exporter$factory" in fn)
) {
Object.defineProperties(fn, {
$exporter$args: { value: args },
$exporter$factory: { value: factory },
});
}
return fn;
}
/** @deprecated Use DataplanPg.PgResourceUniqueExtensions instead */
export type PgResourceUniqueExtensions = DataplanPg.PgResourceUniqueExtensions;
/** @deprecated Use DataplanPg.PgResourceExtensions instead */
export type PgResourceExtensions = DataplanPg.PgResourceExtensions;
/** @deprecated Use DataplanPg.PgResourceParameterExtensions instead */
export type PgResourceParameterExtensions =
DataplanPg.PgResourceParameterExtensions;
/** @internal */
export interface _AnyPgResourceParameter
extends PgResourceParameter<any, any> {}
export interface GenericPgResourceParameter
extends PgResourceParameter<string | null, GenericPgCodec> {}
/**
* If this is a functional (rather than static) resource, this describes one of
* the parameters it accepts.
*/
export interface PgResourceParameter<
TName extends string | null,
TCodec extends _AnyPgCodec,
> {
/**
* Name of the parameter, if null then we must use positional rather than
* named arguments
*/
name: TName;
/**
* The type of this parameter
*/
codec: TCodec;
/**
* If true, then this parameter must be supplied, otherwise it's optional.
*/
required: boolean;
/**
* If true and the parameter is supplied, then the parameter must not be
* null.
*/
notNull?: boolean;
extensions?: PgResourceParameterExtensions;
}
/** @internal */
export interface _AnyPgResourceUnique extends PgResourceUnique<any> {}
export interface GenericPgResourceUnique
extends PgResourceUnique<GenericPgCodecAttribute> {}
/**
* Description of a unique constraint on a PgResource.
*/
export interface PgResourceUnique<TAttributes extends _AnyPgCodecAttribute> {
/**
* The attributes that are unique
*/
attributes: Array<PgCodecAttributeName<TAttributes>>;
/**
* If this is true, this represents the "primary key" of the resource.
*/
isPrimary?: boolean;
description?: string;
/**
* Space for you to add your own metadata
*/
extensions?: PgResourceUniqueExtensions;
}
export interface PgCodecRefPathEntry {
relationName: string;
// Could add conditions here
}
export type PgCodecRefPath = PgCodecRefPathEntry[];
/** @deprecated Use DataplanPg.PgCodecRefExtensions instead */
export type PgCodecRefExtensions = DataplanPg.PgCodecRefExtensions;
export interface PgCodecRef {
definition: PgRefDefinition;
paths: Array<PgCodecRefPath>;
description?: string;
extensions?: PgCodecRefExtensions;
}
export interface PgCodecRefs {
[refName: string]: PgCodecRef;
}
export interface GenericPgResourceOptions<
TCodec extends GenericPgCodec = GenericPgCodec,
> extends PgResourceOptions<
string,
TCodec,
GenericPgResourceUnique,
GenericPgResourceParameter
> {}
/** @internal */
export interface _AnyPgResourceOptions
extends PgResourceOptions<any, any, any, any> {}
export type PgResourceOptionName<U> = U extends PgResourceOptions<
infer TName,
any,
any,
any
>
? TName
: never;
export type PgResourceOptionCodec<U> = U extends PgResourceOptions<
any,
infer TCodec,
any,
any
>
? TCodec
: never;
export type PgResourceOptionUniques<U> = U extends PgResourceOptions<
any,
any,
infer TUniques,
any
>
? TUniques
: never;
export type PgResourceOptionParameters<U> = U extends PgResourceOptions<
any,
any,
any,
infer TParameters
>
? TParameters
: never;
/**
* Configuration options for your PgResource
*/
export interface PgResourceOptions<
TName extends string,
TCodec extends _AnyPgCodec,
TUniques extends PgResourceUnique<PgCodecAttributes<TCodec>>,
TParameters extends _AnyPgResourceParameter,
> {
/**
* The associated codec for this resource
*/
codec: TCodec;
/**
* The PgExecutor to use when servicing this resource; different executors can
* have different caching rules. A plan that uses one executor cannot be
* inlined into a plan for a different executor.
*/
executor: PgExecutor;
// TODO: auth should also apply to insert, update and delete, maybe via insertAuth, updateAuth, etc
selectAuth?: ($step: PgSelectStep<_AnyPgResource>) => void;
name: TName;
identifier?: string;
// see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
from: SQL | ((...args: PgSelectArgumentDigest[]) => SQL);
uniques?: [TUniques] extends [never] ? never : ReadonlyArray<TUniques>;
extensions?: PgResourceExtensions;
parameters?: [TParameters] extends [never]
? never
: ReadonlyArray<TParameters>;
description?: string;
/**
* Set true if this resource will only return at most one record - this is
* generally only useful for PostgreSQL function resources, in which case you
* should set it false if the function `returns setof` and true otherwise.
*/
isUnique?: boolean;
sqlPartitionByIndex?: SQL;
isMutation?: boolean;
/**
* If true, this indicates that this was originally a list (array) and thus
* should be treated as having a predetermined and reasonable length rather
* than being unbounded. It's just a hint to schema generation, it doesn't
* affect planning.
*/
isList?: boolean;
/**
* "Virtual" resources cannot be selected from/inserted to/etc, they're
* normally used to generate other resources that are _not_ virtual.
*/
isVirtual?: boolean;
}
/** @internal */
export interface _AnyPgFunctionResourceOptions
extends PgFunctionResourceOptions<any, any, any, any> {}
export interface GenericPgFunctionResourceOptions
extends PgFunctionResourceOptions<
string,
GenericPgCodec,
GenericPgResourceUnique,
GenericPgResourceParameter
> {}
export interface PgFunctionResourceOptions<
TNewName extends string,
TCodec extends _AnyPgCodec,
TUniques extends PgResourceUnique<PgCodecAttributes<TCodec>>,
TNewParameters extends _AnyPgResourceParameter,
> {
name: TNewName;
identifier?: string;
from: (...args: PgSelectArgumentDigest[]) => SQL;
parameters?: [TNewParameters] extends [never]
? never
: ReadonlyArray<TNewParameters>;
returnsSetof: boolean;
returnsArray: boolean;
uniques?: [TUniques] extends [never] ? never : ReadonlyArray<TUniques>;
extensions?: PgResourceExtensions;
isMutation?: boolean;
selectAuth?: ($step: PgSelectStep<_AnyPgResource>) => void;
description?: string;
}
export type PgResourceName<U> = U extends PgResource<
infer TName,
any,
any,
any,
any
>
? TName
: never;
export type PgResourceCodec<U> = U extends PgResource<
any,
infer TCodec,
any,
any,
any
>
? TCodec
: never;
export type PgResourceUniques<U> = U extends PgResource<
any,
any,
infer TUniques,
any,
any
>
? TUniques
: never;
export type PgResourceParameters<U> = U extends PgResource<
any,
any,
any,
infer TParameters,
any
>
? TParameters
: never;
export type PgResourceRegistry<U> = U extends PgResource<
any,
any,
any,
any,
infer TRegistry
>
? TRegistry
: never;
export interface GenericPgResource
extends PgResource<
string,
GenericPgCodec,
GenericPgResourceUnique,
GenericPgResourceParameter,
any
> {}
/** @internal */
export interface _AnyPgResource extends PgResource<any, any, any, any, any> {}
/** @internal */
export interface _AnyScalarPgResource
extends PgResource<any, _AnyScalarPgCodec, any, any, any> {}
/**
* PgResource represents any resource of SELECT-able data in Postgres: tables,
* views, functions, etc.
*/
export class PgResource<
TName extends string,
TCodec extends _AnyPgCodec,
TUniques extends PgResourceUnique<PgCodecAttributes<TCodec>>,
TParameters extends _AnyPgResourceParameter,
TRegistry extends _AnyPgRegistry,
> {
public readonly registry: TRegistry;
public readonly codec: TCodec;
public readonly executor: PgExecutor;
public readonly name: TName;
public readonly identifier: string;
public readonly from: SQL | ((...args: PgSelectArgumentDigest[]) => SQL);
public readonly uniques: [TUniques] extends [never]
? never
: ReadonlyArray<TUniques>;
private selectAuth?: ($step: PgSelectStep<_AnyPgResource>) => void;
// TODO: make a public interface for this information
/**
* If present, implies that the resource represents a `setof composite[]` (i.e.
* an array of arrays) - and thus is not appropriate to use for GraphQL
* Cursor Connections.
*
* @internal
*/
public sqlPartitionByIndex: SQL | null = null;
public readonly parameters: [TParameters] extends [never]
? never
: ReadonlyArray<TParameters>;
public readonly description: string | undefined;
public readonly isUnique: boolean;
public readonly isMutation: boolean;
/**
* If true, this indicates that this was originally a list (array) and thus
* should be treated as having a predetermined and reasonable length rather
* than being unbounded. It's just a hint to schema generation, it doesn't
* affect planning.
*/
public readonly isList: boolean;
/**
* "Virtual" resources cannot be selected from/inserted to/etc, they're
* normally used to generate other resources that are _not_ virtual.
*/
public readonly isVirtual: boolean;
public extensions: Partial<DataplanPg.PgResourceExtensions> | undefined;
/**
* @param from - the SQL for the `FROM` clause (without any
* aliasing). If this is a subquery don't forget to wrap it in parens.
* @param name - a nickname for this resource. Doesn't need to be unique
* (but should be). Used for making the SQL query and debug messages easier
* to understand.
*/
constructor(
registry: TRegistry,
options: PgResourceOptions<TName, TCodec, TUniques, TParameters>,
) {
const {
codec,
executor,
name,
identifier,
from,
uniques,
extensions,
parameters,
description,
isUnique,
sqlPartitionByIndex,
isMutation,
selectAuth,
isList,
isVirtual,
} = options;
this.registry = registry;
this.extensions = extensions;
this.codec = codec;
this.executor = executor;
this.name = name;
this.identifier = identifier ?? name;
this.from = from;
this.uniques = uniques ?? ([] as never);
this.parameters = parameters ?? ([] as never);
this.description = description;
this.isUnique = !!isUnique;
this.sqlPartitionByIndex = sqlPartitionByIndex ?? null;
this.isMutation = !!isMutation;
this.isList = !!isList;
this.isVirtual = isVirtual ?? false;
this.selectAuth = selectAuth;
// parameters is null iff from is not a function
const sourceIsFunction = typeof this.from === "function";
if (this.parameters == null && sourceIsFunction) {
throw new Error(
`Resource ${this} is invalid - it's a function but without a parameters array. If the function accepts no parameters please pass an empty array.`,
);
}
if (this.parameters != null && !sourceIsFunction) {
throw new Error(
`Resource ${this} is invalid - parameters can only be specified when the resource is a function.`,
);
}
if (this.codec.arrayOfCodec?.attributes) {
throw new Error(
`Resource ${this} is invalid - creating a resource that returns an array of a composite type is forbidden; please \`unnest\` the array.`,
);
}
if (this.isUnique && this.sqlPartitionByIndex) {
throw new Error(
`Resource ${this} is invalid - cannot be unique and also partitionable`,
);
}
}
/**
* Often you can access table records from a table directly but also from a
* view or materialized view. This method makes it convenient to construct
* multiple datasources that all represent the same underlying table
* type/relations/etc.
*/
static alternativeResourceOptions<
TCodec extends _AnyPgCodec,
const TNewUniques extends PgResourceUnique<PgCodecAttributes<TCodec>>,
const TNewName extends string,
>(
baseOptions: PgResourceOptions<any, TCodec, any, never>,
overrideOptions: {
name: TNewName;
identifier?: string;
from: SQL;
uniques?: [TNewUniques] extends [never]
? never
: ReadonlyArray<TNewUniques>;
extensions?: DataplanPg.PgResourceExtensions;
},
): PgResourceOptions<TNewName, TCodec, TNewUniques, never> {
const { name, identifier, from, uniques, extensions } = overrideOptions;
const { codec, executor, selectAuth } = baseOptions;
return {
codec,
executor,
name,
identifier,
from,
uniques,
extensions,
selectAuth,
};
}
/**
* Often you can access table records from a table directly but also from a
* number of functions. This method makes it convenient to construct multiple
* datasources that all represent the same underlying table
* type/relations/etc but pull their rows from functions.
*/
static functionResourceOptions<
TCodec extends _AnyPgCodec,
const TNewParameters extends _AnyPgResourceParameter,
const TNewUniques extends PgResourceUnique<PgCodecAttributes<TCodec>>,
const TNewName extends string,
>(
baseOptions: Pick<
PgResourceOptions<any, TCodec, any, any>,
"codec" | "executor" | "selectAuth"
>,
overrideOptions: PgFunctionResourceOptions<
TNewName,
TCodec,
TNewUniques,
TNewParameters
>,
): PgResourceOptions<TNewName, TCodec, TNewUniques, TNewParameters> {
const { codec, executor, selectAuth } = baseOptions;
const {
name,
identifier,
from: fnFrom,
parameters,
returnsSetof,
returnsArray,
uniques,
extensions,
isMutation,
selectAuth: overrideSelectAuth,
description,
} = overrideOptions;
if (!returnsArray) {
// This is the easy case
return {
codec,
executor,
name,
identifier,
from: fnFrom as any,
uniques,
parameters,
extensions,
isUnique: !returnsSetof,
isMutation: Boolean(isMutation),
selectAuth: overrideSelectAuth ?? selectAuth,
description,
};
} else if (!returnsSetof) {
// This is a `composite[]` function; convert it to a `setof composite` function:
const from = EXPORTABLE(
(fnFrom, sql) =>
(...args: PgSelectArgumentDigest[]) =>
sql`unnest(${fnFrom(...args)})`,
[fnFrom, sql],
);
return {
codec,
executor,
name,
identifier,
from: from as any,
uniques,
parameters,
extensions,
isUnique: false, // set now, not unique
isMutation: Boolean(isMutation),
selectAuth: overrideSelectAuth ?? selectAuth,
isList: true,
description,
};
} else {
// This is a `setof composite[]` function; convert it to `setof composite` and indicate that we should partition it.
const sqlTmp = sql.identifier(Symbol(`${name}_tmp`));
const sqlPartitionByIndex = sql.identifier(Symbol(`${name}_idx`));
const from = EXPORTABLE(
(fnFrom, sql, sqlPartitionByIndex, sqlTmp) =>
(...args: PgSelectArgumentDigest[]) =>
sql`${fnFrom(
...args,
)} with ordinality as ${sqlTmp} (arr, ${sqlPartitionByIndex}) cross join lateral unnest (${sqlTmp}.arr)`,
[fnFrom, sql, sqlPartitionByIndex, sqlTmp],
);
return {
codec,
executor,
name,
identifier,
from: from as any,
uniques,
parameters,
extensions,
isUnique: false, // set now, not unique
sqlPartitionByIndex,
isMutation: Boolean(isMutation),
selectAuth: overrideSelectAuth ?? selectAuth,
description,
};
}
}
public toString(): string {
return chalk.bold.blue(`PgResource(${this.name})`);
}
public getRelations(): GetPgRegistryCodecRelations<TRegistry, TCodec> {
return (this.registry.pgRelations[this.codec.name] ??
Object.create(null)) as any;
}
public getRelation<
TRelationName extends PgCodecRelationConfigName<
GetPgRegistryCodecRelationConfigs<TRegistry, TCodec>
>,
>(
name: TRelationName,
): GetPgRegistryCodecRelations<TRegistry, TCodec>[TRelationName] {
return this.getRelations()[name];
}
public resolveVia<
TRelationName extends PgCodecRelationConfigName<
GetPgRegistryCodecRelationConfigs<TRegistry, TCodec>
>,
TAttribute extends string,
>(
via: PgCodecAttributeVia<TRelationName, TAttribute>,
attr: TAttribute,
): PgCodecAttributeViaExplicit<TRelationName, TAttribute> {
if (!via) {
throw new Error("No via to resolve");
}
if (typeof via === "string") {
// Check
const relation = this.getRelation(via);
if (!relation) {
throw new Error(`Unknown relation '${via}' in ${this}`);
}
if (!relation.remoteResource.codec.attributes![attr]) {
throw new Error(
`${this} relation '${via}' does not have attribute '${attr}'`,
);
}
return { relation: via, attribute: attr };
} else {
return via;
}
}
// PERF: this needs optimization.
public getReciprocal<
TOtherCodec extends GetPgRegistryCodecs<TRegistry>,
TOtherRelationName extends GetPgRegistryCodecRelationConfigs<
TRegistry,
TOtherCodec
>["name"],
>(
otherCodec: TOtherCodec,
otherRelationName: TOtherRelationName,
):
| [
relationName: GetPgRegistryCodecRelationConfigs<
TRegistry,
TCodec
>["name"],
relation: GetPgRegistryCodecRelationConfigs<TRegistry, TCodec>,
]
| null {
if (this.parameters) {
throw new Error(
".getReciprocal() cannot be used with functional resources; please use .execute()",
);
}
const otherRelation =
this.registry.pgRelations[otherCodec.name]?.[otherRelationName];
const relations = this.getRelations();
const reciprocal = Object.entries(relations).find(
([_relationName, relation]) => {
if (relation.remoteResource.codec !== otherCodec) {
return false;
}
if (
!arraysMatch(relation.localAttributes, otherRelation.remoteAttributes)
) {
return false;
}
if (
!arraysMatch(relation.remoteAttributes, otherRelation.localAttributes)
) {
return false;
}
return true;
},
);
// TODO: this is still a bit tricky, :-(, but we're almost here!
return (reciprocal as [any, any]) || null;
}
public get<
TSelectSinglePlanOptions extends PgSelectSinglePlanOptions<this>,
TSpec extends Expand<PlanByUniques<PgCodecAttributes<TCodec>, TUniques>>,
>(
spec: TSpec,
// This is internal, it's an optimisation we can use but you shouldn't.
_internalOptionsDoNotPass?: TSelectSinglePlanOptions,
): PgSelectSingleStep<this>;
public get<
TSelectSinglePlanOptions extends PgSelectSinglePlanOptions<this>,
TSpec extends Expand<PlanByUniques<PgCodecAttributes<TCodec>, TUniques>>,
>(
spec: TSpec,
// This is internal, it's an optimisation we can use but you shouldn't.
_internalOptionsDoNotPass?: TSelectSinglePlanOptions,
): PgClassExpressionStep<TCodec, this>;
public get<
TSelectSinglePlanOptions extends PgSelectSinglePlanOptions<this>,
TSpec extends Expand<PlanByUniques<PgCodecAttributes<TCodec>, TUniques>>,
>(
spec: TSpec,
// This is internal, it's an optimisation we can use but you shouldn't.
_internalOptionsDoNotPass?: TSelectSinglePlanOptions,
): PgClassExpressionStep<TCodec, this> | PgSelectSingleStep<this> {
if (this.parameters) {
throw new Error(
".get() cannot be used with functional resources; please use .execute()",
);
}
if (!spec) {
throw new Error(`Cannot ${this}.get without a valid spec`);
}
const keys = Object.keys(spec);
if (
!this.uniques.some((uniq: _AnyPgResourceUnique) =>
uniq.attributes.every((key) => keys.includes(key)),
)
) {
throw new Error(
`Attempted to call ${this}.get({${keys.join(
", ",
)}}) at child field (TODO: which one?) but that combination of attributes is not unique (uniques: ${JSON.stringify(
this.uniques,
)}). Did you mean to call .find() instead?`,
);
}
return this.find(spec).single(_internalOptionsDoNotPass);
}
public find(
spec: {
[attribute in PgCodecAttributes<TCodec> as PgCodecAttributeName<attribute>]?:
| ExecutableStep
| string
| number;
} = Object.create(null),
): PgSelectStep<this> {
if (this.parameters) {
throw new Error(
".get() cannot be used with functional resources; please use .execute()",
);
}
if (!this.codec.attributes) {
throw new Error("Cannot call find if there's no attributes");
}
const attributes = this.codec.attributes;
const keys = Object.keys(spec) as Array<
PgCodecAttributeName<PgCodecAttributes<TCodec>>
>;
const invalidKeys = keys.filter((key) => attributes[key] == null);
if (invalidKeys.length > 0) {
throw new Error(
`Attempted to call ${this}.get({${keys.join(
", ",
)}}) but that request included attributes that we don't know about: '${invalidKeys.join(
"', '",
)}'`,
);
}
const identifiers = keys.map((key): PgSelectIdentifierSpec => {
const attribute = attributes[key];
if ("via" in attribute && attribute.via) {
throw new Error(
`Attribute '${String(
key,
)}' is defined with a 'via' and thus cannot be used as an identifier for '.find()' or '.get()' calls (requested keys: '${keys.join(
"', '",
)}').`,
);
}
const { codec } = attribute;
const stepOrConstant = spec[key];
if (stepOrConstant == undefined) {
throw new Error(
`Attempted to call ${this}.find({${keys.join(
", ",
)}}) but failed to provide a plan for '${String(key)}'`,
);
}
return {
step:
stepOrConstant instanceof ExecutableStep
? stepOrConstant
: constant(stepOrConstant, false),
codec,
matches: (alias: SQL) =>
typeof attribute.expression === "function"
? attribute.expression(alias)
: sql`${alias}.${sql.identifier(key)}`,
};
});
return pgSelect({ resource: this, identifiers });
}
execute(
args: Array<PgSelectArgumentSpec> = [],
mode: PgSelectMode = this.isMutation ? "mutation" : "normal",
): ExecutableStep<unknown> {
const $select = pgSelect({
resource: this,
identifiers: [],
args,
mode,
});
if (this.isUnique) {
return $select.single();
}
const sqlPartitionByIndex = this.sqlPartitionByIndex;
if (sqlPartitionByIndex) {
// We're a setof array of composite type function, e.g. `setof users[]`, so we need to reconstitute the plan.
return partitionByIndex(
$select,
($row) =>
($row as PgSelectSingleStep<any>).select(
sqlPartitionByIndex,
TYPES.int,
),
// Ordinality is 1-indexed but we want a 0-indexed number
1,
);
} else {
return $select;
}
}
public applyAuthorizationChecksToPlan($step: PgSelectStep<this>): void {
if (this.selectAuth) {
this.selectAuth($step as any);
}
// e.g. $step.where(sql`user_id = ${me}`);
return;
}
/**
* @deprecated Please use `.executor.context()` instead - all resources for the
* same executor must use the same context to allow for SQL inlining, unions,
* etc.
*/
public context(): ObjectStep<PgExecutorContextPlans> {
return this.executor.context();
}
/** @internal */
public executeWithCache<TInput = any, TOutput = any>(
values: GrafastValuesList<PgExecutorInput<TInput>>,
options: PgExecutorOptions,
): Promise<{ values: GrafastValuesList<ReadonlyArray<TOutput>> }> {
return this.executor.executeWithCache(values, options);
}
/** @internal */
public executeWithoutCache<TInput = any, TOutput = any>(
values: GrafastValuesList<PgExecutorInput<TInput>>,
options: PgExecutorOptions,
): Promise<{ values: GrafastValuesList<ReadonlyArray<TOutput>> }> {
return this.executor.executeWithoutCache(values, options);
}
/** @internal */
public executeStream<TInput = any, TOutput = any>(
values: GrafastValuesList<PgExecutorInput<TInput>>,
options: PgExecutorOptions,
) {
return this.executor.executeStream<TInput, TOutput>(values, options);
}
/** @internal */
public executeMutation<TData>(
options: PgExecutorMutationOptions,
): Promise<PgClientResult<TData>> {
return this.executor.executeMutation<TData>(options);
}
/**
* Returns an SQL fragment that evaluates to `'true'` (string) if the row is
* non-null and `'false'` or `null` otherwise.
*
* @see {@link PgCodec.notNullExpression}
*
* @internal
*/
public getNullCheckExpression(alias: SQL): SQL | null {
if (this.codec.notNullExpression) {
// Use the user-provided check
return this.codec.notNullExpression(alias);
} else {
// Every column in a primary key is non-nullable; so just see if one is null
const pk = this.uniques.find((u) => u.isPrimary);
const nonNullableAttribute = this.codec.attributes
? Object.entries(
this.codec.attributes as Record<string, _AnyPgCodecAttribute>,
).find(
([_attributeName, spec]) =>
!spec.via && !spec.expression && spec.notNull,
)?.[0]
: null ?? pk?.attributes[0];
if (nonNullableAttribute) {
const firstAttribute = sql`${alias}.${sql.identifier(
nonNullableAttribute,
)}`;
return sql`(not (${firstAttribute} is null))::text`;
} else {
// Fallback
// NOTE: we cannot use `is distinct from null` here because it's
// commonly used for `select * from ((select my_table.composite).*)`
// and the rows there _are_ distinct from null even if the underlying
// data is not.
return sql`(not (${alias} is null))::text`;
}
}
}
}
exportAs("@dataplan/pg", PgResource, "PgResource");
/** @internal */
export interface _AnyPgRegistryBuilder
extends PgRegistryBuilder<any, any, any> {}
export interface EmptyRegistryBuilder
extends PgRegistryBuilder<never, never, never> {}
export interface DefaultRegistryBuilder
extends PgRegistryBuilder<
GenericPgCodec,
GenericPgResourceOptions,
GenericPgCodecRelationConfig
> {}
export interface PgRegistryBuilder<
TCodecs extends _AnyPgCodec,
TResourceOptions extends _AnyPgResourceOptions,
TRelationConfigs extends _AnyPgCodecRelationConfig,
> {
getRegistryConfig(): PgRegistryConfig<
TCodecs,
TResourceOptions,
TRelationConfigs
>;
addCodec<const TCodec extends _AnyPgCodec>(
codec: TCodec,
): PgRegistryBuilder<TCodecs | TCodec, TResourceOptions, TRelationConfigs>;
addResource<const TResourceOption extends _AnyPgResourceOptions>(
resource: TResourceOption,
): PgRegistryBuilder<
TCodecs | PgResourceOptionCodec<TResourceOption>,
TResourceOptions | TResourceOption,
TRelationConfigs
>;