Debian Codegraph @

packaging/hsql/README.md

raw
1 # hsql
2
3 `hsql` is your agent's favorite SQL client. It's the headless CLI for
4 [Harlequin](https://harlequin.sh), and shares the same config and query engine,
5 with an interface optimized for agents, scripts, and automations.
6
7 > [!TIP]
8 > This README contains a small subset of the docs available at
9 > [harlequin.sh](https://harlequin.sh/docs/getting-started/hsql).
10
11 If you already use Harlequin and know about adapters and config files, jump ahead to [Running hsql](#running-hsql).
12
13 ## Installing hsql
14
15 hsql is packaged with [Harlequin](https://pypi.org/project/harlequin/), so if you already use Harlequin,
16 hsql is already installed.
17
18 Otherwise, you can install hsql directly. hsql is a Python program, and there are many ways to install and run it. We strongly recommend using [uv](https://docs.astral.sh/uv):
19
20 1. [Install uv](https://docs.astral.sh/uv/getting-started/installation/#standalone-installer). From a POSIX shell, run:
21
22 ```bash
23 curl -LsSf https://astral.sh/uv/install.sh | sh
24 ```
25
26 Or using Windows Powershell:
27
28 ```powershell
29 powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
30 ```
31
32 2. Install hsql as a tool using `uv`:
33
34 ```bash
35 uv tool install hsql
36 ```
37
38 This command will install hsql into an isolated environment and add it to your PATH so you can easily run the executable.
39
40 ## Installing Database Adapters
41
42 hsql can connect to dozens of databases using adapter plug-ins. Adapters are distributed as their own Python packages that need to be installed into the same environment as hsql and harlequin.
43
44 For a list of known adapters provided either by the Harlequin maintainers or the broader community, see the [adapters](https://harlequin.sh/docs/adapters) page.
45
46 The adapter docs also include installation instructions (installing an adapter with Harlequin also installs it for hsql). Some adapters can be installed as Harlequin extras, like `postgres`. If you used `uv` to install hsql directly, you can add adapter packages using `--with`:
47
48 ```bash
49 uv tool install hsql --with harlequin-postgres
50 ```
51
52 You can install multiple extras:
53
54 ```bash
55 uv tool install hsql --with harlequin-postgres --with harlequin-mysql
56 ```
57
58 ## Running hsql
59
60 Once hsql is installed, you run it from the command line. If you have used psql or the duckdb CLI, hsql will feel familiar, but hsql has the major advantage that is works with most databases and provides the same interface and produces the same output, regardless of the connected database. This means you (and your agent) can learn one tool, instead of several. In your shell, all hsql commands take the same form:
61
62 ```bash
63 hsql [OPTIONS] [CONN_STR]
64 ```
65
66 where `[OPTIONS]` is 0 or more pairs of the form `--[option-name] [option-value]`, and `[CONN_STR]` is 0 or more connection strings. `[OPTIONS]` are composed of both hsql options and adapter options. For a full list of options, run hsql with the `--help` option:
67
68 ```bash
69 hsql --help
70 ```
71
72 ## Using hsql with DuckDB
73
74 hsql defaults to using its DuckDB database adapter, which ships with hsql and includes the full DuckDB in-process database.
75
76 Run a query against an in-memory DuckDB session, run hsql and pass in a query with the `-c` option:
77
78 ```bash
79 $ hsql -c "select 1"
80 1
81 ---
82 1
83 (1 row)
84 ```
85
86 To query one or more DuckDB database files, pass in relative or absolute paths as connection strings (hsql will create DuckDB databases if they do not exist):
87
88 ```bash
89 $ hsql "path/to/duck.db" -tAc "select count(*) from orders"
90 42
91 ```
92
93 ## Using hsql with SQLite and Other Adapters
94
95 hsql also ships with a SQLite3 adapter. To use that adapter, you specify the `--adapter sqlite` option. Like DuckDB, you can open an in-memory SQLite database by omitting the connection string:
96
97 ```bash
98 $ hsql --adapter sqlite -c "select 'Ted' as author"
99 author
100 --------
101 Ted
102 (1 row)
103 ```
104
105 You can query one or more SQLite database files by passing in their paths as connection strings; note that the `--adapter` option has a short alias, `-a`:
106
107 ```bash
108 $ hsql -a sqlite "path/to/sqlite.db" -c "select * from users"
109 id | name
110 ----+---------
111 1 | Ted
112 2 | Patrick
113 (2 rows)
114 ```
115
116 Other adapters work the same way; for example, Postgres:
117
118 ```bash
119 $ hsql -a postgres "postgresql://example.com/postgres:5432" -c "select * from invoices"
120 ```
121
122 > [!TIP]
123 > You should use Profiles to keep credentials out of your shell
124 > history. For more information, keep reading or see
125 > [the docs](https://harlequin.sh/docs/config-file/index) on
126 > config files.
127
128 ## Configuring hsql and Using Profiles
129
130 hsql supports a number of options for setting the query limit, configuring output formats, and defining connection parameters. Options can be passed as command-line flags, or read from [config files](https://harlequin.sh/docs/config-file/index). Config files store configurations under separate profiles, so you can easily switch between databases by reading from different profiles with the `-P` option:
131
132 ```bash
133 $ hsql -P prod -c "select count(*) from orders" --csv
134 $ hsql -P dev -c "select * from users" --vertical --limit 5
135 $ hsql -P warehouse -c "..." --format parquet -o invoices.pq
136 ```
137
138 hsql reads the same config files as Harlequin, and merges them one profile at a time, nearest file first; pass `--config-path PATH` to read a single file instead, or `-P None` to skip them entirely.
139
140 ### Keeping Credentials Out of Config Files
141
142 A profile's string values can name environment variables, so a config file your team shares — and commits — holds no credentials:
143
144 ```toml
145 [profiles.prod]
146 adapter = "postgres"
147 host = "${MYHOST:-localhost}" # ${VAR:-default} supplies a default
148 password = "${MYPASSWORD}" # ${VAR} is required; hsql exits 2 if it is unset
149 ```
150
151 Write `$${` for a literal `${`, if a value really does start with one.
152
153 Values an adapter declares as secrets are masked wherever hsql prints them — `--config show`, `--info`, and error messages — as is the password inside a connection string.
154
155 ### Inspecting and Writing Config Files
156
157 Five `--config` modes work on your config files instead of running SQL, and none of them connects to a database:
158
159 - `list-profiles` — the names you can pass to `-P`, with each one's adapter, and which is the default.
160 - `show` — the merged config as TOML, with the file each value came from beside it; `--json` for JSON.
161 - `validate` — every problem in every discovered file, exiting `2` if it finds any.
162 - `schema` — a JSON Schema for a config file, covering every adapter you have installed; point your editor at it for completion and validation as you type.
163 - `init` — a profile written from the options you pass, prompting for nothing: `hsql --config init -P prod -a sqlite ./my.db --limit -1` writes `[profiles.prod]` into the nearest config file.
164
165 ```bash
166 $ hsql --config show
167 default_profile = "dev" # from /home/user/.config/harlequin/harlequin.toml
168
169 [profiles.dev] # from /home/user/proj/harlequin.toml, overriding /home/user/.config/harlequin/harlequin.toml
170 adapter = "postgres"
171 host = "${MYHOST:-localhost}"
172 password = "********"
173 limit = 100
174 ```
175
176 `list-profiles` and `validate` are result sets, so `--csv`, `-t`, `-A` and `-o` work on them as they do on a query.
177
178 ## Data Layouts and File Formats
179
180 hsql supports all of the following formats for displaying and writing data:
181 - table
182 - markdown (alias: md)
183 - vertical
184 - csv
185 - tsv
186 - json
187 - jsonl (alias: ndjson)
188 - parquet
189 - orc
190 - feather (alias: arrow)
191 - none (suppresses output)
192
193 You can select a format with the `--format <name>` or using the shorthand `--<name>`, so these are equivalent: `--format csv`, `--csv`.
194
195 Some layouts can present the results from multiple queries. Others will raise an error and exit with code 2 if multiple queries are executed.
196
197 Additionally, for any layout, pass `--stats` to print summary info as JSON to stderr:
198
199 ```bash
200 $ hsql -c "select 1" --format none --stats
201 {"status":"ok","statements":1,"rows":1,"truncated":false,"limit":500,"elapsed_ms":1,"columns":[{"name":"1","type":"#"}]}
202 ```
203
204 ## Exploring the Catalog
205
206 Before you can write a query, you have to know what is in the database. `--catalog` lists the objects one level below `--path`, and exits without running SQL:
207
208 ```bash
209 $ hsql "path/to/duck.db" --catalog
210 path | name | query_name | type | type_label
211 ------+------+------------+----------+------------
212 duck | duck | "duck" | database | db
213 (1 row)
214 ```
215
216 Every row's `path` is what lists that object's own children, so you walk down one level at a time:
217
218 ```bash
219 $ hsql "path/to/duck.db" --catalog --path duck
220 path | name | query_name | type | type_label
221 ----------------+-----------+--------------------+--------+------------
222 duck.analytics | analytics | "duck"."analytics" | schema | sch
223 duck.main | main | "duck"."main" | schema | sch
224 (2 rows)
225
226 $ hsql "path/to/duck.db" --catalog --path duck.analytics
227 path | name | query_name | type | type_label
228 -----------------------------+--------------+----------------------------+------------+------------
229 duck.analytics.customers | customers | "analytics"."customers" | BASE TABLE | t
230 duck.analytics.order_totals | order_totals | "analytics"."order_totals" | VIEW | v
231 duck.analytics.orders | orders | "analytics"."orders" | BASE TABLE | t
232 (3 rows)
233
234 $ hsql "path/to/duck.db" --catalog --path duck.analytics.orders
235 path | name | query_name | type | type_label
236 -----------------------------------+-------------+---------------+---------------+------------
237 duck.analytics.orders.customer_id | customer_id | "customer_id" | BIGINT | ##
238 duck.analytics.orders.id | id | "id" | BIGINT | ##
239 duck.analytics.orders.placed_at | placed_at | "placed_at" | TIMESTAMP | ts
240 duck.analytics.orders.total | total | "total" | DECIMAL(18,2) | #.#
241 (4 rows)
242 ```
243
244 A listing is rows, so every format and output option applies to it, exactly as they do to a query:
245
246 ```bash
247 $ hsql "path/to/duck.db" --catalog --path duck.analytics -tA --csv
248 duck.analytics.customers,customers,"""analytics"".""customers""",BASE TABLE,t
249 duck.analytics.order_totals,order_totals,"""analytics"".""order_totals""",VIEW,v
250 duck.analytics.orders,orders,"""analytics"".""orders""",BASE TABLE,t
251 ```
252
253 ### Searching the Catalog
254
255 Walking is the wrong tool for *where does `orders` live* and *which tables have a `customer_id`*. `--catalog-search TERM` searches every level of the catalog at once, for objects whose name contains TERM:
256
257 ```bash
258 $ hsql "path/to/duck.db" --catalog-search customer_id
259 path | name | query_name | type | type_label
260 -----------------------------------------+-------------+---------------+--------+------------
261 duck.analytics.order_totals.customer_id | customer_id | "customer_id" | BIGINT | ##
262 duck.analytics.orders.customer_id | customer_id | "customer_id" | BIGINT | ##
263 duck.main.staging_events.customer_id | customer_id | "customer_id" | BIGINT | ##
264 (3 rows)
265 ```
266
267 `--path` narrows the search to one subtree, and the output can be laid out like any query:
268
269 ```bash
270 $ hsql "path/to/duck.db" --catalog-search order --path duck.analytics -tA
271 duck.analytics.order_totals|order_totals|"analytics"."order_totals"|VIEW|v
272 duck.analytics.orders|orders|"analytics"."orders"|BASE TABLE|t
273 ```
274
275 Note: not all adapters support catalog search at this time.
276
277 ## Scripting with hsql
278
279 > [!WARNING]
280 > To make hsql safe and efficient for agents, by default hsql applies a 500-row
281 > limit to all queries. To remove this limit, use `--limit -1` or set
282 > `limit = -1` in your profile. If limits truncate data, hsql will print
283 > a warning on stderr; we recommend that you do NOT suppress or redirect
284 > that message so do NOT use hsql with `2>/dev/null`.
285
286 hsql can write data to files, either with the `-o` option or by piping output (hsql only writes data to stdout; other messages go to stderr):
287
288 ```bash
289 $ hsql -P prod --limit -1 -c "select * from users" --format parquet -o "users.pq"
290 $ hsql -P prod --limit -1 -c "select * from users" --csv > users.csv
291 ```
292
293 hsql can execute multiple statements in one invocation, and supports several methods for doing so:
294 - Pass `-c` multiple times
295 - Include multiple queries, separated by `;`, in one `-c` option
296 - Pass one or more .sql files with `-f`, with multiple statements in each
297 - Use `--result` to define which queries output data to stdout
298 - Use `--on-error` to either `stop` or `continue` if one or more queries produces an error.
299
300 In other words, this works:
301 ```bash
302 $ hsql -P prod --limit -1 --format md --result all --on-error stop \
303 -f ./setup.sql \
304 -c "select count(*) from raw_table" \
305 -f ./build-models.sql \
306 -c "select count(*) from modeled_table"
307 ```
308
309 hsql's exit codes are meaningful and stable:
310
311 - 0: Success
312 - 1: Query error
313 - 2: Usage/config error
314 - 3: Connection error
315 - 4: Timeout
316 - 130: Interrupted
317
318 You can also use `--stats` and `jq` together to error on a truncated query:
319 ```bash
320 hsql --limit -1 -c "select 1" --csv -o data.csv --stats 2>&1 | jq -e '.truncated | not' > /dev/null
321 ```
322
323 > [!TIP]
324 > A script or agent that runs many invocations against the same database can
325 > hold one connection open instead of reconnecting for each one.
326 > `hsql --serve dev -P dev` runs a session named `dev`, and
327 > `hsql --session dev -c "..."` (or `HSQL_SESSION=dev`) sends invocations to
328 > it, which answer in milliseconds. A session is state rather than a cache:
329 > temp tables, settings and open transactions survive from one invocation to
330 > the next. POSIX only; see
331 > [warm sessions](https://harlequin.sh/docs/hsql/sessions).
332
333 ## Running Safely
334
335 Two options bound what an invocation can do, and hsql refuses to run at all if the adapter cannot enforce them.
336
337 `--read-only` (or `-r`) connects in a mode the database itself refuses writes in:
338
339 ```bash
340 $ hsql -r "path/to/duck.db" -c "insert into orders values (1)"
341 hsql: error: Invalid Input Error: Cannot execute statement of type "INSERT" on database "duck" which is attached in read-only mode!
342 ```
343
344 `--timeout SECONDS` limits the duration of executing and fetching a query, and exits `4` when it runs out:
345
346 ```bash
347 $ hsql --timeout 0.5 -c "select count(*) from range(100000000000) t(i)"
348 hsql: error: timed out after 0.5s
349 ```
350
351 Both are also profile keys:
352
353 ```toml
354 [profiles.agent]
355 adapter = "postgres"
356 read_only = true
357 timeout = 30
358 ```
359
360 hsql refuses to open a connection with an adapter that cannot enforce `--read-only` or `--timeout`.
361
362 `hsql --info` reports `implements_read_only` and `implements_cancel` for every installed adapter.
363
364 ## Describing hsql to an Agent
365
366 `hsql --help` is written for a person; two flags answer the same questions as JSON, so an agent can find its way around an installation it has never seen. `--spec` is a machine-readable `--help`: every option on the command, plus the connection options every installed adapter declares, each with its type, choices, default and help text. `--info` describes the installation instead — versions, platform, the config files hsql found, the profile that would be active, and what each installed adapter declares it supports — so a script can check that an adapter is there, and what it can do, before depending on it.
367
368 ```bash
369 $ hsql --info -a sqlite | jq '.adapters.sqlite'
370 {
371 "distribution": "harlequin",
372 "version": "2.10.0",
373 "capabilities": {
374 "implements_cancel": true,
375 "implements_catalog_search": true,
376 "implements_read_only": true,
377 "implements_validate_sql": false
378 },
379 "error": null
380 }
381 ```
382
383 Neither connects to a database, both write JSON to stdout, and `-a NAME` narrows either one to a single adapter, which is much faster than importing them all.
384
385 ## Installing the Agent Skill
386
387 hsql ships an [Agent Skill](https://agentskills.io) that teaches an agent how to drive it: ask before you assume, keep credentials off the command line, read the catalog before writing SQL, consider a warm session, watch the 500-row limit, branch on the exit code, and hand off to `harlequin` when a human should drive. `hsql --skill` installs it, with no network and matched to the version you have:
388
389 ```bash
390 $ hsql --skill -o ~/.claude/skills/hsql/ # for you, in every project
391 $ hsql --skill -o .claude/skills/hsql/ # for this repo, committed with it
392 note: wrote 6 files to .claude/skills/hsql: SKILL.md, references/config.md, references/queries.md, references/scripting.md, references/sessions.md, references/troubleshooting.md
393 ```
394
395 With no `-o`, `hsql --skill` writes `SKILL.md` to stdout, so you can read it before you install it.
396
397 In Claude Code, the same skill is a plugin in Harlequin's repository:
398
399 ```
400 /plugin marketplace add tconbeer/harlequin
401 /plugin install hsql@harlequin
402 ```
403
404 ## Keep Reading at [harlequin.sh](https://harlequin.sh/docs/getting-started/hsql)
405
406 Visit [harlequin.sh](https://harlequin.sh/docs/getting-started/hsql) for an overview of features and full documentation.
407
408 ## Getting Help
409
410 To view all command-line options for Harlequin and all installed adapters, after installation, simply type:
411
412 ```bash
413 hsql --help
414 ```
415
416 [GitHub Discussions](https://github.com/tconbeer/harlequin/discussions) are a good place to ask questions, request features, and say hello.
417
418 [GitHub Issues](https://github.com/tconbeer/harlequin/issues) are the best place to report bugs.
419
420 ## Sponsoring Harlequin and hsql
421
422 Please consider [sponsoring Harlequin's author](https://github.com/sponsors/tconbeer), so he can continue to dedicate time to hsql.
423
424 ## Contributing
425
426 Thanks for your interest in Harlequin! Harlequin and hsql are primarily maintained by [Ted Conbeer](https://github.com/tconbeer), but he welcomes all contributions!
427
428 Please see [`CONTRIBUTING.md`](./CONTRIBUTING.md) for more information.
429
430 ## Differences from psql
431
432 `-c`, `-f`, `-t`, `-A` and `-x` mean what they mean in psql, so `hsql -tAc "select count(*) from orders"` prints a bare number, exactly as it would there. These do not:
433
434 | | psql | hsql |
435 |---|---|---|
436 | `-P` | `--pset`, an output setting | `--profile`, a config-file profile |
437 | Field separator | `-F` | `--csv`, `--format tsv`, or any other `--format` |
438 | Listing databases | `-l` | `--catalog` |
439 | Describing an object | `\d`, `\dt` | `--catalog --path`, `--catalog-search` |
440 | Stopping on the first error | `-v ON_ERROR_STOP=1` | `--on-error stop`, which is the default |
441 | One transaction | `-1` | write `begin` and `commit` in your script |
442 | `-o` | a file for query output | a file, or a directory that gets one file per result set |
443 | Connection flags | `-h`, `-p`, `-U`, built in | the adapter's, so `hsql --help -a postgres` lists them |
444 | Row limits | none | 500 rows by default; `--limit -1` removes it |
445 | Suppressing chatter | `-q` | nothing to suppress: stdout is only ever results |
446 | Exit codes | `1` its own error, `2` connection, `3` script error | `1` query error, `2` usage/config, `3` connection, `4` timeout |