x
1
DECLARE
2
organisme text;
3
table_canalisation text;
4
table_ouvrage text;
5
table_appareil text;
6
BEGIN
7
8
-- Calcul de l'identifiant si besoin
9
IF NEW.idrepar IS NULL OR trim(NEW.idrepar) = '' OR trim(NEW.idrepar) = 'INCONNU' THEN
10
NEW.idrepar := raepa.generate_oid(TG_TABLE_NAME::text)::character varying;
11
END IF;
12
13
-- Calcul de la géométrie à partir de X et Y
14
IF ( TG_OP = 'UPDATE' AND NEW.x IS NOT NULL AND NEW.y IS NOT NULL AND ( NEW.x != OLD.x OR NEW.y != OLD.y ) )
15
OR ( TG_OP = 'INSERT' AND NEW.x IS NOT NULL AND NEW.y IS NOT NULL ) THEN
16
NEW.geom := ST_SetSRID(ST_Makepoint(NEW.x, NEW.y), 2154);
17
RAISE NOTICE 'appareil % - X ou Y changé -> changement geom vers POINT(% %)', NEW.idrepar, NEW.x, NEW.y;
18
END IF;
19
20
IF ( TG_OP = 'UPDATE' AND NOT ST_Equals(NEW.geom, OLD.geom) ) OR TG_OP = 'INSERT' THEN
21
22
-- Calcul des X et Y si besoin
23
NEW.x := ST_X(NEW.geom)::numeric(10,3);
24
NEW.y := ST_Y(NEW.geom)::numeric(10,3);
25
END IF;
26
27
28
-- idsuprepar
29
table_canalisation = 'raepa.raepa_canalass_l';
30
IF TG_TABLE_NAME = 'raepa_reparaep_p' THEN
31
table_canalisation = 'raepa.raepa_canalaep_l';
32
END IF;
33
34
table_ouvrage = 'raepa.raepa_ouvrass_p';
35
IF TG_TABLE_NAME = 'raepa_reparaep_p' THEN
36
table_ouvrage = 'raepa.raepa_ouvraep_p';
37
END IF;
38
39
table_appareil = 'raepa.raepa_apparass_p';
40
IF TG_TABLE_NAME = 'raepa_reparaep_p' THEN
41
table_appareil = 'raepa.raepa_apparaep_p';
42
END IF;
43
44
IF NEW.idsuprepar IS NULL OR trim(NEW.idsuprepar) = '' OR trim(NEW.idsuprepar) = 'INCONNU' THEN
45
IF (trim(NEW.supprepare) = '01') THEN
46
EXECUTE format(
47
'
48
SELECT COALESCE(string_agg(c.idcana, '','' ORDER BY idcana), ''INCONNU'')
49
FROM %s AS c
50
WHERE ST_DWithin(c.geom, ''%s''::geometry, 0.05)
51
',
52
table_canalisation,
53
NEW.geom
54
)
55
INTO NEW.idsuprepar;
56
57
58
ELSIF (trim(NEW.supprepare) = '02') THEN
59
EXECUTE format(
60
'
61
SELECT COALESCE(string_agg(a.idappareil, '','' ORDER BY idappareil), ''INCONNU'')
62
FROM %s AS a
63
WHERE ST_DWithin(a.geom, ''%s''::geometry, 0.05)
64
',
65
table_appareil,
66
NEW.geom
67
)
68
INTO NEW.idsuprepar;
69
70
ELSIF (trim(NEW.supprepare) = '03') THEN
71
EXECUTE format(
72
'
73
SELECT COALESCE(string_agg(o.idouvrage, '','' ORDER BY idouvrage), ''INCONNU'')
74
FROM %s AS o
75
WHERE ST_DWithin(o.geom, ''%s''::geometry, 0.05)
76
',
77
table_ouvrage,
78
NEW.geom
79
)
80
INTO NEW.idsuprepar;
81
82
ELSE NEW.idsuprepar:='INCONNU';
83
END IF;
84
END IF;
85
86
87
-- Métadonnées
88
IF (NEW.mouvrage IS NULL) THEN
89
-- Récupération du gestionnaire
90
SELECT INTO organisme
91
s.nom
92
FROM raepa.sys_organisme_gestionnaire s
93
WHERE actif IS TRUE
94
ORDER BY id DESC
95
LIMIT 1;
96
END IF;
97
98
IF NEW.mouvrage IS NULL THEN
99
NEW.mouvrage := organisme;
100
END IF;
101
102
RETURN NEW;
103
104
END;
105