# Buggy code
def get_update_status():
    status = {
        "update": False,
        "success": False,
        "message": "",
        "current_commit_hash": "",
    }
    parents = []

    repository_url = "https://api.github.com/repos/janeczku/calibre-web"
    tz = datetime.timedelta(
        seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
    )

    if request.method == "GET":
        version = helper.get_current_version_info()
        if version is False:
            status["current_commit_hash"] = _("Unknown")
        else:
            status["current_commit_hash"] = version["hash"]

        try:
            r = requests.get(repository_url + "/git/refs/heads/master")
            r.raise_for_status()
            commit = r.json()
        except requests.exceptions.HTTPError as ex:
            status["message"] = _("HTTP Error") + " " + str(ex)
        except requests.exceptions.ConnectionError:
            status["message"] = _("Connection error")
        except requests.exceptions.Timeout:
            status["message"] = _("Timeout while establishing connection")
        except requests.exceptions.RequestException:
            status["message"] = _("General error")

        if status["message"] != "":
            return json.dumps(status)

        if "object" not in commit:
            status["message"] = _("Unexpected data while reading update information")
            return json.dumps(status)

        if commit["object"]["sha"] == status["current_commit_hash"]:
            status.update(
                {
                    "update": False,
                    "success": True,
                    "message": _(
                        "No update available. You already have the latest version installed"
                    ),
                }
            )
            return json.dumps(status)

        # a new update is available
        status["update"] = True

        try:
            r = requests.get(repository_url + "/git/commits/" + commit["object"]["sha"])
            r.raise_for_status()
            update_data = r.json()
        except requests.exceptions.HTTPError as ex:
            status["error"] = _("HTTP Error") + " " + str(ex)
        except requests.exceptions.ConnectionError:
            status["error"] = _("Connection error")
        except requests.exceptions.Timeout:
            status["error"] = _("Timeout while establishing connection")
        except requests.exceptions.RequestException:
            status["error"] = _("General error")

        if status["message"] != "":
            return json.dumps(status)

        if "committer" in update_data and "message" in update_data:
            status["success"] = True
            status["message"] = _(
                "A new update is available. Click on the button below to update to the latest version."
            )

            new_commit_date = (
                datetime.datetime.strptime(
                    update_data["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ"
                )
                - tz
            )
            parents.append(
                [
                    format_datetime(
                        new_commit_date, format="short", locale=get_locale()
                    ),
                    update_data["message"],
                    update_data["sha"],
                ]
            )

            # it only makes sense to analyze the parents if we know the current commit hash
            if status["current_commit_hash"] != "":
                try:
                    parent_commit = update_data["parents"][0]
                    # limit the maximum search depth
                    remaining_parents_cnt = 10
                except IndexError:
                    remaining_parents_cnt = None

                if remaining_parents_cnt is not None:
                    while True:
                        if remaining_parents_cnt == 0:
                            break

                        # check if we are more than one update behind if so, go up the tree
                        if parent_commit["sha"] != status["current_commit_hash"]:
                            try:
                                r = requests.get(parent_commit["url"])
                                r.raise_for_status()
                                parent_data = r.json()

                                parent_commit_date = (
                                    datetime.datetime.strptime(
                                        parent_data["committer"]["date"],
                                        "%Y-%m-%dT%H:%M:%SZ",
                                    )
                                    - tz
                                )
                                parent_commit_date = format_datetime(
                                    parent_commit_date,
                                    format="short",
                                    locale=get_locale(),
                                )

                                parents.append(
                                    [
                                        parent_commit_date,
                                        parent_data["message"],
                                        parent_data["sha"],
                                    ]
                                )
                                parent_commit = parent_data["parents"][0]
                                remaining_parents_cnt -= 1
                            except Exception:
                                # it isn't crucial if we can't get information about the parent
                                break
                        else:
                            # parent is our current version
                            break

        else:
            status["success"] = False
            status["message"] = _("Could not fetch update information")

    status["history"] = parents
    return json.dumps(status)


# 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 get_update_status():
    return updater_thread.get_available_updates(request.method)