Skip to content

feat: add an executable for expanding slash commands to SQL #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

murrayju
Copy link
Owner

@murrayju murrayju commented May 8, 2025

I wanted an executable that takes a psql slash command (like \dt), and expands it into the corresponding SQL without executing it (we will use the SQL for execution elsewhere). This can be accomplished via psql itself like so:

psql postgres://user:pw@localhost:5432/test -q --set=ECHO_HIDDEN=noexec -c '\d'

The problem is, this requires a valid connection string, and must establish a successful connection before outputting the SQL.

What I've done here is take the entrypoint code for psql, and strip it down to the bare minimum that we need here. It creates a fake/empty db connection object, and avoids actually connecting it. I've also simplified the parameters, to just take a single argument (the slash command). Invoking this looks like:

slash2sql '\dt'

To test

brew install icu4c
export PKG_CONFIG_PATH="/opt/homebrew/Cellar/icu4c@77/77.1/lib/pkgconfig:$PKG_CONFIG_PATH" && ./configure
make
DYLD_LIBRARY_PATH=./src/interfaces/libpq ./src/bin/psql/slash2sql '\d'

Can also install, to avoid the lib path issue

sudo make install
/usr/local/pgsql/bin/slash2sql '\d'

Example output

/usr/local/pgsql/bin/slash2sql '\d'
/******** QUERY *********/
SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 't' THEN 'TOAST table' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'partitioned table' WHEN 'I' THEN 'partitioned index' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','m','S','f','')
      AND n.nspname <> 'pg_catalog'
      AND n.nspname !~ '^pg_toast'
      AND n.nspname <> 'information_schema'
  AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
/************************/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant