# Buggy code
def on_cleanup(manager, session):
    # Vacuum can take a long time, and is not needed frequently
    persistence = SimplePersistence("db_vacuum")
    last_vacuum = persistence.get("last_vacuum")
    if not last_vacuum or last_vacuum < datetime.now() - VACUUM_INTERVAL:
        log.info(
            "Running VACUUM on database to improve performance and decrease db size."
        )
        session.execute("VACUUM")
        persistence["last_vacuum"] = datetime.now()


# Traceback (sqlite3.OperationalError)
2016-12-30 14:44 INFO     manager                       Running database cleanup.
2016-12-30 14:44 INFO     db_vacuum                     Running VACUUM on database to improve performance and decrease db size.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 469, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: cannot VACUUM from within a transaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/usr/local/bin/flexget", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.6/site-packages/flexget/__init__.py", line 42, in main
manager.start()
File "/usr/local/lib/python3.6/site-packages/flexget/manager.py", line 327, in start
self.handle_cli()
File "/usr/local/lib/python3.6/site-packages/flexget/manager.py", line 354, in handle_cli
options.cli_command_callback(self, command_options)
File "/usr/local/lib/python3.6/site-packages/flexget/plugins/cli/database.py", line 16, in do_cli
cleanup(manager)
File "/usr/local/lib/python3.6/site-packages/flexget/plugins/cli/database.py", line 26, in cleanup
manager.db_cleanup(force=True)
File "/usr/local/lib/python3.6/site-packages/flexget/manager.py", line 896, in db_cleanup
fire_event('manager.db_cleanup', self, session)
File "/usr/local/lib/python3.6/site-packages/flexget/event.py", line 106, in fire_event
result = event(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flexget/event.py", line 23, in __call__
return self.func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flexget/plugins/generic/db_vacuum.py", line 22, in on_cleanup
session.execute('VACUUM')
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1107, in execute
bind, close_with_result=True).execute(clause, params or {})
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1393, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 185, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 469, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) cannot VACUUM from within a transaction [SQL: 'VACUUM']

# Fixed code
def on_cleanup(manager):
    # Vacuum can take a long time, and is not needed frequently
    persistence = SimplePersistence("db_vacuum")
    last_vacuum = persistence.get("last_vacuum")
    if not last_vacuum or last_vacuum < datetime.now() - VACUUM_INTERVAL:
        log.info(
            "Running VACUUM on database to improve performance and decrease db size."
        )
        with Session() as session:
            try:
                session.execute("VACUUM")
            except OperationalError as e:
                # Does not work on python 3.6, github issue #1596
                log.error("Could not execute VACUUM command: %s", e)
            else:
                persistence["last_vacuum"] = datetime.now()