pg_dump: too many command line arguments - postgresql

what is wrong with this command:
pg_dump -U postgres -W admin --disable-triggers -a -t employees -f D:\ddd.txt postgres
This is giving error of too many command-line arguments

Looks like its the -W option. There is no value to go with that option.
-W, --password force password prompt (should happen automatically)
If you want to run the command without typing is a password, use a .pgpass file.
http://www.postgresql.org/docs/9.1/static/libpq-pgpass.html

For posterity, note that pg_dump and pg_restore (and many other commands) cannot process long hyphens that word processors create. If you are cut-pasting command lines from a word processor, be sure it hasn't converted your hyphens to something else in editing. Else you will get command lines that look correct but hopelessly confuse the argument parsers in these tools.

pg_dump and pg_restore need to ask password on commandline, if you put it command, they always give "too many command-line arguments" error. You can use below for setting related environment variable in commandline or batch file:
"SET PGPASSWORD=<password>"
so that you are not asked to enter password manually in your batch file. They use given environment variable.

Instead of passing password with -W flag start with setting temporary variable for postgres:
PGPASSWORD="mypass" pg_dump -U postgres--disable-triggers -a -t employees -f D:\ddd.txt postgres

-W -> will prompt for a password
to take full DB dump
use some thing like
pg_dump -h 192.168.44.200 -p 5432 -U postgres -W -c -C -Fc -f C:\MMM\backup10_3.backup DATABASE_NAME

I got this from copy-pasting, where 1 of the dashes were different.
Was: –-host= (first dash i a "long" dash)
Corrected to --host= solved it

Another option is to add ~/.pgpass file with content like this:
hostname:port:database:username:password
read more here

Additionally, if you don't want password prompt, use connection string directly.
pg_dump 'postgresql://<username>:<password>#localhost:5432/<dbname>'
So, combination with options in original question,
pg_dump 'postgresql://postgres:<password>#localhost:5432/postgres' --table='"employees"' --format='t' --file='D:\ddd.txt' --data-only --disable-triggers
(Don't forget to use quotes when you have letter-casing issues)
reference:
https://www.postgresql.org/docs/current/app-pgdump.html
Postgres dump specific table with a capital letter

2021-11-30, pg v12, windows 10
pg_dump -U postgres -W -F t postgres > C:\myfolder\pg.tar
-U "postgres" as username,
-W to prompt for psd,
-F t means format is .tar,
> C:\myfolder\pg.tar is the destination path and filename

Related

Is it possible to extract only tables starting with a specific name in pg_dump in Postgres?

Among the hundreds of tables in the postgres DB, only the structure dump of tables starting with a specific name is found.
Example
the name of the table
abc
abc_hello
abc_hi
def
def_hello
def_hi
If you think there is
I want to dump only tables starting with abc*.
pg_dump abc.txt -Fp -t abc* -s DBName
However, it was not recognized because the amount of tables was too large.
it answered,
pg_dump: error: too many command-line arguments (first is "DBName")
but this command works fine
pg_dump abc_hello.txt -Fp -t abc_hello -s DBName
How can I pick them out?
Your main mistake is that you didn't consider that * also is a special character for the shell. If you run
pg_dump -t abc* mydatabase
the shell will replace abc* with the names of all files in the current directory that start with abc, so that your command will actually be something like
pg_dump -t abcfile1 abcfile2 abcfile3 mydatabase
which is syntactically not correct and will make pg_dump complain.
You have to protect the asterisk from being expanded by the shell with single quotes:
pg_dump -t 'abc*' mydatabase
The other error in your command line is that you forgot the -f in -f abc.txt.

Having this psql error: 'extra command-line argument ignored' [duplicate]

I am trying to automate database creation process with a shell script and one thing I've hit a road block with passing a password to psql.
Here is a bit of code from the shell script:
psql -U $DB_USER -h localhost -c"$DB_RECREATE_SQL"
How do I pass a password to psql in a non-interactive way?
Set the PGPASSWORD environment variable inside the script before calling psql
PGPASSWORD=pass1234 psql -U MyUsername myDatabaseName
For reference, see http://www.postgresql.org/docs/current/static/libpq-envars.html
Edit
Since Postgres 9.2 there is also the option to specify a connection string or URI that can contain the username and password. Syntax is:
$ psql postgresql://[user[:password]#][host][:port][,...][/dbname][?param1=value1&...]
Using that is a security risk because the password is visible in plain text when looking at the command line of a running process e.g. using ps (Linux), ProcessExplorer (Windows) or similar tools, by other users.
See also this question on Database Administrators
From the official documentation:
It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.
...
This file should contain lines of the following format:
hostname:port:database:username:password
The password field from the first line that matches the current connection parameters will be used.
in one line:
export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
with command a sql command such as "select * from schema.table"
or more readable:
export PGPASSWORD='password'
psql -h 'server name' -U 'user name' -d 'base name' \
-c 'command' (eg. "select * from schema.table")
I tend to prefer passing a URL to psql:
psql "postgresql://$DB_USER:$DB_PWD#$DB_SERVER/$DB_NAME"
This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.
This requires libpq. The documentation can be found here.
On Windows:
Assign value to PGPASSWORD: C:\>set PGPASSWORD=pass
Run command: C:\>psql -d database -U user
Ready
Or in one line,
set PGPASSWORD=pass&& psql -d database -U user
Note the lack of space before the && !
This can be done by creating a .pgpass file in the home directory of the (Linux) User.
.pgpass file format:
<databaseip>:<port>:<databasename>:<dbusername>:<password>
You can also use wild card * in place of details.
Say I wanted to run tmp.sql without prompting for a password.
With the following code you can in *.sh file
echo "192.168.1.1:*:*:postgres:postgrespwd" > $HOME/.pgpass
echo "` chmod 0600 $HOME/.pgpass `"
echo " ` psql -h 192.168.1.1 -p 5432 -U postgres postgres -f tmp.sql `
An alternative to using the PGPASSWORD environment variable is to use the conninfo string according to the documentation:
An alternative way to specify connection parameters is in a conninfo
string or a URI, which is used instead of a database name. This
mechanism give you very wide control over the connection.
$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"
postgres=>
If its not too late to add most of the options in one answer:
There are a couple of options:
set it in the pgpass file. link
set an environment variable and get it from there:
export PGPASSWORD='password'
and then run your psql to login or even run the command from
there:
psql -h clustername -U username -d testdb
On windows you will have to use "set" :
set PGPASSWORD=pass and then login to the psql bash.
Pass it via URL & env variable:
psql "postgresql://$USER_NAME:$PASSWORD#$HOST_NAME/$DB_NAME"
Just to add more clarity.
You can assign the password to the PGPASSWORD variable.
So instead of the below which will require you to type the password:
psql --host=aurora-postgres.cluster-fgshdjdf.eu-west-1.rds.amazonaws.com --port=5432 --user=my_master_user --password --dbname=postgres
We will replace the --password flag with PGPASSWORD=QghyumjB3ZtCQkdf. So it will be:
PGPASSWORD=QghyumjB3ZtCQkdf psql --host=aurora-postgres.cluster-fgshdjdf.eu-west-1.rds.amazonaws.com --port=5432 --user=my_master_user --dbname=postgres
This way you will not be required to type the password.
Added content of pg_env.sh to my .bashrc:
cat /opt/PostgreSQL/10/pg_env.sh
#!/bin/sh
# The script sets environment variables helpful for PostgreSQL
export PATH=/opt/PostgreSQL/10/bin:$PATH
export PGDATA=/opt/PostgreSQL/10/data
export PGDATABASE=postgres
export PGUSER=postgres
export PGPORT=5433
export PGLOCALEDIR=/opt/PostgreSQL/10/share/locale
export MANPATH=$MANPATH:/opt/PostgreSQL/10/share/man
with addition of (as per user4653174 suggestion)
export PGPASSWORD='password'
psql postgresql://myawsumuser:myPassword#127.0.0.1:5432/myawsumdb

Postgresql Database export to .sql file

I want to export my database as a .sql file.
Can someone help me? The solutions I have found don't work.
A detailed description please.
On Windows 7.
pg_dump defaults to plain SQL export. both data and structure.
open command prompt and
run pg_dump -U username -h localhost databasename >> sqlfile.sql
Above command is preferable as most of the times there will be an error which will be something like - ...FATAL: Peer authentication failed for user ...
In windows, first, make sure the path is added in environment variables PATH
C:\Program Files\PostgreSQL\12\bin
After a successful path adding restart cmd and type command
pg_dump -U username -p portnumber -d dbname -W -f location
this command will export both schema and data
for only schema use -s in place of -W
and for only data use -a.
replace each variable like username, portnumber, dbname and location according to your situation
everything is case sensitive, make sure you insert everything correctly,
and to import
psql -h hostname -p port_number -U username -f your_file.sql databasename
make sure your db is created or creation query is present in .sql file
Documentation: https://www.postgresql.org/docs/current/app-pgdump.html
Go to your command line and run
pg_dump -U userName -h localhost -d databaseName > ~/Desktop/cmsdump.sql

Postgres dump specific table with a capital letter

I am trying to perform a postgres dump of a specific table using -t. However, the table has a capital letter in it and I get a "No matching tables were found." I tried using quotations and double quotations around the table name but they did not work. How can I get pg to recognize the capitals? Thanks!
pg_dump -h hostname dbname -t tableName > pgdump.sql
Here is the complete command to dump your table in plain mode:
pg_dump --host localhost --port 5432 --username "postgres" --role "postgres" --format plain --file "complete_path_file" --table "schema_name.\"table_name\"" "database_name"
OR you can just do:
pg_dump -t '"tablename"' database_name > data_base.sql
Look to the last page here: Documentation
The above solutions do not work for me under Windows 7 x64. PostgreSQL 9.4.5. But this does, at last (sigh):
-t "cms.\"FooContents\""
either...
pg_dump.exe -p 8888 --username=user -t "cms.\"FooContents\"" basdb
...or...
pg_dump.exe -p 8888 --username=user -table="cms.\"FooContents\"" basdb
Inside a cmd window, I had to put three (!) double quotes around the table name if it countains upper case letters.
Example
pg_dump -t """Colors""" database > database.colors.psql
This worked for me:
pg_dump -f file.sql -U user -t 'schema.\"Table\"' database
As part of a node script I had to surround with single and double quotes, e.g.
` ... --table 'public."IndexedData"'`
The accepted solution worked in a bash console, but not as part of a node script, only the single quote approach.
Thanks to #Dirk Zabel suggestion, the following worked for me:
Windows 10 CMD
pg_dump -d "MyDatabase" -h localhost -p 5432 -U postgres --schema=public -t """TableName""" > TableName.sql
Bash
pg_dump -d "MyDatabase" -h localhost -p 5432 -U postgres --schema=public -t "\"TableName\"" > TableName.sql
Powershell
the good (shortest)
& 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe' -d db_name -t '\"CasedTableName\"'
the bad (requires --%)
& 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe' --% -d db_name -t "\"CasedTableName\""
the ugly (requires `")
& 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe' -d db_name -t "\`"CasedTableName\`""
The main point of confusion for me was the absolute necessity of having \" in there. I assumed that maybe there was a weird bug in the way powershell or psql was parsing the arguments, but it turns out it's explained in the docs:
Some native commands expect arguments that contain quote characters. Normally, PowerShell's command line parsing removes the quote character you provided. The parsed arguments are then joined into a single string with each parameter separated by a space. This string is then assigned to the Arguments property of a ProcessStartInfo object. Quotes within the string must be escaped using extra quotes or backslash (\) characters.
And of course ProcessStartInfo.Arguments Remarks tells us:
To include quotation marks in the final parsed argument, triple-escape each mark.

How can I specify the schema to run an sql file against in the Postgresql command line

I run scripts against my database like this...
psql -d myDataBase -a -f myInsertFile.sql
The only problem is I want to be able to specify in this command what schema to run the script against. I could call set search_path='my_schema_01' but the files are supposed to be portable. How can I do this?
You can create one file that contains the set schema ... statement and then include the actual file you want to run:
Create a file run_insert.sql:
set schema 'my_schema_01';
\i myInsertFile.sql
Then call this using:
psql -d myDataBase -a -f run_insert.sql
More universal way is to set search_path (should work in PostgreSQL 7.x and above):
SET search_path TO myschema;
Note that set schema myschema is an alias to above command that is not available in 8.x.
See also: http://www.postgresql.org/docs/9.3/static/ddl-schemas.html
Main Example
The example below will run myfile.sql on database mydatabase using schema myschema.
psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql
The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.
If this parameter contains an = sign or starts with a valid URI prefix
(postgresql:// or postgres://), it is treated as a conninfo string
The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.
Another Example
The example below will connect to host myhost on database mydatabase using schema myschema. The = special character must be url escaped with the escape sequence %3D.
psql postgres://myuser#myhost?options=--search_path%3Dmyschema
The PGOPTIONS environment variable may be used to achieve this in a flexible way.
In an Unix shell:
PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql
If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS only once and export it.
PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS
psql -d somebase
psql -d someotherbase
...
or invoke the top-level shell script with PGOPTIONS set from the outside
PGOPTIONS="--search_path=my_schema_01" ./my-upgrade-script.sh
In Windows CMD environment, set PGOPTIONS=value should work the same.
I'm using something like this and works very well:* :-)
(echo "set schema 'acme';" ; \
cat ~/git/soluvas-framework/schedule/src/main/resources/org/soluvas/schedule/tables_postgres.sql) \
| psql -Upostgres -hlocalhost quikdo_app_dev
Note: Linux/Mac/Bash only, though probably there's a way to do that in Windows/PowerShell too.
This works for me:
psql postgresql://myuser:password#myhost/my_db -f myInsertFile.sql
In my case, I wanted to add schema to a file dynamically so that whatever schema name user will provide from the cli, I will run sql file with that provided schema name.
For this, I replaced some text in the sql file. First I added {{schema}} in the file like this
CREATE OR REPLACE FUNCTION {{schema}}.usp_dailygaintablereportdata(
then replace {{schema}} dynamically with user provided schema name with the help of sed command
sed -i "s/{{schema}}/$pgSchemaName/" $filename
result=$(psql -U $user -h $host -p $port -d $dbName -f "$filename" 2>&1)
sed -i "s/$pgSchemaName/{{schema}}/" $filename
First replace is done, then target file is run and then again our replace is reverted back
I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.
After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:
CREATE TABLE "my_schema"."my_table" (...);
COPY "my_schema"."my_table" (...) FROM stdin;
This way using psql -f xxxxx works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).