annot-server/models.py
changeset 22 986ee928a866
parent 0 e1d4d7a8255a
child 42 926f0426ce78
--- a/annot-server/models.py	Tue Oct 14 18:00:13 2014 +0200
+++ b/annot-server/models.py	Tue Oct 14 05:07:37 2014 +0200
@@ -8,17 +8,39 @@
 import json
 import uuid
 
-def get_table_create_stmt():
-    return (
-        "CREATE TABLE IF NOT EXISTS annotations ( "
-        "id serial PRIMARY KEY, "
-        "uuid uuid UNIQUE, "
-        "created timestamp default (now() at time zone 'utc') NOT NULL, "
-        "ts timestamptz NOT NULL, "
-        "event varchar(255) NOT NULL, "
-        "channel varchar(255) NOT NULL, "
-        "content json);"
-    )
+from sqlalchemy import Column, Integer, String, DateTime, Table, Index, text
+from sqlalchemy.sql import func
+from sqlalchemy.dialects.postgresql import UUID, JSON
+
+from database import Base, engine
+
+#def get_table_create_stmt():
+#    return (
+#        "CREATE TABLE IF NOT EXISTS annotations ( "
+#        "id serial PRIMARY KEY, "
+#        "uuid uuid UNIQUE, "
+#        "created timestamp default (now() at time zone 'utc') NOT NULL, "
+#        "ts timestamptz NOT NULL, "
+#        "event varchar(255) NOT NULL, "
+#        "channel varchar(255) NOT NULL, "
+#        "content json);"
+#    )
+
+class Annotation(Base):
+    __tablename__ = 'annotations'
+
+    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 = Column(String(255), nullable=False)
+    channel = Column(String(255), nullable=False)
+    content = Column(JSON)
+
+Index('idx_event', Annotation.event)
+Index('idx_channel', Annotation.channel)
+Index('idx_ts', Annotation.ts)
+
 
 def insert_annot_async(params, conn):
 
@@ -31,7 +53,9 @@
     if 'ts' not in params:
         params['ts'] = datetime.utcnow()
 
-    defer = conn.runOperation("INSERT INTO annotations (uuid, ts, event, channel, content) VALUES (%(uuid)s, %(ts)s, %(event)s, %(channel)s, %(content)s)", params)
-    defer.addCallback(lambda _: params)
+    stmt = Annotation.__table__.insert().values(**params).compile(engine)
+
+    defer = conn.runOperation(stmt.string, stmt.params)
+    defer.addCallback(lambda _: stmt.params)
 
     return defer