繁体   English   中英

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

[英]How to create index on computed fields in 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的情况下添加索引?

有一个错误,由于ModelIndex构造中的某些代码,功能对象被错误地解释。

固定在这里:

我刚刚完成了对代码的分析。 碰巧是一个错误,已经由@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另一个错误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]

暂无
暂无

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

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