Skip to content

Commit 71204e6

Browse files
perf(better-sqlite3): prepared statements
1 parent ee4c7ba commit 71204e6

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

src/drivers/better-sqlite3.ts

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,25 @@ export function betterSqlite3CacheAdapter<Value = unknown>(
1818
database: Database
1919
},
2020
): Cache<Value> {
21+
// Prepare statements
22+
const getStatement = options.database.prepare(
23+
`SELECT value, metadata FROM ${options.tableName} WHERE key = ?`,
24+
)
25+
const setStatement = options.database.prepare(
26+
`INSERT OR REPLACE INTO ${options.tableName} (key, value, metadata) VALUES (?, ?, ?)`,
27+
)
28+
const deleteStatement = options.database.prepare(
29+
`DELETE FROM ${options.tableName} WHERE key = ?`,
30+
)
31+
2132
return {
2233
name: options.name ?? "better-sqlite3",
2334
get: (key) => {
2435
const cacheKey = buildCacheKey(key, options.keyPrefix)
2536

26-
const row = options.database
27-
.prepare(
28-
`SELECT value, metadata FROM ${options.tableName} WHERE key = ?`,
29-
)
30-
.get(cacheKey) as { value: string; metadata: string } | undefined
37+
const row = getStatement.get(cacheKey) as
38+
| { value: string; metadata: string }
39+
| undefined
3140

3241
if (!row) {
3342
return null
@@ -49,27 +58,21 @@ export function betterSqlite3CacheAdapter<Value = unknown>(
4958

5059
const ttl = totalTtl(entry.metadata)
5160

52-
options.database
53-
.prepare(
54-
`INSERT OR REPLACE INTO ${options.tableName} (key, value, metadata) VALUES (?, ?, ?)`,
55-
)
56-
.run(
57-
cacheKey,
58-
JSON.stringify(entry.value),
59-
JSON.stringify({
60-
...entry.metadata,
61-
ttl: ttl === Number.POSITIVE_INFINITY ? null : ttl,
62-
}),
63-
)
61+
setStatement.run(
62+
cacheKey,
63+
JSON.stringify(entry.value),
64+
JSON.stringify({
65+
...entry.metadata,
66+
ttl: ttl === Number.POSITIVE_INFINITY ? null : ttl,
67+
}),
68+
)
6469

6570
return entry.value
6671
},
6772
delete: (key) => {
6873
const cacheKey = buildCacheKey(key, options.keyPrefix)
6974

70-
options.database
71-
.prepare(`DELETE FROM ${options.tableName} WHERE key = ?`)
72-
.run(cacheKey)
75+
deleteStatement.run(cacheKey)
7376
},
7477
}
7578
}

0 commit comments

Comments
 (0)