pqb 0.30.2 → 0.30.3

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, quoteObjectKey, toArray, singleQuote, addCode, singleQuoteArray, objectHasValues, columnDefaultArgumentToCode, columnErrorMessagesToCode, getValueKey, isExpression, joinTruthy, numberDataToCode, stringDataToCode, getDefaultLanguage, dateDataToCode, pushOrNewArrayToObject, arrayDataToCode, noop, emptyArray, callWithThis, setParserToQuery, applyTransforms, isRawSQL, pushOrNewArray, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, quoteObjectKey, toArray, singleQuote, addCode, singleQuoteArray, objectHasValues, columnDefaultArgumentToCode, columnErrorMessagesToCode, getValueKey, addValue, isExpression, joinTruthy, numberDataToCode, stringDataToCode, getDefaultLanguage, dateDataToCode, pushOrNewArrayToObject, arrayDataToCode, noop, emptyArray, callWithThis, setParserToQuery, applyTransforms, isRawSQL, pushOrNewArray, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, ValExpression, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
2
2
  import pg from 'pg';
3
3
  import { inspect } from 'node:util';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
@@ -27,8 +27,8 @@ const templateLiteralToSQL = (template, ctx, quotedAs) => {
27
27
  class RawSQL extends RawSQLBase {
28
28
  constructor(sql, values, type) {
29
29
  super(sql, values);
30
+ this.result = { value: type };
30
31
  if (type) {
31
- this.result = { value: type };
32
32
  Object.assign(this, type.operators);
33
33
  }
34
34
  }
@@ -834,102 +834,6 @@ const columnCode = (type, t, code, migration, data = type.data, skip) => {
834
834
  return code.length === 1 && typeof code[0] === "string" ? code[0] : code;
835
835
  };
836
836
 
837
- function simpleColumnToSQL(ctx, key, column, quotedAs) {
838
- if (!column)
839
- return `"${key}"`;
840
- const { data } = column;
841
- return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
842
- }
843
- function simpleExistingColumnToSQL(ctx, key, column, quotedAs) {
844
- const { data } = column;
845
- return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
846
- }
847
- const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
848
- var _a, _b, _c, _d, _e;
849
- const index = column.indexOf(".");
850
- if (index !== -1) {
851
- const table = column.slice(0, index);
852
- const key = column.slice(index + 1);
853
- if (key === "*") {
854
- if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
855
- return select ? `row_to_json("${table}".*)` : `"${table}".r`;
856
- }
857
- return column;
858
- }
859
- const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
860
- const quoted = `"${table}"`;
861
- const col = quoted === quotedAs ? shape[key] : (_d = (_c = data.joinedShapes) == null ? void 0 : _c[tableName]) == null ? void 0 : _d[key];
862
- if (col) {
863
- if (col.data.name) {
864
- return `"${tableName}"."${col.data.name}"`;
865
- }
866
- if (col.data.computed) {
867
- return `${col.data.computed.toSQL(ctx, quoted)}`;
868
- }
869
- return `"${tableName}"."${key}"`;
870
- }
871
- return `"${tableName}"."${key}"`;
872
- }
873
- if (!select && ((_e = data.joinedShapes) == null ? void 0 : _e[column])) {
874
- return `"${column}".r`;
875
- }
876
- return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
877
- };
878
- const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
879
- var _a, _b, _c, _d;
880
- const index = column.indexOf(".");
881
- if (index !== -1) {
882
- const table = column.slice(0, index);
883
- const key = column.slice(index + 1);
884
- if (key === "*") {
885
- if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
886
- return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
887
- }
888
- return column;
889
- }
890
- const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
891
- const quoted = `"${table}"`;
892
- const col2 = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
893
- if (col2) {
894
- if (col2.data.name && col2.data.name !== key) {
895
- return `"${tableName}"."${col2.data.name}" "${key}"`;
896
- }
897
- if (col2.data.computed) {
898
- return `${col2.data.computed.toSQL(ctx, quoted)} "${key}"`;
899
- }
900
- }
901
- return `"${tableName}"."${key}"`;
902
- }
903
- if (!select && ((_d = data.joinedShapes) == null ? void 0 : _d[column])) {
904
- return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
905
- }
906
- const col = data.shape[column];
907
- if (col) {
908
- if (col.data.name && col.data.name !== column) {
909
- return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}" "${column}"`;
910
- }
911
- if (col.data.computed) {
912
- return `${col.data.computed.toSQL(ctx, quotedAs)} "${column}"`;
913
- }
914
- }
915
- return `${quotedAs ? `${quotedAs}.` : ""}"${column}"`;
916
- };
917
- const ownColumnToSql = (data, column, quotedAs) => {
918
- var _a;
919
- const name = (_a = data.shape[column]) == null ? void 0 : _a.data.name;
920
- return `${quotedAs ? `${quotedAs}.` : ""}"${name || column}"${name && name !== column ? ` "${column}"` : ""}`;
921
- };
922
- const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
923
- return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
924
- };
925
- const quoteSchemaAndTable = (schema, table) => {
926
- return schema ? `"${schema}"."${table}"` : `"${table}"`;
927
- };
928
- const addValue = (values, value) => {
929
- values.push(value);
930
- return `$${values.length}`;
931
- };
932
-
933
837
  var __defProp$f = Object.defineProperty;
934
838
  var __defProps$7 = Object.defineProperties;
935
839
  var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
@@ -1859,6 +1763,98 @@ const queryTypeWithLimitOne = {
1859
1763
  };
1860
1764
  const isQueryReturnsAll = (q) => !q.q.returnType || q.q.returnType === "all";
1861
1765
 
1766
+ function simpleColumnToSQL(ctx, key, column, quotedAs) {
1767
+ if (!column)
1768
+ return `"${key}"`;
1769
+ const { data } = column;
1770
+ return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
1771
+ }
1772
+ function simpleExistingColumnToSQL(ctx, key, column, quotedAs) {
1773
+ const { data } = column;
1774
+ return data.computed ? data.computed.toSQL(ctx, quotedAs) : `${quotedAs ? `${quotedAs}.` : ""}"${data.name || key}"`;
1775
+ }
1776
+ const columnToSql = (ctx, data, shape, column, quotedAs, select) => {
1777
+ var _a, _b, _c, _d, _e;
1778
+ const index = column.indexOf(".");
1779
+ if (index !== -1) {
1780
+ const table = column.slice(0, index);
1781
+ const key = column.slice(index + 1);
1782
+ if (key === "*") {
1783
+ if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1784
+ return select ? `row_to_json("${table}".*)` : `"${table}".r`;
1785
+ }
1786
+ return column;
1787
+ }
1788
+ const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1789
+ const quoted = `"${table}"`;
1790
+ const col = quoted === quotedAs ? shape[key] : (_d = (_c = data.joinedShapes) == null ? void 0 : _c[tableName]) == null ? void 0 : _d[key];
1791
+ if (col) {
1792
+ if (col.data.name) {
1793
+ return `"${tableName}"."${col.data.name}"`;
1794
+ }
1795
+ if (col.data.computed) {
1796
+ return `${col.data.computed.toSQL(ctx, quoted)}`;
1797
+ }
1798
+ return `"${tableName}"."${key}"`;
1799
+ }
1800
+ return `"${tableName}"."${key}"`;
1801
+ }
1802
+ if (!select && ((_e = data.joinedShapes) == null ? void 0 : _e[column])) {
1803
+ return `"${column}".r`;
1804
+ }
1805
+ return simpleColumnToSQL(ctx, column, shape[column], quotedAs);
1806
+ };
1807
+ const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
1808
+ var _a, _b, _c, _d;
1809
+ const index = column.indexOf(".");
1810
+ if (index !== -1) {
1811
+ const table = column.slice(0, index);
1812
+ const key = column.slice(index + 1);
1813
+ if (key === "*") {
1814
+ if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1815
+ return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
1816
+ }
1817
+ return column;
1818
+ }
1819
+ const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1820
+ const quoted = `"${table}"`;
1821
+ const col2 = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
1822
+ if (col2) {
1823
+ if (col2.data.name && col2.data.name !== key) {
1824
+ return `"${tableName}"."${col2.data.name}" "${key}"`;
1825
+ }
1826
+ if (col2.data.computed) {
1827
+ return `${col2.data.computed.toSQL(ctx, quoted)} "${key}"`;
1828
+ }
1829
+ }
1830
+ return `"${tableName}"."${key}"`;
1831
+ }
1832
+ if (!select && ((_d = data.joinedShapes) == null ? void 0 : _d[column])) {
1833
+ return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
1834
+ }
1835
+ const col = data.shape[column];
1836
+ if (col) {
1837
+ if (col.data.name && col.data.name !== column) {
1838
+ return `${quotedAs ? `${quotedAs}.` : ""}"${col.data.name}" "${column}"`;
1839
+ }
1840
+ if (col.data.computed) {
1841
+ return `${col.data.computed.toSQL(ctx, quotedAs)} "${column}"`;
1842
+ }
1843
+ }
1844
+ return `${quotedAs ? `${quotedAs}.` : ""}"${column}"`;
1845
+ };
1846
+ const ownColumnToSql = (data, column, quotedAs) => {
1847
+ var _a;
1848
+ const name = (_a = data.shape[column]) == null ? void 0 : _a.data.name;
1849
+ return `${quotedAs ? `${quotedAs}.` : ""}"${name || column}"${name && name !== column ? ` "${column}"` : ""}`;
1850
+ };
1851
+ const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
1852
+ return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
1853
+ };
1854
+ const quoteSchemaAndTable = (schema, table) => {
1855
+ return schema ? `"${schema}"."${table}"` : `"${table}"`;
1856
+ };
1857
+
1862
1858
  const pushDistinctSql = (ctx, table, distinct, quotedAs) => {
1863
1859
  ctx.sql.push("DISTINCT");
1864
1860
  if (distinct.length) {
@@ -3688,7 +3684,6 @@ class From {
3688
3684
  * ```ts
3689
3685
  * const value = 123;
3690
3686
  * db.table.fromSql`value = ${value}`;
3691
- * db.table.fromSql(db.table.sql`value = ${value}`);
3692
3687
  * ```
3693
3688
  *
3694
3689
  * @param args - SQL expression
@@ -5412,7 +5407,8 @@ class FnExpression extends Expression {
5412
5407
  }
5413
5408
  }
5414
5409
  function makeFnExpression(self, type, fn, args, options) {
5415
- const q = self.clone();
5410
+ const q = extendQuery(self, type.operators);
5411
+ q.baseQuery.type = ExpressionTypeMethod.prototype.type;
5416
5412
  new FnExpression(
5417
5413
  q,
5418
5414
  fn,
@@ -5434,49 +5430,6 @@ nullableInt.parseItem = nullableInt.parseFn = (input) => input === null ? null :
5434
5430
  const nullableFloat = new RealColumn(defaultSchemaConfig);
5435
5431
  nullableFloat.parseItem = nullableFloat.parseFn = (input) => input === null ? null : parseFloat(input);
5436
5432
  class AggregateMethods {
5437
- /**
5438
- * `fn` allows to call an arbitrary SQL function.
5439
- *
5440
- * For example, calling `sqrt` function to get a square root from some numeric column:
5441
- *
5442
- * ```ts
5443
- * const q = await User.select({
5444
- * // todo: use type callback instead of generic type
5445
- * sqrt: (q) => q.fn<number>('sqrt', ['numericColumn']),
5446
- * }).take();
5447
- *
5448
- * q.sqrt; // has type `number` just as provided
5449
- * ```
5450
- *
5451
- * If this is an aggregate function, you can specify aggregation options via third parameter.
5452
- *
5453
- * Forth parameter is for runtime column type. When specified, allows to chain the function with the column operators:
5454
- *
5455
- * ```ts
5456
- * const q = await User.select({
5457
- * // chain `sqrt("numericColumn")` with the "greater than 5"
5458
- * sqrtIsGreaterThan5: (q) => q.fn('sqrt', ['numericColumn'], {}, (t) => t.float()).gt(5),
5459
- * }).take();
5460
- *
5461
- * // Return type is boolean | null
5462
- * // todo: it should be just boolean if the column is not nullable, but for now it's always nullable
5463
- * q.sqrtIsGreaterThan5
5464
- * ```
5465
- *
5466
- * @param fn
5467
- * @param args
5468
- * @param options
5469
- * @param type
5470
- */
5471
- fn(fn, args, options, type) {
5472
- return makeFnExpression(
5473
- this,
5474
- (type == null ? void 0 : type(this.columnTypes)) || emptyObject,
5475
- fn,
5476
- args,
5477
- options
5478
- );
5479
- }
5480
5433
  /**
5481
5434
  * Use `exists()` to check if there is at least one record-matching condition.
5482
5435
  *
@@ -5821,7 +5774,7 @@ class AggregateMethods {
5821
5774
  * // select a column with alias
5822
5775
  * nameAlias: 'name',
5823
5776
  * // select raw SQL with alias
5824
- * foo: db.table.sql<string>`"bar" || "baz"`,
5777
+ * foo: sql<string>`"bar" || "baz"`,
5825
5778
  * },
5826
5779
  * aggregateOptions,
5827
5780
  * );
@@ -5831,7 +5784,7 @@ class AggregateMethods {
5831
5784
  * object: (q) =>
5832
5785
  * q.jsonObjectAgg({
5833
5786
  * nameAlias: 'name',
5834
- * foo: db.table.sql<string>`"bar" || "baz"`,
5787
+ * foo: sql<string>`"bar" || "baz"`,
5835
5788
  * }),
5836
5789
  * });
5837
5790
  * ```
@@ -6303,7 +6256,7 @@ class Create {
6303
6256
  *
6304
6257
  * await db.table.create({
6305
6258
  * // raw SQL
6306
- * column1: db.table.sql`'John' | 'Doe'`,
6259
+ * column1: sql`'John' || ' ' || 'Doe'`,
6307
6260
  *
6308
6261
  * // query that returns a single value
6309
6262
  * // returning multiple values will result in Postgres error
@@ -6366,7 +6319,7 @@ class Create {
6366
6319
  * ```ts
6367
6320
  * const oneRecord = await db.table.createRaw({
6368
6321
  * columns: ['name', 'amount'],
6369
- * values: db.table.sql`'name', random()`,
6322
+ * values: sql`'name', random()`,
6370
6323
  * });
6371
6324
  * ```
6372
6325
  *
@@ -6395,7 +6348,7 @@ class Create {
6395
6348
  * ```ts
6396
6349
  * const manyRecords = await db.table.createManyRaw({
6397
6350
  * columns: ['name', 'amount'],
6398
- * values: [db.table.sql`'one', 2`, db.table.sql`'three', 4`],
6351
+ * values: [sql`'one', 2`, sql`'three', 4`],
6399
6352
  * });
6400
6353
  * ```
6401
6354
  *
@@ -6549,11 +6502,11 @@ class Create {
6549
6502
  * // raw SQL expression:
6550
6503
  * db.table
6551
6504
  * .create(data)
6552
- * .onConfict(db.table.sql`(email) where condition`)
6505
+ * .onConfict(sql`(email) where condition`)
6553
6506
  * .merge();
6554
6507
  * ```
6555
6508
  *
6556
- * You can use the db.table.sql function in onConflict.
6509
+ * You can use the `sql` function exported from your `BaseTable` file in onConflict.
6557
6510
  * It can be useful to specify a condition when you have a partial index:
6558
6511
  *
6559
6512
  * ```ts
@@ -6564,7 +6517,7 @@ class Create {
6564
6517
  * active: true,
6565
6518
  * })
6566
6519
  * // ignore only when having conflicting email and when active is true.
6567
- * .onConflict(db.table.sql`(email) where active`)
6520
+ * .onConflict(sql`(email) where active`)
6568
6521
  * .ignore();
6569
6522
  * ```
6570
6523
  *
@@ -6664,7 +6617,7 @@ class OnConflictQueryBuilder {
6664
6617
  * db.table
6665
6618
  * .create(data)
6666
6619
  * .onConflict()
6667
- * .set(db.table.sql`raw SQL expression`);
6620
+ * .set(sql`raw SQL expression`);
6668
6621
  *
6669
6622
  * // update records only on certain conditions
6670
6623
  * db.table
@@ -6838,16 +6791,20 @@ class For {
6838
6791
 
6839
6792
  class QueryGet {
6840
6793
  /**
6841
- * `.get` returns a single value, it will add `LIMIT 1` to the query, and accepts a column name or a raw expression.
6842
- * It will throw `NotFoundError` when not found.
6794
+ * `.get` returns a single value, adds `LIMIT 1` to the query, and accepts a column name or a raw SQL expression.
6795
+ *
6796
+ * `get` throws a `NotFoundError` when not found, and `getOptional` returns `undefined`.
6843
6797
  *
6844
6798
  * ```ts
6845
6799
  * import { NumberColumn } from 'orchid-orm';
6800
+ * import { sql } from './baseTable';
6846
6801
  *
6847
6802
  * const firstName: string = await db.table.get('name');
6848
6803
  *
6849
- * const rawResult: number = await db.table.get(
6850
- * db.table.sql((t) => t.integer())`1 + 1`,
6804
+ * const rawResult: number = await db.table.get(sql((t) => t.integer())`1 + 1`);
6805
+ *
6806
+ * const firstNameOptional: string | undefined = await db.table.getOptional(
6807
+ * 'name',
6851
6808
  * );
6852
6809
  * ```
6853
6810
  *
@@ -6935,7 +6892,7 @@ class Having {
6935
6892
  * Provide SQL expression for the `HAVING` SQL statement:
6936
6893
  *
6937
6894
  * ```ts
6938
- * db.table.having`count(*) >= ${10}`;
6895
+ * db.table.havingSql`count(*) >= ${10}`;
6939
6896
  * ```
6940
6897
  *
6941
6898
  * @param args - SQL expression
@@ -7449,7 +7406,8 @@ class Join {
7449
7406
  * ```ts
7450
7407
  * db.user.join(
7451
7408
  * db.message,
7452
- * db.user.sql`lower("message"."text") = lower("user"."name")`,
7409
+ * // `sql` can be imported from your `BaseTable` file
7410
+ * sql`lower("message"."text") = lower("user"."name")`,
7453
7411
  * );
7454
7412
  * ```
7455
7413
  *
@@ -7458,16 +7416,16 @@ class Join {
7458
7416
  * ```ts
7459
7417
  * db.user.join(
7460
7418
  * db.message,
7461
- * db.user.sql`lower("message"."text")`,
7462
- * db.user.sql`lower("user"."name")`,
7419
+ * sql`lower("message"."text")`,
7420
+ * sql`lower("user"."name")`,
7463
7421
  * );
7464
7422
  *
7465
7423
  * // with operator:
7466
7424
  * db.user.join(
7467
7425
  * db.message,
7468
- * db.user.sql`lower("message"."text")`,
7426
+ * sql`lower("message"."text")`,
7469
7427
  * '!=',
7470
- * db.user.sql`lower("user"."name")`,
7428
+ * sql`lower("user"."name")`,
7471
7429
  * );
7472
7430
  * ```
7473
7431
  *
@@ -7481,7 +7439,7 @@ class Join {
7481
7439
  * 'message.userId': 'user.id',
7482
7440
  *
7483
7441
  * // value can be a raw SQL expression:
7484
- * text: db.user.sql`lower("user"."name")`,
7442
+ * text: sql`lower("user"."name")`,
7485
7443
  * });
7486
7444
  * ```
7487
7445
  *
@@ -8271,7 +8229,7 @@ class With {
8271
8229
  * id: columnTypes.integer(),
8272
8230
  * name: columnTypes.text(3, 100),
8273
8231
  * },
8274
- * db.table.sql`SELECT id, name FROM "someTable"`,
8232
+ * sql`SELECT id, name FROM "someTable"`,
8275
8233
  * );
8276
8234
  *
8277
8235
  * // accepts query:
@@ -8279,7 +8237,7 @@ class With {
8279
8237
  *
8280
8238
  * // accepts a callback for a query builder:
8281
8239
  * db.table.with('alias', (qb) =>
8282
- * qb.select({ one: db.table.sql`1`.type((t) => t.integer()) }),
8240
+ * qb.select({ one: sql`1`.type((t) => t.integer()) }),
8283
8241
  * );
8284
8242
  *
8285
8243
  * // All mentioned forms can accept options as a second argument:
@@ -8331,7 +8289,7 @@ class Union {
8331
8289
  * SomeTable.select('id', 'name').union(
8332
8290
  * [
8333
8291
  * OtherTable.select('id', 'name'),
8334
- * SomeTable.sql`SELECT id, name FROM "thirdTable"`,
8292
+ * sql`SELECT id, name FROM "thirdTable"`,
8335
8293
  * ],
8336
8294
  * true, // optional wrap parameter
8337
8295
  * );
@@ -8526,7 +8484,8 @@ class Where {
8526
8484
  * },
8527
8485
  *
8528
8486
  * // where column equals to raw SQL
8529
- * column: db.table.sql`sql expression`,
8487
+ * // import `sql` from your `BaseTable`
8488
+ * column: sql`sql expression`,
8530
8489
  * });
8531
8490
  * ```
8532
8491
  *
@@ -8575,12 +8534,7 @@ class Where {
8575
8534
  * `where` supports raw SQL:
8576
8535
  *
8577
8536
  * ```ts
8578
- * db.table.where(db.table.sql`a = b`);
8579
- *
8580
- * // or
8581
- * import { raw } from 'orchid-orm';
8582
- *
8583
- * db.table.where(raw`a = b`);
8537
+ * db.table.where(sql`a = b`);
8584
8538
  * ```
8585
8539
  *
8586
8540
  * `where` can accept a callback with a specific query builder containing all "where" methods such as `where`, `orWhere`, `whereNot`, `whereIn`, `whereExists`:
@@ -8601,7 +8555,7 @@ class Where {
8601
8555
  * db.table.where(
8602
8556
  * { id: 1 },
8603
8557
  * db.table.where({ name: 'John' }),
8604
- * db.table.sql`a = b`,
8558
+ * sql`a = b`,
8605
8559
  * );
8606
8560
  * ```
8607
8561
  *
@@ -8714,8 +8668,6 @@ class Where {
8714
8668
  * All column operators can take a value of the same type as the column, a sub-query, or a raw SQL expression:
8715
8669
  *
8716
8670
  * ```ts
8717
- * import { sql } from 'orchid-orm';
8718
- *
8719
8671
  * db.table.where({
8720
8672
  * numericColumn: {
8721
8673
  * // lower than 5
@@ -8764,7 +8716,7 @@ class Where {
8764
8716
  * // WHERE "column" IN (SELECT "column" FROM "otherTable")
8765
8717
  * in: OtherTable.select('column'),
8766
8718
  *
8767
- * in: db.table.sql`('a', 'b')`,
8719
+ * in: sql`('a', 'b')`,
8768
8720
  * },
8769
8721
  * });
8770
8722
  * ```
@@ -8811,7 +8763,7 @@ class Where {
8811
8763
  * between: [1, 10],
8812
8764
  *
8813
8765
  * // sub-query and raw SQL expression
8814
- * between: [OtherTable.select('column').take(), db.table.sql`2 + 2`],
8766
+ * between: [OtherTable.select('column').take(), sql`2 + 2`],
8815
8767
  * },
8816
8768
  * });
8817
8769
  * ```
@@ -8903,15 +8855,7 @@ class Where {
8903
8855
  * Use a custom SQL expression in `WHERE` statement:
8904
8856
  *
8905
8857
  * ```ts
8906
- * db.table.where`a = b`;
8907
- *
8908
- * // or
8909
- * db.table.where(db.table.sql`a = b`);
8910
- *
8911
- * // or
8912
- * import { raw } from 'orchid-orm';
8913
- *
8914
- * db.table.where(raw`a = b`);
8858
+ * db.table.whereSql`a = b`;
8915
8859
  * ```
8916
8860
  *
8917
8861
  * @param args - SQL expression
@@ -8944,10 +8888,10 @@ class Where {
8944
8888
  );
8945
8889
  }
8946
8890
  /**
8947
- * `whereNot` version accepting SQL expression:
8891
+ * `whereNotSql` is a version of `whereNot` accepting SQL expression:
8948
8892
  *
8949
8893
  * ```ts
8950
- * db.table.whereNot`sql expression`
8894
+ * db.table.whereNotSql`sql expression`
8951
8895
  * ```
8952
8896
  *
8953
8897
  * @param args - SQL expression
@@ -9024,7 +8968,7 @@ class Where {
9024
8968
  * It supports raw SQL expression:
9025
8969
  *
9026
8970
  * ```ts
9027
- * db.table.whereIn(['id', 'name'], db.table.sql`((1, 'one'), (2, 'two'))`);
8971
+ * db.table.whereIn(['id', 'name'], sql`((1, 'one'), (2, 'two'))`);
9028
8972
  * ```
9029
8973
  */
9030
8974
  whereIn(...args) {
@@ -9338,7 +9282,7 @@ class Update {
9338
9282
  * column1: 123,
9339
9283
  *
9340
9284
  * // use raw SQL to update the column
9341
- * column2: db.table.sql`2 + 2`,
9285
+ * column2: sql`2 + 2`,
9342
9286
  *
9343
9287
  * // use query that returns a single value
9344
9288
  * // returning multiple values will result in Postgres error
@@ -9466,7 +9410,7 @@ class Update {
9466
9410
  * const updatedCount = await db.table.find(1).updateRaw`name = ${value}`;
9467
9411
  *
9468
9412
  * // or update with `sql` function:
9469
- * await db.table.find(1).updateRaw(db.table.sql`name = ${value}`);
9413
+ * await db.table.find(1).updateRaw(sql`name = ${value}`);
9470
9414
  * ```
9471
9415
  * @param args - raw SQL via a template string or by using a `sql` method
9472
9416
  */
@@ -10149,7 +10093,7 @@ class QueryUpsertOrCreate {
10149
10093
  }
10150
10094
  }
10151
10095
 
10152
- class RawSqlMethods {
10096
+ class SqlMethod {
10153
10097
  sql(...args) {
10154
10098
  const sql = raw(...args);
10155
10099
  sql.columnTypes = this.columnTypes;
@@ -10390,6 +10334,118 @@ class RefExpression extends Expression {
10390
10334
  return columnToSql(ctx, this.q, this.q.shape, this.ref, quotedAs);
10391
10335
  }
10392
10336
  }
10337
+ class ExpressionMethods {
10338
+ /**
10339
+ * `column` references a table column, this can be used in raw SQL or when building a column expression.
10340
+ * Only for referencing a column in the query's table. For referencing joined table's columns, see [ref](#ref).
10341
+ *
10342
+ * ```ts
10343
+ * await db.table.select({
10344
+ * // select `("table"."id" = 1 OR "table"."name" = 'name') AS "one"`,
10345
+ * // returns a boolean
10346
+ * one: (q) =>
10347
+ * q.sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
10348
+ *
10349
+ * // selects the same as above, but by building a query
10350
+ * two: (q) => q.column('id').equals(1).or(q.column('name').equals('name')),
10351
+ * });
10352
+ * ```
10353
+ *
10354
+ * @param name - column name
10355
+ */
10356
+ column(name) {
10357
+ const column = this.shape[name];
10358
+ return new ColumnRefExpression(
10359
+ column,
10360
+ name
10361
+ );
10362
+ }
10363
+ /**
10364
+ * `ref` is similar to [column](#column), but it also allows to reference a column of joined table,
10365
+ * and other dynamically defined columns.
10366
+ *
10367
+ * ```ts
10368
+ * await db.table.join('otherTable').select({
10369
+ * // select `("otherTable"."id" = 1 OR "otherTable"."name" = 'name') AS "one"`,
10370
+ * // returns a boolean
10371
+ * one: (q) =>
10372
+ * q.sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
10373
+ * 'otherTable.name',
10374
+ * )} = ${'name'}`,
10375
+ *
10376
+ * // selects the same as above, but by building a query
10377
+ * two: (q) =>
10378
+ * q
10379
+ * .ref('otherTable.id')
10380
+ * .equals(1)
10381
+ * .or(q.ref('otherTable.name').equals('name')),
10382
+ * });
10383
+ * ```
10384
+ *
10385
+ * @param arg - any available column name, such as of a joined table
10386
+ */
10387
+ ref(arg) {
10388
+ const q = this.clone();
10389
+ const { shape } = q.q;
10390
+ let column;
10391
+ const index = arg.indexOf(".");
10392
+ if (index !== -1) {
10393
+ const table = arg.slice(0, index);
10394
+ const col = arg.slice(index + 1);
10395
+ if (table === (q.q.as || q.table)) {
10396
+ column = shape[col];
10397
+ } else {
10398
+ column = q.q.joinedShapes[table][col];
10399
+ }
10400
+ } else {
10401
+ column = shape[arg];
10402
+ }
10403
+ return new RefExpression(column, q.q, arg);
10404
+ }
10405
+ val(value) {
10406
+ return new ValExpression(value);
10407
+ }
10408
+ /**
10409
+ * `fn` allows to call an arbitrary SQL function.
10410
+ *
10411
+ * For example, calling `sqrt` function to get a square root from some numeric column:
10412
+ *
10413
+ * ```ts
10414
+ * const q = await User.select({
10415
+ * sqrt: (q) => q.fn<number>('sqrt', ['numericColumn']),
10416
+ * }).take();
10417
+ *
10418
+ * q.sqrt; // has type `number` just as provided
10419
+ * ```
10420
+ *
10421
+ * If this is an aggregate function, you can specify aggregation options (see [Aggregate](/guide/aggregate.html)) via third parameter.
10422
+ *
10423
+ * Use `type` method to specify a column type so that its operators such as `lt` and `gt` become available:
10424
+ *
10425
+ * ```ts
10426
+ * const q = await User.select({
10427
+ * // Produces `sqrt("numericColumn") > 5`
10428
+ * sqrtIsGreaterThan5: (q) =>
10429
+ * q
10430
+ * .fn('sqrt', ['numericColumn'])
10431
+ * .type((t) => t.float())
10432
+ * .gt(5),
10433
+ * }).take();
10434
+ *
10435
+ * // Return type is boolean | null
10436
+ * // todo: it should be just boolean if the column is not nullable, but for now it's always nullable
10437
+ * q.sqrtIsGreaterThan5;
10438
+ * ```
10439
+ *
10440
+ * @param fn
10441
+ * @param args
10442
+ * @param options
10443
+ */
10444
+ fn(fn, args, options) {
10445
+ return makeFnExpression(this, emptyObject, fn, args, options);
10446
+ }
10447
+ }
10448
+
10393
10449
  const _queryAll = (q) => {
10394
10450
  q.q.returnType = "all";
10395
10451
  q.q.all = true;
@@ -10534,11 +10590,13 @@ class QueryMethods {
10534
10590
  * db.table.distinct().select('name');
10535
10591
  * ```
10536
10592
  *
10537
- * Can accept column names or raw expressions to place it to `DISTINCT ON (...)`:
10593
+ * Can accept column names or raw SQL expressions to place it to `DISTINCT ON (...)`:
10538
10594
  *
10539
10595
  * ```ts
10596
+ * import { sql } from './baseTable';
10597
+ *
10540
10598
  * // Distinct on the name and raw SQL
10541
- * db.table.distinct('name', db.table.sql`raw sql`).select('id', 'name');
10599
+ * db.table.distinct('name', sql`raw sql`).select('id', 'name');
10542
10600
  * ```
10543
10601
  *
10544
10602
  * @param columns - column names or a raw SQL
@@ -10698,9 +10756,11 @@ class QueryMethods {
10698
10756
  * Also, it's possible to group by a selected value:
10699
10757
  *
10700
10758
  * ```ts
10759
+ * import { sql } from './baseTable';
10760
+ *
10701
10761
  * const results = db.product
10702
10762
  * .select({
10703
- * month: db.product.sql`extract(month from "createdAt")`.type((t) =>
10763
+ * month: sql`extract(month from "createdAt")`.type((t) =>
10704
10764
  * // month is returned as string, parse it to int
10705
10765
  * t.string().parse(parseInt),
10706
10766
  * ),
@@ -10804,8 +10864,6 @@ class QueryMethods {
10804
10864
  *
10805
10865
  * ```ts
10806
10866
  * db.table.orderSql`raw sql`;
10807
- * // or
10808
- * db.table.orderSql(db.table.sql`raw sql`);
10809
10867
  * ```
10810
10868
  *
10811
10869
  * @param args - SQL expression
@@ -10999,73 +11057,6 @@ class QueryMethods {
10999
11057
  return fn(q, ...args);
11000
11058
  };
11001
11059
  }
11002
- /**
11003
- * `column` references a table column, this can be used in raw SQL or when building a column expression.
11004
- * Only for referencing a column in the query's table. For referencing joined table's columns, see [ref](#ref).
11005
- *
11006
- * ```ts
11007
- * await db.table.select({
11008
- * // select `("table"."id" = 1 OR "table"."name" = 'name') AS "one"`,
11009
- * // returns a boolean
11010
- * one: (q) =>
11011
- * q.sql<boolean>`${q.column('id')} = ${1} OR ${q.column('name')} = ${'name'}`,
11012
- *
11013
- * // selects the same as above, but by building a query
11014
- * two: (q) => q.column('id').equals(1).or(q.column('name').equals('name')),
11015
- * });
11016
- * ```
11017
- *
11018
- * @param name - column name
11019
- */
11020
- column(name) {
11021
- const column = this.shape[name];
11022
- return new ColumnRefExpression(
11023
- column,
11024
- name
11025
- );
11026
- }
11027
- /**
11028
- * `ref` is similar to [column](#column), but it also allows to reference a column of joined table,
11029
- * and other dynamically defined columns.
11030
- *
11031
- * ```ts
11032
- * await db.table.join('otherTable').select({
11033
- * // select `("otherTable"."id" = 1 OR "otherTable"."name" = 'name') AS "one"`,
11034
- * // returns a boolean
11035
- * one: (q) =>
11036
- * q.sql<boolean>`${q.ref('otherTable.id')} = ${1} OR ${q.ref(
11037
- * 'otherTable.name',
11038
- * )} = ${'name'}`,
11039
- *
11040
- * // selects the same as above, but by building a query
11041
- * two: (q) =>
11042
- * q
11043
- * .ref('otherTable.id')
11044
- * .equals(1)
11045
- * .or(q.ref('otherTable.name').equals('name')),
11046
- * });
11047
- * ```
11048
- *
11049
- * @param arg - any available column name, such as of a joined table
11050
- */
11051
- ref(arg) {
11052
- const q = this.clone();
11053
- const { shape } = q.q;
11054
- let column;
11055
- const index = arg.indexOf(".");
11056
- if (index !== -1) {
11057
- const table = arg.slice(0, index);
11058
- const col = arg.slice(index + 1);
11059
- if (table === (q.q.as || q.table)) {
11060
- column = shape[col];
11061
- } else {
11062
- column = q.q.joinedShapes[table][col];
11063
- }
11064
- } else {
11065
- column = shape[arg];
11066
- }
11067
- return new RefExpression(column, q.q, arg);
11068
- }
11069
11060
  /**
11070
11061
  * Narrows a part of the query output type.
11071
11062
  * Use with caution, type-safety isn't guaranteed with it.
@@ -11122,10 +11113,11 @@ applyMixins(QueryMethods, [
11122
11113
  QueryUpsertOrCreate,
11123
11114
  QueryGet,
11124
11115
  MergeQueryMethods,
11125
- RawSqlMethods,
11116
+ SqlMethod,
11126
11117
  TransformMethods,
11127
11118
  ScopeMethods,
11128
- SoftDeleteMethods
11119
+ SoftDeleteMethods,
11120
+ ExpressionMethods
11129
11121
  ]);
11130
11122
 
11131
11123
  const makeIndex = (columns, first, second) => {
@@ -11702,5 +11694,5 @@ function copyTableData(query, arg) {
11702
11694
  return q;
11703
11695
  }
11704
11696
 
11705
- export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, FnExpression, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RawSqlMethods, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, With, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, makeSQL, parseRecord, parseResult, parseTableData, parseTableDataInput, primaryKeyInnerToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11697
+ export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, With, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, makeSQL, parseRecord, parseResult, parseTableData, parseTableDataInput, primaryKeyInnerToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11706
11698
  //# sourceMappingURL=index.mjs.map