Skip to content

Instantly share code, notes, and snippets.

@gyopiazza
Last active November 10, 2024 10:52
Show Gist options
  • Save gyopiazza/70919f2c97a01d1b9897057d11fb9933 to your computer and use it in GitHub Desktop.
Save gyopiazza/70919f2c97a01d1b9897057d11fb9933 to your computer and use it in GitHub Desktop.
Multi-tenant with Drizzle ORM (multiple sqlite databases) - PoC
import { integer, sqliteTableCreator, text } from 'drizzle-orm/sqlite-core'
const sqliteTable = (tenant?: string) =>
sqliteTableCreator(name => (tenant ? `${tenant}_${name}` : name))
export const users = sqliteTable()('users', {
id: integer('id', { mode: 'number' }).primaryKey({ autoIncrement: true }),
name: text('name'),
})
import fs from 'fs'
import Database from 'better-sqlite3'
import { type BetterSQLite3Database, drizzle } from 'drizzle-orm/better-sqlite3'
import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
const Pool = (maxPool = 10) => {
const tenants: Record<string, BetterSQLite3Database> = {}
return (tenant: string) => {
if (tenants[tenant]) {
return tenants[tenant]
}
if (Object.keys(tenants).length >= maxPool) {
delete tenants[Object.keys(tenants)[0]]
}
const tenantFile = `${tenant}.db`
let requiresMigration = true
try {
fs.accessSync(tenantFile)
requiresMigration = false
} catch (error) {
requiresMigration = true
}
const db = new Database(tenantFile)
tenants[tenant] = drizzle(db)
if (requiresMigration) {
migrate(tenants[tenant], { migrationsFolder: 'migrations' })
}
return tenants[tenant]
}
}
export const pool = Pool()
import { pool } from './sqlite-pool'
import { users } from './schema'
const user = pool(tenant)
.insert(users)
.values({
name: 'Gyo',
})
.run()
const results = pool(tenant)?.select().from(users).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment