Skip to content

DivinPrince/sequelize-schema-sync

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

30 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

sequelize-schema-sync

πŸ”₯ Drizzle-like migrations for Sequelize - Automatically generate migrations from your Sequelize models, just like Drizzle ORM but for Sequelize!

npm version License: MIT

✨ Features

  • πŸ“¦ Models as Source of Truth - Define your schema using Sequelize models
  • πŸ”„ Automatic Migration Generation - Compare models vs database and generate migrations
  • πŸš€ CLI Commands - Simple commands for generate, migrate, and rollback
  • πŸ“ TypeScript Support - Full TypeScript support with type definitions
  • 🎯 Powered by Umzug - Built on the reliable Umzug migration framework
  • πŸ› οΈ Production Ready - Handles complex schema changes, foreign keys, and more
  • πŸ“ Directory-based Loading - Auto-discover models from directories
  • πŸ” Dry-run Mode - Preview changes before generating migrations
  • 🎲 Smart Naming - Auto-generates migration names when not provided

πŸš€ Quick Start

Installation

npm install sequelize-schema-sync
# or
yarn add sequelize-schema-sync

Basic Setup

  1. Initialize configuration:
npx sequelize-schema-sync init
  1. Configure your models in schema-sync.config.ts:
import { Sequelize } from 'sequelize';
import { SchemaSyncConfig } from 'sequelize-schema-sync';
import { User } from './models/User';
import { Post } from './models/Post';

const sequelize = new Sequelize({
  dialect: 'postgres', // or 'mysql', 'sqlite', etc.
  host: 'localhost',
  database: 'myapp',
  username: 'user',
  password: 'password',
});

const config: SchemaSyncConfig = {
  sequelize,
  // Option 1: Provide models array directly
  models: [User, Post],
  // Option 2: Auto-discover from directory (recommended)
  // modelsPath: './models',
  migrationsPath: './migrations',
};

export default config;
  1. Generate your first migration:
npx sequelize-schema-sync generate
  1. Apply migrations:
npx sequelize-schema-sync migrate

πŸ“‹ CLI Commands

generate

Generate a new migration based on model changes

npx sequelize-schema-sync generate
npx sequelize-schema-sync generate --name "add_user_avatar"
npx sequelize-schema-sync generate --dry-run

Options:

  • -n, --name <name> - Custom migration name
  • --dry-run - Preview changes without generating files

migrate

Run all pending migrations

npx sequelize-schema-sync migrate

rollback

Rollback the last applied migration

npx sequelize-schema-sync rollback

status

Show migration status

npx sequelize-schema-sync status

init

Initialize a new schema-sync.config.ts file

npx sequelize-schema-sync init

πŸ“– How It Works

  1. Define Models: Create your Sequelize models as usual
  2. Run Generate: The tool compares your models against the current database schema
  3. Automatic Diff: Detects changes like new tables, columns, type changes, etc.
  4. Generate Migration: Creates a timestamped migration file with up and down functions
  5. Apply Changes: Use the migrate command to apply changes to your database

πŸ—οΈ Example Migration

When you change your models, the tool generates migrations like this:

import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.createTable('users', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  });
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('users');
}

πŸ“ Model Loading Options

Option 1: Direct Model Array (Simple)

const config: SchemaSyncConfig = {
  sequelize,
  models: [User, Post, Comment], // Import and list your models
  migrationsPath: './migrations',
};

Option 2: Directory-based Loading (Recommended)

const config: SchemaSyncConfig = {
  sequelize,
  modelsPath: './models', // Auto-discover models from directory
  migrationsPath: './migrations',
};

Model Factory Pattern:

// models/User.ts
export const UserModel = (sequelize: Sequelize) => {
  const User = sequelize.define('User', {
    email: DataTypes.STRING,
    name: DataTypes.STRING,
  });

  return User;
};

πŸ” Dry-run Mode

Preview what changes will be made before generating migrations:

npx sequelize-schema-sync generate --dry-run

Example Output:

πŸ“Š Schema Analysis Results:
==================================================
Found 2 table(s) with changes:

πŸ“„ Table: users
   Action: alter
   β†’ Will modify 2 column(s):
     - email: change
     - avatar: add

πŸ“„ Table: posts
   Action: create
   β†’ Will create table with 5 columns: id, title, content, userId, createdAt

πŸ’‘ To generate the migration file, run without --dry-run flag

🎯 Supported Schema Changes

  • βœ… Create new tables
  • βœ… Drop tables
  • βœ… Add columns
  • βœ… Remove columns
  • βœ… Change column types
  • βœ… Add/remove primary keys
  • βœ… Add/remove auto-increment
  • βœ… Add/remove unique constraints
  • βœ… Change default values
  • βœ… Add/remove foreign keys

πŸ› οΈ Advanced Configuration

const config: SchemaSyncConfig = {
  sequelize,
  modelsPath: './models',
  migrationsPath: './migrations',
  // Optional: Custom config path
  configPath: './custom-config.ts',
};

βš™οΈ Sequelize Define Options

Configure global options for all your models using Sequelize's define option:

Basic Configuration

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: './database.sqlite',
  
  // Global define options for all models
  define: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    // Use snake_case for all auto-generated fields (timestamps, foreign keys, etc.)
    underscored: true,
    // Prevent table name pluralization
    freezeTableName: true,
    timestamps: true,
  },
});

MySQL/MariaDB Configuration

For MySQL and MariaDB, set charset and collation in both define and dialectOptions:

const sequelize = new Sequelize({
  dialect: 'mysql',
  host: 'localhost',
  database: 'myapp',
  username: 'user',
  password: 'password',
  
  // MySQL-specific options
  dialectOptions: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
  },
  
  // Global define options
  define: {
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    // Use snake_case for all auto-generated fields (timestamps, foreign keys, etc.)
    underscored: true,
    freezeTableName: true,
    timestamps: true,
  },
});

Define Options Explained

Option Description Example
charset Character set for tables 'utf8mb4'
collate Collation for string comparisons 'utf8mb4_general_ci'
underscored Use snake_case for all auto-generated fields true β†’ createdAt becomes created_at, userId becomes user_id
freezeTableName Prevent table name pluralization true β†’ User table stays User, not Users
timestamps Add createdAt/updatedAt automatically true

Model Override Example

Individual models can override global define options:

// models/User.ts
export const UserModel = (sequelize: Sequelize) => {
  return User.init({
    email: DataTypes.STRING,
    firstName: DataTypes.STRING, // Will be first_name in DB with underscored: true
  }, {
    sequelize,
    modelName: 'User',
    // Global options apply, but you can override:
    // freezeTableName: false, // Would override global setting
    // underscored: false,     // Would override global setting
  });
};

πŸ“š Examples

Check out the example/ directory for complete working examples:

  • Directory-based model loading
  • Factory function patterns
  • TypeScript migration generation
  • Migration execution and rollback

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

οΏ½ Acknowledgments

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published