Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a trigger in PostgreSQL to create a new schema when a new row is inserted in a table?

I have a table that holds clients, I have just one client per country, and for each row in this table I must create a new schema and replicate some tables. Like this:

Clients table's columns: 

client      country
----------  -----------
john doe    US
jane doe    UK

Schemas:

clients_US
clients_UK

I need to create a trigger to create those schemas automatically everytime a new client is added to the clients table, using the country column data as part of the schema's name.

In a perfect world this would work, but it clearly doesn't:

CREATE OR REPLACE FUNCTION gcpmanager.create_sle_schema() 
RETURNS trigger LANGUAGE plpgsql
AS
    'begin 
    CREATE SCHEMA "clients_" + new.country
    AUTHORIZATION postgres;
        return new;
    end;';
like image 672
Henrique Miranda Avatar asked Jun 16 '11 13:06

Henrique Miranda


People also ask

What is the use of PostgreSQL triggers?

PostgreSQL Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs. A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies.

How do I write a trigger update in PostgreSQL?

The following is the simple syntax for generating a trigger: >> CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event-name ON table_name [ ----Trigger Logic ]; Here is the explanation of the above general query. To understand the trigger concept briefly, launch the PostgreSQL shell from the applications.

What is instead of trigger in PostgreSQL?

INSTEAD OF triggers do not support WHEN conditions. Typically, row-level BEFORE triggers are used for checking or modifying the data that will be inserted or updated. For example, a BEFORE trigger might be used to insert the current time into a timestamp column, or to check that two elements of the row are consistent.

Is it possible to create the following trigger before or after update trigger for each row?

A new column value can be assigned in a BEFORE row trigger, but not in an AFTER row trigger (because the triggering statement takes effect before an AFTER row trigger is fired). If a BEFORE row trigger changes the value of new .


1 Answers

You will need to use dynamic SQL

CREATE OR REPLACE FUNCTION gcpmanager.create_sle_schema() 
RETURNS trigger LANGUAGE plpgsql
AS
$$
begin 
  execute 'CREATE SCHEMA clients_'||new.country||' AUTHORIZATION postgres';
  return new;
end;
$$

Btw: the string concatenation operator in PostgreSQL is || not + (that is for numbers)

like image 62
a_horse_with_no_name Avatar answered Sep 23 '22 06:09

a_horse_with_no_name