kysely 0.7.9 → 0.9.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.
Files changed (70) hide show
  1. package/README.md +47 -8
  2. package/dist/cjs/dialect/mysql/mysql-driver.js +5 -5
  3. package/dist/cjs/dialect/mysql/mysql-query-compiler.d.ts +0 -2
  4. package/dist/cjs/dialect/mysql/mysql-query-compiler.js +0 -29
  5. package/dist/cjs/dialect/postgres/postgres-driver.js +5 -5
  6. package/dist/cjs/operation-node/create-schema-node.d.ts +1 -1
  7. package/dist/cjs/operation-node/create-schema-node.js +2 -2
  8. package/dist/cjs/operation-node/create-table-node.d.ts +1 -5
  9. package/dist/cjs/operation-node/create-table-node.js +1 -31
  10. package/dist/cjs/operation-node/operation-node-source.d.ts +1 -1
  11. package/dist/cjs/operation-node/operation-node-transformer.js +2 -1
  12. package/dist/cjs/operation-node/primitive-value-list-node.js +1 -1
  13. package/dist/cjs/parser/join-parser.d.ts +6 -3
  14. package/dist/cjs/parser/table-parser.d.ts +18 -7
  15. package/dist/cjs/query-builder/function-builder.d.ts +6 -6
  16. package/dist/cjs/query-builder/function-builder.js +7 -7
  17. package/dist/cjs/query-builder/query-builder.d.ts +7 -7
  18. package/dist/cjs/query-compiler/compiled-query.d.ts +1 -1
  19. package/dist/cjs/query-compiler/default-query-compiler.d.ts +3 -2
  20. package/dist/cjs/query-compiler/default-query-compiler.js +22 -28
  21. package/dist/cjs/query-creator.d.ts +14 -11
  22. package/dist/cjs/query-creator.js +14 -11
  23. package/dist/cjs/raw-builder/raw-builder.d.ts +1 -1
  24. package/dist/cjs/raw-builder/raw-builder.js +6 -6
  25. package/dist/cjs/schema/alter-table-builder.d.ts +3 -0
  26. package/dist/cjs/schema/alter-table-builder.js +3 -0
  27. package/dist/cjs/schema/column-definition-builder.d.ts +14 -5
  28. package/dist/cjs/schema/create-schema-builder.js +1 -1
  29. package/dist/cjs/schema/create-table-builder.d.ts +55 -10
  30. package/dist/cjs/schema/create-table-builder.js +59 -17
  31. package/dist/cjs/schema/schema.d.ts +37 -2
  32. package/dist/cjs/schema/schema.js +36 -1
  33. package/dist/cjs/util/object-utils.d.ts +1 -0
  34. package/dist/cjs/util/object-utils.js +5 -1
  35. package/dist/cjs/util/type-utils.d.ts +3 -0
  36. package/dist/esm/dialect/mysql/mysql-driver.js +5 -5
  37. package/dist/esm/dialect/mysql/mysql-query-compiler.d.ts +0 -2
  38. package/dist/esm/dialect/mysql/mysql-query-compiler.js +0 -29
  39. package/dist/esm/dialect/postgres/postgres-driver.js +5 -5
  40. package/dist/esm/operation-node/create-schema-node.d.ts +1 -1
  41. package/dist/esm/operation-node/create-schema-node.js +2 -2
  42. package/dist/esm/operation-node/create-table-node.d.ts +1 -5
  43. package/dist/esm/operation-node/create-table-node.js +1 -31
  44. package/dist/esm/operation-node/operation-node-source.d.ts +1 -1
  45. package/dist/esm/operation-node/operation-node-transformer.js +2 -1
  46. package/dist/esm/operation-node/primitive-value-list-node.js +1 -1
  47. package/dist/esm/parser/join-parser.d.ts +6 -3
  48. package/dist/esm/parser/table-parser.d.ts +18 -7
  49. package/dist/esm/query-builder/function-builder.d.ts +6 -6
  50. package/dist/esm/query-builder/function-builder.js +7 -7
  51. package/dist/esm/query-builder/query-builder.d.ts +7 -7
  52. package/dist/esm/query-compiler/compiled-query.d.ts +1 -1
  53. package/dist/esm/query-compiler/default-query-compiler.d.ts +3 -2
  54. package/dist/esm/query-compiler/default-query-compiler.js +22 -28
  55. package/dist/esm/query-creator.d.ts +14 -11
  56. package/dist/esm/query-creator.js +14 -11
  57. package/dist/esm/raw-builder/raw-builder.d.ts +1 -1
  58. package/dist/esm/raw-builder/raw-builder.js +6 -6
  59. package/dist/esm/schema/alter-table-builder.d.ts +3 -0
  60. package/dist/esm/schema/alter-table-builder.js +3 -0
  61. package/dist/esm/schema/column-definition-builder.d.ts +14 -5
  62. package/dist/esm/schema/create-schema-builder.js +1 -1
  63. package/dist/esm/schema/create-table-builder.d.ts +55 -10
  64. package/dist/esm/schema/create-table-builder.js +60 -18
  65. package/dist/esm/schema/schema.d.ts +37 -2
  66. package/dist/esm/schema/schema.js +36 -1
  67. package/dist/esm/util/object-utils.d.ts +1 -0
  68. package/dist/esm/util/object-utils.js +3 -0
  69. package/dist/esm/util/type-utils.d.ts +3 -0
  70. package/package.json +6 -6
@@ -10,7 +10,7 @@ export declare class QueryCreator<DB> {
10
10
  #private;
11
11
  constructor(props: QueryCreatorProps);
12
12
  /**
13
- * Creates a `select` query builder against the given table/tables.
13
+ * Creates a `select` query builder for the given table or tables.
14
14
  *
15
15
  * The tables passed to this method are built as the query's `from` clause.
16
16
  *
@@ -221,6 +221,9 @@ export declare class QueryCreator<DB> {
221
221
  * Sets the schema to be used for all table references that don't explicitly
222
222
  * specify a schema.
223
223
  *
224
+ * This only affects the query created through the builder returned from
225
+ * this method and doesn't modify the `db` instance.
226
+ *
224
227
  * @example
225
228
  * ```
226
229
  * await db.withSchema('mammals')
@@ -261,10 +264,10 @@ export declare class QueryCreator<DB> {
261
264
  * Provides a way to pass arbitrary SQL into your query and executing completely
262
265
  * raw queries.
263
266
  *
264
- * You can use strings `?` and `??` in the `sql` to bind parameters such as
267
+ * You can use the strings `?` and `??` in the `sql` to bind parameters such as
265
268
  * user input to the SQL. You should never EVER concatenate untrusted user
266
269
  * input to the SQL string to avoid injection vulnerabilities. Instead use `?`
267
- * in place of the value and pass the actual value in the `params` list. See
270
+ * in place of a value and pass the actual value in the `parameters` list. See
268
271
  * the examples below.
269
272
  *
270
273
  * You should only use `raw` when there is no other way to get the job done. This is
@@ -276,11 +279,11 @@ export declare class QueryCreator<DB> {
276
279
  * Raw builder instances can be passed to pretty much anywhere: `select`, `where`,
277
280
  * `*Join`, `groupBy`, `orderBy` etc. Just try it. If the method accepts it, it works.
278
281
  *
279
- * @param sql - The raw SQL. Special strings `?` and `??` can be used to provide
280
- * parameter bindings. `?` for values and `??` for identifiers such as column names
282
+ * @param sql - The raw SQL. Special strings `?` and `??` can be used as parameter
283
+ * placeholders. `?` for values and `??` for identifiers such as column names
281
284
  * or `column.table` references.
282
285
  *
283
- * @param params - The parameters that will be bound to the `?` and `??` bindings in
286
+ * @param params - The parameters that will be bound to the `?` and `??` placeholders in
284
287
  * the sql string.
285
288
  *
286
289
  * @example
@@ -318,7 +321,7 @@ export declare class QueryCreator<DB> {
318
321
  * the output type. In this case you need to use the `castTo` method on the query
319
322
  * to specify a return type for the query.
320
323
  *
321
- * We could've also used `??` bindings to provide `first_name` and `last_name` like
324
+ * We could've also used a `??` placeholder to provide `first_name` and `last_name` like
322
325
  * this:
323
326
  *
324
327
  * ```ts
@@ -333,9 +336,9 @@ export declare class QueryCreator<DB> {
333
336
  *
334
337
  * But it's often cleaner to just write the column names in the SQL. Again remember to
335
338
  * never concatenate column names or any other untrusted user input to the SQL string or you
336
- * are going to create an injection vulnerability. All user input should go to the bindings
339
+ * are going to create an injection vulnerability. All user input should go to the parameters
337
340
  * array, never to the SQL string directly. But if the column names or values are trusted
338
- * and known at compile time, there is no reason to use bindings.
341
+ * and known at compile time, there is no reason to use parameters.
339
342
  *
340
343
  * @example
341
344
  * Example of using `raw` in `where`:
@@ -361,7 +364,7 @@ export declare class QueryCreator<DB> {
361
364
  *
362
365
  * The function in the above example returns people that are older than the given number of
363
366
  * years. The number of years in this example is an untrusted user input, and therefore we use
364
- * a `?` binding for it.
367
+ * a `?` placeholder for it.
365
368
  *
366
369
  * @example
367
370
  * Example of creating a completely raw query from scratch:
@@ -375,7 +378,7 @@ export declare class QueryCreator<DB> {
375
378
  * The result of `execute()` method is always an array. In this case the type of
376
379
  * the `persons` variable is `Person[]`.
377
380
  */
378
- raw<T = unknown>(sql: string, params?: any[]): RawBuilder<T>;
381
+ raw<T = unknown>(sql: string, parameters?: any[]): RawBuilder<T>;
379
382
  }
380
383
  export interface QueryCreatorProps {
381
384
  readonly executor: QueryExecutor;
@@ -158,6 +158,9 @@ class QueryCreator {
158
158
  * Sets the schema to be used for all table references that don't explicitly
159
159
  * specify a schema.
160
160
  *
161
+ * This only affects the query created through the builder returned from
162
+ * this method and doesn't modify the `db` instance.
163
+ *
161
164
  * @example
162
165
  * ```
163
166
  * await db.withSchema('mammals')
@@ -203,10 +206,10 @@ class QueryCreator {
203
206
  * Provides a way to pass arbitrary SQL into your query and executing completely
204
207
  * raw queries.
205
208
  *
206
- * You can use strings `?` and `??` in the `sql` to bind parameters such as
209
+ * You can use the strings `?` and `??` in the `sql` to bind parameters such as
207
210
  * user input to the SQL. You should never EVER concatenate untrusted user
208
211
  * input to the SQL string to avoid injection vulnerabilities. Instead use `?`
209
- * in place of the value and pass the actual value in the `params` list. See
212
+ * in place of a value and pass the actual value in the `parameters` list. See
210
213
  * the examples below.
211
214
  *
212
215
  * You should only use `raw` when there is no other way to get the job done. This is
@@ -218,11 +221,11 @@ class QueryCreator {
218
221
  * Raw builder instances can be passed to pretty much anywhere: `select`, `where`,
219
222
  * `*Join`, `groupBy`, `orderBy` etc. Just try it. If the method accepts it, it works.
220
223
  *
221
- * @param sql - The raw SQL. Special strings `?` and `??` can be used to provide
222
- * parameter bindings. `?` for values and `??` for identifiers such as column names
224
+ * @param sql - The raw SQL. Special strings `?` and `??` can be used as parameter
225
+ * placeholders. `?` for values and `??` for identifiers such as column names
223
226
  * or `column.table` references.
224
227
  *
225
- * @param params - The parameters that will be bound to the `?` and `??` bindings in
228
+ * @param params - The parameters that will be bound to the `?` and `??` placeholders in
226
229
  * the sql string.
227
230
  *
228
231
  * @example
@@ -260,7 +263,7 @@ class QueryCreator {
260
263
  * the output type. In this case you need to use the `castTo` method on the query
261
264
  * to specify a return type for the query.
262
265
  *
263
- * We could've also used `??` bindings to provide `first_name` and `last_name` like
266
+ * We could've also used a `??` placeholder to provide `first_name` and `last_name` like
264
267
  * this:
265
268
  *
266
269
  * ```ts
@@ -275,9 +278,9 @@ class QueryCreator {
275
278
  *
276
279
  * But it's often cleaner to just write the column names in the SQL. Again remember to
277
280
  * never concatenate column names or any other untrusted user input to the SQL string or you
278
- * are going to create an injection vulnerability. All user input should go to the bindings
281
+ * are going to create an injection vulnerability. All user input should go to the parameters
279
282
  * array, never to the SQL string directly. But if the column names or values are trusted
280
- * and known at compile time, there is no reason to use bindings.
283
+ * and known at compile time, there is no reason to use parameters.
281
284
  *
282
285
  * @example
283
286
  * Example of using `raw` in `where`:
@@ -303,7 +306,7 @@ class QueryCreator {
303
306
  *
304
307
  * The function in the above example returns people that are older than the given number of
305
308
  * years. The number of years in this example is an untrusted user input, and therefore we use
306
- * a `?` binding for it.
309
+ * a `?` placeholder for it.
307
310
  *
308
311
  * @example
309
312
  * Example of creating a completely raw query from scratch:
@@ -317,12 +320,12 @@ class QueryCreator {
317
320
  * The result of `execute()` method is always an array. In this case the type of
318
321
  * the `persons` variable is `Person[]`.
319
322
  */
320
- raw(sql, params) {
323
+ raw(sql, parameters) {
321
324
  return new raw_builder_js_1.RawBuilder({
322
325
  queryId: (0, query_id_js_1.createQueryId)(),
323
326
  executor: this.#props.executor,
324
327
  sql,
325
- params,
328
+ parameters,
326
329
  });
327
330
  }
328
331
  }
@@ -41,5 +41,5 @@ export interface RawBuilderProps {
41
41
  readonly queryId: QueryId;
42
42
  readonly executor: QueryExecutor;
43
43
  readonly sql: string;
44
- readonly params?: any;
44
+ readonly parameters?: any;
45
45
  }
@@ -28,24 +28,24 @@ class RawBuilder {
28
28
  });
29
29
  }
30
30
  toOperationNode() {
31
- const bindingRegex = /(\?\??)/g;
31
+ const parameterPlaceholderRegex = /(\?\??)/g;
32
32
  const sql = this.#props.sql;
33
- const params = this.#props.params ?? [];
33
+ const parameters = this.#props.parameters ?? [];
34
34
  const sqlFragments = [];
35
35
  const argNodes = [];
36
36
  let paramIdx = 0;
37
37
  let sqlIdx = 0;
38
38
  let match = null;
39
- while ((match = bindingRegex.exec(sql))) {
39
+ while ((match = parameterPlaceholderRegex.exec(sql))) {
40
40
  const str = match[1];
41
- if (paramIdx >= params.length) {
42
- throw new Error(`value not provided for all bindings in string ${sql}`);
41
+ if (paramIdx >= parameters.length) {
42
+ throw new Error(`value not provided for all placeholders in string ${sql}`);
43
43
  }
44
44
  if (match.index > 0 && sql[match.index - 1] === '\\') {
45
45
  continue;
46
46
  }
47
47
  sqlFragments.push(sql.slice(sqlIdx, match.index).replaceAll('\\?', '?'));
48
- argNodes.push(parseRawArg(str, params[paramIdx]));
48
+ argNodes.push(parseRawArg(str, parameters[paramIdx]));
49
49
  sqlIdx = match.index + str.length;
50
50
  ++paramIdx;
51
51
  }
@@ -12,6 +12,9 @@ import { QueryId } from '../util/query-id.js';
12
12
  import { QueryExecutor } from '../query-executor/query-executor.js';
13
13
  import { DataTypeExpression } from '../parser/data-type-parser.js';
14
14
  import { ForeignKeyConstraintBuilder, ForeignKeyConstraintBuilderInterface } from './foreign-key-constraint-builder.js';
15
+ /**
16
+ * This builder can be used to create a `alter table` query.
17
+ */
15
18
  export declare class AlterTableBuilder {
16
19
  #private;
17
20
  constructor(props: AlterTableBuilderProps);
@@ -23,6 +23,9 @@ const unique_constraint_node_js_1 = require("../operation-node/unique-constraint
23
23
  const check_constraint_node_js_1 = require("../operation-node/check-constraint-node.js");
24
24
  const foreign_key_constraint_node_js_1 = require("../operation-node/foreign-key-constraint-node.js");
25
25
  const column_node_js_1 = require("../operation-node/column-node.js");
26
+ /**
27
+ * This builder can be used to create a `alter table` query.
28
+ */
26
29
  class AlterTableBuilder {
27
30
  #props;
28
31
  constructor(props) {
@@ -6,11 +6,11 @@ import { AnyRawBuilder } from '../util/type-utils.js';
6
6
  import { DefaultValueExpression } from '../parser/default-value-parser.js';
7
7
  export interface ColumnDefinitionBuilderInterface<R> {
8
8
  /**
9
- * Makes the column automatically incrementing.
9
+ * Adds `auto_increment` or `autoincrement` to the column definition
10
+ * depending on the dialect.
10
11
  *
11
- * On some dialects this may change the column type as well. For example
12
- * on postgres this sets the column type to `serial` no matter what you
13
- * have specified before.
12
+ * Some dialects like PostgreSQL don't support this. On PostgreSQL
13
+ * you can use the `serial` or `bigserial` data type instead.
14
14
  */
15
15
  increments(): R;
16
16
  /**
@@ -23,6 +23,10 @@ export interface ColumnDefinitionBuilderInterface<R> {
23
23
  /**
24
24
  * Adds a foreign key constraint for the column.
25
25
  *
26
+ * If your database engine doesn't support foreign key constraints in the
27
+ * column definition (like MySQL 5) you need to call the table level
28
+ * {@link TableBuilder.addForeignKeyConstraint} method instead.
29
+ *
26
30
  * @example
27
31
  * ```ts
28
32
  * col.references('person.id')
@@ -31,6 +35,11 @@ export interface ColumnDefinitionBuilderInterface<R> {
31
35
  references(ref: string): R;
32
36
  /**
33
37
  * Adds an `on delete` constraint for the foreign key column.
38
+ *
39
+ * If your database engine doesn't support foreign key constraints in the
40
+ * column definition (like MySQL 5) you need to call the table level
41
+ * {@link TableBuilder.addForeignKeyConstraint} method instead.
42
+ *
34
43
  */
35
44
  onDelete(onDelete: OnModifyForeignAction): R;
36
45
  /**
@@ -64,7 +73,7 @@ export interface ColumnDefinitionBuilderInterface<R> {
64
73
  * ```ts
65
74
  * db.schema
66
75
  * .createTable('pet')
67
- * .addColumn('number_of_legs', (col) => col.check('number_of_legs < 5', 'integer'))
76
+ * .addColumn('number_of_legs', 'integer', (col) => col.check('number_of_legs < 5'))
68
77
  * .execute()
69
78
  * ```
70
79
  */
@@ -12,7 +12,7 @@ class CreateSchemaBuilder {
12
12
  ifNotExists() {
13
13
  return new CreateSchemaBuilder({
14
14
  ...this.#props,
15
- createSchemaNode: create_schema_node_js_1.CreateSchemaNode.cloneWithModifier(this.#props.createSchemaNode, 'IfNotExists'),
15
+ createSchemaNode: create_schema_node_js_1.CreateSchemaNode.cloneWith(this.#props.createSchemaNode, { modifier: 'IfNotExists' }),
16
16
  });
17
17
  }
18
18
  toOperationNode() {
@@ -7,7 +7,10 @@ import { ColumnDefinitionBuilder } from './column-definition-builder.js';
7
7
  import { QueryId } from '../util/query-id.js';
8
8
  import { ForeignKeyConstraintBuilder } from './foreign-key-constraint-builder.js';
9
9
  import { DataTypeExpression } from '../parser/data-type-parser.js';
10
- export declare class CreateTableBuilder implements OperationNodeSource, Compilable {
10
+ /**
11
+ * This builder can be used to create a `create table` query.
12
+ */
13
+ export declare class CreateTableBuilder<TB extends string, C extends string = never> implements OperationNodeSource, Compilable {
11
14
  #private;
12
15
  constructor(props: CreateTableBuilderProps);
13
16
  /**
@@ -15,7 +18,7 @@ export declare class CreateTableBuilder implements OperationNodeSource, Compilab
15
18
  *
16
19
  * If the table already exists, no error is thrown if this method has been called.
17
20
  */
18
- ifNotExists(): CreateTableBuilder;
21
+ ifNotExists(): CreateTableBuilder<TB, C>;
19
22
  /**
20
23
  * Adds a column to the table.
21
24
  *
@@ -23,44 +26,86 @@ export declare class CreateTableBuilder implements OperationNodeSource, Compilab
23
26
  * ```ts
24
27
  * await db.schema
25
28
  * .createTable('person')
26
- * .addColumn('int', 'id', (col) => col.increments().primary()),
29
+ * .addColumn('id', 'integer', (col) => col.increments().primaryKey()),
27
30
  * .addColumn('first_name', 'varchar(50), (col) => col.notNull())
28
- * .addColumn('varchar', 'last_name')
29
- * .addColumn('numeric(8, 2)', 'bank_balance')
31
+ * .addColumn('last_name', 'varchar')
32
+ * .addColumn('bank_balance', 'numeric(8, 2)')
30
33
  * .addColumn('data', db.raw('customtype'))
34
+ * .addColumn('parent_id', 'integer', (col) =>
35
+ * col.references('person.id').onDelete('cascade'))
36
+ * )
37
+ * ```
38
+ *
39
+ * With this method, it's once again good to remember that Kysely just builds the query
40
+ * that's as close to the structure of your builder method calls as possible, and doesn't
41
+ * provide the same API for all databses. For example, some databases like older MySQL
42
+ * don't support `references` statement in the column definition. Instead foreign key
43
+ * constraints need to be defined in at the level of the `create table` query. See
44
+ * the next example:
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * .addColumn('parent_id', 'integer')
49
+ * .addForeignKeyConstraint(
50
+ * 'person_parent_id_fk', ['parent_id'], 'person', ['id'],
51
+ * (cb) => cb.onDelete('cascade')
52
+ * )
53
+ * ```
54
+ *
55
+ * Another good example is that PostgreSQL doesn't support the `auto_increment`
56
+ * keyword and you need to define an autoincrementing column for example using
57
+ * `serial`:
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * await db.schema
62
+ * .createTable('person')
63
+ * .addColumn('id', 'serial', (col) => col.primaryKey()),
31
64
  * ```
32
65
  */
33
- addColumn(columnName: string, dataType: DataTypeExpression, build?: ColumnBuilderCallback): CreateTableBuilder;
66
+ addColumn<CN extends string>(columnName: CN, dataType: DataTypeExpression, build?: ColumnBuilderCallback): CreateTableBuilder<TB, C | CN>;
34
67
  /**
35
68
  * Adds a primary key constraint for one or more columns.
36
69
  *
70
+ * The constraint name can be anything you want, but it must be unique
71
+ * across the whole database.
72
+ *
37
73
  * @example
38
74
  * ```ts
39
75
  * addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
40
76
  * ```
41
77
  */
42
- addPrimaryKeyConstraint(constraintName: string, columns: string[]): CreateTableBuilder;
78
+ addPrimaryKeyConstraint(constraintName: string, columns: C[]): CreateTableBuilder<TB, C>;
43
79
  /**
44
80
  * Adds a unique constraint for one or more columns.
45
81
  *
82
+ * The constraint name can be anything you want, but it must be unique
83
+ * across the whole database.
84
+ *
46
85
  * @example
47
86
  * ```ts
48
87
  * addUniqueConstraint('first_name_last_name_unique', ['first_name', 'last_name'])
49
88
  * ```
50
89
  */
51
- addUniqueConstraint(constraintName: string, columns: string[]): CreateTableBuilder;
90
+ addUniqueConstraint(constraintName: string, columns: C[]): CreateTableBuilder<TB, C>;
52
91
  /**
53
92
  * Adds a check constraint.
54
93
  *
94
+ * The constraint name can be anything you want, but it must be unique
95
+ * across the whole database.
96
+ *
55
97
  * @example
56
98
  * ```ts
57
99
  * addCheckConstraint('check_legs', 'number_of_legs < 5')
58
100
  * ```
59
101
  */
60
- addCheckConstraint(constraintName: string, checkExpression: string): CreateTableBuilder;
102
+ addCheckConstraint(constraintName: string, checkExpression: string): CreateTableBuilder<TB, C>;
61
103
  /**
62
104
  * Adds a foreign key constraint.
63
105
  *
106
+ * The constraint name can be anything you want, but it must be unique
107
+ * across the whole database.
108
+ *
64
109
  * @example
65
110
  * ```ts
66
111
  * addForeignKeyConstraint(
@@ -82,7 +127,7 @@ export declare class CreateTableBuilder implements OperationNodeSource, Compilab
82
127
  * )
83
128
  * ```
84
129
  */
85
- addForeignKeyConstraint(constraintName: string, columns: string[], targetTable: string, targetColumns: string[], build?: ForeignKeyConstraintBuilderCallback): CreateTableBuilder;
130
+ addForeignKeyConstraint(constraintName: string, columns: C[], targetTable: string, targetColumns: string[], build?: ForeignKeyConstraintBuilderCallback): CreateTableBuilder<TB, C>;
86
131
  toOperationNode(): CreateTableNode;
87
132
  compile(): CompiledQuery;
88
133
  execute(): Promise<void>;
@@ -11,6 +11,12 @@ const column_node_js_1 = require("../operation-node/column-node.js");
11
11
  const table_node_js_1 = require("../operation-node/table-node.js");
12
12
  const foreign_key_constraint_builder_js_1 = require("./foreign-key-constraint-builder.js");
13
13
  const data_type_parser_js_1 = require("../parser/data-type-parser.js");
14
+ const primary_constraint_node_js_1 = require("../operation-node/primary-constraint-node.js");
15
+ const unique_constraint_node_js_1 = require("../operation-node/unique-constraint-node.js");
16
+ const check_constraint_node_js_1 = require("../operation-node/check-constraint-node.js");
17
+ /**
18
+ * This builder can be used to create a `create table` query.
19
+ */
14
20
  class CreateTableBuilder {
15
21
  #props;
16
22
  constructor(props) {
@@ -34,18 +40,45 @@ class CreateTableBuilder {
34
40
  * ```ts
35
41
  * await db.schema
36
42
  * .createTable('person')
37
- * .addColumn('int', 'id', (col) => col.increments().primary()),
43
+ * .addColumn('id', 'integer', (col) => col.increments().primaryKey()),
38
44
  * .addColumn('first_name', 'varchar(50), (col) => col.notNull())
39
- * .addColumn('varchar', 'last_name')
40
- * .addColumn('numeric(8, 2)', 'bank_balance')
45
+ * .addColumn('last_name', 'varchar')
46
+ * .addColumn('bank_balance', 'numeric(8, 2)')
41
47
  * .addColumn('data', db.raw('customtype'))
48
+ * .addColumn('parent_id', 'integer', (col) =>
49
+ * col.references('person.id').onDelete('cascade'))
50
+ * )
51
+ * ```
52
+ *
53
+ * With this method, it's once again good to remember that Kysely just builds the query
54
+ * that's as close to the structure of your builder method calls as possible, and doesn't
55
+ * provide the same API for all databses. For example, some databases like older MySQL
56
+ * don't support `references` statement in the column definition. Instead foreign key
57
+ * constraints need to be defined in at the level of the `create table` query. See
58
+ * the next example:
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * .addColumn('parent_id', 'integer')
63
+ * .addForeignKeyConstraint(
64
+ * 'person_parent_id_fk', ['parent_id'], 'person', ['id'],
65
+ * (cb) => cb.onDelete('cascade')
66
+ * )
67
+ * ```
68
+ *
69
+ * Another good example is that PostgreSQL doesn't support the `auto_increment`
70
+ * keyword and you need to define an autoincrementing column for example using
71
+ * `serial`:
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * await db.schema
76
+ * .createTable('person')
77
+ * .addColumn('id', 'serial', (col) => col.primaryKey()),
42
78
  * ```
43
79
  */
44
- addColumn(columnName, dataType, build) {
45
- let columnBuilder = new column_definition_builder_js_1.ColumnDefinitionBuilder(column_definition_node_js_1.ColumnDefinitionNode.create(columnName, (0, data_type_parser_js_1.parseDataTypeExpression)(dataType)));
46
- if (build) {
47
- columnBuilder = build(columnBuilder);
48
- }
80
+ addColumn(columnName, dataType, build = object_utils_js_1.noop) {
81
+ const columnBuilder = build(new column_definition_builder_js_1.ColumnDefinitionBuilder(column_definition_node_js_1.ColumnDefinitionNode.create(columnName, (0, data_type_parser_js_1.parseDataTypeExpression)(dataType))));
49
82
  return new CreateTableBuilder({
50
83
  ...this.#props,
51
84
  createTableNode: create_table_node_js_1.CreateTableNode.cloneWithColumn(this.#props.createTableNode, columnBuilder.toOperationNode()),
@@ -54,6 +87,9 @@ class CreateTableBuilder {
54
87
  /**
55
88
  * Adds a primary key constraint for one or more columns.
56
89
  *
90
+ * The constraint name can be anything you want, but it must be unique
91
+ * across the whole database.
92
+ *
57
93
  * @example
58
94
  * ```ts
59
95
  * addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
@@ -62,12 +98,15 @@ class CreateTableBuilder {
62
98
  addPrimaryKeyConstraint(constraintName, columns) {
63
99
  return new CreateTableBuilder({
64
100
  ...this.#props,
65
- createTableNode: create_table_node_js_1.CreateTableNode.cloneWithPrimaryKeyConstraint(this.#props.createTableNode, constraintName, columns),
101
+ createTableNode: create_table_node_js_1.CreateTableNode.cloneWithConstraint(this.#props.createTableNode, primary_constraint_node_js_1.PrimaryConstraintNode.create(columns, constraintName)),
66
102
  });
67
103
  }
68
104
  /**
69
105
  * Adds a unique constraint for one or more columns.
70
106
  *
107
+ * The constraint name can be anything you want, but it must be unique
108
+ * across the whole database.
109
+ *
71
110
  * @example
72
111
  * ```ts
73
112
  * addUniqueConstraint('first_name_last_name_unique', ['first_name', 'last_name'])
@@ -76,12 +115,15 @@ class CreateTableBuilder {
76
115
  addUniqueConstraint(constraintName, columns) {
77
116
  return new CreateTableBuilder({
78
117
  ...this.#props,
79
- createTableNode: create_table_node_js_1.CreateTableNode.cloneWithUniqueConstraint(this.#props.createTableNode, constraintName, columns),
118
+ createTableNode: create_table_node_js_1.CreateTableNode.cloneWithConstraint(this.#props.createTableNode, unique_constraint_node_js_1.UniqueConstraintNode.create(columns, constraintName)),
80
119
  });
81
120
  }
82
121
  /**
83
122
  * Adds a check constraint.
84
123
  *
124
+ * The constraint name can be anything you want, but it must be unique
125
+ * across the whole database.
126
+ *
85
127
  * @example
86
128
  * ```ts
87
129
  * addCheckConstraint('check_legs', 'number_of_legs < 5')
@@ -90,12 +132,15 @@ class CreateTableBuilder {
90
132
  addCheckConstraint(constraintName, checkExpression) {
91
133
  return new CreateTableBuilder({
92
134
  ...this.#props,
93
- createTableNode: create_table_node_js_1.CreateTableNode.cloneWithCheckConstraint(this.#props.createTableNode, constraintName, checkExpression),
135
+ createTableNode: create_table_node_js_1.CreateTableNode.cloneWithConstraint(this.#props.createTableNode, check_constraint_node_js_1.CheckConstraintNode.create(checkExpression, constraintName)),
94
136
  });
95
137
  }
96
138
  /**
97
139
  * Adds a foreign key constraint.
98
140
  *
141
+ * The constraint name can be anything you want, but it must be unique
142
+ * across the whole database.
143
+ *
99
144
  * @example
100
145
  * ```ts
101
146
  * addForeignKeyConstraint(
@@ -117,14 +162,11 @@ class CreateTableBuilder {
117
162
  * )
118
163
  * ```
119
164
  */
120
- addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build) {
121
- let builder = new foreign_key_constraint_builder_js_1.ForeignKeyConstraintBuilder(foreign_key_constraint_node_js_1.ForeignKeyConstraintNode.create(columns.map(column_node_js_1.ColumnNode.create), table_node_js_1.TableNode.create(targetTable), targetColumns.map(column_node_js_1.ColumnNode.create), constraintName));
122
- if (build) {
123
- builder = build(builder);
124
- }
165
+ addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = object_utils_js_1.noop) {
166
+ const builder = build(new foreign_key_constraint_builder_js_1.ForeignKeyConstraintBuilder(foreign_key_constraint_node_js_1.ForeignKeyConstraintNode.create(columns.map(column_node_js_1.ColumnNode.create), table_node_js_1.TableNode.create(targetTable), targetColumns.map(column_node_js_1.ColumnNode.create), constraintName)));
125
167
  return new CreateTableBuilder({
126
168
  ...this.#props,
127
- createTableNode: create_table_node_js_1.CreateTableNode.cloneWithForeignKeyConstraint(this.#props.createTableNode, builder.toOperationNode()),
169
+ createTableNode: create_table_node_js_1.CreateTableNode.cloneWithConstraint(this.#props.createTableNode, builder.toOperationNode()),
128
170
  });
129
171
  }
130
172
  toOperationNode() {
@@ -22,14 +22,49 @@ export declare class SchemaModule {
22
22
  * ```ts
23
23
  * await db.schema
24
24
  * .createTable('person')
25
- * .addColumn('id', 'int', col => col.primaryKey().increments())
25
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
26
26
  * .addColumn('first_name', 'varchar', col => col.notNull())
27
27
  * .addColumn('last_name', 'varchar', col => col.notNull())
28
28
  * .addColumn('gender', 'varchar')
29
29
  * .execute()
30
30
  * ```
31
+ *
32
+ * @example
33
+ * This example creates a table with a foreign key. Not all database
34
+ * engines support column-level foreign key constraint definitions.
35
+ * For example if you are using MySQL 5.X see the next example after
36
+ * this one.
37
+ *
38
+ * ```ts
39
+ * await db.schema
40
+ * .createTable('pet')
41
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
42
+ * .addColumn('owner_id', 'integer', col => col
43
+ * .references('person.id')
44
+ * .onDelete('cascade')
45
+ * )
46
+ * .execute()
47
+ * ```
48
+ *
49
+ * @example
50
+ * This example adds a foreign key constraint for a columns just
51
+ * like the previous example, but using a table-level statement.
52
+ * On MySQL 5.X you need to define foreign key constraints like
53
+ * this:
54
+ *
55
+ * ```ts
56
+ * await db.schema
57
+ * .createTable('pet')
58
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
59
+ * .addColumn('owner_id', 'integer')
60
+ * .addForeignKeyConstraint(
61
+ * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],
62
+ * (constraint) => constraint.onDelete('cascade')
63
+ * )
64
+ * .execute()
65
+ * ```
31
66
  */
32
- createTable(table: string): CreateTableBuilder;
67
+ createTable<TB extends string>(table: TB): CreateTableBuilder<TB, never>;
33
68
  /**
34
69
  * Drop a table.
35
70
  *
@@ -36,12 +36,47 @@ class SchemaModule {
36
36
  * ```ts
37
37
  * await db.schema
38
38
  * .createTable('person')
39
- * .addColumn('id', 'int', col => col.primaryKey().increments())
39
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
40
40
  * .addColumn('first_name', 'varchar', col => col.notNull())
41
41
  * .addColumn('last_name', 'varchar', col => col.notNull())
42
42
  * .addColumn('gender', 'varchar')
43
43
  * .execute()
44
44
  * ```
45
+ *
46
+ * @example
47
+ * This example creates a table with a foreign key. Not all database
48
+ * engines support column-level foreign key constraint definitions.
49
+ * For example if you are using MySQL 5.X see the next example after
50
+ * this one.
51
+ *
52
+ * ```ts
53
+ * await db.schema
54
+ * .createTable('pet')
55
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
56
+ * .addColumn('owner_id', 'integer', col => col
57
+ * .references('person.id')
58
+ * .onDelete('cascade')
59
+ * )
60
+ * .execute()
61
+ * ```
62
+ *
63
+ * @example
64
+ * This example adds a foreign key constraint for a columns just
65
+ * like the previous example, but using a table-level statement.
66
+ * On MySQL 5.X you need to define foreign key constraints like
67
+ * this:
68
+ *
69
+ * ```ts
70
+ * await db.schema
71
+ * .createTable('pet')
72
+ * .addColumn('id', 'integer', col => col.primaryKey().increments())
73
+ * .addColumn('owner_id', 'integer')
74
+ * .addForeignKeyConstraint(
75
+ * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],
76
+ * (constraint) => constraint.onDelete('cascade')
77
+ * )
78
+ * .execute()
79
+ * ```
45
80
  */
46
81
  createTable(table) {
47
82
  return new create_table_builder_js_1.CreateTableBuilder({
@@ -16,3 +16,4 @@ export declare function freeze<T>(obj: T): Readonly<T>;
16
16
  export declare function asArray<T>(arg: T | T[]): T[];
17
17
  export declare function asReadonlyArray<T>(arg: T | ReadonlyArray<T>): ReadonlyArray<T>;
18
18
  export declare function isReadonlyArray(arg: unknown): arg is ReadonlyArray<unknown>;
19
+ export declare function noop<T>(obj: T): T;