如何查看Sequelize.js生成的SQL?


98

我想查看发送到PostgreSQL服务器的SQL命令,因为我需要检查它们是否正确。我特别对表创建命令感兴趣。

例如,ActiveRecord(Ruby)将其SQL语句打印到标准输出。Node.js / ActionHero.js和Sequelize.js也可能吗?

Answers:


154

您可以在初始化sequelize时传递日志记录选项,该选项可以是函数或console.log。

var sequelize = new Sequelize('database', 'username', 'password', {
    logging: console.log
    logging: function (str) {
        // do your own logging
    }
});

如果只想查看表创建查询,也可以将日志记录选项传递给.sync

sequelize.sync({ logging: console.log })

谢谢,这正是我想要的。DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log - 这是什么意思?
ideaboxer 2014年

意味着您应该传递一个函数而不是true。
米克·汉森

5
我从来没有过true
ideaboxer 2014年

1
我参加聚会有点晚,但是console.log工作方式很神秘。您应该能够避免使用{ logging: (msg) => console.log(msg) }或记录日志消息{ logging: function(msg) { console.log(msg) } }。(未经测试,所以我可能完全错了)
3ocene

1
有什么办法可以查看生成的查询,但是查询不应执行?
NIKHIL CM

37

如日志中所述Error: Please note that find* was refactored and uses only one options object from now on.。对于最新的续集版本(4),如果只想获得一个命令的结果:

User.findAll({where: {...}, logging: console.log})


1
这也适用于本地查询:query(statement, { replacements: { userId: userId, superiorPositions: [ 4, 5, 7 ], departments: [ departmentId ] }, logging: console.log });
Christian Noel

1
这是正确的日志记录答案:应该在控制台4中放置console.log。
user627119

30

如果您想查看一个命令的续集,可以听一下它,并将一个函数附加到打印sql上。

看看这个例子:

User.find(1).on('sql', console.log).then(function(user) {
  // do whatever you want with the user here

38
现在,您可以传递记录器作为记录单个语句的选项:User.find(1, { logging: console.log })
Stephen Watkins 2015年

4
煤矿只是说<functionName>.findOne(...).on is not a function 使用sequelize 3.30.4
金纳

1
似乎某些关联mixin不支持日志记录选项。具体来说,get*一个belongsTo关系的源。
汤姆(Tom),

1

您还可以通过设置环境来利用Sequelize对调试模块的使用,从而: DEBUG=sequelize:sql* 在启动应用程序之前。


1
这应该是一个答案!谢谢你的提示!
confiq
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.