1ALTER TABLE acknowledges MODIFY acknowledgeid DEFAULT NULL;
2ALTER TABLE acknowledges MODIFY userid DEFAULT NULL;
3ALTER TABLE acknowledges MODIFY eventid DEFAULT NULL;
4DELETE FROM acknowledges WHERE NOT userid IN (SELECT userid FROM users);
5DELETE FROM acknowledges WHERE NOT eventid IN (SELECT eventid FROM events);
6ALTER TABLE acknowledges ADD CONSTRAINT c_acknowledges_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
7ALTER TABLE acknowledges ADD CONSTRAINT c_acknowledges_2 FOREIGN KEY (eventid) REFERENCES events (eventid) ON DELETE CASCADE;
8ALTER TABLE actions MODIFY actionid DEFAULT NULL;
9UPDATE actions SET esc_period=3600 WHERE eventsource=0 AND esc_period=0;
10ALTER TABLE alerts MODIFY alertid DEFAULT NULL;
11ALTER TABLE alerts MODIFY actionid DEFAULT NULL;
12ALTER TABLE alerts MODIFY eventid DEFAULT NULL;
13ALTER TABLE alerts MODIFY userid DEFAULT NULL;
14ALTER TABLE alerts MODIFY userid NULL;
15ALTER TABLE alerts MODIFY mediatypeid DEFAULT NULL;
16ALTER TABLE alerts MODIFY mediatypeid NULL;
17UPDATE alerts SET userid=NULL WHERE userid=0;
18UPDATE alerts SET mediatypeid=NULL WHERE mediatypeid=0;
19DELETE FROM alerts WHERE NOT actionid IN (SELECT actionid FROM actions);
20DELETE FROM alerts WHERE NOT eventid IN (SELECT eventid FROM events);
21DELETE FROM alerts WHERE NOT userid IN (SELECT userid FROM users);
22DELETE FROM alerts WHERE NOT mediatypeid IN (SELECT mediatypeid FROM media_type);
23ALTER TABLE alerts ADD CONSTRAINT c_alerts_1 FOREIGN KEY (actionid) REFERENCES actions (actionid) ON DELETE CASCADE;
24ALTER TABLE alerts ADD CONSTRAINT c_alerts_2 FOREIGN KEY (eventid) REFERENCES events (eventid) ON DELETE CASCADE;
25ALTER TABLE alerts ADD CONSTRAINT c_alerts_3 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
26ALTER TABLE alerts ADD CONSTRAINT c_alerts_4 FOREIGN KEY (mediatypeid) REFERENCES media_type (mediatypeid) ON DELETE CASCADE;
27ALTER TABLE applications MODIFY applicationid DEFAULT NULL;
28ALTER TABLE applications MODIFY hostid DEFAULT NULL;
29ALTER TABLE applications MODIFY templateid DEFAULT NULL;
30ALTER TABLE applications MODIFY templateid NULL;
31DELETE FROM applications WHERE NOT hostid IN (SELECT hostid FROM hosts);
32UPDATE applications SET templateid=NULL WHERE templateid=0;
33UPDATE applications SET templateid=NULL WHERE NOT templateid IS NULL AND NOT templateid IN (SELECT applicationid FROM applications);
34ALTER TABLE applications ADD CONSTRAINT c_applications_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
35ALTER TABLE applications ADD CONSTRAINT c_applications_2 FOREIGN KEY (templateid) REFERENCES applications (applicationid) ON DELETE CASCADE;
36ALTER TABLE auditlog_details MODIFY auditdetailid DEFAULT NULL;
37ALTER TABLE auditlog_details MODIFY auditid DEFAULT NULL;
38DELETE FROM auditlog_details WHERE NOT auditid IN (SELECT auditid FROM auditlog);
39ALTER TABLE auditlog_details ADD CONSTRAINT c_auditlog_details_1 FOREIGN KEY (auditid) REFERENCES auditlog (auditid) ON DELETE CASCADE;
40ALTER TABLE auditlog MODIFY auditid DEFAULT NULL;
41ALTER TABLE auditlog MODIFY userid DEFAULT NULL;
42DELETE FROM auditlog WHERE NOT userid IN (SELECT userid FROM users);
43ALTER TABLE auditlog ADD CONSTRAINT c_auditlog_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
44DROP INDEX autoreg_host_1;
45CREATE INDEX autoreg_host_1 ON autoreg_host (proxy_hostid,host);
46ALTER TABLE autoreg_host MODIFY autoreg_hostid DEFAULT NULL;
47ALTER TABLE autoreg_host MODIFY proxy_hostid DEFAULT NULL;
48ALTER TABLE autoreg_host MODIFY proxy_hostid NULL;
49ALTER TABLE autoreg_host ADD listen_ip nvarchar2(39) DEFAULT '';
50ALTER TABLE autoreg_host ADD listen_port number(10) DEFAULT '0' NOT NULL;
51ALTER TABLE autoreg_host ADD listen_dns nvarchar2(64) DEFAULT '';
52UPDATE autoreg_host SET proxy_hostid=NULL WHERE proxy_hostid=0;
53DELETE FROM autoreg_host WHERE proxy_hostid IS NOT NULL AND proxy_hostid NOT IN (SELECT hostid FROM hosts);
54ALTER TABLE autoreg_host ADD CONSTRAINT c_autoreg_host_1 FOREIGN KEY (proxy_hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
55ALTER TABLE conditions MODIFY conditionid DEFAULT NULL;
56ALTER TABLE conditions MODIFY actionid DEFAULT NULL;
57DELETE FROM conditions WHERE NOT actionid IN (SELECT actionid FROM actions);
58ALTER TABLE conditions ADD CONSTRAINT c_conditions_1 FOREIGN KEY (actionid) REFERENCES actions (actionid) ON DELETE CASCADE;
59ALTER TABLE config MODIFY configid DEFAULT NULL;
60ALTER TABLE config MODIFY alert_usrgrpid DEFAULT NULL;
61ALTER TABLE config MODIFY alert_usrgrpid NULL;
62ALTER TABLE config MODIFY discovery_groupid DEFAULT NULL;
63ALTER TABLE config MODIFY default_theme nvarchar2(128) DEFAULT 'originalblue' NOT NULL;
64ALTER TABLE config ADD severity_color_0 nvarchar2(6) DEFAULT 'DBDBDB';
65ALTER TABLE config ADD severity_color_1 nvarchar2(6) DEFAULT 'D6F6FF';
66ALTER TABLE config ADD severity_color_2 nvarchar2(6) DEFAULT 'FFF6A5';
67ALTER TABLE config ADD severity_color_3 nvarchar2(6) DEFAULT 'FFB689';
68ALTER TABLE config ADD severity_color_4 nvarchar2(6) DEFAULT 'FF9999';
69ALTER TABLE config ADD severity_color_5 nvarchar2(6) DEFAULT 'FF3838';
70ALTER TABLE config ADD severity_name_0 nvarchar2(32) DEFAULT 'Not classified';
71ALTER TABLE config ADD severity_name_1 nvarchar2(32) DEFAULT 'Information';
72ALTER TABLE config ADD severity_name_2 nvarchar2(32) DEFAULT 'Warning';
73ALTER TABLE config ADD severity_name_3 nvarchar2(32) DEFAULT 'Average';
74ALTER TABLE config ADD severity_name_4 nvarchar2(32) DEFAULT 'High';
75ALTER TABLE config ADD severity_name_5 nvarchar2(32) DEFAULT 'Disaster';
76ALTER TABLE config ADD ok_period number(10) DEFAULT '1800' NOT NULL;
77ALTER TABLE config ADD blink_period number(10) DEFAULT '1800' NOT NULL;
78ALTER TABLE config ADD problem_unack_color nvarchar2(6) DEFAULT 'DC0000';
79ALTER TABLE config ADD problem_ack_color nvarchar2(6) DEFAULT 'DC0000';
80ALTER TABLE config ADD ok_unack_color nvarchar2(6) DEFAULT '00AA00';
81ALTER TABLE config ADD ok_ack_color nvarchar2(6) DEFAULT '00AA00';
82ALTER TABLE config ADD problem_unack_style number(10) DEFAULT '1' NOT NULL;
83ALTER TABLE config ADD problem_ack_style number(10) DEFAULT '1' NOT NULL;
84ALTER TABLE config ADD ok_unack_style number(10) DEFAULT '1' NOT NULL;
85ALTER TABLE config ADD ok_ack_style number(10) DEFAULT '1' NOT NULL;
86ALTER TABLE config ADD snmptrap_logging number(10) DEFAULT '1' NOT NULL;
87ALTER TABLE config ADD server_check_interval number(10) DEFAULT '60' NOT NULL;
88UPDATE config SET alert_usrgrpid=NULL WHERE NOT alert_usrgrpid IN (SELECT usrgrpid FROM usrgrp);
89UPDATE config SET discovery_groupid=(SELECT MIN(groupid) FROM groups) WHERE NOT discovery_groupid IN (SELECT groupid FROM groups);
90
91UPDATE config SET default_theme='darkblue' WHERE default_theme='css_bb.css';
92UPDATE config SET default_theme='originalblue' WHERE default_theme IN ('css_ob.css', 'default.css');
93UPDATE config SET default_theme='darkorange' WHERE default_theme='css_od.css';
94
95ALTER TABLE config ADD CONSTRAINT c_config_1 FOREIGN KEY (alert_usrgrpid) REFERENCES usrgrp (usrgrpid);
96ALTER TABLE config ADD CONSTRAINT c_config_2 FOREIGN KEY (discovery_groupid) REFERENCES groups (groupid);
97-- See drules.sql
98ALTER TABLE dhosts MODIFY dhostid DEFAULT NULL;
99ALTER TABLE dhosts MODIFY druleid DEFAULT NULL;
100DELETE FROM dhosts WHERE NOT druleid IN (SELECT druleid FROM drules);
101ALTER TABLE dhosts ADD CONSTRAINT c_dhosts_1 FOREIGN KEY (druleid) REFERENCES drules (druleid) ON DELETE CASCADE;
102ALTER TABLE dchecks MODIFY dcheckid DEFAULT NULL;
103ALTER TABLE dchecks MODIFY druleid DEFAULT NULL;
104ALTER TABLE dchecks MODIFY key_ DEFAULT '';
105ALTER TABLE dchecks MODIFY snmp_community DEFAULT '';
106ALTER TABLE dchecks ADD uniq number(10) DEFAULT '0' NOT NULL;
107DELETE FROM dchecks WHERE NOT druleid IN (SELECT druleid FROM drules);
108ALTER TABLE dchecks ADD CONSTRAINT c_dchecks_1 FOREIGN KEY (druleid) REFERENCES drules (druleid) ON DELETE CASCADE;
109UPDATE dchecks SET uniq=1 WHERE dcheckid IN (SELECT unique_dcheckid FROM drules);
110ALTER TABLE drules MODIFY druleid DEFAULT NULL;
111ALTER TABLE drules MODIFY proxy_hostid DEFAULT NULL;
112ALTER TABLE drules MODIFY proxy_hostid NULL;
113ALTER TABLE drules MODIFY delay DEFAULT '3600';
114ALTER TABLE drules DROP COLUMN unique_dcheckid;
115UPDATE drules SET proxy_hostid=NULL WHERE NOT proxy_hostid IN (SELECT hostid FROM hosts);
116ALTER TABLE drules ADD CONSTRAINT c_drules_1 FOREIGN KEY (proxy_hostid) REFERENCES hosts (hostid);
117ALTER TABLE dservices MODIFY dserviceid DEFAULT NULL;
118ALTER TABLE dservices MODIFY dhostid DEFAULT NULL;
119ALTER TABLE dservices MODIFY dcheckid DEFAULT NULL;
120ALTER TABLE dservices MODIFY key_ DEFAULT '';
121ALTER TABLE dservices MODIFY value DEFAULT '';
122ALTER TABLE dservices ADD dns nvarchar2(64) DEFAULT '';
123DELETE FROM dservices WHERE NOT dhostid IN (SELECT dhostid FROM dhosts);
124DELETE FROM dservices WHERE NOT dcheckid IN (SELECT dcheckid FROM dchecks);
125ALTER TABLE dservices ADD CONSTRAINT c_dservices_1 FOREIGN KEY (dhostid) REFERENCES dhosts (dhostid) ON DELETE CASCADE;
126ALTER TABLE dservices ADD CONSTRAINT c_dservices_2 FOREIGN KEY (dcheckid) REFERENCES dchecks (dcheckid) ON DELETE CASCADE;
127ALTER TABLE escalations MODIFY escalationid DEFAULT NULL;
128ALTER TABLE escalations MODIFY actionid DEFAULT NULL;
129ALTER TABLE escalations MODIFY triggerid DEFAULT NULL;
130ALTER TABLE escalations MODIFY triggerid NULL;
131ALTER TABLE escalations MODIFY eventid DEFAULT NULL;
132ALTER TABLE escalations MODIFY eventid NULL;
133ALTER TABLE escalations MODIFY r_eventid DEFAULT NULL;
134ALTER TABLE escalations MODIFY r_eventid NULL;
135DROP INDEX escalations_2;
136
137-- 0: ESCALATION_STATUS_ACTIVE
138-- 1: ESCALATION_STATUS_RECOVERY
139-- 2: ESCALATION_STATUS_SLEEP
140-- 4: ESCALATION_STATUS_SUPERSEDED_ACTIVE
141-- 5: ESCALATION_STATUS_SUPERSEDED_RECOVERY
142UPDATE escalations SET status=0 WHERE status in (1,4,5);
143
144VARIABLE escalation_maxid number;
145BEGIN
146SELECT MAX(escalationid) INTO :escalation_maxid FROM escalations;
147END;
148/
149
150CREATE SEQUENCE escalations_seq;
151
152INSERT INTO escalations (escalationid, actionid, triggerid, r_eventid)
153	SELECT :escalation_maxid + escalations_seq.NEXTVAL, actionid, triggerid, r_eventid
154		FROM escalations
155		WHERE status = 0
156			AND eventid IS NOT NULL
157			AND r_eventid IS NOT NULL;
158UPDATE escalations SET r_eventid = NULL WHERE eventid IS NOT NULL AND r_eventid IS NOT NULL;
159
160DROP SEQUENCE escalations_seq;
161-- See triggers.sql
162ALTER TABLE expressions MODIFY expressionid DEFAULT NULL;
163ALTER TABLE expressions MODIFY regexpid DEFAULT NULL;
164DELETE FROM expressions WHERE NOT regexpid IN (SELECT regexpid FROM regexps);
165ALTER TABLE expressions ADD CONSTRAINT c_expressions_1 FOREIGN KEY (regexpid) REFERENCES regexps (regexpid) ON DELETE CASCADE;
166ALTER TABLE functions MODIFY functionid DEFAULT NULL;
167ALTER TABLE functions MODIFY itemid DEFAULT NULL;
168ALTER TABLE functions MODIFY triggerid DEFAULT NULL;
169ALTER TABLE functions DROP COLUMN lastvalue;
170DELETE FROM functions WHERE NOT itemid IN (SELECT itemid FROM items);
171DELETE FROM functions WHERE NOT triggerid IN (SELECT triggerid FROM triggers);
172ALTER TABLE functions ADD CONSTRAINT c_functions_1 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
173ALTER TABLE functions ADD CONSTRAINT c_functions_2 FOREIGN KEY (triggerid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
174ALTER TABLE globalmacro MODIFY globalmacroid DEFAULT NULL;
175CREATE TABLE globalvars (
176	globalvarid              number(20)                                NOT NULL,
177	snmp_lastsize            number(10)      DEFAULT '0'               NOT NULL,
178	PRIMARY KEY (globalvarid)
179);
180CREATE TABLE graph_discovery (
181	graphdiscoveryid         number(20)                                NOT NULL,
182	graphid                  number(20)                                NOT NULL,
183	parent_graphid           number(20)                                NOT NULL,
184	name                     nvarchar2(128)  DEFAULT ''                ,
185	PRIMARY KEY (graphdiscoveryid)
186);
187CREATE UNIQUE INDEX graph_discovery_1 on graph_discovery (graphid,parent_graphid);
188ALTER TABLE graph_discovery ADD CONSTRAINT c_graph_discovery_1 FOREIGN KEY (graphid) REFERENCES graphs (graphid) ON DELETE CASCADE;
189ALTER TABLE graph_discovery ADD CONSTRAINT c_graph_discovery_2 FOREIGN KEY (parent_graphid) REFERENCES graphs (graphid) ON DELETE CASCADE;
190ALTER TABLE graphs_items MODIFY gitemid DEFAULT NULL;
191ALTER TABLE graphs_items MODIFY graphid DEFAULT NULL;
192ALTER TABLE graphs_items MODIFY itemid DEFAULT NULL;
193ALTER TABLE graphs_items DROP COLUMN periods_cnt;
194UPDATE graphs_items SET type=0 WHERE type=1;
195DELETE FROM graphs_items WHERE NOT graphid IN (SELECT graphid FROM graphs);
196DELETE FROM graphs_items WHERE NOT itemid IN (SELECT itemid FROM items);
197ALTER TABLE graphs_items ADD CONSTRAINT c_graphs_items_1 FOREIGN KEY (graphid) REFERENCES graphs (graphid) ON DELETE CASCADE;
198ALTER TABLE graphs_items ADD CONSTRAINT c_graphs_items_2 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
199ALTER TABLE graphs MODIFY graphid DEFAULT NULL;
200ALTER TABLE graphs MODIFY templateid DEFAULT NULL;
201ALTER TABLE graphs MODIFY templateid NULL;
202ALTER TABLE graphs MODIFY ymin_itemid DEFAULT NULL;
203ALTER TABLE graphs MODIFY ymin_itemid NULL;
204ALTER TABLE graphs MODIFY ymax_itemid DEFAULT NULL;
205ALTER TABLE graphs MODIFY ymax_itemid NULL;
206ALTER TABLE graphs MODIFY show_legend DEFAULT 1;
207UPDATE graphs SET show_legend=1 WHERE graphtype=0 OR graphtype=1;
208ALTER TABLE graphs ADD flags number(10) DEFAULT '0' NOT NULL;
209UPDATE graphs SET templateid=NULL WHERE templateid=0;
210UPDATE graphs SET templateid=NULL WHERE NOT templateid IS NULL AND NOT templateid IN (SELECT graphid FROM graphs);
211UPDATE graphs SET ymin_itemid=NULL WHERE ymin_itemid=0 OR NOT ymin_itemid IN (SELECT itemid FROM items);
212UPDATE graphs SET ymax_itemid=NULL WHERE ymax_itemid=0 OR NOT ymax_itemid IN (SELECT itemid FROM items);
213UPDATE graphs SET ymin_type=0 WHERE ymin_type=2 AND ymin_itemid=NULL;
214UPDATE graphs SET ymax_type=0 WHERE ymax_type=2 AND ymax_itemid=NULL;
215ALTER TABLE graphs ADD CONSTRAINT c_graphs_1 FOREIGN KEY (templateid) REFERENCES graphs (graphid) ON DELETE CASCADE;
216ALTER TABLE graphs ADD CONSTRAINT c_graphs_2 FOREIGN KEY (ymin_itemid) REFERENCES items (itemid);
217ALTER TABLE graphs ADD CONSTRAINT c_graphs_3 FOREIGN KEY (ymax_itemid) REFERENCES items (itemid);
218ALTER TABLE graph_theme MODIFY graphthemeid DEFAULT NULL;
219ALTER TABLE graph_theme MODIFY noneworktimecolor DEFAULT 'CCCCCC';
220ALTER TABLE graph_theme RENAME COLUMN noneworktimecolor TO nonworktimecolor;
221
222UPDATE graph_theme SET theme = 'darkblue' WHERE theme = 'css_bb.css';
223UPDATE graph_theme SET theme = 'originalblue' WHERE theme = 'css_ob.css';
224
225-- Insert new graph theme
226INSERT INTO graph_theme (graphthemeid, description, theme, backgroundcolor, graphcolor, graphbordercolor, gridcolor,
227	maingridcolor, gridbordercolor, textcolor, highlightcolor, leftpercentilecolor, rightpercentilecolor,
228	nonworktimecolor, gridview, legendview)
229SELECT (SELECT MAX(graphthemeid) FROM graph_theme) + 1 AS graphthemeid, 'Dark orange' AS description, 'darkorange' AS theme,
230	'333333' AS backgroundcolor, '0A0A0A' AS graphcolor, '888888' AS graphbordercolor, '222222' AS gridcolor,
231	'4F4F4F' AS maingridcolor, 'EFEFEF' AS gridbordercolor, 'DFDFDF' AS textcolor, 'FF5500' AS highlightcolor,
232	'FF5500' AS leftpercentilecolor, 'FF1111' AS rightpercentilecolor, '1F1F1F' AS nonworktimecolor, 1 AS gridview,
233	1 AS legendview
234FROM dual WHERE EXISTS (SELECT NULL FROM graph_theme);
235
236INSERT INTO graph_theme (graphthemeid, description, theme, backgroundcolor, graphcolor, graphbordercolor, gridcolor,
237	maingridcolor, gridbordercolor, textcolor, highlightcolor, leftpercentilecolor, rightpercentilecolor,
238	nonworktimecolor, gridview, legendview)
239SELECT (SELECT MAX(graphthemeid) FROM graph_theme) + 1 AS graphthemeid, 'Classic' AS description, 'classic' AS theme,
240	'F0F0F0' AS backgroundcolor, 'FFFFFF' AS graphcolor, '333333' AS graphbordercolor, 'CCCCCC' AS gridcolor,
241	'AAAAAA' AS maingridcolor, '000000' AS gridbordercolor, '222222' AS textcolor, 'AA4444' AS highlightcolor,
242	'11CC11' AS leftpercentilecolor, 'CC1111' AS rightpercentilecolor, 'E0E0E0' AS nonworktimecolor, 1 AS gridview,
243	1 AS legendview
244FROM dual WHERE EXISTS (SELECT NULL FROM graph_theme);
245
246DELETE FROM ids WHERE table_name = 'graph_theme';
247ALTER TABLE groups MODIFY groupid DEFAULT NULL;
248SET DEFINE OFF
249
250drop table help_items;
251
252CREATE TABLE help_items (
253	itemtype	number(10)	DEFAULT '0'	NOT NULL,
254	key_		nvarchar2(255)	DEFAULT ''	,
255	description	nvarchar2(255)	DEFAULT ''	,
256	PRIMARY KEY (itemtype,key_)
257);
258
259INSERT INTO help_items (itemtype,key_,description) values ('0','agent.ping','Check the agent usability. Always return 1. Can be used as a TCP ping.');
260INSERT INTO help_items (itemtype,key_,description) values ('0','agent.version','Version of zabbix_agent(d) running on monitored host. String value. Example of returned value: 1.1');
261INSERT INTO help_items (itemtype,key_,description) values ('0','kernel.maxfiles','Maximum number of opened files supported by OS.');
262INSERT INTO help_items (itemtype,key_,description) values ('0','kernel.maxproc','Maximum number of processes supported by OS.');
263INSERT INTO help_items (itemtype,key_,description) values ('0','net.dns.record[<ip>,name,<type>,<timeout>,<count>]','Performs a DNS query. On success returns a character string with the required type of information.');
264INSERT INTO help_items (itemtype,key_,description) values ('0','net.dns[<ip>,name,<type>,<timeout>,<count>]','Checks if DNS service is up. 0 - DNS is down (server did not respond or DNS resolution failed), 1 - DNS is up.');
265INSERT INTO help_items (itemtype,key_,description) values ('0','net.if.collisions[if]','Out-of-window collision. Collisions count.');
266INSERT INTO help_items (itemtype,key_,description) values ('0','net.if.in[if,<mode>]','Network interface input statistic. Integer value. If mode is missing bytes is used.');
267INSERT INTO help_items (itemtype,key_,description) values ('0','net.if.list','List of network interfaces. Text value.');
268INSERT INTO help_items (itemtype,key_,description) values ('0','net.if.out[if,<mode>]','Network interface output statistic. Integer value. If mode is missing bytes is used.');
269INSERT INTO help_items (itemtype,key_,description) values ('0','net.if.total[if,<mode>]','Sum of network interface incoming and outgoing statistics. Integer value. Mode - one of bytes (default), packets, errors or dropped');
270INSERT INTO help_items (itemtype,key_,description) values ('0','net.tcp.listen[port]','Checks if this port is in LISTEN state. 0 - it is not, 1 - it is in LISTEN state.');
271INSERT INTO help_items (itemtype,key_,description) values ('0','net.tcp.port[<ip>,port]','Check, if it is possible to make TCP connection to the port number. 0 - cannot connect, 1 - can connect. IP address is optional. If ip is missing, 127.0.0.1 is used. Example: net.tcp.port[,80]');
272INSERT INTO help_items (itemtype,key_,description) values ('0','net.tcp.service.perf[service,<ip>,<port>]','Check performance of service "service". 0 - service is down, sec - number of seconds spent on connection to the service. If ip is missing 127.0.0.1 is used.  If port number is missing, default service port is used.');
273INSERT INTO help_items (itemtype,key_,description) values ('0','net.tcp.service[service,<ip>,<port>]','Check if service is available. 0 - service is down, 1 - service is running. If ip is missing 127.0.0.1 is used. If port number is missing, default service port is used. Example: net.tcp.service[ftp,,45].');
274INSERT INTO help_items (itemtype,key_,description) values ('0','perf_counter[counter,<interval>]','Value of any performance counter, where "counter" parameter is the counter path and "interval" parameter is a number of last seconds, for which the agent returns an average value.');
275INSERT INTO help_items (itemtype,key_,description) values ('0','proc.mem[<name>,<user>,<mode>,<cmdline>]','Memory used by process with name name running under user user. Memory used by processes. Process name, user and mode is optional. If name or user is missing all processes will be calculated. If mode is missing sum is used. Example: proc.mem[,root]');
276INSERT INTO help_items (itemtype,key_,description) values ('0','proc.num[<name>,<user>,<state>,<cmdline>]','Number of processes with name name running under user user having state state. Process name, user and state are optional. Examples: proc.num[,mysql]; proc.num[apache2,www-data]; proc.num[,oracle,sleep,oracleZABBIX]');
277INSERT INTO help_items (itemtype,key_,description) values ('0','proc_info[<process>,<attribute>,<type>]','Different information about specific process(es)');
278INSERT INTO help_items (itemtype,key_,description) values ('0','service_state[service]','State of service. 0 - running, 1 - paused, 2 - start pending, 3 - pause pending, 4 - continue pending, 5 - stop pending, 6 - stopped, 7 - unknown, 255 - no such service');
279INSERT INTO help_items (itemtype,key_,description) values ('0','system.boottime','Timestamp of system boot.');
280INSERT INTO help_items (itemtype,key_,description) values ('0','system.cpu.intr','Device interrupts.');
281INSERT INTO help_items (itemtype,key_,description) values ('0','system.cpu.load[<cpu>,<mode>]','CPU(s) load. Processor load. The cpu and mode are optional. If cpu is missing all is used. If mode is missing avg1 is used. Note that this is not percentage.');
282INSERT INTO help_items (itemtype,key_,description) values ('0','system.cpu.num','Number of available proccessors.');
283INSERT INTO help_items (itemtype,key_,description) values ('0','system.cpu.switches','Context switches.');
284INSERT INTO help_items (itemtype,key_,description) values ('0','system.cpu.util[<cpu>,<type>,<mode>]','CPU(s) utilisation. Processor load in percents. The cpu, type and mode are optional. If cpu is missing all is used.  If type is missing user is used. If mode is missing avg1 is used.');
285INSERT INTO help_items (itemtype,key_,description) values ('0','system.hostname[<type>]','Returns hostname (or NetBIOS name (by default) on Windows). String value. Example of returned value: www.zabbix.com');
286INSERT INTO help_items (itemtype,key_,description) values ('0','system.hw.chassis[<info>]','Chassis info - returns full info by default');
287INSERT INTO help_items (itemtype,key_,description) values ('0','system.hw.cpu[<cpu>,<info>]','CPU info - lists full info for all CPUs by default');
288INSERT INTO help_items (itemtype,key_,description) values ('0','system.hw.devices[<type>]','Device list - lists PCI devices by default');
289INSERT INTO help_items (itemtype,key_,description) values ('0','system.hw.macaddr[<interface>,<format>]','MAC address - lists all MAC addresses with interface names by default');
290INSERT INTO help_items (itemtype,key_,description) values ('0','system.localtime','System local time. Time in seconds.');
291INSERT INTO help_items (itemtype,key_,description) values ('0','system.run[command,<mode>]','Run specified command on the host.');
292INSERT INTO help_items (itemtype,key_,description) values ('0','system.stat[resource,<type>]','Virtual memory statistics.');
293INSERT INTO help_items (itemtype,key_,description) values ('0','system.sw.arch','Software architecture');
294INSERT INTO help_items (itemtype,key_,description) values ('0','system.sw.os[<info>]','Current OS - returns full info by default');
295INSERT INTO help_items (itemtype,key_,description) values ('0','system.sw.packages[<package>,<manager>,<format>]','Software package list - lists all packages for all supported package managers by default');
296INSERT INTO help_items (itemtype,key_,description) values ('0','system.swap.in[<swap>,<type>]','Swap in. If type is count - swapins is returned. If type is pages - pages swapped in is returned. If swap is missing all is used.');
297INSERT INTO help_items (itemtype,key_,description) values ('0','system.swap.out[<swap>,<type>]','Swap out. If type is count - swapouts is returned. If type is pages - pages swapped in is returned. If swap is missing all is used.');
298INSERT INTO help_items (itemtype,key_,description) values ('0','system.swap.size[<swap>,<mode>]','Swap space. Number of bytes. If swap is missing all is used. If mode is missing free is used.');
299INSERT INTO help_items (itemtype,key_,description) values ('0','system.uname','Returns detailed host information. String value');
300INSERT INTO help_items (itemtype,key_,description) values ('0','system.uptime','System uptime in seconds.');
301INSERT INTO help_items (itemtype,key_,description) values ('0','system.users.num','Number of users connected. Command who is used on agent side.');
302INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.dev.read[device,<type>,<mode>]','Device read statistics.');
303INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.dev.write[device,<type>,<mode>]','Device write statistics.');
304INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.cksum[file]','Calculate check sum of a given file. Check sum of the file calculate by standard algorithm used by UNIX utility cksum. Example: vfs.file.cksum[/etc/passwd]');
305INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.contents[file,<encoding>]','Get contents of a given file.');
306INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.exists[file]','Check if file exists. 0 - file does not exist, 1 - file exists');
307INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.md5sum[file]','Calculate MD5 check sum of a given file. String MD5 hash of the file. Can be used for files less than 64MB, unsupported otherwise. Example: vfs.file.md5sum[/usr/local/usr/local/etc/zabbix3_agentd.conf]');
308INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.regexp[file,regexp,<encoding>]','Find string in a file. Matched string');
309INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.regmatch[file,regexp,<encoding>]','Find string in a file. 0 - expression not found, 1 - found');
310INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.size[file]','Size of a given file. Size in bytes. File must have read permissions for user zabbix. Example: vfs.file.size[/var/log/syslog]');
311INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.file.time[file,<mode>]','File time information. Number of seconds.The mode is optional. If mode is missing modify is used.');
312INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.fs.inode[fs,<mode>]','Number of inodes for a given volume. If mode is missing total is used.');
313INSERT INTO help_items (itemtype,key_,description) values ('0','vfs.fs.size[fs,<mode>]','Calculate disk space for a given volume. Disk space in KB. If mode is missing total is used.  In case of mounted volume, unused disk space for local file system is returned. Example: vfs.fs.size[/tmp,free].');
314INSERT INTO help_items (itemtype,key_,description) values ('0','vm.memory.size[<mode>]','Amount of memory size in bytes. If mode is missing total is used.');
315INSERT INTO help_items (itemtype,key_,description) values ('0','web.page.get[host,<path>,<port>]','Get content of web page. Default path is /');
316INSERT INTO help_items (itemtype,key_,description) values ('0','web.page.perf[host,<path>,<port>]','Get timing of loading full web page. Default path is /');
317INSERT INTO help_items (itemtype,key_,description) values ('0','web.page.regexp[host,<path>,<port>,<regexp>,<length>]','Get first occurrence of regexp in web page. Default path is /');
318INSERT INTO help_items (itemtype,key_,description) values ('3','icmppingloss[<target>,<packets>,<interval>,<size>,<timeout>]','Returns percentage of lost ICMP ping packets.');
319INSERT INTO help_items (itemtype,key_,description) values ('3','icmppingsec[<target>,<packets>,<interval>,<size>,<timeout>,<mode>]','Returns ICMP ping response time in seconds. Example: 0.02');
320INSERT INTO help_items (itemtype,key_,description) values ('3','icmpping[<target>,<packets>,<interval>,<size>,<timeout>]','Checks if server is accessible by ICMP ping. 0 - ICMP ping fails. 1 - ICMP ping successful. One of zabbix_server processes performs ICMP pings once per PingerFrequency seconds.');
321INSERT INTO help_items (itemtype,key_,description) values ('3','net.tcp.service.perf[service,<ip>,<port>]','Check performance of service. 0 - service is down, sec - number of seconds spent on connection to the service. If <ip> is missing, IP or DNS name is taken from host definition. If <port> is missing, default service port is used.');
322INSERT INTO help_items (itemtype,key_,description) values ('3','net.tcp.service[service,<ip>,<port>]','Check if service is available. 0 - service is down, 1 - service is running. If <ip> is missing, IP or DNS name is taken from host definition. If <port> is missing, default service port is used.');
323INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[boottime]','Startup time of Zabbix server, Unix timestamp.');
324INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[history]','Number of values stored in table HISTORY.');
325INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[history_log]','Number of values stored in table HISTORY_LOG.');
326INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[history_str]','Number of values stored in table HISTORY_STR.');
327INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[history_text]','Number of values stored in table HISTORY_TEXT.');
328INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[history_uint]','Number of values stored in table HISTORY_UINT.');
329INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[host,<type>,available]','Returns availability of a particular type of checks on the host. Value of this item corresponds to availability icons in the host list. Valid types are: agent, snmp, ipmi, jmx.');
330INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[items]','Number of items in Zabbix database.');
331INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[items_unsupported]','Number of unsupported items in Zabbix database.');
332INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[java,,<param>]','Returns information associated with Zabbix Java gateway. Valid params are: ping, version.');
333INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[process,<type>,<num>,<state>]','Time a particular Zabbix process or a group of processes (identified by <type> and <num>) spent in <state> in percentage.');
334INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[proxy,<name>,<param>]','Time of proxy last access. Name - proxy name. Param - lastaccess. Unix timestamp.');
335INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[queue,<from>,<to>]','Number of items in the queue which are delayed by from to to seconds, inclusive.');
336INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[requiredperformance]','Required performance of the Zabbix server, in new values per second expected.');
337INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[rcache,<cache>,<mode>]','Configuration cache statistics. Cache - buffer (modes: pfree, total, used, free).');
338INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[trends]','Number of values stored in table TRENDS.');
339INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[trends_uint]','Number of values stored in table TRENDS_UINT.');
340INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[triggers]','Number of triggers in Zabbix database.');
341INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[uptime]','Uptime of Zabbix server process in seconds.');
342INSERT INTO help_items (itemtype,key_,description) values ('5','zabbix[wcache,<cache>,<mode>]','Data cache statistics. Cache - one of values (modes: all, float, uint, str, log, text), history (modes: pfree, total, used, free), trend (modes: pfree, total, used, free), text (modes: pfree, total, used, free).');
343INSERT INTO help_items (itemtype,key_,description) values ('7','agent.ping','Check the agent usability. Always return 1. Can be used as a TCP ping.');
344INSERT INTO help_items (itemtype,key_,description) values ('7','agent.version','Version of zabbix_agent(d) running on monitored host. String value. Example of returned value: 1.1');
345INSERT INTO help_items (itemtype,key_,description) values ('7','eventlog[logtype,<pattern>,<severity>,<source>,<eventid>,<maxlines>,<mode>]','Monitoring of Windows event logs. pattern, severity, eventid - regular expressions');
346INSERT INTO help_items (itemtype,key_,description) values ('7','kernel.maxfiles','Maximum number of opened files supported by OS.');
347INSERT INTO help_items (itemtype,key_,description) values ('7','kernel.maxproc','Maximum number of processes supported by OS.');
348INSERT INTO help_items (itemtype,key_,description) values ('7','logrt[file_format,<pattern>,<encoding>,<maxlines>,<mode>]','Monitoring of log file with rotation. fileformat - [path][regexp], pattern - regular expression');
349INSERT INTO help_items (itemtype,key_,description) values ('7','log[file,<pattern>,<encoding>,<maxlines>,<mode>]','Monitoring of log file. pattern - regular expression');
350INSERT INTO help_items (itemtype,key_,description) values ('7','net.dns.record[<ip>,name,<type>,<timeout>,<count>]','Performs a DNS query. On success returns a character string with the required type of information.');
351INSERT INTO help_items (itemtype,key_,description) values ('7','net.dns[<ip>,name,<type>,<timeout>,<count>]','Checks if DNS service is up. 0 - DNS is down (server did not respond or DNS resolution failed), 1 - DNS is up.');
352INSERT INTO help_items (itemtype,key_,description) values ('7','net.if.collisions[if]','Out-of-window collision. Collisions count.');
353INSERT INTO help_items (itemtype,key_,description) values ('7','net.if.in[if,<mode>]','Network interface input statistic. Integer value. If mode is missing bytes is used.');
354INSERT INTO help_items (itemtype,key_,description) values ('7','net.if.list','List of network interfaces. Text value.');
355INSERT INTO help_items (itemtype,key_,description) values ('7','net.if.out[if,<mode>]','Network interface output statistic. Integer value. If mode is missing bytes is used.');
356INSERT INTO help_items (itemtype,key_,description) values ('7','net.if.total[if,<mode>]','Sum of network interface incoming and outgoing statistics. Integer value. Mode - one of bytes (default), packets, errors or dropped');
357INSERT INTO help_items (itemtype,key_,description) values ('7','net.tcp.listen[port]','Checks if this port is in LISTEN state. 0 - it is not, 1 - it is in LISTEN state.');
358INSERT INTO help_items (itemtype,key_,description) values ('7','net.tcp.port[<ip>,port]','Check, if it is possible to make TCP connection to the port number. 0 - cannot connect, 1 - can connect. IP address is optional. If ip is missing, 127.0.0.1 is used. Example: net.tcp.port[,80]');
359INSERT INTO help_items (itemtype,key_,description) values ('7','net.tcp.service.perf[service,<ip>,<port>]','Check performance of service "service". 0 - service is down, sec - number of seconds spent on connection to the service. If ip is missing 127.0.0.1 is used.  If port number is missing, default service port is used.');
360INSERT INTO help_items (itemtype,key_,description) values ('7','net.tcp.service[service,<ip>,<port>]','Check if service is available. 0 - service is down, 1 - service is running. If ip is missing 127.0.0.1 is used. If port number is missing, default service port is used. Example: net.tcp.service[ftp,,45].');
361INSERT INTO help_items (itemtype,key_,description) values ('7','perf_counter[counter,<interval>]','Value of any performance counter, where "counter" parameter is the counter path and "interval" parameter is a number of last seconds, for which the agent returns an average value.');
362INSERT INTO help_items (itemtype,key_,description) values ('7','proc.mem[<name>,<user>,<mode>,<cmdline>]','Memory used by process with name name running under user user. Memory used by processes. Process name, user and mode is optional. If name or user is missing all processes will be calculated. If mode is missing sum is used. Example: proc.mem[,root]');
363INSERT INTO help_items (itemtype,key_,description) values ('7','proc.num[<name>,<user>,<state>,<cmdline>]','Number of processes with name name running under user user having state state. Process name, user and state are optional. Examples: proc.num[,mysql]; proc.num[apache2,www-data]; proc.num[,oracle,sleep,oracleZABBIX]');
364INSERT INTO help_items (itemtype,key_,description) values ('7','proc_info[<process>,<attribute>,<type>]','Different information about specific process(es)');
365INSERT INTO help_items (itemtype,key_,description) values ('7','service_state[service]','State of service. 0 - running, 1 - paused, 2 - start pending, 3 - pause pending, 4 - continue pending, 5 - stop pending, 6 - stopped, 7 - unknown, 255 - no such service');
366INSERT INTO help_items (itemtype,key_,description) values ('7','system.boottime','Timestamp of system boot.');
367INSERT INTO help_items (itemtype,key_,description) values ('7','system.cpu.intr','Device interrupts.');
368INSERT INTO help_items (itemtype,key_,description) values ('7','system.cpu.load[<cpu>,<mode>]','CPU(s) load. Processor load. The cpu and mode are optional. If cpu is missing all is used. If mode is missing avg1 is used. Note that this is not percentage.');
369INSERT INTO help_items (itemtype,key_,description) values ('7','system.cpu.num','Number of available proccessors.');
370INSERT INTO help_items (itemtype,key_,description) values ('7','system.cpu.switches','Context switches.');
371INSERT INTO help_items (itemtype,key_,description) values ('7','system.cpu.util[<cpu>,<type>,<mode>]','CPU(s) utilisation. Processor load in percents. The cpu, type and mode are optional. If cpu is missing all is used.  If type is missing user is used. If mode is missing avg1 is used.');
372INSERT INTO help_items (itemtype,key_,description) values ('7','system.hostname[<type>]','Returns hostname (or NetBIOS name (by default) on Windows). String value. Example of returned value: www.zabbix.com');
373INSERT INTO help_items (itemtype,key_,description) values ('7','system.hw.chassis[<info>]','Chassis info - returns full info by default');
374INSERT INTO help_items (itemtype,key_,description) values ('7','system.hw.cpu[<cpu>,<info>]','CPU info - lists full info for all CPUs by default');
375INSERT INTO help_items (itemtype,key_,description) values ('7','system.hw.devices[<type>]','Device list - lists PCI devices by default');
376INSERT INTO help_items (itemtype,key_,description) values ('7','system.hw.macaddr[<interface>,<format>]','MAC address - lists all MAC addresses with interface names by default');
377INSERT INTO help_items (itemtype,key_,description) values ('7','system.localtime','System local time. Time in seconds.');
378INSERT INTO help_items (itemtype,key_,description) values ('7','system.run[command,<mode>]','Run specified command on the host.');
379INSERT INTO help_items (itemtype,key_,description) values ('7','system.stat[resource,<type>]','Virtual memory statistics.');
380INSERT INTO help_items (itemtype,key_,description) values ('7','system.sw.arch','Software architecture');
381INSERT INTO help_items (itemtype,key_,description) values ('7','system.sw.os[<info>]','Current OS - returns full info by default');
382INSERT INTO help_items (itemtype,key_,description) values ('7','system.sw.packages[<package>,<manager>,<format>]','Software package list - lists all packages for all supported package managers by default');
383INSERT INTO help_items (itemtype,key_,description) values ('7','system.swap.in[<swap>,<type>]','Swap in. If type is count - swapins is returned. If type is pages - pages swapped in is returned. If swap is missing all is used.');
384INSERT INTO help_items (itemtype,key_,description) values ('7','system.swap.out[<swap>,<type>]','Swap out. If type is count - swapouts is returned. If type is pages - pages swapped in is returned. If swap is missing all is used.');
385INSERT INTO help_items (itemtype,key_,description) values ('7','system.swap.size[<swap>,<mode>]','Swap space. Number of bytes. If swap is missing all is used. If mode is missing free is used.');
386INSERT INTO help_items (itemtype,key_,description) values ('7','system.uname','Returns detailed host information. String value');
387INSERT INTO help_items (itemtype,key_,description) values ('7','system.uptime','System uptime in seconds.');
388INSERT INTO help_items (itemtype,key_,description) values ('7','system.users.num','Number of users connected. Command who is used on agent side.');
389INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.dev.read[device,<type>,<mode>]','Device read statistics.');
390INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.dev.write[device,<type>,<mode>]','Device write statistics.');
391INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.cksum[file]','Calculate check sum of a given file. Check sum of the file calculate by standard algorithm used by UNIX utility cksum. Example: vfs.file.cksum[/etc/passwd]');
392INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.contents[file,<encoding>]','Get contents of a given file.');
393INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.exists[file]','Check if file exists. 0 - file does not exist, 1 - file exists');
394INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.md5sum[file]','Calculate MD5 check sum of a given file. String MD5 hash of the file. Can be used for files less than 64MB, unsupported otherwise. Example: vfs.file.md5sum[/usr/local/usr/local/etc/zabbix3_agentd.conf]');
395INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.regexp[file,regexp,<encoding>]','Find string in a file. Matched string');
396INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.regmatch[file,regexp,<encoding>]','Find string in a file. 0 - expression not found, 1 - found');
397INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.size[file]','Size of a given file. Size in bytes. File must have read permissions for user zabbix. Example: vfs.file.size[/var/log/syslog]');
398INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.file.time[file,<mode>]','File time information. Number of seconds.The mode is optional. If mode is missing modify is used.');
399INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.fs.inode[fs,<mode>]','Number of inodes for a given volume. If mode is missing total is used.');
400INSERT INTO help_items (itemtype,key_,description) values ('7','vfs.fs.size[fs,<mode>]','Calculate disk space for a given volume. Disk space in KB. If mode is missing total is used.  In case of mounted volume, unused disk space for local file system is returned. Example: vfs.fs.size[/tmp,free].');
401INSERT INTO help_items (itemtype,key_,description) values ('7','vm.memory.size[<mode>]','Amount of memory size in bytes. If mode is missing total is used.');
402INSERT INTO help_items (itemtype,key_,description) values ('7','web.page.get[host,<path>,<port>]','Get content of web page. Default path is /');
403INSERT INTO help_items (itemtype,key_,description) values ('7','web.page.perf[host,<path>,<port>]','Get timing of loading full web page. Default path is /');
404INSERT INTO help_items (itemtype,key_,description) values ('7','web.page.regexp[host,<path>,<port>,<regexp>,<length>]','Get first occurrence of regexp in web page. Default path is /');
405INSERT INTO help_items (itemtype,key_,description) values ('8','grpfunc[<group>,<key>,<func>,<param>]','Aggregate checks do not require any agent running on a host being monitored. Zabbix server collects aggregate information by doing direct database queries. See Zabbix Manual.');
406INSERT INTO help_items (itemtype,key_,description) values ('17','snmptrap.fallback','Catches all SNMP traps from a corresponding address that were not catched by any of the snmptrap[] items for that interface.');
407INSERT INTO help_items (itemtype,key_,description) values ('17','snmptrap[<regex>]','Catches all SNMP traps from a corresponding address that match regex. Default regex is an empty string.');
408ALTER TABLE history_log MODIFY id DEFAULT NULL;
409ALTER TABLE history_log MODIFY itemid DEFAULT NULL;
410ALTER TABLE history_log ADD ns number(10) DEFAULT '0' NOT NULL;
411ALTER TABLE history MODIFY itemid DEFAULT NULL;
412ALTER TABLE history ADD ns number(10) DEFAULT '0' NOT NULL;
413ALTER TABLE history_str MODIFY itemid DEFAULT NULL;
414ALTER TABLE history_str ADD ns number(10) DEFAULT '0' NOT NULL;
415ALTER TABLE history_str_sync MODIFY itemid DEFAULT NULL;
416ALTER TABLE history_str_sync MODIFY nodeid DEFAULT NULL;
417ALTER TABLE history_str_sync MODIFY nodeid number(10);
418ALTER TABLE history_str_sync ADD ns number(10) DEFAULT '0' NOT NULL;
419ALTER TABLE history_sync MODIFY itemid DEFAULT NULL;
420ALTER TABLE history_sync MODIFY nodeid DEFAULT NULL;
421ALTER TABLE history_sync MODIFY nodeid number(10);
422ALTER TABLE history_sync ADD ns number(10) DEFAULT '0' NOT NULL;
423ALTER TABLE history_text MODIFY id DEFAULT NULL;
424ALTER TABLE history_text MODIFY itemid DEFAULT NULL;
425ALTER TABLE history_text ADD ns number(10) DEFAULT '0' NOT NULL;
426ALTER TABLE history_uint MODIFY itemid DEFAULT NULL;
427ALTER TABLE history_uint ADD ns number(10) DEFAULT '0' NOT NULL;
428ALTER TABLE history_uint_sync MODIFY itemid DEFAULT NULL;
429ALTER TABLE history_uint_sync MODIFY nodeid DEFAULT NULL;
430ALTER TABLE history_uint_sync MODIFY nodeid number(10);
431ALTER TABLE history_uint_sync ADD ns number(10) DEFAULT '0' NOT NULL;
432DELETE FROM hosts_profiles WHERE NOT hostid IN (SELECT hostid FROM hosts);
433DELETE FROM hosts_profiles_ext WHERE NOT hostid IN (SELECT hostid FROM hosts);
434
435CREATE TABLE host_inventory (
436	hostid                   number(20)                                NOT NULL,
437	inventory_mode           number(10)      DEFAULT '0'               NOT NULL,
438	type                     nvarchar2(64)   DEFAULT ''                ,
439	type_full                nvarchar2(64)   DEFAULT ''                ,
440	name                     nvarchar2(64)   DEFAULT ''                ,
441	alias                    nvarchar2(64)   DEFAULT ''                ,
442	os                       nvarchar2(64)   DEFAULT ''                ,
443	os_full                  nvarchar2(255)  DEFAULT ''                ,
444	os_short                 nvarchar2(64)   DEFAULT ''                ,
445	serialno_a               nvarchar2(64)   DEFAULT ''                ,
446	serialno_b               nvarchar2(64)   DEFAULT ''                ,
447	tag                      nvarchar2(64)   DEFAULT ''                ,
448	asset_tag                nvarchar2(64)   DEFAULT ''                ,
449	macaddress_a             nvarchar2(64)   DEFAULT ''                ,
450	macaddress_b             nvarchar2(64)   DEFAULT ''                ,
451	hardware                 nvarchar2(255)  DEFAULT ''                ,
452	hardware_full            nvarchar2(2048) DEFAULT ''                ,
453	software                 nvarchar2(255)  DEFAULT ''                ,
454	software_full            nvarchar2(2048) DEFAULT ''                ,
455	software_app_a           nvarchar2(64)   DEFAULT ''                ,
456	software_app_b           nvarchar2(64)   DEFAULT ''                ,
457	software_app_c           nvarchar2(64)   DEFAULT ''                ,
458	software_app_d           nvarchar2(64)   DEFAULT ''                ,
459	software_app_e           nvarchar2(64)   DEFAULT ''                ,
460	contact                  nvarchar2(2048) DEFAULT ''                ,
461	location                 nvarchar2(2048) DEFAULT ''                ,
462	location_lat             nvarchar2(16)   DEFAULT ''                ,
463	location_lon             nvarchar2(16)   DEFAULT ''                ,
464	notes                    nvarchar2(2048) DEFAULT ''                ,
465	chassis                  nvarchar2(64)   DEFAULT ''                ,
466	model                    nvarchar2(64)   DEFAULT ''                ,
467	hw_arch                  nvarchar2(32)   DEFAULT ''                ,
468	vendor                   nvarchar2(64)   DEFAULT ''                ,
469	contract_number          nvarchar2(64)   DEFAULT ''                ,
470	installer_name           nvarchar2(64)   DEFAULT ''                ,
471	deployment_status        nvarchar2(64)   DEFAULT ''                ,
472	url_a                    nvarchar2(255)  DEFAULT ''                ,
473	url_b                    nvarchar2(255)  DEFAULT ''                ,
474	url_c                    nvarchar2(255)  DEFAULT ''                ,
475	host_networks            nvarchar2(2048) DEFAULT ''                ,
476	host_netmask             nvarchar2(39)   DEFAULT ''                ,
477	host_router              nvarchar2(39)   DEFAULT ''                ,
478	oob_ip                   nvarchar2(39)   DEFAULT ''                ,
479	oob_netmask              nvarchar2(39)   DEFAULT ''                ,
480	oob_router               nvarchar2(39)   DEFAULT ''                ,
481	date_hw_purchase         nvarchar2(64)   DEFAULT ''                ,
482	date_hw_install          nvarchar2(64)   DEFAULT ''                ,
483	date_hw_expiry           nvarchar2(64)   DEFAULT ''                ,
484	date_hw_decomm           nvarchar2(64)   DEFAULT ''                ,
485	site_address_a           nvarchar2(128)  DEFAULT ''                ,
486	site_address_b           nvarchar2(128)  DEFAULT ''                ,
487	site_address_c           nvarchar2(128)  DEFAULT ''                ,
488	site_city                nvarchar2(128)  DEFAULT ''                ,
489	site_state               nvarchar2(64)   DEFAULT ''                ,
490	site_country             nvarchar2(64)   DEFAULT ''                ,
491	site_zip                 nvarchar2(64)   DEFAULT ''                ,
492	site_rack                nvarchar2(128)  DEFAULT ''                ,
493	site_notes               nvarchar2(2048) DEFAULT ''                ,
494	poc_1_name               nvarchar2(128)  DEFAULT ''                ,
495	poc_1_email              nvarchar2(128)  DEFAULT ''                ,
496	poc_1_phone_a            nvarchar2(64)   DEFAULT ''                ,
497	poc_1_phone_b            nvarchar2(64)   DEFAULT ''                ,
498	poc_1_cell               nvarchar2(64)   DEFAULT ''                ,
499	poc_1_screen             nvarchar2(64)   DEFAULT ''                ,
500	poc_1_notes              nvarchar2(2048) DEFAULT ''                ,
501	poc_2_name               nvarchar2(128)  DEFAULT ''                ,
502	poc_2_email              nvarchar2(128)  DEFAULT ''                ,
503	poc_2_phone_a            nvarchar2(64)   DEFAULT ''                ,
504	poc_2_phone_b            nvarchar2(64)   DEFAULT ''                ,
505	poc_2_cell               nvarchar2(64)   DEFAULT ''                ,
506	poc_2_screen             nvarchar2(64)   DEFAULT ''                ,
507	poc_2_notes              nvarchar2(2048) DEFAULT ''                ,
508	PRIMARY KEY (hostid)
509);
510ALTER TABLE host_inventory ADD CONSTRAINT c_host_inventory_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
511
512-- create temporary t_host_inventory table
513CREATE TABLE t_host_inventory (
514	hostid                   number(20),
515	inventory_mode           number(10),
516	type                     nvarchar2(64),
517	type_full                nvarchar2(64),
518	name                     nvarchar2(64),
519	alias                    nvarchar2(64),
520	os                       nvarchar2(64),
521	os_full                  nvarchar2(255),
522	os_short                 nvarchar2(64),
523	serialno_a               nvarchar2(64),
524	serialno_b               nvarchar2(64),
525	tag                      nvarchar2(64),
526	asset_tag                nvarchar2(64),
527	macaddress_a             nvarchar2(64),
528	macaddress_b             nvarchar2(64),
529	hardware                 nvarchar2(255),
530	hardware_full            nvarchar2(2048),
531	software                 nvarchar2(255),
532	software_full            nvarchar2(2048),
533	software_app_a           nvarchar2(64),
534	software_app_b           nvarchar2(64),
535	software_app_c           nvarchar2(64),
536	software_app_d           nvarchar2(64),
537	software_app_e           nvarchar2(64),
538	contact                  nvarchar2(2048),
539	location                 nvarchar2(2048),
540	location_lat             nvarchar2(16),
541	location_lon             nvarchar2(16),
542	notes                    nvarchar2(2048),
543	chassis                  nvarchar2(64),
544	model                    nvarchar2(64),
545	hw_arch                  nvarchar2(32),
546	vendor                   nvarchar2(64),
547	contract_number          nvarchar2(64),
548	installer_name           nvarchar2(64),
549	deployment_status        nvarchar2(64),
550	url_a                    nvarchar2(255),
551	url_b                    nvarchar2(255),
552	url_c                    nvarchar2(255),
553	host_networks            nvarchar2(2048),
554	host_netmask             nvarchar2(39),
555	host_router              nvarchar2(39),
556	oob_ip                   nvarchar2(39),
557	oob_netmask              nvarchar2(39),
558	oob_router               nvarchar2(39),
559	date_hw_purchase         nvarchar2(64),
560	date_hw_install          nvarchar2(64),
561	date_hw_expiry           nvarchar2(64),
562	date_hw_decomm           nvarchar2(64),
563	site_address_a           nvarchar2(128),
564	site_address_b           nvarchar2(128),
565	site_address_c           nvarchar2(128),
566	site_city                nvarchar2(128),
567	site_state               nvarchar2(64),
568	site_country             nvarchar2(64),
569	site_zip                 nvarchar2(64),
570	site_rack                nvarchar2(128),
571	site_notes               nvarchar2(2048),
572	poc_1_name               nvarchar2(128),
573	poc_1_email              nvarchar2(128),
574	poc_1_phone_a            nvarchar2(64),
575	poc_1_phone_b            nvarchar2(64),
576	poc_1_cell               nvarchar2(64),
577	poc_1_screen             nvarchar2(64),
578	poc_1_notes              nvarchar2(2048),
579	poc_2_name               nvarchar2(128),
580	poc_2_email              nvarchar2(128),
581	poc_2_phone_a            nvarchar2(64),
582	poc_2_phone_b            nvarchar2(64),
583	poc_2_cell               nvarchar2(64),
584	poc_2_screen             nvarchar2(64),
585	poc_2_notes              nvarchar2(2048),
586	notes_ext                nvarchar2(2048)
587);
588
589-- select all profiles into temporary table
590INSERT INTO t_host_inventory
591	SELECT p.hostid,0,p.devicetype,ep.device_type,p.name,ep.device_alias,p.os,ep.device_os,ep.device_os_short,
592		p.serialno,ep.device_serial,p.tag,ep.device_tag,p.macaddress,ep.ip_macaddress,ep.device_hardware,
593		p.hardware,ep.device_software,p.software,ep.device_app_01,ep.device_app_02,ep.device_app_03,
594		ep.device_app_04,ep.device_app_05,p.contact,p.location,'','',p.notes,ep.device_chassis,ep.device_model,
595		ep.device_hw_arch,ep.device_vendor,ep.device_contract,ep.device_who,ep.device_status,ep.device_url_1,
596		ep.device_url_2,ep.device_url_3,ep.device_networks,ep.ip_subnet_mask,ep.ip_router,ep.oob_ip,
597		ep.oob_subnet_mask,ep.oob_router,ep.date_hw_buy,ep.date_hw_install,ep.date_hw_expiry,ep.date_hw_decomm,
598		ep.site_street_1,ep.site_street_2,ep.site_street_3,ep.site_city,ep.site_state,ep.site_country,
599		ep.site_zip,ep.site_rack,ep.site_notes,ep.poc_1_name,ep.poc_1_email,ep.poc_1_phone_1,ep.poc_1_phone_2,
600		ep.poc_1_cell,ep.poc_1_screen,ep.poc_1_notes,ep.poc_2_name,ep.poc_2_email,ep.poc_2_phone_1,
601		ep.poc_2_phone_2,ep.poc_2_cell,ep.poc_2_screen,ep.poc_2_notes,ep.device_notes
602	FROM hosts_profiles p LEFT JOIN hosts_profiles_ext ep on p.hostid=ep.hostid
603	UNION ALL
604	SELECT ep.hostid,0,p.devicetype,ep.device_type,p.name,ep.device_alias,p.os,ep.device_os,ep.device_os_short,
605		p.serialno,ep.device_serial,p.tag,ep.device_tag,p.macaddress,ep.ip_macaddress,ep.device_hardware,
606		p.hardware,ep.device_software,p.software,ep.device_app_01,ep.device_app_02,ep.device_app_03,
607		ep.device_app_04,ep.device_app_05,p.contact,p.location,'','',p.notes,ep.device_chassis,ep.device_model,
608		ep.device_hw_arch,ep.device_vendor,ep.device_contract,ep.device_who,ep.device_status,ep.device_url_1,
609		ep.device_url_2,ep.device_url_3,ep.device_networks,ep.ip_subnet_mask,ep.ip_router,ep.oob_ip,
610		ep.oob_subnet_mask,ep.oob_router,ep.date_hw_buy,ep.date_hw_install,ep.date_hw_expiry,ep.date_hw_decomm,
611		ep.site_street_1,ep.site_street_2,ep.site_street_3,ep.site_city,ep.site_state,ep.site_country,
612		ep.site_zip,ep.site_rack,ep.site_notes,ep.poc_1_name,ep.poc_1_email,ep.poc_1_phone_1,ep.poc_1_phone_2,
613		ep.poc_1_cell,ep.poc_1_screen,ep.poc_1_notes,ep.poc_2_name,ep.poc_2_email,ep.poc_2_phone_1,
614		ep.poc_2_phone_2,ep.poc_2_cell,ep.poc_2_screen,ep.poc_2_notes,ep.device_notes
615	FROM hosts_profiles p RIGHT JOIN hosts_profiles_ext ep on p.hostid=ep.hostid
616	WHERE p.hostid IS NULL;
617
618-- merge notes field
619UPDATE t_host_inventory SET notes = notes||CHR(13)||CHR(10)||notes_ext WHERE notes IS NOT NULL AND notes_ext IS NOT NULL;
620UPDATE t_host_inventory SET notes = notes_ext WHERE notes IS NULL;
621ALTER TABLE t_host_inventory DROP COLUMN notes_ext;
622
623-- copy data from temporary table
624INSERT INTO host_inventory SELECT * FROM t_host_inventory;
625
626DROP TABLE t_host_inventory;
627DROP TABLE hosts_profiles;
628DROP TABLE hosts_profiles_ext;
629
630DELETE FROM ids WHERE table_name IN ('hosts_profiles', 'hosts_profiles_ext');
631ALTER TABLE hostmacro MODIFY hostmacroid DEFAULT NULL;
632ALTER TABLE hostmacro MODIFY hostid DEFAULT NULL;
633DELETE FROM hostmacro WHERE NOT hostid IN (SELECT hostid FROM hosts);
634-- remove duplicates to allow unique index
635DELETE FROM hostmacro
636	WHERE hostmacroid IN (
637		SELECT hm1.hostmacroid
638		FROM hostmacro hm1
639		LEFT OUTER JOIN (
640			SELECT MIN(hm2.hostmacroid) AS hostmacroid
641			FROM hostmacro hm2
642			GROUP BY hm2.hostid,hm2.macro
643		) keep_rows ON
644			hm1.hostmacroid=keep_rows.hostmacroid
645		WHERE keep_rows.hostmacroid IS NULL
646	);
647DROP INDEX hostmacro_1;
648CREATE UNIQUE INDEX hostmacro_1 ON hostmacro (hostid,macro);
649ALTER TABLE hostmacro ADD CONSTRAINT c_hostmacro_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
650ALTER TABLE hosts_groups MODIFY hostgroupid DEFAULT NULL;
651ALTER TABLE hosts_groups MODIFY hostid DEFAULT NULL;
652ALTER TABLE hosts_groups MODIFY groupid DEFAULT NULL;
653DELETE FROM hosts_groups WHERE NOT hostid IN (SELECT hostid FROM hosts);
654DELETE FROM hosts_groups WHERE NOT groupid IN (SELECT groupid FROM groups);
655-- remove duplicates to allow unique index
656DELETE FROM hosts_groups
657	WHERE hostgroupid IN (
658		SELECT hg1.hostgroupid
659		FROM hosts_groups hg1
660		LEFT OUTER JOIN (
661			SELECT MIN(hg2.hostgroupid) AS hostgroupid
662			FROM hosts_groups hg2
663			GROUP BY hostid,groupid
664		) keep_rows ON
665			hg1.hostgroupid=keep_rows.hostgroupid
666		WHERE keep_rows.hostgroupid IS NULL
667	);
668DROP INDEX hosts_groups_1;
669CREATE UNIQUE INDEX hosts_groups_1 ON hosts_groups (hostid,groupid);
670ALTER TABLE hosts_groups ADD CONSTRAINT c_hosts_groups_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
671ALTER TABLE hosts_groups ADD CONSTRAINT c_hosts_groups_2 FOREIGN KEY (groupid) REFERENCES groups (groupid) ON DELETE CASCADE;
672-- See host_inventory.sql
673-- See host_inventory.sql
674---- Patching table `interfaces`
675
676CREATE TABLE interface (
677	interfaceid              number(20)                                NOT NULL,
678	hostid                   number(20)                                NOT NULL,
679	main                     number(10)      DEFAULT '0'               NOT NULL,
680	type                     number(10)      DEFAULT '0'               NOT NULL,
681	useip                    number(10)      DEFAULT '1'               NOT NULL,
682	ip                       nvarchar2(39)   DEFAULT '127.0.0.1'       ,
683	dns                      nvarchar2(64)   DEFAULT ''                ,
684	port                     nvarchar2(64)   DEFAULT '10050'           ,
685	PRIMARY KEY (interfaceid)
686);
687CREATE INDEX interface_1 on interface (hostid,type);
688CREATE INDEX interface_2 on interface (ip,dns);
689ALTER TABLE interface ADD CONSTRAINT c_interface_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
690
691-- Passive proxy interface
692INSERT INTO interface (interfaceid,hostid,main,type,ip,dns,useip,port)
693	(SELECT (hostid - (trunc(hostid / 100000000000)*100000000000)) * 3 + (trunc(hostid / 100000000000)*100000000000),
694		hostid,1,0,ip,dns,useip,port
695	FROM hosts
696	WHERE status IN (6));
697
698-- Zabbix Agent interface
699INSERT INTO interface (interfaceid,hostid,main,type,ip,dns,useip,port)
700	(SELECT (hostid - (trunc(hostid / 100000000000)*100000000000)) * 3 + (trunc(hostid / 100000000000)*100000000000),
701		hostid,1,1,ip,dns,useip,port
702	FROM hosts
703	WHERE status IN (0,1));
704
705-- SNMP interface
706INSERT INTO interface (interfaceid,hostid,main,type,ip,dns,useip,port)
707	(SELECT (hostid - (trunc(hostid / 100000000000)*100000000000)) * 3 + (trunc(hostid / 100000000000)*100000000000) + 1,
708		hostid,1,2,ip,dns,useip,'161'
709	FROM hosts
710	WHERE status IN (0,1)
711		AND EXISTS (SELECT DISTINCT i.hostid FROM items i WHERE i.hostid=hosts.hostid and i.type IN (1,4,6)));
712
713-- IPMI interface
714INSERT INTO interface (interfaceid,hostid,main,type,ip,dns,useip,port)
715	(SELECT (hostid - (trunc(hostid / 100000000000)*100000000000)) * 3 + (trunc(hostid / 100000000000)*100000000000) + 2,
716		hostid,1,3,'',ipmi_ip,0,ipmi_port
717	FROM hosts
718	WHERE status IN (0,1) AND useipmi=1);
719
720---- Patching table `items`
721
722ALTER TABLE items RENAME COLUMN description to name;
723ALTER TABLE items MODIFY (
724	itemid DEFAULT NULL,
725	hostid DEFAULT NULL,
726	units nvarchar2(255),
727	templateid DEFAULT NULL NULL,
728	lastlogsize number(20),
729	valuemapid DEFAULT NULL NULL
730);
731ALTER TABLE items ADD (
732	lastns number(10) NULL,
733	flags number(10) DEFAULT '0' NOT NULL,
734	filter nvarchar2(255) DEFAULT '',
735	interfaceid number(20) NULL,
736	port nvarchar2(64) DEFAULT '',
737	description nvarchar2(2048) DEFAULT '',
738	inventory_link number(10) DEFAULT '0' NOT NULL,
739	lifetime nvarchar2(64) DEFAULT '30'
740);
741UPDATE items
742	SET templateid=NULL
743	WHERE templateid=0
744		OR templateid NOT IN (SELECT itemid FROM items);
745UPDATE items
746	SET valuemapid=NULL
747	WHERE valuemapid=0
748		OR valuemapid NOT IN (SELECT valuemapid from valuemaps);
749UPDATE items SET units='Bps' WHERE type=9 AND units='bps';
750DELETE FROM items WHERE NOT hostid IN (SELECT hostid FROM hosts);
751ALTER TABLE items ADD CONSTRAINT c_items_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
752ALTER TABLE items ADD CONSTRAINT c_items_2 FOREIGN KEY (templateid) REFERENCES items (itemid) ON DELETE CASCADE;
753ALTER TABLE items ADD CONSTRAINT c_items_3 FOREIGN KEY (valuemapid) REFERENCES valuemaps (valuemapid);
754ALTER TABLE items ADD CONSTRAINT c_items_4 FOREIGN KEY (interfaceid) REFERENCES interface (interfaceid);
755
756UPDATE items SET port=snmp_port;
757ALTER TABLE items DROP COLUMN snmp_port;
758
759CREATE INDEX items_5 on items (valuemapid);
760
761-- host interface for non IPMI, SNMP and non templated items
762UPDATE items
763	SET interfaceid=(SELECT interfaceid FROM interface WHERE hostid=items.hostid AND main=1 AND type=1)
764	WHERE EXISTS (SELECT hostid FROM hosts WHERE hosts.hostid=items.hostid AND hosts.status IN (0,1))
765		AND type IN (0,3,10,11,13,14)	-- ZABBIX, SIMPLE, EXTERNAL, DB_MONITOR, SSH, TELNET
766/
767
768-- host interface for SNMP and non templated items
769UPDATE items
770	SET interfaceid=(SELECT interfaceid FROM interface WHERE hostid=items.hostid AND main=1 AND type=2)
771	WHERE EXISTS (SELECT hostid FROM hosts WHERE hosts.hostid=items.hostid AND hosts.status IN (0,1))
772		AND type IN (1,4,6)		-- SNMPv1, SNMPv2c, SNMPv3
773/
774
775-- host interface for IPMI and non templated items
776UPDATE items
777	SET interfaceid=(SELECT interfaceid FROM interface WHERE hostid=items.hostid AND main=1 AND type=3)
778	WHERE EXISTS (SELECT hostid FROM hosts WHERE hosts.hostid=items.hostid AND hosts.status IN (0,1))
779		AND type IN (12)		-- IPMI
780/
781
782-- clear port number for non SNMP items
783UPDATE items
784	SET port=''
785	WHERE type NOT IN (1,4,6)		-- SNMPv1, SNMPv2c, SNMPv3
786/
787
788-- add a first parameter {HOST.CONN} for external checks
789
790UPDATE items
791	SET key_ = SUBSTR(key_, 1, INSTR(key_, '[')) || '"{HOST.CONN}",' || SUBSTR(key_, INSTR(key_, '[') + 1)
792	WHERE type IN (10)	-- EXTERNAL
793		AND INSTR(key_, '[') <> 0;
794
795UPDATE items
796	SET key_ = key_ || '["{HOST.CONN}"]'
797	WHERE type IN (10)	-- EXTERNAL
798		AND INSTR(key_, '[') = 0;
799
800-- convert simple check keys to a new form
801
802CREATE FUNCTION zbx_key_exists(v_hostid IN number, new_key IN nvarchar2)
803	RETURN number IS key_exists number(10);
804	BEGIN
805		SELECT COUNT(*) INTO key_exists FROM items WHERE hostid = v_hostid AND key_ = new_key;
806		RETURN key_exists;
807	END;
808/
809
810DECLARE
811	v_itemid number(20);
812	v_hostid number(20);
813	v_key nvarchar2(255);
814	new_key nvarchar2(255);
815	pos number(10);
816
817	CURSOR i_cur IS
818		SELECT itemid,hostid,key_
819			FROM items
820			WHERE type IN (3)	-- SIMPLE
821				AND (key_ IN ('ftp','http','imap','ldap','nntp','ntp','pop','smtp','ssh',
822					'ftp_perf','http_perf', 'imap_perf','ldap_perf','nntp_perf','ntp_perf','pop_perf',
823					'smtp_perf','ssh_perf')
824					OR key_ LIKE 'ftp,%' OR key_ LIKE 'http,%' OR key_ LIKE 'imap,%' OR key_ LIKE 'ldap,%'
825					OR key_ LIKE 'nntp,%' OR key_ LIKE 'ntp,%' OR key_ LIKE 'pop,%' OR key_ LIKE 'smtp,%'
826					OR key_ LIKE 'ssh,%' OR key_ LIKE 'tcp,%'
827					OR key_ LIKE 'ftp_perf,%' OR key_ LIKE 'http_perf,%' OR key_ LIKE 'imap_perf,%'
828					OR key_ LIKE 'ldap_perf,%' OR key_ LIKE 'nntp_perf,%' OR key_ LIKE 'ntp_perf,%'
829					OR key_ LIKE 'pop_perf,%' OR key_ LIKE 'smtp_perf,%' OR key_ LIKE 'ssh_perf,%'
830					OR key_ LIKE 'tcp_perf,%');
831BEGIN
832	OPEN i_cur;
833
834	LOOP
835		FETCH i_cur INTO v_itemid, v_hostid, v_key;
836
837		EXIT WHEN i_cur%NOTFOUND;
838
839		new_key := 'net.tcp.service';
840		pos := INSTR(v_key, '_perf');
841		IF 0 <> pos THEN
842			new_key := new_key || '.perf';
843			v_key := SUBSTR(v_key, 1, pos - 1) || SUBSTR(v_key, pos + 5);
844		END IF;
845		new_key := new_key || '[';
846		pos := INSTR(v_key, ',');
847		IF 0 <> pos THEN
848			new_key := new_key || '"' || SUBSTR(v_key, 1, pos - 1) || '"';
849			v_key := SUBSTR(v_key, pos + 1);
850		ELSE
851			new_key := new_key || '"' || v_key || '"';
852			v_key := '';
853		END IF;
854		IF 0 <> LENGTH(v_key) THEN
855			new_key := new_key || ',,"' || v_key || '"';
856		END IF;
857
858		WHILE 0 <> zbx_key_exists(v_hostid, new_key || ']') LOOP
859			new_key := new_key || ' ';
860		END LOOP;
861
862		new_key := new_key || ']';
863
864		UPDATE items SET key_ = new_key WHERE itemid = v_itemid;
865	END LOOP;
866
867	CLOSE i_cur;
868END;
869/
870
871DROP FUNCTION zbx_key_exists;
872
873-- adding web.test.error[<web check>] items
874
875DECLARE
876	httptest_nodeid number(10);
877	min_nodeid number(20);
878	max_nodeid number(20);
879	init_nodeid number(20);
880	CURSOR node_cursor IS SELECT DISTINCT TRUNC(httptestid / 100000000000000) FROM httptest;
881
882	max_itemid number(20);
883	max_httptestitemid number(20);
884	max_itemappid number(20);
885BEGIN
886	OPEN node_cursor;
887
888	LOOP
889		FETCH node_cursor INTO httptest_nodeid;
890		EXIT WHEN node_cursor%NOTFOUND;
891
892		min_nodeid := httptest_nodeid * 100000000000000;
893		max_nodeid := min_nodeid + 99999999999999;
894		init_nodeid := (httptest_nodeid * 1000 + httptest_nodeid) * 100000000000;
895
896		SELECT MAX(itemid) INTO max_itemid FROM items WHERE itemid BETWEEN min_nodeid AND max_nodeid;
897		IF max_itemid IS NULL THEN
898			max_itemid := init_nodeid;
899		END IF;
900		EXECUTE IMMEDIATE 'CREATE SEQUENCE items_seq MINVALUE ' || (max_itemid + 1);
901
902		SELECT MAX(httptestitemid) INTO max_httptestitemid FROM httptestitem WHERE httptestitemid BETWEEN min_nodeid AND max_nodeid;
903		IF max_httptestitemid IS NULL THEN
904			max_httptestitemid := init_nodeid;
905		END IF;
906		EXECUTE IMMEDIATE 'CREATE SEQUENCE httptestitem_seq MINVALUE ' || (max_httptestitemid + 1);
907
908		SELECT MAX(itemappid) INTO max_itemappid FROM items_applications WHERE itemappid BETWEEN min_nodeid AND max_nodeid;
909		IF max_itemappid IS NULL THEN
910			max_itemappid := init_nodeid;
911		END IF;
912		EXECUTE IMMEDIATE 'CREATE SEQUENCE items_applications_seq MINVALUE ' || (max_itemappid + 1);
913
914		EXECUTE IMMEDIATE 'INSERT INTO items (itemid, hostid, type, name, key_, value_type, units, delay, history, trends, status)
915			SELECT items_seq.NEXTVAL, hostid, type, ''Last error message of scenario ''''$1'''''', ''web.test.error'' || SUBSTR(key_, INSTR(key_, ''['')), 1, '''', delay, history, 0, status
916			FROM items
917			WHERE type = 9
918				AND key_ LIKE ''web.test.fail%''
919				AND itemid BETWEEN ' || min_nodeid ||' AND ' || max_nodeid;
920
921		EXECUTE IMMEDIATE 'INSERT INTO httptestitem (httptestitemid, httptestid, itemid, type)
922			SELECT httptestitem_seq.NEXTVAL, ht.httptestid, i.itemid, 4
923			FROM httptest ht,applications a,items i
924			WHERE ht.applicationid=a.applicationid
925				AND a.hostid=i.hostid
926				AND ''web.test.error['' || ht.name || '']'' = i.key_
927				AND itemid BETWEEN ' || min_nodeid ||' AND ' || max_nodeid;
928
929		EXECUTE IMMEDIATE 'INSERT INTO items_applications (itemappid, applicationid, itemid)
930			SELECT items_applications_seq.NEXTVAL, ht.applicationid, hti.itemid
931			FROM httptest ht, httptestitem hti
932			WHERE ht.httptestid = hti.httptestid
933				AND hti.type = 4
934				AND itemid BETWEEN ' || min_nodeid ||' AND ' || max_nodeid;
935
936		EXECUTE IMMEDIATE 'DROP SEQUENCE items_seq';
937		EXECUTE IMMEDIATE 'DROP SEQUENCE httptestitem_seq';
938		EXECUTE IMMEDIATE 'DROP SEQUENCE items_applications_seq';
939
940	END LOOP;
941
942	CLOSE node_cursor;
943END;
944/
945
946DELETE FROM ids WHERE table_name IN ('items', 'httptestitem', 'items_applications');
947
948---- Patching table `hosts`
949
950ALTER TABLE hosts MODIFY hostid DEFAULT NULL;
951ALTER TABLE hosts MODIFY proxy_hostid DEFAULT NULL;
952ALTER TABLE hosts MODIFY proxy_hostid NULL;
953ALTER TABLE hosts MODIFY maintenanceid DEFAULT NULL;
954ALTER TABLE hosts MODIFY maintenanceid NULL;
955ALTER TABLE hosts DROP COLUMN ip;
956ALTER TABLE hosts DROP COLUMN dns;
957ALTER TABLE hosts DROP COLUMN port;
958ALTER TABLE hosts DROP COLUMN useip;
959ALTER TABLE hosts DROP COLUMN useipmi;
960ALTER TABLE hosts DROP COLUMN ipmi_ip;
961ALTER TABLE hosts DROP COLUMN ipmi_port;
962ALTER TABLE hosts DROP COLUMN inbytes;
963ALTER TABLE hosts DROP COLUMN outbytes;
964ALTER TABLE hosts ADD jmx_disable_until number(10) DEFAULT '0' NOT NULL;
965ALTER TABLE hosts ADD jmx_available number(10) DEFAULT '0' NOT NULL;
966ALTER TABLE hosts ADD jmx_errors_from number(10) DEFAULT '0' NOT NULL;
967ALTER TABLE hosts ADD jmx_error nvarchar2(128) DEFAULT '';
968ALTER TABLE hosts ADD name nvarchar2(64) DEFAULT '';
969UPDATE hosts
970	SET proxy_hostid=NULL
971	WHERE proxy_hostid=0
972		OR NOT EXISTS (SELECT 1 FROM hosts h WHERE h.hostid=hosts.proxy_hostid);
973UPDATE hosts
974	SET maintenanceid=NULL,
975		maintenance_status=0,
976		maintenance_type=0,
977		maintenance_from=0
978	WHERE maintenanceid=0
979		OR NOT EXISTS (SELECT 1 FROM maintenances m WHERE m.maintenanceid=hosts.maintenanceid);
980UPDATE hosts SET name=host WHERE status in (0,1,3)	-- MONITORED, NOT_MONITORED, TEMPLATE
981/
982CREATE INDEX hosts_4 on hosts (name);
983ALTER TABLE hosts ADD CONSTRAINT c_hosts_1 FOREIGN KEY (proxy_hostid) REFERENCES hosts (hostid);
984ALTER TABLE hosts ADD CONSTRAINT c_hosts_2 FOREIGN KEY (maintenanceid) REFERENCES maintenances (maintenanceid);
985DELETE FROM hosts_templates WHERE hostid NOT IN (SELECT hostid FROM hosts);
986DELETE FROM hosts_templates WHERE templateid NOT IN (SELECT hostid FROM hosts);
987
988CREATE TABLE t_hosts_templates (
989	hosttemplateid           number(20)                                NOT NULL,
990	hostid                   number(20)                                NOT NULL,
991	templateid               number(20)                                NOT NULL
992);
993
994INSERT INTO t_hosts_templates (SELECT hosttemplateid, hostid, templateid FROM hosts_templates);
995
996DROP TABLE hosts_templates;
997
998CREATE TABLE hosts_templates (
999	hosttemplateid           number(20)                                NOT NULL,
1000	hostid                   number(20)                                NOT NULL,
1001	templateid               number(20)                                NOT NULL,
1002	PRIMARY KEY (hosttemplateid)
1003);
1004CREATE UNIQUE INDEX hosts_templates_1 ON hosts_templates (hostid,templateid);
1005CREATE INDEX hosts_templates_2 ON hosts_templates (templateid);
1006ALTER TABLE hosts_templates ADD CONSTRAINT c_hosts_templates_1 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
1007ALTER TABLE hosts_templates ADD CONSTRAINT c_hosts_templates_2 FOREIGN KEY (templateid) REFERENCES hosts (hostid) ON DELETE CASCADE;
1008
1009INSERT INTO hosts_templates (SELECT hosttemplateid, hostid, templateid FROM t_hosts_templates);
1010
1011DROP TABLE t_hosts_templates;
1012ALTER TABLE housekeeper MODIFY housekeeperid DEFAULT NULL;
1013ALTER TABLE housekeeper MODIFY value DEFAULT NULL;
1014ALTER TABLE httpstepitem MODIFY httpstepitemid DEFAULT NULL;
1015ALTER TABLE httpstepitem MODIFY httpstepid DEFAULT NULL;
1016ALTER TABLE httpstepitem MODIFY itemid DEFAULT NULL;
1017DELETE FROM httpstepitem WHERE NOT httpstepid IN (SELECT httpstepid FROM httpstep);
1018DELETE FROM httpstepitem WHERE NOT itemid IN (SELECT itemid FROM items);
1019ALTER TABLE httpstepitem ADD CONSTRAINT c_httpstepitem_1 FOREIGN KEY (httpstepid) REFERENCES httpstep (httpstepid) ON DELETE CASCADE;
1020ALTER TABLE httpstepitem ADD CONSTRAINT c_httpstepitem_2 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
1021ALTER TABLE httpstep MODIFY httpstepid DEFAULT NULL;
1022ALTER TABLE httpstep MODIFY httptestid DEFAULT NULL;
1023DELETE FROM httpstep WHERE NOT httptestid IN (SELECT httptestid FROM httptest);
1024ALTER TABLE httpstep ADD CONSTRAINT c_httpstep_1 FOREIGN KEY (httptestid) REFERENCES httptest (httptestid) ON DELETE CASCADE;
1025ALTER TABLE httptestitem MODIFY httptestitemid DEFAULT NULL;
1026ALTER TABLE httptestitem MODIFY httptestid DEFAULT NULL;
1027ALTER TABLE httptestitem MODIFY itemid DEFAULT NULL;
1028DELETE FROM httptestitem WHERE NOT httptestid IN (SELECT httptestid FROM httptest);
1029DELETE FROM httptestitem WHERE NOT itemid IN (SELECT itemid FROM items);
1030ALTER TABLE httptestitem ADD CONSTRAINT c_httptestitem_1 FOREIGN KEY (httptestid) REFERENCES httptest (httptestid) ON DELETE CASCADE;
1031ALTER TABLE httptestitem ADD CONSTRAINT c_httptestitem_2 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
1032ALTER TABLE httptest MODIFY httptestid DEFAULT NULL;
1033ALTER TABLE httptest MODIFY applicationid DEFAULT NULL;
1034ALTER TABLE httptest DROP COLUMN lastcheck;
1035ALTER TABLE httptest DROP COLUMN curstate;
1036ALTER TABLE httptest DROP COLUMN curstep;
1037ALTER TABLE httptest DROP COLUMN lastfailedstep;
1038ALTER TABLE httptest DROP COLUMN time;
1039ALTER TABLE httptest DROP COLUMN error;
1040DELETE FROM httptest WHERE applicationid NOT IN (SELECT applicationid FROM applications);
1041ALTER TABLE httptest ADD CONSTRAINT c_httptest_1 FOREIGN KEY (applicationid) REFERENCES applications (applicationid) ON DELETE CASCADE;
1042-- See icon_map.sql
1043CREATE TABLE icon_map (
1044	iconmapid                number(20)                                NOT NULL,
1045	name                     nvarchar2(64)   DEFAULT ''                ,
1046	default_iconid           number(20)                                NOT NULL,
1047	PRIMARY KEY (iconmapid)
1048);
1049CREATE INDEX icon_map_1 ON icon_map (name);
1050ALTER TABLE icon_map ADD CONSTRAINT c_icon_map_1 FOREIGN KEY (default_iconid) REFERENCES images (imageid);
1051
1052CREATE TABLE icon_mapping (
1053	iconmappingid            number(20)                                NOT NULL,
1054	iconmapid                number(20)                                NOT NULL,
1055	iconid                   number(20)                                NOT NULL,
1056	inventory_link           number(10)      DEFAULT '0'               NOT NULL,
1057	expression               nvarchar2(64)   DEFAULT ''                ,
1058	sortorder                number(10)      DEFAULT '0'               NOT NULL,
1059	PRIMARY KEY (iconmappingid)
1060);
1061CREATE INDEX icon_mapping_1 ON icon_mapping (iconmapid);
1062ALTER TABLE icon_mapping ADD CONSTRAINT c_icon_mapping_1 FOREIGN KEY (iconmapid) REFERENCES icon_map (iconmapid) ON DELETE CASCADE;
1063ALTER TABLE icon_mapping ADD CONSTRAINT c_icon_mapping_2 FOREIGN KEY (iconid) REFERENCES images (imageid);
1064ALTER TABLE ids MODIFY nodeid DEFAULT NULL;
1065ALTER TABLE ids MODIFY nextid DEFAULT NULL;
1066ALTER TABLE images MODIFY imageid DEFAULT NULL;
1067-- See hosts.sql
1068CREATE TABLE item_discovery (
1069	itemdiscoveryid          number(20)                                NOT NULL,
1070	itemid                   number(20)                                NOT NULL,
1071	parent_itemid            number(20)                                NOT NULL,
1072	key_                     nvarchar2(255)  DEFAULT ''                ,
1073	lastcheck                number(10)      DEFAULT '0'               NOT NULL,
1074	ts_delete                number(10)      DEFAULT '0'               NOT NULL,
1075	PRIMARY KEY (itemdiscoveryid)
1076);
1077CREATE UNIQUE INDEX item_discovery_1 on item_discovery (itemid,parent_itemid);
1078ALTER TABLE item_discovery ADD CONSTRAINT c_item_discovery_1 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
1079ALTER TABLE item_discovery ADD CONSTRAINT c_item_discovery_2 FOREIGN KEY (parent_itemid) REFERENCES items (itemid) ON DELETE CASCADE;
1080ALTER TABLE items_applications MODIFY itemappid DEFAULT NULL;
1081ALTER TABLE items_applications MODIFY applicationid DEFAULT NULL;
1082ALTER TABLE items_applications MODIFY itemid DEFAULT NULL;
1083DROP INDEX items_applications_1;
1084DELETE FROM items_applications WHERE applicationid NOT IN (SELECT applicationid FROM applications);
1085DELETE FROM items_applications WHERE itemid NOT IN (SELECT itemid FROM items);
1086CREATE UNIQUE INDEX items_applications_1 ON items_applications (applicationid,itemid);
1087ALTER TABLE items_applications ADD CONSTRAINT c_items_applications_1 FOREIGN KEY (applicationid) REFERENCES applications (applicationid) ON DELETE CASCADE;
1088ALTER TABLE items_applications ADD CONSTRAINT c_items_applications_2 FOREIGN KEY (itemid) REFERENCES items (itemid) ON DELETE CASCADE;
1089-- See hosts.sql
1090ALTER TABLE maintenances_groups MODIFY maintenance_groupid DEFAULT NULL;
1091ALTER TABLE maintenances_groups MODIFY maintenanceid DEFAULT NULL;
1092ALTER TABLE maintenances_groups MODIFY groupid DEFAULT NULL;
1093DROP INDEX maintenances_groups_1;
1094DELETE FROM maintenances_groups WHERE maintenanceid NOT IN (SELECT maintenanceid FROM maintenances);
1095DELETE FROM maintenances_groups WHERE groupid NOT IN (SELECT groupid FROM groups);
1096CREATE UNIQUE INDEX maintenances_groups_1 ON maintenances_groups (maintenanceid,groupid);
1097ALTER TABLE maintenances_groups ADD CONSTRAINT c_maintenances_groups_1 FOREIGN KEY (maintenanceid) REFERENCES maintenances (maintenanceid) ON DELETE CASCADE;
1098ALTER TABLE maintenances_groups ADD CONSTRAINT c_maintenances_groups_2 FOREIGN KEY (groupid) REFERENCES groups (groupid) ON DELETE CASCADE;
1099ALTER TABLE maintenances_hosts MODIFY maintenance_hostid DEFAULT NULL;
1100ALTER TABLE maintenances_hosts MODIFY maintenanceid DEFAULT NULL;
1101ALTER TABLE maintenances_hosts MODIFY hostid DEFAULT NULL;
1102DROP INDEX maintenances_hosts_1;
1103DELETE FROM maintenances_hosts WHERE maintenanceid NOT IN (SELECT maintenanceid FROM maintenances);
1104DELETE FROM maintenances_hosts WHERE hostid NOT IN (SELECT hostid FROM hosts);
1105CREATE UNIQUE INDEX maintenances_hosts_1 ON maintenances_hosts (maintenanceid,hostid);
1106ALTER TABLE maintenances_hosts ADD CONSTRAINT c_maintenances_hosts_1 FOREIGN KEY (maintenanceid) REFERENCES maintenances (maintenanceid) ON DELETE CASCADE;
1107ALTER TABLE maintenances_hosts ADD CONSTRAINT c_maintenances_hosts_2 FOREIGN KEY (hostid) REFERENCES hosts (hostid) ON DELETE CASCADE;
1108ALTER TABLE maintenances MODIFY maintenanceid DEFAULT NULL;
1109ALTER TABLE maintenances_windows MODIFY maintenance_timeperiodid DEFAULT NULL;
1110ALTER TABLE maintenances_windows MODIFY maintenanceid DEFAULT NULL;
1111ALTER TABLE maintenances_windows MODIFY timeperiodid DEFAULT NULL;
1112DROP INDEX maintenances_windows_1;
1113DELETE FROM maintenances_windows WHERE maintenanceid NOT IN (SELECT maintenanceid FROM maintenances);
1114DELETE FROM maintenances_windows WHERE timeperiodid NOT IN (SELECT timeperiodid FROM timeperiods);
1115CREATE UNIQUE INDEX maintenances_windows_1 ON maintenances_windows (maintenanceid,timeperiodid);
1116ALTER TABLE maintenances_windows ADD CONSTRAINT c_maintenances_windows_1 FOREIGN KEY (maintenanceid) REFERENCES maintenances (maintenanceid) ON DELETE CASCADE;
1117ALTER TABLE maintenances_windows ADD CONSTRAINT c_maintenances_windows_2 FOREIGN KEY (timeperiodid) REFERENCES timeperiods (timeperiodid) ON DELETE CASCADE;
1118ALTER TABLE mappings MODIFY mappingid DEFAULT NULL;
1119ALTER TABLE mappings MODIFY valuemapid DEFAULT NULL;
1120DELETE FROM mappings WHERE NOT valuemapid IN (SELECT valuemapid FROM valuemaps);
1121ALTER TABLE mappings ADD CONSTRAINT c_mappings_1 FOREIGN KEY (valuemapid) REFERENCES valuemaps (valuemapid) ON DELETE CASCADE;
1122ALTER TABLE media MODIFY mediaid DEFAULT NULL;
1123ALTER TABLE media MODIFY userid DEFAULT NULL;
1124ALTER TABLE media MODIFY mediatypeid DEFAULT NULL;
1125ALTER TABLE media MODIFY period DEFAULT '1-7,00:00-24:00';
1126DELETE FROM media WHERE NOT userid IN (SELECT userid FROM users);
1127DELETE FROM media WHERE NOT mediatypeid IN (SELECT mediatypeid FROM media_type);
1128ALTER TABLE media ADD CONSTRAINT c_media_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
1129ALTER TABLE media ADD CONSTRAINT c_media_2 FOREIGN KEY (mediatypeid) REFERENCES media_type (mediatypeid) ON DELETE CASCADE;
1130ALTER TABLE media_type MODIFY mediatypeid DEFAULT NULL;
1131ALTER TABLE media_type ADD status number(10) DEFAULT '0' NOT NULL;
1132DECLARE index_not_exists EXCEPTION;
1133PRAGMA EXCEPTION_INIT(index_not_exists, -1418);
1134BEGIN
1135	EXECUTE IMMEDIATE 'DROP INDEX NODE_CKSUM_1';
1136EXCEPTION
1137	WHEN index_not_exists THEN NULL;
1138END;
1139/
1140DECLARE index_not_exists EXCEPTION;
1141PRAGMA EXCEPTION_INIT(index_not_exists, -1418);
1142BEGIN
1143	EXECUTE IMMEDIATE 'DROP INDEX NODE_CKSUM_CKSUM_1';
1144EXCEPTION
1145	WHEN index_not_exists THEN NULL;
1146END;
1147/
1148ALTER TABLE node_cksum MODIFY nodeid DEFAULT NULL;
1149ALTER TABLE node_cksum MODIFY recordid DEFAULT NULL;
1150DELETE FROM node_cksum WHERE NOT nodeid IN (SELECT nodeid FROM nodes);
1151CREATE INDEX node_cksum_1 ON node_cksum (nodeid,cksumtype,tablename,recordid);
1152ALTER TABLE node_cksum ADD CONSTRAINT c_node_cksum_1 FOREIGN KEY (nodeid) REFERENCES nodes (nodeid) ON DELETE CASCADE;
1153ALTER TABLE nodes MODIFY nodeid DEFAULT NULL;
1154ALTER TABLE nodes MODIFY masterid DEFAULT NULL;
1155ALTER TABLE nodes MODIFY masterid NULL;
1156ALTER TABLE nodes DROP COLUMN timezone;
1157ALTER TABLE nodes DROP COLUMN slave_history;
1158ALTER TABLE nodes DROP COLUMN slave_trends;
1159UPDATE nodes SET masterid=NULL WHERE masterid=0;
1160ALTER TABLE nodes ADD CONSTRAINT c_nodes_1 FOREIGN KEY (masterid) REFERENCES nodes (nodeid);
1161-- See operations.sql
1162-- See operations.sql
1163-- See operations.sql
1164CREATE TABLE t_operations (
1165	operationid		number(20),
1166	actionid		number(20),
1167	operationtype		number(10),
1168	object			number(10),
1169	objectid		number(20),
1170	shortdata		nvarchar2(255),
1171	longdata		nvarchar2(2048),
1172	esc_period		number(10),
1173	esc_step_from		number(10),
1174	esc_step_to		number(10),
1175	default_msg		number(10),
1176	evaltype		number(10),
1177	mediatypeid		number(20)
1178);
1179
1180CREATE TABLE t_opconditions (
1181	operationid		number(20),
1182	conditiontype		number(10),
1183	operator		number(10),
1184	value			nvarchar2(255)
1185);
1186
1187INSERT INTO t_operations
1188	SELECT o.operationid, o.actionid, o.operationtype, o.object, o.objectid, o.shortdata, o.longdata,
1189			o.esc_period, o.esc_step_from, o.esc_step_to, o.default_msg, o.evaltype, omt.mediatypeid
1190		FROM actions a, operations o
1191			LEFT JOIN opmediatypes omt ON omt.operationid=o.operationid
1192		WHERE a.actionid=o.actionid;
1193
1194INSERT INTO t_opconditions
1195	SELECT operationid, conditiontype, operator, value FROM opconditions;
1196
1197UPDATE t_operations
1198	SET mediatypeid = NULL
1199	WHERE NOT EXISTS (SELECT 1 FROM media_type mt WHERE mt.mediatypeid = t_operations.mediatypeid);
1200
1201UPDATE t_operations
1202	SET objectid = NULL
1203	WHERE operationtype = 0		-- OPERATION_TYPE_MESSAGE
1204		AND object = 0		-- OPERATION_OBJECT_USER
1205		AND NOT EXISTS (SELECT 1 FROM users u WHERE u.userid = t_operations.objectid);
1206
1207UPDATE t_operations
1208	SET objectid = NULL
1209	WHERE operationtype = 0		-- OPERATION_TYPE_MESSAGE
1210		AND object = 1		-- OPERATION_OBJECT_GROUP
1211		AND NOT EXISTS (SELECT 1 FROM usrgrp g WHERE g.usrgrpid = t_operations.objectid);
1212
1213DELETE FROM t_operations
1214	WHERE operationtype IN (4,5)	-- OPERATION_TYPE_GROUP_ADD, OPERATION_TYPE_GROUP_REMOVE
1215		AND NOT EXISTS (SELECT 1 FROM groups g WHERE g.groupid = t_operations.objectid);
1216
1217DELETE FROM t_operations
1218	WHERE operationtype IN (6,7)	-- OPERATION_TYPE_TEMPLATE_ADD, OPERATION_TYPE_TEMPLATE_REMOVE
1219		AND NOT EXISTS (SELECT 1 FROM hosts h WHERE h.hostid = t_operations.objectid);
1220
1221DROP TABLE operations;
1222DROP TABLE opmediatypes;
1223DROP TABLE opconditions;
1224
1225CREATE TABLE operations (
1226	operationid              number(20)                                NOT NULL,
1227	actionid                 number(20)                                NOT NULL,
1228	operationtype            number(10)      DEFAULT '0'               NOT NULL,
1229	esc_period               number(10)      DEFAULT '0'               NOT NULL,
1230	esc_step_from            number(10)      DEFAULT '1'               NOT NULL,
1231	esc_step_to              number(10)      DEFAULT '1'               NOT NULL,
1232	evaltype                 number(10)      DEFAULT '0'               NOT NULL,
1233	PRIMARY KEY (operationid)
1234);
1235CREATE INDEX operations_1 ON operations (actionid);
1236ALTER TABLE operations ADD CONSTRAINT c_operations_1 FOREIGN KEY (actionid) REFERENCES actions (actionid) ON DELETE CASCADE;
1237
1238CREATE TABLE opmessage (
1239	operationid              number(20)                                NOT NULL,
1240	default_msg              number(10)      DEFAULT '0'               NOT NULL,
1241	subject                  nvarchar2(255)  DEFAULT ''                ,
1242	message                  nvarchar2(2048) DEFAULT ''                ,
1243	mediatypeid              number(20)                                NULL,
1244	PRIMARY KEY (operationid)
1245);
1246ALTER TABLE opmessage ADD CONSTRAINT c_opmessage_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1247ALTER TABLE opmessage ADD CONSTRAINT c_opmessage_2 FOREIGN KEY (mediatypeid) REFERENCES media_type (mediatypeid);
1248
1249CREATE TABLE opmessage_grp (
1250	opmessage_grpid          number(20)                                NOT NULL,
1251	operationid              number(20)                                NOT NULL,
1252	usrgrpid                 number(20)                                NOT NULL,
1253	PRIMARY KEY (opmessage_grpid)
1254);
1255CREATE UNIQUE INDEX opmessage_grp_1 ON opmessage_grp (operationid,usrgrpid);
1256ALTER TABLE opmessage_grp ADD CONSTRAINT c_opmessage_grp_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1257ALTER TABLE opmessage_grp ADD CONSTRAINT c_opmessage_grp_2 FOREIGN KEY (usrgrpid) REFERENCES usrgrp (usrgrpid);
1258
1259CREATE TABLE opmessage_usr (
1260	opmessage_usrid          number(20)                                NOT NULL,
1261	operationid              number(20)                                NOT NULL,
1262	userid                   number(20)                                NOT NULL,
1263	PRIMARY KEY (opmessage_usrid)
1264);
1265CREATE UNIQUE INDEX opmessage_usr_1 ON opmessage_usr (operationid,userid);
1266ALTER TABLE opmessage_usr ADD CONSTRAINT c_opmessage_usr_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1267ALTER TABLE opmessage_usr ADD CONSTRAINT c_opmessage_usr_2 FOREIGN KEY (userid) REFERENCES users (userid);
1268
1269CREATE TABLE opcommand (
1270	operationid              number(20)                                NOT NULL,
1271	type                     number(10)      DEFAULT '0'               NOT NULL,
1272	scriptid                 number(20)                                NULL,
1273	execute_on               number(10)      DEFAULT '0'               NOT NULL,
1274	port                     nvarchar2(64)   DEFAULT ''                ,
1275	authtype                 number(10)      DEFAULT '0'               NOT NULL,
1276	username                 nvarchar2(64)   DEFAULT ''                ,
1277	password                 nvarchar2(64)   DEFAULT ''                ,
1278	publickey                nvarchar2(64)   DEFAULT ''                ,
1279	privatekey               nvarchar2(64)   DEFAULT ''                ,
1280	command                  nvarchar2(2048) DEFAULT ''                ,
1281	PRIMARY KEY (operationid)
1282);
1283ALTER TABLE opcommand ADD CONSTRAINT c_opcommand_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1284ALTER TABLE opcommand ADD CONSTRAINT c_opcommand_2 FOREIGN KEY (scriptid) REFERENCES scripts (scriptid);
1285
1286CREATE TABLE opcommand_hst (
1287	opcommand_hstid          number(20)                                NOT NULL,
1288	operationid              number(20)                                NOT NULL,
1289	hostid                   number(20)                                NULL,
1290	PRIMARY KEY (opcommand_hstid)
1291);
1292CREATE INDEX opcommand_hst_1 ON opcommand_hst (operationid);
1293ALTER TABLE opcommand_hst ADD CONSTRAINT c_opcommand_hst_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1294ALTER TABLE opcommand_hst ADD CONSTRAINT c_opcommand_hst_2 FOREIGN KEY (hostid) REFERENCES hosts (hostid);
1295
1296CREATE TABLE opcommand_grp (
1297	opcommand_grpid          number(20)                                NOT NULL,
1298	operationid              number(20)                                NOT NULL,
1299	groupid                  number(20)                                NOT NULL,
1300	PRIMARY KEY (opcommand_grpid)
1301);
1302CREATE INDEX opcommand_grp_1 ON opcommand_grp (operationid);
1303ALTER TABLE opcommand_grp ADD CONSTRAINT c_opcommand_grp_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1304ALTER TABLE opcommand_grp ADD CONSTRAINT c_opcommand_grp_2 FOREIGN KEY (groupid) REFERENCES groups (groupid);
1305
1306CREATE TABLE opgroup (
1307	opgroupid                number(20)                                NOT NULL,
1308	operationid              number(20)                                NOT NULL,
1309	groupid                  number(20)                                NOT NULL,
1310	PRIMARY KEY (opgroupid)
1311);
1312CREATE UNIQUE INDEX opgroup_1 ON opgroup (operationid,groupid);
1313ALTER TABLE opgroup ADD CONSTRAINT c_opgroup_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1314ALTER TABLE opgroup ADD CONSTRAINT c_opgroup_2 FOREIGN KEY (groupid) REFERENCES groups (groupid);
1315
1316CREATE TABLE optemplate (
1317	optemplateid             number(20)                                NOT NULL,
1318	operationid              number(20)                                NOT NULL,
1319	templateid               number(20)                                NOT NULL,
1320	PRIMARY KEY (optemplateid)
1321);
1322CREATE UNIQUE INDEX optemplate_1 ON optemplate (operationid,templateid);
1323ALTER TABLE optemplate ADD CONSTRAINT c_optemplate_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1324ALTER TABLE optemplate ADD CONSTRAINT c_optemplate_2 FOREIGN KEY (templateid) REFERENCES hosts (hostid);
1325
1326CREATE TABLE opconditions (
1327	opconditionid            number(20)                                NOT NULL,
1328	operationid              number(20)                                NOT NULL,
1329	conditiontype            number(10)      DEFAULT '0'               NOT NULL,
1330	operator                 number(10)      DEFAULT '0'               NOT NULL,
1331	value                    nvarchar2(255)  DEFAULT ''                ,
1332	PRIMARY KEY (opconditionid)
1333);
1334CREATE INDEX opconditions_1 ON opconditions (operationid);
1335ALTER TABLE opconditions ADD CONSTRAINT c_opconditions_1 FOREIGN KEY (operationid) REFERENCES operations (operationid) ON DELETE CASCADE;
1336
1337CREATE SEQUENCE opconditions_seq;
1338
1339DECLARE
1340	v_nodeid number(10);
1341	minid number(20);
1342	maxid number(20);
1343	new_operationid number(20);
1344	new_opmessage_grpid number(20);
1345	new_opmessage_usrid number(20);
1346	new_opgroupid number(20);
1347	new_optemplateid number(20);
1348	new_opcommand_hstid number(20);
1349	new_opcommand_grpid number(20);
1350
1351	CURSOR n_cur IS SELECT DISTINCT TRUNC(operationid / 100000000000000) FROM t_operations;
1352BEGIN
1353	OPEN n_cur;
1354
1355	LOOP
1356		FETCH n_cur INTO v_nodeid;
1357
1358		EXIT WHEN n_cur%NOTFOUND;
1359
1360		minid := v_nodeid * 100000000000000;
1361		maxid := minid + 99999999999999;
1362		new_operationid := minid;
1363		new_opmessage_grpid := minid;
1364		new_opmessage_usrid := minid;
1365		new_opgroupid := minid;
1366		new_optemplateid := minid;
1367		new_opcommand_hstid := minid;
1368		new_opcommand_grpid := minid;
1369
1370		DECLARE
1371			v_operationid number(20);
1372			v_actionid number(20);
1373			v_operationtype number(10);
1374			v_esc_period number(10);
1375			v_esc_step_from number(10);
1376			v_esc_step_to number(10);
1377			v_evaltype number(10);
1378			v_default_msg number(10);
1379			v_shortdata nvarchar2(255);
1380			v_longdata nvarchar2(2048);
1381			v_mediatypeid number(20);
1382			v_object number(10);
1383			v_objectid number(20);
1384			l_pos number(10);
1385			r_pos number(10);
1386			h_pos number(10);
1387			g_pos number(10);
1388			cur_string nvarchar2(2048);
1389			v_host nvarchar2(64);
1390			v_group nvarchar2(64);
1391			v_hostid number(20);
1392			v_groupid number(20);
1393			CURSOR o_cur IS
1394				SELECT operationid, actionid, operationtype, esc_period, esc_step_from, esc_step_to,
1395						evaltype, default_msg, shortdata, longdata, mediatypeid, object, objectid
1396					FROM t_operations
1397					WHERE operationid BETWEEN minid AND maxid;
1398		BEGIN
1399			OPEN o_cur;
1400
1401			LOOP
1402				FETCH o_cur INTO v_operationid, v_actionid, v_operationtype, v_esc_period, v_esc_step_from,
1403						v_esc_step_to, v_evaltype, v_default_msg, v_shortdata, v_longdata,
1404						v_mediatypeid, v_object, v_objectid;
1405
1406				EXIT WHEN o_cur%NOTFOUND;
1407
1408				IF v_operationtype IN (0) THEN			-- OPERATION_TYPE_MESSAGE
1409					new_operationid := new_operationid + 1;
1410
1411					INSERT INTO operations (operationid, actionid, operationtype, esc_period,
1412							esc_step_from, esc_step_to, evaltype)
1413						VALUES (new_operationid, v_actionid, v_operationtype, v_esc_period,
1414							v_esc_step_from, v_esc_step_to, v_evaltype);
1415
1416					INSERT INTO opmessage (operationid, default_msg, subject, message, mediatypeid)
1417						VALUES (new_operationid, v_default_msg, v_shortdata, v_longdata, v_mediatypeid);
1418
1419					IF v_object = 0 AND v_objectid IS NOT NULL THEN	-- OPERATION_OBJECT_USER
1420						new_opmessage_usrid := new_opmessage_usrid + 1;
1421
1422						INSERT INTO opmessage_usr (opmessage_usrid, operationid, userid)
1423							VALUES (new_opmessage_usrid, new_operationid, v_objectid);
1424					END IF;
1425
1426					IF v_object = 1 AND v_objectid IS NOT NULL THEN	-- OPERATION_OBJECT_GROUP
1427						new_opmessage_grpid := new_opmessage_grpid + 1;
1428
1429						INSERT INTO opmessage_grp (opmessage_grpid, operationid, usrgrpid)
1430							VALUES (new_opmessage_grpid, new_operationid, v_objectid);
1431					END IF;
1432
1433					INSERT INTO opconditions
1434						SELECT minid + opconditions_seq.NEXTVAL, new_operationid, conditiontype,
1435								operator, value
1436							FROM t_opconditions
1437							WHERE operationid = v_operationid;
1438				ELSIF v_operationtype IN (1) THEN		-- OPERATION_TYPE_COMMAND
1439					r_pos := 1;
1440					l_pos := 1;
1441
1442					WHILE r_pos > 0 LOOP
1443						r_pos := INSTR(v_longdata, CHR(10), l_pos);
1444
1445						IF r_pos = 0 THEN
1446							cur_string := SUBSTR(v_longdata, l_pos);
1447						ELSE
1448							cur_string := SUBSTR(v_longdata, l_pos, r_pos - l_pos);
1449						END IF;
1450
1451						cur_string := TRIM(RTRIM(cur_string, CHR(13)));
1452
1453						IF LENGTH(cur_string) <> 0 THEN
1454							h_pos := INSTR(cur_string, ':');
1455							g_pos := INSTR(cur_string, '#');
1456
1457							IF h_pos <> 0 OR g_pos <> 0 THEN
1458								new_operationid := new_operationid + 1;
1459
1460								INSERT INTO operations (operationid, actionid, operationtype,
1461										esc_period, esc_step_from, esc_step_to, evaltype)
1462								VALUES (new_operationid, v_actionid, v_operationtype, v_esc_period,
1463										v_esc_step_from, v_esc_step_to, v_evaltype);
1464
1465								INSERT INTO opconditions
1466									SELECT minid + opconditions_seq.NEXTVAL,
1467											new_operationid, conditiontype,
1468											operator, value
1469										FROM t_opconditions
1470										WHERE operationid = v_operationid;
1471
1472								IF h_pos <> 0 AND (g_pos = 0 OR h_pos < g_pos) THEN
1473									INSERT INTO opcommand (operationid, command)
1474										VALUES (new_operationid, TRIM(SUBSTR(cur_string, h_pos + 1)));
1475
1476									v_host := TRIM(SUBSTR(cur_string, 1, h_pos - 1));
1477
1478									IF v_host = '{HOSTNAME}' THEN
1479										new_opcommand_hstid := new_opcommand_hstid + 1;
1480
1481										INSERT INTO opcommand_hst
1482											VALUES (new_opcommand_hstid, new_operationid, NULL);
1483									ELSE
1484										SELECT MIN(hostid) INTO v_hostid
1485											FROM hosts
1486											WHERE host = v_host
1487												AND TRUNC(hostid / 100000000000000) = v_nodeid;
1488
1489										IF v_hostid IS NOT NULL THEN
1490											new_opcommand_hstid := new_opcommand_hstid + 1;
1491
1492											INSERT INTO opcommand_hst
1493												VALUES (new_opcommand_hstid, new_operationid, v_hostid);
1494										END IF;
1495									END IF;
1496								END IF;
1497
1498								IF g_pos <> 0 AND (h_pos = 0 OR g_pos < h_pos) THEN
1499									INSERT INTO opcommand (operationid, command)
1500										VALUES (new_operationid, TRIM(SUBSTR(cur_string, g_pos + 1)));
1501
1502									v_group := TRIM(SUBSTR(cur_string, 1, g_pos - 1));
1503
1504									SELECT MIN(groupid) INTO v_groupid
1505										FROM groups
1506										WHERE name = v_group
1507											AND TRUNC(groupid / 100000000000000) = v_nodeid;
1508
1509									IF v_groupid IS NOT NULL THEN
1510										new_opcommand_grpid := new_opcommand_grpid + 1;
1511
1512										INSERT INTO opcommand_grp
1513											VALUES (new_opcommand_grpid, new_operationid, v_groupid);
1514									END IF;
1515								END IF;
1516							END IF;
1517						END IF;
1518
1519						l_pos := r_pos + 1;
1520					END LOOP;
1521				ELSIF v_operationtype IN (2, 3, 8, 9) THEN	-- OPERATION_TYPE_HOST_(ADD, REMOVE, ENABLE, DISABLE)
1522					new_operationid := new_operationid + 1;
1523
1524					INSERT INTO operations (operationid, actionid, operationtype)
1525						VALUES (new_operationid, v_actionid, v_operationtype);
1526				ELSIF v_operationtype IN (4, 5) THEN		-- OPERATION_TYPE_GROUP_(ADD, REMOVE)
1527					new_operationid := new_operationid + 1;
1528
1529					INSERT INTO operations (operationid, actionid, operationtype)
1530						VALUES (new_operationid, v_actionid, v_operationtype);
1531
1532					new_opgroupid := new_opgroupid + 1;
1533
1534					INSERT INTO opgroup (opgroupid, operationid, groupid)
1535						VALUES (new_opgroupid, new_operationid, v_objectid);
1536				ELSIF v_operationtype IN (6, 7) THEN		-- OPERATION_TYPE_TEMPLATE_(ADD, REMOVE)
1537					new_operationid := new_operationid + 1;
1538
1539					INSERT INTO operations (operationid, actionid, operationtype)
1540						VALUES (new_operationid, v_actionid, v_operationtype);
1541
1542					new_optemplateid := new_optemplateid + 1;
1543
1544					INSERT INTO optemplate (optemplateid, operationid, templateid)
1545						VALUES (new_optemplateid, new_operationid, v_objectid);
1546				END IF;
1547			END LOOP;
1548
1549			CLOSE o_cur;
1550		END;
1551	END LOOP;
1552
1553	CLOSE n_cur;
1554END;
1555/
1556
1557DROP SEQUENCE opconditions_seq;
1558
1559DROP TABLE t_operations;
1560DROP TABLE t_opconditions;
1561
1562UPDATE opcommand
1563	SET type = 1, command = TRIM(SUBSTR(CAST(command AS nvarchar2(2048)), 5))
1564	WHERE SUBSTR(CAST(command AS nvarchar2(2048)), 1, 4) = 'IPMI';
1565
1566DELETE FROM ids WHERE table_name IN ('operations', 'opconditions', 'opmediatypes');
1567-- See operations.sql
1568-- See operations.sql
1569-- See operations.sql
1570-- See operations.sql
1571-- See operations.sql
1572-- See operations.sql
1573ALTER TABLE profiles MODIFY profileid DEFAULT NULL;
1574ALTER TABLE profiles MODIFY userid DEFAULT NULL;
1575DELETE FROM profiles WHERE NOT userid IN (SELECT userid FROM users);
1576DELETE FROM profiles WHERE idx LIKE 'web.%.sort' OR idx LIKE 'web.%.sortorder';
1577ALTER TABLE profiles ADD CONSTRAINT c_profiles_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
1578
1579UPDATE profiles SET idx = 'web.screens.period' WHERE idx = 'web.charts.period';
1580UPDATE profiles SET idx = 'web.screens.stime' WHERE idx = 'web.charts.stime';
1581UPDATE profiles SET idx = 'web.screens.timelinefixed' WHERE idx = 'web.charts.timelinefixed';
1582ALTER TABLE proxy_autoreg_host ADD listen_ip nvarchar2(39) DEFAULT '';
1583ALTER TABLE proxy_autoreg_host ADD listen_port number(10) DEFAULT '0' NOT NULL;
1584ALTER TABLE proxy_autoreg_host ADD listen_dns nvarchar2(64) DEFAULT '';
1585DELETE FROM proxy_dhistory WHERE druleid NOT IN (SELECT druleid FROM drules);
1586DELETE FROM proxy_dhistory WHERE dcheckid<>0 AND dcheckid NOT IN (SELECT dcheckid FROM dchecks);
1587ALTER TABLE proxy_dhistory MODIFY druleid DEFAULT NULL;
1588ALTER TABLE proxy_dhistory MODIFY dcheckid NULL;
1589ALTER TABLE proxy_dhistory MODIFY dcheckid DEFAULT NULL;
1590ALTER TABLE proxy_dhistory ADD dns nvarchar2(64) DEFAULT '';
1591UPDATE proxy_dhistory SET dcheckid=NULL WHERE dcheckid=0;
1592ALTER TABLE proxy_history MODIFY itemid DEFAULT NULL;
1593ALTER TABLE proxy_history ADD ns number(10) DEFAULT '0' NOT NULL;
1594ALTER TABLE proxy_history ADD status number(10) DEFAULT '0' NOT NULL;
1595ALTER TABLE regexps MODIFY regexpid DEFAULT NULL;
1596ALTER TABLE rights MODIFY rightid DEFAULT NULL;
1597ALTER TABLE rights MODIFY groupid DEFAULT NULL;
1598ALTER TABLE rights MODIFY id NOT NULL;
1599DELETE FROM rights WHERE NOT groupid IN (SELECT usrgrpid FROM usrgrp);
1600DELETE FROM rights WHERE NOT id IN (SELECT groupid FROM groups);
1601ALTER TABLE rights ADD CONSTRAINT c_rights_1 FOREIGN KEY (groupid) REFERENCES usrgrp (usrgrpid) ON DELETE CASCADE;
1602ALTER TABLE rights ADD CONSTRAINT c_rights_2 FOREIGN KEY (id) REFERENCES groups (groupid) ON DELETE CASCADE;
1603ALTER TABLE screens_items MODIFY screenitemid DEFAULT NULL;
1604ALTER TABLE screens_items MODIFY screenid DEFAULT NULL;
1605ALTER TABLE screens_items ADD sort_triggers number(10) DEFAULT '0' NOT NULL;
1606DELETE FROM screens_items WHERE screenid NOT IN (SELECT screenid FROM screens);
1607ALTER TABLE screens_items ADD CONSTRAINT c_screens_items_1 FOREIGN KEY (screenid) REFERENCES screens (screenid) ON DELETE CASCADE;
1608ALTER TABLE screens MODIFY screenid DEFAULT NULL;
1609ALTER TABLE screens MODIFY name DEFAULT NULL;
1610ALTER TABLE screens ADD templateid number(20) NULL;
1611ALTER TABLE screens ADD CONSTRAINT c_screens_1 FOREIGN KEY (templateid) REFERENCES hosts (hostid) ON DELETE CASCADE;
1612ALTER TABLE scripts MODIFY scriptid DEFAULT NULL;
1613ALTER TABLE scripts MODIFY usrgrpid DEFAULT NULL;
1614ALTER TABLE scripts MODIFY usrgrpid NULL;
1615ALTER TABLE scripts MODIFY groupid DEFAULT NULL;
1616ALTER TABLE scripts MODIFY groupid NULL;
1617ALTER TABLE scripts ADD description nvarchar2(2048) DEFAULT '';
1618ALTER TABLE scripts ADD confirmation nvarchar2(255) DEFAULT '';
1619ALTER TABLE scripts ADD type number(10) DEFAULT '0' NOT NULL;
1620ALTER TABLE scripts ADD execute_on number(10) DEFAULT '1' NOT NULL;
1621UPDATE scripts SET usrgrpid=NULL WHERE usrgrpid=0;
1622UPDATE scripts SET groupid=NULL WHERE groupid=0;
1623UPDATE scripts SET type=1,command=TRIM(SUBSTR(command, 5)) WHERE SUBSTR(command, 1, 4)='IPMI';
1624DELETE FROM scripts WHERE usrgrpid IS NOT NULL AND usrgrpid NOT IN (SELECT usrgrpid FROM usrgrp);
1625DELETE FROM scripts WHERE groupid IS NOT NULL AND groupid NOT IN (SELECT groupid FROM groups);
1626ALTER TABLE scripts ADD CONSTRAINT c_scripts_1 FOREIGN KEY (usrgrpid) REFERENCES usrgrp (usrgrpid);
1627ALTER TABLE scripts ADD CONSTRAINT c_scripts_2 FOREIGN KEY (groupid) REFERENCES groups (groupid);
1628ALTER TABLE service_alarms MODIFY servicealarmid DEFAULT NULL;
1629ALTER TABLE service_alarms MODIFY serviceid DEFAULT NULL;
1630DELETE FROM service_alarms WHERE NOT serviceid IN (SELECT serviceid FROM services);
1631ALTER TABLE service_alarms ADD CONSTRAINT c_service_alarms_1 FOREIGN KEY (serviceid) REFERENCES services (serviceid) ON DELETE CASCADE;
1632ALTER TABLE services_links MODIFY linkid DEFAULT NULL;
1633ALTER TABLE services_links MODIFY serviceupid DEFAULT NULL;
1634ALTER TABLE services_links MODIFY servicedownid DEFAULT NULL;
1635DELETE FROM services_links WHERE NOT serviceupid IN (SELECT serviceid FROM services);
1636DELETE FROM services_links WHERE NOT servicedownid IN (SELECT serviceid FROM services);
1637ALTER TABLE services_links ADD CONSTRAINT c_services_links_1 FOREIGN KEY (serviceupid) REFERENCES services (serviceid) ON DELETE CASCADE;
1638ALTER TABLE services_links ADD CONSTRAINT c_services_links_2 FOREIGN KEY (servicedownid) REFERENCES services (serviceid) ON DELETE CASCADE;
1639UPDATE services SET triggerid = NULL WHERE NOT EXISTS (SELECT 1 FROM triggers t WHERE t.triggerid = services.triggerid);
1640ALTER TABLE services MODIFY serviceid DEFAULT NULL;
1641ALTER TABLE services ADD CONSTRAINT c_services_1 FOREIGN KEY (triggerid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1642ALTER TABLE services_times MODIFY timeid DEFAULT NULL;
1643ALTER TABLE services_times MODIFY serviceid DEFAULT NULL;
1644DELETE FROM services_times WHERE NOT serviceid IN (SELECT serviceid FROM services);
1645ALTER TABLE services_times ADD CONSTRAINT c_services_times_1 FOREIGN KEY (serviceid) REFERENCES services (serviceid) ON DELETE CASCADE;
1646ALTER TABLE sessions MODIFY userid DEFAULT NULL;
1647DELETE FROM sessions WHERE NOT userid IN (SELECT userid FROM users);
1648ALTER TABLE sessions ADD CONSTRAINT c_sessions_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
1649ALTER TABLE slideshows MODIFY slideshowid DEFAULT NULL;
1650ALTER TABLE slides MODIFY slideid DEFAULT NULL;
1651ALTER TABLE slides MODIFY slideshowid DEFAULT NULL;
1652ALTER TABLE slides MODIFY screenid DEFAULT NULL;
1653DELETE FROM slides WHERE NOT slideshowid IN (SELECT slideshowid FROM slideshows);
1654DELETE FROM slides WHERE NOT screenid IN (SELECT screenid FROM screens);
1655ALTER TABLE slides ADD CONSTRAINT c_slides_1 FOREIGN KEY (slideshowid) REFERENCES slideshows (slideshowid) ON DELETE CASCADE;
1656ALTER TABLE slides ADD CONSTRAINT c_slides_2 FOREIGN KEY (screenid) REFERENCES screens (screenid) ON DELETE CASCADE;
1657-- See sysmaps_elements.sql
1658CREATE TABLE sysmap_element_url (
1659	sysmapelementurlid       number(20)                                NOT NULL,
1660	selementid               number(20)                                NOT NULL,
1661	name                     nvarchar2(255)                            ,
1662	url                      nvarchar2(255)  DEFAULT ''                ,
1663	PRIMARY KEY (sysmapelementurlid)
1664);
1665CREATE UNIQUE INDEX sysmap_element_url_1 on sysmap_element_url (selementid,name);
1666ALTER TABLE sysmap_element_url ADD CONSTRAINT c_sysmap_element_url_1 FOREIGN KEY (selementid) REFERENCES sysmaps_elements (selementid) ON DELETE CASCADE;
1667
1668INSERT INTO sysmap_element_url (sysmapelementurlid,selementid,name,url)
1669	SELECT selementid,selementid,url,url FROM sysmaps_elements WHERE url IS NOT NULL;
1670
1671ALTER TABLE sysmaps_elements MODIFY selementid DEFAULT NULL;
1672ALTER TABLE sysmaps_elements MODIFY sysmapid DEFAULT NULL;
1673ALTER TABLE sysmaps_elements MODIFY iconid_off DEFAULT NULL;
1674ALTER TABLE sysmaps_elements MODIFY iconid_off NULL;
1675ALTER TABLE sysmaps_elements MODIFY iconid_on DEFAULT NULL;
1676ALTER TABLE sysmaps_elements MODIFY iconid_on NULL;
1677ALTER TABLE sysmaps_elements DROP COLUMN iconid_unknown;
1678ALTER TABLE sysmaps_elements MODIFY iconid_disabled DEFAULT NULL;
1679ALTER TABLE sysmaps_elements MODIFY iconid_disabled NULL;
1680ALTER TABLE sysmaps_elements MODIFY iconid_maintenance DEFAULT NULL;
1681ALTER TABLE sysmaps_elements MODIFY iconid_maintenance NULL;
1682ALTER TABLE sysmaps_elements DROP COLUMN url;
1683ALTER TABLE sysmaps_elements ADD elementsubtype number(10) DEFAULT '0' NOT NULL;
1684ALTER TABLE sysmaps_elements ADD areatype number(10) DEFAULT '0' NOT NULL;
1685ALTER TABLE sysmaps_elements ADD width number(10) DEFAULT '200' NOT NULL;
1686ALTER TABLE sysmaps_elements ADD height number(10) DEFAULT '200' NOT NULL;
1687ALTER TABLE sysmaps_elements ADD viewtype number(10) DEFAULT '0' NOT NULL;
1688ALTER TABLE sysmaps_elements ADD use_iconmap number(10) DEFAULT '1' NOT NULL;
1689
1690DELETE FROM sysmaps_elements WHERE sysmapid NOT IN (SELECT sysmapid FROM sysmaps);
1691UPDATE sysmaps_elements SET iconid_off=NULL WHERE iconid_off=0;
1692UPDATE sysmaps_elements SET iconid_on=NULL WHERE iconid_on=0;
1693UPDATE sysmaps_elements SET iconid_disabled=NULL WHERE iconid_disabled=0;
1694UPDATE sysmaps_elements SET iconid_maintenance=NULL WHERE iconid_maintenance=0;
1695UPDATE sysmaps_elements SET iconid_off=NULL WHERE NOT iconid_off IS NULL AND NOT iconid_off IN (SELECT imageid FROM images WHERE imagetype=1);
1696UPDATE sysmaps_elements SET iconid_on=NULL WHERE NOT iconid_on IS NULL AND NOT iconid_on IN (SELECT imageid FROM images WHERE imagetype=1);
1697UPDATE sysmaps_elements SET iconid_disabled=NULL WHERE NOT iconid_disabled IS NULL AND NOT iconid_disabled IN (SELECT imageid FROM images WHERE imagetype=1);
1698UPDATE sysmaps_elements SET iconid_maintenance=NULL WHERE NOT iconid_maintenance IS NULL AND NOT iconid_maintenance IN (SELECT imageid FROM images WHERE imagetype=1);
1699ALTER TABLE sysmaps_elements ADD CONSTRAINT c_sysmaps_elements_1 FOREIGN KEY (sysmapid) REFERENCES sysmaps (sysmapid) ON DELETE CASCADE;
1700ALTER TABLE sysmaps_elements ADD CONSTRAINT c_sysmaps_elements_2 FOREIGN KEY (iconid_off) REFERENCES images (imageid);
1701ALTER TABLE sysmaps_elements ADD CONSTRAINT c_sysmaps_elements_3 FOREIGN KEY (iconid_on) REFERENCES images (imageid);
1702ALTER TABLE sysmaps_elements ADD CONSTRAINT c_sysmaps_elements_4 FOREIGN KEY (iconid_disabled) REFERENCES images (imageid);
1703ALTER TABLE sysmaps_elements ADD CONSTRAINT c_sysmaps_elements_5 FOREIGN KEY (iconid_maintenance) REFERENCES images (imageid);
1704ALTER TABLE sysmaps_links MODIFY linkid DEFAULT NULL;
1705ALTER TABLE sysmaps_links MODIFY sysmapid DEFAULT NULL;
1706ALTER TABLE sysmaps_links MODIFY selementid1 DEFAULT NULL;
1707ALTER TABLE sysmaps_links MODIFY selementid2 DEFAULT NULL;
1708DELETE FROM sysmaps_links WHERE sysmapid NOT IN (SELECT sysmapid FROM sysmaps);
1709DELETE FROM sysmaps_links WHERE selementid1 NOT IN (SELECT selementid FROM sysmaps_elements);
1710DELETE FROM sysmaps_links WHERE selementid2 NOT IN (SELECT selementid FROM sysmaps_elements);
1711ALTER TABLE sysmaps_links ADD CONSTRAINT c_sysmaps_links_1 FOREIGN KEY (sysmapid) REFERENCES sysmaps (sysmapid) ON DELETE CASCADE;
1712ALTER TABLE sysmaps_links ADD CONSTRAINT c_sysmaps_links_2 FOREIGN KEY (selementid1) REFERENCES sysmaps_elements (selementid) ON DELETE CASCADE;
1713ALTER TABLE sysmaps_links ADD CONSTRAINT c_sysmaps_links_3 FOREIGN KEY (selementid2) REFERENCES sysmaps_elements (selementid) ON DELETE CASCADE;
1714ALTER TABLE sysmaps_link_triggers MODIFY linktriggerid DEFAULT NULL;
1715ALTER TABLE sysmaps_link_triggers MODIFY linkid DEFAULT NULL;
1716ALTER TABLE sysmaps_link_triggers MODIFY triggerid DEFAULT NULL;
1717DELETE FROM sysmaps_link_triggers WHERE linkid NOT IN (SELECT linkid FROM sysmaps_links);
1718DELETE FROM sysmaps_link_triggers WHERE triggerid NOT IN (SELECT triggerid FROM triggers);
1719ALTER TABLE sysmaps_link_triggers ADD CONSTRAINT c_sysmaps_link_triggers_1 FOREIGN KEY (linkid) REFERENCES sysmaps_links (linkid) ON DELETE CASCADE;
1720ALTER TABLE sysmaps_link_triggers ADD CONSTRAINT c_sysmaps_link_triggers_2 FOREIGN KEY (triggerid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1721ALTER TABLE sysmaps MODIFY sysmapid DEFAULT NULL;
1722ALTER TABLE sysmaps MODIFY width DEFAULT '600';
1723ALTER TABLE sysmaps MODIFY height DEFAULT '400';
1724ALTER TABLE sysmaps MODIFY backgroundid DEFAULT NULL;
1725ALTER TABLE sysmaps MODIFY backgroundid NULL;
1726ALTER TABLE sysmaps MODIFY label_type DEFAULT '2';
1727ALTER TABLE sysmaps MODIFY label_location DEFAULT '3';
1728ALTER TABLE sysmaps ADD expandproblem number(10) DEFAULT '1' NOT NULL;
1729ALTER TABLE sysmaps ADD markelements number(10) DEFAULT '0' NOT NULL;
1730ALTER TABLE sysmaps ADD show_unack number(10) DEFAULT '0' NOT NULL;
1731ALTER TABLE sysmaps ADD grid_size number(10) DEFAULT '50' NOT NULL;
1732ALTER TABLE sysmaps ADD grid_show number(10) DEFAULT '1' NOT NULL;
1733ALTER TABLE sysmaps ADD grid_align number(10) DEFAULT '1' NOT NULL;
1734ALTER TABLE sysmaps ADD label_format number(10) DEFAULT '0' NOT NULL;
1735ALTER TABLE sysmaps ADD label_type_host number(10) DEFAULT '2' NOT NULL;
1736ALTER TABLE sysmaps ADD label_type_hostgroup number(10) DEFAULT '2' NOT NULL;
1737ALTER TABLE sysmaps ADD label_type_trigger number(10) DEFAULT '2' NOT NULL;
1738ALTER TABLE sysmaps ADD label_type_map number(10) DEFAULT '2' NOT NULL;
1739ALTER TABLE sysmaps ADD label_type_image number(10) DEFAULT '2' NOT NULL;
1740ALTER TABLE sysmaps ADD label_string_host nvarchar2(255) DEFAULT '';
1741ALTER TABLE sysmaps ADD label_string_hostgroup nvarchar2(255) DEFAULT '';
1742ALTER TABLE sysmaps ADD label_string_trigger nvarchar2(255) DEFAULT '';
1743ALTER TABLE sysmaps ADD label_string_map nvarchar2(255) DEFAULT '';
1744ALTER TABLE sysmaps ADD label_string_image nvarchar2(255) DEFAULT '';
1745ALTER TABLE sysmaps ADD iconmapid number(20) NULL;
1746ALTER TABLE sysmaps ADD expand_macros number(10) DEFAULT '0' NOT NULL;
1747UPDATE sysmaps SET backgroundid=NULL WHERE backgroundid=0;
1748UPDATE sysmaps SET show_unack=1 WHERE highlight>7 AND highlight<16;
1749UPDATE sysmaps SET show_unack=2 WHERE highlight>23;
1750UPDATE sysmaps SET highlight=(highlight-16) WHERE highlight>15;
1751UPDATE sysmaps SET highlight=(highlight-8) WHERE highlight>7;
1752UPDATE sysmaps SET markelements=1 WHERE highlight>3  AND highlight<8;
1753UPDATE sysmaps SET highlight=(highlight-4) WHERE highlight>3;
1754UPDATE sysmaps SET expandproblem=0 WHERE highlight>1 AND highlight<4;
1755UPDATE sysmaps SET highlight=(highlight-2) WHERE highlight>1;
1756ALTER TABLE sysmaps ADD CONSTRAINT c_sysmaps_1 FOREIGN KEY (backgroundid) REFERENCES images (imageid);
1757ALTER TABLE sysmaps ADD CONSTRAINT c_sysmaps_2 FOREIGN KEY (iconmapid) REFERENCES icon_map (iconmapid);
1758CREATE TABLE sysmap_url (
1759	sysmapurlid              number(20)                                NOT NULL,
1760	sysmapid                 number(20)                                NOT NULL,
1761	name                     nvarchar2(255)                            ,
1762	url                      nvarchar2(255)  DEFAULT ''                ,
1763	elementtype              number(10)      DEFAULT '0'               NOT NULL,
1764	PRIMARY KEY (sysmapurlid)
1765);
1766CREATE UNIQUE INDEX sysmap_url_1 on sysmap_url (sysmapid,name);
1767ALTER TABLE sysmap_url ADD CONSTRAINT c_sysmap_url_1 FOREIGN KEY (sysmapid) REFERENCES sysmaps (sysmapid) ON DELETE CASCADE;
1768ALTER TABLE timeperiods MODIFY timeperiodid DEFAULT NULL;
1769ALTER TABLE trends MODIFY itemid DEFAULT NULL;
1770ALTER TABLE trends_uint MODIFY itemid DEFAULT NULL;
1771ALTER TABLE trigger_depends MODIFY triggerdepid DEFAULT NULL;
1772ALTER TABLE trigger_depends MODIFY triggerid_down DEFAULT NULL;
1773ALTER TABLE trigger_depends MODIFY triggerid_up DEFAULT NULL;
1774DROP INDEX trigger_depends_1;
1775DELETE FROM trigger_depends WHERE triggerid_down NOT IN (SELECT triggerid FROM triggers);
1776DELETE FROM trigger_depends WHERE triggerid_up NOT IN (SELECT triggerid FROM triggers);
1777-- remove duplicates to allow unique index
1778DELETE FROM trigger_depends
1779	WHERE triggerdepid IN (
1780		SELECT td1.triggerdepid
1781		FROM trigger_depends td1
1782		LEFT OUTER JOIN (
1783			SELECT MIN(td2.triggerdepid) AS triggerdepid
1784			FROM trigger_depends td2
1785			GROUP BY td2.triggerid_down,td2.triggerid_up
1786		) keep_rows ON
1787			td1.triggerdepid=keep_rows.triggerdepid
1788		WHERE keep_rows.triggerdepid IS NULL
1789	);
1790CREATE UNIQUE INDEX trigger_depends_1 ON trigger_depends (triggerid_down,triggerid_up);
1791ALTER TABLE trigger_depends ADD CONSTRAINT c_trigger_depends_1 FOREIGN KEY (triggerid_down) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1792ALTER TABLE trigger_depends ADD CONSTRAINT c_trigger_depends_2 FOREIGN KEY (triggerid_up) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1793CREATE TABLE trigger_discovery (
1794	triggerdiscoveryid       number(20)                                NOT NULL,
1795	triggerid                number(20)                                NOT NULL,
1796	parent_triggerid         number(20)                                NOT NULL,
1797	name                     nvarchar2(255)  DEFAULT ''                ,
1798	PRIMARY KEY (triggerdiscoveryid)
1799);
1800CREATE UNIQUE INDEX trigger_discovery_1 on trigger_discovery (triggerid,parent_triggerid);
1801ALTER TABLE trigger_discovery ADD CONSTRAINT c_trigger_discovery_1 FOREIGN KEY (triggerid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1802ALTER TABLE trigger_discovery ADD CONSTRAINT c_trigger_discovery_2 FOREIGN KEY (parent_triggerid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1803----
1804---- Patching table `events`
1805----
1806
1807DROP INDEX events_2;
1808CREATE INDEX events_2 on events (clock);
1809ALTER TABLE events MODIFY eventid DEFAULT NULL;
1810ALTER TABLE events ADD ns number(10) DEFAULT '0' NOT NULL;
1811ALTER TABLE events ADD value_changed number(10) DEFAULT '0' NOT NULL;
1812
1813-- Begin event redesign patch
1814
1815CREATE TABLE tmp_events_eventid (eventid number(20) PRIMARY KEY,prev_value number(10),value number(10));
1816CREATE INDEX tmp_events_index on events (source, object, objectid, clock, eventid, value);
1817
1818CREATE OR REPLACE FUNCTION get_prev_value(eventid IN NUMBER, triggerid IN NUMBER, clock IN NUMBER)
1819RETURN NUMBER IS
1820prev_value NUMBER(10);
1821BEGIN
1822	SELECT value
1823		INTO prev_value
1824		FROM (
1825		SELECT value
1826			FROM events
1827			WHERE source=0			-- EVENT_SOURCE_TRIGGERS
1828				AND object=0		-- EVENT_OBJECT_TRIGGER
1829				AND objectid=get_prev_value.triggerid
1830				AND (clock<get_prev_value.clock
1831					OR (clock=get_prev_value.clock
1832						AND eventid<get_prev_value.eventid)
1833					)
1834				AND value IN (0,1)	-- TRIGGER_VALUE_FALSE (OK), TRIGGER_VALUE_TRUE (PROBLEM)
1835			ORDER BY source DESC,
1836				object DESC,
1837				objectid DESC,
1838				clock DESC,
1839				eventid DESC,
1840				value DESC
1841		) WHERE rownum = 1;
1842	RETURN prev_value;
1843END;
1844/
1845
1846-- Which OK events should have value_changed flag set?
1847-- Those that have a PROBLEM event (or no event) before them.
1848
1849INSERT INTO tmp_events_eventid (eventid, prev_value, value)
1850	SELECT eventid,get_prev_value(eventid, objectid, clock) AS prev_value, value
1851	FROM events
1852	WHERE source=0					-- EVENT_SOURCE_TRIGGERS
1853		AND object=0				-- EVENT_OBJECT_TRIGGER
1854		AND value=0				-- TRIGGER_VALUE_FALSE (OK)
1855/
1856
1857-- Which PROBLEM events should have value_changed flag set?
1858-- (1) Those that have an OK event (or no event) before them.
1859
1860INSERT INTO tmp_events_eventid (eventid, prev_value, value)
1861	SELECT e.eventid,get_prev_value(e.eventid, e.objectid, e.clock) AS prev_value, e.value
1862	FROM events e,triggers t
1863	WHERE e.source=0				-- EVENT_SOURCE_TRIGGERS
1864		AND e.object=0				-- EVENT_OBJECT_TRIGGER
1865		AND e.objectid=t.triggerid
1866		AND e.value=1				-- TRIGGER_VALUE_TRUE (PROBLEM)
1867		AND t.type=0
1868/
1869
1870-- (2) Those that came from a "MULTIPLE PROBLEM" trigger.
1871
1872INSERT INTO tmp_events_eventid (eventid, value)
1873	SELECT e.eventid, e.value
1874		FROM events e,triggers t
1875		WHERE e.source=0			-- EVENT_SOURCE_TRIGGERS
1876			AND e.object=0			-- EVENT_OBJECT_TRIGGER
1877			AND e.objectid=t.triggerid
1878			AND e.value=1			-- TRIGGER_VALUE_TRUE (PROBLEM)
1879			AND t.type=1
1880/
1881
1882DELETE FROM tmp_events_eventid WHERE prev_value = value;
1883
1884-- Update the value_changed flag.
1885
1886DROP INDEX tmp_events_index;
1887DROP FUNCTION get_prev_value;
1888
1889UPDATE events SET value_changed=1 WHERE eventid IN (SELECT eventid FROM tmp_events_eventid);
1890
1891DROP TABLE tmp_events_eventid;
1892
1893-- End event redesign patch
1894
1895----
1896---- Patching table `triggers`
1897----
1898
1899ALTER TABLE triggers MODIFY triggerid DEFAULT NULL;
1900ALTER TABLE triggers MODIFY templateid DEFAULT NULL;
1901ALTER TABLE triggers MODIFY templateid NULL;
1902ALTER TABLE triggers DROP COLUMN dep_level;
1903ALTER TABLE triggers ADD value_flags number(10) DEFAULT '0' NOT NULL;
1904ALTER TABLE triggers ADD flags number(10) DEFAULT '0' NOT NULL;
1905UPDATE triggers SET templateid=NULL WHERE templateid=0;
1906UPDATE triggers SET templateid=NULL WHERE NOT templateid IS NULL AND NOT templateid IN (SELECT triggerid FROM triggers);
1907ALTER TABLE triggers ADD CONSTRAINT c_triggers_1 FOREIGN KEY (templateid) REFERENCES triggers (triggerid) ON DELETE CASCADE;
1908
1909-- Begin event redesign patch
1910
1911CREATE TABLE tmp_triggers (triggerid number(20) PRIMARY KEY, eventid number(20))
1912/
1913
1914INSERT INTO tmp_triggers (triggerid, eventid)
1915(
1916	SELECT t.triggerid, MAX(e.eventid)
1917		FROM triggers t, events e
1918		WHERE t.value=2				-- TRIGGER_VALUE_UNKNOWN
1919			AND e.source=0			-- EVENT_SOURCE_TRIGGERS
1920			AND e.object=0			-- EVENT_OBJECT_TRIGGER
1921			AND e.objectid=t.triggerid
1922			AND e.value IN (0,1)		-- TRIGGER_VALUE_FALSE (OK), TRIGGER_VALUE_TRUE (PROBLEM)
1923		GROUP BY t.triggerid
1924)
1925/
1926
1927UPDATE triggers
1928	SET value=(
1929		SELECT e.value
1930			FROM events e,tmp_triggers t
1931			WHERE e.eventid=t.eventid
1932				AND triggers.triggerid=t.triggerid
1933	)
1934	WHERE triggerid IN (
1935		SELECT triggerid
1936			FROM tmp_triggers
1937	)
1938/
1939
1940UPDATE triggers
1941	SET value=0,					-- TRIGGER_VALUE_FALSE
1942		value_flags=1
1943	WHERE value NOT IN (0,1)			-- TRIGGER_VALUE_FALSE (OK), TRIGGER_VALUE_TRUE (PROBLEM)
1944/
1945
1946DROP TABLE tmp_triggers
1947/
1948
1949-- End event redesign patch
1950ALTER TABLE user_history MODIFY userhistoryid DEFAULT NULL;
1951ALTER TABLE user_history MODIFY userid DEFAULT NULL;
1952DELETE FROM user_history WHERE NOT userid IN (SELECT userid FROM users);
1953ALTER TABLE user_history ADD CONSTRAINT c_user_history_1 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
1954ALTER TABLE users_groups MODIFY id DEFAULT NULL;
1955ALTER TABLE users_groups MODIFY usrgrpid DEFAULT NULL;
1956ALTER TABLE users_groups MODIFY userid DEFAULT NULL;
1957DELETE FROM users_groups WHERE usrgrpid NOT IN (SELECT usrgrpid FROM usrgrp);
1958DELETE FROM users_groups WHERE userid NOT IN (SELECT userid FROM users);
1959
1960-- remove duplicates to allow unique index
1961DELETE FROM users_groups
1962	WHERE id IN (
1963		SELECT ug1.id
1964		FROM users_groups ug1
1965		LEFT OUTER JOIN (
1966			SELECT MIN(ug2.id) AS id
1967			FROM users_groups ug2
1968			GROUP BY ug2.usrgrpid,ug2.userid
1969		) keep_rows ON
1970			ug1.id=keep_rows.id
1971		WHERE keep_rows.id IS NULL
1972	);
1973
1974DROP INDEX users_groups_1;
1975CREATE UNIQUE INDEX users_groups_1 ON users_groups (usrgrpid,userid);
1976ALTER TABLE users_groups ADD CONSTRAINT c_users_groups_1 FOREIGN KEY (usrgrpid) REFERENCES usrgrp (usrgrpid) ON DELETE CASCADE;
1977ALTER TABLE users_groups ADD CONSTRAINT c_users_groups_2 FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE;
1978ALTER TABLE users MODIFY (
1979	userid DEFAULT NULL,
1980	lang DEFAULT 'en_GB',
1981	theme DEFAULT 'default'
1982);
1983UPDATE users SET lang = 'zh_CN' WHERE lang = 'cn_zh';
1984UPDATE users SET lang = 'es_ES' WHERE lang = 'sp_sp';
1985UPDATE users SET lang = 'en_GB' WHERE lang = 'en_gb';
1986UPDATE users SET lang = 'cs_CZ' WHERE lang = 'cs_cz';
1987UPDATE users SET lang = 'nl_NL' WHERE lang = 'nl_nl';
1988UPDATE users SET lang = 'fr_FR' WHERE lang = 'fr_fr';
1989UPDATE users SET lang = 'de_DE' WHERE lang = 'de_de';
1990UPDATE users SET lang = 'hu_HU' WHERE lang = 'hu_hu';
1991UPDATE users SET lang = 'ko_KR' WHERE lang = 'ko_kr';
1992UPDATE users SET lang = 'ja_JP' WHERE lang = 'ja_jp';
1993UPDATE users SET lang = 'lv_LV' WHERE lang = 'lv_lv';
1994UPDATE users SET lang = 'pl_PL' WHERE lang = 'pl_pl';
1995UPDATE users SET lang = 'pt_BR' WHERE lang = 'pt_br';
1996UPDATE users SET lang = 'ru_RU' WHERE lang = 'ru_ru';
1997UPDATE users SET lang = 'sv_SE' WHERE lang = 'sv_se';
1998UPDATE users SET lang = 'uk_UA' WHERE lang = 'ua_ua';
1999
2000UPDATE users SET theme = 'darkblue' WHERE theme = 'css_bb.css';
2001UPDATE users SET theme = 'originalblue' WHERE theme = 'css_ob.css';
2002UPDATE users SET theme = 'darkorange' WHERE theme = 'css_od.css';
2003UPDATE users SET theme = 'default' WHERE theme = 'default.css';
2004ALTER TABLE usrgrp MODIFY usrgrpid DEFAULT NULL;
2005ALTER TABLE usrgrp DROP COLUMN api_access;
2006ALTER TABLE valuemaps MODIFY valuemapid DEFAULT NULL;
2007