-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathraw-builder.ts
205 lines (185 loc) · 5.92 KB
/
raw-builder.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
import { QueryResult } from '../driver/database-connection.js'
import { AliasNode } from '../operation-node/alias-node.js'
import { RawNode } from '../operation-node/raw-node.js'
import { CompiledQuery } from '../query-compiler/compiled-query.js'
import { preventAwait } from '../util/prevent-await.js'
import { QueryExecutor } from '../query-executor/query-executor.js'
import { freeze, isFunction, isObject } from '../util/object-utils.js'
import { KyselyPlugin } from '../plugin/kysely-plugin.js'
import { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js'
import { QueryExecutorProvider } from '../query-executor/query-executor-provider.js'
import { QueryId } from '../util/query-id.js'
import { IdentifierNode } from '../operation-node/identifier-node.js'
import { AliasedExpression, Expression } from '../expression/expression.js'
import { isOperationNodeSource } from '../operation-node/operation-node-source.js'
/**
* An instance of this class can be used to create raw SQL snippets or queries.
*
* You shouldn't need to create `RawBuilder` instances directly. Instead you should
* use the {@link sql} template tag.
*/
export class RawBuilder<O> implements Expression<O> {
readonly #props: RawBuilderProps
constructor(props: RawBuilderProps) {
this.#props = freeze(props)
}
/** @private */
get expressionType(): O | undefined {
return undefined
}
/**
* Returns an aliased version of the SQL expression.
*
* In addition to slapping `as "the_alias"` to the end of the SQL,
* this method also provides strict typing:
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select(
* sql<string>`concat(first_name, ' ', last_name)`.as('full_name')
* )
* .executeTakeFirstOrThrow()
*
* // `full_name: string` field exists in the result type.
* console.log(result.full_name)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```ts
* select concat(first_name, ' ', last_name) as "full_name"
* from "person"
* ```
*
* You can also pass in a raw SQL snippet but in that case you must
* provide the alias as the only type argument:
*
* ```ts
* const values = sql<{ a: number, b: string }>`(values (1, 'foo'))`
*
* // The alias is `t(a, b)` which specifies the column names
* // in addition to the table name. We must tell kysely that
* // columns of the table can be referenced through `t`
* // by providing an explicit type argument.
* const aliasedValues = values.as<'t'>(sql`t(a, b)`)
*
* await db
* .insertInto('person')
* .columns(['first_name', 'last_name'])
* .expression(
* db.selectFrom(aliasedValues).select(['t.a', 't.b'])
* )
* ```
*
* The generated SQL (PostgreSQL):
*
* ```ts
* insert into "person" ("first_name", "last_name")
* from (values (1, 'foo')) as t(a, b)
* select "t"."a", "t"."b"
* ```
*/
as<A extends string>(alias: A): AliasedRawBuilder<O, A>
as<A extends string = never>(alias: Expression<any>): AliasedRawBuilder<O, A>
as(alias: string | Expression<any>): AliasedRawBuilder<O, string> {
return new AliasedRawBuilder(this, alias)
}
/**
* Change the output type of the raw expression.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `RawBuilder` with a new output type.
*/
castTo<T>(): RawBuilder<T> {
return new RawBuilder({ ...this.#props })
}
/**
* Adds a plugin for this SQL snippet.
*/
withPlugin(plugin: KyselyPlugin): RawBuilder<O> {
return new RawBuilder({
...this.#props,
plugins:
this.#props.plugins !== undefined
? freeze([...this.#props.plugins, plugin])
: freeze([plugin]),
})
}
toOperationNode(): RawNode {
const executor =
this.#props.plugins !== undefined
? NOOP_QUERY_EXECUTOR.withPlugins(this.#props.plugins)
: NOOP_QUERY_EXECUTOR
return this.#toOperationNode(executor)
}
async execute(
executorProvider: QueryExecutorProvider
): Promise<QueryResult<O>> {
const executor =
this.#props.plugins !== undefined
? executorProvider.getExecutor().withPlugins(this.#props.plugins)
: executorProvider.getExecutor()
return executor.executeQuery<O>(
this.#compile(executor),
this.#props.queryId
)
}
#toOperationNode(executor: QueryExecutor): RawNode {
return executor.transformQuery(this.#props.rawNode, this.#props.queryId)
}
#compile(executor: QueryExecutor): CompiledQuery {
return executor.compileQuery(
this.#toOperationNode(executor),
this.#props.queryId
)
}
}
export function isRawBuilder(obj: unknown): obj is RawBuilder<unknown> {
return (
isObject(obj) &&
isFunction(obj.as) &&
isFunction(obj.castTo) &&
isFunction(obj.withPlugin) &&
isFunction(obj.toOperationNode) &&
isFunction(obj.execute)
)
}
preventAwait(
RawBuilder,
"don't await RawBuilder instances directly. To execute the query you need to call `execute`"
)
/**
* {@link RawBuilder} with an alias. The result of calling {@link RawBuilder.as}.
*/
export class AliasedRawBuilder<O = unknown, A extends string = never>
implements AliasedExpression<O, A>
{
readonly #rawBuilder: RawBuilder<O>
readonly #alias: A | Expression<any>
constructor(rawBuilder: RawBuilder<O>, alias: A | Expression<any>) {
this.#rawBuilder = rawBuilder
this.#alias = alias
}
/** @private */
get expression(): Expression<O> {
return this.#rawBuilder
}
/** @private */
get alias(): A {
return this.#alias as A
}
toOperationNode(): AliasNode {
return AliasNode.create(
this.#rawBuilder.toOperationNode(),
isOperationNodeSource(this.#alias)
? this.#alias.toOperationNode()
: IdentifierNode.create(this.#alias)
)
}
}
export interface RawBuilderProps {
readonly queryId: QueryId
readonly rawNode: RawNode
readonly plugins?: ReadonlyArray<KyselyPlugin>
}