pqb 0.4.6 → 0.4.8

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.
Files changed (53) hide show
  1. package/dist/index.d.ts +25 -11
  2. package/dist/index.esm.js +78 -40
  3. package/dist/index.esm.js.map +1 -1
  4. package/dist/index.js +79 -39
  5. package/dist/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/src/columnSchema/columnType.test.ts +220 -0
  8. package/src/columnSchema/columnType.ts +7 -0
  9. package/src/columnSchema/columnTypes.test.ts +55 -53
  10. package/src/columnSchema/dateTime.ts +11 -0
  11. package/src/columnSchema/timestamps.test.ts +3 -4
  12. package/src/columnSchema/timestamps.ts +1 -1
  13. package/src/columnsOperators.test.ts +18 -19
  14. package/src/columnsOperators.ts +1 -1
  15. package/src/common.ts +17 -30
  16. package/src/db.ts +23 -9
  17. package/src/errors.test.ts +2 -4
  18. package/src/index.ts +1 -1
  19. package/src/query.ts +7 -1
  20. package/src/queryMethods/aggregate.test.ts +9 -7
  21. package/src/queryMethods/create.test.ts +48 -5
  22. package/src/queryMethods/create.ts +28 -6
  23. package/src/queryMethods/for.test.ts +1 -2
  24. package/src/queryMethods/for.ts +1 -1
  25. package/src/queryMethods/from.test.ts +2 -3
  26. package/src/queryMethods/get.test.ts +5 -5
  27. package/src/queryMethods/having.test.ts +6 -5
  28. package/src/queryMethods/index.ts +1 -0
  29. package/src/queryMethods/json.ts +2 -2
  30. package/src/queryMethods/merge.test.ts +10 -4
  31. package/src/queryMethods/queryMethods.test.ts +10 -12
  32. package/src/queryMethods/queryMethods.ts +7 -4
  33. package/src/queryMethods/raw.test.ts +19 -0
  34. package/src/queryMethods/raw.ts +27 -0
  35. package/src/queryMethods/select.test.ts +4 -4
  36. package/src/queryMethods/then.test.ts +2 -4
  37. package/src/queryMethods/union.test.ts +11 -6
  38. package/src/queryMethods/update.test.ts +21 -3
  39. package/src/queryMethods/update.ts +11 -1
  40. package/src/queryMethods/where.test.ts +65 -56
  41. package/src/queryMethods/where.ts +1 -1
  42. package/src/queryMethods/with.test.ts +5 -6
  43. package/src/sql/common.ts +0 -1
  44. package/src/sql/fromAndAs.ts +1 -1
  45. package/src/sql/insert.ts +1 -1
  46. package/src/sql/join.ts +1 -1
  47. package/src/sql/orderBy.ts +1 -1
  48. package/src/sql/select.ts +1 -2
  49. package/src/sql/toSql.ts +1 -1
  50. package/src/sql/update.ts +1 -1
  51. package/src/sql/where.ts +1 -1
  52. package/src/sql/window.ts +3 -4
  53. package/src/sql/with.ts +1 -1
package/dist/index.d.ts CHANGED
@@ -7,6 +7,10 @@ declare type RawExpression<C extends ColumnType = ColumnType> = {
7
7
  __values: unknown[];
8
8
  __column: C;
9
9
  };
10
+ declare const raw: (sql: string, ...values: unknown[]) => RawExpression;
11
+ declare const isRaw: (obj: object) => obj is RawExpression<ColumnType<unknown, Operators, unknown>>;
12
+ declare const getRaw: (raw: RawExpression, values: unknown[]) => string;
13
+ declare const getRawSql: (raw: RawExpression) => string;
10
14
  declare type Expression<T extends Query = Query, C extends ColumnType = ColumnType> = StringKey<keyof T['selectable']> | RawExpression<C>;
11
15
  declare type ExpressionOfType<T extends Query, C extends ColumnType, Type> = {
12
16
  [K in keyof T['selectable']]: ColumnOutput<T['selectable'][K]['column']> extends Type | null ? K : never;
@@ -15,10 +19,6 @@ declare type NumberExpression<T extends Query, C extends ColumnType = ColumnType
15
19
  declare type StringExpression<T extends Query, C extends ColumnType = ColumnType> = ExpressionOfType<T, C, string>;
16
20
  declare type BooleanExpression<T extends Query, C extends ColumnType = ColumnType> = ExpressionOfType<T, C, boolean>;
17
21
  declare type ExpressionOutput<T extends Query, Expr extends Expression<T>> = Expr extends keyof T['selectable'] ? T['selectable'][Expr]['column'] : Expr extends RawExpression<infer ColumnType> ? ColumnType : never;
18
- declare const raw: <C extends ColumnType<unknown, Operators, unknown>>(...args: [column: C, sql: string, ...values: unknown[]] | [sql: string, ...values: unknown[]]) => RawExpression<C>;
19
- declare const isRaw: (obj: object) => obj is RawExpression<ColumnType<unknown, Operators, unknown>>;
20
- declare const getRaw: (raw: RawExpression, values: unknown[]) => string;
21
- declare const getRawSql: (raw: RawExpression) => string;
22
22
  declare const EMPTY_OBJECT: {};
23
23
  declare const getQueryParsers: (q: Query) => ColumnsParsers | undefined;
24
24
 
@@ -877,11 +877,13 @@ declare class UnhandledTypeError extends PormInternalError {
877
877
  declare type DbTableOptions = {
878
878
  schema?: string;
879
879
  } & QueryLogOptions;
880
- interface Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations']> extends QueryMethods {
881
- new (adapter: Adapter, queryBuilder: Db, table?: Table, shape?: Shape, options?: DbTableOptions): this;
880
+ declare const anyShape: Record<string, ColumnType<unknown, Operators, unknown>>;
881
+ interface Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = ColumnTypesBase> extends QueryMethods {
882
+ new (adapter: Adapter, queryBuilder: Db<Table, Shape, Relations, CT>, table?: Table, shape?: Shape, options?: DbTableOptions): this;
882
883
  adapter: Adapter;
883
884
  columns: (keyof ColumnShapeOutput<Shape>)[];
884
885
  queryBuilder: Db;
886
+ columnTypes: CT;
885
887
  whereQueryBuilder: Query['whereQueryBuilder'];
886
888
  onQueryBuilder: Query['onQueryBuilder'];
887
889
  table: Table;
@@ -920,16 +922,17 @@ interface Db<Table extends string | undefined = undefined, Shape extends Columns
920
922
  [K in keyof Shape]: Shape[K]['hasDefault'] extends true ? K : never;
921
923
  }[keyof Shape], true>;
922
924
  }
923
- declare class Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations']> implements Query {
925
+ declare class Db<Table extends string | undefined = undefined, Shape extends ColumnsShape = Record<string, never>, Relations extends Query['relations'] = Query['relations'], CT extends ColumnTypesBase = ColumnTypesBase> implements Query {
924
926
  adapter: Adapter;
925
927
  queryBuilder: Db;
926
928
  table: Table;
927
929
  shape: Shape;
930
+ columnTypes: CT;
928
931
  whereQueryBuilder: typeof WhereQueryBuilder;
929
932
  onQueryBuilder: typeof OnQueryBuilder;
930
- constructor(adapter: Adapter, queryBuilder: Db, table: Table, shape: Shape, options: DbTableOptions);
933
+ constructor(adapter: Adapter, queryBuilder: Db, table: Table, shape: Shape, columnTypes: CT, options: DbTableOptions);
931
934
  }
932
- declare type DbResult<CT extends ColumnTypesBase> = Db & {
935
+ declare type DbResult<CT extends ColumnTypesBase> = Db<string, Record<string, never>, Query['relations'], CT> & {
933
936
  <Table extends string, Shape extends ColumnsShape = ColumnsShape>(table: Table, shape?: ((t: CT) => Shape) | Shape, options?: DbTableOptions): Db<Table, Shape>;
934
937
  adapter: Adapter;
935
938
  close: Adapter['close'];
@@ -1313,6 +1316,11 @@ declare class MergeQueryMethods {
1313
1316
  _merge<T extends Query, Q extends Query>(this: T, q: Q): MergeQuery<T, Q>;
1314
1317
  }
1315
1318
 
1319
+ declare type RawArgs<CT extends ColumnTypesBase, C extends ColumnType> = [column: (types: CT) => C, sql: string, ...values: unknown[]] | [sql: string, ...values: unknown[]];
1320
+ declare class RawMethods {
1321
+ raw<T extends Query, C extends ColumnType>(this: T, ...args: RawArgs<T['columnTypes'], C>): RawExpression<C>;
1322
+ }
1323
+
1316
1324
  declare type WindowArg<T extends Query> = Record<string, WindowArgDeclaration<T> | RawExpression>;
1317
1325
  declare type WindowArgDeclaration<T extends Query = Query> = {
1318
1326
  partitionBy?: Expression<T> | Expression<T>[];
@@ -1325,7 +1333,7 @@ declare type OrderArg<T extends Query> = keyof T['selectable'] | {
1325
1333
  nulls: 'FIRST' | 'LAST';
1326
1334
  };
1327
1335
  } | RawExpression;
1328
- interface QueryMethods extends Aggregate, Select, From, Join, With, Union, Json, Create, Update, Delete, Transaction, For, ColumnInfoMethods, Where, Clear, Having, Window, Then, QueryLog, QueryCallbacks, QueryUpsert, QueryGet, MergeQueryMethods {
1336
+ interface QueryMethods extends Aggregate, Select, From, Join, With, Union, Json, Create, Update, Delete, Transaction, For, ColumnInfoMethods, Where, Clear, Having, Window, Then, QueryLog, QueryCallbacks, QueryUpsert, QueryGet, MergeQueryMethods, RawMethods {
1329
1337
  }
1330
1338
  declare class QueryMethods {
1331
1339
  windows: EmptyObject;
@@ -1542,6 +1550,7 @@ declare type defaultsKey = typeof defaultsKey;
1542
1550
  declare const defaultsKey: unique symbol;
1543
1551
  declare type Query = QueryMethods & {
1544
1552
  queryBuilder: Db;
1553
+ columnTypes: ColumnTypesBase;
1545
1554
  whereQueryBuilder: typeof WhereQueryBuilder;
1546
1555
  onQueryBuilder: typeof OnQueryBuilder;
1547
1556
  table?: string;
@@ -2338,6 +2347,7 @@ declare abstract class ColumnType<Type = unknown, Ops extends Operators = Operat
2338
2347
  parse<T extends ColumnType, Output>(this: T, fn: (input: T['type']) => Output): Omit<T, 'type'> & {
2339
2348
  type: Output;
2340
2349
  };
2350
+ as<T extends ColumnType, C extends ColumnType<T['type'], Operators, T['inputType']>>(this: T, _: C): C;
2341
2351
  toSQL(): string;
2342
2352
  default<T extends ColumnType>(this: T, value: T['type'] | RawExpression): T & {
2343
2353
  hasDefault: true;
@@ -3412,6 +3422,10 @@ declare abstract class DateBaseColumn extends ColumnType<string, typeof Operator
3412
3422
  type: Query | RawExpression<ColumnType<unknown, Operators, unknown>> | Date[];
3413
3423
  };
3414
3424
  };
3425
+ asNumber(): IntegerColumn;
3426
+ asDate<T extends ColumnType>(this: T): Omit<T, "type"> & {
3427
+ type: Date;
3428
+ };
3415
3429
  }
3416
3430
  declare class DateColumn extends DateBaseColumn {
3417
3431
  dataType: "date";
@@ -4329,4 +4343,4 @@ declare const setQueryObjectValue: <T extends {
4329
4343
  query: QueryData;
4330
4344
  }>(q: T, object: string, key: string, value: unknown) => T;
4331
4345
 
4332
- export { Adapter, AdapterOptions, AddQueryJoinedTable, AddQuerySelect, AddQueryWith, AfterCallback, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, AnyColumnType, AnyColumnTypeCreator, ArrayCardinality, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AssertArray, BaseNumberData, BaseRelation, BaseStringData, BeforeCallback, BelongsToNestedInsert, BelongsToNestedUpdate, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ClearStatement, CoalesceString, ColumnData, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnInput, ColumnNameOfModel, ColumnOperators, ColumnOutput, ColumnParser, ColumnShapeInput, ColumnShapeOutput, ColumnType, ColumnTypes, ColumnTypesBase, ColumnsObject, ColumnsParsers, ColumnsShape, CommonQueryData, Create, CreateData, CreateMethodsNames, DateBaseColumn, DateColumn, DateColumnData, DateTimeBaseClass, DateTimeColumnData, DateTimeWithTimeZoneBaseClass, Db, DbOptions, DbTableOptions, DecimalBaseColumn, DecimalColumn, DecimalColumnData, DeepPartial, DefaultSelectColumns, Delete, DeleteMethodsNames, DeleteQueryData, DoublePrecisionColumn, DropMode, EMPTY_OBJECT, EmptyObject, EnumColumn, EnumLike, Except, Expression, ExpressionOfType, ExpressionOutput, FilterTuple, For, ForeignKey, ForeignKeyModel, ForeignKeyModelWithColumns, ForeignKeyOptions, From, GetArg, HasAndBelongsToManyRelation, HasManyNestedInsert, HasManyNestedUpdate, HasManyRelation, HasOneNestedInsert, HasOneNestedUpdate, HasOneRelation, Having, HavingArg, HavingItem, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsEqual, JSONAny, JSONArray, JSONBigInt, JSONBoolean, JSONColumn, JSONDate, JSONDiscriminatedObject, JSONDiscriminatedUnion, JSONEnum, JSONInstanceOf, JSONIntersection, JSONLazy, JSONLiteral, JSONMap, JSONNaN, JSONNativeEnum, JSONNever, JSONNotNullable, JSONNotNullish, JSONNull, JSONNullable, JSONNullish, JSONNumber, JSONObject, JSONObjectShape, JSONOptional, JSONRecord, JSONRecordKeyType, JSONRequired, JSONSet, JSONString, JSONTextColumn, JSONTuple, JSONTupleItems, JSONType, JSONTypeAny, JSONTypeData, JSONTypes, JSONUndefined, JSONUnion, JSONUnknown, JSONVoid, Join, JoinArgs, JoinCallback, JoinCallbackArg, JoinItem, JoinedTablesBase, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MaybeArray, Merge, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NestedInsertItem, NestedInsertManyItems, NestedInsertOneItem, NestedUpdateItem, NestedUpdateManyItems, NestedUpdateOneItem, NotFoundError, NullableColumn, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrderArg, OrderItem, OutputTypeOfTuple, OutputTypeOfTupleWithRest, OwnTypeProps, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, Primitive, Query, QueryArraysResult, QueryBase, QueryCallbacks, QueryData, QueryError, QueryErrorName, QueryGet, QueryInput, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryResultRow, QueryReturnType, QueryReturnsAll, QuerySelectAll, QueryThen, QueryUpsert, QueryWithTable, RawExpression, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SerialColumn, SetOptional, SetQueryJoinedTables, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumnInfo, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWindows, SetQueryWith, SimpleSpread, SingleColumnIndexOptions, SinglePrimaryKey, SmallIntColumn, SmallSerialColumn, SomeIsTrue, SortDir, Spread, Sql, StringColumn, StringExpression, StringKey, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, ThenResult, TimeColumn, TimeInterval, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnknownKeysParam, Update, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertData, UpsertResult, UpsertThis, ValidationContext, VarCharColumn, Where, WhereArg, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addQuestionMarks, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, applyMixins, array, arrayToEnum, baseObjectOutputType, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, flatten, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, identity, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
4346
+ export { Adapter, AdapterOptions, AddQueryJoinedTable, AddQuerySelect, AddQueryWith, AfterCallback, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, AnyColumnType, AnyColumnTypeCreator, ArrayCardinality, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AssertArray, BaseNumberData, BaseRelation, BaseStringData, BeforeCallback, BelongsToNestedInsert, BelongsToNestedUpdate, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ClearStatement, CoalesceString, ColumnData, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnInput, ColumnNameOfModel, ColumnOperators, ColumnOutput, ColumnParser, ColumnShapeInput, ColumnShapeOutput, ColumnType, ColumnTypes, ColumnTypesBase, ColumnsObject, ColumnsParsers, ColumnsShape, CommonQueryData, Create, CreateData, CreateMethodsNames, DateBaseColumn, DateColumn, DateColumnData, DateTimeBaseClass, DateTimeColumnData, DateTimeWithTimeZoneBaseClass, Db, DbOptions, DbTableOptions, DecimalBaseColumn, DecimalColumn, DecimalColumnData, DeepPartial, DefaultSelectColumns, Delete, DeleteMethodsNames, DeleteQueryData, DoublePrecisionColumn, DropMode, EMPTY_OBJECT, EmptyObject, EnumColumn, EnumLike, Except, Expression, ExpressionOfType, ExpressionOutput, FilterTuple, For, ForeignKey, ForeignKeyModel, ForeignKeyModelWithColumns, ForeignKeyOptions, From, GetArg, HasAndBelongsToManyRelation, HasManyNestedInsert, HasManyNestedUpdate, HasManyRelation, HasOneNestedInsert, HasOneNestedUpdate, HasOneRelation, Having, HavingArg, HavingItem, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsEqual, JSONAny, JSONArray, JSONBigInt, JSONBoolean, JSONColumn, JSONDate, JSONDiscriminatedObject, JSONDiscriminatedUnion, JSONEnum, JSONInstanceOf, JSONIntersection, JSONLazy, JSONLiteral, JSONMap, JSONNaN, JSONNativeEnum, JSONNever, JSONNotNullable, JSONNotNullish, JSONNull, JSONNullable, JSONNullish, JSONNumber, JSONObject, JSONObjectShape, JSONOptional, JSONRecord, JSONRecordKeyType, JSONRequired, JSONSet, JSONString, JSONTextColumn, JSONTuple, JSONTupleItems, JSONType, JSONTypeAny, JSONTypeData, JSONTypes, JSONUndefined, JSONUnion, JSONUnknown, JSONVoid, Join, JoinArgs, JoinCallback, JoinCallbackArg, JoinItem, JoinedTablesBase, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MaybeArray, Merge, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NestedInsertItem, NestedInsertManyItems, NestedInsertOneItem, NestedUpdateItem, NestedUpdateManyItems, NestedUpdateOneItem, NotFoundError, NullableColumn, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrderArg, OrderItem, OutputTypeOfTuple, OutputTypeOfTupleWithRest, OwnTypeProps, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, Primitive, Query, QueryArraysResult, QueryBase, QueryCallbacks, QueryData, QueryError, QueryErrorName, QueryGet, QueryInput, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryResultRow, QueryReturnType, QueryReturnsAll, QuerySelectAll, QueryThen, QueryUpsert, QueryWithTable, RawExpression, RawMethods, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SerialColumn, SetOptional, SetQueryJoinedTables, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumnInfo, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWindows, SetQueryWith, SimpleSpread, SingleColumnIndexOptions, SinglePrimaryKey, SmallIntColumn, SmallSerialColumn, SomeIsTrue, SortDir, Spread, Sql, StringColumn, StringExpression, StringKey, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, ThenResult, TimeColumn, TimeInterval, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnknownKeysParam, Update, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertData, UpsertResult, UpsertThis, ValidationContext, VarCharColumn, Where, WhereArg, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addQuestionMarks, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, applyMixins, array, arrayToEnum, baseObjectOutputType, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, flatten, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, identity, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
package/dist/index.esm.js CHANGED
@@ -66,6 +66,9 @@ class ColumnType {
66
66
  this.parseItem = fn;
67
67
  return this;
68
68
  }
69
+ as(_) {
70
+ return this;
71
+ }
69
72
  toSQL() {
70
73
  return this.dataType;
71
74
  }
@@ -115,33 +118,6 @@ class ColumnType {
115
118
  }
116
119
  }
117
120
 
118
- const raw = (...args) => {
119
- if (typeof args[0] === "string") {
120
- return {
121
- __raw: args[0],
122
- __values: args.slice(1)
123
- };
124
- } else {
125
- return {
126
- __column: args[0],
127
- __raw: args[1],
128
- __values: args.slice(2)
129
- };
130
- }
131
- };
132
- const isRaw = (obj) => "__raw" in obj;
133
- const getRaw = (raw2, values) => {
134
- values.push(...raw2.__values);
135
- return raw2.__raw;
136
- };
137
- const getRawSql = (raw2) => {
138
- return raw2.__raw;
139
- };
140
- const EMPTY_OBJECT = {};
141
- const getQueryParsers = (q) => {
142
- return q.query.parsers || q.columnsParsers;
143
- };
144
-
145
121
  const singleQuoteRegex = /'/g;
146
122
  const doubleQuoteRegex = /"/g;
147
123
  const quoteValue$1 = (value) => {
@@ -180,6 +156,23 @@ const quote = (value) => {
180
156
  return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
181
157
  };
182
158
 
159
+ const raw = (sql, ...values) => ({
160
+ __raw: sql,
161
+ __values: values
162
+ });
163
+ const isRaw = (obj) => "__raw" in obj;
164
+ const getRaw = (raw2, values) => {
165
+ values.push(...raw2.__values);
166
+ return raw2.__raw;
167
+ };
168
+ const getRawSql = (raw2) => {
169
+ return raw2.__raw;
170
+ };
171
+ const EMPTY_OBJECT = {};
172
+ const getQueryParsers = (q) => {
173
+ return q.query.parsers || q.columnsParsers;
174
+ };
175
+
183
176
  const q = (sql) => `"${sql}"`;
184
177
  const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
185
178
  const quoteFullColumn = (fullColumn, quotedAs) => {
@@ -1959,6 +1952,14 @@ class DateBaseColumn extends ColumnType {
1959
1952
  this.data = {};
1960
1953
  this.operators = Operators.date;
1961
1954
  }
1955
+ asNumber() {
1956
+ return this.encode((input) => new Date(input)).parse(
1957
+ Date.parse
1958
+ );
1959
+ }
1960
+ asDate() {
1961
+ return this.parse((input) => new Date(input));
1962
+ }
1962
1963
  }
1963
1964
  assignMethodsToClass(DateBaseColumn, dateTypeMethods);
1964
1965
  class DateColumn extends DateBaseColumn {
@@ -4184,8 +4185,9 @@ const handleSelect = (q) => {
4184
4185
  q.query.select = ["*"];
4185
4186
  }
4186
4187
  };
4187
- const processCreateItem = (item, rowIndex, ctx, columns, columnsMap) => {
4188
+ const processCreateItem = (item, rowIndex, ctx, columns, encoders, columnsMap, shape) => {
4188
4189
  Object.keys(item).forEach((key) => {
4190
+ var _a;
4189
4191
  if (ctx.relations[key]) {
4190
4192
  if (ctx.relations[key].type === "belongsTo") {
4191
4193
  const foreignKey = ctx.relations[key].options.foreignKey;
@@ -4210,8 +4212,9 @@ const processCreateItem = (item, rowIndex, ctx, columns, columnsMap) => {
4210
4212
  item[key]
4211
4213
  ]);
4212
4214
  }
4213
- } else if (columnsMap[key] === void 0) {
4215
+ } else if (columnsMap[key] === void 0 && (shape[key] || shape === anyShape)) {
4214
4216
  columnsMap[key] = columns.length;
4217
+ encoders[key] = (_a = shape[key]) == null ? void 0 : _a.encodeFn;
4215
4218
  columns.push(key);
4216
4219
  }
4217
4220
  });
@@ -4238,30 +4241,37 @@ const getManyReturnType = (q) => {
4238
4241
  return "rowCount";
4239
4242
  }
4240
4243
  };
4244
+ const mapColumnValues = (columns, encoders, data) => {
4245
+ return columns.map(
4246
+ (key) => encoders[key] ? encoders[key](data[key]) : data[key]
4247
+ );
4248
+ };
4241
4249
  const handleOneData = (q, data, ctx) => {
4242
4250
  const columns = [];
4251
+ const encoders = {};
4243
4252
  const columnsMap = {};
4244
4253
  const defaults = q.query.defaults;
4245
4254
  if (defaults) {
4246
4255
  data = __spreadValues$4(__spreadValues$4({}, defaults), data);
4247
4256
  }
4248
- processCreateItem(data, 0, ctx, columns, columnsMap);
4249
- const values = [columns.map((key) => data[key])];
4257
+ processCreateItem(data, 0, ctx, columns, encoders, columnsMap, q.shape);
4258
+ const values = [mapColumnValues(columns, encoders, data)];
4250
4259
  return { columns, values };
4251
4260
  };
4252
4261
  const handleManyData = (q, data, ctx) => {
4253
4262
  const columns = [];
4263
+ const encoders = {};
4254
4264
  const columnsMap = {};
4255
4265
  const defaults = q.query.defaults;
4256
4266
  if (defaults) {
4257
4267
  data = data.map((item) => __spreadValues$4(__spreadValues$4({}, defaults), item));
4258
4268
  }
4259
4269
  data.forEach((item, i) => {
4260
- processCreateItem(item, i, ctx, columns, columnsMap);
4270
+ processCreateItem(item, i, ctx, columns, encoders, columnsMap, q.shape);
4261
4271
  });
4262
4272
  const values = Array(data.length);
4263
4273
  data.forEach((item, i) => {
4264
- values[i] = columns.map((key) => item[key]);
4274
+ values[i] = mapColumnValues(columns, encoders, item);
4265
4275
  });
4266
4276
  return { columns, values };
4267
4277
  };
@@ -4762,7 +4772,7 @@ class Json {
4762
4772
  _json() {
4763
4773
  const q = this._wrap(this.__model.clone());
4764
4774
  q._getOptional(
4765
- raw(
4775
+ this.raw(
4766
4776
  queryTypeWithLimitOne[this.query.returnType] ? `row_to_json("t".*)` : `COALESCE(json_agg(row_to_json("t".*)), '[]')`
4767
4777
  )
4768
4778
  );
@@ -5133,7 +5143,7 @@ class Update {
5133
5143
  const data = args[0];
5134
5144
  const set = __spreadValues$1({}, data);
5135
5145
  pushQueryValue(this, "updateData", set);
5136
- const relations = this.relations;
5146
+ const { relations, shape } = this;
5137
5147
  const prependRelations = {};
5138
5148
  const appendRelations = {};
5139
5149
  const originalReturnType = query.returnType || "all";
@@ -5151,6 +5161,12 @@ class Update {
5151
5161
  }
5152
5162
  appendRelations[key] = data[key];
5153
5163
  }
5164
+ } else if (!shape[key] && shape !== anyShape) {
5165
+ delete set[key];
5166
+ } else {
5167
+ const encode = shape[key].encodeFn;
5168
+ if (encode)
5169
+ set[key] = encode(set[key]);
5154
5170
  }
5155
5171
  }
5156
5172
  const state = {};
@@ -5377,6 +5393,23 @@ class QueryUpsert {
5377
5393
  }
5378
5394
  }
5379
5395
 
5396
+ class RawMethods {
5397
+ raw(...args) {
5398
+ if (typeof args[0] === "string") {
5399
+ return {
5400
+ __raw: args[0],
5401
+ __values: args.slice(1)
5402
+ };
5403
+ } else {
5404
+ return {
5405
+ __column: args[0](this.columnTypes),
5406
+ __raw: args[1],
5407
+ __values: args.slice(2)
5408
+ };
5409
+ }
5410
+ }
5411
+ }
5412
+
5380
5413
  class QueryMethods {
5381
5414
  all() {
5382
5415
  return this.clone()._all();
@@ -5496,7 +5529,7 @@ class QueryMethods {
5496
5529
  _wrap(query, as) {
5497
5530
  const sql = this.toSql();
5498
5531
  return query.as(as != null ? as : "t")._from(
5499
- raw(`(${sql.text})`, ...sql.values)
5532
+ this.raw(`(${sql.text})`, ...sql.values)
5500
5533
  );
5501
5534
  }
5502
5535
  order(...args) {
@@ -5523,7 +5556,7 @@ class QueryMethods {
5523
5556
  return this.clone()._exists();
5524
5557
  }
5525
5558
  _exists() {
5526
- const q = this._getOptional(raw("true"));
5559
+ const q = this._getOptional(this.raw("true"));
5527
5560
  q.query.notFoundDefault = false;
5528
5561
  q.query.coalesceValue = false;
5529
5562
  return q;
@@ -5566,7 +5599,8 @@ applyMixins(QueryMethods, [
5566
5599
  QueryCallbacks,
5567
5600
  QueryUpsert,
5568
5601
  QueryGet,
5569
- MergeQueryMethods
5602
+ MergeQueryMethods,
5603
+ RawMethods
5570
5604
  ]);
5571
5605
 
5572
5606
  var __defProp = Object.defineProperty;
@@ -5597,12 +5631,14 @@ var __objRest = (source, exclude) => {
5597
5631
  }
5598
5632
  return target;
5599
5633
  };
5634
+ const anyShape = {};
5600
5635
  class Db {
5601
- constructor(adapter, queryBuilder, table = void 0, shape = {}, options) {
5636
+ constructor(adapter, queryBuilder, table = void 0, shape = anyShape, columnTypes, options) {
5602
5637
  this.adapter = adapter;
5603
5638
  this.queryBuilder = queryBuilder;
5604
5639
  this.table = table;
5605
5640
  this.shape = shape;
5641
+ this.columnTypes = columnTypes;
5606
5642
  this.whereQueryBuilder = WhereQueryBuilder;
5607
5643
  this.onQueryBuilder = OnQueryBuilder;
5608
5644
  this.__model = this;
@@ -5677,6 +5713,7 @@ const createDb = (_a) => {
5677
5713
  void 0,
5678
5714
  void 0,
5679
5715
  {},
5716
+ ct,
5680
5717
  commonOptions
5681
5718
  );
5682
5719
  qb.queryBuilder = qb;
@@ -5687,6 +5724,7 @@ const createDb = (_a) => {
5687
5724
  qb,
5688
5725
  table,
5689
5726
  typeof shape === "function" ? getColumnTypes(ct, shape) : shape,
5727
+ ct,
5690
5728
  __spreadValues(__spreadValues({}, commonOptions), options2)
5691
5729
  );
5692
5730
  },
@@ -5699,5 +5737,5 @@ const createDb = (_a) => {
5699
5737
  return db;
5700
5738
  };
5701
5739
 
5702
- export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, Create, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, applyMixins, array, arrayToEnum, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
5740
+ export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, Create, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RawMethods, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, applyMixins, array, arrayToEnum, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
5703
5741
  //# sourceMappingURL=index.esm.js.map