@cossackframework/database 0.7.5 → 0.7.6

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.6",
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,18 +1,24 @@
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
 
18
24
  /**
@@ -41,8 +47,98 @@ export class D1Dialect implements Dialect {
41
47
  return new SqliteAdapter();
42
48
  }
43
49
  createIntrospector(db: Kysely<any>): DatabaseIntrospector {
44
- return new SqliteIntrospector(db);
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;
45
140
  }
141
+ return undefined;
46
142
  }
47
143
 
48
144
  /** Marshals a Kysely parameter into a value D1's `bind()` accepts. */