activerecord-sqlserver-adapter unicode慢性能

时间:2014-07-18 15:17:02

标签: ruby-on-rails sql-server performance activerecord unicode

我在Rails 3.2.18和MRI-Ruby-2.0.0

的Gemfile:

gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter'

$ gem list | grep -E" tds | sql"

activerecord-sqlserver-adapter (3.2.12)
sqlite3 (1.3.9)
tiny_tds (0.6.2)

database.yml中:

development:
  adapter: sqlserver
  database: DBTEST
  username: domain\username
  password: somepwd
  host: myhostname
  port: 1433
  timeout: 180000

问题:查询需要很长时间才能完成。参见:

> MyModel.find_all_by_NRPIS '12700333166'
  MyModel Load (85869.3ms)  EXEC sp_executesql N'SELECT [MyTable].* FROM [MyTable] WHERE [MyTable].[NRPIS] = N''12700333166'''

所以我发现问题出现在N unicode转换中,因为当我查询它时,它真的很快,请参阅:

   >> ActiveRecord::Base.connection.select_all   "SELECT [MyTable].* FROM [MyTable] WHERE [MyTable].[NRPIS] = '12700333166'" }
   (62.5ms)  EXEC sp_executesql N'SELECT [MyTable].* FROM [MyTable] WHERE [TBCAGEDTrabalhador].[NRPIS] = ''12700333166'''

   >> ActiveRecord::Base.connection.select_all   "SELECT [MyTable].* FROM [MyTable] WHERE [MyTable].[NRPIS] = N'12700333166'" }
   (102324.0ms)  EXEC sp_executesql N'SELECT [MyTable].* FROM [MyTable] WHERE [MyTable].[NRPIS] = N''12700333166'''

这里发生了什么,我该如何解决这个问题?

我见过THIS QUESTION,但我真的想告诉sqlserver-adapter不要将任何内容转换为unicode。

1 个答案:

答案 0 :(得分:3)

找到它。

此问题已在此处讨论:disabling N'...' quoting for strings #124

问题在于引用utf-8字符串。除了上面的解决方案,也许您可​​以强制使用其他编码,以便字符串不会被引用,例如:

> a = MyModel.where "NRPIS = ?", '12700233166'.force_encoding("ISO-8859-1")
 MyModel Load (53.1ms)  EXEC sp_executesql N'SELECT [MyTable].* FROM [MyTable] WHERE (NRPIS = ''12700193166'')'

作为附加信息,MyModel引用的表没有定义primary_keys,只有NRPIS的索引。

我注意到,当我查询定义了primary_keys的表并且您只查询primary_keys时,索引不会被忽略,即使使用unicode引用,查询也会快速运行。