kysely 0.16.11 → 0.17.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 (170) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/dialect/mysql/mysql-adapter.js +3 -4
  3. package/dist/cjs/dialect/mysql/mysql-introspector.js +2 -1
  4. package/dist/cjs/dialect/postgres/postgres-adapter.js +3 -2
  5. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +2 -1
  6. package/dist/cjs/index-nodeless.d.ts +2 -0
  7. package/dist/cjs/index-nodeless.js +2 -0
  8. package/dist/cjs/kysely.d.ts +3 -6
  9. package/dist/cjs/kysely.js +7 -12
  10. package/dist/cjs/migration/migrator.js +4 -4
  11. package/dist/cjs/operation-node/operation-node-transformer.js +1 -1
  12. package/dist/cjs/operation-node/raw-node.d.ts +4 -2
  13. package/dist/cjs/operation-node/raw-node.js +8 -2
  14. package/dist/cjs/parser/complex-expression-parser.d.ts +5 -5
  15. package/dist/cjs/parser/complex-expression-parser.js +5 -4
  16. package/dist/cjs/parser/filter-parser.d.ts +9 -9
  17. package/dist/cjs/parser/filter-parser.js +31 -30
  18. package/dist/cjs/parser/group-by-parser.d.ts +1 -2
  19. package/dist/cjs/parser/group-by-parser.js +2 -2
  20. package/dist/cjs/parser/insert-values-parser.d.ts +1 -2
  21. package/dist/cjs/parser/insert-values-parser.js +6 -6
  22. package/dist/cjs/parser/join-parser.d.ts +1 -2
  23. package/dist/cjs/parser/join-parser.js +8 -7
  24. package/dist/cjs/parser/order-by-parser.d.ts +1 -2
  25. package/dist/cjs/parser/order-by-parser.js +4 -4
  26. package/dist/cjs/parser/parse-utils.d.ts +10 -0
  27. package/dist/cjs/parser/parse-utils.js +38 -0
  28. package/dist/cjs/parser/reference-parser.d.ts +2 -3
  29. package/dist/cjs/parser/reference-parser.js +5 -5
  30. package/dist/cjs/parser/select-parser.d.ts +1 -2
  31. package/dist/cjs/parser/select-parser.js +5 -5
  32. package/dist/cjs/parser/table-parser.d.ts +2 -3
  33. package/dist/cjs/parser/table-parser.js +5 -5
  34. package/dist/cjs/parser/update-set-parser.d.ts +1 -2
  35. package/dist/cjs/parser/update-set-parser.js +2 -2
  36. package/dist/cjs/parser/value-parser.d.ts +3 -4
  37. package/dist/cjs/parser/value-parser.js +7 -7
  38. package/dist/cjs/parser/with-parser.d.ts +1 -2
  39. package/dist/cjs/parser/with-parser.js +3 -2
  40. package/dist/cjs/query-builder/delete-query-builder.d.ts +23 -19
  41. package/dist/cjs/query-builder/delete-query-builder.js +15 -15
  42. package/dist/cjs/query-builder/expression-builder.d.ts +4 -13
  43. package/dist/cjs/query-builder/expression-builder.js +12 -21
  44. package/dist/cjs/query-builder/function-builder.d.ts +2 -6
  45. package/dist/cjs/query-builder/function-builder.js +5 -8
  46. package/dist/cjs/query-builder/insert-query-builder.d.ts +12 -8
  47. package/dist/cjs/query-builder/insert-query-builder.js +8 -7
  48. package/dist/cjs/query-builder/join-builder.d.ts +0 -2
  49. package/dist/cjs/query-builder/join-builder.js +8 -8
  50. package/dist/cjs/query-builder/on-conflict-builder.d.ts +24 -20
  51. package/dist/cjs/query-builder/on-conflict-builder.js +17 -17
  52. package/dist/cjs/query-builder/returning-interface.d.ts +3 -1
  53. package/dist/cjs/query-builder/select-query-builder.d.ts +41 -29
  54. package/dist/cjs/query-builder/select-query-builder.js +28 -26
  55. package/dist/cjs/query-builder/update-query-builder.d.ts +30 -24
  56. package/dist/cjs/query-builder/update-query-builder.js +22 -20
  57. package/dist/cjs/query-builder/where-interface.d.ts +20 -16
  58. package/dist/cjs/query-compiler/default-query-compiler.js +1 -1
  59. package/dist/cjs/query-creator.d.ts +10 -129
  60. package/dist/cjs/query-creator.js +5 -136
  61. package/dist/cjs/query-executor/default-query-executor.d.ts +8 -1
  62. package/dist/cjs/query-executor/default-query-executor.js +13 -13
  63. package/dist/cjs/query-executor/noop-query-executor.d.ts +8 -0
  64. package/dist/cjs/query-executor/noop-query-executor.js +8 -1
  65. package/dist/cjs/query-executor/query-executor-provider.d.ts +8 -0
  66. package/dist/cjs/query-executor/query-executor-provider.js +2 -0
  67. package/dist/cjs/query-executor/query-executor.d.ts +7 -0
  68. package/dist/cjs/raw-builder/raw-builder.d.ts +42 -11
  69. package/dist/cjs/raw-builder/raw-builder.js +55 -56
  70. package/dist/cjs/raw-builder/sql.d.ts +323 -0
  71. package/dist/cjs/raw-builder/sql.js +153 -0
  72. package/dist/cjs/schema/alter-table-builder.d.ts +20 -8
  73. package/dist/cjs/schema/column-definition-builder.d.ts +20 -8
  74. package/dist/cjs/schema/create-index-builder.d.ts +3 -1
  75. package/dist/cjs/schema/create-index-builder.js +3 -1
  76. package/dist/cjs/schema/create-table-builder.d.ts +6 -2
  77. package/dist/cjs/schema/create-table-builder.js +6 -2
  78. package/dist/cjs/schema/create-view-builder.d.ts +3 -3
  79. package/dist/cjs/schema/create-view-builder.js +3 -3
  80. package/dist/cjs/util/query-id.js +10 -4
  81. package/dist/cjs/util/random-string.js +65 -2
  82. package/dist/esm/dialect/mysql/mysql-adapter.js +3 -4
  83. package/dist/esm/dialect/mysql/mysql-introspector.js +2 -1
  84. package/dist/esm/dialect/postgres/postgres-adapter.js +3 -2
  85. package/dist/esm/dialect/sqlite/sqlite-introspector.js +2 -1
  86. package/dist/esm/index-nodeless.d.ts +2 -0
  87. package/dist/esm/index-nodeless.js +2 -0
  88. package/dist/esm/kysely.d.ts +3 -6
  89. package/dist/esm/kysely.js +7 -12
  90. package/dist/esm/migration/migrator.js +4 -4
  91. package/dist/esm/operation-node/operation-node-transformer.js +1 -1
  92. package/dist/esm/operation-node/raw-node.d.ts +4 -2
  93. package/dist/esm/operation-node/raw-node.js +8 -2
  94. package/dist/esm/parser/complex-expression-parser.d.ts +5 -5
  95. package/dist/esm/parser/complex-expression-parser.js +5 -4
  96. package/dist/esm/parser/filter-parser.d.ts +9 -9
  97. package/dist/esm/parser/filter-parser.js +31 -30
  98. package/dist/esm/parser/group-by-parser.d.ts +1 -2
  99. package/dist/esm/parser/group-by-parser.js +2 -2
  100. package/dist/esm/parser/insert-values-parser.d.ts +1 -2
  101. package/dist/esm/parser/insert-values-parser.js +6 -6
  102. package/dist/esm/parser/join-parser.d.ts +1 -2
  103. package/dist/esm/parser/join-parser.js +8 -7
  104. package/dist/esm/parser/order-by-parser.d.ts +1 -2
  105. package/dist/esm/parser/order-by-parser.js +4 -4
  106. package/dist/esm/parser/parse-utils.d.ts +10 -0
  107. package/dist/esm/parser/parse-utils.js +32 -0
  108. package/dist/esm/parser/reference-parser.d.ts +2 -3
  109. package/dist/esm/parser/reference-parser.js +5 -5
  110. package/dist/esm/parser/select-parser.d.ts +1 -2
  111. package/dist/esm/parser/select-parser.js +5 -5
  112. package/dist/esm/parser/table-parser.d.ts +2 -3
  113. package/dist/esm/parser/table-parser.js +5 -5
  114. package/dist/esm/parser/update-set-parser.d.ts +1 -2
  115. package/dist/esm/parser/update-set-parser.js +2 -2
  116. package/dist/esm/parser/value-parser.d.ts +3 -4
  117. package/dist/esm/parser/value-parser.js +7 -7
  118. package/dist/esm/parser/with-parser.d.ts +1 -2
  119. package/dist/esm/parser/with-parser.js +3 -2
  120. package/dist/esm/query-builder/delete-query-builder.d.ts +23 -19
  121. package/dist/esm/query-builder/delete-query-builder.js +15 -15
  122. package/dist/esm/query-builder/expression-builder.d.ts +4 -13
  123. package/dist/esm/query-builder/expression-builder.js +12 -21
  124. package/dist/esm/query-builder/function-builder.d.ts +2 -6
  125. package/dist/esm/query-builder/function-builder.js +5 -8
  126. package/dist/esm/query-builder/insert-query-builder.d.ts +12 -8
  127. package/dist/esm/query-builder/insert-query-builder.js +8 -7
  128. package/dist/esm/query-builder/join-builder.d.ts +0 -2
  129. package/dist/esm/query-builder/join-builder.js +8 -8
  130. package/dist/esm/query-builder/on-conflict-builder.d.ts +24 -20
  131. package/dist/esm/query-builder/on-conflict-builder.js +17 -17
  132. package/dist/esm/query-builder/returning-interface.d.ts +3 -1
  133. package/dist/esm/query-builder/select-query-builder.d.ts +41 -29
  134. package/dist/esm/query-builder/select-query-builder.js +28 -26
  135. package/dist/esm/query-builder/update-query-builder.d.ts +30 -24
  136. package/dist/esm/query-builder/update-query-builder.js +22 -20
  137. package/dist/esm/query-builder/where-interface.d.ts +20 -16
  138. package/dist/esm/query-compiler/default-query-compiler.js +1 -1
  139. package/dist/esm/query-creator.d.ts +10 -129
  140. package/dist/esm/query-creator.js +5 -136
  141. package/dist/esm/query-executor/default-query-executor.d.ts +8 -1
  142. package/dist/esm/query-executor/default-query-executor.js +13 -13
  143. package/dist/esm/query-executor/noop-query-executor.d.ts +8 -0
  144. package/dist/esm/query-executor/noop-query-executor.js +7 -0
  145. package/dist/esm/query-executor/query-executor-provider.d.ts +8 -0
  146. package/dist/esm/query-executor/query-executor-provider.js +2 -0
  147. package/dist/esm/query-executor/query-executor.d.ts +7 -0
  148. package/dist/esm/raw-builder/raw-builder.d.ts +42 -11
  149. package/dist/esm/raw-builder/raw-builder.js +56 -57
  150. package/dist/esm/raw-builder/sql.d.ts +323 -0
  151. package/dist/esm/raw-builder/sql.js +151 -0
  152. package/dist/esm/schema/alter-table-builder.d.ts +20 -8
  153. package/dist/esm/schema/column-definition-builder.d.ts +20 -8
  154. package/dist/esm/schema/create-index-builder.d.ts +3 -1
  155. package/dist/esm/schema/create-index-builder.js +3 -1
  156. package/dist/esm/schema/create-table-builder.d.ts +6 -2
  157. package/dist/esm/schema/create-table-builder.js +6 -2
  158. package/dist/esm/schema/create-view-builder.d.ts +3 -3
  159. package/dist/esm/schema/create-view-builder.js +3 -3
  160. package/dist/esm/util/query-id.js +10 -4
  161. package/dist/esm/util/random-string.js +65 -2
  162. package/package.json +13 -13
  163. package/dist/cjs/parser/parse-context.d.ts +0 -55
  164. package/dist/cjs/parser/parse-context.js +0 -50
  165. package/dist/cjs/util/private-symbols.d.ts +0 -5
  166. package/dist/cjs/util/private-symbols.js +0 -8
  167. package/dist/esm/parser/parse-context.d.ts +0 -55
  168. package/dist/esm/parser/parse-context.js +0 -47
  169. package/dist/esm/util/private-symbols.d.ts +0 -5
  170. package/dist/esm/util/private-symbols.js +0 -6
@@ -1,74 +1,84 @@
1
1
  /// <reference types="./raw-builder.d.ts" />
2
2
  import { AliasNode } from '../operation-node/alias-node.js';
3
- import { isOperationNodeSource, } from '../operation-node/operation-node-source.js';
4
- import { RawNode } from '../operation-node/raw-node.js';
5
- import { ValueNode } from '../operation-node/value-node.js';
6
- import { parseStringReference } from '../parser/reference-parser.js';
7
3
  import { preventAwait } from '../util/prevent-await.js';
8
- import { createQueryId } from '../util/query-id.js';
9
4
  import { freeze } from '../util/object-utils.js';
10
- import { NoopQueryExecutor } from '../query-executor/noop-query-executor.js';
5
+ import { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';
6
+ /**
7
+ * An instance of this class can be used to create raw SQL snippets or queries.
8
+ *
9
+ * You shouldn't need to create `RawBuilder` instances directly. Instead you should
10
+ * use the {@link sql} template tag.
11
+ */
11
12
  export class RawBuilder {
12
13
  #props;
13
14
  constructor(props) {
14
- this.#props = freeze({
15
- queryId: props.queryId ?? createQueryId(),
16
- executor: props.executor ?? new NoopQueryExecutor(),
17
- sql: props.sql,
18
- parameters: props.parameters,
19
- });
15
+ this.#props = freeze(props);
20
16
  }
17
+ /**
18
+ * Returns an aliased version of the SQL expression.
19
+ *
20
+ * In addition to slapping `as "the_alias"` to the end of the SQL,
21
+ * this method also provides strict typing:
22
+ *
23
+ * ```ts
24
+ * const result = await db
25
+ * .selectFrom('person')
26
+ * .select(
27
+ * sql<string>`concat(first_name, ' ', last_name)`.as('full_name')
28
+ * )
29
+ * .executeTakeFirstOrThrow()
30
+ *
31
+ * // `full_name: string` field exists in the result type.
32
+ * console.log(result.full_name)
33
+ * ```
34
+ *
35
+ * The generated SQL (PostgreSQL):
36
+ *
37
+ * ```ts
38
+ * select concat(first_name, ' ', last_name) as "full_name"
39
+ * from "person"
40
+ * ```
41
+ */
21
42
  as(alias) {
22
43
  return new AliasedRawBuilder(this, alias);
23
44
  }
24
45
  /**
25
46
  * Change the output type of the raw expression.
26
47
  *
27
- * This doesn't produce any SQL. This methods simply returns a copy
28
- * of this `RawBuilder` with a new output type.
48
+ * This method call doesn't change the SQL in any way. This methods simply
49
+ * returns a copy of this `RawBuilder` with a new output type.
29
50
  */
30
51
  castTo() {
31
- return new RawBuilder({
32
- ...this.#props,
33
- });
52
+ return new RawBuilder({ ...this.#props });
34
53
  }
54
+ /**
55
+ * Adds a plugin for this SQL snippet.
56
+ */
35
57
  withPlugin(plugin) {
36
58
  return new RawBuilder({
37
59
  ...this.#props,
38
- executor: this.#props.executor.withPlugin(plugin),
60
+ plugins: this.#props.plugins !== undefined
61
+ ? freeze([...this.#props.plugins, plugin])
62
+ : freeze([plugin]),
39
63
  });
40
64
  }
41
65
  toOperationNode() {
42
- const parameterPlaceholderRegex = /(\?\??)/g;
43
- const sql = this.#props.sql;
44
- const parameters = this.#props.parameters ?? [];
45
- const sqlFragments = [];
46
- const argNodes = [];
47
- let paramIdx = 0;
48
- let sqlIdx = 0;
49
- let match = null;
50
- while ((match = parameterPlaceholderRegex.exec(sql))) {
51
- const str = match[1];
52
- if (paramIdx >= parameters.length) {
53
- throw new Error(`value not provided for all placeholders in string ${sql}`);
54
- }
55
- if (match.index > 0 && sql[match.index - 1] === '\\') {
56
- continue;
57
- }
58
- sqlFragments.push(sql.slice(sqlIdx, match.index).replace(/\\\?/g, '?'));
59
- argNodes.push(parseRawArg(str, parameters[paramIdx]));
60
- sqlIdx = match.index + str.length;
61
- ++paramIdx;
62
- }
63
- sqlFragments.push(sql.slice(sqlIdx));
64
- const rawNode = RawNode.create(sqlFragments, argNodes);
65
- return this.#props.executor.transformQuery(rawNode, this.#props.queryId);
66
+ const executor = this.#props.plugins !== undefined
67
+ ? NOOP_QUERY_EXECUTOR.withPlugins(this.#props.plugins)
68
+ : NOOP_QUERY_EXECUTOR;
69
+ return this.#toOperationNode(executor);
66
70
  }
67
- compile() {
68
- return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
71
+ async execute(executorProvider) {
72
+ const executor = this.#props.plugins !== undefined
73
+ ? executorProvider.getExecutor().withPlugins(this.#props.plugins)
74
+ : executorProvider.getExecutor();
75
+ return executor.executeQuery(this.#compile(executor), this.#props.queryId);
69
76
  }
70
- async execute() {
71
- return this.#props.executor.executeQuery(this.compile(), this.#props.queryId);
77
+ #toOperationNode(executor) {
78
+ return executor.transformQuery(this.#props.rawNode, this.#props.queryId);
79
+ }
80
+ #compile(executor) {
81
+ return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);
72
82
  }
73
83
  }
74
84
  preventAwait(RawBuilder, "don't await RawBuilder instances directly. To execute the query you need to call `execute`");
@@ -97,14 +107,3 @@ export class AliasedRawBuilder {
97
107
  this.#alias = alias;
98
108
  }
99
109
  }
100
- function parseRawArg(match, arg) {
101
- if (isOperationNodeSource(arg)) {
102
- return arg.toOperationNode();
103
- }
104
- else if (match === '??') {
105
- return parseStringReference(arg);
106
- }
107
- else {
108
- return ValueNode.create(arg);
109
- }
110
- }
@@ -0,0 +1,323 @@
1
+ import { RawBuilder } from './raw-builder.js';
2
+ export interface Sql {
3
+ <T = unknown>(sqlFragments: TemplateStringsArray, ...parameters: unknown[]): RawBuilder<T>;
4
+ /**
5
+ * This can be used to add runtime column references to SQL snippets.
6
+ *
7
+ * By default `${}` substitutions in {@link sql} template strings get
8
+ * transformed into parameters. You can use this function to tell
9
+ * Kysely to interpret them as column references instead.
10
+ *
11
+ * WARNING! Using this with unchecked inputs WILL lead to SQL injection
12
+ * vulnerabilities. The input is not checked or escaped by Kysely in any way.
13
+ *
14
+ * ```ts
15
+ * const columnRef = 'first_name'
16
+ *
17
+ * sql`select ${sql.ref(columnRef)} from person`
18
+ * ```
19
+ *
20
+ * The generated SQL (PostgreSQL):
21
+ *
22
+ * ```sql
23
+ * select "first_name" from person
24
+ * ```
25
+ *
26
+ * The refefences can also include a table name:
27
+ *
28
+ * ```ts
29
+ * const columnRef = 'person.first_name'
30
+ *
31
+ * sql`select ${sql.ref(columnRef)}} from person`
32
+ * ```
33
+ *
34
+ * The generated SQL (PostgreSQL):
35
+ *
36
+ * ```sql
37
+ * select "person"."first_name" from person
38
+ * ```
39
+ *
40
+ * The refefences can also include a schema on supported databases:
41
+ *
42
+ * ```ts
43
+ * const columnRef = 'public.person.first_name'
44
+ *
45
+ * sql`select ${sql.ref(columnRef)}} from person`
46
+ * ```
47
+ *
48
+ * The generated SQL (PostgreSQL):
49
+ *
50
+ * ```sql
51
+ * select "public"."person"."first_name" from person
52
+ * ```
53
+ */
54
+ ref(columnReference: string): RawBuilder<unknown>;
55
+ /**
56
+ * This can be used to add runtime table references to SQL snippets.
57
+ *
58
+ * By default `${}` substitutions in {@link sql} template strings get
59
+ * transformed into parameters. You can use this function to tell
60
+ * Kysely to interpret them as table references instead.
61
+ *
62
+ * WARNING! Using this with unchecked inputs WILL lead to SQL injection
63
+ * vulnerabilities. The input is not checked or escaped by Kysely in any way.
64
+ *
65
+ * ```ts
66
+ * const table = 'person'
67
+ *
68
+ * sql`select first_name from ${sql.table(table)}`
69
+ * ```
70
+ *
71
+ * The generated SQL (PostgreSQL):
72
+ *
73
+ * ```sql
74
+ * select first_name from "person"
75
+ * ```
76
+ *
77
+ * The refefences can also include a schema on supported databases:
78
+ *
79
+ * ```ts
80
+ * const table = 'public.person'
81
+ *
82
+ * sql`select first_name from ${sql.table(table)}`
83
+ * ```
84
+ *
85
+ * The generated SQL (PostgreSQL):
86
+ *
87
+ * ```sql
88
+ * select first_name from "public"."person"
89
+ * ```
90
+ */
91
+ table(tableReference: string): RawBuilder<unknown>;
92
+ /**
93
+ * This can be used to add arbitrary identifiers to SQL snippets.
94
+ *
95
+ * Does the same thing as {@link Sql.ref | ref} and {@link Sql.table | table}
96
+ * but can also be used for any other identifiers like index names.
97
+ *
98
+ * You should use {@link Sql.ref | ref} and {@link Sql.table | table}
99
+ * instead of this whenever possible as they produce a more sematic
100
+ * operation node tree.
101
+ *
102
+ * WARNING! Using this with unchecked inputs WILL lead to SQL injection
103
+ * vulnerabilities. The input is not checked or escaped by Kysely in any way.
104
+ *
105
+ * ```ts
106
+ * const indexName = 'person_first_name_index'
107
+ *
108
+ * sql`create index ${indexName} on person`
109
+ * ```
110
+ *
111
+ * The generated SQL (PostgreSQL):
112
+ *
113
+ * ```sql
114
+ * create index "person_first_name_index" on person
115
+ * ```
116
+ *
117
+ * Multiple identifiers get separated by dots:
118
+ *
119
+ * ```ts
120
+ * const schema = 'public'
121
+ * const columnName = 'first_name'
122
+ * const table = 'person'
123
+ *
124
+ * sql`select ${sql.id(schema, table, columnName)}} from ${sql.id(schema, table)}`
125
+ * ```
126
+ *
127
+ * The generated SQL (PostgreSQL):
128
+ *
129
+ * ```sql
130
+ * select "public"."person"."first_name" from "public"."person"
131
+ * ```
132
+ */
133
+ id(...ids: string[]): RawBuilder<unknown>;
134
+ /**
135
+ * This can be used to add literal values to SQL snippets.
136
+ *
137
+ * WARNING! Using this with unchecked inputs WILL lead to SQL injection
138
+ * vulnerabilities. The input is not checked or escaped by Kysely in any way.
139
+ * You almost always want to use normal substitutions that get sent to the
140
+ * db as parameters.
141
+ *
142
+ * ```ts
143
+ * const firstName = 'first_name'
144
+ *
145
+ * sql`select * from person where first_name = ${sql.literal(firstName)}`
146
+ * ```
147
+ *
148
+ * The generated SQL (PostgreSQL):
149
+ *
150
+ * ```sql
151
+ * select * from person where first_name = 'first_name'
152
+ * ```
153
+ *
154
+ * As you can see from the example above, the value was added directly to
155
+ * the SQL string instead of as a parameter. Only use this function when
156
+ * something can't be sent as a parameter.
157
+ */
158
+ literal(value: unknown): RawBuilder<unknown>;
159
+ /**
160
+ * This can be used to add arbitrary runtime SQL to SQL snippets.
161
+ *
162
+ * WARNING! Using this with unchecked inputs WILL lead to SQL injection
163
+ * vulnerabilities. The input is not checked or escaped by Kysely in any way.
164
+ *
165
+ * ```ts
166
+ * const firstName = "'first_name'"
167
+ *
168
+ * sql`select * from person where first_name = ${sql.raw(firstName)}`
169
+ * ```
170
+ *
171
+ * The generated SQL (PostgreSQL):
172
+ *
173
+ * ```sql
174
+ * select * from person where first_name = 'first_name'
175
+ * ```
176
+ *
177
+ * Note that the difference to `sql.literal` is that this function
178
+ * doesn't assume the inputs are values. The input to this function
179
+ * can be any sql and it's simply glued to the parent string as-is.
180
+ */
181
+ raw(anySql: string): RawBuilder<unknown>;
182
+ /**
183
+ * This can be used to add lists of things to SQL snippets.
184
+ *
185
+ * ### Examples
186
+ *
187
+ * ```ts
188
+ * function findByNicknames(nicknames: string[]): Promise<Person[]> {
189
+ * return db
190
+ * .selectFrom('person')
191
+ * .selectAll()
192
+ * .where('nicknames', '@>', sql`ARRAY[${sql.join(nicknames)}]`)
193
+ * .execute()
194
+ * }
195
+ * ```
196
+ *
197
+ * The generated SQL (PostgreSQL):
198
+ *
199
+ * ```sql
200
+ * select * from "person"
201
+ * where "nicknames" @> ARRAY[$1, $2, $3, $4, $5, $6, $7, $8]
202
+ * ```
203
+ *
204
+ * The second argument is the joining SQL expression that defaults
205
+ * to
206
+ *
207
+ * ```ts
208
+ * sql`, `
209
+ * ```
210
+ *
211
+ * In addition to values, items in the list can be also {@link sql}
212
+ * expressions, queries or anything else the normal substitutions
213
+ * support:
214
+ *
215
+ * ```ts
216
+ * const things = [
217
+ * 123,
218
+ * sql`(1 == 1)`,
219
+ * db.selectFrom('person').selectAll(),
220
+ * sql.literal(false),
221
+ * sql.id('first_name')
222
+ * ]
223
+ *
224
+ * sql`BEFORE ${sql.array(things, sql`::varchar, `)} AFTER`
225
+ * ```
226
+ *
227
+ * The generated SQL (PostgreSQL):
228
+ *
229
+ * ```sql
230
+ * BEFORE $1::varchar, (1 == 1)::varchar, (select * from "person")::varchar, false::varchar, "first_name" AFTER
231
+ * ```
232
+ */
233
+ join(array: unknown[], separator?: RawBuilder<any>): RawBuilder<unknown>;
234
+ }
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 concate(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) => sql<string>`concat(${eb.ref('first_name')}, ' ', ${eb.ref('last_name')})`.as('full_name')
317
+ * ])
318
+ * ```
319
+ *
320
+ * don't know if that amount of ceremony is worth the small increase in
321
+ * type-safety though... But it's possible.
322
+ */
323
+ export declare const sql: Sql;
@@ -0,0 +1,151 @@
1
+ /// <reference types="./sql.d.ts" />
2
+ import { IdentifierNode } from '../operation-node/identifier-node.js';
3
+ import { RawNode } from '../operation-node/raw-node.js';
4
+ import { ValueNode } from '../operation-node/value-node.js';
5
+ import { parseStringReference } from '../parser/reference-parser.js';
6
+ import { parseTable } from '../parser/table-parser.js';
7
+ import { parseValueExpression } from '../parser/value-parser.js';
8
+ import { createQueryId } from '../util/query-id.js';
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 concate(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) => sql<string>`concat(${eb.ref('first_name')}, ' ', ${eb.ref('last_name')})`.as('full_name')
92
+ * ])
93
+ * ```
94
+ *
95
+ * don't know if that amount of ceremony is worth the small increase in
96
+ * type-safety though... But it's possible.
97
+ */
98
+ export const sql = Object.assign((sqlFragments, ...parameters) => {
99
+ return new RawBuilder({
100
+ queryId: createQueryId(),
101
+ rawNode: RawNode.create(sqlFragments, parameters?.map(parseValueExpression) ?? []),
102
+ });
103
+ }, {
104
+ ref(columnReference) {
105
+ return new RawBuilder({
106
+ queryId: createQueryId(),
107
+ rawNode: RawNode.createWithChild(parseStringReference(columnReference)),
108
+ });
109
+ },
110
+ table(tableReference) {
111
+ return new RawBuilder({
112
+ queryId: createQueryId(),
113
+ rawNode: RawNode.createWithChild(parseTable(tableReference)),
114
+ });
115
+ },
116
+ id(...ids) {
117
+ const fragments = new Array(ids.length + 1).fill('.');
118
+ fragments[0] = '';
119
+ fragments[fragments.length - 1] = '';
120
+ return new RawBuilder({
121
+ queryId: createQueryId(),
122
+ rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),
123
+ });
124
+ },
125
+ literal(value) {
126
+ return new RawBuilder({
127
+ queryId: createQueryId(),
128
+ rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),
129
+ });
130
+ },
131
+ raw(sql) {
132
+ return new RawBuilder({
133
+ queryId: createQueryId(),
134
+ rawNode: RawNode.createWithSql(sql),
135
+ });
136
+ },
137
+ join(array, separator = sql `, `) {
138
+ const nodes = new Array(2 * array.length - 1);
139
+ const sep = separator.toOperationNode();
140
+ for (let i = 0; i < array.length; ++i) {
141
+ nodes[2 * i] = parseValueExpression(array[i]);
142
+ if (i !== array.length - 1) {
143
+ nodes[2 * i + 1] = sep;
144
+ }
145
+ }
146
+ return new RawBuilder({
147
+ queryId: createQueryId(),
148
+ rawNode: RawNode.createWithChildren(nodes),
149
+ });
150
+ },
151
+ });