Skip to content
Snippets Groups Projects
database.py 2.51 KiB
Newer Older
  • Learn to ignore specific revisions
  • import binascii
    import os
    import socket
    import struct
    import logging
    from contextlib import contextmanager
    from sqlalchemy import create_engine
    from sqlalchemy import types, text
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    import ipaddress
    
    logger = logging.getLogger(__name__)
    
    DB_ADDRESS = os.getenv('DB_ADDRESS', '127.0.0.1')
    DB_DATABASE = os.getenv('DB_DATABASE')
    DB_PASSWORD = os.getenv('DB_PASSWORD')
    DB_USER = os.getenv('DB_USER')
    SQLALCHEMY_DATABASE_URL = 'postgresql://' + DB_USER + ':' + DB_PASSWORD + '@' + DB_ADDRESS + '/' + DB_DATABASE
    
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    Base = declarative_base()
    
    
    @contextmanager
    def get_db_context():
        """Provide a transactional scope around a series of operations."""
        db = SessionLocal()
        try:
            yield db
            db.commit()
        except:
            db.rollback()
            raise
        finally:
            db.close()
    
    
    def get_db():
        with get_db_context() as db:
            yield db
    
    
    
    def init_database():
        try:
            with get_db_context() as db:
                with open("./init.sql") as file:
                    query = text(file.read())
                    db.execute(query)
        except Exception as e:
            logger.error(f"Failed to initialize database schema; message: {e}")
            raise
    
    
    class MAC(types.TypeDecorator):
        impl = types.VARBINARY
    
        def process_result_value(self, value, dialect):
            if value is None:
                return value
            return binascii.hexlify(value, ':')
    
        def process_bind_param(self, value, dialect):
            if value is None:
                return value
            return binascii.unhexlify(value.replace(':', ''))
    
    
    class SERIAL(types.TypeDecorator):
        impl = types.VARBINARY
    
        def process_result_value(self, value, dialect):
            if value is None:
                return value
            r = bytes(value.hex(), 'utf-8')
            return r
    
        def process_bind_param(self, value, dialect):
            if value is None:
                return value
            return bytes.fromhex(value.decode())
    
    
    class IP(types.TypeDecorator):
        impl = types.BIGINT
    
        def process_result_value(self, value, dialect):
            if value is None:
                return value
            return ipaddress.IPv4Address(socket.inet_ntoa(struct.pack('!L', value)))
    
        def process_bind_param(self, value, dialect):
            if value is None:
                return value
            packed_ip = socket.inet_aton(str(value))
            return struct.unpack("!L", packed_ip)[0]