-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathsetup.ts
More file actions
565 lines (498 loc) · 22.8 KB
/
setup.ts
File metadata and controls
565 lines (498 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import { mkdir, copyFile, writeFile, readFile } from 'node:fs/promises'
import chokidar from 'chokidar'
import { glob } from 'tinyglobby'
import { join, resolve as resolveFs, relative } from 'pathe'
import { defu } from 'defu'
import { addServerImports, addTemplate, addServerPlugin, addTypeTemplate, getLayerDirectories, updateTemplates, logger, addServerHandler } from '@nuxt/kit'
import { resolve, resolvePath, logWhenReady, addWranglerBinding } from '../utils'
import { copyDatabaseMigrationsToHubDir, copyDatabaseQueriesToHubDir, copyDatabaseAssets, applyBuildTimeMigrations, getDatabaseSchemaPathMetadata, buildDatabaseSchema } from './lib'
import { cloudflareHooks } from '../hosting/cloudflare'
import type { Nuxt } from '@nuxt/schema'
import type { HubConfig, ResolvedHubConfig, ResolvedDatabaseConfig } from '@nuxthub/core'
const log = logger.withTag('nuxt:hub')
/**
* Generate a lazy-initialized db template with Proxy wrapper
* Used for runtime env resolution (Docker/multi-deploy) and CF bindings
*/
function generateLazyDbTemplate(imports: string, getDbBody: string): string {
return `${imports}
import * as schema from './db/schema.mjs'
let _db
function getDb() {
if (!_db) {
try {
${getDbBody}
} catch (e) { throw new Error('[nuxt-hub] ' + e.message) }
}
return _db
}
const db = new Proxy({}, { get(_, prop) { return getDb()[prop] } })
export { db, schema }
`
}
/**
* Resolve database configuration from string or object format
*/
export async function resolveDatabaseConfig(nuxt: Nuxt, hub: HubConfig): Promise<ResolvedDatabaseConfig | false> {
if (!hub.db) return false
let config = typeof hub.db === 'string' ? { dialect: hub.db } : hub.db
config = defu(config, {
migrationsDirs: getLayerDirectories(nuxt).map(layer => join(layer.server, 'db/migrations')),
queriesPaths: [],
applyMigrationsDuringBuild: true
})
switch (config.dialect) {
case 'sqlite': {
// User explicitly set driver: 'libsql' - track for lazy env resolution
const userExplicitLibsql = config.driver === 'libsql'
// Turso Cloud
if (process.env.TURSO_DATABASE_URL && process.env.TURSO_AUTH_TOKEN) {
config.driver = 'libsql'
config.connection = defu(config.connection, {
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN
})
break
}
// Cloudflare D1 over HTTP
if (config.driver === 'd1-http') {
config.connection = defu(config.connection, {
accountId: process.env.NUXT_HUB_CLOUDFLARE_ACCOUNT_ID || undefined,
apiToken: process.env.NUXT_HUB_CLOUDFLARE_API_TOKEN || undefined,
databaseId: process.env.NUXT_HUB_CLOUDFLARE_DATABASE_ID || undefined
}) as ResolvedDatabaseConfig['connection']
if (!config.connection?.accountId || !config.connection?.apiToken || !config.connection?.databaseId) {
throw new Error('D1 HTTP driver requires NUXT_HUB_CLOUDFLARE_ACCOUNT_ID, NUXT_HUB_CLOUDFLARE_API_TOKEN, and NUXT_HUB_CLOUDFLARE_DATABASE_ID environment variables')
}
break
}
// Cloudflare D1 (production only - dev uses local libsql)
if (hub.hosting.includes('cloudflare') && !nuxt.options.dev) {
config.driver = 'd1'
break
}
// User explicitly set libsql without env vars - allow lazy resolution at runtime
if (userExplicitLibsql) {
config.connection = defu(config.connection, { url: '' })
break
}
config.driver ||= 'libsql'
config.connection = defu(config.connection, { url: `file:${join(hub.dir!, 'db/sqlite.db')}` })
await mkdir(join(hub.dir, 'db'), { recursive: true })
break
}
case 'postgresql': {
// Cloudflare Hyperdrive with explicit hyperdriveId
if (hub.hosting.includes('cloudflare') && config.connection?.hyperdriveId && !config.driver) {
config.driver = 'postgres-js'
break
}
config.connection = defu(config.connection, { url: process.env.POSTGRES_URL || process.env.POSTGRESQL_URL || process.env.DATABASE_URL || '' })
// Only error at build time if migrations need to run
if (config.applyMigrationsDuringBuild && config.driver && ['neon-http', 'postgres-js'].includes(config.driver) && !config.connection.url) {
throw new Error(`\`${config.driver}\` driver requires \`DATABASE_URL\`, \`POSTGRES_URL\`, or \`POSTGRESQL_URL\` environment variable when \`applyMigrationsDuringBuild\` is enabled`)
}
if (config.connection.url) {
config.driver ||= 'postgres-js'
break
}
config.driver ||= 'pglite'
config.connection = defu(config.connection, { dataDir: join(hub.dir, 'db/pglite') })
await mkdir(join(hub.dir, 'db/pglite'), { recursive: true })
break
}
case 'mysql': {
// Cloudflare Hyperdrive with explicit hyperdriveId
if (hub.hosting.includes('cloudflare') && config.connection?.hyperdriveId && !config.driver) {
config.driver = 'mysql2'
break
}
config.driver ||= 'mysql2'
config.connection = defu(config.connection, { uri: process.env.MYSQL_URL || process.env.DATABASE_URL || '' })
// Only error at build time if migrations need to run
if (config.applyMigrationsDuringBuild && !config.connection.uri) {
throw new Error('MySQL requires DATABASE_URL or MYSQL_URL environment variable when `applyMigrationsDuringBuild` is enabled')
}
break
}
}
// Disable migrations if database connection is not supported in CI
if (config.driver === 'd1') {
config.applyMigrationsDuringBuild = false
}
return config as ResolvedDatabaseConfig
}
export async function setupDatabase(nuxt: Nuxt, hub: HubConfig, deps: Record<string, string>) {
hub.db = await resolveDatabaseConfig(nuxt, hub)
if (!hub.db) return
const { dialect, driver, connection, migrationsDirs, queriesPaths } = hub.db as ResolvedDatabaseConfig
logWhenReady(nuxt, `\`hub:db\` using \`${dialect}\` database with \`${driver}\` driver`, 'info')
if (driver === 'd1' && connection?.databaseId) {
addWranglerBinding(nuxt, 'd1_databases', { binding: 'DB', database_id: connection.databaseId })
}
if (['postgres-js', 'mysql2'].includes(driver) && connection?.hyperdriveId) {
const binding = driver === 'postgres-js' ? 'POSTGRES' : 'MYSQL'
addWranglerBinding(nuxt, 'hyperdrive', { binding, id: connection.hyperdriveId })
}
// Verify development database dependencies are installed
if (!deps['drizzle-orm'] || !deps['drizzle-kit']) {
logWhenReady(nuxt, 'Please run `npx nypm i drizzle-orm drizzle-kit` to properly setup Drizzle ORM with NuxtHub.', 'error')
}
if (driver === 'postgres-js' && !deps['postgres']) {
logWhenReady(nuxt, 'Please run `npx nypm i postgres` to use PostgreSQL as database.', 'error')
} else if (driver === 'neon-http' && !deps['@neondatabase/serverless']) {
logWhenReady(nuxt, 'Please run `npx nypm i @neondatabase/serverless` to use Neon serverless database.', 'error')
} else if (driver === 'pglite' && !deps['@electric-sql/pglite']) {
logWhenReady(nuxt, 'Please run `npx nypm i @electric-sql/pglite` to use PGlite as database.', 'error')
} else if (driver === 'mysql2' && !deps.mysql2) {
logWhenReady(nuxt, 'Please run `npx nypm i mysql2` to use MySQL as database.', 'error')
} else if (driver === 'libsql' && !deps['@libsql/client']) {
logWhenReady(nuxt, 'Please run `npx nypm i @libsql/client` to use SQLite as database.', 'error')
}
// Add Server scanning
addServerPlugin(resolve('db/runtime/plugins/migrations.dev'))
// Handle migrations
nuxt.hook('modules:done', async () => {
// generate database schema
await generateDatabaseSchema(nuxt, hub as ResolvedHubConfig)
// Call hub:db:migrations:dirs hook
await nuxt.callHook('hub:db:migrations:dirs', migrationsDirs)
// Copy all migrations files to the hub.dir directory
await copyDatabaseMigrationsToHubDir(hub as ResolvedHubConfig)
// Call hub:db:queries:paths hook
await nuxt.callHook('hub:db:queries:paths', queriesPaths, dialect)
await copyDatabaseQueriesToHubDir(hub as ResolvedHubConfig)
})
// Copy database assets to public directory during build
nuxt.hook('nitro:build:public-assets', async (nitro) => {
// Database migrations & queries
await copyDatabaseAssets(nitro, hub as ResolvedHubConfig)
await applyBuildTimeMigrations(nitro, hub as ResolvedHubConfig)
})
// Add D1 migrations settings to wrangler.json for Cloudflare deployments
if (driver === 'd1') {
cloudflareHooks.hook('wrangler:config', (config) => {
const d1Databases = config.d1_databases as {
binding: string
database_id?: string
migrations_table?: string
migrations_dir?: string
}[] | undefined
if (!d1Databases?.length) return
const dbBinding = d1Databases.find(db => db.binding === 'DB')
if (dbBinding) {
dbBinding.migrations_table ||= '_hub_migrations'
dbBinding.migrations_dir ||= '.output/server/db/migrations/'
}
})
}
await setupDatabaseClient(nuxt, hub as ResolvedHubConfig)
await setupDatabaseConfig(nuxt, hub as ResolvedHubConfig)
}
async function generateDatabaseSchema(nuxt: Nuxt, hub: ResolvedHubConfig) {
if (!hub.db) return
const dialect = hub.db.dialect
const getSchemaPaths = async () => {
const schemaPatterns = getLayerDirectories(nuxt).map(layer => [
resolveFs(layer.server, 'db/schema.ts'),
resolveFs(layer.server, `db/schema.${dialect}.ts`),
resolveFs(layer.server, 'db/schema/*.ts')
]).flat()
let schemaPaths = await glob(schemaPatterns, { absolute: true, onlyFiles: true })
await nuxt.callHook('hub:db:schema:extend', { dialect, paths: schemaPaths })
schemaPaths = schemaPaths.filter((path) => {
const meta = getDatabaseSchemaPathMetadata(path)
return !meta.dialect || meta.dialect === dialect
})
return schemaPaths
}
// Export Drizzle global schema object including all schema files
let schemaPaths = await getSchemaPaths()
// Watch schema files for changes
if (nuxt.options.dev && !nuxt.options._prepare) {
// chokidar doesn't support glob patterns, so we need to watch the server/db directories
const watchDirs = getLayerDirectories(nuxt).map(layer => resolveFs(layer.server, 'db'))
const watcher = chokidar.watch(watchDirs, {
ignoreInitial: true
})
watcher.on('all', async (event, path) => {
if (!path.endsWith('db/schema.ts') && !path.endsWith(`db/schema.${dialect}.ts`) && !path.includes('/db/schema/')) return
if (['add', 'unlink', 'change'].includes(event) === false) return
const meta = getDatabaseSchemaPathMetadata(path)
if (meta.dialect && meta.dialect !== dialect) return
log.info(`Database schema ${event === 'add' ? 'added' : event === 'unlink' ? 'removed' : 'changed'}: \`${relative(nuxt.options.rootDir, path)}\``)
log.info('Make sure to run `npx nuxt db generate` to generate the database migrations.')
schemaPaths = await getSchemaPaths()
await updateTemplates({ filter: template => template.filename.includes('hub/db/schema.entry.ts') })
await buildDatabaseSchema(nuxt.options.buildDir, { relativeDir: nuxt.options.rootDir })
// Also copy to node_modules/@nuxthub/db/ for workflow compatibility
const physicalDbDir = join(nuxt.options.rootDir, 'node_modules', '@nuxthub', 'db')
try {
await copyFile(join(nuxt.options.buildDir, 'hub/db/schema.mjs'), join(physicalDbDir, 'schema.mjs'))
await copyFile(join(nuxt.options.buildDir, 'hub/db/schema.d.mts'), join(physicalDbDir, 'schema.d.mts'))
} catch (error) {
// Ignore errors during watch
}
})
nuxt.hook('close', () => watcher.close())
}
// Generate final database schema file at .nuxt/hub/db/schema.mjs
addTemplate({
filename: 'hub/db/schema.entry.ts',
getContents: () => `${schemaPaths.map(path => `export * from '${path}'`).join('\n')}`,
write: true
})
if (!nuxt.options._prepare) {
nuxt.hooks.hookOnce('app:templatesGenerated', async () => {
await buildDatabaseSchema(nuxt.options.buildDir, { relativeDir: nuxt.options.rootDir })
// Also copy schema.mjs to node_modules/@nuxthub/db/ for workflow compatibility
const physicalDbDir = join(nuxt.options.rootDir, 'node_modules', '@nuxthub', 'db')
await mkdir(physicalDbDir, { recursive: true })
try {
await copyFile(join(nuxt.options.buildDir, 'hub/db/schema.mjs'), join(physicalDbDir, 'schema.mjs'))
// Try to copy the generated .d.mts file for TypeScript support
// The .d.mts is generated in the same directory as schema.mjs
const schemaDtsSource = join(nuxt.options.buildDir, 'hub/db/schema.d.mts')
try {
const schemaTypes = await readFile(schemaDtsSource, 'utf-8')
await writeFile(join(physicalDbDir, 'schema.d.mts'), schemaTypes)
} catch {
// Fallback: create a simple re-export if .d.mts doesn't exist yet
await writeFile(
join(physicalDbDir, 'schema.d.mts'),
`export * from './schema.mjs'`
)
}
// Create a minimal package.json for Node.js module resolution
const packageJson = {
name: '@nuxthub/db',
version: '0.0.0',
type: 'module',
exports: {
'.': {
types: './db.d.ts',
default: './db.mjs'
},
'./schema': {
types: './schema.d.mts',
default: './schema.mjs'
}
}
}
await writeFile(
join(physicalDbDir, 'package.json'),
JSON.stringify(packageJson, null, 2)
)
} catch (error) {
log.warn(`Failed to copy schema to node_modules/.hub/: ${error}`)
}
})
}
nuxt.options.alias ||= {}
// Create hub:db:schema alias to @nuxthub/db/schema for backwards compatibility
addTypeTemplate({
filename: 'hub/db/schema.d.ts',
getContents: () => `declare module 'hub:db:schema' {
export * from '#build/hub/db/schema.mjs'
}`
}, { nitro: true, nuxt: true })
nuxt.options.alias['hub:db:schema'] = '@nuxthub/db/schema'
}
async function setupDatabaseClient(nuxt: Nuxt, hub: ResolvedHubConfig) {
const { dialect, driver, connection, mode, casing } = hub.db as ResolvedDatabaseConfig
// For types, d1-http uses sqlite-proxy
const driverForTypes = driver === 'd1-http' ? 'sqlite-proxy' : driver
// Setup Database Types for hub:db - point to @nuxthub/db for type definitions
const databaseTypes = `declare module 'hub:db' {
export * from '@nuxthub/db'
}`
addTypeTemplate({
filename: 'hub/db.d.ts',
getContents: () => databaseTypes
}, { nitro: true, nuxt: true })
// Setup Drizzle ORM
// Generate simplified drizzle() implementation
const modeOption = dialect === 'mysql' ? `, mode: '${mode || 'default'}'` : ''
const casingOption = casing ? `, casing: '${casing}'` : ''
let drizzleOrmContent = `import { drizzle } from 'drizzle-orm/${driver}'
import * as schema from './db/schema.mjs'
const db = drizzle({ connection: ${JSON.stringify(connection)}, schema${modeOption}${casingOption} })
export { db, schema }
`
if (driver === 'pglite' && nuxt.options.dev) {
// PGlite instance exported for use in devtools Drizzle Studio
drizzleOrmContent = `import { drizzle } from 'drizzle-orm/pglite'
import { PGlite } from '@electric-sql/pglite'
import * as schema from './db/schema.mjs'
const client = new PGlite(${JSON.stringify(connection.dataDir)})
const db = drizzle({ client, schema${casingOption} })
export { db, schema, client }
`
addServerHandler({
handler: await resolvePath('db/runtime/api/launch-studio.post.dev'),
method: 'post',
route: '/api/_hub/db/launch-studio'
})
}
if (driver === 'postgres-js' && nuxt.options.dev) {
// disable notice logger for postgres-js in dev
drizzleOrmContent = `import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from './db/schema.mjs'
const client = postgres('${connection.url}', {
onnotice: () => {}
})
const db = drizzle({ client, schema${casingOption} });
export { db, schema }
`
}
if (driver === 'neon-http') {
const urlExpr = connection.url ? `'${connection.url}'` : `process.env.POSTGRES_URL || process.env.POSTGRESQL_URL || process.env.DATABASE_URL`
drizzleOrmContent = generateLazyDbTemplate(
`import { neon } from '@neondatabase/serverless'\nimport { drizzle } from 'drizzle-orm/neon-http'`,
` const url = ${urlExpr}
if (!url) throw new Error('DATABASE_URL, POSTGRES_URL, or POSTGRESQL_URL required')
const sql = neon(url)
_db = drizzle(sql, { schema${casingOption} })`
)
}
if (driver === 'd1') {
drizzleOrmContent = generateLazyDbTemplate(
`import { drizzle } from 'drizzle-orm/d1'`,
` const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
if (!binding) throw new Error('DB binding not found')
_db = drizzle(binding, { schema${casingOption} })`
)
}
if (driver === 'd1-http') {
// D1 over HTTP using sqlite-proxy
drizzleOrmContent = `import { drizzle } from 'drizzle-orm/sqlite-proxy'
import * as schema from './db/schema.mjs'
const accountId = ${JSON.stringify(connection.accountId)}
const databaseId = ${JSON.stringify(connection.databaseId)}
const apiToken = ${JSON.stringify(connection.apiToken)}
async function d1HttpDriver(sql, params, method) {
if (method === 'values') method = 'all'
const { errors, success, result } = await $fetch(\`https://api.cloudflare.com/client/v4/accounts/\${accountId}/d1/db/\${databaseId}/raw\`, {
method: 'POST',
headers: {
Authorization: \`Bearer \${apiToken}\`,
'Content-Type': 'application/json'
},
async onResponseError({ request, response, options }) {
console.error(
"D1 HTTP Error:",
request,
options.body,
response.status,
response._data,
)
},
body: { sql, params }
})
if (errors?.length > 0 || !success) {
throw new Error(\`D1 HTTP error: \${JSON.stringify({ errors, success, result })}\`)
}
const queryResult = result?.[0]
if (!queryResult?.success) {
throw new Error(\`D1 HTTP error: \${JSON.stringify({ errors, success, result })}\`)
}
const rows = queryResult.results?.rows || []
if (method === 'get') {
if (rows.length === 0) {
return { rows: [] }
}
return { rows: rows[0] }
}
return { rows }
}
const db = drizzle(d1HttpDriver, { schema${casingOption} })
export { db, schema }
`
}
if (['postgres-js', 'mysql2'].includes(driver) && hub.hosting.includes('cloudflare') && connection?.hyperdriveId) {
const bindingName = driver === 'postgres-js' ? 'POSTGRES' : 'MYSQL'
drizzleOrmContent = generateLazyDbTemplate(
`import { drizzle } from 'drizzle-orm/${driver}'`,
` const hyperdrive = process.env.${bindingName} || globalThis.__env__?.${bindingName} || globalThis.${bindingName}
if (!hyperdrive) throw new Error('${bindingName} binding not found')
_db = drizzle({ connection: hyperdrive.connectionString, schema${modeOption}${casingOption} })`
)
}
// Non-CF postgres-js: lazy env resolution for Docker/multi-deploy scenarios
if (driver === 'postgres-js' && !nuxt.options.dev && !hub.hosting.includes('cloudflare')) {
const urlExpr = connection.url ? `'${connection.url}'` : `process.env.POSTGRES_URL || process.env.POSTGRESQL_URL || process.env.DATABASE_URL`
drizzleOrmContent = generateLazyDbTemplate(
`import { drizzle } from 'drizzle-orm/postgres-js'\nimport postgres from 'postgres'`,
` const url = ${urlExpr}
if (!url) throw new Error('DATABASE_URL, POSTGRES_URL, or POSTGRESQL_URL required')
const client = postgres(url, { onnotice: () => {} })
_db = drizzle({ client, schema${casingOption} })`
)
}
// Non-CF mysql2: lazy env resolution for Docker/multi-deploy scenarios
if (driver === 'mysql2' && !nuxt.options.dev && !hub.hosting.includes('cloudflare')) {
const uriExpr = connection.uri ? `'${connection.uri}'` : `process.env.MYSQL_URL || process.env.DATABASE_URL`
drizzleOrmContent = generateLazyDbTemplate(
`import { drizzle } from 'drizzle-orm/mysql2'`,
` const uri = ${uriExpr}
if (!uri) throw new Error('DATABASE_URL or MYSQL_URL required')
_db = drizzle({ connection: { uri }, schema${modeOption}${casingOption} })`
)
}
// libsql: lazy env resolution for Docker/multi-deploy scenarios (when no URL baked in)
if (driver === 'libsql' && !connection.url) {
drizzleOrmContent = generateLazyDbTemplate(
`import { drizzle } from 'drizzle-orm/libsql'`,
` const url = process.env.TURSO_DATABASE_URL || process.env.LIBSQL_URL || process.env.DATABASE_URL
const authToken = process.env.TURSO_AUTH_TOKEN || process.env.LIBSQL_AUTH_TOKEN
if (!url) throw new Error('Database URL not found. Set TURSO_DATABASE_URL, LIBSQL_URL, or DATABASE_URL')
_db = drizzle({ connection: { url, authToken }, schema${casingOption} })`
)
}
// Write to node_modules/@nuxthub/db/ for direct imports (workflow compatibility)
const physicalDbDir = join(nuxt.options.rootDir, 'node_modules', '@nuxthub', 'db')
await mkdir(physicalDbDir, { recursive: true })
// Write db.mjs to node_modules/@nuxthub/db/
await writeFile(
join(physicalDbDir, 'db.mjs'),
drizzleOrmContent.replace(/from '\.\/db\/schema\.mjs'/g, 'from \'./schema.mjs\'')
)
// Write db.d.ts for TypeScript support
const physicalDbTypes = `import type { DrizzleConfig } from 'drizzle-orm'
import { drizzle as drizzleCore } from 'drizzle-orm/${driverForTypes}'
import * as schema from './schema.mjs'
/**
* The database schema object
* Defined in server/db/schema.ts and server/db/schema/*.ts
*/
export { schema }
/**
* The ${driver} database client.
*/
export const db: ReturnType<typeof drizzleCore<typeof schema>>
`
await writeFile(
join(physicalDbDir, 'db.d.ts'),
physicalDbTypes
)
// Create hub:db alias to @nuxthub/db for backwards compatibility
nuxt.options.alias!['hub:db'] = '@nuxthub/db'
// Add auto-imports for both @nuxthub/db and hub:db
addServerImports({ name: 'db', from: '@nuxthub/db', meta: { description: `The ${driver} database client.` } })
addServerImports({ name: 'schema', from: '@nuxthub/db', meta: { description: `The database schema object` } })
}
async function setupDatabaseConfig(nuxt: Nuxt, hub: ResolvedHubConfig) {
// generate drizzle.config.ts in .nuxt/hub/db/drizzle.config.ts
const { dialect, casing } = hub.db as ResolvedDatabaseConfig
const casingConfig = casing ? `\n casing: '${casing}',` : ''
addTemplate({
filename: 'hub/db/drizzle.config.ts',
write: true,
getContents: () => `import { defineConfig } from 'drizzle-kit'
export default defineConfig({
dialect: '${dialect}',${casingConfig}
schema: '${relative(nuxt.options.rootDir, resolve(nuxt.options.buildDir, 'hub/db/schema.mjs'))}',
out: '${relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, `server/db/migrations/${dialect}`))}'
});` })
}