Skip to content
berendPublic

About

SQL over named PostgreSQL and MySQL profiles, shaped for coding agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dq

SQL over named Postgres and MySQL profiles, shaped for a coding agent to call.

$ dq dwh_analytics --query "select id, name, spend from accounts limit 2"
[
  {"id":1, "name":"Acme", "spend":"1234.5600000001"},
  {"id":2, "name":"Globex", "spend":"0.0000000000"}
]

Pipe JSON output through jq when only one value is needed:

$ dq dwh_analytics --query "select id, name, spend from accounts limit 2" | jq -r '.[] | select(.name == "Acme") | .spend'
1234.5600000001

Returning only the value the agent needs keeps unnecessary result data out of its context and saves tokens. The metadata line remains visible on stderr.

dq 0.2 supports PostgreSQL 16 and MySQL 8. It is a single static binary with no cgo. Profiles contain complete database connection strings, including passwords, in a local TOML file.

Security model

The database user's grants are the security boundary. dq does not parse statements to decide whether they are safe, does not start read-only transactions, and does not otherwise promise read-only access.

If a person or agent must only be able to read, configure the profile with a database user that only has the necessary read grants. If the configured user can write, dq can write.

The profile file contains plaintext credentials. Keep it private, exclude it from source control and backups that are not allowed to contain secrets, and use separate database users with the minimum necessary grants.

Install

go install github.com/berend/dq@latest

This is the canonical installation command for current Go versions. Ensure Go's binary directory (usually ~/go/bin, or the value of GOBIN) is on your PATH. Then run dq config to see the configuration path and example TOML, create that file manually, and verify a profile with dq test <profile>.

Coding-agent setup

To help coding harnesses discover and use dq, add this text to the relevant project or user-level AGENTS.md:

Use the installed `dq` CLI for database access through named profiles. Start
with `dq ls` to discover profiles and `dq help` for the command contract. Use
`dq <profile> --tables`, `--describe`, and `--search` for schema discovery, and
`dq <profile> --query "..."` for queries. Use `--exec` only when a
data-changing statement is intended. Pipe JSON stdout through `jq` to select
only the fields or rows needed; smaller results save context tokens. Always
inspect stderr metadata; `"truncated": true` means the result is incomplete.
Do not print or read the profile config because it contains plaintext
credentials. Database grants are the security boundary.

Using it

dq <profile> --query "select ..."     # or -q
dq <profile> --exec "update ..."      # or -e; reports affected_rows
dq <profile> --file query.sql         # or -f
dq <profile> < query.sql              # or on stdin

dq <profile> --tables [--schema s]    # name, kind, row_estimate
dq <profile> --describe <table>       # columns, types, nullability, PK, FK, indexes
dq <profile> --search <pattern>       # match table and column names

dq ls                                 # profiles as JSON; DSNs are not shown
dq config                             # config path and example TOML as JSON
dq test <name>                        # connect and report server version
dq grants <name>                      # list grants visible for the database user

MySQL introspection defaults to the database selected by the profile DSN. MySQL users can have access to other databases on the same server, but those are only inspected when --schema other_database is supplied explicitly.

Flags: --format json|csv|tsv|table, --max-rows n, --timeout 90s, --null <s>, --schema s, --quiet.

The output contract

stdout is a JSON array of objects, one per row, with keys in column order. Nothing else is written there, so | jq works and an empty result is []. A statement with no returned rows also produces [].

Use --exec for statements that do not return a result set. It returns one row with affected_rows, for example [{"affected_rows":3}]. --query is the capped result-streaming path; do not use it for data-changing statements with a large RETURNING result because early truncation cancels the PostgreSQL connection. Every invocation accepts exactly one non-empty SQL statement.

stderr is one JSON metadata line on successful query and introspection commands:

{"profile":"dwh_analytics","dialect":"postgres","rows":200,"truncated":true,
 "max_rows":200,"elapsed_ms":41,"hint":"more rows exist; add LIMIT/WHERE or raise --max-rows"}

Read that line. "truncated": true means more rows existed than were emitted.

On failure, stdout is empty and stderr carries an error object:

{"error":{"code":"sql_error","sqlstate":"42703","message":"column \"nam\" does not exist",
          "position":8,"server_hint":"Perhaps you meant to reference the column \"accounts.name\"."}}

Exit codes are deliberately coarse:

code meaning
0 ok
1 usage, config or profile problem
2 connection, TLS or authentication failure
3 statement failed on the server

Configuration

Profiles live in ~/.config/dq/profiles.toml; override the path with DQ_CONFIG. dq config prints the resolved path and a complete example as JSON, and the no_config error directs callers to that command.

[defaults]
max_rows = 200
statement_timeout = "30s"
max_bytes = 1048576
format = "json"

[profiles.dwh_analytics]
driver = "postgres"
dsn = "postgres://reader:plain-text-password@dwh.internal:5432/dwh?sslmode=require&search_path=analytics"

[profiles.analytics_mysql]
driver = "mysql"
dsn = "reader:plain-text-password@tcp(mysql.internal:3306)/analytics?tls=preferred&charset=utf8mb4"

Postgres DSNs use pgx/libpq connection-string syntax, either a URL as above or keyword/value form. MySQL DSNs use go-sql-driver/mysql syntax. TLS, database, schema/search path, and driver-specific options belong in the DSN. dq sets the session statement timeout and timezone to UTC for consistent query behavior and timestamp output.

Create the file manually and restrict it to its owner:

chmod 600 ~/.config/dq/profiles.toml

dq rejects a profile file with any group or other permission bits. Profile addition, editing and removal are deliberately manual in v0.2.

Grant reporting

dq grants <profile> reports the grants visible for the connected database user. Its columns are:

column meaning
user connected database identity
granted_via account to which the object grant was assigned, or a directly assigned role
object_type global, database, schema, table, column, sequence or role
object granted object
privilege database-native privilege name
grantable whether the user can grant the privilege onward

This is a literal list of grants assigned directly to the login plus direct role memberships. It is informational output, not an effective-permission audit. Inherited role privileges, PUBLIC, ownership, superuser status, default privileges and row-level policies are deliberately not expanded. Normal row and byte caps apply, with truncation reported on stderr.

Type mapping

Values travel from both drivers as raw server text and are decoded once:

SQL JSON note
smallint … bigint number server digits pass through unchanged
real, double number NaN/Infinity become strings
numeric, decimal string preserves exact high-precision values
boolean true / false Postgres; MySQL TINYINT(1) stays numeric
text, uuid, inet, enum, interval string
bytea, blob string base64
json, jsonb embedded JSON not double-encoded
date, time, timestamp(tz) string RFC 3339 where possible
Postgres arrays JSON array nested values and NULL elements supported
NULL null distinct from an empty string

Both sessions are pinned to UTC. Postgres timestamptz carries an offset; MySQL DATETIME and Postgres timestamp do not, and dq does not invent one.

For CSV and TSV, NULL is an empty field by default and is therefore indistinguishable from an empty string. Pass --null '\N' when that matters. Table output uses NULL by default.

Duplicate result-column names are renamed to id, id_2, and so on. Renames are included in renamed_columns on stderr so object-shaped JSON never silently loses a value.

Row and byte caps

max_rows is enforced by reading max_rows + 1 rows. The SQL text is never rewritten. The extra row makes truncated accurate. MySQL also receives a session sql_select_limit; Postgres severs the connection after early exit so the driver does not drain the remaining result.

max_bytes is an approximate output budget. At least one row is retained so the result shape stays visible. These caps limit returned output; they do not make an expensive query cheap. statement_timeout is the cost backstop.

Each invocation uses one connection and one independently autocommitted statement. Transactions cannot span invocations. dq owns the session timezone (UTC), statement timeout, result caps, and MySQL max_execution_time setting; failure to establish those promised session settings is an error.

Development

make check         # vet, unit tests, gofmt
make integration   # Postgres 16 and MySQL 8 in throwaway Docker containers
make cross         # darwin/linux on amd64/arm64 with CGO_ENABLED=0

Current limitations

  • Plaintext profile storage is intentional for the first version.
  • PostgreSQL and MySQL use their native, different DSN syntaxes.
  • TLS modes and certificate verification still need real-server coverage.
  • MariaDB is not supported in v0.2.
  • Exactly one non-empty statement is accepted per invocation.

About

SQL over named PostgreSQL and MySQL profiles, shaped for coding agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages