node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

How to log all SQL query ?

Open gsdt opened this issue 5 years ago • 9 comments

var mysql = require("mysql2");
const chalk = require('chalk');
...
pool.on("connection", function (connection) {
  connection.on("enqueue", function (sequence) {
    if ("Query" === sequence.constructor.name) {
      console.log(chalk.green(`[+] mysql: ${sequence.sql}`));
    }
  });
});
...

I expect to see this on console:

[+] mysql: start transaction; insert into `entities` (`type`) values (3); insert into `companies` set `id` = last_insert_id(), `name` = 'google', `created_by` = 4, `url` = '/google2'; commit;

but nothing happens?

how to make it work on mysql2 ?

gsdt avatar May 15 '20 02:05 gsdt

is it something that worked with mysqljs/mysql and does not work with mysql2?

Before I start helping with "how to make this example work" can you please describe what you see and how it's not matching what you want to see

sidorares avatar May 15 '20 02:05 sidorares

thank you for replying me, this question has been asked 3 years ago: https://github.com/sidorares/node-mysql2/issues/610#issuecomment-314933491 did you add this feature?

gsdt avatar May 15 '20 02:05 gsdt

I'll have to check, can't remember. ( or you can try to check it yourself in https://github.com/sidorares/node-mysql2/blob/master/lib/pool.js )

If not added I might have time to add this weekend

sidorares avatar May 15 '20 02:05 sidorares

It seems doesn't work. Please add a feature to log all queries.

gsdt avatar May 15 '20 02:05 gsdt

I need this feature badly.

joynal avatar Jun 24 '20 11:06 joynal

+1 this feature would be very helpful!

alete89 avatar Oct 06 '20 17:10 alete89

@joynal @alete89 did you solve this?

damianobarbati avatar Dec 16 '20 16:12 damianobarbati

Was it resolved? Is there any simple listener I can use to console.log any query executed?

deepakaggarwal7 avatar Sep 17 '23 09:09 deepakaggarwal7

@damianobarbati no, nothing added as far as I know. I'm open to adding something like

connection.on('commandStart', command => {
  if (command.name === 'Query') {
      console.log(command.sql);
  } 
});

It might be that all we need is this.emit('commandStart', this._command) on https://github.com/sidorares/node-mysql2/blob/b5b336b0783462b9d1d9b8801ec026e536006ea3/lib/connection.js#L482

do you want to try and create PR @damianobarbati ?

sidorares avatar Sep 17 '23 10:09 sidorares