Sling Academy
Home/Node.js/How to View Raw SQL Queries Generated by Sequelize.js

How to View Raw SQL Queries Generated by Sequelize.js

Last updated: December 29, 2023

Learn how to view the raw SQL queries generated by Sequelize.js.

Solution 1: Using the logging Option

The logging option provided by Sequelize can be set during the Sequelize instance creation. It can be a boolean or a function. If set to true, Sequelize will log all SQL statements to the console. If a function is provided, it can be customized to handle the log output, allowing developers to see the raw SQL queries being executed.

  1. Create a Sequelize instance with the logging option.
  2. Specify a function to handle the SQL log output.
  3. Execute your Sequelize query as usual.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql',
  logging: console.log,
});

sequelize.query('SELECT * FROM users').then(result => {
  console.log(result);
});

Pros: Simple and easy to implement. Can be enabled globally for all queries.

Cons: May clutter the console if logging every query is not necessary.

Solution 2: Enabling Logger for Specific Query

Instead of enabling the logging for all queries, Sequelize allows you to pass the logging option directly to individual queries. This can be useful for debugging specific queries without affecting the output of others.

  1. Perform a query with an additional option for logging.
  2. Provide a function to output the raw SQL of just that query.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql',
});

sequelize.query('SELECT * FROM users', {
  logging: console.log,
}).then(result => {
  console.log(result);
});

Pros: Allows for selective logging. Good for debugging individual queries.

Cons: Requires adding the logging option to each specific query.

Solution 3: Hooking into Sequelize Promises

Another approach is to hook into the promise returned by a Sequelize query and print out the SQL statement before it’s executed. Sequelize queries return promises, and by attaching a then function, you can extract and log the SQL.

  1. Define a wrapper function to intercept and log the SQL statement.
  2. Use the wrapper function around your Sequelize query calls.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql',
});

function logSql(queryPromise) {
  return queryPromise.then(queryResult => {
    console.log(queryResult.sql);
    return queryResult;
  });
}

const query = sequelize.query('SELECT * FROM users');
logSql(query).then(result => {
  console.log(result);
});

Pros: Allows for logging on a per-query basis without altering global settings or the original query.

Cons: Requires extra wrapping and might become cumbersome with a large number of queries.

In conclusion, observing raw SQL generated by Sequelize.js is a valuable debugging tool that can be implemented in several ways. The logging option is the most straightforward method, offering both global and per-query logging. Hooking into Sequelize promises provides a flexible way to log SQL without modifying existing queries, suitable for selective debugging. Developers should choose the method that best fits their current debugging context and the level of logging granularity required.

Next Article: Sequelize.js: How to connect to MySQL database

Previous Article: Node.js & Sequelize: How to Make Join Queries

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates