|
1 |
| -import { SqliteAdapter, type Kysely } from 'kysely' |
| 1 | +import { SqliteAdapter, type Kysely, MysqlAdapter } from 'kysely' |
2 | 2 |
|
3 | 3 | import type { DatabaseAdapter, KyselyConfig } from '../types/main.js'
|
4 | 4 |
|
5 | 5 | /**
|
6 | 6 | * Kysely adapter for the DatabaseDriver
|
7 | 7 | */
|
8 | 8 | export class KyselyAdapter implements DatabaseAdapter {
|
9 |
| - #isSqlite: boolean |
| 9 | + #dialect: 'mysql' | 'pg' | 'sqlite' |
10 | 10 | #tableName!: string
|
11 | 11 | #connection: Kysely<any>
|
12 | 12 |
|
13 | 13 | constructor(config: KyselyConfig) {
|
14 | 14 | this.#connection = config.connection
|
15 |
| - this.#isSqlite = config.connection.getExecutor().adapter instanceof SqliteAdapter |
| 15 | + |
| 16 | + const adapter = this.#connection.getExecutor().adapter |
| 17 | + if (adapter instanceof SqliteAdapter) { |
| 18 | + this.#dialect = 'sqlite' |
| 19 | + } else if (adapter instanceof MysqlAdapter) { |
| 20 | + this.#dialect = 'mysql' |
| 21 | + } else { |
| 22 | + this.#dialect = 'pg' |
| 23 | + } |
16 | 24 | }
|
17 | 25 |
|
18 | 26 | setTableName(tableName: string): void {
|
@@ -75,14 +83,19 @@ export class KyselyAdapter implements DatabaseAdapter {
|
75 | 83 | }
|
76 | 84 |
|
77 | 85 | async set(row: { value: any; key: string; expiresAt: Date | null }): Promise<void> {
|
78 |
| - const expiresAt = this.#isSqlite ? row.expiresAt?.getTime() : row.expiresAt |
| 86 | + const expiresAt = this.#dialect === 'sqlite' ? row.expiresAt?.getTime() : row.expiresAt |
79 | 87 |
|
80 | 88 | await this.#connection
|
81 | 89 | .insertInto(this.#tableName)
|
82 | 90 | .values({ key: row.key, value: row.value, expires_at: expiresAt ?? null })
|
83 |
| - // .onConflict((conflict) => |
84 |
| - // conflict.columns(['key']).doUpdateSet({ value: row.value, expires_at: row.expiresAt }), |
85 |
| - // ) |
| 91 | + .$if(this.#dialect === 'mysql', (query) => |
| 92 | + query.onDuplicateKeyUpdate({ value: row.value, expires_at: expiresAt }), |
| 93 | + ) |
| 94 | + .$if(this.#dialect !== 'mysql', (query) => { |
| 95 | + return query.onConflict((conflict) => { |
| 96 | + return conflict.columns(['key']).doUpdateSet({ value: row.value, expires_at: expiresAt }) |
| 97 | + }) |
| 98 | + }) |
86 | 99 | .execute()
|
87 | 100 | }
|
88 | 101 | }
|
0 commit comments