Skip to content

Commit

Permalink
Handle database errors in /-/insert, refs #1866, #1873
Browse files Browse the repository at this point in the history
Also improved API explorer to show HTTP status of response, refs #1871
  • Loading branch information
simonw committed Nov 1, 2022
1 parent 9bec7c3 commit 497290b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
14 changes: 9 additions & 5 deletions datasette/templates/api_explorer.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ <h1>API Explorer</h1>
</form>

<div id="output" style="display: none">
<h2>API response</h2>
<h2>API response: HTTP <span id="response-status"></span></h2>
</h2>
<ul class="errors message-error"></ul>
<pre></pre>
</div>
Expand Down Expand Up @@ -64,20 +65,23 @@ <h2>API response</h2>
headers: {
'Content-Type': 'application/json',
}
}).then(r => r.json()).then(r => {
}).then(r => {
document.getElementById('response-status').textContent = r.status;
return r.json();
}).then(data => {
var errorList = output.querySelector('.errors');
if (r.errors) {
if (data.errors) {
errorList.style.display = 'block';
errorList.innerHTML = '';
r.errors.forEach(error => {
data.errors.forEach(error => {
var li = document.createElement('li');
li.textContent = error;
errorList.appendChild(li);
});
} else {
errorList.style.display = 'none';
}
output.querySelector('pre').innerText = JSON.stringify(r, null, 2);
output.querySelector('pre').innerText = JSON.stringify(data, null, 2);
output.style.display = 'block';
}).catch(err => {
alert("Error: " + err);
Expand Down
5 changes: 4 additions & 1 deletion datasette/views/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1206,7 +1206,10 @@ def insert_rows(conn):
else:
table.insert_all(rows, ignore=ignore, replace=replace)

rows = await db.execute_write_fn(insert_rows)
try:
rows = await db.execute_write_fn(insert_rows)
except Exception as e:
return _error([str(e)])
result = {"ok": True}
if should_return:
result["rows"] = rows
Expand Down
11 changes: 11 additions & 0 deletions tests/test_api_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,13 @@ async def test_write_rows(ds_write, return_rows):
400,
["Too many rows, maximum allowed is 100"],
),
(
"/data/docs/-/insert",
{"rows": [{"id": 1, "title": "Test"}]},
"duplicate_id",
400,
["UNIQUE constraint failed: docs.id"],
),
(
"/data/docs/-/insert",
{"rows": [{"title": "Test"}], "ignore": True, "replace": True},
Expand Down Expand Up @@ -194,6 +201,10 @@ async def test_write_row_errors(
ds_write, path, input, special_case, expected_status, expected_errors
):
token = write_token(ds_write)
if special_case == "duplicate_id":
await ds_write.get_database("data").execute_write(
"insert into docs (id) values (1)"
)
if special_case == "bad_token":
token += "bad"
kwargs = dict(
Expand Down

0 comments on commit 497290b

Please sign in to comment.