这是我想要生成的SQL:
CREATE UNIQUE INDEX users_lower_email_key ON users (LOWER(email));
从SQLAlchemy Index documentation我希望这可行:
Index('users_lower_email_key', func.lower(users.c.email), unique=True)
但是在我调用metadata.create(engine)
之后,表被创建但是这个索引没有。我来自conf import dsn,DEBUG
engine = create_engine(dsn.engine_info())
metadata = MetaData()
metadata.bind = engine
users = Table('users', metadata,
Column('user_id', Integer, primary_key=True),
Column('email', String),
Column('first_name', String, nullable=False),
Column('last_name', String, nullable=False),
)
Index('users_lower_email_key', func.lower(users.c.email), unique=True)
metadata.create_all(engine)
在PostgreSQL中查看表定义我看到没有创建这个索引。
\d users
Table "public.users"
Column | Type | Modifiers
------------+-------------------+---------------------------------------------------------
user_id | integer | not null default nextval('users_user_id_seq'::regclass)
email | character varying |
first_name | character varying | not null
last_name | character varying | not null
Indexes:
"users_pkey" PRIMARY KEY, btree (user_id)
如何创建较低的唯一索引?
答案 0 :(得分:2)
我不知道你为什么要用小写索引整数列;问题是生成的sql没有进行类型检查:
LINE 1: CREATE UNIQUE INDEX banana123 ON mytable (lower(col5))
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
'CREATE UNIQUE INDEX banana123 ON mytable (lower(col5))' {}
另一方面,如果您使用实际的字符串类型:
Column('col5string', String),
...
Index('banana123', func.lower(mytable.c.col5string), unique=True)
索引按预期创建。如果,由于一些非常奇怪的原因,你坚持这个荒谬的索引,你只需要修复类型:
Index('lowercasedigits', func.lower(cast(mytable.c.col5, String)), unique=True)
哪个产得非常好:
CREATE UNIQUE INDEX lowercasedigits ON mytable (lower(CAST(col5 AS VARCHAR)))