如何使用占位符为AR SQL Server适配器编写原始SQL?

时间:2013-10-01 20:10:53

标签: sql ruby-on-rails sql-server-2008 activerecord

我有一个复杂的连接条件,有三个插值是双引号(作为AR引用的一部分,以避免SQL注入攻击,我认为)。

我已经准备好了其他问题,说我可以使用:sanitize_sql:sanitize_sql_array?占位符,但唉,这些似乎未定义activerecord-sqlserver-adapter

所以,我的问题是,如何通过ActiveRecord与SQL服务器一起工作?


def self.with_active_deal_counts
  joins(<<-SQL.squish
    LEFT OUTER JOIN (
      SELECT [b].[merchant_id], COUNT(*) deal_count
      FROM   [tbl_deal] b
      WHERE deal_active = 1
        AND deal_archive = 2
        AND ( deal_end = '1900-01-01'
              OR deal_end > '#{Time.now + Time.now.utc_offset - 1.day}')
        AND deal_start <= '#{Time.now + Time.now.utc_offset}'
      GROUP BY [b].[merchant_id]
    ) a ON a.[merchant_id] = [tbl_merchant].[merchant_id]
    SQL
  ).select("tbl_merchant.*, a.deal_count")
end

这会产生

EXEC sp_executesql N'SELECT tbl_merchant.*, a.deal_count FROM [tbl_merchant] LEFT OUTER JOIN (
 SELECT [b].[merchant_id], COUNT(*) deal_count
 FROM [tbl_deal] b
 WHERE deal_active = 1
 AND deal_archive = 2
 AND ( deal_end = ''1900-01-01''
 OR deal_end > ''2013-09-30 07:07:20 -0700'')
 AND deal_start <= ''2013-10-01 07:07:20 -0700''
 GROUP BY [b].[merchant_id]
) a ON a.[merchant_id] = [tbl_merchant].[merchant_id]'

...由于双引号值而无效,例如。 ''2013-09-30 07:07:20 -0700''

具体来说,我得到Incorrect syntax near '1900'(在SQL Management Studio中运行查询时。

1 个答案:

答案 0 :(得分:0)

我知道你的问题是关于占位符的,我不确定。我遇到了类似的情况,最后使用ruby“插入字符串”,这可能值得一看。

%Qhttp://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals)或对于多行sql,heredoc可能很方便。以下是如何将%Q用于sql:

sql = %Q[ some crazy SQL with '#{Time.now}' ]

示例用法如下:

sql = %Q[ select '#{Time.now}' ]
# This translates to
N' select ''2013-10-01 16:25:46 -0400'' '
=> #<ActiveRecord::Result:0x000000052acc40 @columns=[""], @rows=[["2013-10-01 16:25:46 -0400"]], @hash_rows=nil>