{"id":17360,"library":"sequelize-auto","title":"Sequelize Auto Model Generator","description":"Sequelize-Auto is a utility that automates the generation of Sequelize ORM models directly from an existing database schema. It supports various SQL dialects including MySQL/MariaDB, PostgreSQL, SQLite, and MSSQL. The current stable version is 0.8.8, and it is primarily a command-line interface tool, though it also offers programmatic usage. Its main purpose is to reduce manual boilerplate by converting an existing database structure into ready-to-use Sequelize model definitions, including basic column definitions and data types. Users must install Sequelize and the specific database dialect driver separately, as these are no longer direct dependencies.","status":"active","version":"0.8.8","language":"javascript","source_language":"en","source_url":"https://github.com/sequelize/sequelize-auto","tags":["javascript","mysql","mssql","sqlite","postgres","sequelize","sequelizejs","generator","mapper","typescript"],"install":[{"cmd":"npm install sequelize-auto","lang":"bash","label":"npm"},{"cmd":"yarn add sequelize-auto","lang":"bash","label":"yarn"},{"cmd":"pnpm add sequelize-auto","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core ORM library required for generated models and sequelize-auto's internal operations.","package":"sequelize","optional":false},{"reason":"MySQL/MariaDB dialect driver. Required if connecting to MySQL or MariaDB databases.","package":"mysql2","optional":true},{"reason":"PostgreSQL dialect driver. Required if connecting to PostgreSQL databases.","package":"pg","optional":true},{"reason":"PostgreSQL HSTORE type support. Often used in conjunction with 'pg' for PostgreSQL.","package":"pg-hstore","optional":true},{"reason":"SQLite dialect driver. Required if connecting to SQLite databases.","package":"sqlite3","optional":true},{"reason":"MSSQL dialect driver. Required if connecting to Microsoft SQL Server databases.","package":"tedious","optional":true}],"imports":[{"note":"For CommonJS environments (default for this package), this is the correct way to import the main class for programmatic use.","wrong":"import SequelizeAuto from 'sequelize-auto';","symbol":"SequelizeAuto","correct":"const SequelizeAuto = require('sequelize-auto');"},{"note":"For ECMAScript Modules (ESM) projects, `sequelize-auto` is typically imported as a default export, often requiring bundler configuration or specific `package.json` setup for dual CJS/ESM support.","wrong":"const SequelizeAuto = require('sequelize-auto');","symbol":"SequelizeAuto","correct":"import SequelizeAuto from 'sequelize-auto';"},{"note":"This type import provides definitions for the options object passed to the `SequelizeAuto` constructor when using it programmatically in TypeScript projects.","symbol":"AutoOptions","correct":"import type { AutoOptions } from 'sequelize-auto';"}],"quickstart":{"code":"const { execSync } = require('child_process');\nconst path = require('path');\n\n// --- Prerequisites ---\n// 1. Install sequelize and a dialect driver (e.g., mysql2):\n//    npm install sequelize mysql2\n// 2. Ensure a database and table exist, e.g., for MySQL:\n//    CREATE DATABASE my_auto_db;\n//    USE my_auto_db;\n//    CREATE TABLE products (\n//      id INT PRIMARY KEY AUTO_INCREMENT,\n//      name VARCHAR(255) NOT NULL,\n//      price DECIMAL(10, 2) DEFAULT 0.00\n//    );\n//    INSERT INTO products (name, price) VALUES ('Laptop', 1200.00);\n\n// --- Configuration ---\nconst outputDir = path.join(__dirname, 'generated_models');\nconst host = process.env.DB_HOST ?? 'localhost';\nconst user = process.env.DB_USER ?? 'root';\nconst password = process.env.DB_PASSWORD ?? 'password'; // !! Use secure methods for passwords in production\nconst database = 'my_auto_db';\nconst dialect = 'mysql';\nconst tableName = 'products';\n\n// Ensure the output directory exists\ntry {\n  execSync(`mkdir -p ${outputDir}`);\n  console.log(`Ensured output directory: ${outputDir}`);\n} catch (e) {\n  console.error('Failed to create output directory:', e.message);\n  process.exit(1);\n}\n\n// --- Run sequelize-auto CLI ---\nconst cliCommand = [\n  'sequelize-auto',\n  `-h ${host}`,\n  `-d ${database}`,\n  `-u ${user}`,\n  `-x ${password}`,\n  `--dialect ${dialect}`,\n  `-o ${outputDir}`,\n  `-t ${tableName}`\n].join(' ');\n\nconsole.log(`\nExecuting CLI command: ${cliCommand}\n`);\n\ntry {\n  const stdout = execSync(cliCommand, { encoding: 'utf8', stdio: 'pipe' });\n  console.log('Sequelize models generated successfully:');\n  console.log(stdout);\n  console.log(`\nCheck the '${outputDir}' directory for generated model files.`);\n\n  // --- Example of programmatic usage (after models are generated) ---\n  console.log('\\n--- Demonstrating programmatic usage of generated models (conceptual) ---');\n  const { Sequelize, DataTypes } = require('sequelize');\n  const sequelize = new Sequelize(database, user, password, {\n    host,\n    dialect,\n    logging: false // Suppress Sequelize SQL logging\n  });\n\n  // Dynamically require the generated model\n  // Note: The actual model file name might vary based on case options (e.g., 'product.js' or 'Product.js')\n  const ProductModel = require(path.join(outputDir, tableName.charAt(0).toUpperCase() + tableName.slice(1))) (sequelize, DataTypes);\n\n  async function fetchProduct() {\n    try {\n      await sequelize.authenticate();\n      console.log('Database connection successful.');\n      const product = await ProductModel.findOne({ where: { name: 'Laptop' } });\n      if (product) {\n        console.log('Found product:', product.toJSON());\n      } else {\n        console.log('Product not found.');\n      }\n    } catch (error) {\n      console.error('Error during database operation:', error);\n    } finally {\n      await sequelize.close();\n      console.log('Database connection closed.');\n    }\n  }\n\n  fetchProduct();\n\n} catch (error) {\n  console.error('\\nFailed to generate Sequelize models:');\n  console.error(error.message);\n  if (error.stderr) {\n    console.error('Stderr:', error.stderr);\n  }\n  process.exit(1);\n}","lang":"javascript","description":"This quickstart demonstrates how to use `sequelize-auto` via its command-line interface to generate Sequelize models from an existing MySQL database table, including setup instructions and a conceptual example of using the generated model programmatically."},"warnings":[{"fix":"Run `npm install sequelize <dialect-driver>` (e.g., `npm install sequelize mysql2`) in your project.","message":"As of a prior major version, `sequelize-auto` no longer includes `sequelize` as a direct dependency. Users must manually install `sequelize` and the appropriate dialect driver (e.g., `mysql2`, `pg`, `sqlite3`, `tedious`) separately. Failing to do so will result in 'module not found' errors.","severity":"breaking","affected_versions":">=0.5.0 (based on project history, though specific version change is not in excerpt)"},{"fix":"Always test generated models thoroughly with your specific `sequelize` version. For critical applications, consider explicitly pinning to a `sequelize` version known to be compatible, such as `^5` or `^6`, and review `sequelize`'s breaking changes for newer versions.","message":"The peer dependency for `sequelize` is specified as `>3.30.0`. While `sequelize-auto` may function with modern `sequelize` versions (v6/v7), this broad and older range can lead to unexpected behavior or incompatibilities if breaking changes were introduced in `sequelize` versions not fully anticipated by `sequelize-auto`.","severity":"gotcha","affected_versions":">=0.8.0"},{"fix":"For production or automated scripts, prefer securing credentials using environment variables (e.g., `process.env.DB_PASSWORD`), configuration files (`-c`), or interactive prompts when appropriate, rather than hardcoding passwords in commands.","message":"When using the `--pass` (or `-x`) option, if no password value is provided, `sequelize-auto` will interactively prompt for the password in the terminal. Directly providing passwords in command-line arguments can pose security risks (e.g., shell history).","severity":"gotcha","affected_versions":">=0.8.0"},{"fix":"Ensure that any JSON configuration files are syntactically correct and contain valid options as per the Sequelize documentation for constructor options (for `-c`) and `Model.init` options (for `-a`).","message":"The `-c` (config) and `-a` (additional) options expect paths to JSON files for Sequelize options and model options, respectively. Incorrect JSON formatting or invalid Sequelize-specific options in these files can lead to generation failures or malformed models.","severity":"gotcha","affected_versions":">=0.8.0"},{"fix":"Use TypeScript 4.x or newer when generating TypeScript models. If using ES modules, ensure your `tsconfig.json` and Node.js environment are correctly configured for ESM support.","message":"Generated model files, especially for TypeScript (`-l ts`), rely on specific Sequelize versions and TypeScript configurations. Older TypeScript versions (pre-4.x) might fail to compile generated TypeScript models due to syntax or feature usage.","severity":"gotcha","affected_versions":">=0.8.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Install `sequelize` as a project dependency: `npm install sequelize` or `yarn add sequelize`.","cause":"The `sequelize` package is not installed or not resolvable in the current project's `node_modules`.","error":"Error: Cannot find module 'sequelize'"},{"fix":"Install the required driver package: `npm install <dialect-driver-package>` (e.g., `npm install mysql2` for MySQL/MariaDB).","cause":"The specific database dialect driver (e.g., `mysql2`, `pg`, `sqlite3`, `tedious`) corresponding to the `--dialect` option is missing.","error":"Error: Please install the '<dialect-driver>' package manually"},{"fix":"Verify the `-h`, `-d`, `-u`, `-x`, `-p` options. Check your database server status, credentials, firewall rules, and network connectivity.","cause":"Incorrect database connection parameters (host, user, password, port, database name) or the database server is inaccessible/not running.","error":"Unhandled rejection SequelizeConnectionError: Access denied for user 'user'@'host' (or similar connection error)"},{"fix":"Create the output directory manually before running `sequelize-auto`: `mkdir -p /path/to/models` (or `New-Item -Path /path/to/models -ItemType Directory` on Windows).","cause":"The directory specified by the `-o` or `--output` option for generated models does not exist.","error":"Error: Output directory does not exist: /path/to/models"}],"ecosystem":"npm","meta_description":null}