This repository was archived by the owner on Mar 1, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathclient-impl.ts
More file actions
676 lines (606 loc) · 23.6 KB
/
client-impl.ts
File metadata and controls
676 lines (606 loc) · 23.6 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
import { invariant } from '@zenstackhq/common-helpers';
import type { QueryExecutor } from 'kysely';
import {
CompiledQuery,
DefaultConnectionProvider,
DefaultQueryExecutor,
Kysely,
Log,
sql,
Transaction,
type KyselyProps,
} from 'kysely';
import type { ProcedureDef, SchemaDef } from '../schema';
import type { AnyKysely } from '../utils/kysely-utils';
import type { UnwrapTuplePromises } from '../utils/type-utils';
import type {
AuthType,
ClientConstructor,
ClientContract,
ModelOperations,
TransactionIsolationLevel,
} from './contract';
import { AggregateOperationHandler } from './crud/operations/aggregate';
import type { AllCrudOperations, CoreCrudOperations } from './crud/operations/base';
import { BaseOperationHandler } from './crud/operations/base';
import { CountOperationHandler } from './crud/operations/count';
import { CreateOperationHandler } from './crud/operations/create';
import { DeleteOperationHandler } from './crud/operations/delete';
import { ExistsOperationHandler } from './crud/operations/exists';
import { FindOperationHandler } from './crud/operations/find';
import { GroupByOperationHandler } from './crud/operations/group-by';
import { UpdateOperationHandler } from './crud/operations/update';
import { InputValidator } from './crud/validator';
import { createConfigError, createNotFoundError } from './errors';
import { ZenStackDriver } from './executor/zenstack-driver';
import { ZenStackQueryExecutor } from './executor/zenstack-query-executor';
import * as BuiltinFunctions from './functions';
import { SchemaDbPusher } from './helpers/schema-db-pusher';
import type { ClientOptions, ProceduresOptions } from './options';
import type { AnyPlugin } from './plugin';
import { createZenStackPromise, type ZenStackPromise } from './promise';
import { ResultProcessor } from './result-processor';
/**
* ZenStack ORM client.
*/
export const ZenStackClient = function <Schema extends SchemaDef>(
this: any,
schema: Schema,
options: ClientOptions<Schema>,
) {
return new ClientImpl(schema, options as ClientOptions<SchemaDef>);
} as unknown as ClientConstructor;
export class ClientImpl {
private kysely: AnyKysely;
private kyselyRaw: AnyKysely;
public readonly $options: ClientOptions<SchemaDef>;
public readonly $schema: SchemaDef;
readonly kyselyProps: KyselyProps;
private auth: AuthType<SchemaDef> | undefined;
inputValidator: InputValidator<SchemaDef>;
constructor(
private readonly schema: SchemaDef,
private options: ClientOptions<SchemaDef>,
baseClient?: ClientImpl,
executor?: QueryExecutor,
) {
this.$schema = schema;
this.$options = options;
this.$options.functions = {
...BuiltinFunctions,
...this.$options.functions,
};
// here we use kysely's props constructor so we can pass a custom query executor
if (baseClient) {
this.kyselyProps = {
...baseClient.kyselyProps,
executor:
executor ??
new ZenStackQueryExecutor(
this,
baseClient.kyselyProps.driver as ZenStackDriver,
baseClient.kyselyProps.dialect.createQueryCompiler(),
baseClient.kyselyProps.dialect.createAdapter(),
new DefaultConnectionProvider(baseClient.kyselyProps.driver),
),
};
this.kyselyRaw = baseClient.kyselyRaw;
this.auth = baseClient.auth;
} else {
const driver = new ZenStackDriver(options.dialect.createDriver(), new Log(this.$options.log ?? []));
const compiler = options.dialect.createQueryCompiler();
const adapter = options.dialect.createAdapter();
const connectionProvider = new DefaultConnectionProvider(driver);
this.kyselyProps = {
config: {
dialect: options.dialect,
log: this.$options.log,
},
dialect: options.dialect,
driver,
executor: executor ?? new ZenStackQueryExecutor(this, driver, compiler, adapter, connectionProvider),
};
// raw kysely instance with default executor
this.kyselyRaw = new Kysely({
...this.kyselyProps,
executor: new DefaultQueryExecutor(compiler, adapter, connectionProvider, []),
});
}
this.kysely = new Kysely(this.kyselyProps);
this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this as any);
return createClientProxy(this);
}
get $qb() {
return this.kysely;
}
get $qbRaw() {
return this.kyselyRaw;
}
get isTransaction() {
return this.kysely.isTransaction;
}
/**
* Create a new client with a new query executor.
*/
withExecutor(executor: QueryExecutor) {
return new ClientImpl(this.schema, this.$options, this, executor);
}
// overload for interactive transaction
$transaction<T>(
callback: (tx: ClientContract<SchemaDef>) => Promise<T>,
options?: { isolationLevel?: TransactionIsolationLevel },
): Promise<T>;
// overload for sequential transaction
$transaction<P extends ZenStackPromise<SchemaDef, any>[]>(
arg: [...P],
options?: { isolationLevel?: TransactionIsolationLevel },
): Promise<UnwrapTuplePromises<P>>;
// implementation
async $transaction(input: any, options?: { isolationLevel?: TransactionIsolationLevel }) {
invariant(
typeof input === 'function' || (Array.isArray(input) && input.every((p) => p.then && p.cb)),
'Invalid transaction input, expected a function or an array of ZenStackPromise',
);
if (typeof input === 'function') {
return this.interactiveTransaction(input, options);
} else {
return this.sequentialTransaction(input, options);
}
}
forceTransaction() {
if (!this.kysely.isTransaction) {
this.kysely = new Transaction(this.kyselyProps);
}
}
private async interactiveTransaction(
callback: (tx: ClientContract<SchemaDef>) => Promise<any>,
options?: { isolationLevel?: TransactionIsolationLevel },
): Promise<any> {
if (this.kysely.isTransaction) {
// proceed directly if already in a transaction
return callback(this as unknown as ClientContract<SchemaDef>);
} else {
// otherwise, create a new transaction, clone the client, and execute the callback
let txBuilder = this.kysely.transaction();
if (options?.isolationLevel) {
txBuilder = txBuilder.setIsolationLevel(options.isolationLevel);
}
return txBuilder.execute((tx) => {
const txClient = new ClientImpl(this.schema, this.$options, this);
txClient.kysely = tx;
return callback(txClient as unknown as ClientContract<SchemaDef>);
});
}
}
private async sequentialTransaction(
arg: ZenStackPromise<SchemaDef, any>[],
options?: { isolationLevel?: TransactionIsolationLevel },
) {
const execute = async (tx: AnyKysely) => {
const txClient = new ClientImpl(this.schema, this.$options, this);
txClient.kysely = tx;
const result: any[] = [];
for (const promise of arg) {
result.push(await promise.cb(txClient as unknown as ClientContract<SchemaDef>));
}
return result;
};
if (this.kysely.isTransaction) {
// proceed directly if already in a transaction
return execute(this.kysely);
} else {
// otherwise, create a new transaction, clone the client, and execute the callback
let txBuilder = this.kysely.transaction();
if (options?.isolationLevel) {
txBuilder = txBuilder.setIsolationLevel(options.isolationLevel);
}
return txBuilder.execute((tx) => execute(tx as AnyKysely));
}
}
get $procs() {
return Object.keys(this.$schema.procedures ?? {}).reduce((acc, name) => {
acc[name] = (input?: unknown) => this.handleProc(name, input);
return acc;
}, {} as any);
}
private async handleProc(name: string, input: unknown) {
if (!('procedures' in this.$options) || !this.$options || typeof this.$options.procedures !== 'object') {
throw createConfigError('Procedures are not configured for the client.');
}
const procDef = (this.$schema.procedures ?? {})[name];
if (!procDef) {
throw createConfigError(`Procedure "${name}" is not defined in schema.`);
}
const procOptions = this.$options.procedures as ProceduresOptions<
SchemaDef & {
procedures: Record<string, ProcedureDef>;
}
>;
if (!procOptions[name] || typeof procOptions[name] !== 'function') {
throw createConfigError(`Procedure "${name}" does not have a handler configured.`);
}
// Validate inputs using the same validator infrastructure as CRUD operations.
const validatedInput = this.inputValidator.validateProcedureInput(name, input);
const handler = procOptions[name] as Function;
const invokeWithClient = async (client: any, _input: unknown) => {
let proceed = async (nextInput: unknown) => {
const sanitizedNextInput =
nextInput && typeof nextInput === 'object' && !Array.isArray(nextInput) ? nextInput : {};
return handler({ client, ...sanitizedNextInput });
};
// apply plugins
const plugins = [...(client.$options?.plugins ?? [])];
for (const plugin of plugins) {
const onProcedure = plugin.onProcedure;
if (onProcedure) {
const _proceed = proceed;
proceed = (nextInput: unknown) =>
onProcedure({
client,
name,
mutation: !!procDef.mutation,
input: nextInput,
proceed: (finalInput: unknown) => _proceed(finalInput),
}) as Promise<unknown>;
}
}
return proceed(_input);
};
return invokeWithClient(this as any, validatedInput);
}
async $connect() {
await this.kysely.connection().execute(async (conn) => {
await conn.executeQuery(sql`select 1`.compile(this.kysely));
});
}
async $disconnect() {
await this.kysely.destroy();
}
async $pushSchema() {
await new SchemaDbPusher(this.schema, this.kysely).push();
}
$use(plugin: AnyPlugin) {
const newPlugins: AnyPlugin[] = [...(this.$options.plugins ?? []), plugin];
const newOptions: ClientOptions<SchemaDef> = {
...this.options,
plugins: newPlugins,
};
const newClient = new ClientImpl(this.schema, newOptions, this);
// create a new validator to have a fresh schema cache, because plugins may extend the
// query args schemas
newClient.inputValidator = new InputValidator(newClient as any);
return newClient;
}
$unuse(pluginId: string) {
// tsc perf
const newPlugins: AnyPlugin[] = [];
for (const plugin of this.options.plugins ?? []) {
if (plugin.id !== pluginId) {
newPlugins.push(plugin);
}
}
const newOptions: ClientOptions<SchemaDef> = {
...this.options,
plugins: newPlugins,
};
const newClient = new ClientImpl(this.schema, newOptions, this);
// create a new validator to have a fresh schema cache, because plugins may
// extend the query args schemas
newClient.inputValidator = new InputValidator(newClient as any);
return newClient;
}
$unuseAll() {
// tsc perf
const newOptions: ClientOptions<SchemaDef> = {
...this.options,
plugins: [] as AnyPlugin[],
};
const newClient = new ClientImpl(this.schema, newOptions, this);
// create a new validator to have a fresh schema cache, because plugins may
// extend the query args schemas
newClient.inputValidator = new InputValidator(newClient as any);
return newClient;
}
$setAuth(auth: AuthType<SchemaDef> | undefined) {
if (auth !== undefined && typeof auth !== 'object') {
throw new Error('Invalid auth object');
}
const newClient = new ClientImpl(this.schema, this.$options, this);
newClient.auth = auth;
return newClient;
}
get $auth() {
return this.auth;
}
$setOptions<Options extends ClientOptions<SchemaDef>>(options: Options): ClientContract<SchemaDef, Options> {
const newClient = new ClientImpl(this.schema, options as ClientOptions<SchemaDef>, this);
// create a new validator to have a fresh schema cache, because options may change validation settings
newClient.inputValidator = new InputValidator(newClient as any);
return newClient as unknown as ClientContract<SchemaDef, Options>;
}
$setInputValidation(enable: boolean) {
const newOptions: ClientOptions<SchemaDef> = {
...this.options,
validateInput: enable,
};
return this.$setOptions(newOptions);
}
$executeRaw(query: TemplateStringsArray, ...values: any[]) {
return createZenStackPromise(async () => {
const result = await sql(query, ...values).execute(this.kysely);
return Number(result.numAffectedRows ?? 0);
});
}
$executeRawUnsafe(query: string, ...values: any[]) {
return createZenStackPromise(async () => {
const compiledQuery = this.createRawCompiledQuery(query, values);
const result = await this.kysely.executeQuery(compiledQuery);
return Number(result.numAffectedRows ?? 0);
});
}
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]) {
return createZenStackPromise(async () => {
const result = await sql(query, ...values).execute(this.kysely);
return result.rows as T;
});
}
$queryRawUnsafe<T = unknown>(query: string, ...values: any[]) {
return createZenStackPromise(async () => {
const compiledQuery = this.createRawCompiledQuery(query, values);
const result = await this.kysely.executeQuery(compiledQuery);
return result.rows as T;
});
}
private createRawCompiledQuery(query: string, values: any[]) {
const q = CompiledQuery.raw(query, values);
return { ...q, $raw: true } as CompiledQuery;
}
}
function createClientProxy(client: ClientImpl): ClientImpl {
const resultProcessor = new ResultProcessor(client.$schema, client.$options);
return new Proxy(client, {
get: (target, prop, receiver) => {
if (typeof prop === 'string' && prop.startsWith('$')) {
// Check for plugin-provided members (search in reverse order so later plugins win)
const plugins = target.$options.plugins ?? [];
for (let i = plugins.length - 1; i >= 0; i--) {
const plugin = plugins[i];
const clientMembers = plugin?.client as Record<string, unknown> | undefined;
if (clientMembers && prop in clientMembers) {
return clientMembers[prop];
}
}
// Fall through to built-in $ methods
return Reflect.get(target, prop, receiver);
}
if (typeof prop === 'string') {
const model = Object.keys(client.$schema.models).find((m) => m.toLowerCase() === prop.toLowerCase());
if (model) {
return createModelCrudHandler(client as any, model, client.inputValidator, resultProcessor);
}
}
return Reflect.get(target, prop, receiver);
},
}) as unknown as ClientImpl;
}
function createModelCrudHandler(
client: ClientContract<any>,
model: string,
inputValidator: InputValidator<any>,
resultProcessor: ResultProcessor<any>,
): ModelOperations<any, any> {
const createPromise = (
operation: CoreCrudOperations,
nominalOperation: AllCrudOperations,
args: unknown,
handler: BaseOperationHandler<any>,
postProcess = false,
throwIfNoResult = false,
) => {
return createZenStackPromise(async (txClient?: ClientContract<any>) => {
let proceed = async (_args: unknown) => {
const _handler = txClient ? handler.withClient(txClient) : handler;
const r = await _handler.handle(operation, _args);
if (!r && throwIfNoResult) {
throw createNotFoundError(model);
}
let result: unknown;
if (r && postProcess) {
result = resultProcessor.processResult(r, model, args);
} else {
result = r ?? null;
}
return result;
};
// apply plugins
const plugins = [...(client.$options.plugins ?? [])];
for (const plugin of plugins) {
const onQuery = plugin.onQuery;
if (onQuery) {
const _proceed = proceed;
proceed = (_args: unknown) => {
const ctx: any = {
client,
model,
operation: nominalOperation,
// reflect the latest override if provided
args: _args,
// ensure inner overrides are propagated to the previous proceed
proceed: (nextArgs: unknown) => _proceed(nextArgs),
};
return (onQuery as (ctx: any) => Promise<unknown>)(ctx);
};
}
}
return proceed(args);
});
};
// type parameters to operation handlers are explicitly specified to improve tsc performance
return {
findUnique: (args: unknown) => {
return createPromise(
'findUnique',
'findUnique',
args,
new FindOperationHandler<any>(client, model, inputValidator),
true,
);
},
findUniqueOrThrow: (args: unknown) => {
return createPromise(
'findUnique',
'findUniqueOrThrow',
args,
new FindOperationHandler<any>(client, model, inputValidator),
true,
true,
);
},
findFirst: (args: unknown) => {
return createPromise(
'findFirst',
'findFirst',
args,
new FindOperationHandler<any>(client, model, inputValidator),
true,
);
},
findFirstOrThrow: (args: unknown) => {
return createPromise(
'findFirst',
'findFirstOrThrow',
args,
new FindOperationHandler<any>(client, model, inputValidator),
true,
true,
);
},
findMany: (args: unknown) => {
return createPromise(
'findMany',
'findMany',
args,
new FindOperationHandler<any>(client, model, inputValidator),
true,
false,
);
},
create: (args: unknown) => {
return createPromise(
'create',
'create',
args,
new CreateOperationHandler<any>(client, model, inputValidator),
true,
);
},
createMany: (args: unknown) => {
return createPromise(
'createMany',
'createMany',
args,
new CreateOperationHandler<any>(client, model, inputValidator),
false,
);
},
createManyAndReturn: (args: unknown) => {
return createPromise(
'createManyAndReturn',
'createManyAndReturn',
args,
new CreateOperationHandler<any>(client, model, inputValidator),
true,
);
},
update: (args: unknown) => {
return createPromise(
'update',
'update',
args,
new UpdateOperationHandler<any>(client, model, inputValidator),
true,
);
},
updateMany: (args: unknown) => {
return createPromise(
'updateMany',
'updateMany',
args,
new UpdateOperationHandler<any>(client, model, inputValidator),
false,
);
},
updateManyAndReturn: (args: unknown) => {
return createPromise(
'updateManyAndReturn',
'updateManyAndReturn',
args,
new UpdateOperationHandler<any>(client, model, inputValidator),
true,
);
},
upsert: (args: unknown) => {
return createPromise(
'upsert',
'upsert',
args,
new UpdateOperationHandler<any>(client, model, inputValidator),
true,
);
},
delete: (args: unknown) => {
return createPromise(
'delete',
'delete',
args,
new DeleteOperationHandler<any>(client, model, inputValidator),
true,
);
},
deleteMany: (args: unknown) => {
return createPromise(
'deleteMany',
'deleteMany',
args,
new DeleteOperationHandler<any>(client, model, inputValidator),
false,
);
},
count: (args: unknown) => {
return createPromise(
'count',
'count',
args,
new CountOperationHandler<any>(client, model, inputValidator),
false,
);
},
aggregate: (args: unknown) => {
return createPromise(
'aggregate',
'aggregate',
args,
new AggregateOperationHandler<any>(client, model, inputValidator),
false,
);
},
groupBy: (args: unknown) => {
return createPromise(
'groupBy',
'groupBy',
args,
new GroupByOperationHandler<any>(client, model, inputValidator),
true,
);
},
exists: (args: unknown) => {
return createPromise(
'exists',
'exists',
args,
new ExistsOperationHandler<any>(client, model, inputValidator),
false,
);
},
} as ModelOperations<any, any>;
}