From ca2b26130f6c5fd030973ce593b02f08d19c9d84 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 16 Jun 2021 16:51:48 -0700 Subject: [PATCH] sqlite-utils dump command, closes #274 --- docs/cli.rst | 13 +++++++++++++ sqlite_utils/cli.py | 15 +++++++++++++++ tests/test_cli.py | 7 +++++++ 3 files changed, 35 insertions(+) diff --git a/docs/cli.rst b/docs/cli.rst index c953a0f..a45f3b8 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1256,6 +1256,19 @@ You can disable WAL mode using ``disable-wal``:: Both of these commands accept one or more database files as arguments. +.. _cli_dump: + +Dumping the database to SQL +=========================== + +The ``dump`` command outputs a SQL dump of the schema and full contents of the specified database file:: + + $ sqlite-utils dump mydb.db + BEGIN TRANSACTION; + CREATE TABLE ... + ... + COMMIT; + .. _cli_load_extension: Loading SQLite extensions diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 4208830..1e43a8b 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -308,6 +308,21 @@ def vacuum(path): sqlite_utils.Database(path).vacuum() +@cli.command() +@click.argument( + "path", + type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False), + required=True, +) +@load_extension_option +def dump(path, load_extension): + """Output a SQL dump of the schema and full contents of the database""" + db = sqlite_utils.Database(path) + _load_extensions(db, load_extension) + for line in db.conn.iterdump(): + click.echo(line) + + @cli.command(name="add-column") @click.argument( "path", diff --git a/tests/test_cli.py b/tests/test_cli.py index 5cb4af0..c68c7db 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -502,6 +502,13 @@ def test_vacuum(db_path): assert 0 == result.exit_code +def test_dump(db_path): + result = CliRunner().invoke(cli.cli, ["dump", db_path]) + assert result.exit_code == 0 + assert result.output.startswith("BEGIN TRANSACTION;") + assert result.output.strip().endswith("COMMIT;") + + @pytest.mark.parametrize("tables", ([], ["Gosh"], ["Gosh2"])) def test_optimize(db_path, tables): db = Database(db_path)