From 231224ba1a4de42f3d3885a0accd05dcf85570e7 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Thu, 24 Jan 2019 19:39:04 -0800 Subject: [PATCH] Added vacuum to CLI and Python API --- docs/cli.rst | 7 +++++++ docs/python-api.rst | 9 +++++++++ sqlite_utils/cli.py | 11 +++++++++++ sqlite_utils/db.py | 3 +++ tests/test_cli.py | 5 +++++ tests/test_create.py | 5 +++++ 6 files changed, 40 insertions(+) diff --git a/docs/cli.rst b/docs/cli.rst index cf46853..93b343a 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -15,3 +15,10 @@ You can list the names of tables in a database using the ``table_names`` subcomm dogs cats chickens + +Vacuum +====== + +You can run VACUUM to optimize your database like so:: + + $ sqlite-utils vacuum mydb.db diff --git a/docs/python-api.rst b/docs/python-api.rst index 194a309..b3a29a5 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -313,3 +313,12 @@ By default the index will be named ``idx_{table-name}_{columns}`` - if you want ["is_good_dog", "age"], index_name="good_dogs_by_age" ) + +Vacuum +====== + +You can optimize your database by running VACUUM against it like so: + +.. code-block:: python + + Database("my_database.py").vacuum() diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 8b252e4..1a86379 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -20,3 +20,14 @@ def table_names(path): db = sqlite_utils.Database(path) for name in db.table_names: print(name) + + +@cli.command() +@click.argument( + "path", + type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False), + required=True, +) +def vacuum(path): + """Run VACUUM against the database""" + sqlite_utils.Database(path).vacuum() diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 4127057..ae8c57c 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -98,6 +98,9 @@ class Database: ) ) + def vacuum(self): + self.conn.execute("VACUUM;") + class Table: def __init__(self, db, name): diff --git a/tests/test_cli.py b/tests/test_cli.py index 8b8c061..f24ddb1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -21,3 +21,8 @@ def db_path(tmpdir): def test_table_names(db_path): result = CliRunner().invoke(cli.cli, ["table_names", db_path]) assert "Gosh\nGosh2" == result.output.strip() + + +def test_vacuum(db_path): + result = CliRunner().invoke(cli.cli, ["vacuum", db_path]) + assert 0 == result.exit_code diff --git a/tests/test_create.py b/tests/test_create.py index 82eb7ed..af0c39f 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -176,3 +176,8 @@ def test_create_view(fresh_db): fresh_db.create_view("bar", "select bar from data") rows = fresh_db.conn.execute("select * from bar").fetchall() assert [("bar",)] == rows + + +def test_vacuum(fresh_db): + fresh_db["data"].insert({"foo": "foo", "bar": "bar"}) + fresh_db.vacuum()