rascunho

commit 5d5ca5affa46e0d525f2cd18dc0a7055e21e2b63

Author: Pedro Lucas Porcellis <pedrolucasporcellis@gmail.com>

Rig it up database

 core/database.py | 33 +++++++++++++++++++++++++++++++++
 core/types/__init__.py | 1 +
 core/types/document.py | 20 ++++++++++++++++++++


diff --git a/core/database.py b/core/database.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c68f5788eadcf97c0c3f878188d8ba70aaca780
--- /dev/null
+++ b/core/database.py
@@ -0,0 +1,33 @@
+from sqlalchemy import create_engine, event
+from sqlalchemy.orm import sessionmaker, scoped_session
+from sqlalchemy.ext.declarative import declarative_base
+
+from datetime import datetime
+
+from core.config import read_from_config
+
+engine = create_engine(read_from_config('connection-string'), echo=True)
+db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
+
+Base = declarative_base()
+Base.query = db.query_property()
+
+def init_database():
+    @event.listens_for(Base, 'before_insert', propagate=True)
+    def before_insert(mapper, connection, target):
+        if hasattr(target, '_no_autoupdate'):
+            return
+        if hasattr(target, 'created_at'):
+            target.created_at = datetime.utcnow()
+        if hasattr(target, 'updated_at'):
+            target.updated_at = datetime.utcnow()
+
+    @event.listens_for(Base, 'before_update', propagate=True)
+    def before_insert(mapper, connection, target):
+        if hasattr(target, '_no_autoupdate'):
+            return
+        if hasattr(target, 'updated_at'):
+            target.updated_at = datetime.utcnow()
+
+    import core.types
+    Base.metadata.create_all(bind=engine)




diff --git a/core/types/__init__.py b/core/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c01ea2470e408389a5b947f4247f87ecd21a81d
--- /dev/null
+++ b/core/types/__init__.py
@@ -0,0 +1 @@
+from . import document




diff --git a/core/types/document.py b/core/types/document.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f6cf83adf823e11b6bb9fb671eb7a8528fd00d9
--- /dev/null
+++ b/core/types/document.py
@@ -0,0 +1,20 @@
+import sqlalchemy as sa
+from core.database import Base
+
+class Document(Base):
+    __tablename__ = 'documents'
+
+    id = sa.Column(sa.Integer, primary_key=True)
+    sha = sa.Column(sa.String(40), nullable=False, index=True)
+    content = sa.Column(sa.Unicode, nullable=False)
+
+    created_at = sa.Column(sa.DateTime, nullable=False)
+    updated_at = sa.Column(sa.DateTime, nullable=False)
+
+    def to_dict(self):
+        return {
+            "sha": self.sha,
+            "content": self.content,
+            "created_at": self.created_at,
+            "updated_at": self.updated_at
+        }