kysely 0.8.1 → 0.9.3

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 (110) hide show
  1. package/README.md +47 -4
  2. package/dist/cjs/dialect/mysql/mysql-driver.js +2 -2
  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/operation-node/create-schema-node.d.ts +1 -1
  6. package/dist/cjs/operation-node/create-schema-node.js +2 -2
  7. package/dist/cjs/operation-node/create-table-node.d.ts +1 -5
  8. package/dist/cjs/operation-node/create-table-node.js +1 -31
  9. package/dist/cjs/operation-node/join-node.d.ts +2 -1
  10. package/dist/cjs/operation-node/join-node.js +8 -6
  11. package/dist/cjs/operation-node/operation-node-source.d.ts +1 -1
  12. package/dist/cjs/operation-node/operation-node-transformer.d.ts +2 -0
  13. package/dist/cjs/operation-node/operation-node-transformer.js +11 -1
  14. package/dist/cjs/operation-node/operation-node-visitor.d.ts +61 -59
  15. package/dist/cjs/operation-node/operation-node-visitor.js +1 -316
  16. package/dist/cjs/operation-node/operation-node.d.ts +1 -1
  17. package/dist/cjs/operation-node/primitive-value-list-node.js +1 -1
  18. package/dist/cjs/operation-node/query-node.d.ts +4 -3
  19. package/dist/cjs/operation-node/query-node.js +10 -2
  20. package/dist/cjs/operation-node/select-query-node.d.ts +5 -1
  21. package/dist/cjs/operation-node/select-query-node.js +18 -2
  22. package/dist/cjs/operation-node/union-node.d.ts +16 -0
  23. package/dist/cjs/operation-node/union-node.js +19 -0
  24. package/dist/cjs/parser/group-by-parser.d.ts +4 -0
  25. package/dist/cjs/parser/group-by-parser.js +9 -0
  26. package/dist/cjs/parser/insert-values-parser.d.ts +1 -1
  27. package/dist/cjs/parser/join-parser.d.ts +6 -3
  28. package/dist/cjs/parser/order-by-parser.d.ts +2 -4
  29. package/dist/cjs/parser/order-by-parser.js +6 -3
  30. package/dist/cjs/parser/reference-parser.d.ts +1 -1
  31. package/dist/cjs/parser/reference-parser.js +1 -1
  32. package/dist/cjs/parser/table-parser.d.ts +8 -8
  33. package/dist/cjs/parser/union-parser.d.ts +5 -0
  34. package/dist/cjs/parser/union-parser.js +13 -0
  35. package/dist/cjs/parser/value-parser.d.ts +1 -1
  36. package/dist/cjs/query-builder/function-builder.d.ts +6 -6
  37. package/dist/cjs/query-builder/function-builder.js +6 -6
  38. package/dist/cjs/query-builder/join-builder.js +8 -8
  39. package/dist/cjs/query-builder/query-builder.d.ts +30 -1
  40. package/dist/cjs/query-builder/query-builder.js +66 -22
  41. package/dist/cjs/query-compiler/compiled-query.d.ts +1 -1
  42. package/dist/cjs/query-compiler/default-query-compiler.d.ts +8 -2
  43. package/dist/cjs/query-compiler/default-query-compiler.js +33 -22
  44. package/dist/cjs/query-creator.d.ts +6 -3
  45. package/dist/cjs/query-creator.js +5 -2
  46. package/dist/cjs/schema/alter-table-builder.d.ts +3 -0
  47. package/dist/cjs/schema/alter-table-builder.js +3 -0
  48. package/dist/cjs/schema/column-definition-builder.d.ts +14 -5
  49. package/dist/cjs/schema/create-schema-builder.js +1 -1
  50. package/dist/cjs/schema/create-table-builder.d.ts +55 -10
  51. package/dist/cjs/schema/create-table-builder.js +59 -17
  52. package/dist/cjs/schema/schema.d.ts +37 -2
  53. package/dist/cjs/schema/schema.js +36 -1
  54. package/dist/cjs/util/object-utils.d.ts +12 -11
  55. package/dist/cjs/util/object-utils.js +6 -2
  56. package/dist/esm/dialect/mysql/mysql-driver.js +3 -3
  57. package/dist/esm/dialect/mysql/mysql-query-compiler.d.ts +0 -2
  58. package/dist/esm/dialect/mysql/mysql-query-compiler.js +0 -29
  59. package/dist/esm/operation-node/create-schema-node.d.ts +1 -1
  60. package/dist/esm/operation-node/create-schema-node.js +2 -2
  61. package/dist/esm/operation-node/create-table-node.d.ts +1 -5
  62. package/dist/esm/operation-node/create-table-node.js +1 -31
  63. package/dist/esm/operation-node/join-node.d.ts +2 -1
  64. package/dist/esm/operation-node/join-node.js +8 -6
  65. package/dist/esm/operation-node/operation-node-source.d.ts +1 -1
  66. package/dist/esm/operation-node/operation-node-transformer.d.ts +2 -0
  67. package/dist/esm/operation-node/operation-node-transformer.js +11 -1
  68. package/dist/esm/operation-node/operation-node-visitor.d.ts +61 -59
  69. package/dist/esm/operation-node/operation-node-visitor.js +1 -316
  70. package/dist/esm/operation-node/operation-node.d.ts +1 -1
  71. package/dist/esm/operation-node/primitive-value-list-node.js +1 -1
  72. package/dist/esm/operation-node/query-node.d.ts +4 -3
  73. package/dist/esm/operation-node/query-node.js +10 -2
  74. package/dist/esm/operation-node/select-query-node.d.ts +5 -1
  75. package/dist/esm/operation-node/select-query-node.js +18 -2
  76. package/dist/esm/operation-node/union-node.d.ts +16 -0
  77. package/dist/esm/operation-node/union-node.js +16 -0
  78. package/dist/esm/parser/group-by-parser.d.ts +4 -0
  79. package/dist/esm/parser/group-by-parser.js +5 -0
  80. package/dist/esm/parser/insert-values-parser.d.ts +1 -1
  81. package/dist/esm/parser/join-parser.d.ts +6 -3
  82. package/dist/esm/parser/order-by-parser.d.ts +2 -4
  83. package/dist/esm/parser/order-by-parser.js +6 -2
  84. package/dist/esm/parser/reference-parser.d.ts +1 -1
  85. package/dist/esm/parser/reference-parser.js +2 -2
  86. package/dist/esm/parser/table-parser.d.ts +8 -8
  87. package/dist/esm/parser/union-parser.d.ts +5 -0
  88. package/dist/esm/parser/union-parser.js +9 -0
  89. package/dist/esm/parser/value-parser.d.ts +1 -1
  90. package/dist/esm/query-builder/function-builder.d.ts +6 -6
  91. package/dist/esm/query-builder/function-builder.js +6 -6
  92. package/dist/esm/query-builder/join-builder.js +8 -8
  93. package/dist/esm/query-builder/query-builder.d.ts +30 -1
  94. package/dist/esm/query-builder/query-builder.js +67 -23
  95. package/dist/esm/query-compiler/compiled-query.d.ts +1 -1
  96. package/dist/esm/query-compiler/default-query-compiler.d.ts +8 -2
  97. package/dist/esm/query-compiler/default-query-compiler.js +33 -22
  98. package/dist/esm/query-creator.d.ts +6 -3
  99. package/dist/esm/query-creator.js +5 -2
  100. package/dist/esm/schema/alter-table-builder.d.ts +3 -0
  101. package/dist/esm/schema/alter-table-builder.js +3 -0
  102. package/dist/esm/schema/column-definition-builder.d.ts +14 -5
  103. package/dist/esm/schema/create-schema-builder.js +1 -1
  104. package/dist/esm/schema/create-table-builder.d.ts +55 -10
  105. package/dist/esm/schema/create-table-builder.js +60 -18
  106. package/dist/esm/schema/schema.d.ts +37 -2
  107. package/dist/esm/schema/schema.js +36 -1
  108. package/dist/esm/util/object-utils.d.ts +12 -11
  109. package/dist/esm/util/object-utils.js +4 -1
  110. package/package.json +1 -1
@@ -60,6 +60,8 @@ import { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constrai
60
60
  import { ColumnDefinitionNode } from '../operation-node/column-definition-node.js';
61
61
  import { ModifyColumnNode } from '../operation-node/modify-column-node.js';
62
62
  import { OnDuplicateKeyNode } from '../operation-node/on-duplicate-key-node.js';
63
+ import { ColumnNode } from '../operation-node/column-node.js';
64
+ import { UnionNode } from '../operation-node/union-node.js';
63
65
  export declare class DefaultQueryCompiler extends OperationNodeVisitor implements QueryCompiler {
64
66
  #private;
65
67
  protected get numParameters(): number;
@@ -67,6 +69,8 @@ export declare class DefaultQueryCompiler extends OperationNodeVisitor implement
67
69
  protected getSql(): string;
68
70
  protected visitSelectQuery(node: SelectQueryNode): void;
69
71
  protected visitFrom(node: FromNode): void;
72
+ protected visitSelection(node: SelectionNode): void;
73
+ protected visitColumn(node: ColumnNode): void;
70
74
  protected compileDistinctOn(selections: ReadonlyArray<SelectionNode>): void;
71
75
  protected compileList(nodes: ReadonlyArray<OperationNode>, separator?: string): void;
72
76
  protected visitWhere(node: WhereNode): void;
@@ -92,6 +96,7 @@ export declare class DefaultQueryCompiler extends OperationNodeVisitor implement
92
96
  protected visitTable(node: TableNode): void;
93
97
  protected visitCreateTable(node: CreateTableNode): void;
94
98
  protected visitColumnDefinition(node: ColumnDefinitionNode): void;
99
+ protected getAutoIncrement(): string;
95
100
  protected visitReferences(node: ReferencesNode): void;
96
101
  protected visitDropTable(node: DropTableNode): void;
97
102
  protected visitDataType(node: DataTypeNode): void;
@@ -124,11 +129,12 @@ export declare class DefaultQueryCompiler extends OperationNodeVisitor implement
124
129
  protected visitModifyColumn(node: ModifyColumnNode): void;
125
130
  protected visitAddConstraint(node: AddConstraintNode): void;
126
131
  protected visitDropConstraint(node: DropConstraintNode): void;
132
+ protected visitUnion(node: UnionNode): void;
127
133
  protected append(str: string): void;
128
- protected appendValue(value: PrimitiveValue): void;
134
+ protected appendValue(parameter: unknown): void;
129
135
  protected getLeftIdentifierWrapper(): string;
130
136
  protected getRightIdentifierWrapper(): string;
131
137
  protected getCurrentParameterPlaceholder(): string;
132
- protected addParameter(parameter: any): void;
138
+ protected addParameter(parameter: unknown): void;
133
139
  protected appendImmediateValue(value: PrimitiveValue): void;
134
140
  }
@@ -1,25 +1,24 @@
1
- import { DataTypeNode } from '../operation-node/data-type-node.js';
2
1
  import { OperationNodeVisitor } from '../operation-node/operation-node-visitor.js';
3
2
  import { QueryNode } from '../operation-node/query-node.js';
4
3
  import { RawNode } from '../operation-node/raw-node.js';
5
4
  import { getLast, freeze, isString, isNumber, isBoolean, isNull, isDate, isBigInt, } from '../util/object-utils.js';
6
5
  export class DefaultQueryCompiler extends OperationNodeVisitor {
7
- #sqlFragments = [];
6
+ #sql = '';
8
7
  #parameters = [];
9
8
  get numParameters() {
10
9
  return this.#parameters.length;
11
10
  }
12
11
  compileQuery(node) {
13
- this.#sqlFragments = [];
12
+ this.#sql = '';
14
13
  this.#parameters = [];
15
14
  this.visitNode(node);
16
15
  return freeze({
17
16
  sql: this.getSql(),
18
- parameters: this.#parameters,
17
+ parameters: [...this.#parameters],
19
18
  });
20
19
  }
21
20
  getSql() {
22
- return this.#sqlFragments.join('');
21
+ return this.#sql;
23
22
  }
24
23
  visitSelectQuery(node) {
25
24
  // This is a sub query if this is not the root node.
@@ -61,6 +60,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
61
60
  this.append(' ');
62
61
  this.visitNode(node.having);
63
62
  }
63
+ if (node.union) {
64
+ this.append(' ');
65
+ this.compileList(node.union, ' ');
66
+ }
64
67
  if (node.orderBy) {
65
68
  this.append(' ');
66
69
  this.visitNode(node.orderBy);
@@ -87,6 +90,12 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
87
90
  this.append('from ');
88
91
  this.compileList(node.froms);
89
92
  }
93
+ visitSelection(node) {
94
+ this.visitNode(node.selection);
95
+ }
96
+ visitColumn(node) {
97
+ this.visitNode(node.column);
98
+ }
90
99
  compileDistinctOn(selections) {
91
100
  this.append('distinct on (');
92
101
  this.compileList(selections);
@@ -289,19 +298,7 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
289
298
  visitColumnDefinition(node) {
290
299
  this.visitNode(node.column);
291
300
  this.append(' ');
292
- if (node.isAutoIncrementing) {
293
- // Postgres overrides the data type for autoincrementing columns.
294
- if (DataTypeNode.is(node.dataType) &&
295
- node.dataType.dataType === 'bigint') {
296
- this.append('bigserial');
297
- }
298
- else {
299
- this.append('serial');
300
- }
301
- }
302
- else {
303
- this.visitNode(node.dataType);
304
- }
301
+ this.visitNode(node.dataType);
305
302
  if (node.defaultTo) {
306
303
  this.append(' default ');
307
304
  this.visitNode(node.defaultTo);
@@ -309,6 +306,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
309
306
  if (!node.isNullable) {
310
307
  this.append(' not null');
311
308
  }
309
+ if (node.isAutoIncrementing) {
310
+ this.append(' ');
311
+ this.append(this.getAutoIncrement());
312
+ }
312
313
  if (node.isUnique) {
313
314
  this.append(' unique');
314
315
  }
@@ -324,6 +325,9 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
324
325
  this.visitNode(node.check);
325
326
  }
326
327
  }
328
+ getAutoIncrement() {
329
+ return 'auto_increment';
330
+ }
327
331
  visitReferences(node) {
328
332
  this.append('references ');
329
333
  this.visitNode(node.table);
@@ -633,11 +637,18 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
633
637
  this.append('drop constraint ');
634
638
  this.visitNode(node.constraintName);
635
639
  }
640
+ visitUnion(node) {
641
+ this.append('union ');
642
+ if (node.all) {
643
+ this.append('all ');
644
+ }
645
+ this.visitNode(node.union);
646
+ }
636
647
  append(str) {
637
- this.#sqlFragments.push(str);
648
+ this.#sql += str;
638
649
  }
639
- appendValue(value) {
640
- this.addParameter(value);
650
+ appendValue(parameter) {
651
+ this.addParameter(parameter);
641
652
  this.append(this.getCurrentParameterPlaceholder());
642
653
  }
643
654
  getLeftIdentifierWrapper() {
@@ -678,7 +689,7 @@ const SELECT_MODIFIER_SQL = {
678
689
  ForNoKeyUpdate: 'for no key update',
679
690
  ForUpdate: 'for update',
680
691
  ForShare: 'for share',
681
- NoWait: 'no wait',
692
+ NoWait: 'nowait',
682
693
  SkipLocked: 'skip locked',
683
694
  };
684
695
  const JOIN_TYPE_SQL = {
@@ -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
@@ -155,6 +155,9 @@ export class QueryCreator {
155
155
  * Sets the schema to be used for all table references that don't explicitly
156
156
  * specify a schema.
157
157
  *
158
+ * This only affects the query created through the builder returned from
159
+ * this method and doesn't modify the `db` instance.
160
+ *
158
161
  * @example
159
162
  * ```
160
163
  * await db.withSchema('mammals')
@@ -200,10 +203,10 @@ export class QueryCreator {
200
203
  * Provides a way to pass arbitrary SQL into your query and executing completely
201
204
  * raw queries.
202
205
  *
203
- * You can use strings `?` and `??` in the `sql` to bind parameters such as
206
+ * You can use the strings `?` and `??` in the `sql` to bind parameters such as
204
207
  * user input to the SQL. You should never EVER concatenate untrusted user
205
208
  * input to the SQL string to avoid injection vulnerabilities. Instead use `?`
206
- * in place of the value and pass the actual value in the `params` list. See
209
+ * in place of a value and pass the actual value in the `parameters` list. See
207
210
  * the examples below.
208
211
  *
209
212
  * You should only use `raw` when there is no other way to get the job done. This is
@@ -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);
@@ -20,6 +20,9 @@ import { UniqueConstraintNode } from '../operation-node/unique-constraint-node.j
20
20
  import { CheckConstraintNode } from '../operation-node/check-constraint-node.js';
21
21
  import { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';
22
22
  import { ColumnNode } from '../operation-node/column-node.js';
23
+ /**
24
+ * This builder can be used to create a `alter table` query.
25
+ */
23
26
  export class AlterTableBuilder {
24
27
  #props;
25
28
  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
  */
@@ -9,7 +9,7 @@ export class CreateSchemaBuilder {
9
9
  ifNotExists() {
10
10
  return new CreateSchemaBuilder({
11
11
  ...this.#props,
12
- createSchemaNode: CreateSchemaNode.cloneWithModifier(this.#props.createSchemaNode, 'IfNotExists'),
12
+ createSchemaNode: CreateSchemaNode.cloneWith(this.#props.createSchemaNode, { modifier: 'IfNotExists' }),
13
13
  });
14
14
  }
15
15
  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>;
@@ -2,12 +2,18 @@ import { ColumnDefinitionNode } from '../operation-node/column-definition-node.j
2
2
  import { CreateTableNode } from '../operation-node/create-table-node.js';
3
3
  import { preventAwait } from '../util/prevent-await.js';
4
4
  import { ColumnDefinitionBuilder } from './column-definition-builder.js';
5
- import { freeze } from '../util/object-utils.js';
5
+ import { freeze, noop } from '../util/object-utils.js';
6
6
  import { ForeignKeyConstraintNode } from '../operation-node/foreign-key-constraint-node.js';
7
7
  import { ColumnNode } from '../operation-node/column-node.js';
8
8
  import { TableNode } from '../operation-node/table-node.js';
9
9
  import { ForeignKeyConstraintBuilder } from './foreign-key-constraint-builder.js';
10
10
  import { parseDataTypeExpression, } from '../parser/data-type-parser.js';
11
+ import { PrimaryConstraintNode } from '../operation-node/primary-constraint-node.js';
12
+ import { UniqueConstraintNode } from '../operation-node/unique-constraint-node.js';
13
+ import { CheckConstraintNode } from '../operation-node/check-constraint-node.js';
14
+ /**
15
+ * This builder can be used to create a `create table` query.
16
+ */
11
17
  export class CreateTableBuilder {
12
18
  #props;
13
19
  constructor(props) {
@@ -31,18 +37,45 @@ export class CreateTableBuilder {
31
37
  * ```ts
32
38
  * await db.schema
33
39
  * .createTable('person')
34
- * .addColumn('int', 'id', (col) => col.increments().primary()),
40
+ * .addColumn('id', 'integer', (col) => col.increments().primaryKey()),
35
41
  * .addColumn('first_name', 'varchar(50), (col) => col.notNull())
36
- * .addColumn('varchar', 'last_name')
37
- * .addColumn('numeric(8, 2)', 'bank_balance')
42
+ * .addColumn('last_name', 'varchar')
43
+ * .addColumn('bank_balance', 'numeric(8, 2)')
38
44
  * .addColumn('data', db.raw('customtype'))
45
+ * .addColumn('parent_id', 'integer', (col) =>
46
+ * col.references('person.id').onDelete('cascade'))
47
+ * )
48
+ * ```
49
+ *
50
+ * With this method, it's once again good to remember that Kysely just builds the query
51
+ * that's as close to the structure of your builder method calls as possible, and doesn't
52
+ * provide the same API for all databses. For example, some databases like older MySQL
53
+ * don't support `references` statement in the column definition. Instead foreign key
54
+ * constraints need to be defined in at the level of the `create table` query. See
55
+ * the next example:
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * .addColumn('parent_id', 'integer')
60
+ * .addForeignKeyConstraint(
61
+ * 'person_parent_id_fk', ['parent_id'], 'person', ['id'],
62
+ * (cb) => cb.onDelete('cascade')
63
+ * )
64
+ * ```
65
+ *
66
+ * Another good example is that PostgreSQL doesn't support the `auto_increment`
67
+ * keyword and you need to define an autoincrementing column for example using
68
+ * `serial`:
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * await db.schema
73
+ * .createTable('person')
74
+ * .addColumn('id', 'serial', (col) => col.primaryKey()),
39
75
  * ```
40
76
  */
41
- addColumn(columnName, dataType, build) {
42
- let columnBuilder = new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)));
43
- if (build) {
44
- columnBuilder = build(columnBuilder);
45
- }
77
+ addColumn(columnName, dataType, build = noop) {
78
+ const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
46
79
  return new CreateTableBuilder({
47
80
  ...this.#props,
48
81
  createTableNode: CreateTableNode.cloneWithColumn(this.#props.createTableNode, columnBuilder.toOperationNode()),
@@ -51,6 +84,9 @@ export class CreateTableBuilder {
51
84
  /**
52
85
  * Adds a primary key constraint for one or more columns.
53
86
  *
87
+ * The constraint name can be anything you want, but it must be unique
88
+ * across the whole database.
89
+ *
54
90
  * @example
55
91
  * ```ts
56
92
  * addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
@@ -59,12 +95,15 @@ export class CreateTableBuilder {
59
95
  addPrimaryKeyConstraint(constraintName, columns) {
60
96
  return new CreateTableBuilder({
61
97
  ...this.#props,
62
- createTableNode: CreateTableNode.cloneWithPrimaryKeyConstraint(this.#props.createTableNode, constraintName, columns),
98
+ createTableNode: CreateTableNode.cloneWithConstraint(this.#props.createTableNode, PrimaryConstraintNode.create(columns, constraintName)),
63
99
  });
64
100
  }
65
101
  /**
66
102
  * Adds a unique constraint for one or more columns.
67
103
  *
104
+ * The constraint name can be anything you want, but it must be unique
105
+ * across the whole database.
106
+ *
68
107
  * @example
69
108
  * ```ts
70
109
  * addUniqueConstraint('first_name_last_name_unique', ['first_name', 'last_name'])
@@ -73,12 +112,15 @@ export class CreateTableBuilder {
73
112
  addUniqueConstraint(constraintName, columns) {
74
113
  return new CreateTableBuilder({
75
114
  ...this.#props,
76
- createTableNode: CreateTableNode.cloneWithUniqueConstraint(this.#props.createTableNode, constraintName, columns),
115
+ createTableNode: CreateTableNode.cloneWithConstraint(this.#props.createTableNode, UniqueConstraintNode.create(columns, constraintName)),
77
116
  });
78
117
  }
79
118
  /**
80
119
  * Adds a check constraint.
81
120
  *
121
+ * The constraint name can be anything you want, but it must be unique
122
+ * across the whole database.
123
+ *
82
124
  * @example
83
125
  * ```ts
84
126
  * addCheckConstraint('check_legs', 'number_of_legs < 5')
@@ -87,12 +129,15 @@ export class CreateTableBuilder {
87
129
  addCheckConstraint(constraintName, checkExpression) {
88
130
  return new CreateTableBuilder({
89
131
  ...this.#props,
90
- createTableNode: CreateTableNode.cloneWithCheckConstraint(this.#props.createTableNode, constraintName, checkExpression),
132
+ createTableNode: CreateTableNode.cloneWithConstraint(this.#props.createTableNode, CheckConstraintNode.create(checkExpression, constraintName)),
91
133
  });
92
134
  }
93
135
  /**
94
136
  * Adds a foreign key constraint.
95
137
  *
138
+ * The constraint name can be anything you want, but it must be unique
139
+ * across the whole database.
140
+ *
96
141
  * @example
97
142
  * ```ts
98
143
  * addForeignKeyConstraint(
@@ -114,14 +159,11 @@ export class CreateTableBuilder {
114
159
  * )
115
160
  * ```
116
161
  */
117
- addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build) {
118
- let builder = new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), TableNode.create(targetTable), targetColumns.map(ColumnNode.create), constraintName));
119
- if (build) {
120
- builder = build(builder);
121
- }
162
+ addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {
163
+ const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), TableNode.create(targetTable), targetColumns.map(ColumnNode.create), constraintName)));
122
164
  return new CreateTableBuilder({
123
165
  ...this.#props,
124
- createTableNode: CreateTableNode.cloneWithForeignKeyConstraint(this.#props.createTableNode, builder.toOperationNode()),
166
+ createTableNode: CreateTableNode.cloneWithConstraint(this.#props.createTableNode, builder.toOperationNode()),
125
167
  });
126
168
  }
127
169
  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
  *