Sequelize CLI

repository·main·Indexed 25 days ago

https://github.com/sequelize/cli

A command-line tool for the Sequelize ORM designed to automate common tasks including managing database migrations, generating models, and handling seed data. It provides a suite of commands for database management (db:create, db:migrate), project initialization (init), and generation (model:generate, migration:generate, seed:generate). The CLI supports configuration via .sequelizerc and environment variables, and allows for flexible migration and seeder storage options.

Tokens
6.8K
Snippets
23
Records
50
Agent score
82%

What's inside sequelize-cli

  1. Create a migration file

    main

    Migrations follow the [umzug] schema. Each migration file must export an object with up and down functions.

    • The up function handles applying the change.
    • The down function handles reverting the change.

    Asynchronous logic can be handled by either returning a Promise or calling the done callback. If you pass an argument to the done callback, it will be treated as an error.

    You can access the Sequelize instance via queryInterface.sequelize.

    "use strict";
    
    module.exports = {
      up: function(queryInterface, Sequelize, done) {
        done();
      },
    
      down: function(queryInterface) {
        return new Promise(function (resolve, reject) {
          resolve();
        });
      }
    };
  2. Install the Sequelize CLI

    main

    Before installing the CLI, ensure that the sequelize ORM is already installed in your project. You can then install the CLI as a development dependency using npm.

    npm install --save-dev sequelize-cli
  3. Configure SSL for database connections

    main

    To connect over SSL, you must specify ssl: true in both the base configuration and within the dialectOptions object.

    {
        "production": {
            "use_env_variable":"DB_CONNECTION_STRING",
            "dialect":"postgres",
            "ssl": true,
            "dialectOptions": {
                "ssl": true
            }
        }
    }
  4. Configure database connections

    main

    The CLI uses a configuration file (defaulting to config/config.js or config/config.json) to manage database connections for different environments (e.g., development, test, production).

    Connection Methods

    1. Standard Properties: Define username, password, database, host, and dialect for each environment.
    2. Connection URL: Use the url property to provide a full connection string.
    3. Connection String Flag: Pass a connection string directly via the CLI using the --url flag.
    4. Environment Variables:
      • Use the use_env_variable key in your config file to specify the name of an environment variable containing the connection URL.
      • Alternatively, access process.env directly inside a config.js file.
    {
      "development": {
        "username": "root",
        "password": null,
        "database": "database_development",
        "host": "127.0.0.1",
        "dialect": "mysql"
      }
    }
    # Using the --url flag
    sequelize db:migrate --url 'mysql://root:password@mysql_host.com/database_name'
    {
        "production": {
            "use_env_variable": "DB_CONNECTION_STRING"
        }
    }
  5. Configure the CLI using .sequelizerc

    main

    If you need to define specific paths or flags every time you run the CLI, you can create a .sequelizerc file in your project root. This file can be a JSON file or a Node.js script that exports a hash. The CLI will automatically require this file if it exists.

    Common keys to export in .sequelizerc include:

    • config: Path to your configuration file.
    • migrations-path: Directory where migrations are stored.
    • seeders-path: Directory where seeders are stored.
    • models-path: Directory where models are stored.
    var path = require('path')
    
    module.exports = {
      'config':          path.resolve('config', 'database.json'),
      'migrations-path': path.resolve('db', 'migrate')
    }
  6. Pass dialect-specific options

    main

    Use the dialectOptions property in your configuration file to pass specific settings to the underlying database connector (e.g., SSL certificates for MySQL).

    var fs = require('fs');
    
    module.exports = {
      development: {
        dialect: 'mysql',
        dialectOptions: {
          ssl: {
            ca: fs.readFileSync(__dirname + '/mysql-ca.crt')
          }
        }
      }
    };
  7. Structure of a generated Sequelize model file

    main

    When using the sequelize-cli to generate models, the resulting files follow a specific template structure. Each model is exported as a function that receives the sequelize instance and DataTypes.

    Key components of the generated file include:

    • A class extending Model.
    • A static associate(models) method used to define relationships (associations) between models. This method is intended to be called by the models/index.js file.
    • An .init() call to define the model's attributes and configuration.
    • Configuration options such as modelName and optionally underscored: true.
    'use strict';
    
    const { Model } = require('sequelize');
    
    module.exports = (sequelize, DataTypes) => {
      class <%= name %> extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate (models) {
          // define association here
        }
      }
    
    <%= name %>.init({
        // attributes defined here
      }, {
        sequelize,
        modelName: '<%= name %>',
        <%= underscored ? 'underscored: true,' : '' %>
      });
    
    return <%= name %>;
    };
  8. Structure of a Sequelize migration file

    main

    A Sequelize migration file is a JavaScript module that exports an object containing two asynchronous functions: up and down.

    • up: Defines the changes to be applied to the database (e.g., creating a table).
    • down: Defines how to undo the changes made by up (e.g., dropping the table).

    Both functions receive queryInterface (used to interact with the database schema) and Sequelize (the Sequelize library instance used for data types) as arguments.

    'use strict';
    
    /** @type {import('sequelize-cli').Migration} */
    module.exports = {
      async up (queryInterface, Sequelize) {
        // Logic to apply changes
      },
    
      async down (queryInterface, Sequelize) {
        // Logic to revert changes
      }
    };
  9. Configure Migration and Seeder storage

    main

    The CLI allows you to choose how to track executed migrations and seeds using the migrationStorage and seederStorage options.

    Storage Types

    • sequelize: Stores records in a database table (Default for migrations).
    • json: Stores records in a JSON file.
    • none: Does not store any record (Not recommended for migrations).

    Migration Configuration Options

    • migrationStorage: Type of storage (sequelize, json, or none).
    • migrationStoragePath: File path if using json storage (Default: sequelize-meta.json).
    • migrationStorageTableName: Table name if using sequelize storage (Default: SequelizeMeta).
    • migrationStorageTableSchema: Schema name for the table (Postgres-only).

    Seeder Configuration Options

    • seederStorage: Type of storage (sequelize, json, or none). Default is none.
    • seederStoragePath: File path if using json storage (Default: sequelize-data.json).
    • seederStorageTableName: Table name if using sequelize storage (Default: SequelizeData).
    {
      "development": {
        "username": "root",
        "password": null,
        "database": "database_development",
        "host": "127.0.0.1",
        "dialect": "mysql",
    
        // Use a different storage type. Default: sequelize
        "migrationStorage": "json",
    
        // Use a different file name. Default: sequelize-meta.json
        "migrationStoragePath": "sequelizeMeta.json",
    
        // Use a different table name. Default: SequelizeMeta
        "migrationStorageTableName": "sequelize_meta",
    
        // Use a different schema (Postgres-only). Default: undefined
        "migrationStorageTableSchema": "sequelize_schema"
      }
    }
  10. Structure of the generated models entry point file

    main

    The models/index.js file is a template generated by the Sequelize CLI that serves as the central entry point for all models in your project. It performs the following tasks:

    1. Initializes Sequelize: It reads your configuration from the specified config file and initializes a Sequelize instance using either credentials provided in the config or an environment variable defined by config.use_env_variable.
    2. Auto-loads Models: It scans the current directory for .js files (excluding the entry point itself and test files) and requires them, passing the sequelize instance and Sequelize.DataTypes to each model factory.
    3. Registers Models: It populates a db object with the loaded models, using the model's name as the key.
    4. Sets up Associations: It iterates through all loaded models and, if a model has an associate method, calls it, passing the db object to allow models to reference each other.
    5. Exports the Database Object: It exports an object containing all models, the sequelize instance, and the Sequelize library itself.

    When using this file in your application, you typically import the db object to access your models and the database connection.