sql.cjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 name2 in all)
  8. __defProp(target, name2, { get: all[name2], 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 sql_exports = {};
  20. __export(sql_exports, {
  21. FakePrimitiveParam: () => FakePrimitiveParam,
  22. Name: () => Name,
  23. Param: () => Param,
  24. Placeholder: () => Placeholder,
  25. SQL: () => SQL,
  26. StringChunk: () => StringChunk,
  27. View: () => View,
  28. fillPlaceholders: () => fillPlaceholders,
  29. getViewName: () => getViewName,
  30. isDriverValueEncoder: () => isDriverValueEncoder,
  31. isSQLWrapper: () => isSQLWrapper,
  32. isView: () => isView,
  33. name: () => name,
  34. noopDecoder: () => noopDecoder,
  35. noopEncoder: () => noopEncoder,
  36. noopMapper: () => noopMapper,
  37. param: () => param,
  38. placeholder: () => placeholder,
  39. sql: () => sql
  40. });
  41. module.exports = __toCommonJS(sql_exports);
  42. var import_entity = require("../entity.cjs");
  43. var import_enum = require("../pg-core/columns/enum.cjs");
  44. var import_subquery = require("../subquery.cjs");
  45. var import_tracing = require("../tracing.cjs");
  46. var import_view_common = require("../view-common.cjs");
  47. var import_column = require("../column.cjs");
  48. var import_table = require("../table.cjs");
  49. class FakePrimitiveParam {
  50. static [import_entity.entityKind] = "FakePrimitiveParam";
  51. }
  52. function isSQLWrapper(value) {
  53. return value !== null && value !== void 0 && typeof value.getSQL === "function";
  54. }
  55. function mergeQueries(queries) {
  56. const result = { sql: "", params: [] };
  57. for (const query of queries) {
  58. result.sql += query.sql;
  59. result.params.push(...query.params);
  60. if (query.typings?.length) {
  61. if (!result.typings) {
  62. result.typings = [];
  63. }
  64. result.typings.push(...query.typings);
  65. }
  66. }
  67. return result;
  68. }
  69. class StringChunk {
  70. static [import_entity.entityKind] = "StringChunk";
  71. value;
  72. constructor(value) {
  73. this.value = Array.isArray(value) ? value : [value];
  74. }
  75. getSQL() {
  76. return new SQL([this]);
  77. }
  78. }
  79. class SQL {
  80. constructor(queryChunks) {
  81. this.queryChunks = queryChunks;
  82. for (const chunk of queryChunks) {
  83. if ((0, import_entity.is)(chunk, import_table.Table)) {
  84. const schemaName = chunk[import_table.Table.Symbol.Schema];
  85. this.usedTables.push(
  86. schemaName === void 0 ? chunk[import_table.Table.Symbol.Name] : schemaName + "." + chunk[import_table.Table.Symbol.Name]
  87. );
  88. }
  89. }
  90. }
  91. static [import_entity.entityKind] = "SQL";
  92. /** @internal */
  93. decoder = noopDecoder;
  94. shouldInlineParams = false;
  95. /** @internal */
  96. usedTables = [];
  97. append(query) {
  98. this.queryChunks.push(...query.queryChunks);
  99. return this;
  100. }
  101. toQuery(config) {
  102. return import_tracing.tracer.startActiveSpan("drizzle.buildSQL", (span) => {
  103. const query = this.buildQueryFromSourceParams(this.queryChunks, config);
  104. span?.setAttributes({
  105. "drizzle.query.text": query.sql,
  106. "drizzle.query.params": JSON.stringify(query.params)
  107. });
  108. return query;
  109. });
  110. }
  111. buildQueryFromSourceParams(chunks, _config) {
  112. const config = Object.assign({}, _config, {
  113. inlineParams: _config.inlineParams || this.shouldInlineParams,
  114. paramStartIndex: _config.paramStartIndex || { value: 0 }
  115. });
  116. const {
  117. casing,
  118. escapeName,
  119. escapeParam,
  120. prepareTyping,
  121. inlineParams,
  122. paramStartIndex
  123. } = config;
  124. return mergeQueries(chunks.map((chunk) => {
  125. if ((0, import_entity.is)(chunk, StringChunk)) {
  126. return { sql: chunk.value.join(""), params: [] };
  127. }
  128. if ((0, import_entity.is)(chunk, Name)) {
  129. return { sql: escapeName(chunk.value), params: [] };
  130. }
  131. if (chunk === void 0) {
  132. return { sql: "", params: [] };
  133. }
  134. if (Array.isArray(chunk)) {
  135. const result = [new StringChunk("(")];
  136. for (const [i, p] of chunk.entries()) {
  137. result.push(p);
  138. if (i < chunk.length - 1) {
  139. result.push(new StringChunk(", "));
  140. }
  141. }
  142. result.push(new StringChunk(")"));
  143. return this.buildQueryFromSourceParams(result, config);
  144. }
  145. if ((0, import_entity.is)(chunk, SQL)) {
  146. return this.buildQueryFromSourceParams(chunk.queryChunks, {
  147. ...config,
  148. inlineParams: inlineParams || chunk.shouldInlineParams
  149. });
  150. }
  151. if ((0, import_entity.is)(chunk, import_table.Table)) {
  152. const schemaName = chunk[import_table.Table.Symbol.Schema];
  153. const tableName = chunk[import_table.Table.Symbol.Name];
  154. return {
  155. sql: schemaName === void 0 || chunk[import_table.IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
  156. params: []
  157. };
  158. }
  159. if ((0, import_entity.is)(chunk, import_column.Column)) {
  160. const columnName = casing.getColumnCasing(chunk);
  161. if (_config.invokeSource === "indexes") {
  162. return { sql: escapeName(columnName), params: [] };
  163. }
  164. const schemaName = chunk.table[import_table.Table.Symbol.Schema];
  165. return {
  166. sql: chunk.table[import_table.IsAlias] || schemaName === void 0 ? escapeName(chunk.table[import_table.Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[import_table.Table.Symbol.Name]) + "." + escapeName(columnName),
  167. params: []
  168. };
  169. }
  170. if ((0, import_entity.is)(chunk, View)) {
  171. const schemaName = chunk[import_view_common.ViewBaseConfig].schema;
  172. const viewName = chunk[import_view_common.ViewBaseConfig].name;
  173. return {
  174. sql: schemaName === void 0 || chunk[import_view_common.ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
  175. params: []
  176. };
  177. }
  178. if ((0, import_entity.is)(chunk, Param)) {
  179. if ((0, import_entity.is)(chunk.value, Placeholder)) {
  180. return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
  181. }
  182. const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
  183. if ((0, import_entity.is)(mappedValue, SQL)) {
  184. return this.buildQueryFromSourceParams([mappedValue], config);
  185. }
  186. if (inlineParams) {
  187. return { sql: this.mapInlineParam(mappedValue, config), params: [] };
  188. }
  189. let typings = ["none"];
  190. if (prepareTyping) {
  191. typings = [prepareTyping(chunk.encoder)];
  192. }
  193. return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
  194. }
  195. if ((0, import_entity.is)(chunk, Placeholder)) {
  196. return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
  197. }
  198. if ((0, import_entity.is)(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) {
  199. return { sql: escapeName(chunk.fieldAlias), params: [] };
  200. }
  201. if ((0, import_entity.is)(chunk, import_subquery.Subquery)) {
  202. if (chunk._.isWith) {
  203. return { sql: escapeName(chunk._.alias), params: [] };
  204. }
  205. return this.buildQueryFromSourceParams([
  206. new StringChunk("("),
  207. chunk._.sql,
  208. new StringChunk(") "),
  209. new Name(chunk._.alias)
  210. ], config);
  211. }
  212. if ((0, import_enum.isPgEnum)(chunk)) {
  213. if (chunk.schema) {
  214. return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
  215. }
  216. return { sql: escapeName(chunk.enumName), params: [] };
  217. }
  218. if (isSQLWrapper(chunk)) {
  219. if (chunk.shouldOmitSQLParens?.()) {
  220. return this.buildQueryFromSourceParams([chunk.getSQL()], config);
  221. }
  222. return this.buildQueryFromSourceParams([
  223. new StringChunk("("),
  224. chunk.getSQL(),
  225. new StringChunk(")")
  226. ], config);
  227. }
  228. if (inlineParams) {
  229. return { sql: this.mapInlineParam(chunk, config), params: [] };
  230. }
  231. return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
  232. }));
  233. }
  234. mapInlineParam(chunk, { escapeString }) {
  235. if (chunk === null) {
  236. return "null";
  237. }
  238. if (typeof chunk === "number" || typeof chunk === "boolean") {
  239. return chunk.toString();
  240. }
  241. if (typeof chunk === "string") {
  242. return escapeString(chunk);
  243. }
  244. if (typeof chunk === "object") {
  245. const mappedValueAsString = chunk.toString();
  246. if (mappedValueAsString === "[object Object]") {
  247. return escapeString(JSON.stringify(chunk));
  248. }
  249. return escapeString(mappedValueAsString);
  250. }
  251. throw new Error("Unexpected param value: " + chunk);
  252. }
  253. getSQL() {
  254. return this;
  255. }
  256. as(alias) {
  257. if (alias === void 0) {
  258. return this;
  259. }
  260. return new SQL.Aliased(this, alias);
  261. }
  262. mapWith(decoder) {
  263. this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
  264. return this;
  265. }
  266. inlineParams() {
  267. this.shouldInlineParams = true;
  268. return this;
  269. }
  270. /**
  271. * This method is used to conditionally include a part of the query.
  272. *
  273. * @param condition - Condition to check
  274. * @returns itself if the condition is `true`, otherwise `undefined`
  275. */
  276. if(condition) {
  277. return condition ? this : void 0;
  278. }
  279. }
  280. class Name {
  281. constructor(value) {
  282. this.value = value;
  283. }
  284. static [import_entity.entityKind] = "Name";
  285. brand;
  286. getSQL() {
  287. return new SQL([this]);
  288. }
  289. }
  290. function name(value) {
  291. return new Name(value);
  292. }
  293. function isDriverValueEncoder(value) {
  294. return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
  295. }
  296. const noopDecoder = {
  297. mapFromDriverValue: (value) => value
  298. };
  299. const noopEncoder = {
  300. mapToDriverValue: (value) => value
  301. };
  302. const noopMapper = {
  303. ...noopDecoder,
  304. ...noopEncoder
  305. };
  306. class Param {
  307. /**
  308. * @param value - Parameter value
  309. * @param encoder - Encoder to convert the value to a driver parameter
  310. */
  311. constructor(value, encoder = noopEncoder) {
  312. this.value = value;
  313. this.encoder = encoder;
  314. }
  315. static [import_entity.entityKind] = "Param";
  316. brand;
  317. getSQL() {
  318. return new SQL([this]);
  319. }
  320. }
  321. function param(value, encoder) {
  322. return new Param(value, encoder);
  323. }
  324. function sql(strings, ...params) {
  325. const queryChunks = [];
  326. if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
  327. queryChunks.push(new StringChunk(strings[0]));
  328. }
  329. for (const [paramIndex, param2] of params.entries()) {
  330. queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
  331. }
  332. return new SQL(queryChunks);
  333. }
  334. ((sql2) => {
  335. function empty() {
  336. return new SQL([]);
  337. }
  338. sql2.empty = empty;
  339. function fromList(list) {
  340. return new SQL(list);
  341. }
  342. sql2.fromList = fromList;
  343. function raw(str) {
  344. return new SQL([new StringChunk(str)]);
  345. }
  346. sql2.raw = raw;
  347. function join(chunks, separator) {
  348. const result = [];
  349. for (const [i, chunk] of chunks.entries()) {
  350. if (i > 0 && separator !== void 0) {
  351. result.push(separator);
  352. }
  353. result.push(chunk);
  354. }
  355. return new SQL(result);
  356. }
  357. sql2.join = join;
  358. function identifier(value) {
  359. return new Name(value);
  360. }
  361. sql2.identifier = identifier;
  362. function placeholder2(name2) {
  363. return new Placeholder(name2);
  364. }
  365. sql2.placeholder = placeholder2;
  366. function param2(value, encoder) {
  367. return new Param(value, encoder);
  368. }
  369. sql2.param = param2;
  370. })(sql || (sql = {}));
  371. ((SQL2) => {
  372. class Aliased {
  373. constructor(sql2, fieldAlias) {
  374. this.sql = sql2;
  375. this.fieldAlias = fieldAlias;
  376. }
  377. static [import_entity.entityKind] = "SQL.Aliased";
  378. /** @internal */
  379. isSelectionField = false;
  380. getSQL() {
  381. return this.sql;
  382. }
  383. /** @internal */
  384. clone() {
  385. return new Aliased(this.sql, this.fieldAlias);
  386. }
  387. }
  388. SQL2.Aliased = Aliased;
  389. })(SQL || (SQL = {}));
  390. class Placeholder {
  391. constructor(name2) {
  392. this.name = name2;
  393. }
  394. static [import_entity.entityKind] = "Placeholder";
  395. getSQL() {
  396. return new SQL([this]);
  397. }
  398. }
  399. function placeholder(name2) {
  400. return new Placeholder(name2);
  401. }
  402. function fillPlaceholders(params, values) {
  403. return params.map((p) => {
  404. if ((0, import_entity.is)(p, Placeholder)) {
  405. if (!(p.name in values)) {
  406. throw new Error(`No value for placeholder "${p.name}" was provided`);
  407. }
  408. return values[p.name];
  409. }
  410. if ((0, import_entity.is)(p, Param) && (0, import_entity.is)(p.value, Placeholder)) {
  411. if (!(p.value.name in values)) {
  412. throw new Error(`No value for placeholder "${p.value.name}" was provided`);
  413. }
  414. return p.encoder.mapToDriverValue(values[p.value.name]);
  415. }
  416. return p;
  417. });
  418. }
  419. const IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
  420. class View {
  421. static [import_entity.entityKind] = "View";
  422. /** @internal */
  423. [import_view_common.ViewBaseConfig];
  424. /** @internal */
  425. [IsDrizzleView] = true;
  426. constructor({ name: name2, schema, selectedFields, query }) {
  427. this[import_view_common.ViewBaseConfig] = {
  428. name: name2,
  429. originalName: name2,
  430. schema,
  431. selectedFields,
  432. query,
  433. isExisting: !query,
  434. isAlias: false
  435. };
  436. }
  437. getSQL() {
  438. return new SQL([this]);
  439. }
  440. }
  441. function isView(view) {
  442. return typeof view === "object" && view !== null && IsDrizzleView in view;
  443. }
  444. function getViewName(view) {
  445. return view[import_view_common.ViewBaseConfig].name;
  446. }
  447. import_column.Column.prototype.getSQL = function() {
  448. return new SQL([this]);
  449. };
  450. import_table.Table.prototype.getSQL = function() {
  451. return new SQL([this]);
  452. };
  453. import_subquery.Subquery.prototype.getSQL = function() {
  454. return new SQL([this]);
  455. };
  456. // Annotate the CommonJS export names for ESM import in node:
  457. 0 && (module.exports = {
  458. FakePrimitiveParam,
  459. Name,
  460. Param,
  461. Placeholder,
  462. SQL,
  463. StringChunk,
  464. View,
  465. fillPlaceholders,
  466. getViewName,
  467. isDriverValueEncoder,
  468. isSQLWrapper,
  469. isView,
  470. name,
  471. noopDecoder,
  472. noopEncoder,
  473. noopMapper,
  474. param,
  475. placeholder,
  476. sql
  477. });
  478. //# sourceMappingURL=sql.cjs.map