pqb 0.30.2 → 0.30.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29,8 +29,8 @@ const templateLiteralToSQL = (template, ctx, quotedAs) => {
29
29
  class RawSQL extends orchidCore.RawSQLBase {
30
30
  constructor(sql, values, type) {
31
31
  super(sql, values);
32
+ this.result = { value: type };
32
33
  if (type) {
33
- this.result = { value: type };
34
34
  Object.assign(this, type.operators);
35
35
  }
36
36
  }
@@ -836,102 +836,6 @@ const columnCode = (type, t, code, migration, data = type.data, skip) => {
836
836
  return code.length === 1 && typeof code[0] === "string" ? code[0] : code;
837
837
  };
838
838
 
839
- function simpleColumnToSQL(ctx, key, column, quotedAs) {
840
- if (!column)
841
- return `"${key}"`;
842
- const { data } = column;
843
- return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
844
- }
845
- function simpleExistingColumnToSQL(ctx, key, column, quotedAs) {
846
- const { data } = column;
847
- return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
848
- }
849
- const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
850
- var _a, _b, _c, _d, _e;
851
- const index = column.indexOf(".");
852
- if (index !== -1) {
853
- const table = column.slice(0, index);
854
- const key = column.slice(index + 1);
855
- if (key === "*") {
856
- if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
857
- return select ? `row_to_json("${table}".*)` : `"${table}".r`;
858
- }
859
- return column;
860
- }
861
- const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
862
- const quoted = `"${table}"`;
863
- const col = quoted === quotedAs ? shape[key] : (_d = (_c = data.joinedShapes) == null ? void 0 : _c[tableName]) == null ? void 0 : _d[key];
864
- if (col) {
865
- if (col.data.name) {
866
- return `"${tableName}"."${col.data.name}"`;
867
- }
868
- if (col.data.computed) {
869
- return `${col.data.computed.toSQL(ctx, quoted)}`;
870
- }
871
- return `"${tableName}"."${key}"`;
872
- }
873
- return `"${tableName}"."${key}"`;
874
- }
875
- if (!select && ((_e = data.joinedShapes) == null ? void 0 : _e[column])) {
876
- return `"${column}".r`;
877
- }
878
- return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
879
- };
880
- const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
881
- var _a, _b, _c, _d;
882
- const index = column.indexOf(".");
883
- if (index !== -1) {
884
- const table = column.slice(0, index);
885
- const key = column.slice(index + 1);
886
- if (key === "*") {
887
- if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
888
- return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
889
- }
890
- return column;
891
- }
892
- const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
893
- const quoted = `"${table}"`;
894
- const col2 = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
895
- if (col2) {
896
- if (col2.data.name && col2.data.name !== key) {
897
- return `"${tableName}"."${col2.data.name}" "${key}"`;
898
- }
899
- if (col2.data.computed) {
900
- return `${col2.data.computed.toSQL(ctx, quoted)} "${key}"`;
901
- }
902
- }
903
- return `"${tableName}"."${key}"`;
904
- }
905
- if (!select && ((_d = data.joinedShapes) == null ? void 0 : _d[column])) {
906
- return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
907
- }
908
- const col = data.shape[column];
909
- if (col) {
910
- if (col.data.name && col.data.name !== column) {
911
- return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}" "${column}"`;
912
- }
913
- if (col.data.computed) {
914
- return `${col.data.computed.toSQL(ctx, quotedAs)} "${column}"`;
915
- }
916
- }
917
- return `${quotedAs ? `${quotedAs}.` : ""}"${column}"`;
918
- };
919
- const ownColumnToSql = (data, column, quotedAs) => {
920
- var _a;
921
- const name = (_a = data.shape[column]) == null ? void 0 : _a.data.name;
922
- return `${quotedAs ? `${quotedAs}.` : ""}"${name || column}"${name && name !== column ? ` "${column}"` : ""}`;
923
- };
924
- const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
925
- return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
926
- };
927
- const quoteSchemaAndTable = (schema, table) => {
928
- return schema ? `"${schema}"."${table}"` : `"${table}"`;
929
- };
930
- const addValue = (values, value) => {
931
- values.push(value);
932
- return `$${values.length}`;
933
- };
934
-
935
839
  var __defProp$f = Object.defineProperty;
936
840
  var __defProps$7 = Object.defineProperties;
937
841
  var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
@@ -979,7 +883,7 @@ const make = (_op) => {
979
883
  const quoteValue$1 = (arg, ctx, quotedAs, jsonArray) => {
980
884
  if (arg && typeof arg === "object") {
981
885
  if (!jsonArray && Array.isArray(arg)) {
982
- return `(${arg.map((value) => addValue(ctx.values, value)).join(", ")})`;
886
+ return `(${arg.map((value) => orchidCore.addValue(ctx.values, value)).join(", ")})`;
983
887
  }
984
888
  if (orchidCore.isExpression(arg)) {
985
889
  return arg.toSQL(ctx, quotedAs);
@@ -988,7 +892,7 @@ const quoteValue$1 = (arg, ctx, quotedAs, jsonArray) => {
988
892
  return `(${arg.toSQL({ values: ctx.values }).text})`;
989
893
  }
990
894
  }
991
- return addValue(ctx.values, arg);
895
+ return orchidCore.addValue(ctx.values, arg);
992
896
  };
993
897
  const base = {
994
898
  equals: make(
@@ -1861,6 +1765,98 @@ const queryTypeWithLimitOne = {
1861
1765
  };
1862
1766
  const isQueryReturnsAll = (q) => !q.q.returnType || q.q.returnType === "all";
1863
1767
 
1768
+ function simpleColumnToSQL(ctx, key, column, quotedAs) {
1769
+ if (!column)
1770
+ return `"${key}"`;
1771
+ const { data } = column;
1772
+ return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
1773
+ }
1774
+ function simpleExistingColumnToSQL(ctx, key, column, quotedAs) {
1775
+ const { data } = column;
1776
+ return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
1777
+ }
1778
+ const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
1779
+ var _a, _b, _c, _d, _e;
1780
+ const index = column.indexOf(".");
1781
+ if (index !== -1) {
1782
+ const table = column.slice(0, index);
1783
+ const key = column.slice(index + 1);
1784
+ if (key === "*") {
1785
+ if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1786
+ return select ? `row_to_json("${table}".*)` : `"${table}".r`;
1787
+ }
1788
+ return column;
1789
+ }
1790
+ const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1791
+ const quoted = `"${table}"`;
1792
+ const col = quoted === quotedAs ? shape[key] : (_d = (_c = data.joinedShapes) == null ? void 0 : _c[tableName]) == null ? void 0 : _d[key];
1793
+ if (col) {
1794
+ if (col.data.name) {
1795
+ return `"${tableName}"."${col.data.name}"`;
1796
+ }
1797
+ if (col.data.computed) {
1798
+ return `${col.data.computed.toSQL(ctx, quoted)}`;
1799
+ }
1800
+ return `"${tableName}"."${key}"`;
1801
+ }
1802
+ return `"${tableName}"."${key}"`;
1803
+ }
1804
+ if (!select && ((_e = data.joinedShapes) == null ? void 0 : _e[column])) {
1805
+ return `"${column}".r`;
1806
+ }
1807
+ return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
1808
+ };
1809
+ const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
1810
+ var _a, _b, _c, _d;
1811
+ const index = column.indexOf(".");
1812
+ if (index !== -1) {
1813
+ const table = column.slice(0, index);
1814
+ const key = column.slice(index + 1);
1815
+ if (key === "*") {
1816
+ if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1817
+ return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
1818
+ }
1819
+ return column;
1820
+ }
1821
+ const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1822
+ const quoted = `"${table}"`;
1823
+ const col2 = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
1824
+ if (col2) {
1825
+ if (col2.data.name && col2.data.name !== key) {
1826
+ return `"${tableName}"."${col2.data.name}" "${key}"`;
1827
+ }
1828
+ if (col2.data.computed) {
1829
+ return `${col2.data.computed.toSQL(ctx, quoted)} "${key}"`;
1830
+ }
1831
+ }
1832
+ return `"${tableName}"."${key}"`;
1833
+ }
1834
+ if (!select && ((_d = data.joinedShapes) == null ? void 0 : _d[column])) {
1835
+ return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
1836
+ }
1837
+ const col = data.shape[column];
1838
+ if (col) {
1839
+ if (col.data.name && col.data.name !== column) {
1840
+ return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}" "${column}"`;
1841
+ }
1842
+ if (col.data.computed) {
1843
+ return `${col.data.computed.toSQL(ctx, quotedAs)} "${column}"`;
1844
+ }
1845
+ }
1846
+ return `${quotedAs ? `${quotedAs}.` : ""}"${column}"`;
1847
+ };
1848
+ const ownColumnToSql = (data, column, quotedAs) => {
1849
+ var _a;
1850
+ const name = (_a = data.shape[column]) == null ? void 0 : _a.data.name;
1851
+ return `${quotedAs ? `${quotedAs}.` : ""}"${name || column}"${name && name !== column ? ` "${column}"` : ""}`;
1852
+ };
1853
+ const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
1854
+ return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
1855
+ };
1856
+ const quoteSchemaAndTable = (schema, table) => {
1857
+ return schema ? `"${schema}"."${table}"` : `"${table}"`;
1858
+ };
1859
+
1864
1860
  const pushDistinctSql = (ctx, table, distinct, quotedAs) => {
1865
1861
  ctx.sql.push("DISTINCT");
1866
1862
  if (distinct.length) {
@@ -2028,13 +2024,23 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
2028
2024
  qb.q.and = qb.q.or = void 0;
2029
2025
  qb.q.isSubQuery = true;
2030
2026
  const res = resolveSubQueryCallback(qb, data);
2031
- const expr = res instanceof orchidCore.Expression ? res : res.q.expr;
2032
- if (!(res instanceof orchidCore.Expression) && res.q.expr) {
2033
- const q = joinSubQuery(table, res);
2034
- q.q.select = [expr];
2035
- ands.push(`(${makeSQL(q, ctx).text})`);
2027
+ if (orchidCore.isExpression(res)) {
2028
+ ands.push(`(${res.toSQL(ctx, quotedAs)})`);
2036
2029
  } else {
2037
- pushWhereToSql(ands, ctx, res, res.q, quotedAs, true);
2030
+ if (res.q.expr) {
2031
+ const q = joinSubQuery(table, res);
2032
+ q.q.select = [res.q.expr];
2033
+ ands.push(`(${makeSQL(q, ctx).text})`);
2034
+ } else {
2035
+ pushWhereToSql(
2036
+ ands,
2037
+ ctx,
2038
+ res,
2039
+ res.q,
2040
+ quotedAs,
2041
+ true
2042
+ );
2043
+ }
2038
2044
  }
2039
2045
  return;
2040
2046
  }
@@ -2090,10 +2096,10 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
2090
2096
  );
2091
2097
  const rightPath = item[3];
2092
2098
  ands.push(
2093
- `jsonb_path_query_first(${leftColumn}, ${addValue(
2099
+ `jsonb_path_query_first(${leftColumn}, ${orchidCore.addValue(
2094
2100
  ctx.values,
2095
2101
  leftPath
2096
- )}) = jsonb_path_query_first(${rightColumn}, ${addValue(
2102
+ )}) = jsonb_path_query_first(${rightColumn}, ${orchidCore.addValue(
2097
2103
  ctx.values,
2098
2104
  rightPath
2099
2105
  )})`
@@ -2212,9 +2218,15 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
2212
2218
  }
2213
2219
  }
2214
2220
  } else {
2215
- ands.push(
2216
- `${columnToSql(ctx, query, query.shape, key, quotedAs)} ${value === null ? "IS NULL" : `= ${addValue(ctx.values, value)}`}`
2217
- );
2221
+ const column = columnToSql(ctx, query, query.shape, key, quotedAs);
2222
+ if (typeof value === "function") {
2223
+ const expr = value(table);
2224
+ ands.push(`${column} = ${expr.toSQL(ctx, quotedAs)}`);
2225
+ } else {
2226
+ ands.push(
2227
+ `${column} ${value === null ? "IS NULL" : `= ${orchidCore.addValue(ctx.values, value)}`}`
2228
+ );
2229
+ }
2218
2230
  }
2219
2231
  }
2220
2232
  };
@@ -2226,7 +2238,7 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
2226
2238
  let value;
2227
2239
  if (Array.isArray(arg.values)) {
2228
2240
  value = `${arg.values.map(
2229
- multiple ? (arr) => `(${arr.map((value2) => addValue(ctx.values, value2)).join(", ")})` : (arr) => `${arr.map((value2) => addValue(ctx.values, value2)).join(", ")}`
2241
+ multiple ? (arr) => `(${arr.map((value2) => orchidCore.addValue(ctx.values, value2)).join(", ")})` : (arr) => `${arr.map((value2) => orchidCore.addValue(ctx.values, value2)).join(", ")}`
2230
2242
  ).join(", ")}`;
2231
2243
  value = `(${value})`;
2232
2244
  } else if (orchidCore.isExpression(arg.values)) {
@@ -3690,7 +3702,6 @@ class From {
3690
3702
  * ```ts
3691
3703
  * const value = 123;
3692
3704
  * db.table.fromSql`value = ${value}`;
3693
- * db.table.fromSql(db.table.sql`value = ${value}`);
3694
3705
  * ```
3695
3706
  *
3696
3707
  * @param args - SQL expression
@@ -3760,7 +3771,7 @@ const jsonToSql = (ctx, table, item, values, quotedAs) => {
3760
3771
  column,
3761
3772
  values,
3762
3773
  quotedAs
3763
- )}, ${addValue(values, path)}${(options == null ? void 0 : options.vars) ? `, ${addValue(values, options.vars)}` : ""}${(options == null ? void 0 : options.silent) ? ", true" : ""})`;
3774
+ )}, ${orchidCore.addValue(values, path)}${(options == null ? void 0 : options.vars) ? `, ${orchidCore.addValue(values, options.vars)}` : ""}${(options == null ? void 0 : options.silent) ? ", true" : ""})`;
3764
3775
  } else if (json[0] === "set") {
3765
3776
  const [, , , column, path, value, options] = json;
3766
3777
  return `jsonb_set(${jsonColumnOrMethodToSql(
@@ -3769,7 +3780,7 @@ const jsonToSql = (ctx, table, item, values, quotedAs) => {
3769
3780
  column,
3770
3781
  values,
3771
3782
  quotedAs
3772
- )}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.createIfMissing) ? ", true" : ""})`;
3783
+ )}, '{${path.join(", ")}}', ${orchidCore.addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.createIfMissing) ? ", true" : ""})`;
3773
3784
  } else if (json[0] === "insert") {
3774
3785
  const [, , , column, path, value, options] = json;
3775
3786
  return `jsonb_insert(${jsonColumnOrMethodToSql(
@@ -3778,7 +3789,7 @@ const jsonToSql = (ctx, table, item, values, quotedAs) => {
3778
3789
  column,
3779
3790
  values,
3780
3791
  quotedAs
3781
- )}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.insertAfter) ? ", true" : ""})`;
3792
+ )}, '{${path.join(", ")}}', ${orchidCore.addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.insertAfter) ? ", true" : ""})`;
3782
3793
  } else if (json[0] === "remove") {
3783
3794
  const [, , , column, path] = json;
3784
3795
  return `${jsonColumnOrMethodToSql(
@@ -3911,7 +3922,7 @@ const pushSubQuerySql = (ctx, query, as, list, quotedAs) => {
3911
3922
  const coalesce = (ctx, query, sql, quotedAs) => {
3912
3923
  const { coalesceValue } = query.q;
3913
3924
  if (coalesceValue !== void 0) {
3914
- const value = orchidCore.isExpression(coalesceValue) ? coalesceValue.toSQL(ctx, quotedAs) : addValue(ctx.values, coalesceValue);
3925
+ const value = orchidCore.isExpression(coalesceValue) ? coalesceValue.toSQL(ctx, quotedAs) : orchidCore.addValue(ctx.values, coalesceValue);
3915
3926
  return `COALESCE(${sql}, ${value})`;
3916
3927
  }
3917
3928
  return sql;
@@ -3941,7 +3952,7 @@ const addOrder = (ctx, data, column, quotedAs, dir) => {
3941
3952
  if ((_a = data.sources) == null ? void 0 : _a[column]) {
3942
3953
  const search = data.sources[column];
3943
3954
  const order = dir || (!search.order || search.order === true ? orchidCore.emptyObject : search.order);
3944
- return `${order.coverDensity ? "ts_rank_cd" : "ts_rank"}(${order.weights ? `${addValue(ctx.values, `{${order.weights}}`)}, ` : ""}${search.vectorSQL}, "${column}"${order.normalization !== void 0 ? `, ${addValue(ctx.values, order.normalization)}` : ""}) ${order.dir || "DESC"}`;
3955
+ return `${order.coverDensity ? "ts_rank_cd" : "ts_rank"}(${order.weights ? `${orchidCore.addValue(ctx.values, `{${order.weights}}`)}, ` : ""}${search.vectorSQL}, "${column}"${order.normalization !== void 0 ? `, ${orchidCore.addValue(ctx.values, order.normalization)}` : ""}) ${order.dir || "DESC"}`;
3945
3956
  }
3946
3957
  return `${columnToSql(ctx, data, data.shape, column, quotedAs)} ${dir || "ASC"}`;
3947
3958
  };
@@ -4093,7 +4104,7 @@ const fromToSql = (ctx, data, from, quotedAs) => {
4093
4104
  };
4094
4105
  const getSearchLang = (ctx, data, source, quotedAs) => {
4095
4106
  var _a;
4096
- return (_a = source.langSQL) != null ? _a : source.langSQL = "languageColumn" in source ? columnToSql(ctx, data, data.shape, source.languageColumn, quotedAs) : orchidCore.isRawSQL(source.language) ? source.language.toSQL(ctx) : addValue(ctx.values, source.language || data.language || "english");
4107
+ return (_a = source.langSQL) != null ? _a : source.langSQL = "languageColumn" in source ? columnToSql(ctx, data, data.shape, source.languageColumn, quotedAs) : orchidCore.isRawSQL(source.language) ? source.language.toSQL(ctx) : orchidCore.addValue(ctx.values, source.language || data.language || "english");
4097
4108
  };
4098
4109
  const getSearchText = (ctx, data, source, quotedAs, forHeadline) => {
4099
4110
  let sql = source.textSQL;
@@ -4119,7 +4130,7 @@ const getSearchText = (ctx, data, source, quotedAs, forHeadline) => {
4119
4130
  sql = columnToSql(ctx, data, data.shape, source.vector, quotedAs);
4120
4131
  } else {
4121
4132
  if (typeof source.text === "string") {
4122
- sql = addValue(ctx.values, source.text);
4133
+ sql = orchidCore.addValue(ctx.values, source.text);
4123
4134
  } else {
4124
4135
  sql = source.text.toSQL(ctx, quotedAs);
4125
4136
  }
@@ -4135,7 +4146,7 @@ const getTsVector = (ctx, data, lang, source, quotedAs) => {
4135
4146
  let tsVector = "";
4136
4147
  let i = 0;
4137
4148
  for (const key in source.in) {
4138
- tsVector = (tsVector ? `${tsVector} || ` : "") + `setweight(to_tsvector(${lang}, ${text[i++]}), ${addValue(
4149
+ tsVector = (tsVector ? `${tsVector} || ` : "") + `setweight(to_tsvector(${lang}, ${text[i++]}), ${orchidCore.addValue(
4139
4150
  ctx.values,
4140
4151
  source.in[key]
4141
4152
  )})`;
@@ -4198,7 +4209,7 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
4198
4209
  if (orchidCore.isExpression(values)) {
4199
4210
  let valuesSql = values.toSQL(ctx, quotedAs);
4200
4211
  if (runtimeDefaults) {
4201
- valuesSql += `, ${runtimeDefaults.map((fn) => addValue(ctx.values, fn())).join(", ")}`;
4212
+ valuesSql += `, ${runtimeDefaults.map((fn) => orchidCore.addValue(ctx.values, fn())).join(", ")}`;
4202
4213
  }
4203
4214
  ctx.sql.push(`VALUES (${valuesSql})`);
4204
4215
  } else {
@@ -4208,7 +4219,7 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
4208
4219
  sql = values.map(
4209
4220
  (raw) => (
4210
4221
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4211
- `(${raw.toSQL(ctx, quotedAs)}, ${runtimeDefaults.map((fn) => addValue(v, fn())).join(", ")})`
4222
+ `(${raw.toSQL(ctx, quotedAs)}, ${runtimeDefaults.map((fn) => orchidCore.addValue(v, fn())).join(", ")})`
4212
4223
  )
4213
4224
  ).join(", ");
4214
4225
  } else {
@@ -4288,7 +4299,7 @@ const pushInsertSql = (ctx, q, query, quotedAs) => {
4288
4299
  const arr = [];
4289
4300
  for (const key in set) {
4290
4301
  arr.push(
4291
- `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${addValue(
4302
+ `"${((_d = shape[key]) == null ? void 0 : _d.data.name) || key}" = ${orchidCore.addValue(
4292
4303
  ctx.values,
4293
4304
  set[key]
4294
4305
  )}`
@@ -4322,11 +4333,11 @@ const encodeRow = (ctx, q, QueryClass, row, runtimeDefaults, quotedAs) => {
4322
4333
  return `(${joinSubQuery(q, value).toSQL(ctx).text})`;
4323
4334
  }
4324
4335
  }
4325
- return value === void 0 ? "DEFAULT" : addValue(ctx.values, value);
4336
+ return value === void 0 ? "DEFAULT" : orchidCore.addValue(ctx.values, value);
4326
4337
  });
4327
4338
  if (runtimeDefaults) {
4328
4339
  for (const fn of runtimeDefaults) {
4329
- arr.push(addValue(ctx.values, fn()));
4340
+ arr.push(orchidCore.addValue(ctx.values, fn()));
4330
4341
  }
4331
4342
  }
4332
4343
  return arr.join(", ");
@@ -4442,10 +4453,10 @@ const processValue = (ctx, table, QueryClass, key, value, quotedAs) => {
4442
4453
  } else if (value instanceof QueryClass) {
4443
4454
  return `(${joinSubQuery(table, value).toSQL(ctx).text})`;
4444
4455
  } else if ("op" in value && "arg" in value) {
4445
- return `"${table.q.shape[key].data.name || key}" ${value.op} ${addValue(ctx.values, value.arg)}`;
4456
+ return `"${table.q.shape[key].data.name || key}" ${value.op} ${orchidCore.addValue(ctx.values, value.arg)}`;
4446
4457
  }
4447
4458
  }
4448
- return addValue(ctx.values, value);
4459
+ return orchidCore.addValue(ctx.values, value);
4449
4460
  };
4450
4461
 
4451
4462
  const pushDeleteSql = (ctx, table, query, quotedAs) => {
@@ -4510,14 +4521,14 @@ const pushTruncateSql = (ctx, table, query) => {
4510
4521
  const pushColumnInfoSql = (ctx, table, query) => {
4511
4522
  var _a;
4512
4523
  ctx.sql.push(
4513
- `SELECT * FROM information_schema.columns WHERE table_name = ${addValue(
4524
+ `SELECT * FROM information_schema.columns WHERE table_name = ${orchidCore.addValue(
4514
4525
  ctx.values,
4515
4526
  table.table
4516
4527
  )} AND table_catalog = current_database() AND table_schema = ${query.schema || "current_schema()"}`
4517
4528
  );
4518
4529
  if (query.column) {
4519
4530
  ctx.sql.push(
4520
- `AND column_name = ${addValue(
4531
+ `AND column_name = ${orchidCore.addValue(
4521
4532
  ctx.values,
4522
4533
  ((_a = table.q.shape[query.column]) == null ? void 0 : _a.data.name) || query.column
4523
4534
  )}`
@@ -4711,7 +4722,7 @@ const makeSQL = (table, options) => {
4711
4722
  sql.push(`WINDOW ${window.join(", ")}`);
4712
4723
  }
4713
4724
  if (query.union) {
4714
- query.union.forEach((item) => {
4725
+ for (const item of query.union) {
4715
4726
  let itemSql;
4716
4727
  if (orchidCore.isExpression(item.arg)) {
4717
4728
  itemSql = item.arg.toSQL(ctx, quotedAs);
@@ -4720,14 +4731,14 @@ const makeSQL = (table, options) => {
4720
4731
  itemSql = argSql.text;
4721
4732
  }
4722
4733
  sql.push(`${item.kind} ${item.wrap ? `(${itemSql})` : itemSql}`);
4723
- });
4734
+ }
4724
4735
  }
4725
4736
  if (query.order) {
4726
4737
  pushOrderBySql(ctx, query, quotedAs, query.order);
4727
4738
  }
4728
4739
  pushLimitSQL(sql, values, query);
4729
4740
  if (query.offset) {
4730
- sql.push(`OFFSET ${addValue(values, query.offset)}`);
4741
+ sql.push(`OFFSET ${orchidCore.addValue(values, query.offset)}`);
4731
4742
  }
4732
4743
  if (query.for) {
4733
4744
  sql.push("FOR", query.for.type);
@@ -4748,7 +4759,7 @@ function pushLimitSQL(sql, values, q) {
4748
4759
  if (queryTypeWithLimitOne[q.returnType]) {
4749
4760
  sql.push(`LIMIT 1`);
4750
4761
  } else if (q.limit) {
4751
- sql.push(`LIMIT ${addValue(values, q.limit)}`);
4762
+ sql.push(`LIMIT ${orchidCore.addValue(values, q.limit)}`);
4752
4763
  }
4753
4764
  }
4754
4765
  }
@@ -5362,7 +5373,7 @@ class FnExpression extends orchidCore.Expression {
5362
5373
  for (const key in pairs) {
5363
5374
  args.push(
5364
5375
  // ::text is needed to bypass "could not determine data type of parameter" postgres error
5365
- `${addValue(values, key)}::text, ${rawOrColumnToSql(
5376
+ `${orchidCore.addValue(values, key)}::text, ${rawOrColumnToSql(
5366
5377
  ctx,
5367
5378
  this.q,
5368
5379
  pairs[key],
@@ -5372,7 +5383,7 @@ class FnExpression extends orchidCore.Expression {
5372
5383
  }
5373
5384
  return args.join(", ");
5374
5385
  } else {
5375
- return addValue(values, arg.value);
5386
+ return orchidCore.addValue(values, arg.value);
5376
5387
  }
5377
5388
  }).join(", ")
5378
5389
  );
@@ -5414,7 +5425,8 @@ class FnExpression extends orchidCore.Expression {
5414
5425
  }
5415
5426
  }
5416
5427
  function makeFnExpression(self, type, fn, args, options) {
5417
- const q = self.clone();
5428
+ const q = extendQuery(self, type.operators);
5429
+ q.baseQuery.type = orchidCore.ExpressionTypeMethod.prototype.type;
5418
5430
  new FnExpression(
5419
5431
  q,
5420
5432
  fn,
@@ -5436,49 +5448,6 @@ nullableInt.parseItem = nullableInt.parseFn = (input) => input === null ? null :
5436
5448
  const nullableFloat = new RealColumn(defaultSchemaConfig);
5437
5449
  nullableFloat.parseItem = nullableFloat.parseFn = (input) => input === null ? null : parseFloat(input);
5438
5450
  class AggregateMethods {
5439
- /**
5440
- * `fn` allows to call an arbitrary SQL function.
5441
- *
5442
- * For example, calling `sqrt` function to get a square root from some numeric column:
5443
- *
5444
- * ```ts
5445
- * const q = await User.select({
5446
- * // todo: use type callback instead of generic type
5447
- * sqrt: (q) => q.fn<number>('sqrt', ['numericColumn']),
5448
- * }).take();
5449
- *
5450
- * q.sqrt; // has type `number` just as provided
5451
- * ```
5452
- *
5453
- * If this is an aggregate function, you can specify aggregation options via third parameter.
5454
- *
5455
- * Forth parameter is for runtime column type. When specified, allows to chain the function with the column operators:
5456
- *
5457
- * ```ts
5458
- * const q = await User.select({
5459
- * // chain `sqrt("numericColumn")` with the "greater than 5"
5460
- * sqrtIsGreaterThan5: (q) => q.fn('sqrt', ['numericColumn'], {}, (t) => t.float()).gt(5),
5461
- * }).take();
5462
- *
5463
- * // Return type is boolean | null
5464
- * // todo: it should be just boolean if the column is not nullable, but for now it's always nullable
5465
- * q.sqrtIsGreaterThan5
5466
- * ```
5467
- *
5468
- * @param fn
5469
- * @param args
5470
- * @param options
5471
- * @param type
5472
- */
5473
- fn(fn, args, options, type) {
5474
- return makeFnExpression(
5475
- this,
5476
- (type == null ? void 0 : type(this.columnTypes)) || orchidCore.emptyObject,
5477
- fn,
5478
- args,
5479
- options
5480
- );
5481
- }
5482
5451
  /**
5483
5452
  * Use `exists()` to check if there is at least one record-matching condition.
5484
5453
  *
@@ -5823,7 +5792,7 @@ class AggregateMethods {
5823
5792
  * // select a column with alias
5824
5793
  * nameAlias: 'name',
5825
5794
  * // select raw SQL with alias
5826
- * foo: db.table.sql<string>`"bar" || "baz"`,
5795
+ * foo: sql<string>`"bar" || "baz"`,
5827
5796
  * },
5828
5797
  * aggregateOptions,
5829
5798
  * );
@@ -5833,7 +5802,7 @@ class AggregateMethods {
5833
5802
  * object: (q) =>
5834
5803
  * q.jsonObjectAgg({
5835
5804
  * nameAlias: 'name',
5836
- * foo: db.table.sql<string>`"bar" || "baz"`,
5805
+ * foo: sql<string>`"bar" || "baz"`,
5837
5806
  * }),
5838
5807
  * });
5839
5808
  * ```
@@ -6305,7 +6274,7 @@ class Create {
6305
6274
  *
6306
6275
  * await db.table.create({
6307
6276
  * // raw SQL
6308
- * column1: db.table.sql`'John' | 'Doe'`,
6277
+ * column1: sql`'John' || ' ' || 'Doe'`,
6309
6278
  *
6310
6279
  * // query that returns a single value
6311
6280
  * // returning multiple values will result in Postgres error
@@ -6368,7 +6337,7 @@ class Create {
6368
6337
  * ```ts
6369
6338
  * const oneRecord = await db.table.createRaw({
6370
6339
  * columns: ['name', 'amount'],
6371
- * values: db.table.sql`'name', random()`,
6340
+ * values: sql`'name', random()`,
6372
6341
  * });
6373
6342
  * ```
6374
6343
  *
@@ -6397,7 +6366,7 @@ class Create {
6397
6366
  * ```ts
6398
6367
  * const manyRecords = await db.table.createManyRaw({
6399
6368
  * columns: ['name', 'amount'],
6400
- * values: [db.table.sql`'one', 2`, db.table.sql`'three', 4`],
6369
+ * values: [sql`'one', 2`, sql`'three', 4`],
6401
6370
  * });
6402
6371
  * ```
6403
6372
  *
@@ -6551,11 +6520,11 @@ class Create {
6551
6520
  * // raw SQL expression:
6552
6521
  * db.table
6553
6522
  * .create(data)
6554
- * .onConfict(db.table.sql`(email) where condition`)
6523
+ * .onConfict(sql`(email) where condition`)
6555
6524
  * .merge();
6556
6525
  * ```
6557
6526
  *
6558
- * You can use the db.table.sql function in onConflict.
6527
+ * You can use the `sql` function exported from your `BaseTable` file in onConflict.
6559
6528
  * It can be useful to specify a condition when you have a partial index:
6560
6529
  *
6561
6530
  * ```ts
@@ -6566,7 +6535,7 @@ class Create {
6566
6535
  * active: true,
6567
6536
  * })
6568
6537
  * // ignore only when having conflicting email and when active is true.
6569
- * .onConflict(db.table.sql`(email) where active`)
6538
+ * .onConflict(sql`(email) where active`)
6570
6539
  * .ignore();
6571
6540
  * ```
6572
6541
  *
@@ -6666,7 +6635,7 @@ class OnConflictQueryBuilder {
6666
6635
  * db.table
6667
6636
  * .create(data)
6668
6637
  * .onConflict()
6669
- * .set(db.table.sql`raw SQL expression`);
6638
+ * .set(sql`raw SQL expression`);
6670
6639
  *
6671
6640
  * // update records only on certain conditions
6672
6641
  * db.table
@@ -6840,16 +6809,20 @@ class For {
6840
6809
 
6841
6810
  class QueryGet {
6842
6811
  /**
6843
- * `.get` returns a single value, it will add `LIMIT 1` to the query, and accepts a column name or a raw expression.
6844
- * It will throw `NotFoundError` when not found.
6812
+ * `.get` returns a single value, adds `LIMIT 1` to the query, and accepts a column name or a raw SQL expression.
6813
+ *
6814
+ * `get` throws a `NotFoundError` when not found, and `getOptional` returns `undefined`.
6845
6815
  *
6846
6816
  * ```ts
6847
6817
  * import { NumberColumn } from 'orchid-orm';
6818
+ * import { sql } from './baseTable';
6848
6819
  *
6849
6820
  * const firstName: string = await db.table.get('name');
6850
6821
  *
6851
- * const rawResult: number = await db.table.get(
6852
- * db.table.sql((t) => t.integer())`1 + 1`,
6822
+ * const rawResult: number = await db.table.get(sql((t) => t.integer())`1 + 1`);
6823
+ *
6824
+ * const firstNameOptional: string | undefined = await db.table.getOptional(
6825
+ * 'name',
6853
6826
  * );
6854
6827
  * ```
6855
6828
  *
@@ -6937,7 +6910,7 @@ class Having {
6937
6910
  * Provide SQL expression for the `HAVING` SQL statement:
6938
6911
  *
6939
6912
  * ```ts
6940
- * db.table.having`count(*) >= ${10}`;
6913
+ * db.table.havingSql`count(*) >= ${10}`;
6941
6914
  * ```
6942
6915
  *
6943
6916
  * @param args - SQL expression
@@ -7451,7 +7424,8 @@ class Join {
7451
7424
  * ```ts
7452
7425
  * db.user.join(
7453
7426
  * db.message,
7454
- * db.user.sql`lower("message"."text") = lower("user"."name")`,
7427
+ * // `sql` can be imported from your `BaseTable` file
7428
+ * sql`lower("message"."text") = lower("user"."name")`,
7455
7429
  * );
7456
7430
  * ```
7457
7431
  *
@@ -7460,16 +7434,16 @@ class Join {
7460
7434
  * ```ts
7461
7435
  * db.user.join(
7462
7436
  * db.message,
7463
- * db.user.sql`lower("message"."text")`,
7464
- * db.user.sql`lower("user"."name")`,
7437
+ * sql`lower("message"."text")`,
7438
+ * sql`lower("user"."name")`,
7465
7439
  * );
7466
7440
  *
7467
7441
  * // with operator:
7468
7442
  * db.user.join(
7469
7443
  * db.message,
7470
- * db.user.sql`lower("message"."text")`,
7444
+ * sql`lower("message"."text")`,
7471
7445
  * '!=',
7472
- * db.user.sql`lower("user"."name")`,
7446
+ * sql`lower("user"."name")`,
7473
7447
  * );
7474
7448
  * ```
7475
7449
  *
@@ -7483,7 +7457,7 @@ class Join {
7483
7457
  * 'message.userId': 'user.id',
7484
7458
  *
7485
7459
  * // value can be a raw SQL expression:
7486
- * text: db.user.sql`lower("user"."name")`,
7460
+ * text: sql`lower("user"."name")`,
7487
7461
  * });
7488
7462
  * ```
7489
7463
  *
@@ -8273,7 +8247,7 @@ class With {
8273
8247
  * id: columnTypes.integer(),
8274
8248
  * name: columnTypes.text(3, 100),
8275
8249
  * },
8276
- * db.table.sql`SELECT id, name FROM "someTable"`,
8250
+ * sql`SELECT id, name FROM "someTable"`,
8277
8251
  * );
8278
8252
  *
8279
8253
  * // accepts query:
@@ -8281,7 +8255,7 @@ class With {
8281
8255
  *
8282
8256
  * // accepts a callback for a query builder:
8283
8257
  * db.table.with('alias', (qb) =>
8284
- * qb.select({ one: db.table.sql`1`.type((t) => t.integer()) }),
8258
+ * qb.select({ one: sql`1`.type((t) => t.integer()) }),
8285
8259
  * );
8286
8260
  *
8287
8261
  * // All mentioned forms can accept options as a second argument:
@@ -8333,7 +8307,7 @@ class Union {
8333
8307
  * SomeTable.select('id', 'name').union(
8334
8308
  * [
8335
8309
  * OtherTable.select('id', 'name'),
8336
- * SomeTable.sql`SELECT id, name FROM "thirdTable"`,
8310
+ * sql`SELECT id, name FROM "thirdTable"`,
8337
8311
  * ],
8338
8312
  * true, // optional wrap parameter
8339
8313
  * );
@@ -8528,7 +8502,13 @@ class Where {
8528
8502
  * },
8529
8503
  *
8530
8504
  * // where column equals to raw SQL
8531
- * column: db.table.sql`sql expression`,
8505
+ * // import `sql` from your `BaseTable`
8506
+ * column: sql`sql expression`,
8507
+ * // or use `(q) => q.sql` for the same
8508
+ * column2: (q) => q.sql`sql expression`,
8509
+ *
8510
+ * // reference other columns in such a way:
8511
+ * firstName: (q) => q.ref('lastName'),
8532
8512
  * });
8533
8513
  * ```
8534
8514
  *
@@ -8577,12 +8557,7 @@ class Where {
8577
8557
  * `where` supports raw SQL:
8578
8558
  *
8579
8559
  * ```ts
8580
- * db.table.where(db.table.sql`a = b`);
8581
- *
8582
- * // or
8583
- * import { raw } from 'orchid-orm';
8584
- *
8585
- * db.table.where(raw`a = b`);
8560
+ * db.table.where(sql`a = b`);
8586
8561
  * ```
8587
8562
  *
8588
8563
  * `where` can accept a callback with a specific query builder containing all "where" methods such as `where`, `orWhere`, `whereNot`, `whereIn`, `whereExists`:
@@ -8603,7 +8578,7 @@ class Where {
8603
8578
  * db.table.where(
8604
8579
  * { id: 1 },
8605
8580
  * db.table.where({ name: 'John' }),
8606
- * db.table.sql`a = b`,
8581
+ * sql`a = b`,
8607
8582
  * );
8608
8583
  * ```
8609
8584
  *
@@ -8716,8 +8691,6 @@ class Where {
8716
8691
  * All column operators can take a value of the same type as the column, a sub-query, or a raw SQL expression:
8717
8692
  *
8718
8693
  * ```ts
8719
- * import { sql } from 'orchid-orm';
8720
- *
8721
8694
  * db.table.where({
8722
8695
  * numericColumn: {
8723
8696
  * // lower than 5
@@ -8766,7 +8739,7 @@ class Where {
8766
8739
  * // WHERE "column" IN (SELECT "column" FROM "otherTable")
8767
8740
  * in: OtherTable.select('column'),
8768
8741
  *
8769
- * in: db.table.sql`('a', 'b')`,
8742
+ * in: sql`('a', 'b')`,
8770
8743
  * },
8771
8744
  * });
8772
8745
  * ```
@@ -8813,7 +8786,7 @@ class Where {
8813
8786
  * between: [1, 10],
8814
8787
  *
8815
8788
  * // sub-query and raw SQL expression
8816
- * between: [OtherTable.select('column').take(), db.table.sql`2 + 2`],
8789
+ * between: [OtherTable.select('column').take(), sql`2 + 2`],
8817
8790
  * },
8818
8791
  * });
8819
8792
  * ```
@@ -8905,15 +8878,7 @@ class Where {
8905
8878
  * Use a custom SQL expression in `WHERE` statement:
8906
8879
  *
8907
8880
  * ```ts
8908
- * db.table.where`a = b`;
8909
- *
8910
- * // or
8911
- * db.table.where(db.table.sql`a = b`);
8912
- *
8913
- * // or
8914
- * import { raw } from 'orchid-orm';
8915
- *
8916
- * db.table.where(raw`a = b`);
8881
+ * db.table.whereSql`a = b`;
8917
8882
  * ```
8918
8883
  *
8919
8884
  * @param args - SQL expression
@@ -8946,10 +8911,10 @@ class Where {
8946
8911
  );
8947
8912
  }
8948
8913
  /**
8949
- * `whereNot` version accepting SQL expression:
8914
+ * `whereNotSql` is a version of `whereNot` accepting SQL expression:
8950
8915
  *
8951
8916
  * ```ts
8952
- * db.table.whereNot`sql expression`
8917
+ * db.table.whereNotSql`sql expression`
8953
8918
  * ```
8954
8919
  *
8955
8920
  * @param args - SQL expression
@@ -9026,7 +8991,7 @@ class Where {
9026
8991
  * It supports raw SQL expression:
9027
8992
  *
9028
8993
  * ```ts
9029
- * db.table.whereIn(['id', 'name'], db.table.sql`((1, 'one'), (2, 'two'))`);
8994
+ * db.table.whereIn(['id', 'name'], sql`((1, 'one'), (2, 'two'))`);
9030
8995
  * ```
9031
8996
  */
9032
8997
  whereIn(...args) {
@@ -9340,7 +9305,7 @@ class Update {
9340
9305
  * column1: 123,
9341
9306
  *
9342
9307
  * // use raw SQL to update the column
9343
- * column2: db.table.sql`2 + 2`,
9308
+ * column2: sql`2 + 2`,
9344
9309
  *
9345
9310
  * // use query that returns a single value
9346
9311
  * // returning multiple values will result in Postgres error
@@ -9468,7 +9433,7 @@ class Update {
9468
9433
  * const updatedCount = await db.table.find(1).updateRaw`name = ${value}`;
9469
9434
  *
9470
9435
  * // or update with `sql` function:
9471
- * await db.table.find(1).updateRaw(db.table.sql`name = ${value}`);
9436
+ * await db.table.find(1).updateRaw(sql`name = ${value}`);
9472
9437
  * ```
9473
9438
  * @param args - raw SQL via a template string or by using a `sql` method
9474
9439
  */
@@ -9734,7 +9699,7 @@ class Headline extends orchidCore.Expression {
9734
9699
  const { q, source, params } = this;
9735
9700
  const lang = getSearchLang(ctx, q, source, quotedAs);
9736
9701
  const text = (params == null ? void 0 : params.text) ? params.text instanceof orchidCore.Expression ? params.text.toSQL(ctx, quotedAs) : columnToSql(ctx, q, q.shape, params.text, quotedAs) : getSearchText(ctx, q, source, quotedAs, true);
9737
- const options = (params == null ? void 0 : params.options) ? `, ${params.options instanceof orchidCore.Expression ? params.options.toSQL(ctx, quotedAs) : addValue(ctx.values, params.options)}` : "";
9702
+ const options = (params == null ? void 0 : params.options) ? `, ${params.options instanceof orchidCore.Expression ? params.options.toSQL(ctx, quotedAs) : orchidCore.addValue(ctx.values, params.options)}` : "";
9738
9703
  return `ts_headline(${lang}, ${text}, "${source.as}"${options})`;
9739
9704
  }
9740
9705
  }
@@ -10151,7 +10116,7 @@ class QueryUpsertOrCreate {
10151
10116
  }
10152
10117
  }
10153
10118
 
10154
- class RawSqlMethods {
10119
+ class SqlMethod {
10155
10120
  sql(...args) {
10156
10121
  const sql = raw(...args);
10157
10122
  sql.columnTypes = this.columnTypes;
@@ -10392,6 +10357,144 @@ class RefExpression extends orchidCore.Expression {
10392
10357
  return columnToSql(ctx, this.q, this.q.shape, this.ref, quotedAs);
10393
10358
  }
10394
10359
  }
10360
+ class OrExpression extends orchidCore.Expression {
10361
+ constructor(args) {
10362
+ super();
10363
+ this.args = args;
10364
+ this.q = { expr: this };
10365
+ }
10366
+ makeSQL(ctx, quotedAs) {
10367
+ const res = [];
10368
+ for (const arg of this.args) {
10369
+ if (arg) {
10370
+ if (orchidCore.isExpression(arg)) {
10371
+ const sql = arg.toSQL(ctx, quotedAs);
10372
+ if (sql)
10373
+ res.push(sql);
10374
+ } else {
10375
+ res.push(`(${arg.toSQL(ctx).text})`);
10376
+ }
10377
+ }
10378
+ }
10379
+ return `(${res.join(" OR ")})`;
10380
+ }
10381
+ }
10382
+ Object.assign(OrExpression.prototype, Operators.boolean);
10383
+ class ExpressionMethods {
10384
+ /**
10385
+ * `column` references a table column, this can be used in raw SQL or when building a column expression.
10386
+ * Only for referencing a column in the query's table. For referencing joined table's columns, see [ref](#ref).
10387
+ *
10388
+ * ```ts
10389
+ * await db.table.select({
10390
+ * // select `("table"."id" = 1 OR "table"."name" = 'name') AS "one"`,
10391
+ * // returns a boolean
10392
+ * one: (q) =>
10393
+ * q.sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
10394
+ *
10395
+ * // selects the same as above, but by building a query
10396
+ * two: (q) => q.column('id').equals(1).or(q.column('name').equals('name')),
10397
+ * });
10398
+ * ```
10399
+ *
10400
+ * @param name - column name
10401
+ */
10402
+ column(name) {
10403
+ const column = this.shape[name];
10404
+ return new ColumnRefExpression(
10405
+ column,
10406
+ name
10407
+ );
10408
+ }
10409
+ /**
10410
+ * `ref` is similar to [column](#column), but it also allows to reference a column of joined table,
10411
+ * and other dynamically defined columns.
10412
+ *
10413
+ * ```ts
10414
+ * await db.table.join('otherTable').select({
10415
+ * // select `("otherTable"."id" = 1 OR "otherTable"."name" = 'name') AS "one"`,
10416
+ * // returns a boolean
10417
+ * one: (q) =>
10418
+ * q.sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
10419
+ * 'otherTable.name',
10420
+ * )} = ${'name'}`,
10421
+ *
10422
+ * // selects the same as above, but by building a query
10423
+ * two: (q) =>
10424
+ * q
10425
+ * .ref('otherTable.id')
10426
+ * .equals(1)
10427
+ * .or(q.ref('otherTable.name').equals('name')),
10428
+ * });
10429
+ * ```
10430
+ *
10431
+ * @param arg - any available column name, such as of a joined table
10432
+ */
10433
+ ref(arg) {
10434
+ const q = this.clone();
10435
+ const { shape } = q.q;
10436
+ let column;
10437
+ const index = arg.indexOf(".");
10438
+ if (index !== -1) {
10439
+ const table = arg.slice(0, index);
10440
+ const col = arg.slice(index + 1);
10441
+ if (table === (q.q.as || q.table)) {
10442
+ column = shape[col];
10443
+ } else {
10444
+ column = q.q.joinedShapes[table][col];
10445
+ }
10446
+ } else {
10447
+ column = shape[arg];
10448
+ }
10449
+ return new RefExpression(column, q.q, arg);
10450
+ }
10451
+ val(value) {
10452
+ return new orchidCore.ValExpression(value);
10453
+ }
10454
+ /**
10455
+ * `fn` allows to call an arbitrary SQL function.
10456
+ *
10457
+ * For example, calling `sqrt` function to get a square root from some numeric column:
10458
+ *
10459
+ * ```ts
10460
+ * const q = await User.select({
10461
+ * sqrt: (q) => q.fn<number>('sqrt', ['numericColumn']),
10462
+ * }).take();
10463
+ *
10464
+ * q.sqrt; // has type `number` just as provided
10465
+ * ```
10466
+ *
10467
+ * If this is an aggregate function, you can specify aggregation options (see [Aggregate](/guide/aggregate.html)) via third parameter.
10468
+ *
10469
+ * Use `type` method to specify a column type so that its operators such as `lt` and `gt` become available:
10470
+ *
10471
+ * ```ts
10472
+ * const q = await User.select({
10473
+ * // Produces `sqrt("numericColumn") > 5`
10474
+ * sqrtIsGreaterThan5: (q) =>
10475
+ * q
10476
+ * .fn('sqrt', ['numericColumn'])
10477
+ * .type((t) => t.float())
10478
+ * .gt(5),
10479
+ * }).take();
10480
+ *
10481
+ * // Return type is boolean | null
10482
+ * // todo: it should be just boolean if the column is not nullable, but for now it's always nullable
10483
+ * q.sqrtIsGreaterThan5;
10484
+ * ```
10485
+ *
10486
+ * @param fn
10487
+ * @param args
10488
+ * @param options
10489
+ */
10490
+ fn(fn, args, options) {
10491
+ return makeFnExpression(this, orchidCore.emptyObject, fn, args, options);
10492
+ }
10493
+ or(...args) {
10494
+ return new OrExpression(args);
10495
+ }
10496
+ }
10497
+
10395
10498
  const _queryAll = (q) => {
10396
10499
  q.q.returnType = "all";
10397
10500
  q.q.all = true;
@@ -10536,11 +10639,13 @@ class QueryMethods {
10536
10639
  * db.table.distinct().select('name');
10537
10640
  * ```
10538
10641
  *
10539
- * Can accept column names or raw expressions to place it to `DISTINCT ON (...)`:
10642
+ * Can accept column names or raw SQL expressions to place it to `DISTINCT ON (...)`:
10540
10643
  *
10541
10644
  * ```ts
10645
+ * import { sql } from './baseTable';
10646
+ *
10542
10647
  * // Distinct on the name and raw SQL
10543
- * db.table.distinct('name', db.table.sql`raw sql`).select('id', 'name');
10648
+ * db.table.distinct('name', sql`raw sql`).select('id', 'name');
10544
10649
  * ```
10545
10650
  *
10546
10651
  * @param columns - column names or a raw SQL
@@ -10700,9 +10805,11 @@ class QueryMethods {
10700
10805
  * Also, it's possible to group by a selected value:
10701
10806
  *
10702
10807
  * ```ts
10808
+ * import { sql } from './baseTable';
10809
+ *
10703
10810
  * const results = db.product
10704
10811
  * .select({
10705
- * month: db.product.sql`extract(month from "createdAt")`.type((t) =>
10812
+ * month: sql`extract(month from "createdAt")`.type((t) =>
10706
10813
  * // month is returned as string, parse it to int
10707
10814
  * t.string().parse(parseInt),
10708
10815
  * ),
@@ -10806,8 +10913,6 @@ class QueryMethods {
10806
10913
  *
10807
10914
  * ```ts
10808
10915
  * db.table.orderSql`raw sql`;
10809
- * // or
10810
- * db.table.orderSql(db.table.sql`raw sql`);
10811
10916
  * ```
10812
10917
  *
10813
10918
  * @param args - SQL expression
@@ -11001,73 +11106,6 @@ class QueryMethods {
11001
11106
  return fn(q, ...args);
11002
11107
  };
11003
11108
  }
11004
- /**
11005
- * `column` references a table column, this can be used in raw SQL or when building a column expression.
11006
- * Only for referencing a column in the query's table. For referencing joined table's columns, see [ref](#ref).
11007
- *
11008
- * ```ts
11009
- * await db.table.select({
11010
- * // select `("table"."id" = 1 OR "table"."name" = 'name') AS "one"`,
11011
- * // returns a boolean
11012
- * one: (q) =>
11013
- * q.sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
11014
- *
11015
- * // selects the same as above, but by building a query
11016
- * two: (q) => q.column('id').equals(1).or(q.column('name').equals('name')),
11017
- * });
11018
- * ```
11019
- *
11020
- * @param name - column name
11021
- */
11022
- column(name) {
11023
- const column = this.shape[name];
11024
- return new ColumnRefExpression(
11025
- column,
11026
- name
11027
- );
11028
- }
11029
- /**
11030
- * `ref` is similar to [column](#column), but it also allows to reference a column of joined table,
11031
- * and other dynamically defined columns.
11032
- *
11033
- * ```ts
11034
- * await db.table.join('otherTable').select({
11035
- * // select `("otherTable"."id" = 1 OR "otherTable"."name" = 'name') AS "one"`,
11036
- * // returns a boolean
11037
- * one: (q) =>
11038
- * q.sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
11039
- * 'otherTable.name',
11040
- * )} = ${'name'}`,
11041
- *
11042
- * // selects the same as above, but by building a query
11043
- * two: (q) =>
11044
- * q
11045
- * .ref('otherTable.id')
11046
- * .equals(1)
11047
- * .or(q.ref('otherTable.name').equals('name')),
11048
- * });
11049
- * ```
11050
- *
11051
- * @param arg - any available column name, such as of a joined table
11052
- */
11053
- ref(arg) {
11054
- const q = this.clone();
11055
- const { shape } = q.q;
11056
- let column;
11057
- const index = arg.indexOf(".");
11058
- if (index !== -1) {
11059
- const table = arg.slice(0, index);
11060
- const col = arg.slice(index + 1);
11061
- if (table === (q.q.as || q.table)) {
11062
- column = shape[col];
11063
- } else {
11064
- column = q.q.joinedShapes[table][col];
11065
- }
11066
- } else {
11067
- column = shape[arg];
11068
- }
11069
- return new RefExpression(column, q.q, arg);
11070
- }
11071
11109
  /**
11072
11110
  * Narrows a part of the query output type.
11073
11111
  * Use with caution, type-safety isn't guaranteed with it.
@@ -11124,10 +11162,11 @@ orchidCore.applyMixins(QueryMethods, [
11124
11162
  QueryUpsertOrCreate,
11125
11163
  QueryGet,
11126
11164
  MergeQueryMethods,
11127
- RawSqlMethods,
11165
+ SqlMethod,
11128
11166
  TransformMethods,
11129
11167
  ScopeMethods,
11130
- SoftDeleteMethods
11168
+ SoftDeleteMethods,
11169
+ ExpressionMethods
11131
11170
  ]);
11132
11171
 
11133
11172
  const makeIndex = (columns, first, second) => {
@@ -11735,6 +11774,7 @@ exports.DomainColumn = DomainColumn;
11735
11774
  exports.DoublePrecisionColumn = DoublePrecisionColumn;
11736
11775
  exports.DynamicRawSQL = DynamicRawSQL;
11737
11776
  exports.EnumColumn = EnumColumn;
11777
+ exports.ExpressionMethods = ExpressionMethods;
11738
11778
  exports.FnExpression = FnExpression;
11739
11779
  exports.For = For;
11740
11780
  exports.From = From;
@@ -11762,6 +11802,7 @@ exports.NumberBaseColumn = NumberBaseColumn;
11762
11802
  exports.OnConflictQueryBuilder = OnConflictQueryBuilder;
11763
11803
  exports.OnMethods = OnMethods;
11764
11804
  exports.Operators = Operators;
11805
+ exports.OrExpression = OrExpression;
11765
11806
  exports.OrchidOrmError = OrchidOrmError;
11766
11807
  exports.OrchidOrmInternalError = OrchidOrmInternalError;
11767
11808
  exports.PathColumn = PathColumn;
@@ -11775,7 +11816,6 @@ exports.QueryLog = QueryLog;
11775
11816
  exports.QueryMethods = QueryMethods;
11776
11817
  exports.QueryUpsertOrCreate = QueryUpsertOrCreate;
11777
11818
  exports.RawSQL = RawSQL;
11778
- exports.RawSqlMethods = RawSqlMethods;
11779
11819
  exports.RealColumn = RealColumn;
11780
11820
  exports.RefExpression = RefExpression;
11781
11821
  exports.SearchMethods = SearchMethods;
@@ -11783,6 +11823,7 @@ exports.Select = Select;
11783
11823
  exports.SerialColumn = SerialColumn;
11784
11824
  exports.SmallIntColumn = SmallIntColumn;
11785
11825
  exports.SmallSerialColumn = SmallSerialColumn;
11826
+ exports.SqlMethod = SqlMethod;
11786
11827
  exports.StringColumn = StringColumn;
11787
11828
  exports.TextBaseColumn = TextBaseColumn;
11788
11829
  exports.TextColumn = TextColumn;