Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

kysely-mapper

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kysely-mapper - npm Package Compare versions

Comparing version 0.4.1 to 0.4.2

dist/cjs/mappers/entire-row-transforms.d.ts

2

dist/cjs/index.d.ts

@@ -5,4 +5,4 @@ export * from './mappers/abstract-table-mapper';

export * from './mappers/table-mapper-transforms';
export * from './mappers/complete-row-transforms';
export * from './mappers/entire-row-transforms';
export * from './lib/query-filter';
//# sourceMappingURL=index.d.ts.map

@@ -21,4 +21,4 @@ "use strict";

__exportStar(require("./mappers/table-mapper-transforms"), exports);
__exportStar(require("./mappers/complete-row-transforms"), exports);
__exportStar(require("./mappers/entire-row-transforms"), exports);
__exportStar(require("./lib/query-filter"), exports);
//# sourceMappingURL=index.js.map

@@ -27,12 +27,12 @@ /**

/**
* A filter that matches one or more key columns.
*/
type KeyColumnFilter<DB, TB extends keyof DB, K extends keyof Selectable<DB[TB]> & string> = NonNullable<Selectable<DB[TB]>[K]>;
/**
* A filter that matches columns against the fields of an object.
*/
type FieldMatchingFilter<DB, TB extends keyof DB & string, RE extends ReferenceExpression<DB, TB>> = {
export type FieldMatchingFilter<DB, TB extends keyof DB & string, RE extends ReferenceExpression<DB, TB>> = {
[K in RE & string]?: SelectType<ExtractTypeFromStringReference<DB, TB, K>> | Readonly<SelectType<ExtractTypeFromStringReference<DB, TB, K>>[]>;
};
/**
* A filter that matches a single key column.
*/
type KeyColumnFilter<DB, TB extends keyof DB, K extends keyof Selectable<DB[TB]> & string> = NonNullable<Selectable<DB[TB]>[K]>;
export {};
//# sourceMappingURL=query-filter.d.ts.map

@@ -8,4 +8,4 @@ /**

* found in the table interface `T`. Supports up to 4 columns.
* @typeparam T Table interface.
* @typeparam KA Array of the key column names.
* @typeParam T Table interface.
* @typeParam KA Array of the key column names.
*/

@@ -20,4 +20,4 @@ export type KeyTuple<T, KA extends Readonly<(keyof Selectable<T> & string)[]>> = KA[3] extends string ? [

* Require specified properties of a type, leaving the rest optional.
* @typeparam T Type to require properties from.
* @typeparam K Keys of the properties to require.
* @typeParam T Type to require properties from.
* @typeParam K Keys of the properties to require.
*/

@@ -24,0 +24,0 @@ export type RequireSome<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;

@@ -20,21 +20,21 @@ import { Kysely, Insertable, ReferenceExpression, Selectable, InsertQueryBuilder, InsertResult, SelectQueryBuilder, Selection, DeleteQueryBuilder, DeleteResult, UpdateResult, UpdateQueryBuilder, ComparisonOperatorExpression, OperandValueExpressionOrList, Updateable } from 'kysely';

* mappers should extend this class with means for providing transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam ReturnCount Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam ReturnCount Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -41,0 +41,0 @@ */

@@ -26,21 +26,21 @@ "use strict";

* mappers should extend this class with means for providing transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam ReturnCount Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam ReturnCount Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -47,0 +47,0 @@ */

import { SelectableColumnTuple, SelectionColumn } from '../lib/type-utils';
/**
* Settings governing table mapper behavior, excluding transformations.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns

@@ -18,19 +18,21 @@ * none and is the default. May specify aliases.

export interface TableMapperSettings<DB, TB extends keyof DB & string, KeyColumns extends Readonly<SelectableColumnTuple<DB[TB]>> | Readonly<[]> = [], SelectedColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = ['*'], InsertReturnColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = Readonly<KeyColumns>, UpdateReturnColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = []> {
/** Tuple of the columns that make up the table's key. May be `[]`. */
/**
* Tuple of the columns that make up the table's key. Defaults to `[]`,
* indicating that no columns are keys.
*/
keyColumns?: KeyColumns;
/**
* Columns to return from selection queries. `[*]` selects all columns.
* May contain aliases.
* Columns to return from selection queries. Defaults to `[*]`, selecting
* all columns. May contain aliases.
*/
selectedColumns?: SelectedColumns;
/**
* Columns to return from the table on insert queries that return columns.
* `['*']` returns all columns; `[]` returns none. May specify aliases.
* Defaults to `KeyColumns`.
* Columns to return from insert queries that return columns. `['*']`
* returns all columns; `[]` returns none. May specify aliases. Defaults
* to `KeyColumns`.
*/
insertReturnColumns?: InsertReturnColumns;
/**
* Columns to return from the table on update queries that return columns.
* `['*']` returns all columns; `[]` returns none and is the default. May
* specify aliases.
* Columns to return from update queries that return columns. `['*']` returns
* all columns; `[]` returns none and is the default. May specify aliases.
*/

@@ -37,0 +39,0 @@ updateReturnColumns?: UpdateReturnColumns;

@@ -7,21 +7,21 @@ import { Insertable, Selectable, Selection, Updateable } from 'kysely';

* value is passed through unchanged.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -33,4 +33,5 @@ */

/**
* Transformation to apply to bigint count results before returning
* the count to the client. `count` is the count returned by the query.
* Transformation to apply to bigint count results indicating the number of
* rows affected, before returning the count to the client. `count` is the
* count returned by the query.
*/

@@ -37,0 +38,0 @@ countTransform?: (count: bigint) => ReturnCount;

@@ -8,21 +8,21 @@ import { Insertable, Selectable, Selection, Updateable } from 'kysely';

* unchanged, allowing the selective overloading of transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -32,4 +32,4 @@ */

/**
* Constructs a new table mapper.
* Returns a new table mapper that uses the provided transformations.
* Returns a new table mapper that uses the provided transformations, along
* with the settings of the current table mapper.
* @param transforms The transforms to use.

@@ -36,0 +36,0 @@ * @returns A new table mapper that uses the provided transforms.

@@ -8,21 +8,21 @@ "use strict";

* unchanged, allowing the selective overloading of transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -32,4 +32,4 @@ */

/**
* Constructs a new table mapper.
* Returns a new table mapper that uses the provided transformations.
* Returns a new table mapper that uses the provided transformations, along
* with the settings of the current table mapper.
* @param transforms The transforms to use.

@@ -36,0 +36,0 @@ * @returns A new table mapper that uses the provided transforms.

@@ -19,3 +19,3 @@ import { DeleteQueryBuilder, DeleteResult, Kysely } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -22,0 +22,0 @@ * @returns A compiling delete query.

@@ -28,3 +28,3 @@ "use strict";

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -31,0 +31,0 @@ * @returns A compiling delete query.

@@ -20,3 +20,3 @@ import { Kysely, SelectQueryBuilder } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling select query.

@@ -28,3 +28,3 @@ "use strict";

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -31,0 +31,0 @@ * @returns A compiling select query.

@@ -18,3 +18,3 @@ import { Kysely, InsertQueryBuilder, InsertResult, Insertable } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -21,0 +21,0 @@ * @returns A compiling insert query.

@@ -20,3 +20,3 @@ "use strict";

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling insert query.

@@ -20,3 +20,3 @@ import { Kysely, UpdateQueryBuilder, UpdateResult, Updateable } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling update query.

@@ -20,3 +20,3 @@ "use strict";

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling update query.

@@ -15,3 +15,3 @@ "use strict";

const table_mapper_1 = require("../mappers/table-mapper");
const complete_row_transforms_1 = require("../mappers/complete-row-transforms");
const entire_row_transforms_1 = require("../mappers/entire-row-transforms");
let db;

@@ -37,3 +37,3 @@ beforeAll(() => __awaiter(void 0, void 0, void 0, function* () {

updateReturnColumns: ['id', 'name'],
}).withTransforms(new complete_row_transforms_1.CompleteRowTransforms(keyColumns));
}).withTransforms(new entire_row_transforms_1.EntireRowTransforms(keyColumns));
// test updating a non-existent user

@@ -40,0 +40,0 @@ const userWithID = new MappedUser(1, test_objects_1.USERS[0].name, test_objects_1.USERS[0].handle, test_objects_1.USERS[0].email);

@@ -101,2 +101,17 @@ "use strict";

}));
it('selects with a binary operation filter using .ref()', () => __awaiter(void 0, void 0, void 0, function* () {
yield userMapper.insert().run(test_objects_1.USERS);
// Test selecting by condition (with results)
let users = yield userMapper
.select(userMapper.ref('name'), '=', test_objects_1.USERS[0].name)
.returnAll();
expect(users.length).toEqual(2);
expect(users[0].handle).toEqual(test_objects_1.USERS[0].handle);
expect(users[1].handle).toEqual(test_objects_1.USERS[2].handle);
// Test selecting by condition (no results)
users = yield userMapper
.select(userMapper.ref('email'), '=', 'nonexistent')
.returnAll();
expect(users.length).toEqual(0);
}));
it('selects with a query expression filter', () => __awaiter(void 0, void 0, void 0, function* () {

@@ -103,0 +118,0 @@ yield userMapper.insert().run(test_objects_1.USERS);

@@ -5,4 +5,4 @@ export * from './mappers/abstract-table-mapper';

export * from './mappers/table-mapper-transforms';
export * from './mappers/complete-row-transforms';
export * from './mappers/entire-row-transforms';
export * from './lib/query-filter';
//# sourceMappingURL=index.d.ts.map

@@ -5,4 +5,4 @@ export * from './mappers/abstract-table-mapper';

export * from './mappers/table-mapper-transforms';
export * from './mappers/complete-row-transforms';
export * from './mappers/entire-row-transforms';
export * from './lib/query-filter';
//# sourceMappingURL=index.js.map

@@ -27,12 +27,12 @@ /**

/**
* A filter that matches one or more key columns.
*/
type KeyColumnFilter<DB, TB extends keyof DB, K extends keyof Selectable<DB[TB]> & string> = NonNullable<Selectable<DB[TB]>[K]>;
/**
* A filter that matches columns against the fields of an object.
*/
type FieldMatchingFilter<DB, TB extends keyof DB & string, RE extends ReferenceExpression<DB, TB>> = {
export type FieldMatchingFilter<DB, TB extends keyof DB & string, RE extends ReferenceExpression<DB, TB>> = {
[K in RE & string]?: SelectType<ExtractTypeFromStringReference<DB, TB, K>> | Readonly<SelectType<ExtractTypeFromStringReference<DB, TB, K>>[]>;
};
/**
* A filter that matches a single key column.
*/
type KeyColumnFilter<DB, TB extends keyof DB, K extends keyof Selectable<DB[TB]> & string> = NonNullable<Selectable<DB[TB]>[K]>;
export {};
//# sourceMappingURL=query-filter.d.ts.map

@@ -8,4 +8,4 @@ /**

* found in the table interface `T`. Supports up to 4 columns.
* @typeparam T Table interface.
* @typeparam KA Array of the key column names.
* @typeParam T Table interface.
* @typeParam KA Array of the key column names.
*/

@@ -20,4 +20,4 @@ export type KeyTuple<T, KA extends Readonly<(keyof Selectable<T> & string)[]>> = KA[3] extends string ? [

* Require specified properties of a type, leaving the rest optional.
* @typeparam T Type to require properties from.
* @typeparam K Keys of the properties to require.
* @typeParam T Type to require properties from.
* @typeParam K Keys of the properties to require.
*/

@@ -24,0 +24,0 @@ export type RequireSome<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;

@@ -20,21 +20,21 @@ import { Kysely, Insertable, ReferenceExpression, Selectable, InsertQueryBuilder, InsertResult, SelectQueryBuilder, Selection, DeleteQueryBuilder, DeleteResult, UpdateResult, UpdateQueryBuilder, ComparisonOperatorExpression, OperandValueExpressionOrList, Updateable } from 'kysely';

* mappers should extend this class with means for providing transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam ReturnCount Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam ReturnCount Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -41,0 +41,0 @@ */

@@ -23,21 +23,21 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {

* mappers should extend this class with means for providing transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam ReturnCount Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam ReturnCount Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -44,0 +44,0 @@ */

import { SelectableColumnTuple, SelectionColumn } from '../lib/type-utils';
/**
* Settings governing table mapper behavior, excluding transformations.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns

@@ -18,19 +18,21 @@ * none and is the default. May specify aliases.

export interface TableMapperSettings<DB, TB extends keyof DB & string, KeyColumns extends Readonly<SelectableColumnTuple<DB[TB]>> | Readonly<[]> = [], SelectedColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = ['*'], InsertReturnColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = Readonly<KeyColumns>, UpdateReturnColumns extends Readonly<SelectionColumn<DB, TB>[]> | ['*'] = []> {
/** Tuple of the columns that make up the table's key. May be `[]`. */
/**
* Tuple of the columns that make up the table's key. Defaults to `[]`,
* indicating that no columns are keys.
*/
keyColumns?: KeyColumns;
/**
* Columns to return from selection queries. `[*]` selects all columns.
* May contain aliases.
* Columns to return from selection queries. Defaults to `[*]`, selecting
* all columns. May contain aliases.
*/
selectedColumns?: SelectedColumns;
/**
* Columns to return from the table on insert queries that return columns.
* `['*']` returns all columns; `[]` returns none. May specify aliases.
* Defaults to `KeyColumns`.
* Columns to return from insert queries that return columns. `['*']`
* returns all columns; `[]` returns none. May specify aliases. Defaults
* to `KeyColumns`.
*/
insertReturnColumns?: InsertReturnColumns;
/**
* Columns to return from the table on update queries that return columns.
* `['*']` returns all columns; `[]` returns none and is the default. May
* specify aliases.
* Columns to return from update queries that return columns. `['*']` returns
* all columns; `[]` returns none and is the default. May specify aliases.
*/

@@ -37,0 +39,0 @@ updateReturnColumns?: UpdateReturnColumns;

@@ -7,21 +7,21 @@ import { Insertable, Selectable, Selection, Updateable } from 'kysely';

* value is passed through unchanged.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -33,4 +33,5 @@ */

/**
* Transformation to apply to bigint count results before returning
* the count to the client. `count` is the count returned by the query.
* Transformation to apply to bigint count results indicating the number of
* rows affected, before returning the count to the client. `count` is the
* count returned by the query.
*/

@@ -37,0 +38,0 @@ countTransform?: (count: bigint) => ReturnCount;

@@ -8,21 +8,21 @@ import { Insertable, Selectable, Selection, Updateable } from 'kysely';

* unchanged, allowing the selective overloading of transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -32,4 +32,4 @@ */

/**
* Constructs a new table mapper.
* Returns a new table mapper that uses the provided transformations.
* Returns a new table mapper that uses the provided transformations, along
* with the settings of the current table mapper.
* @param transforms The transforms to use.

@@ -36,0 +36,0 @@ * @returns A new table mapper that uses the provided transforms.

@@ -5,21 +5,21 @@ import { AbstractTableMapper } from './abstract-table-mapper';

* unchanged, allowing the selective overloading of transforms.
* @typeparam DB Interface whose fields are table names defining tables.
* @typeparam TB Name of the table.
* @typeparam KeyColumns Tuple of the names of the table's key columns.
* @typeParam DB Interface whose fields are table names defining tables.
* @typeParam TB Name of the table.
* @typeParam KeyColumns Tuple of the names of the table's key columns.
* Defaults to `[]`, indicating no key columns. Supports up to 4 columns.
* @typeparam SelectedColumns Columns to return from selection queries.
* @typeParam SelectedColumns Columns to return from selection queries.
* Defaults to `['*']`, returning all columns. May specify aliases.
* @typeparam SelectedObject Type of objects returned by select queries.
* @typeparam InsertedObject Type of objects inserted into the table.
* @typeparam UpdatingObject Type of objects used to update rows of the table.
* @typeparam Type of the count of the number of affected rows.
* @typeparam InsertReturnColumns Columns to return from the table on insert
* @typeParam SelectedObject Type of objects returned by select queries.
* @typeParam InsertedObject Type of objects inserted into the table.
* @typeParam UpdatingObject Type of objects used to update rows of the table.
* @typeParam Type of the count of the number of affected rows.
* @typeParam InsertReturnColumns Columns to return from the table on insert
* queries that return columns. `['*']` returns all columns; `[]` returns
* none. May specify aliases. Defaults to `KeyColumns`.
* @typeparam UpdateReturnColumns Columns to return from the table on update
* @typeParam UpdateReturnColumns Columns to return from the table on update
* queries that return columns. `['*']` returns all columns; `[]` returns
* none and is the default. May specify aliases.
* @typeparam InsertReturn Type returned from inserts. Defaults to an object
* @typeParam InsertReturn Type returned from inserts. Defaults to an object
* whose properties are the columns of `InsertReturnColumns`.
* @typeparam UpdateReturn Type returned from updates. Defaults to an object
* @typeParam UpdateReturn Type returned from updates. Defaults to an object
* whose properties are the columns of `UpdateReturnColumns`.

@@ -29,4 +29,4 @@ */

/**
* Constructs a new table mapper.
* Returns a new table mapper that uses the provided transformations.
* Returns a new table mapper that uses the provided transformations, along
* with the settings of the current table mapper.
* @param transforms The transforms to use.

@@ -33,0 +33,0 @@ * @returns A new table mapper that uses the provided transforms.

@@ -19,3 +19,3 @@ import { DeleteQueryBuilder, DeleteResult, Kysely } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -22,0 +22,0 @@ * @returns A compiling delete query.

@@ -25,3 +25,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -28,0 +28,0 @@ * @returns A compiling delete query.

@@ -20,3 +20,3 @@ import { Kysely, SelectQueryBuilder } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling select query.

@@ -25,3 +25,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -28,0 +28,0 @@ * @returns A compiling select query.

@@ -18,3 +18,3 @@ import { Kysely, InsertQueryBuilder, InsertResult, Insertable } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -21,0 +21,0 @@ * @returns A compiling insert query.

@@ -17,3 +17,3 @@ import { MappingInsertQuery } from './insert-query';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -20,0 +20,0 @@ * @returns A compiling insert query.

@@ -20,3 +20,3 @@ import { Kysely, UpdateQueryBuilder, UpdateResult, Updateable } from 'kysely';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -23,0 +23,0 @@ * @returns A compiling update query.

@@ -17,3 +17,3 @@ import { MappingUpdateQuery } from './update-query';

* Frees the query builder on the first execution to reduce memory usage.
* @typeparam Parameters Record characterizing the parameter names and
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.

@@ -20,0 +20,0 @@ * @returns A compiling update query.

@@ -13,3 +13,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import { TableMapper } from '../mappers/table-mapper';
import { CompleteRowTransforms } from '../mappers/complete-row-transforms';
import { EntireRowTransforms } from '../mappers/entire-row-transforms';
let db;

@@ -35,3 +35,3 @@ beforeAll(() => __awaiter(void 0, void 0, void 0, function* () {

updateReturnColumns: ['id', 'name'],
}).withTransforms(new CompleteRowTransforms(keyColumns));
}).withTransforms(new EntireRowTransforms(keyColumns));
// test updating a non-existent user

@@ -38,0 +38,0 @@ const userWithID = new MappedUser(1, USERS[0].name, USERS[0].handle, USERS[0].email);

@@ -99,2 +99,17 @@ /**

}));
it('selects with a binary operation filter using .ref()', () => __awaiter(void 0, void 0, void 0, function* () {
yield userMapper.insert().run(USERS);
// Test selecting by condition (with results)
let users = yield userMapper
.select(userMapper.ref('name'), '=', USERS[0].name)
.returnAll();
expect(users.length).toEqual(2);
expect(users[0].handle).toEqual(USERS[0].handle);
expect(users[1].handle).toEqual(USERS[2].handle);
// Test selecting by condition (no results)
users = yield userMapper
.select(userMapper.ref('email'), '=', 'nonexistent')
.returnAll();
expect(users.length).toEqual(0);
}));
it('selects with a query expression filter', () => __awaiter(void 0, void 0, void 0, function* () {

@@ -101,0 +116,0 @@ yield userMapper.insert().run(USERS);

{
"name": "kysely-mapper",
"version": "0.4.1",
"version": "0.4.2",
"author": "Joseph T. Lapp <arachnojoe@gmail.com>",

@@ -33,2 +33,4 @@ "license": "MIT",

"build": "rm -rdf dist && tsc && tsc -p tsconfig.cjs.json",
"build-docs": "typedoc --options ./typedoc.js ./src/index.ts",
"build-all": "pnpm build && pnpm build-docs",
"test": "jest"

@@ -46,4 +48,5 @@ },

"ts-jest": "^29.0.5",
"typedoc": "^0.24.5",
"typescript": "^4.9.5"
}
}

@@ -5,4 +5,2 @@ # kysely-mapper

**CURRENTY UNDER DEVELOPMENT. NOT READY FOR USE.**
## Overview

@@ -16,2 +14,6 @@

[Jump to the Quick Reference](https://github.com/jtlapp/kysely-mapper#quick-reference)
[Open the API Reference](https://jtlapp.github.io/kysely-mapper/)
## Installation

@@ -31,13 +33,72 @@

This package provides three classes for mapping tables: `AbstractTableMapper`, `TableMapper` and `CompleteRowTransforms`. `AbstractTableMapper` is a base class for constructing your own kinds of table mappers. `TableMapper` is a generic mapping utility that implements `AbstractTableMapper` and should suffice for most of your needs. `CompleteRowTransforms` provides default mappings for a table mapper whose queries input and output entire rows of the underlying table.
This package provides three classes for mapping tables: `AbstractTableMapper`, `TableMapper` and `EntireRowTransforms`. `AbstractTableMapper` is a base class for constructing your own kinds of table mappers. `TableMapper` is a generic mapping utility that implements `AbstractTableMapper` and should suffice for most of your needs. `EntireRowTransforms` provides default mappings for a table mapper whose queries input and output entire rows of the underlying table.
For the examples that follow, assume we have the following '**users**' table:
Most of the examples in this document assume the following 'users' table:
- **id**: auto-incrementing integer, primary key
- **name**: text
- **birth_year**: integer
- **modified**: date, maintained by a database trigger
| Users Table Column | Column Type |
| ------------------ | -------------------------------------- |
| id | auto-incrementing integer, primary key |
| name | text |
| birth_year | integer |
| modified | date, maintained by a database trigger |
### Introduction to Querying
We first configure a table mapper by specifying key columns, selected columns, insert return columns, and update return columns, where they differ from the defaults. We also specify any needed transformations between objects and table row columns. For example:
```ts
const table = new TableMapper(db, 'users', {
keyColumns: ['id'],
insertReturnColumns: ['id', 'modified'],
updateReturnColumns: ['modified'],
}).withTransforms({
insertTransform: (source: User) => ({
name: `${source.firstName} ${source.lastName}`,
birth_year: source.birthYear,
}),
insertReturnTransform: (source: User, returns) =>
new User(
returns.id,
source.firstName,
source.lastName,
source.birthYear,
returns.modified
),
selectTransform: (row) => {
const names = row.name.split(' ');
return new User(row.id, names[0], names[1], row.birth_year, row.modified);
},
});
```
We then call methods on the table mapper for creating queries. Table mappers support insert, update, select, and delete queries. Except for insert, the queries take filters that generate 'where' clauses for constraining the query.
After creating a query, we can call methods on the query to execute it. The names of these methods are consistent across queries: `run`, `returnCount`, `returnOne`, and `returnAll`. The particular methods available and the parameters they take vary by kind of query.
Here are some examples of creating and executing queries:
```ts
await table.insert().run(userToInsert1);
user = await table.insert().returnOne(userToInsert2);
user = await table.select(userID).returnOne();
users = await table.select('name', '=', 'John Doe').returnAll();
users = await table
.select({ name: 'Jane Smith' })
.modify((qb) => qb.orderBy('birth_year', 'desc'))
.returnAll();
await table.update({ name: 'Joe Mac' }).run({ name: 'Joseph Mack' });
updateCount = await table
.update({ name: 'Jane Smith' })
.returnCount({ email: 'js2@abc.def' });
await table.delete({ name: 'John Doe' }).run();
deleteCount = await table.delete({ name: 'John Doe' }).returnCount();
```
Additional methods are available for directly modifying the underlying query builder (`modify`), for creating compiling queries (`compile`), and for parameterizing compiling queries (`parameterize`), the latter of which is a method on table mappers.
The following sections explain everything in detail.
## Issuing Queries
Let's begin by looking at how we query instances of `TableMapper`. If we don't configure `TableMapper`, no mapping occurs: objects provided to the queries are passed directly to Kysely, and objects returned by Kysely are passed directly back to the caller. Consider:

@@ -53,7 +114,11 @@

The first selection returns all rows from the 'users' table, representing each row as an object with fields `id`, `name`, and `birth_year`. The second selection returns just the first user. If we want to return specific rows, we can supply a filter:
The first selection returns all rows from the 'users' table, representing each row as an object with fields `id`, `name`, and `birth_year`. The second selection returns just the first user. If we want to return specific rows, we can supply a query filter:
```ts
users = await table.select().returnAll(); // returns all users
users = await table.select({ name: 'Jane Smith' }).returnAll();
users = await table.select('name', '=', 'Jane Smith').returnAll();
users = await table.select(sql`name = ${findName}`).returnAll();
users = await table

@@ -71,2 +136,3 @@ .select({

.returnAll();
users = await table

@@ -78,3 +144,2 @@ .select({

.returnAll();
users = await table.select(sql`name = ${targetName}`).returnAll();
```

@@ -171,3 +236,3 @@

### Introduction to Mapping
## Mapping Queries

@@ -348,27 +413,289 @@ The query methods don't provide much (if any) value over writing pure Kysely. The real value of this utility is it's ability to centrally define how objects are mapped to and from database tables. The query methods then perform these mappings automatically.

user = await table.update(user.id).returnOne({ name: 'Janice Smith' });
await table.update({ name: 'Joe Smith' }).run({ name: 'Joseph Smith' });
await table.update({ name: 'Joe Mac' }).run({ name: 'Joseph Mack' });
```
### Introduction to CompleteRowTransforms
## Compiling Queries
TBD
Table mappers are also able to produce parameterized, compiling queries that compile the underlying Kysely query builder on the first execution and use this compilation for subsequent executions. You can provide parameters for values that can vary from execution to execution, particularly in query filters that define "where" clauses. Inserted and updating objects are always fully parameterized, so these too can vary from execution to execution.
## Parameterizing and Compiling Queries
Any mapped query can be compiled by calling its `compile()` method, and the resulting compilation can be called via the methods available to the uncompiled query. However, you must call `columns()` on insert and update queries prior to compilation:
TBD
```ts
const compilingInsert = table
.insert()
.columns(['name', 'birth_year']) // columns to insert
.compile();
await compilingInsert.run(userToInsert);
const compilingUpdate = table
.update({ name: 'Joe Mac' }) // columns to update
.columns(['name'])
.compile();
user = await compilingUpdate.returnOne({}, { name: 'Joseph Mack' });
const compilingSelect = table.select({ name: 'Joseph Mack' }).compile();
users = await compilingSelect.returnAll({});
const compilingDelete = table.delete({ name: 'Joseph Mack' }).compile();
count = await compilingDelete.returnCount({});
```
We have to call `columns()` on insertions and updates to tell the utility what columns to set, because Kysely normally gets this information from the values object itself. The utility compiles the query prior to receiving the values object, so that the values object can vary by execution within the same compiled query. This requires the columns to be known in advance of executing the query.
Except for insertions, the methods of compiling queries all take an additional argument, which is `{}` in each case above. This is an object that provides parameter values. When we create a compiling query by calling `compile()`, we are not parameterizing anything but the values for inserting or updating. The second argument of these methods provides these values. Given that there are no additional parameters to provide, the parameters object will be empty.
If we want to parameterize the query filter, we call `parameterize()` on the table mapper instead of calling `compile()` on the query. We also provide `parameterize()` with a type parameter that defines the available parameters as the properties of an object. The following examples all use the same type parameters, `Params`:
```ts
interface Params {
findName: string;
}
const compilingUpdate = table.parameterize<Params>(({ mapper, param }) =>
mapper.update({ name: param('findName') }).columns(['name'])
);
user = await compilingUpdate.returnOne(
{ findName: 'Joe Mac' },
{ name: 'Joseph Mack' }
);
const compilingSelect = table.parameterize<Params>(({ mapper, param }) =>
mapper.select({ name: param('findName') })
);
users = await compilingSelect.returnAll({ findName: 'Joe Mac' });
const compilingDelete = table.parameterize<Params>(({ mapper, param }) =>
mapper.delete({ name: param('findName') })
);
count = await compilingDelete.returnCount({ findName: 'Joe Mac' });
```
No example is shown for insertion, because not having query filters, there is nothing further to parameterize.
In these examples, the parameter is called `findName` to make it clear that parameters are names you make up, rather than having to be column names. However, we can use column names as parameter names if we want, because the parameters used to insert values are in their own namespace.
We hand `parameterize()` a factory function that returns a compilable query. To make this query, the function receives a reference to the table mapper (`mapper`) and a `param()` function. Construct the query from `mapper`, replacing the filter right-hand-values you wish to parameterize with calls to `param()`. Provide `param()` with the parameter name, which must be a property of the parameters type (here, `Params`). The parameter must have a type in the type parameter that is permitted for the right-hand-value it provides. The factory function must must call `columns()` on update queries before returning the query.
`parameterize()` returns a compiling query that can be repeatedly called with different parameters (unless it's an insertion) and different values (for insertions and updates). The compiling query compiles on its first execution, caches the compilation, discards the underlying Kysely query builder to free memory, and uses the cached compilation on subsequent executions. (Insertions and updates may actually cache two compilations on the first execution &mdash; one for queries that return values and one for queries that don't).
Kysely queries are fast, and the present utility doesn't do much additional work on top of Kysely, so you are not likely to need compiling queries to improve query speed. However, query builders do use memory, increase garbage collection, and consume clock cycles that could be used elsewhere. Compiling queries allow you to minimize resource usage for the kinds of applications that can benefit. (Note that the [kysely-params](https://github.com/jtlapp/kysely-params) utility that the present utility relies on lets you compile and parameterize arbitrary Kysely queries.)
Compilation adds a bit of complication to your queries. It's best to implement the application without compilation until you find that you need it: you may discover that you never needed the additional complication. The compilation facility exists to help you feel comfortable using the tool for any kind of application.
## Usage in Repository Classes
TBD
We typically want to use table mappers in repository classes that represent database tables with application-specific interfaces. We also typically want to create instances of these classes with dependency injection, passing in dependencies rather than hard-coding them. Table mappers depend on instances of the `Kysely` class and present a complication for dependency injection. This section documents a simple solution to this complication.
The `TableMapper` class has many type parameters, and we would rather not have to specify them. When we create a table mapper, passing in its various column settings and transforms, TypeScript can infer all of the type parameters from these settings and transforms. However, we require an instance of `Kysely` to create the table mapper. If we want to define the table mapper prior to creating it, such as to make it a property of a repository class, and if we only receive the `Kysely` instance at repository construction, we may be inclined to specify all of the type parameters in our definition.
A better solution is to provide a method on the repository class that returns a table mapper and then define the table mapper property as the return type of this method. This provides the best of both worlds: we infer all of the type parameters and have a property based on the inferred types. Here is an example:
```ts
export class UserRepo {
readonly #table: ReturnType<UserRepo['getMapper']>;
constructor(readonly db: Kysely<Database>) {
this.#table = this.getMapper(db);
}
async getByID(id: number): Promise<User | null> {
return this.#table.select(id).returnOne();
}
async deleteById(id: number): Promise<boolean> {
return this.#table.delete(id).run();
}
async store(user: User): Promise<User | null> {
return user.id
? (await this.#table.update(user.id).run(user))
? user
: null
: this.#table.insert().returnOne(user);
}
private getMapper(db: Kysely<Database>) {
return new TableMapper(db, 'users', {
keyColumns: ['id'],
}).withTransforms({
insertTransform: (source: User) => {
const insertion = { ...source } as any;
delete insertion['id'];
return insertion;
},
insertReturnTransform: (source: User, returns) =>
new User({ ...source, id: returns.id }),
selectTransform: (row) => new User(row),
});
}
}
```
We can do something similar when using compiling queries. There's no need to keep the table mapper around if all queries are compiling, as we only need the compiled queries:
```ts
export class UserRepo {
readonly #queries: ReturnType<UserRepo['getQueries']>;
constructor(readonly db: Kysely<Database>) {
this.#queries = this.getQueries(db);
}
async deleteById(id: number): Promise<boolean> {
return this.#queries.deleteByID.run({ id });
}
async getByID(id: number): Promise<User | null> {
return this.#queries.selectByID.returnOne({ id });
}
async store(user: User): Promise<User | null> {
return user.id
? (await this.#queries.updateByID.run({ id: user.id }, user))
? user
: null
: this.#queries.insert.returnOne(user);
}
private getQueries(db: Kysely<Database>) {
const table = new TableMapper(db, 'users', {
keyColumns: ['id'],
}).withTransforms({
insertTransform: (user: User) => {
const insertion = { ...user } as any;
delete insertion['id'];
return insertion;
},
insertReturnTransform: (user: User, returns) =>
new User({ ...user, id: returns.id }),
selectTransform: (row) => new User(row),
});
return {
// prettier-ignore
deleteByID: table.parameterize<{ id: number }>(
({ mapper, param }) => mapper.delete(param('id'))
),
// prettier-ignore
selectByID: table.parameterize<{ id: number }>(
({ mapper, param }) => mapper.select(param('id'))
),
// prettier-ignore
updateByID: table.parameterize<{ id: number }>(
({ mapper, param }) =>
mapper.update(param('id')).columns(['name', 'birth_year'])
),
insert: table.insert().columns(['name', 'birth_year']).compile(),
};
}
}
```
## EntireRowTransforms
`EntireRowTransforms` is a class that provides transforms for defining a table mapper whose queries all receive and return entire rows of the table. Use it when you want to read and write entire rows but also respect the expected insert and update return columns. The class exists merely for your convenience.
Here is how you create a table mapper that uses these transforms:
```ts
const KEY_COLUMNS = ['id'];
const table = new TableMapper(db, 'users', {
keyColumns: KEY_COLUMNS,
insertReturnColumns: ['id', 'modified'],
updateReturnColumns: ['modified'],
}).withTransforms(new EntireRowTransforms(KEY_COLUMNS));
```
The transforms are only compatible with with table mappers that select all columns, as the above does because `selectedColumns` defaults to `['*']`.
The resulting table mapper has these properties:
- Upon insertion, key columns with falsy values are removed from the query; when you want the table to generate a key, set the key value to `null`, 0, or an empty string `""`. You can further restrict inserted columns by calling `columns`()` on the query.
- The row returned from an insertion is the row provided for insertion merged with the columns returned from the insertion.
- Select queries return entire rows.
- The caller provides an entire row when updating, setting all columns, unless you restrict columns by calling `columns()` on the query.
- The row returned from an update is the row provided with the update merged with the columns returned from the update.
- Counts of the number of affected rows have type `number`.
## Quick Reference
TBD
Here are some quick-reference charts that should help make this utility easy to learn. Hopefully, the charts also reveal both the simplicity and the flexibility of the solution. Also see the [API Reference](https://jtlapp.github.io/kysely-mapper/).
## API Reference
`TableMapper` has the following constructor and methods:
TBD
<!-- prettier-ignore -->
| Method of TableMapper | Description |
| --- | --- |
| `constructor(settings)` | Constructs a `TableMapper` from the provided settings, which characterize columns. |
| `withTransforms(transforms)` | Returns a new `TableMapper` that combines the settings of the current table mapper with the provided transforms. |
| `insert()` | Returns an insert query. |
| `update(filter?)` | Returns an update query that updates rows matching the optionally provided filter. |
| `select(filter?)` | Returns a select query that selects rows matching the optionally provided filter. |
| `delete(filter?)` | Returns a delete query that deletes rows matching the optionally provided filter. |
| `ref(column)` | Returns a reference to a column with a dynamically-generated name. (Shorthand for `db.dynamic.ref(column)`.) |
| `parameterize<Params>(`<br/>`({ mapper, param }) =>`<br/>`new query)` | Returns a compiling query with a parameterized filter. Its argument is a factory method that returns a parameterized, compilable query. |
The `TableMapper` constructor takes a settings object, all of whose properties are optional:
<!-- prettier-ignore -->
| TableMapper Setting | Description |
| --- | --- |
| `keyColumns` | Tuple of the columns that make up the table's key. Defaults to `[]`, indicating that no columns are keys. |
| `selectedColumns` | Array of columns to return from selection queries. Defaults to `[*]`, selecting all columns. May contain aliases. |
| `insertReturnColumns` | Array of columns to return from insert queries that return columns. `['*']` returns all columns; `[]` returns none. May specify aliases. Defaults to `keyColumns`. |
| `updateReturnColumns` | Array of columns to return from update queries that return columns. `['*']` returns all columns; `[]` returns none and is the default. May specify aliases. |
The `tableMapper.withTransforms` method takes a transforms object, all of whose properties are optional:
<!-- prettier-ignore -->
| TableMapper Transform | Description |
| --- | --- |
| `insertTransform` | (source-object) => table columns object<br/> Transforms the source object into the table column-values to insert. The default assumes the source object contains only table columns. |
| `insertReturnTransform` | (source-object, returns) => insert return<br/> Transforms the source object and the returned column-values into the value to return from the insert query. The default returns an object containing the returned columns, unless there are no `insertReturnColumns`, in which case the return type is `void`. |
| `updateTransform` | (source-object) => table columns object<br/> Transforms the source object into the table column-values to update. The default assumes the source object contains only table columns. |
| `updateReturnTransform` | (source-object, returns) => update return<br/> Transforms the source object and the returned column-values into the value to return from the udpate query. The default returns an object containing the returned columns, unless there are no `updateReturnColumns`, in which case the return type is `void`. |
| `selectTransform` | (selected-row) => selected object<br/> Transforms a selected row of column-values into the object to return from the select query. The default returns the selected row. |
| `countTransform` | (count: bigint) => return count<br/> Transforms the number of affected rows into the value to return from `returnCount` methods. Returns a `bigint` by default. |
The argument to `update()`, `select()`, and `delete()` is an optional query filter. The following query filters are available:
<!-- prettier-ignore -->
| Query Filter | Description |
| :---: | --- |
| *none* | All rows match when there is no filter argument. |
| `string` or `number` | Value of the row's primary key, matching rows with this key value. Only available if the row has a single-column primary key. |
| [key1, key2, ...] | Tuple of the row's single or compound key, matching rows with this key combination. Values match according to the order of columns in `keyColumns`. Only available if the row has at least one key column. |
| object | Object of fields, matching rows whose columns match the values of the object's properties. Non-array property values are compared by equality, while array properties match via `where ... in ...` expressions. `{}` matches all rows.
| left-hand-side, operation, right-hand-side | Providing three arguments matches via a Kysely binary operation (e.g. `'total', '>', '100'`). |
| kysely where expression factory | Function that builds a Kysely where expression. (e.g. `({ any, cmpr }) => any(cmpr('status', '!=', 'down'), cmpr('service', '=', 'messaging')`). |
| kysely `sql` expression | A Kysely `sql` expression (e.g. `` sql`status = ${targetStatus}` ``).
The queries that `TableFilter` methods return all have similar methods, as this chart summarizes:
<!-- prettier-ignore -->
| Method of Query | insert() | update(filter?) | select(filter?) | delete(filter?) |
| --- | --- | --- | --- | --- |
| `modify` | ((kysely-QB) =><br/> new kysely QB) => new insert query | ((kysely-QB) =><br/> new kysely QB) => new update query | ((kysely-QB) =><br/> new kysely QB) => select query | ((kysely-QB) =><br/> new kysely QB) => delete query |
| `columns` | (columns-to-insert array) =><br/> column-restricted insert query | (columns-to-update array) =><br/> column-restricted update query | N/A | N/A |
| `run` | (values) =><br/> true (always) | (values) =><br/> boolean (whether any updated) | N/A | () =><br/> boolean (whether any deleted) |
| `returnCount` | N/A | (values) =><br/> return count | N/A | () =><br/> return count |
| `returnOne` | (values) =><br/> insert return | (values) =><br/> update return | () =><br/> selected object | N/A |
| `returnAll` | (values[]) =><br/> (insert return)[] | (values) =><br/> (update return)[] | () => (<br/>selected object)[] | N/A |
| `compile` | after calling `columns`: () =><br/> compiling insert query | after calling `columns`: () =><br/> compiling update query | () =><br/> compiling select query | () =><br/> compiling delete query |
`modify` returns an instance of the kind of query on which it was called. All select and delete queries are compilable, but you must call `columns` to get a compilable version of an insert or update query.
`tableMapper.parameterize()` and `query.compile()` both return compiling queries, which compile on their first execution. These queries have similar methods, as shown in this chart:
<!-- prettier-ignore -->
| Method of Compiling Query | Compiling Insert Query | Compiling Update Query | Compiling Select Query | Compiling Delete Query |
| --- | --- | --- | --- | --- |
| `run` | (values) =><br/> true (always) | (params, values) =><br/> boolean (whether any updated) | N/A | (params) =><br/> boolean (whether any deleted) |
| `returnCount` | N/A | (params, values) =><br/> return count | N/A | (params) =><br/> return count |
| `returnOne` | (values) =><br/> insert return | (params, values) =><br/> update return | (params) =><br/> selected object | N/A |
| `returnAll` | (values[]) =><br/> (insert return)[] | (params, values) =><br/> (update return)[] | (params) =><br/> (selected object)[] | N/A |
## License
MIT License. Copyright &copy; 2023 Joseph T. Lapp

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc