From 52418cea8018d93eba36aa1d73d43c02ced61653 Mon Sep 17 00:00:00 2001 From: Thomas Sibley Date: Tue, 7 Jul 2020 12:32:48 -0700 Subject: [PATCH 1/2] Failing test showing that DML in `sqlite-utils query` doesn't work --- tests/test_cli.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_cli.py b/tests/test_cli.py index 9e43fb9ca..c9f4658d4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1126,3 +1126,6 @@ def test_query_update(db_path, args, expected): cli.cli, [db_path, "update dogs set age = 5 where name = 'Cleo'"] + args ) assert expected == result.output.strip() + assert db.execute_returning_dicts("select * from dogs") == [ + {"id": 1, "age": 5, "name": "Cleo"}, + ] From 6a660d12a27864d6ab552e11eef9fd13bc281198 Mon Sep 17 00:00:00 2001 From: Thomas Sibley Date: Tue, 7 Jul 2020 12:33:39 -0700 Subject: [PATCH 2/2] Run `sqlite-utils query` in a transaction so that DML is committed The failing test I added in the previous commit now passes. Diff best viewed with whitespace ignored (git diff/show -w), as most of the change is indentation for the new "with" block. --- sqlite_utils/cli.py | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index fe5cd643b..ab77366c0 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -669,24 +669,25 @@ def drop_view(path, view): def query(path, sql, nl, arrays, csv, no_headers, table, fmt, json_cols): "Execute SQL query and return the results as JSON" db = sqlite_utils.Database(path) - cursor = db.conn.execute(sql) - if cursor.description is None: - # This was an update/insert - headers = ["rows_affected"] - cursor = [[cursor.rowcount]] - else: - headers = [c[0] for c in cursor.description] - if table: - print(tabulate.tabulate(list(cursor), headers=headers, tablefmt=fmt)) - elif csv: - writer = csv_std.writer(sys.stdout) - if not no_headers: - writer.writerow(headers) - for row in cursor: - writer.writerow(row) - else: - for line in output_rows(cursor, headers, nl, arrays, json_cols): - click.echo(line) + with db.conn: + cursor = db.conn.execute(sql) + if cursor.description is None: + # This was an update/insert + headers = ["rows_affected"] + cursor = [[cursor.rowcount]] + else: + headers = [c[0] for c in cursor.description] + if table: + print(tabulate.tabulate(list(cursor), headers=headers, tablefmt=fmt)) + elif csv: + writer = csv_std.writer(sys.stdout) + if not no_headers: + writer.writerow(headers) + for row in cursor: + writer.writerow(row) + else: + for line in output_rows(cursor, headers, nl, arrays, json_cols): + click.echo(line) @cli.command()