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;';
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.
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.
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.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With