Marcin Roguski
Marcin Roguski

Reputation: 779

How to run postgres sql script from another script?

I have a bunch of SQL scripts that create tables in the database. Each table is located in a separate file so that editing them is much easier.

I wanted to prepare a single SQL script that will create the full schema, create tables, insert test data and generate sequences for the tables.

I was able to do such thing for oracle database but I am having problems with postgres. The thing is - I do not know how to run the table creating script from another script.

In oracle I do it using the following syntax:

@@'path of the script related to the path of the currently running sql file'

And everything works like a charm.

In postgres I was trying to search for something alike and found this:

\ir 'relative path to the file'

Unfortunately when I run my main script I get the message:

No such file or directory.

The example call is here:

\ir './tables/map_user_groups.sql'

I use Postgres 9.3. I tried to run the script using psql:

psql -U postgres -h localhost -d postgres < "path to my main sql file"

The file executes fine except for the calling of those other scripts.

Does anybody know how to solve the problem ?

If something in the question is unclear - just let me know :)

Upvotes: 38

Views: 29159

Answers (1)

Evandro Coan
Evandro Coan

Reputation: 9428

Based on the answer It is possible to reference another SQL file from SQL script, on PostgreSQL, you can include another SQL's files just using the \i syntax. I just tested and is working good on PostgreSQL 9.6:

\i other_script.sql
SELECT * FROM table_1;
SELECT * FROM table_2;

By the @wildplasser comment:

psql -U postgres -h localhost -d postgres < "path to my main sql file"

From psql's perspective the main_sql file is just stdin, and stdin has no "filename". Use -f filename to submit a file with a name:

psql -U postgres -h localhost -d postgres -f filename.sql

How to run postgres sql script from another script?

Seems the same question as: How to import external sql scripts from a sql script in PostgreSQL?

Upvotes: 33

Related Questions