From cea032ecb83a589be94860f6045c55533237c529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20=27Necoro=27=20Neumann?= Date: Tue, 3 Oct 2017 22:07:57 +0200 Subject: Unique index on tags as a functional one. See also: https://github.com/coleifer/peewee/issues/1357 --- archivist/model.py | 6 ++++-- archivist/peewee_ext.py | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/archivist/model.py b/archivist/model.py index f03927e..8aa8897 100644 --- a/archivist/model.py +++ b/archivist/model.py @@ -7,7 +7,7 @@ import datetime from enum import Enum, unique from pkg_resources import resource_filename -from .peewee_ext import EnumField +from .peewee_ext import EnumField, SQLIndex from .peewee_fixes import * # dummy to force evaluation of those fixes db = SqliteExtDatabase('test.db', pragmas=[('foreign_keys', 'ON')]) @@ -122,6 +122,7 @@ class Prefix(BaseModel): @table class Tag(BaseModel): __keys__ = ('name', 'prefix') + name = CharField() prefix = ForeignKeyField(Prefix, null=True, related_name = 'tag', db_column = 'prefix') description = CharField(null=True) @@ -140,7 +141,8 @@ class Tag(BaseModel): class Meta: indexes = [ - (('name', 'prefix'), True) + (('name', 'prefix'), False), + (('name', SQLIndex('coalescePrefix', "COALESCE(prefix,'')")), True) ] @property diff --git a/archivist/peewee_ext.py b/archivist/peewee_ext.py index 40fe5e7..ff03861 100644 --- a/archivist/peewee_ext.py +++ b/archivist/peewee_ext.py @@ -1,4 +1,4 @@ -from peewee import Field +from peewee import Field, SQL from itertools import starmap from functools import reduce @@ -42,3 +42,18 @@ class EnumField(Field): def python_value(self, value): return value if value is None else self._enum_value(value) +class SQLIndex(SQL): + """Ugly hack to allow arbitrary index creation.""" + def __init__(self, field, sql): + self.field = field + super().__init__(sql) + + def clone_base(self): + return SQLWithField(field, self.value) + + @property + def db_column(self): + return self.field + + def as_entity(self): + return self -- cgit v1.2.3