postgresqldatabase-connectionconnection-string

How to specify the libpq correct connection string URL for Unix domain socket connection in the shell?


https://www.postgresql.org/docs/current/libpq-example.html
compile the 1st example source code.

gcc test.c -L/usr/local/pgsql15/lib -I/usr/local/pgsql15/include -lpq

Cannot figure out the connection string. All the following failed.

./a.out postgresql:///test15?host=/tmp&port=5415
./a.out postgresql://test15?host=/tmp:5415
./a.out postgresql://test15?host=/tmp&port='5415'
./a.out postgresql://test15?host=/tmp:'5415'
./a.out postgresql://test15?host=/tmp&port=/tmp
./a.out postgresql:///tmp:5415/test15?

The error is almost similar:

connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory
        Is the server running locally and accepting connections on that socket?

[1]+  Exit 1                  ./a.out postgresql:///test15?host=/tmp

cat /usr/local/pgsql15/data_42091266/postgresql.conf | rg unix return

unix_socket_directories = '/tmp'        # comma-separated list of directories
#unix_socket_group = ''                 # (change requires restart)
unix_socket_permissions = 0777          # begin with 0 to use octal notation

Solution

  • Thanks to jjanes
    The following two way works.

    ./a.out postgresql:///test15?host=/tmp\&port=5415
    
    ./a.out "postgresql:///test15?host=/tmp&port=5415"
    

    https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.htmlhttps://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html

    Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to preserve the literal meaning of the special characters in the next paragraph, prevent reserved words from being recognized as such, and prevent parameter expansion and command substitution within here-document processing (see Here-Document).

    The application shall quote the following characters if they are to represent themselves:

    | & ; < > ( ) $ ` \ " '