Jhonson Doe
Jhonson Doe

Reputation: 91

How to connect and execute a SQL file non interactively using psql?

I am trying to run the following command using psql but the --file argument is ignored event tough I manage to connect to the database.

psql "postgresql://postgres:admin12345@localhost:5432/Phoenix" -f "tables/book.sql"

The output on the terminal is as the screenshot shows.

Command output

What am I missing here? Thanks in advance.

Upvotes: 2

Views: 1713

Answers (1)

Jhonson Doe
Jhonson Doe

Reputation: 91

After googling and wasting hours on testing different SO answers, this worked for me:

psql -f "tables/book.sql" "postgresql://postgres:admin12345@localhost:5432/Phoenix"

It looks like the psql command requires that the command-line arguments appear before the connection string. That's a bit weird but it worked for me.

Also the quotes are optional. This also works:

psql -f tables/book.sql postgresql://postgres:admin12345@localhost:5432/Phoenix

I tried changing code page as indicated on the section "Notes for Windows Users" in the psql doc psql docmentation. The result is the warning does not show anymore but the command line args are still ignored if the connection string precedes them like as shown in the following logs:

C:\Users\Zack
λ cmd.exe /c chcp 1252

Active code page: 1252

C:\Users\Zack
λ psql postgresql://postgres:admin12345@localhost:5432/Phoenix -f "tables/book.sql"

psql: warning: extra command-line argument "tables/book.sql" ignored
psql (13.2)
Type "help" for help.

Phoenix=#

Theo only fix that works for me now is making the other args preced the connection string.

If someone knows more about why command-line args should precede the connection string, please provide more details.

Upvotes: 3

Related Questions