使用Postgresql在Datamapper中像(ilike)一样不区分大小写

moo*_*use 7 ruby postgresql datamapper

我们在Sinatra应用程序中使用Datamapper,并且希望使用不区分大小写,就像Sqlite(开发中的本地)和Postgresql(生产中的Heroku)一样.

我们有这样的陈述

TreeItem.all(:name.like =>"%#{term}%",:unique => true,:limit => 20)
Run Code Online (Sandbox Code Playgroud)

如果term是"BERL",我们从Sqlite和Postgresql后端获得建议"BERLIN".但是,如果term是"Berl",我们只从Sqlite而不是Postgresql获得结果.

我想这与dm-postgres-adapter和dm-sqlite-adapter LIKE在结果SQL查询中输出a这一事实有关.由于Postgresql具有区分大小写,因此LIKE我们得到了这个(对于我们不需要的)行为.

有没有办法像Datamapper一样获得不区分大小写,而不需要使用原始SQL查询到适配器或修补适配器ILIKE而不是LIKE

我当然可以在两者之间使用某些东西,例如:

TreeItem.all(:conditions => ["name LIKE ?","%#{term}%"],:unique => true,:limit => 20)
Run Code Online (Sandbox Code Playgroud)

但是我们将在我们自己的代码中使用Postgresql,而不仅仅是作为适配器的配置.

moo*_*use 4

通过编写我自己的数据对象适配器来覆盖该like_operator方法,我设法使 Postgres 不区分大小写ILIKE

require 'do_postgres'
require 'dm-do-adapter'

module DataMapper
  module Adapters

    class PostgresAdapter < DataObjectsAdapter

      module SQL #:nodoc:
        private

        # @api private
        def supports_returning?
          true
        end

        def like_operator(operand)
          'ILIKE'
        end
      end

      include SQL

    end

    const_added(:PostgresAdapter)

  end
end
Run Code Online (Sandbox Code Playgroud)

然而,最终我决定移植相关应用程序以使用文档数据库。