@cossackframework/database 0.7.6 → 0.8.0-distprobe.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.
Files changed (199) hide show
  1. package/dist/adapter/index.d.ts +4 -0
  2. package/dist/adapter/index.d.ts.map +1 -0
  3. package/dist/adapter/index.js +3 -0
  4. package/dist/adapter/index.js.map +1 -0
  5. package/dist/adapter/memory.d.ts +23 -0
  6. package/dist/adapter/memory.d.ts.map +1 -0
  7. package/dist/adapter/memory.js +53 -0
  8. package/dist/adapter/memory.js.map +1 -0
  9. package/dist/adapter/scope.d.ts +7 -0
  10. package/dist/adapter/scope.d.ts.map +1 -0
  11. package/dist/adapter/scope.js +7 -0
  12. package/dist/adapter/scope.js.map +1 -0
  13. package/dist/adapter/types.d.ts +73 -0
  14. package/dist/adapter/types.d.ts.map +1 -0
  15. package/dist/adapter/types.js +2 -0
  16. package/dist/adapter/types.js.map +1 -0
  17. package/dist/cli.d.ts +3 -0
  18. package/dist/cli.d.ts.map +1 -0
  19. package/dist/cli.js +6 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/codec.d.ts +4 -0
  22. package/dist/codec.d.ts.map +1 -0
  23. package/dist/codec.js +52 -0
  24. package/dist/codec.js.map +1 -0
  25. package/dist/config.d.ts +19 -0
  26. package/dist/config.d.ts.map +1 -0
  27. package/dist/config.js +4 -0
  28. package/dist/config.js.map +1 -0
  29. package/dist/cossack/index.d.ts +49 -0
  30. package/dist/cossack/index.d.ts.map +1 -0
  31. package/dist/cossack/index.js +254 -0
  32. package/dist/cossack/index.js.map +1 -0
  33. package/dist/dialect/dialects.d.ts +6 -0
  34. package/dist/dialect/dialects.d.ts.map +1 -0
  35. package/dist/dialect/dialects.js +102 -0
  36. package/dist/dialect/dialects.js.map +1 -0
  37. package/dist/entity/base-entity.d.ts +21 -0
  38. package/dist/entity/base-entity.d.ts.map +1 -0
  39. package/dist/entity/base-entity.js +64 -0
  40. package/dist/entity/base-entity.js.map +1 -0
  41. package/dist/entity/manager.d.ts +25 -0
  42. package/dist/entity/manager.d.ts.map +1 -0
  43. package/dist/entity/manager.js +72 -0
  44. package/dist/entity/manager.js.map +1 -0
  45. package/dist/errors.d.ts +37 -0
  46. package/dist/errors.d.ts.map +1 -0
  47. package/dist/errors.js +62 -0
  48. package/dist/errors.js.map +1 -0
  49. package/dist/index.d.ts +25 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +21 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/metadata/decorators.d.ts +27 -0
  54. package/dist/metadata/decorators.d.ts.map +1 -0
  55. package/dist/metadata/decorators.js +271 -0
  56. package/dist/metadata/decorators.js.map +1 -0
  57. package/dist/metadata/finalize.d.ts +4 -0
  58. package/dist/metadata/finalize.d.ts.map +1 -0
  59. package/dist/metadata/finalize.js +267 -0
  60. package/dist/metadata/finalize.js.map +1 -0
  61. package/dist/metadata/naming.d.ts +9 -0
  62. package/dist/metadata/naming.d.ts.map +1 -0
  63. package/dist/metadata/naming.js +21 -0
  64. package/dist/metadata/naming.js.map +1 -0
  65. package/dist/metadata/stage3.d.ts +26 -0
  66. package/dist/metadata/stage3.d.ts.map +1 -0
  67. package/dist/metadata/stage3.js +38 -0
  68. package/dist/metadata/stage3.js.map +1 -0
  69. package/dist/metadata/store.d.ts +29 -0
  70. package/dist/metadata/store.d.ts.map +1 -0
  71. package/dist/metadata/store.js +22 -0
  72. package/dist/metadata/store.js.map +1 -0
  73. package/dist/metadata/types.d.ts +83 -0
  74. package/dist/metadata/types.d.ts.map +1 -0
  75. package/dist/metadata/types.js +2 -0
  76. package/dist/metadata/types.js.map +1 -0
  77. package/dist/migration/runner.d.ts +22 -0
  78. package/dist/migration/runner.d.ts.map +1 -0
  79. package/dist/migration/runner.js +182 -0
  80. package/dist/migration/runner.js.map +1 -0
  81. package/dist/migration/types.d.ts +26 -0
  82. package/dist/migration/types.d.ts.map +1 -0
  83. package/dist/migration/types.js +2 -0
  84. package/dist/migration/types.js.map +1 -0
  85. package/dist/orm.d.ts +63 -0
  86. package/dist/orm.d.ts.map +1 -0
  87. package/dist/orm.js +643 -0
  88. package/dist/orm.js.map +1 -0
  89. package/dist/query/builder.d.ts +63 -0
  90. package/dist/query/builder.d.ts.map +1 -0
  91. package/dist/query/builder.js +303 -0
  92. package/dist/query/builder.js.map +1 -0
  93. package/dist/query/expression.d.ts +27 -0
  94. package/dist/query/expression.d.ts.map +1 -0
  95. package/dist/query/expression.js +90 -0
  96. package/dist/query/expression.js.map +1 -0
  97. package/dist/query/types.d.ts +33 -0
  98. package/dist/query/types.d.ts.map +1 -0
  99. package/dist/query/types.js +11 -0
  100. package/dist/query/types.js.map +1 -0
  101. package/dist/runtime/bun.d.ts +30 -0
  102. package/dist/runtime/bun.d.ts.map +1 -0
  103. package/dist/runtime/bun.js +63 -0
  104. package/dist/runtime/bun.js.map +1 -0
  105. package/dist/runtime/cloudflare.d.ts +70 -0
  106. package/dist/runtime/cloudflare.d.ts.map +1 -0
  107. package/dist/runtime/cloudflare.js +230 -0
  108. package/dist/runtime/cloudflare.js.map +1 -0
  109. package/dist/runtime/deno.d.ts +26 -0
  110. package/dist/runtime/deno.d.ts.map +1 -0
  111. package/dist/runtime/deno.js +40 -0
  112. package/dist/runtime/deno.js.map +1 -0
  113. package/dist/runtime/helpers.d.ts +4 -0
  114. package/dist/runtime/helpers.d.ts.map +1 -0
  115. package/dist/runtime/helpers.js +22 -0
  116. package/dist/runtime/helpers.js.map +1 -0
  117. package/dist/runtime/node.d.ts +88 -0
  118. package/dist/runtime/node.d.ts.map +1 -0
  119. package/dist/runtime/node.js +221 -0
  120. package/dist/runtime/node.js.map +1 -0
  121. package/dist/schema/builder.d.ts +16 -0
  122. package/dist/schema/builder.d.ts.map +1 -0
  123. package/dist/schema/builder.js +49 -0
  124. package/dist/schema/builder.js.map +1 -0
  125. package/dist/schema/ddl.d.ts +7 -0
  126. package/dist/schema/ddl.d.ts.map +1 -0
  127. package/dist/schema/ddl.js +114 -0
  128. package/dist/schema/ddl.js.map +1 -0
  129. package/dist/schema/diff.d.ts +8 -0
  130. package/dist/schema/diff.d.ts.map +1 -0
  131. package/dist/schema/diff.js +224 -0
  132. package/dist/schema/diff.js.map +1 -0
  133. package/dist/schema/introspection.d.ts +8 -0
  134. package/dist/schema/introspection.d.ts.map +1 -0
  135. package/dist/schema/introspection.js +165 -0
  136. package/dist/schema/introspection.js.map +1 -0
  137. package/dist/schema/operations.d.ts +44 -0
  138. package/dist/schema/operations.d.ts.map +1 -0
  139. package/dist/schema/operations.js +2 -0
  140. package/dist/schema/operations.js.map +1 -0
  141. package/dist/schema/types.d.ts +76 -0
  142. package/dist/schema/types.d.ts.map +1 -0
  143. package/dist/schema/types.js +2 -0
  144. package/dist/schema/types.js.map +1 -0
  145. package/dist/scope.d.ts +5 -0
  146. package/dist/scope.d.ts.map +1 -0
  147. package/dist/scope.js +28 -0
  148. package/dist/scope.js.map +1 -0
  149. package/dist/seeding/runner.d.ts +14 -0
  150. package/dist/seeding/runner.d.ts.map +1 -0
  151. package/dist/seeding/runner.js +107 -0
  152. package/dist/seeding/runner.js.map +1 -0
  153. package/dist/seeding/types.d.ts +33 -0
  154. package/dist/seeding/types.d.ts.map +1 -0
  155. package/dist/seeding/types.js +4 -0
  156. package/dist/seeding/types.js.map +1 -0
  157. package/dist/sql/client.d.ts +16 -0
  158. package/dist/sql/client.d.ts.map +1 -0
  159. package/dist/sql/client.js +71 -0
  160. package/dist/sql/client.js.map +1 -0
  161. package/dist/sql/executable.d.ts +8 -0
  162. package/dist/sql/executable.d.ts.map +1 -0
  163. package/dist/sql/executable.js +11 -0
  164. package/dist/sql/executable.js.map +1 -0
  165. package/dist/sql/fragment.d.ts +37 -0
  166. package/dist/sql/fragment.d.ts.map +1 -0
  167. package/dist/sql/fragment.js +40 -0
  168. package/dist/sql/fragment.js.map +1 -0
  169. package/dist/sql/tag.d.ts +20 -0
  170. package/dist/sql/tag.d.ts.map +1 -0
  171. package/dist/sql/tag.js +123 -0
  172. package/dist/sql/tag.js.map +1 -0
  173. package/dist/tooling/generate.d.ts +9 -0
  174. package/dist/tooling/generate.d.ts.map +1 -0
  175. package/dist/tooling/generate.js +83 -0
  176. package/dist/tooling/generate.js.map +1 -0
  177. package/dist/tooling/index.d.ts +12 -0
  178. package/dist/tooling/index.d.ts.map +1 -0
  179. package/dist/tooling/index.js +389 -0
  180. package/dist/tooling/index.js.map +1 -0
  181. package/package.json +93 -21
  182. package/LICENSE +0 -21
  183. package/README.md +0 -188
  184. package/src/accessor.ts +0 -27
  185. package/src/als.ts +0 -29
  186. package/src/cache-store.ts +0 -285
  187. package/src/create-database.ts +0 -36
  188. package/src/dialects/d1.ts +0 -204
  189. package/src/dialects/libsql.ts +0 -104
  190. package/src/index.ts +0 -67
  191. package/src/middleware.ts +0 -42
  192. package/src/migrations/migrator.ts +0 -90
  193. package/src/seeder/runner.ts +0 -73
  194. package/src/session-als.ts +0 -46
  195. package/src/session-middleware.ts +0 -98
  196. package/src/session-store.ts +0 -201
  197. package/src/session.ts +0 -59
  198. package/src/store.ts +0 -38
  199. package/src/types.ts +0 -108
@@ -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
- }
@@ -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
- }
@@ -1,204 +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 {@link Dialect} for Cloudflare D1.
26
- *
27
- * Uses Kysely's SQLite query compiler/adapter/introspector and a custom driver
28
- * that talks to the `D1Database` binding (`prepare().bind().all()`). No extra
29
- * runtime dependencies — the D1 binding is provided by the Workers runtime.
30
- *
31
- * Note: D1 does not support interactive (`BEGIN`/`COMMIT`) transactions. For
32
- * atomic multi-statement writes, use the raw D1 binding's `.batch([...])`
33
- * (e.g. `c.env.DB.batch([...])` with prepared statements) — Kysely has no
34
- * `.batch()`. Kysely's migrator is unaffected because the SQLite adapter
35
- * reports `supportsTransactionalDdl: false`.
36
- */
37
- export class D1Dialect implements Dialect {
38
- constructor(private readonly d1: D1DatabaseLike) {}
39
-
40
- createDriver(): Driver {
41
- return new D1Driver(this.d1);
42
- }
43
- createQueryCompiler(): SqliteQueryCompiler {
44
- return new SqliteQueryCompiler();
45
- }
46
- createAdapter(): SqliteAdapter {
47
- return new SqliteAdapter();
48
- }
49
- createIntrospector(db: Kysely<any>): DatabaseIntrospector {
50
- return new D1Introspector(db);
51
- }
52
- }
53
-
54
- interface D1TableRow {
55
- name: string;
56
- sql: string | null;
57
- type: 'table' | 'view';
58
- }
59
-
60
- interface D1ColumnRow {
61
- cid: number;
62
- name: string;
63
- type: string;
64
- notnull: number;
65
- dflt_value: unknown;
66
- pk: number;
67
- }
68
-
69
- /**
70
- * D1 stores a protected `_cf_METADATA` table beside application tables.
71
- * Kysely's stock SQLite introspector feeds every non-`sqlite_*` table into
72
- * `pragma_table_info()`, which includes `_cf_METADATA`; D1 rejects inspection
73
- * of that internal table with `SQLITE_AUTH`. Query application tables first,
74
- * explicitly excluding `_cf_*`, then introspect each safe name separately.
75
- */
76
- class D1Introspector implements DatabaseIntrospector {
77
- constructor(private readonly db: Kysely<any>) {}
78
-
79
- async getSchemas(): Promise<[]> {
80
- return [];
81
- }
82
-
83
- async getTables(
84
- options: DatabaseMetadataOptions = { withInternalKyselyTables: false },
85
- ): Promise<TableMetadata[]> {
86
- let query = this.db
87
- .selectFrom('sqlite_master')
88
- .where('type', 'in', ['table', 'view'])
89
- .where('name', 'not like', 'sqlite_%')
90
- .where(sql<boolean>`name not glob ${'_cf_*'}`)
91
- .select(['name', 'sql', 'type'])
92
- .orderBy('name');
93
-
94
- if (!options.withInternalKyselyTables) {
95
- query = query
96
- .where('name', '!=', DEFAULT_MIGRATION_TABLE)
97
- .where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);
98
- }
99
-
100
- const tables = await query.execute() as D1TableRow[];
101
- return Promise.all(tables.map(async (table): Promise<TableMetadata> => {
102
- const result = await sql<D1ColumnRow>`
103
- select * from pragma_table_info(${table.name})
104
- `.execute(this.db);
105
- const columns = result.rows;
106
- const autoIncrementColumn = findAutoIncrementColumn(table.sql, columns);
107
- return {
108
- name: table.name,
109
- isView: table.type === 'view',
110
- isForeign: false,
111
- columns: columns.map((column) => ({
112
- name: column.name,
113
- dataType: column.type,
114
- isNullable: !column.notnull,
115
- isAutoIncrementing: column.name === autoIncrementColumn,
116
- hasDefaultValue: column.dflt_value != null,
117
- comment: undefined,
118
- })),
119
- };
120
- }));
121
- }
122
- }
123
-
124
- function findAutoIncrementColumn(
125
- tableSql: string | null,
126
- columns: D1ColumnRow[],
127
- ): string | undefined {
128
- const declared = tableSql
129
- ?.split(/[\(\),]/)
130
- .find((part) => part.toLowerCase().includes('autoincrement'))
131
- ?.trimStart()
132
- .split(/\s+/)[0]
133
- ?.replace(/["`]/g, '');
134
- if (declared) return declared;
135
-
136
- const primaryKeys = columns.filter((column) => column.pk > 0);
137
- if (primaryKeys.length === 1 &&
138
- primaryKeys[0].type.toLowerCase() === 'integer') {
139
- return primaryKeys[0].name;
140
- }
141
- return undefined;
142
- }
143
-
144
- /** Marshals a Kysely parameter into a value D1's `bind()` accepts. */
145
- function marshalD1Param(value: unknown): unknown {
146
- if (value === undefined) return null;
147
- if (typeof value === 'boolean') return value ? 1 : 0;
148
- if (typeof value === 'bigint') return Number(value);
149
- if (value instanceof Date) return value.toISOString();
150
- return value;
151
- }
152
-
153
- class D1Driver implements Driver {
154
- private readonly connection: D1Connection;
155
- constructor(d1: D1DatabaseLike) {
156
- this.connection = new D1Connection(d1);
157
- }
158
- async init(): Promise<void> {}
159
- async acquireConnection(): Promise<DatabaseConnection> {
160
- return this.connection;
161
- }
162
- async beginTransaction(): Promise<void> {
163
- throw new Error(
164
- '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().',
165
- );
166
- }
167
- async commitTransaction(): Promise<void> {
168
- throw new Error(
169
- '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().',
170
- );
171
- }
172
- async rollbackTransaction(): Promise<void> {
173
- throw new Error(
174
- '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().',
175
- );
176
- }
177
- async releaseConnection(): Promise<void> {}
178
- async destroy(): Promise<void> {}
179
- }
180
-
181
- class D1Connection implements DatabaseConnection {
182
- constructor(private readonly d1: D1DatabaseLike) {}
183
-
184
- async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
185
- const statement = this.d1.prepare(compiledQuery.sql);
186
- const bound =
187
- compiledQuery.parameters.length > 0
188
- ? statement.bind(...compiledQuery.parameters.map(marshalD1Param))
189
- : statement;
190
- const result = await bound.all<R>();
191
-
192
- const rows = (result.results ?? []) as R[];
193
- const out: { rows: R[]; numAffectedRows?: bigint; insertId?: bigint } = { rows };
194
- const changes = result.meta?.changes;
195
- const lastRowId = result.meta?.last_row_id;
196
- if (typeof changes === 'number') out.numAffectedRows = BigInt(changes);
197
- if (lastRowId !== undefined && lastRowId !== null) out.insertId = BigInt(lastRowId);
198
- return out as QueryResult<R>;
199
- }
200
-
201
- async *streamQuery<R>(compiledQuery: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
202
- yield await this.executeQuery<R>(compiledQuery);
203
- }
204
- }
@@ -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
- }
package/src/index.ts DELETED
@@ -1,67 +0,0 @@
1
- // src/index.ts
2
-
3
- // Re-export all of Kysely so consumers don't need to install it separately.
4
- // `Kysely`, `Generated`, `sql`, `Insertable`, `Selectable`, etc. are all
5
- // available via `import { ... } from '@cossackframework/database'`.
6
- export * from 'kysely';
7
- export { Migrator, FileMigrationProvider, NO_MIGRATIONS } from 'kysely/migration';
8
- export type {
9
- Migration,
10
- MigrationProvider,
11
- MigrationResultSet,
12
- MigrationResult,
13
- MigrationInfo,
14
- } from 'kysely/migration';
15
-
16
- // Core API
17
- export { createDatabase } from './create-database';
18
- export { createDbMiddleware } from './middleware';
19
- export type { DbMiddlewareOptions } from './middleware';
20
- export { getDb } from './accessor';
21
- export { db, setDbStoreGetter } from './store';
22
- export { ensureDbAlsWired, runWithDb } from './als';
23
-
24
- // Sessions
25
- export { SessionStore } from './session-store';
26
- export type { SessionRow } from './session-store';
27
- export { session } from './session';
28
- export { createSessionMiddleware } from './session-middleware';
29
- export type { SessionMiddlewareOptions } from './session-middleware';
30
- export { runWithSession, ensureSessionAlsWired } from './session-als';
31
- export type { SessionScope } from './session-als';
32
-
33
- // Cache (database-backed driver; structurally compatible with core's CacheStore)
34
- export { DatabaseCacheStore } from './cache-store';
35
- export type { CacheItemRow, CacheStoreLike } from './cache-store';
36
-
37
- // Dialects (advanced — for custom Kysely instances)
38
- export { D1Dialect } from './dialects/d1';
39
- export { LibsqlDialect } from './dialects/libsql';
40
-
41
- // Migrations & seeders
42
- export {
43
- runMigrations,
44
- resetMigrations,
45
- getMigrationStatus,
46
- formatMigrationResult,
47
- defaultMigrationsFolder,
48
- } from './migrations/migrator';
49
- export type { RunMigrationsOptions, MigrationDirection } from './migrations/migrator';
50
- export { runSeeders, defaultSeedersFolder } from './seeder/runner';
51
- export type { Seeder, RunSeedersOptions } from './seeder/runner';
52
-
53
- // Types
54
- export type {
55
- Database,
56
- DbClient,
57
- DbConfig,
58
- D1Config,
59
- LibsqlConfig,
60
- D1DatabaseLike,
61
- D1PreparedStatementLike,
62
- D1ResultLike,
63
- LibsqlClientLike,
64
- LibsqlInStatement,
65
- LibsqlResultSetLike,
66
- LibsqlRowLike,
67
- } from './types';