Skip to content

Instantly share code, notes, and snippets.

@mlafeldt
Created September 12, 2024 14:01
Show Gist options
  • Save mlafeldt/608551b38fec7410909af89b39425033 to your computer and use it in GitHub Desktop.
Save mlafeldt/608551b38fec7410909af89b39425033 to your computer and use it in GitHub Desktop.
Drizzle config for local development with wrangler
import { defineConfig } from 'drizzle-kit'
import crypto from 'node:crypto'
import { mkdirSync } from 'node:fs'
import path from 'node:path'
// Based on https://github.com/cloudflare/workers-sdk/blob/64710904ad4055054bea09ebb23ededab140aa79/packages/miniflare/src/plugins/shared/index.ts#L194
function idFromName(uniqueKey: string, name: string) {
const key = new Uint8Array(crypto.createHash('sha256').update(uniqueKey).digest())
const nameHmac = new Uint8Array(crypto.createHmac('sha256', key).update(name).digest().subarray(0, 16))
const hmac = new Uint8Array(crypto.createHmac('sha256', key).update(nameHmac).digest().subarray(0, 16))
return Buffer.concat([nameHmac, hmac]).toString('hex')
}
// Knowing the path used by wrangler allows drizzle-kit migrate/push to create the database in advance
function getLocalDbPath(databaseId: string) {
const uniqueKey = 'miniflare-D1DatabaseObject'
const dbDir = path.join('.wrangler', 'state', 'v3', 'd1', uniqueKey)
mkdirSync(dbDir, { recursive: true })
const dbPath = path.join(dbDir, idFromName(uniqueKey, databaseId) + '.sqlite')
console.log('Using', dbPath)
return dbPath
}
export default defineConfig({
schema: './src/schema.ts',
out: './migrations',
migrations: { prefix: 'timestamp' },
dialect: 'sqlite',
dbCredentials: {
url: getLocalDbPath(process.env.DB_ID!),
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment