kysely 0.19.10 → 0.19.11

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 (62) hide show
  1. package/README.md +51 -3
  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/postgres/postgres-dialect-config.d.ts +29 -0
  6. package/dist/cjs/dialect/postgres/postgres-driver.d.ts +6 -2
  7. package/dist/cjs/dialect/postgres/postgres-driver.js +24 -2
  8. package/dist/cjs/dialect/sqlite/sqlite-driver.js +3 -0
  9. package/dist/cjs/driver/database-connection.d.ts +1 -0
  10. package/dist/cjs/driver/dummy-driver.js +3 -0
  11. package/dist/cjs/index.d.ts +4 -0
  12. package/dist/cjs/index.js +4 -0
  13. package/dist/cjs/operation-node/data-type-node.d.ts +1 -1
  14. package/dist/cjs/operation-node/insert-query-node.d.ts +2 -1
  15. package/dist/cjs/operation-node/insert-query-node.js +2 -1
  16. package/dist/cjs/operation-node/operation-node-transformer.js +1 -0
  17. package/dist/cjs/query-builder/insert-query-builder.d.ts +1 -1
  18. package/dist/cjs/query-builder/select-query-builder.d.ts +27 -0
  19. package/dist/cjs/query-builder/select-query-builder.js +34 -2
  20. package/dist/cjs/query-compiler/default-query-compiler.js +1 -1
  21. package/dist/cjs/query-creator.d.ts +27 -0
  22. package/dist/cjs/query-creator.js +33 -0
  23. package/dist/cjs/query-executor/query-executor-base.d.ts +6 -0
  24. package/dist/cjs/query-executor/query-executor-base.js +19 -0
  25. package/dist/cjs/query-executor/query-executor.d.ts +11 -0
  26. package/dist/cjs/schema/create-table-builder.d.ts +6 -6
  27. package/dist/cjs/schema/create-table-builder.js +6 -6
  28. package/dist/cjs/schema/create-type-builder.d.ts +9 -0
  29. package/dist/cjs/schema/create-type-builder.js +9 -0
  30. package/dist/cjs/util/deferred.d.ts +7 -0
  31. package/dist/cjs/util/deferred.js +28 -0
  32. package/dist/esm/dialect/mysql/mysql-dialect-config.d.ts +10 -0
  33. package/dist/esm/dialect/mysql/mysql-driver.d.ts +1 -0
  34. package/dist/esm/dialect/mysql/mysql-driver.js +25 -0
  35. package/dist/esm/dialect/postgres/postgres-dialect-config.d.ts +29 -0
  36. package/dist/esm/dialect/postgres/postgres-driver.d.ts +6 -2
  37. package/dist/esm/dialect/postgres/postgres-driver.js +24 -2
  38. package/dist/esm/dialect/sqlite/sqlite-driver.js +3 -0
  39. package/dist/esm/driver/database-connection.d.ts +1 -0
  40. package/dist/esm/driver/dummy-driver.js +3 -0
  41. package/dist/esm/index.d.ts +4 -0
  42. package/dist/esm/index.js +4 -0
  43. package/dist/esm/operation-node/data-type-node.d.ts +1 -1
  44. package/dist/esm/operation-node/insert-query-node.d.ts +2 -1
  45. package/dist/esm/operation-node/insert-query-node.js +2 -1
  46. package/dist/esm/operation-node/operation-node-transformer.js +1 -0
  47. package/dist/esm/query-builder/insert-query-builder.d.ts +1 -1
  48. package/dist/esm/query-builder/select-query-builder.d.ts +27 -0
  49. package/dist/esm/query-builder/select-query-builder.js +34 -2
  50. package/dist/esm/query-compiler/default-query-compiler.js +1 -1
  51. package/dist/esm/query-creator.d.ts +27 -0
  52. package/dist/esm/query-creator.js +33 -0
  53. package/dist/esm/query-executor/query-executor-base.d.ts +6 -0
  54. package/dist/esm/query-executor/query-executor-base.js +19 -0
  55. package/dist/esm/query-executor/query-executor.d.ts +11 -0
  56. package/dist/esm/schema/create-table-builder.d.ts +6 -6
  57. package/dist/esm/schema/create-table-builder.js +6 -6
  58. package/dist/esm/schema/create-type-builder.d.ts +9 -0
  59. package/dist/esm/schema/create-type-builder.js +9 -0
  60. package/dist/esm/util/deferred.d.ts +7 -0
  61. package/dist/esm/util/deferred.js +25 -0
  62. package/package.json +5 -2
@@ -47,17 +47,17 @@ export declare class CreateTableBuilder<TB extends string, C extends string = ne
47
47
  * .addColumn('first_name', 'varchar(50)', (col) => col.notNull())
48
48
  * .addColumn('last_name', 'varchar(255)')
49
49
  * .addColumn('bank_balance', 'numeric(8, 2)')
50
- * .addColumn('data', sql`customtype`)
50
+ * .addColumn('data', sql`some_type`)
51
51
  * .addColumn('parent_id', 'integer', (col) =>
52
52
  * col.references('person.id').onDelete('cascade'))
53
53
  * )
54
54
  * ```
55
55
  *
56
- * With this method, it's once again good to remember that Kysely just builds the query
57
- * and doesn't provide the same API for all databses. For example, some databases like
58
- * older MySQL don't support `references` statement in the column definition. Instead
59
- * foreign key constraints need to be defined in at the level of the `create table`
60
- * query. See the next example:
56
+ * With this method, it's once again good to remember that Kysely just builds the
57
+ * query and doesn't provide the same API for all databses. For example, some
58
+ * databases like older MySQL don't support the `references` statement in the
59
+ * column definition. Instead foreign key constraints need to be defined in the
60
+ * `create table` query. See the next example:
61
61
  *
62
62
  * ```ts
63
63
  * .addColumn('parent_id', 'integer')
@@ -76,17 +76,17 @@ class CreateTableBuilder {
76
76
  * .addColumn('first_name', 'varchar(50)', (col) => col.notNull())
77
77
  * .addColumn('last_name', 'varchar(255)')
78
78
  * .addColumn('bank_balance', 'numeric(8, 2)')
79
- * .addColumn('data', sql`customtype`)
79
+ * .addColumn('data', sql`some_type`)
80
80
  * .addColumn('parent_id', 'integer', (col) =>
81
81
  * col.references('person.id').onDelete('cascade'))
82
82
  * )
83
83
  * ```
84
84
  *
85
- * With this method, it's once again good to remember that Kysely just builds the query
86
- * and doesn't provide the same API for all databses. For example, some databases like
87
- * older MySQL don't support `references` statement in the column definition. Instead
88
- * foreign key constraints need to be defined in at the level of the `create table`
89
- * query. See the next example:
85
+ * With this method, it's once again good to remember that Kysely just builds the
86
+ * query and doesn't provide the same API for all databses. For example, some
87
+ * databases like older MySQL don't support the `references` statement in the
88
+ * column definition. Instead foreign key constraints need to be defined in the
89
+ * `create table` query. See the next example:
90
90
  *
91
91
  * ```ts
92
92
  * .addColumn('parent_id', 'integer')
@@ -8,6 +8,15 @@ export declare class CreateTypeBuilder implements OperationNodeSource, Compilabl
8
8
  #private;
9
9
  constructor(props: CreateTypeBuilderProps);
10
10
  toOperationNode(): CreateTypeNode;
11
+ /**
12
+ * Creates an anum type.
13
+ *
14
+ * ### Examples
15
+ *
16
+ * ```ts
17
+ * db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])
18
+ * ```
19
+ */
11
20
  asEnum(values: string[]): CreateTypeBuilder;
12
21
  compile(): CompiledQuery;
13
22
  execute(): Promise<void>;
@@ -12,6 +12,15 @@ class CreateTypeBuilder {
12
12
  toOperationNode() {
13
13
  return this.#props.executor.transformQuery(this.#props.createTypeNode, this.#props.queryId);
14
14
  }
15
+ /**
16
+ * Creates an anum type.
17
+ *
18
+ * ### Examples
19
+ *
20
+ * ```ts
21
+ * db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])
22
+ * ```
23
+ */
15
24
  asEnum(values) {
16
25
  return new CreateTypeBuilder({
17
26
  ...this.#props,
@@ -0,0 +1,7 @@
1
+ export declare class Deferred<T> {
2
+ #private;
3
+ constructor();
4
+ get promise(): Promise<T>;
5
+ resolve: (value: T | PromiseLike<T>) => void;
6
+ reject: (reason?: any) => void;
7
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Deferred = void 0;
4
+ class Deferred {
5
+ #promise;
6
+ #resolve;
7
+ #reject;
8
+ constructor() {
9
+ this.#promise = new Promise((resolve, reject) => {
10
+ this.#reject = reject;
11
+ this.#resolve = resolve;
12
+ });
13
+ }
14
+ get promise() {
15
+ return this.#promise;
16
+ }
17
+ resolve = (value) => {
18
+ if (this.#resolve) {
19
+ this.#resolve(value);
20
+ }
21
+ };
22
+ reject = (reason) => {
23
+ if (this.#reject) {
24
+ this.#reject(reason);
25
+ }
26
+ };
27
+ }
28
+ exports.Deferred = Deferred;
@@ -31,9 +31,19 @@ export interface MysqlPool {
31
31
  end(callback: (error: unknown) => void): void;
32
32
  }
33
33
  export interface MysqlPoolConnection {
34
+ query(sql: string, parameters: ReadonlyArray<unknown>): {
35
+ stream: <T>(options: MysqlStreamOptions) => MysqlStream<T>;
36
+ };
34
37
  query(sql: string, parameters: ReadonlyArray<unknown>, callback: (error: unknown, result: MysqlQueryResult) => void): void;
35
38
  release(): void;
36
39
  }
40
+ export interface MysqlStreamOptions {
41
+ highWaterMark?: number;
42
+ objectMode?: boolean;
43
+ }
44
+ export interface MysqlStream<T> {
45
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
46
+ }
37
47
  export interface MysqlOkPacket {
38
48
  affectedRows: number;
39
49
  insertId: number;
@@ -42,6 +42,7 @@ declare class MysqlConnection implements DatabaseConnection {
42
42
  #private;
43
43
  constructor(rawConnection: MysqlPoolConnection);
44
44
  executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>>;
45
+ streamQuery<O>(compiledQuery: CompiledQuery, chunkSize: number): AsyncIterableIterator<QueryResult<O>>;
45
46
  [PRIVATE_RELEASE_METHOD](): void;
46
47
  }
47
48
  export {};
@@ -121,6 +121,31 @@ class MysqlConnection {
121
121
  });
122
122
  });
123
123
  }
124
+ async *streamQuery(compiledQuery, chunkSize) {
125
+ const stream = this.#rawConnection
126
+ .query(compiledQuery.sql, compiledQuery.parameters)
127
+ .stream({
128
+ objectMode: true,
129
+ });
130
+ try {
131
+ for await (const row of stream) {
132
+ yield {
133
+ rows: [row],
134
+ };
135
+ }
136
+ }
137
+ catch (ex) {
138
+ if (ex &&
139
+ typeof ex === 'object' &&
140
+ 'code' in ex &&
141
+ // @ts-ignore
142
+ ex.code === 'ERR_STREAM_PREMATURE_CLOSE') {
143
+ // Most likely because of https://github.com/mysqljs/mysql/blob/master/lib/protocol/sequences/Query.js#L220
144
+ return;
145
+ }
146
+ throw ex;
147
+ }
148
+ }
124
149
  [PRIVATE_RELEASE_METHOD]() {
125
150
  this.#rawConnection.release();
126
151
  }
@@ -1,4 +1,14 @@
1
1
  import { DatabaseConnection } from '../../driver/database-connection.js';
2
+ export declare type PostgresCursorConstructor = new <T>(sql: string, parameters: readonly unknown[]) => PostgresCursor<T>;
3
+ export declare type PostgresCursor<T> = {
4
+ state: 'initialized' | 'idle' | 'submitted' | 'busy';
5
+ read: (rowsCount: number) => Promise<T[]>;
6
+ } | {
7
+ state: 'done';
8
+ } | {
9
+ state: 'error';
10
+ _error: Error;
11
+ };
2
12
  /**
3
13
  * Config for the PostgreSQL dialect.
4
14
  */
@@ -11,6 +21,19 @@ export interface PostgresDialectConfig {
11
21
  * https://node-postgres.com/api/pool
12
22
  */
13
23
  pool: PostgresPool | (() => Promise<PostgresPool>);
24
+ /**
25
+ * https://github.com/brianc/node-postgres/tree/master/packages/pg-cursor
26
+ * ```ts
27
+ * import Cursor from 'pg-cursor'
28
+ * // or
29
+ * import * as Cursor from 'pg-cursor'
30
+ *
31
+ * new PostgresDialect({
32
+ * cursor: Cursor
33
+ * })
34
+ * ```
35
+ */
36
+ cursor?: PostgresCursorConstructor;
14
37
  /**
15
38
  * Called once for each created connection.
16
39
  */
@@ -30,6 +53,7 @@ export interface PostgresPool {
30
53
  }
31
54
  export interface PostgresPoolClient {
32
55
  query<R>(sql: string, parameters: ReadonlyArray<unknown>): Promise<PostgresQueryResult<R>>;
56
+ query<R>(cursor: PostgresCursor<R>): PostgresCursor<R>;
33
57
  release(): void;
34
58
  }
35
59
  export interface PostgresQueryResult<R> {
@@ -37,3 +61,8 @@ export interface PostgresQueryResult<R> {
37
61
  rowCount: number;
38
62
  rows: R[];
39
63
  }
64
+ export interface PostgresStreamOptions {
65
+ }
66
+ export interface PostgresStream<T> {
67
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
68
+ }
@@ -1,7 +1,7 @@
1
1
  import { DatabaseConnection, QueryResult } from '../../driver/database-connection.js';
2
2
  import { Driver, TransactionSettings } from '../../driver/driver.js';
3
3
  import { CompiledQuery } from '../../query-compiler/compiled-query.js';
4
- import { PostgresDialectConfig, PostgresPoolClient } from './postgres-dialect-config.js';
4
+ import { PostgresCursorConstructor, PostgresDialectConfig, PostgresPoolClient } from './postgres-dialect-config.js';
5
5
  declare const PRIVATE_RELEASE_METHOD: unique symbol;
6
6
  export declare class PostgresDriver implements Driver {
7
7
  #private;
@@ -38,10 +38,14 @@ export declare class PostgresDriver implements Driver {
38
38
  */
39
39
  destroy(): Promise<void>;
40
40
  }
41
+ interface PostgresConnectionOptions {
42
+ cursor: PostgresCursorConstructor | null;
43
+ }
41
44
  declare class PostgresConnection implements DatabaseConnection {
42
45
  #private;
43
- constructor(client: PostgresPoolClient);
46
+ constructor(client: PostgresPoolClient, options: PostgresConnectionOptions);
44
47
  executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>>;
48
+ streamQuery<O>(compiledQuery: CompiledQuery, chunkSize: number): AsyncIterableIterator<QueryResult<O>>;
45
49
  [PRIVATE_RELEASE_METHOD](): void;
46
50
  }
47
51
  export {};
@@ -19,7 +19,9 @@ export class PostgresDriver {
19
19
  const client = await this.#pool.connect();
20
20
  let connection = this.#connections.get(client);
21
21
  if (!connection) {
22
- connection = new PostgresConnection(client);
22
+ connection = new PostgresConnection(client, {
23
+ cursor: this.#config.cursor ?? null,
24
+ });
23
25
  this.#connections.set(client, connection);
24
26
  // The driver must take care of calling `onCreateConnection` when a new
25
27
  // connection is created. The `pg` module doesn't provide an async hook
@@ -57,8 +59,10 @@ export class PostgresDriver {
57
59
  }
58
60
  class PostgresConnection {
59
61
  #client;
60
- constructor(client) {
62
+ #options;
63
+ constructor(client, options) {
61
64
  this.#client = client;
65
+ this.#options = options;
62
66
  }
63
67
  async executeQuery(compiledQuery) {
64
68
  try {
@@ -79,6 +83,24 @@ class PostgresConnection {
79
83
  throw extendStackTrace(err, new Error());
80
84
  }
81
85
  }
86
+ async *streamQuery(compiledQuery, chunkSize) {
87
+ if (!this.#options.cursor) {
88
+ throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");
89
+ }
90
+ const cursor = this.#client.query(new this.#options.cursor(compiledQuery.sql, compiledQuery.parameters));
91
+ while (true) {
92
+ if (cursor.state === 'done') {
93
+ break;
94
+ }
95
+ if (cursor.state === 'error') {
96
+ throw cursor._error;
97
+ }
98
+ const rows = await cursor.read(chunkSize);
99
+ yield {
100
+ rows,
101
+ };
102
+ }
103
+ }
82
104
  [PRIVATE_RELEASE_METHOD]() {
83
105
  this.#client.release();
84
106
  }
@@ -66,6 +66,9 @@ class SqliteConnection {
66
66
  });
67
67
  }
68
68
  }
69
+ async *streamQuery() {
70
+ throw new Error("Sqlite driver doesn't support streaming");
71
+ }
69
72
  }
70
73
  class ConnectionMutex {
71
74
  #promise;
@@ -6,6 +6,7 @@ import { CompiledQuery } from '../query-compiler/compiled-query.js';
6
6
  */
7
7
  export interface DatabaseConnection {
8
8
  executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>>;
9
+ streamQuery<R>(compiledQuery: CompiledQuery, chunkSize?: number): AsyncIterableIterator<QueryResult<R>>;
9
10
  }
10
11
  export interface QueryResult<O> {
11
12
  /**
@@ -64,4 +64,7 @@ class DummyConnection {
64
64
  rows: [],
65
65
  };
66
66
  }
67
+ async *streamQuery() {
68
+ // Nothing to do here.
69
+ }
67
70
  }
@@ -25,7 +25,9 @@ export * from './query-compiler/default-query-compiler.js';
25
25
  export * from './query-compiler/compiled-query.js';
26
26
  export * from './schema/schema.js';
27
27
  export * from './schema/create-table-builder.js';
28
+ export * from './schema/create-type-builder.js';
28
29
  export * from './schema/drop-table-builder.js';
30
+ export * from './schema/drop-type-builder.js';
29
31
  export * from './schema/create-index-builder.js';
30
32
  export * from './schema/drop-index-builder.js';
31
33
  export * from './schema/create-schema-builder.js';
@@ -87,6 +89,7 @@ export * from './operation-node/constraint-node.js';
87
89
  export * from './operation-node/create-index-node.js';
88
90
  export * from './operation-node/create-schema-node.js';
89
91
  export * from './operation-node/create-table-node.js';
92
+ export * from './operation-node/create-type-node.js';
90
93
  export * from './operation-node/create-view-node.js';
91
94
  export * from './operation-node/data-type-node.js';
92
95
  export * from './operation-node/default-value-node.js';
@@ -96,6 +99,7 @@ export * from './operation-node/drop-constraint-node.js';
96
99
  export * from './operation-node/drop-index-node.js';
97
100
  export * from './operation-node/drop-schema-node.js';
98
101
  export * from './operation-node/drop-table-node.js';
102
+ export * from './operation-node/drop-type-node.js';
99
103
  export * from './operation-node/drop-view-node.js';
100
104
  export * from './operation-node/filter-node.js';
101
105
  export * from './operation-node/foreign-key-constraint-node.js';
package/dist/esm/index.js CHANGED
@@ -26,7 +26,9 @@ export * from './query-compiler/default-query-compiler.js';
26
26
  export * from './query-compiler/compiled-query.js';
27
27
  export * from './schema/schema.js';
28
28
  export * from './schema/create-table-builder.js';
29
+ export * from './schema/create-type-builder.js';
29
30
  export * from './schema/drop-table-builder.js';
31
+ export * from './schema/drop-type-builder.js';
30
32
  export * from './schema/create-index-builder.js';
31
33
  export * from './schema/drop-index-builder.js';
32
34
  export * from './schema/create-schema-builder.js';
@@ -88,6 +90,7 @@ export * from './operation-node/constraint-node.js';
88
90
  export * from './operation-node/create-index-node.js';
89
91
  export * from './operation-node/create-schema-node.js';
90
92
  export * from './operation-node/create-table-node.js';
93
+ export * from './operation-node/create-type-node.js';
91
94
  export * from './operation-node/create-view-node.js';
92
95
  export * from './operation-node/data-type-node.js';
93
96
  export * from './operation-node/default-value-node.js';
@@ -97,6 +100,7 @@ export * from './operation-node/drop-constraint-node.js';
97
100
  export * from './operation-node/drop-index-node.js';
98
101
  export * from './operation-node/drop-schema-node.js';
99
102
  export * from './operation-node/drop-table-node.js';
103
+ export * from './operation-node/drop-type-node.js';
100
104
  export * from './operation-node/drop-view-node.js';
101
105
  export * from './operation-node/filter-node.js';
102
106
  export * from './operation-node/foreign-key-constraint-node.js';
@@ -1,5 +1,5 @@
1
1
  import { OperationNode } from './operation-node.js';
2
- export declare type ColumnDataType = 'varchar' | `varchar(${number})` | 'text' | 'integer' | 'int2' | 'int4' | 'int8' | 'bigint' | 'boolean' | 'real' | 'double precision' | 'float4' | 'float8' | 'decimal' | `decimal(${number}, ${number})` | 'numeric' | `numeric(${number}, ${number})` | 'binary' | 'date' | 'datetime' | 'time' | 'timetz' | 'timestamp' | 'timestamptz' | 'serial' | 'bigserial' | 'uuid' | 'json' | 'jsonb' | 'blob';
2
+ export declare type ColumnDataType = 'varchar' | `varchar(${number})` | 'text' | 'integer' | 'int2' | 'int4' | 'int8' | 'bigint' | 'boolean' | 'real' | 'double precision' | 'float4' | 'float8' | 'decimal' | `decimal(${number}, ${number})` | 'numeric' | `numeric(${number}, ${number})` | 'binary' | 'date' | 'datetime' | `datetime(${number})` | 'time' | `time(${number})` | 'timetz' | `timetz(${number})` | 'timestamp' | `timestamp(${number})` | 'timestamptz' | `timestamptz(${number})` | 'serial' | 'bigserial' | 'uuid' | 'json' | 'jsonb' | 'blob';
3
3
  export declare type DataTypeParams = Omit<DataTypeNode, 'kind' | 'dataType'>;
4
4
  export interface DataTypeNode extends OperationNode {
5
5
  readonly kind: 'DataTypeNode';
@@ -19,12 +19,13 @@ export interface InsertQueryNode extends OperationNode {
19
19
  readonly onDuplicateKey?: OnDuplicateKeyNode;
20
20
  readonly with?: WithNode;
21
21
  readonly ignore?: boolean;
22
+ readonly replace?: boolean;
22
23
  }
23
24
  /**
24
25
  * @internal
25
26
  */
26
27
  export declare const InsertQueryNode: Readonly<{
27
28
  is(node: OperationNode): node is InsertQueryNode;
28
- create(into: TableNode, withNode?: WithNode): InsertQueryNode;
29
+ create(into: TableNode, withNode?: WithNode, replace?: boolean): InsertQueryNode;
29
30
  cloneWith(insertQuery: InsertQueryNode, props: InsertQueryNodeProps): InsertQueryNode;
30
31
  }>;
@@ -7,11 +7,12 @@ export const InsertQueryNode = freeze({
7
7
  is(node) {
8
8
  return node.kind === 'InsertQueryNode';
9
9
  },
10
- create(into, withNode) {
10
+ create(into, withNode, replace) {
11
11
  return freeze({
12
12
  kind: 'InsertQueryNode',
13
13
  into,
14
14
  ...(withNode && { with: withNode }),
15
+ replace,
15
16
  });
16
17
  },
17
18
  cloneWith(insertQuery, props) {
@@ -242,6 +242,7 @@ export class OperationNodeTransformer {
242
242
  onDuplicateKey: this.transformNode(node.onDuplicateKey),
243
243
  with: this.transformNode(node.with),
244
244
  ignore: node.ignore,
245
+ replace: node.replace,
245
246
  });
246
247
  }
247
248
  transformValues(node) {
@@ -43,7 +43,7 @@ export declare class InsertQueryBuilder<DB, TB extends keyof DB, O> implements R
43
43
  *
44
44
  * Insert a row into `person`:
45
45
  * ```ts
46
- * const id = await db
46
+ * const result = await db
47
47
  * .insertInto('person')
48
48
  * .values({
49
49
  * first_name: 'Jennifer',
@@ -1343,6 +1343,33 @@ export declare class SelectQueryBuilder<DB, TB extends keyof DB, O> implements W
1343
1343
  * error.
1344
1344
  */
1345
1345
  executeTakeFirstOrThrow(errorConstructor?: NoResultErrorConstructor): Promise<O>;
1346
+ /**
1347
+ * Executes the query and streams the rows.
1348
+ *
1349
+ * The optional argument `chunkSize` defines how many rows to fetch from the database
1350
+ * at a time. It only affects some dialects like PostgreSQL that support it.
1351
+ *
1352
+ * ### Examples
1353
+ *
1354
+ * ```ts
1355
+ * const stream = db.
1356
+ * .selectFrom('person')
1357
+ * .select(['first_name', 'last_name'])
1358
+ * .where('gender', '=', 'other')
1359
+ * .stream()
1360
+ *
1361
+ * for await (const person of stream) {
1362
+ * console.log(person.first_name)
1363
+ *
1364
+ * if (person.last_name === 'Something') {
1365
+ * // Breaking or returning before the stream has ended will release
1366
+ * // the database connection and invalidate the stream.
1367
+ * break
1368
+ * }
1369
+ * }
1370
+ * ```
1371
+ */
1372
+ stream(chunkSize?: number): AsyncIterableIterator<O>;
1346
1373
  }
1347
1374
  export interface SelectQueryBuilderProps {
1348
1375
  readonly queryId: QueryId;
@@ -1,5 +1,6 @@
1
1
  /// <reference types="./select-query-builder.d.ts" />
2
2
  import { AliasNode } from '../operation-node/alias-node.js';
3
+ import { SelectModifierNode } from '../operation-node/select-modifier-node.js';
3
4
  import { parseJoin, } from '../parser/join-parser.js';
4
5
  import { parseSelectExpressionOrList, parseSelectAll, } from '../parser/select-parser.js';
5
6
  import { parseExistFilter, parseReferenceFilter, parseWhereFilter, parseHavingFilter, parseNotExistFilter, } from '../parser/filter-parser.js';
@@ -14,7 +15,6 @@ import { parseGroupBy } from '../parser/group-by-parser.js';
14
15
  import { parseUnion } from '../parser/union-parser.js';
15
16
  import { NoResultError } from './no-result-error.js';
16
17
  import { IdentifierNode } from '../operation-node/identifier-node.js';
17
- import { SelectModifierNode } from '../operation-node/select-modifier-node.js';
18
18
  export class SelectQueryBuilder {
19
19
  #props;
20
20
  constructor(props) {
@@ -628,7 +628,6 @@ export class SelectQueryBuilder {
628
628
  */
629
629
  async execute() {
630
630
  const compildQuery = this.compile();
631
- const query = compildQuery.query;
632
631
  const result = await this.#props.executor.executeQuery(compildQuery, this.#props.queryId);
633
632
  return result.rows;
634
633
  }
@@ -655,6 +654,39 @@ export class SelectQueryBuilder {
655
654
  }
656
655
  return result;
657
656
  }
657
+ /**
658
+ * Executes the query and streams the rows.
659
+ *
660
+ * The optional argument `chunkSize` defines how many rows to fetch from the database
661
+ * at a time. It only affects some dialects like PostgreSQL that support it.
662
+ *
663
+ * ### Examples
664
+ *
665
+ * ```ts
666
+ * const stream = db.
667
+ * .selectFrom('person')
668
+ * .select(['first_name', 'last_name'])
669
+ * .where('gender', '=', 'other')
670
+ * .stream()
671
+ *
672
+ * for await (const person of stream) {
673
+ * console.log(person.first_name)
674
+ *
675
+ * if (person.last_name === 'Something') {
676
+ * // Breaking or returning before the stream has ended will release
677
+ * // the database connection and invalidate the stream.
678
+ * break
679
+ * }
680
+ * }
681
+ * ```
682
+ */
683
+ async *stream(chunkSize = 100) {
684
+ const compildQuery = this.compile();
685
+ const stream = this.#props.executor.stream(compildQuery, chunkSize, this.#props.queryId);
686
+ for await (const item of stream) {
687
+ yield* item.rows;
688
+ }
689
+ }
658
690
  }
659
691
  preventAwait(SelectQueryBuilder, "don't await SelectQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.");
660
692
  /**
@@ -132,7 +132,7 @@ export class DefaultQueryCompiler extends OperationNodeVisitor {
132
132
  this.visitNode(node.with);
133
133
  this.append(' ');
134
134
  }
135
- this.append('insert');
135
+ this.append(node.replace ? 'replace' : 'insert');
136
136
  if (node.ignore) {
137
137
  this.append(' ignore');
138
138
  }
@@ -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
  */