Gayan
Gayan

Reputation: 1563

Run same script on under different schema - postgres

I have a script called populate.sql which contains create tables.

CREATE TABLE "EXAMPLE" (
.................
..............
);
CREATE TABLE "BlaBla" (
..........
........
);
CREATE TABLE ...

This script creates more than 20 tables. I want to run this populate.sql on top of different schemas. Let's say I want to run this script on schema1, schema2 and schema3.

Then I can write;

CREATE SCHEMA IF NOT EXISTS "schema1";
SET SCHEMA 'schema1';

on populate.sql and create those tables on one schema.

how can I create those tables on all schema within one psql command?

As far as I feel I have to do FOR LOOP on psql and create schema first and create tables on top of that scheme.

Upvotes: 0

Views: 1137

Answers (1)

ChrisB
ChrisB

Reputation: 2585

Tables will get created in the currently set search_path (if not otherwise specifically set in the create statement).

You could use a loop. In that loop you have to set the searchpath to your schema.

DO 
$$
  DECLARE schemaname text;
BEGIN
    FOR i IN 1..3 LOOP

    schemaname := 'schema' || i::text;

    execute 'CREATE SCHEMA ' || schemaname;
    execute 'SET SCHEMA ' || schemaname;    
    execute 'SET search_path TO ' || schemaname;

    -- conent of populate.sql

  END LOOP;
END
$$;

You cannot call external scripts inside this do block as mentioned by a_horse_with_no_name in the comments. Therefore this answer is only relevant if you want to extend your populate.sql file and wrap this do block around it.

Upvotes: 1

Related Questions