pqb 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,9 @@ import {
4
4
  ColumnsParsers,
5
5
  Query,
6
6
  QueryBase,
7
+ QueryReturnsAll,
7
8
  QuerySelectAll,
9
+ queryTypeWithLimitOne,
8
10
  } from '../query';
9
11
  import {
10
12
  ArrayOfColumnsObjects,
@@ -75,7 +77,7 @@ type SelectResult<
75
77
 
76
78
  type SelectSubQueryResult<
77
79
  Arg extends Query & { [isRequiredRelationKey]?: boolean },
78
- > = Arg['returnType'] extends 'all'
80
+ > = QueryReturnsAll<Arg['returnType']> extends true
79
81
  ? ArrayOfColumnsObjects<Arg['result']>
80
82
  : Arg['returnType'] extends 'valueOrThrow'
81
83
  ? Arg['result']['value']
@@ -107,7 +109,7 @@ export const addParserForSelectItem = <T extends Query>(
107
109
  const rel = arg(q);
108
110
  const parsers = getQueryParsers(rel);
109
111
  if (parsers) {
110
- if (rel.query.take) {
112
+ if (queryTypeWithLimitOne[rel.query.returnType]) {
111
113
  addParserToQuery(q.query, key, (item) => parseRecord(parsers, item));
112
114
  } else {
113
115
  addParserToQuery(q.query, key, (items) =>
@@ -49,7 +49,7 @@ export const handleResult: CommonQueryData['handleResult'] = async (
49
49
  q,
50
50
  result: QueryResult,
51
51
  ) => {
52
- return parseResult(q, q.query.returnType, result);
52
+ return parseResult(q, q.query.returnType || 'all', result);
53
53
  };
54
54
 
55
55
  const then = async (
@@ -89,7 +89,7 @@ const then = async (
89
89
  }
90
90
 
91
91
  const queryResult = await q.query.adapter[
92
- queryMethodByReturnType[q.query.returnType] as 'query'
92
+ queryMethodByReturnType[q.query.returnType || 'all'] as 'query'
93
93
  ](sql);
94
94
 
95
95
  if (q.query.log) {
@@ -119,7 +119,7 @@ const then = async (
119
119
 
120
120
  export const parseResult = (
121
121
  q: Query,
122
- returnType: QueryReturnType,
122
+ returnType: QueryReturnType | undefined = 'all',
123
123
  result: QueryResult,
124
124
  ): unknown => {
125
125
  switch (returnType) {
@@ -1,4 +1,4 @@
1
- import { Query, SetQueryReturnsRowCount } from '../query';
1
+ import { Query, QueryReturnsAll, SetQueryReturnsRowCount } from '../query';
2
2
  import { pushQueryArray, pushQueryValue } from '../queryDataUtils';
3
3
  import { isRaw, RawExpression, StringKey } from '../common';
4
4
  import {
@@ -43,7 +43,7 @@ type UpdateBelongsToData<T extends Query, Rel extends BelongsToRelation> =
43
43
  | {
44
44
  create: InsertData<Rel['nestedCreateQuery']>;
45
45
  }
46
- | (T['returnType'] extends 'all'
46
+ | (QueryReturnsAll<T['returnType']> extends true
47
47
  ? never
48
48
  : {
49
49
  upsert: {
@@ -56,7 +56,7 @@ type UpdateHasOneData<T extends Query, Rel extends HasOneRelation> =
56
56
  | { disconnect: boolean }
57
57
  | { delete: boolean }
58
58
  | { update: UpdateData<Rel['model']> }
59
- | (T['returnType'] extends 'all'
59
+ | (QueryReturnsAll<T['returnType']> extends true
60
60
  ? never
61
61
  :
62
62
  | { set: WhereArg<Rel['model']> }
@@ -77,7 +77,7 @@ type UpdateHasManyData<T extends Query, Rel extends HasManyRelation> = {
77
77
  where: MaybeArray<WhereArg<Rel['model']>>;
78
78
  data: UpdateData<Rel['model']>;
79
79
  };
80
- } & (T['returnType'] extends 'all'
80
+ } & (QueryReturnsAll<T['returnType']> extends true
81
81
  ? EmptyObject
82
82
  : {
83
83
  set?: MaybeArray<WhereArg<Rel['model']>>;
@@ -107,9 +107,9 @@ type UpdateRawArgs<T extends Query, ForceAll extends boolean> = (
107
107
  ? [update: RawExpression]
108
108
  : [update: RawExpression, forceAll: true];
109
109
 
110
- type UpdateResult<T extends Query> = T['hasSelect'] extends false
111
- ? SetQueryReturnsRowCount<T>
112
- : T;
110
+ type UpdateResult<T extends Query> = T['hasSelect'] extends true
111
+ ? T
112
+ : SetQueryReturnsRowCount<T>;
113
113
 
114
114
  type ChangeCountArg<T extends Query> =
115
115
  | keyof T['shape']
@@ -179,7 +179,7 @@ export class Update {
179
179
  const prependRelations: Record<string, Record<string, unknown>> = {};
180
180
  const appendRelations: Record<string, Record<string, unknown>> = {};
181
181
 
182
- const originalReturnType = query.returnType;
182
+ const originalReturnType = query.returnType || 'all';
183
183
 
184
184
  for (const key in data) {
185
185
  if (relations[key]) {
@@ -287,6 +287,11 @@ export class Update {
287
287
  appendRelationKeys.map((relationName) => {
288
288
  return (q: Query, result: Record<string, unknown>[]) => {
289
289
  const all = resultOfTypeAll || result;
290
+
291
+ if (q.query.returnType !== originalReturnType) {
292
+ q.query.returnType = originalReturnType;
293
+ }
294
+
290
295
  return (
291
296
  relations[relationName].nestedUpdate as HasOneNestedUpdate
292
297
  )?.(q, all, appendRelations[relationName] as NestedUpdateOneItem);
@@ -1,7 +1,7 @@
1
1
  import { getRaw, isRaw } from '../common';
2
2
  import { quoteSchemaAndTable } from './common';
3
3
  import { QueryBase } from '../query';
4
- import { queryKeysOfNotSimpleQuery, SelectQueryData } from './types';
4
+ import { checkIfASimpleQuery, SelectQueryData } from './types';
5
5
  import { ToSqlCtx } from './toSql';
6
6
 
7
7
  export const pushFromAndAs = (
@@ -38,9 +38,8 @@ const getFrom = (
38
38
  }
39
39
 
40
40
  const q = query.from.query;
41
- const keys = Object.keys(q) as (keyof SelectQueryData)[];
42
41
  // if query contains more than just schema return (SELECT ...)
43
- if (keys.some((key) => queryKeysOfNotSimpleQuery.includes(key))) {
42
+ if (!checkIfASimpleQuery(q)) {
44
43
  const sql = query.from.toSql({ values });
45
44
  return `(${sql.text})`;
46
45
  }
package/src/sql/select.ts CHANGED
@@ -142,7 +142,7 @@ const pushSubQuerySql = (
142
142
  values: unknown[],
143
143
  list: string[],
144
144
  ) => {
145
- const { returnType } = query.query;
145
+ const { returnType = 'all' } = query.query;
146
146
  switch (returnType) {
147
147
  case 'all':
148
148
  case 'one':
@@ -160,7 +160,6 @@ const pushSubQuerySql = (
160
160
  select[0] = { selectAs: { c: first } } as SelectItem;
161
161
  query = query._wrap(query.__model.clone()) as unknown as typeof query;
162
162
  query._getOptional(raw<StringColumn>(`COALESCE(json_agg("c"), '[]')`));
163
- delete query.query.take;
164
163
  break;
165
164
  }
166
165
  case 'rows':
package/src/sql/toSql.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getRaw, isRaw } from '../common';
2
- import { Query } from '../query';
2
+ import { Query, queryTypeWithLimitOne } from '../query';
3
3
  import { addValue, q, qc } from './common';
4
4
  import { JoinItem, QueryData, Sql } from './types';
5
5
  import { pushDistinctSql } from './distinct';
@@ -156,8 +156,9 @@ const makeSql = (model: Query, { values = [] }: ToSqlOptions = {}): Sql => {
156
156
  pushOrderBySql(ctx, quotedAs, query.order);
157
157
  }
158
158
 
159
- if (query.take || query.limit !== undefined) {
160
- sql.push(`LIMIT ${addValue(values, query.take ? 1 : query.limit)}`);
159
+ const limit = queryTypeWithLimitOne[query.returnType] ? 1 : query.limit;
160
+ if (limit) {
161
+ sql.push(`LIMIT ${addValue(values, limit)}`);
161
162
  }
162
163
 
163
164
  if (query.offset) {
package/src/sql/types.ts CHANGED
@@ -21,8 +21,13 @@ export type Sql = {
21
21
  };
22
22
 
23
23
  // used in `from` logic to decide if convert query to sql or just write table name
24
- export const queryKeysOfNotSimpleQuery: (keyof SelectQueryData)[] = [
25
- 'take',
24
+ export const checkIfASimpleQuery = (q: QueryData) => {
25
+ if (q.returnType && q.returnType !== 'all') return false;
26
+ const keys = Object.keys(q) as (keyof SelectQueryData)[];
27
+ return !keys.some((key) => queryKeysOfNotSimpleQuery.includes(key));
28
+ };
29
+
30
+ const queryKeysOfNotSimpleQuery: (keyof SelectQueryData)[] = [
26
31
  'with',
27
32
  'as',
28
33
  'from',
@@ -51,7 +56,6 @@ export type CommonQueryData = {
51
56
  inTransaction?: boolean;
52
57
  wrapInTransaction?: boolean;
53
58
  throwOnNotFound?: boolean;
54
- take?: boolean;
55
59
  with?: WithItem[];
56
60
  withShapes?: Record<string, ColumnsShape>;
57
61
  schema?: string;
package/src/sql/window.ts CHANGED
@@ -5,7 +5,7 @@ import { expressionToSql, q } from './common';
5
5
  import { orderByToSql } from './orderBy';
6
6
 
7
7
  export const windowToSql = <T extends Query>(
8
- window: T['windows'][number] | WindowDeclaration | RawExpression,
8
+ window: keyof T['windows'] | WindowDeclaration | RawExpression,
9
9
  values: unknown[],
10
10
  quotedAs?: string,
11
11
  ) => {
package/src/sql/with.ts CHANGED
@@ -7,26 +7,31 @@ export const pushWithSql = (
7
7
  ctx: ToSqlCtx,
8
8
  withData: Exclude<QueryData['with'], undefined>,
9
9
  ) => {
10
- withData.forEach((withItem) => {
11
- const [name, options, query] = withItem;
10
+ if (!withData.length) return;
12
11
 
13
- let inner: string;
14
- if (isRaw(query)) {
15
- inner = getRaw(query, ctx.values);
16
- } else {
17
- inner = query.toSql({ values: ctx.values }).text;
18
- }
12
+ ctx.sql.push(
13
+ 'WITH',
14
+ withData
15
+ .map((withItem) => {
16
+ const [name, options, query] = withItem;
19
17
 
20
- ctx.sql.push(
21
- `WITH ${options.recursive ? 'RECURSIVE ' : ''}${q(name)}${
22
- options.columns ? `(${options.columns.map(q).join(', ')})` : ''
23
- } AS ${
24
- options.materialized
25
- ? 'MATERIALIZED '
26
- : options.notMaterialized
27
- ? 'NOT MATERIALIZED '
28
- : ''
29
- }(${inner})`,
30
- );
31
- });
18
+ let inner: string;
19
+ if (isRaw(query)) {
20
+ inner = getRaw(query, ctx.values);
21
+ } else {
22
+ inner = query.toSql({ values: ctx.values }).text;
23
+ }
24
+
25
+ return `${options.recursive ? 'RECURSIVE ' : ''}${q(name)}${
26
+ options.columns ? `(${options.columns.map(q).join(', ')})` : ''
27
+ } AS ${
28
+ options.materialized
29
+ ? 'MATERIALIZED '
30
+ : options.notMaterialized
31
+ ? 'NOT MATERIALIZED '
32
+ : ''
33
+ }(${inner})`;
34
+ })
35
+ .join(', '),
36
+ );
32
37
  };
package/src/utils.ts CHANGED
@@ -38,24 +38,6 @@ export type UnionToOvlds<U> = UnionToIntersection<
38
38
  U extends any ? (f: U) => void : never
39
39
  >;
40
40
 
41
- type PopPropertyKeyUnion<U> = UnionToOvlds<U> extends (
42
- a: infer A extends PropertyKey,
43
- ) => void
44
- ? A
45
- : never;
46
-
47
- type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
48
-
49
- export type PropertyKeyUnionToArray<
50
- T,
51
- A extends PropertyKey[] = [],
52
- > = IsUnion<T> extends true
53
- ? PropertyKeyUnionToArray<
54
- Exclude<T, PopPropertyKeyUnion<T>>,
55
- [PopPropertyKeyUnion<T>, ...A]
56
- >
57
- : [T, ...A];
58
-
59
41
  type OptionalPropertyNames<T> = {
60
42
  // eslint-disable-next-line @typescript-eslint/ban-types
61
43
  [K in keyof T]-?: {} extends { [P in K]: T[K] } ? K : never;