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
Maintainers
Readme
MySQL Sequelize Model Generator
π 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-devQuick Start
- Set up environment variables:
DB_HOST=localhost
DB_USER=your_username
DB_PASSWORD=your_password
DB_NAME=your_database
DB_PORT=3306- 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
ModelFKenum (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 enumAfter (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 --save2. Set Environment Variables
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_NAME=my_database
DB_PORT=33063. 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! β
