Sequelize Auto Model Generator

0.8.8 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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.

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);
}

view raw JSON →