SQL → Sequelize TS
データベース&ORMコード生成

SQL DDL から Sequelize TypeScript モデルへのジェネレーター

SQLのCREATE TABLE文からSequelizeのTypeScriptモデル、DataTypes定義、CreationOptional属性、およびModel.init初期化コードを生成するための包括的開発者リファレンス。

100% クライアント側プライバシー
サーバー送信ゼロ
プリセット:
SQLコンパイラオプション&スキーママッピング
postgres•Model.init
PostgreSQL5 テーブル
SQL CREATE TABLE DDL 入力PostgreSQL
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,
  };
}

検出されたテーブルと構造 (5)

usersUser
カラム8
主キー:id
外部キー:0
user_profilesUserProfile
カラム6
主キー:id
外部キー:1
productsProduct
カラム8
主キー:id
外部キー:0
ordersOrder
カラム7
主キー:id
外部キー:1
order_itemsOrderItem
カラム5
主キー:id
外部キー:2

完全ローカル・プライバシー保証

すべてのSQL DDL解析とSequelizeモデルコード合成は、ブラウザ内のローカル環境で100%完結します。データベース定義が外部サーバーに送信されることは一切ありません。

デュアルTypeScriptアーキテクチャ

標準のSequelize v6/v7 Model.init宣言(Attributes/CreationAttributesインターフェース付き)と、モダンなsequelize-typescriptデコレーター構文の両方に対応。

リレーション&マイグレーション完備

外部キー制約から1対1、1対多、多対多のリレーションを自動判定し、hasMany / belongsTo / belongsToMany定義およびSequelize CLI用マイグレーションファイルを生成します。

技術リファレンス&アーキテクチャガイド

SQL DDLからSequelize TypeScriptモデルへの変換ジェネレーター — リファレンスガイド

SQLのCREATE TABLE文からSequelizeのTypeScriptモデル、DataTypes定義、CreationOptional属性、およびModel.init初期化コードを生成するための包括的開発者リファレンス。

主要パラメータ&設定項目

ddlInputstring

カラム定義、主キー、NULL制約、デフォルト値、外部キー制約を含むSQL CREATE TABLEステートメント。

初期値: CREATE TABLE users (...)
dialectenum ('postgres' | 'mysql' | 'sqlite' | 'mssql')

方言固有のSequelize DataTypes(JSONB、UUID、ENUM、INETなど)を決定するターゲットデータベース言語。

初期値: postgres
tsSyntaxenum ('v6-infer' | 'decorators' | 'interface')

出力するTypeScriptモデル構文のスタイル(Sequelize v6 InferAttributes、sequelize-typescriptデコレータ、またはクラシックな型付きインターフェース)。

初期値: v6-infer
camelCaseboolean

スネークケースのSQLカラム名を自動的にキャメルケースのTypeScript属性に変換し、明示的なfieldマッピングを付与します。

初期値: true

プロの活用テクニック&推奨設定

自動生成カラムにはCreationOptionalを活用する

Sequelize v6以降では、自動増分主キーやDEFAULT句付きカラム、タイムスタンプに`declare id: CreationOptional<number>;`を指定します。これにより、`Model.create()`時に指定不要としつつ、取得したインスタンス上では非Nullとして安全に型付けできます。

fieldマッピングを活用してクリーンなAPIインターフェースを維持

キャメルケース変換を有効化すると、TypeScriptコード内では慣用的なキャメルケース(例: createdAt, userId)を扱いながら、Sequelizeのカラム定義オプション`field: 'created_at'`によってDBカラム名と正確に連携できます。

外部キー制約を保持してリレーションシップ定義を効率化

SQLの`FOREIGN KEY`制約からSequelizeの外部キー定義が自動生成されます。出力された型定義モデルを活用して、循環参照エラーを起こさずにhasManyやbelongsToのアソシエーションを安全に構築できます。

よくあるトラブルと解決策

TypeScriptエラー: プロパティ 'id' に初期化子がなく、コンストラクタで割り当てられていません (TS2564)

`useDefineForClassFields: true`が有効なTypeScriptプロジェクトでは、モデルの属性定義に`declare`キーワードを使用してください(例: `declare id: CreationOptional<number>;`)。

方言切り替え時に未サポートのDataTypeエラーが発生する(例: MySQL環境でのDataTypes.JSONB)

DDL変換前に正しい対象SQL方言を選択してください。ジェネレーターがJSONBやARRAYなどの特定エンジン依存型を、`DataTypes.JSON`や`DataTypes.TEXT`などの汎用的な型に自動的にフォールバックします。

よくある質問 (FAQ)

SQLのデータ型はSequelizeのDataTypesにどのようにマッピングされますか?▼

VARCHAR、INT、BIGINT、TIMESTAMP、BOOLEAN、TEXT、DECIMAL、JSONなどの標準SQL型は、それぞれ対応するSequelize DataTypes(STRING, INTEGER, BIGINT, DATE, BOOLEAN, TEXT, DECIMAL, JSON)に正確に変換されます。PostgreSQLのUUIDやJSONBなども対象方言に応じて最適化されます。

Sequelize v6のInferAttributesとsequelize-typescriptデコレータの両方に対応していますか?▼

はい。Sequelize v6標準の`Model<InferAttributes<T>, InferCreationAttributes<T>>`および`Model.init`形式と、sequelize-typescript向けのデコレータ形式(`@Table`、`@Column`、`@PrimaryKey`、`@DataType`)の双方を自由に選択して出力可能です。

DEFAULT値やNOT NULL制約はどのようにコードへ反映されますか?▼

NOT NULL制約は`allowNull: false`に変換され、DEFAULT値は`defaultValue: ...`としてマッピングされます。また、TypeScript側では自動的に`CreationOptional<T>`として型定義され、作成時の柔軟性と安全性を両立します。

入力したSQL DDLやデータベーススキーマが外部サーバーに送信されることはありますか?▼

いいえ。すべてのSQL構文解析、トークン化、TypeScriptコード生成処理は、ブラウザ内のローカル環境(Web Worker)上で完結します。データベース情報が外部サーバーへ送信・保存されることは一切ありません。

関連するおすすめ開発ツール

すべてのツール →
Json To Elixir Ecto開発ツール

生のJSONデータからElixir Ectoスキーマ、マイグレーション、Changeset、Dialyzer型仕様(typespec)を自動生成するためのアーキテクチャ設計仕様書。

ツールを開く→
JSON to Scala 3 & Scala 2 Case Class 変換ツール開発ツール

JSONペイロードを高精度に解析し、型安全なScala 3およびScala 2のケースクラスへ変換。Circe、Play JSON、zio-jsonコーデックの自動導出に対応。

ツールを開く→
JSON to PHP 8.2+ 型付き Readonly DTO ジェネレーター開発ツール

JSON データをコンストラクタプロモーションと fromArray デシリアライザを備えた最新の PHP 8.2+ readonly class DTO(データ転送オブジェクト)に変換します。

ツールを開く→
TypeScript to GraphQL SDL開発ツール

TypeScriptのインターフェース、型エイリアス、列挙型を本番環境向けGraphQLスキーマ定義言語(SDL)へ変換するための開発者リファレンス。

ツールを開く→
TypeScript インターフェースから Protocol Buffers proto3 への変換ツール開発ツール

TypeScriptのinterfaceやtype定義を、インクリメンタルなタグ番号を持つProtobuf 3構文のmessage、field、enumに変換します。

ツールを開く→
GitLab CI パイプライン生成リファレンス開発ツール

Node.js、Python、Go、Rust、Kaniko コンテナワークフローに対応した本番仕様の .gitlab-ci.yml パイプライン構築と最適化のための技術リファレンス。

ツールを開く→