Skip to content

Commit

Permalink
sqlite-utils rows --order option, closes #469
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Aug 27, 2022
1 parent f4fb78f commit 7a9a636
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/cli-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,7 @@ See :ref:`cli_rows`.
Options:
-c, --column TEXT Columns to return
--where TEXT Optional where clause
-o, --order TEXT Order by ('column' or 'column desc')
-p, --param <TEXT TEXT>... Named :parameters for where clause
--limit INTEGER Number of rows to return - defaults to everything
--offset INTEGER SQL offset to use
Expand Down
2 changes: 2 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,8 @@ Or pass named parameters using ``--where`` in combination with ``-p``::
$ sqlite-utils rows dogs.db dogs -c name --where 'name = :name' -p name Cleo
[{"name": "Cleo"}]

You can define a sort order using ``--order column`` or ``--order 'column desc'``.

Use ``--limit N`` to only return the first ``N`` rows. Use ``--offset N`` to return rows starting from the specified offset.

.. note::
Expand Down
4 changes: 4 additions & 0 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1985,6 +1985,7 @@ def search(
@click.argument("dbtable")
@click.option("-c", "--column", type=str, multiple=True, help="Columns to return")
@click.option("--where", help="Optional where clause")
@click.option("-o", "--order", type=str, help="Order by ('column' or 'column desc')")
@click.option(
"-p",
"--param",
Expand All @@ -2011,6 +2012,7 @@ def rows(
dbtable,
column,
where,
order,
param,
limit,
offset,
Expand All @@ -2037,6 +2039,8 @@ def rows(
sql = "select {} from [{}]".format(columns, dbtable)
if where:
sql += " where " + where
if order:
sql += " order by " + order
if limit:
sql += " limit {}".format(limit)
if offset:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,15 @@ def test_query_memory_does_not_create_file(tmpdir):
["-c", "name", "--where", "id = :id", "--param", "id", "1"],
'[{"name": "Cleo"}]',
),
# --order
(
["-c", "id", "--order", "id desc", "--limit", "1"],
'[{"id": 2}]',
),
(
["-c", "id", "--order", "id", "--limit", "1"],
'[{"id": 1}]',
),
],
)
def test_rows(db_path, args, expected):
Expand Down

0 comments on commit 7a9a636

Please sign in to comment.