You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
1.7 KiB

#!/usr/bin/env python3
# module extended from:
# https://github.com/auth0-blog/sqlalchemy-orm-tutorial/blob/master/examples/common/base.py
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import models.state
from models.state import StateBase
# TODO: replace with project relative path
_engine = create_engine('sqlite:///.data/state.db')
_SessionFactory = sessionmaker(bind=_engine)
# used to connect to the state database
# must close it after calling
def _get_session():
StateBase.metadata.create_all(_engine)
return _SessionFactory()
# decorator to connect to the state database
# will close session after function completes
def pass_session(func):
def wrapper(*args, **kwargs):
s = _get_session()
res = func(s, *args, **kwargs)
s.close()
return res
return wrapper
# using pass_session is more convenient
@pass_session
def add_state(sess, State):
'''Add a new entry to the given Table in the State database.'''
sess.add(State)
sess.commit()
@pass_session
def remove_state(sess, State, filter_expr):
'''Delete an entry that matches the given filter expression
from the given Table in the State database.'''
sess.query(State).filter(filter_expr).delete()
sess.commit()
@pass_session
def select_state(sess, State, filter_expr):
'''Return entries that match the given filter expression
from the given Table in the State database.'''
q = sess.query(State).filter(filter_expr).all() # TODO: make return first, all, and reveresed
return q
@pass_session
def list_state(sess, State):
'''Return all entires in the given Table in the State database.'''
q = sess.query(State).all()
return q