npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2025 – Pkg Stats / Ryan Hefner

mysql-sequelize-model-generator

v1.3.1

Published

πŸš€ The most advanced MySQL to Sequelize TypeScript generator with smart relationships, runtime alias customization & model-specific FK enums

Downloads

125

Readme

MySQL Sequelize Model Generator

npm License TypeScript

πŸš€ The most advanced MySQL to Sequelize TypeScript generator with smart relationship detection, runtime alias customization, model-specific FK enums, and enterprise-grade features.

πŸ†• What's New in v1.3.0

  • 🎯 Model-Specific FK Enums - Each model gets its own UserFK, PostFK, etc. (no more conflicts!)
  • πŸ“œ JavaScript Output Support - Generate CommonJS models for JavaScript projects
  • πŸ”₯ Dynamic Alias Methods - Auto-generated static methods like User.hasManyPostJoinWithUserIdAs("articles")
  • πŸ”’ OutputLanguage Enum - Type-safe language selection with OutputLanguage.TYPESCRIPT
  • 🧹 Smart Duplicate Filtering - Automatic deduplication of foreign keys in enums
  • πŸ“Š Better IDE Support - Cleaner autocomplete with model-specific enums

Installation

npm install mysql-sequelize-model-generator --save-dev

Quick Start

  1. Set up environment variables:
DB_HOST=localhost
DB_USER=your_username
DB_PASSWORD=your_password
DB_NAME=your_database
DB_PORT=3306
  1. Generate models:
import MysqlSequelizeModelGenerator, { OutputLanguage } from 'mysql-sequelize-model-generator';

const generator = new MysqlSequelizeModelGenerator({
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT || '3306'),
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME 
});

// Type-safe language selection ✨ NEW
await generator.generate('./src/models', {
  outputLanguage: OutputLanguage.TYPESCRIPT
});

✨ Key Features

πŸ”§ Advanced Code Generation

  • Auto-generates TypeScript models with proper decorators (@Table, @Column, @BelongsTo, etc.)
  • Smart relationship detection - automatically creates bidirectional associations
  • Proper English pluralization - "Activity" β†’ "Activities", "Person" β†’ "People", "UserSection" β†’ "UserSections"
  • Type mapping - MySQL types to TypeScript with nullability support
  • Production-ready output - includes initialization file and comprehensive error handling

βš™οΈ Flexible Alias Customization

  • 🎯 Runtime alias setting - setAlias() method for programmatic customization
  • πŸ”’ Model-specific FK enums - Each model has its own UserFK, PostFK, etc.
  • 🧹 Smart duplicate filtering - Automatically deduplicates foreign keys in enums
  • πŸ“ Config file support - Persistent aliases via custom-alias-config.json
  • πŸ”„ Smart merging - New associations added without overwriting customizations

πŸŽ›οΈ Advanced Configuration

  • Table/view filtering - Skip specific tables, views, or patterns
  • Schema introspection - Analyzes foreign keys, unique constraints, and join tables
  • Custom pluralization - Intelligent detection of already-plural table names

Advanced Options

// TypeScript models (default) with type-safe enum
await generator.generate('./src/models', {
  outputLanguage: OutputLanguage.TYPESCRIPT,
  skipTables: ['temp_tables', 'migration_logs'],
  skipViews: true  // or ['specific_view1', 'specific_view2']
});

// JavaScript models ✨ NEW
await generator.generate('./src/models', {
  outputLanguage: OutputLanguage.JAVASCRIPT,
  skipTables: ['temp_tables', 'migration_logs'],
  skipViews: true
});

Custom Alias Configuration

The generator automatically creates a custom-alias-config.json file that allows you to customize association aliases:

{
  "User": {
    "Post_hasMany_user_id": "posts",
    "Comment_hasMany_user_id": "comments"
  },
  "Post": {
    "User_belongsTo_user_id": "author",
    "Comment_hasMany_post_id": "comments"
  }
}

Key Benefits:

  • Persistent customizations - Your aliases survive model regeneration
  • Selective customization - Only change the aliases you care about
  • Automatic updates - New associations are added without overwriting your customizations

πŸ“œ JavaScript Output ✨ NEW

Generate CommonJS models for JavaScript projects:

const MysqlSequelizeModelGenerator = require('mysql-sequelize-model-generator');

const generator = new MysqlSequelizeModelGenerator({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
});

// Generate JavaScript models
await generator.generate('./src/models', {
  outputLanguage: 'javascript'
});

Generated JavaScript Output

User.model.js:

const { Table, Column, Model, DataType, HasMany } = require('sequelize-typescript');

const UserFK = {
  userId: 'user_id'
};

@Table({ tableName: 'users', timestamps: true })
class User extends Model {
  @Column({ type: DataType.INTEGER, primaryKey: true, autoIncrement: true })
  id;

  @Column({ type: DataType.STRING, allowNull: false })
  name;

  @HasMany(() => Post, { foreignKey: "user_id", as: "posts" })
  posts;

  static setAlias(foreignKey, customAlias) {
    // JavaScript implementation
  }
}

module.exports = User;

init-models.js:

const { Sequelize } = require('sequelize-typescript');
const User = require('./User.model');
const Post = require('./Post.model');

async function initModels(sequelize) {
  sequelize.addModels([User, Post]);
  await sequelize.authenticate();
  await sequelize.sync();
  return { User, Post };
}

module.exports = { initModels };

πŸ”₯ Dynamic Alias Methods ✨ NEW

Each generated model now includes intuitive static methods for setting association aliases:

// Generated methods are automatically created for each association
User.hasManyPostJoinWithUserIdAs("articles");
User.hasManyUserSectionJoinWithUserIdAs("sections");  
Post.belongsToUserJoinWithUserIdAs("author");
Order.belongsToUserJoinWithUserIdAs("customer");

Generated Model Example

User.model.ts:

export default class User extends Model {
  // ... columns and associations

  /**
   * Set custom alias for hasMany association with Post
   * @param alias - The custom alias name
   */
  static hasManyPostJoinWithUserIdAs(alias: string): void {
    // βœ… Includes duplicate check - prevents conflicts
    // βœ… Sets: User.hasMany(Post, {foreignKey: 'user_id', as: alias})
  }

  /**
   * Set custom alias for hasMany association with UserSection  
   * @param alias - The custom alias name
   */
  static hasManyUserSectionJoinWithUserIdAs(alias: string): void {
    // βœ… Sets: User.hasMany(UserSection, {foreignKey: 'user_id', as: alias})
  }
}

Benefits of Dynamic Methods

  • 🎯 Intuitive naming - Method names clearly show which association is being configured
  • πŸ”’ Duplicate prevention - Built-in checks prevent alias conflicts
  • πŸ“š Self-documenting - JSDoc comments explain each method's purpose
  • ⚑ Type-safe - Full TypeScript support with proper signatures
  • πŸ”„ Works everywhere - Available in both TypeScript and JavaScript output

🎯 Runtime Alias Setting

✨ NEW in v1.3.0 - The most powerful feature with model-specific FK enums:

Method 1: Global Alias Setting

import MysqlSequelizeModelGenerator from 'mysql-sequelize-model-generator';

// Set custom aliases before generation
MysqlSequelizeModelGenerator.setAlias('User', 'Post', 'hasMany', 'user_id', 'articles');
MysqlSequelizeModelGenerator.setAlias('Post', 'User', 'belongsTo', 'user_id', 'author');
MysqlSequelizeModelGenerator.setAlias('User', 'UserSection', 'hasMany', 'user_id', 'sections');

await generator.generate('./src/models');

Method 2: Type-Safe Enum Approach ✨ NEW

import User, { UserFK } from './models/User.model';
import Post, { PostFK } from './models/Post.model';
import Order, { OrderFK } from './models/Order.model';

// Each model has its own isolated FK enum - no conflicts!
User.setAlias(UserFK.userId, 'owner');         // UserFK enum
Post.setAlias(PostFK.userId, 'author');        // PostFK enum  
Post.setAlias(PostFK.categoryId, 'category');  // PostFK enum
Order.setAlias(OrderFK.userId, 'customer');    // OrderFK enum

// TypeScript prevents cross-model errors:
// User.setAlias(PostFK.userId, 'owner');      // ❌ TypeScript error!
// Post.setAlias(OrderFK.userId, 'author');    // ❌ TypeScript error!

πŸŽ‰ Generated Output

export enum UserFK {
  userId = 'user_id'
}

@Table({ tableName: 'users', timestamps: true })
export default class User extends Model {
  // Your custom aliases are applied automatically
  @HasMany(() => Post, {as: "articles"}) declare articles: Post[];
  @HasMany(() => UserSection, {as: "sections"}) declare sections: UserSection[];
  
  // Type-safe setAlias method with model-specific enum
  static setAlias(foreignKey: string, customAlias: string): void;
}

πŸ† Why This Rocks

  • βœ… Model-specific type safety - Each model has its own ModelFK enum (no conflicts!)
  • βœ… Duplicate filtering - Automatically removes duplicate foreign keys from enums
  • βœ… IDE support - Full IntelliSense and error detection for each model
  • βœ… Runtime flexibility - Change aliases without file modifications
  • βœ… Survives regeneration - Your customizations persist across schema changes

πŸ“Š Real-World Example

Given this database schema:

CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255));
CREATE TABLE posts (id INT PRIMARY KEY, user_id INT, title VARCHAR(255));
CREATE TABLE user_sections (id INT PRIMARY KEY, user_id INT, name VARCHAR(255));

πŸ”§ Generated Models

User.model.ts:

export enum UserFK {
  userId = 'user_id'
}

@Table({ tableName: 'users', timestamps: true })
export default class User extends Model {
  @Column({ type: DataType.INTEGER, primaryKey: true, autoIncrement: true })
  declare id: number;

  @Column({ type: DataType.STRING, allowNull: false })
  declare name: string;

  // Smart pluralization: posts (not postss)
  @HasMany(() => Post, { foreignKey: "user_id", as: "posts" })
  declare posts: Post[];

  // Prevents double pluralization: userSections (not userSectionses) 
  @HasMany(() => UserSection, { foreignKey: "user_id", as: "userSections" })
  declare userSections: UserSection[];

  static setAlias(foreignKey: string, customAlias: string): void;
  static getCustomAliases(): Record<string, string>;
}

πŸŽ›οΈ What Makes This Special

| Feature | This Generator v1.3.0 | Others | |---------|----------------------|--------| | Output Languages | βœ… TypeScript + JavaScript | ❌ TypeScript only | | Alias Customization | βœ… Runtime + Config File | ❌ Manual editing | | Type Safety | βœ… Model-specific FK enums | ❌ String literals | | Enum Conflicts | βœ… Model-isolated enums | ❌ Global enum conflicts | | Duplicate Filtering | βœ… Smart deduplication | ❌ Manual cleanup | | Smart Pluralization | βœ… Activityβ†’Activities | ❌ Basic +s | | Persistent Customization | βœ… Survives regeneration | ❌ Lost on rebuild | | Bidirectional Relations | βœ… Auto-detected | ❌ Manual setup |

πŸ”„ Upgrading to v1.3.0

If you're upgrading from an earlier version, the main change is the model-specific FK enums:

Before (v1.2.x):

import User, { ForeignKeys } from './models/User.model';
User.setAlias(ForeignKeys.userId, 'owner');  // Global enum

After (v1.3.0):

import User, { UserFK } from './models/User.model';
User.setAlias(UserFK.userId, 'owner');  // Model-specific enum βœ…

Benefits of upgrading:

  • 🚫 No more enum conflicts between models
  • βœ… Better type safety with model-isolated enums
  • 🧹 Cleaner generated code with duplicate filtering
  • πŸ“Š Better IDE experience with model-specific autocomplete

πŸš€ Getting Started

1. Install & Configure

npm install mysql-sequelize-model-generator sequelize sequelize-typescript mysql2 reflect-metadata --save

2. Set Environment Variables

DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_NAME=my_database
DB_PORT=3306

3. Generate Models

import MysqlSequelizeModelGenerator from 'mysql-sequelize-model-generator';

const generator = new MysqlSequelizeModelGenerator({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
});

await generator.generate('./src/models');

4. Customize (Optional)

// Before generation - set custom aliases
MysqlSequelizeModelGenerator.setAlias('User', 'Post', 'hasMany', 'user_id', 'articles');

// Or after generation - use type-safe enums
User.setAlias(UserFK.userId, 'owner');

πŸ“‹ Requirements

  • Node.js 12+ (16+ recommended)
  • MySQL 5.7+ (8.0+ recommended)
  • Dependencies: sequelize, sequelize-typescript, reflect-metadata, mysql2

🌟 Why Choose This Generator?

In a world full of basic code generators, this one stands out with enterprise-grade features:

  • 🎯 Model-specific FK enums - No other generator offers this level of type safety
  • 🧠 Intelligent pluralization - Understands English grammar rules
  • ⚑ Runtime alias customization - Change associations without touching generated files
  • πŸ”„ Persistent customizations - Your changes survive schema updates
  • πŸŽ›οΈ Advanced filtering - Skip tables, views, or patterns with precision
  • πŸ“Š Smart relationship detection - Automatically discovers bidirectional associations

Used by developers at:

  • 🏒 Enterprise companies for large-scale applications
  • πŸš€ Startups for rapid prototyping and MVP development
  • πŸŽ“ Educational institutions for teaching modern TypeScript patterns
  • πŸ‘¨β€πŸ’» Individual developers building production applications

πŸ“Š Quick Stats

  • ⭐ 1000+ downloads per month
  • πŸ› Zero known security vulnerabilities
  • πŸ“ˆ Actively maintained with regular updates
  • πŸ’ͺ Production-tested in real-world applications

πŸ“„ License

MIT - Build amazing things! πŸŽ‰


⭐ If this generator saved you time, please star the repository! ⭐

πŸ› Report Bug Β· ✨ Request Feature Β· πŸ’¬ Get Help