@cossackframework/database 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tan Nguyen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # @cossackframework/database
2
+
3
+ Database support for the [Cossack Framework](https://github.com/cossackframework/cossack) — a type-safe query builder built on [Kysely](https://kysely.dev), with first-class dialects for **Cloudflare D1** and **Turso** (libSQL), plus migrations and seeders.
4
+
5
+ - Re-exports Kysely — no need to install it separately (`import { Kysely, Generated, sql } from '@cossackframework/database'`).
6
+ - Custom D1 and libSQL/Turso dialects written against Kysely 0.29 (the community `kysely-d1` / `kysely-libsql` packages are stale).
7
+ - Per-request client via Hono middleware **and** a global `db()` helper (AsyncLocalStorage).
8
+ - Kysely migrator + seeder runners, driven by the `cossack` CLI.
9
+
10
+ > Database support is **included by default** in new Cossack apps — the project template ships default migrations, wires the `dbMiddleware`, and registers the database cache driver. The framework itself stays decoupled (no hard dependency), so apps that don't need a database — or want a different client (Drizzle, SurrealDB, …) — can remove the package and middleware cleanly.
11
+
12
+ ## Install
13
+
14
+ Database support ships with every new project created via `create-cossack-app`. To add it to an existing project that predates it:
15
+
16
+ ```bash
17
+ npx cossack add database
18
+ ```
19
+
20
+ This scaffolds `src/models/`, `src/migrations/`, `src/seeders/`, and `src/db/config.ts`, adds the dependency to `package.json`, and (for D1) injects a `[[d1_databases]]` binding into `wrangler.jsonc`.
21
+
22
+ ## Connecting
23
+
24
+ A Kysely client is created with `createDatabase()`, which selects the dialect. Pick one (the `cossack add database` command generates the right one for your chosen dialect):
25
+
26
+ **Cloudflare D1** — pass the binding:
27
+
28
+ ```ts
29
+ import { createDatabase } from '@cossackframework/database'
30
+
31
+ export function createClient(env: { DB: D1Database }) {
32
+ return createDatabase({ dialect: 'd1', binding: env.DB })
33
+ }
34
+ ```
35
+
36
+ **Turso / libSQL** — pass a client built from `@tursodatabase/serverless/compat` (recommended, fetch-based) or `@libsql/client/web`. Works on Workers + Node:
37
+
38
+ ```ts
39
+ import { createDatabase } from '@cossackframework/database'
40
+ import { createClient as createLibsqlClient } from '@tursodatabase/serverless/compat'
41
+
42
+ export function createClient(env: { TURSO_URL: string; TURSO_TOKEN?: string }) {
43
+ return createDatabase({
44
+ dialect: 'libsql',
45
+ client: createLibsqlClient({ url: env.TURSO_URL, authToken: env.TURSO_TOKEN }),
46
+ })
47
+ }
48
+ ```
49
+
50
+ The generated `src/db/config.ts` also exports a `getCliClient()` for the migration/seeder CLI commands (see [Migrations](../../docs/migrations.md)).
51
+
52
+ ### Wiring the middleware
53
+
54
+ `cossack add database` registers the middleware in `src/bootstrap/middlewares.ts` — the project's global request middleware registry, which `createApp()` auto-loads. No `src/index.ts` edits:
55
+
56
+ ```ts
57
+ // src/bootstrap/middlewares.ts
58
+ import type { MiddlewareHandler } from 'hono'
59
+ import { dbMiddleware } from '../middlewares/db'
60
+
61
+ const middlewares: MiddlewareHandler[] = [
62
+ dbMiddleware,
63
+ ]
64
+ export default middlewares
65
+ ```
66
+
67
+ The middleware is defined in `src/middlewares/db.ts`:
68
+
69
+ ```ts
70
+ // src/middlewares/db.ts
71
+ import { createDbMiddleware } from '@cossackframework/database'
72
+ import { createClient } from '../db/config'
73
+
74
+ export const dbMiddleware = createDbMiddleware({
75
+ client: (c) => createClient(c.env),
76
+ })
77
+ ```
78
+
79
+ This exposes the client on the request (`c.get('db')` / `getDb(c)`) and wraps the request in a scope so the global `db()` helper resolves to it.
80
+
81
+ ## Querying
82
+
83
+ From a component method:
84
+
85
+ ```ts
86
+ import { db } from '@cossackframework/database'
87
+
88
+ @Server()
89
+ async getUsers() {
90
+ return await db().selectFrom('users').selectAll().execute()
91
+ }
92
+ ```
93
+
94
+ From an API route:
95
+
96
+ ```ts
97
+ import { getDb } from '@cossackframework/database'
98
+
99
+ export default async (c: Context) => {
100
+ const users = await getDb(c).selectFrom('users').selectAll().execute()
101
+ return c.json(users)
102
+ }
103
+ ```
104
+
105
+ ## Typing your schema
106
+
107
+ The `Database` interface (table → row) and the `User` (auth) interface are both empty by default and augmented from `src/models/`:
108
+
109
+ ```ts
110
+ // src/models/User.ts
111
+ import type { Generated } from '@cossackframework/database'
112
+
113
+ export interface UserRow {
114
+ id: Generated<string>
115
+ email: string
116
+ name: string
117
+ passwordHash: string
118
+ }
119
+
120
+ declare module '@cossackframework/database' {
121
+ interface Database { users: UserRow }
122
+ }
123
+
124
+ // Safe subset exposed as this.user / c.get('user') (no passwordHash)
125
+ declare module '@cossackframework/core' {
126
+ interface User { id: string; email: string; name: string }
127
+ }
128
+ ```
129
+
130
+ ## Migrations & seeders (CLI)
131
+
132
+ ```bash
133
+ cossack generate migration create_users
134
+ cossack migration up # apply pending
135
+ cossack migration down # revert the latest
136
+ cossack migration status
137
+
138
+ cossack generate seeder users
139
+ cossack seeder run
140
+ ```
141
+
142
+ ## Transactions
143
+
144
+ - **Turso / libSQL** supports interactive transactions via Kysely's `db().transaction().execute(async (trx) => { ... })`.
145
+ - **D1** does **not** support `BEGIN`/`COMMIT` through its binding. For atomic multi-statement writes, use the raw D1 binding's `.batch([...])` with prepared statements (e.g. `c.env.DB.batch([...])`) — Kysely has no `.batch()`; for single-statement writes, just call the Kysely builder directly.
146
+
147
+ The migrator is unaffected — the SQLite adapter reports `supportsTransactionalDdl: false`, so each migration runs without a transaction wrapper.
148
+
149
+ ## Dialects
150
+
151
+ | Dialect | Config | Where it runs | Driver |
152
+ |---|---|---|---|
153
+ | **D1** | `{ dialect: 'd1', binding: env.DB }` | Cloudflare Workers | The D1 binding (no extra dep) |
154
+ | **Turso / libSQL** | `{ dialect: 'libsql', client }` | Workers + Node | `@tursodatabase/serverless/compat` (recommended) or `@libsql/client/web` |
155
+
156
+ Postgres and MySQL adapters are planned for a later release.
157
+
158
+ ## No build step
159
+
160
+ This package is **published and consumed as TypeScript source** — there is no `build` script and no `dist/` directory, just like `@cossackframework/auth`. The `package.json` entry points straight at `src/index.ts`:
161
+
162
+ ```json
163
+ {
164
+ "main": "src/index.ts",
165
+ "exports": { ".": { "types": "./src/index.ts", "import": "./src/index.ts" } },
166
+ "files": ["src"]
167
+ }
168
+ ```
169
+
170
+ Consumers compile it at their own build/run time:
171
+
172
+ - **User apps** — the framework's Vite build bundles it into the Worker (SSR) bundle; it never reaches the client bundle (server-only).
173
+ - **The `cossack` CLI** — the `migration` / `seeder` commands run under `tsx`, which loads the `.ts` source directly.
174
+
175
+ This keeps the source debuggable, avoids a stale `dist/` to rebuild before every change, and means the publish workflow needs no build step — it runs `pnpm publish --filter @cossackframework/database` straight from `src/`.
176
+
177
+ To work on this package locally: edit files under `src/`, then run `pnpm vitest --run` from the package directory (or `pnpm tsc --noEmit` to typecheck). The [root tsconfig](../tsconfig.json) maps `@cossackframework/database` to `./packages/database/src` so workspace consumers resolve your edits immediately.
178
+
179
+ ## License
180
+
181
+ MIT
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@cossackframework/database",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Database support for the Cossack Framework — Kysely-based query builder with D1 and Turso dialects, migrations, and seeders",
6
+ "license": "MIT",
7
+ "main": "src/index.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "import": "./src/index.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "src"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "dependencies": {
21
+ "kysely": "^0.29.3"
22
+ },
23
+ "peerDependencies": {
24
+ "@libsql/client": "^0.14.0",
25
+ "@tursodatabase/serverless": "^0.1.0",
26
+ "hono": "^4.12.31"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "@tursodatabase/serverless": {
30
+ "optional": true
31
+ },
32
+ "@libsql/client": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "devDependencies": {
37
+ "@libsql/client": "^0.14.0",
38
+ "@types/node": "^22.19.0",
39
+ "hono": "^4.12.31",
40
+ "miniflare": "^4.20260623.0",
41
+ "typescript": "^7.0.2",
42
+ "vitest": "^4.1.10"
43
+ },
44
+ "scripts": {
45
+ "test": "vitest"
46
+ }
47
+ }
@@ -0,0 +1,27 @@
1
+ // src/accessor.ts
2
+ import type { Context } from 'hono';
3
+ import type { DbClient } from './types';
4
+
5
+ /**
6
+ * Returns the per-request {@link DbClient} from the Hono context (`c.get('db')`),
7
+ * set by the database middleware.
8
+ *
9
+ * ```ts
10
+ * export default async (c: Context) => {
11
+ * const users = await getDb(c).selectFrom('users').selectAll().execute()
12
+ * return c.json(users)
13
+ * }
14
+ * ```
15
+ *
16
+ * Throws if the database middleware isn't registered.
17
+ */
18
+ export function getDb(c: Context): DbClient {
19
+ const client = (c as any).get('db') as DbClient | undefined;
20
+ if (!client) {
21
+ throw new Error(
22
+ '[Cossack] No database client on the request context. ' +
23
+ 'Register the database middleware (createDbMiddleware) on your app.',
24
+ );
25
+ }
26
+ return client;
27
+ }
package/src/als.ts ADDED
@@ -0,0 +1,29 @@
1
+ // src/als.ts
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { setDbStoreGetter } from './store';
4
+ import type { DbClient } from './types';
5
+
6
+ const dbAls = new AsyncLocalStorage<DbClient>();
7
+
8
+ let wired = false;
9
+
10
+ /**
11
+ * One-time wiring of the AsyncLocalStorage store-getter into the global
12
+ * {@link db} helper. Idempotent.
13
+ */
14
+ export function ensureDbAlsWired(): void {
15
+ if (wired) return;
16
+ setDbStoreGetter(() => dbAls.getStore());
17
+ wired = true;
18
+ }
19
+
20
+ /**
21
+ * Runs `fn` inside a database scope. Any call to {@link db} inside `fn`
22
+ * (or its async descendants) resolves to `client`.
23
+ *
24
+ * Used by the database middleware to wrap each request, and by standalone
25
+ * scripts (seeders, tests) that need the global `db()` helper.
26
+ */
27
+ export function runWithDb<T>(client: DbClient, fn: () => T | Promise<T>): T | Promise<T> {
28
+ return dbAls.run(client, fn as () => T);
29
+ }
@@ -0,0 +1,285 @@
1
+ // src/cache-store.ts
2
+ //
3
+ // Database-backed cache store. Mirrors `session-store.ts` (DB-backed key/value
4
+ // storage with TTL) but for general-purpose cache data instead of per-session
5
+ // bags.
6
+ //
7
+ // This package intentionally does NOT depend on @cossackframework/framework
8
+ // (see the note in session-store.ts). So instead of importing the `CacheStore`
9
+ // interface from the framework, we declare a structurally-compatible local
10
+ // interface (`CacheStoreLike`). TypeScript's structural typing means a
11
+ // `DatabaseCacheStore` is assignable to the framework's `CacheStore` at the
12
+ // call site —
13
+ //
14
+ // import { extendCacheDriver } from '@cossackframework/framework/cache';
15
+ // import { DatabaseCacheStore } from '@cossackframework/database';
16
+ // extendCacheDriver('database', () => new DatabaseCacheStore()); // ✓
17
+ //
18
+ // Register it once at startup. The store resolves the per-request `db()` client
19
+ // lazily on each operation, so a single instance serves every request. See
20
+ // docs/cache.md.
21
+ //
22
+ // Expected schema (shipped as a default migration — 0006_create_cache_table.ts):
23
+ // create table cache_items (
24
+ // key text primary key not null,
25
+ // value text not null, -- JSON
26
+ // expires_at integer, -- epoch ms; null = never
27
+ // updated_at integer not null
28
+ // );
29
+ // create index cache_items_expires_at_index on cache_items (expires_at);
30
+
31
+ import type { DbClient } from './types';
32
+ import { db } from './store';
33
+
34
+ /** `cache_items` table row shape (snake_case to match the migration). */
35
+ export interface CacheItemRow {
36
+ key: string;
37
+ value: string;
38
+ /** Epoch-millis expiry, or null for "never expires". */
39
+ expires_at: number | null;
40
+ /** Epoch-millis of the last write. */
41
+ updated_at: number;
42
+ }
43
+
44
+ // Augment the Database interface so `selectFrom('cache_items')` is typed.
45
+ declare module './types' {
46
+ interface Database {
47
+ cache_items: CacheItemRow;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A local `CacheStore`-compatible interface, declared locally so this package
53
+ * stays free of a framework dependency. Structurally identical to
54
+ * `@cossackframework/framework/cache`'s `CacheStore`, so a `DatabaseCacheStore`
55
+ * is assignable wherever a `CacheStore` is expected.
56
+ */
57
+ export interface CacheStoreLike {
58
+ get<T = unknown>(key: string): Promise<T | undefined>;
59
+ set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void>;
60
+ has(key: string): Promise<boolean>;
61
+ delete(key: string): Promise<void>;
62
+ flush(): Promise<void>;
63
+ getMany<T = unknown>(keys: string[]): Promise<(T | undefined)[]>;
64
+ setMany<T = unknown>(
65
+ entries: { key: string; value: T; ttlSeconds?: number }[],
66
+ ): Promise<void>;
67
+ deleteMany(keys: string[]): Promise<void>;
68
+ }
69
+
70
+ function expiryFromTtl(ttlSeconds?: number): number | null {
71
+ if (ttlSeconds === undefined) return null;
72
+ return Date.now() + Math.max(0, ttlSeconds) * 1000;
73
+ }
74
+
75
+ function isExpired(expiresAt: number | null): boolean {
76
+ return expiresAt !== null && Date.now() >= expiresAt;
77
+ }
78
+
79
+ /**
80
+ * Database-backed cache store. Each operation resolves the per-request `db()`
81
+ * Kysely client from the database ALS scope (so it shares the same D1/Turso
82
+ * connection as the rest of your app), unless you pass an explicit client for
83
+ * scripts/tests.
84
+ *
85
+ * TTLs are in **seconds** (matching the rest of the cache API). Values are
86
+ * stored as JSON text. Expired rows are reaped lazily on read and via
87
+ * {@link DatabaseCacheStore.purgeExpired}.
88
+ *
89
+ * The client is resolved **lazily per operation** (not at construction), so a
90
+ * single `DatabaseCacheStore()` instance works for every request. Register it
91
+ * as a cache driver from your `src/index.ts` (or any server-only module loaded
92
+ * at startup), then declare `database` as a store in `config/cache.ts`:
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * // src/index.ts (or any startup module)
97
+ * import { extendCacheDriver } from '@cossackframework/framework/cache';
98
+ * import { DatabaseCacheStore } from '@cossackframework/database';
99
+ *
100
+ * // Register once — DatabaseCacheStore resolves `db()` per request.
101
+ * extendCacheDriver('database', () => new DatabaseCacheStore());
102
+ * ```
103
+ *
104
+ * ```ts
105
+ * // src/config/cache.ts — declare the store
106
+ * export default ({ env }) => ({
107
+ * default: 'database',
108
+ * stores: { database: { driver: 'database' } },
109
+ * });
110
+ * ```
111
+ *
112
+ * Requires the `cache_items` table — included as a default migration
113
+ * (0006_create_cache_table.ts). Apply with `cossack migration up`.
114
+ */
115
+ export class DatabaseCacheStore implements CacheStoreLike {
116
+ /**
117
+ * @param client Optional explicit Kysely client. When omitted, each
118
+ * operation resolves the per-request client via `db()` — the one scoped
119
+ * by the database middleware. Registering one `DatabaseCacheStore()`
120
+ * globally (e.g. next to your db middleware) then works for every request,
121
+ * because `db()` picks up each request's client from AsyncLocalStorage.
122
+ * Pass an explicit client only for scripts/tests outside a request scope.
123
+ */
124
+ constructor(private readonly explicitClient?: DbClient) {}
125
+
126
+ /** Resolve the active client — explicit, else the per-request `db()`. */
127
+ private client(): DbClient {
128
+ return this.explicitClient ?? db();
129
+ }
130
+
131
+ async get<T = unknown>(key: string): Promise<T | undefined> {
132
+ const c = this.client();
133
+ const row = await c
134
+ .selectFrom('cache_items')
135
+ .select(['value', 'expires_at'])
136
+ .where('key', '=', key)
137
+ .executeTakeFirst();
138
+ if (!row) return undefined;
139
+ if (isExpired(row.expires_at as number | null)) {
140
+ await c.deleteFrom('cache_items').where('key', '=', key).execute();
141
+ return undefined;
142
+ }
143
+ try {
144
+ return JSON.parse(row.value as string) as T;
145
+ } catch {
146
+ await c.deleteFrom('cache_items').where('key', '=', key).execute();
147
+ return undefined;
148
+ }
149
+ }
150
+
151
+ async set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void> {
152
+ const c = this.client();
153
+ if (value === undefined) {
154
+ await c.deleteFrom('cache_items').where('key', '=', key).execute();
155
+ return;
156
+ }
157
+ // Compute once — both the insert values and the onConflict update use these.
158
+ const json = JSON.stringify(value);
159
+ const expiresAt = expiryFromTtl(ttlSeconds);
160
+ const now = Date.now();
161
+ await c
162
+ .insertInto('cache_items')
163
+ .values({
164
+ key,
165
+ value: json,
166
+ expires_at: expiresAt,
167
+ updated_at: now,
168
+ })
169
+ .onConflict((oc) =>
170
+ oc.column('key').doUpdateSet({
171
+ value: json,
172
+ expires_at: expiresAt,
173
+ updated_at: now,
174
+ }),
175
+ )
176
+ .execute();
177
+ }
178
+
179
+ async has(key: string): Promise<boolean> {
180
+ const c = this.client();
181
+ const row = await c
182
+ .selectFrom('cache_items')
183
+ .select('expires_at')
184
+ .where('key', '=', key)
185
+ .executeTakeFirst();
186
+ if (!row) return false;
187
+ if (isExpired(row.expires_at as number | null)) {
188
+ await c.deleteFrom('cache_items').where('key', '=', key).execute();
189
+ return false;
190
+ }
191
+ return true;
192
+ }
193
+
194
+ async delete(key: string): Promise<void> {
195
+ await this.client().deleteFrom('cache_items').where('key', '=', key).execute();
196
+ }
197
+
198
+ async flush(): Promise<void> {
199
+ await this.client().deleteFrom('cache_items').execute();
200
+ }
201
+
202
+ async getMany<T = unknown>(keys: string[]): Promise<(T | undefined)[]> {
203
+ if (keys.length === 0) return [];
204
+ const c = this.client();
205
+ const rows = await c
206
+ .selectFrom('cache_items')
207
+ .select(['key', 'value', 'expires_at'])
208
+ .where('key', 'in', keys)
209
+ .execute();
210
+ const byKey = new Map<string, { value: string; expires_at: number | null }>();
211
+ const expiredKeys: string[] = [];
212
+ for (const r of rows) {
213
+ byKey.set(r.key, { value: r.value, expires_at: r.expires_at as number | null });
214
+ if (isExpired(r.expires_at as number | null)) expiredKeys.push(r.key);
215
+ }
216
+ if (expiredKeys.length > 0) {
217
+ await c.deleteFrom('cache_items').where('key', 'in', expiredKeys).execute();
218
+ for (const k of expiredKeys) byKey.delete(k);
219
+ }
220
+ const corruptKeys: string[] = [];
221
+ const out = keys.map((k) => {
222
+ const entry = byKey.get(k);
223
+ if (!entry) return undefined;
224
+ try {
225
+ return JSON.parse(entry.value) as T;
226
+ } catch {
227
+ corruptKeys.push(k);
228
+ return undefined;
229
+ }
230
+ });
231
+ if (corruptKeys.length > 0) {
232
+ await c.deleteFrom('cache_items').where('key', 'in', corruptKeys).execute();
233
+ }
234
+ return out;
235
+ }
236
+
237
+ async setMany<T = unknown>(
238
+ entries: { key: string; value: T; ttlSeconds?: number }[],
239
+ ): Promise<void> {
240
+ if (entries.length === 0) return;
241
+ const c = this.client();
242
+ const now = Date.now();
243
+ const inserts = entries
244
+ .filter((e) => e.value !== undefined)
245
+ .map((e) => ({
246
+ key: e.key,
247
+ value: JSON.stringify(e.value),
248
+ expires_at: expiryFromTtl(e.ttlSeconds),
249
+ updated_at: now,
250
+ }));
251
+ if (inserts.length > 0) {
252
+ await c
253
+ .insertInto('cache_items')
254
+ .values(inserts)
255
+ .onConflict((oc) =>
256
+ oc.column('key').doUpdateSet({
257
+ value: (ov: any) => ov.ref('excluded.value'),
258
+ expires_at: (ov: any) => ov.ref('excluded.expires_at'),
259
+ updated_at: (ov: any) => ov.ref('excluded.updated_at'),
260
+ }),
261
+ )
262
+ .execute();
263
+ }
264
+ const deletes = entries.filter((e) => e.value === undefined).map((e) => e.key);
265
+ if (deletes.length > 0) {
266
+ await c.deleteFrom('cache_items').where('key', 'in', deletes).execute();
267
+ }
268
+ }
269
+
270
+ async deleteMany(keys: string[]): Promise<void> {
271
+ if (keys.length === 0) return;
272
+ await this.client().deleteFrom('cache_items').where('key', 'in', keys).execute();
273
+ }
274
+
275
+ /** Delete all expired rows. Call opportunistically (e.g. on a sample of requests). */
276
+ async purgeExpired(): Promise<number> {
277
+ const now = Date.now();
278
+ const result = await this.client()
279
+ .deleteFrom('cache_items')
280
+ .where('expires_at', 'is not', null)
281
+ .where('expires_at', '<', now)
282
+ .executeTakeFirst();
283
+ return Number(result?.numDeletedRows ?? 0);
284
+ }
285
+ }
@@ -0,0 +1,36 @@
1
+ // src/create-database.ts
2
+ import { Kysely } from 'kysely';
3
+ import { D1Dialect } from './dialects/d1';
4
+ import { LibsqlDialect } from './dialects/libsql';
5
+ import type { Database, D1Config, DbClient, LibsqlConfig } from './types';
6
+
7
+ /**
8
+ * Creates a {@link DbClient} (a typed Kysely instance) for the configured
9
+ * dialect.
10
+ *
11
+ * - **D1**: pass the Cloudflare binding.
12
+ * - **libSQL / Turso**: pass a client created from `@tursodatabase/serverless/compat`
13
+ * (recommended) or `@libsql/client/web`.
14
+ *
15
+ * ```ts
16
+ * // Cloudflare D1
17
+ * const db = createDatabase({ dialect: 'd1', binding: env.DB })
18
+ *
19
+ * // Turso
20
+ * import { createClient } from '@tursodatabase/serverless/compat'
21
+ * const db = createDatabase({
22
+ * dialect: 'libsql',
23
+ * client: createClient({ url: env.TURSO_URL, authToken: env.TURSO_TOKEN }),
24
+ * })
25
+ * ```
26
+ */
27
+ export function createDatabase(config: D1Config | LibsqlConfig): DbClient;
28
+ export function createDatabase(config: D1Config): DbClient;
29
+ export function createDatabase(config: LibsqlConfig): DbClient;
30
+ export function createDatabase(config: D1Config | LibsqlConfig): DbClient {
31
+ const dialect =
32
+ config.dialect === 'd1'
33
+ ? new D1Dialect(config.binding)
34
+ : new LibsqlDialect(config.client);
35
+ return new Kysely<Database>({ dialect });
36
+ }