# Buggy code
def migrate_Database():
    if not engine.dialect.has_table(engine.connect(), "bookmark"):
        Bookmark.__table__.create(bind=engine)
    if not engine.dialect.has_table(engine.connect(), "registration"):
        ReadBook.__table__.create(bind=engine)
        conn = engine.connect()
        conn.execute("insert into registration (domain) values('%.%')")
        session.commit()
    # Handle table exists, but no content
    cnt = session.query(Registration).count()
    if not cnt:
        conn = engine.connect()
        conn.execute("insert into registration (domain) values('%.%')")
        session.commit()
    try:
        session.query(exists().where(Settings.config_use_google_drive)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_use_google_drive` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_google_drive_folder` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_google_drive_watch_changes_response` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_columns_to_ignore)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_columns_to_ignore` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_default_role)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_default_role` SmallInteger DEFAULT 0"
        )
        session.commit()
    try:
        session.query(exists().where(BookShelf.order)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute("ALTER TABLE book_shelf_link ADD column 'order' INTEGER DEFAULT 1")
        session.commit()
    try:
        session.query(exists().where(Settings.config_rarfile_location)).scalar()
        session.commit()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_rarfile_location` String DEFAULT ''"
        )
        session.commit()
    try:
        create = False
        session.query(exists().where(User.sidebar_view)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute("ALTER TABLE user ADD column `sidebar_view` Integer DEFAULT 1")
        session.commit()
        create = True
    try:
        if create:
            conn = engine.connect()
            conn.execute("SELECT language_books FROM user")
            session.commit()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "UPDATE user SET 'sidebar_view' = (random_books* :side_random + language_books * :side_lang "
            "+ series_books * :side_series + category_books * :side_category + hot_books * "
            ":side_hot + :side_autor + :detail_random)",
            {
                "side_random": SIDEBAR_RANDOM,
                "side_lang": SIDEBAR_LANGUAGE,
                "side_series": SIDEBAR_SERIES,
                "side_category": SIDEBAR_CATEGORY,
                "side_hot": SIDEBAR_HOT,
                "side_autor": SIDEBAR_AUTHOR,
                "detail_random": DETAIL_RANDOM,
            },
        )
        session.commit()
    try:
        session.query(exists().where(User.mature_content)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute("ALTER TABLE user ADD column `mature_content` INTEGER DEFAULT 1")
    try:
        session.query(exists().where(User.theme)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute("ALTER TABLE user ADD column `theme` INTEGER DEFAULT 0")
        session.commit()
    if (
        session.query(User)
        .filter(User.role.op("&")(ROLE_ANONYMOUS) == ROLE_ANONYMOUS)
        .first()
        is None
    ):
        create_anonymous_user()
    try:
        session.query(exists().where(Settings.config_remote_login)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_remote_login` INTEGER DEFAULT 0"
        )
    try:
        session.query(exists().where(Settings.config_use_goodreads)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_use_goodreads` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_goodreads_api_key` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_goodreads_api_secret` String DEFAULT ''"
        )
    try:
        session.query(exists().where(Settings.config_mature_content_tags)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_mature_content_tags` String DEFAULT ''"
        )
    try:
        session.query(exists().where(Settings.config_default_show)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_default_show` SmallInteger DEFAULT 2047"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_logfile)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_logfile` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_certfile)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_certfile` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_keyfile` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_read_column)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_read_column` INTEGER DEFAULT 0"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_ebookconverter)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_ebookconverter` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_converterpath` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_calibre` String DEFAULT ''"
        )
        session.commit()

    # Remove login capability of user Guest
    conn = engine.connect()
    conn.execute(
        "UPDATE user SET password='' where nickname = 'Guest' and password !=''"
    )
    session.commit()


# Traceback (OperationalError)
ERROR:cps.web:Exception on /book/125 [GET]
Traceback (most recent call last):
File "/Users/jgillman/Code/calibre-web/vendor/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/jgillman/Code/calibre-web/vendor/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/jgillman/Code/calibre-web/vendor/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/jgillman/Code/calibre-web/vendor/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/jgillman/Code/calibre-web/vendor/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/jgillman/Code/calibre-web/vendor/flask_login.py", line 717, in decorated_view
return func(*args, **kwargs)
File "/Users/jgillman/Code/calibre-web/cps/web.py", line 381, in show_book
return render_template('detail.html', entry=entries,  cc=cc, title=entries.title, books_shelfs=book_in_shelfs)
File "/Users/jgillman/Code/calibre-web/vendor/flask/templating.py", line 128, in render_template
context, ctx.app)
File "/Users/jgillman/Code/calibre-web/vendor/flask/templating.py", line 110, in _render
rv = template.render(context)
File "/Users/jgillman/Code/calibre-web/vendor/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/jgillman/Code/calibre-web/vendor/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/jgillman/Code/calibre-web/cps/templates/detail.html", line 1, in top-level template code
{% extends "layout.html" %}
File "/Users/jgillman/Code/calibre-web/cps/templates/layout.html", line 136, in top-level template code
{% block body %}{% endblock %}
File "/Users/jgillman/Code/calibre-web/cps/templates/detail.html", line 66, in block "body"
{% if entry['custom_column_' ~ c.id]|length > 0 %}
File "/Users/jgillman/Code/calibre-web/vendor/jinja2/environment.py", line 387, in getitem
return getattr(obj, attr)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/attributes.py", line 316, in __get__
return self.impl.get(instance_state(instance), dict_)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/attributes.py", line 613, in get
value = self.callable_(state, passive)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/strategies.py", line 524, in _load_for_state
return self._emit_lazyload(session, state, ident_key, passive)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/strategies.py", line 585, in _emit_lazyload
result = q.all()
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/query.py", line 2241, in all
return list(self)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/query.py", line 2353, in __iter__
return self._execute_and_instances(context)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/orm/query.py", line 2368, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/base.py", line 662, in execute
params)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/base.py", line 874, in _execute_context
context)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception
exc_info
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/util/compat.py", line 196, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/base.py", line 867, in _execute_context
context)
File "/Users/jgillman/Code/calibre-web/vendor/sqlalchemy/engine/default.py", line 324, in do_execute
cursor.execute(statement, parameters)
OperationalError: (OperationalError) no such table: books_custom_column_1_link u'SELECT custom_column_1.id AS custom_column_1_id, custom_column_1.value AS custom_column_1_value \
nFROM custom_column_1, books_custom_column_1_link \nWHERE ? = books_custom_column_1_link.book AND custom_column_1.id = books_custom_column_1_link.value' (125,)
ERROR:tornado.access:500 GET /book/125 (::1) 89.60ms

# Fixed code
def migrate_Database():
    if not engine.dialect.has_table(engine.connect(), "book_read_link"):
        ReadBook.__table__.create(bind=engine)
    if not engine.dialect.has_table(engine.connect(), "bookmark"):
        Bookmark.__table__.create(bind=engine)
    if not engine.dialect.has_table(engine.connect(), "registration"):
        ReadBook.__table__.create(bind=engine)
        conn = engine.connect()
        conn.execute("insert into registration (domain) values('%.%')")
        session.commit()
    # Handle table exists, but no content
    cnt = session.query(Registration).count()
    if not cnt:
        conn = engine.connect()
        conn.execute("insert into registration (domain) values('%.%')")
        session.commit()
    try:
        session.query(exists().where(Settings.config_use_google_drive)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_use_google_drive` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_google_drive_folder` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_google_drive_watch_changes_response` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_columns_to_ignore)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_columns_to_ignore` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_default_role)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_default_role` SmallInteger DEFAULT 0"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_authors_max)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_authors_max` INTEGER DEFAULT 0"
        )
        session.commit()
    try:
        session.query(exists().where(BookShelf.order)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute("ALTER TABLE book_shelf_link ADD column 'order' INTEGER DEFAULT 1")
        session.commit()
    try:
        session.query(exists().where(Settings.config_rarfile_location)).scalar()
        session.commit()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_rarfile_location` String DEFAULT ''"
        )
        session.commit()
    try:
        create = False
        session.query(exists().where(User.sidebar_view)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute("ALTER TABLE user ADD column `sidebar_view` Integer DEFAULT 1")
        session.commit()
        create = True
    try:
        if create:
            conn = engine.connect()
            conn.execute("SELECT language_books FROM user")
            session.commit()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "UPDATE user SET 'sidebar_view' = (random_books* :side_random + language_books * :side_lang "
            "+ series_books * :side_series + category_books * :side_category + hot_books * "
            ":side_hot + :side_autor + :detail_random)",
            {
                "side_random": SIDEBAR_RANDOM,
                "side_lang": SIDEBAR_LANGUAGE,
                "side_series": SIDEBAR_SERIES,
                "side_category": SIDEBAR_CATEGORY,
                "side_hot": SIDEBAR_HOT,
                "side_autor": SIDEBAR_AUTHOR,
                "detail_random": DETAIL_RANDOM,
            },
        )
        session.commit()
    try:
        session.query(exists().where(User.mature_content)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute("ALTER TABLE user ADD column `mature_content` INTEGER DEFAULT 1")

    if (
        session.query(User)
        .filter(User.role.op("&")(ROLE_ANONYMOUS) == ROLE_ANONYMOUS)
        .first()
        is None
    ):
        create_anonymous_user()
    try:
        session.query(exists().where(Settings.config_remote_login)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_remote_login` INTEGER DEFAULT 0"
        )
    try:
        session.query(exists().where(Settings.config_use_goodreads)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_use_goodreads` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_goodreads_api_key` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_goodreads_api_secret` String DEFAULT ''"
        )
    try:
        session.query(exists().where(Settings.config_mature_content_tags)).scalar()
    except exc.OperationalError:
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_mature_content_tags` String DEFAULT ''"
        )
    try:
        session.query(exists().where(Settings.config_default_show)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_default_show` SmallInteger DEFAULT 2047"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_logfile)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_logfile` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_certfile)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_certfile` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_keyfile` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_read_column)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_read_column` INTEGER DEFAULT 0"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_ebookconverter)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_ebookconverter` INTEGER DEFAULT 0"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_converterpath` String DEFAULT ''"
        )
        conn.execute(
            "ALTER TABLE Settings ADD column `config_calibre` String DEFAULT ''"
        )
        session.commit()
    try:
        session.query(exists().where(Settings.config_theme)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute("ALTER TABLE Settings ADD column `config_theme` INTEGER DEFAULT 0")
        session.commit()
    try:
        session.query(exists().where(Settings.config_updatechannel)).scalar()
    except exc.OperationalError:  # Database is not compatible, some rows are missing
        conn = engine.connect()
        conn.execute(
            "ALTER TABLE Settings ADD column `config_updatechannel` INTEGER DEFAULT 0"
        )
        session.commit()

    # Remove login capability of user Guest
    conn = engine.connect()
    conn.execute(
        "UPDATE user SET password='' where nickname = 'Guest' and password !=''"
    )
    session.commit()