Run migrations programatically

Is there a way to programatically run new migrations? The use case for this would be in a testing scenario (if I'm not doing something completely wrong here): - When running my tests I'd like to drop all of my existing tables in my database designated for testing - Then I'd like to generate and push the migrations based on the existing schema to the database, which will create the empty tables - Finally I'd like to seed the testing tables with some fake data that I can use as the starting point for my testing I've found this github issue (https://github.com/drizzle-team/drizzle-orm/discussions/1901) mentioning the usage of the undocumented generateDrizzleJson and generateMigration functions from the drizzle-kit/api file. But when I use these functions in my tests setup file, I get the following error: Error: Dynamic require of "fs" is not supported. I'm using DrizzleORM v0.36.4; with NodeJS / Express application written in Typescript and using Vitest as the testing library. Any solutions / workarounds to this? Is there any other way I could programatically run the migrations? I think this is somewhat commonly requested feature.
GitHub
Generating migration commands programmatically · drizzle-team drizz...
We have some sync code that dynamically write tables & columns into our database based on shape of the incoming object. Therefore are not able to use a static schemas.ts file with the existing ...
3 Replies
Mario564
Mario5649mo ago
If you just want to apply migrations, you can make use of the migrate function from the respective driver (drizzle-orm/[driver]/migrate)
pecko0326
pecko0326OP9mo ago
Thanks, will give that a try!
DiamondDragon
DiamondDragon2w ago
man this is annoying . i was trying to use import { pushSchema } from 'drizzle-kit/api' in a vitest test. Also tried using the setup below and the polyfill wasnt working Even if you use migrate, it requires the migration json to be passed in. you can build it manually, but it uses import { generateDrizzleJson, generateMigration } from 'drizzle-kit/api' which require fs
import path from 'node:path'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import { defineConfig, mergeConfig } from 'vitest/config'
import baseConfig from '../../vitest.config'

export default mergeConfig(
baseConfig,
defineConfig({
plugins: [nodePolyfills({ include: ['fs'] })],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
test: {
include: ['src/**/*.test.ts'],
},
}),
)
import path from 'node:path'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import { defineConfig, mergeConfig } from 'vitest/config'
import baseConfig from '../../vitest.config'

export default mergeConfig(
baseConfig,
defineConfig({
plugins: [nodePolyfills({ include: ['fs'] })],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
test: {
include: ['src/**/*.test.ts'],
},
}),
)
but problem is the migrate function needs the json file?

Did you find this page helpful?