@better-auth/kysely-adapter 1.5.0-beta.9

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.
@@ -0,0 +1,16 @@
1
+
2
+ > @better-auth/kysely-adapter@1.5.0-beta.9 build /home/runner/work/better-auth/better-auth/packages/kysely-adapter
3
+ > tsdown
4
+
5
+ ℹ tsdown v0.19.0 powered by rolldown v1.0.0-beta.59
6
+ ℹ config file: /home/runner/work/better-auth/better-auth/packages/kysely-adapter/tsdown.config.ts
7
+ ℹ entry: src/index.ts, src/node-sqlite-dialect.ts
8
+ ℹ tsconfig: tsconfig.json
9
+ ℹ Build start
10
+ ℹ dist/index.mjs 15.21 kB │ gzip: 3.58 kB
11
+ ℹ dist/node-sqlite-dialect.mjs  4.12 kB │ gzip: 1.41 kB
12
+ ℹ dist/bun-sqlite-dialect-deBGXcrd.mjs  4.11 kB │ gzip: 1.41 kB
13
+ ℹ dist/index.d.mts  1.61 kB │ gzip: 0.60 kB
14
+ ℹ dist/node-sqlite-dialect.d.mts  0.89 kB │ gzip: 0.44 kB
15
+ ℹ 5 files, total: 25.95 kB
16
+ ✔ Build complete in 9280ms
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,155 @@
1
+ import { CompiledQuery, DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, DefaultQueryCompiler, sql } from "kysely";
2
+
3
+ //#region src/bun-sqlite-dialect.ts
4
+ var BunSqliteAdapter = class {
5
+ get supportsCreateIfNotExists() {
6
+ return true;
7
+ }
8
+ get supportsTransactionalDdl() {
9
+ return false;
10
+ }
11
+ get supportsReturning() {
12
+ return true;
13
+ }
14
+ async acquireMigrationLock() {}
15
+ async releaseMigrationLock() {}
16
+ get supportsOutput() {
17
+ return true;
18
+ }
19
+ };
20
+ var BunSqliteDriver = class {
21
+ #config;
22
+ #connectionMutex = new ConnectionMutex();
23
+ #db;
24
+ #connection;
25
+ constructor(config) {
26
+ this.#config = { ...config };
27
+ }
28
+ async init() {
29
+ this.#db = this.#config.database;
30
+ this.#connection = new BunSqliteConnection(this.#db);
31
+ if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection);
32
+ }
33
+ async acquireConnection() {
34
+ await this.#connectionMutex.lock();
35
+ return this.#connection;
36
+ }
37
+ async beginTransaction(connection) {
38
+ await connection.executeQuery(CompiledQuery.raw("begin"));
39
+ }
40
+ async commitTransaction(connection) {
41
+ await connection.executeQuery(CompiledQuery.raw("commit"));
42
+ }
43
+ async rollbackTransaction(connection) {
44
+ await connection.executeQuery(CompiledQuery.raw("rollback"));
45
+ }
46
+ async releaseConnection() {
47
+ this.#connectionMutex.unlock();
48
+ }
49
+ async destroy() {
50
+ this.#db?.close();
51
+ }
52
+ };
53
+ var BunSqliteConnection = class {
54
+ #db;
55
+ constructor(db) {
56
+ this.#db = db;
57
+ }
58
+ executeQuery(compiledQuery) {
59
+ const { sql: sql$1, parameters } = compiledQuery;
60
+ const stmt = this.#db.prepare(sql$1);
61
+ return Promise.resolve({ rows: stmt.all(parameters) });
62
+ }
63
+ async *streamQuery() {
64
+ throw new Error("Streaming query is not supported by SQLite driver.");
65
+ }
66
+ };
67
+ var ConnectionMutex = class {
68
+ #promise;
69
+ #resolve;
70
+ async lock() {
71
+ while (this.#promise !== void 0) await this.#promise;
72
+ this.#promise = new Promise((resolve) => {
73
+ this.#resolve = resolve;
74
+ });
75
+ }
76
+ unlock() {
77
+ const resolve = this.#resolve;
78
+ this.#promise = void 0;
79
+ this.#resolve = void 0;
80
+ resolve?.();
81
+ }
82
+ };
83
+ var BunSqliteIntrospector = class {
84
+ #db;
85
+ constructor(db) {
86
+ this.#db = db;
87
+ }
88
+ async getSchemas() {
89
+ return [];
90
+ }
91
+ async getTables(options = { withInternalKyselyTables: false }) {
92
+ let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo();
93
+ if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
94
+ const tables = await query.execute();
95
+ return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));
96
+ }
97
+ async getMetadata(options) {
98
+ return { tables: await this.getTables(options) };
99
+ }
100
+ async #getTableMetadata(table) {
101
+ const db = this.#db;
102
+ const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, "");
103
+ return {
104
+ name: table,
105
+ columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([
106
+ "name",
107
+ "type",
108
+ "notnull",
109
+ "dflt_value"
110
+ ]).execute()).map((col) => ({
111
+ name: col.name,
112
+ dataType: col.type,
113
+ isNullable: !col.notnull,
114
+ isAutoIncrementing: col.name === autoIncrementCol,
115
+ hasDefaultValue: col.dflt_value != null
116
+ })),
117
+ isView: true
118
+ };
119
+ }
120
+ };
121
+ var BunSqliteQueryCompiler = class extends DefaultQueryCompiler {
122
+ getCurrentParameterPlaceholder() {
123
+ return "?";
124
+ }
125
+ getLeftIdentifierWrapper() {
126
+ return "\"";
127
+ }
128
+ getRightIdentifierWrapper() {
129
+ return "\"";
130
+ }
131
+ getAutoIncrement() {
132
+ return "autoincrement";
133
+ }
134
+ };
135
+ var BunSqliteDialect = class {
136
+ #config;
137
+ constructor(config) {
138
+ this.#config = { ...config };
139
+ }
140
+ createDriver() {
141
+ return new BunSqliteDriver(this.#config);
142
+ }
143
+ createQueryCompiler() {
144
+ return new BunSqliteQueryCompiler();
145
+ }
146
+ createAdapter() {
147
+ return new BunSqliteAdapter();
148
+ }
149
+ createIntrospector(db) {
150
+ return new BunSqliteIntrospector(db);
151
+ }
152
+ };
153
+
154
+ //#endregion
155
+ export { BunSqliteDialect };
@@ -0,0 +1,49 @@
1
+ import { Kysely } from "kysely";
2
+ import { DBAdapter, DBAdapterDebugLogOption } from "@better-auth/core/db/adapter";
3
+ import { BetterAuthOptions } from "@better-auth/core";
4
+
5
+ //#region src/types.d.ts
6
+ type KyselyDatabaseType = "postgres" | "mysql" | "sqlite" | "mssql";
7
+ //#endregion
8
+ //#region src/dialect.d.ts
9
+ declare function getKyselyDatabaseType(db: BetterAuthOptions["database"]): KyselyDatabaseType | null;
10
+ declare const createKyselyAdapter: (config: BetterAuthOptions) => Promise<{
11
+ kysely: Kysely<any>;
12
+ databaseType: "postgres" | "mysql" | "sqlite" | "mssql";
13
+ transaction: boolean | undefined;
14
+ } | {
15
+ kysely: Kysely<any> | null;
16
+ databaseType: KyselyDatabaseType | null;
17
+ transaction: undefined;
18
+ }>;
19
+ //#endregion
20
+ //#region src/kysely-adapter.d.ts
21
+ interface KyselyAdapterConfig {
22
+ /**
23
+ * Database type.
24
+ */
25
+ type?: KyselyDatabaseType | undefined;
26
+ /**
27
+ * Enable debug logs for the adapter
28
+ *
29
+ * @default false
30
+ */
31
+ debugLogs?: DBAdapterDebugLogOption | undefined;
32
+ /**
33
+ * Use plural for table names.
34
+ *
35
+ * @default false
36
+ */
37
+ usePlural?: boolean | undefined;
38
+ /**
39
+ * Whether to execute multiple operations in a transaction.
40
+ *
41
+ * If the database doesn't support transactions,
42
+ * set this to `false` and operations will be executed sequentially.
43
+ * @default false
44
+ */
45
+ transaction?: boolean | undefined;
46
+ }
47
+ declare const kyselyAdapter: (db: Kysely<any>, config?: KyselyAdapterConfig | undefined) => (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
48
+ //#endregion
49
+ export { KyselyDatabaseType, createKyselyAdapter, getKyselyDatabaseType, kyselyAdapter };
package/dist/index.mjs ADDED
@@ -0,0 +1,364 @@
1
+ import { Kysely, MssqlDialect, MysqlDialect, PostgresDialect, SqliteDialect, sql } from "kysely";
2
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
3
+
4
+ //#region src/dialect.ts
5
+ function getKyselyDatabaseType(db) {
6
+ if (!db) return null;
7
+ if ("dialect" in db) return getKyselyDatabaseType(db.dialect);
8
+ if ("createDriver" in db) {
9
+ if (db instanceof SqliteDialect) return "sqlite";
10
+ if (db instanceof MysqlDialect) return "mysql";
11
+ if (db instanceof PostgresDialect) return "postgres";
12
+ if (db instanceof MssqlDialect) return "mssql";
13
+ }
14
+ if ("aggregate" in db) return "sqlite";
15
+ if ("getConnection" in db) return "mysql";
16
+ if ("connect" in db) return "postgres";
17
+ if ("fileControl" in db) return "sqlite";
18
+ if ("open" in db && "close" in db && "prepare" in db) return "sqlite";
19
+ return null;
20
+ }
21
+ const createKyselyAdapter = async (config) => {
22
+ const db = config.database;
23
+ if (!db) return {
24
+ kysely: null,
25
+ databaseType: null,
26
+ transaction: void 0
27
+ };
28
+ if ("db" in db) return {
29
+ kysely: db.db,
30
+ databaseType: db.type,
31
+ transaction: db.transaction
32
+ };
33
+ if ("dialect" in db) return {
34
+ kysely: new Kysely({ dialect: db.dialect }),
35
+ databaseType: db.type,
36
+ transaction: db.transaction
37
+ };
38
+ let dialect = void 0;
39
+ const databaseType = getKyselyDatabaseType(db);
40
+ if ("createDriver" in db) dialect = db;
41
+ if ("aggregate" in db && !("createSession" in db)) dialect = new SqliteDialect({ database: db });
42
+ if ("getConnection" in db) dialect = new MysqlDialect(db);
43
+ if ("connect" in db) dialect = new PostgresDialect({ pool: db });
44
+ if ("fileControl" in db) {
45
+ const { BunSqliteDialect } = await import("./bun-sqlite-dialect-deBGXcrd.mjs");
46
+ dialect = new BunSqliteDialect({ database: db });
47
+ }
48
+ if ("createSession" in db && typeof window === "undefined") {
49
+ let DatabaseSync = void 0;
50
+ try {
51
+ const nodeSqlite = "node:sqlite";
52
+ ({DatabaseSync} = await import(
53
+ /* @vite-ignore */
54
+ /* webpackIgnore: true */
55
+ nodeSqlite
56
+ ));
57
+ } catch (error) {
58
+ if (error !== null && typeof error === "object" && "code" in error && error.code !== "ERR_UNKNOWN_BUILTIN_MODULE") throw error;
59
+ }
60
+ if (DatabaseSync && db instanceof DatabaseSync) {
61
+ const { NodeSqliteDialect } = await import("./node-sqlite-dialect.mjs");
62
+ dialect = new NodeSqliteDialect({ database: db });
63
+ }
64
+ }
65
+ return {
66
+ kysely: dialect ? new Kysely({ dialect }) : null,
67
+ databaseType,
68
+ transaction: void 0
69
+ };
70
+ };
71
+
72
+ //#endregion
73
+ //#region src/kysely-adapter.ts
74
+ const kyselyAdapter = (db, config) => {
75
+ let lazyOptions = null;
76
+ const createCustomAdapter = (db$1) => {
77
+ return ({ getFieldName, schema, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => {
78
+ const selectAllJoins = (join) => {
79
+ const allSelects = [];
80
+ const allSelectsStr = [];
81
+ if (join) for (const [joinModel, _] of Object.entries(join)) {
82
+ const fields = schema[getDefaultModelName(joinModel)]?.fields;
83
+ const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel];
84
+ if (!fields) continue;
85
+ fields.id = { type: "string" };
86
+ for (const [field, fieldAttr] of Object.entries(fields)) {
87
+ allSelects.push(sql`${sql.ref(`join_${joinModelName}`)}.${sql.ref(fieldAttr.fieldName || field)} as ${sql.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`);
88
+ allSelectsStr.push({
89
+ joinModel,
90
+ joinModelRef: joinModelName,
91
+ fieldName: fieldAttr.fieldName || field
92
+ });
93
+ }
94
+ }
95
+ return {
96
+ allSelectsStr,
97
+ allSelects
98
+ };
99
+ };
100
+ const withReturning = async (values, builder, model, where) => {
101
+ let res;
102
+ if (config?.type === "mysql") {
103
+ await builder.execute();
104
+ const field = values.id ? "id" : where.length > 0 && where[0]?.field ? where[0].field : "id";
105
+ if (!values.id && where.length === 0) {
106
+ res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({
107
+ model,
108
+ field
109
+ }), "desc").limit(1).executeTakeFirst();
110
+ return res;
111
+ }
112
+ const value = values[field] || where[0]?.value;
113
+ res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({
114
+ model,
115
+ field
116
+ }), "desc").where(getFieldName({
117
+ model,
118
+ field
119
+ }), "=", value).limit(1).executeTakeFirst();
120
+ return res;
121
+ }
122
+ if (config?.type === "mssql") {
123
+ res = await builder.outputAll("inserted").executeTakeFirst();
124
+ return res;
125
+ }
126
+ res = await builder.returningAll().executeTakeFirst();
127
+ return res;
128
+ };
129
+ function convertWhereClause(model, w) {
130
+ if (!w) return {
131
+ and: null,
132
+ or: null
133
+ };
134
+ const conditions = {
135
+ and: [],
136
+ or: []
137
+ };
138
+ w.forEach((condition) => {
139
+ const { field: _field, value: _value, operator = "=", connector = "AND" } = condition;
140
+ const value = _value;
141
+ const field = getFieldName({
142
+ model,
143
+ field: _field
144
+ });
145
+ const expr = (eb) => {
146
+ const f = `${model}.${field}`;
147
+ if (operator.toLowerCase() === "in") return eb(f, "in", Array.isArray(value) ? value : [value]);
148
+ if (operator.toLowerCase() === "not_in") return eb(f, "not in", Array.isArray(value) ? value : [value]);
149
+ if (operator === "contains") return eb(f, "like", `%${value}%`);
150
+ if (operator === "starts_with") return eb(f, "like", `${value}%`);
151
+ if (operator === "ends_with") return eb(f, "like", `%${value}`);
152
+ if (operator === "eq") return eb(f, "=", value);
153
+ if (operator === "ne") return eb(f, "<>", value);
154
+ if (operator === "gt") return eb(f, ">", value);
155
+ if (operator === "gte") return eb(f, ">=", value);
156
+ if (operator === "lt") return eb(f, "<", value);
157
+ if (operator === "lte") return eb(f, "<=", value);
158
+ return eb(f, operator, value);
159
+ };
160
+ if (connector === "OR") conditions.or.push(expr);
161
+ else conditions.and.push(expr);
162
+ });
163
+ return {
164
+ and: conditions.and.length ? conditions.and : null,
165
+ or: conditions.or.length ? conditions.or : null
166
+ };
167
+ }
168
+ function processJoinedResults(rows, joinConfig, allSelectsStr) {
169
+ if (!joinConfig || !rows.length) return rows;
170
+ const groupedByMainId = /* @__PURE__ */ new Map();
171
+ for (const currentRow of rows) {
172
+ const mainModelFields = {};
173
+ const joinedModelFields = {};
174
+ for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {};
175
+ for (const [key, value] of Object.entries(currentRow)) {
176
+ const keyStr = String(key);
177
+ let assigned = false;
178
+ for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}`) {
179
+ joinedModelFields[getModelName(joinModel)][getFieldName({
180
+ model: joinModel,
181
+ field: fieldName
182
+ })] = value;
183
+ assigned = true;
184
+ break;
185
+ }
186
+ if (!assigned) mainModelFields[key] = value;
187
+ }
188
+ const mainId = mainModelFields.id;
189
+ if (!mainId) continue;
190
+ if (!groupedByMainId.has(mainId)) {
191
+ const entry$1 = { ...mainModelFields };
192
+ for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry$1[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : [];
193
+ groupedByMainId.set(mainId, entry$1);
194
+ }
195
+ const entry = groupedByMainId.get(mainId);
196
+ for (const [joinModel, joinAttr] of Object.entries(joinConfig)) {
197
+ const isUnique = joinAttr.relation === "one-to-one";
198
+ const limit = joinAttr.limit ?? 100;
199
+ const joinedObj = joinedModelFields[getModelName(joinModel)];
200
+ const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0);
201
+ if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null;
202
+ else {
203
+ const joinModelName = getModelName(joinModel);
204
+ if (Array.isArray(entry[joinModelName]) && hasData) {
205
+ if (entry[joinModelName].length >= limit) continue;
206
+ const idFieldName = getFieldName({
207
+ model: joinModel,
208
+ field: "id"
209
+ });
210
+ const joinedId = joinedObj[idFieldName];
211
+ if (joinedId) {
212
+ if (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);
213
+ } else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj);
214
+ }
215
+ }
216
+ }
217
+ }
218
+ const result = Array.from(groupedByMainId.values());
219
+ for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") {
220
+ const joinModelName = getModelName(joinModel);
221
+ if (Array.isArray(entry[joinModelName])) {
222
+ const limit = joinAttr.limit ?? 100;
223
+ if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit);
224
+ }
225
+ }
226
+ return result;
227
+ }
228
+ return {
229
+ async create({ data, model }) {
230
+ return await withReturning(data, db$1.insertInto(model).values(data), model, []);
231
+ },
232
+ async findOne({ model, where, select, join }) {
233
+ const { and, or } = convertWhereClause(model, where);
234
+ let query = db$1.selectFrom((eb) => {
235
+ let b = eb.selectFrom(model);
236
+ if (and) b = b.where((eb$1) => eb$1.and(and.map((expr) => expr(eb$1))));
237
+ if (or) b = b.where((eb$1) => eb$1.or(or.map((expr) => expr(eb$1))));
238
+ return b.selectAll().as("primary");
239
+ }).selectAll("primary");
240
+ if (join) for (const [joinModel, joinAttr] of Object.entries(join)) {
241
+ const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel];
242
+ query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`));
243
+ }
244
+ const { allSelectsStr, allSelects } = selectAllJoins(join);
245
+ query = query.select(allSelects);
246
+ const res = await query.execute();
247
+ if (!res || !Array.isArray(res) || res.length === 0) return null;
248
+ const row = res[0];
249
+ if (join) return processJoinedResults(res, join, allSelectsStr)[0];
250
+ return row;
251
+ },
252
+ async findMany({ model, where, limit, offset, sortBy, join }) {
253
+ const { and, or } = convertWhereClause(model, where);
254
+ let query = db$1.selectFrom((eb) => {
255
+ let b = eb.selectFrom(model);
256
+ if (config?.type === "mssql") {
257
+ if (offset !== void 0) {
258
+ if (!sortBy) b = b.orderBy(getFieldName({
259
+ model,
260
+ field: "id"
261
+ }));
262
+ b = b.offset(offset).fetch(limit || 100);
263
+ } else if (limit !== void 0) b = b.top(limit);
264
+ } else {
265
+ if (limit !== void 0) b = b.limit(limit);
266
+ if (offset !== void 0) b = b.offset(offset);
267
+ }
268
+ if (sortBy?.field) b = b.orderBy(`${getFieldName({
269
+ model,
270
+ field: sortBy.field
271
+ })}`, sortBy.direction);
272
+ if (and) b = b.where((eb$1) => eb$1.and(and.map((expr) => expr(eb$1))));
273
+ if (or) b = b.where((eb$1) => eb$1.or(or.map((expr) => expr(eb$1))));
274
+ return b.selectAll().as("primary");
275
+ }).selectAll("primary");
276
+ if (join) for (const [joinModel, joinAttr] of Object.entries(join)) {
277
+ const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel];
278
+ query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`));
279
+ }
280
+ const { allSelectsStr, allSelects } = selectAllJoins(join);
281
+ query = query.select(allSelects);
282
+ if (sortBy?.field) query = query.orderBy(`${getFieldName({
283
+ model,
284
+ field: sortBy.field
285
+ })}`, sortBy.direction);
286
+ const res = await query.execute();
287
+ if (!res) return [];
288
+ if (join) return processJoinedResults(res, join, allSelectsStr);
289
+ return res;
290
+ },
291
+ async update({ model, where, update: values }) {
292
+ const { and, or } = convertWhereClause(model, where);
293
+ let query = db$1.updateTable(model).set(values);
294
+ if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
295
+ if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
296
+ return await withReturning(values, query, model, where);
297
+ },
298
+ async updateMany({ model, where, update: values }) {
299
+ const { and, or } = convertWhereClause(model, where);
300
+ let query = db$1.updateTable(model).set(values);
301
+ if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
302
+ if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
303
+ const res = (await query.executeTakeFirst()).numUpdatedRows;
304
+ return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);
305
+ },
306
+ async count({ model, where }) {
307
+ const { and, or } = convertWhereClause(model, where);
308
+ let query = db$1.selectFrom(model).select(db$1.fn.count("id").as("count"));
309
+ if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
310
+ if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
311
+ const res = await query.execute();
312
+ if (typeof res[0].count === "number") return res[0].count;
313
+ if (typeof res[0].count === "bigint") return Number(res[0].count);
314
+ return parseInt(res[0].count);
315
+ },
316
+ async delete({ model, where }) {
317
+ const { and, or } = convertWhereClause(model, where);
318
+ let query = db$1.deleteFrom(model);
319
+ if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
320
+ if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
321
+ await query.execute();
322
+ },
323
+ async deleteMany({ model, where }) {
324
+ const { and, or } = convertWhereClause(model, where);
325
+ let query = db$1.deleteFrom(model);
326
+ if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
327
+ if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
328
+ const res = (await query.executeTakeFirst()).numDeletedRows;
329
+ return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);
330
+ },
331
+ options: config
332
+ };
333
+ };
334
+ };
335
+ let adapterOptions = null;
336
+ adapterOptions = {
337
+ config: {
338
+ adapterId: "kysely",
339
+ adapterName: "Kysely Adapter",
340
+ usePlural: config?.usePlural,
341
+ debugLogs: config?.debugLogs,
342
+ supportsBooleans: config?.type === "sqlite" || config?.type === "mssql" || config?.type === "mysql" || !config?.type ? false : true,
343
+ supportsDates: config?.type === "sqlite" || config?.type === "mssql" || !config?.type ? false : true,
344
+ supportsJSON: config?.type === "postgres" ? true : false,
345
+ supportsArrays: false,
346
+ supportsUUIDs: config?.type === "postgres" ? true : false,
347
+ transaction: config?.transaction ? (cb) => db.transaction().execute((trx) => {
348
+ return cb(createAdapterFactory({
349
+ config: adapterOptions.config,
350
+ adapter: createCustomAdapter(trx)
351
+ })(lazyOptions));
352
+ }) : false
353
+ },
354
+ adapter: createCustomAdapter(db)
355
+ };
356
+ const adapter = createAdapterFactory(adapterOptions);
357
+ return (options) => {
358
+ lazyOptions = options;
359
+ return adapter(options);
360
+ };
361
+ };
362
+
363
+ //#endregion
364
+ export { createKyselyAdapter, getKyselyDatabaseType, kyselyAdapter };
@@ -0,0 +1,28 @@
1
+ import { DatabaseConnection, DatabaseIntrospector, Dialect, DialectAdapter, Driver, Kysely, QueryCompiler } from "kysely";
2
+ import { DatabaseSync } from "node:sqlite";
3
+
4
+ //#region src/node-sqlite-dialect.d.ts
5
+
6
+ /**
7
+ * Config for the SQLite dialect.
8
+ */
9
+ interface NodeSqliteDialectConfig {
10
+ /**
11
+ * A sqlite DatabaseSync instance or a function that returns one.
12
+ */
13
+ database: DatabaseSync;
14
+ /**
15
+ * Called once when the first query is executed.
16
+ */
17
+ onCreateConnection?: ((connection: DatabaseConnection) => Promise<void>) | undefined;
18
+ }
19
+ declare class NodeSqliteDialect implements Dialect {
20
+ #private;
21
+ constructor(config: NodeSqliteDialectConfig);
22
+ createDriver(): Driver;
23
+ createQueryCompiler(): QueryCompiler;
24
+ createAdapter(): DialectAdapter;
25
+ createIntrospector(db: Kysely<any>): DatabaseIntrospector;
26
+ }
27
+ //#endregion
28
+ export { NodeSqliteDialect, NodeSqliteDialectConfig };