optimize command now accepts optional tables, refs #155

This commit is contained in:
Simon Willison 2020-09-08 15:34:55 -07:00
commit 76548596a6
3 changed files with 13 additions and 5 deletions

View file

@ -703,7 +703,7 @@ You can run VACUUM to optimize your database like so::
Optimize
========
The optimize command can dramatically reduce the size of your database if you are using SQLite full-text search. It runs OPTIMIZE against all of our FTS4 and FTS5 tables, then runs VACUUM.
The optimize command can dramatically reduce the size of your database if you are using SQLite full-text search. It runs OPTIMIZE against all of your FTS4 and FTS5 tables, then runs VACUUM.
If you just want to run OPTIMIZE without the VACUUM, use the ``--no-vacuum`` flag.
@ -715,6 +715,11 @@ If you just want to run OPTIMIZE without the VACUUM, use the ``--no-vacuum`` fla
# Optimize but skip the VACUUM
$ sqlite-utils optimize --no-vacuum mydb.db
To optimize specific tables rather than every FTS table, pass those tables as extra arguments:
::
$ sqlite-utils optimize mydb.db table_1 table_2
.. _cli_wal:
WAL mode

View file

@ -218,11 +218,13 @@ def vacuum(path):
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
required=True,
)
@click.argument("tables", nargs=-1)
@click.option("--no-vacuum", help="Don't run VACUUM", default=False, is_flag=True)
def optimize(path, no_vacuum):
def optimize(path, tables, no_vacuum):
"""Optimize all FTS tables and then run VACUUM - should shrink the database file"""
db = sqlite_utils.Database(path)
tables = db.table_names(fts4=True) + db.table_names(fts5=True)
if not tables:
tables = db.table_names(fts4=True) + db.table_names(fts5=True)
with db.conn:
for table in tables:
db[table].optimize()

View file

@ -454,7 +454,8 @@ def test_vacuum(db_path):
assert 0 == result.exit_code
def test_optimize(db_path):
@pytest.mark.parametrize("tables", ([], ["Gosh"], ["Gosh2"]))
def test_optimize(db_path, tables):
db = Database(db_path)
with db.conn:
for table in ("Gosh", "Gosh2"):
@ -471,7 +472,7 @@ def test_optimize(db_path):
db["Gosh"].enable_fts(["c1", "c2", "c3"], fts_version="FTS4")
db["Gosh2"].enable_fts(["c1", "c2", "c3"], fts_version="FTS5")
size_before_optimize = os.stat(db_path).st_size
result = CliRunner().invoke(cli.cli, ["optimize", db_path])
result = CliRunner().invoke(cli.cli, ["optimize", db_path] + tables)
assert 0 == result.exit_code
size_after_optimize = os.stat(db_path).st_size
assert size_after_optimize < size_before_optimize