Sequelize Auto Model Generator
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.
Common errors
-
Error: Cannot find module 'sequelize'
cause The `sequelize` package is not installed or not resolvable in the current project's `node_modules`.fixInstall `sequelize` as a project dependency: `npm install sequelize` or `yarn add sequelize`. -
Error: Please install the '<dialect-driver>' package manually
cause The specific database dialect driver (e.g., `mysql2`, `pg`, `sqlite3`, `tedious`) corresponding to the `--dialect` option is missing.fixInstall the required driver package: `npm install <dialect-driver-package>` (e.g., `npm install mysql2` for MySQL/MariaDB). -
Unhandled rejection SequelizeConnectionError: Access denied for user 'user'@'host' (or similar connection error)
cause Incorrect database connection parameters (host, user, password, port, database name) or the database server is inaccessible/not running.fixVerify the `-h`, `-d`, `-u`, `-x`, `-p` options. Check your database server status, credentials, firewall rules, and network connectivity. -
Error: Output directory does not exist: /path/to/models
cause The directory specified by the `-o` or `--output` option for generated models does not exist.fixCreate the output directory manually before running `sequelize-auto`: `mkdir -p /path/to/models` (or `New-Item -Path /path/to/models -ItemType Directory` on Windows).
Warnings
- breaking 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.
- gotcha 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`.
- gotcha 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).
- gotcha 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.
- gotcha 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.
Install
-
npm install sequelize-auto -
yarn add sequelize-auto -
pnpm add sequelize-auto
Imports
- SequelizeAuto
import SequelizeAuto from 'sequelize-auto';
const SequelizeAuto = require('sequelize-auto'); - SequelizeAuto
const SequelizeAuto = require('sequelize-auto');import SequelizeAuto from 'sequelize-auto';
- AutoOptions
import type { AutoOptions } from 'sequelize-auto';
Quickstart
const { execSync } = require('child_process');
const path = require('path');
// --- Prerequisites ---
// 1. Install sequelize and a dialect driver (e.g., mysql2):
// npm install sequelize mysql2
// 2. Ensure a database and table exist, e.g., for MySQL:
// CREATE DATABASE my_auto_db;
// USE my_auto_db;
// CREATE TABLE products (
// id INT PRIMARY KEY AUTO_INCREMENT,
// name VARCHAR(255) NOT NULL,
// price DECIMAL(10, 2) DEFAULT 0.00
// );
// INSERT INTO products (name, price) VALUES ('Laptop', 1200.00);
// --- Configuration ---
const outputDir = path.join(__dirname, 'generated_models');
const host = process.env.DB_HOST ?? 'localhost';
const user = process.env.DB_USER ?? 'root';
const password = process.env.DB_PASSWORD ?? 'password'; // !! Use secure methods for passwords in production
const database = 'my_auto_db';
const dialect = 'mysql';
const tableName = 'products';
// Ensure the output directory exists
try {
execSync(`mkdir -p ${outputDir}`);
console.log(`Ensured output directory: ${outputDir}`);
} catch (e) {
console.error('Failed to create output directory:', e.message);
process.exit(1);
}
// --- Run sequelize-auto CLI ---
const cliCommand = [
'sequelize-auto',
`-h ${host}`,
`-d ${database}`,
`-u ${user}`,
`-x ${password}`,
`--dialect ${dialect}`,
`-o ${outputDir}`,
`-t ${tableName}`
].join(' ');
console.log(`
Executing CLI command: ${cliCommand}
`);
try {
const stdout = execSync(cliCommand, { encoding: 'utf8', stdio: 'pipe' });
console.log('Sequelize models generated successfully:');
console.log(stdout);
console.log(`
Check the '${outputDir}' directory for generated model files.`);
// --- Example of programmatic usage (after models are generated) ---
console.log('\n--- Demonstrating programmatic usage of generated models (conceptual) ---');
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize(database, user, password, {
host,
dialect,
logging: false // Suppress Sequelize SQL logging
});
// Dynamically require the generated model
// Note: The actual model file name might vary based on case options (e.g., 'product.js' or 'Product.js')
const ProductModel = require(path.join(outputDir, tableName.charAt(0).toUpperCase() + tableName.slice(1))) (sequelize, DataTypes);
async function fetchProduct() {
try {
await sequelize.authenticate();
console.log('Database connection successful.');
const product = await ProductModel.findOne({ where: { name: 'Laptop' } });
if (product) {
console.log('Found product:', product.toJSON());
} else {
console.log('Product not found.');
}
} catch (error) {
console.error('Error during database operation:', error);
} finally {
await sequelize.close();
console.log('Database connection closed.');
}
}
fetchProduct();
} catch (error) {
console.error('\nFailed to generate Sequelize models:');
console.error(error.message);
if (error.stderr) {
console.error('Stderr:', error.stderr);
}
process.exit(1);
}