@marianmeres/kv 3.0.0 → 3.1.1
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/AGENTS.md +26 -14
- package/API.md +75 -11
- package/README.md +47 -21
- package/dist/adapter/abstract.d.ts +4 -4
- package/dist/adapter/abstract.js +3 -3
- package/dist/adapter/memory.d.ts +1 -0
- package/dist/adapter/memory.js +3 -0
- package/dist/adapter/postgres.d.ts +1 -0
- package/dist/adapter/postgres.js +9 -2
- package/dist/adapter/sqlite.d.ts +103 -0
- package/dist/adapter/sqlite.js +419 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/kv.d.ts +12 -0
- package/dist/kv.js +10 -0
- package/package.json +10 -8
package/AGENTS.md
CHANGED
|
@@ -5,9 +5,12 @@ Machine-friendly reference for AI agents working with this codebase.
|
|
|
5
5
|
## Quick Reference
|
|
6
6
|
|
|
7
7
|
- **Stack**: TypeScript (erasable-only), Node LTS (`.node-version`), pnpm, `node:test`, Biome.
|
|
8
|
-
- **Install**: `pnpm install` | **Test**: `pnpm test` (needs Postgres + Redis
|
|
8
|
+
- **Install**: `pnpm install` | **Test**: `pnpm test` (needs Postgres + Redis; SQLite runs in memory) |
|
|
9
9
|
**Check all**: `pnpm run ci` | **Build**: `pnpm run build`
|
|
10
10
|
- **Published**: npm (`dist/`, built by `tsc`) and JSR (`src/` via `jsr.json`, for Deno consumers)
|
|
11
|
+
- **JSR imports**: `jsr.json` maps `@marianmeres/clog` to `jsr:` so Deno apps get one copy;
|
|
12
|
+
keep its range equal to `package.json`'s. `pg` and `redis` resolve from `package.json` as
|
|
13
|
+
`npm:`. Only `deno publish` reads `jsr.json`: `test:deno` still runs against npm clog.
|
|
11
14
|
|
|
12
15
|
## Purpose
|
|
13
16
|
|
|
@@ -23,7 +26,8 @@ src/
|
|
|
23
26
|
│ ├── abstract.ts — Base class + shared types
|
|
24
27
|
│ ├── memory.ts — In-memory adapter
|
|
25
28
|
│ ├── redis.ts — Redis adapter
|
|
26
|
-
│
|
|
29
|
+
│ ├── postgres.ts — PostgreSQL adapter
|
|
30
|
+
│ └── sqlite.ts — SQLite adapter (`node:sqlite`)
|
|
27
31
|
└── utils/
|
|
28
32
|
└── sleep.ts — Sleep utility function
|
|
29
33
|
|
|
@@ -31,7 +35,9 @@ tests/
|
|
|
31
35
|
├── kv.test.ts — Main test file (node:test); every test runs against all adapters
|
|
32
36
|
├── _tests-runner.ts — Test harness: builds one client per adapter per test
|
|
33
37
|
├── _redis.ts — Redis test helper
|
|
34
|
-
|
|
38
|
+
├── _pg.ts — PostgreSQL test helper
|
|
39
|
+
├── _sqlite.ts — SQLite test helper (fresh `:memory:` database per test)
|
|
40
|
+
└── _no-destroy-child.ts — child process: an adapter left running must not hold it open
|
|
35
41
|
|
|
36
42
|
dist/ — `tsc -p tsconfig.build.json` output; gitignored; the npm payload
|
|
37
43
|
```
|
|
@@ -57,14 +63,18 @@ dist/ — `tsc -p tsconfig.build.json` output; gitignored; the
|
|
|
57
63
|
7. TTL is in seconds; stored as absolute `Date` internally.
|
|
58
64
|
8. Pattern matching: Redis-style (`*` = any chars, `?` = single char). All other characters — including `.`, `(`, `[`, `%`, `_` — are matched **literally**.
|
|
59
65
|
9. TTL resolution: `options.ttl ?? defaultTtl`; `0` or negative disables expiration for that call (explicitly overrides `defaultTtl`).
|
|
60
|
-
10.
|
|
66
|
+
10. Shared helpers live in `abstract.ts` — use `_globToRegex()`, `_resolveTtl()`, `_normalizePairs()`; do not re-implement per-adapter. The SQL adapters keep their own pattern escaping next to the SQL that uses it: Postgres `#likePattern` (LIKE, `ESCAPE '\'`), SQLite `#globPattern` (GLOB — case-sensitive, unlike SQLite's LIKE; `[` → `[[]`). Both escape the namespace as a literal prefix.
|
|
61
67
|
11. Postgres `transaction()` must pin a single connection via `pool.connect()`; every nested query uses that client, not `this.options.db`.
|
|
62
|
-
12. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag).
|
|
68
|
+
12. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag). The Postgres and SQLite adapters never close the `db` they were given.
|
|
63
69
|
13. Key validation lives in `_withNs()` — enforced when `options.validateKeys !== false`. Reject empty strings, keys with `\0`, and total `namespace + key` length > 512.
|
|
64
70
|
14. `ttl()` returns `TtlResult = { state: "missing" | "no-ttl" | "expires"; at? }` — discriminated union, not `Date | null | false`.
|
|
65
|
-
15. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; Memory = plain read-modify-write (single-threaded).
|
|
66
|
-
16. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02
|
|
67
|
-
17. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`.
|
|
71
|
+
15. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; SQLite = a single UPSERT/UPDATE (`setIfAbsent`, `cas`) or a read-modify-write inside `#atomic()` (`getSet`, `incr`/`decr`); Memory = plain read-modify-write (single-threaded).
|
|
72
|
+
16. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02`; SQLite checks `typeof` in JS, like Memory.
|
|
73
|
+
17. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`. SQLite pages by keyset (`key > last`), so nothing stays open between yields.
|
|
74
|
+
18. SQLite: `src/` imports `node:sqlite` **type-only** — the caller passes the `DatabaseSync`. A runtime import would make every consumer of the package load `node:sqlite`.
|
|
75
|
+
19. SQLite multi-statement operations go through `#atomic()`: `BEGIN IMMEDIATE`, or a savepoint when `db.isTransaction` (the caller's transaction on the same handle). The callback must stay synchronous — an `await` inside would let other work join the transaction.
|
|
76
|
+
20. SQLite stores `value` as JSON text and `expires_at` as epoch ms (INTEGER), compared against a bound `Date.now()` — never SQLite's own clock. Read counts/integers through `Number()` (a handle opened with `readBigInts` returns bigints).
|
|
77
|
+
21. TTL cleanup timers are `unref()`ed (`unref?.()`: browser and worker timers are plain numbers), so a client nobody destroyed cannot hold the process open; `destroy()` still clears them. Postgres's tick awaits its query, so it re-checks `_initialized` before re-arming, and `destroy()` clears `_initialized` before its first `await`. SQLite stops the cleanup (one error log) when it finds `db.isOpen` false.
|
|
68
78
|
|
|
69
79
|
## Before Making Changes
|
|
70
80
|
|
|
@@ -74,11 +84,12 @@ dist/ — `tsc -p tsconfig.build.json` output; gitignored; the
|
|
|
74
84
|
|
|
75
85
|
## Supported Adapters
|
|
76
86
|
|
|
77
|
-
| Adapter | Type String | Required Options | Limitations
|
|
78
|
-
| ---------- | ------------ | --------------------- |
|
|
79
|
-
| Memory | `"memory"` | None | Not persisted
|
|
80
|
-
| Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode
|
|
81
|
-
| PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix
|
|
87
|
+
| Adapter | Type String | Required Options | Limitations |
|
|
88
|
+
| ---------- | ------------ | --------------------- | --------------------------------------------------------------------------- |
|
|
89
|
+
| Memory | `"memory"` | None | Not persisted |
|
|
90
|
+
| Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
|
|
91
|
+
| PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix |
|
|
92
|
+
| SQLite | `"sqlite"` | `db` (`DatabaseSync`) | `tableName` limited to `[A-Za-z0-9_]`, no schema prefix; synchronous driver |
|
|
82
93
|
|
|
83
94
|
## Core API
|
|
84
95
|
|
|
@@ -168,7 +179,8 @@ human action.
|
|
|
168
179
|
|
|
169
180
|
## Test Environment Variables
|
|
170
181
|
|
|
171
|
-
Every test runs against all
|
|
182
|
+
Every test runs against all four adapters, so tests need a live Postgres and Redis (SQLite
|
|
183
|
+
uses a fresh `:memory:` database per test and needs nothing). Put
|
|
172
184
|
these in `.env` (see `.env.example`); CI provides them via service containers
|
|
173
185
|
(`.github/workflows/ci.yml`). The harness deletes **every key** in the Redis DB before each
|
|
174
186
|
test — use a scratch DB.
|
package/API.md
CHANGED
|
@@ -31,11 +31,11 @@ function createKVClient<T extends keyof KnownTypes>(
|
|
|
31
31
|
|
|
32
32
|
**Parameters:**
|
|
33
33
|
|
|
34
|
-
| Parameter | Type
|
|
35
|
-
| ----------- |
|
|
36
|
-
| `namespace` | `string`
|
|
37
|
-
| `type` | `"memory" \| "redis" \| "postgres"` | `"memory"` | The storage backend to use. |
|
|
38
|
-
| `options` | `Partial<AdapterOptions>`
|
|
34
|
+
| Parameter | Type | Default | Description |
|
|
35
|
+
| ----------- | ----------------------------------------------- | ---------- | -------------------------------------------------------------------- |
|
|
36
|
+
| `namespace` | `string` | `""` | Key prefix applied to all operations. Must end with `:` or be empty. |
|
|
37
|
+
| `type` | `"memory" \| "redis" \| "postgres" \| "sqlite"` | `"memory"` | The storage backend to use. |
|
|
38
|
+
| `options` | `Partial<AdapterOptions>` | `{}` | Adapter-specific configuration options. |
|
|
39
39
|
|
|
40
40
|
**Returns:** A configured adapter instance. Call `initialize()` before use.
|
|
41
41
|
|
|
@@ -64,6 +64,11 @@ import pg from "pg";
|
|
|
64
64
|
const pool = new pg.Pool({ connectionString: "..." });
|
|
65
65
|
const postgres = createKVClient("myapp:", "postgres", { db: pool });
|
|
66
66
|
await postgres.initialize();
|
|
67
|
+
|
|
68
|
+
// SQLite storage (node:sqlite ships with Node)
|
|
69
|
+
import { DatabaseSync } from "node:sqlite";
|
|
70
|
+
const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
|
|
71
|
+
await sqlite.initialize();
|
|
67
72
|
```
|
|
68
73
|
|
|
69
74
|
---
|
|
@@ -98,9 +103,12 @@ destroy(hard?: boolean): Promise<void>
|
|
|
98
103
|
|
|
99
104
|
**Parameters:**
|
|
100
105
|
|
|
101
|
-
| Parameter | Type | Default | Description
|
|
102
|
-
| --------- | --------- | ------- |
|
|
103
|
-
| `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL). |
|
|
106
|
+
| Parameter | Type | Default | Description |
|
|
107
|
+
| --------- | --------- | ------- | --------------------------------------------------------------------------------- |
|
|
108
|
+
| `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL and SQLite). |
|
|
109
|
+
|
|
110
|
+
Stops the TTL cleanup timer (`ttlCleanupIntervalSec`). That timer never keeps the process
|
|
111
|
+
alive on its own, so a short-lived script that skips `destroy()` still exits.
|
|
104
112
|
|
|
105
113
|
---
|
|
106
114
|
|
|
@@ -116,7 +124,7 @@ info(): AdapterInfo
|
|
|
116
124
|
|
|
117
125
|
```typescript
|
|
118
126
|
const info = client.info();
|
|
119
|
-
console.log(info.type); // "redis", "postgres", or "memory"
|
|
127
|
+
console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
|
|
120
128
|
```
|
|
121
129
|
|
|
122
130
|
---
|
|
@@ -453,6 +461,7 @@ Ordering is not guaranteed across adapters — use `keys()` if you need sorted o
|
|
|
453
461
|
**Per-adapter behavior:**
|
|
454
462
|
- Redis: wraps `SCAN` (non-blocking).
|
|
455
463
|
- PostgreSQL: uses a server-side cursor (`DECLARE CURSOR`) inside a short transaction. Early break releases the cursor and commits.
|
|
464
|
+
- SQLite: keyset pages of 500 keys (`key > last ORDER BY key`). Nothing stays open between pages, so an early break has nothing to release.
|
|
456
465
|
- Memory: yields from the internal `Map`.
|
|
457
466
|
|
|
458
467
|
**Example:**
|
|
@@ -581,8 +590,9 @@ Atomicity per adapter:
|
|
|
581
590
|
| Memory | ✓ | Single-threaded by nature |
|
|
582
591
|
| Redis | ✓ | Uses `MULTI`/`EXEC` |
|
|
583
592
|
| PostgreSQL | ✓ | Pins a single connection for `BEGIN`/…/`COMMIT`, even on a `pg.Pool` |
|
|
593
|
+
| SQLite | ✓ | `BEGIN IMMEDIATE`; a savepoint inside a caller-opened transaction |
|
|
584
594
|
|
|
585
|
-
Per-operation `options.ttl` is honored by **all** adapters (Redis, PostgreSQL, Memory).
|
|
595
|
+
Per-operation `options.ttl` is honored by **all** adapters (Redis, PostgreSQL, SQLite, Memory).
|
|
586
596
|
|
|
587
597
|
**Parameters:**
|
|
588
598
|
|
|
@@ -627,7 +637,7 @@ Information about the adapter instance.
|
|
|
627
637
|
```typescript
|
|
628
638
|
interface AdapterInfo {
|
|
629
639
|
/** The adapter type identifier. */
|
|
630
|
-
type: string; // "redis" | "postgres" | "memory"
|
|
640
|
+
type: string; // "redis" | "postgres" | "sqlite" | "memory"
|
|
631
641
|
}
|
|
632
642
|
```
|
|
633
643
|
|
|
@@ -708,6 +718,7 @@ interface AdapterMemoryOptions extends AdapterAbstractOptions {
|
|
|
708
718
|
* Interval in seconds for automatic cleanup of expired keys.
|
|
709
719
|
* Set to 0 to disable automatic cleanup (expired keys will still be
|
|
710
720
|
* lazily removed on access).
|
|
721
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
711
722
|
*/
|
|
712
723
|
ttlCleanupIntervalSec: number;
|
|
713
724
|
}
|
|
@@ -760,6 +771,7 @@ interface AdapterPostgresOptions extends AdapterAbstractOptions {
|
|
|
760
771
|
/**
|
|
761
772
|
* Interval in seconds for automatic cleanup of expired keys.
|
|
762
773
|
* Set to 0 to disable automatic cleanup.
|
|
774
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
763
775
|
*/
|
|
764
776
|
ttlCleanupIntervalSec: number;
|
|
765
777
|
}
|
|
@@ -777,6 +789,58 @@ interface AdapterPostgresOptions extends AdapterAbstractOptions {
|
|
|
777
789
|
|
|
778
790
|
---
|
|
779
791
|
|
|
792
|
+
### `AdapterSqliteOptions`
|
|
793
|
+
|
|
794
|
+
```typescript
|
|
795
|
+
interface AdapterSqliteOptions extends AdapterAbstractOptions {
|
|
796
|
+
/**
|
|
797
|
+
* An open `node:sqlite` database, e.g. `new DatabaseSync("kv.db")`. The caller owns
|
|
798
|
+
* it: `destroy()` never closes it, so one handle can be shared across adapters.
|
|
799
|
+
*/
|
|
800
|
+
db: DatabaseSync;
|
|
801
|
+
/**
|
|
802
|
+
* Name of the table to use for storing key-value pairs.
|
|
803
|
+
* The table will be created automatically if it doesn't exist.
|
|
804
|
+
* Must match `^[A-Za-z_][A-Za-z0-9_]*$` (no `schema.` prefix).
|
|
805
|
+
* @default "__kv"
|
|
806
|
+
*/
|
|
807
|
+
tableName: string;
|
|
808
|
+
/**
|
|
809
|
+
* Interval in seconds for automatic cleanup of expired keys.
|
|
810
|
+
* Set to 0 to disable automatic cleanup.
|
|
811
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
812
|
+
*/
|
|
813
|
+
ttlCleanupIntervalSec: number;
|
|
814
|
+
}
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
**Connection ownership:** the adapter never opens, closes or reconfigures the handle — it
|
|
818
|
+
sets no pragmas. Call `destroy()` before you close the handle: if the TTL cleanup finds it
|
|
819
|
+
closed, it logs one error and stops. For several processes on one file, open it with a busy
|
|
820
|
+
timeout (`new DatabaseSync(path, { timeout: 5000 })`) so a locked write waits instead of
|
|
821
|
+
failing, and consider `PRAGMA journal_mode = WAL`.
|
|
822
|
+
|
|
823
|
+
**Atomicity:** `setIfAbsent`, `cas`, `expire` and `set` are single statements.
|
|
824
|
+
`getSet`, `incr`/`decr`, `setMultiple`, `clear` and `transaction` run in `BEGIN IMMEDIATE`,
|
|
825
|
+
which takes the write lock up front, so they stay atomic against other connections and
|
|
826
|
+
processes. Called inside a transaction you opened on the same handle (`db.isTransaction`),
|
|
827
|
+
they use a savepoint instead: their own failure rolls back only themselves, and your
|
|
828
|
+
`COMMIT`/`ROLLBACK` decides the rest.
|
|
829
|
+
|
|
830
|
+
**Synchronous driver:** `node:sqlite` blocks the event loop for the duration of each call.
|
|
831
|
+
Every method still returns a Promise, like the other adapters.
|
|
832
|
+
|
|
833
|
+
**Pattern matching** uses SQLite `GLOB`, which is case-sensitive and uses the primary-key
|
|
834
|
+
index for a literal prefix. `[` is escaped, so `keys()` / `clear()` follow the same
|
|
835
|
+
literal-except-`*`/`?` rules as every adapter.
|
|
836
|
+
|
|
837
|
+
**Table Schema:**
|
|
838
|
+
- `key` (TEXT) - Primary key
|
|
839
|
+
- `value` (TEXT) - Stored value as JSON text
|
|
840
|
+
- `expires_at` (INTEGER) - Expiration time as epoch milliseconds; `NULL` = no expiration
|
|
841
|
+
|
|
842
|
+
---
|
|
843
|
+
|
|
780
844
|
## Utility Functions
|
|
781
845
|
|
|
782
846
|
### `sleep(timeout, __timeout_ref__?)`
|
package/README.md
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
Key-value storage abstraction layer with support for multiple backend adapters:
|
|
8
8
|
- redis
|
|
9
9
|
- postgresql
|
|
10
|
+
- sqlite (`node:sqlite`)
|
|
10
11
|
- memory
|
|
11
12
|
|
|
12
13
|
The API is inspired by the Redis API.
|
|
@@ -18,8 +19,8 @@ npm install @marianmeres/kv # or pnpm add
|
|
|
18
19
|
deno add jsr:@marianmeres/kv # Deno
|
|
19
20
|
```
|
|
20
21
|
|
|
21
|
-
The `redis` and `
|
|
22
|
-
Requires Node >= 24.12.
|
|
22
|
+
The `redis`, `postgres` and `sqlite` adapters take a client you create yourself (`redis`,
|
|
23
|
+
`pg`, or a `node:sqlite` `DatabaseSync`, which ships with Node). Requires Node >= 24.12.
|
|
23
24
|
|
|
24
25
|
## Usage
|
|
25
26
|
|
|
@@ -32,7 +33,7 @@ const client = createKVClient("my-app-namespace:");
|
|
|
32
33
|
// Or specify a different adapter type
|
|
33
34
|
const redisClient = createKVClient(
|
|
34
35
|
"my-app-namespace:",
|
|
35
|
-
"redis", // 'redis' | 'postgres' | 'memory'
|
|
36
|
+
"redis", // 'redis' | 'postgres' | 'sqlite' | 'memory'
|
|
36
37
|
{ db: myRedisClient }, // adapter-specific options
|
|
37
38
|
);
|
|
38
39
|
|
|
@@ -97,20 +98,20 @@ type TtlResult =
|
|
|
97
98
|
|
|
98
99
|
## Adapter Feature Matrix
|
|
99
100
|
|
|
100
|
-
| Feature | Memory | Redis | PostgreSQL |
|
|
101
|
-
| --------------------------------------------------------- | :-----------------: | :--------------------: | :--------------: |
|
|
102
|
-
| Persistent | ✗ | ✓ | ✓ |
|
|
103
|
-
| TTL on `set()` | ✓ | ✓ | ✓ |
|
|
104
|
-
| `ttl()` → `expires`/`no-ttl`/`missing` | ✓ | ✓ | ✓ |
|
|
105
|
-
| `expire()` | ✓ | ✓ | ✓ |
|
|
106
|
-
| Atomic `setIfAbsent` / `incr` / `decr` / `cas` / `getSet` | ✓ | ✓ (Lua) | ✓ (UPSERT) |
|
|
107
|
-
| Sorted `keys()` | ✓ | ✓ | ✓ |
|
|
108
|
-
| Streaming `keysIter()` | ✓ | ✓ (SCAN) | ✓ (cursor) |
|
|
109
|
-
| Per-pair TTL in `setMultiple` | ✓ | ✓ | ✓ |
|
|
110
|
-
| Atomic `transaction()` | ✓ (single-threaded) | ✓ (MULTI) | ✓ (BEGIN/COMMIT) |
|
|
111
|
-
| `delete()` returns real existed-flag | ✓ | ✓ | ✓ |
|
|
112
|
-
| Background TTL cleanup | optional | native (Redis does it) | optional |
|
|
113
|
-
| `keys()` / `clear()` | ✓ | ✓ (non-cluster only) | ✓ |
|
|
101
|
+
| Feature | Memory | Redis | PostgreSQL | SQLite |
|
|
102
|
+
| --------------------------------------------------------- | :-----------------: | :--------------------: | :--------------: | :-----------------------: |
|
|
103
|
+
| Persistent | ✗ | ✓ | ✓ | ✓ (file database) |
|
|
104
|
+
| TTL on `set()` | ✓ | ✓ | ✓ | ✓ |
|
|
105
|
+
| `ttl()` → `expires`/`no-ttl`/`missing` | ✓ | ✓ | ✓ | ✓ |
|
|
106
|
+
| `expire()` | ✓ | ✓ | ✓ | ✓ |
|
|
107
|
+
| Atomic `setIfAbsent` / `incr` / `decr` / `cas` / `getSet` | ✓ | ✓ (Lua) | ✓ (UPSERT) | ✓ (UPSERT / IMMEDIATE tx) |
|
|
108
|
+
| Sorted `keys()` | ✓ | ✓ | ✓ | ✓ |
|
|
109
|
+
| Streaming `keysIter()` | ✓ | ✓ (SCAN) | ✓ (cursor) | ✓ (keyset paging) |
|
|
110
|
+
| Per-pair TTL in `setMultiple` | ✓ | ✓ | ✓ | ✓ |
|
|
111
|
+
| Atomic `transaction()` | ✓ (single-threaded) | ✓ (MULTI) | ✓ (BEGIN/COMMIT) | ✓ (BEGIN IMMEDIATE) |
|
|
112
|
+
| `delete()` returns real existed-flag | ✓ | ✓ | ✓ | ✓ |
|
|
113
|
+
| Background TTL cleanup | optional | native (Redis does it) | optional | optional |
|
|
114
|
+
| `keys()` / `clear()` | ✓ | ✓ (non-cluster only) | ✓ | ✓ |
|
|
114
115
|
|
|
115
116
|
## Adapter-Specific Limitations
|
|
116
117
|
|
|
@@ -127,6 +128,31 @@ type TtlResult =
|
|
|
127
128
|
- `transaction()` pins a single connection from the Pool for the whole BEGIN/…/COMMIT block — safe to call against a `pg.Pool`.
|
|
128
129
|
- Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
|
|
129
130
|
|
|
131
|
+
### SQLite
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
import { DatabaseSync } from "node:sqlite";
|
|
135
|
+
|
|
136
|
+
const client = createKVClient("my-app-namespace:", "sqlite", {
|
|
137
|
+
db: new DatabaseSync("kv.db"),
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- Takes an open `node:sqlite` `DatabaseSync` and never closes it — the handle is yours,
|
|
142
|
+
and can be shared with your own tables or other adapters.
|
|
143
|
+
- Creates a table (default: `__kv`). `tableName` must match `^[A-Za-z_][A-Za-z0-9_]*$` — no
|
|
144
|
+
`schema.` prefix.
|
|
145
|
+
- `node:sqlite` is synchronous: each call blocks the event loop while it runs.
|
|
146
|
+
- Multi-statement operations (`getSet`, `incr`/`decr`, `setMultiple`, `clear`,
|
|
147
|
+
`transaction`) run in `BEGIN IMMEDIATE`. Called inside a transaction you opened on the
|
|
148
|
+
same handle, they use a savepoint instead, so your `COMMIT`/`ROLLBACK` decides.
|
|
149
|
+
- The adapter does not touch connection settings. For several processes on one file,
|
|
150
|
+
open it with a busy timeout (`new DatabaseSync(path, { timeout: 5000 })`) and consider
|
|
151
|
+
`PRAGMA journal_mode = WAL`.
|
|
152
|
+
- `cas()` compares the stored JSON text, so object key order matters (as with Memory and
|
|
153
|
+
Redis; PostgreSQL compares `jsonb`, which ignores key order).
|
|
154
|
+
- Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
|
|
155
|
+
|
|
130
156
|
### Memory
|
|
131
157
|
|
|
132
158
|
- Data is not persisted (in-memory only).
|
|
@@ -214,10 +240,10 @@ For complete API documentation including all methods, types, and adapter-specifi
|
|
|
214
240
|
Node LTS (`.node-version`), pnpm, Biome, `node:test`. The source is erasable-only
|
|
215
241
|
TypeScript that Node runs directly; `dist/` is built only for publishing.
|
|
216
242
|
|
|
217
|
-
Every test runs against all
|
|
218
|
-
Redis. Copy `.env.example` to `.env` and fill
|
|
219
|
-
|
|
220
|
-
default is `/13`).
|
|
243
|
+
Every test runs against all four adapters, so `pnpm test` needs a running PostgreSQL and
|
|
244
|
+
Redis (SQLite runs in memory, nothing to set up). Copy `.env.example` to `.env` and fill
|
|
245
|
+
in the connection details. Redis keys in the target database are deleted before each
|
|
246
|
+
test, so point it at a scratch database (the default is `/13`).
|
|
221
247
|
|
|
222
248
|
| Command | Does |
|
|
223
249
|
| ----------------------------------- | -------------------------------------------------- |
|
|
@@ -15,7 +15,7 @@ export interface SetOptions extends Record<string, any> {
|
|
|
15
15
|
* Information about the adapter instance.
|
|
16
16
|
*/
|
|
17
17
|
export interface AdapterInfo {
|
|
18
|
-
/** The adapter type identifier (e.g., "redis", "postgres", "memory"). */
|
|
18
|
+
/** The adapter type identifier (e.g., "redis", "postgres", "sqlite", "memory"). */
|
|
19
19
|
type: string;
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
@@ -323,7 +323,7 @@ export declare abstract class AdapterAbstract {
|
|
|
323
323
|
/**
|
|
324
324
|
* Retrieves multiple values in a single batch operation.
|
|
325
325
|
*
|
|
326
|
-
* More efficient than multiple individual `get` calls, especially for Redis and
|
|
326
|
+
* More efficient than multiple individual `get` calls, especially for Redis, PostgreSQL and SQLite.
|
|
327
327
|
*
|
|
328
328
|
* @param keys - An array of keys to retrieve.
|
|
329
329
|
* @returns A promise that resolves to an object mapping keys to their values.
|
|
@@ -339,7 +339,7 @@ export declare abstract class AdapterAbstract {
|
|
|
339
339
|
/**
|
|
340
340
|
* Executes multiple operations within a single transaction.
|
|
341
341
|
*
|
|
342
|
-
* For adapters that support it (Redis, PostgreSQL), operations are atomic.
|
|
342
|
+
* For adapters that support it (Redis, PostgreSQL, SQLite), operations are atomic.
|
|
343
343
|
* For memory, operations are executed sequentially.
|
|
344
344
|
*
|
|
345
345
|
* @param operations - An array of operations to execute.
|
|
@@ -393,7 +393,7 @@ export declare abstract class AdapterAbstract {
|
|
|
393
393
|
* @example
|
|
394
394
|
* ```typescript
|
|
395
395
|
* const info = client.info();
|
|
396
|
-
* console.log(info.type); // "redis", "postgres", or "memory"
|
|
396
|
+
* console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
|
|
397
397
|
* ```
|
|
398
398
|
*/
|
|
399
399
|
info(): AdapterInfo;
|
package/dist/adapter/abstract.js
CHANGED
|
@@ -302,7 +302,7 @@ export class AdapterAbstract {
|
|
|
302
302
|
/**
|
|
303
303
|
* Retrieves multiple values in a single batch operation.
|
|
304
304
|
*
|
|
305
|
-
* More efficient than multiple individual `get` calls, especially for Redis and
|
|
305
|
+
* More efficient than multiple individual `get` calls, especially for Redis, PostgreSQL and SQLite.
|
|
306
306
|
*
|
|
307
307
|
* @param keys - An array of keys to retrieve.
|
|
308
308
|
* @returns A promise that resolves to an object mapping keys to their values.
|
|
@@ -320,7 +320,7 @@ export class AdapterAbstract {
|
|
|
320
320
|
/**
|
|
321
321
|
* Executes multiple operations within a single transaction.
|
|
322
322
|
*
|
|
323
|
-
* For adapters that support it (Redis, PostgreSQL), operations are atomic.
|
|
323
|
+
* For adapters that support it (Redis, PostgreSQL, SQLite), operations are atomic.
|
|
324
324
|
* For memory, operations are executed sequentially.
|
|
325
325
|
*
|
|
326
326
|
* @param operations - An array of operations to execute.
|
|
@@ -380,7 +380,7 @@ export class AdapterAbstract {
|
|
|
380
380
|
* @example
|
|
381
381
|
* ```typescript
|
|
382
382
|
* const info = client.info();
|
|
383
|
-
* console.log(info.type); // "redis", "postgres", or "memory"
|
|
383
|
+
* console.log(info.type); // "redis", "postgres", "sqlite", or "memory"
|
|
384
384
|
* ```
|
|
385
385
|
*/
|
|
386
386
|
info() {
|
package/dist/adapter/memory.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export interface AdapterMemoryOptions extends AdapterAbstractOptions {
|
|
|
12
12
|
* Interval in seconds for automatic cleanup of expired keys.
|
|
13
13
|
* Set to 0 to disable automatic cleanup (expired keys will still be
|
|
14
14
|
* lazily removed on access).
|
|
15
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
15
16
|
*/
|
|
16
17
|
ttlCleanupIntervalSec: number;
|
|
17
18
|
}
|
package/dist/adapter/memory.js
CHANGED
|
@@ -67,6 +67,9 @@ export class AdapterMemory extends AdapterAbstract {
|
|
|
67
67
|
}
|
|
68
68
|
// schedule next...
|
|
69
69
|
this.#cleanupTimer = setTimeout(this.#maybeTTLCleanup.bind(this), this.options.ttlCleanupIntervalSec * 1000);
|
|
70
|
+
// housekeeping must not hold the process open; destroy() still clears it
|
|
71
|
+
// (`?.`: browser and worker timers are plain numbers)
|
|
72
|
+
this.#cleanupTimer.unref?.();
|
|
70
73
|
}
|
|
71
74
|
}
|
|
72
75
|
#isExpired(key) {
|
|
@@ -22,6 +22,7 @@ export interface AdapterPostgresOptions extends AdapterAbstractOptions {
|
|
|
22
22
|
/**
|
|
23
23
|
* Interval in seconds for automatic cleanup of expired keys.
|
|
24
24
|
* Set to 0 to disable automatic cleanup.
|
|
25
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
25
26
|
*/
|
|
26
27
|
ttlCleanupIntervalSec: number;
|
|
27
28
|
}
|
package/dist/adapter/postgres.js
CHANGED
|
@@ -65,14 +65,15 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
65
65
|
}
|
|
66
66
|
/** @inheritdoc */
|
|
67
67
|
async destroy(hard) {
|
|
68
|
-
// stop the timer first so a pending tick cannot fire during DROP
|
|
68
|
+
// stop the timer first so a pending tick cannot fire during DROP, and mark the
|
|
69
|
+
// adapter down before any await so an in-flight tick does not re-arm it
|
|
69
70
|
clearTimeout(this.#cleanupTimer);
|
|
70
71
|
this.#cleanupTimer = undefined;
|
|
72
|
+
this._initialized = false;
|
|
71
73
|
if (hard) {
|
|
72
74
|
const { db, tableName } = this.options;
|
|
73
75
|
await db.query(`DROP TABLE IF EXISTS ${tableName}`);
|
|
74
76
|
}
|
|
75
|
-
this._initialized = false;
|
|
76
77
|
}
|
|
77
78
|
async #maybeTTLCleanup() {
|
|
78
79
|
clearTimeout(this.#cleanupTimer); // safety
|
|
@@ -87,8 +88,14 @@ export class AdapterPostgres extends AdapterAbstract {
|
|
|
87
88
|
catch (err) {
|
|
88
89
|
logger?.error?.(`TTL cleanup error: ${err}`);
|
|
89
90
|
}
|
|
91
|
+
// destroy() ran while the query was in flight
|
|
92
|
+
if (!this._initialized)
|
|
93
|
+
return;
|
|
90
94
|
// schedule next...
|
|
91
95
|
this.#cleanupTimer = setTimeout(this.#maybeTTLCleanup.bind(this), this.options.ttlCleanupIntervalSec * 1000);
|
|
96
|
+
// housekeeping must not hold the process open; destroy() still clears it
|
|
97
|
+
// (`?.`: browser and worker timers are plain numbers)
|
|
98
|
+
this.#cleanupTimer.unref?.();
|
|
92
99
|
}
|
|
93
100
|
}
|
|
94
101
|
/**
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* SQLite key-value storage adapter implementation (`node:sqlite`).
|
|
5
|
+
*/
|
|
6
|
+
import type { DatabaseSync } from "node:sqlite";
|
|
7
|
+
import { AdapterAbstract, type AdapterAbstractOptions, type Operation, type SetMultipleEntry, type SetOptions, type TtlResult } from "./abstract.ts";
|
|
8
|
+
/**
|
|
9
|
+
* Configuration options for the SQLite KV adapter.
|
|
10
|
+
*/
|
|
11
|
+
export interface AdapterSqliteOptions extends AdapterAbstractOptions {
|
|
12
|
+
/**
|
|
13
|
+
* An open `node:sqlite` database, e.g. `new DatabaseSync("kv.db")`. The caller owns
|
|
14
|
+
* it: `destroy()` never closes it, so one handle can be shared across adapters.
|
|
15
|
+
*/
|
|
16
|
+
db: DatabaseSync;
|
|
17
|
+
/**
|
|
18
|
+
* Name of the table to use for storing key-value pairs.
|
|
19
|
+
* The table will be created automatically if it doesn't exist.
|
|
20
|
+
* Only word characters are allowed (no `schema.` prefix).
|
|
21
|
+
* @default "__kv"
|
|
22
|
+
*/
|
|
23
|
+
tableName: string;
|
|
24
|
+
/**
|
|
25
|
+
* Interval in seconds for automatic cleanup of expired keys.
|
|
26
|
+
* Set to 0 to disable automatic cleanup.
|
|
27
|
+
* The timer never keeps the process alive; `destroy()` stops it.
|
|
28
|
+
*/
|
|
29
|
+
ttlCleanupIntervalSec: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* SQLite key-value storage adapter.
|
|
33
|
+
*
|
|
34
|
+
* Provides persistent key-value storage on a `node:sqlite` database: values are JSON
|
|
35
|
+
* text, expirations are epoch milliseconds. Automatically creates the required table
|
|
36
|
+
* and index on initialization.
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
* - `node:sqlite` is synchronous, so every operation blocks the event loop for its
|
|
40
|
+
* duration (typically microseconds) and nothing else on the handle interleaves.
|
|
41
|
+
* - Multi-statement operations run in `BEGIN IMMEDIATE`, so they stay atomic against
|
|
42
|
+
* other connections and processes on the same file. Inside a transaction the caller
|
|
43
|
+
* already opened on the same handle, they use a savepoint instead.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { DatabaseSync } from "node:sqlite";
|
|
48
|
+
*
|
|
49
|
+
* const client = createKVClient("myapp:", "sqlite", {
|
|
50
|
+
* db: new DatabaseSync("kv.db"),
|
|
51
|
+
* });
|
|
52
|
+
* await client.initialize();
|
|
53
|
+
* await client.set("session:abc", { userId: 123 }, { ttl: 3600 });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare class AdapterSqlite extends AdapterAbstract {
|
|
57
|
+
#private;
|
|
58
|
+
_type: string;
|
|
59
|
+
readonly options: AdapterSqliteOptions;
|
|
60
|
+
constructor(namespace?: string, options?: Partial<AdapterSqliteOptions>);
|
|
61
|
+
/** @inheritdoc */
|
|
62
|
+
initialize(): Promise<void>;
|
|
63
|
+
/** @inheritdoc */
|
|
64
|
+
destroy(hard?: boolean): Promise<void>;
|
|
65
|
+
/** @inheritdoc */
|
|
66
|
+
set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
|
|
67
|
+
/** @inheritdoc */
|
|
68
|
+
setIfAbsent(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
|
|
69
|
+
/** @inheritdoc */
|
|
70
|
+
getSet(key: string, value: any, options?: Partial<SetOptions>): Promise<any>;
|
|
71
|
+
/** @inheritdoc */
|
|
72
|
+
incr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
|
|
73
|
+
/** @inheritdoc */
|
|
74
|
+
decr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
|
|
75
|
+
/** @inheritdoc */
|
|
76
|
+
cas(key: string, expected: any, next: any, options?: Partial<SetOptions>): Promise<boolean>;
|
|
77
|
+
/** @inheritdoc */
|
|
78
|
+
get(key: string): Promise<any>;
|
|
79
|
+
/** @inheritdoc */
|
|
80
|
+
delete(key: string): Promise<boolean>;
|
|
81
|
+
/** @inheritdoc */
|
|
82
|
+
exists(key: string): Promise<boolean>;
|
|
83
|
+
/** @inheritdoc */
|
|
84
|
+
keys(pattern: string): Promise<string[]>;
|
|
85
|
+
/** @inheritdoc */
|
|
86
|
+
keysIter(pattern: string): AsyncIterable<string>;
|
|
87
|
+
/** @inheritdoc */
|
|
88
|
+
clear(pattern: string): Promise<number>;
|
|
89
|
+
/** @inheritdoc */
|
|
90
|
+
setMultiple(entries: readonly SetMultipleEntry[], options?: Partial<SetOptions>): Promise<boolean[]>;
|
|
91
|
+
/** @inheritdoc */
|
|
92
|
+
getMultiple(keys: string[]): Promise<Record<string, any>>;
|
|
93
|
+
/** @inheritdoc */
|
|
94
|
+
expire(key: string, ttl: number): Promise<boolean>;
|
|
95
|
+
/** @inheritdoc */
|
|
96
|
+
ttl(key: string): Promise<TtlResult>;
|
|
97
|
+
/** @inheritdoc */
|
|
98
|
+
transaction(operations: Operation[]): Promise<any[]>;
|
|
99
|
+
__debug_dump(): Promise<Record<string, {
|
|
100
|
+
value: any;
|
|
101
|
+
ttl: Date | null;
|
|
102
|
+
}>>;
|
|
103
|
+
}
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
*
|
|
4
|
+
* SQLite key-value storage adapter implementation (`node:sqlite`).
|
|
5
|
+
*/
|
|
6
|
+
import { createClog } from "@marianmeres/clog";
|
|
7
|
+
import { AdapterAbstract, } from "./abstract.js";
|
|
8
|
+
/** Rows fetched per page by {@link AdapterSqlite.keysIter}. */
|
|
9
|
+
const KEYS_ITER_PAGE = 500;
|
|
10
|
+
/** A row is live when it has no expiry or expires after the bound `now` (epoch ms). */
|
|
11
|
+
const LIVE = "(expires_at IS NULL OR expires_at > ?)";
|
|
12
|
+
/**
|
|
13
|
+
* SQLite key-value storage adapter.
|
|
14
|
+
*
|
|
15
|
+
* Provides persistent key-value storage on a `node:sqlite` database: values are JSON
|
|
16
|
+
* text, expirations are epoch milliseconds. Automatically creates the required table
|
|
17
|
+
* and index on initialization.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* - `node:sqlite` is synchronous, so every operation blocks the event loop for its
|
|
21
|
+
* duration (typically microseconds) and nothing else on the handle interleaves.
|
|
22
|
+
* - Multi-statement operations run in `BEGIN IMMEDIATE`, so they stay atomic against
|
|
23
|
+
* other connections and processes on the same file. Inside a transaction the caller
|
|
24
|
+
* already opened on the same handle, they use a savepoint instead.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* import { DatabaseSync } from "node:sqlite";
|
|
29
|
+
*
|
|
30
|
+
* const client = createKVClient("myapp:", "sqlite", {
|
|
31
|
+
* db: new DatabaseSync("kv.db"),
|
|
32
|
+
* });
|
|
33
|
+
* await client.initialize();
|
|
34
|
+
* await client.set("session:abc", { userId: 123 }, { ttl: 3600 });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export class AdapterSqlite extends AdapterAbstract {
|
|
38
|
+
_type = "sqlite";
|
|
39
|
+
options = {
|
|
40
|
+
defaultTtl: 0, // no ttl by default
|
|
41
|
+
logger: createClog("KV/sqlite"),
|
|
42
|
+
db: null, // will be set in constructor via options merge
|
|
43
|
+
tableName: "__kv",
|
|
44
|
+
ttlCleanupIntervalSec: 0,
|
|
45
|
+
validateKeys: true,
|
|
46
|
+
};
|
|
47
|
+
#cleanupTimer;
|
|
48
|
+
/** Prepared statements by SQL text — a small, fixed set per adapter. */
|
|
49
|
+
#statements = new Map();
|
|
50
|
+
constructor(namespace = "", options = {}) {
|
|
51
|
+
super(namespace);
|
|
52
|
+
this.options = Object.freeze({ ...this.options, ...(options || {}) });
|
|
53
|
+
if (!this.options.db) {
|
|
54
|
+
throw new Error("Missing sqlite database instance");
|
|
55
|
+
}
|
|
56
|
+
// tableName is spliced into SQL verbatim, so guard against surprises.
|
|
57
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(this.options.tableName)) {
|
|
58
|
+
throw new Error(`Invalid tableName "${this.options.tableName}". Only word characters are allowed.`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
#stmt(sql) {
|
|
62
|
+
let stmt = this.#statements.get(sql);
|
|
63
|
+
if (!stmt) {
|
|
64
|
+
stmt = this.options.db.prepare(sql);
|
|
65
|
+
this.#statements.set(sql, stmt);
|
|
66
|
+
}
|
|
67
|
+
return stmt;
|
|
68
|
+
}
|
|
69
|
+
#expiresAt(ttl) {
|
|
70
|
+
return ttl ? Math.round(Date.now() + ttl * 1000) : null;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Runs `fn` as one unit: `BEGIN IMMEDIATE` takes the write lock up front, so no other
|
|
74
|
+
* connection can write between its statements. Inside a transaction the caller opened
|
|
75
|
+
* on this handle, a savepoint keeps `fn` all-or-nothing without committing theirs.
|
|
76
|
+
* `fn` must stay synchronous — an `await` inside would let other work join the
|
|
77
|
+
* transaction.
|
|
78
|
+
*/
|
|
79
|
+
#atomic(fn) {
|
|
80
|
+
const { db, logger } = this.options;
|
|
81
|
+
const [begin, commit, rollback] = db.isTransaction
|
|
82
|
+
? ["SAVEPOINT kv_atomic", "RELEASE kv_atomic", "ROLLBACK TO kv_atomic"]
|
|
83
|
+
: ["BEGIN IMMEDIATE", "COMMIT", "ROLLBACK"];
|
|
84
|
+
db.exec(begin);
|
|
85
|
+
try {
|
|
86
|
+
const result = fn();
|
|
87
|
+
db.exec(commit);
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
try {
|
|
92
|
+
db.exec(rollback);
|
|
93
|
+
// a savepoint survives ROLLBACK TO; release it to leave the caller's
|
|
94
|
+
// transaction exactly as it was
|
|
95
|
+
if (begin.startsWith("SAVEPOINT"))
|
|
96
|
+
db.exec(commit);
|
|
97
|
+
}
|
|
98
|
+
catch (rollbackErr) {
|
|
99
|
+
logger?.error?.(`Rollback failed: ${rollbackErr}`);
|
|
100
|
+
}
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** @inheritdoc */
|
|
105
|
+
async initialize() {
|
|
106
|
+
const { db, tableName } = this.options;
|
|
107
|
+
db.exec(`
|
|
108
|
+
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
109
|
+
key TEXT NOT NULL PRIMARY KEY,
|
|
110
|
+
value TEXT NOT NULL,
|
|
111
|
+
expires_at INTEGER
|
|
112
|
+
)
|
|
113
|
+
`);
|
|
114
|
+
db.exec(`
|
|
115
|
+
CREATE INDEX IF NOT EXISTS idx_${tableName}_expires_at
|
|
116
|
+
ON ${tableName} (expires_at)
|
|
117
|
+
WHERE expires_at IS NOT NULL
|
|
118
|
+
`);
|
|
119
|
+
this._initialized = true;
|
|
120
|
+
this.#maybeTTLCleanup();
|
|
121
|
+
}
|
|
122
|
+
/** @inheritdoc */
|
|
123
|
+
async destroy(hard) {
|
|
124
|
+
// stop the timer first so a pending tick cannot fire during DROP
|
|
125
|
+
clearTimeout(this.#cleanupTimer);
|
|
126
|
+
this.#cleanupTimer = undefined;
|
|
127
|
+
this.#statements.clear();
|
|
128
|
+
if (hard) {
|
|
129
|
+
const { db, tableName } = this.options;
|
|
130
|
+
db.exec(`DROP TABLE IF EXISTS ${tableName}`);
|
|
131
|
+
}
|
|
132
|
+
this._initialized = false;
|
|
133
|
+
}
|
|
134
|
+
#maybeTTLCleanup() {
|
|
135
|
+
clearTimeout(this.#cleanupTimer); // safety
|
|
136
|
+
if (this.options.ttlCleanupIntervalSec) {
|
|
137
|
+
const { db, tableName, logger } = this.options;
|
|
138
|
+
// The caller closed the handle without destroy(). Every later tick would fail
|
|
139
|
+
// the same way, so say it once and stop.
|
|
140
|
+
if (!db.isOpen) {
|
|
141
|
+
logger?.error?.("TTL cleanup stopped: the database handle was closed before destroy()");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
// do the cleanup now
|
|
145
|
+
try {
|
|
146
|
+
this.#stmt(`DELETE FROM ${tableName}
|
|
147
|
+
WHERE expires_at IS NOT NULL AND expires_at <= ?`).run(Date.now());
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
logger?.error?.(`TTL cleanup error: ${err}`);
|
|
151
|
+
}
|
|
152
|
+
// schedule next...
|
|
153
|
+
this.#cleanupTimer = setTimeout(this.#maybeTTLCleanup.bind(this), this.options.ttlCleanupIntervalSec * 1000);
|
|
154
|
+
// housekeeping must not hold the process open; destroy() still clears it
|
|
155
|
+
// (`?.`: browser and worker timers are plain numbers)
|
|
156
|
+
this.#cleanupTimer.unref?.();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Convert a Redis-style glob to an SQLite GLOB pattern. GLOB already reads `*` and `?`
|
|
161
|
+
* as wildcards; its one other metacharacter, `[`, is made literal as `[[]`. Unlike
|
|
162
|
+
* LIKE, GLOB is case-sensitive and can use the primary-key index for a literal prefix.
|
|
163
|
+
*/
|
|
164
|
+
#globPattern(pattern) {
|
|
165
|
+
return pattern.replace(/\[/g, "[[]");
|
|
166
|
+
}
|
|
167
|
+
#withNsGlob(pattern) {
|
|
168
|
+
// namespace is a literal prefix — its own `*`/`?`/`[` must be escaped too
|
|
169
|
+
const ns = this.namespace.replace(/[*?[]/g, "[$&]");
|
|
170
|
+
return ns + this.#globPattern(pattern);
|
|
171
|
+
}
|
|
172
|
+
#upsertSql() {
|
|
173
|
+
return `INSERT INTO ${this.options.tableName} (key, value, expires_at)
|
|
174
|
+
VALUES (?, ?, ?)
|
|
175
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
176
|
+
value = excluded.value,
|
|
177
|
+
expires_at = excluded.expires_at`;
|
|
178
|
+
}
|
|
179
|
+
#set(key, value, options = {}) {
|
|
180
|
+
this._assertInitialized();
|
|
181
|
+
this.#stmt(this.#upsertSql()).run(this._withNs(key), JSON.stringify(value ?? null), this.#expiresAt(this._resolveTtl(options)));
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
/** @inheritdoc */
|
|
185
|
+
async set(key, value, options = {}) {
|
|
186
|
+
return this.#set(key, value, options);
|
|
187
|
+
}
|
|
188
|
+
/** @inheritdoc */
|
|
189
|
+
async setIfAbsent(key, value, options = {}) {
|
|
190
|
+
this._assertInitialized();
|
|
191
|
+
const nsKey = this._withNs(key);
|
|
192
|
+
// INSERT on new keys; UPDATE only when the existing row is expired.
|
|
193
|
+
// (Live keys stay untouched — the hallmark of setIfAbsent.)
|
|
194
|
+
const { changes } = this.#stmt(`${this.#upsertSql()}
|
|
195
|
+
WHERE expires_at IS NOT NULL AND expires_at <= ?`).run(nsKey, JSON.stringify(value ?? null), this.#expiresAt(this._resolveTtl(options)), Date.now());
|
|
196
|
+
return Number(changes) > 0;
|
|
197
|
+
}
|
|
198
|
+
/** @inheritdoc */
|
|
199
|
+
async getSet(key, value, options = {}) {
|
|
200
|
+
this._assertInitialized();
|
|
201
|
+
return this.#atomic(() => {
|
|
202
|
+
const previous = this.#get(key);
|
|
203
|
+
this.#set(key, value, options);
|
|
204
|
+
return previous;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
#incrBy(key, delta, options = {}) {
|
|
208
|
+
this._assertInitialized();
|
|
209
|
+
const nsKey = this._withNs(key);
|
|
210
|
+
const { tableName } = this.options;
|
|
211
|
+
// Read-modify-write in JS, so the arithmetic is exactly the memory adapter's.
|
|
212
|
+
return this.#atomic(() => {
|
|
213
|
+
const row = this.#stmt(`SELECT value FROM ${tableName} WHERE key = ? AND ${LIVE}`).get(nsKey, Date.now());
|
|
214
|
+
// - New key OR expired key: value = delta, expires_at = $ttl
|
|
215
|
+
// - Live key: value = old + delta, preserve existing expires_at
|
|
216
|
+
if (!row) {
|
|
217
|
+
this.#stmt(this.#upsertSql()).run(nsKey, JSON.stringify(delta), this.#expiresAt(this._resolveTtl(options)));
|
|
218
|
+
return delta;
|
|
219
|
+
}
|
|
220
|
+
const current = JSON.parse(row.value);
|
|
221
|
+
if (typeof current !== "number") {
|
|
222
|
+
throw new TypeError("KV value is not a number");
|
|
223
|
+
}
|
|
224
|
+
const next = current + delta;
|
|
225
|
+
this.#stmt(`UPDATE ${tableName} SET value = ? WHERE key = ?`).run(JSON.stringify(next), nsKey);
|
|
226
|
+
return next;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** @inheritdoc */
|
|
230
|
+
async incr(key, by = 1, options = {}) {
|
|
231
|
+
return this.#incrBy(key, by, options);
|
|
232
|
+
}
|
|
233
|
+
/** @inheritdoc */
|
|
234
|
+
async decr(key, by = 1, options = {}) {
|
|
235
|
+
return this.#incrBy(key, -by, options);
|
|
236
|
+
}
|
|
237
|
+
/** @inheritdoc */
|
|
238
|
+
async cas(key, expected, next, options = {}) {
|
|
239
|
+
this._assertInitialized();
|
|
240
|
+
const nsKey = this._withNs(key);
|
|
241
|
+
const { tableName } = this.options;
|
|
242
|
+
const hasTtl = options.ttl !== undefined;
|
|
243
|
+
// Stored values are `JSON.stringify` output, so comparing the text is comparing
|
|
244
|
+
// the values — with the memory and Redis adapters' key-order sensitivity.
|
|
245
|
+
const params = [JSON.stringify(next ?? null)];
|
|
246
|
+
if (hasTtl)
|
|
247
|
+
params.push(this.#expiresAt(this._resolveTtl(options)));
|
|
248
|
+
params.push(nsKey, JSON.stringify(expected ?? null), Date.now());
|
|
249
|
+
const { changes } = this.#stmt(`UPDATE ${tableName}
|
|
250
|
+
SET value = ?${hasTtl ? ", expires_at = ?" : ""}
|
|
251
|
+
WHERE key = ? AND value = ? AND ${LIVE}`).run(...params);
|
|
252
|
+
return Number(changes) > 0;
|
|
253
|
+
}
|
|
254
|
+
#get(key) {
|
|
255
|
+
this._assertInitialized();
|
|
256
|
+
const row = this.#stmt(`SELECT value FROM ${this.options.tableName} WHERE key = ? AND ${LIVE}`).get(this._withNs(key), Date.now());
|
|
257
|
+
return row ? JSON.parse(row.value) : null;
|
|
258
|
+
}
|
|
259
|
+
/** @inheritdoc */
|
|
260
|
+
async get(key) {
|
|
261
|
+
return this.#get(key);
|
|
262
|
+
}
|
|
263
|
+
#delete(key) {
|
|
264
|
+
this._assertInitialized();
|
|
265
|
+
const { changes } = this.#stmt(`DELETE FROM ${this.options.tableName} WHERE key = ?`).run(this._withNs(key));
|
|
266
|
+
return Number(changes) > 0;
|
|
267
|
+
}
|
|
268
|
+
/** @inheritdoc */
|
|
269
|
+
async delete(key) {
|
|
270
|
+
return this.#delete(key);
|
|
271
|
+
}
|
|
272
|
+
/** @inheritdoc */
|
|
273
|
+
async exists(key) {
|
|
274
|
+
this._assertInitialized();
|
|
275
|
+
const row = this.#stmt(`SELECT 1 FROM ${this.options.tableName} WHERE key = ? AND ${LIVE}`).get(this._withNs(key), Date.now());
|
|
276
|
+
return row !== undefined;
|
|
277
|
+
}
|
|
278
|
+
/** @inheritdoc */
|
|
279
|
+
async keys(pattern) {
|
|
280
|
+
this._assertInitialized();
|
|
281
|
+
const rows = this.#stmt(`SELECT key FROM ${this.options.tableName}
|
|
282
|
+
WHERE key GLOB ? AND ${LIVE}
|
|
283
|
+
ORDER BY key`).all(this.#withNsGlob(pattern), Date.now());
|
|
284
|
+
return rows.map((row) => this._withoutNs(row.key)).toSorted();
|
|
285
|
+
}
|
|
286
|
+
/** @inheritdoc */
|
|
287
|
+
async *keysIter(pattern) {
|
|
288
|
+
this._assertInitialized();
|
|
289
|
+
const { tableName } = this.options;
|
|
290
|
+
const glob = this.#withNsGlob(pattern);
|
|
291
|
+
// Keyset pages instead of one open statement: nothing is left open (no read
|
|
292
|
+
// snapshot held) while the consumer awaits between yields, and an early break
|
|
293
|
+
// leaves nothing to release.
|
|
294
|
+
let after;
|
|
295
|
+
while (true) {
|
|
296
|
+
const rows = (after === undefined
|
|
297
|
+
? this.#stmt(`SELECT key FROM ${tableName}
|
|
298
|
+
WHERE key GLOB ? AND ${LIVE}
|
|
299
|
+
ORDER BY key LIMIT ${KEYS_ITER_PAGE}`).all(glob, Date.now())
|
|
300
|
+
: this.#stmt(`SELECT key FROM ${tableName}
|
|
301
|
+
WHERE key GLOB ? AND key > ? AND ${LIVE}
|
|
302
|
+
ORDER BY key LIMIT ${KEYS_ITER_PAGE}`).all(glob, after, Date.now()));
|
|
303
|
+
for (const row of rows) {
|
|
304
|
+
yield this._withoutNs(row.key);
|
|
305
|
+
}
|
|
306
|
+
if (rows.length < KEYS_ITER_PAGE)
|
|
307
|
+
return;
|
|
308
|
+
after = rows[rows.length - 1].key;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** @inheritdoc */
|
|
312
|
+
async clear(pattern) {
|
|
313
|
+
this._assertInitialized();
|
|
314
|
+
const { tableName } = this.options;
|
|
315
|
+
const glob = this.#withNsGlob(pattern);
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
return this.#atomic(() => {
|
|
318
|
+
const { changes } = this.#stmt(`DELETE FROM ${tableName} WHERE key GLOB ? AND ${LIVE}`).run(glob, now);
|
|
319
|
+
// expired rows under the pattern are already invisible; drop them too, but
|
|
320
|
+
// don't count them
|
|
321
|
+
this.#stmt(`DELETE FROM ${tableName}
|
|
322
|
+
WHERE key GLOB ? AND expires_at IS NOT NULL AND expires_at <= ?`).run(glob, now);
|
|
323
|
+
return Number(changes);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
/** @inheritdoc */
|
|
327
|
+
async setMultiple(entries, options = {}) {
|
|
328
|
+
this._assertInitialized();
|
|
329
|
+
if (entries.length === 0)
|
|
330
|
+
return [];
|
|
331
|
+
// validate every key before writing any
|
|
332
|
+
const rows = this._normalizePairs(entries).map(({ key, value, ttl }) => [
|
|
333
|
+
this._withNs(key),
|
|
334
|
+
JSON.stringify(value ?? null),
|
|
335
|
+
this.#expiresAt(this._resolveTtl({ ttl: ttl ?? options.ttl })),
|
|
336
|
+
]);
|
|
337
|
+
// one transaction: all-or-nothing, and a single commit instead of one per row
|
|
338
|
+
this.#atomic(() => {
|
|
339
|
+
const upsert = this.#stmt(this.#upsertSql());
|
|
340
|
+
for (const params of rows)
|
|
341
|
+
upsert.run(...params);
|
|
342
|
+
});
|
|
343
|
+
return rows.map(() => true);
|
|
344
|
+
}
|
|
345
|
+
/** @inheritdoc */
|
|
346
|
+
async getMultiple(keys) {
|
|
347
|
+
this._assertInitialized();
|
|
348
|
+
if (keys.length === 0)
|
|
349
|
+
return {};
|
|
350
|
+
// one JSON-array parameter instead of N placeholders: no bound-variable limit,
|
|
351
|
+
// and a single cached statement for every batch size
|
|
352
|
+
const rows = this.#stmt(`SELECT key, value FROM ${this.options.tableName}
|
|
353
|
+
WHERE key IN (SELECT j.value FROM json_each(?) AS j) AND ${LIVE}`).all(JSON.stringify(keys.map((k) => this._withNs(k))), Date.now());
|
|
354
|
+
const found = Object.create(null);
|
|
355
|
+
for (const row of rows) {
|
|
356
|
+
found[this._withoutNs(row.key)] = JSON.parse(row.value);
|
|
357
|
+
}
|
|
358
|
+
// preserve explicit null / false / 0 / "" — missing keys become null
|
|
359
|
+
const resultMap = {};
|
|
360
|
+
for (const key of keys) {
|
|
361
|
+
resultMap[key] = key in found ? found[key] : null;
|
|
362
|
+
}
|
|
363
|
+
return resultMap;
|
|
364
|
+
}
|
|
365
|
+
/** @inheritdoc */
|
|
366
|
+
async expire(key, ttl) {
|
|
367
|
+
this._assertInitialized();
|
|
368
|
+
const { changes } = this.#stmt(`UPDATE ${this.options.tableName}
|
|
369
|
+
SET expires_at = ?
|
|
370
|
+
WHERE key = ? AND ${LIVE}`).run(Math.round(Date.now() + ttl * 1000), this._withNs(key), Date.now());
|
|
371
|
+
return Number(changes) > 0;
|
|
372
|
+
}
|
|
373
|
+
/** @inheritdoc */
|
|
374
|
+
async ttl(key) {
|
|
375
|
+
this._assertInitialized();
|
|
376
|
+
const row = this.#stmt(`SELECT expires_at FROM ${this.options.tableName} WHERE key = ?`).get(this._withNs(key));
|
|
377
|
+
if (!row)
|
|
378
|
+
return { state: "missing" };
|
|
379
|
+
if (row.expires_at === null)
|
|
380
|
+
return { state: "no-ttl" };
|
|
381
|
+
// expired-but-not-yet-cleaned counts as missing (matches get() filter)
|
|
382
|
+
const at = new Date(Number(row.expires_at));
|
|
383
|
+
if (at.valueOf() <= Date.now())
|
|
384
|
+
return { state: "missing" };
|
|
385
|
+
return { state: "expires", at };
|
|
386
|
+
}
|
|
387
|
+
/** @inheritdoc */
|
|
388
|
+
async transaction(operations) {
|
|
389
|
+
this._assertInitialized();
|
|
390
|
+
return this.#atomic(() => {
|
|
391
|
+
const results = [];
|
|
392
|
+
for (const op of operations) {
|
|
393
|
+
switch (op.type) {
|
|
394
|
+
case "set":
|
|
395
|
+
results.push(this.#set(op.key, op.value, op.options || {}));
|
|
396
|
+
break;
|
|
397
|
+
case "get":
|
|
398
|
+
results.push(this.#get(op.key));
|
|
399
|
+
break;
|
|
400
|
+
case "delete":
|
|
401
|
+
results.push(this.#delete(op.key));
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return results;
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
async __debug_dump() {
|
|
409
|
+
this._assertInitialized();
|
|
410
|
+
const rows = this.#stmt(`SELECT key, value, expires_at FROM ${this.options.tableName} WHERE key GLOB ?`).all(this.#withNsGlob("*"));
|
|
411
|
+
return rows.reduce((m, row) => {
|
|
412
|
+
m[this._withoutNs(row.key)] = {
|
|
413
|
+
value: JSON.parse(row.value),
|
|
414
|
+
ttl: row.expires_at === null ? null : new Date(Number(row.expires_at)),
|
|
415
|
+
};
|
|
416
|
+
return m;
|
|
417
|
+
}, {});
|
|
418
|
+
}
|
|
419
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/kv.d.ts
CHANGED
|
@@ -9,11 +9,13 @@
|
|
|
9
9
|
import { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.ts";
|
|
10
10
|
import { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.ts";
|
|
11
11
|
import { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.ts";
|
|
12
|
+
import { AdapterSqlite, type AdapterSqliteOptions } from "./adapter/sqlite.ts";
|
|
12
13
|
export type { AdapterAbstractOptions, AdapterInfo, Operation, SetMultipleEntry, SetOptions, TtlResult, } from "./adapter/abstract.ts";
|
|
13
14
|
export { AdapterAbstract } from "./adapter/abstract.ts";
|
|
14
15
|
export { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.ts";
|
|
15
16
|
export { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.ts";
|
|
16
17
|
export { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.ts";
|
|
18
|
+
export { AdapterSqlite, type AdapterSqliteOptions } from "./adapter/sqlite.ts";
|
|
17
19
|
export { sleep } from "./utils/sleep.ts";
|
|
18
20
|
/**
|
|
19
21
|
* Type mapping for all supported KV adapter types.
|
|
@@ -32,6 +34,10 @@ interface KnownTypes {
|
|
|
32
34
|
options: AdapterRedisOptions;
|
|
33
35
|
adapter: AdapterRedis;
|
|
34
36
|
};
|
|
37
|
+
sqlite: {
|
|
38
|
+
options: AdapterSqliteOptions;
|
|
39
|
+
adapter: AdapterSqlite;
|
|
40
|
+
};
|
|
35
41
|
}
|
|
36
42
|
/**
|
|
37
43
|
* Factory function to create a KV client with the specified adapter type.
|
|
@@ -47,6 +53,7 @@ interface KnownTypes {
|
|
|
47
53
|
* - `"memory"` - In-memory storage (default, not persisted)
|
|
48
54
|
* - `"redis"` - Redis server (requires `db` option with Redis client)
|
|
49
55
|
* - `"postgres"` - PostgreSQL database (requires `db` option with pg client/pool)
|
|
56
|
+
* - `"sqlite"` - SQLite database (requires `db` option with a `node:sqlite` `DatabaseSync`)
|
|
50
57
|
* @param options - Adapter-specific configuration options.
|
|
51
58
|
*
|
|
52
59
|
* @returns A configured adapter instance. Call `initialize()` before use.
|
|
@@ -72,6 +79,11 @@ interface KnownTypes {
|
|
|
72
79
|
* const pool = new pg.Pool({ connectionString: '...' });
|
|
73
80
|
* const postgres = createKVClient("myapp:", "postgres", { db: pool });
|
|
74
81
|
* await postgres.initialize();
|
|
82
|
+
*
|
|
83
|
+
* // SQLite storage
|
|
84
|
+
* import { DatabaseSync } from 'node:sqlite';
|
|
85
|
+
* const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
|
|
86
|
+
* await sqlite.initialize();
|
|
75
87
|
* ```
|
|
76
88
|
*/
|
|
77
89
|
export declare function createKVClient<T extends keyof KnownTypes>(namespace?: string, type?: T, options?: Partial<KnownTypes[T]["options"]>): KnownTypes[T]["adapter"];
|
package/dist/kv.js
CHANGED
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
import { AdapterMemory } from "./adapter/memory.js";
|
|
10
10
|
import { AdapterPostgres } from "./adapter/postgres.js";
|
|
11
11
|
import { AdapterRedis } from "./adapter/redis.js";
|
|
12
|
+
import { AdapterSqlite } from "./adapter/sqlite.js";
|
|
12
13
|
export { AdapterAbstract } from "./adapter/abstract.js";
|
|
13
14
|
export { AdapterMemory } from "./adapter/memory.js";
|
|
14
15
|
export { AdapterPostgres } from "./adapter/postgres.js";
|
|
15
16
|
export { AdapterRedis } from "./adapter/redis.js";
|
|
17
|
+
export { AdapterSqlite } from "./adapter/sqlite.js";
|
|
16
18
|
export { sleep } from "./utils/sleep.js";
|
|
17
19
|
/**
|
|
18
20
|
* Factory function to create a KV client with the specified adapter type.
|
|
@@ -28,6 +30,7 @@ export { sleep } from "./utils/sleep.js";
|
|
|
28
30
|
* - `"memory"` - In-memory storage (default, not persisted)
|
|
29
31
|
* - `"redis"` - Redis server (requires `db` option with Redis client)
|
|
30
32
|
* - `"postgres"` - PostgreSQL database (requires `db` option with pg client/pool)
|
|
33
|
+
* - `"sqlite"` - SQLite database (requires `db` option with a `node:sqlite` `DatabaseSync`)
|
|
31
34
|
* @param options - Adapter-specific configuration options.
|
|
32
35
|
*
|
|
33
36
|
* @returns A configured adapter instance. Call `initialize()` before use.
|
|
@@ -53,6 +56,11 @@ export { sleep } from "./utils/sleep.js";
|
|
|
53
56
|
* const pool = new pg.Pool({ connectionString: '...' });
|
|
54
57
|
* const postgres = createKVClient("myapp:", "postgres", { db: pool });
|
|
55
58
|
* await postgres.initialize();
|
|
59
|
+
*
|
|
60
|
+
* // SQLite storage
|
|
61
|
+
* import { DatabaseSync } from 'node:sqlite';
|
|
62
|
+
* const sqlite = createKVClient("myapp:", "sqlite", { db: new DatabaseSync("kv.db") });
|
|
63
|
+
* await sqlite.initialize();
|
|
56
64
|
* ```
|
|
57
65
|
*/
|
|
58
66
|
export function createKVClient(namespace = "", type = "memory", options = {}) {
|
|
@@ -63,6 +71,8 @@ export function createKVClient(namespace = "", type = "memory", options = {}) {
|
|
|
63
71
|
return new AdapterPostgres(namespace, options);
|
|
64
72
|
if (type === "redis")
|
|
65
73
|
return new AdapterRedis(namespace, options);
|
|
74
|
+
if (type === "sqlite")
|
|
75
|
+
return new AdapterSqlite(namespace, options);
|
|
66
76
|
//
|
|
67
77
|
throw new TypeError(`Unsupported KV client type "${type}"`);
|
|
68
78
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marianmeres/kv",
|
|
3
|
-
"version": "3.
|
|
4
|
-
"description": "Key-value storage abstraction with a unified, Redis-inspired API over memory, Redis and
|
|
3
|
+
"version": "3.1.1",
|
|
4
|
+
"description": "Key-value storage abstraction with a unified, Redis-inspired API over memory, Redis, PostgreSQL and SQLite backends.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Marian Meres",
|
|
7
7
|
"type": "module",
|
|
@@ -37,19 +37,20 @@
|
|
|
37
37
|
"redis",
|
|
38
38
|
"postgres",
|
|
39
39
|
"postgresql",
|
|
40
|
+
"sqlite",
|
|
40
41
|
"cache",
|
|
41
42
|
"ttl",
|
|
42
43
|
"storage"
|
|
43
44
|
],
|
|
44
45
|
"dependencies": {
|
|
45
|
-
"@marianmeres/clog": "^3.
|
|
46
|
-
"@types/pg": "^8.
|
|
47
|
-
"pg": "^8.
|
|
48
|
-
"redis": "^6.
|
|
46
|
+
"@marianmeres/clog": "^3.23.0",
|
|
47
|
+
"@types/pg": "^8.23.1",
|
|
48
|
+
"pg": "^8.23.1",
|
|
49
|
+
"redis": "^6.3.1"
|
|
49
50
|
},
|
|
50
51
|
"devDependencies": {
|
|
51
|
-
"@biomejs/biome": "^2.6.
|
|
52
|
-
"@types/node": "^26.6.
|
|
52
|
+
"@biomejs/biome": "^2.6.4",
|
|
53
|
+
"@types/node": "^26.6.6",
|
|
53
54
|
"typescript": "^7.0.2"
|
|
54
55
|
},
|
|
55
56
|
"scripts": {
|
|
@@ -62,6 +63,7 @@
|
|
|
62
63
|
"test:watch": "node --test --watch --env-file-if-exists=.env \"tests/**/*.test.ts\"",
|
|
63
64
|
"test:deno": "deno test -A --no-check --env-file tests/",
|
|
64
65
|
"ci": "pnpm run typecheck && pnpm run lint && pnpm test",
|
|
66
|
+
"jsr:check": "deno publish --dry-run --allow-dirty --no-check --set-version \"$npm_package_version\"",
|
|
65
67
|
"release": "npx --yes @marianmeres/release@^2.2.0",
|
|
66
68
|
"publish:jsr": "pnpm run test:deno && deno publish --no-check --set-version \"$npm_package_version\"",
|
|
67
69
|
"publish:all": "pnpm publish && pnpm run publish:jsr",
|