blockchain/database.py

58 lines
1.4 KiB
Python
Raw Normal View History

2017-12-25 18:12:25 +01:00
from sqlalchemy import Column, DateTime, Integer, PickleType, String, create_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import scoped_session, sessionmaker
# Set up the Database
engine = create_engine('sqlite:///electron.db')
db = scoped_session(sessionmaker(bind=engine))
2017-12-28 22:59:48 +01:00
2017-12-29 19:52:43 +01:00
Base = declarative_base()
class BaseModel(Base):
__abstract__ = True
2017-12-25 18:12:25 +01:00
@declared_attr
def __tablename__(self):
"""
2017-12-28 21:52:11 +01:00
Ensures all tables have the same name as their models (below)
2017-12-25 18:12:25 +01:00
"""
2017-12-28 21:52:11 +01:00
return self.__name__.lower()
2017-12-25 18:12:25 +01:00
def to_dict(self):
"""
2017-12-28 21:52:11 +01:00
Helper method to convert any database row to dict
2017-12-25 18:12:25 +01:00
"""
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
2017-12-29 19:52:43 +01:00
class Peer(BaseModel):
2017-12-25 18:12:25 +01:00
identifier = Column(String(32), primary_key=True)
2017-12-28 21:52:11 +01:00
hostname = Column(String, index=True, unique=True)
2017-12-29 19:52:43 +01:00
timestamp = Column(DateTime, index=True)
2017-12-25 18:12:25 +01:00
2017-12-29 19:52:43 +01:00
class Block(BaseModel):
2017-12-29 20:32:55 +01:00
height = Column(Integer, primary_key=True)
2017-12-25 18:12:25 +01:00
timestamp = Column(DateTime, index=True)
transactions = Column(PickleType)
previous_hash = Column(String(64))
proof = Column(String(64))
hash = Column(String(64))
2017-12-29 19:52:43 +01:00
class Config(BaseModel):
2017-12-25 18:12:25 +01:00
key = Column(String(64), primary_key=True, unique=True)
value = Column(PickleType)
def reset_db():
"""
2017-12-28 21:52:11 +01:00
Drops and Re-creates the Database
2017-12-25 18:12:25 +01:00
"""
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
2017-12-29 19:52:43 +01:00