@cossackframework/database 0.7.7 → 0.8.0-licenseprobe.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 +1 -1
- package/package.json +93 -21
- package/README.md +0 -188
- package/src/accessor.ts +0 -27
- package/src/als.ts +0 -29
- package/src/cache-store.ts +0 -285
- package/src/create-database.ts +0 -36
- package/src/dialects/d1.ts +0 -215
- package/src/dialects/libsql.ts +0 -104
- package/src/index.ts +0 -67
- package/src/middleware.ts +0 -42
- package/src/migrations/migrator.ts +0 -90
- package/src/seeder/runner.ts +0 -73
- package/src/session-als.ts +0 -46
- package/src/session-middleware.ts +0 -98
- package/src/session-store.ts +0 -201
- package/src/session.ts +0 -59
- package/src/store.ts +0 -38
- package/src/types.ts +0 -108
package/LICENSE
CHANGED
package/package.json
CHANGED
|
@@ -1,47 +1,119 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cossackframework/database",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0-licenseprobe.0",
|
|
4
|
+
"description": "Serverless-first Active Record ORM for Cossack",
|
|
4
5
|
"type": "module",
|
|
5
|
-
"description": "Database support for the Cossack Framework — Kysely-based query builder with D1 and Turso dialects, migrations, and seeders",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"
|
|
8
|
-
|
|
9
|
-
"
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/cossackframework/cossack",
|
|
10
|
+
"directory": "packages/database"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cossackframework/cossack/tree/main/packages/database#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/cossackframework/cossack/issues"
|
|
15
|
+
},
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"bin": {
|
|
21
|
+
"cossack-orm": "dist/cli.js"
|
|
13
22
|
},
|
|
14
23
|
"files": [
|
|
15
|
-
"
|
|
24
|
+
"dist",
|
|
25
|
+
"docs",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
16
28
|
],
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./adapter": {
|
|
35
|
+
"types": "./dist/adapter/index.d.ts",
|
|
36
|
+
"import": "./dist/adapter/index.js"
|
|
37
|
+
},
|
|
38
|
+
"./node": {
|
|
39
|
+
"types": "./dist/runtime/node.d.ts",
|
|
40
|
+
"import": "./dist/runtime/node.js"
|
|
41
|
+
},
|
|
42
|
+
"./bun": {
|
|
43
|
+
"types": "./dist/runtime/bun.d.ts",
|
|
44
|
+
"import": "./dist/runtime/bun.js"
|
|
45
|
+
},
|
|
46
|
+
"./cloudflare": {
|
|
47
|
+
"types": "./dist/runtime/cloudflare.d.ts",
|
|
48
|
+
"import": "./dist/runtime/cloudflare.js"
|
|
49
|
+
},
|
|
50
|
+
"./deno": {
|
|
51
|
+
"types": "./dist/runtime/deno.d.ts",
|
|
52
|
+
"import": "./dist/runtime/deno.js"
|
|
53
|
+
},
|
|
54
|
+
"./cossack": {
|
|
55
|
+
"types": "./dist/cossack/index.d.ts",
|
|
56
|
+
"import": "./dist/cossack/index.js"
|
|
57
|
+
},
|
|
58
|
+
"./tooling": {
|
|
59
|
+
"types": "./dist/tooling/index.d.ts",
|
|
60
|
+
"import": "./dist/tooling/index.js"
|
|
61
|
+
},
|
|
62
|
+
"./cli": "./dist/cli.js",
|
|
63
|
+
"./package.json": "./package.json"
|
|
64
|
+
},
|
|
17
65
|
"publishConfig": {
|
|
18
66
|
"access": "public"
|
|
19
67
|
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "tsc -p tsconfig.build.json",
|
|
70
|
+
"check": "tsc --noEmit",
|
|
71
|
+
"test": "vitest run",
|
|
72
|
+
"test:watch": "vitest",
|
|
73
|
+
"audit:bundle": "node scripts/audit-bundles.mjs",
|
|
74
|
+
"example:sqlite": "tsx ./examples/sqlite-starter/run.ts",
|
|
75
|
+
"example:sqlite:reset": "tsx ./examples/sqlite-starter/run.ts --reset",
|
|
76
|
+
"example:sqlite:create": "tsx ./examples/sqlite-starter/create-database.ts",
|
|
77
|
+
"example:sqlite:migrate": "tsx ./examples/sqlite-starter/migrate.ts",
|
|
78
|
+
"example:sqlite:seed": "tsx ./examples/sqlite-starter/seed.ts",
|
|
79
|
+
"example:sqlite:query": "tsx ./examples/sqlite-starter/query.ts",
|
|
80
|
+
"example:multiple-connections": "tsx ./examples/multiple-connections/run.ts",
|
|
81
|
+
"example:multiple-connections:reset": "tsx ./examples/multiple-connections/run.ts --reset",
|
|
82
|
+
"prepack": "pnpm build && pnpm test && pnpm audit:bundle"
|
|
83
|
+
},
|
|
20
84
|
"dependencies": {
|
|
21
|
-
"
|
|
85
|
+
"tsx": "^4.23.0"
|
|
22
86
|
},
|
|
23
87
|
"peerDependencies": {
|
|
24
|
-
"@libsql/client": "
|
|
25
|
-
"
|
|
26
|
-
"hono": "^4.12.0"
|
|
88
|
+
"@libsql/client": ">=0.14",
|
|
89
|
+
"better-sqlite3": ">=11",
|
|
90
|
+
"hono": "^4.12.0",
|
|
91
|
+
"mysql2": ">=3.11",
|
|
92
|
+
"pg": ">=8.13",
|
|
93
|
+
"reflect-metadata": ">=0.2"
|
|
27
94
|
},
|
|
28
95
|
"peerDependenciesMeta": {
|
|
29
|
-
"@
|
|
96
|
+
"@libsql/client": {
|
|
30
97
|
"optional": true
|
|
31
98
|
},
|
|
32
|
-
"
|
|
99
|
+
"better-sqlite3": {
|
|
100
|
+
"optional": true
|
|
101
|
+
},
|
|
102
|
+
"mysql2": {
|
|
103
|
+
"optional": true
|
|
104
|
+
},
|
|
105
|
+
"pg": {
|
|
106
|
+
"optional": true
|
|
107
|
+
},
|
|
108
|
+
"reflect-metadata": {
|
|
33
109
|
"optional": true
|
|
34
110
|
}
|
|
35
111
|
},
|
|
36
112
|
"devDependencies": {
|
|
37
|
-
"@libsql/client": "^0.14.0",
|
|
38
113
|
"@types/node": "^22.19.0",
|
|
39
114
|
"hono": "^4.12.31",
|
|
40
|
-
"
|
|
115
|
+
"reflect-metadata": "^0.2.2",
|
|
41
116
|
"typescript": "^7.0.2",
|
|
42
117
|
"vitest": "^4.1.10"
|
|
43
|
-
},
|
|
44
|
-
"scripts": {
|
|
45
|
-
"test": "vitest"
|
|
46
118
|
}
|
|
47
|
-
}
|
|
119
|
+
}
|
package/README.md
DELETED
|
@@ -1,188 +0,0 @@
|
|
|
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 the Database, Auth, and Full Stack recipes.
|
|
11
|
-
> Those recipes ship migrations, wire `dbMiddleware`, and register the database
|
|
12
|
-
> cache driver. The framework itself stays decoupled (no hard dependency).
|
|
13
|
-
|
|
14
|
-
## Install
|
|
15
|
-
|
|
16
|
-
Select the Database or Full Stack preset with `cossack create`, or add database
|
|
17
|
-
support to an existing project:
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npx cossack add database
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
This scaffolds `src/models/`, `src/migrations/`, `src/seeders/`,
|
|
24
|
-
`src/db/config.ts` for the application runtime, and `src/db/cli.ts` for
|
|
25
|
-
Node-only tools. It also adds the dependency to `package.json` and (for D1)
|
|
26
|
-
injects a `[[d1_databases]]` binding into `wrangler.jsonc`.
|
|
27
|
-
|
|
28
|
-
## Connecting
|
|
29
|
-
|
|
30
|
-
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):
|
|
31
|
-
|
|
32
|
-
**Cloudflare D1** — pass the binding:
|
|
33
|
-
|
|
34
|
-
```ts
|
|
35
|
-
import { createDatabase } from '@cossackframework/database'
|
|
36
|
-
|
|
37
|
-
export function createClient(env: { DB: D1Database }) {
|
|
38
|
-
return createDatabase({ dialect: 'd1', binding: env.DB })
|
|
39
|
-
}
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
**Turso / libSQL** — pass a client built from `@tursodatabase/serverless/compat` (recommended, fetch-based) or `@libsql/client/web`. Works on Workers + Node:
|
|
43
|
-
|
|
44
|
-
```ts
|
|
45
|
-
import { createDatabase } from '@cossackframework/database'
|
|
46
|
-
import { createClient as createLibsqlClient } from '@tursodatabase/serverless/compat'
|
|
47
|
-
|
|
48
|
-
export function createClient(env: { TURSO_URL: string; TURSO_TOKEN?: string }) {
|
|
49
|
-
return createDatabase({
|
|
50
|
-
dialect: 'libsql',
|
|
51
|
-
client: createLibsqlClient({ url: env.TURSO_URL, authToken: env.TURSO_TOKEN }),
|
|
52
|
-
})
|
|
53
|
-
}
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
The generated `src/db/cli.ts` exports `getCliClient()` for migration, seeder,
|
|
57
|
-
and Studio commands (see [Migrations](../../docs/migrations.md)).
|
|
58
|
-
|
|
59
|
-
### Wiring the middleware
|
|
60
|
-
|
|
61
|
-
`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:
|
|
62
|
-
|
|
63
|
-
```ts
|
|
64
|
-
// src/bootstrap/middlewares.ts
|
|
65
|
-
import type { MiddlewareHandler } from 'hono'
|
|
66
|
-
import { dbMiddleware } from '../middlewares/db'
|
|
67
|
-
|
|
68
|
-
const middlewares: MiddlewareHandler[] = [
|
|
69
|
-
dbMiddleware,
|
|
70
|
-
]
|
|
71
|
-
export default middlewares
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
The middleware is defined in `src/middlewares/db.ts`:
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
// src/middlewares/db.ts
|
|
78
|
-
import { createDbMiddleware } from '@cossackframework/database'
|
|
79
|
-
import { createClient } from '../db/config'
|
|
80
|
-
|
|
81
|
-
export const dbMiddleware = createDbMiddleware({
|
|
82
|
-
client: (c) => createClient(c.env),
|
|
83
|
-
})
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
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.
|
|
87
|
-
|
|
88
|
-
## Querying
|
|
89
|
-
|
|
90
|
-
From a component method:
|
|
91
|
-
|
|
92
|
-
```ts
|
|
93
|
-
import { db } from '@cossackframework/database'
|
|
94
|
-
|
|
95
|
-
@Server()
|
|
96
|
-
async getUsers() {
|
|
97
|
-
return await db().selectFrom('users').selectAll().execute()
|
|
98
|
-
}
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
From an API route:
|
|
102
|
-
|
|
103
|
-
```ts
|
|
104
|
-
import { getDb } from '@cossackframework/database'
|
|
105
|
-
|
|
106
|
-
export default async (c: Context) => {
|
|
107
|
-
const users = await getDb(c).selectFrom('users').selectAll().execute()
|
|
108
|
-
return c.json(users)
|
|
109
|
-
}
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
## Typing your schema
|
|
113
|
-
|
|
114
|
-
The `Database` interface (table → row) and the `User` (auth) interface are both empty by default and augmented from `src/models/`:
|
|
115
|
-
|
|
116
|
-
```ts
|
|
117
|
-
// src/models/User.ts
|
|
118
|
-
import type { Generated } from '@cossackframework/database'
|
|
119
|
-
|
|
120
|
-
export interface UserRow {
|
|
121
|
-
id: Generated<string>
|
|
122
|
-
email: string
|
|
123
|
-
name: string
|
|
124
|
-
passwordHash: string
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
declare module '@cossackframework/database' {
|
|
128
|
-
interface Database { users: UserRow }
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Safe subset exposed as this.user / c.get('user') (no passwordHash)
|
|
132
|
-
declare module '@cossackframework/core' {
|
|
133
|
-
interface User { id: string; email: string; name: string }
|
|
134
|
-
}
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
## Migrations & seeders (CLI)
|
|
138
|
-
|
|
139
|
-
```bash
|
|
140
|
-
cossack generate migration create_users
|
|
141
|
-
cossack migration up # apply pending
|
|
142
|
-
cossack migration down # revert the latest
|
|
143
|
-
cossack migration status
|
|
144
|
-
|
|
145
|
-
cossack generate seeder users
|
|
146
|
-
cossack seeder run
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
## Transactions
|
|
150
|
-
|
|
151
|
-
- **Turso / libSQL** supports interactive transactions via Kysely's `db().transaction().execute(async (trx) => { ... })`.
|
|
152
|
-
- **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.
|
|
153
|
-
|
|
154
|
-
The migrator is unaffected — the SQLite adapter reports `supportsTransactionalDdl: false`, so each migration runs without a transaction wrapper.
|
|
155
|
-
|
|
156
|
-
## Dialects
|
|
157
|
-
|
|
158
|
-
| Dialect | Config | Where it runs | Driver |
|
|
159
|
-
|---|---|---|---|
|
|
160
|
-
| **D1** | `{ dialect: 'd1', binding: env.DB }` | Cloudflare Workers | The D1 binding (no extra dep) |
|
|
161
|
-
| **Turso / libSQL** | `{ dialect: 'libsql', client }` | Workers + Node | `@tursodatabase/serverless/compat` (recommended) or `@libsql/client/web` |
|
|
162
|
-
|
|
163
|
-
Postgres and MySQL adapters are planned for a later release.
|
|
164
|
-
|
|
165
|
-
## No build step
|
|
166
|
-
|
|
167
|
-
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`:
|
|
168
|
-
|
|
169
|
-
```json
|
|
170
|
-
{
|
|
171
|
-
"main": "src/index.ts",
|
|
172
|
-
"exports": { ".": { "types": "./src/index.ts", "import": "./src/index.ts" } },
|
|
173
|
-
"files": ["src"]
|
|
174
|
-
}
|
|
175
|
-
```
|
|
176
|
-
|
|
177
|
-
Consumers compile it at their own build/run time:
|
|
178
|
-
|
|
179
|
-
- **User apps** — the framework's Vite build bundles it into the Worker (SSR) bundle; it never reaches the client bundle (server-only).
|
|
180
|
-
- **The `cossack` CLI** — the `migration` / `seeder` commands run under `tsx`, which loads the `.ts` source directly.
|
|
181
|
-
|
|
182
|
-
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/`.
|
|
183
|
-
|
|
184
|
-
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.
|
|
185
|
-
|
|
186
|
-
## License
|
|
187
|
-
|
|
188
|
-
MIT
|
package/src/accessor.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
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
|
-
}
|
package/src/cache-store.ts
DELETED
|
@@ -1,285 +0,0 @@
|
|
|
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
|
-
}
|