node.js 如何查看 Sequelize.js 生成的 SQL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21427501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I see the SQL generated by Sequelize.js?
提问by ideaboxer
I want to see the SQL commands that are sent to the PostgreSQL server because I need to check if they are correct. In particular, I am interested in the table creation commands.
我想查看发送到 PostgreSQL 服务器的 SQL 命令,因为我需要检查它们是否正确。特别是,我对表创建命令感兴趣。
For instance, ActiveRecord (Ruby) prints its SQL statements to standard output. Is this possible with Node.js/ActionHero.js and Sequelize.js as well?
例如,ActiveRecord (Ruby) 将其 SQL 语句打印到标准输出。Node.js/ActionHero.js 和 Sequelize.js 也可以这样做吗?
回答by Jan Aagaard Meier
You can pass a logging option when initializing sequelize, which can either be a function or console.log
你可以在初始化 sequelize 时传递一个日志选项,它可以是一个函数或 console.log
var sequelize = new Sequelize('database', 'username', 'password', {
logging: console.log
logging: function (str) {
// do your own logging
}
});
You can also pass a logging option to .sync if you only want to view the table creation queries
如果您只想查看表创建查询,您还可以将日志记录选项传递给 .sync
sequelize.sync({ logging: console.log })
回答by Adlen Afane
As stated in the log Error: Please note that find* was refactored and uses only one options object from now on.. For the latest sequelize version (4) if you want to have the result for only one command:
如日志中所述Error: Please note that find* was refactored and uses only one options object from now on.。对于最新的续集版本 (4),如果您只想获得一个命令的结果:
User.findAll({where: {...}, logging: console.log})
User.findAll({where: {...}, logging: console.log})
回答by vpontis
If you want to look at the sequelize for one command you can listen to it and attach a function to the print the sql.
如果您想查看一个命令的续集,您可以收听它并附加一个函数来打印 sql。
Check out this example:
看看这个例子:
User.find(1).on('sql', console.log).then(function(user) {
// do whatever you want with the user here

