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