@cloudbase/wx-cloud-client-sdk 1.6.1 → 1.7.1

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.
@@ -0,0 +1,33 @@
1
+ import type { GenericRelationship, GenericSchema, GenericTable, Prettify } from "../types";
2
+ export type { GenericRelationship, GenericSchema, GenericTable, Prettify };
3
+ export type AggregateWithoutColumnFunctions = "count";
4
+ export type AggregateWithColumnFunctions = "sum" | "avg" | "min" | "max" | AggregateWithoutColumnFunctions;
5
+ export type AggregateFunctions = AggregateWithColumnFunctions;
6
+ export type Json = string | number | boolean | null | {
7
+ [key: string]: Json | undefined;
8
+ } | Json[];
9
+ type PostgresSQLNumberTypes = "int2" | "int4" | "int8" | "float4" | "float8" | "numeric";
10
+ type PostgresSQLStringTypes = "bytea" | "bpchar" | "varchar" | "date" | "text" | "citext" | "time" | "timetz" | "timestamp" | "timestamptz" | "uuid" | "vector";
11
+ type SingleValuePostgreSQLTypes = PostgresSQLNumberTypes | PostgresSQLStringTypes | "bool" | "json" | "jsonb" | "void" | "record" | string;
12
+ type ArrayPostgreSQLTypes = `_${SingleValuePostgreSQLTypes}`;
13
+ type TypeScriptSingleValueTypes<T extends SingleValuePostgreSQLTypes> = T extends "bool" ? boolean : T extends PostgresSQLNumberTypes ? number : T extends PostgresSQLStringTypes ? string : T extends "json" | "jsonb" ? Json : T extends "void" ? undefined : T extends "record" ? Record<string, unknown> : unknown;
14
+ type StripUnderscore<T extends string> = T extends `_${infer U}` ? U : T;
15
+ export type PostgreSQLTypes = SingleValuePostgreSQLTypes | ArrayPostgreSQLTypes;
16
+ export type TypeScriptTypes<T extends PostgreSQLTypes> = T extends ArrayPostgreSQLTypes ? TypeScriptSingleValueTypes<StripUnderscore<Extract<T, SingleValuePostgreSQLTypes>>>[] : TypeScriptSingleValueTypes<T>;
17
+ export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
18
+ export type LastOf<T> = UnionToIntersection<T extends any ? () => T : never> extends () => infer R ? R : never;
19
+ export type Push<T extends any[], V> = [...T, V];
20
+ export type UnionToTuple<T, L = LastOf<T>, N = [T] extends [never] ? true : false> = N extends true ? [] : Push<UnionToTuple<Exclude<T, L>>, L>;
21
+ export type UnionToArray<T> = UnionToTuple<T>;
22
+ export type ExtractFirstProperty<T> = T extends {
23
+ [K in keyof T]: infer U;
24
+ } ? U : never;
25
+ export type ContainsNull<T> = null extends T ? true : false;
26
+ export type IsNonEmptyArray<T> = Exclude<T, undefined> extends readonly [
27
+ unknown,
28
+ ...unknown[]
29
+ ] ? true : false;
30
+ export type TablesAndViews<Schema extends GenericSchema> = Schema["Tables"] & Exclude<Schema["Views"], "">;
31
+ export type GetTableRelationships<Schema extends GenericSchema, Tname extends string> = TablesAndViews<Schema>[Tname] extends {
32
+ Relationships: infer R;
33
+ } ? R : false;
@@ -0,0 +1,266 @@
1
+ import { Ast } from "./parser";
2
+ import { AggregateFunctions, ContainsNull, GenericRelationship, GenericSchema, GenericTable, IsNonEmptyArray, TablesAndViews, UnionToArray } from "./types";
3
+ export type IsAny<T> = 0 extends 1 & T ? true : false;
4
+ export type SelectQueryError<Message extends string> = {
5
+ error: true;
6
+ } & Message;
7
+ export type DeduplicateRelationships<T extends readonly unknown[]> = T extends readonly [infer First, ...infer Rest] ? First extends Rest[number] ? DeduplicateRelationships<Rest extends readonly unknown[] ? Rest : []> : [
8
+ First,
9
+ ...DeduplicateRelationships<Rest extends readonly unknown[] ? Rest : []>
10
+ ] : T;
11
+ export type GetFieldNodeResultName<Field extends Ast.FieldNode> = Field["alias"] extends string ? Field["alias"] : Field["aggregateFunction"] extends AggregateFunctions ? Field["aggregateFunction"] : Field["name"];
12
+ type FilterRelationNodes<Nodes extends Ast.Node[]> = UnionToArray<{
13
+ [K in keyof Nodes]: Nodes[K] extends Ast.SpreadNode ? Nodes[K]["target"] : Nodes[K] extends Ast.FieldNode ? IsNonEmptyArray<Nodes[K]["children"]> extends true ? Nodes[K] : never : never;
14
+ }[number]>;
15
+ type ResolveRelationships<Schema extends GenericSchema, RelationName extends string, Relationships extends GenericRelationship[], Nodes extends Ast.FieldNode[]> = UnionToArray<{
16
+ [K in keyof Nodes]: Nodes[K] extends Ast.FieldNode ? ResolveRelationship<Schema, Relationships, Nodes[K], RelationName> extends infer Relation ? Relation extends {
17
+ relation: {
18
+ referencedRelation: string;
19
+ foreignKeyName: string;
20
+ match: string;
21
+ };
22
+ from: string;
23
+ } ? {
24
+ referencedTable: Relation["relation"]["referencedRelation"];
25
+ fkName: Relation["relation"]["foreignKeyName"];
26
+ from: Relation["from"];
27
+ match: Relation["relation"]["match"];
28
+ fieldName: GetFieldNodeResultName<Nodes[K]>;
29
+ } : Relation : never : never;
30
+ }>[0];
31
+ /**
32
+ * Checks if a relation is implicitly referenced twice, requiring disambiguation
33
+ */
34
+ type IsDoubleReference<T, U> = T extends {
35
+ referencedTable: infer RT;
36
+ fieldName: infer FN;
37
+ match: infer M;
38
+ } ? M extends "col" | "refrel" ? U extends {
39
+ referencedTable: RT;
40
+ fieldName: FN;
41
+ match: M;
42
+ } ? true : false : false : false;
43
+ /**
44
+ * Compares one element with all other elements in the array to find duplicates
45
+ */
46
+ type CheckDuplicates<Arr extends any[], Current> = Arr extends [
47
+ infer Head,
48
+ ...infer Tail
49
+ ] ? IsDoubleReference<Current, Head> extends true ? Head | CheckDuplicates<Tail, Current> : CheckDuplicates<Tail, Current> : never;
50
+ /**
51
+ * Iterates over the elements of the array to find duplicates
52
+ */
53
+ type FindDuplicatesWithinDeduplicated<Arr extends any[]> = Arr extends [
54
+ infer Head,
55
+ ...infer Tail
56
+ ] ? CheckDuplicates<Tail, Head> | FindDuplicatesWithinDeduplicated<Tail> : never;
57
+ type FindDuplicates<Arr extends any[]> = FindDuplicatesWithinDeduplicated<DeduplicateRelationships<Arr>>;
58
+ export type CheckDuplicateEmbededReference<Schema extends GenericSchema, RelationName extends string, Relationships extends GenericRelationship[], Nodes extends Ast.Node[]> = FilterRelationNodes<Nodes> extends infer RelationsNodes ? RelationsNodes extends Ast.FieldNode[] ? ResolveRelationships<Schema, RelationName, Relationships, RelationsNodes> extends infer ResolvedRels ? ResolvedRels extends unknown[] ? FindDuplicates<ResolvedRels> extends infer Duplicates ? Duplicates extends never ? false : Duplicates extends {
59
+ fieldName: infer FieldName;
60
+ } ? FieldName extends string ? {
61
+ [K in FieldName]: SelectQueryError<`table "${RelationName}" specified more than once use hinting for desambiguation`>;
62
+ } : false : false : false : false : false : false : false;
63
+ /**
64
+ * Returns a boolean representing whether there is a foreign key referencing
65
+ * a given relation.
66
+ */
67
+ type HasFKeyToFRel<FRelName, Relationships> = Relationships extends [infer R] ? R extends {
68
+ referencedRelation: FRelName;
69
+ } ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKeyToFRel<FRelName, [R]> extends true ? true : HasFKeyToFRel<FRelName, Rest> : false;
70
+ /**
71
+ * Checks if there is more than one relation to a given foreign relation name in the Relationships.
72
+ */
73
+ type HasMultipleFKeysToFRelDeduplicated<FRelName, Relationships> = Relationships extends [infer R, ...infer Rest] ? R extends {
74
+ referencedRelation: FRelName;
75
+ } ? HasFKeyToFRel<FRelName, Rest> extends true ? true : HasMultipleFKeysToFRelDeduplicated<FRelName, Rest> : HasMultipleFKeysToFRelDeduplicated<FRelName, Rest> : false;
76
+ type HasMultipleFKeysToFRel<FRelName, Relationships extends unknown[]> = HasMultipleFKeysToFRelDeduplicated<FRelName, DeduplicateRelationships<Relationships>>;
77
+ type CheckRelationshipError<Schema extends GenericSchema, Relationships extends GenericRelationship[], CurrentTableOrView extends keyof TablesAndViews<Schema> & string, FoundRelation> = FoundRelation extends SelectQueryError<string> ? FoundRelation : FoundRelation extends {
78
+ relation: {
79
+ referencedRelation: infer RelatedRelationName;
80
+ name: string;
81
+ };
82
+ direction: "reverse";
83
+ } ? RelatedRelationName extends string ? HasMultipleFKeysToFRel<RelatedRelationName, Relationships> extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}!<columnName> ?`> : FoundRelation : never : FoundRelation extends {
84
+ relation: {
85
+ referencedRelation: infer RelatedRelationName;
86
+ name: string;
87
+ };
88
+ direction: "forward";
89
+ from: infer From;
90
+ } ? RelatedRelationName extends string ? From extends keyof TablesAndViews<Schema> & string ? HasMultipleFKeysToFRel<RelatedRelationName, TablesAndViews<Schema>[From]["Relationships"]> extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${From}' and '${RelatedRelationName}' you need to hint the column with ${From}!<columnName> ?`> : FoundRelation : never : never : FoundRelation;
91
+ /**
92
+ * Resolves relationships for embedded resources and retrieves the referenced Table
93
+ */
94
+ export type ResolveRelationship<Schema extends GenericSchema, Relationships extends GenericRelationship[], Field extends Ast.FieldNode, CurrentTableOrView extends keyof TablesAndViews<Schema> & string> = ResolveReverseRelationship<Schema, Relationships, Field, CurrentTableOrView> extends infer ReverseRelationship ? ReverseRelationship extends false ? CheckRelationshipError<Schema, Relationships, CurrentTableOrView, ResolveForwardRelationship<Schema, Field, CurrentTableOrView>> : CheckRelationshipError<Schema, Relationships, CurrentTableOrView, ReverseRelationship> : never;
95
+ /**
96
+ * Resolves reverse relationships (from children to parent)
97
+ */
98
+ type ResolveReverseRelationship<Schema extends GenericSchema, Relationships extends GenericRelationship[], Field extends Ast.FieldNode, CurrentTableOrView extends keyof TablesAndViews<Schema> & string> = FindFieldMatchingRelationships<Schema, Relationships, Field> extends infer FoundRelation ? FoundRelation extends never ? false : FoundRelation extends {
99
+ referencedRelation: infer RelatedRelationName;
100
+ } ? RelatedRelationName extends string ? RelatedRelationName extends keyof TablesAndViews<Schema> ? FoundRelation extends {
101
+ hint: string;
102
+ } ? {
103
+ referencedTable: TablesAndViews<Schema>[RelatedRelationName];
104
+ relation: FoundRelation;
105
+ direction: "reverse";
106
+ from: CurrentTableOrView;
107
+ } : HasMultipleFKeysToFRel<RelatedRelationName, Relationships> extends true ? SelectQueryError<`Could not embed because more than one relationship was found for '${RelatedRelationName}' and '${CurrentTableOrView}' you need to hint the column with ${RelatedRelationName}!<columnName> ?`> : {
108
+ referencedTable: TablesAndViews<Schema>[RelatedRelationName];
109
+ relation: FoundRelation;
110
+ direction: "reverse";
111
+ from: CurrentTableOrView;
112
+ } : SelectQueryError<`Relation '${RelatedRelationName}' not found in schema.`> : false : false : false;
113
+ export type FindMatchingTableRelationships<Schema extends GenericSchema, Relationships extends GenericRelationship[], value extends string> = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends {
114
+ referencedRelation: infer ReferencedRelation;
115
+ } ? ReferencedRelation extends keyof Schema["Tables"] ? R extends {
116
+ foreignKeyName: value;
117
+ } ? R & {
118
+ match: "fkname";
119
+ } : R extends {
120
+ referencedRelation: value;
121
+ } ? R & {
122
+ match: "refrel";
123
+ } : R extends {
124
+ columns: [value];
125
+ } ? R & {
126
+ match: "col";
127
+ } : FindMatchingTableRelationships<Schema, Rest, value> : FindMatchingTableRelationships<Schema, Rest, value> : false : false : false;
128
+ export type FindMatchingViewRelationships<Schema extends GenericSchema, Relationships extends GenericRelationship[], value extends string> = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends {
129
+ referencedRelation: infer ReferencedRelation;
130
+ } ? ReferencedRelation extends keyof Schema["Views"] ? R extends {
131
+ foreignKeyName: value;
132
+ } ? R & {
133
+ match: "fkname";
134
+ } : R extends {
135
+ referencedRelation: value;
136
+ } ? R & {
137
+ match: "refrel";
138
+ } : R extends {
139
+ columns: [value];
140
+ } ? R & {
141
+ match: "col";
142
+ } : FindMatchingViewRelationships<Schema, Rest, value> : FindMatchingViewRelationships<Schema, Rest, value> : false : false : false;
143
+ export type FindMatchingHintTableRelationships<Schema extends GenericSchema, Relationships extends GenericRelationship[], hint extends string, name extends string> = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends {
144
+ referencedRelation: infer ReferencedRelation;
145
+ } ? ReferencedRelation extends name ? R extends {
146
+ foreignKeyName: hint;
147
+ } ? R & {
148
+ match: "fkname";
149
+ } : R extends {
150
+ referencedRelation: hint;
151
+ } ? R & {
152
+ match: "refrel";
153
+ } : R extends {
154
+ columns: [hint];
155
+ } ? R & {
156
+ match: "col";
157
+ } : FindMatchingHintTableRelationships<Schema, Rest, hint, name> : FindMatchingHintTableRelationships<Schema, Rest, hint, name> : false : false : false;
158
+ export type FindMatchingHintViewRelationships<Schema extends GenericSchema, Relationships extends GenericRelationship[], hint extends string, name extends string> = Relationships extends [infer R, ...infer Rest] ? Rest extends GenericRelationship[] ? R extends {
159
+ referencedRelation: infer ReferencedRelation;
160
+ } ? ReferencedRelation extends name ? R extends {
161
+ foreignKeyName: hint;
162
+ } ? R & {
163
+ match: "fkname";
164
+ } : R extends {
165
+ referencedRelation: hint;
166
+ } ? R & {
167
+ match: "refrel";
168
+ } : R extends {
169
+ columns: [hint];
170
+ } ? R & {
171
+ match: "col";
172
+ } : FindMatchingHintViewRelationships<Schema, Rest, hint, name> : FindMatchingHintViewRelationships<Schema, Rest, hint, name> : false : false : false;
173
+ type IsColumnsNullable<Table extends Pick<GenericTable, "Row">, Columns extends (keyof Table["Row"])[]> = Columns extends [infer Column, ...infer Rest] ? Column extends keyof Table["Row"] ? ContainsNull<Table["Row"][Column]> extends true ? true : IsColumnsNullable<Table, Rest extends (keyof Table["Row"])[] ? Rest : []> : false : false;
174
+ export type IsRelationNullable<Table extends GenericTable, Relation extends GenericRelationship> = IsColumnsNullable<Table, Relation["columns"]>;
175
+ type TableForwardRelationships<Schema extends GenericSchema, TName> = TName extends keyof TablesAndViews<Schema> ? UnionToArray<RecursivelyFindRelationships<Schema, TName, keyof TablesAndViews<Schema>>> extends infer R ? R extends (GenericRelationship & {
176
+ from: keyof TablesAndViews<Schema>;
177
+ })[] ? R : [] : [] : [];
178
+ type RecursivelyFindRelationships<Schema extends GenericSchema, TName, Keys extends keyof TablesAndViews<Schema>> = Keys extends infer K ? K extends keyof TablesAndViews<Schema> ? FilterRelationships<TablesAndViews<Schema>[K]["Relationships"], TName, K> extends never ? RecursivelyFindRelationships<Schema, TName, Exclude<Keys, K>> : FilterRelationships<TablesAndViews<Schema>[K]["Relationships"], TName, K> | RecursivelyFindRelationships<Schema, TName, Exclude<Keys, K>> : false : false;
179
+ type FilterRelationships<R, TName, From> = R extends readonly (infer Rel)[] ? Rel extends {
180
+ referencedRelation: TName;
181
+ } ? Rel & {
182
+ from: From;
183
+ } : never : never;
184
+ export type ResolveForwardRelationship<Schema extends GenericSchema, Field extends Ast.FieldNode, CurrentTableOrView extends keyof TablesAndViews<Schema> & string> = FindFieldMatchingRelationships<Schema, TablesAndViews<Schema>[Field["name"]]["Relationships"], Ast.FieldNode & {
185
+ name: CurrentTableOrView;
186
+ hint: Field["hint"];
187
+ }> extends infer FoundByName ? FoundByName extends GenericRelationship ? {
188
+ referencedTable: TablesAndViews<Schema>[Field["name"]];
189
+ relation: FoundByName;
190
+ direction: "forward";
191
+ from: Field["name"];
192
+ type: "found-by-name";
193
+ } : FindFieldMatchingRelationships<Schema, TableForwardRelationships<Schema, CurrentTableOrView>, Field> extends infer FoundByMatch ? FoundByMatch extends GenericRelationship & {
194
+ from: keyof TablesAndViews<Schema>;
195
+ } ? {
196
+ referencedTable: TablesAndViews<Schema>[FoundByMatch["from"]];
197
+ relation: FoundByMatch;
198
+ direction: "forward";
199
+ from: CurrentTableOrView;
200
+ type: "found-by-match";
201
+ } : FindJoinTableRelationship<Schema, CurrentTableOrView, Field["name"]> extends infer FoundByJoinTable ? FoundByJoinTable extends GenericRelationship ? {
202
+ referencedTable: TablesAndViews<Schema>[FoundByJoinTable["referencedRelation"]];
203
+ relation: FoundByJoinTable & {
204
+ match: "refrel";
205
+ };
206
+ direction: "forward";
207
+ from: CurrentTableOrView;
208
+ type: "found-by-join-table";
209
+ } : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field["name"]}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field["name"]}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field["name"]}`> : SelectQueryError<`could not find the relation between ${CurrentTableOrView} and ${Field["name"]}`>;
210
+ /**
211
+ * Given a CurrentTableOrView, finds all join tables to this relation.
212
+ * For example, if products and categories are linked via product_categories table:
213
+ *
214
+ * @example
215
+ * Given:
216
+ * - CurrentTableView = 'products'
217
+ * - FieldName = "categories"
218
+ *
219
+ * It should return this relationship from product_categories:
220
+ * {
221
+ * foreignKeyName: "product_categories_category_id_fkey",
222
+ * columns: ["category_id"],
223
+ * isOneToOne: false,
224
+ * referencedRelation: "categories",
225
+ * referencedColumns: ["id"]
226
+ * }
227
+ */
228
+ type ResolveJoinTableRelationship<Schema extends GenericSchema, CurrentTableOrView extends keyof TablesAndViews<Schema> & string, FieldName extends string> = {
229
+ [TableName in keyof TablesAndViews<Schema>]: DeduplicateRelationships<TablesAndViews<Schema>[TableName]["Relationships"]> extends readonly (infer Rel)[] ? Rel extends {
230
+ referencedRelation: CurrentTableOrView;
231
+ } ? DeduplicateRelationships<TablesAndViews<Schema>[TableName]["Relationships"]> extends readonly (infer OtherRel)[] ? OtherRel extends {
232
+ referencedRelation: FieldName;
233
+ } ? OtherRel : never : never : never : never;
234
+ }[keyof TablesAndViews<Schema>];
235
+ export type FindJoinTableRelationship<Schema extends GenericSchema, CurrentTableOrView extends keyof TablesAndViews<Schema> & string, FieldName extends string> = ResolveJoinTableRelationship<Schema, CurrentTableOrView, FieldName> extends infer Result ? [Result] extends [never] ? false : Result : never;
236
+ /**
237
+ * Finds a matching relationship based on the FieldNode's name and optional hint.
238
+ */
239
+ export type FindFieldMatchingRelationships<Schema extends GenericSchema, Relationships extends GenericRelationship[], Field extends Ast.FieldNode> = Field extends {
240
+ hint: string;
241
+ } ? FindMatchingHintTableRelationships<Schema, Relationships, Field["hint"], Field["name"]> extends GenericRelationship ? FindMatchingHintTableRelationships<Schema, Relationships, Field["hint"], Field["name"]> & {
242
+ branch: "found-in-table-via-hint";
243
+ hint: Field["hint"];
244
+ } : FindMatchingHintViewRelationships<Schema, Relationships, Field["hint"], Field["name"]> extends GenericRelationship ? FindMatchingHintViewRelationships<Schema, Relationships, Field["hint"], Field["name"]> & {
245
+ branch: "found-in-view-via-hint";
246
+ hint: Field["hint"];
247
+ } : SelectQueryError<"Failed to find matching relation via hint"> : FindMatchingTableRelationships<Schema, Relationships, Field["name"]> extends GenericRelationship ? FindMatchingTableRelationships<Schema, Relationships, Field["name"]> & {
248
+ branch: "found-in-table-via-name";
249
+ name: Field["name"];
250
+ } : FindMatchingViewRelationships<Schema, Relationships, Field["name"]> extends GenericRelationship ? FindMatchingViewRelationships<Schema, Relationships, Field["name"]> & {
251
+ branch: "found-in-view-via-name";
252
+ name: Field["name"];
253
+ } : SelectQueryError<"Failed to find matching relation via name">;
254
+ export type JsonPathToAccessor<Path extends string> = Path extends `${infer P1}->${infer P2}` ? P2 extends `>${infer Rest}` ? JsonPathToAccessor<`${P1}.${Rest}`> : P2 extends string ? JsonPathToAccessor<`${P1}.${P2}`> : Path : Path extends `>${infer Rest}` ? JsonPathToAccessor<Rest> : Path extends `${infer P1}::${infer _}` ? JsonPathToAccessor<P1> : Path extends `${infer P1}${")" | ","}${infer _}` ? P1 : Path;
255
+ export type JsonPathToType<T, Path extends string> = Path extends "" ? T : ContainsNull<T> extends true ? JsonPathToType<Exclude<T, null>, Path> : Path extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? JsonPathToType<T[Key], Rest> : never : Path extends keyof T ? T[Path] : never;
256
+ export type IsStringUnion<T> = string extends T ? false : T extends string ? [T] extends [never] ? false : true : false;
257
+ type ComputedField<Schema extends GenericSchema, RelationName extends keyof TablesAndViews<Schema>, FieldName extends keyof TablesAndViews<Schema>[RelationName]["Row"]> = FieldName extends keyof Schema["Functions"] ? Schema["Functions"][FieldName] extends {
258
+ Args: {
259
+ "": TablesAndViews<Schema>[RelationName]["Row"];
260
+ };
261
+ Returns: any;
262
+ } ? FieldName : never : never;
263
+ export type GetComputedFields<Schema extends GenericSchema, RelationName extends keyof TablesAndViews<Schema>> = {
264
+ [K in keyof TablesAndViews<Schema>[RelationName]["Row"]]: ComputedField<Schema, RelationName, K>;
265
+ }[keyof TablesAndViews<Schema>[RelationName]["Row"]];
266
+ export {};
@@ -0,0 +1,109 @@
1
+ import PostgrestError from "./PostgrestError";
2
+ import { ContainsNull } from "./select-query-parser/types";
3
+ import { IsAny, SelectQueryError } from "./select-query-parser/utils";
4
+ export type Fetch = typeof fetch;
5
+ /**
6
+ * Response format
7
+ *
8
+ * {@link https://github.com/supabase/supabase-js/issues/32}
9
+ */
10
+ interface PostgrestResponseBase {
11
+ status: number;
12
+ statusText: string;
13
+ }
14
+ export interface PostgrestResponseSuccess<T> extends PostgrestResponseBase {
15
+ error: null;
16
+ data: T;
17
+ count: number | null;
18
+ }
19
+ export interface PostgrestResponseFailure extends PostgrestResponseBase {
20
+ error: PostgrestError;
21
+ data: null;
22
+ count: null;
23
+ }
24
+ export type PostgrestSingleResponse<T> = PostgrestResponseSuccess<T> | PostgrestResponseFailure;
25
+ export type PostgrestMaybeSingleResponse<T> = PostgrestSingleResponse<T | null>;
26
+ export type PostgrestResponse<T> = PostgrestSingleResponse<T[]>;
27
+ export type GenericRelationship = {
28
+ foreignKeyName: string;
29
+ columns: string[];
30
+ isOneToOne?: boolean;
31
+ referencedRelation: string;
32
+ referencedColumns: string[];
33
+ };
34
+ export type GenericTable = {
35
+ Row: Record<string, unknown>;
36
+ Insert: Record<string, unknown>;
37
+ Update: Record<string, unknown>;
38
+ Relationships: GenericRelationship[];
39
+ };
40
+ export type GenericUpdatableView = {
41
+ Row: Record<string, unknown>;
42
+ Insert: Record<string, unknown>;
43
+ Update: Record<string, unknown>;
44
+ Relationships: GenericRelationship[];
45
+ };
46
+ export type GenericNonUpdatableView = {
47
+ Row: Record<string, unknown>;
48
+ Relationships: GenericRelationship[];
49
+ };
50
+ export type GenericView = GenericUpdatableView | GenericNonUpdatableView;
51
+ export type GenericFunction = {
52
+ Args: Record<string, unknown>;
53
+ Returns: unknown;
54
+ };
55
+ export type GenericSchema = {
56
+ Tables: Record<string, GenericTable>;
57
+ Views: Record<string, GenericView>;
58
+ Functions: Record<string, GenericFunction>;
59
+ };
60
+ export type ClientServerOptions = {
61
+ PostgrestVersion?: string;
62
+ };
63
+ export type DatabaseWithOptions<Database, Options extends ClientServerOptions> = {
64
+ db: Database;
65
+ options: Options;
66
+ };
67
+ declare const INTERNAL_SUPABASE_OPTIONS = "__InternalSupabase";
68
+ export type GetGenericDatabaseWithOptions<Database, Opts extends ClientServerOptions = {
69
+ PostgrestVersion: "12";
70
+ }> = IsAny<Database> extends true ? DatabaseWithOptions<Database, Opts> : typeof INTERNAL_SUPABASE_OPTIONS extends keyof Database ? Database[typeof INTERNAL_SUPABASE_OPTIONS] extends ClientServerOptions ? DatabaseWithOptions<Omit<Database, typeof INTERNAL_SUPABASE_OPTIONS>, Database[typeof INTERNAL_SUPABASE_OPTIONS]> : DatabaseWithOptions<Omit<Database, typeof INTERNAL_SUPABASE_OPTIONS>, Opts> : DatabaseWithOptions<Database, Opts>;
71
+ export type MaxAffectedEnabled<PostgrestVersion extends string | undefined> = PostgrestVersion extends `13${string}` ? true : false;
72
+ export type Prettify<T> = {
73
+ [K in keyof T]: T[K];
74
+ } & {};
75
+ export type SimplifyDeep<Type, ExcludeType = never> = ConditionalSimplifyDeep<Type, ExcludeType | NonRecursiveType | Set<unknown> | Map<unknown, unknown>, object>;
76
+ type ConditionalSimplifyDeep<Type, ExcludeType = never, IncludeType = unknown> = Type extends ExcludeType ? Type : Type extends IncludeType ? {
77
+ [TypeKey in keyof Type]: ConditionalSimplifyDeep<Type[TypeKey], ExcludeType, IncludeType>;
78
+ } : Type;
79
+ type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown);
80
+ type BuiltIns = Primitive | void | Date | RegExp;
81
+ type Primitive = null | undefined | string | number | boolean | symbol | bigint;
82
+ export type IsValidResultOverride<Result, NewResult, ErrorResult, ErrorNewResult> = Result extends any[] ? NewResult extends any[] ? true : ErrorResult : NewResult extends any[] ? ErrorNewResult : true;
83
+ /**
84
+ * Utility type to check if array types match between Result and NewResult.
85
+ * Returns either the valid NewResult type or an error message type.
86
+ */
87
+ export type CheckMatchingArrayTypes<Result, NewResult> = Result extends SelectQueryError<string> ? NewResult : IsValidResultOverride<Result, NewResult, {
88
+ Error: "Type mismatch: Cannot cast array result to a single object. Use .overrideTypes<Array<YourType>> or .returns<Array<YourType>> (deprecated) for array results or .single() to convert the result to a single object";
89
+ }, {
90
+ Error: "Type mismatch: Cannot cast single object to array type. Remove Array wrapper from return type or make sure you are not using .single() up in the calling chain";
91
+ }> extends infer ValidationResult ? ValidationResult extends true ? ContainsNull<Result> extends true ? NewResult | null : NewResult : ValidationResult : never;
92
+ type Simplify<T> = T extends object ? {
93
+ [K in keyof T]: T[K];
94
+ } : T;
95
+ type ExplicitKeys<T> = {
96
+ [K in keyof T]: string extends K ? never : K;
97
+ }[keyof T];
98
+ type MergeExplicit<New, Row> = {
99
+ [K in ExplicitKeys<New> | ExplicitKeys<Row>]: K extends keyof New ? K extends keyof Row ? Row[K] extends SelectQueryError<string> ? New[K] : New[K] extends any[] ? Row[K] extends any[] ? Array<Simplify<MergeDeep<NonNullable<New[K][number]>, NonNullable<Row[K][number]>>>> : New[K] : IsPlainObject<NonNullable<New[K]>> extends true ? IsPlainObject<NonNullable<Row[K]>> extends true ? ContainsNull<New[K]> extends true ? // If the override wants to preserve optionality
100
+ Simplify<MergeDeep<NonNullable<New[K]>, NonNullable<Row[K]>>> | null : Simplify<MergeDeep<New[K], NonNullable<Row[K]>>> : New[K] : New[K] : New[K] : K extends keyof Row ? Row[K] : never;
101
+ };
102
+ type MergeDeep<New, Row> = Simplify<MergeExplicit<New, Row> & (string extends keyof Row ? {
103
+ [K: string]: Row[string];
104
+ } : {})>;
105
+ type IsPlainObject<T> = T extends any[] ? false : T extends object ? true : false;
106
+ export type MergePartialResult<NewResult, Result, Options> = Options extends {
107
+ merge: true;
108
+ } ? Result extends any[] ? NewResult extends any[] ? Array<Simplify<MergeDeep<NewResult[number], Result[number]>>> : never : Simplify<MergeDeep<NewResult, Result>> : NewResult;
109
+ export {};
@@ -0,0 +1 @@
1
+ export declare const version = "0.0.0-automated";
package/lib/index.d.ts CHANGED
@@ -1,16 +1,28 @@
1
- import { CloudBaseInstance, ExtendedCloudBaseInstance, OrmClient } from './types';
1
+ import { CloudBaseInstance, ExtendedCloudBaseInstance, IMySqlOptions, OrmClient } from './types';
2
2
  import { generateHTTPClient } from './orm/http-orm-client';
3
+ import { MySqlClient } from './db/mysql';
4
+ import { Fetch } from './db/postgrest/types';
3
5
  export declare function initHTTPOverCallFunction(cloud: CloudBaseInstance, options?: {
6
+ envId?: string;
4
7
  baseUrl?: string;
5
8
  sqlBaseUrl?: string;
9
+ mysqlBaseUrl?: string;
6
10
  }): ExtendedCloudBaseInstance;
7
- export declare function init(cloud: CloudBaseInstance): ExtendedCloudBaseInstance;
11
+ export declare function init(cloud: CloudBaseInstance, options?: {
12
+ envId?: string;
13
+ }): ExtendedCloudBaseInstance;
14
+ declare function generateMySQLClient(cloud: CloudBaseInstance, options?: {
15
+ envId?: string;
16
+ mysqlBaseUrl?: string;
17
+ fetch?: Fetch;
18
+ }): (options?: IMySqlOptions) => MySqlClient<any, {}>;
8
19
  export * from './types';
9
- export { generateHTTPClient };
20
+ export { generateHTTPClient, generateMySQLClient };
10
21
  declare const _default: {
11
22
  init: typeof init;
12
23
  generateHTTPClient: (callFunction: import("./types").CallFunction, fetch: (options: import("@cloudbase/adapter-interface").IFetchOptions) => any, baseUrl: string, options?: {
13
24
  sqlBaseUrl?: string | undefined;
14
25
  } | undefined) => OrmClient;
26
+ generateMySQLClient: typeof generateMySQLClient;
15
27
  };
16
28
  export default _default;
@@ -1,4 +1,5 @@
1
1
  import { SDKRequestInterface } from '@cloudbase/adapter-interface';
2
+ import { MySqlClient } from '../db/mysql';
2
3
  /**
3
4
  * 基础 Model 类型定义
4
5
  */
@@ -709,12 +710,14 @@ export type CloudBaseInstance = {
709
710
  callFunction: CallFunction;
710
711
  auth: any;
711
712
  };
713
+ export type IMySqlClient = (options?: IMySqlOptions) => MySqlClient;
712
714
  /**
713
715
  * 扩展的云实例接口,扩展了云函数调用接口并包含ORM客户端。
714
716
  * @hidden
715
717
  */
716
718
  export interface ExtendedCloudBaseInstance extends CloudBaseInstance {
717
719
  models: OrmClient & OrmRawQueryClient;
720
+ mysql: IMySqlClient;
718
721
  }
719
722
  /**
720
723
  * 云函数调用方法定义。
@@ -727,4 +730,8 @@ export type CallFunction = (args: {
727
730
  data: Record<string, any>;
728
731
  }) => Promise<any>;
729
732
  export type ModelFetch = NonNullable<SDKRequestInterface['fetch']>;
733
+ export interface IMySqlOptions {
734
+ instance?: string;
735
+ database?: string;
736
+ }
730
737
  export {};