SQL → Sequelize TS
Geração de código de banco de dados e ORM

Gerador de Modelos Sequelize TypeScript a partir de SQL DDL

Referência técnica completa para converter instruções SQL CREATE TABLE DDL em modelos Sequelize TypeScript fortemente tipados, definições DataTypes, atributos CreationOptional e chamadas Model.init.

Privacidade 100% no cliente
Zero transmissão ao servidor
Predefinições:
Opções do compilador SQL e mapeamento de esquema
postgres•Model.init
PostgreSQL5 tabelas
Entrada DDL SQL CREATE TABLEPostgreSQL
import { DataTypes, Model, Optional, Sequelize } from 'sequelize';

// ============================================================================
// Sequelize TypeScript Models Generated by ToolsAA
// Dialect: POSTGRES | Syntax: Model.init
// ============================================================================

UserAttributes {
  id?: string;
  email: string;
  fullName?: string | null;
  role?: 'CUSTOMER' | 'ADMIN' | 'VENDOR';
  isActive?: boolean;
  metadata?: Record<string, any> | null;
  createdAt?: Date;
  updatedAt?: Date;
}

UserCreationAttributes extends Optional<UserAttributes, 'id' | 'fullName' | 'role' | 'isActive' | 'metadata' | 'createdAt' | 'updatedAt'> {}

export class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes {
  public id!: string;
  public email!: string;
  public fullName!: string | null;
  public role!: 'CUSTOMER' | 'ADMIN' | 'VENDOR';
  public isActive!: boolean;
  public metadata!: Record<string, any> | null;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

initUser(sequelize: Sequelize): typeof User {
  User.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      email: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
      },
      fullName: {
        type: DataTypes.STRING(120),
        allowNull: true,
        field: 'full_name',
      },
      role: {
        type: DataTypes.ENUM('CUSTOMER', 'ADMIN', 'VENDOR'),
        allowNull: false,
        defaultValue: 'CUSTOMER',
      },
      isActive: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        field: 'is_active',
      },
      metadata: {
        type: DataTypes.JSONB,
        allowNull: true,
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'created_at',
      },
      updatedAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'updated_at',
      },
    },
    {
      sequelize,
      tableName: 'users',
      modelName: 'User',
      timestamps: true,
      underscored: true,
    }
  );
  return User;
}

UserProfileAttributes {
  id?: string;
  userId: string;
  avatarUrl?: string | null;
  phone?: string | null;
  shippingAddress?: string | null;
  taxIdentifier?: string | null;
}

UserProfileCreationAttributes extends Optional<UserProfileAttributes, 'id' | 'avatarUrl' | 'phone' | 'shippingAddress' | 'taxIdentifier'> {}

export class UserProfile extends Model<UserProfileAttributes, UserProfileCreationAttributes> implements UserProfileAttributes {
  public id!: string;
  public userId!: string;
  public avatarUrl!: string | null;
  public phone!: string | null;
  public shippingAddress!: string | null;
  public taxIdentifier!: string | null;

  // Association Mixin Placeholders
  // public getUser!: BelongsToGetAssociationMixin<User>;
}

initUserProfile(sequelize: Sequelize): typeof UserProfile {
  UserProfile.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      userId: {
        type: DataTypes.UUID,
        allowNull: false,
        unique: true,
        field: 'user_id',
        references: {
          model: 'users',
          key: 'id',
        },
        onDelete: 'CASCADE',
      },
      avatarUrl: {
        type: DataTypes.STRING(500),
        allowNull: true,
        field: 'avatar_url',
      },
      phone: {
        type: DataTypes.STRING(30),
        allowNull: true,
      },
      shippingAddress: {
        type: DataTypes.TEXT,
        allowNull: true,
        field: 'shipping_address',
      },
      taxIdentifier: {
        type: DataTypes.STRING(50),
        allowNull: true,
        field: 'tax_identifier',
      },
    },
    {
      sequelize,
      tableName: 'user_profiles',
      modelName: 'UserProfile',
      timestamps: true,
      underscored: true,
    }
  );
  return UserProfile;
}

ProductAttributes {
  id?: number;
  sku: string;
  title: string;
  description?: string | null;
  price?: number;
  inventory?: number;
  isPublished?: boolean;
  createdAt?: Date;
}

ProductCreationAttributes extends Optional<ProductAttributes, 'id' | 'description' | 'price' | 'inventory' | 'isPublished' | 'createdAt'> {}

export class Product extends Model<ProductAttributes, ProductCreationAttributes> implements ProductAttributes {
  public id!: number;
  public sku!: string;
  public title!: string;
  public description!: string | null;
  public price!: number;
  public inventory!: number;
  public isPublished!: boolean;
  public readonly createdAt!: Date;
}

initProduct(sequelize: Sequelize): typeof Product {
  Product.init(
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
      },
      sku: {
        type: DataTypes.STRING(64),
        allowNull: false,
        unique: true,
      },
      title: {
        type: DataTypes.STRING(200),
        allowNull: false,
      },
      description: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      price: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        defaultValue: 0.00,
      },
      inventory: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
      },
      isPublished: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        field: 'is_published',
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'created_at',
      },
    },
    {
      sequelize,
      tableName: 'products',
      modelName: 'Product',
      timestamps: true,
      underscored: true,
      indexes: [
        {
          name: 'idx_products_sku',
          fields: ['sku'],
        },
      ],
    }
  );
  return Product;
}

OrderAttributes {
  id?: string;
  customerId: string;
  orderNumber: string;
  status?: 'PENDING' | 'PAID' | 'PROCESSING' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED';
  totalAmount?: number;
  notes?: string | null;
  createdAt?: Date;
}

OrderCreationAttributes extends Optional<OrderAttributes, 'id' | 'status' | 'totalAmount' | 'notes' | 'createdAt'> {}

export class Order extends Model<OrderAttributes, OrderCreationAttributes> implements OrderAttributes {
  public id!: string;
  public customerId!: string;
  public orderNumber!: string;
  public status!: 'PENDING' | 'PAID' | 'PROCESSING' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED';
  public totalAmount!: number;
  public notes!: string | null;
  public readonly createdAt!: Date;

  // Association Mixin Placeholders
  // public getUser!: BelongsToGetAssociationMixin<User>;
}

initOrder(sequelize: Sequelize): typeof Order {
  Order.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      customerId: {
        type: DataTypes.UUID,
        allowNull: false,
        field: 'customer_id',
        references: {
          model: 'users',
          key: 'id',
        },
        onDelete: 'RESTRICT',
      },
      orderNumber: {
        type: DataTypes.STRING(64),
        allowNull: false,
        unique: true,
        field: 'order_number',
      },
      status: {
        type: DataTypes.ENUM('PENDING', 'PAID', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CANCELLED'),
        allowNull: false,
        defaultValue: 'PENDING',
      },
      totalAmount: {
        type: DataTypes.DECIMAL(12, 2),
        allowNull: false,
        defaultValue: 0.00,
        field: 'total_amount',
      },
      notes: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'created_at',
      },
    },
    {
      sequelize,
      tableName: 'orders',
      modelName: 'Order',
      timestamps: true,
      underscored: true,
      indexes: [
        {
          name: 'idx_orders_customer',
          fields: ['customer_id'],
        },
      ],
    }
  );
  return Order;
}

OrderItemAttributes {
  id?: number;
  orderId: string;
  productId: number;
  quantity?: number;
  unitPrice: number;
}

OrderItemCreationAttributes extends Optional<OrderItemAttributes, 'id' | 'quantity'> {}

export class OrderItem extends Model<OrderItemAttributes, OrderItemCreationAttributes> implements OrderItemAttributes {
  public id!: number;
  public orderId!: string;
  public productId!: number;
  public quantity!: number;
  public unitPrice!: number;

  // Association Mixin Placeholders
  // public getOrder!: BelongsToGetAssociationMixin<Order>;
  // public getProduct!: BelongsToGetAssociationMixin<Product>;
}

initOrderItem(sequelize: Sequelize): typeof OrderItem {
  OrderItem.init(
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
      },
      orderId: {
        type: DataTypes.UUID,
        allowNull: false,
        field: 'order_id',
        references: {
          model: 'orders',
          key: 'id',
        },
        onDelete: 'CASCADE',
      },
      productId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        field: 'product_id',
        references: {
          model: 'products',
          key: 'id',
        },
        onDelete: 'RESTRICT',
      },
      quantity: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 1,
      },
      unitPrice: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        field: 'unit_price',
      },
    },
    {
      sequelize,
      tableName: 'order_items',
      modelName: 'OrderItem',
      timestamps: true,
      underscored: true,
    }
  );
  return OrderItem;
}

// ============================================================================
// Unified Model Registry & Associations Initializer
// ============================================================================

DatabaseModels {
  User: typeof User;
  UserProfile: typeof UserProfile;
  Product: typeof Product;
  Order: typeof Order;
  OrderItem: typeof OrderItem;
}

initModels(sequelize: Sequelize): DatabaseModels {
  initUser(sequelize);
  initUserProfile(sequelize);
  initProduct(sequelize);
  initOrder(sequelize);
  initOrderItem(sequelize);

  // Setup Relationships
  UserProfile.belongsTo(User, { foreignKey: 'userId', as: 'user' });
  User.hasMany(UserProfile, { foreignKey: 'userId', as: 'userProfiles' });
  Order.belongsTo(User, { foreignKey: 'customerId', as: 'user' });
  User.hasMany(Order, { foreignKey: 'customerId', as: 'orders' });
  OrderItem.belongsTo(Order, { foreignKey: 'orderId', as: 'order' });
  Order.hasMany(OrderItem, { foreignKey: 'orderId', as: 'orderItems' });
  OrderItem.belongsTo(Product, { foreignKey: 'productId', as: 'product' });
  Product.hasMany(OrderItem, { foreignKey: 'productId', as: 'orderItems' });

  return {
    User,
    UserProfile,
    Product,
    Order,
    OrderItem,
  };
}

Tabelas e arquitetura detectadas (5)

usersUser
Colunas8
Chave primária:id
Chaves estrangeiras:0
user_profilesUserProfile
Colunas6
Chave primária:id
Chaves estrangeiras:1
productsProduct
Colunas8
Chave primária:id
Chaves estrangeiras:0
ordersOrder
Colunas7
Chave primária:id
Chaves estrangeiras:1
order_itemsOrderItem
Colunas5
Chave primária:id
Chaves estrangeiras:2

Privacidade Local Sem Envio de Dados

Toda a análise do DDL SQL e a sintetização de modelos Sequelize ocorrem 100% localmente no sandbox do navegador. Seus esquemas confidenciais nunca saem da sua máquina.

Dupla Arquitetura TypeScript

Gere declarações Model.init padrão do Sequelize v6/v7 com interfaces de atributos completas ou decoradores modernos do sequelize-typescript com tipagem estrita em tempo de compilação.

Associações e Migrações Prontas

Detecta automaticamente relações de chaves estrangeiras 1:1, 1:N e N:M para gerar hasMany, belongsTo e scripts de migração completos para o Sequelize CLI.

Referência técnica e guia de arquitetura

Guia do Desenvolvedor: Gerador de Modelos Sequelize TypeScript a partir de SQL DDL — Guia de referência

Referência técnica completa para converter instruções SQL CREATE TABLE DDL em modelos Sequelize TypeScript fortemente tipados, definições DataTypes, atributos CreationOptional e chamadas Model.init.

Parâmetros principais e controles

ddlInputstring

Instruções SQL CREATE TABLE brutas contendo definições de colunas, chaves primárias, restrições de nulidade, valores padrão e chaves estrangeiras.

Padrão: CREATE TABLE users (...)
dialectenum ('postgres' | 'mysql' | 'sqlite' | 'mssql')

Dialeto de banco de dados SQL de destino que determina DataTypes específicos do Sequelize (como JSONB, UUID, ENUM ou INET).

Padrão: postgres
tsSyntaxenum ('v6-infer' | 'decorators' | 'interface')

Estilo de sintaxe TypeScript do modelo: Sequelize v6 InferAttributes/InferCreationAttributes, decoradores sequelize-typescript ou interfaces tipadas tradicionais.

Padrão: v6-infer
camelCaseboolean

Converte automaticamente nomes de colunas em snake_case para atributos camelCase no TypeScript com mapeamento explícito da propriedade field.

Padrão: true

Dicas profissionais e melhores práticas

No Sequelize v6+

No Sequelize v6+, anote chaves primárias autoincrementais, colunas com cláusula DEFAULT e timestamps com `declare id: CreationOptional<number>;`. Isso evita que o método `Model.create()` exija esses campos na criação, mantendo-os não-nulos em instâncias carregadas.

Habilite a conversão para camelCase

Habilite a conversão para camelCase para manipular atributos idiomáticos em TypeScript (como createdAt ou userId), enquanto o Sequelize realiza a correspondência com a coluna do banco por meio de `field: 'created_at'`.

Cláusulas FOREIGN KEY do SQL geram

Cláusulas FOREIGN KEY do SQL geram atributos de chave estrangeira no Sequelize. Combine-as com interfaces tipadas exportadas para estruturar associações hasMany e belongsTo sem conflitos circulares de tipos.

Problemas comuns e solução de problemas

Erro do TypeScript: A propriedade 'id' não possui inicializador e não está definitivamente atribuída no construtor (TS2564)

Adicione o modificador `declare` aos atributos do modelo (ex.: `declare id: CreationOptional<number>;`) em projetos configurados com `useDefineForClassFields: true` no TypeScript.

Erro de DataType não suportado ao trocar de dialeto (ex.: DataTypes.JSONB no MySQL)

Selecione o dialeto de banco de dados correto nas opções antes da conversão. O gerador substitui tipos específicos de engine (como JSONB ou ARRAY) por formatos universais compatíveis, como `DataTypes.JSON` ou `DataTypes.TEXT`.

Perguntas frequentes (FAQ)

Como os tipos de dados do SQL são convertidos em Sequelize DataTypes?▼

Os tipos padrão do SQL (VARCHAR, INT, BIGINT, TIMESTAMP, BOOLEAN, TEXT, DECIMAL, JSON) são convertidos com precisão para os tipos equivalentes do Sequelize (DataTypes.STRING, DataTypes.INTEGER, DataTypes.BIGINT, DataTypes.DATE, DataTypes.BOOLEAN, etc.). Tipos específicos como UUID ou JSONB do PostgreSQL são preservados ao configurar o dialeto.

O gerador oferece suporte tanto ao Sequelize v6 InferAttributes quanto ao sequelize-typescript?▼

Sim. É possível alternar livremente entre o padrão moderno do Sequelize v6 (`Model<InferAttributes<T>, InferCreationAttributes<T>>` com `Model.init`) e o estilo baseado em decoradores do sequelize-typescript (`@Table`, `@Column`, `@PrimaryKey`, `@DataType`).

Como restrições NOT NULL e valores DEFAULT são manipulados?▼

Colunas NOT NULL recebem `allowNull: false`. Definições de valor DEFAULT são convertidas em `defaultValue: ...` e tipadas no modelo TypeScript com `CreationOptional<T>`, garantindo flexibilidade e segurança de tipos em inserções.

Minha estrutura de banco de dados ou SQL DDL é enviada para algum servidor?▼

Não. Todas as rotinas de análise sintática, conversão e geração de código TypeScript operam de forma 100% local no navegador por meio de Web Workers. Nenhum esquema ou comando SQL é transmitido ou gravado remotamente.

Ferramentas e utilitários relacionados

Todas as ferramentas →