drizzle-orm 0.25.2 → 0.25.3-4cc2d87

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 (249) hide show
  1. package/aws-data-api/pg/index.cjs +234 -1
  2. package/aws-data-api/pg/index.cjs.map +1 -1
  3. package/aws-data-api/pg/index.d.ts +5 -6
  4. package/aws-data-api/pg/index.mjs +228 -1
  5. package/aws-data-api/pg/index.mjs.map +1 -1
  6. package/aws-data-api/pg/migrator.cjs +13 -1
  7. package/aws-data-api/pg/migrator.cjs.map +1 -1
  8. package/aws-data-api/pg/migrator.d.ts +5 -6
  9. package/aws-data-api/pg/migrator.mjs +11 -1
  10. package/aws-data-api/pg/migrator.mjs.map +1 -1
  11. package/better-sqlite3/index.cjs +119 -1
  12. package/better-sqlite3/index.cjs.map +1 -1
  13. package/better-sqlite3/index.d.ts +14 -12
  14. package/better-sqlite3/index.mjs +114 -1
  15. package/better-sqlite3/index.mjs.map +1 -1
  16. package/better-sqlite3/migrator.cjs +13 -1
  17. package/better-sqlite3/migrator.cjs.map +1 -1
  18. package/better-sqlite3/migrator.d.ts +5 -5
  19. package/better-sqlite3/migrator.mjs +11 -1
  20. package/better-sqlite3/migrator.mjs.map +1 -1
  21. package/bun-sqlite/index.cjs +126 -1
  22. package/bun-sqlite/index.cjs.map +1 -1
  23. package/bun-sqlite/index.d.ts +14 -12
  24. package/bun-sqlite/index.mjs +121 -1
  25. package/bun-sqlite/index.mjs.map +1 -1
  26. package/bun-sqlite/migrator.cjs +13 -1
  27. package/bun-sqlite/migrator.cjs.map +1 -1
  28. package/bun-sqlite/migrator.d.ts +5 -5
  29. package/bun-sqlite/migrator.mjs +11 -1
  30. package/bun-sqlite/migrator.mjs.map +1 -1
  31. package/{column.d-8b137277.d.ts → column.d-c31e7ad3.d.ts} +77 -6
  32. package/d1/index.cjs +116 -1
  33. package/d1/index.cjs.map +1 -1
  34. package/d1/index.d.ts +15 -12
  35. package/d1/index.mjs +111 -1
  36. package/d1/index.mjs.map +1 -1
  37. package/d1/migrator.cjs +13 -1
  38. package/d1/migrator.cjs.map +1 -1
  39. package/d1/migrator.d.ts +5 -5
  40. package/d1/migrator.mjs +11 -1
  41. package/d1/migrator.mjs.map +1 -1
  42. package/{db.d-ae495c35.d.ts → db.d-a2311092.d.ts} +121 -44
  43. package/{db.d-66553b9e.d.ts → db.d-bc9a1d6c.d.ts} +193 -16
  44. package/driver.d-17ca4c15.d.ts +8 -0
  45. package/driver.d-300ddb0e.d.ts +64 -0
  46. package/driver.d-45e56643.d.ts +60 -0
  47. package/driver.d-64f2125c.d.ts +8 -0
  48. package/driver.d-7fde2e9d.d.ts +55 -0
  49. package/driver.d-9d703b84.d.ts +8 -0
  50. package/driver.d-b2b94bf9.d.ts +46 -0
  51. package/driver.d-b70ee7ee.d.ts +55 -0
  52. package/driver.d-dea23ee6.d.ts +8 -0
  53. package/driver.d-e54af17b.d.ts +52 -0
  54. package/driver.d-eb490c91.d.ts +9 -0
  55. package/driver.d-ef6fa2df.d.ts +14 -0
  56. package/errors-bb636d84.mjs +19 -0
  57. package/errors-bb636d84.mjs.map +1 -0
  58. package/errors-d0192d62.cjs +22 -0
  59. package/errors-d0192d62.cjs.map +1 -0
  60. package/index.cjs +105 -1
  61. package/index.cjs.map +1 -1
  62. package/index.d.ts +16 -432
  63. package/index.mjs +3 -1
  64. package/index.mjs.map +1 -1
  65. package/knex/index.cjs +2 -1
  66. package/knex/index.cjs.map +1 -1
  67. package/knex/index.d.ts +1 -1
  68. package/kysely/index.cjs +2 -1
  69. package/kysely/index.cjs.map +1 -1
  70. package/kysely/index.d.ts +1 -1
  71. package/libsql/index.cjs +155 -1
  72. package/libsql/index.cjs.map +1 -1
  73. package/libsql/index.d.ts +14 -12
  74. package/libsql/index.mjs +150 -1
  75. package/libsql/index.mjs.map +1 -1
  76. package/libsql/migrator.cjs +13 -1
  77. package/libsql/migrator.cjs.map +1 -1
  78. package/libsql/migrator.d.ts +5 -5
  79. package/libsql/migrator.mjs +11 -1
  80. package/libsql/migrator.mjs.map +1 -1
  81. package/logger-caa1ca6e.cjs +34 -0
  82. package/logger-caa1ca6e.cjs.map +1 -0
  83. package/logger-caf75bde.mjs +30 -0
  84. package/logger-caf75bde.mjs.map +1 -0
  85. package/migrator.cjs +48 -1
  86. package/migrator.cjs.map +1 -1
  87. package/migrator.mjs +46 -1
  88. package/migrator.mjs.map +1 -1
  89. package/mysql-core/index.cjs +1004 -1
  90. package/mysql-core/index.cjs.map +1 -1
  91. package/mysql-core/index.d.ts +347 -347
  92. package/mysql-core/index.mjs +869 -1
  93. package/mysql-core/index.mjs.map +1 -1
  94. package/mysql2/index.cjs +230 -1
  95. package/mysql2/index.cjs.map +1 -1
  96. package/mysql2/index.d.ts +5 -6
  97. package/mysql2/index.mjs +223 -1
  98. package/mysql2/index.mjs.map +1 -1
  99. package/mysql2/migrator.cjs +13 -1
  100. package/mysql2/migrator.cjs.map +1 -1
  101. package/mysql2/migrator.d.ts +5 -6
  102. package/mysql2/migrator.mjs +11 -1
  103. package/mysql2/migrator.mjs.map +1 -1
  104. package/neon-serverless/index.cjs +155 -1
  105. package/neon-serverless/index.cjs.map +1 -1
  106. package/neon-serverless/index.d.ts +5 -6
  107. package/neon-serverless/index.mjs +149 -1
  108. package/neon-serverless/index.mjs.map +1 -1
  109. package/neon-serverless/migrator.cjs +13 -1
  110. package/neon-serverless/migrator.cjs.map +1 -1
  111. package/neon-serverless/migrator.d.ts +5 -6
  112. package/neon-serverless/migrator.mjs +11 -1
  113. package/neon-serverless/migrator.mjs.map +1 -1
  114. package/node-postgres/index.cjs +157 -1
  115. package/node-postgres/index.cjs.map +1 -1
  116. package/node-postgres/index.d.ts +5 -6
  117. package/node-postgres/index.mjs +151 -1
  118. package/node-postgres/index.mjs.map +1 -1
  119. package/node-postgres/migrator.cjs +13 -1
  120. package/node-postgres/migrator.cjs.map +1 -1
  121. package/node-postgres/migrator.d.ts +5 -6
  122. package/node-postgres/migrator.mjs +11 -1
  123. package/node-postgres/migrator.mjs.map +1 -1
  124. package/package.json +97 -34
  125. package/pg-core/index.cjs +652 -1
  126. package/pg-core/index.cjs.map +1 -1
  127. package/pg-core/index.d.ts +13 -7
  128. package/pg-core/index.mjs +501 -1
  129. package/pg-core/index.mjs.map +1 -1
  130. package/planetscale-serverless/index.cjs +111 -1
  131. package/planetscale-serverless/index.cjs.map +1 -1
  132. package/planetscale-serverless/index.d.ts +5 -6
  133. package/planetscale-serverless/index.mjs +106 -1
  134. package/planetscale-serverless/index.mjs.map +1 -1
  135. package/planetscale-serverless/migrator.cjs +13 -1
  136. package/planetscale-serverless/migrator.cjs.map +1 -1
  137. package/planetscale-serverless/migrator.d.ts +5 -6
  138. package/planetscale-serverless/migrator.mjs +11 -1
  139. package/planetscale-serverless/migrator.mjs.map +1 -1
  140. package/postgres-js/index.cjs +113 -1
  141. package/postgres-js/index.cjs.map +1 -1
  142. package/postgres-js/index.d.ts +5 -6
  143. package/postgres-js/index.mjs +108 -1
  144. package/postgres-js/index.mjs.map +1 -1
  145. package/postgres-js/migrator.cjs +13 -1
  146. package/postgres-js/migrator.cjs.map +1 -1
  147. package/postgres-js/migrator.d.ts +5 -6
  148. package/postgres-js/migrator.mjs +11 -1
  149. package/postgres-js/migrator.mjs.map +1 -1
  150. package/query-promise.d-e370e0a9.d.ts +617 -0
  151. package/relations-47eb5c5f.mjs +2954 -0
  152. package/relations-47eb5c5f.mjs.map +1 -0
  153. package/relations-5e2d30dd.cjs +3117 -0
  154. package/relations-5e2d30dd.cjs.map +1 -0
  155. package/{select.types.d-c3e86d45.d.ts → select.types.d-34d7f74e.d.ts} +1 -1
  156. package/{select.types.d-adb82002.d.ts → select.types.d-ae2f8e44.d.ts} +58 -14
  157. package/session-483ed08d.mjs +1263 -0
  158. package/session-483ed08d.mjs.map +1 -0
  159. package/session-6bd76405.cjs +362 -0
  160. package/session-6bd76405.cjs.map +1 -0
  161. package/session-a90df8a2.cjs +1252 -0
  162. package/session-a90df8a2.cjs.map +1 -0
  163. package/session-b99382a2.mjs +1223 -0
  164. package/session-b99382a2.mjs.map +1 -0
  165. package/session-c62f6348.cjs +1298 -0
  166. package/session-c62f6348.cjs.map +1 -0
  167. package/session-e8745392.mjs +351 -0
  168. package/session-e8745392.mjs.map +1 -0
  169. package/sql-js/index.cjs +175 -1
  170. package/sql-js/index.cjs.map +1 -1
  171. package/sql-js/index.d.ts +14 -12
  172. package/sql-js/index.mjs +170 -1
  173. package/sql-js/index.mjs.map +1 -1
  174. package/sql-js/migrator.cjs +13 -1
  175. package/sql-js/migrator.cjs.map +1 -1
  176. package/sql-js/migrator.d.ts +5 -5
  177. package/sql-js/migrator.mjs +11 -1
  178. package/sql-js/migrator.mjs.map +1 -1
  179. package/sqlite-core/index.cjs +516 -1
  180. package/sqlite-core/index.cjs.map +1 -1
  181. package/sqlite-core/index.d.ts +6 -5
  182. package/sqlite-core/index.mjs +441 -1
  183. package/sqlite-core/index.mjs.map +1 -1
  184. package/sqlite-proxy/index.cjs +118 -1
  185. package/sqlite-proxy/index.cjs.map +1 -1
  186. package/sqlite-proxy/index.d.ts +12 -11
  187. package/sqlite-proxy/index.mjs +113 -1
  188. package/sqlite-proxy/index.mjs.map +1 -1
  189. package/sqlite-proxy/migrator.cjs +25 -2
  190. package/sqlite-proxy/migrator.cjs.map +1 -1
  191. package/sqlite-proxy/migrator.d.ts +5 -5
  192. package/sqlite-proxy/migrator.mjs +23 -2
  193. package/sqlite-proxy/migrator.mjs.map +1 -1
  194. package/version.cjs +9 -1
  195. package/version.cjs.map +1 -1
  196. package/version.d.ts +1 -1
  197. package/version.mjs +6 -1
  198. package/version.mjs.map +1 -1
  199. package/README.md +0 -150
  200. package/column-builder-592f0191.mjs +0 -2
  201. package/column-builder-592f0191.mjs.map +0 -1
  202. package/column-builder-b48639f3.cjs +0 -2
  203. package/column-builder-b48639f3.cjs.map +0 -1
  204. package/driver.d-0158cd93.d.ts +0 -11
  205. package/driver.d-1f73a4a9.d.ts +0 -70
  206. package/driver.d-2e907d12.d.ts +0 -17
  207. package/driver.d-3781598a.d.ts +0 -11
  208. package/driver.d-3a8adf2a.d.ts +0 -61
  209. package/driver.d-59580d08.d.ts +0 -11
  210. package/driver.d-5f3fc125.d.ts +0 -12
  211. package/driver.d-693f7f9f.d.ts +0 -56
  212. package/driver.d-6c43e393.d.ts +0 -60
  213. package/driver.d-b00fc6ec.d.ts +0 -57
  214. package/driver.d-e4bd120b.d.ts +0 -47
  215. package/driver.d-f4b5b390.d.ts +0 -11
  216. package/index-59b7992d.cjs +0 -2
  217. package/index-59b7992d.cjs.map +0 -1
  218. package/index-b71998f1.mjs +0 -2
  219. package/index-b71998f1.mjs.map +0 -1
  220. package/logger-04bad527.cjs +0 -2
  221. package/logger-04bad527.cjs.map +0 -1
  222. package/logger-2598bf05.mjs +0 -2
  223. package/logger-2598bf05.mjs.map +0 -1
  224. package/logger.d-37185354.d.ts +0 -21
  225. package/query-builder-2f2e8229.cjs +0 -2
  226. package/query-builder-2f2e8229.cjs.map +0 -1
  227. package/query-builder-2fcde2f0.mjs +0 -2
  228. package/query-builder-2fcde2f0.mjs.map +0 -1
  229. package/query-promise-2c5b43ab.cjs +0 -2
  230. package/query-promise-2c5b43ab.cjs.map +0 -1
  231. package/query-promise-a65edd44.mjs +0 -2
  232. package/query-promise-a65edd44.mjs.map +0 -1
  233. package/query-promise.d-a8af8583.d.ts +0 -9
  234. package/session-8a621f09.mjs +0 -8
  235. package/session-8a621f09.mjs.map +0 -1
  236. package/session-b6939bab.cjs +0 -14
  237. package/session-b6939bab.cjs.map +0 -1
  238. package/session-b977ce56.mjs +0 -14
  239. package/session-b977ce56.mjs.map +0 -1
  240. package/session-c891400d.mjs +0 -8
  241. package/session-c891400d.mjs.map +0 -1
  242. package/session-e6db6732.cjs +0 -8
  243. package/session-e6db6732.cjs.map +0 -1
  244. package/session-ef1ef979.cjs +0 -8
  245. package/session-ef1ef979.cjs.map +0 -1
  246. package/utils-9d882195.cjs +0 -2
  247. package/utils-9d882195.cjs.map +0 -1
  248. package/utils-e6870670.mjs +0 -2
  249. package/utils-e6870670.mjs.map +0 -1
@@ -0,0 +1,1252 @@
1
+ 'use strict';
2
+
3
+ var errors = require('./errors-d0192d62.cjs');
4
+ var relations = require('./relations-5e2d30dd.cjs');
5
+
6
+ var _a, _b;
7
+ /** @internal */
8
+ const InlineForeignKeys = Symbol('InlineForeignKeys');
9
+ class SQLiteTable extends relations.Table {
10
+ constructor() {
11
+ super(...arguments);
12
+ /** @internal */
13
+ this[_a] = [];
14
+ /** @internal */
15
+ this[_b] = undefined;
16
+ }
17
+ }
18
+ relations.Table.Symbol.Columns, _a = InlineForeignKeys, _b = relations.Table.Symbol.ExtraConfigBuilder;
19
+ /** @internal */
20
+ SQLiteTable.Symbol = Object.assign({}, relations.Table.Symbol, {
21
+ InlineForeignKeys: InlineForeignKeys,
22
+ });
23
+ function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
24
+ const rawTable = new SQLiteTable(name, schema, baseName);
25
+ const builtColumns = Object.fromEntries(Object.entries(columns).map(([name, colBuilder]) => {
26
+ const column = colBuilder.build(rawTable);
27
+ rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
28
+ return [name, column];
29
+ }));
30
+ const table = Object.assign(rawTable, builtColumns);
31
+ table[relations.Table.Symbol.Columns] = builtColumns;
32
+ if (extraConfig) {
33
+ table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
34
+ }
35
+ return table;
36
+ }
37
+ const sqliteTable = (name, columns, extraConfig) => {
38
+ return sqliteTableBase(name, columns, extraConfig);
39
+ };
40
+ function sqliteTableCreator(customizeTableName) {
41
+ return (name, columns, extraConfig) => {
42
+ return sqliteTableBase(customizeTableName(name), columns, extraConfig, undefined, name);
43
+ };
44
+ }
45
+
46
+ class SQLiteDelete {
47
+ constructor(table, session, dialect) {
48
+ this.table = table;
49
+ this.session = session;
50
+ this.dialect = dialect;
51
+ this.run = (placeholderValues) => {
52
+ return this.prepare(true).run(placeholderValues);
53
+ };
54
+ this.all = (placeholderValues) => {
55
+ return this.prepare(true).all(placeholderValues);
56
+ };
57
+ this.get = (placeholderValues) => {
58
+ return this.prepare(true).get(placeholderValues);
59
+ };
60
+ this.values = (placeholderValues) => {
61
+ return this.prepare(true).values(placeholderValues);
62
+ };
63
+ this.config = { table };
64
+ }
65
+ where(where) {
66
+ this.config.where = where;
67
+ return this;
68
+ }
69
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
70
+ this.config.returning = relations.orderSelectedFields(fields);
71
+ return this;
72
+ }
73
+ /** @internal */
74
+ getSQL() {
75
+ return this.dialect.buildDeleteQuery(this.config);
76
+ }
77
+ toSQL() {
78
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
79
+ return rest;
80
+ }
81
+ prepare(isOneTimeQuery) {
82
+ return this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](this.dialect.sqlToQuery(this.getSQL()), this.config.returning);
83
+ }
84
+ }
85
+
86
+ class SQLiteInsertBuilder {
87
+ constructor(table, session, dialect) {
88
+ this.table = table;
89
+ this.session = session;
90
+ this.dialect = dialect;
91
+ }
92
+ values(values) {
93
+ values = Array.isArray(values) ? values : [values];
94
+ if (values.length === 0) {
95
+ throw new Error('values() must be called with at least one value');
96
+ }
97
+ const mappedValues = values.map((entry) => {
98
+ const result = {};
99
+ const cols = this.table[relations.Table.Symbol.Columns];
100
+ for (const colKey of Object.keys(entry)) {
101
+ const colValue = entry[colKey];
102
+ result[colKey] = colValue instanceof relations.SQL ? colValue : new relations.Param(colValue, cols[colKey]);
103
+ }
104
+ return result;
105
+ });
106
+ return new SQLiteInsert(this.table, mappedValues, this.session, this.dialect);
107
+ }
108
+ }
109
+ class SQLiteInsert {
110
+ constructor(table, values, session, dialect) {
111
+ this.session = session;
112
+ this.dialect = dialect;
113
+ this.run = (placeholderValues) => {
114
+ return this.prepare(true).run(placeholderValues);
115
+ };
116
+ this.all = (placeholderValues) => {
117
+ return this.prepare(true).all(placeholderValues);
118
+ };
119
+ this.get = (placeholderValues) => {
120
+ return this.prepare(true).get(placeholderValues);
121
+ };
122
+ this.values = (placeholderValues) => {
123
+ return this.prepare(true).values(placeholderValues);
124
+ };
125
+ this.config = { table, values };
126
+ }
127
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
128
+ this.config.returning = relations.orderSelectedFields(fields);
129
+ return this;
130
+ }
131
+ onConflictDoNothing(config = {}) {
132
+ if (config.target === undefined) {
133
+ this.config.onConflict = relations.sql `do nothing`;
134
+ }
135
+ else {
136
+ const whereSql = config.where ? relations.sql ` where ${config.where}` : relations.sql ``;
137
+ this.config.onConflict = relations.sql `(${config.target})${whereSql} do nothing`;
138
+ }
139
+ return this;
140
+ }
141
+ onConflictDoUpdate(config) {
142
+ const whereSql = config.where ? relations.sql ` where ${config.where}` : relations.sql ``;
143
+ const setSql = this.dialect.buildUpdateSet(this.config.table, relations.mapUpdateSet(this.config.table, config.set));
144
+ this.config.onConflict = relations.sql `(${config.target})${whereSql} do update set ${setSql}`;
145
+ return this;
146
+ }
147
+ /** @internal */
148
+ getSQL() {
149
+ return this.dialect.buildInsertQuery(this.config);
150
+ }
151
+ toSQL() {
152
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
153
+ return rest;
154
+ }
155
+ prepare(isOneTimeQuery) {
156
+ return this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](this.dialect.sqlToQuery(this.getSQL()), this.config.returning);
157
+ }
158
+ }
159
+
160
+ class ViewBuilderCore {
161
+ constructor(name) {
162
+ this.name = name;
163
+ this.config = {};
164
+ }
165
+ }
166
+ class ViewBuilder extends ViewBuilderCore {
167
+ as(qb) {
168
+ if (typeof qb === 'function') {
169
+ qb = qb(new QueryBuilder());
170
+ }
171
+ const selectionProxy = new relations.SelectionProxyHandler({
172
+ alias: this.name,
173
+ sqlBehavior: 'error',
174
+ sqlAliasedBehavior: 'alias',
175
+ replaceOriginalName: true,
176
+ });
177
+ // const aliasedSelectedFields = new Proxy(qb.getSelectedFields(), selectionProxy);
178
+ const aliasedSelectedFields = qb.getSelectedFields();
179
+ return new Proxy(new SQLiteView({
180
+ sqliteConfig: this.config,
181
+ config: {
182
+ name: this.name,
183
+ schema: undefined,
184
+ selectedFields: aliasedSelectedFields,
185
+ query: qb.getSQL().inlineParams(),
186
+ },
187
+ }), selectionProxy);
188
+ }
189
+ }
190
+ class ManualViewBuilder extends ViewBuilderCore {
191
+ constructor(name, columns) {
192
+ super(name);
193
+ this.columns = relations.getTableColumns(sqliteTable(name, columns));
194
+ }
195
+ existing() {
196
+ return new Proxy(new SQLiteView({
197
+ sqliteConfig: undefined,
198
+ config: {
199
+ name: this.name,
200
+ schema: undefined,
201
+ selectedFields: this.columns,
202
+ query: undefined,
203
+ },
204
+ }), new relations.SelectionProxyHandler({
205
+ alias: this.name,
206
+ sqlBehavior: 'error',
207
+ sqlAliasedBehavior: 'alias',
208
+ replaceOriginalName: true,
209
+ }));
210
+ }
211
+ as(query) {
212
+ return new Proxy(new SQLiteView({
213
+ sqliteConfig: this.config,
214
+ config: {
215
+ name: this.name,
216
+ schema: undefined,
217
+ selectedFields: this.columns,
218
+ query: query.inlineParams(),
219
+ },
220
+ }), new relations.SelectionProxyHandler({
221
+ alias: this.name,
222
+ sqlBehavior: 'error',
223
+ sqlAliasedBehavior: 'alias',
224
+ replaceOriginalName: true,
225
+ }));
226
+ }
227
+ }
228
+ class SQLiteViewBase extends relations.View {
229
+ }
230
+ const SQLiteViewConfig = Symbol('SQLiteViewConfig');
231
+ class SQLiteView extends SQLiteViewBase {
232
+ constructor({ sqliteConfig, config }) {
233
+ super(config);
234
+ this[SQLiteViewConfig] = sqliteConfig;
235
+ }
236
+ }
237
+ function sqliteView(name, selection) {
238
+ if (selection) {
239
+ return new ManualViewBuilder(name, selection);
240
+ }
241
+ return new ViewBuilder(name);
242
+ }
243
+ const view = sqliteView;
244
+
245
+ class SQLiteDialect {
246
+ escapeName(name) {
247
+ return `"${name}"`;
248
+ }
249
+ escapeParam(_num) {
250
+ return '?';
251
+ }
252
+ escapeString(str) {
253
+ return `'${str.replace(/'/g, "''")}'`;
254
+ }
255
+ buildDeleteQuery({ table, where, returning }) {
256
+ const returningSql = returning
257
+ ? relations.sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
258
+ : undefined;
259
+ const whereSql = where ? relations.sql ` where ${where}` : undefined;
260
+ return relations.sql `delete from ${table}${whereSql}${returningSql}`;
261
+ }
262
+ buildUpdateSet(table, set) {
263
+ const setEntries = Object.entries(set);
264
+ const setSize = setEntries.length;
265
+ return relations.sql.fromList(setEntries
266
+ .flatMap(([colName, value], i) => {
267
+ const col = table[relations.Table.Symbol.Columns][colName];
268
+ const res = relations.sql `${relations.name(col.name)} = ${value}`;
269
+ if (i < setSize - 1) {
270
+ return [res, relations.sql.raw(', ')];
271
+ }
272
+ return [res];
273
+ }));
274
+ }
275
+ buildUpdateQuery({ table, set, where, returning }) {
276
+ const setSql = this.buildUpdateSet(table, set);
277
+ const returningSql = returning
278
+ ? relations.sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
279
+ : undefined;
280
+ const whereSql = where ? relations.sql ` where ${where}` : undefined;
281
+ return relations.sql `update ${table} set ${setSql}${whereSql}${returningSql}`;
282
+ }
283
+ /**
284
+ * Builds selection SQL with provided fields/expressions
285
+ *
286
+ * Examples:
287
+ *
288
+ * `select <selection> from`
289
+ *
290
+ * `insert ... returning <selection>`
291
+ *
292
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
293
+ */
294
+ buildSelection(fields, { isSingleTable = false } = {}) {
295
+ const columnsLen = fields.length;
296
+ const chunks = fields
297
+ .flatMap(({ field }, i) => {
298
+ const chunk = [];
299
+ if (field instanceof relations.SQL.Aliased && field.isSelectionField) {
300
+ chunk.push(relations.name(field.fieldAlias));
301
+ }
302
+ else if (field instanceof relations.SQL.Aliased || field instanceof relations.SQL) {
303
+ const query = field instanceof relations.SQL.Aliased ? field.sql : field;
304
+ if (isSingleTable) {
305
+ chunk.push(new relations.SQL(query.queryChunks.map((c) => {
306
+ if (c instanceof relations.Column) {
307
+ return relations.name(c.name);
308
+ }
309
+ return c;
310
+ })));
311
+ }
312
+ else {
313
+ chunk.push(query);
314
+ }
315
+ if (field instanceof relations.SQL.Aliased) {
316
+ chunk.push(relations.sql ` as ${relations.name(field.fieldAlias)}`);
317
+ }
318
+ }
319
+ else if (field instanceof relations.Column) {
320
+ const tableName = field.table[relations.Table.Symbol.Name];
321
+ const columnName = field.name;
322
+ if (isSingleTable) {
323
+ chunk.push(relations.name(columnName));
324
+ }
325
+ else {
326
+ chunk.push(relations.sql `${relations.name(tableName)}.${relations.name(columnName)}`);
327
+ }
328
+ }
329
+ if (i < columnsLen - 1) {
330
+ chunk.push(relations.sql `, `);
331
+ }
332
+ return chunk;
333
+ });
334
+ return relations.sql.fromList(chunks);
335
+ }
336
+ buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset }) {
337
+ const fieldsList = fieldsFlat ?? relations.orderSelectedFields(fields);
338
+ for (const f of fieldsList) {
339
+ if (f.field instanceof relations.Column
340
+ && relations.getTableName(f.field.table)
341
+ !== (table instanceof relations.Subquery
342
+ ? table[relations.SubqueryConfig].alias
343
+ : table instanceof SQLiteViewBase
344
+ ? table[relations.ViewBaseConfig].name
345
+ : table instanceof relations.SQL
346
+ ? undefined
347
+ : relations.getTableName(table))
348
+ && !((table) => joins.some(({ alias }) => alias === relations.getTableName(table)))(f.field.table)) {
349
+ const tableName = relations.getTableName(f.field.table);
350
+ throw new Error(`Your "${f.path.join('->')}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
351
+ }
352
+ }
353
+ const isSingleTable = joins.length === 0;
354
+ let withSql;
355
+ if (withList.length) {
356
+ const withSqlChunks = [relations.sql `with `];
357
+ for (const [i, w] of withList.entries()) {
358
+ withSqlChunks.push(relations.sql `${relations.name(w[relations.SubqueryConfig].alias)} as (${w[relations.SubqueryConfig].sql})`);
359
+ if (i < withList.length - 1) {
360
+ withSqlChunks.push(relations.sql `, `);
361
+ }
362
+ }
363
+ withSqlChunks.push(relations.sql ` `);
364
+ withSql = relations.sql.fromList(withSqlChunks);
365
+ }
366
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
367
+ const tableSql = (() => {
368
+ if (table instanceof relations.Table && table[relations.Table.Symbol.OriginalName] !== table[relations.Table.Symbol.Name]) {
369
+ return relations.sql `${relations.name(table[relations.Table.Symbol.OriginalName])} ${relations.name(table[relations.Table.Symbol.Name])}`;
370
+ }
371
+ return table;
372
+ })();
373
+ const joinsArray = [];
374
+ for (const [index, joinMeta] of joins.entries()) {
375
+ if (index === 0) {
376
+ joinsArray.push(relations.sql ` `);
377
+ }
378
+ const table = joinMeta.table;
379
+ if (table instanceof SQLiteTable) {
380
+ const tableName = table[SQLiteTable.Symbol.Name];
381
+ const tableSchema = table[SQLiteTable.Symbol.Schema];
382
+ const origTableName = table[SQLiteTable.Symbol.OriginalName];
383
+ const alias = tableName === origTableName ? undefined : joinMeta.alias;
384
+ joinsArray.push(relations.sql `${relations.sql.raw(joinMeta.joinType)} join ${tableSchema ? relations.sql `${relations.sql.identifier(tableSchema)}.` : undefined}${relations.name(origTableName)}${alias && relations.sql ` ${relations.name(alias)}`} on ${joinMeta.on}`);
385
+ }
386
+ else {
387
+ joinsArray.push(relations.sql `${relations.sql.raw(joinMeta.joinType)} join ${table} on ${joinMeta.on}`);
388
+ }
389
+ if (index < joins.length - 1) {
390
+ joinsArray.push(relations.sql ` `);
391
+ }
392
+ }
393
+ const joinsSql = relations.sql.fromList(joinsArray);
394
+ const whereSql = where ? relations.sql ` where ${where}` : undefined;
395
+ const havingSql = having ? relations.sql ` having ${having}` : undefined;
396
+ const orderByList = [];
397
+ for (const [index, orderByValue] of orderBy.entries()) {
398
+ orderByList.push(orderByValue);
399
+ if (index < orderBy.length - 1) {
400
+ orderByList.push(relations.sql `, `);
401
+ }
402
+ }
403
+ const groupByList = [];
404
+ for (const [index, groupByValue] of groupBy.entries()) {
405
+ groupByList.push(groupByValue);
406
+ if (index < groupBy.length - 1) {
407
+ groupByList.push(relations.sql `, `);
408
+ }
409
+ }
410
+ const groupBySql = groupByList.length > 0 ? relations.sql ` group by ${relations.sql.fromList(groupByList)}` : undefined;
411
+ const orderBySql = orderByList.length > 0 ? relations.sql ` order by ${relations.sql.fromList(orderByList)}` : undefined;
412
+ const limitSql = limit ? relations.sql ` limit ${limit}` : undefined;
413
+ const offsetSql = offset ? relations.sql ` offset ${offset}` : undefined;
414
+ return relations.sql `${withSql}select ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
415
+ }
416
+ buildInsertQuery({ table, values, onConflict, returning }) {
417
+ const isSingleValue = values.length === 1;
418
+ const valuesSqlList = [];
419
+ const columns = table[relations.Table.Symbol.Columns];
420
+ const colEntries = isSingleValue
421
+ ? Object.keys(values[0]).map((fieldName) => [fieldName, columns[fieldName]])
422
+ : Object.entries(columns);
423
+ const insertOrder = colEntries.map(([, column]) => relations.name(column.name));
424
+ for (const [valueIndex, value] of values.entries()) {
425
+ const valueList = [];
426
+ for (const [fieldName, col] of colEntries) {
427
+ const colValue = value[fieldName];
428
+ if (colValue === undefined || (colValue instanceof relations.Param && colValue.value === undefined)) {
429
+ let defaultValue;
430
+ if (col.default !== null && col.default !== undefined) {
431
+ defaultValue = col.default instanceof relations.SQL ? col.default : relations.param(col.default, col);
432
+ }
433
+ else {
434
+ defaultValue = relations.sql `null`;
435
+ }
436
+ valueList.push(defaultValue);
437
+ }
438
+ else {
439
+ valueList.push(colValue);
440
+ }
441
+ }
442
+ valuesSqlList.push(valueList);
443
+ if (valueIndex < values.length - 1) {
444
+ valuesSqlList.push(relations.sql `, `);
445
+ }
446
+ }
447
+ const valuesSql = relations.sql.fromList(valuesSqlList);
448
+ const returningSql = returning
449
+ ? relations.sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
450
+ : undefined;
451
+ const onConflictSql = onConflict ? relations.sql ` on conflict ${onConflict}` : undefined;
452
+ return relations.sql `insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
453
+ }
454
+ sqlToQuery(sql) {
455
+ return sql.toQuery({
456
+ escapeName: this.escapeName,
457
+ escapeParam: this.escapeParam,
458
+ escapeString: this.escapeString,
459
+ });
460
+ }
461
+ buildRelationalQuery(fullSchema, schema, tableNamesMap, table, tableConfig, config, tableAlias, relationColumns, isRoot = false) {
462
+ if (config === true) {
463
+ const selectionEntries = Object.entries(tableConfig.columns);
464
+ const selection = selectionEntries.map(([key, value]) => ({
465
+ dbKey: value.name,
466
+ tsKey: key,
467
+ field: value,
468
+ tableTsKey: undefined,
469
+ isJson: false,
470
+ selection: [],
471
+ }));
472
+ return {
473
+ tableTsKey: tableConfig.tsName,
474
+ sql: this.buildSelectQuery({
475
+ table,
476
+ fields: {},
477
+ fieldsFlat: selectionEntries.map(([, c]) => ({
478
+ path: [c.name],
479
+ field: c,
480
+ })),
481
+ groupBy: [],
482
+ orderBy: [],
483
+ joins: [],
484
+ withList: [],
485
+ }),
486
+ selection,
487
+ };
488
+ }
489
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, relations.aliasedTableColumn(value, tableAlias)]));
490
+ const aliasedRelations = Object.fromEntries(Object.entries(tableConfig.relations).map(([key, value]) => [key, relations.aliasedRelation(value, tableAlias)]));
491
+ const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
492
+ const fieldsSelection = {};
493
+ let selectedColumns = [];
494
+ let selectedExtras = [];
495
+ let selectedRelations = [];
496
+ if (config.columns) {
497
+ let isIncludeMode = false;
498
+ for (const [field, value] of Object.entries(config.columns)) {
499
+ if (value === undefined) {
500
+ continue;
501
+ }
502
+ if (field in tableConfig.columns) {
503
+ if (!isIncludeMode && value === true) {
504
+ isIncludeMode = true;
505
+ }
506
+ selectedColumns.push(field);
507
+ }
508
+ }
509
+ if (selectedColumns.length > 0) {
510
+ selectedColumns = isIncludeMode
511
+ ? selectedColumns.filter((c) => config.columns?.[c] === true)
512
+ : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
513
+ }
514
+ }
515
+ if (config.with) {
516
+ selectedRelations = Object.entries(config.with)
517
+ .filter((entry) => !!entry[1])
518
+ .map(([key, value]) => ({ key, value }));
519
+ }
520
+ if (!config.columns) {
521
+ selectedColumns = Object.keys(tableConfig.columns);
522
+ }
523
+ if (config.extras) {
524
+ const extrasOrig = typeof config.extras === 'function'
525
+ ? config.extras(aliasedFields, { sql: relations.sql })
526
+ : config.extras;
527
+ selectedExtras = Object.entries(extrasOrig).map(([key, value]) => ({
528
+ key,
529
+ value: relations.mapColumnsInAliasedSQLToAlias(value, tableAlias),
530
+ }));
531
+ }
532
+ for (const field of selectedColumns) {
533
+ const column = tableConfig.columns[field];
534
+ fieldsSelection[field] = column;
535
+ }
536
+ for (const { key, value } of selectedExtras) {
537
+ fieldsSelection[key] = value;
538
+ }
539
+ const builtRelations = [];
540
+ const joins = [];
541
+ const builtRelationFields = [];
542
+ for (const { key: selectedRelationKey, value: selectedRelationValue } of selectedRelations) {
543
+ let relation;
544
+ for (const [relationKey, relationValue] of Object.entries(tableConfig.relations)) {
545
+ if (relationValue instanceof relations.Relation && relationKey === selectedRelationKey) {
546
+ relation = relationValue;
547
+ break;
548
+ }
549
+ }
550
+ if (!relation) {
551
+ throw new Error(`Relation ${selectedRelationKey} not found`);
552
+ }
553
+ const normalizedRelation = relations.normalizeRelation(schema, tableNamesMap, relation);
554
+ const relationAlias = `${tableAlias}_${selectedRelationKey}`;
555
+ const builtRelation = this.buildRelationalQuery(fullSchema, schema, tableNamesMap, fullSchema[tableNamesMap[relation.referencedTable[relations.Table.Symbol.Name]]], schema[tableNamesMap[relation.referencedTable[relations.Table.Symbol.Name]]], selectedRelationValue, relationAlias, normalizedRelation.references);
556
+ builtRelations.push({ key: selectedRelationKey, value: builtRelation });
557
+ joins.push({
558
+ table: new relations.Subquery(builtRelation.sql, {}, relationAlias),
559
+ alias: selectedRelationKey,
560
+ on: relations.and(...normalizedRelation.fields.map((field, i) => relations.eq(relations.aliasedTableColumn(field, tableAlias), relations.aliasedTableColumn(normalizedRelation.references[i], relationAlias)))),
561
+ joinType: 'left',
562
+ });
563
+ const elseField = relations.sql `json_group_array(json_array(${relations.sql.join(builtRelation.selection.map(({ dbKey: key, isJson }) => {
564
+ const field = relations.sql `${relations.sql.identifier(relationAlias)}.${relations.sql.identifier(key)}`;
565
+ return isJson ? relations.sql `json(${field})` : field;
566
+ }), relations.sql `, `)}))`;
567
+ const field = relations.sql `case when count(${relations.sql.join(normalizedRelation.references.map((c) => relations.aliasedTableColumn(c, relationAlias)), relations.sql.raw(' or '))}) = 0 then '[]' else ${elseField} end`.as(selectedRelationKey);
568
+ builtRelationFields.push({
569
+ path: [selectedRelationKey],
570
+ field,
571
+ });
572
+ }
573
+ const finalFieldsSelection = Object.entries(fieldsSelection).map(([key, value]) => {
574
+ return {
575
+ path: [key],
576
+ field: value instanceof relations.Column ? relations.aliasedTableColumn(value, tableAlias) : value,
577
+ };
578
+ });
579
+ const initialWhere = relations.and(...selectedRelations.filter(({ key }) => {
580
+ const relation = config.with?.[key];
581
+ return typeof relation === 'object' && relation.limit !== undefined;
582
+ }).map(({ key }) => {
583
+ const field = relations.sql `${relations.sql.identifier(`${tableAlias}_${key}`)}.${relations.sql.identifier('__drizzle_row_number')}`;
584
+ const value = config.with[key];
585
+ const cond = relations.or(relations.and(relations.sql `${field} <= ${value.limit}`), relations.sql `(${field} is null)`);
586
+ return cond;
587
+ }));
588
+ const groupBy = (builtRelationFields.length
589
+ ? (tableConfig.primaryKey.length ? tableConfig.primaryKey : Object.values(tableConfig.columns)).map((c) => relations.aliasedTableColumn(c, tableAlias))
590
+ : []);
591
+ const finalFieldsFlat = isRoot
592
+ ? [
593
+ ...finalFieldsSelection.map(({ path, field }) => ({
594
+ path,
595
+ field: field instanceof relations.SQL.Aliased ? relations.sql `${relations.sql.identifier(field.fieldAlias)}` : field,
596
+ })),
597
+ ...builtRelationFields.map(({ path, field }) => ({
598
+ path,
599
+ field: relations.sql `json(${relations.sql.identifier(field.fieldAlias)})`,
600
+ })),
601
+ ]
602
+ : [
603
+ ...Object.entries(tableConfig.columns).map(([tsKey, column]) => ({
604
+ path: [tsKey],
605
+ field: relations.aliasedTableColumn(column, tableAlias),
606
+ })),
607
+ ...selectedExtras.map(({ key, value }) => ({
608
+ path: [key],
609
+ field: value,
610
+ })),
611
+ ...builtRelationFields.map(({ path, field }) => ({
612
+ path,
613
+ field: relations.sql `${relations.sql.identifier(tableAlias)}.${relations.sql.identifier(field.fieldAlias)}`,
614
+ })),
615
+ ];
616
+ if (finalFieldsFlat.length === 0) {
617
+ finalFieldsFlat.push({
618
+ path: [],
619
+ field: relations.sql.raw('1'),
620
+ });
621
+ }
622
+ const initialFieldsFlat = [
623
+ {
624
+ path: [],
625
+ field: relations.sql `${relations.sql.identifier(tableAlias)}.*`,
626
+ },
627
+ ...selectedExtras.map(({ key, value }) => ({
628
+ path: [key],
629
+ field: value,
630
+ })),
631
+ ...builtRelationFields,
632
+ ];
633
+ let orderByOrig = typeof config.orderBy === 'function'
634
+ ? config.orderBy(aliasedFields, relations.orderByOperators)
635
+ : config.orderBy ?? [];
636
+ if (!Array.isArray(orderByOrig)) {
637
+ orderByOrig = [orderByOrig];
638
+ }
639
+ const orderBy = orderByOrig.map((orderByValue) => {
640
+ if (orderByValue instanceof relations.Column) {
641
+ return relations.aliasedTableColumn(orderByValue, tableAlias);
642
+ }
643
+ return relations.mapColumnsInSQLToAlias(orderByValue, tableAlias);
644
+ });
645
+ if (!isRoot && !config.limit && orderBy.length > 0) {
646
+ finalFieldsFlat.push({
647
+ path: ['__drizzle_row_number'],
648
+ field: relations.sql `row_number() over(order by ${relations.sql.join(orderBy, relations.sql `, `)})`,
649
+ });
650
+ }
651
+ let limit, offset;
652
+ if (config.limit !== undefined || config.offset !== undefined) {
653
+ if (isRoot) {
654
+ limit = config.limit;
655
+ offset = config.offset;
656
+ }
657
+ else {
658
+ finalFieldsFlat.push({
659
+ path: ['__drizzle_row_number'],
660
+ field: relations.sql `row_number() over(partition by ${relationColumns.map((c) => relations.aliasedTableColumn(c, tableAlias))}${(orderBy.length > 0 && !isRoot) ? relations.sql ` order by ${relations.sql.join(orderBy, relations.sql `, `)}` : undefined})`
661
+ .as('__drizzle_row_number'),
662
+ });
663
+ }
664
+ }
665
+ let result = this.buildSelectQuery({
666
+ table: relations.aliasedTable(table, tableAlias),
667
+ fields: {},
668
+ fieldsFlat: initialFieldsFlat,
669
+ where: initialWhere,
670
+ groupBy,
671
+ orderBy: [],
672
+ joins,
673
+ withList: [],
674
+ });
675
+ let where;
676
+ if (config.where) {
677
+ const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, relations.operators) : config.where;
678
+ where = whereSql && relations.mapColumnsInSQLToAlias(whereSql, tableAlias);
679
+ }
680
+ result = this.buildSelectQuery({
681
+ table: new relations.Subquery(result, {}, tableAlias),
682
+ fields: {},
683
+ fieldsFlat: finalFieldsFlat,
684
+ where,
685
+ groupBy: [],
686
+ orderBy: isRoot ? orderBy : [],
687
+ joins: [],
688
+ withList: [],
689
+ limit,
690
+ offset: offset,
691
+ });
692
+ return {
693
+ tableTsKey: tableConfig.tsName,
694
+ sql: result,
695
+ selection: [
696
+ ...finalFieldsSelection.map(({ path, field }) => ({
697
+ dbKey: field instanceof relations.SQL.Aliased ? field.fieldAlias : tableConfig.columns[path[0]].name,
698
+ tsKey: path[0],
699
+ field,
700
+ tableTsKey: undefined,
701
+ isJson: false,
702
+ selection: [],
703
+ })),
704
+ ...builtRelations.map(({ key, value }) => ({
705
+ dbKey: key,
706
+ tsKey: key,
707
+ field: undefined,
708
+ tableTsKey: value.tableTsKey,
709
+ isJson: true,
710
+ selection: value.selection,
711
+ })),
712
+ ],
713
+ };
714
+ }
715
+ }
716
+ class SQLiteSyncDialect extends SQLiteDialect {
717
+ migrate(migrations, session) {
718
+ const migrationTableCreate = relations.sql `
719
+ CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
720
+ id SERIAL PRIMARY KEY,
721
+ hash text NOT NULL,
722
+ created_at numeric
723
+ )
724
+ `;
725
+ session.run(migrationTableCreate);
726
+ const dbMigrations = session.values(relations.sql `SELECT id, hash, created_at FROM "__drizzle_migrations" ORDER BY created_at DESC LIMIT 1`);
727
+ const lastDbMigration = dbMigrations[0] ?? undefined;
728
+ session.run(relations.sql `BEGIN`);
729
+ try {
730
+ for (const migration of migrations) {
731
+ if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
732
+ for (const stmt of migration.sql) {
733
+ session.run(relations.sql.raw(stmt));
734
+ }
735
+ session.run(relations.sql `INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
736
+ }
737
+ }
738
+ session.run(relations.sql `COMMIT`);
739
+ }
740
+ catch (e) {
741
+ session.run(relations.sql `ROLLBACK`);
742
+ throw e;
743
+ }
744
+ }
745
+ }
746
+ class SQLiteAsyncDialect extends SQLiteDialect {
747
+ async migrate(migrations, session) {
748
+ const migrationTableCreate = relations.sql `
749
+ CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
750
+ id SERIAL PRIMARY KEY,
751
+ hash text NOT NULL,
752
+ created_at numeric
753
+ )
754
+ `;
755
+ await session.run(migrationTableCreate);
756
+ const dbMigrations = await session.values(relations.sql `SELECT id, hash, created_at FROM "__drizzle_migrations" ORDER BY created_at DESC LIMIT 1`);
757
+ const lastDbMigration = dbMigrations[0] ?? undefined;
758
+ await session.transaction(async (tx) => {
759
+ for (const migration of migrations) {
760
+ if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
761
+ for (const stmt of migration.sql) {
762
+ await tx.run(relations.sql.raw(stmt));
763
+ }
764
+ await tx.run(relations.sql `INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
765
+ }
766
+ }
767
+ });
768
+ }
769
+ }
770
+
771
+ class SQLiteSelectBuilder {
772
+ constructor(fields, session, dialect, withList = []) {
773
+ this.fields = fields;
774
+ this.session = session;
775
+ this.dialect = dialect;
776
+ this.withList = withList;
777
+ }
778
+ from(source) {
779
+ const isPartialSelect = !!this.fields;
780
+ let fields;
781
+ if (this.fields) {
782
+ fields = this.fields;
783
+ }
784
+ else if (source instanceof relations.Subquery) {
785
+ // This is required to use the proxy handler to get the correct field values from the subquery
786
+ fields = Object.fromEntries(Object.keys(source[relations.SubqueryConfig].selection).map((key) => [key, source[key]]));
787
+ }
788
+ else if (source instanceof SQLiteViewBase) {
789
+ fields = source[relations.ViewBaseConfig].selectedFields;
790
+ }
791
+ else if (source instanceof relations.SQL) {
792
+ fields = {};
793
+ }
794
+ else {
795
+ fields = relations.getTableColumns(source);
796
+ }
797
+ return new SQLiteSelect(source, fields, isPartialSelect, this.session, this.dialect, this.withList);
798
+ }
799
+ }
800
+ class SQLiteSelectQueryBuilder extends relations.TypedQueryBuilder {
801
+ constructor(table, fields, isPartialSelect, session, dialect, withList) {
802
+ super();
803
+ this.isPartialSelect = isPartialSelect;
804
+ this.session = session;
805
+ this.dialect = dialect;
806
+ this.leftJoin = this.createJoin('left');
807
+ this.rightJoin = this.createJoin('right');
808
+ this.innerJoin = this.createJoin('inner');
809
+ this.fullJoin = this.createJoin('full');
810
+ this.config = {
811
+ withList,
812
+ table,
813
+ fields: { ...fields },
814
+ joins: [],
815
+ orderBy: [],
816
+ groupBy: [],
817
+ };
818
+ this._ = {
819
+ selectedFields: fields,
820
+ };
821
+ this.tableName = relations.getTableLikeName(table);
822
+ this.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};
823
+ }
824
+ createJoin(joinType) {
825
+ return (table, on) => {
826
+ const baseTableName = this.tableName;
827
+ const tableName = relations.getTableLikeName(table);
828
+ if (typeof tableName === 'string' && this.config.joins.some((join) => join.alias === tableName)) {
829
+ throw new Error(`Alias "${tableName}" is already used in this query`);
830
+ }
831
+ if (!this.isPartialSelect) {
832
+ // If this is the first join and this is not a partial select and we're not selecting from raw SQL, "move" the fields from the main table to the nested object
833
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {
834
+ this.config.fields = {
835
+ [baseTableName]: this.config.fields,
836
+ };
837
+ }
838
+ if (typeof tableName === 'string' && !(table instanceof relations.SQL)) {
839
+ const selection = table instanceof relations.Subquery
840
+ ? table[relations.SubqueryConfig].selection
841
+ : table instanceof relations.View
842
+ ? table[relations.ViewBaseConfig].selectedFields
843
+ : table[relations.Table.Symbol.Columns];
844
+ this.config.fields[tableName] = selection;
845
+ }
846
+ }
847
+ if (typeof on === 'function') {
848
+ on = on(new Proxy(this.config.fields, new relations.SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
849
+ }
850
+ this.config.joins.push({ on, table, joinType, alias: tableName });
851
+ if (typeof tableName === 'string') {
852
+ switch (joinType) {
853
+ case 'left': {
854
+ this.joinsNotNullableMap[tableName] = false;
855
+ break;
856
+ }
857
+ case 'right': {
858
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
859
+ this.joinsNotNullableMap[tableName] = true;
860
+ break;
861
+ }
862
+ case 'inner': {
863
+ this.joinsNotNullableMap[tableName] = true;
864
+ break;
865
+ }
866
+ case 'full': {
867
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
868
+ this.joinsNotNullableMap[tableName] = false;
869
+ break;
870
+ }
871
+ }
872
+ }
873
+ return this;
874
+ };
875
+ }
876
+ where(where) {
877
+ if (typeof where === 'function') {
878
+ where = where(new Proxy(this.config.fields, new relations.SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
879
+ }
880
+ this.config.where = where;
881
+ return this;
882
+ }
883
+ having(having) {
884
+ if (typeof having === 'function') {
885
+ having = having(new Proxy(this.config.fields, new relations.SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
886
+ }
887
+ this.config.having = having;
888
+ return this;
889
+ }
890
+ groupBy(...columns) {
891
+ if (typeof columns[0] === 'function') {
892
+ const groupBy = columns[0](new Proxy(this.config.fields, new relations.SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
893
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
894
+ }
895
+ else {
896
+ this.config.groupBy = columns;
897
+ }
898
+ return this;
899
+ }
900
+ orderBy(...columns) {
901
+ if (typeof columns[0] === 'function') {
902
+ const orderBy = columns[0](new Proxy(this.config.fields, new relations.SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
903
+ this.config.orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
904
+ }
905
+ else {
906
+ this.config.orderBy = columns;
907
+ }
908
+ return this;
909
+ }
910
+ limit(limit) {
911
+ this.config.limit = limit;
912
+ return this;
913
+ }
914
+ offset(offset) {
915
+ this.config.offset = offset;
916
+ return this;
917
+ }
918
+ /** @internal */
919
+ getSQL() {
920
+ return this.dialect.buildSelectQuery(this.config);
921
+ }
922
+ toSQL() {
923
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
924
+ return rest;
925
+ }
926
+ as(alias) {
927
+ return new Proxy(new relations.Subquery(this.getSQL(), this.config.fields, alias), new relations.SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
928
+ }
929
+ getSelectedFields() {
930
+ return new Proxy(this.config.fields, new relations.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
931
+ }
932
+ }
933
+ class SQLiteSelect extends SQLiteSelectQueryBuilder {
934
+ constructor() {
935
+ super(...arguments);
936
+ this.run = (placeholderValues) => {
937
+ return this.prepare(true).run(placeholderValues);
938
+ };
939
+ this.all = (placeholderValues) => {
940
+ return this.prepare(true).all(placeholderValues);
941
+ };
942
+ this.get = (placeholderValues) => {
943
+ return this.prepare(true).get(placeholderValues);
944
+ };
945
+ this.values = (placeholderValues) => {
946
+ return this.prepare(true).values(placeholderValues);
947
+ };
948
+ }
949
+ prepare(isOneTimeQuery) {
950
+ if (!this.session) {
951
+ throw new Error('Cannot execute a query on a query builder. Please use a database instance instead.');
952
+ }
953
+ const fieldsList = relations.orderSelectedFields(this.config.fields);
954
+ const query = this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](this.dialect.sqlToQuery(this.getSQL()), fieldsList);
955
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
956
+ return query;
957
+ }
958
+ }
959
+
960
+ class QueryBuilder {
961
+ $with(alias) {
962
+ const queryBuilder = this;
963
+ return {
964
+ as(qb) {
965
+ if (typeof qb === 'function') {
966
+ qb = qb(queryBuilder);
967
+ }
968
+ return new Proxy(new relations.WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new relations.SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
969
+ },
970
+ };
971
+ }
972
+ with(...queries) {
973
+ const self = this;
974
+ function select(fields) {
975
+ return new SQLiteSelectBuilder(fields ?? undefined, undefined, self.getDialect(), queries);
976
+ }
977
+ return { select };
978
+ }
979
+ select(fields) {
980
+ return new SQLiteSelectBuilder(fields ?? undefined, undefined, this.getDialect());
981
+ }
982
+ // Lazy load dialect to avoid circular dependency
983
+ getDialect() {
984
+ if (!this.dialect) {
985
+ this.dialect = new SQLiteSyncDialect();
986
+ }
987
+ return this.dialect;
988
+ }
989
+ }
990
+
991
+ class SQLiteUpdateBuilder {
992
+ constructor(table, session, dialect) {
993
+ this.table = table;
994
+ this.session = session;
995
+ this.dialect = dialect;
996
+ }
997
+ set(values) {
998
+ return new SQLiteUpdate(this.table, relations.mapUpdateSet(this.table, values), this.session, this.dialect);
999
+ }
1000
+ }
1001
+ class SQLiteUpdate {
1002
+ constructor(table, set, session, dialect) {
1003
+ this.session = session;
1004
+ this.dialect = dialect;
1005
+ this.run = (placeholderValues) => {
1006
+ return this.prepare(true).run(placeholderValues);
1007
+ };
1008
+ this.all = (placeholderValues) => {
1009
+ return this.prepare(true).all(placeholderValues);
1010
+ };
1011
+ this.get = (placeholderValues) => {
1012
+ return this.prepare(true).get(placeholderValues);
1013
+ };
1014
+ this.values = (placeholderValues) => {
1015
+ return this.prepare(true).values(placeholderValues);
1016
+ };
1017
+ this.config = { set, table };
1018
+ }
1019
+ where(where) {
1020
+ this.config.where = where;
1021
+ return this;
1022
+ }
1023
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
1024
+ this.config.returning = relations.orderSelectedFields(fields);
1025
+ return this;
1026
+ }
1027
+ /** @internal */
1028
+ getSQL() {
1029
+ return this.dialect.buildUpdateQuery(this.config);
1030
+ }
1031
+ toSQL() {
1032
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1033
+ return rest;
1034
+ }
1035
+ prepare(isOneTimeQuery) {
1036
+ return this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](this.dialect.sqlToQuery(this.getSQL()), this.config.returning);
1037
+ }
1038
+ }
1039
+
1040
+ class AsyncRelationalQueryBuilder {
1041
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
1042
+ this.fullSchema = fullSchema;
1043
+ this.schema = schema;
1044
+ this.tableNamesMap = tableNamesMap;
1045
+ this.table = table;
1046
+ this.tableConfig = tableConfig;
1047
+ this.dialect = dialect;
1048
+ this.session = session;
1049
+ }
1050
+ findMany(config) {
1051
+ return new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : true, 'many');
1052
+ }
1053
+ findFirst(config) {
1054
+ return new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, 'first');
1055
+ }
1056
+ }
1057
+ class SyncRelationalQueryBuilder {
1058
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
1059
+ this.fullSchema = fullSchema;
1060
+ this.schema = schema;
1061
+ this.tableNamesMap = tableNamesMap;
1062
+ this.table = table;
1063
+ this.tableConfig = tableConfig;
1064
+ this.dialect = dialect;
1065
+ this.session = session;
1066
+ }
1067
+ prepareFindMany(config) {
1068
+ const query = new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : true, 'many').prepare();
1069
+ return {
1070
+ execute: query.all.bind(query),
1071
+ };
1072
+ }
1073
+ findMany(config) {
1074
+ return this.prepareFindMany(config).execute();
1075
+ }
1076
+ prepareFindFirst(config) {
1077
+ const query = new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : true, 'first').prepare();
1078
+ return {
1079
+ execute: query.get.bind(query),
1080
+ };
1081
+ }
1082
+ findFirst(config) {
1083
+ return this.prepareFindFirst(config).execute();
1084
+ }
1085
+ }
1086
+ class SQLiteRelationalQuery {
1087
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
1088
+ this.fullSchema = fullSchema;
1089
+ this.schema = schema;
1090
+ this.tableNamesMap = tableNamesMap;
1091
+ this.table = table;
1092
+ this.tableConfig = tableConfig;
1093
+ this.dialect = dialect;
1094
+ this.session = session;
1095
+ this.config = config;
1096
+ this.mode = mode;
1097
+ }
1098
+ prepare() {
1099
+ const query = this.dialect.buildRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.config, this.tableConfig.tsName, [], true);
1100
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
1101
+ return this.session.prepareQuery(builtQuery, undefined, (rawRows, mapColumnValue) => {
1102
+ const rows = rawRows.map((row) => relations.mapRelationalRow(this.schema, this.tableConfig, row, query.selection, true, mapColumnValue));
1103
+ if (this.mode === 'first') {
1104
+ return rows[0];
1105
+ }
1106
+ return rows;
1107
+ });
1108
+ }
1109
+ execute() {
1110
+ if (this.mode === 'first') {
1111
+ return this.prepare().get();
1112
+ }
1113
+ return this.prepare().all();
1114
+ }
1115
+ }
1116
+ relations.applyMixins(SQLiteRelationalQuery, [relations.QueryPromise]);
1117
+
1118
+ class BaseSQLiteDatabase {
1119
+ constructor(resultKind,
1120
+ /** @internal */
1121
+ dialect,
1122
+ /** @internal */
1123
+ session, schema) {
1124
+ this.dialect = dialect;
1125
+ this.session = session;
1126
+ this._ = schema
1127
+ ? { schema: schema.schema, tableNamesMap: schema.tableNamesMap }
1128
+ : { schema: undefined, tableNamesMap: {} };
1129
+ this.query = {};
1130
+ if (this._.schema) {
1131
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
1132
+ this.query[tableName] =
1133
+ new (resultKind === 'async' ? AsyncRelationalQueryBuilder : SyncRelationalQueryBuilder)(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
1134
+ }
1135
+ }
1136
+ }
1137
+ $with(alias) {
1138
+ return {
1139
+ as(qb) {
1140
+ if (typeof qb === 'function') {
1141
+ qb = qb(new QueryBuilder());
1142
+ }
1143
+ return new Proxy(new relations.WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new relations.SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
1144
+ },
1145
+ };
1146
+ }
1147
+ with(...queries) {
1148
+ const self = this;
1149
+ function select(fields) {
1150
+ return new SQLiteSelectBuilder(fields ?? undefined, self.session, self.dialect, queries);
1151
+ }
1152
+ return { select };
1153
+ }
1154
+ select(fields) {
1155
+ return new SQLiteSelectBuilder(fields ?? undefined, this.session, this.dialect);
1156
+ }
1157
+ update(table) {
1158
+ return new SQLiteUpdateBuilder(table, this.session, this.dialect);
1159
+ }
1160
+ insert(into) {
1161
+ return new SQLiteInsertBuilder(into, this.session, this.dialect);
1162
+ }
1163
+ delete(from) {
1164
+ return new SQLiteDelete(from, this.session, this.dialect);
1165
+ }
1166
+ run(query) {
1167
+ return this.session.run(query.getSQL());
1168
+ }
1169
+ all(query) {
1170
+ return this.session.all(query.getSQL());
1171
+ }
1172
+ get(query) {
1173
+ return this.session.get(query.getSQL());
1174
+ }
1175
+ values(query) {
1176
+ return this.session.values(query.getSQL());
1177
+ }
1178
+ transaction(transaction, config) {
1179
+ return this.session.transaction(transaction, config);
1180
+ }
1181
+ }
1182
+
1183
+ let PreparedQuery$1 = class PreparedQuery {
1184
+ };
1185
+ class SQLiteSession {
1186
+ constructor(
1187
+ /** @internal */
1188
+ dialect) {
1189
+ this.dialect = dialect;
1190
+ }
1191
+ prepareOneTimeQuery(query, fields) {
1192
+ return this.prepareQuery(query, fields);
1193
+ }
1194
+ run(query) {
1195
+ const staticQuery = this.dialect.sqlToQuery(query);
1196
+ try {
1197
+ return this.prepareOneTimeQuery(staticQuery, undefined).run();
1198
+ }
1199
+ catch (err) {
1200
+ throw errors.DrizzleError.wrap(err, `Failed to run the query '${staticQuery.sql}'`);
1201
+ }
1202
+ }
1203
+ all(query) {
1204
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined).all();
1205
+ }
1206
+ get(query) {
1207
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined).get();
1208
+ }
1209
+ values(query) {
1210
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined).values();
1211
+ }
1212
+ }
1213
+ class SQLiteTransaction extends BaseSQLiteDatabase {
1214
+ constructor(resultType, dialect, session, schema, nestedIndex = 0) {
1215
+ super(resultType, dialect, session, schema);
1216
+ this.schema = schema;
1217
+ this.nestedIndex = nestedIndex;
1218
+ }
1219
+ rollback() {
1220
+ throw new errors.TransactionRollbackError();
1221
+ }
1222
+ }
1223
+
1224
+ exports.BaseSQLiteDatabase = BaseSQLiteDatabase;
1225
+ exports.InlineForeignKeys = InlineForeignKeys;
1226
+ exports.ManualViewBuilder = ManualViewBuilder;
1227
+ exports.PreparedQuery = PreparedQuery$1;
1228
+ exports.QueryBuilder = QueryBuilder;
1229
+ exports.SQLiteAsyncDialect = SQLiteAsyncDialect;
1230
+ exports.SQLiteDelete = SQLiteDelete;
1231
+ exports.SQLiteDialect = SQLiteDialect;
1232
+ exports.SQLiteInsert = SQLiteInsert;
1233
+ exports.SQLiteInsertBuilder = SQLiteInsertBuilder;
1234
+ exports.SQLiteSelect = SQLiteSelect;
1235
+ exports.SQLiteSelectBuilder = SQLiteSelectBuilder;
1236
+ exports.SQLiteSelectQueryBuilder = SQLiteSelectQueryBuilder;
1237
+ exports.SQLiteSession = SQLiteSession;
1238
+ exports.SQLiteSyncDialect = SQLiteSyncDialect;
1239
+ exports.SQLiteTable = SQLiteTable;
1240
+ exports.SQLiteTransaction = SQLiteTransaction;
1241
+ exports.SQLiteUpdate = SQLiteUpdate;
1242
+ exports.SQLiteUpdateBuilder = SQLiteUpdateBuilder;
1243
+ exports.SQLiteView = SQLiteView;
1244
+ exports.SQLiteViewBase = SQLiteViewBase;
1245
+ exports.SQLiteViewConfig = SQLiteViewConfig;
1246
+ exports.ViewBuilder = ViewBuilder;
1247
+ exports.ViewBuilderCore = ViewBuilderCore;
1248
+ exports.sqliteTable = sqliteTable;
1249
+ exports.sqliteTableCreator = sqliteTableCreator;
1250
+ exports.sqliteView = sqliteView;
1251
+ exports.view = view;
1252
+ //# sourceMappingURL=session-a90df8a2.cjs.map