pqb 0.26.4 → 0.26.5

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, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, emptyObject, quoteObjectKey, toArray, singleQuote, addCode, objectHasValues, singleQuoteArray, columnDefaultArgumentToCode, columnErrorMessagesToCode, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, noop, setParserToQuery, applyTransforms, getValueKey, emptyArray, isRawSQL, pushOrNewArray, pushOrNewArrayToObject, numberDataToCode, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, applyMixins, callWithThis, isObjectEmpty, toSnakeCase, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, emptyObject, quoteObjectKey, toArray, singleQuote, addCode, objectHasValues, singleQuoteArray, columnDefaultArgumentToCode, columnErrorMessagesToCode, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, noop, getValueKey, emptyArray, callWithThis, setParserToQuery, applyTransforms, isRawSQL, pushOrNewArray, pushOrNewArrayToObject, numberDataToCode, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, applyMixins, isObjectEmpty, 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';
@@ -1803,369 +1803,726 @@ const defaultSchemaConfig = {
1803
1803
  timestamp: (precision) => new TimestampTZColumn(defaultSchemaConfig, precision)
1804
1804
  };
1805
1805
 
1806
- const addParserForRawExpression = (q, key, raw) => {
1807
- const type = raw._type;
1808
- if (type.parseFn)
1809
- setParserToQuery(q.q, key, type.parseFn);
1810
- };
1811
- const subQueryResult = {
1812
- // sub query can't return a rowCount, use -1 as for impossible case
1813
- rowCount: -1,
1814
- rows: emptyArray,
1815
- fields: emptyArray
1806
+ const queryMethodByReturnType = {
1807
+ all: "query",
1808
+ rows: "arrays",
1809
+ pluck: "arrays",
1810
+ one: "query",
1811
+ oneOrThrow: "query",
1812
+ value: "arrays",
1813
+ valueOrThrow: "arrays",
1814
+ rowCount: "arrays",
1815
+ void: "arrays"
1816
1816
  };
1817
- const addParsersForSelectJoined = (q, arg, as = arg) => {
1818
- var _a;
1819
- const parsers = (_a = q.q.joinedParsers) == null ? void 0 : _a[arg];
1820
- if (parsers) {
1821
- setParserToQuery(q.q, as, (item) => {
1822
- subQueryResult.rows = [item];
1823
- return q.q.handleResult(q, "one", subQueryResult, true);
1817
+ class Then {
1818
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1819
+ catch(fn) {
1820
+ return this.then(void 0, fn);
1821
+ }
1822
+ }
1823
+ let queryError = void 0;
1824
+ let getThen;
1825
+ if (process.versions.bun) {
1826
+ getThen = function() {
1827
+ queryError = new Error();
1828
+ if (!this.internal)
1829
+ return maybeWrappedThen;
1830
+ const trx = this.internal.transactionStorage.getStore();
1831
+ if (!trx)
1832
+ return maybeWrappedThen;
1833
+ return (resolve, reject) => {
1834
+ return this.internal.transactionStorage.run(trx, () => {
1835
+ return maybeWrappedThen.call(this, resolve, reject);
1836
+ });
1837
+ };
1838
+ };
1839
+ } else {
1840
+ getThen = function() {
1841
+ queryError = new Error();
1842
+ return maybeWrappedThen;
1843
+ };
1844
+ }
1845
+ Object.defineProperty(Then.prototype, "then", {
1846
+ get: getThen,
1847
+ set(value) {
1848
+ Object.defineProperty(this, "then", {
1849
+ value
1824
1850
  });
1825
1851
  }
1852
+ });
1853
+ const handleResult = (q, returnType, result, isSubQuery) => {
1854
+ return parseResult(q, q.q.parsers, returnType, result, isSubQuery);
1826
1855
  };
1827
- const addParserForSelectItem = (q, as, key, arg) => {
1828
- if (typeof arg === "object" || typeof arg === "function") {
1829
- if (isExpression(arg)) {
1830
- addParserForRawExpression(q, key, arg);
1831
- } else {
1832
- const { q: query } = arg;
1833
- if (query.parsers || query.transform) {
1834
- setParserToQuery(q.q, key, (item) => {
1835
- const t = query.returnType || "all";
1836
- subQueryResult.rows = t === "value" || t === "valueOrThrow" ? [[item]] : t === "one" || t === "oneOrThrow" ? [item] : item;
1837
- return applyTransforms(
1838
- query.transform,
1839
- query.handleResult(arg, t, subQueryResult, true)
1840
- );
1841
- });
1842
- }
1856
+ function maybeWrappedThen(resolve, reject) {
1857
+ const { q } = this;
1858
+ let beforeHooks;
1859
+ let afterHooks;
1860
+ let afterCommitHooks;
1861
+ if (q.type) {
1862
+ if (q.type === "insert") {
1863
+ beforeHooks = q.beforeCreate;
1864
+ afterHooks = q.afterCreate;
1865
+ afterCommitHooks = q.afterCreateCommit;
1866
+ } else if (q.type === "update") {
1867
+ beforeHooks = q.beforeUpdate;
1868
+ afterHooks = q.afterUpdate;
1869
+ afterCommitHooks = q.afterUpdateCommit;
1870
+ } else if (q.type === "delete") {
1871
+ beforeHooks = q.beforeDelete;
1872
+ afterHooks = q.afterDelete;
1873
+ afterCommitHooks = q.afterDeleteCommit;
1843
1874
  }
1844
- return arg;
1845
- }
1846
- return setParserForSelectedString(q, arg, as, key);
1847
- };
1848
- const emptyArrSQL = new RawSQL("'[]'");
1849
- const processSelectArg = (q, as, arg, columnAs) => {
1850
- var _a, _b, _c, _d;
1851
- if (typeof arg === "string") {
1852
- return setParserForSelectedString(q, arg, as, columnAs);
1853
1875
  }
1854
- const selectAs = {};
1855
- for (const key in arg) {
1856
- let value = arg[key];
1857
- if (typeof value === "function") {
1858
- value = resolveSubQueryCallback(q, value);
1859
- if (!isExpression(value) && value.joinQuery) {
1860
- value = value.joinQuery(value, q);
1861
- let query;
1862
- const returnType = value.q.returnType;
1863
- if (!returnType || returnType === "all") {
1864
- query = value.json(false);
1865
- value.q.coalesceValue = emptyArrSQL;
1866
- } else if (returnType === "pluck") {
1867
- query = value.wrap(value.baseQuery.clone()).jsonAgg(value.q.select[0]);
1868
- value.q.coalesceValue = emptyArrSQL;
1869
- } else {
1870
- if ((returnType === "value" || returnType === "valueOrThrow") && value.q.select) {
1871
- if (typeof value.q.select[0] === "string") {
1872
- value.q.select[0] = {
1873
- selectAs: { r: value.q.select[0] }
1874
- };
1875
- }
1876
- }
1877
- query = value;
1878
- }
1879
- let asOverride = key;
1880
- if ((_a = value.q.joinedShapes) == null ? void 0 : _a[key]) {
1881
- let suffix = 2;
1882
- const joinOverrides = (_c = (_b = q.q).joinOverrides) != null ? _c : _b.joinOverrides = {};
1883
- while (joinOverrides[asOverride = `${key}${suffix}`]) {
1884
- suffix++;
1885
- }
1886
- joinOverrides[asOverride] = asOverride;
1887
- joinOverrides[key] = asOverride;
1888
- }
1889
- value.q.joinedForSelect = asOverride;
1890
- _joinLateral(
1891
- q,
1892
- value.q.innerJoinLateral ? "JOIN" : "LEFT JOIN",
1893
- query,
1894
- (q2) => q2,
1895
- key
1876
+ const trx = this.internal.transactionStorage.getStore();
1877
+ if ((q.wrapInTransaction || afterHooks) && !trx) {
1878
+ return this.transaction(
1879
+ () => new Promise((resolve2, reject2) => {
1880
+ const trx2 = this.internal.transactionStorage.getStore();
1881
+ return then(
1882
+ this,
1883
+ trx2.adapter,
1884
+ trx2,
1885
+ beforeHooks,
1886
+ afterHooks,
1887
+ afterCommitHooks,
1888
+ resolve2,
1889
+ reject2
1896
1890
  );
1897
- } else if (((_d = value.q) == null ? void 0 : _d.isSubQuery) && value.q.expr) {
1898
- value = value.q.expr;
1899
- }
1900
- }
1901
- selectAs[key] = addParserForSelectItem(
1902
- q,
1903
- as,
1904
- key,
1905
- value
1891
+ })
1892
+ ).then(resolve, reject);
1893
+ } else {
1894
+ return then(
1895
+ this,
1896
+ (trx == null ? void 0 : trx.adapter) || this.q.adapter,
1897
+ trx,
1898
+ beforeHooks,
1899
+ afterHooks,
1900
+ afterCommitHooks,
1901
+ resolve,
1902
+ reject
1906
1903
  );
1907
1904
  }
1908
- return { selectAs };
1905
+ }
1906
+ const queriesNames = {};
1907
+ let nameI = 0;
1908
+ const callAfterHook = function(cb) {
1909
+ return cb(this[0], this[1]);
1909
1910
  };
1910
- const setParserForSelectedString = (q, arg, as, columnAs) => {
1911
- var _a, _b, _c, _d;
1912
- const index = arg.indexOf(".");
1913
- if (index !== -1) {
1914
- const table = arg.slice(0, index);
1915
- const column = arg.slice(index + 1);
1916
- if (column === "*") {
1917
- addParsersForSelectJoined(q, table, columnAs);
1918
- return table === as ? column : arg;
1919
- } else {
1920
- if (table === as) {
1921
- const parser = (_a = q.q.parsers) == null ? void 0 : _a[column];
1922
- if (parser)
1923
- setParserToQuery(q.q, columnAs || column, parser);
1924
- return column;
1925
- } else {
1926
- const parser = (_c = (_b = q.q.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
1927
- if (parser)
1928
- setParserToQuery(q.q, columnAs || column, parser);
1929
- return arg;
1930
- }
1911
+ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks, resolve, reject) => {
1912
+ var _a;
1913
+ const { q: query } = q;
1914
+ let sql;
1915
+ let logData;
1916
+ const localError = queryError;
1917
+ try {
1918
+ if (beforeHooks || query.before) {
1919
+ await Promise.all(
1920
+ [...beforeHooks || emptyArray, ...query.before || emptyArray].map(
1921
+ callWithThis,
1922
+ q
1923
+ )
1924
+ );
1931
1925
  }
1932
- } else {
1933
- const parser = (_d = q.q.parsers) == null ? void 0 : _d[arg];
1934
- if (parser)
1935
- setParserToQuery(q.q, columnAs || arg, parser);
1936
- return arg;
1937
- }
1938
- };
1939
- const getShapeFromSelect = (q, isSubQuery) => {
1940
- const query = q.q;
1941
- const { select, shape } = query;
1942
- let result;
1943
- if (!select) {
1944
- if (isSubQuery) {
1945
- result = {};
1946
- for (const key in shape) {
1947
- const column = shape[key];
1948
- result[key] = column.data.name ? setColumnData(column, "name", void 0) : column;
1949
- }
1950
- } else {
1951
- result = shape;
1926
+ sql = q.toSQL();
1927
+ const { hookSelect } = sql;
1928
+ if (query.autoPreparedStatements) {
1929
+ sql.name = queriesNames[sql.text] || (queriesNames[sql.text] = (nameI++).toString(36));
1952
1930
  }
1953
- } else {
1954
- result = {};
1955
- for (const item of select) {
1956
- if (typeof item === "string") {
1957
- addColumnToShapeFromSelect(q, item, shape, query, result, isSubQuery);
1958
- } else if ("selectAs" in item) {
1959
- for (const key in item.selectAs) {
1960
- const it = item.selectAs[key];
1961
- if (typeof it === "string") {
1962
- addColumnToShapeFromSelect(
1963
- q,
1964
- it,
1965
- shape,
1966
- query,
1967
- result,
1968
- isSubQuery,
1969
- key
1970
- );
1971
- } else if (isExpression(it)) {
1972
- result[key] = it._type;
1973
- } else {
1974
- const { returnType } = it.q;
1975
- if (returnType === "value" || returnType === "valueOrThrow") {
1976
- const type = it.q[getValueKey];
1977
- if (type)
1978
- result[key] = type;
1979
- } else {
1980
- result[key] = new JSONTextColumn(defaultSchemaConfig);
1981
- }
1982
- }
1931
+ if (query.log) {
1932
+ logData = query.log.beforeQuery(sql);
1933
+ }
1934
+ const { returnType = "all" } = query;
1935
+ const returns = hookSelect ? "all" : returnType;
1936
+ const queryResult = await adapter[hookSelect ? "query" : queryMethodByReturnType[returnType]](sql);
1937
+ if (query.patchResult) {
1938
+ await query.patchResult(q, queryResult);
1939
+ }
1940
+ if (query.log) {
1941
+ query.log.afterQuery(sql, logData);
1942
+ sql = void 0;
1943
+ }
1944
+ let result = query.handleResult(q, returns, queryResult);
1945
+ if (afterHooks || afterCommitHooks || query.after) {
1946
+ if (queryResult.rowCount) {
1947
+ if (afterHooks || query.after) {
1948
+ const args = [result, q];
1949
+ await Promise.all(
1950
+ [...afterHooks || emptyArray, ...query.after || emptyArray].map(
1951
+ callAfterHook,
1952
+ args
1953
+ )
1954
+ );
1955
+ }
1956
+ if (afterCommitHooks && trx) {
1957
+ ((_a = trx.afterCommit) != null ? _a : trx.afterCommit = []).push(
1958
+ result,
1959
+ q,
1960
+ afterCommitHooks
1961
+ );
1962
+ } else if (afterCommitHooks) {
1963
+ const args = [result, q];
1964
+ await Promise.all(afterCommitHooks.map(callAfterHook, args));
1983
1965
  }
1966
+ } else if (query.after) {
1967
+ const args = [result, q];
1968
+ await Promise.all(query.after.map(callAfterHook, args));
1969
+ }
1970
+ if (hookSelect)
1971
+ result = filterResult(q, returnType, queryResult, hookSelect, result);
1972
+ }
1973
+ if (query.transform) {
1974
+ for (const fn of query.transform) {
1975
+ result = fn(result);
1976
+ }
1977
+ }
1978
+ return resolve == null ? void 0 : resolve(result);
1979
+ } catch (err) {
1980
+ let error;
1981
+ if (err instanceof pg.DatabaseError) {
1982
+ error = new q.error();
1983
+ assignError(error, err);
1984
+ error.cause = localError;
1985
+ } else {
1986
+ error = err;
1987
+ if (error instanceof Error) {
1988
+ error.cause = localError;
1984
1989
  }
1985
1990
  }
1991
+ if (query.log && sql) {
1992
+ query.log.onError(error, sql, logData);
1993
+ }
1994
+ return reject == null ? void 0 : reject(error);
1986
1995
  }
1987
- return result;
1988
1996
  };
1989
- const addColumnToShapeFromSelect = (q, arg, shape, query, result, isSubQuery, key) => {
1997
+ const assignError = (to, from) => {
1998
+ to.message = from.message;
1999
+ to.length = from.length;
2000
+ to.name = from.name;
2001
+ to.severity = from.severity;
2002
+ to.code = from.code;
2003
+ to.detail = from.detail;
2004
+ to.hint = from.hint;
2005
+ to.position = from.position;
2006
+ to.internalPosition = from.internalPosition;
2007
+ to.internalQuery = from.internalQuery;
2008
+ to.where = from.where;
2009
+ to.schema = from.schema;
2010
+ to.table = from.table;
2011
+ to.column = from.column;
2012
+ to.dataType = from.dataType;
2013
+ to.constraint = from.constraint;
2014
+ to.file = from.file;
2015
+ to.line = from.line;
2016
+ to.routine = from.routine;
2017
+ return to;
2018
+ };
2019
+ const parseResult = (q, parsers, returnType = "all", result, isSubQuery) => {
1990
2020
  var _a, _b;
1991
- if (q.relations[arg]) {
1992
- result[key || arg] = emptyObject;
1993
- return;
2021
+ switch (returnType) {
2022
+ case "all": {
2023
+ if (q.q.throwOnNotFound && result.rows.length === 0)
2024
+ throw new NotFoundError(q);
2025
+ const { rows } = result;
2026
+ if (parsers) {
2027
+ for (const row of rows) {
2028
+ parseRecord(parsers, row);
2029
+ }
2030
+ }
2031
+ return rows;
2032
+ }
2033
+ case "one": {
2034
+ const row = result.rows[0];
2035
+ if (!row)
2036
+ return;
2037
+ return parsers ? parseRecord(parsers, row) : row;
2038
+ }
2039
+ case "oneOrThrow": {
2040
+ const row = result.rows[0];
2041
+ if (!row)
2042
+ throw new NotFoundError(q);
2043
+ return parsers ? parseRecord(parsers, row) : row;
2044
+ }
2045
+ case "rows": {
2046
+ return parsers ? parseRows(
2047
+ parsers,
2048
+ result.fields,
2049
+ result.rows
2050
+ ) : result.rows;
2051
+ }
2052
+ case "pluck": {
2053
+ const pluck = parsers == null ? void 0 : parsers.pluck;
2054
+ if (pluck) {
2055
+ return result.rows.map(isSubQuery ? pluck : (row) => pluck(row[0]));
2056
+ } else if (isSubQuery) {
2057
+ return result.rows;
2058
+ }
2059
+ return result.rows.map((row) => row[0]);
2060
+ }
2061
+ case "value": {
2062
+ const value = (_a = result.rows[0]) == null ? void 0 : _a[0];
2063
+ return value !== void 0 ? parseValue(value, parsers) : q.q.notFoundDefault;
2064
+ }
2065
+ case "valueOrThrow": {
2066
+ const value = (_b = result.rows[0]) == null ? void 0 : _b[0];
2067
+ if (value === void 0)
2068
+ throw new NotFoundError(q);
2069
+ return parseValue(value, parsers);
2070
+ }
2071
+ case "rowCount": {
2072
+ if (q.q.throwOnNotFound && result.rowCount === 0) {
2073
+ throw new NotFoundError(q);
2074
+ }
2075
+ return result.rowCount;
2076
+ }
2077
+ case "void": {
2078
+ return;
2079
+ }
1994
2080
  }
1995
- const index = arg.indexOf(".");
1996
- if (index !== -1) {
1997
- const table = arg.slice(0, index);
1998
- const column = arg.slice(index + 1);
1999
- if (table === (q.q.as || q.table)) {
2000
- result[key || column] = shape[column];
2001
- } else {
2002
- const it = (_b = (_a = query.joinedShapes) == null ? void 0 : _a[table]) == null ? void 0 : _b[column];
2003
- if (it)
2004
- result[key || column] = maybeUnNameColumn(it, isSubQuery);
2081
+ };
2082
+ const parseRecord = (parsers, row) => {
2083
+ for (const key in parsers) {
2084
+ if (key in row) {
2085
+ row[key] = parsers[key](row[key]);
2005
2086
  }
2006
- } else if (arg === "*") {
2007
- for (const key2 in shape) {
2008
- result[key2] = maybeUnNameColumn(shape[key2], isSubQuery);
2087
+ }
2088
+ return row;
2089
+ };
2090
+ const parseRows = (parsers, fields, rows) => {
2091
+ for (let i = fields.length - 1; i >= 0; i--) {
2092
+ const parser = parsers[fields[i].name];
2093
+ if (parser) {
2094
+ for (const row of rows) {
2095
+ row[i] = parser(row[i]);
2096
+ }
2009
2097
  }
2010
- } else {
2011
- result[key || arg] = maybeUnNameColumn(shape[arg], isSubQuery);
2012
2098
  }
2099
+ return rows;
2013
2100
  };
2014
- const maybeUnNameColumn = (column, isSubQuery) => {
2015
- return isSubQuery && (column == null ? void 0 : column.data.name) ? setColumnData(column, "name", void 0) : column;
2101
+ const parseValue = (value, parsers) => {
2102
+ const parser = parsers == null ? void 0 : parsers[getValueKey];
2103
+ return parser ? parser(value) : value;
2016
2104
  };
2017
- function _querySelect(q, args) {
2018
- if (!args.length) {
2019
- return q;
2105
+ const filterResult = (q, returnType, queryResult, hookSelect, result) => {
2106
+ var _a;
2107
+ if (returnType === "all") {
2108
+ const pick = getSelectPick(queryResult, hookSelect);
2109
+ return result.map((full) => {
2110
+ const filtered = {};
2111
+ for (const key of pick) {
2112
+ filtered[key] = full[key];
2113
+ }
2114
+ return filtered;
2115
+ });
2020
2116
  }
2021
- const as = q.q.as || q.table;
2022
- const selectArgs = args.map((item) => processSelectArg(q, as, item));
2023
- return pushQueryArray(q, "select", selectArgs);
2024
- }
2025
- class Select {
2026
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2027
- select(...args) {
2028
- return _querySelect(this.clone(), args);
2117
+ if (returnType === "oneOrThrow" || returnType === "one") {
2118
+ const row = result[0];
2119
+ if (!row) {
2120
+ if (returnType === "oneOrThrow")
2121
+ throw new NotFoundError(q);
2122
+ return void 0;
2123
+ } else {
2124
+ result = {};
2125
+ for (const key in row) {
2126
+ if (!hookSelect.includes(key)) {
2127
+ result[key] = row[key];
2128
+ }
2129
+ }
2130
+ return result;
2131
+ }
2029
2132
  }
2030
- /**
2031
- * When querying the table or creating records, all columns are selected by default,
2032
- * but updating and deleting queries are returning affected row counts by default.
2033
- *
2034
- * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
2035
- *
2036
- * ```ts
2037
- * const selectFull = await db.table
2038
- * .select('id', 'name') // discarded by `selectAll`
2039
- * .selectAll();
2040
- *
2041
- * const updatedFull = await db.table.selectAll().where(conditions).update(data);
2042
- *
2043
- * const deletedFull = await db.table.selectAll().where(conditions).delete();
2044
- * ```
2045
- */
2046
- selectAll() {
2047
- const q = this.clone();
2048
- q.q.select = ["*"];
2049
- return q;
2133
+ if (returnType === "value") {
2134
+ return (_a = result[0]) == null ? void 0 : _a[queryResult.fields[0].name];
2050
2135
  }
2051
- }
2052
-
2053
- class SelectItemExpression extends Expression {
2054
- constructor(q, item, _type) {
2055
- super();
2056
- this.q = q;
2057
- this.item = item;
2058
- this._type = _type;
2136
+ if (returnType === "valueOrThrow") {
2137
+ const row = result[0];
2138
+ if (!row)
2139
+ throw new NotFoundError(q);
2140
+ return row[queryResult.fields[0].name];
2059
2141
  }
2060
- // `makeSQL` acts similarly to how select args are handled,
2061
- // except that it will use non-aliasing `columnToSql` when `ctx.aliasValue` is true,
2062
- // it is needed for relation sub-queries that returns a single column.
2063
- makeSQL(ctx, quotedAs) {
2064
- return typeof this.item === "string" ? this.item === "*" ? selectAllSql(this.q, this.q.q, quotedAs) : ctx.aliasValue ? columnToSql(ctx, this.q.q, this.q.q.shape, this.item, quotedAs, true) : columnToSqlWithAs(ctx, this.q.q, this.item, quotedAs, true) : selectedObjectToSQL(ctx, this.q, quotedAs, this.item);
2142
+ if (returnType === "rowCount") {
2143
+ return queryResult.rowCount;
2065
2144
  }
2066
- }
2145
+ if (returnType === "pluck") {
2146
+ const key = queryResult.fields[0].name;
2147
+ return result.map((row) => row[key]);
2148
+ }
2149
+ if (returnType === "rows") {
2150
+ const pick = getSelectPick(queryResult, hookSelect);
2151
+ return result.map(
2152
+ (full) => pick.map((key) => full[key])
2153
+ );
2154
+ }
2155
+ return;
2156
+ };
2157
+ const getSelectPick = (queryResult, hookSelect) => {
2158
+ const pick = [];
2159
+ for (const field of queryResult.fields) {
2160
+ if (!hookSelect.includes(field.name))
2161
+ pick.push(field.name);
2162
+ }
2163
+ return pick;
2164
+ };
2067
2165
 
2068
- const _get = (query, returnType, arg) => {
2069
- var _a, _b;
2070
- const q = query.q;
2071
- q.returnType = returnType;
2072
- let type;
2166
+ const addParserForRawExpression = (q, key, raw) => {
2167
+ const type = raw._type;
2168
+ if (type.parseFn)
2169
+ setParserToQuery(q.q, key, type.parseFn);
2170
+ };
2171
+ const subQueryResult = {
2172
+ // sub query can't return a rowCount, use -1 as for impossible case
2173
+ rowCount: -1,
2174
+ rows: emptyArray,
2175
+ fields: emptyArray
2176
+ };
2177
+ const addParsersForSelectJoined = (q, arg, as = arg) => {
2178
+ var _a;
2179
+ const parsers = (_a = q.q.joinedParsers) == null ? void 0 : _a[arg];
2180
+ if (parsers) {
2181
+ setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
2182
+ }
2183
+ };
2184
+ const addParserForSelectItem = (q, as, key, arg) => {
2185
+ if (typeof arg === "object" || typeof arg === "function") {
2186
+ if (isExpression(arg)) {
2187
+ addParserForRawExpression(q, key, arg);
2188
+ } else {
2189
+ const { q: query } = arg;
2190
+ if (query.parsers || query.transform) {
2191
+ setParserToQuery(q.q, key, (item) => {
2192
+ const t = query.returnType || "all";
2193
+ subQueryResult.rows = t === "value" || t === "valueOrThrow" ? [[item]] : t === "one" || t === "oneOrThrow" ? [item] : item;
2194
+ return applyTransforms(
2195
+ query.transform,
2196
+ query.handleResult(arg, t, subQueryResult, true)
2197
+ );
2198
+ });
2199
+ }
2200
+ }
2201
+ return arg;
2202
+ }
2203
+ return setParserForSelectedString(q, arg, as, key);
2204
+ };
2205
+ const emptyArrSQL = new RawSQL("'[]'");
2206
+ const processSelectArg = (q, as, arg, columnAs) => {
2207
+ var _a, _b, _c, _d;
2073
2208
  if (typeof arg === "string") {
2074
- type = q.shape[arg];
2075
- if (!type) {
2076
- const index = arg.indexOf(".");
2077
- if (index !== -1) {
2078
- const table = arg.slice(0, index);
2079
- const column = arg.slice(index + 1);
2080
- if (table === (q.as || query.table)) {
2081
- type = q.shape[column];
2209
+ return setParserForSelectedString(q, arg, as, columnAs);
2210
+ }
2211
+ const selectAs = {};
2212
+ for (const key in arg) {
2213
+ let value = arg[key];
2214
+ if (typeof value === "function") {
2215
+ value = resolveSubQueryCallback(q, value);
2216
+ if (!isExpression(value) && value.joinQuery) {
2217
+ value = value.joinQuery(value, q);
2218
+ let query;
2219
+ const returnType = value.q.returnType;
2220
+ if (!returnType || returnType === "all") {
2221
+ query = value.json(false);
2222
+ value.q.coalesceValue = emptyArrSQL;
2223
+ } else if (returnType === "pluck") {
2224
+ query = value.wrap(value.baseQuery.clone()).jsonAgg(value.q.select[0]);
2225
+ value.q.coalesceValue = emptyArrSQL;
2082
2226
  } else {
2083
- type = (_b = (_a = q.joinedShapes) == null ? void 0 : _a[table]) == null ? void 0 : _b[column];
2227
+ if ((returnType === "value" || returnType === "valueOrThrow") && value.q.select) {
2228
+ if (typeof value.q.select[0] === "string") {
2229
+ value.q.select[0] = {
2230
+ selectAs: { r: value.q.select[0] }
2231
+ };
2232
+ }
2233
+ }
2234
+ query = value;
2235
+ }
2236
+ let asOverride = key;
2237
+ if ((_a = value.q.joinedShapes) == null ? void 0 : _a[key]) {
2238
+ let suffix = 2;
2239
+ const joinOverrides = (_c = (_b = q.q).joinOverrides) != null ? _c : _b.joinOverrides = {};
2240
+ while (joinOverrides[asOverride = `${key}${suffix}`]) {
2241
+ suffix++;
2242
+ }
2243
+ joinOverrides[asOverride] = asOverride;
2244
+ joinOverrides[key] = asOverride;
2084
2245
  }
2246
+ value.q.joinedForSelect = asOverride;
2247
+ _joinLateral(
2248
+ q,
2249
+ value.q.innerJoinLateral ? "JOIN" : "LEFT JOIN",
2250
+ query,
2251
+ (q2) => q2,
2252
+ key
2253
+ );
2254
+ } else if (((_d = value.q) == null ? void 0 : _d.isSubQuery) && value.q.expr) {
2255
+ value = value.q.expr;
2085
2256
  }
2086
2257
  }
2087
- q[getValueKey] = type;
2088
- setParserForSelectedString(
2089
- query,
2090
- arg,
2091
- getQueryAs(query),
2092
- getValueKey
2093
- );
2094
- q.expr = new SelectItemExpression(
2095
- query,
2096
- arg,
2097
- type || emptyObject
2258
+ selectAs[key] = addParserForSelectItem(
2259
+ q,
2260
+ as,
2261
+ key,
2262
+ value
2098
2263
  );
2099
- } else {
2100
- type = arg._type;
2101
- q[getValueKey] = type;
2102
- addParserForRawExpression(query, getValueKey, arg);
2103
- q.expr = arg;
2104
2264
  }
2105
- q.select = [q.expr];
2106
- return setQueryOperators(
2107
- query,
2108
- (type == null ? void 0 : type.operators) || Operators.any
2109
- );
2110
- };
2111
- function _queryGet(self, arg) {
2112
- return _get(self, "valueOrThrow", arg);
2113
- }
2114
- function _queryGetOptional(self, arg) {
2115
- return _get(self, "value", arg);
2116
- }
2117
-
2118
- const _queryAs = (self, as) => {
2119
- self.q.as = as;
2120
- return self;
2265
+ return { selectAs };
2121
2266
  };
2122
- class AsMethods {
2123
- /**
2124
- * Sets table alias:
2125
- *
2126
- * ```ts
2127
- * db.table.as('u').select('u.name');
2128
- *
2129
- * // Can be used in the join:
2130
- * db.table.join(Profile.as('p'), 'p.userId', 'user.id');
2131
- * ```
2132
- *
2133
- * @param as - alias for the table of this query
2134
- */
2135
- as(as) {
2136
- return _queryAs(this.clone(), as);
2137
- }
2138
- }
2139
-
2140
- function queryFrom(self, arg, options) {
2141
- const data = self.q;
2142
- if (typeof arg === "string") {
2143
- data.as || (data.as = arg);
2144
- } else if (!isExpression(arg)) {
2145
- const q = arg;
2146
- data.as || (data.as = q.q.as || q.table || "t");
2147
- data.shape = getShapeFromSelect(arg, true);
2148
- data.parsers = q.q.parsers;
2267
+ const setParserForSelectedString = (q, arg, as, columnAs) => {
2268
+ var _a, _b, _c, _d;
2269
+ const index = arg.indexOf(".");
2270
+ if (index !== -1) {
2271
+ const table = arg.slice(0, index);
2272
+ const column = arg.slice(index + 1);
2273
+ if (column === "*") {
2274
+ addParsersForSelectJoined(q, table, columnAs);
2275
+ return table === as ? column : arg;
2276
+ } else {
2277
+ if (table === as) {
2278
+ const parser = (_a = q.q.parsers) == null ? void 0 : _a[column];
2279
+ if (parser)
2280
+ setParserToQuery(q.q, columnAs || column, parser);
2281
+ return column;
2282
+ } else {
2283
+ const parser = (_c = (_b = q.q.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
2284
+ if (parser)
2285
+ setParserToQuery(q.q, columnAs || column, parser);
2286
+ return arg;
2287
+ }
2288
+ }
2149
2289
  } else {
2150
- data.as || (data.as = "t");
2151
- }
2152
- if (options == null ? void 0 : options.only) {
2153
- data.fromOnly = options.only;
2290
+ const parser = (_d = q.q.parsers) == null ? void 0 : _d[arg];
2291
+ if (parser)
2292
+ setParserToQuery(q.q, columnAs || arg, parser);
2293
+ return arg;
2154
2294
  }
2155
- data.from = arg;
2156
- return self;
2157
- }
2158
- function queryFromSql(self, args) {
2159
- const data = self.q;
2160
- data.as || (data.as = "t");
2161
- data.from = sqlQueryArgsToExpression(args);
2162
- return self;
2163
- }
2164
- class From {
2165
- /**
2166
- * Set the `FROM` value, by default the table name is used.
2167
- *
2168
- * ```ts
2295
+ };
2296
+ const getShapeFromSelect = (q, isSubQuery) => {
2297
+ const query = q.q;
2298
+ const { select, shape } = query;
2299
+ let result;
2300
+ if (!select) {
2301
+ if (isSubQuery) {
2302
+ result = {};
2303
+ for (const key in shape) {
2304
+ const column = shape[key];
2305
+ result[key] = column.data.name ? setColumnData(column, "name", void 0) : column;
2306
+ }
2307
+ } else {
2308
+ result = shape;
2309
+ }
2310
+ } else {
2311
+ result = {};
2312
+ for (const item of select) {
2313
+ if (typeof item === "string") {
2314
+ addColumnToShapeFromSelect(q, item, shape, query, result, isSubQuery);
2315
+ } else if ("selectAs" in item) {
2316
+ for (const key in item.selectAs) {
2317
+ const it = item.selectAs[key];
2318
+ if (typeof it === "string") {
2319
+ addColumnToShapeFromSelect(
2320
+ q,
2321
+ it,
2322
+ shape,
2323
+ query,
2324
+ result,
2325
+ isSubQuery,
2326
+ key
2327
+ );
2328
+ } else if (isExpression(it)) {
2329
+ result[key] = it._type;
2330
+ } else {
2331
+ const { returnType } = it.q;
2332
+ if (returnType === "value" || returnType === "valueOrThrow") {
2333
+ const type = it.q[getValueKey];
2334
+ if (type)
2335
+ result[key] = type;
2336
+ } else {
2337
+ result[key] = new JSONTextColumn(defaultSchemaConfig);
2338
+ }
2339
+ }
2340
+ }
2341
+ }
2342
+ }
2343
+ }
2344
+ return result;
2345
+ };
2346
+ const addColumnToShapeFromSelect = (q, arg, shape, query, result, isSubQuery, key) => {
2347
+ var _a, _b;
2348
+ if (q.relations[arg]) {
2349
+ result[key || arg] = emptyObject;
2350
+ return;
2351
+ }
2352
+ const index = arg.indexOf(".");
2353
+ if (index !== -1) {
2354
+ const table = arg.slice(0, index);
2355
+ const column = arg.slice(index + 1);
2356
+ if (table === (q.q.as || q.table)) {
2357
+ result[key || column] = shape[column];
2358
+ } else {
2359
+ const it = (_b = (_a = query.joinedShapes) == null ? void 0 : _a[table]) == null ? void 0 : _b[column];
2360
+ if (it)
2361
+ result[key || column] = maybeUnNameColumn(it, isSubQuery);
2362
+ }
2363
+ } else if (arg === "*") {
2364
+ for (const key2 in shape) {
2365
+ result[key2] = maybeUnNameColumn(shape[key2], isSubQuery);
2366
+ }
2367
+ } else {
2368
+ result[key || arg] = maybeUnNameColumn(shape[arg], isSubQuery);
2369
+ }
2370
+ };
2371
+ const maybeUnNameColumn = (column, isSubQuery) => {
2372
+ return isSubQuery && (column == null ? void 0 : column.data.name) ? setColumnData(column, "name", void 0) : column;
2373
+ };
2374
+ function _querySelect(q, args) {
2375
+ if (!args.length) {
2376
+ return q;
2377
+ }
2378
+ const as = q.q.as || q.table;
2379
+ const selectArgs = args.map((item) => processSelectArg(q, as, item));
2380
+ return pushQueryArray(q, "select", selectArgs);
2381
+ }
2382
+ class Select {
2383
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2384
+ select(...args) {
2385
+ return _querySelect(this.clone(), args);
2386
+ }
2387
+ /**
2388
+ * When querying the table or creating records, all columns are selected by default,
2389
+ * but updating and deleting queries are returning affected row counts by default.
2390
+ *
2391
+ * Use `selectAll` to select all columns. If the `.select` method was applied before it will be discarded.
2392
+ *
2393
+ * ```ts
2394
+ * const selectFull = await db.table
2395
+ * .select('id', 'name') // discarded by `selectAll`
2396
+ * .selectAll();
2397
+ *
2398
+ * const updatedFull = await db.table.selectAll().where(conditions).update(data);
2399
+ *
2400
+ * const deletedFull = await db.table.selectAll().where(conditions).delete();
2401
+ * ```
2402
+ */
2403
+ selectAll() {
2404
+ const q = this.clone();
2405
+ q.q.select = ["*"];
2406
+ return q;
2407
+ }
2408
+ }
2409
+
2410
+ class SelectItemExpression extends Expression {
2411
+ constructor(q, item, _type) {
2412
+ super();
2413
+ this.q = q;
2414
+ this.item = item;
2415
+ this._type = _type;
2416
+ }
2417
+ // `makeSQL` acts similarly to how select args are handled,
2418
+ // except that it will use non-aliasing `columnToSql` when `ctx.aliasValue` is true,
2419
+ // it is needed for relation sub-queries that returns a single column.
2420
+ makeSQL(ctx, quotedAs) {
2421
+ return typeof this.item === "string" ? this.item === "*" ? selectAllSql(this.q, this.q.q, quotedAs) : ctx.aliasValue ? columnToSql(ctx, this.q.q, this.q.q.shape, this.item, quotedAs, true) : columnToSqlWithAs(ctx, this.q.q, this.item, quotedAs, true) : selectedObjectToSQL(ctx, this.q, quotedAs, this.item);
2422
+ }
2423
+ }
2424
+
2425
+ const _get = (query, returnType, arg) => {
2426
+ var _a, _b;
2427
+ const q = query.q;
2428
+ q.returnType = returnType;
2429
+ let type;
2430
+ if (typeof arg === "string") {
2431
+ type = q.shape[arg];
2432
+ if (!type) {
2433
+ const index = arg.indexOf(".");
2434
+ if (index !== -1) {
2435
+ const table = arg.slice(0, index);
2436
+ const column = arg.slice(index + 1);
2437
+ if (table === (q.as || query.table)) {
2438
+ type = q.shape[column];
2439
+ } else {
2440
+ type = (_b = (_a = q.joinedShapes) == null ? void 0 : _a[table]) == null ? void 0 : _b[column];
2441
+ }
2442
+ }
2443
+ }
2444
+ q[getValueKey] = type;
2445
+ setParserForSelectedString(
2446
+ query,
2447
+ arg,
2448
+ getQueryAs(query),
2449
+ getValueKey
2450
+ );
2451
+ q.expr = new SelectItemExpression(
2452
+ query,
2453
+ arg,
2454
+ type || emptyObject
2455
+ );
2456
+ } else {
2457
+ type = arg._type;
2458
+ q[getValueKey] = type;
2459
+ addParserForRawExpression(query, getValueKey, arg);
2460
+ q.expr = arg;
2461
+ }
2462
+ q.select = [q.expr];
2463
+ return setQueryOperators(
2464
+ query,
2465
+ (type == null ? void 0 : type.operators) || Operators.any
2466
+ );
2467
+ };
2468
+ function _queryGet(self, arg) {
2469
+ return _get(self, "valueOrThrow", arg);
2470
+ }
2471
+ function _queryGetOptional(self, arg) {
2472
+ return _get(self, "value", arg);
2473
+ }
2474
+
2475
+ const _queryAs = (self, as) => {
2476
+ self.q.as = as;
2477
+ return self;
2478
+ };
2479
+ class AsMethods {
2480
+ /**
2481
+ * Sets table alias:
2482
+ *
2483
+ * ```ts
2484
+ * db.table.as('u').select('u.name');
2485
+ *
2486
+ * // Can be used in the join:
2487
+ * db.table.join(Profile.as('p'), 'p.userId', 'user.id');
2488
+ * ```
2489
+ *
2490
+ * @param as - alias for the table of this query
2491
+ */
2492
+ as(as) {
2493
+ return _queryAs(this.clone(), as);
2494
+ }
2495
+ }
2496
+
2497
+ function queryFrom(self, arg, options) {
2498
+ const data = self.q;
2499
+ if (typeof arg === "string") {
2500
+ data.as || (data.as = arg);
2501
+ } else if (!isExpression(arg)) {
2502
+ const q = arg;
2503
+ data.as || (data.as = q.q.as || q.table || "t");
2504
+ data.shape = getShapeFromSelect(arg, true);
2505
+ data.parsers = q.q.parsers;
2506
+ } else {
2507
+ data.as || (data.as = "t");
2508
+ }
2509
+ if (options == null ? void 0 : options.only) {
2510
+ data.fromOnly = options.only;
2511
+ }
2512
+ data.from = arg;
2513
+ return self;
2514
+ }
2515
+ function queryFromSql(self, args) {
2516
+ const data = self.q;
2517
+ data.as || (data.as = "t");
2518
+ data.from = sqlQueryArgsToExpression(args);
2519
+ return self;
2520
+ }
2521
+ class From {
2522
+ /**
2523
+ * Set the `FROM` value, by default the table name is used.
2524
+ *
2525
+ * ```ts
2169
2526
  * // accepts sub-query:
2170
2527
  * db.table.from(Otherdb.table.select('foo', 'bar'));
2171
2528
  *
@@ -8262,366 +8619,6 @@ class MergeQueryMethods {
8262
8619
  }
8263
8620
  }
8264
8621
 
8265
- const queryMethodByReturnType = {
8266
- all: "query",
8267
- rows: "arrays",
8268
- pluck: "arrays",
8269
- one: "query",
8270
- oneOrThrow: "query",
8271
- value: "arrays",
8272
- valueOrThrow: "arrays",
8273
- rowCount: "arrays",
8274
- void: "arrays"
8275
- };
8276
- class Then {
8277
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8278
- catch(fn) {
8279
- return this.then(void 0, fn);
8280
- }
8281
- }
8282
- let queryError = void 0;
8283
- let getThen;
8284
- if (process.versions.bun) {
8285
- getThen = function() {
8286
- queryError = new Error();
8287
- if (!this.internal)
8288
- return maybeWrappedThen;
8289
- const trx = this.internal.transactionStorage.getStore();
8290
- if (!trx)
8291
- return maybeWrappedThen;
8292
- return (resolve, reject) => {
8293
- return this.internal.transactionStorage.run(trx, () => {
8294
- return maybeWrappedThen.call(this, resolve, reject);
8295
- });
8296
- };
8297
- };
8298
- } else {
8299
- getThen = function() {
8300
- queryError = new Error();
8301
- return maybeWrappedThen;
8302
- };
8303
- }
8304
- Object.defineProperty(Then.prototype, "then", {
8305
- get: getThen,
8306
- set(value) {
8307
- Object.defineProperty(this, "then", {
8308
- value
8309
- });
8310
- }
8311
- });
8312
- const handleResult = (q, returnType, result, isSubQuery) => {
8313
- return parseResult(q, q.q.parsers, returnType, result, isSubQuery);
8314
- };
8315
- function maybeWrappedThen(resolve, reject) {
8316
- const { q } = this;
8317
- let beforeHooks;
8318
- let afterHooks;
8319
- let afterCommitHooks;
8320
- if (q.type) {
8321
- if (q.type === "insert") {
8322
- beforeHooks = q.beforeCreate;
8323
- afterHooks = q.afterCreate;
8324
- afterCommitHooks = q.afterCreateCommit;
8325
- } else if (q.type === "update") {
8326
- beforeHooks = q.beforeUpdate;
8327
- afterHooks = q.afterUpdate;
8328
- afterCommitHooks = q.afterUpdateCommit;
8329
- } else if (q.type === "delete") {
8330
- beforeHooks = q.beforeDelete;
8331
- afterHooks = q.afterDelete;
8332
- afterCommitHooks = q.afterDeleteCommit;
8333
- }
8334
- }
8335
- const trx = this.internal.transactionStorage.getStore();
8336
- if ((q.wrapInTransaction || afterHooks) && !trx) {
8337
- return this.transaction(
8338
- () => new Promise((resolve2, reject2) => {
8339
- const trx2 = this.internal.transactionStorage.getStore();
8340
- return then(
8341
- this,
8342
- trx2.adapter,
8343
- trx2,
8344
- beforeHooks,
8345
- afterHooks,
8346
- afterCommitHooks,
8347
- resolve2,
8348
- reject2
8349
- );
8350
- })
8351
- ).then(resolve, reject);
8352
- } else {
8353
- return then(
8354
- this,
8355
- (trx == null ? void 0 : trx.adapter) || this.q.adapter,
8356
- trx,
8357
- beforeHooks,
8358
- afterHooks,
8359
- afterCommitHooks,
8360
- resolve,
8361
- reject
8362
- );
8363
- }
8364
- }
8365
- const queriesNames = {};
8366
- let nameI = 0;
8367
- const callAfterHook = function(cb) {
8368
- return cb(this[0], this[1]);
8369
- };
8370
- const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks, resolve, reject) => {
8371
- var _a;
8372
- const { q: query } = q;
8373
- let sql;
8374
- let logData;
8375
- const localError = queryError;
8376
- try {
8377
- if (beforeHooks || query.before) {
8378
- await Promise.all(
8379
- [...beforeHooks || emptyArray, ...query.before || emptyArray].map(
8380
- callWithThis,
8381
- q
8382
- )
8383
- );
8384
- }
8385
- sql = q.toSQL();
8386
- const { hookSelect } = sql;
8387
- if (query.autoPreparedStatements) {
8388
- sql.name = queriesNames[sql.text] || (queriesNames[sql.text] = (nameI++).toString(36));
8389
- }
8390
- if (query.log) {
8391
- logData = query.log.beforeQuery(sql);
8392
- }
8393
- const { returnType = "all" } = query;
8394
- const returns = hookSelect ? "all" : returnType;
8395
- const queryResult = await adapter[hookSelect ? "query" : queryMethodByReturnType[returnType]](sql);
8396
- if (query.patchResult) {
8397
- await query.patchResult(q, queryResult);
8398
- }
8399
- if (query.log) {
8400
- query.log.afterQuery(sql, logData);
8401
- sql = void 0;
8402
- }
8403
- let result = query.handleResult(q, returns, queryResult);
8404
- if (afterHooks || afterCommitHooks || query.after) {
8405
- if (queryResult.rowCount) {
8406
- if (afterHooks || query.after) {
8407
- const args = [result, q];
8408
- await Promise.all(
8409
- [...afterHooks || emptyArray, ...query.after || emptyArray].map(
8410
- callAfterHook,
8411
- args
8412
- )
8413
- );
8414
- }
8415
- if (afterCommitHooks && trx) {
8416
- ((_a = trx.afterCommit) != null ? _a : trx.afterCommit = []).push(
8417
- result,
8418
- q,
8419
- afterCommitHooks
8420
- );
8421
- } else if (afterCommitHooks) {
8422
- const args = [result, q];
8423
- await Promise.all(afterCommitHooks.map(callAfterHook, args));
8424
- }
8425
- } else if (query.after) {
8426
- const args = [result, q];
8427
- await Promise.all(query.after.map(callAfterHook, args));
8428
- }
8429
- if (hookSelect)
8430
- result = filterResult(q, returnType, queryResult, hookSelect, result);
8431
- }
8432
- if (query.transform) {
8433
- for (const fn of query.transform) {
8434
- result = fn(result);
8435
- }
8436
- }
8437
- return resolve == null ? void 0 : resolve(result);
8438
- } catch (err) {
8439
- let error;
8440
- if (err instanceof pg.DatabaseError) {
8441
- error = new q.error();
8442
- assignError(error, err);
8443
- error.cause = localError;
8444
- } else {
8445
- error = err;
8446
- if (error instanceof Error) {
8447
- error.cause = localError;
8448
- }
8449
- }
8450
- if (query.log && sql) {
8451
- query.log.onError(error, sql, logData);
8452
- }
8453
- return reject == null ? void 0 : reject(error);
8454
- }
8455
- };
8456
- const assignError = (to, from) => {
8457
- to.message = from.message;
8458
- to.length = from.length;
8459
- to.name = from.name;
8460
- to.severity = from.severity;
8461
- to.code = from.code;
8462
- to.detail = from.detail;
8463
- to.hint = from.hint;
8464
- to.position = from.position;
8465
- to.internalPosition = from.internalPosition;
8466
- to.internalQuery = from.internalQuery;
8467
- to.where = from.where;
8468
- to.schema = from.schema;
8469
- to.table = from.table;
8470
- to.column = from.column;
8471
- to.dataType = from.dataType;
8472
- to.constraint = from.constraint;
8473
- to.file = from.file;
8474
- to.line = from.line;
8475
- to.routine = from.routine;
8476
- return to;
8477
- };
8478
- const parseResult = (q, parsers, returnType = "all", result, isSubQuery) => {
8479
- var _a, _b;
8480
- switch (returnType) {
8481
- case "all": {
8482
- if (q.q.throwOnNotFound && result.rows.length === 0)
8483
- throw new NotFoundError(q);
8484
- const { rows } = result;
8485
- if (parsers) {
8486
- for (const row of rows) {
8487
- parseRecord(parsers, row);
8488
- }
8489
- }
8490
- return rows;
8491
- }
8492
- case "one": {
8493
- const row = result.rows[0];
8494
- if (!row)
8495
- return;
8496
- return parsers ? parseRecord(parsers, row) : row;
8497
- }
8498
- case "oneOrThrow": {
8499
- const row = result.rows[0];
8500
- if (!row)
8501
- throw new NotFoundError(q);
8502
- return parsers ? parseRecord(parsers, row) : row;
8503
- }
8504
- case "rows": {
8505
- return parsers ? parseRows(
8506
- parsers,
8507
- result.fields,
8508
- result.rows
8509
- ) : result.rows;
8510
- }
8511
- case "pluck": {
8512
- const pluck = parsers == null ? void 0 : parsers.pluck;
8513
- if (pluck) {
8514
- return result.rows.map(isSubQuery ? pluck : (row) => pluck(row[0]));
8515
- } else if (isSubQuery) {
8516
- return result.rows;
8517
- }
8518
- return result.rows.map((row) => row[0]);
8519
- }
8520
- case "value": {
8521
- const value = (_a = result.rows[0]) == null ? void 0 : _a[0];
8522
- return value !== void 0 ? parseValue(value, parsers) : q.q.notFoundDefault;
8523
- }
8524
- case "valueOrThrow": {
8525
- const value = (_b = result.rows[0]) == null ? void 0 : _b[0];
8526
- if (value === void 0)
8527
- throw new NotFoundError(q);
8528
- return parseValue(value, parsers);
8529
- }
8530
- case "rowCount": {
8531
- if (q.q.throwOnNotFound && result.rowCount === 0) {
8532
- throw new NotFoundError(q);
8533
- }
8534
- return result.rowCount;
8535
- }
8536
- case "void": {
8537
- return;
8538
- }
8539
- }
8540
- };
8541
- const parseRecord = (parsers, row) => {
8542
- for (const key in parsers) {
8543
- if (key in row) {
8544
- row[key] = parsers[key](row[key]);
8545
- }
8546
- }
8547
- return row;
8548
- };
8549
- const parseRows = (parsers, fields, rows) => {
8550
- for (let i = fields.length - 1; i >= 0; i--) {
8551
- const parser = parsers[fields[i].name];
8552
- if (parser) {
8553
- for (const row of rows) {
8554
- row[i] = parser(row[i]);
8555
- }
8556
- }
8557
- }
8558
- return rows;
8559
- };
8560
- const parseValue = (value, parsers) => {
8561
- const parser = parsers == null ? void 0 : parsers[getValueKey];
8562
- return parser ? parser(value) : value;
8563
- };
8564
- const filterResult = (q, returnType, queryResult, hookSelect, result) => {
8565
- var _a;
8566
- if (returnType === "all") {
8567
- const pick = getSelectPick(queryResult, hookSelect);
8568
- return result.map((full) => {
8569
- const filtered = {};
8570
- for (const key of pick) {
8571
- filtered[key] = full[key];
8572
- }
8573
- return filtered;
8574
- });
8575
- }
8576
- if (returnType === "oneOrThrow" || returnType === "one") {
8577
- const row = result[0];
8578
- if (!row) {
8579
- if (returnType === "oneOrThrow")
8580
- throw new NotFoundError(q);
8581
- return void 0;
8582
- } else {
8583
- result = {};
8584
- for (const key in row) {
8585
- if (!hookSelect.includes(key)) {
8586
- result[key] = row[key];
8587
- }
8588
- }
8589
- return result;
8590
- }
8591
- }
8592
- if (returnType === "value") {
8593
- return (_a = result[0]) == null ? void 0 : _a[queryResult.fields[0].name];
8594
- }
8595
- if (returnType === "valueOrThrow") {
8596
- const row = result[0];
8597
- if (!row)
8598
- throw new NotFoundError(q);
8599
- return row[queryResult.fields[0].name];
8600
- }
8601
- if (returnType === "rowCount") {
8602
- return queryResult.rowCount;
8603
- }
8604
- if (returnType === "pluck") {
8605
- const key = queryResult.fields[0].name;
8606
- return result.map((row) => row[key]);
8607
- }
8608
- if (returnType === "rows") {
8609
- const pick = getSelectPick(queryResult, hookSelect);
8610
- return result.map(
8611
- (full) => pick.map((key) => full[key])
8612
- );
8613
- }
8614
- return;
8615
- };
8616
- const getSelectPick = (queryResult, hookSelect) => {
8617
- const pick = [];
8618
- for (const field of queryResult.fields) {
8619
- if (!hookSelect.includes(field.name))
8620
- pick.push(field.name);
8621
- }
8622
- return pick;
8623
- };
8624
-
8625
8622
  var __defProp$4 = Object.defineProperty;
8626
8623
  var __defProps$2 = Object.defineProperties;
8627
8624
  var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;