@fragno-dev/db 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +137 -13
- package/.turbo/turbo-test.log +36 -0
- package/CHANGELOG.md +7 -0
- package/dist/adapters/adapters.d.ts +18 -0
- package/dist/adapters/adapters.d.ts.map +1 -0
- package/dist/adapters/drizzle/drizzle-adapter.d.ts +21 -0
- package/dist/adapters/drizzle/drizzle-adapter.d.ts.map +1 -0
- package/dist/adapters/drizzle/drizzle-adapter.js +62 -0
- package/dist/adapters/drizzle/drizzle-adapter.js.map +1 -0
- package/dist/adapters/drizzle/drizzle-query.d.ts +17 -0
- package/dist/adapters/drizzle/drizzle-query.d.ts.map +1 -0
- package/dist/adapters/drizzle/drizzle-query.js +139 -0
- package/dist/adapters/drizzle/drizzle-query.js.map +1 -0
- package/dist/adapters/drizzle/drizzle-uow-compiler.d.ts +9 -0
- package/dist/adapters/drizzle/drizzle-uow-compiler.d.ts.map +1 -0
- package/dist/adapters/drizzle/drizzle-uow-compiler.js +300 -0
- package/dist/adapters/drizzle/drizzle-uow-compiler.js.map +1 -0
- package/dist/adapters/drizzle/drizzle-uow-decoder.js +82 -0
- package/dist/adapters/drizzle/drizzle-uow-decoder.js.map +1 -0
- package/dist/adapters/drizzle/drizzle-uow-executor.js +125 -0
- package/dist/adapters/drizzle/drizzle-uow-executor.js.map +1 -0
- package/dist/adapters/drizzle/generate.js +273 -0
- package/dist/adapters/drizzle/generate.js.map +1 -0
- package/dist/adapters/drizzle/join-column-utils.js +28 -0
- package/dist/adapters/drizzle/join-column-utils.js.map +1 -0
- package/dist/adapters/drizzle/shared.js +11 -0
- package/dist/adapters/drizzle/shared.js.map +1 -0
- package/dist/adapters/kysely/kysely-adapter.d.ts +23 -0
- package/dist/adapters/kysely/kysely-adapter.d.ts.map +1 -0
- package/dist/adapters/kysely/kysely-adapter.js +119 -0
- package/dist/adapters/kysely/kysely-adapter.js.map +1 -0
- package/dist/adapters/kysely/kysely-query-builder.js +306 -0
- package/dist/adapters/kysely/kysely-query-builder.js.map +1 -0
- package/dist/adapters/kysely/kysely-query-compiler.js +67 -0
- package/dist/adapters/kysely/kysely-query-compiler.js.map +1 -0
- package/dist/adapters/kysely/kysely-query.js +158 -0
- package/dist/adapters/kysely/kysely-query.js.map +1 -0
- package/dist/adapters/kysely/kysely-uow-compiler.js +139 -0
- package/dist/adapters/kysely/kysely-uow-compiler.js.map +1 -0
- package/dist/adapters/kysely/kysely-uow-executor.js +89 -0
- package/dist/adapters/kysely/kysely-uow-executor.js.map +1 -0
- package/dist/adapters/kysely/migration/execute.js +176 -0
- package/dist/adapters/kysely/migration/execute.js.map +1 -0
- package/dist/fragment.d.ts +54 -0
- package/dist/fragment.d.ts.map +1 -0
- package/dist/fragment.js +92 -0
- package/dist/fragment.js.map +1 -0
- package/dist/id.d.ts +2 -0
- package/dist/migration-engine/auto-from-schema.js +116 -0
- package/dist/migration-engine/auto-from-schema.js.map +1 -0
- package/dist/migration-engine/create.d.ts +41 -0
- package/dist/migration-engine/create.d.ts.map +1 -0
- package/dist/migration-engine/create.js +58 -0
- package/dist/migration-engine/create.js.map +1 -0
- package/dist/migration-engine/shared.d.ts +90 -0
- package/dist/migration-engine/shared.d.ts.map +1 -0
- package/dist/migration-engine/shared.js +8 -0
- package/dist/migration-engine/shared.js.map +1 -0
- package/dist/mod.d.ts +55 -2
- package/dist/mod.d.ts.map +1 -1
- package/dist/mod.js +111 -2
- package/dist/mod.js.map +1 -1
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/column-builder.js +108 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/column-builder.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/column.js +55 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/column.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/entity.js +18 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/entity.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/columns/common.js +183 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/columns/common.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/columns/enum.js +58 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/columns/enum.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/foreign-keys.js +68 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/foreign-keys.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/unique-constraint.js +56 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/unique-constraint.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/utils/array.js +65 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/pg-core/utils/array.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/expressions/conditions.js +81 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/expressions/conditions.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/expressions/select.js +13 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/expressions/select.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/functions/aggregate.js +10 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/functions/aggregate.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/sql.js +372 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/sql/sql.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/subquery.js +23 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/subquery.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/table.js +62 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/table.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/table.utils.js +6 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/table.utils.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/tracing-utils.js +8 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/tracing-utils.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/tracing.js +8 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/tracing.js.map +1 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/view-common.js +6 -0
- package/dist/node_modules/.bun/drizzle-orm@0.44.6_4fae081eecb963e2/node_modules/drizzle-orm/view-common.js.map +1 -0
- package/dist/query/condition-builder.d.ts +41 -0
- package/dist/query/condition-builder.d.ts.map +1 -0
- package/dist/query/condition-builder.js +93 -0
- package/dist/query/condition-builder.js.map +1 -0
- package/dist/query/cursor.d.ts +88 -0
- package/dist/query/cursor.d.ts.map +1 -0
- package/dist/query/cursor.js +103 -0
- package/dist/query/cursor.js.map +1 -0
- package/dist/query/orm/orm.d.ts +18 -0
- package/dist/query/orm/orm.d.ts.map +1 -0
- package/dist/query/orm/orm.js +48 -0
- package/dist/query/orm/orm.js.map +1 -0
- package/dist/query/query.d.ts +79 -0
- package/dist/query/query.d.ts.map +1 -0
- package/dist/query/query.js +1 -0
- package/dist/query/result-transform.js +155 -0
- package/dist/query/result-transform.js.map +1 -0
- package/dist/query/unit-of-work.d.ts +435 -0
- package/dist/query/unit-of-work.d.ts.map +1 -0
- package/dist/query/unit-of-work.js +549 -0
- package/dist/query/unit-of-work.js.map +1 -0
- package/dist/schema/create.d.ts +273 -116
- package/dist/schema/create.d.ts.map +1 -1
- package/dist/schema/create.js +410 -222
- package/dist/schema/create.js.map +1 -1
- package/dist/schema/serialize.js +101 -0
- package/dist/schema/serialize.js.map +1 -0
- package/dist/schema-generator/schema-generator.d.ts +15 -0
- package/dist/schema-generator/schema-generator.d.ts.map +1 -0
- package/dist/shared/providers.d.ts +6 -0
- package/dist/shared/providers.d.ts.map +1 -0
- package/dist/util/import-generator.js +26 -0
- package/dist/util/import-generator.js.map +1 -0
- package/dist/util/parse.js +15 -0
- package/dist/util/parse.js.map +1 -0
- package/dist/util/types.d.ts +8 -0
- package/dist/util/types.d.ts.map +1 -0
- package/package.json +63 -2
- package/src/adapters/adapters.ts +22 -0
- package/src/adapters/drizzle/drizzle-adapter-pglite.test.ts +433 -0
- package/src/adapters/drizzle/drizzle-adapter.test.ts +122 -0
- package/src/adapters/drizzle/drizzle-adapter.ts +118 -0
- package/src/adapters/drizzle/drizzle-query.ts +234 -0
- package/src/adapters/drizzle/drizzle-uow-compiler.test.ts +1084 -0
- package/src/adapters/drizzle/drizzle-uow-compiler.ts +546 -0
- package/src/adapters/drizzle/drizzle-uow-decoder.ts +165 -0
- package/src/adapters/drizzle/drizzle-uow-executor.ts +213 -0
- package/src/adapters/drizzle/generate.test.ts +643 -0
- package/src/adapters/drizzle/generate.ts +481 -0
- package/src/adapters/drizzle/join-column-utils.test.ts +79 -0
- package/src/adapters/drizzle/join-column-utils.ts +39 -0
- package/src/adapters/drizzle/migrate-drizzle.test.ts +226 -0
- package/src/adapters/drizzle/shared.ts +22 -0
- package/src/adapters/drizzle/test-utils.ts +56 -0
- package/src/adapters/kysely/kysely-adapter-pglite.test.ts +789 -0
- package/src/adapters/kysely/kysely-adapter.ts +196 -0
- package/src/adapters/kysely/kysely-query-builder.test.ts +1344 -0
- package/src/adapters/kysely/kysely-query-builder.ts +611 -0
- package/src/adapters/kysely/kysely-query-compiler.ts +124 -0
- package/src/adapters/kysely/kysely-query.ts +254 -0
- package/src/adapters/kysely/kysely-uow-compiler.test.ts +916 -0
- package/src/adapters/kysely/kysely-uow-compiler.ts +271 -0
- package/src/adapters/kysely/kysely-uow-executor.ts +149 -0
- package/src/adapters/kysely/kysely-uow-joins.test.ts +811 -0
- package/src/adapters/kysely/migration/execute-mysql.test.ts +1173 -0
- package/src/adapters/kysely/migration/execute-postgres.test.ts +2657 -0
- package/src/adapters/kysely/migration/execute.ts +382 -0
- package/src/adapters/kysely/migration/kysely-migrator.test.ts +197 -0
- package/src/fragment.test.ts +287 -0
- package/src/fragment.ts +198 -0
- package/src/migration-engine/auto-from-schema.test.ts +118 -58
- package/src/migration-engine/auto-from-schema.ts +103 -32
- package/src/migration-engine/create.test.ts +34 -46
- package/src/migration-engine/create.ts +41 -26
- package/src/migration-engine/shared.ts +26 -6
- package/src/mod.ts +197 -1
- package/src/query/condition-builder.test.ts +379 -0
- package/src/query/condition-builder.ts +294 -0
- package/src/query/cursor.test.ts +296 -0
- package/src/query/cursor.ts +147 -0
- package/src/query/orm/orm.ts +92 -0
- package/src/query/query-type.test.ts +429 -0
- package/src/query/query.ts +200 -0
- package/src/query/result-transform.test.ts +795 -0
- package/src/query/result-transform.ts +247 -0
- package/src/query/unit-of-work-types.test.ts +192 -0
- package/src/query/unit-of-work.test.ts +947 -0
- package/src/query/unit-of-work.ts +1199 -0
- package/src/schema/create.test.ts +653 -110
- package/src/schema/create.ts +708 -337
- package/src/schema/serialize.test.ts +559 -0
- package/src/schema/serialize.ts +359 -0
- package/src/schema-generator/schema-generator.ts +12 -0
- package/src/shared/config.ts +0 -8
- package/src/util/import-generator.ts +28 -0
- package/src/util/parse.ts +16 -0
- package/src/util/types.ts +4 -0
- package/tsconfig.json +1 -1
- package/tsdown.config.ts +11 -1
- package/vitest.config.ts +3 -0
- /package/dist/{cuid.js → id.js} +0 -0
- /package/src/{cuid.ts → id.ts} +0 -0
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { Column } from "../../schema/create.js";
|
|
2
|
+
import { serialize } from "../../schema/serialize.js";
|
|
3
|
+
import { ReferenceSubquery, encodeValues } from "../../query/result-transform.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
|
|
6
|
+
//#region src/adapters/kysely/kysely-query-builder.ts
|
|
7
|
+
/**
|
|
8
|
+
* Returns the fully qualified SQL name for a column (table.column).
|
|
9
|
+
*
|
|
10
|
+
* @param column - The column to get the full name for
|
|
11
|
+
* @returns The fully qualified SQL name in the format "tableName.columnName"
|
|
12
|
+
* @internal
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* fullSQLName(userTable.columns.email)
|
|
17
|
+
* // Returns: "users.email"
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
function fullSQLName(column) {
|
|
21
|
+
return `${column.tableName}.${column.name}`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Builds a WHERE clause expression from a Condition tree.
|
|
25
|
+
*
|
|
26
|
+
* Recursively processes condition objects to build Kysely WHERE expressions.
|
|
27
|
+
* Handles comparison operators, logical AND/OR/NOT, and special string operators
|
|
28
|
+
* like "contains", "starts with", and "ends with".
|
|
29
|
+
*
|
|
30
|
+
* @param condition - The condition tree to build the WHERE clause from
|
|
31
|
+
* @param eb - Kysely expression builder for constructing SQL expressions
|
|
32
|
+
* @param provider - The SQL provider (affects SQL generation)
|
|
33
|
+
* @returns A Kysely expression wrapper representing the WHERE clause
|
|
34
|
+
* @internal
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* const condition = {
|
|
39
|
+
* type: "compare",
|
|
40
|
+
* a: userTable.columns.name,
|
|
41
|
+
* operator: "contains",
|
|
42
|
+
* b: "john"
|
|
43
|
+
* };
|
|
44
|
+
* const whereClause = buildWhere(condition, eb, 'postgresql');
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
function buildWhere(condition, eb, provider) {
|
|
48
|
+
if (condition.type === "compare") {
|
|
49
|
+
const left = condition.a;
|
|
50
|
+
const op = condition.operator;
|
|
51
|
+
let val = condition.b;
|
|
52
|
+
if (!(val instanceof Column)) val = serialize(val, left, provider);
|
|
53
|
+
let v;
|
|
54
|
+
let rhs;
|
|
55
|
+
switch (op) {
|
|
56
|
+
case "contains":
|
|
57
|
+
v = "like";
|
|
58
|
+
rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))}, '%')` : `%${val}%`;
|
|
59
|
+
break;
|
|
60
|
+
case "not contains":
|
|
61
|
+
v = "not like";
|
|
62
|
+
rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))}, '%')` : `%${val}%`;
|
|
63
|
+
break;
|
|
64
|
+
case "starts with":
|
|
65
|
+
v = "like";
|
|
66
|
+
rhs = val instanceof Column ? sql`concat(${eb.ref(fullSQLName(val))}, '%')` : `${val}%`;
|
|
67
|
+
break;
|
|
68
|
+
case "not starts with":
|
|
69
|
+
v = "not like";
|
|
70
|
+
rhs = val instanceof Column ? sql`concat(${eb.ref(fullSQLName(val))}, '%')` : `${val}%`;
|
|
71
|
+
break;
|
|
72
|
+
case "ends with":
|
|
73
|
+
v = "like";
|
|
74
|
+
rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))})` : `%${val}`;
|
|
75
|
+
break;
|
|
76
|
+
case "not ends with":
|
|
77
|
+
v = "not like";
|
|
78
|
+
rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))})` : `%${val}`;
|
|
79
|
+
break;
|
|
80
|
+
default:
|
|
81
|
+
v = op;
|
|
82
|
+
rhs = val instanceof Column ? eb.ref(fullSQLName(val)) : val;
|
|
83
|
+
}
|
|
84
|
+
return eb(fullSQLName(left), v, rhs);
|
|
85
|
+
}
|
|
86
|
+
if (condition.type === "and") return eb.and(condition.items.map((v) => buildWhere(v, eb, provider)));
|
|
87
|
+
if (condition.type === "not") return eb.not(buildWhere(condition.item, eb, provider));
|
|
88
|
+
return eb.or(condition.items.map((v) => buildWhere(v, eb, provider)));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Maps a select clause to SQL column names with optional aliases.
|
|
92
|
+
*
|
|
93
|
+
* Converts application-level select clauses (either array of keys or "select all")
|
|
94
|
+
* into SQL-compatible column selections with proper aliasing for relations.
|
|
95
|
+
*
|
|
96
|
+
* @param select - The select clause (array of keys or true for all columns)
|
|
97
|
+
* @param table - The table schema containing column definitions
|
|
98
|
+
* @param options - Optional configuration
|
|
99
|
+
* @param options.relation - Relation name to prefix in aliases (for joined data)
|
|
100
|
+
* @param options.tableName - Override the table name in the SQL (defaults to table.name)
|
|
101
|
+
* @returns Array of SQL select strings in the format "tableName.columnName as alias"
|
|
102
|
+
* @internal
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```ts
|
|
106
|
+
* mapSelect(['id', 'name'], userTable)
|
|
107
|
+
* // Returns: ['users.id as id', 'users.name as name']
|
|
108
|
+
*
|
|
109
|
+
* mapSelect(['title'], postTable, { relation: 'posts' })
|
|
110
|
+
* // Returns: ['posts.title as posts:title']
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
function mapSelect(select, table, options = {}) {
|
|
114
|
+
const { relation, tableName = table.name } = options;
|
|
115
|
+
const out = [];
|
|
116
|
+
const keys = Array.isArray(select) ? select : Object.keys(table.columns);
|
|
117
|
+
for (const key of keys) {
|
|
118
|
+
const col = table.columns[key];
|
|
119
|
+
if (Array.isArray(select) && col.isHidden) continue;
|
|
120
|
+
const name = relation ? `${relation}:${key}` : key;
|
|
121
|
+
out.push(`${tableName}.${col.name} as ${name}`);
|
|
122
|
+
}
|
|
123
|
+
for (const key in table.columns) {
|
|
124
|
+
const col = table.columns[key];
|
|
125
|
+
if (col.isHidden && !keys.includes(key)) {
|
|
126
|
+
const name = relation ? `${relation}:${key}` : key;
|
|
127
|
+
out.push(`${tableName}.${col.name} as ${name}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Creates a builder that can extend a select clause with additional keys.
|
|
134
|
+
*
|
|
135
|
+
* This is useful when you need to temporarily include columns for join operations
|
|
136
|
+
* or other internal processing, but don't want them in the final result.
|
|
137
|
+
*
|
|
138
|
+
* @param original - The original select clause from the user
|
|
139
|
+
* @returns A select builder with extend() and compile() methods
|
|
140
|
+
* @internal
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```ts
|
|
144
|
+
* const builder = extendSelect(['name', 'email']);
|
|
145
|
+
* builder.extend('id'); // Add id for join operation
|
|
146
|
+
* const { result, removeExtendedKeys } = builder.compile();
|
|
147
|
+
* // result: ['name', 'email', 'id']
|
|
148
|
+
*
|
|
149
|
+
* const record = { name: 'John', email: 'j@ex.com', id: 123 };
|
|
150
|
+
* removeExtendedKeys(record);
|
|
151
|
+
* // record: { name: 'John', email: 'j@ex.com' }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
function extendSelect(original) {
|
|
155
|
+
const select = Array.isArray(original) ? new Set(original) : true;
|
|
156
|
+
const extendedKeys = [];
|
|
157
|
+
return {
|
|
158
|
+
extend(key) {
|
|
159
|
+
if (select === true || select.has(key)) return;
|
|
160
|
+
select.add(key);
|
|
161
|
+
extendedKeys.push(key);
|
|
162
|
+
},
|
|
163
|
+
compile() {
|
|
164
|
+
return {
|
|
165
|
+
result: select instanceof Set ? Array.from(select) : true,
|
|
166
|
+
extendedKeys,
|
|
167
|
+
removeExtendedKeys(record) {
|
|
168
|
+
for (const key of extendedKeys) delete record[key];
|
|
169
|
+
return record;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Processes encoded values and replaces ReferenceSubquery markers with actual SQL subqueries.
|
|
177
|
+
*
|
|
178
|
+
* @param values - The encoded values that may contain ReferenceSubquery objects
|
|
179
|
+
* @param kysely - The Kysely database instance for building subqueries
|
|
180
|
+
* @returns Processed values with subqueries in place of ReferenceSubquery markers
|
|
181
|
+
* @internal
|
|
182
|
+
*/
|
|
183
|
+
function processReferenceSubqueries(values, kysely) {
|
|
184
|
+
const processed = {};
|
|
185
|
+
for (const [key, value] of Object.entries(values)) if (value instanceof ReferenceSubquery) {
|
|
186
|
+
const refTable = value.referencedTable;
|
|
187
|
+
const externalId = value.externalIdValue;
|
|
188
|
+
processed[key] = kysely.selectFrom(refTable.name).select(refTable.getInternalIdColumn().name).where(refTable.getIdColumn().name, "=", externalId).limit(1);
|
|
189
|
+
} else processed[key] = value;
|
|
190
|
+
return processed;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Creates a query compiler that builds and compiles Kysely queries without executing them.
|
|
194
|
+
*
|
|
195
|
+
* Each method takes table and query parameters and returns a CompiledQuery that can be
|
|
196
|
+
* executed later using kysely.executeQuery().
|
|
197
|
+
*
|
|
198
|
+
* @param kysely - The Kysely database instance
|
|
199
|
+
* @param provider - The SQL provider (affects SQL generation)
|
|
200
|
+
* @returns An object with methods for compiling various database operations
|
|
201
|
+
* @internal
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* const builder = createKyselyQueryBuilder(kysely, 'postgresql');
|
|
206
|
+
* const query = builder.count(userTable, { where: someCondition });
|
|
207
|
+
* const result = await kysely.executeQuery(query);
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
function createKyselyQueryBuilder(kysely, provider) {
|
|
211
|
+
return {
|
|
212
|
+
count(table, { where }) {
|
|
213
|
+
let query = kysely.selectFrom(table.name).select(kysely.fn.countAll().as("count"));
|
|
214
|
+
if (where) query = query.where((b) => buildWhere(where, b, provider));
|
|
215
|
+
return query.compile();
|
|
216
|
+
},
|
|
217
|
+
create(table, values) {
|
|
218
|
+
const processedValues = processReferenceSubqueries(encodeValues(values, table, true, provider), kysely);
|
|
219
|
+
const insert = kysely.insertInto(table.name).values(processedValues);
|
|
220
|
+
if (provider === "mssql") return insert.output(mapSelect(true, table, { tableName: "inserted" })).compile();
|
|
221
|
+
if (provider === "postgresql" || provider === "sqlite") return insert.returning(mapSelect(true, table)).compile();
|
|
222
|
+
return insert.compile();
|
|
223
|
+
},
|
|
224
|
+
findMany(table, v) {
|
|
225
|
+
let query = kysely.selectFrom(table.name);
|
|
226
|
+
const where = v.where;
|
|
227
|
+
if (where) query = query.where((eb) => buildWhere(where, eb, provider));
|
|
228
|
+
if (v.offset !== void 0) query = query.offset(v.offset);
|
|
229
|
+
if (v.limit !== void 0) query = provider === "mssql" ? query.top(v.limit) : query.limit(v.limit);
|
|
230
|
+
if (v.orderBy) for (const [col, mode] of v.orderBy) query = query.orderBy(fullSQLName(col), mode);
|
|
231
|
+
const selectBuilder = extendSelect(v.select);
|
|
232
|
+
const mappedSelect = [];
|
|
233
|
+
const processJoins = (joins, parentTable, parentTableName, parentPath = "") => {
|
|
234
|
+
for (const join of joins ?? []) {
|
|
235
|
+
const { options: joinOptions, relation } = join;
|
|
236
|
+
if (joinOptions === false) continue;
|
|
237
|
+
const targetTable = relation.table;
|
|
238
|
+
const fullPath = parentPath ? `${parentPath}:${relation.name}` : relation.name;
|
|
239
|
+
const joinName = fullPath.replace(/:/g, "_");
|
|
240
|
+
mappedSelect.push(...mapSelect(joinOptions.select, targetTable, {
|
|
241
|
+
relation: fullPath,
|
|
242
|
+
tableName: joinName
|
|
243
|
+
}));
|
|
244
|
+
query = query.leftJoin(`${targetTable.name} as ${joinName}`, (b) => b.on((eb) => {
|
|
245
|
+
const conditions = [];
|
|
246
|
+
for (const [left, right] of relation.on) {
|
|
247
|
+
const actualRight = targetTable.columns[right]?.role === "external-id" ? "_internalId" : right;
|
|
248
|
+
conditions.push(eb(`${parentTableName}.${parentTable.columns[left].name}`, "=", eb.ref(`${joinName}.${targetTable.columns[actualRight].name}`)));
|
|
249
|
+
}
|
|
250
|
+
if (joinOptions.where) conditions.push(buildWhere(joinOptions.where, eb, provider));
|
|
251
|
+
return eb.and(conditions);
|
|
252
|
+
}));
|
|
253
|
+
processJoins(joinOptions.join, targetTable, joinName, fullPath);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
processJoins(v.join, table, table.name);
|
|
257
|
+
const compiledSelect = selectBuilder.compile();
|
|
258
|
+
mappedSelect.push(...mapSelect(compiledSelect.result, table));
|
|
259
|
+
return query.select(mappedSelect).compile();
|
|
260
|
+
},
|
|
261
|
+
updateMany(table, v) {
|
|
262
|
+
const processed = processReferenceSubqueries(encodeValues(v.set, table, false, provider), kysely);
|
|
263
|
+
const versionCol = table.getVersionColumn();
|
|
264
|
+
processed[versionCol.name] = sql.raw(`COALESCE(${versionCol.name}, 0) + 1`);
|
|
265
|
+
let query = kysely.updateTable(table.name).set(processed);
|
|
266
|
+
const { where } = v;
|
|
267
|
+
if (where) query = query.where((eb) => buildWhere(where, eb, provider));
|
|
268
|
+
return query.compile();
|
|
269
|
+
},
|
|
270
|
+
upsertCheck(table, where) {
|
|
271
|
+
const idColumn = table.getIdColumn();
|
|
272
|
+
let query = kysely.selectFrom(table.name).select([`${idColumn.name} as id`]);
|
|
273
|
+
if (where) query = query.where((b) => buildWhere(where, b, provider));
|
|
274
|
+
return query.limit(1).compile();
|
|
275
|
+
},
|
|
276
|
+
upsertUpdate(table, update, where, top) {
|
|
277
|
+
const processed = processReferenceSubqueries(encodeValues(update, table, false, provider), kysely);
|
|
278
|
+
let query = kysely.updateTable(table.name).set(processed);
|
|
279
|
+
if (top) query = query.top(1);
|
|
280
|
+
if (where) query = query.where((b) => buildWhere(where, b, provider));
|
|
281
|
+
return query.compile();
|
|
282
|
+
},
|
|
283
|
+
upsertUpdateById(table, update, id) {
|
|
284
|
+
const idColumn = table.getIdColumn();
|
|
285
|
+
const processed = processReferenceSubqueries(encodeValues(update, table, false, provider), kysely);
|
|
286
|
+
return kysely.updateTable(table.name).set(processed).where(idColumn.name, "=", id).compile();
|
|
287
|
+
},
|
|
288
|
+
createMany(table, values) {
|
|
289
|
+
const processedValues = values.map((v) => encodeValues(v, table, true, provider)).map((v) => processReferenceSubqueries(v, kysely));
|
|
290
|
+
return kysely.insertInto(table.name).values(processedValues).compile();
|
|
291
|
+
},
|
|
292
|
+
deleteMany(table, { where }) {
|
|
293
|
+
let query = kysely.deleteFrom(table.name);
|
|
294
|
+
if (where) query = query.where((eb) => buildWhere(where, eb, provider));
|
|
295
|
+
return query.compile();
|
|
296
|
+
},
|
|
297
|
+
findById(table, idValue) {
|
|
298
|
+
const idColumn = table.getIdColumn();
|
|
299
|
+
return kysely.selectFrom(table.name).select(mapSelect(true, table)).where(idColumn.name, "=", idValue).limit(1).compile();
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
//#endregion
|
|
305
|
+
export { createKyselyQueryBuilder };
|
|
306
|
+
//# sourceMappingURL=kysely-query-builder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-query-builder.js","names":["v: BinaryOperator","rhs: unknown","out: string[]","extendedKeys: string[]","processed: Record<string, unknown>","mappedSelect: string[]"],"sources":["../../../src/adapters/kysely/kysely-query-builder.ts"],"sourcesContent":["import {\n type BinaryOperator,\n type CompiledQuery,\n type ExpressionBuilder,\n type ExpressionWrapper,\n type Kysely,\n sql,\n} from \"kysely\";\nimport type { AnySelectClause, FindManyOptions } from \"../../query/query\";\nimport type { SqlBool } from \"kysely\";\nimport { type AnyColumn, type AnyTable, Column } from \"../../schema/create\";\nimport type { SQLProvider } from \"../../shared/providers\";\nimport type { Condition } from \"../../query/condition-builder\";\nimport { serialize } from \"../../schema/serialize\";\nimport type { CompiledJoin, SimplifyFindOptions } from \"../../query/orm/orm\";\nimport { decodeResult, encodeValues, ReferenceSubquery } from \"../../query/result-transform\";\n\n/**\n * Returns the fully qualified SQL name for a column (table.column).\n *\n * @param column - The column to get the full name for\n * @returns The fully qualified SQL name in the format \"tableName.columnName\"\n * @internal\n *\n * @example\n * ```ts\n * fullSQLName(userTable.columns.email)\n * // Returns: \"users.email\"\n * ```\n */\nexport function fullSQLName(column: AnyColumn) {\n return `${column.tableName}.${column.name}`;\n}\n\n/**\n * Builds a WHERE clause expression from a Condition tree.\n *\n * Recursively processes condition objects to build Kysely WHERE expressions.\n * Handles comparison operators, logical AND/OR/NOT, and special string operators\n * like \"contains\", \"starts with\", and \"ends with\".\n *\n * @param condition - The condition tree to build the WHERE clause from\n * @param eb - Kysely expression builder for constructing SQL expressions\n * @param provider - The SQL provider (affects SQL generation)\n * @returns A Kysely expression wrapper representing the WHERE clause\n * @internal\n *\n * @example\n * ```ts\n * const condition = {\n * type: \"compare\",\n * a: userTable.columns.name,\n * operator: \"contains\",\n * b: \"john\"\n * };\n * const whereClause = buildWhere(condition, eb, 'postgresql');\n * ```\n */\nexport function buildWhere(\n condition: Condition,\n eb: ExpressionBuilder<any, any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n provider: SQLProvider,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): ExpressionWrapper<any, any, SqlBool> {\n if (condition.type === \"compare\") {\n const left = condition.a;\n const op = condition.operator;\n let val = condition.b;\n\n if (!(val instanceof Column)) {\n val = serialize(val, left, provider);\n }\n\n let v: BinaryOperator;\n let rhs: unknown;\n\n switch (op) {\n case \"contains\":\n v = \"like\";\n rhs =\n val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))}, '%')` : `%${val}%`;\n break;\n case \"not contains\":\n v = \"not like\";\n rhs =\n val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))}, '%')` : `%${val}%`;\n break;\n case \"starts with\":\n v = \"like\";\n rhs = val instanceof Column ? sql`concat(${eb.ref(fullSQLName(val))}, '%')` : `${val}%`;\n break;\n case \"not starts with\":\n v = \"not like\";\n rhs = val instanceof Column ? sql`concat(${eb.ref(fullSQLName(val))}, '%')` : `${val}%`;\n break;\n case \"ends with\":\n v = \"like\";\n rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))})` : `%${val}`;\n break;\n case \"not ends with\":\n v = \"not like\";\n rhs = val instanceof Column ? sql`concat('%', ${eb.ref(fullSQLName(val))})` : `%${val}`;\n break;\n default:\n v = op;\n rhs = val instanceof Column ? eb.ref(fullSQLName(val)) : val;\n }\n\n return eb(fullSQLName(left), v, rhs);\n }\n\n // Nested conditions\n if (condition.type === \"and\") {\n return eb.and(condition.items.map((v) => buildWhere(v, eb, provider)));\n }\n\n if (condition.type === \"not\") {\n return eb.not(buildWhere(condition.item, eb, provider));\n }\n\n return eb.or(condition.items.map((v) => buildWhere(v, eb, provider)));\n}\n\n/**\n * Maps a select clause to SQL column names with optional aliases.\n *\n * Converts application-level select clauses (either array of keys or \"select all\")\n * into SQL-compatible column selections with proper aliasing for relations.\n *\n * @param select - The select clause (array of keys or true for all columns)\n * @param table - The table schema containing column definitions\n * @param options - Optional configuration\n * @param options.relation - Relation name to prefix in aliases (for joined data)\n * @param options.tableName - Override the table name in the SQL (defaults to table.name)\n * @returns Array of SQL select strings in the format \"tableName.columnName as alias\"\n * @internal\n *\n * @example\n * ```ts\n * mapSelect(['id', 'name'], userTable)\n * // Returns: ['users.id as id', 'users.name as name']\n *\n * mapSelect(['title'], postTable, { relation: 'posts' })\n * // Returns: ['posts.title as posts:title']\n * ```\n */\nexport function mapSelect(\n select: AnySelectClause,\n table: AnyTable,\n options: {\n relation?: string;\n tableName?: string;\n } = {},\n): string[] {\n const { relation, tableName = table.name } = options;\n const out: string[] = [];\n const keys = Array.isArray(select) ? select : Object.keys(table.columns);\n\n for (const key of keys) {\n const col = table.columns[key];\n\n // Skip hidden columns when explicitly selecting\n if (Array.isArray(select) && col.isHidden) {\n continue;\n }\n\n // Add the column to the select list\n const name = relation ? `${relation}:${key}` : key;\n out.push(`${tableName}.${col.name} as ${name}`);\n }\n\n // Always include hidden columns (for FragnoId construction with internal ID and version)\n for (const key in table.columns) {\n const col = table.columns[key];\n if (col.isHidden && !keys.includes(key)) {\n const name = relation ? `${relation}:${key}` : key;\n out.push(`${tableName}.${col.name} as ${name}`);\n }\n }\n\n return out;\n}\n\n/**\n * Result type from compiling a select clause with extensions.\n * @internal\n */\nexport interface CompiledSelect {\n /**\n * The final select clause to use in the query\n */\n result: AnySelectClause;\n\n /**\n * Keys that were added to the select clause (not originally requested)\n */\n extendedKeys: string[];\n\n /**\n * Removes the extended keys from a record (mutates the record).\n * Used to clean up keys that were only needed for join operations.\n *\n * @param record - The record to remove extended keys from\n * @returns The same record with extended keys removed\n */\n removeExtendedKeys: (record: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/**\n * Builder for extending a select clause with additional keys.\n * @internal\n */\nexport interface SelectBuilder {\n /**\n * Adds a key to the select clause if not already present.\n * Tracks which keys were added for later removal.\n *\n * @param key - The key to add to the select clause\n */\n extend: (key: string) => void;\n\n /**\n * Compiles the select clause into its final form.\n *\n * @returns The compiled select information\n */\n compile: () => CompiledSelect;\n}\n\n/**\n * Creates a builder that can extend a select clause with additional keys.\n *\n * This is useful when you need to temporarily include columns for join operations\n * or other internal processing, but don't want them in the final result.\n *\n * @param original - The original select clause from the user\n * @returns A select builder with extend() and compile() methods\n * @internal\n *\n * @example\n * ```ts\n * const builder = extendSelect(['name', 'email']);\n * builder.extend('id'); // Add id for join operation\n * const { result, removeExtendedKeys } = builder.compile();\n * // result: ['name', 'email', 'id']\n *\n * const record = { name: 'John', email: 'j@ex.com', id: 123 };\n * removeExtendedKeys(record);\n * // record: { name: 'John', email: 'j@ex.com' }\n * ```\n */\nexport function extendSelect(original: AnySelectClause): SelectBuilder {\n const select = Array.isArray(original) ? new Set(original) : true;\n const extendedKeys: string[] = [];\n\n return {\n extend(key) {\n if (select === true || select.has(key)) {\n return;\n }\n\n select.add(key);\n extendedKeys.push(key);\n },\n compile() {\n return {\n result: select instanceof Set ? Array.from(select) : true,\n extendedKeys,\n removeExtendedKeys(record) {\n for (const key of extendedKeys) {\n delete record[key];\n }\n return record;\n },\n };\n },\n };\n}\n\n/**\n * Executes a SELECT query to find multiple records.\n *\n * Builds and executes a Kysely query with the provided options including\n * filtering (where), ordering (orderBy), pagination (limit/offset), and\n * column selection (select).\n *\n * @param kysely - The Kysely database instance\n * @param provider - The SQL provider (affects SQL generation)\n * @param table - The table to query from\n * @param v - Query options including where, select, orderBy, limit, and offset\n * @param runSubQueryJoin - Function to execute subquery joins on the results\n * @returns Array of decoded records matching the query criteria\n * @internal\n *\n * @example\n * ```ts\n * const records = await findMany(kysely, 'postgresql', userTable, {\n * where: someCondition,\n * orderBy: [['name', 'asc']],\n * limit: 10\n * });\n * ```\n */\nexport async function findMany(\n kysely: Kysely<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n provider: SQLProvider,\n table: AnyTable,\n v: SimplifyFindOptions<FindManyOptions>,\n runSubQueryJoin: (records: Record<string, unknown>[], join: CompiledJoin) => Promise<void>,\n) {\n let query = kysely.selectFrom(table.name);\n\n const where = v.where;\n if (where) {\n query = query.where((eb) => buildWhere(where, eb, provider));\n }\n\n if (v.offset !== undefined) {\n query = query.offset(v.offset);\n }\n\n if (v.limit !== undefined) {\n query = provider === \"mssql\" ? query.top(v.limit) : query.limit(v.limit);\n }\n\n if (v.orderBy) {\n for (const [col, mode] of v.orderBy) {\n query = query.orderBy(fullSQLName(col), mode);\n }\n }\n\n const selectBuilder = extendSelect(v.select);\n const mappedSelect: string[] = [];\n const subqueryJoins: CompiledJoin[] = [];\n\n const compiledSelect = selectBuilder.compile();\n mappedSelect.push(...mapSelect(compiledSelect.result, table));\n\n const records = (await query.select(mappedSelect).execute()).map((v) =>\n decodeResult(v, table, provider),\n );\n\n await Promise.all(subqueryJoins.map((join) => runSubQueryJoin(records, join)));\n for (const record of records) {\n compiledSelect.removeExtendedKeys(record);\n }\n\n return records;\n}\n\n/**\n * Processes encoded values and replaces ReferenceSubquery markers with actual SQL subqueries.\n *\n * @param values - The encoded values that may contain ReferenceSubquery objects\n * @param kysely - The Kysely database instance for building subqueries\n * @returns Processed values with subqueries in place of ReferenceSubquery markers\n * @internal\n */\nfunction processReferenceSubqueries(\n values: Record<string, unknown>,\n kysely: Kysely<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n): Record<string, unknown> {\n const processed: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(values)) {\n if (value instanceof ReferenceSubquery) {\n const refTable = value.referencedTable;\n const externalId = value.externalIdValue;\n\n // Build a subquery: SELECT _internal_id FROM referenced_table WHERE id = external_id LIMIT 1\n processed[key] = kysely\n .selectFrom(refTable.name)\n .select(refTable.getInternalIdColumn().name)\n .where(refTable.getIdColumn().name, \"=\", externalId)\n .limit(1);\n } else {\n processed[key] = value;\n }\n }\n\n return processed;\n}\n\n/**\n * Creates a query compiler that builds and compiles Kysely queries without executing them.\n *\n * Each method takes table and query parameters and returns a CompiledQuery that can be\n * executed later using kysely.executeQuery().\n *\n * @param kysely - The Kysely database instance\n * @param provider - The SQL provider (affects SQL generation)\n * @returns An object with methods for compiling various database operations\n * @internal\n *\n * @example\n * ```ts\n * const builder = createKyselyQueryBuilder(kysely, 'postgresql');\n * const query = builder.count(userTable, { where: someCondition });\n * const result = await kysely.executeQuery(query);\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createKyselyQueryBuilder(kysely: Kysely<any>, provider: SQLProvider) {\n return {\n count(table: AnyTable, { where }: { where?: Condition }): CompiledQuery {\n let query = kysely.selectFrom(table.name).select(kysely.fn.countAll().as(\"count\"));\n if (where) {\n query = query.where((b) => buildWhere(where, b, provider));\n }\n return query.compile();\n },\n\n create(table: AnyTable, values: Record<string, unknown>): CompiledQuery {\n const encodedValues = encodeValues(values, table, true, provider);\n const processedValues = processReferenceSubqueries(encodedValues, kysely);\n const insert = kysely.insertInto(table.name).values(processedValues);\n\n if (provider === \"mssql\") {\n return (\n insert\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .output(mapSelect(true, table, { tableName: \"inserted\" }) as any[])\n .compile()\n );\n }\n\n if (provider === \"postgresql\" || provider === \"sqlite\") {\n return insert.returning(mapSelect(true, table)).compile();\n }\n\n // For MySQL/other providers, return the insert query\n return insert.compile();\n },\n\n findMany<T extends AnyTable>(\n table: T,\n v: SimplifyFindOptions<FindManyOptions<T>>,\n ): CompiledQuery {\n let query = kysely.selectFrom(table.name);\n\n const where = v.where;\n if (where) {\n query = query.where((eb) => buildWhere(where, eb, provider));\n }\n\n if (v.offset !== undefined) {\n query = query.offset(v.offset);\n }\n\n if (v.limit !== undefined) {\n query = provider === \"mssql\" ? query.top(v.limit) : query.limit(v.limit);\n }\n\n if (v.orderBy) {\n for (const [col, mode] of v.orderBy) {\n query = query.orderBy(fullSQLName(col), mode);\n }\n }\n\n const selectBuilder = extendSelect(v.select);\n const mappedSelect: string[] = [];\n\n // Process joins recursively to support nested joins\n const processJoins = (\n joins: CompiledJoin[] | undefined,\n parentTable: AnyTable,\n parentTableName: string,\n parentPath: string = \"\",\n ) => {\n for (const join of joins ?? []) {\n const { options: joinOptions, relation } = join;\n\n if (joinOptions === false) {\n continue;\n }\n\n const targetTable = relation.table;\n // Build the full path for this join (e.g., \"author:inviter\")\n const fullPath = parentPath ? `${parentPath}:${relation.name}` : relation.name;\n // SQL table alias uses underscores (e.g., \"author_inviter\")\n const joinName = fullPath.replace(/:/g, \"_\");\n\n // update select\n mappedSelect.push(\n ...mapSelect(joinOptions.select, targetTable, {\n relation: fullPath, // Use full path with colons for column aliases\n tableName: joinName, // Use underscore version for table name\n }),\n );\n\n query = query.leftJoin(`${targetTable.name} as ${joinName}`, (b) =>\n b.on((eb) => {\n const conditions = [];\n for (const [left, right] of relation.on) {\n // Foreign keys always use internal IDs\n // If the relation references an external ID column (any name), translate to \"_internalId\"\n const rightCol = targetTable.columns[right];\n const actualRight = rightCol?.role === \"external-id\" ? \"_internalId\" : right;\n\n conditions.push(\n eb(\n `${parentTableName}.${parentTable.columns[left].name}`,\n \"=\",\n eb.ref(`${joinName}.${targetTable.columns[actualRight].name}`),\n ),\n );\n }\n\n if (joinOptions.where) {\n conditions.push(buildWhere(joinOptions.where, eb, provider));\n }\n\n return eb.and(conditions);\n }),\n );\n\n // Recursively process nested joins with the full path\n processJoins(joinOptions.join, targetTable, joinName, fullPath);\n }\n };\n\n processJoins(v.join, table, table.name);\n\n const compiledSelect = selectBuilder.compile();\n mappedSelect.push(...mapSelect(compiledSelect.result, table));\n\n return query.select(mappedSelect).compile();\n },\n\n updateMany(\n table: AnyTable,\n v: {\n where?: Condition;\n set: Record<string, unknown>;\n },\n ): CompiledQuery {\n const encoded = encodeValues(v.set, table, false, provider);\n const processed = processReferenceSubqueries(encoded, kysely);\n\n // Automatically increment _version for optimistic concurrency control\n const versionCol = table.getVersionColumn();\n // Safe cast: we're building a SQL expression for incrementing the version\n processed[versionCol.name] = sql.raw(`COALESCE(${versionCol.name}, 0) + 1`) as unknown;\n\n let query = kysely.updateTable(table.name).set(processed);\n const { where } = v;\n if (where) {\n query = query.where((eb) => buildWhere(where, eb, provider));\n }\n return query.compile();\n },\n\n upsertCheck(table: AnyTable, where: Condition | undefined): CompiledQuery {\n const idColumn = table.getIdColumn();\n let query = kysely.selectFrom(table.name).select([`${idColumn.name} as id`]);\n if (where) {\n query = query.where((b) => buildWhere(where, b, provider));\n }\n return query.limit(1).compile();\n },\n\n upsertUpdate(\n table: AnyTable,\n update: Record<string, unknown>,\n where: Condition | undefined,\n top?: boolean,\n ): CompiledQuery {\n const encoded = encodeValues(update, table, false, provider);\n const processed = processReferenceSubqueries(encoded, kysely);\n let query = kysely.updateTable(table.name).set(processed);\n if (top) {\n query = query.top(1);\n }\n if (where) {\n query = query.where((b) => buildWhere(where, b, provider));\n }\n return query.compile();\n },\n\n upsertUpdateById(table: AnyTable, update: Record<string, unknown>, id: unknown): CompiledQuery {\n const idColumn = table.getIdColumn();\n const encoded = encodeValues(update, table, false, provider);\n const processed = processReferenceSubqueries(encoded, kysely);\n return kysely.updateTable(table.name).set(processed).where(idColumn.name, \"=\", id).compile();\n },\n\n createMany(table: AnyTable, values: Record<string, unknown>[]): CompiledQuery {\n const encodedValues = values.map((v) => encodeValues(v, table, true, provider));\n const processedValues = encodedValues.map((v) => processReferenceSubqueries(v, kysely));\n return kysely.insertInto(table.name).values(processedValues).compile();\n },\n\n deleteMany(table: AnyTable, { where }: { where?: Condition }): CompiledQuery {\n let query = kysely.deleteFrom(table.name);\n if (where) {\n query = query.where((eb) => buildWhere(where, eb, provider));\n }\n return query.compile();\n },\n\n findById(table: AnyTable, idValue: unknown): CompiledQuery {\n const idColumn = table.getIdColumn();\n return kysely\n .selectFrom(table.name)\n .select(mapSelect(true, table))\n .where(idColumn.name, \"=\", idValue)\n .limit(1)\n .compile();\n },\n };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AAW,OAAO,GAAG,SAAS,CAAC;AAE5D,UAAO,MAAM,SAAS;;EAGxB,iBAAiB,OAAiB,QAAiC,IAA4B;GAC7F,MAAM,WAAW,MAAM,aAAa;GAEpC,MAAM,YAAY,2BADF,aAAa,QAAQ,OAAO,OAAO,SAAS,EACN,OAAO;AAC7D,UAAO,OAAO,YAAY,MAAM,KAAK,CAAC,IAAI,UAAU,CAAC,MAAM,SAAS,MAAM,KAAK,GAAG,CAAC,SAAS;;EAG9F,WAAW,OAAiB,QAAkD;GAE5E,MAAM,kBADgB,OAAO,KAAK,MAAM,aAAa,GAAG,OAAO,MAAM,SAAS,CAAC,CACzC,KAAK,MAAM,2BAA2B,GAAG,OAAO,CAAC;AACvF,UAAO,OAAO,WAAW,MAAM,KAAK,CAAC,OAAO,gBAAgB,CAAC,SAAS;;EAGxE,WAAW,OAAiB,EAAE,SAA+C;GAC3E,IAAI,QAAQ,OAAO,WAAW,MAAM,KAAK;AACzC,OAAI,MACF,SAAQ,MAAM,OAAO,OAAO,WAAW,OAAO,IAAI,SAAS,CAAC;AAE9D,UAAO,MAAM,SAAS;;EAGxB,SAAS,OAAiB,SAAiC;GACzD,MAAM,WAAW,MAAM,aAAa;AACpC,UAAO,OACJ,WAAW,MAAM,KAAK,CACtB,OAAO,UAAU,MAAM,MAAM,CAAC,CAC9B,MAAM,SAAS,MAAM,KAAK,QAAQ,CAClC,MAAM,EAAE,CACR,SAAS;;EAEf"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { buildCondition } from "../../query/condition-builder.js";
|
|
2
|
+
import { buildFindOptions } from "../../query/orm/orm.js";
|
|
3
|
+
import { createKyselyQueryBuilder } from "./kysely-query-builder.js";
|
|
4
|
+
|
|
5
|
+
//#region src/adapters/kysely/kysely-query-compiler.ts
|
|
6
|
+
function createKyselyQueryCompiler(schema, config) {
|
|
7
|
+
const { db: kysely, provider } = config;
|
|
8
|
+
const queryBuilder = createKyselyQueryBuilder(kysely, provider);
|
|
9
|
+
function toTable(name) {
|
|
10
|
+
const table = schema.tables[name];
|
|
11
|
+
if (!table) throw new Error(`Invalid table name ${name}.`);
|
|
12
|
+
return table;
|
|
13
|
+
}
|
|
14
|
+
return {
|
|
15
|
+
count(name, { where } = {}) {
|
|
16
|
+
const table = toTable(name);
|
|
17
|
+
let conditions = where ? buildCondition(table.columns, where) : void 0;
|
|
18
|
+
if (conditions === true) conditions = void 0;
|
|
19
|
+
if (conditions === false) return null;
|
|
20
|
+
return queryBuilder.count(table, { where: conditions });
|
|
21
|
+
},
|
|
22
|
+
findFirst(name, options) {
|
|
23
|
+
const table = toTable(name);
|
|
24
|
+
const compiledOptions = buildFindOptions(table, options);
|
|
25
|
+
if (compiledOptions === false) return null;
|
|
26
|
+
return queryBuilder.findMany(table, {
|
|
27
|
+
...compiledOptions,
|
|
28
|
+
limit: 1
|
|
29
|
+
});
|
|
30
|
+
},
|
|
31
|
+
findMany(name, options = {}) {
|
|
32
|
+
const table = toTable(name);
|
|
33
|
+
const compiledOptions = buildFindOptions(table, options);
|
|
34
|
+
if (compiledOptions === false) return null;
|
|
35
|
+
return queryBuilder.findMany(table, compiledOptions);
|
|
36
|
+
},
|
|
37
|
+
create(name, values) {
|
|
38
|
+
const table = toTable(name);
|
|
39
|
+
return queryBuilder.create(table, values);
|
|
40
|
+
},
|
|
41
|
+
createMany(name, values) {
|
|
42
|
+
const table = toTable(name);
|
|
43
|
+
return queryBuilder.createMany(table, values);
|
|
44
|
+
},
|
|
45
|
+
updateMany(name, { set, where }) {
|
|
46
|
+
const table = toTable(name);
|
|
47
|
+
let conditions = where ? buildCondition(table.columns, where) : void 0;
|
|
48
|
+
if (conditions === true) conditions = void 0;
|
|
49
|
+
if (conditions === false) return null;
|
|
50
|
+
return queryBuilder.updateMany(table, {
|
|
51
|
+
set,
|
|
52
|
+
where: conditions
|
|
53
|
+
});
|
|
54
|
+
},
|
|
55
|
+
deleteMany(name, { where }) {
|
|
56
|
+
const table = toTable(name);
|
|
57
|
+
let conditions = where ? buildCondition(table.columns, where) : void 0;
|
|
58
|
+
if (conditions === true) conditions = void 0;
|
|
59
|
+
if (conditions === false) return null;
|
|
60
|
+
return queryBuilder.deleteMany(table, { where: conditions });
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
//#endregion
|
|
66
|
+
export { createKyselyQueryCompiler };
|
|
67
|
+
//# sourceMappingURL=kysely-query-compiler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-query-compiler.js","names":[],"sources":["../../../src/adapters/kysely/kysely-query-compiler.ts"],"sourcesContent":["import type { CompiledQuery } from \"kysely\";\nimport type { AnySchema, AnyTable } from \"../../schema/create\";\nimport { buildCondition } from \"../../query/condition-builder\";\nimport { buildFindOptions } from \"../../query/orm/orm\";\nimport type { KyselyConfig } from \"./kysely-adapter\";\nimport { createKyselyQueryBuilder } from \"./kysely-query-builder\";\nimport type { ConditionBuilder, Condition } from \"../../query/condition-builder\";\n\n/**\n * Internal query compiler interface for Kysely\n * Used by the UOW compiler to generate compiled queries\n */\nexport interface KyselyQueryCompiler {\n count: (\n name: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options?: { where?: (eb: ConditionBuilder<any>) => any },\n ) => CompiledQuery | null;\n findFirst: (name: string, options: any) => CompiledQuery | null; // eslint-disable-line @typescript-eslint/no-explicit-any\n findMany: (name: string, options?: any) => CompiledQuery | null; // eslint-disable-line @typescript-eslint/no-explicit-any\n create: (name: string, values: any) => CompiledQuery; // eslint-disable-line @typescript-eslint/no-explicit-any\n createMany: (name: string, values: any[]) => CompiledQuery; // eslint-disable-line @typescript-eslint/no-explicit-any\n updateMany: (name: string, options: { set: any; where?: any }) => CompiledQuery | null; // eslint-disable-line @typescript-eslint/no-explicit-any\n deleteMany: (name: string, options: { where?: any }) => CompiledQuery | null; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\nexport function createKyselyQueryCompiler<T extends AnySchema>(\n schema: T,\n config: KyselyConfig,\n): KyselyQueryCompiler {\n const { db: kysely, provider } = config;\n const queryBuilder = createKyselyQueryBuilder(kysely, provider);\n\n function toTable(name: unknown): AnyTable {\n const table = schema.tables[name as string];\n if (!table) {\n throw new Error(`Invalid table name ${name}.`);\n }\n return table;\n }\n\n return {\n count(name, { where } = {}) {\n const table = toTable(name);\n let conditions = where ? buildCondition(table.columns, where) : undefined;\n if (conditions === true) {\n conditions = undefined;\n }\n if (conditions === false) {\n return null;\n }\n\n return queryBuilder.count(table, { where: conditions });\n },\n\n findFirst(name, options) {\n const table = toTable(name);\n // Safe cast: FindFirstOptions is structurally compatible with FindManyOptions\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const compiledOptions = buildFindOptions(table, options as any);\n if (compiledOptions === false) {\n return null;\n }\n\n return queryBuilder.findMany(table, {\n ...compiledOptions,\n limit: 1,\n });\n },\n\n findMany(name, options = {}) {\n const table = toTable(name);\n // Safe cast: FindManyOptions from compiler matches FindManyOptions from buildFindOptions\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const compiledOptions = buildFindOptions(table, options as any);\n if (compiledOptions === false) {\n return null;\n }\n\n return queryBuilder.findMany(table, compiledOptions);\n },\n\n create(name, values) {\n const table = toTable(name);\n return queryBuilder.create(table, values);\n },\n\n createMany(name, values) {\n const table = toTable(name);\n return queryBuilder.createMany(table, values);\n },\n\n updateMany(name, { set, where }) {\n const table = toTable(name);\n let conditions = where ? buildCondition(table.columns, where) : undefined;\n if (conditions === true) {\n conditions = undefined;\n }\n if (conditions === false) {\n return null;\n }\n\n // Safe: conditions is Condition | undefined after filtering out true/false\n return queryBuilder.updateMany(table, {\n set,\n where: conditions as Condition | undefined,\n });\n },\n\n deleteMany(name, { where }) {\n const table = toTable(name);\n let conditions = where ? buildCondition(table.columns, where) : undefined;\n if (conditions === true) {\n conditions = undefined;\n }\n if (conditions === false) {\n return null;\n }\n\n // Safe: conditions is Condition | undefined after filtering out true/false\n return queryBuilder.dele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,eAAe,MAAM,SAAS,MAAM,GAAG;AAChE,OAAI,eAAe,KACjB,cAAa;AAEf,OAAI,eAAe,MACjB,QAAO;AAIT,UAAO,aAAa,WAAW,OAAO;IACpC;IACA,OAAO;IACR,CAAC;;EAGJ,WAAW,MAAM,EAAE,SAAS;GAC1B,MAAM,QAAQ,QAAQ,KAAK;GAC3B,IAAI,aAAa,QAAQ,eAAe,MAAM,SAAS,MAAM,GAAG;AAChE,OAAI,eAAe,KACjB,cAAa;AAEf,OAAI,eAAe,MACjB,QAAO;AAIT,UAAO,aAAa,WAAW,OAAO,EAAE,OAAO,YAAqC,CAAC;;EAExF"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { UnitOfWork } from "../../query/unit-of-work.js";
|
|
2
|
+
import { decodeResult } from "../../query/result-transform.js";
|
|
3
|
+
import { createKyselyUOWCompiler } from "./kysely-uow-compiler.js";
|
|
4
|
+
import { executeKyselyMutationPhase, executeKyselyRetrievalPhase } from "./kysely-uow-executor.js";
|
|
5
|
+
|
|
6
|
+
//#region src/adapters/kysely/kysely-query.ts
|
|
7
|
+
/**
|
|
8
|
+
* Creates a Kysely-based query engine for the given schema.
|
|
9
|
+
*
|
|
10
|
+
* This is the main entry point for creating a database query interface using Kysely.
|
|
11
|
+
* It uses a compiler-based architecture where queries are compiled to SQL and then executed,
|
|
12
|
+
* enabling features like SQL snapshot testing.
|
|
13
|
+
*
|
|
14
|
+
* @param schema - The database schema definition
|
|
15
|
+
* @param config - Kysely configuration containing the database instance and provider
|
|
16
|
+
* @returns An AbstractQuery instance for performing database operations
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const queryEngine = fromKysely(mySchema, {
|
|
21
|
+
* db: kysely,
|
|
22
|
+
* provider: 'postgresql'
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* const users = await queryEngine.findMany('users', {
|
|
26
|
+
* where: (b) => b('age', '>', 18),
|
|
27
|
+
* orderBy: [['name', 'asc']]
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
function fromKysely(schema, config) {
|
|
32
|
+
const { db: kysely, provider } = config;
|
|
33
|
+
const uowCompiler = createKyselyUOWCompiler(schema, config);
|
|
34
|
+
function createUOW(name) {
|
|
35
|
+
const executor = {
|
|
36
|
+
executeRetrievalPhase: (retrievalBatch) => executeKyselyRetrievalPhase(kysely, retrievalBatch),
|
|
37
|
+
executeMutationPhase: (mutationBatch) => executeKyselyMutationPhase(kysely, mutationBatch)
|
|
38
|
+
};
|
|
39
|
+
const decoder = (rawResults, ops) => {
|
|
40
|
+
if (rawResults.length !== ops.length) throw new Error("rawResults and ops must have the same length");
|
|
41
|
+
return rawResults.map((rows, index) => {
|
|
42
|
+
const op = ops[index];
|
|
43
|
+
if (!op) throw new Error("op must be defined");
|
|
44
|
+
if (op.type === "count") {
|
|
45
|
+
const firstRow = rows[0];
|
|
46
|
+
if (!firstRow) return 0;
|
|
47
|
+
const count = Number(firstRow["count"]);
|
|
48
|
+
if (Number.isNaN(count)) throw new Error(`Unexpected result for count, received: ${count}`);
|
|
49
|
+
return count;
|
|
50
|
+
}
|
|
51
|
+
return rows.map((row) => decodeResult(row, op.table, provider));
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
return new UnitOfWork(schema, uowCompiler, executor, decoder, name);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
async find(tableName, builderFn) {
|
|
58
|
+
const uow = createUOW();
|
|
59
|
+
uow.find(tableName, builderFn);
|
|
60
|
+
const [result] = await uow.executeRetrieve();
|
|
61
|
+
return result ?? [];
|
|
62
|
+
},
|
|
63
|
+
async findFirst(tableName, builderFn) {
|
|
64
|
+
const uow = createUOW();
|
|
65
|
+
if (builderFn) uow.find(tableName, (b) => builderFn(b).pageSize(1));
|
|
66
|
+
else uow.find(tableName, (b) => b.whereIndex("primary").pageSize(1));
|
|
67
|
+
const [result] = await uow.executeRetrieve();
|
|
68
|
+
return result?.[0] ?? null;
|
|
69
|
+
},
|
|
70
|
+
async create(tableName, values) {
|
|
71
|
+
const uow = createUOW();
|
|
72
|
+
uow.create(tableName, values);
|
|
73
|
+
const { success } = await uow.executeMutations();
|
|
74
|
+
if (!success) throw new Error("Failed to create record");
|
|
75
|
+
const [createdId] = uow.getCreatedIds();
|
|
76
|
+
if (!createdId) throw new Error("Failed to get created ID");
|
|
77
|
+
return createdId;
|
|
78
|
+
},
|
|
79
|
+
async createMany(tableName, valuesArray) {
|
|
80
|
+
const uow = createUOW();
|
|
81
|
+
for (const values of valuesArray) uow.create(tableName, values);
|
|
82
|
+
const { success } = await uow.executeMutations();
|
|
83
|
+
if (!success) throw new Error("Failed to create records");
|
|
84
|
+
return uow.getCreatedIds();
|
|
85
|
+
},
|
|
86
|
+
async update(tableName, id, builderFn) {
|
|
87
|
+
const uow = createUOW();
|
|
88
|
+
uow.update(tableName, id, builderFn);
|
|
89
|
+
const { success } = await uow.executeMutations();
|
|
90
|
+
if (!success) throw new Error("Failed to update record (version conflict or record not found)");
|
|
91
|
+
},
|
|
92
|
+
async updateMany(tableName, builderFn) {
|
|
93
|
+
let whereConfig = {};
|
|
94
|
+
let setValues;
|
|
95
|
+
builderFn({
|
|
96
|
+
whereIndex(indexName, condition) {
|
|
97
|
+
whereConfig = {
|
|
98
|
+
indexName,
|
|
99
|
+
condition
|
|
100
|
+
};
|
|
101
|
+
return this;
|
|
102
|
+
},
|
|
103
|
+
set(values) {
|
|
104
|
+
setValues = values;
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
if (!whereConfig.indexName) throw new Error("whereIndex() must be called in updateMany");
|
|
109
|
+
if (!setValues) throw new Error("set() must be called in updateMany");
|
|
110
|
+
const findUow = createUOW();
|
|
111
|
+
findUow.find(tableName, (b) => {
|
|
112
|
+
if (whereConfig.condition) return b.whereIndex(whereConfig.indexName, whereConfig.condition);
|
|
113
|
+
return b.whereIndex(whereConfig.indexName);
|
|
114
|
+
});
|
|
115
|
+
const records = (await findUow.executeRetrieve())[0];
|
|
116
|
+
if (!records || records.length === 0) return;
|
|
117
|
+
const updateUow = createUOW();
|
|
118
|
+
for (const record of records) updateUow.update(tableName, record.id, (b) => b.set(setValues));
|
|
119
|
+
const { success } = await updateUow.executeMutations();
|
|
120
|
+
if (!success) throw new Error("Failed to update records (version conflict)");
|
|
121
|
+
},
|
|
122
|
+
async delete(tableName, id, builderFn) {
|
|
123
|
+
const uow = createUOW();
|
|
124
|
+
uow.delete(tableName, id, builderFn);
|
|
125
|
+
const { success } = await uow.executeMutations();
|
|
126
|
+
if (!success) throw new Error("Failed to delete record (version conflict or record not found)");
|
|
127
|
+
},
|
|
128
|
+
async deleteMany(tableName, builderFn) {
|
|
129
|
+
let whereConfig = {};
|
|
130
|
+
builderFn({ whereIndex(indexName, condition) {
|
|
131
|
+
whereConfig = {
|
|
132
|
+
indexName,
|
|
133
|
+
condition
|
|
134
|
+
};
|
|
135
|
+
return this;
|
|
136
|
+
} });
|
|
137
|
+
if (!whereConfig.indexName) throw new Error("whereIndex() must be called in deleteMany");
|
|
138
|
+
const findUow = createUOW();
|
|
139
|
+
findUow.find(tableName, (b) => {
|
|
140
|
+
if (whereConfig.condition) return b.whereIndex(whereConfig.indexName, whereConfig.condition);
|
|
141
|
+
return b.whereIndex(whereConfig.indexName);
|
|
142
|
+
});
|
|
143
|
+
const records = (await findUow.executeRetrieve())[0];
|
|
144
|
+
if (!records || records.length === 0) return;
|
|
145
|
+
const deleteUow = createUOW();
|
|
146
|
+
for (const record of records) deleteUow.delete(tableName, record.id);
|
|
147
|
+
const { success } = await deleteUow.executeMutations();
|
|
148
|
+
if (!success) throw new Error("Failed to delete records (version conflict)");
|
|
149
|
+
},
|
|
150
|
+
createUnitOfWork(name) {
|
|
151
|
+
return createUOW(name);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
//#endregion
|
|
157
|
+
export { fromKysely };
|
|
158
|
+
//# sourceMappingURL=kysely-query.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-query.js","names":["executor: UOWExecutor<CompiledQuery, unknown>","decoder: UOWDecoder<T>","whereConfig: { indexName?: string; condition?: unknown }","setValues: unknown"],"sources":["../../../src/adapters/kysely/kysely-query.ts"],"sourcesContent":["import type { AbstractQuery } from \"../../query/query\";\nimport type { AnySchema } from \"../../schema/create\";\nimport type { KyselyConfig } from \"./kysely-adapter\";\nimport type { CompiledMutation, UOWDecoder, UOWExecutor } from \"../../query/unit-of-work\";\nimport { decodeResult } from \"../../query/result-transform\";\nimport { createKyselyUOWCompiler } from \"./kysely-uow-compiler\";\nimport { executeKyselyRetrievalPhase, executeKyselyMutationPhase } from \"./kysely-uow-executor\";\nimport { UnitOfWork } from \"../../query/unit-of-work\";\nimport type { CompiledQuery } from \"kysely\";\n\n/**\n * Creates a Kysely-based query engine for the given schema.\n *\n * This is the main entry point for creating a database query interface using Kysely.\n * It uses a compiler-based architecture where queries are compiled to SQL and then executed,\n * enabling features like SQL snapshot testing.\n *\n * @param schema - The database schema definition\n * @param config - Kysely configuration containing the database instance and provider\n * @returns An AbstractQuery instance for performing database operations\n *\n * @example\n * ```ts\n * const queryEngine = fromKysely(mySchema, {\n * db: kysely,\n * provider: 'postgresql'\n * });\n *\n * const users = await queryEngine.findMany('users', {\n * where: (b) => b('age', '>', 18),\n * orderBy: [['name', 'asc']]\n * });\n * ```\n */\nexport function fromKysely<T extends AnySchema>(schema: T, config: KyselyConfig): AbstractQuery<T> {\n const { db: kysely, provider } = config;\n const uowCompiler = createKyselyUOWCompiler(schema, config);\n\n function createUOW(name?: string): UnitOfWork<T, []> {\n const executor: UOWExecutor<CompiledQuery, unknown> = {\n executeRetrievalPhase: (retrievalBatch: CompiledQuery[]) =>\n executeKyselyRetrievalPhase(kysely, retrievalBatch),\n executeMutationPhase: (mutationBatch: CompiledMutation<CompiledQuery>[]) =>\n executeKyselyMutationPhase(kysely, mutationBatch),\n };\n\n // Create a decoder function to transform raw results into application format\n const decoder: UOWDecoder<T> = (rawResults, ops) => {\n if (rawResults.length !== ops.length) {\n throw new Error(\"rawResults and ops must have the same length\");\n }\n\n return rawResults.map((rows, index) => {\n const op = ops[index];\n if (!op) {\n throw new Error(\"op must be defined\");\n }\n\n // Handle count operations differently - return the count number directly\n if (op.type === \"count\") {\n const rowArray = rows as Record<string, unknown>[];\n const firstRow = rowArray[0];\n if (!firstRow) {\n return 0;\n }\n const count = Number(firstRow[\"count\"]);\n if (Number.isNaN(count)) {\n throw new Error(`Unexpected result for count, received: ${count}`);\n }\n return count;\n }\n\n // Each result is an array of rows - decode each row\n const rowArray = rows as Record<string, unknown>[];\n return rowArray.map((row) => decodeResult(row, op.table, provider));\n });\n };\n\n return new UnitOfWork(schema, uowCompiler, executor, decoder, name);\n }\n\n return {\n async find(tableName, builderFn) {\n const uow = createUOW();\n uow.find(tableName, builderFn);\n // executeRetrieve returns an array of results (one per find operation)\n // Since we only have one find, unwrap the first result\n const [result]: unknown[][] = await uow.executeRetrieve();\n return result ?? [];\n },\n\n async findFirst(tableName, builderFn) {\n const uow = createUOW();\n if (builderFn) {\n uow.find(tableName, (b) => builderFn(b as never).pageSize(1));\n } else {\n uow.find(tableName, (b) => b.whereIndex(\"primary\").pageSize(1));\n }\n // executeRetrieve runs an array of `find` operation results, which each return an array of rows\n const [result]: unknown[][] = await uow.executeRetrieve();\n return result?.[0] ?? null;\n },\n\n async create(tableName, values) {\n const uow = createUOW();\n uow.create(tableName, values);\n const { success } = await uow.executeMutations();\n if (!success) {\n // This should not happen because we don't `.check()` this call.\n // TODO: Verify what happens when there are unique constraints\n throw new Error(\"Failed to create record\");\n }\n\n const [createdId] = uow.getCreatedIds();\n if (!createdId) {\n throw new Error(\"Failed to get created ID\");\n }\n return createdId;\n },\n\n async createMany(tableName, valuesArray) {\n const uow = createUOW();\n for (const values of valuesArray) {\n uow.create(tableName, values);\n }\n const { success } = await uow.executeMutations();\n if (!success) {\n throw new Error(\"Failed to create records\");\n }\n\n return uow.getCreatedIds();\n },\n\n async update(tableName, id, builderFn) {\n const uow = createUOW();\n uow.update(tableName, id, builderFn);\n const { success } = await uow.executeMutations();\n if (!success) {\n throw new Error(\"Failed to update record (version conflict or record not found)\");\n }\n },\n\n async updateMany(tableName, builderFn) {\n // Create a special builder that captures both where and set operations\n let whereConfig: { indexName?: string; condition?: unknown } = {};\n let setValues: unknown;\n\n const specialBuilder = {\n whereIndex(indexName: string, condition?: unknown) {\n whereConfig = { indexName, condition };\n return this;\n },\n set(values: unknown) {\n setValues = values;\n return this;\n },\n };\n\n builderFn(specialBuilder);\n\n if (!whereConfig.indexName) {\n throw new Error(\"whereIndex() must be called in updateMany\");\n }\n if (!setValues) {\n throw new Error(\"set() must be called in updateMany\");\n }\n\n // First, find all matching records\n const findUow = createUOW();\n findUow.find(tableName, (b) => {\n if (whereConfig.condition) {\n return b.whereIndex(whereConfig.indexName as never, whereConfig.condition as never);\n }\n return b.whereIndex(whereConfig.indexName as never);\n });\n const findResults: unknown[][] = await findUow.executeRetrieve();\n const records = findResults[0];\n\n if (!records || records.length === 0) {\n return;\n }\n\n // Now update all found records\n const updateUow = createUOW();\n for (const record of records as never as Array<{ id: unknown }>) {\n updateUow.update(tableName as string, record.id as string, (b) =>\n b.set(setValues as never),\n );\n }\n const { success } = await updateUow.executeMutations();\n if (!success) {\n throw new Error(\"Failed to update records (version conflict)\");\n }\n },\n\n async delete(tableName, id, builderFn) {\n const uow = createUOW();\n uow.delete(tableName, id, builderFn as never);\n const { success } = await uow.executeMutations();\n if (!success) {\n throw new Error(\"Failed to delete record (version conflict or record not found)\");\n }\n },\n\n async deleteMany(tableName, builderFn) {\n // Create a special builder that captures where configuration\n let whereConfig: { indexName?: string; condition?: unknown } = {};\n\n const specialBuilder = {\n whereIndex(indexName: string, condition?: unknown) {\n whereConfig = { indexName, condition };\n return this;\n },\n };\n\n // Safe: Call builderFn to capture the configuration\n builderFn(specialBuilder as never);\n\n if (!whereConfig.indexName) {\n throw new Error(\"whereIndex() must be called in deleteMany\");\n }\n\n // First, find all matching records\n const findUow = createUOW();\n findUow.find(tableName as string, (b) => {\n if (whereConfig.condition) {\n return b.whereIndex(whereConfig.indexName as never, whereConfig.condition as never);\n }\n return b.whereIndex(whereConfig.indexName as never);\n });\n const findResults2 = await findUow.executeRetrieve();\n const records = (findResults2 as unknown as [unknown])[0];\n\n // @ts-expect-error - Type narrowing doesn't work through unknown cast\n if (!records || records.length === 0) {\n return;\n }\n\n // Now delete all found records\n const deleteUow = createUOW();\n for (const record of records as never as Array<{ id: unknown }>) {\n deleteUow.delete(tableName as string, record.id as string);\n }\n const { success } = await deleteUow.executeMutations();\n if (!success) {\n throw new Error(\"Failed to delete records (version conflict)\");\n }\n },\n\n createUnitOfWork(name) {\n return createUOW(name);\n },\n } as AbstractQuery<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,WAAgC,QAAW,QAAwC;CACjG,MAAM,EAAE,IAAI,QAAQ,aAAa;CACjC,MAAM,cAAc,wBAAwB,QAAQ,OAAO;CAE3D,SAAS,UAAU,MAAkC;EACnD,MAAMA,WAAgD;GACpD,wBAAwB,mBACtB,4BAA4B,QAAQ,eAAe;GACrD,uBAAuB,kBACrB,2BAA2B,QAAQ,cAAc;GACpD;EAGD,MAAMC,WAA0B,YAAY,QAAQ;AAClD,OAAI,WAAW,WAAW,IAAI,OAC5B,OAAM,IAAI,MAAM,+CAA+C;AAGjE,UAAO,WAAW,KAAK,MAAM,UAAU;IACrC,MAAM,KAAK,IAAI;AACf,QAAI,CAAC,GACH,OAAM,IAAI,MAAM,qBAAqB;AAIvC,QAAI,GAAG,SAAS,SAAS;KAEvB,MAAM,WADW,KACS;AAC1B,SAAI,CAAC,SACH,QAAO;KAET,MAAM,QAAQ,OAAO,SAAS,SAAS;AACvC,SAAI,OAAO,MAAM,MAAM,CACrB,OAAM,IAAI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