-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sql
More file actions
54 lines (47 loc) · 1.74 KB
/
setup.sql
File metadata and controls
54 lines (47 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
-- Crée une table simple pour la gestion des tâches.
-- Vous pouvez l'adapter à votre propre structure.
CREATE TABLE IF NOT EXISTS taches (
id SERIAL PRIMARY KEY,
titre VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
updated_by VARCHAR(100)
);
-- Crée la fonction qui sera appelée par le trigger.
-- Cette fonction prépare une charge utile (payload) JSON et l'envoie
-- sur le canal 'taches_changes' que le workflow n8n écoute.
CREATE OR REPLACE FUNCTION notify_taches_changes()
RETURNS TRIGGER AS $$
DECLARE
payload JSON;
operation_type TEXT;
old_data JSON;
new_data JSON;
BEGIN
-- Détermine le type d'opération (INSERT, UPDATE, DELETE)
operation_type := TG_OP;
-- Construit les objets JSON pour les anciennes et nouvelles données
old_data := row_to_json(OLD);
new_data := row_to_json(NEW);
-- Construit la charge utile finale
payload := json_build_object(
'operation', operation_type,
'timestamp', NOW(),
'schema', TG_TABLE_SCHEMA,
'table', TG_TABLE_NAME,
'old', old_data,
'new', new_data
);
-- Envoie la notification avec la charge utile sur le canal spécifié
PERFORM pg_notify('taches_changes', payload::text);
-- Retourne la nouvelle ligne pour les opérations INSERT/UPDATE
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Supprime le trigger existant s'il y en a un pour éviter les doublons
DROP TRIGGER IF EXISTS trg_taches_changes ON taches;
-- Attache le trigger à la table 'taches'.
-- Il se déclenchera après chaque INSERT, UPDATE ou DELETE.
CREATE TRIGGER trg_taches_changes
AFTER INSERT OR UPDATE OR DELETE ON taches
FOR EACH ROW EXECUTE FUNCTION notify_taches_changes();