Created
March 17, 2025 00:10
-
-
Save fl0wo/b3b0dc6ab4f0ec38ef78679cb74ceb99 to your computer and use it in GitHub Desktop.
script that lists all multi-tenant databases and applies schema migrations using Turso and Drizzle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createClient } from "@tursodatabase/api"; | |
import { createClient as createTursoClient } from "@libsql/client" | |
import {migrate} from "drizzle-orm/libsql/migrator"; | |
import {drizzle} from "drizzle-orm/libsql"; | |
// THE SCHEMA OF THE ORG DBs (not the main one) | |
import * as schema from "../drizzle/org-schemas"; | |
import {DEFAULT_API_TOKEN, TURSO_API_TOKEN} from "./secrets"; | |
const listDBs = async () => { | |
const turso = createClient({ | |
org: "bluvo", | |
token: TURSO_API_TOKEN, | |
}); | |
const dbs = await turso | |
.databases | |
.list(); | |
return dbs | |
// My "tenant-dbs" have long names. | |
.filter(db=>db.name.length > 'my-main-db'.length) | |
.map(db => db.hostname); | |
} | |
export const getDB = (orgHostName: string) => { | |
const workplaceClient = createTursoClient({ | |
url: `libsql://${orgHostName}`, | |
authToken: DEFAULT_API_TOKEN, | |
}); | |
return drizzle(workplaceClient, { | |
schema | |
}); | |
}; | |
(async ()=>{ | |
const dbHostNames = await listDBs(); | |
// for each one of those dbHostNames apply the migrate script for the current schema | |
for(const dbHostName of dbHostNames) { | |
console.log(`⏳ Running migration for ${dbHostName}...`); | |
const start = Date.now(); | |
await migrateDB(dbHostName); | |
console.log("✅ Migrations completed in", Date.now() - start, "ms"); | |
await sleep(250); | |
} | |
})(); | |
async function sleep(ms:number) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
const migrateDB = async (orgHostName: string) => { | |
const db = getDB(orgHostName); | |
await migrate(db, { | |
migrationsFolder: "../drizzle/org-migrations", | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment