-
-
Notifications
You must be signed in to change notification settings - Fork 480
/
sql.ts
651 lines (553 loc) 路 16.5 KB
/
sql.ts
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
import { entityKind, is } from '~/entity.ts';
import type { SelectedFields } from '~/operations.ts';
import { isPgEnum } from '~/pg-core/columns/enum.ts';
import { Subquery } from '~/subquery.ts';
import { tracer } from '~/tracing.ts';
import { ViewBaseConfig } from '~/view-common.ts';
import type { AnyColumn } from '../column.ts';
import { Column } from '../column.ts';
import { Table } from '../table.ts';
/**
* This class is used to indicate a primitive param value that is used in `sql` tag.
* It is only used on type level and is never instantiated at runtime.
* If you see a value of this type in the code, its runtime value is actually the primitive param value.
*/
export class FakePrimitiveParam {
static readonly [entityKind]: string = 'FakePrimitiveParam';
}
export type Chunk =
| string
| Table
| View
| AnyColumn
| Name
| Param
| Placeholder
| SQL;
export interface BuildQueryConfig {
escapeName(name: string): string;
escapeParam(num: number, value: unknown): string;
escapeString(str: string): string;
prepareTyping?: (encoder: DriverValueEncoder<unknown, unknown>) => QueryTypingsValue;
paramStartIndex?: { value: number };
inlineParams?: boolean;
}
export type QueryTypingsValue = 'json' | 'decimal' | 'time' | 'timestamp' | 'uuid' | 'date' | 'none';
export interface Query {
sql: string;
params: unknown[];
}
export interface QueryWithTypings extends Query {
typings?: QueryTypingsValue[];
}
/**
* Any value that implements the `getSQL` method. The implementations include:
* - `Table`
* - `Column`
* - `View`
* - `Subquery`
* - `SQL`
* - `SQL.Aliased`
* - `Placeholder`
* - `Param`
*/
export interface SQLWrapper {
getSQL(): SQL;
}
export function isSQLWrapper(value: unknown): value is SQLWrapper {
return value !== null && value !== undefined && typeof (value as any).getSQL === 'function';
}
function mergeQueries(queries: QueryWithTypings[]): QueryWithTypings {
const result: QueryWithTypings = { sql: '', params: [] };
for (const query of queries) {
result.sql += query.sql;
result.params.push(...query.params);
if (query.typings?.length) {
if (!result.typings) {
result.typings = [];
}
result.typings.push(...query.typings);
}
}
return result;
}
export class StringChunk implements SQLWrapper {
static readonly [entityKind]: string = 'StringChunk';
readonly value: string[];
constructor(value: string | string[]) {
this.value = Array.isArray(value) ? value : [value];
}
getSQL(): SQL<unknown> {
return new SQL([this]);
}
}
export class SQL<T = unknown> implements SQLWrapper {
static readonly [entityKind]: string = 'SQL';
declare _: {
brand: 'SQL';
type: T;
};
/** @internal */
decoder: DriverValueDecoder<T, any> = noopDecoder;
private shouldInlineParams = false;
constructor(readonly queryChunks: SQLChunk[]) {}
append(query: SQL): this {
this.queryChunks.push(...query.queryChunks);
return this;
}
toQuery(config: BuildQueryConfig): QueryWithTypings {
return tracer.startActiveSpan('drizzle.buildSQL', (span) => {
const query = this.buildQueryFromSourceParams(this.queryChunks, config);
span?.setAttributes({
'drizzle.query.text': query.sql,
'drizzle.query.params': JSON.stringify(query.params),
});
return query;
});
}
buildQueryFromSourceParams(chunks: SQLChunk[], _config: BuildQueryConfig): Query {
const config = Object.assign({}, _config, {
inlineParams: _config.inlineParams || this.shouldInlineParams,
paramStartIndex: _config.paramStartIndex || { value: 0 },
});
const {
escapeName,
escapeParam,
prepareTyping,
inlineParams,
paramStartIndex,
} = config;
return mergeQueries(chunks.map((chunk): QueryWithTypings => {
if (is(chunk, StringChunk)) {
return { sql: chunk.value.join(''), params: [] };
}
if (is(chunk, Name)) {
return { sql: escapeName(chunk.value), params: [] };
}
if (chunk === undefined) {
return { sql: '', params: [] };
}
if (Array.isArray(chunk)) {
const result: SQLChunk[] = [new StringChunk('(')];
for (const [i, p] of chunk.entries()) {
result.push(p);
if (i < chunk.length - 1) {
result.push(new StringChunk(', '));
}
}
result.push(new StringChunk(')'));
return this.buildQueryFromSourceParams(result, config);
}
if (is(chunk, SQL)) {
return this.buildQueryFromSourceParams(chunk.queryChunks, {
...config,
inlineParams: inlineParams || chunk.shouldInlineParams,
});
}
if (is(chunk, Table)) {
const schemaName = chunk[Table.Symbol.Schema];
const tableName = chunk[Table.Symbol.Name];
return {
sql: schemaName === undefined
? escapeName(tableName)
: escapeName(schemaName) + '.' + escapeName(tableName),
params: [],
};
}
if (is(chunk, Column)) {
return { sql: escapeName(chunk.table[Table.Symbol.Name]) + '.' + escapeName(chunk.name), params: [] };
}
if (is(chunk, View)) {
const schemaName = chunk[ViewBaseConfig].schema;
const viewName = chunk[ViewBaseConfig].name;
return {
sql: schemaName === undefined
? escapeName(viewName)
: escapeName(schemaName) + '.' + escapeName(viewName),
params: [],
};
}
if (is(chunk, Param)) {
const mappedValue = (chunk.value === null) ? null : chunk.encoder.mapToDriverValue(chunk.value);
if (is(mappedValue, SQL)) {
return this.buildQueryFromSourceParams([mappedValue], config);
}
if (inlineParams) {
return { sql: this.mapInlineParam(mappedValue, config), params: [] };
}
let typings: QueryTypingsValue[] | undefined;
if (prepareTyping !== undefined) {
typings = [prepareTyping(chunk.encoder)];
}
return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
}
if (is(chunk, Placeholder)) {
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk] };
}
if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
return { sql: escapeName(chunk.fieldAlias), params: [] };
}
if (is(chunk, Subquery)) {
if (chunk._.isWith) {
return { sql: escapeName(chunk._.alias), params: [] };
}
return this.buildQueryFromSourceParams([
new StringChunk('('),
chunk._.sql,
new StringChunk(') '),
new Name(chunk._.alias),
], config);
}
if (isPgEnum(chunk)) {
if (chunk.schema) {
return { sql: escapeName(chunk.schema) + '.' + escapeName(chunk.enumName), params: [] };
}
return { sql: escapeName(chunk.enumName), params: [] };
}
if (isSQLWrapper(chunk)) {
return this.buildQueryFromSourceParams([
new StringChunk('('),
chunk.getSQL(),
new StringChunk(')'),
], config);
}
if (inlineParams) {
return { sql: this.mapInlineParam(chunk, config), params: [] };
}
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk] };
}));
}
private mapInlineParam(
chunk: unknown,
{ escapeString }: BuildQueryConfig,
): string {
if (chunk === null) {
return 'null';
}
if (typeof chunk === 'number' || typeof chunk === 'boolean') {
return chunk.toString();
}
if (typeof chunk === 'string') {
return escapeString(chunk);
}
if (typeof chunk === 'object') {
const mappedValueAsString = chunk.toString();
if (mappedValueAsString === '[object Object]') {
return escapeString(JSON.stringify(chunk));
}
return escapeString(mappedValueAsString);
}
throw new Error('Unexpected param value: ' + chunk);
}
getSQL(): SQL {
return this;
}
as(alias: string): SQL.Aliased<T>;
/**
* @deprecated
* Use ``sql<DataType>`query`.as(alias)`` instead.
*/
as<TData>(): SQL<TData>;
/**
* @deprecated
* Use ``sql<DataType>`query`.as(alias)`` instead.
*/
as<TData>(alias: string): SQL.Aliased<TData>;
as(alias?: string): SQL<T> | SQL.Aliased<T> {
// TODO: remove with deprecated overloads
if (alias === undefined) {
return this;
}
return new SQL.Aliased(this, alias);
}
mapWith<
TDecoder extends
| DriverValueDecoder<any, any>
| DriverValueDecoder<any, any>['mapFromDriverValue'],
>(decoder: TDecoder): SQL<GetDecoderResult<TDecoder>> {
this.decoder = typeof decoder === 'function' ? { mapFromDriverValue: decoder } : decoder;
return this as SQL<GetDecoderResult<TDecoder>>;
}
inlineParams(): this {
this.shouldInlineParams = true;
return this;
}
/**
* This method is used to conditionally include a part of the query.
*
* @param condition - Condition to check
* @returns itself if the condition is `true`, otherwise `undefined`
*/
if(condition: any | undefined): this | undefined {
return condition ? this : undefined;
}
}
export type GetDecoderResult<T> = T extends Column ? T['_']['data'] : T extends
| DriverValueDecoder<infer TData, any>
| DriverValueDecoder<infer TData, any>['mapFromDriverValue'] ? TData
: never;
/**
* Any DB name (table, column, index etc.)
*/
export class Name implements SQLWrapper {
static readonly [entityKind]: string = 'Name';
protected brand!: 'Name';
constructor(readonly value: string) {}
getSQL(): SQL<unknown> {
return new SQL([this]);
}
}
/**
* Any DB name (table, column, index etc.)
* @deprecated Use `sql.identifier` instead.
*/
export function name(value: string): Name {
return new Name(value);
}
export interface DriverValueDecoder<TData, TDriverParam> {
mapFromDriverValue(value: TDriverParam): TData;
}
export interface DriverValueEncoder<TData, TDriverParam> {
mapToDriverValue(value: TData): TDriverParam | SQL;
}
export function isDriverValueEncoder(value: unknown): value is DriverValueEncoder<any, any> {
return typeof value === 'object' && value !== null && 'mapToDriverValue' in value
&& typeof (value as any).mapToDriverValue === 'function';
}
export const noopDecoder: DriverValueDecoder<any, any> = {
mapFromDriverValue: (value) => value,
};
export const noopEncoder: DriverValueEncoder<any, any> = {
mapToDriverValue: (value) => value,
};
export interface DriverValueMapper<TData, TDriverParam>
extends DriverValueDecoder<TData, TDriverParam>, DriverValueEncoder<TData, TDriverParam>
{}
export const noopMapper: DriverValueMapper<any, any> = {
...noopDecoder,
...noopEncoder,
};
/** Parameter value that is optionally bound to an encoder (for example, a column). */
export class Param<TDataType = unknown, TDriverParamType = TDataType> implements SQLWrapper {
static readonly [entityKind]: string = 'Param';
protected brand!: 'BoundParamValue';
/**
* @param value - Parameter value
* @param encoder - Encoder to convert the value to a driver parameter
*/
constructor(
readonly value: TDataType,
readonly encoder: DriverValueEncoder<TDataType, TDriverParamType> = noopEncoder,
) {}
getSQL(): SQL<unknown> {
return new SQL([this]);
}
}
/** @deprecated Use `sql.param` instead. */
export function param<TData, TDriver>(
value: TData,
encoder?: DriverValueEncoder<TData, TDriver>,
): Param<TData, TDriver> {
return new Param(value, encoder);
}
/**
* Anything that can be passed to the `` sql`...` `` tagged function.
*/
export type SQLChunk =
| StringChunk
| SQLChunk[]
| SQLWrapper
| SQL
| Table
| View
| Subquery
| AnyColumn
| Param
| Name
| undefined
| FakePrimitiveParam
| Placeholder;
export function sql<T>(strings: TemplateStringsArray, ...params: any[]): SQL<T>;
/*
The type of `params` is specified as `SQLSourceParam[]`, but that's slightly incorrect -
in runtime, users won't pass `FakePrimitiveParam` instances as `params` - they will pass primitive values
which will be wrapped in `Param` using `buildChunksFromParam(...)`. That's why the overload
specify `params` as `any[]` and not as `SQLSourceParam[]`. This type is used to make our lives easier and
the type checker happy.
*/
export function sql(strings: TemplateStringsArray, ...params: SQLChunk[]): SQL {
const queryChunks: SQLChunk[] = [];
if (params.length > 0 || (strings.length > 0 && strings[0] !== '')) {
queryChunks.push(new StringChunk(strings[0]!));
}
for (const [paramIndex, param] of params.entries()) {
queryChunks.push(param, new StringChunk(strings[paramIndex + 1]!));
}
return new SQL(queryChunks);
}
export namespace sql {
export function empty(): SQL {
return new SQL([]);
}
/** @deprecated - use `sql.join()` */
export function fromList(list: SQLChunk[]): SQL {
return new SQL(list);
}
/**
* Convenience function to create an SQL query from a raw string.
* @param str The raw SQL query string.
*/
export function raw(str: string): SQL {
return new SQL([new StringChunk(str)]);
}
/**
* Join a list of SQL chunks with a separator.
* @example
* ```ts
* const query = sql.join([sql`a`, sql`b`, sql`c`]);
* // sql`abc`
* ```
* @example
* ```ts
* const query = sql.join([sql`a`, sql`b`, sql`c`], sql`, `);
* // sql`a, b, c`
* ```
*/
export function join(chunks: SQLChunk[], separator?: SQLChunk): SQL {
const result: SQLChunk[] = [];
for (const [i, chunk] of chunks.entries()) {
if (i > 0 && separator !== undefined) {
result.push(separator);
}
result.push(chunk);
}
return new SQL(result);
}
/**
* Create a SQL chunk that represents a DB identifier (table, column, index etc.).
* When used in a query, the identifier will be escaped based on the DB engine.
* For example, in PostgreSQL, identifiers are escaped with double quotes.
*
* **WARNING: This function does not offer any protection against SQL injections, so you must validate any user input beforehand.**
*
* @example ```ts
* const query = sql`SELECT * FROM ${sql.identifier('my-table')}`;
* // 'SELECT * FROM "my-table"'
* ```
*/
export function identifier(value: string): Name {
return new Name(value);
}
export function placeholder<TName extends string>(name: TName): Placeholder<TName> {
return new Placeholder(name);
}
export function param<TData, TDriver>(
value: TData,
encoder?: DriverValueEncoder<TData, TDriver>,
): Param<TData, TDriver> {
return new Param(value, encoder);
}
}
export namespace SQL {
export class Aliased<T = unknown> implements SQLWrapper {
static readonly [entityKind]: string = 'SQL.Aliased';
declare _: {
brand: 'SQL.Aliased';
type: T;
};
/** @internal */
isSelectionField = false;
constructor(
readonly sql: SQL,
readonly fieldAlias: string,
) {}
getSQL(): SQL {
return this.sql;
}
/** @internal */
clone() {
return new Aliased(this.sql, this.fieldAlias);
}
}
}
export class Placeholder<TName extends string = string, TValue = any> implements SQLWrapper {
static readonly [entityKind]: string = 'Placeholder';
declare protected: TValue;
constructor(readonly name: TName) {}
getSQL(): SQL {
return new SQL([this]);
}
}
/** @deprecated Use `sql.placeholder` instead. */
export function placeholder<TName extends string>(name: TName): Placeholder<TName> {
return new Placeholder(name);
}
export function fillPlaceholders(params: unknown[], values: Record<string, unknown>): unknown[] {
return params.map((p) => {
if (is(p, Placeholder)) {
if (!(p.name in values)) {
throw new Error(`No value for placeholder "${p.name}" was provided`);
}
return values[p.name];
}
return p;
});
}
export type ColumnsSelection = Record<string, unknown>;
export abstract class View<
TName extends string = string,
TExisting extends boolean = boolean,
TSelection extends ColumnsSelection = ColumnsSelection,
> implements SQLWrapper {
static readonly [entityKind]: string = 'View';
declare _: {
brand: 'View';
viewBrand: string;
name: TName;
existing: TExisting;
selectedFields: TSelection;
};
/** @internal */
[ViewBaseConfig]: {
name: TName;
originalName: TName;
schema: string | undefined;
selectedFields: SelectedFields<AnyColumn, Table>;
isExisting: TExisting;
query: TExisting extends true ? undefined : SQL;
isAlias: boolean;
};
constructor(
{ name, schema, selectedFields, query }: {
name: TName;
schema: string | undefined;
selectedFields: SelectedFields<AnyColumn, Table>;
query: SQL | undefined;
},
) {
this[ViewBaseConfig] = {
name,
originalName: name,
schema,
selectedFields,
query: query as (TExisting extends true ? undefined : SQL),
isExisting: !query as TExisting,
isAlias: false,
};
}
getSQL(): SQL<unknown> {
return new SQL([this]);
}
}
// Defined separately from the Column class to resolve circular dependency
Column.prototype.getSQL = function() {
return new SQL([this]);
};
// Defined separately from the Table class to resolve circular dependency
Table.prototype.getSQL = function() {
return new SQL([this]);
};
// Defined separately from the Column class to resolve circular dependency
Subquery.prototype.getSQL = function() {
return new SQL([this]);
};