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

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).

Related

PostgreSql Equivalent of sqlplus -S username/password \#lock?

What will be Postgres equivalent of following:
sqlplus -S username/password \#lock.
Also what does #lock means here?
I don't know PostgreSQL, but - as of Oracle, here you are:
That command means that
you'll connect to Oracle's command line tool called SQL*Plus (executable name is sqlplus)
in silent mode (that's what -s does)
providing username and password
and execute .SQL script whose name is lock (I have no idea what it does; you'll have to open it in any text editor and have a look)
Now, how someone establishes connection to PostgreSQL and runs a .SQL script, that's something I wouldn't know, but - reading online documentation - it might be
psql -U username -d database_name -a -f lock
According to the explanations in the comments and the other answer, the equivalent in PostgreSQL should be
psql 'user=username password=password dbname=mydatabase' -f lock

Postgres PSQL Import file from certain location [duplicate]

I'm new to postgreSQL and I have a simple question:
I'm trying to create a simple script that creates a DB so I can later call it like this:
psql -f createDB.sql
I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this:
\i script1.sql
\i script2.sql
It works fine provided that createDB.sql is in the same dir.
But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this:
\i script1.sql
\i somedir\script2.sql
I get an error:
psql:createDB.sql:2: somedir: Permission denied
I'm using Postgres Plus 8.3 for windows, default postgres user.
EDIT:
Silly me, unix slashes solved the problem.
Postgres started on Linux/Unix. I suspect that reversing the slash with fix it.
\i somedir/script2.sql
If you need to fully qualify something
\i c:/somedir/script2.sql
If that doesn't fix it, my next guess would be you need to escape the backslash.
\i somedir\\script2.sql
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
Try this, I work myself to do so
\i 'somedir\\script2.sql'
i did try this and its working in windows machine to run a sql file on a specific schema.
psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql

PostgreSQL - read an SQL file into a PostgreSQL database from the commandline

I use Ruby to generate a bunch of SQL commands, and store this into a file.
I then login to my PostgreSQL database. Then I do something like:
\i /tmp/bla.sql
And this populates my database.
This all works fine as it is, no problem here.
I dislike the manual part where I have to use \i, though (because I need this to work in a cron job eventually, and I think commands like \i are only available when you are directly in the interactive psql prompt).
So my question now is:
Is it possible to use a psql command from the command line that directly will start to read in an external file?
You can directly use the psql command as shown below.
Works for me with Ubuntu and Mint. On Windows it should be quite the same...
psql -U user -d database -f filepath
Example:
psql -U postgres -d testdb -f /home/you/file.sql
For more information take a lock at the official documentation: http://www.postgresql.org/docs/current/static/app-psql.html
When you try to execute an sql file using cron, you will also need to set the environment - database name, password etc. This is a short shell script snippet that does it all
source /var/lib/pgsql/scripts/.pgenv
echo $PATH
psql << AAA
select current_date;
select sp_pg_myprocedure(current_date);
AAA
In .pgenv, you set the values such as
export PGPORT=<yourport>
export PGHOST=<yourhost>
export PGDATA=<yourdatadir>
Also have a .pgpass file so that the password is supplied.
http://www.postgresql.org/docs/current/static/libpq-pgpass.html
Replace the part where SELECT is being done with whatever you want to do, or do it as #Kuchi has shown.

pg_dump: too many command line arguments

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

How to execute PostgreSQL script-file from command line without userinput / password

During the installation of my app, I want to create a PostgreSQL-Database and some tables and functions.
For that purpose I use PSQL.EXE that ships with PostgreSQL. I have 2 scripts. The first one creates the database and a corresponding user that has rights to execute scripts on that database. I want to execute the second script as this just created user. Unfortunately I can't find a way to pass the password for that user as a command line argument. Omitting the password leads to a stop of execution and a prompt for the user to enter the password, which I would like to avoid - since this is executed during installtion of my app.
Is there any way to pass the password as argument or is there any other command line tool I could use?
To explain the environment a bit further. I use WiX 3.5 setup as a "MSI-Builder".
You can either use a pgpass file as dbenhur answerd, or you can set the environment variable PGPASSWORD before calling psql:
SET PGPASSWORD=my_very_secret_password
psql somedb someuser
All supported environment variables are documented in the manual: http://www.postgresql.org/docs/current/static/libpq-envars.html
You can't supply password via cmdline arg (and don't want to as that's poor security practice).
You can provide a .pgpass file to support automatic script authentication. Here's the docs.
Better still, if you have access to create the db role then you already have all the access you need without having to carefully log in with a password. Have the second script operate under the same user as the first but include the following line to switch user:
set role my_new_user;
Where my_new_user is the name of the role you want to run it as.
If you only divided the scripts because of the different logins then with this they can go in the same file and just switch role mid way through.
Note:
On the off chance that you are not creating the DB and new role as a super user this may be a little more complex. If this is the case you will need to create the new role with:
create role my_new_role ... ADMIN my_role;
Where my_new_role is the role you're creating and my_role is your current user. Then when you're finished simply:
revoke my_new_role from my_role;
For completion, you can also use URI (doc link)
List dbs
psql "postgresql://username:password#localhost/postgres" -l
I also crafted this command to have only names (please tell me if you know a better way):
psql "postgresql://username:password#localhost/postgres" -l | awk -F '|' '{print $1}'| sed -e '/^\s*$/ d' -e '1,3d'|sed '$d'|awk '{print $1}'
You can also use unix socket to connect:
# ss -x -a |grep postgres|awk '{print $5}'
/var/run/postgresql/.s.PGSQL.5432
Note that the parent directory of the socket is used:
# sudo -u postgres psql -d "postgresql:///postgres?host=/var/run/postgresql/" -l
You can only do this if you have this line in your pg_hba.conf:
local all postgres ident
"ident" uses unix user for authent
dump a db
Here I added a different port number
pg_dump -Fc "postgresql://username:password#localhost:9001/${db}" > "backup_${db}.pgdump"
With dumpall you need a super user or role (with CREATE ROLE ... SUPERUSER). And it must have access to all DB. By default postgres can.
but in my case I couldn't use pg_dumpall with postgres because his password was removed by devs.
So I used:
sudo -u postgres pg_dumpall -d "postgresql:///?host=/var/run/postgresql/" > all.dump
tested version
# cat /opt/postgresql/PG_VERSION
9.6
hth