Initial dclient query command, refs #1

This commit is contained in:
Simon Willison 2022-11-21 18:16:28 -08:00
commit 1ecb6a02e8
5 changed files with 94 additions and 27 deletions

View file

@ -1,4 +1,6 @@
import click
import httpx
import json
@click.group()
@ -7,15 +9,25 @@ def cli():
"A client CLI utility for Datasette instances"
@cli.command(name="command")
@click.argument(
"example"
)
@click.option(
"-o",
"--option",
help="An example option",
)
def first_command(example, option):
"Command description goes here"
click.echo("Here is some output")
@cli.command()
@click.argument("url")
@click.argument("sql")
def query(url, sql):
"""
Run a SQL query against a Datasette database URL
Returns a JSON array of objects
"""
if not url.endswith(".json"):
url += ".json"
response = httpx.get(url, params={"sql": sql, "_shape": "objects"})
if response.status_code != 200 or not response.json()["ok"]:
data = response.json()
bits = []
if data.get("title"):
bits.append(data["title"])
if data.get("error"):
bits.append(data["error"])
raise click.ClickException(": ".join(bits))
else:
click.echo(json.dumps(response.json()["rows"], indent=2))