Skip to content

Commit cc637c9

Browse files
committed
refactor: handle specific onConflict for mysql
1 parent e1f63bb commit cc637c9

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

packages/bentocache/src/drivers/kysely.ts

+20-7
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,26 @@
1-
import { SqliteAdapter, type Kysely } from 'kysely'
1+
import { SqliteAdapter, type Kysely, MysqlAdapter } from 'kysely'
22

33
import type { DatabaseAdapter, KyselyConfig } from '../types/main.js'
44

55
/**
66
* Kysely adapter for the DatabaseDriver
77
*/
88
export class KyselyAdapter implements DatabaseAdapter {
9-
#isSqlite: boolean
9+
#dialect: 'mysql' | 'pg' | 'sqlite'
1010
#tableName!: string
1111
#connection: Kysely<any>
1212

1313
constructor(config: KyselyConfig) {
1414
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+
}
1624
}
1725

1826
setTableName(tableName: string): void {
@@ -75,14 +83,19 @@ export class KyselyAdapter implements DatabaseAdapter {
7583
}
7684

7785
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
7987

8088
await this.#connection
8189
.insertInto(this.#tableName)
8290
.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+
})
8699
.execute()
87100
}
88101
}

packages/bentocache/tests/drivers/kysely/postgres.spec.ts

-4
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,6 @@ import { Kysely, PostgresDialect } from 'kysely'
55
import { createKyselyStore } from './helpers.js'
66
import { registerCacheDriverTestSuite } from '../../../src/test_suite.js'
77

8-
const db = new Kysely<any>({
9-
dialect: new PostgresDialect({ pool: new pg.Pool({ user: 'postgres', password: 'postgres' }) }),
10-
})
11-
128
test.group('Kysely | Postgres driver', (group) => {
139
registerCacheDriverTestSuite({
1410
test,

0 commit comments

Comments
 (0)