Sql rake 文件中的查询未显示结果
Sql Query in rake file not showing result
我正尝试在 rake 任务中 运行 这个 SQL 查询,但它确实显示了任何结果。但是我已经在 Dbeaver 中尝试了 运行ning 这个查询并且它 运行 非常好。第一个 puts 只在终端中显示 # 而 second puts 不显示任何值。请帮我找到问题。
namespace :expense do
desc "send emails"
task send_reminder: :environment do
sql = <<-SQL
SELECT
c.id as corporation_id
, cs_i.id as issue_id
, MAX(i.id) as expense_id
, MAX(i."date") as expense_date
FROM companies c
JOIN expenses i on i.corporation_id = c.id
JOIN issues cs_i on i.issue_id = cs_i.id
WHERE c.amount > 0 and
cs_i.amount > 0 and
i."date" < (select (current_date at time zone 'UTC' - interval '1 week')) and i.amount_type = 0
GROUP BY c.id, cs_i.id
SQL
scope = Expense.connection.execute(sql)
puts "#{scope}"
scope.each do |expense|
puts "#{expense}"
end
end
end
如果您尝试 运行 原始 SQL,您可能不应该使用 connection.execute
。请参阅 execute
方法的文档:
Executes the SQL statement in the context of this connection and returns the raw result from the connection adapter. Note: depending on your database connector, the result returned by this method may be manually memory managed. Consider using the exec_query
wrapper instead.
execute
returns 来自您的连接适配器的原始结果。例如,对于 PostgreSQL 它是 PG::Result
对象。
您可能也不想使用 exec_query
,因为它也会 return 某种原始结果。
根据我在您的代码中看到的情况,您可能想使用 find_by_sql
。它执行查询和 returns 标准 ActiveRecord 对象:
namespace :expense do
desc "send emails"
task send_reminder: :environment do
sql = <<-SQL
sql truncated...
SQL
scope = Expense.find_by_sql(sql)
puts "#{scope}"
scope.each do |expense|
puts "#{expense}"
end
end
end
我正尝试在 rake 任务中 运行 这个 SQL 查询,但它确实显示了任何结果。但是我已经在 Dbeaver 中尝试了 运行ning 这个查询并且它 运行 非常好。第一个 puts 只在终端中显示 # 而 second puts 不显示任何值。请帮我找到问题。
namespace :expense do
desc "send emails"
task send_reminder: :environment do
sql = <<-SQL
SELECT
c.id as corporation_id
, cs_i.id as issue_id
, MAX(i.id) as expense_id
, MAX(i."date") as expense_date
FROM companies c
JOIN expenses i on i.corporation_id = c.id
JOIN issues cs_i on i.issue_id = cs_i.id
WHERE c.amount > 0 and
cs_i.amount > 0 and
i."date" < (select (current_date at time zone 'UTC' - interval '1 week')) and i.amount_type = 0
GROUP BY c.id, cs_i.id
SQL
scope = Expense.connection.execute(sql)
puts "#{scope}"
scope.each do |expense|
puts "#{expense}"
end
end
end
如果您尝试 运行 原始 SQL,您可能不应该使用 connection.execute
。请参阅 execute
方法的文档:
Executes the SQL statement in the context of this connection and returns the raw result from the connection adapter. Note: depending on your database connector, the result returned by this method may be manually memory managed. Consider using the
exec_query
wrapper instead.
execute
returns 来自您的连接适配器的原始结果。例如,对于 PostgreSQL 它是 PG::Result
对象。
您可能也不想使用 exec_query
,因为它也会 return 某种原始结果。
根据我在您的代码中看到的情况,您可能想使用 find_by_sql
。它执行查询和 returns 标准 ActiveRecord 对象:
namespace :expense do
desc "send emails"
task send_reminder: :environment do
sql = <<-SQL
sql truncated...
SQL
scope = Expense.find_by_sql(sql)
puts "#{scope}"
scope.each do |expense|
puts "#{expense}"
end
end
end