@cossackframework/database 0.7.7 → 0.8.0-manifestprobe.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/package.json +93 -21
- package/LICENSE +0 -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/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
|
-
}
|
package/src/create-database.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
}
|
package/src/dialects/d1.ts
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
// src/dialects/d1.ts
|
|
2
|
-
import {
|
|
3
|
-
SqliteAdapter,
|
|
4
|
-
SqliteQueryCompiler,
|
|
5
|
-
sql,
|
|
6
|
-
} from 'kysely';
|
|
7
|
-
import type {
|
|
8
|
-
CompiledQuery,
|
|
9
|
-
DatabaseConnection,
|
|
10
|
-
DatabaseMetadataOptions,
|
|
11
|
-
DatabaseIntrospector,
|
|
12
|
-
Dialect,
|
|
13
|
-
Driver,
|
|
14
|
-
Kysely,
|
|
15
|
-
QueryResult,
|
|
16
|
-
TableMetadata,
|
|
17
|
-
} from 'kysely';
|
|
18
|
-
import {
|
|
19
|
-
DEFAULT_MIGRATION_LOCK_TABLE,
|
|
20
|
-
DEFAULT_MIGRATION_TABLE,
|
|
21
|
-
} from 'kysely/migration';
|
|
22
|
-
import type { D1DatabaseLike } from '../types';
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Kysely's SQLite behavior with an explicit, duplicate-install-safe D1 brand.
|
|
26
|
-
*
|
|
27
|
-
* Consumers should inspect `cossackDialect` instead of relying on
|
|
28
|
-
* `instanceof` or constructor names, which can change across package copies
|
|
29
|
-
* and build tools.
|
|
30
|
-
*/
|
|
31
|
-
export class D1Adapter extends SqliteAdapter {
|
|
32
|
-
readonly cossackDialect = 'd1' as const;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Kysely {@link Dialect} for Cloudflare D1.
|
|
37
|
-
*
|
|
38
|
-
* Uses Kysely's SQLite query compiler/adapter/introspector and a custom driver
|
|
39
|
-
* that talks to the `D1Database` binding (`prepare().bind().all()`). No extra
|
|
40
|
-
* runtime dependencies — the D1 binding is provided by the Workers runtime.
|
|
41
|
-
*
|
|
42
|
-
* Note: D1 does not support interactive (`BEGIN`/`COMMIT`) transactions. For
|
|
43
|
-
* atomic multi-statement writes, use the raw D1 binding's `.batch([...])`
|
|
44
|
-
* (e.g. `c.env.DB.batch([...])` with prepared statements) — Kysely has no
|
|
45
|
-
* `.batch()`. Kysely's migrator is unaffected because the SQLite adapter
|
|
46
|
-
* reports `supportsTransactionalDdl: false`.
|
|
47
|
-
*/
|
|
48
|
-
export class D1Dialect implements Dialect {
|
|
49
|
-
constructor(private readonly d1: D1DatabaseLike) {}
|
|
50
|
-
|
|
51
|
-
createDriver(): Driver {
|
|
52
|
-
return new D1Driver(this.d1);
|
|
53
|
-
}
|
|
54
|
-
createQueryCompiler(): SqliteQueryCompiler {
|
|
55
|
-
return new SqliteQueryCompiler();
|
|
56
|
-
}
|
|
57
|
-
createAdapter(): D1Adapter {
|
|
58
|
-
return new D1Adapter();
|
|
59
|
-
}
|
|
60
|
-
createIntrospector(db: Kysely<any>): DatabaseIntrospector {
|
|
61
|
-
return new D1Introspector(db);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
interface D1TableRow {
|
|
66
|
-
name: string;
|
|
67
|
-
sql: string | null;
|
|
68
|
-
type: 'table' | 'view';
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
interface D1ColumnRow {
|
|
72
|
-
cid: number;
|
|
73
|
-
name: string;
|
|
74
|
-
type: string;
|
|
75
|
-
notnull: number;
|
|
76
|
-
dflt_value: unknown;
|
|
77
|
-
pk: number;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* D1 stores a protected `_cf_METADATA` table beside application tables.
|
|
82
|
-
* Kysely's stock SQLite introspector feeds every non-`sqlite_*` table into
|
|
83
|
-
* `pragma_table_info()`, which includes `_cf_METADATA`; D1 rejects inspection
|
|
84
|
-
* of that internal table with `SQLITE_AUTH`. Query application tables first,
|
|
85
|
-
* explicitly excluding `_cf_*`, then introspect each safe name separately.
|
|
86
|
-
*/
|
|
87
|
-
class D1Introspector implements DatabaseIntrospector {
|
|
88
|
-
constructor(private readonly db: Kysely<any>) {}
|
|
89
|
-
|
|
90
|
-
async getSchemas(): Promise<[]> {
|
|
91
|
-
return [];
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async getTables(
|
|
95
|
-
options: DatabaseMetadataOptions = { withInternalKyselyTables: false },
|
|
96
|
-
): Promise<TableMetadata[]> {
|
|
97
|
-
let query = this.db
|
|
98
|
-
.selectFrom('sqlite_master')
|
|
99
|
-
.where('type', 'in', ['table', 'view'])
|
|
100
|
-
.where('name', 'not like', 'sqlite_%')
|
|
101
|
-
.where(sql<boolean>`name not glob ${'_cf_*'}`)
|
|
102
|
-
.select(['name', 'sql', 'type'])
|
|
103
|
-
.orderBy('name');
|
|
104
|
-
|
|
105
|
-
if (!options.withInternalKyselyTables) {
|
|
106
|
-
query = query
|
|
107
|
-
.where('name', '!=', DEFAULT_MIGRATION_TABLE)
|
|
108
|
-
.where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const tables = await query.execute() as D1TableRow[];
|
|
112
|
-
return Promise.all(tables.map(async (table): Promise<TableMetadata> => {
|
|
113
|
-
const result = await sql<D1ColumnRow>`
|
|
114
|
-
select * from pragma_table_info(${table.name})
|
|
115
|
-
`.execute(this.db);
|
|
116
|
-
const columns = result.rows;
|
|
117
|
-
const autoIncrementColumn = findAutoIncrementColumn(table.sql, columns);
|
|
118
|
-
return {
|
|
119
|
-
name: table.name,
|
|
120
|
-
isView: table.type === 'view',
|
|
121
|
-
isForeign: false,
|
|
122
|
-
columns: columns.map((column) => ({
|
|
123
|
-
name: column.name,
|
|
124
|
-
dataType: column.type,
|
|
125
|
-
isNullable: !column.notnull,
|
|
126
|
-
isAutoIncrementing: column.name === autoIncrementColumn,
|
|
127
|
-
hasDefaultValue: column.dflt_value != null,
|
|
128
|
-
comment: undefined,
|
|
129
|
-
})),
|
|
130
|
-
};
|
|
131
|
-
}));
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function findAutoIncrementColumn(
|
|
136
|
-
tableSql: string | null,
|
|
137
|
-
columns: D1ColumnRow[],
|
|
138
|
-
): string | undefined {
|
|
139
|
-
const declared = tableSql
|
|
140
|
-
?.split(/[\(\),]/)
|
|
141
|
-
.find((part) => part.toLowerCase().includes('autoincrement'))
|
|
142
|
-
?.trimStart()
|
|
143
|
-
.split(/\s+/)[0]
|
|
144
|
-
?.replace(/["`]/g, '');
|
|
145
|
-
if (declared) return declared;
|
|
146
|
-
|
|
147
|
-
const primaryKeys = columns.filter((column) => column.pk > 0);
|
|
148
|
-
if (primaryKeys.length === 1 &&
|
|
149
|
-
primaryKeys[0].type.toLowerCase() === 'integer') {
|
|
150
|
-
return primaryKeys[0].name;
|
|
151
|
-
}
|
|
152
|
-
return undefined;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Marshals a Kysely parameter into a value D1's `bind()` accepts. */
|
|
156
|
-
function marshalD1Param(value: unknown): unknown {
|
|
157
|
-
if (value === undefined) return null;
|
|
158
|
-
if (typeof value === 'boolean') return value ? 1 : 0;
|
|
159
|
-
if (typeof value === 'bigint') return Number(value);
|
|
160
|
-
if (value instanceof Date) return value.toISOString();
|
|
161
|
-
return value;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
class D1Driver implements Driver {
|
|
165
|
-
private readonly connection: D1Connection;
|
|
166
|
-
constructor(d1: D1DatabaseLike) {
|
|
167
|
-
this.connection = new D1Connection(d1);
|
|
168
|
-
}
|
|
169
|
-
async init(): Promise<void> {}
|
|
170
|
-
async acquireConnection(): Promise<DatabaseConnection> {
|
|
171
|
-
return this.connection;
|
|
172
|
-
}
|
|
173
|
-
async beginTransaction(): Promise<void> {
|
|
174
|
-
throw new Error(
|
|
175
|
-
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
async commitTransaction(): Promise<void> {
|
|
179
|
-
throw new Error(
|
|
180
|
-
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
181
|
-
);
|
|
182
|
-
}
|
|
183
|
-
async rollbackTransaction(): Promise<void> {
|
|
184
|
-
throw new Error(
|
|
185
|
-
'D1 does not support interactive transactions. For atomic multi-statement writes, use the raw D1 binding (.batch([...]), e.g. c.env.DB.batch([...])) — Kysely has no .batch().',
|
|
186
|
-
);
|
|
187
|
-
}
|
|
188
|
-
async releaseConnection(): Promise<void> {}
|
|
189
|
-
async destroy(): Promise<void> {}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
class D1Connection implements DatabaseConnection {
|
|
193
|
-
constructor(private readonly d1: D1DatabaseLike) {}
|
|
194
|
-
|
|
195
|
-
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
196
|
-
const statement = this.d1.prepare(compiledQuery.sql);
|
|
197
|
-
const bound =
|
|
198
|
-
compiledQuery.parameters.length > 0
|
|
199
|
-
? statement.bind(...compiledQuery.parameters.map(marshalD1Param))
|
|
200
|
-
: statement;
|
|
201
|
-
const result = await bound.all<R>();
|
|
202
|
-
|
|
203
|
-
const rows = (result.results ?? []) as R[];
|
|
204
|
-
const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = { rows };
|
|
205
|
-
const changes = result.meta?.changes;
|
|
206
|
-
const lastRowId = result.meta?.last_row_id;
|
|
207
|
-
if (typeof changes === 'number') out.numAffectedRows = BigInt(changes);
|
|
208
|
-
if (lastRowId !== undefined && lastRowId !== null) out.insertId = BigInt(lastRowId);
|
|
209
|
-
return out as QueryResult<R>;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
|
|
213
|
-
yield await this.executeQuery<R>(compiledQuery);
|
|
214
|
-
}
|
|
215
|
-
}
|
package/src/dialects/libsql.ts
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
// src/dialects/libsql.ts
|
|
2
|
-
import {
|
|
3
|
-
CompiledQuery,
|
|
4
|
-
SqliteAdapter,
|
|
5
|
-
SqliteIntrospector,
|
|
6
|
-
SqliteQueryCompiler,
|
|
7
|
-
} from 'kysely';
|
|
8
|
-
import type {
|
|
9
|
-
DatabaseConnection,
|
|
10
|
-
DatabaseIntrospector,
|
|
11
|
-
Dialect,
|
|
12
|
-
Driver,
|
|
13
|
-
Kysely,
|
|
14
|
-
QueryResult,
|
|
15
|
-
} from 'kysely';
|
|
16
|
-
import type { LibsqlClientLike, LibsqlResultSetLike } from '../types';
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Kysely {@link Dialect} for libSQL / Turso.
|
|
20
|
-
*
|
|
21
|
-
* Works with any client that matches the libSQL `Client` contract — pass one
|
|
22
|
-
* built from `@tursodatabase/serverless/compat` (recommended, fetch-based, runs
|
|
23
|
-
* on Workers + Node) or `@libsql/client/web`.
|
|
24
|
-
*
|
|
25
|
-
* The libSQL client returns rows as array-indexable objects; we remap them to
|
|
26
|
-
* plain objects keyed by column name for Kysely.
|
|
27
|
-
*/
|
|
28
|
-
export class LibsqlDialect implements Dialect {
|
|
29
|
-
constructor(private readonly client: LibsqlClientLike) {}
|
|
30
|
-
|
|
31
|
-
createDriver(): Driver {
|
|
32
|
-
return new LibsqlDriver(this.client);
|
|
33
|
-
}
|
|
34
|
-
createQueryCompiler(): SqliteQueryCompiler {
|
|
35
|
-
return new SqliteQueryCompiler();
|
|
36
|
-
}
|
|
37
|
-
createAdapter(): SqliteAdapter {
|
|
38
|
-
return new SqliteAdapter();
|
|
39
|
-
}
|
|
40
|
-
createIntrospector(db: Kysely<any>): DatabaseIntrospector {
|
|
41
|
-
return new SqliteIntrospector(db);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function toRows<R>(resultSet: LibsqlResultSetLike): R[] {
|
|
46
|
-
const { columns, rows } = resultSet;
|
|
47
|
-
return rows.map((row) => {
|
|
48
|
-
const obj: Record<string, unknown> = {};
|
|
49
|
-
for (let i = 0; i < columns.length; i++) {
|
|
50
|
-
obj[columns[i]] = row[i];
|
|
51
|
-
}
|
|
52
|
-
return obj as R;
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
class LibsqlDriver implements Driver {
|
|
57
|
-
private readonly connection: LibsqlConnection;
|
|
58
|
-
constructor(client: LibsqlClientLike) {
|
|
59
|
-
this.connection = new LibsqlConnection(client);
|
|
60
|
-
}
|
|
61
|
-
async init(): Promise<void> {}
|
|
62
|
-
async acquireConnection(): Promise<DatabaseConnection> {
|
|
63
|
-
return this.connection;
|
|
64
|
-
}
|
|
65
|
-
async beginTransaction(connection: DatabaseConnection): Promise<void> {
|
|
66
|
-
await connection.executeQuery(CompiledQuery.raw('BEGIN'));
|
|
67
|
-
}
|
|
68
|
-
async commitTransaction(connection: DatabaseConnection): Promise<void> {
|
|
69
|
-
await connection.executeQuery(CompiledQuery.raw('COMMIT'));
|
|
70
|
-
}
|
|
71
|
-
async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
|
|
72
|
-
await connection.executeQuery(CompiledQuery.raw('ROLLBACK'));
|
|
73
|
-
}
|
|
74
|
-
async releaseConnection(): Promise<void> {}
|
|
75
|
-
async destroy(): Promise<void> {
|
|
76
|
-
this.connection.close();
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
class LibsqlConnection implements DatabaseConnection {
|
|
81
|
-
constructor(private readonly client: LibsqlClientLike) {}
|
|
82
|
-
|
|
83
|
-
close(): void {
|
|
84
|
-
this.client.close?.();
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
88
|
-
const args = compiledQuery.parameters.map((p) => (p === undefined ? null : p));
|
|
89
|
-
const resultSet = await this.client.execute({ sql: compiledQuery.sql, args });
|
|
90
|
-
|
|
91
|
-
const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = {
|
|
92
|
-
rows: toRows<R>(resultSet),
|
|
93
|
-
};
|
|
94
|
-
out.numAffectedRows = BigInt(resultSet.rowsAffected);
|
|
95
|
-
if (resultSet.lastInsertRowid !== undefined && resultSet.lastInsertRowid !== null) {
|
|
96
|
-
out.insertId = BigInt(resultSet.lastInsertRowid);
|
|
97
|
-
}
|
|
98
|
-
return out as QueryResult<R>;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
|
|
102
|
-
yield await this.executeQuery<R>(compiledQuery);
|
|
103
|
-
}
|
|
104
|
-
}
|