简体   繁体   English

Rails:您可以将此SQL查询从MySQL转换为SQlite吗?

[英]Rails: Can you translate this SQL Query from MySQL to SQlite?

can you translate this Rails code for MySQL: 您可以为MySQL翻译以下Rails代码:

def Customer.find_by_key(key)
  Customer.find(:all, :conditions => "pre_name REGEXP '.*#{key}.*' 
      OR sur_name REGEXP '.*#{key}.*' 
      OR street REGEXP '.*#{key}.*' 
      OR zip REGEXP '.*#{key}.*' 
      OR city REGEXP '.*#{key}.*' 
      OR phone_1 REGEXP '.*#{key}.*' 
      OR phone_2 REGEXP '.*#{key}.*' 
      OR email REGEXP '.*#{key}.*' 
      OR company REGEXP '.*#{key}.*'")
end

to SQlite3 code? 到SQlite3代码?

Replace these: 替换这些:

pre_name REGEXP '.*#{key}.*'

with LIKE: 与LIKE:

pre_name LIKE '%#{key}%'

Or better, use placeholders: 或者更好的是,使用占位符:

:conditions => [
    "pre_name LIKE :pattern OR sur_name LIKE :pattern ...",
    { :pattern => '%' + key + '%' }
]

SQLite understands REGEXP but it is not implemented by default , you have to implement it yourself. SQLite 理解REGEXP,但默认情况下未实现 ,您必须自己实现。 You could add your implementation but there's no point when LIKE will probably do the job. 您可以添加实现,但是LIKE何时可以完成这项工作毫无意义。

The REGEXP function isn't defined by default in sqlite3, you'll have to do a bit of work before. 在sqlite3中,默认情况下未定义REGEXP函数,您需要做一些工作。

Stick this in an initializer (for example config/initializers/sqlite_regexp.rb ), works with rails 3.1 (see below for rails 3.0): 将其粘贴在初始化程序中(例如config/initializers/sqlite_regexp.rb ),可与rails 3.1一起使用(对于rails 3.0,请参见下文):

require 'active_record/connection_adapters/sqlite3_adapter'

class ActiveRecord::ConnectionAdapters::SQLite3Adapter
  def initialize(db, logger, config)
    super
    db.create_function('regexp', 2) do |func, pattern, expression|
      regexp = Regexp.new(pattern.to_s, Regexp::IGNORECASE)

      if expression.to_s.match(regexp)
        func.result = 1
      else
        func.result = 0
      end
    end
  end
end

Code stolen here . 代码在这里被盗。

You could of course rewrite your query as in @mu's answer, but I figured it would be nice to know how to really implement the function. 您当然可以按照@mu的答案来重写查询,但是我认为知道如何真正实现该功能将非常高兴。

Update 更新资料

The code above doesn't work for rails 3.0, this should work: 上面的代码不适用于rails 3.0,这应该可以工作:

require 'active_record/base'
require 'active_record/connection_adapters/sqlite_adapter'

module ActiveRecord::ConnectionAdapters
  class SQLite3Adapter < SQLiteAdapter
    def initialize(db, logger, config)
      super
      db.create_function('regexp', 2) do |func, pattern, expression|
        regexp = Regexp.new(pattern.to_s, Regexp::IGNORECASE)

        if expression.to_s.match(regexp)
          func.result = 1
        else
          func.result = 0
        end
      end
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM