annot-server/models.py
author ymh <ymh.work@gmail.com>
Sun, 19 Oct 2014 12:52:38 +0200
changeset 42 926f0426ce78
parent 22 986ee928a866
child 43 e27c3c1c57f1
permissions -rw-r--r--
add event + event session + admin + category json management. Must rebuild database


#
# See LICENCE for detail
# Copyright (c) 2014 IRI
#

import datetime
import json
import uuid

from sqlalchemy import Column, Integer, String, DateTime, Text, Table, Index, text, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import UUID, JSON

from database import Base, engine


class Annotation(Base):
    __tablename__ = 'annotation'

    id = Column(Integer, primary_key=True, nullable=False)
    uuid = Column(UUID, unique=True, nullable=False)
    created = Column(DateTime, nullable=False, server_default=text("(now() at time zone 'utc')") )
    ts = Column(DateTime(timezone=True), nullable=False)
    event_code = Column(String(255), ForeignKey('event.code'), nullable=False)
    channel = Column(String(255), nullable=False)
    content = Column(JSON)

Index('idx_annotation_event', Annotation.event_code)
Index('idx_annotation_channel', Annotation.channel)
Index('idx_annotation_ts', Annotation.ts)


def insert_annot_async(params, conn):

    content = params.get('content', {})
    if not isinstance(content, basestring):
        params['content'] = json.dumps(content)
    if 'uuid' not in params:
        params['uuid'] = uuid.uuid4()

    if 'ts' not in params:
        params['ts'] = datetime.utcnow()

    stmt = Annotation.__table__.insert().values(**params).compile(engine)

    defer = conn.runOperation(stmt.string, stmt.params)
    defer.addCallback(lambda _: stmt.params)

    return defer


class Event(Base):
    __tablename__ = 'event'

    id = Column(Integer, primary_key=True, nullable=False)
    code = Column(String(255), unique=True, nullable=False)
    label = Column(String(2048), nullable=False)
    description = Column(Text(), nullable=True)

    sessions = relationship("EventSession", order_by="EventSession.order", backref="event")

    def __unicode__(self):
        return self.code

Index('idx_event_code', Event.code)

class EventSession(Base):
    __tablename__ = 'event_session'

    id = Column(Integer, primary_key=True, nullable=False)
    event_id = Column(Integer, ForeignKey(Event.id), nullable=False)
    project_id = Column(String(2048), nullable=True)
    order = Column(Integer, nullable=False, default=0)
    categories_json = Column(JSON, nullable=True)


Index('idx_event_session_order', EventSession.order)