# Buggy code
def show_book(book_id):
    entries = (
        db.session.query(db.Books)
        .filter(db.Books.id == book_id)
        .filter(common_filters())
        .first()
    )
    if entries:
        for index in range(0, len(entries.languages)):
            try:
                entries.languages[index].language_name = LC.parse(
                    entries.languages[index].lang_code
                ).get_language_name(get_locale())
            except UnknownLocaleError:
                entries.languages[index].language_name = _(
                    isoLanguages.get(part3=entries.languages[index].lang_code).name
                )
        tmpcc = (
            db.session.query(db.Custom_Columns)
            .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions))
            .all()
        )

        if config.config_columns_to_ignore:
            cc = []
            for col in tmpcc:
                r = re.compile(config.config_columns_to_ignore)
                if r.match(col.label):
                    cc.append(col)
        else:
            cc = tmpcc
        book_in_shelfs = []
        shelfs = (
            ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all()
        )
        for entry in shelfs:
            book_in_shelfs.append(entry.shelf)

        if not current_user.is_anonymous:
            if not config.config_read_column:
                matching_have_read_book = (
                    ub.session.query(ub.ReadBook)
                    .filter(
                        ub.and_(
                            ub.ReadBook.user_id == int(current_user.id),
                            ub.ReadBook.book_id == book_id,
                        )
                    )
                    .all()
                )
                have_read = (
                    len(matching_have_read_book) > 0
                    and matching_have_read_book[0].is_read
                )
            else:
                try:
                    matching_have_read_book = getattr(
                        entries, "custom_column_" + str(config.config_read_column)
                    )
                    have_read = (
                        len(matching_have_read_book) > 0
                        and matching_have_read_book[0].value
                    )
                except KeyError:
                    app.logger.error(
                        "Custom Column No.%d is not exisiting in calibre database"
                        % config.config_read_column
                    )
                    have_read = None

        else:
            have_read = None

        entries.tags = sort(entries.tags, key=lambda tag: tag.name)

        return render_title_template(
            "detail.html",
            entry=entries,
            cc=cc,
            is_xhr=request.is_xhr,
            title=entries.title,
            books_shelfs=book_in_shelfs,
            have_read=have_read,
            page="book",
        )
    else:
        flash(
            _("Error opening eBook. File does not exist or file is not accessible:"),
            category="error",
        )
        return redirect(url_for("index"))


# 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 show_book(book_id):
    entries = (
        db.session.query(db.Books)
        .filter(db.Books.id == book_id)
        .filter(common_filters())
        .first()
    )
    if entries:
        for index in range(0, len(entries.languages)):
            try:
                entries.languages[index].language_name = LC.parse(
                    entries.languages[index].lang_code
                ).get_language_name(get_locale())
            except UnknownLocaleError:
                entries.languages[index].language_name = _(
                    isoLanguages.get(part3=entries.languages[index].lang_code).name
                )
        tmpcc = (
            db.session.query(db.Custom_Columns)
            .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions))
            .all()
        )

        if config.config_columns_to_ignore:
            cc = []
            for col in tmpcc:
                r = re.compile(config.config_columns_to_ignore)
                if r.match(col.label):
                    cc.append(col)
        else:
            cc = tmpcc
        book_in_shelfs = []
        shelfs = (
            ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all()
        )
        for entry in shelfs:
            book_in_shelfs.append(entry.shelf)

        if not current_user.is_anonymous:
            if not config.config_read_column:
                matching_have_read_book = (
                    ub.session.query(ub.ReadBook)
                    .filter(
                        ub.and_(
                            ub.ReadBook.user_id == int(current_user.id),
                            ub.ReadBook.book_id == book_id,
                        )
                    )
                    .all()
                )
                have_read = (
                    len(matching_have_read_book) > 0
                    and matching_have_read_book[0].is_read
                )
            else:
                try:
                    matching_have_read_book = getattr(
                        entries, "custom_column_" + str(config.config_read_column)
                    )
                    have_read = (
                        len(matching_have_read_book) > 0
                        and matching_have_read_book[0].value
                    )
                except KeyError:
                    app.logger.error(
                        "Custom Column No.%d is not exisiting in calibre database"
                        % config.config_read_column
                    )
                    have_read = None

        else:
            have_read = None

        entries.tags = sort(entries.tags, key=lambda tag: tag.name)

        entries = order_authors(entries)

        kindle_list = helper.check_send_to_kindle(entries)
        reader_list = helper.check_read_formats(entries)

        return render_title_template(
            "detail.html",
            entry=entries,
            cc=cc,
            is_xhr=request.is_xhr,
            title=entries.title,
            books_shelfs=book_in_shelfs,
            have_read=have_read,
            kindle_list=kindle_list,
            reader_list=reader_list,
            page="book",
        )
    else:
        flash(
            _("Error opening eBook. File does not exist or file is not accessible:"),
            category="error",
        )
        return redirect(url_for("index"))