Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 591
benstpierre Avatar asked Dec 07 '12 21:12

benstpierre


People also ask

How do I connect to a specific schema in PostgreSQL?

How to Use Schema With PostgreSQL. To access an object of a database schema, we must specify the schema's name before the name of a given database object that we want to use. For example, to query table product within schema store, we need to use the qualified name of the table: SELECT * FROM store.

How do you run a SQL file in PostgreSQL?

Another easiest and most used way to run any SQL file in PostgreSQL is via its SQL shell. Open the SQL shell from the menu bar of Windows 10. Add your server name, database name where you want to import the file, the port number you are currently active on, PostgreSQL username, and password to start using SQL shell.


2 Answers

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 
like image 144
a_horse_with_no_name Avatar answered Oct 06 '22 12:10

a_horse_with_no_name


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

like image 39
Nux Avatar answered Oct 06 '22 12:10

Nux