如何在peewee中的计算字段上创建索引

时间:2018-10-03 19:34:03

标签: python peewee

我有以下peewee模型(简化):

class Foo(BaseModel):
    a = IntegerField() # actually a ForeignKey
    b = IntegerField(null=True) # ForeignKey
    c = IntegerField(null=True) # ForeignKey
    d = TextField()
    e = TextField(null=True)

我想在将NULL值视为相等的字段(a,b,c,d)上创建唯一索引。例如,应该只能插入一次(1,NULL,NULL,2,NULL)。

我设法编写了原始SQL查询来添加索引(-1应该是安全的,因为b和c是int> 0上的外键)

CapsuleTranslatorBundle.add_index(SQL('''CREATE UNIQUE INDEX foo_idx ON foo (
    a, # a_id if a is a foreign key
    COALESCE(b, -1),
    COALESCE(c, -1),
    d
);
'''))

我尝试了

idx = Foo.index(Foo.a,
                fn.COALESCE(Foo.b, -1),
                fn.COALESCE(Foo.c, -1),
                Foo.d, unique=True)
Foo.add_index(idx)

但是得到了

peewee.OperationalError: near "USING": syntax error

如何在不使用原始SQL的情况下添加索引?

2 个答案:

答案 0 :(得分:1)

存在一个错误,由于在ModelIndex结构中存在一些代码,因此无法正确解释功能对象。

固定在这里:

答案 1 :(得分:1)

我刚刚完成了对代码的分析。碰巧是一个错误,已经由@coleifer在存储库中确认并修复-谢谢!

这是一个快速修复程序,可以在peewee 3.7.0上生成有效的SQL(对于sqlite3)(在发布固定代码之前可能会派上用场):

idx = Foo.index(Foo.a,
                Value(fn.COALESCE(Foo.b, SQL('-1'))),
                Value(fn.COALESCE(Foo.c, SQL('-1'))),
                Foo.d, unique=True)
Foo.add_index(idx)

产生

('CREATE UNIQUE INDEX IF NOT EXISTS "foo_a_d" ON "foo" ("a", COALESCE("b", -1), COALESCE("c", -1), "d")', [])

没有SQL('-1')(仅使用-1),我又遇到了另一个错误peewee.OperationalError: parameters prohibited in index expressions,生成的查询是:'CREATE UNIQUE INDEX IF NOT EXISTS "foo_a_d" ON "foo" ("a", COALESCE("b", ?), COALESCE("c", ?), "d")', [-1, -1]