mirror of
https://github.com/simonw/dclient.git
synced 2026-08-06 01:14:28 +02:00
Initial dclient query command, refs #1
This commit is contained in:
parent
56c4672f37
commit
1ecb6a02e8
5 changed files with 94 additions and 27 deletions
|
|
@ -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))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue