{"id":13457856,"url":"https://github.com/sequelize/sequelize-auto","last_synced_at":"2025-05-13T21:06:18.445Z","repository":{"id":8900713,"uuid":"10623309","full_name":"sequelize/sequelize-auto","owner":"sequelize","description":"Automatically generate bare sequelize models from your database.","archived":false,"fork":false,"pushed_at":"2024-08-20T10:07:18.000Z","size":779,"stargazers_count":2931,"open_issues_count":113,"forks_count":530,"subscribers_count":57,"default_branch":"master","last_synced_at":"2025-05-10T03:38:25.769Z","etag":null,"topics":["database","javascript","orm","sequelize"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sequelize.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":null,"patreon":null,"open_collective":"sequelize","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2013-06-11T14:34:05.000Z","updated_at":"2025-05-07T09:09:43.000Z","dependencies_parsed_at":"2022-06-26T10:31:08.767Z","dependency_job_id":"4c735b26-8592-49b0-8da1-6e0c171672bf","html_url":"https://github.com/sequelize/sequelize-auto","commit_stats":{"total_commits":438,"total_committers":80,"mean_commits":5.475,"dds":0.6689497716894977,"last_synced_commit":"8a8eb9d384851e5949ec19079300a2ebc33c2107"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sequelize%2Fsequelize-auto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sequelize%2Fsequelize-auto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sequelize%2Fsequelize-auto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sequelize%2Fsequelize-auto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sequelize","download_url":"https://codeload.github.com/sequelize/sequelize-auto/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253433690,"owners_count":21907777,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","javascript","orm","sequelize"],"created_at":"2024-07-31T09:00:38.395Z","updated_at":"2025-05-13T21:06:13.436Z","avatar_url":"https://github.com/sequelize.png","language":"TypeScript","readme":"# Sequelize-Auto\n\n\u003c!-- [![Greenkeeper badge](https://badges.greenkeeper.io/sequelize/sequelize-auto.svg)](https://greenkeeper.io/) --\u003e\n\n[![Build Status](http://img.shields.io/travis/sequelize/sequelize-auto/master.svg)](https://travis-ci.org/sequelize/sequelize-auto) [![Build status](https://ci.appveyor.com/api/projects/status/bf9lb89rmpj6iveb?svg=true)](https://ci.appveyor.com/project/durango/sequelize-auto) [![Code Climate](https://codeclimate.com/github/sequelize/sequelize-auto/badges/gpa.svg)](https://codeclimate.com/github/sequelize/sequelize-auto) [![Test Coverage](https://codeclimate.com/github/sequelize/sequelize-auto/badges/coverage.svg)](https://codeclimate.com/github/sequelize/sequelize-auto/coverage)\n\nAutomatically generate models for [SequelizeJS](https://github.com/sequelize/sequelize) via the command line.\n\n## Install\n\n    npm install sequelize-auto\n\n## Prerequisites\n\nYou will need to install `sequelize`; it's no longer installed by `sequelize-auto`.\n\nYou will need to install the correct dialect binding before using sequelize-auto.\n\nDialect | Install\n---|---\nMySQL/MariaDB | `npm install sequelize mysql2`\nPostgres | `npm install sequelize pg pg-hstore`\nSqlite | `npm install sequelize sqlite3`\nMSSQL | `npm install sequelize tedious`\n\n\n## Usage\n\n    sequelize-auto -h \u003chost\u003e -d \u003cdatabase\u003e -u \u003cuser\u003e -x [password] -p [port]  --dialect [dialect] -c [/path/to/config] -o [/path/to/models] -t [tableName]\n```\nOptions:\n    --help               Show help                                   [boolean]\n    --version            Show version number                         [boolean]\n-h, --host               IP/Hostname for the database.                [string]\n-d, --database           Database name.                               [string]\n-u, --user               Username for database.                       [string]\n-x, --pass               Password for database. If specified without providing\n                          a password, it will be requested interactively from\n                          the terminal.\n-p, --port               Port number for database (not for sqlite). Ex:\n                          MySQL/MariaDB: 3306, Postgres: 5432, MSSQL: 1433\n                                                                      [number]\n-c, --config             Path to JSON file for Sequelize-Auto options and\n                          Sequelize's constructor \"options\" flag object as\n                          defined here:\n                          https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-constructor-constructor\n                                                                      [string]\n-o, --output             What directory to place the models.          [string]\n-e, --dialect            The dialect/engine that you're using: postgres,\n                          mysql, sqlite, mssql                         [string]\n-a, --additional         Path to JSON file containing model options (for all\n                          tables). See the options: https://sequelize.org/api/v6/class/src/model.js~model#static-method-init\n                                                                      [string]\n    --indentation        Number of spaces to indent                   [number]\n-t, --tables             Space-separated names of tables to import     [array]\n-T, --skipTables         Space-separated names of tables to skip       [array]\n--caseModel, --cm        Set case of model names: c|l|o|p|u\n                          c = camelCase\n                          l = lower_case\n                          o = original (default)\n                          p = PascalCase\n                          u = UPPER_CASE\n--caseProp, --cp         Set case of property names: c|l|o|p|u\n--caseFile, --cf         Set case of file names: c|l|o|p|u|k\n                          k = kebab-case\n--noAlias                Avoid creating alias `as` property in relations\n                                                                     [boolean]\n--noInitModels           Prevent writing the init-models file        [boolean]\n-n, --noWrite            Prevent writing the models to disk          [boolean]\n-s, --schema             Database schema from which to retrieve tables[string]\n-v, --views              Include database views in generated models  [boolean]\n-l, --lang               Language for Model output: es5|es6|esm|ts\n                          es5 = ES5 CJS modules (default)\n                          es6 = ES6 CJS modules\n                          esm = ES6 ESM modules\n                          ts = TypeScript                             [string]\n--useDefine              Use `sequelize.define` instead of `init` for es6|esm|ts\n--singularize, --sg      Singularize model and file names from plural table\n                          names                                      [boolean]\n```\n\n\u003e On Windows, provide the path to sequelize-auto: `node_modules\\.bin\\sequelize-auto [args]`\n\n## Example\n\n    sequelize-auto -o \"./models\" -d sequelize_auto_test -h localhost -u my_username -p 5432 -x my_password -e postgres\n\nProduces a file/files such as `./models/User.js` which looks like:\n\n```js\nmodule.exports = function(sequelize, DataTypes) {\n  return sequelize.define('User', {\n    id: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    username: {\n      type: DataTypes.STRING(20),\n      allowNull: true\n    },\n    aNumber: {\n      type: DataTypes.SMALLINT,\n      allowNull: true\n    },\n    dateAllowNullTrue: {\n      type: DataTypes.DATE,\n      allowNull: true\n    },\n    defaultValueBoolean: {\n      type: DataTypes.BOOLEAN,\n      allowNull: true,\n      defaultValue: true\n    }\n  }, {\n    tableName: 'User',\n  });\n};\n```\n\nSequelize-auto also generates an initialization file, `./models/init-models.js`, which contains the code to load each model definition into Sequelize:\n\n```js\nvar DataTypes = require(\"sequelize\").DataTypes;\nvar _User = require(\"./User\");\nvar _Product = require(\"./Product\");\n\nfunction initModels(sequelize) {\n  var User = _User(sequelize, DataTypes);\n  var Product = _Product(sequelize, DataTypes);\n\n  return {\n    User,\n    Product,\n  };\n}\nmodule.exports = { initModels };\n```\n\nThis makes it easy to import all your models into Sequelize by calling `initModels(sequelize)`.\n\n```js\nvar initModels = require(\"./models/init-models\");\n...\nvar models = initModels(sequelize);\n\nmodels.User.findAll({ where: { username: \"tony\" }}).then(...);\n```\n\nAlternatively, you can [Sequelize.import](http://docs.sequelizejs.com/en/latest/docs/models-definition/#import) each model (for Sequelize versions \u003c 6), or `require` each file and call the returned function:\n\n```js\nvar User = require('path/to/user')(sequelize, DataTypes);\n```\n\n## ES6\n\nYou can use the `-l es6` option to create the model definition files as ES6 classes, or `-l esm` option to create ES6 modules.  Then you would `require` or `import` the classes and call the `init(sequelize, DataTypes)` method on each class.\n\n## TypeScript\n\nAdd `-l ts` to cli options or `lang: 'ts'` to programmatic options.  This will generate a TypeScript class in each model file, and an `init-model.ts` file\nto import and initialize all the classes.\n\n\u003e Note that you need TypeScript **4.x** to compile the generated files.\n\nThe TypeScript model classes are created as described in the [Sequelize manual](https://sequelize.org/master/manual/typescript.html)\n\nExample model class, `order.ts`:\n\n```js\nimport Sequelize, { DataTypes, Model, Optional } from 'sequelize';\nimport type { Customer, CustomerId } from './customer';\nimport type { OrderItem, OrderItemId } from './order_item';\n\nexport interface OrderAttributes {\n  id: number;\n  orderDate: Date;\n  orderNumber?: string;\n  customerId: number;\n  totalAmount?: number;\n  status: 'PROCESSING' | 'SHIPPED' | 'UNKNOWN';\n}\n\nexport type OrderPk = \"id\";\nexport type OrderId = Order[OrderPk];\nexport type OrderCreationAttributes = Optional\u003cOrderAttributes, OrderPk\u003e;\n\nexport class Order extends Model\u003cOrderAttributes, OrderCreationAttributes\u003e implements OrderAttributes {\n  id!: number;\n  orderDate!: Date;\n  orderNumber?: string;\n  customerId!: number;\n  totalAmount?: number;\n  status!: 'PROCESSING' | 'SHIPPED' | 'UNKNOWN';\n\n  // Order belongsTo Customer via customerId\n  customer!: Customer;\n  getCustomer!: Sequelize.BelongsToGetAssociationMixin\u003cCustomer\u003e;\n  setCustomer!: Sequelize.BelongsToSetAssociationMixin\u003cCustomer, CustomerId\u003e;\n  createCustomer!: Sequelize.BelongsToCreateAssociationMixin\u003cCustomer\u003e;\n  // Order hasMany OrderItem via orderId\n  orderItems!: OrderItem[];\n  getOrderItems!: Sequelize.HasManyGetAssociationsMixin\u003cOrderItem\u003e;\n  setOrderItems!: Sequelize.HasManySetAssociationsMixin\u003cOrderItem, OrderItemId\u003e;\n  addOrderItem!: Sequelize.HasManyAddAssociationMixin\u003cOrderItem, OrderItemId\u003e;\n  addOrderItems!: Sequelize.HasManyAddAssociationsMixin\u003cOrderItem, OrderItemId\u003e;\n  createOrderItem!: Sequelize.HasManyCreateAssociationMixin\u003cOrderItem\u003e;\n  removeOrderItem!: Sequelize.HasManyRemoveAssociationMixin\u003cOrderItem, OrderItemId\u003e;\n  removeOrderItems!: Sequelize.HasManyRemoveAssociationsMixin\u003cOrderItem, OrderItemId\u003e;\n  hasOrderItem!: Sequelize.HasManyHasAssociationMixin\u003cOrderItem, OrderItemId\u003e;\n  hasOrderItems!: Sequelize.HasManyHasAssociationsMixin\u003cOrderItem, OrderItemId\u003e;\n  countOrderItems!: Sequelize.HasManyCountAssociationsMixin;\n\n  static initModel(sequelize: Sequelize.Sequelize): typeof Order {\n    Order.init({\n    id: {\n      autoIncrement: true,\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      primaryKey: true\n    },\n    orderDate: {\n      type: DataTypes.DATE,\n      allowNull: false,\n      defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),\n      field: 'OrderDate'\n    },\n    orderNumber: {\n      type: DataTypes.STRING(10),\n      allowNull: true,\n      field: 'OrderNumber'\n    },\n    customerId: {\n      type: DataTypes.INTEGER,\n      allowNull: false,\n      references: {\n        model: 'customer',\n        key: 'Id'\n      },\n      field: 'CustomerId'\n    },\n    totalAmount: {\n      type: DataTypes.DECIMAL(12,2),\n      allowNull: true,\n      defaultValue: 0.00,\n      field: 'TotalAmount'\n    },\n    status: {\n      type: DataTypes.ENUM('PROCESSING','SHIPPED','UNKNOWN'),\n      allowNull: false,\n      defaultValue: \"UNKNOWN\",\n      field: 'Status'\n    }\n  }, {\n    sequelize,\n    tableName: 'order',\n    timestamps: false,\n  });\n  return Order;\n  }\n}\n```\n\nExample `init-models.ts`:\n\n```js\nimport { Sequelize } from \"sequelize\";\nimport { Customer, CustomerAttributes, CustomerCreationAttributes } from \"./customer\";\nimport { Order, OrderAttributes, OrderCreationAttributes } from \"./order\";\nimport { OrderItem, OrderItemAttributes, OrderItemCreationAttributes } from \"./order_item\";\nimport { Product, ProductAttributes, ProductCreationAttributes } from \"./product\";\nimport { Supplier, SupplierAttributes, SupplierCreationAttributes } from \"./supplier\";\n\nexport {\n  Customer, CustomerAttributes, CustomerCreationAttributes,\n  Order, OrderAttributes, OrderCreationAttributes,\n  OrderItem, OrderItemAttributes, OrderItemCreationAttributes,\n  Product, ProductAttributes, ProductCreationAttributes,\n  Supplier, SupplierAttributes, SupplierCreationAttributes,\n};\n\nexport function initModels(sequelize: Sequelize) {\n  Customer.initModel(sequelize);\n  Order.initModel(sequelize);\n  OrderItem.initModel(sequelize);\n  Product.initModel(sequelize);\n  Supplier.initModel(sequelize);\n\n  Order.belongsTo(Customer, { as: \"customer\", foreignKey: \"customerId\"});\n  Customer.hasMany(Order, { as: \"orders\", foreignKey: \"customerId\"});\n  OrderItem.belongsTo(Order, { as: \"order\", foreignKey: \"orderId\"});\n  Order.hasMany(OrderItem, { as: \"orderItems\", foreignKey: \"orderId\"});\n  OrderItem.belongsTo(Product, { as: \"product\", foreignKey: \"productId\"});\n  Product.hasMany(OrderItem, { as: \"orderItems\", foreignKey: \"productId\"});\n  Product.belongsTo(Supplier, { as: \"supplier\", foreignKey: \"supplierId\"});\n  Supplier.hasMany(Product, { as: \"products\", foreignKey: \"supplierId\"});\n\n  return {\n    Customer: Customer,\n    OrderItem: OrderItem,\n    Order: Order,\n    Product: Product,\n    Supplier: Supplier,\n  };\n}\n```\n\nModel usage in a TypeScript program:\n\n```js\n// Order is the sequelize Model class\n// OrderAttributes is the interface defining the fields\n// OrderCreationAttributes is the interface defining the fields when creating a new record\nimport { initModels, Order, OrderCreationAttributes } from \"./models/init-models\";\n\n// import models into sequelize instance\ninitModels(this.sequelize);\n\nconst myOrders = await Order.findAll({ where: { \"customerId\": cust.id }, include: ['customer'] });\n\nconst attr: OrderCreationAttributes = {\n  customerId: cust.id,\n  orderDate: new Date(),\n  orderNumber: \"ORD123\",\n  totalAmount: 223.45\n};\nconst newOrder = await Order.create(attr);\n```\n\n\n## Configuration options\n\nFor the `-c, --config` option, various JSON/configuration parameters are defined by Sequelize's `options` flag within the constructor. See the [Sequelize docs](https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor) for more info.\n\n## Programmatic API\n\n```js\nconst SequelizeAuto = require('sequelize-auto');\nconst auto = new SequelizeAuto('database', 'user', 'pass');\n\nauto.run().then(data =\u003e {\n  console.log(data.tables);      // table and field list\n  console.log(data.foreignKeys); // table foreign key list\n  console.log(data.indexes);     // table indexes\n  console.log(data.hasTriggerTables); // tables that have triggers\n  console.log(data.relations);   // relationships between models\n  console.log(data.text)         // text of generated models\n});\n```\n\nWith options:\n\n```js\nconst auto = new SequelizeAuto('database', 'user', 'pass', {\n    host: 'localhost',\n    dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',\n    directory: './models', // where to write files\n    port: 'port',\n    caseModel: 'c', // convert snake_case column names to camelCase field names: user_id -\u003e userId\n    caseFile: 'c', // file names created for each model use camelCase.js not snake_case.js\n    singularize: true, // convert plural table names to singular model names\n    additional: {\n        timestamps: false\n        // ...options added to each model\n    },\n    tables: ['table1', 'table2', 'myschema.table3'] // use all tables, if omitted\n    //...\n})\n```\n\nOr you can create the `sequelize` instance first, using a [connection string](https://sequelize.org/master/manual/getting-started.html#connecting-to-a-database),\nand then pass it to SequelizeAuto:\n```js\nconst SequelizeAuto = require('sequelize-auto');\nconst Sequelize = require('sequelize');\n\n// const sequelize = new Sequelize('sqlite::memory:');\nconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');\nconst options = { caseFile: 'l', caseModel: 'p', caseProp: 'c' };\n\nconst auto = new SequelizeAuto(sequelize, null, null, options);\nauto.run();\n```\n\n## Resources\n\n - [Changelog](https://github.com/sequelize/sequelize-auto/blob/master/CHANGELOG.md)\n\n## Testing\n\nTo set up:\n\n1. Create an empty database called `sequelize_auto_test` on your database server (sqlite excepted)\n2. Create a `.env` file from `sample.env` and set your username/password/port etc.  The env is read by `test/config.js`\n3. Build the TypeScript from the `src` directory into the `lib` directory:\n\n    `npm run build`\n\nThen run one of the test commands below:\n\n    # mysql only\n    npm run test-mysql\n\n    # postgres only\n    npm run test-postgres\n\n    # mssql  only\n    npm run test-mssql\n\n    # sqlite only\n    npm run test-sqlite\n\nAlso see the [sample](https://github.com/sequelize/sequelize-auto/tree/master/sample) directory which has an example including database scripts, export script, and a sample app.\n","funding_links":["https://opencollective.com/sequelize"],"categories":["TypeScript","JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsequelize%2Fsequelize-auto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsequelize%2Fsequelize-auto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsequelize%2Fsequelize-auto/lists"}