Basic usage

To get the ball rollin' you first have to create an instance of Sequelize. Use it the following way:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. dialect: 'mysql'
  3. });

This will save the passed database credentials and provide all further methods.

Furthermore you can specify a non-default host/port:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. dialect: 'mysql',
  3. host: "my.server.tld",
  4. port: 9821,
  5. })

If you just don't have a password:

  1. const sequelize = new Sequelize({
  2. database: 'db_name',
  3. username: 'username',
  4. password: null,
  5. dialect: 'mysql'
  6. });

You can also use a connection string:

  1. const sequelize = new Sequelize('mysql://user:pass@example.com:9821/db_name', {
  2. // Look to the next section for possible options
  3. })

Options

Besides the host and the port, Sequelize comes with a whole bunch of options. Here they are:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. // the sql dialect of the database
  3. // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql'
  4. dialect: 'mysql',
  5. // custom host; default: localhost
  6. host: 'my.server.tld',
  7. // custom port; default: dialect default
  8. port: 12345,
  9. // custom protocol; default: 'tcp'
  10. // postgres only, useful for Heroku
  11. protocol: null,
  12. // disable logging; default: console.log
  13. logging: false,
  14. // you can also pass any dialect options to the underlying dialect library
  15. // - default is empty
  16. // - currently supported: 'mysql', 'postgres', 'mssql'
  17. dialectOptions: {
  18. socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',
  19. supportBigNumbers: true,
  20. bigNumberStrings: true
  21. },
  22. // the storage engine for sqlite
  23. // - default ':memory:'
  24. storage: 'path/to/database.sqlite',
  25. // disable inserting undefined values as NULL
  26. // - default: false
  27. omitNull: true,
  28. // a flag for using a native library or not.
  29. // in the case of 'pg' -- set this to true will allow SSL support
  30. // - default: false
  31. native: true,
  32. // Specify options, which are used when sequelize.define is called.
  33. // The following example:
  34. // define: { timestamps: false }
  35. // is basically the same as:
  36. // sequelize.define(name, attributes, { timestamps: false })
  37. // so defining the timestamps for each model will be not necessary
  38. define: {
  39. underscored: false
  40. freezeTableName: false,
  41. charset: 'utf8',
  42. dialectOptions: {
  43. collate: 'utf8_general_ci'
  44. },
  45. timestamps: true
  46. },
  47. // similar for sync: you can define this to always force sync for models
  48. sync: { force: true },
  49. // pool configuration used to pool database connections
  50. pool: {
  51. max: 5,
  52. idle: 30000,
  53. acquire: 60000,
  54. },
  55. // isolation level of each transaction
  56. // defaults to dialect default
  57. isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ
  58. })

Hint: You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.

Read replication

Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is not handled by Sequelize, but should be set up by database backend).

  1. const sequelize = new Sequelize('database', null, null, {
  2. dialect: 'mysql',
  3. port: 3306
  4. replication: {
  5. read: [
  6. { host: '8.8.8.8', username: 'read-username', password: 'some-password' },
  7. { host: '9.9.9.9', username: 'another-username', password: null }
  8. ],
  9. write: { host: '1.1.1.1', username: 'write-username', password: 'any-password' }
  10. },
  11. pool: { // If you want to override the options used for the read/write pool you can do so here
  12. max: 20,
  13. idle: 30000
  14. },
  15. })

If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:host,port,username,password,database.

Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using pool configuration.

If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.

Each write or useMaster: true query will use write pool. For SELECT read pool will be used. Read replica are switched using a basic round robin scheduling.

Dialects

With the release of Sequelize 1.6.0, the library got independent from specific dialects. This means, that you'll have to add the respective connector library to your project yourself.

MySQL

In order to get Sequelize working nicely together with MySQL, you'll need to installmysql2@^1.0.0-rc.10or higher. Once that's done you can use it like this:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. dialect: 'mysql'
  3. })

Note: You can pass options directly to dialect library by setting thedialectOptions parameter. See Optionsfor examples (currently only mysql is supported).

SQLite

For SQLite compatibility you'll needsqlite3@~3.0.0. Configure Sequelize like this:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. // sqlite! now!
  3. dialect: 'sqlite',
  4. // the storage engine for sqlite
  5. // - default ':memory:'
  6. storage: 'path/to/database.sqlite'
  7. })

Or you can use a connection string as well with a path:

  1. const sequelize = new Sequelize('sqlite:/home/abs/path/dbname.db')
  2. const sequelize = new Sequelize('sqlite:relativePath/dbname.db')

PostgreSQL

The library for PostgreSQL ispg@^5.0.0 || ^6.0.0 You'll just need to define the dialect:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. // gimme postgres, please!
  3. dialect: 'postgres'
  4. })

MSSQL

The library for MSSQL istedious@^1.7.0 You'll just need to define the dialect:

  1. const sequelize = new Sequelize('database', 'username', 'password', {
  2. dialect: 'mssql'
  3. })

Executing raw SQL queries

As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function sequelize.query.

Here is how it works:

  1. // Arguments for raw queries
  2. sequelize.query('your query', [, options])
  3. // Quick example
  4. sequelize.query("SELECT * FROM myTable").then(myTableRows => {
  5. console.log(myTableRows)
  6. })
  7. // If you want to return sequelize instances use the model options.
  8. // This allows you to easily map a query to a predefined model for sequelize e.g:
  9. sequelize
  10. .query('SELECT * FROM projects', { model: Projects })
  11. .then(projects => {
  12. // Each record will now be mapped to the project's model.
  13. console.log(projects)
  14. })
  15. // Options is an object with the following keys:
  16. sequelize
  17. .query('SELECT 1', {
  18. // A function (or false) for logging your queries
  19. // Will get called for every SQL query that gets send
  20. // to the server.
  21. logging: console.log,
  22. // If plain is true, then sequelize will only return the first
  23. // record of the result set. In case of false it will all records.
  24. plain: false,
  25. // Set this to true if you don't have a model definition for your query.
  26. raw: false,
  27. // The type of query you are executing. The query type affects how results are formatted before they are passed back.
  28. type: Sequelize.QueryTypes.SELECT
  29. })
  30. // Note the second argument being null!
  31. // Even if we declared a callee here, the raw: true would
  32. // supersede and return a raw object.
  33. sequelize
  34. .query('SELECT * FROM projects', { raw: true })
  35. .then(projects => {
  36. console.log(projects)
  37. })

Replacements in a query can be done in two different ways, either usingnamed parameters (starting with :), or unnamed, represented by a ?

The syntax used depends on the replacements option passed to the function:

  • If an array is passed, ? will be replaced in the order that they appear in the array
  • If an object is passed, :key will be replaced with the keys from that object.If the object contains keys not found in the query or vice versa, an exceptionwill be thrown.
  1. sequelize
  2. .query(
  3. 'SELECT * FROM projects WHERE status = ?',
  4. { raw: true, replacements: ['active']
  5. )
  6. .then(projects => {
  7. console.log(projects)
  8. })
  9. sequelize
  10. .query(
  11. 'SELECT * FROM projects WHERE status = :status ',
  12. { raw: true, replacements: { status: 'active' } }
  13. )
  14. .then(projects => {
  15. console.log(projects)
  16. })

One note: If the attribute names of the table contain dots, the resulting objects will be nested:

  1. sequelize.query('select 1 as `foo.bar.baz`').then(rows => {
  2. console.log(JSON.stringify(rows))
  3. /*
  4. [{
  5. "foo": {
  6. "bar": {
  7. "baz": 1
  8. }
  9. }
  10. }]
  11. */
  12. })