@cossackframework/database 0.7.5 → 0.7.7

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/README.md CHANGED
@@ -20,7 +20,10 @@ support to an existing project:
20
20
  npx cossack add database
21
21
  ```
22
22
 
23
- This scaffolds `src/models/`, `src/migrations/`, `src/seeders/`, and `src/db/config.ts`, adds the dependency to `package.json`, and (for D1) injects a `[[d1_databases]]` binding into `wrangler.jsonc`.
23
+ This scaffolds `src/models/`, `src/migrations/`, `src/seeders/`,
24
+ `src/db/config.ts` for the application runtime, and `src/db/cli.ts` for
25
+ Node-only tools. It also adds the dependency to `package.json` and (for D1)
26
+ injects a `[[d1_databases]]` binding into `wrangler.jsonc`.
24
27
 
25
28
  ## Connecting
26
29
 
@@ -50,7 +53,8 @@ export function createClient(env: { TURSO_URL: string; TURSO_TOKEN?: string }) {
50
53
  }
51
54
  ```
52
55
 
53
- The generated `src/db/config.ts` also exports a `getCliClient()` for the migration/seeder CLI commands (see [Migrations](../../docs/migrations.md)).
56
+ The generated `src/db/cli.ts` exports `getCliClient()` for migration, seeder,
57
+ and Studio commands (see [Migrations](../../docs/migrations.md)).
54
58
 
55
59
  ### Wiring the middleware
56
60
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/database",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "type": "module",
5
5
  "description": "Database support for the Cossack Framework — Kysely-based query builder with D1 and Turso dialects, migrations, and seeders",
6
6
  "license": "MIT",
@@ -1,20 +1,37 @@
1
1
  // src/dialects/d1.ts
2
2
  import {
3
3
  SqliteAdapter,
4
- SqliteIntrospector,
5
4
  SqliteQueryCompiler,
5
+ sql,
6
6
  } from 'kysely';
7
7
  import type {
8
8
  CompiledQuery,
9
9
  DatabaseConnection,
10
+ DatabaseMetadataOptions,
10
11
  DatabaseIntrospector,
11
12
  Dialect,
12
13
  Driver,
13
14
  Kysely,
14
15
  QueryResult,
16
+ TableMetadata,
15
17
  } from 'kysely';
18
+ import {
19
+ DEFAULT_MIGRATION_LOCK_TABLE,
20
+ DEFAULT_MIGRATION_TABLE,
21
+ } from 'kysely/migration';
16
22
  import type { D1DatabaseLike } from '../types';
17
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
+
18
35
  /**
19
36
  * Kysely {@link Dialect} for Cloudflare D1.
20
37
  *
@@ -37,12 +54,102 @@ export class D1Dialect implements Dialect {
37
54
  createQueryCompiler(): SqliteQueryCompiler {
38
55
  return new SqliteQueryCompiler();
39
56
  }
40
- createAdapter(): SqliteAdapter {
41
- return new SqliteAdapter();
57
+ createAdapter(): D1Adapter {
58
+ return new D1Adapter();
42
59
  }
43
60
  createIntrospector(db: Kysely<any>): DatabaseIntrospector {
44
- return new SqliteIntrospector(db);
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;
45
151
  }
152
+ return undefined;
46
153
  }
47
154
 
48
155
  /** Marshals a Kysely parameter into a value D1's `bind()` accepts. */
package/src/index.ts CHANGED
@@ -35,7 +35,7 @@ export { DatabaseCacheStore } from './cache-store';
35
35
  export type { CacheItemRow, CacheStoreLike } from './cache-store';
36
36
 
37
37
  // Dialects (advanced — for custom Kysely instances)
38
- export { D1Dialect } from './dialects/d1';
38
+ export { D1Adapter, D1Dialect } from './dialects/d1';
39
39
  export { LibsqlDialect } from './dialects/libsql';
40
40
 
41
41
  // Migrations & seeders