Docs for --save and --dump plus made SQL optional for those, refs #273

This commit is contained in:
Simon Willison 2021-06-16 08:15:44 -07:00
commit 435096c563
3 changed files with 39 additions and 4 deletions

View file

@ -279,6 +279,35 @@ To read from standard input, use ``-`` as the filename - then use ``stdin`` or `
$ cat example.csv | sqlite-utils memory - "select * from stdin"
.. _cli_query_memory_dump_save:
--dump and --save
-----------------
You can dump out the SQL used for the temporary in-memory database, complete with all imported data, using the ``--dump`` option::
% sqlite-utils memory dogs.csv --dump
BEGIN TRANSACTION;
CREATE TABLE [dogs] (
[rowid] TEXT,
[id] TEXT,
[dog_age] TEXT,
[name] TEXT
);
INSERT INTO "dogs" VALUES('1','1','4','Cleo');
INSERT INTO "dogs" VALUES('2','2','2','Pancakes');
INSERT INTO "dogs" VALUES('3','2','3','Pancakes');
CREATE VIEW t1 AS select * from [dogs];
CREATE VIEW t AS select * from [dogs];
COMMIT;
Passing ``--save other.db`` will instead use that SQL to populate a new database file::
% sqlite-utils memory dogs.csv --save dogs.db
These features are mainly intented as debugging tools - for much more finely grained control over how data is inserted into a SQLite database file see :ref:`cli_inserting_data` and :ref:`cli_insert_csv_tsv`.
.. _cli_rows:
Returning all rows in a table

View file

@ -1143,6 +1143,10 @@ def memory(
):
"Execute SQL query against an in-memory database, optionally populated by imported data"
db = sqlite_utils.Database(memory=True)
# If --dump or --save used but no paths detected, assume SQL query is a path:
if (dump or save) and not paths:
paths = [sql]
sql = None
for i, path in enumerate(paths):
if path == "-":
csv_fp = sys.stdin

View file

@ -34,10 +34,11 @@ def test_memory_csv(tmpdir, sql_from, use_stdin):
)
def test_memory_dump():
@pytest.mark.parametrize("extra_args", ([], ["select 1"]))
def test_memory_dump(extra_args):
result = CliRunner().invoke(
cli.cli,
["memory", "-", "select 1", "--dump"],
["memory", "-"] + extra_args + ["--dump"],
input="id,name\n1,Cleo\n2,Bants",
)
assert result.exit_code == 0
@ -55,11 +56,12 @@ def test_memory_dump():
)
def test_memory_save(tmpdir):
@pytest.mark.parametrize("extra_args", ([], ["select 1"]))
def test_memory_save(tmpdir, extra_args):
save_to = str(tmpdir / "save.db")
result = CliRunner().invoke(
cli.cli,
["memory", "-", "select 1", "--save", save_to],
["memory", "-"] + extra_args + ["--save", save_to],
input="id,name\n1,Cleo\n2,Bants",
)
assert result.exit_code == 0