We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Wrong sort for Date column
It happens if sort by date column with UI.

Screenshot shows everything. 

<img width="544" alt="2016-12-06 14 37 07" src="https://cloud.githubusercontent.com/assets/7091907/20924299/dea511b4-bbc1-11e6-8ffd-2bdda4bcbbd8.png">


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `redash/handlers/queries.py`
Content:
```
1 from itertools import chain
2 
3 import sqlparse
4 from flask import jsonify, request
5 from flask_login import login_required
6 from flask_restful import abort
7 from funcy import distinct, take
8 from sqlalchemy.orm.exc import StaleDataError
9 
10 from redash import models
11 from redash.handlers.base import (BaseResource, get_object_or_404,
12                                   org_scoped_rule, paginate, routes)
13 from redash.handlers.query_results import run_query
14 from redash.permissions import (can_modify, not_view_only, require_access,
15                                 require_admin_or_owner,
16                                 require_object_modify_permission,
17                                 require_permission, view_only)
18 from redash.utils import collect_parameters_from_request
19 
20 
21 @routes.route(org_scoped_rule('/api/queries/format'), methods=['POST'])
22 @login_required
23 def format_sql_query(org_slug=None):
24     arguments = request.get_json(force=True)
25     query = arguments.get("query", "")
26 
27     return jsonify({'query': sqlparse.format(query, reindent=True, keyword_case='upper')})
28 
29 
30 class QuerySearchResource(BaseResource):
31     @require_permission('view_query')
32     def get(self):
33         term = request.args.get('q', '')
34 
35         return [q.to_dict(with_last_modified_by=False) for q in models.Query.search(term, self.current_user.group_ids)]
36 
37 
38 class QueryRecentResource(BaseResource):
39     @require_permission('view_query')
40     def get(self):
41         queries = models.Query.recent(self.current_user.group_ids, self.current_user.id)
42         recent = [d.to_dict(with_last_modified_by=False) for d in queries]
43 
44         global_recent = []
45         if len(recent) < 10:
46             global_recent = [d.to_dict(with_last_modified_by=False) for d in models.Query.recent(self.current_user.group_ids)]
47 
48         return take(20, distinct(chain(recent, global_recent), key=lambda d: d['id']))
49 
50 
51 class QueryListResource(BaseResource):
52     @require_permission('create_query')
53     def post(self):
54         query_def = request.get_json(force=True)
55         data_source = models.DataSource.get_by_id_and_org(query_def.pop('data_source_id'), self.current_org)
56         require_access(data_source.groups, self.current_user, not_view_only)
57 
58         for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'last_modified_by']:
59             query_def.pop(field, None)
60 
61         # If we already executed this query, save the query result reference
62         if 'latest_query_data_id' in query_def:
63             query_def['latest_query_data'] = query_def.pop('latest_query_data_id')
64 
65         query_def['query_text'] = query_def.pop('query')
66         query_def['user'] = self.current_user
67         query_def['data_source'] = data_source
68         query_def['org'] = self.current_org
69         query_def['is_draft'] = True
70         query = models.Query.create(**query_def)
71         models.db.session.add(query)
72         models.db.session.commit()
73 
74         self.record_event({
75             'action': 'create',
76             'object_id': query.id,
77             'object_type': 'query'
78         })
79 
80         return query.to_dict()
81 
82     @require_permission('view_query')
83     def get(self):
84         results = models.Query.all_queries(self.current_user.group_ids)
85         page = request.args.get('page', 1, type=int)
86         page_size = request.args.get('page_size', 25, type=int)
87         return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))
88 
89 
90 class MyQueriesResource(BaseResource):
91     @require_permission('view_query')
92     def get(self):
93         drafts = request.args.get('drafts') is not None
94         results = models.Query.by_user(self.current_user, drafts)
95         page = request.args.get('page', 1, type=int)
96         page_size = request.args.get('page_size', 25, type=int)
97         return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))
98 
99 
100 class QueryResource(BaseResource):
101     @require_permission('edit_query')
102     def post(self, query_id):
103         query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)
104         query_def = request.get_json(force=True)
105 
106         require_object_modify_permission(query, self.current_user)
107 
108         for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'user', 'last_modified_by', 'org']:
109             query_def.pop(field, None)
110 
111         if 'query' in query_def:
112             query_def['query_text'] = query_def.pop('query')
113 
114         query_def['last_modified_by'] = self.current_user
115         query_def['changed_by'] = self.current_user
116         # SQLAlchemy handles the case where a concurrent transaction beats us
117         # to the update. But we still have to make sure that we're not starting
118         # out behind.
119         if 'version' in query_def and query_def['version'] != query.version:
120             abort(409)
121 
122         try:
123             self.update_model(query, query_def)
124             models.db.session.commit()
125         except StaleDataError:
126             abort(409)
127 
128         result = query.to_dict(with_visualizations=True)
129         return result
130 
131     @require_permission('view_query')
132     def get(self, query_id):
133         q = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)
134         require_access(q.groups, self.current_user, view_only)
135 
136         result = q.to_dict(with_visualizations=True)
137         result['can_edit'] = can_modify(q, self.current_user)
138         return result
139 
140     # TODO: move to resource of its own? (POST /queries/{id}/archive)
141     def delete(self, query_id):
142         query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)
143         require_admin_or_owner(query.user_id)
144         query.archive(self.current_user)
145 
146 
147 class QueryForkResource(BaseResource):
148     @require_permission('edit_query')
149     def post(self, query_id):
150         query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)
151         forked_query = query.fork(self.current_user)
152         return forked_query.to_dict(with_visualizations=True)
153 
154 
155 class QueryRefreshResource(BaseResource):
156     def post(self, query_id):
157         query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)
158         require_access(query.groups, self.current_user, not_view_only)
159 
160         parameter_values = collect_parameters_from_request(request.args)
161 
162         return run_query(query.data_source, parameter_values, query.query_text, query.id)
163
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/redash/handlers/queries.py b/redash/handlers/queries.py
--- a/redash/handlers/queries.py
+++ b/redash/handlers/queries.py
@@ -58,10 +58,6 @@
         for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'last_modified_by']:
             query_def.pop(field, None)
 
-        # If we already executed this query, save the query result reference
-        if 'latest_query_data_id' in query_def:
-            query_def['latest_query_data'] = query_def.pop('latest_query_data_id')
-
         query_def['query_text'] = query_def.pop('query')
         query_def['user'] = self.current_user
         query_def['data_source'] = data_source

{"golden_diff": "diff --git a/redash/handlers/queries.py b/redash/handlers/queries.py\n--- a/redash/handlers/queries.py\n+++ b/redash/handlers/queries.py\n@@ -58,10 +58,6 @@\n         for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'last_modified_by']:\n             query_def.pop(field, None)\n \n-        # If we already executed this query, save the query result reference\n-        if 'latest_query_data_id' in query_def:\n-            query_def['latest_query_data'] = query_def.pop('latest_query_data_id')\n-\n         query_def['query_text'] = query_def.pop('query')\n         query_def['user'] = self.current_user\n         query_def['data_source'] = data_source\n", "issue": "Wrong sort for Date column\nIt happens if sort by date column with UI.\r\n\r\nScreenshot shows everything. \r\n\r\n<img width=\"544\" alt=\"2016-12-06 14 37 07\" src=\"https://cloud.githubusercontent.com/assets/7091907/20924299/dea511b4-bbc1-11e6-8ffd-2bdda4bcbbd8.png\">\r\n\n", "before_files": [{"content": "from itertools import chain\n\nimport sqlparse\nfrom flask import jsonify, request\nfrom flask_login import login_required\nfrom flask_restful import abort\nfrom funcy import distinct, take\nfrom sqlalchemy.orm.exc import StaleDataError\n\nfrom redash import models\nfrom redash.handlers.base import (BaseResource, get_object_or_404,\n                                  org_scoped_rule, paginate, routes)\nfrom redash.handlers.query_results import run_query\nfrom redash.permissions import (can_modify, not_view_only, require_access,\n                                require_admin_or_owner,\n                                require_object_modify_permission,\n                                require_permission, view_only)\nfrom redash.utils import collect_parameters_from_request\n\n\n@routes.route(org_scoped_rule('/api/queries/format'), methods=['POST'])\n@login_required\ndef format_sql_query(org_slug=None):\n    arguments = request.get_json(force=True)\n    query = arguments.get(\"query\", \"\")\n\n    return jsonify({'query': sqlparse.format(query, reindent=True, keyword_case='upper')})\n\n\nclass QuerySearchResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        term = request.args.get('q', '')\n\n        return [q.to_dict(with_last_modified_by=False) for q in models.Query.search(term, self.current_user.group_ids)]\n\n\nclass QueryRecentResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        queries = models.Query.recent(self.current_user.group_ids, self.current_user.id)\n        recent = [d.to_dict(with_last_modified_by=False) for d in queries]\n\n        global_recent = []\n        if len(recent) < 10:\n            global_recent = [d.to_dict(with_last_modified_by=False) for d in models.Query.recent(self.current_user.group_ids)]\n\n        return take(20, distinct(chain(recent, global_recent), key=lambda d: d['id']))\n\n\nclass QueryListResource(BaseResource):\n    @require_permission('create_query')\n    def post(self):\n        query_def = request.get_json(force=True)\n        data_source = models.DataSource.get_by_id_and_org(query_def.pop('data_source_id'), self.current_org)\n        require_access(data_source.groups, self.current_user, not_view_only)\n\n        for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'last_modified_by']:\n            query_def.pop(field, None)\n\n        # If we already executed this query, save the query result reference\n        if 'latest_query_data_id' in query_def:\n            query_def['latest_query_data'] = query_def.pop('latest_query_data_id')\n\n        query_def['query_text'] = query_def.pop('query')\n        query_def['user'] = self.current_user\n        query_def['data_source'] = data_source\n        query_def['org'] = self.current_org\n        query_def['is_draft'] = True\n        query = models.Query.create(**query_def)\n        models.db.session.add(query)\n        models.db.session.commit()\n\n        self.record_event({\n            'action': 'create',\n            'object_id': query.id,\n            'object_type': 'query'\n        })\n\n        return query.to_dict()\n\n    @require_permission('view_query')\n    def get(self):\n        results = models.Query.all_queries(self.current_user.group_ids)\n        page = request.args.get('page', 1, type=int)\n        page_size = request.args.get('page_size', 25, type=int)\n        return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))\n\n\nclass MyQueriesResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        drafts = request.args.get('drafts') is not None\n        results = models.Query.by_user(self.current_user, drafts)\n        page = request.args.get('page', 1, type=int)\n        page_size = request.args.get('page_size', 25, type=int)\n        return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))\n\n\nclass QueryResource(BaseResource):\n    @require_permission('edit_query')\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        query_def = request.get_json(force=True)\n\n        require_object_modify_permission(query, self.current_user)\n\n        for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'user', 'last_modified_by', 'org']:\n            query_def.pop(field, None)\n\n        if 'query' in query_def:\n            query_def['query_text'] = query_def.pop('query')\n\n        query_def['last_modified_by'] = self.current_user\n        query_def['changed_by'] = self.current_user\n        # SQLAlchemy handles the case where a concurrent transaction beats us\n        # to the update. But we still have to make sure that we're not starting\n        # out behind.\n        if 'version' in query_def and query_def['version'] != query.version:\n            abort(409)\n\n        try:\n            self.update_model(query, query_def)\n            models.db.session.commit()\n        except StaleDataError:\n            abort(409)\n\n        result = query.to_dict(with_visualizations=True)\n        return result\n\n    @require_permission('view_query')\n    def get(self, query_id):\n        q = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_access(q.groups, self.current_user, view_only)\n\n        result = q.to_dict(with_visualizations=True)\n        result['can_edit'] = can_modify(q, self.current_user)\n        return result\n\n    # TODO: move to resource of its own? (POST /queries/{id}/archive)\n    def delete(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_admin_or_owner(query.user_id)\n        query.archive(self.current_user)\n\n\nclass QueryForkResource(BaseResource):\n    @require_permission('edit_query')\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        forked_query = query.fork(self.current_user)\n        return forked_query.to_dict(with_visualizations=True)\n\n\nclass QueryRefreshResource(BaseResource):\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_access(query.groups, self.current_user, not_view_only)\n\n        parameter_values = collect_parameters_from_request(request.args)\n\n        return run_query(query.data_source, parameter_values, query.query_text, query.id)\n", "path": "redash/handlers/queries.py"}], "after_files": [{"content": "from itertools import chain\n\nimport sqlparse\nfrom flask import jsonify, request\nfrom flask_login import login_required\nfrom flask_restful import abort\nfrom funcy import distinct, take\nfrom sqlalchemy.orm.exc import StaleDataError\n\nfrom redash import models\nfrom redash.handlers.base import (BaseResource, get_object_or_404,\n                                  org_scoped_rule, paginate, routes)\nfrom redash.handlers.query_results import run_query\nfrom redash.permissions import (can_modify, not_view_only, require_access,\n                                require_admin_or_owner,\n                                require_object_modify_permission,\n                                require_permission, view_only)\nfrom redash.utils import collect_parameters_from_request\n\n\n@routes.route(org_scoped_rule('/api/queries/format'), methods=['POST'])\n@login_required\ndef format_sql_query(org_slug=None):\n    arguments = request.get_json(force=True)\n    query = arguments.get(\"query\", \"\")\n\n    return jsonify({'query': sqlparse.format(query, reindent=True, keyword_case='upper')})\n\n\nclass QuerySearchResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        term = request.args.get('q', '')\n\n        return [q.to_dict(with_last_modified_by=False) for q in models.Query.search(term, self.current_user.group_ids)]\n\n\nclass QueryRecentResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        queries = models.Query.recent(self.current_user.group_ids, self.current_user.id)\n        recent = [d.to_dict(with_last_modified_by=False) for d in queries]\n\n        global_recent = []\n        if len(recent) < 10:\n            global_recent = [d.to_dict(with_last_modified_by=False) for d in models.Query.recent(self.current_user.group_ids)]\n\n        return take(20, distinct(chain(recent, global_recent), key=lambda d: d['id']))\n\n\nclass QueryListResource(BaseResource):\n    @require_permission('create_query')\n    def post(self):\n        query_def = request.get_json(force=True)\n        data_source = models.DataSource.get_by_id_and_org(query_def.pop('data_source_id'), self.current_org)\n        require_access(data_source.groups, self.current_user, not_view_only)\n\n        for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'last_modified_by']:\n            query_def.pop(field, None)\n\n        query_def['query_text'] = query_def.pop('query')\n        query_def['user'] = self.current_user\n        query_def['data_source'] = data_source\n        query_def['org'] = self.current_org\n        query_def['is_draft'] = True\n        query = models.Query.create(**query_def)\n        models.db.session.add(query)\n        models.db.session.commit()\n\n        self.record_event({\n            'action': 'create',\n            'object_id': query.id,\n            'object_type': 'query'\n        })\n\n        return query.to_dict()\n\n    @require_permission('view_query')\n    def get(self):\n        results = models.Query.all_queries(self.current_user.group_ids)\n        page = request.args.get('page', 1, type=int)\n        page_size = request.args.get('page_size', 25, type=int)\n        return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))\n\n\nclass MyQueriesResource(BaseResource):\n    @require_permission('view_query')\n    def get(self):\n        drafts = request.args.get('drafts') is not None\n        results = models.Query.by_user(self.current_user, drafts)\n        page = request.args.get('page', 1, type=int)\n        page_size = request.args.get('page_size', 25, type=int)\n        return paginate(results, page, page_size, lambda q: q.to_dict(with_stats=True, with_last_modified_by=False))\n\n\nclass QueryResource(BaseResource):\n    @require_permission('edit_query')\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        query_def = request.get_json(force=True)\n\n        require_object_modify_permission(query, self.current_user)\n\n        for field in ['id', 'created_at', 'api_key', 'visualizations', 'latest_query_data', 'user', 'last_modified_by', 'org']:\n            query_def.pop(field, None)\n\n        if 'query' in query_def:\n            query_def['query_text'] = query_def.pop('query')\n\n        query_def['last_modified_by'] = self.current_user\n        query_def['changed_by'] = self.current_user\n        # SQLAlchemy handles the case where a concurrent transaction beats us\n        # to the update. But we still have to make sure that we're not starting\n        # out behind.\n        if 'version' in query_def and query_def['version'] != query.version:\n            abort(409)\n\n        try:\n            self.update_model(query, query_def)\n            models.db.session.commit()\n        except StaleDataError:\n            abort(409)\n\n        result = query.to_dict(with_visualizations=True)\n        return result\n\n    @require_permission('view_query')\n    def get(self, query_id):\n        q = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_access(q.groups, self.current_user, view_only)\n\n        result = q.to_dict(with_visualizations=True)\n        result['can_edit'] = can_modify(q, self.current_user)\n        return result\n\n    # TODO: move to resource of its own? (POST /queries/{id}/archive)\n    def delete(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_admin_or_owner(query.user_id)\n        query.archive(self.current_user)\n\n\nclass QueryForkResource(BaseResource):\n    @require_permission('edit_query')\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        forked_query = query.fork(self.current_user)\n        return forked_query.to_dict(with_visualizations=True)\n\n\nclass QueryRefreshResource(BaseResource):\n    def post(self, query_id):\n        query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org)\n        require_access(query.groups, self.current_user, not_view_only)\n\n        parameter_values = collect_parameters_from_request(request.args)\n\n        return run_query(query.data_source, parameter_values, query.query_text, query.id)\n", "path": "redash/handlers/queries.py"}]}