简体   繁体   English

使用Active Record区分大小写的数据库搜索

[英]Case-sensitive database search with Active Record

Does Active Record provide a way to generate SQL that forces a text search to be case-sensitive? Active Record是否提供一种生成SQL的方法,以强制将文本搜索区分大小写?

Ruby-on-Rails generators instructed to create a string-type column produce a simple VARCHAR(255) field, in a mysql database. Ruby-on-Rails生成器被指示创建一个字符串类型的列,它在mysql数据库中生成一个简单的VARCHAR(255)字段。 It turns out that queries on such columns are case insensitive by default . 事实证明, 对此类列的查询默认情况下不区分大小写

Thus, an Active Record search such as: 因此,进行Active Record搜索,例如:

Secret.where(token: 'abcde')

will match records with tokens abcde , ABcdE , etc. 将匹配具有令牌abcdeABcdE等的记录。

Without changing the underlying database column (eg specifying a utf8_bin collation) searches can be made case sensitive by explicitly tweaking the where clause: 在不更改基础数据库列的情况下(例如,指定utf8_bin排序规则),可以通过显式调整where子句使搜索区分大小写:

Secret.where('binary token = ?', 'abcde')

However, this is database-specific, and I am wondering if Active Record has an idiom to accomplish the same for any database. 但是,这是特定于数据库的,我想知道Active Record是否有一个习惯用法可以对任何数据库完成相同的操作。 Just as an example, something resembling the where.not construct: 例如,类似于where.not构造的东西:

Secret.where.binary(token: 'abcde')

Wouldn't this be a common enough need? 这不是足够普遍的需求吗?

In short: there is NO ActiveRecord idiom for case- sensitive search. 简而言之:没有区分大小写的 ActiveRecord习惯用法。


For case- insensitive search you can try to use this . 对于不区分大小写的搜索,您可以尝试使用this It still works, but source code was changed a bit. 它仍然有效,但是源代码有所更改。 So, use it on your own risk. 因此,使用它需要您自担风险。

In general, case sensitivity is subset of the Collation idiom. 通常,区分大小写是整理习惯用法的子集。 And different DBMS use very different default collations for string(text) data types, including default case sensitivity . 不同的DBMS对字符串(文本)数据类型使用非常不同的默认排序规则,包括默认的区分大小写 Detailed description for MySQL. MySQL的详细说明

There is a sql operator COLLATE which is very common across DBMS(but seems still is not in SQL Standard). 有一个SQL运算符COLLATE在DBMS中非常常见(但似乎在SQL Standard中仍然不存在)。 But ActiveRecord sources show it only in schema creation code. 但是ActiveRecord源仅在架构创建代码中显示它。 Neither ActiveRecord , nor Arel gems do not use COLLATE in where search(sad). ActiveRecordArel gem都不where搜索(悲伤)的where使用COLLATE

Note: Please, don't miss the database tag( mysql etc) in a Question. 注意:请不要在问题中遗漏数据库标签( mysql等)。 There are many Questions and Answers on SO without the tags(or with sql one), which are completely irrelevant for the most of DBMSs except author's one. 关于SO的问题和答案有很多,没有标签(或带有sql ),这与大多数 DBMS完全无关,除了作者的。

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

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