diff --git a/docs/cli.rst b/docs/cli.rst index b4d4578..84f6a80 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -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 diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 925c428..ae0077b 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -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 diff --git a/tests/test_cli_memory.py b/tests/test_cli_memory.py index 6fbbcc5..f018837 100644 --- a/tests/test_cli_memory.py +++ b/tests/test_cli_memory.py @@ -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