From 324ebc31308752004fe5f7e4941fc83706c5539c Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Tue, 11 Jan 2022 15:19:29 -0800 Subject: [PATCH] sqlite-utils rows --limit and --offset options, closes #381 --- docs/cli-reference.rst | 2 ++ docs/cli.rst | 2 ++ sqlite_utils/cli.py | 19 ++++++++++++++++++- tests/test_cli.py | 8 ++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index 76630bb..90e3f7d 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -585,6 +585,8 @@ See :ref:`cli_rows`. Options: -c, --column TEXT Columns to return + --limit INTEGER Number of rows to return - defaults to everything + --offset INTEGER SQL offset to use --nl Output newline-delimited JSON --arrays Output rows as arrays instead of objects --csv Output CSV diff --git a/docs/cli.rst b/docs/cli.rst index d2fd9e7..dda1007 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -449,6 +449,8 @@ You can use the ``-c`` option to specify a subset of columns to return:: [{"age": 4, "name": "Cleo"}, {"age": 2, "name": "Pancakes"}] +Use ``--limit N`` to only return the first ``N`` rows. Use ``--offset N`` to return rows starting from the specified offset. + .. _cli_tables: Listing tables diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 0dd7f71..9c768b0 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1723,6 +1723,16 @@ def search( ) @click.argument("dbtable") @click.option("-c", "--column", type=str, multiple=True, help="Columns to return") +@click.option( + "--limit", + type=int, + help="Number of rows to return - defaults to everything", +) +@click.option( + "--offset", + type=int, + help="SQL offset to use", +) @output_options @load_extension_option @click.pass_context @@ -1731,6 +1741,8 @@ def rows( path, dbtable, column, + limit, + offset, nl, arrays, csv, @@ -1745,10 +1757,15 @@ def rows( columns = "*" if column: columns = ", ".join("[{}]".format(c) for c in column) + sql = "select {} from [{}]".format(columns, dbtable) + if limit: + sql += " limit {}".format(limit) + if offset: + sql += " offset {}".format(offset) ctx.invoke( query, path=path, - sql="select {} from [{}]".format(columns, dbtable), + sql=sql, nl=nl, arrays=arrays, csv=csv, diff --git a/tests/test_cli.py b/tests/test_cli.py index 5f095a6..1db0849 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -851,6 +851,14 @@ def test_query_memory_does_not_create_file(tmpdir): ["--nl", "-c", "age", "-c", "name"], '{"age": 4, "name": "Cleo"}\n{"age": 2, "name": "Pancakes"}', ), + ( + ["-c", "name", "--limit", "1"], + '[{"name": "Cleo"}]', + ), + ( + ["-c", "name", "--limit", "1", "--offset", "1"], + '[{"name": "Pancakes"}]', + ), ], ) def test_rows(db_path, args, expected):