SQLAlchemy中大小写不敏感的字符串列?

问题描述:

我可以在sqlalchemy中创建一个不区分大小写的字符串列吗?即时通讯使用SQLite和theres probaby一种方式来通过数据库通过更改排序,但我想保持它在sqlalchemy/python。SQLAlchemy中大小写不敏感的字符串列?

SQLite的确实允许NOCASE collation上的文本字段:

SQLite version 3.6.22 
sqlite> create table me (name text collate nocase); 
sqlite> .schema 
CREATE TABLE me (name text collate nocase); 
sqlite> insert into me values("Bob"); 
sqlite> insert into me values("alice"); 
sqlite> select * from me order by name; 
alice 
Bob 

和SQLAlchemy中有一个模式的collation()操作,但是当你运用它,我不知道。

默认情况下,SQLAlchemy似乎不允许在表创建(DDL)阶段使用COLLATE子句,但我终于想出了一种方法来使SQLAlchemy 0.6+工作。不幸的是,它涉及到一些子类和装饰,但它相当紧凑。

from sqlalchemy import * 
from sqlalchemy.ext.compiler import compiles 
from sqlalchemy.types import TypeDecorator 

class CI_String(TypeDecorator): 
    """ Case-insensitive String subclass definition""" 
    impl = String 
    def __init__(self, length, **kwargs): 
     if kwargs.get('collate'): 
      if kwargs['collate'].upper() not in ['BINARY','NOCASE','RTRIM']: 
       raise TypeError("%s is not a valid SQLite collation" % kwargs['collate']) 
      self.collation = kwargs.pop('collate').upper() 
     super(CI_String, self).__init__(length=length, **kwargs) 

@compiles(CI_String, 'sqlite') 
def compile_ci_string(element, compiler, **kwargs): 
    base_visit = compiler.visit_string(element, **kwargs) 
    if element.collation: 
     return "%s COLLATE %s" % (base_visit, element.collation) 
    else: 
     return base_visit 

新的字符串类型然后可以用于创建表的正常使用:

just_a_table = Table('table_name', metadata, 
       Column('case_insensitive', CI_String(8, collate='NOCASE'), nullable=False)) 

希望有人认为这有用!

在SQLAlchemy 0.8中,他们将排序规则参数添加到所有字符串类型。 COLLATE关键字现在支持几个数据库后端,包括MySQL,SQLite和Postgresql。你应该能够写出这样的事:

my_table = Table('table_name', meta, Column('my_column', 
        String(255, collate = 'NOCASE'), nullable=False)) 

https://bitbucket.org/zzzeek/sqlalchemy/issues/2276

+3

注:'collat​​ion'不'collat​​e' – 2016-03-02 23:48:54