import { execSync } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' import { defineConfig } from 'drizzle-kit' const dbName = 'orbitkit-lite-start' /** * Workaround to make drizzle-kit work with local Cloudflare D1 databases. * * Since drizzle-kit doesn't natively understand D1's local development setup, * this function finds or creates the local SQLite file that wrangler manages. * * Enables: drizzle-kit studio, push, generate, migrate commands locally. */ function getLocalD1DB() { try { const basePath = path.resolve('.wrangler/state/v3/d1') let dbFile = null if (fs.existsSync(basePath)) { dbFile = fs .readdirSync(basePath, { encoding: 'utf-8', recursive: true }) .find((f) => f.endsWith('.sqlite')) } if (!dbFile) { console.log('Creating local D1 database...') execSync(`pnpm wrangler d1 execute ${dbName} --command="select 1"`, { stdio: 'inherit', }) dbFile = fs .readdirSync(basePath, { encoding: 'utf-8', recursive: true }) .find((f) => f.endsWith('.sqlite')) if (!dbFile) { throw new Error('Failed to create local database') } } return path.resolve(basePath, dbFile) } catch (err) { console.error(err) return null } } /** * Drizzle-kit config that works with both local D1 (development) * and remote D1 (production). * * Local: Uses SQLite file via getLocalD1DB() workaround * Production: Uses D1 HTTP API (requires env vars) */ export default defineConfig({ out: './src/db/migrations', schema: './src/db/schema/index.ts', dialect: 'sqlite', ...(process.env.NODE_ENV === 'production' ? { driver: 'd1-http', dbCredentials: { accountId: process.env.CLOUDFLARE_ACCOUNT_ID, databaseId: process.env.DATABASE_ID, token: process.env.CLOUDFLARE_API_TOKEN, }, } : { dbCredentials: { url: getLocalD1DB(), }, }), })