-
Notifications
You must be signed in to change notification settings - Fork 279
/
create-table-builder.ts
279 lines (262 loc) · 8.03 KB
/
create-table-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
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
import { ColumnDefinitionNode } from '../operation-node/column-definition-node.js'
import { CreateTableNode } from '../operation-node/create-table-node.js'
import { OperationNodeSource } from '../operation-node/operation-node-source.js'
import { CompiledQuery } from '../query-compiler/compiled-query.js'
import { Compilable } from '../util/compilable.js'
import { preventAwait } from '../util/prevent-await.js'
import { QueryExecutor } from '../query-executor/query-executor.js'
import { ColumnDefinitionBuilder } from './column-definition-builder.js'
import { QueryId } from '../util/query-id.js'
import { freeze, noop } from '../util/object-utils.js'
import { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js'
import { ColumnNode } from '../operation-node/column-node.js'
import { TableNode } from '../operation-node/table-node.js'
import { ForeignKeyConstraintBuilder } from './foreign-key-constraint-builder.js'
import {
DataTypeExpression,
parseDataTypeExpression,
} from '../parser/data-type-parser.js'
import { PrimaryConstraintNode } from '../operation-node/primary-constraint-node.js'
import { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js'
import { CheckConstraintNode } from '../operation-node/check-constraint-node.js'
/**
* This builder can be used to create a `create table` query.
*/
export class CreateTableBuilder<TB extends string, C extends string = never>
implements OperationNodeSource, Compilable
{
readonly #props: CreateTableBuilderProps
constructor(props: CreateTableBuilderProps) {
this.#props = freeze(props)
}
/**
* Adds the "if not exists" modifier.
*
* If the table already exists, no error is thrown if this method has been called.
*/
ifNotExists(): CreateTableBuilder<TB, C> {
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithModifier(
this.#props.createTableNode,
'IfNotExists'
),
})
}
/**
* Adds a column to the table.
*
* @example
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', (col) => col.increments().primaryKey()),
* .addColumn('first_name', 'varchar(50), (col) => col.notNull())
* .addColumn('last_name', 'varchar')
* .addColumn('bank_balance', 'numeric(8, 2)')
* .addColumn('data', db.raw('customtype'))
* .addColumn('parent_id', 'integer', (col) =>
* col.references('person.id').onDelete('cascade'))
* )
* ```
*
* With this method, it's once again good to remember that Kysely just builds the query
* that's as close to the structure of your builder method calls as possible, and doesn't
* provide the same API for all databses. For example, some databases like older MySQL
* don't support `references` statement in the column definition. Instead foreign key
* constraints need to be defined in at the level of the `create table` query. See
* the next example:
*
* @example
* ```ts
* .addColumn('parent_id', 'integer')
* .addForeignKeyConstraint(
* 'person_parent_id_fk', ['parent_id'], 'person', ['id'],
* (cb) => cb.onDelete('cascade')
* )
* ```
*
* Another good example is that PostgreSQL doesn't support the `auto_increment`
* keyword and you need to define an autoincrementing column for example using
* `serial`:
*
* @example
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'serial', (col) => col.primaryKey()),
* ```
*/
addColumn<CN extends string>(
columnName: CN,
dataType: DataTypeExpression,
build: ColumnBuilderCallback = noop
): CreateTableBuilder<TB, C | CN> {
const columnBuilder = build(
new ColumnDefinitionBuilder(
ColumnDefinitionNode.create(
columnName,
parseDataTypeExpression(dataType)
)
)
)
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithColumn(
this.#props.createTableNode,
columnBuilder.toOperationNode()
),
})
}
/**
* Adds a primary key constraint for one or more columns.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* @example
* ```ts
* addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
* ```
*/
addPrimaryKeyConstraint(
constraintName: string,
columns: C[]
): CreateTableBuilder<TB, C> {
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithConstraint(
this.#props.createTableNode,
PrimaryConstraintNode.create(columns, constraintName)
),
})
}
/**
* Adds a unique constraint for one or more columns.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* @example
* ```ts
* addUniqueConstraint('first_name_last_name_unique', ['first_name', 'last_name'])
* ```
*/
addUniqueConstraint(
constraintName: string,
columns: C[]
): CreateTableBuilder<TB, C> {
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithConstraint(
this.#props.createTableNode,
UniqueConstraintNode.create(columns, constraintName)
),
})
}
/**
* Adds a check constraint.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* @example
* ```ts
* addCheckConstraint('check_legs', 'number_of_legs < 5')
* ```
*/
addCheckConstraint(
constraintName: string,
checkExpression: string
): CreateTableBuilder<TB, C> {
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithConstraint(
this.#props.createTableNode,
CheckConstraintNode.create(checkExpression, constraintName)
),
})
}
/**
* Adds a foreign key constraint.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* @example
* ```ts
* addForeignKeyConstraint(
* 'owner_id_foreign',
* ['owner_id'],
* 'person',
* ['id'],
* )
* ```
*
* @example
* ```ts
* addForeignKeyConstraint(
* 'owner_id_foreign',
* ['owner_id1', 'owner_id2'],
* 'person',
* ['id1', 'id2'],
* (cb) => cb.onDelete('cascade')
* )
* ```
*/
addForeignKeyConstraint(
constraintName: string,
columns: C[],
targetTable: string,
targetColumns: string[],
build: ForeignKeyConstraintBuilderCallback = noop
): CreateTableBuilder<TB, C> {
const builder = build(
new ForeignKeyConstraintBuilder(
ForeignKeyConstraintNode.create(
columns.map(ColumnNode.create),
TableNode.create(targetTable),
targetColumns.map(ColumnNode.create),
constraintName
)
)
)
return new CreateTableBuilder({
...this.#props,
createTableNode: CreateTableNode.cloneWithConstraint(
this.#props.createTableNode,
builder.toOperationNode()
),
})
}
toOperationNode(): CreateTableNode {
return this.#props.executor.transformQuery(
this.#props.createTableNode,
this.#props.queryId
)
}
compile(): CompiledQuery {
return this.#props.executor.compileQuery(
this.toOperationNode(),
this.#props.queryId
)
}
async execute(): Promise<void> {
await this.#props.executor.executeQuery(this.compile(), this.#props.queryId)
}
}
preventAwait(
CreateTableBuilder,
"don't await CreateTableBuilder instances directly. To execute the query you need to call `execute`"
)
export interface CreateTableBuilderProps {
readonly queryId: QueryId
readonly executor: QueryExecutor
readonly createTableNode: CreateTableNode
}
export type ColumnBuilderCallback = (
builder: ColumnDefinitionBuilder
) => ColumnDefinitionBuilder
export type ForeignKeyConstraintBuilderCallback = (
builder: ForeignKeyConstraintBuilder
) => ForeignKeyConstraintBuilder