{"library":"migrate","title":"Node Migrate","description":"Node Migrate is an abstract migration framework designed for Node.js applications, offering both a command-line interface (CLI) and a programmatic API for managing schema or data changes. As of its latest version, 2.1.0, it provides a flexible mechanism to create, apply, and rollback migrations, supporting various database types through custom logic within migration files. It distinguishes itself by providing a simple, generator-based approach to migration file creation, allowing users to define their own templates and compilers (like Babel or TypeScript) for modern JavaScript features. The package prioritizes flexibility, enabling developers to integrate it into diverse project setups. Its release cadence is not explicitly stated but appears to be stable with infrequent major updates, making it a reliable choice for established Node.js projects requiring robust migration management.","language":"javascript","status":"maintenance","last_verified":"Sun Apr 19","install":{"commands":["npm install migrate"],"cli":{"name":"migrate","version":null}},"imports":["const migrate = require('migrate');","migrate.load({ stateStore: '.migrate' }, function (err, set) { /* ... */ });","exports.up = function (next) { /* ... */ next(); }\nexports.down = async function () { /* ... */ }"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import migrate from 'migrate';\nimport { resolve } from 'path';\nimport { existsSync, mkdirSync, writeFileSync } from 'fs';\n\n// Mock database object shared across migrations.\n// In a real application, this would be your actual database client or ORM connection.\nconst mockGlobalDb: { users?: string[]; products?: string[]; } = {};\n\n// Paths for migrations and state store\nconst migrationsDir = resolve('./migrations_quickstart_simple');\nconst stateStorePath = resolve('./.migrate_quickstart_simple_state');\n\n// Ensure directories and state file exist\nif (!existsSync(migrationsDir)) mkdirSync(migrationsDir);\nif (!existsSync(stateStorePath)) {\n  writeFileSync(stateStorePath, JSON.stringify({ lastRun: null, migrations: [] }), 'utf8');\n}\n\n// Create mock migration files\nconst createUsersMigrationContent = `\n// This 'db' variable refers to 'mockGlobalDb' from the quickstart example.\n// In real migrations, you would typically import or pass your database client.\nexports.up = function (next) {\n  console.log('Running UP: Create Users');\n  // Simulate a database operation\n  module.parent.exports.mockGlobalDb.users = ['Alice', 'Bob'];\n  next();\n};\n\nexports.down = function (next) {\n  console.log('Running DOWN: Drop Users');\n  // Simulate rolling back a database operation\n  delete module.parent.exports.mockGlobalDb.users;\n  next();\n};\n`;\n\nconst addProductsMigrationContent = `\n// This 'db' variable refers to 'mockGlobalDb' from the quickstart example.\nexports.up = async function () { // Using async/await, no 'next' callback needed\n  console.log('Running UP: Add Products');\n  // Simulate a database operation\n  module.parent.exports.mockGlobalDb.products = ['Laptop', 'Mouse'];\n};\n\nexports.down = async function () {\n  console.log('Running DOWN: Remove Products');\n  // Simulate rolling back a database operation\n  delete module.parent.exports.mockGlobalDb.products;\n};\n`;\n\n// Write the migration files for the quickstart to execute\nconst ts1 = Date.now() - 10000;\nconst ts2 = Date.now();\nwriteFileSync(resolve(migrationsDir, `${ts1}-create-users.js`), createUsersMigrationContent, 'utf8');\nwriteFileSync(resolve(migrationsDir, `${ts2}-add-products.js`), addProductsMigrationContent, 'utf8');\n\n// Expose mockGlobalDb so migration files (which are 'require'd) can access it.\n// This is a quickstart hack; in a real app, you'd pass your DB client correctly.\nObject.assign(module.exports, { mockGlobalDb });\n\nconsole.log('Initializing migrations...');\nmigrate.load({\n  stateStore: stateStorePath,\n  migrationsDirectory: migrationsDir\n}, function (err, set) {\n  if (err) {\n    console.error('Failed to load migrations:', err);\n    process.exit(1);\n  }\n\n  console.log('Migrations loaded. Current status:');\n  set.migrations.forEach(m => console.log(`- ${m.title}: ${m.state}`));\n\n  set.up(function (err) {\n    if (err) {\n      console.error('Failed to run UP migrations:', err);\n      process.exit(1);\n    }\n    console.log('\\nAll UP migrations successfully executed!');\n    console.log('Current mock database state:', mockGlobalDb);\n\n    // To demonstrate rolling back, uncomment the following:\n    /*\n    console.log('\\nRunning DOWN to \"create-users\" migration...');\n    set.down('create-users', function(err) {\n      if (err) {\n        console.error('Failed to run DOWN migrations:', err);\n        process.exit(1);\n      }\n      console.log('Successfully rolled back to \"create-users\"!');\n      console.log('Current mock database state after partial DOWN:', mockGlobalDb);\n    });\n    */\n  });\n});","lang":"typescript","description":"This example demonstrates the programmatic API of `migrate`, loading migrations from a temporary directory and executing them against a mock database object, including handling both callback-based and async functions.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}