1001Ferramentas
๐ŸฆŠ Generators

Sequelize Model Generator from Table

Generates a Sequelize (JS) model with sequelize.define, columns and timestamps from a table name.

โ€”

Sequelize models: associations, migrations, and validation

Sequelize is the pioneer JavaScript ORM for Node.js, created by Sascha Depold in 2011 โ€” years before TypeScript was popular and well before Prisma existed. It uses a promise-based async API on top of plain ES6 classes, and supports a broad list of SQL dialects: PostgreSQL, MySQL, MariaDB, SQLite, MSSQL, Snowflake, and DB2. Its maturity is its main strength โ€” battle-tested in production for over a decade โ€” while its imperative, somewhat verbose API is the trade-off that pushed newer projects toward Prisma or Drizzle.

This generator emits a starting sequelize.define block; the rest of this guide covers the full model definition syntax, associations, migrations with sequelize-cli, hooks, validations, transactions, and how Sequelize compares to TypeORM and Prisma in 2026.

Defining a model

const { DataTypes } = require('sequelize');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  name: { type: DataTypes.STRING, allowNull: false },
  email: {
    type: DataTypes.STRING,
    unique: true,
    validate: { isEmail: true },
  },
}, {
  timestamps: true,
  paranoid: true, // soft delete via deletedAt
});

Common data types: STRING, TEXT, INTEGER, BIGINT, FLOAT, DECIMAL, BOOLEAN, DATE, UUID, JSON, JSONB (Postgres), ENUM, ARRAY. Options at column level: allowNull, unique, defaultValue, primaryKey, autoIncrement, field (map to a different column name), references (foreign key).

Associations and eager loading

Sequelize represents relationships with four helpers: hasOne, hasMany, belongsTo, and belongsToMany. Declare them after defining each model:

User.hasMany(Post, { foreignKey: 'userId' });
Post.belongsTo(User, { foreignKey: 'userId' });
Article.belongsToMany(Tag, { through: 'ArticleTags' });

// Eager loading โ€” avoids N+1
const users = await User.findAll({
  include: [{ model: Post, where: { published: true } }],
});

The include option generates a JOIN; without it, accessing user.posts requires a separate query and triggers the classic N+1 problem.

Migrations, hooks, transactions

Migrations are managed by sequelize-cli: run npx sequelize-cli migration:generate --name add-user-email to scaffold a file with up() and down(); npx sequelize-cli db:migrate applies pending ones. Hooks (lifecycle) let you intercept events: beforeCreate, afterUpdate, beforeDestroy and more โ€” useful for hashing passwords, emitting events, or audit logging. Validations live on each column: isEmail, len: [min, max], isAlpha, isUrl, plus a custom validate(value) function that throws on invalid input. Transactions come in two flavors: managed (auto-commits on success, auto-rolls back if you throw) and unmanaged (you call t.commit() / t.rollback() yourself).

v6 vs v7, NestJS, comparisons

  • Sequelize v7 (2024) shipped a TypeScript-first rewrite with improved decorators and stricter typings, while v6 remains widely used in legacy apps.
  • NestJS integration: @nestjs/sequelize provides module-level model injection, similar to @nestjs/typeorm.
  • vs TypeORM: Sequelize uses ES6 classes and sequelize.define; TypeORM uses decorators. Sequelize's API is older and more verbose but battle-tested.
  • vs Prisma: Sequelize is imperative (define models in code); Prisma is declarative (one .prisma schema generates a typed client). Prisma wins on DX and type safety; Sequelize wins on dialect breadth and raw flexibility.
  • Raw queries: when an ORM gets in the way, fall back to sequelize.query('SELECT ...', { type: QueryTypes.SELECT }).
  • Pooling: a connection pool is built in โ€” configure via pool: { max, min, idle } in the Sequelize constructor.

FAQ

Is Sequelize better than Prisma? Neither is universally better. Prisma has sharper DX and full type inference; Sequelize has wider dialect support (Snowflake, DB2) and a mature ecosystem of plugins. Pick Prisma for greenfield TypeScript; Sequelize for legacy or polyglot SQL stacks.

Can I run raw SQL? Yes โ€” sequelize.query() takes any SQL string and returns results in the shape you specify. Useful for window functions, CTEs, or vendor-specific syntax the ORM doesn't model.

Do managed transactions roll back on throw? Yes. Wrap your work in await sequelize.transaction(async (t) => { ... }) and any exception thrown inside the callback triggers an automatic rollback.

What is paranoid mode? Setting paranoid: true on the model adds a deletedAt column and makes destroy() a soft delete; queries filter out trashed rows by default, and paranoid: false on a single query brings them back.

Related Tools