dialect.cjs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var dialect_exports = {};
  20. __export(dialect_exports, {
  21. SQLiteAsyncDialect: () => SQLiteAsyncDialect,
  22. SQLiteDialect: () => SQLiteDialect,
  23. SQLiteSyncDialect: () => SQLiteSyncDialect
  24. });
  25. module.exports = __toCommonJS(dialect_exports);
  26. var import_alias = require("../alias.cjs");
  27. var import_casing = require("../casing.cjs");
  28. var import_column = require("../column.cjs");
  29. var import_entity = require("../entity.cjs");
  30. var import_errors = require("../errors.cjs");
  31. var import_relations = require("../relations.cjs");
  32. var import_sql = require("../sql/index.cjs");
  33. var import_sql2 = require("../sql/sql.cjs");
  34. var import_columns = require("./columns/index.cjs");
  35. var import_table = require("./table.cjs");
  36. var import_subquery = require("../subquery.cjs");
  37. var import_table2 = require("../table.cjs");
  38. var import_utils = require("../utils.cjs");
  39. var import_view_common = require("../view-common.cjs");
  40. var import_view_base = require("./view-base.cjs");
  41. class SQLiteDialect {
  42. static [import_entity.entityKind] = "SQLiteDialect";
  43. /** @internal */
  44. casing;
  45. constructor(config) {
  46. this.casing = new import_casing.CasingCache(config?.casing);
  47. }
  48. escapeName(name) {
  49. return `"${name.replace(/"/g, '""')}"`;
  50. }
  51. escapeParam(_num) {
  52. return "?";
  53. }
  54. escapeString(str) {
  55. return `'${str.replace(/'/g, "''")}'`;
  56. }
  57. buildWithCTE(queries) {
  58. if (!queries?.length) return void 0;
  59. const withSqlChunks = [import_sql2.sql`with `];
  60. for (const [i, w] of queries.entries()) {
  61. withSqlChunks.push(import_sql2.sql`${import_sql2.sql.identifier(w._.alias)} as (${w._.sql})`);
  62. if (i < queries.length - 1) {
  63. withSqlChunks.push(import_sql2.sql`, `);
  64. }
  65. }
  66. withSqlChunks.push(import_sql2.sql` `);
  67. return import_sql2.sql.join(withSqlChunks);
  68. }
  69. buildDeleteQuery({
  70. table,
  71. where,
  72. returning,
  73. withList,
  74. limit,
  75. orderBy
  76. }) {
  77. const withSql = this.buildWithCTE(withList);
  78. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
  79. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  80. const orderBySql = this.buildOrderBy(orderBy);
  81. const limitSql = this.buildLimit(limit);
  82. return import_sql2.sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`;
  83. }
  84. buildUpdateSet(table, set) {
  85. const tableColumns = table[import_table2.Table.Symbol.Columns];
  86. const columnNames = Object.keys(tableColumns).filter(
  87. (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
  88. );
  89. const setSize = columnNames.length;
  90. return import_sql2.sql.join(
  91. columnNames.flatMap((colName, i) => {
  92. const col = tableColumns[colName];
  93. const onUpdateFnResult = col.onUpdateFn?.();
  94. const value = set[colName] ?? ((0, import_entity.is)(onUpdateFnResult, import_sql2.SQL) ? onUpdateFnResult : import_sql2.sql.param(onUpdateFnResult, col));
  95. const res = import_sql2.sql`${import_sql2.sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
  96. if (i < setSize - 1) {
  97. return [res, import_sql2.sql.raw(", ")];
  98. }
  99. return [res];
  100. })
  101. );
  102. }
  103. buildUpdateQuery({
  104. table,
  105. set,
  106. where,
  107. returning,
  108. withList,
  109. joins,
  110. from,
  111. limit,
  112. orderBy
  113. }) {
  114. const withSql = this.buildWithCTE(withList);
  115. const setSql = this.buildUpdateSet(table, set);
  116. const fromSql = from && import_sql2.sql.join([import_sql2.sql.raw(" from "), this.buildFromTable(from)]);
  117. const joinsSql = this.buildJoins(joins);
  118. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
  119. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  120. const orderBySql = this.buildOrderBy(orderBy);
  121. const limitSql = this.buildLimit(limit);
  122. return import_sql2.sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
  123. }
  124. /**
  125. * Builds selection SQL with provided fields/expressions
  126. *
  127. * Examples:
  128. *
  129. * `select <selection> from`
  130. *
  131. * `insert ... returning <selection>`
  132. *
  133. * If `isSingleTable` is true, then columns won't be prefixed with table name
  134. */
  135. buildSelection(fields, { isSingleTable = false } = {}) {
  136. const columnsLen = fields.length;
  137. const chunks = fields.flatMap(({ field }, i) => {
  138. const chunk = [];
  139. if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) && field.isSelectionField) {
  140. chunk.push(import_sql2.sql.identifier(field.fieldAlias));
  141. } else if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) || (0, import_entity.is)(field, import_sql2.SQL)) {
  142. const query = (0, import_entity.is)(field, import_sql2.SQL.Aliased) ? field.sql : field;
  143. if (isSingleTable) {
  144. chunk.push(
  145. new import_sql2.SQL(
  146. query.queryChunks.map((c) => {
  147. if ((0, import_entity.is)(c, import_column.Column)) {
  148. return import_sql2.sql.identifier(this.casing.getColumnCasing(c));
  149. }
  150. return c;
  151. })
  152. )
  153. );
  154. } else {
  155. chunk.push(query);
  156. }
  157. if ((0, import_entity.is)(field, import_sql2.SQL.Aliased)) {
  158. chunk.push(import_sql2.sql` as ${import_sql2.sql.identifier(field.fieldAlias)}`);
  159. }
  160. } else if ((0, import_entity.is)(field, import_column.Column)) {
  161. const tableName = field.table[import_table2.Table.Symbol.Name];
  162. if (field.columnType === "SQLiteNumericBigInt") {
  163. if (isSingleTable) {
  164. chunk.push(
  165. import_sql2.sql`cast(${import_sql2.sql.identifier(this.casing.getColumnCasing(field))} as text)`
  166. );
  167. } else {
  168. chunk.push(
  169. import_sql2.sql`cast(${import_sql2.sql.identifier(tableName)}.${import_sql2.sql.identifier(this.casing.getColumnCasing(field))} as text)`
  170. );
  171. }
  172. } else {
  173. if (isSingleTable) {
  174. chunk.push(import_sql2.sql.identifier(this.casing.getColumnCasing(field)));
  175. } else {
  176. chunk.push(
  177. import_sql2.sql`${import_sql2.sql.identifier(tableName)}.${import_sql2.sql.identifier(this.casing.getColumnCasing(field))}`
  178. );
  179. }
  180. }
  181. } else if ((0, import_entity.is)(field, import_subquery.Subquery)) {
  182. const entries = Object.entries(field._.selectedFields);
  183. if (entries.length === 1) {
  184. const entry = entries[0][1];
  185. const fieldDecoder = (0, import_entity.is)(entry, import_sql2.SQL) ? entry.decoder : (0, import_entity.is)(entry, import_column.Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
  186. if (fieldDecoder) field._.sql.decoder = fieldDecoder;
  187. }
  188. chunk.push(field);
  189. }
  190. if (i < columnsLen - 1) {
  191. chunk.push(import_sql2.sql`, `);
  192. }
  193. return chunk;
  194. });
  195. return import_sql2.sql.join(chunks);
  196. }
  197. buildJoins(joins) {
  198. if (!joins || joins.length === 0) {
  199. return void 0;
  200. }
  201. const joinsArray = [];
  202. if (joins) {
  203. for (const [index, joinMeta] of joins.entries()) {
  204. if (index === 0) {
  205. joinsArray.push(import_sql2.sql` `);
  206. }
  207. const table = joinMeta.table;
  208. const onSql = joinMeta.on ? import_sql2.sql` on ${joinMeta.on}` : void 0;
  209. if ((0, import_entity.is)(table, import_table.SQLiteTable)) {
  210. const tableName = table[import_table.SQLiteTable.Symbol.Name];
  211. const tableSchema = table[import_table.SQLiteTable.Symbol.Schema];
  212. const origTableName = table[import_table.SQLiteTable.Symbol.OriginalName];
  213. const alias = tableName === origTableName ? void 0 : joinMeta.alias;
  214. joinsArray.push(
  215. import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join ${tableSchema ? import_sql2.sql`${import_sql2.sql.identifier(tableSchema)}.` : void 0}${import_sql2.sql.identifier(
  216. origTableName
  217. )}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`}${onSql}`
  218. );
  219. } else {
  220. joinsArray.push(
  221. import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join ${table}${onSql}`
  222. );
  223. }
  224. if (index < joins.length - 1) {
  225. joinsArray.push(import_sql2.sql` `);
  226. }
  227. }
  228. }
  229. return import_sql2.sql.join(joinsArray);
  230. }
  231. buildLimit(limit) {
  232. return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
  233. }
  234. buildOrderBy(orderBy) {
  235. const orderByList = [];
  236. if (orderBy) {
  237. for (const [index, orderByValue] of orderBy.entries()) {
  238. orderByList.push(orderByValue);
  239. if (index < orderBy.length - 1) {
  240. orderByList.push(import_sql2.sql`, `);
  241. }
  242. }
  243. }
  244. return orderByList.length > 0 ? import_sql2.sql` order by ${import_sql2.sql.join(orderByList)}` : void 0;
  245. }
  246. buildFromTable(table) {
  247. if ((0, import_entity.is)(table, import_table2.Table) && table[import_table2.Table.Symbol.IsAlias]) {
  248. return import_sql2.sql`${import_sql2.sql`${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Schema] ?? "")}.`.if(table[import_table2.Table.Symbol.Schema])}${import_sql2.sql.identifier(
  249. table[import_table2.Table.Symbol.OriginalName]
  250. )} ${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Name])}`;
  251. }
  252. return table;
  253. }
  254. buildSelectQuery({
  255. withList,
  256. fields,
  257. fieldsFlat,
  258. where,
  259. having,
  260. table,
  261. joins,
  262. orderBy,
  263. groupBy,
  264. limit,
  265. offset,
  266. distinct,
  267. setOperators
  268. }) {
  269. const fieldsList = fieldsFlat ?? (0, import_utils.orderSelectedFields)(fields);
  270. for (const f of fieldsList) {
  271. if ((0, import_entity.is)(f.field, import_column.Column) && (0, import_table2.getTableName)(f.field.table) !== ((0, import_entity.is)(table, import_subquery.Subquery) ? table._.alias : (0, import_entity.is)(table, import_view_base.SQLiteViewBase) ? table[import_view_common.ViewBaseConfig].name : (0, import_entity.is)(table, import_sql2.SQL) ? void 0 : (0, import_table2.getTableName)(table)) && !((table2) => joins?.some(
  272. ({ alias }) => alias === (table2[import_table2.Table.Symbol.IsAlias] ? (0, import_table2.getTableName)(table2) : table2[import_table2.Table.Symbol.BaseName])
  273. ))(f.field.table)) {
  274. const tableName = (0, import_table2.getTableName)(f.field.table);
  275. throw new Error(
  276. `Your "${f.path.join(
  277. "->"
  278. )}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
  279. );
  280. }
  281. }
  282. const isSingleTable = !joins || joins.length === 0;
  283. const withSql = this.buildWithCTE(withList);
  284. const distinctSql = distinct ? import_sql2.sql` distinct` : void 0;
  285. const selection = this.buildSelection(fieldsList, { isSingleTable });
  286. const tableSql = this.buildFromTable(table);
  287. const joinsSql = this.buildJoins(joins);
  288. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  289. const havingSql = having ? import_sql2.sql` having ${having}` : void 0;
  290. const groupByList = [];
  291. if (groupBy) {
  292. for (const [index, groupByValue] of groupBy.entries()) {
  293. groupByList.push(groupByValue);
  294. if (index < groupBy.length - 1) {
  295. groupByList.push(import_sql2.sql`, `);
  296. }
  297. }
  298. }
  299. const groupBySql = groupByList.length > 0 ? import_sql2.sql` group by ${import_sql2.sql.join(groupByList)}` : void 0;
  300. const orderBySql = this.buildOrderBy(orderBy);
  301. const limitSql = this.buildLimit(limit);
  302. const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
  303. const finalQuery = import_sql2.sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
  304. if (setOperators.length > 0) {
  305. return this.buildSetOperations(finalQuery, setOperators);
  306. }
  307. return finalQuery;
  308. }
  309. buildSetOperations(leftSelect, setOperators) {
  310. const [setOperator, ...rest] = setOperators;
  311. if (!setOperator) {
  312. throw new Error("Cannot pass undefined values to any set operator");
  313. }
  314. if (rest.length === 0) {
  315. return this.buildSetOperationQuery({ leftSelect, setOperator });
  316. }
  317. return this.buildSetOperations(
  318. this.buildSetOperationQuery({ leftSelect, setOperator }),
  319. rest
  320. );
  321. }
  322. buildSetOperationQuery({
  323. leftSelect,
  324. setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
  325. }) {
  326. const leftChunk = import_sql2.sql`${leftSelect.getSQL()} `;
  327. const rightChunk = import_sql2.sql`${rightSelect.getSQL()}`;
  328. let orderBySql;
  329. if (orderBy && orderBy.length > 0) {
  330. const orderByValues = [];
  331. for (const singleOrderBy of orderBy) {
  332. if ((0, import_entity.is)(singleOrderBy, import_columns.SQLiteColumn)) {
  333. orderByValues.push(import_sql2.sql.identifier(singleOrderBy.name));
  334. } else if ((0, import_entity.is)(singleOrderBy, import_sql2.SQL)) {
  335. for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
  336. const chunk = singleOrderBy.queryChunks[i];
  337. if ((0, import_entity.is)(chunk, import_columns.SQLiteColumn)) {
  338. singleOrderBy.queryChunks[i] = import_sql2.sql.identifier(
  339. this.casing.getColumnCasing(chunk)
  340. );
  341. }
  342. }
  343. orderByValues.push(import_sql2.sql`${singleOrderBy}`);
  344. } else {
  345. orderByValues.push(import_sql2.sql`${singleOrderBy}`);
  346. }
  347. }
  348. orderBySql = import_sql2.sql` order by ${import_sql2.sql.join(orderByValues, import_sql2.sql`, `)}`;
  349. }
  350. const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
  351. const operatorChunk = import_sql2.sql.raw(`${type} ${isAll ? "all " : ""}`);
  352. const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
  353. return import_sql2.sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
  354. }
  355. buildInsertQuery({
  356. table,
  357. values: valuesOrSelect,
  358. onConflict,
  359. returning,
  360. withList,
  361. select
  362. }) {
  363. const valuesSqlList = [];
  364. const columns = table[import_table2.Table.Symbol.Columns];
  365. const colEntries = Object.entries(columns).filter(
  366. ([_, col]) => !col.shouldDisableInsert()
  367. );
  368. const insertOrder = colEntries.map(([, column]) => import_sql2.sql.identifier(this.casing.getColumnCasing(column)));
  369. if (select) {
  370. const select2 = valuesOrSelect;
  371. if ((0, import_entity.is)(select2, import_sql2.SQL)) {
  372. valuesSqlList.push(select2);
  373. } else {
  374. valuesSqlList.push(select2.getSQL());
  375. }
  376. } else {
  377. const values = valuesOrSelect;
  378. valuesSqlList.push(import_sql2.sql.raw("values "));
  379. for (const [valueIndex, value] of values.entries()) {
  380. const valueList = [];
  381. for (const [fieldName, col] of colEntries) {
  382. const colValue = value[fieldName];
  383. if (colValue === void 0 || (0, import_entity.is)(colValue, import_sql2.Param) && colValue.value === void 0) {
  384. let defaultValue;
  385. if (col.default !== null && col.default !== void 0) {
  386. defaultValue = (0, import_entity.is)(col.default, import_sql2.SQL) ? col.default : import_sql2.sql.param(col.default, col);
  387. } else if (col.defaultFn !== void 0) {
  388. const defaultFnResult = col.defaultFn();
  389. defaultValue = (0, import_entity.is)(defaultFnResult, import_sql2.SQL) ? defaultFnResult : import_sql2.sql.param(defaultFnResult, col);
  390. } else if (!col.default && col.onUpdateFn !== void 0) {
  391. const onUpdateFnResult = col.onUpdateFn();
  392. defaultValue = (0, import_entity.is)(onUpdateFnResult, import_sql2.SQL) ? onUpdateFnResult : import_sql2.sql.param(onUpdateFnResult, col);
  393. } else {
  394. defaultValue = import_sql2.sql`null`;
  395. }
  396. valueList.push(defaultValue);
  397. } else {
  398. valueList.push(colValue);
  399. }
  400. }
  401. valuesSqlList.push(valueList);
  402. if (valueIndex < values.length - 1) {
  403. valuesSqlList.push(import_sql2.sql`, `);
  404. }
  405. }
  406. }
  407. const withSql = this.buildWithCTE(withList);
  408. const valuesSql = import_sql2.sql.join(valuesSqlList);
  409. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
  410. const onConflictSql = onConflict?.length ? import_sql2.sql.join(onConflict) : void 0;
  411. return import_sql2.sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
  412. }
  413. sqlToQuery(sql2, invokeSource) {
  414. return sql2.toQuery({
  415. casing: this.casing,
  416. escapeName: this.escapeName,
  417. escapeParam: this.escapeParam,
  418. escapeString: this.escapeString,
  419. invokeSource
  420. });
  421. }
  422. buildRelationalQuery({
  423. fullSchema,
  424. schema,
  425. tableNamesMap,
  426. table,
  427. tableConfig,
  428. queryConfig: config,
  429. tableAlias,
  430. nestedQueryRelation,
  431. joinOn
  432. }) {
  433. let selection = [];
  434. let limit, offset, orderBy = [], where;
  435. const joins = [];
  436. if (config === true) {
  437. const selectionEntries = Object.entries(tableConfig.columns);
  438. selection = selectionEntries.map(([key, value]) => ({
  439. dbKey: value.name,
  440. tsKey: key,
  441. field: (0, import_alias.aliasedTableColumn)(value, tableAlias),
  442. relationTableTsKey: void 0,
  443. isJson: false,
  444. selection: []
  445. }));
  446. } else {
  447. const aliasedColumns = Object.fromEntries(
  448. Object.entries(tableConfig.columns).map(([key, value]) => [
  449. key,
  450. (0, import_alias.aliasedTableColumn)(value, tableAlias)
  451. ])
  452. );
  453. if (config.where) {
  454. const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0, import_relations.getOperators)()) : config.where;
  455. where = whereSql && (0, import_alias.mapColumnsInSQLToAlias)(whereSql, tableAlias);
  456. }
  457. const fieldsSelection = [];
  458. let selectedColumns = [];
  459. if (config.columns) {
  460. let isIncludeMode = false;
  461. for (const [field, value] of Object.entries(config.columns)) {
  462. if (value === void 0) {
  463. continue;
  464. }
  465. if (field in tableConfig.columns) {
  466. if (!isIncludeMode && value === true) {
  467. isIncludeMode = true;
  468. }
  469. selectedColumns.push(field);
  470. }
  471. }
  472. if (selectedColumns.length > 0) {
  473. selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter(
  474. (key) => !selectedColumns.includes(key)
  475. );
  476. }
  477. } else {
  478. selectedColumns = Object.keys(tableConfig.columns);
  479. }
  480. for (const field of selectedColumns) {
  481. const column = tableConfig.columns[field];
  482. fieldsSelection.push({ tsKey: field, value: column });
  483. }
  484. let selectedRelations = [];
  485. if (config.with) {
  486. selectedRelations = Object.entries(config.with).filter(
  487. (entry) => !!entry[1]
  488. ).map(([tsKey, queryConfig]) => ({
  489. tsKey,
  490. queryConfig,
  491. relation: tableConfig.relations[tsKey]
  492. }));
  493. }
  494. let extras;
  495. if (config.extras) {
  496. extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: import_sql2.sql }) : config.extras;
  497. for (const [tsKey, value] of Object.entries(extras)) {
  498. fieldsSelection.push({
  499. tsKey,
  500. value: (0, import_alias.mapColumnsInAliasedSQLToAlias)(value, tableAlias)
  501. });
  502. }
  503. }
  504. for (const { tsKey, value } of fieldsSelection) {
  505. selection.push({
  506. dbKey: (0, import_entity.is)(value, import_sql2.SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
  507. tsKey,
  508. field: (0, import_entity.is)(value, import_column.Column) ? (0, import_alias.aliasedTableColumn)(value, tableAlias) : value,
  509. relationTableTsKey: void 0,
  510. isJson: false,
  511. selection: []
  512. });
  513. }
  514. let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0, import_relations.getOrderByOperators)()) : config.orderBy ?? [];
  515. if (!Array.isArray(orderByOrig)) {
  516. orderByOrig = [orderByOrig];
  517. }
  518. orderBy = orderByOrig.map((orderByValue) => {
  519. if ((0, import_entity.is)(orderByValue, import_column.Column)) {
  520. return (0, import_alias.aliasedTableColumn)(orderByValue, tableAlias);
  521. }
  522. return (0, import_alias.mapColumnsInSQLToAlias)(orderByValue, tableAlias);
  523. });
  524. limit = config.limit;
  525. offset = config.offset;
  526. for (const {
  527. tsKey: selectedRelationTsKey,
  528. queryConfig: selectedRelationConfigValue,
  529. relation
  530. } of selectedRelations) {
  531. const normalizedRelation = (0, import_relations.normalizeRelation)(
  532. schema,
  533. tableNamesMap,
  534. relation
  535. );
  536. const relationTableName = (0, import_table2.getTableUniqueName)(relation.referencedTable);
  537. const relationTableTsName = tableNamesMap[relationTableName];
  538. const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
  539. const joinOn2 = (0, import_sql.and)(
  540. ...normalizedRelation.fields.map(
  541. (field2, i) => (0, import_sql.eq)(
  542. (0, import_alias.aliasedTableColumn)(
  543. normalizedRelation.references[i],
  544. relationTableAlias
  545. ),
  546. (0, import_alias.aliasedTableColumn)(field2, tableAlias)
  547. )
  548. )
  549. );
  550. const builtRelation = this.buildRelationalQuery({
  551. fullSchema,
  552. schema,
  553. tableNamesMap,
  554. table: fullSchema[relationTableTsName],
  555. tableConfig: schema[relationTableTsName],
  556. queryConfig: (0, import_entity.is)(relation, import_relations.One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
  557. tableAlias: relationTableAlias,
  558. joinOn: joinOn2,
  559. nestedQueryRelation: relation
  560. });
  561. const field = import_sql2.sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
  562. selection.push({
  563. dbKey: selectedRelationTsKey,
  564. tsKey: selectedRelationTsKey,
  565. field,
  566. relationTableTsKey: relationTableTsName,
  567. isJson: true,
  568. selection: builtRelation.selection
  569. });
  570. }
  571. }
  572. if (selection.length === 0) {
  573. throw new import_errors.DrizzleError({
  574. message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
  575. });
  576. }
  577. let result;
  578. where = (0, import_sql.and)(joinOn, where);
  579. if (nestedQueryRelation) {
  580. let field = import_sql2.sql`json_array(${import_sql2.sql.join(
  581. selection.map(
  582. ({ field: field2 }) => (0, import_entity.is)(field2, import_columns.SQLiteColumn) ? import_sql2.sql.identifier(this.casing.getColumnCasing(field2)) : (0, import_entity.is)(field2, import_sql2.SQL.Aliased) ? field2.sql : field2
  583. ),
  584. import_sql2.sql`, `
  585. )})`;
  586. if ((0, import_entity.is)(nestedQueryRelation, import_relations.Many)) {
  587. field = import_sql2.sql`coalesce(json_group_array(${field}), json_array())`;
  588. }
  589. const nestedSelection = [
  590. {
  591. dbKey: "data",
  592. tsKey: "data",
  593. field: field.as("data"),
  594. isJson: true,
  595. relationTableTsKey: tableConfig.tsName,
  596. selection
  597. }
  598. ];
  599. const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
  600. if (needsSubquery) {
  601. result = this.buildSelectQuery({
  602. table: (0, import_alias.aliasedTable)(table, tableAlias),
  603. fields: {},
  604. fieldsFlat: [
  605. {
  606. path: [],
  607. field: import_sql2.sql.raw("*")
  608. }
  609. ],
  610. where,
  611. limit,
  612. offset,
  613. orderBy,
  614. setOperators: []
  615. });
  616. where = void 0;
  617. limit = void 0;
  618. offset = void 0;
  619. orderBy = void 0;
  620. } else {
  621. result = (0, import_alias.aliasedTable)(table, tableAlias);
  622. }
  623. result = this.buildSelectQuery({
  624. table: (0, import_entity.is)(result, import_table.SQLiteTable) ? result : new import_subquery.Subquery(result, {}, tableAlias),
  625. fields: {},
  626. fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
  627. path: [],
  628. field: (0, import_entity.is)(field2, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field2, tableAlias) : field2
  629. })),
  630. joins,
  631. where,
  632. limit,
  633. offset,
  634. orderBy,
  635. setOperators: []
  636. });
  637. } else {
  638. result = this.buildSelectQuery({
  639. table: (0, import_alias.aliasedTable)(table, tableAlias),
  640. fields: {},
  641. fieldsFlat: selection.map(({ field }) => ({
  642. path: [],
  643. field: (0, import_entity.is)(field, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field, tableAlias) : field
  644. })),
  645. joins,
  646. where,
  647. limit,
  648. offset,
  649. orderBy,
  650. setOperators: []
  651. });
  652. }
  653. return {
  654. tableTsKey: tableConfig.tsName,
  655. sql: result,
  656. selection
  657. };
  658. }
  659. }
  660. class SQLiteSyncDialect extends SQLiteDialect {
  661. static [import_entity.entityKind] = "SQLiteSyncDialect";
  662. migrate(migrations, session, config) {
  663. const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
  664. const migrationTableCreate = import_sql2.sql`
  665. CREATE TABLE IF NOT EXISTS ${import_sql2.sql.identifier(migrationsTable)} (
  666. id SERIAL PRIMARY KEY,
  667. hash text NOT NULL,
  668. created_at numeric
  669. )
  670. `;
  671. session.run(migrationTableCreate);
  672. const dbMigrations = session.values(
  673. import_sql2.sql`SELECT id, hash, created_at FROM ${import_sql2.sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
  674. );
  675. const lastDbMigration = dbMigrations[0] ?? void 0;
  676. session.run(import_sql2.sql`BEGIN`);
  677. try {
  678. for (const migration of migrations) {
  679. if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
  680. for (const stmt of migration.sql) {
  681. session.run(import_sql2.sql.raw(stmt));
  682. }
  683. session.run(
  684. import_sql2.sql`INSERT INTO ${import_sql2.sql.identifier(
  685. migrationsTable
  686. )} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
  687. );
  688. }
  689. }
  690. session.run(import_sql2.sql`COMMIT`);
  691. } catch (e) {
  692. session.run(import_sql2.sql`ROLLBACK`);
  693. throw e;
  694. }
  695. }
  696. }
  697. class SQLiteAsyncDialect extends SQLiteDialect {
  698. static [import_entity.entityKind] = "SQLiteAsyncDialect";
  699. async migrate(migrations, session, config) {
  700. const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
  701. const migrationTableCreate = import_sql2.sql`
  702. CREATE TABLE IF NOT EXISTS ${import_sql2.sql.identifier(migrationsTable)} (
  703. id SERIAL PRIMARY KEY,
  704. hash text NOT NULL,
  705. created_at numeric
  706. )
  707. `;
  708. await session.run(migrationTableCreate);
  709. const dbMigrations = await session.values(
  710. import_sql2.sql`SELECT id, hash, created_at FROM ${import_sql2.sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
  711. );
  712. const lastDbMigration = dbMigrations[0] ?? void 0;
  713. await session.transaction(async (tx) => {
  714. for (const migration of migrations) {
  715. if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
  716. for (const stmt of migration.sql) {
  717. await tx.run(import_sql2.sql.raw(stmt));
  718. }
  719. await tx.run(
  720. import_sql2.sql`INSERT INTO ${import_sql2.sql.identifier(
  721. migrationsTable
  722. )} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
  723. );
  724. }
  725. }
  726. });
  727. }
  728. }
  729. // Annotate the CommonJS export names for ESM import in node:
  730. 0 && (module.exports = {
  731. SQLiteAsyncDialect,
  732. SQLiteDialect,
  733. SQLiteSyncDialect
  734. });
  735. //# sourceMappingURL=dialect.cjs.map