kysely 0.19.10 → 0.20.0

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 (148) hide show
  1. package/README.md +52 -4
  2. package/dist/cjs/dialect/mysql/mysql-dialect-config.d.ts +10 -0
  3. package/dist/cjs/dialect/mysql/mysql-driver.d.ts +1 -0
  4. package/dist/cjs/dialect/mysql/mysql-driver.js +25 -0
  5. package/dist/cjs/dialect/mysql/mysql-introspector.js +2 -0
  6. package/dist/cjs/dialect/mysql/mysql-query-compiler.d.ts +5 -0
  7. package/dist/cjs/dialect/mysql/mysql-query-compiler.js +16 -0
  8. package/dist/cjs/dialect/postgres/postgres-dialect-config.d.ts +29 -0
  9. package/dist/cjs/dialect/postgres/postgres-driver.d.ts +6 -2
  10. package/dist/cjs/dialect/postgres/postgres-driver.js +24 -2
  11. package/dist/cjs/dialect/postgres/postgres-introspector.js +7 -1
  12. package/dist/cjs/dialect/postgres/postgres-query-compiler.d.ts +1 -3
  13. package/dist/cjs/dialect/postgres/postgres-query-compiler.js +3 -8
  14. package/dist/cjs/dialect/sqlite/sqlite-driver.js +3 -0
  15. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +2 -0
  16. package/dist/cjs/dialect/sqlite/sqlite-query-compiler.d.ts +3 -0
  17. package/dist/cjs/dialect/sqlite/sqlite-query-compiler.js +10 -0
  18. package/dist/cjs/driver/database-connection.d.ts +1 -0
  19. package/dist/cjs/driver/dummy-driver.js +3 -0
  20. package/dist/cjs/index.d.ts +6 -0
  21. package/dist/cjs/index.js +6 -0
  22. package/dist/cjs/operation-node/create-table-node.d.ts +9 -2
  23. package/dist/cjs/operation-node/create-table-node.js +18 -1
  24. package/dist/cjs/operation-node/data-type-node.d.ts +1 -1
  25. package/dist/cjs/operation-node/delete-query-node.d.ts +3 -0
  26. package/dist/cjs/operation-node/delete-query-node.js +6 -0
  27. package/dist/cjs/operation-node/explain-node.d.ts +16 -0
  28. package/dist/cjs/operation-node/explain-node.js +19 -0
  29. package/dist/cjs/operation-node/foreign-key-constraint-node.d.ts +2 -2
  30. package/dist/cjs/operation-node/insert-query-node.d.ts +4 -1
  31. package/dist/cjs/operation-node/insert-query-node.js +2 -1
  32. package/dist/cjs/operation-node/operation-node-transformer.d.ts +2 -0
  33. package/dist/cjs/operation-node/operation-node-transformer.js +15 -0
  34. package/dist/cjs/operation-node/operation-node-visitor.d.ts +2 -0
  35. package/dist/cjs/operation-node/operation-node-visitor.js +1 -0
  36. package/dist/cjs/operation-node/operation-node.d.ts +1 -1
  37. package/dist/cjs/operation-node/references-node.d.ts +3 -1
  38. package/dist/cjs/operation-node/references-node.js +8 -1
  39. package/dist/cjs/operation-node/select-query-node.d.ts +3 -0
  40. package/dist/cjs/operation-node/select-query-node.js +6 -0
  41. package/dist/cjs/operation-node/update-query-node.d.ts +3 -0
  42. package/dist/cjs/operation-node/update-query-node.js +6 -0
  43. package/dist/cjs/parser/on-commit-action-parse.d.ts +2 -0
  44. package/dist/cjs/parser/on-commit-action-parse.js +11 -0
  45. package/dist/cjs/parser/on-modify-action-parser.d.ts +2 -0
  46. package/dist/cjs/parser/on-modify-action-parser.js +11 -0
  47. package/dist/cjs/query-builder/delete-query-builder.d.ts +19 -1
  48. package/dist/cjs/query-builder/delete-query-builder.js +24 -0
  49. package/dist/cjs/query-builder/function-builder.d.ts +3 -3
  50. package/dist/cjs/query-builder/insert-query-builder.d.ts +21 -3
  51. package/dist/cjs/query-builder/insert-query-builder.js +26 -0
  52. package/dist/cjs/query-builder/select-query-builder.d.ts +65 -1
  53. package/dist/cjs/query-builder/select-query-builder.js +79 -4
  54. package/dist/cjs/query-builder/update-query-builder.d.ts +20 -1
  55. package/dist/cjs/query-builder/update-query-builder.js +25 -0
  56. package/dist/cjs/query-compiler/default-query-compiler.d.ts +7 -0
  57. package/dist/cjs/query-compiler/default-query-compiler.js +75 -2
  58. package/dist/cjs/query-creator.d.ts +27 -0
  59. package/dist/cjs/query-creator.js +33 -0
  60. package/dist/cjs/query-executor/query-executor-base.d.ts +6 -0
  61. package/dist/cjs/query-executor/query-executor-base.js +19 -0
  62. package/dist/cjs/query-executor/query-executor.d.ts +11 -0
  63. package/dist/cjs/raw-builder/sql.d.ts +96 -96
  64. package/dist/cjs/raw-builder/sql.js +0 -96
  65. package/dist/cjs/schema/column-definition-builder.js +3 -2
  66. package/dist/cjs/schema/create-table-builder.d.ts +60 -6
  67. package/dist/cjs/schema/create-table-builder.js +72 -7
  68. package/dist/cjs/schema/create-type-builder.d.ts +9 -0
  69. package/dist/cjs/schema/create-type-builder.js +9 -0
  70. package/dist/cjs/schema/foreign-key-constraint-builder.js +3 -2
  71. package/dist/cjs/util/deferred.d.ts +7 -0
  72. package/dist/cjs/util/deferred.js +28 -0
  73. package/dist/cjs/util/explainable.d.ts +5 -0
  74. package/dist/cjs/util/explainable.js +2 -0
  75. package/dist/esm/dialect/mysql/mysql-dialect-config.d.ts +10 -0
  76. package/dist/esm/dialect/mysql/mysql-driver.d.ts +1 -0
  77. package/dist/esm/dialect/mysql/mysql-driver.js +25 -0
  78. package/dist/esm/dialect/mysql/mysql-introspector.js +2 -0
  79. package/dist/esm/dialect/mysql/mysql-query-compiler.d.ts +5 -0
  80. package/dist/esm/dialect/mysql/mysql-query-compiler.js +16 -0
  81. package/dist/esm/dialect/postgres/postgres-dialect-config.d.ts +29 -0
  82. package/dist/esm/dialect/postgres/postgres-driver.d.ts +6 -2
  83. package/dist/esm/dialect/postgres/postgres-driver.js +24 -2
  84. package/dist/esm/dialect/postgres/postgres-introspector.js +7 -1
  85. package/dist/esm/dialect/postgres/postgres-query-compiler.d.ts +1 -3
  86. package/dist/esm/dialect/postgres/postgres-query-compiler.js +3 -8
  87. package/dist/esm/dialect/sqlite/sqlite-driver.js +3 -0
  88. package/dist/esm/dialect/sqlite/sqlite-introspector.js +2 -0
  89. package/dist/esm/dialect/sqlite/sqlite-query-compiler.d.ts +3 -0
  90. package/dist/esm/dialect/sqlite/sqlite-query-compiler.js +10 -0
  91. package/dist/esm/driver/database-connection.d.ts +1 -0
  92. package/dist/esm/driver/dummy-driver.js +3 -0
  93. package/dist/esm/index.d.ts +6 -0
  94. package/dist/esm/index.js +6 -0
  95. package/dist/esm/operation-node/create-table-node.d.ts +9 -2
  96. package/dist/esm/operation-node/create-table-node.js +17 -0
  97. package/dist/esm/operation-node/data-type-node.d.ts +1 -1
  98. package/dist/esm/operation-node/delete-query-node.d.ts +3 -0
  99. package/dist/esm/operation-node/delete-query-node.js +6 -0
  100. package/dist/esm/operation-node/explain-node.d.ts +16 -0
  101. package/dist/esm/operation-node/explain-node.js +17 -0
  102. package/dist/esm/operation-node/foreign-key-constraint-node.d.ts +2 -2
  103. package/dist/esm/operation-node/insert-query-node.d.ts +4 -1
  104. package/dist/esm/operation-node/insert-query-node.js +2 -1
  105. package/dist/esm/operation-node/operation-node-transformer.d.ts +2 -0
  106. package/dist/esm/operation-node/operation-node-transformer.js +15 -0
  107. package/dist/esm/operation-node/operation-node-visitor.d.ts +2 -0
  108. package/dist/esm/operation-node/operation-node-visitor.js +1 -0
  109. package/dist/esm/operation-node/operation-node.d.ts +1 -1
  110. package/dist/esm/operation-node/references-node.d.ts +3 -1
  111. package/dist/esm/operation-node/references-node.js +7 -0
  112. package/dist/esm/operation-node/select-query-node.d.ts +3 -0
  113. package/dist/esm/operation-node/select-query-node.js +6 -0
  114. package/dist/esm/operation-node/update-query-node.d.ts +3 -0
  115. package/dist/esm/operation-node/update-query-node.js +6 -0
  116. package/dist/esm/parser/on-commit-action-parse.d.ts +2 -0
  117. package/dist/esm/parser/on-commit-action-parse.js +8 -0
  118. package/dist/esm/parser/on-modify-action-parser.d.ts +2 -0
  119. package/dist/esm/parser/on-modify-action-parser.js +8 -0
  120. package/dist/esm/query-builder/delete-query-builder.d.ts +19 -1
  121. package/dist/esm/query-builder/delete-query-builder.js +24 -0
  122. package/dist/esm/query-builder/function-builder.d.ts +3 -3
  123. package/dist/esm/query-builder/insert-query-builder.d.ts +21 -3
  124. package/dist/esm/query-builder/insert-query-builder.js +26 -0
  125. package/dist/esm/query-builder/select-query-builder.d.ts +65 -1
  126. package/dist/esm/query-builder/select-query-builder.js +79 -4
  127. package/dist/esm/query-builder/update-query-builder.d.ts +20 -1
  128. package/dist/esm/query-builder/update-query-builder.js +25 -0
  129. package/dist/esm/query-compiler/default-query-compiler.d.ts +7 -0
  130. package/dist/esm/query-compiler/default-query-compiler.js +75 -2
  131. package/dist/esm/query-creator.d.ts +27 -0
  132. package/dist/esm/query-creator.js +33 -0
  133. package/dist/esm/query-executor/query-executor-base.d.ts +6 -0
  134. package/dist/esm/query-executor/query-executor-base.js +19 -0
  135. package/dist/esm/query-executor/query-executor.d.ts +11 -0
  136. package/dist/esm/raw-builder/sql.d.ts +96 -96
  137. package/dist/esm/raw-builder/sql.js +0 -96
  138. package/dist/esm/schema/column-definition-builder.js +3 -2
  139. package/dist/esm/schema/create-table-builder.d.ts +60 -6
  140. package/dist/esm/schema/create-table-builder.js +72 -7
  141. package/dist/esm/schema/create-type-builder.d.ts +9 -0
  142. package/dist/esm/schema/create-type-builder.js +9 -0
  143. package/dist/esm/schema/foreign-key-constraint-builder.js +3 -2
  144. package/dist/esm/util/deferred.d.ts +7 -0
  145. package/dist/esm/util/deferred.js +25 -0
  146. package/dist/esm/util/explainable.d.ts +5 -0
  147. package/dist/esm/util/explainable.js +2 -0
  148. package/package.json +7 -2
@@ -10,6 +10,7 @@ import { preventAwait } from '../util/prevent-await.js';
10
10
  import { freeze } from '../util/object-utils.js';
11
11
  import { UpdateResult } from './update-result.js';
12
12
  import { NoResultError } from './no-result-error.js';
13
+ import { ExplainNode } from '../operation-node/explain-node.js';
13
14
  export class UpdateQueryBuilder {
14
15
  #props;
15
16
  constructor(props) {
@@ -330,5 +331,29 @@ export class UpdateQueryBuilder {
330
331
  }
331
332
  return result;
332
333
  }
334
+ /**
335
+ * Executes query with `explain` statement before `update` keyword.
336
+ *
337
+ * ```ts
338
+ * const explained = await db
339
+ * .updateTable('person')
340
+ * .set(updates)
341
+ * .where('id', '=', 123)
342
+ * .explain('json')
343
+ * ```
344
+ *
345
+ * The generated SQL (MySQL):
346
+ *
347
+ * ```sql
348
+ * explain format=json update `person` set `first_name` = ?, `last_name` = ? where `id` = ?
349
+ * ```
350
+ */
351
+ async explain(format, options) {
352
+ const builder = new UpdateQueryBuilder({
353
+ ...this.#props,
354
+ queryNode: UpdateQueryNode.cloneWithExplain(this.#props.queryNode, ExplainNode.create(format, options)),
355
+ });
356
+ return await builder.execute();
357
+ }
333
358
  }
334
359
  preventAwait(UpdateQueryBuilder, "don't await UpdateQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.");
@@ -71,6 +71,7 @@ import { CommonTableExpressionNameNode } from '../operation-node/common-table-ex
71
71
  import { SelectModifierNode } from '../operation-node/select-modifier-node.js';
72
72
  import { CreateTypeNode } from '../operation-node/create-type-node.js';
73
73
  import { DropTypeNode } from '../operation-node/drop-type-node.js';
74
+ import { ExplainNode } from '../operation-node/explain-node.js';
74
75
  export declare class DefaultQueryCompiler extends OperationNodeVisitor implements QueryCompiler {
75
76
  #private;
76
77
  protected get numParameters(): number;
@@ -149,11 +150,17 @@ export declare class DefaultQueryCompiler extends OperationNodeVisitor implement
149
150
  protected visitSelectModifier(node: SelectModifierNode): void;
150
151
  protected visitCreateType(node: CreateTypeNode): void;
151
152
  protected visitDropType(node: DropTypeNode): void;
153
+ protected visitExplain(node: ExplainNode): void;
152
154
  protected append(str: string): void;
153
155
  protected appendValue(parameter: unknown): void;
154
156
  protected getLeftIdentifierWrapper(): string;
155
157
  protected getRightIdentifierWrapper(): string;
156
158
  protected getCurrentParameterPlaceholder(): string;
159
+ protected getLeftExplainOptionsWrapper(): string;
160
+ protected getExplainOptionAssignment(): string;
161
+ protected getExplainOptionsDelimiter(): string;
162
+ protected getRightExplainOptionsWrapper(): string;
163
+ protected sanitizeIdentifier(identifier: string): string;
157
164
  protected addParameter(parameter: unknown): void;
158
165
  protected appendImmediateValue(value: unknown): void;
159
166
  }
@@ -30,6 +30,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
30
30
  !InsertQueryNode.is(this.parentNode) &&
31
31
  !CreateViewNode.is(this.parentNode) &&
32
32
  !UnionNode.is(this.parentNode);
33
+ if (this.parentNode === undefined && node.explain) {
34
+ this.visitNode(node.explain);
35
+ this.append(' ');
36
+ }
33
37
  if (wrapInParens) {
34
38
  this.append('(');
35
39
  }
@@ -125,6 +129,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
125
129
  }
126
130
  visitInsertQuery(node) {
127
131
  const isSubQuery = this.nodeStack.find(QueryNode.is) !== node;
132
+ if (!isSubQuery && node.explain) {
133
+ this.visitNode(node.explain);
134
+ this.append(' ');
135
+ }
128
136
  if (isSubQuery) {
129
137
  this.append('(');
130
138
  }
@@ -132,7 +140,7 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
132
140
  this.visitNode(node.with);
133
141
  this.append(' ');
134
142
  }
135
- this.append('insert');
143
+ this.append(node.replace ? 'replace' : 'insert');
136
144
  if (node.ignore) {
137
145
  this.append(' ignore');
138
146
  }
@@ -169,6 +177,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
169
177
  }
170
178
  visitDeleteQuery(node) {
171
179
  const isSubQuery = this.nodeStack.find(QueryNode.is) !== node;
180
+ if (!isSubQuery && node.explain) {
181
+ this.visitNode(node.explain);
182
+ this.append(' ');
183
+ }
172
184
  if (isSubQuery) {
173
185
  this.append('(');
174
186
  }
@@ -225,7 +237,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
225
237
  this.append(this.getRightIdentifierWrapper());
226
238
  }
227
239
  compileUnwrappedIdentifier(node) {
228
- this.append(node.identifier);
240
+ if (!isString(node.identifier)) {
241
+ throw new Error('a non-string identifier was passed to compileUnwrappedIdentifier.');
242
+ }
243
+ this.append(this.sanitizeIdentifier(node.identifier));
229
244
  }
230
245
  visitFilter(node) {
231
246
  if (node.left) {
@@ -309,6 +324,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
309
324
  }
310
325
  visitCreateTable(node) {
311
326
  this.append('create ');
327
+ if (node.frontModifiers) {
328
+ this.compileList(node.frontModifiers, ' ');
329
+ this.append(' ');
330
+ }
312
331
  if (node.temporary) {
313
332
  this.append('temporary ');
314
333
  }
@@ -324,6 +343,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
324
343
  this.append(' on commit ');
325
344
  this.append(node.onCommit);
326
345
  }
346
+ if (node.endModifiers) {
347
+ this.append(' ');
348
+ this.compileList(node.endModifiers, ' ');
349
+ }
327
350
  }
328
351
  visitColumnDefinition(node) {
329
352
  this.visitNode(node.column);
@@ -410,6 +433,10 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
410
433
  }
411
434
  visitUpdateQuery(node) {
412
435
  const isSubQuery = this.nodeStack.find(QueryNode.is) !== node;
436
+ if (!isSubQuery && node.explain) {
437
+ this.visitNode(node.explain);
438
+ this.append(' ');
439
+ }
413
440
  if (isSubQuery) {
414
441
  this.append('(');
415
442
  }
@@ -804,6 +831,25 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
804
831
  }
805
832
  this.visitNode(node.name);
806
833
  }
834
+ visitExplain(node) {
835
+ this.append('explain');
836
+ if (node.options || node.format) {
837
+ this.append(' ');
838
+ this.append(this.getLeftExplainOptionsWrapper());
839
+ if (node.options) {
840
+ this.visitNode(node.options);
841
+ if (node.format) {
842
+ this.append(this.getExplainOptionsDelimiter());
843
+ }
844
+ }
845
+ if (node.format) {
846
+ this.append('format');
847
+ this.append(this.getExplainOptionAssignment());
848
+ this.append(node.format);
849
+ }
850
+ this.append(this.getRightExplainOptionsWrapper());
851
+ }
852
+ }
807
853
  append(str) {
808
854
  this.#sql += str;
809
855
  }
@@ -820,6 +866,33 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
820
866
  getCurrentParameterPlaceholder() {
821
867
  return '$' + this.numParameters;
822
868
  }
869
+ getLeftExplainOptionsWrapper() {
870
+ return '(';
871
+ }
872
+ getExplainOptionAssignment() {
873
+ return ' ';
874
+ }
875
+ getExplainOptionsDelimiter() {
876
+ return ', ';
877
+ }
878
+ getRightExplainOptionsWrapper() {
879
+ return ')';
880
+ }
881
+ sanitizeIdentifier(identifier) {
882
+ const leftWrap = this.getLeftIdentifierWrapper();
883
+ const rightWrap = this.getRightIdentifierWrapper();
884
+ let sanitized = '';
885
+ for (const c of identifier) {
886
+ sanitized += c;
887
+ if (c === leftWrap) {
888
+ sanitized += leftWrap;
889
+ }
890
+ else if (c === rightWrap) {
891
+ sanitized += rightWrap;
892
+ }
893
+ }
894
+ return sanitized;
895
+ }
823
896
  addParameter(parameter) {
824
897
  this.#parameters.push(parameter);
825
898
  }
@@ -161,6 +161,33 @@ export declare class QueryCreator<DB> {
161
161
  * ```
162
162
  */
163
163
  insertInto<T extends keyof DB & string>(table: T): InsertQueryBuilder<DB, T, InsertResult>;
164
+ /**
165
+ * Creates a replace query.
166
+ *
167
+ * A MySQL-only statement similar to {@link InsertQueryBuilder.onDuplicateKeyUpdate}
168
+ * that deletes and inserts values on collision instead of updating existing rows.
169
+ *
170
+ * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
171
+ * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
172
+ * the inserted row if the db returned one.
173
+ *
174
+ * See the {@link InsertQueryBuilder.values | values} method for more info and examples.
175
+ *
176
+ * ### Examples
177
+ *
178
+ * ```ts
179
+ * const result = await db
180
+ * .replaceInto('person')
181
+ * .values({
182
+ * first_name: 'Jennifer',
183
+ * last_name: 'Aniston'
184
+ * })
185
+ * .executeTakeFirst()
186
+ *
187
+ * console.log(result.insertId)
188
+ * ```
189
+ */
190
+ replaceInto<T extends keyof DB & string>(table: T): InsertQueryBuilder<DB, T, InsertResult>;
164
191
  /**
165
192
  * Creates a delete query.
166
193
  *
@@ -70,6 +70,39 @@ export class QueryCreator {
70
70
  queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode),
71
71
  });
72
72
  }
73
+ /**
74
+ * Creates a replace query.
75
+ *
76
+ * A MySQL-only statement similar to {@link InsertQueryBuilder.onDuplicateKeyUpdate}
77
+ * that deletes and inserts values on collision instead of updating existing rows.
78
+ *
79
+ * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
80
+ * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
81
+ * the inserted row if the db returned one.
82
+ *
83
+ * See the {@link InsertQueryBuilder.values | values} method for more info and examples.
84
+ *
85
+ * ### Examples
86
+ *
87
+ * ```ts
88
+ * const result = await db
89
+ * .replaceInto('person')
90
+ * .values({
91
+ * first_name: 'Jennifer',
92
+ * last_name: 'Aniston'
93
+ * })
94
+ * .executeTakeFirst()
95
+ *
96
+ * console.log(result.insertId)
97
+ * ```
98
+ */
99
+ replaceInto(table) {
100
+ return new InsertQueryBuilder({
101
+ queryId: createQueryId(),
102
+ executor: this.#props.executor,
103
+ queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true),
104
+ });
105
+ }
73
106
  /**
74
107
  * Creates a delete query.
75
108
  *
@@ -36,6 +36,12 @@ export declare abstract class QueryExecutorBase implements QueryExecutor {
36
36
  * `transformResult` method.
37
37
  */
38
38
  executeQuery<R>(compiledQuery: CompiledQuery, queryId: QueryId): Promise<QueryResult<R>>;
39
+ /**
40
+ * Executes a compiled query and runs the result through all plugins'
41
+ * `transformResult` method. Results are streamead instead of loaded
42
+ * at once.
43
+ */
44
+ stream<R>(compiledQuery: CompiledQuery, chunkSize: number, queryId: QueryId): AsyncIterableIterator<QueryResult<R>>;
39
45
  /**
40
46
  * Returns a copy of this executor with a new connection provider.
41
47
  */
@@ -1,5 +1,6 @@
1
1
  /// <reference types="./query-executor-base.d.ts" />
2
2
  import { freeze } from '../util/object-utils.js';
3
+ import { Deferred } from '../util/deferred.js';
3
4
  const NO_PLUGINS = freeze([]);
4
5
  export class QueryExecutorBase {
5
6
  #plugins;
@@ -34,6 +35,24 @@ export class QueryExecutorBase {
34
35
  return this.#transformResult(result, queryId);
35
36
  });
36
37
  }
38
+ async *stream(compiledQuery, chunkSize, queryId) {
39
+ const connectionDefer = new Deferred();
40
+ const connectionReleaseDefer = new Deferred();
41
+ this.provideConnection(async (connection) => {
42
+ connectionDefer.resolve(connection);
43
+ // Lets wait until we don't need connection before returning here (returning releases connection)
44
+ return await connectionReleaseDefer.promise;
45
+ }).catch((ex) => connectionDefer.reject(ex));
46
+ const connection = await connectionDefer.promise;
47
+ try {
48
+ for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {
49
+ yield await this.#transformResult(result, queryId);
50
+ }
51
+ }
52
+ finally {
53
+ connectionReleaseDefer.resolve();
54
+ }
55
+ }
37
56
  async #transformResult(result, queryId) {
38
57
  for (const plugin of this.#plugins) {
39
58
  result = await plugin.transformResult({ result, queryId });
@@ -37,6 +37,17 @@ export interface QueryExecutor extends ConnectionProvider {
37
37
  * `transformResult` method.
38
38
  */
39
39
  executeQuery<R>(compiledQuery: CompiledQuery, queryId: QueryId): Promise<QueryResult<R>>;
40
+ /**
41
+ * Executes a compiled query and runs the result through all plugins'
42
+ * `transformResult` method. Results are streamead instead of loaded
43
+ * at once.
44
+ */
45
+ stream<R>(compiledQuery: CompiledQuery,
46
+ /**
47
+ * How many rows should be pulled from the database at once. Supported
48
+ * only by the postgres driver.
49
+ */
50
+ chunkSize: number, queryId: QueryId): AsyncIterableIterator<QueryResult<R>>;
40
51
  /**
41
52
  * Returns a copy of this executor with a new connection provider.
42
53
  */
@@ -1,5 +1,101 @@
1
1
  import { RawBuilder } from './raw-builder.js';
2
2
  export interface Sql {
3
+ /**
4
+ * Template tag for creating raw SQL snippets and queries.
5
+ *
6
+ * ```ts
7
+ * import { sql } from 'kysely'
8
+ *
9
+ * const id = 123
10
+ *
11
+ * const snippet = sql<Person[]>`select * from person where id = ${id}`
12
+ * ```
13
+ *
14
+ * Substitutions (the things inside `${}`) are automatically passed to the database
15
+ * as parameters and are NOT interpolated to the SQL string. There's no need to worry
16
+ * about SQL injection vulnerabilities.
17
+ *
18
+ * If you need your substitutions to be interpreted as identifiers, value literals or
19
+ * lists of things, see the {@link Sql.ref}, {@link Sql.table}, {@link Sql.id},
20
+ * {@link Sql.literal}, {@link Sql.raw} and {@link Sql.join} functions.
21
+ *
22
+ * You can pass sql snippets returned by the `sql` tag pretty much anywhere. Whenever
23
+ * something can't be done using the Kysely API, you should be able to drop down to
24
+ * raw SQL using the `sql` tag. Here's an example query that uses raw sql in a bunch
25
+ * of methods:
26
+ *
27
+ * ```ts
28
+ * const persons = await db
29
+ * .selectFrom('person')
30
+ * .select(
31
+ * // If you use `sql` in a select statement, remember to call the `as`
32
+ * // method to give it an alias. Otherwise Kysely is not able to add
33
+ * // the column to the result type.
34
+ * sql<string>`concat(first_name, ' ', last_name)`.as('full_name')
35
+ * )
36
+ * .where(sql`birthdate between ${date1} and ${date2}`)
37
+ * // Here we assume we have list of nicknames for the person
38
+ * // (a list of strings) and we use the PostgreSQL `@>` operator
39
+ * // to test if all of them are valid nicknames for the user.
40
+ * .where('nicknames', '@>', sql`ARRAY[${sql.join(nicknames)}]`)
41
+ * .orderBy(sql`concat(first_name, ' ', last_name)`)
42
+ * .execute()
43
+ * ```
44
+ *
45
+ * The generated SQL (PostgreSQL):
46
+ *
47
+ * ```sql
48
+ * select concat(first_name, ' ', last_name) as "full_name"
49
+ * from "person"
50
+ * where birthdate between $1 and $2
51
+ * and "nicknames" @> ARRAY[$3, $4, $5, $6, $7, $8, $9, $10]
52
+ * order by concat(first_name, ' ', last_name)
53
+ * ```
54
+ *
55
+ * SQL snippets can be executed by calling the `execute` method and passing a `Kysely`
56
+ * instance as the only argument:
57
+ *
58
+ * ```ts
59
+ * const result = await sql<Person[]>`select * from person`.execute(db)
60
+ * ```
61
+ *
62
+ * You can merge other `sql` expressions and queries using substitutions:
63
+ *
64
+ * ```ts
65
+ * const petName = db.selectFrom('pet').select('name').limit(1)
66
+ * const fullName = sql`concat(first_name, ' ', last_name)`
67
+ *
68
+ * sql`
69
+ * select ${fullName} as full_name, ${petName} as pet_name
70
+ * from person
71
+ * `
72
+ * ```
73
+ *
74
+ * Substitutions also handle {@link ExpressionBuilder.ref},
75
+ * {@link DynamicModule.ref} and pretty much anything else you
76
+ * throw at it. Here's an example of calling a function in a
77
+ * type-safe way:
78
+ *
79
+ * ```ts
80
+ * db.selectFrom('person')
81
+ * .select([
82
+ * 'first_name',
83
+ * 'last_name',
84
+ * (eb) => {
85
+ * // The `eb.ref` method is type-safe and only accepts
86
+ * // column references that are possible.
87
+ * const firstName = eb.ref('first_name')
88
+ * const lastName = eb.ref('last_name')
89
+ *
90
+ * const fullName = sql<string>`concat(${firstName}, ' ', ${lastName})`
91
+ * return fullName.as('full_name')
92
+ * }
93
+ * ])
94
+ * ```
95
+ *
96
+ * don't know if that amount of ceremony is worth the small increase in
97
+ * type-safety though... But it's possible.
98
+ */
3
99
  <T = unknown>(sqlFragments: TemplateStringsArray, ...parameters: unknown[]): RawBuilder<T>;
4
100
  /**
5
101
  * This can be used to add runtime column references to SQL snippets.
@@ -232,100 +328,4 @@ export interface Sql {
232
328
  */
233
329
  join(array: unknown[], separator?: RawBuilder<any>): RawBuilder<unknown>;
234
330
  }
235
- /**
236
- * Template tag for creating raw SQL snippets and queries.
237
- *
238
- * ```ts
239
- * import { sql } from 'kysely'
240
- *
241
- * const id = 123
242
- *
243
- * const snippet = sql<Person[]>`select * from person where id = ${id}`
244
- * ```
245
- *
246
- * Substitutions (the things inside `${}`) are automatically passed to the database
247
- * as parameters and are NOT interpolated to the SQL string. There's no need to worry
248
- * about SQL injection vulnerabilities.
249
- *
250
- * If you need your substitutions to be interpreted as identifiers, value literals or
251
- * lists of things, see the {@link Sql.ref}, {@link Sql.table}, {@link Sql.id},
252
- * {@link Sql.literal}, {@link Sql.raw} and {@link Sql.join} functions.
253
- *
254
- * You can pass sql snippets returned by the `sql` tag pretty much anywhere. Whenever
255
- * something can't be done using the Kysely API, you should be able to drop down to
256
- * raw SQL using the `sql` tag. Here's an example query that uses raw sql in a bunch
257
- * of methods:
258
- *
259
- * ```ts
260
- * const persons = await db
261
- * .selectFrom('person')
262
- * .select(
263
- * // If you use `sql` in a select statement, remember to call the `as`
264
- * // method to give it an alias. Otherwise Kysely is not able to add
265
- * // the column to the result type.
266
- * sql<string>`concat(first_name, ' ', last_name)`.as('full_name')
267
- * )
268
- * .where(sql`birthdate between ${date1} and ${date2}`)
269
- * // Here we assume we have list of nicknames for the person
270
- * // (a list of strings) and we use the PostgreSQL `@>` operator
271
- * // to test if all of them are valid nicknames for the user.
272
- * .where('nicknames', '@>', sql`ARRAY[${sql.join(nicknames)}]`)
273
- * .orderBy(sql`concat(first_name, ' ', last_name)`)
274
- * .execute()
275
- * ```
276
- *
277
- * The generated SQL (PostgreSQL):
278
- *
279
- * ```sql
280
- * select concat(first_name, ' ', last_name) as "full_name"
281
- * from "person"
282
- * where birthdate between $1 and $2
283
- * and "nicknames" @> ARRAY[$3, $4, $5, $6, $7, $8, $9, $10]
284
- * order by concat(first_name, ' ', last_name)
285
- * ```
286
- *
287
- * SQL snippets can be executed by calling the `execute` method and passing a `Kysely`
288
- * instance as the only argument:
289
- *
290
- * ```ts
291
- * const result = await sql<Person[]>`select * from person`.execute(db)
292
- * ```
293
- *
294
- * You can merge other `sql` expressions and queries using substitutions:
295
- *
296
- * ```ts
297
- * const petName = db.selectFrom('pet').select('name').limit(1)
298
- * const fullName = sql`concat(first_name, ' ', last_name)`
299
- *
300
- * sql`
301
- * select ${fullName} as full_name, ${petName} as pet_name
302
- * from person
303
- * `
304
- * ```
305
- *
306
- * Substitutions also handle {@link ExpressionBuilder.ref},
307
- * {@link DynamicModule.ref} and pretty much anything else you
308
- * throw at it. Here's an example of calling a function in a
309
- * type-safe way:
310
- *
311
- * ```ts
312
- * db.selectFrom('person')
313
- * .select([
314
- * 'first_name',
315
- * 'last_name',
316
- * (eb) => {
317
- * // The `eb.ref` method is type-safe and only accepts
318
- * // column references that are possible.
319
- * const firstName = eb.ref('first_name')
320
- * const lastName = eb.ref('last_name')
321
- *
322
- * const fullName = sql<string>`concat(${firstName}, ' ', ${lastName})`
323
- * return fullName.as('full_name')
324
- * }
325
- * ])
326
- * ```
327
- *
328
- * don't know if that amount of ceremony is worth the small increase in
329
- * type-safety though... But it's possible.
330
- */
331
331
  export declare const sql: Sql;
@@ -7,102 +7,6 @@ import { parseTable } from '../parser/table-parser.js';
7
7
  import { parseValueExpression } from '../parser/value-parser.js';
8
8
  import { createQueryId } from '../util/query-id.js';
9
9
  import { RawBuilder } from './raw-builder.js';
10
- /**
11
- * Template tag for creating raw SQL snippets and queries.
12
- *
13
- * ```ts
14
- * import { sql } from 'kysely'
15
- *
16
- * const id = 123
17
- *
18
- * const snippet = sql<Person[]>`select * from person where id = ${id}`
19
- * ```
20
- *
21
- * Substitutions (the things inside `${}`) are automatically passed to the database
22
- * as parameters and are NOT interpolated to the SQL string. There's no need to worry
23
- * about SQL injection vulnerabilities.
24
- *
25
- * If you need your substitutions to be interpreted as identifiers, value literals or
26
- * lists of things, see the {@link Sql.ref}, {@link Sql.table}, {@link Sql.id},
27
- * {@link Sql.literal}, {@link Sql.raw} and {@link Sql.join} functions.
28
- *
29
- * You can pass sql snippets returned by the `sql` tag pretty much anywhere. Whenever
30
- * something can't be done using the Kysely API, you should be able to drop down to
31
- * raw SQL using the `sql` tag. Here's an example query that uses raw sql in a bunch
32
- * of methods:
33
- *
34
- * ```ts
35
- * const persons = await db
36
- * .selectFrom('person')
37
- * .select(
38
- * // If you use `sql` in a select statement, remember to call the `as`
39
- * // method to give it an alias. Otherwise Kysely is not able to add
40
- * // the column to the result type.
41
- * sql<string>`concat(first_name, ' ', last_name)`.as('full_name')
42
- * )
43
- * .where(sql`birthdate between ${date1} and ${date2}`)
44
- * // Here we assume we have list of nicknames for the person
45
- * // (a list of strings) and we use the PostgreSQL `@>` operator
46
- * // to test if all of them are valid nicknames for the user.
47
- * .where('nicknames', '@>', sql`ARRAY[${sql.join(nicknames)}]`)
48
- * .orderBy(sql`concat(first_name, ' ', last_name)`)
49
- * .execute()
50
- * ```
51
- *
52
- * The generated SQL (PostgreSQL):
53
- *
54
- * ```sql
55
- * select concat(first_name, ' ', last_name) as "full_name"
56
- * from "person"
57
- * where birthdate between $1 and $2
58
- * and "nicknames" @> ARRAY[$3, $4, $5, $6, $7, $8, $9, $10]
59
- * order by concat(first_name, ' ', last_name)
60
- * ```
61
- *
62
- * SQL snippets can be executed by calling the `execute` method and passing a `Kysely`
63
- * instance as the only argument:
64
- *
65
- * ```ts
66
- * const result = await sql<Person[]>`select * from person`.execute(db)
67
- * ```
68
- *
69
- * You can merge other `sql` expressions and queries using substitutions:
70
- *
71
- * ```ts
72
- * const petName = db.selectFrom('pet').select('name').limit(1)
73
- * const fullName = sql`concat(first_name, ' ', last_name)`
74
- *
75
- * sql`
76
- * select ${fullName} as full_name, ${petName} as pet_name
77
- * from person
78
- * `
79
- * ```
80
- *
81
- * Substitutions also handle {@link ExpressionBuilder.ref},
82
- * {@link DynamicModule.ref} and pretty much anything else you
83
- * throw at it. Here's an example of calling a function in a
84
- * type-safe way:
85
- *
86
- * ```ts
87
- * db.selectFrom('person')
88
- * .select([
89
- * 'first_name',
90
- * 'last_name',
91
- * (eb) => {
92
- * // The `eb.ref` method is type-safe and only accepts
93
- * // column references that are possible.
94
- * const firstName = eb.ref('first_name')
95
- * const lastName = eb.ref('last_name')
96
- *
97
- * const fullName = sql<string>`concat(${firstName}, ' ', ${lastName})`
98
- * return fullName.as('full_name')
99
- * }
100
- * ])
101
- * ```
102
- *
103
- * don't know if that amount of ceremony is worth the small increase in
104
- * type-safety though... But it's possible.
105
- */
106
10
  export const sql = Object.assign((sqlFragments, ...parameters) => {
107
11
  return new RawBuilder({
108
12
  queryId: createQueryId(),
@@ -9,6 +9,7 @@ import { ColumnDefinitionNode } from '../operation-node/column-definition-node.j
9
9
  import { parseDefaultValueExpression, } from '../parser/default-value-parser.js';
10
10
  import { GeneratedNode } from '../operation-node/generated-node.js';
11
11
  import { DefaultValueNode } from '../operation-node/default-value-node.js';
12
+ import { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js';
12
13
  export class ColumnDefinitionBuilder {
13
14
  #node;
14
15
  constructor(node) {
@@ -36,7 +37,7 @@ export class ColumnDefinitionBuilder {
36
37
  throw new Error('on delete constraint can only be added for foreign keys');
37
38
  }
38
39
  return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
39
- references: ReferencesNode.cloneWithOnDelete(this.#node.references, onDelete),
40
+ references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)),
40
41
  }));
41
42
  }
42
43
  onUpdate(onUpdate) {
@@ -44,7 +45,7 @@ export class ColumnDefinitionBuilder {
44
45
  throw new Error('on update constraint can only be added for foreign keys');
45
46
  }
46
47
  return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, {
47
- references: ReferencesNode.cloneWithOnUpdate(this.#node.references, onUpdate),
48
+ references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)),
48
49
  }));
49
50
  }
50
51
  unique() {