ForbesLindesay / atdatabases

TypeScript clients for databases that prevent SQL Injection
https://www.atdatabases.org
MIT License
608 stars 47 forks source link

Using @databases/pg-schema-cli with unix socket connection #184

Open MartinRamm opened 3 years ago

MartinRamm commented 3 years ago

I tried using the package pg-schema-cli with a db connection via unix socket. For this, I configured a config.json file (implementing this interface) and the --config option with a path to said config.json file, but the command outputs that a connection string is required.

As far as I can tell, connection strings don't support unix socket paths yet - leaving me no real options here.

My current workaround is to temporarily bind the unix socket to a TCP port via socat using this code:

#!/usr/bin/env bash

echo "Binding db unix socket to localhost"
socat 'TCP-LISTEN:1337,reuseaddr,fork' 'UNIX-CONNECT:/var/run/postgresql/.s.PGSQL.5432' &
SOCAT_PID="$!"

npx '@databases/pg-schema-cli'                                                                                                                              \
  --database "postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@localhost:1337/$POSTGRES_DB"  \
  --directory "$TS_FOLDER";

echo "GENERATED TS TYPES IN $TS_FOLDER";

echo "Unbinding db unix socket from localhost (killing pid $SOCAT_PID)"
kill -9 "$SOCAT_PID"

However, I think a case could be made to allow this behavior without the workaround. I could imagine the easiest fix that works for all packages could be to extend the schema of the connection string to allow unix sockets as hosts. If the maintenance team agrees with me, I would be willing to provide an implementation (scoped to postgres).

ForbesLindesay commented 2 years ago

I think this should be achievable by using a "Keyword/Value Connection String" (see https://www.postgresql.org/docs/10/libpq-connect.html)

This would look something like:

npx '@databases/pg-schema-cli' \
  --database "host='/var/run/postgresql/' user='$POSTGRES_USER' password='$POSTGRES_PASSWORD' dbname='$POSTGRES_DB'"  \
  --directory "$TS_FOLDER";

It's also possible to provide most of these parameters via environment variables (PGHOST, PGUSER etc.) but currently the pg-schema-cli util does require a connection string of some sort.