def __process_propulsion_events(session: session.Session) -> OPNAV_EXIT_STATUS: """ Processes propulsion events (if there are any) using the trajectory ukf. [session]: db session @return opnav_exit_status """ entries = session.query(OpNavPropulsionModel).all() num_entries = len(entries) logger.info("[OPNAV]: process propulsion...") for entry_index, entry in enumerate(entries): logger.info( f'[OPNAV]: propulsion event: {entry_index+1}/{num_entries}') logger.info(f'[OPNAV]: ----------PROPULSION EVENT----------') logger.info(entry) exit_status = __process_propulsion(session, entry) if exit_status is not OPNAV_EXIT_STATUS.SUCCESS: return exit_status logger.info(f'[OPNAV] -------------------------------------') # clear table try: num_rows_deleted = session.query(OpNavPropulsionModel).delete() session.commit() assert num_entries == num_rows_deleted return OPNAV_EXIT_STATUS.SUCCESS except: session.rollback() return OPNAV_EXIT_STATUS.FAILURE
def S(*args, **kwargs): """Boilerplate context manager for creating and using sessions. This makes using a database session as simple as: .. code-block:: python with S('postgresql:///databasename') as s: s.execute('select 1;') Does `commit()` on close, `rollback()` on exception. Also uses `scoped_session` under the hood. """ Session = get_scoped_session_maker(*args, **kwargs) try: session = Session() yield session session.commit() except Exception: session.rollback() raise finally: session.close()
def session_scope(versioned=True, ignore_soft_deletes=True, namespace_id=None): """ Provide a transactional scope around a series of operations. Takes care of rolling back failed transactions and closing the session when it goes out of scope. Note that sqlalchemy automatically starts a new database transaction when the session is created, and restarts a new transaction after every commit() on the session. Your database backend's transaction semantics are important here when reasoning about concurrency. Parameters ---------- versioned : bool Do you want to enable the transaction log? ignore_soft_deletes : bool Whether or not to ignore soft-deleted objects in query results. namespace_id : int Namespace to limit query results with. Yields ------ InboxSession The created session. """ session = InboxSession(versioned, ignore_soft_deletes, namespace_id) try: yield session session.commit() except: session.rollback() raise finally: session.close()
def __get_session() -> Generator[Session, None, None]: session = None try: csession = scoped_session(SESS_MAKER) session = csession() yield session session.commit() except Exception as e: session.rollback() raise SessionError(e) finally: if session: session.close()
def transactional(auto_close=True): """Provide a transactional scope around a series of operations.""" using_scope = CONF.portal.using_scope session = get_session() try: yield session if not using_scope: session.commit() except: if not using_scope: session.rollback() raise finally: if auto_close and not using_scope: session.close()
def fill_one_financialv2(ticker: str, year: int = 1900): stock0: Stock = session.query(Stock).filter_by( stock_ticker=ticker).one_or_none() print('current financials:', stock0) pe = randrange(1, 100) pb = randrange(1, 100) try: fin = Financials(price_book=pb, price_earning=pe, year=year, refer_stock_ticker=stock0.stock_ticker) except sqlite3.IntegrityError: session.rollback() year += 1 raise else: session.add(fin) session.commit() print('financials after', stock0.financials) session.close()
chars_dict = [] latin_arg_name = getfullargspec(Card.__init__)[INIT_ARGS][1] original_appearance_name = getfullargspec(Card.__init__)[INIT_ARGS][2] with open(filepath, newline='') as csvfile: hirareader = csv.reader(csvfile, delimiter=',') for row in hirareader: chars_dict.append({latin_arg_name: row[0], original_appearance_name: row[1]}) return chars_dict if __name__ == '__main__': hira: list = load_characters('src/sources/hiragana.csv') kata: list = load_characters('src/sources/katakana.csv') conn = engine.connect() session = Session(bind=conn) try: HiraganaCard().bulk_create(session, hira) KatakanaCard().bulk_create(session, kata) session.commit() logging.info("Import successed") except Exception: session.rollback() raise RuntimeError('CSV import failure') finally: session.close()