dialect.cjs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. PgDialect: () => PgDialect
  22. });
  23. module.exports = __toCommonJS(dialect_exports);
  24. var import_alias = require("../alias.cjs");
  25. var import_casing = require("../casing.cjs");
  26. var import_column = require("../column.cjs");
  27. var import_entity = require("../entity.cjs");
  28. var import_errors = require("../errors.cjs");
  29. var import_columns = require("./columns/index.cjs");
  30. var import_table = require("./table.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_subquery = require("../subquery.cjs");
  35. var import_table2 = require("../table.cjs");
  36. var import_utils = require("../utils.cjs");
  37. var import_view_common = require("../view-common.cjs");
  38. var import_view_base = require("./view-base.cjs");
  39. class PgDialect {
  40. static [import_entity.entityKind] = "PgDialect";
  41. /** @internal */
  42. casing;
  43. constructor(config) {
  44. this.casing = new import_casing.CasingCache(config?.casing);
  45. }
  46. async migrate(migrations, session, config) {
  47. const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
  48. const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
  49. const migrationTableCreate = import_sql2.sql`
  50. CREATE TABLE IF NOT EXISTS ${import_sql2.sql.identifier(migrationsSchema)}.${import_sql2.sql.identifier(migrationsTable)} (
  51. id SERIAL PRIMARY KEY,
  52. hash text NOT NULL,
  53. created_at bigint
  54. )
  55. `;
  56. await session.execute(import_sql2.sql`CREATE SCHEMA IF NOT EXISTS ${import_sql2.sql.identifier(migrationsSchema)}`);
  57. await session.execute(migrationTableCreate);
  58. const dbMigrations = await session.all(
  59. import_sql2.sql`select id, hash, created_at from ${import_sql2.sql.identifier(migrationsSchema)}.${import_sql2.sql.identifier(migrationsTable)} order by created_at desc limit 1`
  60. );
  61. const lastDbMigration = dbMigrations[0];
  62. await session.transaction(async (tx) => {
  63. for await (const migration of migrations) {
  64. if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
  65. for (const stmt of migration.sql) {
  66. await tx.execute(import_sql2.sql.raw(stmt));
  67. }
  68. await tx.execute(
  69. import_sql2.sql`insert into ${import_sql2.sql.identifier(migrationsSchema)}.${import_sql2.sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
  70. );
  71. }
  72. }
  73. });
  74. }
  75. escapeName(name) {
  76. return `"${name.replace(/"/g, '""')}"`;
  77. }
  78. escapeParam(num) {
  79. return `$${num + 1}`;
  80. }
  81. escapeString(str) {
  82. return `'${str.replace(/'/g, "''")}'`;
  83. }
  84. buildWithCTE(queries) {
  85. if (!queries?.length) return void 0;
  86. const withSqlChunks = [import_sql2.sql`with `];
  87. for (const [i, w] of queries.entries()) {
  88. withSqlChunks.push(import_sql2.sql`${import_sql2.sql.identifier(w._.alias)} as (${w._.sql})`);
  89. if (i < queries.length - 1) {
  90. withSqlChunks.push(import_sql2.sql`, `);
  91. }
  92. }
  93. withSqlChunks.push(import_sql2.sql` `);
  94. return import_sql2.sql.join(withSqlChunks);
  95. }
  96. buildDeleteQuery({ table, where, returning, withList }) {
  97. const withSql = this.buildWithCTE(withList);
  98. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
  99. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  100. return import_sql2.sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
  101. }
  102. buildUpdateSet(table, set) {
  103. const tableColumns = table[import_table2.Table.Symbol.Columns];
  104. const columnNames = Object.keys(tableColumns).filter(
  105. (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
  106. );
  107. const setSize = columnNames.length;
  108. return import_sql2.sql.join(columnNames.flatMap((colName, i) => {
  109. const col = tableColumns[colName];
  110. const onUpdateFnResult = col.onUpdateFn?.();
  111. const value = set[colName] ?? ((0, import_entity.is)(onUpdateFnResult, import_sql2.SQL) ? onUpdateFnResult : import_sql2.sql.param(onUpdateFnResult, col));
  112. const res = import_sql2.sql`${import_sql2.sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
  113. if (i < setSize - 1) {
  114. return [res, import_sql2.sql.raw(", ")];
  115. }
  116. return [res];
  117. }));
  118. }
  119. buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
  120. const withSql = this.buildWithCTE(withList);
  121. const tableName = table[import_table.PgTable.Symbol.Name];
  122. const tableSchema = table[import_table.PgTable.Symbol.Schema];
  123. const origTableName = table[import_table.PgTable.Symbol.OriginalName];
  124. const alias = tableName === origTableName ? void 0 : tableName;
  125. const tableSql = import_sql2.sql`${tableSchema ? import_sql2.sql`${import_sql2.sql.identifier(tableSchema)}.` : void 0}${import_sql2.sql.identifier(origTableName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`}`;
  126. const setSql = this.buildUpdateSet(table, set);
  127. const fromSql = from && import_sql2.sql.join([import_sql2.sql.raw(" from "), this.buildFromTable(from)]);
  128. const joinsSql = this.buildJoins(joins);
  129. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
  130. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  131. return import_sql2.sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
  132. }
  133. /**
  134. * Builds selection SQL with provided fields/expressions
  135. *
  136. * Examples:
  137. *
  138. * `select <selection> from`
  139. *
  140. * `insert ... returning <selection>`
  141. *
  142. * If `isSingleTable` is true, then columns won't be prefixed with table name
  143. */
  144. buildSelection(fields, { isSingleTable = false } = {}) {
  145. const columnsLen = fields.length;
  146. const chunks = fields.flatMap(({ field }, i) => {
  147. const chunk = [];
  148. if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) && field.isSelectionField) {
  149. chunk.push(import_sql2.sql.identifier(field.fieldAlias));
  150. } else if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) || (0, import_entity.is)(field, import_sql2.SQL)) {
  151. const query = (0, import_entity.is)(field, import_sql2.SQL.Aliased) ? field.sql : field;
  152. if (isSingleTable) {
  153. chunk.push(
  154. new import_sql2.SQL(
  155. query.queryChunks.map((c) => {
  156. if ((0, import_entity.is)(c, import_columns.PgColumn)) {
  157. return import_sql2.sql.identifier(this.casing.getColumnCasing(c));
  158. }
  159. return c;
  160. })
  161. )
  162. );
  163. } else {
  164. chunk.push(query);
  165. }
  166. if ((0, import_entity.is)(field, import_sql2.SQL.Aliased)) {
  167. chunk.push(import_sql2.sql` as ${import_sql2.sql.identifier(field.fieldAlias)}`);
  168. }
  169. } else if ((0, import_entity.is)(field, import_column.Column)) {
  170. if (isSingleTable) {
  171. chunk.push(import_sql2.sql.identifier(this.casing.getColumnCasing(field)));
  172. } else {
  173. chunk.push(field);
  174. }
  175. } else if ((0, import_entity.is)(field, import_subquery.Subquery)) {
  176. const entries = Object.entries(field._.selectedFields);
  177. if (entries.length === 1) {
  178. const entry = entries[0][1];
  179. 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;
  180. if (fieldDecoder) {
  181. field._.sql.decoder = fieldDecoder;
  182. }
  183. }
  184. chunk.push(field);
  185. }
  186. if (i < columnsLen - 1) {
  187. chunk.push(import_sql2.sql`, `);
  188. }
  189. return chunk;
  190. });
  191. return import_sql2.sql.join(chunks);
  192. }
  193. buildJoins(joins) {
  194. if (!joins || joins.length === 0) {
  195. return void 0;
  196. }
  197. const joinsArray = [];
  198. for (const [index, joinMeta] of joins.entries()) {
  199. if (index === 0) {
  200. joinsArray.push(import_sql2.sql` `);
  201. }
  202. const table = joinMeta.table;
  203. const lateralSql = joinMeta.lateral ? import_sql2.sql` lateral` : void 0;
  204. const onSql = joinMeta.on ? import_sql2.sql` on ${joinMeta.on}` : void 0;
  205. if ((0, import_entity.is)(table, import_table.PgTable)) {
  206. const tableName = table[import_table.PgTable.Symbol.Name];
  207. const tableSchema = table[import_table.PgTable.Symbol.Schema];
  208. const origTableName = table[import_table.PgTable.Symbol.OriginalName];
  209. const alias = tableName === origTableName ? void 0 : joinMeta.alias;
  210. joinsArray.push(
  211. import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? import_sql2.sql`${import_sql2.sql.identifier(tableSchema)}.` : void 0}${import_sql2.sql.identifier(origTableName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`}${onSql}`
  212. );
  213. } else if ((0, import_entity.is)(table, import_sql.View)) {
  214. const viewName = table[import_view_common.ViewBaseConfig].name;
  215. const viewSchema = table[import_view_common.ViewBaseConfig].schema;
  216. const origViewName = table[import_view_common.ViewBaseConfig].originalName;
  217. const alias = viewName === origViewName ? void 0 : joinMeta.alias;
  218. joinsArray.push(
  219. import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? import_sql2.sql`${import_sql2.sql.identifier(viewSchema)}.` : void 0}${import_sql2.sql.identifier(origViewName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`}${onSql}`
  220. );
  221. } else {
  222. joinsArray.push(
  223. import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`
  224. );
  225. }
  226. if (index < joins.length - 1) {
  227. joinsArray.push(import_sql2.sql` `);
  228. }
  229. }
  230. return import_sql2.sql.join(joinsArray);
  231. }
  232. buildFromTable(table) {
  233. if ((0, import_entity.is)(table, import_table2.Table) && table[import_table2.Table.Symbol.IsAlias]) {
  234. let fullName = import_sql2.sql`${import_sql2.sql.identifier(table[import_table2.Table.Symbol.OriginalName])}`;
  235. if (table[import_table2.Table.Symbol.Schema]) {
  236. fullName = import_sql2.sql`${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Schema])}.${fullName}`;
  237. }
  238. return import_sql2.sql`${fullName} ${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Name])}`;
  239. }
  240. return table;
  241. }
  242. buildSelectQuery({
  243. withList,
  244. fields,
  245. fieldsFlat,
  246. where,
  247. having,
  248. table,
  249. joins,
  250. orderBy,
  251. groupBy,
  252. limit,
  253. offset,
  254. lockingClause,
  255. distinct,
  256. setOperators
  257. }) {
  258. const fieldsList = fieldsFlat ?? (0, import_utils.orderSelectedFields)(fields);
  259. for (const f of fieldsList) {
  260. 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.PgViewBase) ? table[import_view_common.ViewBaseConfig].name : (0, import_entity.is)(table, import_sql2.SQL) ? void 0 : (0, import_table2.getTableName)(table)) && !((table2) => joins?.some(
  261. ({ alias }) => alias === (table2[import_table2.Table.Symbol.IsAlias] ? (0, import_table2.getTableName)(table2) : table2[import_table2.Table.Symbol.BaseName])
  262. ))(f.field.table)) {
  263. const tableName = (0, import_table2.getTableName)(f.field.table);
  264. throw new Error(
  265. `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?`
  266. );
  267. }
  268. }
  269. const isSingleTable = !joins || joins.length === 0;
  270. const withSql = this.buildWithCTE(withList);
  271. let distinctSql;
  272. if (distinct) {
  273. distinctSql = distinct === true ? import_sql2.sql` distinct` : import_sql2.sql` distinct on (${import_sql2.sql.join(distinct.on, import_sql2.sql`, `)})`;
  274. }
  275. const selection = this.buildSelection(fieldsList, { isSingleTable });
  276. const tableSql = this.buildFromTable(table);
  277. const joinsSql = this.buildJoins(joins);
  278. const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
  279. const havingSql = having ? import_sql2.sql` having ${having}` : void 0;
  280. let orderBySql;
  281. if (orderBy && orderBy.length > 0) {
  282. orderBySql = import_sql2.sql` order by ${import_sql2.sql.join(orderBy, import_sql2.sql`, `)}`;
  283. }
  284. let groupBySql;
  285. if (groupBy && groupBy.length > 0) {
  286. groupBySql = import_sql2.sql` group by ${import_sql2.sql.join(groupBy, import_sql2.sql`, `)}`;
  287. }
  288. const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
  289. const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
  290. const lockingClauseSql = import_sql2.sql.empty();
  291. if (lockingClause) {
  292. const clauseSql = import_sql2.sql` for ${import_sql2.sql.raw(lockingClause.strength)}`;
  293. if (lockingClause.config.of) {
  294. clauseSql.append(
  295. import_sql2.sql` of ${import_sql2.sql.join(
  296. Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
  297. import_sql2.sql`, `
  298. )}`
  299. );
  300. }
  301. if (lockingClause.config.noWait) {
  302. clauseSql.append(import_sql2.sql` nowait`);
  303. } else if (lockingClause.config.skipLocked) {
  304. clauseSql.append(import_sql2.sql` skip locked`);
  305. }
  306. lockingClauseSql.append(clauseSql);
  307. }
  308. const finalQuery = import_sql2.sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
  309. if (setOperators.length > 0) {
  310. return this.buildSetOperations(finalQuery, setOperators);
  311. }
  312. return finalQuery;
  313. }
  314. buildSetOperations(leftSelect, setOperators) {
  315. const [setOperator, ...rest] = setOperators;
  316. if (!setOperator) {
  317. throw new Error("Cannot pass undefined values to any set operator");
  318. }
  319. if (rest.length === 0) {
  320. return this.buildSetOperationQuery({ leftSelect, setOperator });
  321. }
  322. return this.buildSetOperations(
  323. this.buildSetOperationQuery({ leftSelect, setOperator }),
  324. rest
  325. );
  326. }
  327. buildSetOperationQuery({
  328. leftSelect,
  329. setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
  330. }) {
  331. const leftChunk = import_sql2.sql`(${leftSelect.getSQL()}) `;
  332. const rightChunk = import_sql2.sql`(${rightSelect.getSQL()})`;
  333. let orderBySql;
  334. if (orderBy && orderBy.length > 0) {
  335. const orderByValues = [];
  336. for (const singleOrderBy of orderBy) {
  337. if ((0, import_entity.is)(singleOrderBy, import_columns.PgColumn)) {
  338. orderByValues.push(import_sql2.sql.identifier(singleOrderBy.name));
  339. } else if ((0, import_entity.is)(singleOrderBy, import_sql2.SQL)) {
  340. for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
  341. const chunk = singleOrderBy.queryChunks[i];
  342. if ((0, import_entity.is)(chunk, import_columns.PgColumn)) {
  343. singleOrderBy.queryChunks[i] = import_sql2.sql.identifier(chunk.name);
  344. }
  345. }
  346. orderByValues.push(import_sql2.sql`${singleOrderBy}`);
  347. } else {
  348. orderByValues.push(import_sql2.sql`${singleOrderBy}`);
  349. }
  350. }
  351. orderBySql = import_sql2.sql` order by ${import_sql2.sql.join(orderByValues, import_sql2.sql`, `)} `;
  352. }
  353. const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
  354. const operatorChunk = import_sql2.sql.raw(`${type} ${isAll ? "all " : ""}`);
  355. const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
  356. return import_sql2.sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
  357. }
  358. buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
  359. const valuesSqlList = [];
  360. const columns = table[import_table2.Table.Symbol.Columns];
  361. const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
  362. const insertOrder = colEntries.map(
  363. ([, column]) => import_sql2.sql.identifier(this.casing.getColumnCasing(column))
  364. );
  365. if (select) {
  366. const select2 = valuesOrSelect;
  367. if ((0, import_entity.is)(select2, import_sql2.SQL)) {
  368. valuesSqlList.push(select2);
  369. } else {
  370. valuesSqlList.push(select2.getSQL());
  371. }
  372. } else {
  373. const values = valuesOrSelect;
  374. valuesSqlList.push(import_sql2.sql.raw("values "));
  375. for (const [valueIndex, value] of values.entries()) {
  376. const valueList = [];
  377. for (const [fieldName, col] of colEntries) {
  378. const colValue = value[fieldName];
  379. if (colValue === void 0 || (0, import_entity.is)(colValue, import_sql2.Param) && colValue.value === void 0) {
  380. if (col.defaultFn !== void 0) {
  381. const defaultFnResult = col.defaultFn();
  382. const defaultValue = (0, import_entity.is)(defaultFnResult, import_sql2.SQL) ? defaultFnResult : import_sql2.sql.param(defaultFnResult, col);
  383. valueList.push(defaultValue);
  384. } else if (!col.default && col.onUpdateFn !== void 0) {
  385. const onUpdateFnResult = col.onUpdateFn();
  386. const newValue = (0, import_entity.is)(onUpdateFnResult, import_sql2.SQL) ? onUpdateFnResult : import_sql2.sql.param(onUpdateFnResult, col);
  387. valueList.push(newValue);
  388. } else {
  389. valueList.push(import_sql2.sql`default`);
  390. }
  391. } else {
  392. valueList.push(colValue);
  393. }
  394. }
  395. valuesSqlList.push(valueList);
  396. if (valueIndex < values.length - 1) {
  397. valuesSqlList.push(import_sql2.sql`, `);
  398. }
  399. }
  400. }
  401. const withSql = this.buildWithCTE(withList);
  402. const valuesSql = import_sql2.sql.join(valuesSqlList);
  403. const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
  404. const onConflictSql = onConflict ? import_sql2.sql` on conflict ${onConflict}` : void 0;
  405. const overridingSql = overridingSystemValue_ === true ? import_sql2.sql`overriding system value ` : void 0;
  406. return import_sql2.sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
  407. }
  408. buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
  409. const concurrentlySql = concurrently ? import_sql2.sql` concurrently` : void 0;
  410. const withNoDataSql = withNoData ? import_sql2.sql` with no data` : void 0;
  411. return import_sql2.sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
  412. }
  413. prepareTyping(encoder) {
  414. if ((0, import_entity.is)(encoder, import_columns.PgJsonb) || (0, import_entity.is)(encoder, import_columns.PgJson)) {
  415. return "json";
  416. } else if ((0, import_entity.is)(encoder, import_columns.PgNumeric)) {
  417. return "decimal";
  418. } else if ((0, import_entity.is)(encoder, import_columns.PgTime)) {
  419. return "time";
  420. } else if ((0, import_entity.is)(encoder, import_columns.PgTimestamp) || (0, import_entity.is)(encoder, import_columns.PgTimestampString)) {
  421. return "timestamp";
  422. } else if ((0, import_entity.is)(encoder, import_columns.PgDate) || (0, import_entity.is)(encoder, import_columns.PgDateString)) {
  423. return "date";
  424. } else if ((0, import_entity.is)(encoder, import_columns.PgUUID)) {
  425. return "uuid";
  426. } else {
  427. return "none";
  428. }
  429. }
  430. sqlToQuery(sql2, invokeSource) {
  431. return sql2.toQuery({
  432. casing: this.casing,
  433. escapeName: this.escapeName,
  434. escapeParam: this.escapeParam,
  435. escapeString: this.escapeString,
  436. prepareTyping: this.prepareTyping,
  437. invokeSource
  438. });
  439. }
  440. // buildRelationalQueryWithPK({
  441. // fullSchema,
  442. // schema,
  443. // tableNamesMap,
  444. // table,
  445. // tableConfig,
  446. // queryConfig: config,
  447. // tableAlias,
  448. // isRoot = false,
  449. // joinOn,
  450. // }: {
  451. // fullSchema: Record<string, unknown>;
  452. // schema: TablesRelationalConfig;
  453. // tableNamesMap: Record<string, string>;
  454. // table: PgTable;
  455. // tableConfig: TableRelationalConfig;
  456. // queryConfig: true | DBQueryConfig<'many', true>;
  457. // tableAlias: string;
  458. // isRoot?: boolean;
  459. // joinOn?: SQL;
  460. // }): BuildRelationalQueryResult<PgTable, PgColumn> {
  461. // // For { "<relation>": true }, return a table with selection of all columns
  462. // if (config === true) {
  463. // const selectionEntries = Object.entries(tableConfig.columns);
  464. // const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
  465. // [key, value],
  466. // ) => ({
  467. // dbKey: value.name,
  468. // tsKey: key,
  469. // field: value as PgColumn,
  470. // relationTableTsKey: undefined,
  471. // isJson: false,
  472. // selection: [],
  473. // }));
  474. // return {
  475. // tableTsKey: tableConfig.tsName,
  476. // sql: table,
  477. // selection,
  478. // };
  479. // }
  480. // // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
  481. // // let selectionForBuild = selection;
  482. // const aliasedColumns = Object.fromEntries(
  483. // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
  484. // );
  485. // const aliasedRelations = Object.fromEntries(
  486. // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
  487. // );
  488. // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
  489. // let where, hasUserDefinedWhere;
  490. // if (config.where) {
  491. // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
  492. // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
  493. // hasUserDefinedWhere = !!where;
  494. // }
  495. // where = and(joinOn, where);
  496. // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
  497. // let joins: Join[] = [];
  498. // let selectedColumns: string[] = [];
  499. // // Figure out which columns to select
  500. // if (config.columns) {
  501. // let isIncludeMode = false;
  502. // for (const [field, value] of Object.entries(config.columns)) {
  503. // if (value === undefined) {
  504. // continue;
  505. // }
  506. // if (field in tableConfig.columns) {
  507. // if (!isIncludeMode && value === true) {
  508. // isIncludeMode = true;
  509. // }
  510. // selectedColumns.push(field);
  511. // }
  512. // }
  513. // if (selectedColumns.length > 0) {
  514. // selectedColumns = isIncludeMode
  515. // ? selectedColumns.filter((c) => config.columns?.[c] === true)
  516. // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
  517. // }
  518. // } else {
  519. // // Select all columns if selection is not specified
  520. // selectedColumns = Object.keys(tableConfig.columns);
  521. // }
  522. // // for (const field of selectedColumns) {
  523. // // const column = tableConfig.columns[field]! as PgColumn;
  524. // // fieldsSelection.push({ tsKey: field, value: column });
  525. // // }
  526. // let initiallySelectedRelations: {
  527. // tsKey: string;
  528. // queryConfig: true | DBQueryConfig<'many', false>;
  529. // relation: Relation;
  530. // }[] = [];
  531. // // let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
  532. // // Figure out which relations to select
  533. // if (config.with) {
  534. // initiallySelectedRelations = Object.entries(config.with)
  535. // .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
  536. // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
  537. // }
  538. // const manyRelations = initiallySelectedRelations.filter((r) =>
  539. // is(r.relation, Many)
  540. // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
  541. // );
  542. // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
  543. // const isInnermostQuery = manyRelations.length < 2;
  544. // const selectedExtras: {
  545. // tsKey: string;
  546. // value: SQL.Aliased;
  547. // }[] = [];
  548. // // Figure out which extras to select
  549. // if (isInnermostQuery && config.extras) {
  550. // const extras = typeof config.extras === 'function'
  551. // ? config.extras(aliasedFields, { sql })
  552. // : config.extras;
  553. // for (const [tsKey, value] of Object.entries(extras)) {
  554. // selectedExtras.push({
  555. // tsKey,
  556. // value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
  557. // });
  558. // }
  559. // }
  560. // // Transform `fieldsSelection` into `selection`
  561. // // `fieldsSelection` shouldn't be used after this point
  562. // // for (const { tsKey, value, isExtra } of fieldsSelection) {
  563. // // selection.push({
  564. // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
  565. // // tsKey,
  566. // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
  567. // // relationTableTsKey: undefined,
  568. // // isJson: false,
  569. // // isExtra,
  570. // // selection: [],
  571. // // });
  572. // // }
  573. // let orderByOrig = typeof config.orderBy === 'function'
  574. // ? config.orderBy(aliasedFields, orderByOperators)
  575. // : config.orderBy ?? [];
  576. // if (!Array.isArray(orderByOrig)) {
  577. // orderByOrig = [orderByOrig];
  578. // }
  579. // const orderBy = orderByOrig.map((orderByValue) => {
  580. // if (is(orderByValue, Column)) {
  581. // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
  582. // }
  583. // return mapColumnsInSQLToAlias(orderByValue, tableAlias);
  584. // });
  585. // const limit = isInnermostQuery ? config.limit : undefined;
  586. // const offset = isInnermostQuery ? config.offset : undefined;
  587. // // For non-root queries without additional config except columns, return a table with selection
  588. // if (
  589. // !isRoot
  590. // && initiallySelectedRelations.length === 0
  591. // && selectedExtras.length === 0
  592. // && !where
  593. // && orderBy.length === 0
  594. // && limit === undefined
  595. // && offset === undefined
  596. // ) {
  597. // return {
  598. // tableTsKey: tableConfig.tsName,
  599. // sql: table,
  600. // selection: selectedColumns.map((key) => ({
  601. // dbKey: tableConfig.columns[key]!.name,
  602. // tsKey: key,
  603. // field: tableConfig.columns[key] as PgColumn,
  604. // relationTableTsKey: undefined,
  605. // isJson: false,
  606. // selection: [],
  607. // })),
  608. // };
  609. // }
  610. // const selectedRelationsWithoutPK:
  611. // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
  612. // for (
  613. // const {
  614. // tsKey: selectedRelationTsKey,
  615. // queryConfig: selectedRelationConfigValue,
  616. // relation,
  617. // } of initiallySelectedRelations
  618. // ) {
  619. // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
  620. // const relationTableName = relation.referencedTable[Table.Symbol.Name];
  621. // const relationTableTsName = tableNamesMap[relationTableName]!;
  622. // const relationTable = schema[relationTableTsName]!;
  623. // if (relationTable.primaryKey.length > 0) {
  624. // continue;
  625. // }
  626. // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
  627. // const joinOn = and(
  628. // ...normalizedRelation.fields.map((field, i) =>
  629. // eq(
  630. // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
  631. // aliasedTableColumn(field, tableAlias),
  632. // )
  633. // ),
  634. // );
  635. // const builtRelation = this.buildRelationalQueryWithoutPK({
  636. // fullSchema,
  637. // schema,
  638. // tableNamesMap,
  639. // table: fullSchema[relationTableTsName] as PgTable,
  640. // tableConfig: schema[relationTableTsName]!,
  641. // queryConfig: selectedRelationConfigValue,
  642. // tableAlias: relationTableAlias,
  643. // joinOn,
  644. // nestedQueryRelation: relation,
  645. // });
  646. // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
  647. // joins.push({
  648. // on: sql`true`,
  649. // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
  650. // alias: relationTableAlias,
  651. // joinType: 'left',
  652. // lateral: true,
  653. // });
  654. // selectedRelations.push({
  655. // dbKey: selectedRelationTsKey,
  656. // tsKey: selectedRelationTsKey,
  657. // field,
  658. // relationTableTsKey: relationTableTsName,
  659. // isJson: true,
  660. // selection: builtRelation.selection,
  661. // });
  662. // }
  663. // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
  664. // is(r.relation, One)
  665. // );
  666. // // Process all One relations with PKs, because they can all be joined on the same level
  667. // for (
  668. // const {
  669. // tsKey: selectedRelationTsKey,
  670. // queryConfig: selectedRelationConfigValue,
  671. // relation,
  672. // } of oneRelations
  673. // ) {
  674. // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
  675. // const relationTableName = relation.referencedTable[Table.Symbol.Name];
  676. // const relationTableTsName = tableNamesMap[relationTableName]!;
  677. // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
  678. // const relationTable = schema[relationTableTsName]!;
  679. // if (relationTable.primaryKey.length === 0) {
  680. // continue;
  681. // }
  682. // const joinOn = and(
  683. // ...normalizedRelation.fields.map((field, i) =>
  684. // eq(
  685. // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
  686. // aliasedTableColumn(field, tableAlias),
  687. // )
  688. // ),
  689. // );
  690. // const builtRelation = this.buildRelationalQueryWithPK({
  691. // fullSchema,
  692. // schema,
  693. // tableNamesMap,
  694. // table: fullSchema[relationTableTsName] as PgTable,
  695. // tableConfig: schema[relationTableTsName]!,
  696. // queryConfig: selectedRelationConfigValue,
  697. // tableAlias: relationTableAlias,
  698. // joinOn,
  699. // });
  700. // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
  701. // sql.join(
  702. // builtRelation.selection.map(({ field }) =>
  703. // is(field, SQL.Aliased)
  704. // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
  705. // : is(field, Column)
  706. // ? aliasedTableColumn(field, relationTableAlias)
  707. // : field
  708. // ),
  709. // sql`, `,
  710. // )
  711. // }) end`.as(selectedRelationTsKey);
  712. // const isLateralJoin = is(builtRelation.sql, SQL);
  713. // joins.push({
  714. // on: isLateralJoin ? sql`true` : joinOn,
  715. // table: is(builtRelation.sql, SQL)
  716. // ? new Subquery(builtRelation.sql, {}, relationTableAlias)
  717. // : aliasedTable(builtRelation.sql, relationTableAlias),
  718. // alias: relationTableAlias,
  719. // joinType: 'left',
  720. // lateral: is(builtRelation.sql, SQL),
  721. // });
  722. // selectedRelations.push({
  723. // dbKey: selectedRelationTsKey,
  724. // tsKey: selectedRelationTsKey,
  725. // field,
  726. // relationTableTsKey: relationTableTsName,
  727. // isJson: true,
  728. // selection: builtRelation.selection,
  729. // });
  730. // }
  731. // let distinct: PgSelectConfig['distinct'];
  732. // let tableFrom: PgTable | Subquery = table;
  733. // // Process first Many relation - each one requires a nested subquery
  734. // const manyRelation = manyRelations[0];
  735. // if (manyRelation) {
  736. // const {
  737. // tsKey: selectedRelationTsKey,
  738. // queryConfig: selectedRelationQueryConfig,
  739. // relation,
  740. // } = manyRelation;
  741. // distinct = {
  742. // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
  743. // };
  744. // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
  745. // const relationTableName = relation.referencedTable[Table.Symbol.Name];
  746. // const relationTableTsName = tableNamesMap[relationTableName]!;
  747. // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
  748. // const joinOn = and(
  749. // ...normalizedRelation.fields.map((field, i) =>
  750. // eq(
  751. // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
  752. // aliasedTableColumn(field, tableAlias),
  753. // )
  754. // ),
  755. // );
  756. // const builtRelationJoin = this.buildRelationalQueryWithPK({
  757. // fullSchema,
  758. // schema,
  759. // tableNamesMap,
  760. // table: fullSchema[relationTableTsName] as PgTable,
  761. // tableConfig: schema[relationTableTsName]!,
  762. // queryConfig: selectedRelationQueryConfig,
  763. // tableAlias: relationTableAlias,
  764. // joinOn,
  765. // });
  766. // const builtRelationSelectionField = sql`case when ${
  767. // sql.identifier(relationTableAlias)
  768. // } is null then '[]' else json_agg(json_build_array(${
  769. // sql.join(
  770. // builtRelationJoin.selection.map(({ field }) =>
  771. // is(field, SQL.Aliased)
  772. // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
  773. // : is(field, Column)
  774. // ? aliasedTableColumn(field, relationTableAlias)
  775. // : field
  776. // ),
  777. // sql`, `,
  778. // )
  779. // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
  780. // const isLateralJoin = is(builtRelationJoin.sql, SQL);
  781. // joins.push({
  782. // on: isLateralJoin ? sql`true` : joinOn,
  783. // table: isLateralJoin
  784. // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
  785. // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
  786. // alias: relationTableAlias,
  787. // joinType: 'left',
  788. // lateral: isLateralJoin,
  789. // });
  790. // // Build the "from" subquery with the remaining Many relations
  791. // const builtTableFrom = this.buildRelationalQueryWithPK({
  792. // fullSchema,
  793. // schema,
  794. // tableNamesMap,
  795. // table,
  796. // tableConfig,
  797. // queryConfig: {
  798. // ...config,
  799. // where: undefined,
  800. // orderBy: undefined,
  801. // limit: undefined,
  802. // offset: undefined,
  803. // with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
  804. // (result, { tsKey, queryConfig: configValue }) => {
  805. // result[tsKey] = configValue;
  806. // return result;
  807. // },
  808. // {},
  809. // ),
  810. // },
  811. // tableAlias,
  812. // });
  813. // selectedRelations.push({
  814. // dbKey: selectedRelationTsKey,
  815. // tsKey: selectedRelationTsKey,
  816. // field: builtRelationSelectionField,
  817. // relationTableTsKey: relationTableTsName,
  818. // isJson: true,
  819. // selection: builtRelationJoin.selection,
  820. // });
  821. // // selection = builtTableFrom.selection.map((item) =>
  822. // // is(item.field, SQL.Aliased)
  823. // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
  824. // // : item
  825. // // );
  826. // // selectionForBuild = [{
  827. // // dbKey: '*',
  828. // // tsKey: '*',
  829. // // field: sql`${sql.identifier(tableAlias)}.*`,
  830. // // selection: [],
  831. // // isJson: false,
  832. // // relationTableTsKey: undefined,
  833. // // }];
  834. // // const newSelectionItem: (typeof selection)[number] = {
  835. // // dbKey: selectedRelationTsKey,
  836. // // tsKey: selectedRelationTsKey,
  837. // // field,
  838. // // relationTableTsKey: relationTableTsName,
  839. // // isJson: true,
  840. // // selection: builtRelationJoin.selection,
  841. // // };
  842. // // selection.push(newSelectionItem);
  843. // // selectionForBuild.push(newSelectionItem);
  844. // tableFrom = is(builtTableFrom.sql, PgTable)
  845. // ? builtTableFrom.sql
  846. // : new Subquery(builtTableFrom.sql, {}, tableAlias);
  847. // }
  848. // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
  849. // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
  850. // }
  851. // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
  852. // function prepareSelectedColumns() {
  853. // return selectedColumns.map((key) => ({
  854. // dbKey: tableConfig.columns[key]!.name,
  855. // tsKey: key,
  856. // field: tableConfig.columns[key] as PgColumn,
  857. // relationTableTsKey: undefined,
  858. // isJson: false,
  859. // selection: [],
  860. // }));
  861. // }
  862. // function prepareSelectedExtras() {
  863. // return selectedExtras.map((item) => ({
  864. // dbKey: item.value.fieldAlias,
  865. // tsKey: item.tsKey,
  866. // field: item.value,
  867. // relationTableTsKey: undefined,
  868. // isJson: false,
  869. // selection: [],
  870. // }));
  871. // }
  872. // if (isRoot) {
  873. // selection = [
  874. // ...prepareSelectedColumns(),
  875. // ...prepareSelectedExtras(),
  876. // ];
  877. // }
  878. // if (hasUserDefinedWhere || orderBy.length > 0) {
  879. // tableFrom = new Subquery(
  880. // this.buildSelectQuery({
  881. // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
  882. // fields: {},
  883. // fieldsFlat: selectionForBuild.map(({ field }) => ({
  884. // path: [],
  885. // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
  886. // })),
  887. // joins,
  888. // distinct,
  889. // }),
  890. // {},
  891. // tableAlias,
  892. // );
  893. // selectionForBuild = selection.map((item) =>
  894. // is(item.field, SQL.Aliased)
  895. // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
  896. // : item
  897. // );
  898. // joins = [];
  899. // distinct = undefined;
  900. // }
  901. // const result = this.buildSelectQuery({
  902. // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
  903. // fields: {},
  904. // fieldsFlat: selectionForBuild.map(({ field }) => ({
  905. // path: [],
  906. // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
  907. // })),
  908. // where,
  909. // limit,
  910. // offset,
  911. // joins,
  912. // orderBy,
  913. // distinct,
  914. // });
  915. // return {
  916. // tableTsKey: tableConfig.tsName,
  917. // sql: result,
  918. // selection,
  919. // };
  920. // }
  921. buildRelationalQueryWithoutPK({
  922. fullSchema,
  923. schema,
  924. tableNamesMap,
  925. table,
  926. tableConfig,
  927. queryConfig: config,
  928. tableAlias,
  929. nestedQueryRelation,
  930. joinOn
  931. }) {
  932. let selection = [];
  933. let limit, offset, orderBy = [], where;
  934. const joins = [];
  935. if (config === true) {
  936. const selectionEntries = Object.entries(tableConfig.columns);
  937. selection = selectionEntries.map(([key, value]) => ({
  938. dbKey: value.name,
  939. tsKey: key,
  940. field: (0, import_alias.aliasedTableColumn)(value, tableAlias),
  941. relationTableTsKey: void 0,
  942. isJson: false,
  943. selection: []
  944. }));
  945. } else {
  946. const aliasedColumns = Object.fromEntries(
  947. Object.entries(tableConfig.columns).map(([key, value]) => [key, (0, import_alias.aliasedTableColumn)(value, tableAlias)])
  948. );
  949. if (config.where) {
  950. const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0, import_relations.getOperators)()) : config.where;
  951. where = whereSql && (0, import_alias.mapColumnsInSQLToAlias)(whereSql, tableAlias);
  952. }
  953. const fieldsSelection = [];
  954. let selectedColumns = [];
  955. if (config.columns) {
  956. let isIncludeMode = false;
  957. for (const [field, value] of Object.entries(config.columns)) {
  958. if (value === void 0) {
  959. continue;
  960. }
  961. if (field in tableConfig.columns) {
  962. if (!isIncludeMode && value === true) {
  963. isIncludeMode = true;
  964. }
  965. selectedColumns.push(field);
  966. }
  967. }
  968. if (selectedColumns.length > 0) {
  969. selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
  970. }
  971. } else {
  972. selectedColumns = Object.keys(tableConfig.columns);
  973. }
  974. for (const field of selectedColumns) {
  975. const column = tableConfig.columns[field];
  976. fieldsSelection.push({ tsKey: field, value: column });
  977. }
  978. let selectedRelations = [];
  979. if (config.with) {
  980. selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
  981. }
  982. let extras;
  983. if (config.extras) {
  984. extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: import_sql2.sql }) : config.extras;
  985. for (const [tsKey, value] of Object.entries(extras)) {
  986. fieldsSelection.push({
  987. tsKey,
  988. value: (0, import_alias.mapColumnsInAliasedSQLToAlias)(value, tableAlias)
  989. });
  990. }
  991. }
  992. for (const { tsKey, value } of fieldsSelection) {
  993. selection.push({
  994. dbKey: (0, import_entity.is)(value, import_sql2.SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
  995. tsKey,
  996. field: (0, import_entity.is)(value, import_column.Column) ? (0, import_alias.aliasedTableColumn)(value, tableAlias) : value,
  997. relationTableTsKey: void 0,
  998. isJson: false,
  999. selection: []
  1000. });
  1001. }
  1002. let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0, import_relations.getOrderByOperators)()) : config.orderBy ?? [];
  1003. if (!Array.isArray(orderByOrig)) {
  1004. orderByOrig = [orderByOrig];
  1005. }
  1006. orderBy = orderByOrig.map((orderByValue) => {
  1007. if ((0, import_entity.is)(orderByValue, import_column.Column)) {
  1008. return (0, import_alias.aliasedTableColumn)(orderByValue, tableAlias);
  1009. }
  1010. return (0, import_alias.mapColumnsInSQLToAlias)(orderByValue, tableAlias);
  1011. });
  1012. limit = config.limit;
  1013. offset = config.offset;
  1014. for (const {
  1015. tsKey: selectedRelationTsKey,
  1016. queryConfig: selectedRelationConfigValue,
  1017. relation
  1018. } of selectedRelations) {
  1019. const normalizedRelation = (0, import_relations.normalizeRelation)(schema, tableNamesMap, relation);
  1020. const relationTableName = (0, import_table2.getTableUniqueName)(relation.referencedTable);
  1021. const relationTableTsName = tableNamesMap[relationTableName];
  1022. const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
  1023. const joinOn2 = (0, import_sql.and)(
  1024. ...normalizedRelation.fields.map(
  1025. (field2, i) => (0, import_sql.eq)(
  1026. (0, import_alias.aliasedTableColumn)(normalizedRelation.references[i], relationTableAlias),
  1027. (0, import_alias.aliasedTableColumn)(field2, tableAlias)
  1028. )
  1029. )
  1030. );
  1031. const builtRelation = this.buildRelationalQueryWithoutPK({
  1032. fullSchema,
  1033. schema,
  1034. tableNamesMap,
  1035. table: fullSchema[relationTableTsName],
  1036. tableConfig: schema[relationTableTsName],
  1037. queryConfig: (0, import_entity.is)(relation, import_relations.One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
  1038. tableAlias: relationTableAlias,
  1039. joinOn: joinOn2,
  1040. nestedQueryRelation: relation
  1041. });
  1042. const field = import_sql2.sql`${import_sql2.sql.identifier(relationTableAlias)}.${import_sql2.sql.identifier("data")}`.as(selectedRelationTsKey);
  1043. joins.push({
  1044. on: import_sql2.sql`true`,
  1045. table: new import_subquery.Subquery(builtRelation.sql, {}, relationTableAlias),
  1046. alias: relationTableAlias,
  1047. joinType: "left",
  1048. lateral: true
  1049. });
  1050. selection.push({
  1051. dbKey: selectedRelationTsKey,
  1052. tsKey: selectedRelationTsKey,
  1053. field,
  1054. relationTableTsKey: relationTableTsName,
  1055. isJson: true,
  1056. selection: builtRelation.selection
  1057. });
  1058. }
  1059. }
  1060. if (selection.length === 0) {
  1061. throw new import_errors.DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
  1062. }
  1063. let result;
  1064. where = (0, import_sql.and)(joinOn, where);
  1065. if (nestedQueryRelation) {
  1066. let field = import_sql2.sql`json_build_array(${import_sql2.sql.join(
  1067. selection.map(
  1068. ({ field: field2, tsKey, isJson }) => isJson ? import_sql2.sql`${import_sql2.sql.identifier(`${tableAlias}_${tsKey}`)}.${import_sql2.sql.identifier("data")}` : (0, import_entity.is)(field2, import_sql2.SQL.Aliased) ? field2.sql : field2
  1069. ),
  1070. import_sql2.sql`, `
  1071. )})`;
  1072. if ((0, import_entity.is)(nestedQueryRelation, import_relations.Many)) {
  1073. field = import_sql2.sql`coalesce(json_agg(${field}${orderBy.length > 0 ? import_sql2.sql` order by ${import_sql2.sql.join(orderBy, import_sql2.sql`, `)}` : void 0}), '[]'::json)`;
  1074. }
  1075. const nestedSelection = [{
  1076. dbKey: "data",
  1077. tsKey: "data",
  1078. field: field.as("data"),
  1079. isJson: true,
  1080. relationTableTsKey: tableConfig.tsName,
  1081. selection
  1082. }];
  1083. const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
  1084. if (needsSubquery) {
  1085. result = this.buildSelectQuery({
  1086. table: (0, import_alias.aliasedTable)(table, tableAlias),
  1087. fields: {},
  1088. fieldsFlat: [{
  1089. path: [],
  1090. field: import_sql2.sql.raw("*")
  1091. }],
  1092. where,
  1093. limit,
  1094. offset,
  1095. orderBy,
  1096. setOperators: []
  1097. });
  1098. where = void 0;
  1099. limit = void 0;
  1100. offset = void 0;
  1101. orderBy = [];
  1102. } else {
  1103. result = (0, import_alias.aliasedTable)(table, tableAlias);
  1104. }
  1105. result = this.buildSelectQuery({
  1106. table: (0, import_entity.is)(result, import_table.PgTable) ? result : new import_subquery.Subquery(result, {}, tableAlias),
  1107. fields: {},
  1108. fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
  1109. path: [],
  1110. field: (0, import_entity.is)(field2, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field2, tableAlias) : field2
  1111. })),
  1112. joins,
  1113. where,
  1114. limit,
  1115. offset,
  1116. orderBy,
  1117. setOperators: []
  1118. });
  1119. } else {
  1120. result = this.buildSelectQuery({
  1121. table: (0, import_alias.aliasedTable)(table, tableAlias),
  1122. fields: {},
  1123. fieldsFlat: selection.map(({ field }) => ({
  1124. path: [],
  1125. field: (0, import_entity.is)(field, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field, tableAlias) : field
  1126. })),
  1127. joins,
  1128. where,
  1129. limit,
  1130. offset,
  1131. orderBy,
  1132. setOperators: []
  1133. });
  1134. }
  1135. return {
  1136. tableTsKey: tableConfig.tsName,
  1137. sql: result,
  1138. selection
  1139. };
  1140. }
  1141. }
  1142. // Annotate the CommonJS export names for ESM import in node:
  1143. 0 && (module.exports = {
  1144. PgDialect
  1145. });
  1146. //# sourceMappingURL=dialect.cjs.map