from peewee import * from playhouse.fields import CompressedField from playhouse.hybrid import * import datetime from .prefixes import query_pseudo_prefix db = SqliteDatabase('test.db', pragmas=[('foreign_keys', 'ON')]) __tables__ = [] __all__ = ['create_tables', 'drop_tables'] def table(cls): __tables__.append(cls) __all__.append(cls.__name__) return cls def create_tables(): db.create_tables(__tables__, True) def drop_tables(): db.drop_tables(__tables__, True) class BaseModel(Model): class Meta: database = db @table class Document(BaseModel): content = CompressedField() created = DateField(default=datetime.datetime.now) description = CharField(null=True) direction = BooleanField(null=True) original_path = CharField(null=True) inserted = DateTimeField(default=datetime.datetime.now) @classmethod def matches(cls, prefix, value): return query_pseudo_prefix(prefix, value) or Document.id << ( DocumentTag.select(DocumentTag.document) .join(Tag, on=Tag.matches(prefix, value))) @table class Prefix(BaseModel): name = CharField(primary_key = True) builtin = BooleanField(default = False) pseudo = BooleanField(default = False) description = CharField(null=True) def __str__ (self): return self.name def __repr__ (self): if self.builtin: ext = ' (bp)' if self.pseudo else ' (b)' else: ext = '' return "<%s %s%s>" % (self.__class__.__name__, self.name, ext) @table class Tag(BaseModel): name = CharField() prefix = ForeignKeyField(Prefix, null=True, related_name = 'tag', db_column = 'prefix') description = CharField(null=True) @hybrid_method def matches(self, prefix, name): if isinstance(prefix, Prefix): prefix = prefix.name return (self.prefix_id == prefix) & (self.name == name) class Meta: indexes = [ (('name', 'prefix'), True) ] def prefixed_name(self): if self.prefix_id: return "%s:%s" % (self.prefix_id, self.name) else: return self.name def __str__(self): description = ' -- ' + self.description if self.description else '' return self.prefixed_name() + description def __repr__(self): return "<%s (#%d) %s>" % (self.__class__.__name__, self.id, self.prefixed_name()) @table class DocumentTag(BaseModel): document = ForeignKeyField(Document, related_name = 'tags') tag = ForeignKeyField(Tag) class Meta: primary_key = CompositeKey('document', 'tag') @table class TagImplications(BaseModel): tag = ForeignKeyField(Tag) implies_tag = ForeignKeyField(Tag, related_name = 'implications') class Meta: primary_key = CompositeKey('tag', 'implies_tag') def __repr__(self): return "<%s %d --> %d>" % (self.__class__.__name__, self.tag_id, self.implies_tag_id)