@better-auth/kysely-adapter 1.7.4 → 1.7.6

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.
@@ -1,5 +1,5 @@
1
- import { n as DEFAULT_MIGRATION_TABLE, t as DEFAULT_MIGRATION_LOCK_TABLE } from "./kysely-migration-tables-DFfmKhq-.mjs";
2
- import { CompiledQuery, DefaultQueryCompiler, sql } from "kysely";
1
+ import { t as createSqliteIntrospector } from "./sqlite-introspector-DSCAP82F.mjs";
2
+ import { CompiledQuery, DefaultQueryCompiler } from "kysely";
3
3
  //#region src/bun-sqlite-dialect.ts
4
4
  var BunSqliteAdapter = class {
5
5
  get supportsCreateIfNotExists() {
@@ -87,44 +87,6 @@ var ConnectionMutex = class {
87
87
  resolve?.();
88
88
  }
89
89
  };
90
- var BunSqliteIntrospector = class {
91
- #db;
92
- constructor(db) {
93
- this.#db = db;
94
- }
95
- async getSchemas() {
96
- return [];
97
- }
98
- async getTables(options = { withInternalKyselyTables: false }) {
99
- let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo();
100
- if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
101
- const tables = await query.execute();
102
- return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));
103
- }
104
- async getMetadata(options) {
105
- return { tables: await this.getTables(options) };
106
- }
107
- async #getTableMetadata(table) {
108
- const db = this.#db;
109
- 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, "");
110
- return {
111
- name: table,
112
- columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([
113
- "name",
114
- "type",
115
- "notnull",
116
- "dflt_value"
117
- ]).execute()).map((col) => ({
118
- name: col.name,
119
- dataType: col.type,
120
- isNullable: !col.notnull,
121
- isAutoIncrementing: col.name === autoIncrementCol,
122
- hasDefaultValue: col.dflt_value != null
123
- })),
124
- isView: false
125
- };
126
- }
127
- };
128
90
  var BunSqliteQueryCompiler = class extends DefaultQueryCompiler {
129
91
  getCurrentParameterPlaceholder() {
130
92
  return "?";
@@ -154,7 +116,7 @@ var BunSqliteDialect = class {
154
116
  return new BunSqliteAdapter();
155
117
  }
156
118
  createIntrospector(db) {
157
- return new BunSqliteIntrospector(db);
119
+ return createSqliteIntrospector(db);
158
120
  }
159
121
  };
160
122
  //#endregion
@@ -1,4 +1,4 @@
1
- import { n as DEFAULT_MIGRATION_TABLE, t as DEFAULT_MIGRATION_LOCK_TABLE } from "./kysely-migration-tables-DFfmKhq-.mjs";
1
+ import { a as DEFAULT_MIGRATION_LOCK_TABLE, i as toSqliteTableMetadata, o as DEFAULT_MIGRATION_TABLE, r as sqliteIntegerPrimaryKeyColumn } from "./sqlite-introspector-DSCAP82F.mjs";
2
2
  import { SqliteAdapter, SqliteQueryCompiler } from "kysely";
3
3
  //#region src/d1-sqlite-dialect.ts
4
4
  function quoteSqliteStringLiteral(value) {
@@ -86,35 +86,24 @@ var D1SqliteIntrospector = class {
86
86
  return [];
87
87
  }
88
88
  async getTables(options = { withInternalKyselyTables: false }) {
89
- let query = this.#db.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").where("name", "not like", "_cf_%").select([
90
- "name",
91
- "type",
92
- "sql"
93
- ]).$castTo();
89
+ let query = this.#db.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").where("name", "not like", "_cf_%").select(["name", "type"]).$castTo();
94
90
  if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
95
91
  const tables = await query.execute();
96
92
  if (tables.length === 0) return [];
97
93
  const statements = tables.map((table) => this.#d1.prepare("SELECT * FROM pragma_table_info(?)").bind(table.name));
98
94
  const batchResults = await this.#d1.batch(statements);
95
+ const rowidCandidates = tables.flatMap((table, index) => {
96
+ const column = sqliteIntegerPrimaryKeyColumn(batchResults[index]?.results ?? []);
97
+ return column ? [{
98
+ index,
99
+ tableName: table.name,
100
+ column
101
+ }] : [];
102
+ });
103
+ const indexResults = rowidCandidates.length ? await this.#d1.batch(rowidCandidates.map(({ tableName }) => this.#d1.prepare(`PRAGMA index_list(${quoteSqliteStringLiteral(tableName)})`))) : [];
104
+ const generatedColumns = new Map(rowidCandidates.filter((_, index) => !indexResults[index]?.results?.some((row) => row.origin === "pk")).map(({ index, column }) => [index, column]));
99
105
  return tables.map((table, index) => {
100
- const columnInfo = batchResults[index]?.results ?? [];
101
- let autoIncrementCol = table.sql?.split(/[(),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.filter(Boolean)?.[0]?.replace(/["`]/g, "");
102
- if (!autoIncrementCol) {
103
- const pkCols = columnInfo.filter((r) => r.pk > 0);
104
- const singlePk = pkCols.length === 1 ? pkCols[0] : void 0;
105
- if (singlePk && singlePk.type.toLowerCase() === "integer") autoIncrementCol = singlePk.name;
106
- }
107
- return {
108
- name: table.name,
109
- isView: table.type === "view",
110
- columns: columnInfo.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
- };
106
+ return toSqliteTableMetadata(table, batchResults[index]?.results ?? [], generatedColumns.get(index));
118
107
  });
119
108
  }
120
109
  async getMetadata(options) {
package/dist/index.d.mts CHANGED
@@ -38,9 +38,16 @@ type DatabaseIndexIntrospector = (tableNames: readonly string[]) => Promise<read
38
38
  //#region src/dialect.d.ts
39
39
  declare function getKyselyDatabaseType(db: BetterAuthOptions["database"]): KyselyDatabaseType | null;
40
40
  declare const createKyselyAdapter: (config: BetterAuthOptions) => Promise<{
41
+ kysely: Kysely<any>;
42
+ databaseType: "postgres" | "mysql" | "sqlite" | "mssql";
43
+ introspectIndexes: undefined;
44
+ schemaName: string | undefined;
45
+ transaction: boolean | undefined;
46
+ } | {
41
47
  kysely: Kysely<any> | null;
42
48
  databaseType: KyselyDatabaseType | null;
43
49
  introspectIndexes: DatabaseIndexIntrospector | undefined;
50
+ schemaName: undefined;
44
51
  transaction: boolean | undefined;
45
52
  }>;
46
53
  //#endregion
package/dist/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { n as introspectSqliteTables } from "./sqlite-introspector-DSCAP82F.mjs";
2
+ import { BetterAuthError } from "@better-auth/core/error";
1
3
  import { ColumnNode, Kysely, MssqlDialect, MysqlDialect, PostgresDialect, ReferenceNode, SelectQueryNode, SqliteDialect, TableNode, sql } from "kysely";
2
4
  import { createAdapterFactory } from "@better-auth/core/db/adapter";
3
5
  import { checksSchema, createSchemaCheck, diffSchema, getExpectedSchema, registerSchemaCheck } from "@better-auth/core/db/internal";
@@ -21,26 +23,43 @@ function getKyselyDatabaseType(db) {
21
23
  if ("batch" in db && "exec" in db && "prepare" in db) return "sqlite";
22
24
  return null;
23
25
  }
26
+ function checkSchemaName(schemaName, databaseType) {
27
+ if (schemaName === void 0) return;
28
+ if (typeof schemaName !== "string" || schemaName.length === 0) throw new BetterAuthError("`database.schemaName` must be a non-empty schema name.");
29
+ if (databaseType !== "postgres") throw new BetterAuthError(`\`database.schemaName\` is only supported on PostgreSQL, but the configured database type is "${databaseType ?? "unknown"}".`);
30
+ }
24
31
  const createKyselyAdapter = async (config) => {
25
32
  const db = config.database;
26
33
  if (!db) return {
27
34
  kysely: null,
28
35
  databaseType: null,
29
36
  introspectIndexes: void 0,
37
+ schemaName: void 0,
30
38
  transaction: void 0
31
39
  };
32
- if ("db" in db) return {
33
- kysely: db.db,
34
- databaseType: db.type,
35
- introspectIndexes: void 0,
36
- transaction: db.transaction
37
- };
38
- if ("dialect" in db) return {
39
- kysely: new Kysely({ dialect: db.dialect }),
40
- databaseType: db.type,
41
- introspectIndexes: void 0,
42
- transaction: db.transaction
43
- };
40
+ if ("db" in db) {
41
+ const schemaName = db.schemaName;
42
+ checkSchemaName(schemaName, db.type);
43
+ return {
44
+ kysely: schemaName ? db.db.withSchema(schemaName) : db.db,
45
+ databaseType: db.type,
46
+ introspectIndexes: void 0,
47
+ schemaName,
48
+ transaction: db.transaction
49
+ };
50
+ }
51
+ if ("dialect" in db) {
52
+ const schemaName = db.schemaName;
53
+ checkSchemaName(schemaName, db.type);
54
+ const kysely = new Kysely({ dialect: db.dialect });
55
+ return {
56
+ kysely: schemaName ? kysely.withSchema(schemaName) : kysely,
57
+ databaseType: db.type,
58
+ introspectIndexes: void 0,
59
+ schemaName,
60
+ transaction: db.transaction
61
+ };
62
+ }
44
63
  let dialect = void 0;
45
64
  let introspectIndexes = void 0;
46
65
  let transaction = void 0;
@@ -59,7 +78,7 @@ const createKyselyAdapter = async (config) => {
59
78
  transaction = true;
60
79
  }
61
80
  if ("fileControl" in db) {
62
- const { BunSqliteDialect } = await import("./bun-sqlite-dialect-C7ftEUSI.mjs");
81
+ const { BunSqliteDialect } = await import("./bun-sqlite-dialect-DoOVo4ja.mjs");
63
82
  dialect = new BunSqliteDialect({ database: db });
64
83
  transaction = true;
65
84
  }
@@ -82,7 +101,7 @@ const createKyselyAdapter = async (config) => {
82
101
  }
83
102
  }
84
103
  if ("batch" in db && "exec" in db && "prepare" in db) {
85
- const { createD1IndexIntrospector, D1SqliteDialect } = await import("./d1-sqlite-dialect-D4qp4-wW.mjs");
104
+ const { createD1IndexIntrospector, D1SqliteDialect } = await import("./d1-sqlite-dialect-Cru74LbR.mjs");
86
105
  dialect = new D1SqliteDialect({ database: db });
87
106
  introspectIndexes = createD1IndexIntrospector(db);
88
107
  transaction = false;
@@ -91,6 +110,7 @@ const createKyselyAdapter = async (config) => {
91
110
  kysely: dialect ? new Kysely({ dialect }) : null,
92
111
  databaseType,
93
112
  introspectIndexes,
113
+ schemaName: void 0,
94
114
  transaction
95
115
  };
96
116
  };
@@ -230,6 +250,7 @@ async function schemaSearchPath(db, dbType) {
230
250
  */
231
251
  async function findSchemaProblems(db, dbType, expected) {
232
252
  const physical = toPhysicalSchema(db, expected);
253
+ if (dbType === "sqlite") return diffSchema(physical, toIntrospectedTables(await introspectSqliteTables(db, Object.entries(physical).flatMap(([name, table]) => table.disableMigrations ? [] : [name]))));
233
254
  return db.connection().execute(async (connection) => {
234
255
  const searchPath = await schemaSearchPath(connection, dbType);
235
256
  const tables = toIntrospectedTables(await connection.introspection.getTables());
@@ -254,8 +275,8 @@ const kyselyAdapter = (db, config) => {
254
275
  const selectAllJoins = (join) => {
255
276
  const allSelects = [];
256
277
  const allSelectsStr = [];
257
- if (join) for (const [joinModel, _] of Object.entries(join)) {
258
- const fields = schema[getDefaultModelName(joinModel)]?.fields;
278
+ if (join) for (const [joinModel, joinConfig] of Object.entries(join)) {
279
+ const fields = schema[joinConfig.modelKey ?? getDefaultModelName(joinModel)]?.fields;
259
280
  const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel];
260
281
  if (!fields) continue;
261
282
  fields.id = { type: "string" };
@@ -273,7 +294,7 @@ const kyselyAdapter = (db, config) => {
273
294
  allSelects
274
295
  };
275
296
  };
276
- const withReturning = async (values, builder, model, where) => {
297
+ const withReturning = async (values, builder, model, modelKey, where) => {
277
298
  if (config?.type === "mysql") {
278
299
  if (where.length > 0) {
279
300
  const updateResult = await builder.executeTakeFirst();
@@ -292,28 +313,28 @@ const kyselyAdapter = (db, config) => {
292
313
  reselectValue = values[reselectField] !== void 0 ? values[reselectField] : where[0].value;
293
314
  } else return null;
294
315
  return await db.selectFrom(model).selectAll().where(getFieldName({
295
- model,
316
+ model: modelKey,
296
317
  field: reselectField
297
318
  }), reselectValue === null ? "is" : "=", reselectValue).limit(1).executeTakeFirst();
298
319
  }
299
320
  await builder.execute();
300
321
  const fetchInserted = async (trx) => {
301
322
  if (values.id) return await trx.selectFrom(model).selectAll().where(getFieldName({
302
- model,
323
+ model: modelKey,
303
324
  field: "id"
304
325
  }), "=", values.id).limit(1).executeTakeFirst();
305
326
  if (options.advanced?.database?.generateId === "serial") {
306
327
  const lastId = (await sql`SELECT LAST_INSERT_ID() as id`.execute(trx)).rows[0]?.id;
307
328
  if (lastId) return await trx.selectFrom(model).selectAll().where(getFieldName({
308
- model,
329
+ model: modelKey,
309
330
  field: "id"
310
331
  }), "=", lastId).limit(1).executeTakeFirst();
311
332
  }
312
- const modelSchema = schema[getDefaultModelName(model)]?.fields;
333
+ const modelSchema = schema[modelKey]?.fields;
313
334
  if (modelSchema) for (const [fieldKey, fieldAttr] of Object.entries(modelSchema)) {
314
335
  if (!fieldAttr.unique) continue;
315
336
  const dbFieldName = getFieldName({
316
- model,
337
+ model: modelKey,
317
338
  field: fieldKey
318
339
  });
319
340
  const val = values[dbFieldName];
@@ -340,7 +361,7 @@ const kyselyAdapter = (db, config) => {
340
361
  if (config?.type === "mssql") return await builder.outputAll("inserted").executeTakeFirst();
341
362
  return await builder.returningAll().executeTakeFirst();
342
363
  };
343
- function convertWhereClause(model, w) {
364
+ function convertWhereClause(model, modelKey, w) {
344
365
  if (!w) return {
345
366
  and: null,
346
367
  or: null
@@ -353,7 +374,7 @@ const kyselyAdapter = (db, config) => {
353
374
  const { field: _field, value: _value, operator = "eq", connector = "AND", mode = "sensitive" } = condition;
354
375
  const value = _value;
355
376
  const field = getFieldName({
356
- model,
377
+ model: modelKey,
357
378
  field: _field
358
379
  });
359
380
  const isInsensitive = mode === "insensitive" && (typeof value === "string" || Array.isArray(value) && value.every((v) => typeof v === "string"));
@@ -421,13 +442,13 @@ const kyselyAdapter = (db, config) => {
421
442
  for (const currentRow of rows) {
422
443
  const mainModelFields = {};
423
444
  const joinedModelFields = {};
424
- for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {};
445
+ for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[joinModel] = {};
425
446
  for (const [key, value] of Object.entries(currentRow)) {
426
447
  const keyStr = String(key);
427
448
  let assigned = false;
428
449
  for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}` || keyStr === `_Joined${capitalizeFirstLetter(joinModelRef)}${capitalizeFirstLetter(fieldName)}`) {
429
- joinedModelFields[getModelName(joinModel)][getFieldName({
430
- model: joinModel,
450
+ joinedModelFields[joinModel][getFieldName({
451
+ model: joinConfig[joinModel]?.modelKey ?? joinModel,
431
452
  field: fieldName
432
453
  })] = value;
433
454
  assigned = true;
@@ -439,22 +460,22 @@ const kyselyAdapter = (db, config) => {
439
460
  if (!mainId) continue;
440
461
  if (!groupedByMainId.has(mainId)) {
441
462
  const entry = { ...mainModelFields };
442
- for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : [];
463
+ for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry[joinModel] = joinAttr.relation === "one-to-one" ? null : [];
443
464
  groupedByMainId.set(mainId, entry);
444
465
  }
445
466
  const entry = groupedByMainId.get(mainId);
446
467
  for (const [joinModel, joinAttr] of Object.entries(joinConfig)) {
447
468
  const isUnique = joinAttr.relation === "one-to-one";
448
469
  const limit = joinAttr.limit ?? 100;
449
- const joinedObj = joinedModelFields[getModelName(joinModel)];
470
+ const joinedObj = joinedModelFields[joinModel];
450
471
  const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0);
451
- if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null;
472
+ if (isUnique) entry[joinModel] = hasData ? joinedObj : null;
452
473
  else {
453
- const joinModelName = getModelName(joinModel);
474
+ const joinModelName = joinModel;
454
475
  if (Array.isArray(entry[joinModelName]) && hasData) {
455
476
  if (entry[joinModelName].length >= limit) continue;
456
477
  const idFieldName = getFieldName({
457
- model: joinModel,
478
+ model: joinAttr.modelKey ?? joinModel,
458
479
  field: "id"
459
480
  });
460
481
  const joinedId = joinedObj[idFieldName];
@@ -467,7 +488,7 @@ const kyselyAdapter = (db, config) => {
467
488
  }
468
489
  const result = Array.from(groupedByMainId.values());
469
490
  for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") {
470
- const joinModelName = getModelName(joinModel);
491
+ const joinModelName = joinModel;
471
492
  if (Array.isArray(entry[joinModelName])) {
472
493
  const limit = joinAttr.limit ?? 100;
473
494
  if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit);
@@ -476,17 +497,17 @@ const kyselyAdapter = (db, config) => {
476
497
  return result;
477
498
  }
478
499
  return {
479
- async create({ data, model }) {
480
- return await withReturning(data, db.insertInto(model).values(data), model, []);
500
+ async create({ data, model, modelKey = model }) {
501
+ return await withReturning(data, db.insertInto(model).values(data), model, modelKey, []);
481
502
  },
482
- async findOne({ model, where, select, join }) {
483
- const { and, or } = convertWhereClause(model, where);
503
+ async findOne({ model, modelKey = model, where, select, join }) {
504
+ const { and, or } = convertWhereClause(model, modelKey, where);
484
505
  let query = db.selectFrom((eb) => {
485
506
  let b = eb.selectFrom(model);
486
507
  if (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));
487
508
  if (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));
488
509
  if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({
489
- model,
510
+ model: modelKey,
490
511
  field
491
512
  })));
492
513
  else b = b.selectAll();
@@ -504,14 +525,14 @@ const kyselyAdapter = (db, config) => {
504
525
  if (join) return processJoinedResults(res, join, allSelectsStr)[0];
505
526
  return row;
506
527
  },
507
- async findMany({ model, where, limit, select, offset, sortBy, join }) {
508
- const { and, or } = convertWhereClause(model, where);
528
+ async findMany({ model, modelKey = model, where, limit, select, offset, sortBy, join }) {
529
+ const { and, or } = convertWhereClause(model, modelKey, where);
509
530
  let query = db.selectFrom((eb) => {
510
531
  let b = eb.selectFrom(model);
511
532
  if (config?.type === "mssql") {
512
533
  if (offset !== void 0) {
513
534
  if (!sortBy) b = b.orderBy(getFieldName({
514
- model,
535
+ model: modelKey,
515
536
  field: "id"
516
537
  }));
517
538
  b = b.offset(offset).fetch(limit || 100);
@@ -521,13 +542,13 @@ const kyselyAdapter = (db, config) => {
521
542
  if (offset !== void 0) b = b.offset(offset);
522
543
  }
523
544
  if (sortBy?.field) b = b.orderBy(`${getFieldName({
524
- model,
545
+ model: modelKey,
525
546
  field: sortBy.field
526
547
  })}`, sortBy.direction);
527
548
  if (and) b = b.where((eb) => eb.and(and.map((expr) => expr(eb))));
528
549
  if (or) b = b.where((eb) => eb.or(or.map((expr) => expr(eb))));
529
550
  if (select?.length && select.length > 0) b = b.select(select.map((field) => getFieldName({
530
- model,
551
+ model: modelKey,
531
552
  field
532
553
  })));
533
554
  else b = b.selectAll();
@@ -540,7 +561,7 @@ const kyselyAdapter = (db, config) => {
540
561
  const { allSelectsStr, allSelects } = selectAllJoins(join);
541
562
  query = query.select(allSelects);
542
563
  if (sortBy?.field) query = query.orderBy(`${getFieldName({
543
- model,
564
+ model: modelKey,
544
565
  field: sortBy.field
545
566
  })}`, sortBy.direction);
546
567
  const res = await query.execute();
@@ -548,24 +569,24 @@ const kyselyAdapter = (db, config) => {
548
569
  if (join) return processJoinedResults(res, join, allSelectsStr);
549
570
  return res;
550
571
  },
551
- async update({ model, where, update: values }) {
572
+ async update({ model, modelKey = model, where, update: values }) {
552
573
  if (where.length === 0) return null;
553
- const { and, or } = convertWhereClause(model, where);
574
+ const { and, or } = convertWhereClause(model, modelKey, where);
554
575
  let query = db.updateTable(model).set(values);
555
576
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
556
577
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
557
- return await withReturning(values, query, model, where);
578
+ return await withReturning(values, query, model, modelKey, where);
558
579
  },
559
- async updateMany({ model, where, update: values }) {
560
- const { and, or } = convertWhereClause(model, where);
580
+ async updateMany({ model, modelKey = model, where, update: values }) {
581
+ const { and, or } = convertWhereClause(model, modelKey, where);
561
582
  let query = db.updateTable(model).set(values);
562
583
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
563
584
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
564
585
  const res = (await query.executeTakeFirst()).numUpdatedRows;
565
586
  return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);
566
587
  },
567
- async count({ model, where }) {
568
- const { and, or } = convertWhereClause(model, where);
588
+ async count({ model, modelKey = model, where }) {
589
+ const { and, or } = convertWhereClause(model, modelKey, where);
569
590
  let query = db.selectFrom(model).select(db.fn.count("id").as("count"));
570
591
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
571
592
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
@@ -574,30 +595,30 @@ const kyselyAdapter = (db, config) => {
574
595
  if (typeof res[0].count === "bigint") return Number(res[0].count);
575
596
  return parseInt(res[0].count);
576
597
  },
577
- async delete({ model, where }) {
578
- const { and, or } = convertWhereClause(model, where);
598
+ async delete({ model, modelKey = model, where }) {
599
+ const { and, or } = convertWhereClause(model, modelKey, where);
579
600
  let query = db.deleteFrom(model);
580
601
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
581
602
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
582
603
  await query.execute();
583
604
  },
584
- async deleteMany({ model, where }) {
585
- const { and, or } = convertWhereClause(model, where);
605
+ async deleteMany({ model, modelKey = model, where }) {
606
+ const { and, or } = convertWhereClause(model, modelKey, where);
586
607
  let query = db.deleteFrom(model);
587
608
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
588
609
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
589
610
  const res = (await query.executeTakeFirst()).numDeletedRows;
590
611
  return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res);
591
612
  },
592
- async consumeOne({ model, where }) {
593
- const { and, or } = convertWhereClause(model, where);
613
+ async consumeOne({ model, modelKey = model, where }) {
614
+ const { and, or } = convertWhereClause(model, modelKey, where);
594
615
  const applyWhere = (query) => {
595
616
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
596
617
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
597
618
  return query;
598
619
  };
599
620
  const idField = getFieldName({
600
- model,
621
+ model: modelKey,
601
622
  field: "id"
602
623
  });
603
624
  const deleteSelectedRow = async (db, row) => {
@@ -627,8 +648,8 @@ const kyselyAdapter = (db, config) => {
627
648
  const targetIds = config?.type === "mssql" ? selectIds.top(1) : selectIds.limit(1);
628
649
  return deleteWithReturning(db.deleteFrom(model).where(`${model}.${idField}`, "in", targetIds));
629
650
  },
630
- async incrementOne({ model, where, increment, set }) {
631
- const { and, or } = convertWhereClause(model, where);
651
+ async incrementOne({ model, modelKey = model, where, increment, set }) {
652
+ const { and, or } = convertWhereClause(model, modelKey, where);
632
653
  const applyWhere = (query) => {
633
654
  if (and) query = query.where((eb) => eb.and(and.map((expr) => expr(eb))));
634
655
  if (or) query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
@@ -637,7 +658,7 @@ const kyselyAdapter = (db, config) => {
637
658
  const assignments = { ...set ?? {} };
638
659
  for (const [field, delta] of Object.entries(increment)) assignments[field] = sql`${sql.ref(field)} + ${delta}`;
639
660
  const idField = getFieldName({
640
- model,
661
+ model: modelKey,
641
662
  field: "id"
642
663
  });
643
664
  if (config?.type === "mysql") {
@@ -690,7 +711,7 @@ const kyselyAdapter = (db, config) => {
690
711
  return (options) => {
691
712
  lazyOptions = options;
692
713
  const instance = adapter(options);
693
- if (checksSchema(options)) registerSchemaCheck(instance, createSchemaCheck(() => findSchemaProblems(db, config?.type, getExpectedSchema(options, { usePlural: config?.usePlural })), "database", options.database));
714
+ registerSchemaCheck(instance, createSchemaCheck(() => findSchemaProblems(db, config?.type, getExpectedSchema(options, { usePlural: config?.usePlural })), "database", options.database), { runtimeEnabled: checksSchema(options) });
694
715
  return instance;
695
716
  };
696
717
  };
@@ -1,5 +1,5 @@
1
- import { n as DEFAULT_MIGRATION_TABLE, t as DEFAULT_MIGRATION_LOCK_TABLE } from "./kysely-migration-tables-DFfmKhq-.mjs";
2
- import { CompiledQuery, DefaultQueryCompiler, sql } from "kysely";
1
+ import { t as createSqliteIntrospector } from "./sqlite-introspector-DSCAP82F.mjs";
2
+ import { CompiledQuery, DefaultQueryCompiler } from "kysely";
3
3
  //#region src/node-sqlite-dialect.ts
4
4
  var NodeSqliteAdapter = class {
5
5
  get supportsCreateIfNotExists() {
@@ -87,44 +87,6 @@ var ConnectionMutex = class {
87
87
  resolve?.();
88
88
  }
89
89
  };
90
- var NodeSqliteIntrospector = class {
91
- #db;
92
- constructor(db) {
93
- this.#db = db;
94
- }
95
- async getSchemas() {
96
- return [];
97
- }
98
- async getTables(options = { withInternalKyselyTables: false }) {
99
- let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo();
100
- if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
101
- const tables = await query.execute();
102
- return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));
103
- }
104
- async getMetadata(options) {
105
- return { tables: await this.getTables(options) };
106
- }
107
- async #getTableMetadata(table) {
108
- const db = this.#db;
109
- 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, "");
110
- return {
111
- name: table,
112
- columns: (await db.selectFrom(sql`pragma_table_info(${table})`.as("table_info")).select([
113
- "name",
114
- "type",
115
- "notnull",
116
- "dflt_value"
117
- ]).execute()).map((col) => ({
118
- name: col.name,
119
- dataType: col.type,
120
- isNullable: !col.notnull,
121
- isAutoIncrementing: col.name === autoIncrementCol,
122
- hasDefaultValue: col.dflt_value != null
123
- })),
124
- isView: false
125
- };
126
- }
127
- };
128
90
  var NodeSqliteQueryCompiler = class extends DefaultQueryCompiler {
129
91
  getCurrentParameterPlaceholder() {
130
92
  return "?";
@@ -154,7 +116,7 @@ var NodeSqliteDialect = class {
154
116
  return new NodeSqliteAdapter();
155
117
  }
156
118
  createIntrospector(db) {
157
- return new NodeSqliteIntrospector(db);
119
+ return createSqliteIntrospector(db);
158
120
  }
159
121
  };
160
122
  //#endregion
@@ -0,0 +1,90 @@
1
+ import { sql } from "kysely";
2
+ //#region src/kysely-migration-tables.ts
3
+ /**
4
+ * Kysely's internal migration table names, mirrored as local constants.
5
+ *
6
+ * Kysely 0.29 moved these from its main entry to the `kysely/migration`
7
+ * subpath (which 0.28 lacks), and the main entry now exports only type stubs
8
+ * with no runtime value, which breaks strict ESM bundlers.
9
+ *
10
+ * The values are stable parts of Kysely's public migration contract. Mirroring
11
+ * them allows the SQLite dialects to support both Kysely 0.28 and 0.29.
12
+ *
13
+ * TODO: Import these from `kysely/migration` after dropping Kysely 0.28.
14
+ */
15
+ const DEFAULT_MIGRATION_TABLE = "kysely_migration";
16
+ const DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock";
17
+ //#endregion
18
+ //#region src/sqlite-introspector.ts
19
+ function sqliteIntegerPrimaryKeyColumn(columns) {
20
+ const primaryKeys = columns.filter((column) => column.pk > 0);
21
+ const primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : void 0;
22
+ return primaryKey?.type.toLowerCase() === "integer" ? primaryKey.name : void 0;
23
+ }
24
+ async function sqliteGeneratedPrimaryKeyColumn(db, name, columns) {
25
+ const column = sqliteIntegerPrimaryKeyColumn(columns);
26
+ if (!column) return;
27
+ const { rows } = await sql`
28
+ PRAGMA index_list(${sql.id(name)})
29
+ `.execute(db.withoutPlugins());
30
+ return rows.some((index) => index.origin === "pk") ? void 0 : column;
31
+ }
32
+ function toSqliteTableMetadata(table, columns, autoIncrementColumn) {
33
+ return {
34
+ name: table.name,
35
+ isView: table.type === "view",
36
+ columns: columns.map((column) => ({
37
+ name: column.name,
38
+ dataType: column.type,
39
+ isNullable: column.notnull === 0,
40
+ isAutoIncrementing: column.name === autoIncrementColumn,
41
+ hasDefaultValue: column.dflt_value != null
42
+ }))
43
+ };
44
+ }
45
+ async function readTableMetadata(db, name) {
46
+ const { rows: columns } = await sql`
47
+ PRAGMA table_info(${sql.id(name)})
48
+ `.execute(db.withoutPlugins());
49
+ if (columns.length === 0) return;
50
+ const generatedColumn = await sqliteGeneratedPrimaryKeyColumn(db, name, columns);
51
+ return toSqliteTableMetadata({ name }, columns, generatedColumn);
52
+ }
53
+ async function introspectSqliteTables(db, tableNames) {
54
+ if (tableNames.length === 0) return [];
55
+ try {
56
+ return await db.introspection.getTables();
57
+ } catch {
58
+ return (await Promise.all(tableNames.map((name) => readTableMetadata(db, name)))).filter((table) => table !== void 0);
59
+ }
60
+ }
61
+ function createSqliteIntrospector(db) {
62
+ const systemDb = db;
63
+ async function getSchemas() {
64
+ return [];
65
+ }
66
+ async function getTables(options = { withInternalKyselyTables: false }) {
67
+ let query = systemDb.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name");
68
+ if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
69
+ const tables = await query.execute();
70
+ return Promise.all(tables.map(async ({ name }) => {
71
+ const columns = await db.selectFrom(sql`pragma_table_info(${name})`.as("table_info")).select([
72
+ "cid",
73
+ "name",
74
+ "type",
75
+ "notnull",
76
+ "dflt_value",
77
+ "pk"
78
+ ]).execute();
79
+ const generatedColumn = await sqliteGeneratedPrimaryKeyColumn(db, name, columns);
80
+ return toSqliteTableMetadata({ name }, columns, generatedColumn);
81
+ }));
82
+ }
83
+ return {
84
+ getSchemas,
85
+ getTables,
86
+ getMetadata: async (options) => ({ tables: await getTables(options) })
87
+ };
88
+ }
89
+ //#endregion
90
+ export { DEFAULT_MIGRATION_LOCK_TABLE as a, toSqliteTableMetadata as i, introspectSqliteTables as n, DEFAULT_MIGRATION_TABLE as o, sqliteIntegerPrimaryKeyColumn as r, createSqliteIntrospector as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-auth/kysely-adapter",
3
- "version": "1.7.4",
3
+ "version": "1.7.6",
4
4
  "description": "Kysely adapter for Better Auth",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -42,7 +42,7 @@
42
42
  "peerDependencies": {
43
43
  "@better-auth/utils": "0.4.2",
44
44
  "kysely": "^0.28.17 || ^0.29.0",
45
- "@better-auth/core": "^1.7.4"
45
+ "@better-auth/core": "^1.7.6"
46
46
  },
47
47
  "peerDependenciesMeta": {
48
48
  "kysely": {
@@ -57,7 +57,7 @@
57
57
  "pg": "^8.0.0",
58
58
  "tsdown": "0.21.10",
59
59
  "typescript": "^6.0.3",
60
- "@better-auth/core": "1.7.4"
60
+ "@better-auth/core": "1.7.6"
61
61
  },
62
62
  "scripts": {
63
63
  "build": "tsdown",
@@ -1,17 +0,0 @@
1
- //#region src/kysely-migration-tables.ts
2
- /**
3
- * Kysely's internal migration table names, mirrored as local constants.
4
- *
5
- * Kysely 0.29 moved these from its main entry to the `kysely/migration`
6
- * subpath (which 0.28 lacks), and the main entry now exports only type stubs
7
- * with no runtime value, which breaks strict ESM bundlers.
8
- *
9
- * The values are stable parts of Kysely's public migration contract. Mirroring
10
- * them allows the SQLite dialects to support both Kysely 0.28 and 0.29.
11
- *
12
- * TODO: Import these from `kysely/migration` after dropping Kysely 0.28.
13
- */
14
- const DEFAULT_MIGRATION_TABLE = "kysely_migration";
15
- const DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock";
16
- //#endregion
17
- export { DEFAULT_MIGRATION_TABLE as n, DEFAULT_MIGRATION_LOCK_TABLE as t };