1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
|
<?php
/*
** Zabbix
** Copyright (C) 2001-2021 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
class DB {
const SCHEMA_FILE = 'schema.inc.php';
const DBEXECUTE_ERROR = 1;
const RESERVEIDS_ERROR = 2;
const SCHEMA_ERROR = 3;
const INPUT_ERROR = 4;
const TABLE_TYPE_CONFIG = 1;
const TABLE_TYPE_HISTORY = 2;
const FIELD_TYPE_INT = 'int';
const FIELD_TYPE_CHAR = 'char';
const FIELD_TYPE_ID = 'id';
const FIELD_TYPE_FLOAT = 'float';
const FIELD_TYPE_UINT = 'uint';
const FIELD_TYPE_BLOB = 'blob';
const FIELD_TYPE_TEXT = 'text';
const FIELD_TYPE_NCLOB = 'nclob';
const FIELD_TYPE_CUID = 'cuid';
private static $schema = null;
/**
* @var DbBackend
*/
private static $dbBackend;
/**
* Get necessary DB class.
*
* @return DbBackend
*/
public static function getDbBackend() {
global $DB;
if (!self::$dbBackend) {
switch ($DB['TYPE']) {
case ZBX_DB_MYSQL:
self::$dbBackend = new MysqlDbBackend();
break;
case ZBX_DB_POSTGRESQL:
self::$dbBackend = new PostgresqlDbBackend();
break;
case ZBX_DB_ORACLE:
self::$dbBackend = new OracleDbBackend();
break;
}
}
return self::$dbBackend;
}
private static function exception($code, $error) {
throw new DBException($error, $code);
}
/**
* Reserve ids for primary key of passed table.
* If record for table does not exist or value is out of range, ids record is created
* using maximum id from table or minimum allowed value.
*
* @throw APIException
*
* @static
*
* @param string $table table name
* @param int $count number of ids to reserve
*
* @return string
*/
public static function reserveIds($table, $count) {
global $DB;
$tableSchema = self::getSchema($table);
$id_name = $tableSchema['key'];
$sql = 'SELECT nextid'.
' FROM ids'.
' WHERE table_name='.zbx_dbstr($table).
' AND field_name='.zbx_dbstr($id_name).
' FOR UPDATE';
$res = DBfetch(DBselect($sql));
if ($res) {
$maxNextId = bcadd($res['nextid'], $count, 0);
if (bccomp($maxNextId, ZBX_DB_MAX_ID) == 1) {
$nextid = self::refreshIds($table, $count);
}
else {
$sql = 'UPDATE ids'.
' SET nextid='.$maxNextId.
' WHERE table_name='.zbx_dbstr($table).
' AND field_name='.zbx_dbstr($id_name);
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, 'DBEXECUTE_ERROR');
}
$nextid = bcadd($res['nextid'], 1, 0);
}
}
/*
* Detect either the query is executable at all? If query is valid and schema is correct but query still cannot
* be executed, then there is a good chance that previous transaction has left row level lock unreleased or it
* is still running. In such a case execution must be stopped, otherwise it will call self::refreshIds method.
*/
elseif (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR,
_('Your database is not working properly. Please wait a few minutes and try to repeat this action. If the problem still persists, please contact system administrator. The problem might be caused by long running transaction or row level lock accomplished by your database management system.')
);
}
// If query is executable, but still returns false, only then call refreshIds.
else {
$nextid = self::refreshIds($table, $count);
}
return $nextid;
}
/**
* Refresh id record for given table.
* Record is deleted and then created again with value of maximum id from table or minimum allowed.
*
* @throw APIException
*
* @static
*
* @param string $table table name
* @param int $count number of ids to reserve
*
* @return string
*/
private static function refreshIds($table, $count) {
$tableSchema = self::getSchema($table);
$id_name = $tableSchema['key'];
// when we reach the maximum ID, we try to refresh them to check if any IDs have been freed
$sql = 'DELETE FROM ids WHERE table_name='.zbx_dbstr($table).' AND field_name='.zbx_dbstr($id_name);
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, 'DBEXECUTE_ERROR');
}
$row = DBfetch(DBselect('SELECT MAX('.$id_name.') AS id FROM '.$table));
$nextid = ($row && $row['id']) ? $row['id'] : 0;
$maxNextId = bcadd($nextid, $count, 0);
if (bccomp($maxNextId, ZBX_DB_MAX_ID) == 1) {
self::exception(
self::RESERVEIDS_ERROR, __METHOD__.' ID greater than maximum allowed for table "'.$table.'"'
);
}
$sql = 'INSERT INTO ids (table_name,field_name,nextid)'.
' VALUES ('.zbx_dbstr($table).','.zbx_dbstr($id_name).','.$maxNextId.')';
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, 'DBEXECUTE_ERROR');
}
$nextid = bcadd($nextid, 1, 0);
return $nextid;
}
/**
* Returns the array describing the database schema.
*
* If the $table parameter is passed, the method will return the schema for the given table,
* otherwise - for the whole database.
*
* @static
*
* @throws APIException if the given table does not exist
*
* @param string $table
*
* @return array
*/
public static function getSchema($table = null) {
if (is_null(self::$schema)) {
self::$schema = include(dirname(__FILE__).'/../../'.self::SCHEMA_FILE);
}
if (is_null($table)) {
return self::$schema;
}
elseif (isset(self::$schema[$table])) {
return self::$schema[$table];
}
else {
self::exception(self::SCHEMA_ERROR, _s('Table "%1$s" does not exist.', $table));
}
}
/**
* Returns the names of the fields that are used as the primary key of the table.
*
* @static
*
* @param string $table_name
*
* @return string
*/
public static function getPk(string $table_name): string {
$schema = self::getSchema($table_name);
return $schema['key'];
}
/**
* Returns true if the table $tableName has the $fieldName field.
*
* @static
*
* @param string $tableName
* @param string $fieldName
*
* @return bool
*/
public static function hasField($tableName, $fieldName) {
$schema = self::getSchema($tableName);
return isset($schema['fields'][$fieldName]);
}
/**
* Returns length of the field.
*
* @static
*
* @param string $table_name
* @param string $field_name
*
* @return int
*/
public static function getFieldLength($table_name, $field_name) {
global $DB;
$schema = self::getSchema($table_name);
if ($schema['fields'][$field_name]['type'] == self::FIELD_TYPE_TEXT) {
return ($DB['TYPE'] == ZBX_DB_ORACLE) ? 2048 : 65535;
}
if ($schema['fields'][$field_name]['type'] == self::FIELD_TYPE_NCLOB) {
return 65535;
}
return $schema['fields'][$field_name]['length'];
}
public static function getDefaults($table) {
$table = self::getSchema($table);
$defaults = [];
foreach ($table['fields'] as $name => $field) {
if (isset($field['default'])) {
$defaults[$name] = $field['default'];
}
}
return $defaults;
}
/**
* Returns the default value of the given field.
*
* @param string $table name of the table
* @param string $field name of the field
*
* @return string|null
*/
public static function getDefault($table, $field) {
$table = self::getSchema($table);
$field = $table['fields'][$field];
return isset($field['default']) ? $field['default'] : null;
}
/**
* Get the updated values of a record by correctly comparing the new and old ones, taking field types into account.
*
* @param string $table_name
* @param array $new_values
* @param array $old_values
*
* @return array
*/
public static function getUpdatedValues(string $table_name, array $new_values, array $old_values): array {
$updated_values = [];
// Discard field names not existing in the target table.
$fields = array_intersect_key(DB::getSchema($table_name)['fields'], $new_values);
foreach ($fields as $name => $spec) {
if (!array_key_exists($name, $old_values)) {
$updated_values[$name] = $new_values[$name];
continue;
}
switch ($spec['type']) {
case DB::FIELD_TYPE_ID:
if (bccomp($new_values[$name], $old_values[$name]) != 0) {
$updated_values[$name] = $new_values[$name];
}
break;
case DB::FIELD_TYPE_INT:
case DB::FIELD_TYPE_UINT:
case DB::FIELD_TYPE_FLOAT:
if ($new_values[$name] != $old_values[$name]) {
$updated_values[$name] = $new_values[$name];
}
break;
default:
if ($new_values[$name] !== $old_values[$name]) {
$updated_values[$name] = $new_values[$name];
}
break;
}
}
return $updated_values;
}
private static function checkValueTypes($tableSchema, &$values) {
global $DB;
foreach ($values as $field => $value) {
if (!isset($tableSchema['fields'][$field])) {
unset($values[$field]);
continue;
}
if (isset($tableSchema['fields'][$field]['ref_table'])) {
if ($tableSchema['fields'][$field]['null']) {
$values[$field] = ($values[$field] == '0') ? NULL : $values[$field];
}
}
if (is_null($values[$field])) {
if ($tableSchema['fields'][$field]['null']) {
$values[$field] = 'NULL';
}
elseif (isset($tableSchema['fields'][$field]['default'])) {
$values[$field] = zbx_dbstr($tableSchema['fields'][$field]['default']);
}
else {
self::exception(self::DBEXECUTE_ERROR,
_s('Field "%1$s" cannot be set to NULL.', $field)
);
}
}
else {
switch ($tableSchema['fields'][$field]['type']) {
case self::FIELD_TYPE_CUID:
case self::FIELD_TYPE_CHAR:
$length = mb_strlen($values[$field]);
if ($length > $tableSchema['fields'][$field]['length']) {
self::exception(self::SCHEMA_ERROR, _s('Value "%1$s" is too long for field "%2$s" - %3$d characters. Allowed length is %4$d characters.',
$values[$field], $field, $length, $tableSchema['fields'][$field]['length']));
}
$values[$field] = zbx_dbstr($values[$field]);
break;
case self::FIELD_TYPE_ID:
case self::FIELD_TYPE_UINT:
if (!zbx_ctype_digit($values[$field])) {
self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for unsigned int field "%2$s".', $values[$field], $field));
}
$values[$field] = zbx_dbstr($values[$field]);
break;
case self::FIELD_TYPE_INT:
if (!zbx_is_int($values[$field])) {
self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for int field "%2$s".', $values[$field], $field));
}
$values[$field] = zbx_dbstr($values[$field]);
break;
case self::FIELD_TYPE_FLOAT:
if (!is_numeric($values[$field])) {
self::exception(self::DBEXECUTE_ERROR, _s('Incorrect value "%1$s" for float field "%2$s".', $values[$field], $field));
}
$values[$field] = zbx_dbstr($values[$field]);
break;
case self::FIELD_TYPE_TEXT:
if ($DB['TYPE'] == ZBX_DB_ORACLE) {
$length = mb_strlen($values[$field]);
if ($length > 2048) {
self::exception(self::SCHEMA_ERROR, _s('Value "%1$s" is too long for field "%2$s" - %3$d characters. Allowed length is %4$d characters.',
$values[$field], $field, $length, 2048));
}
}
$values[$field] = zbx_dbstr($values[$field]);
break;
case self::FIELD_TYPE_NCLOB:
// Using strlen because 4000 bytes is largest possible string literal in oracle query.
if ($DB['TYPE'] == ZBX_DB_ORACLE && strlen($values[$field]) > ORACLE_MAX_STRING_SIZE) {
$chunks = zbx_dbstr(self::chunkMultibyteStr($values[$field], ORACLE_MAX_STRING_SIZE));
$values[$field] = 'TO_NCLOB('.implode(') || TO_NCLOB(', $chunks).')';
}
else {
$values[$field] = zbx_dbstr($values[$field]);
}
break;
case self::FIELD_TYPE_BLOB:
switch ($DB['TYPE']) {
case ZBX_DB_MYSQL:
$values[$field] = zbx_dbstr($values[$field]);
break;
case ZBX_DB_POSTGRESQL:
$values[$field] = "'".pg_escape_bytea($values[$field])."'";
break;
case ZBX_DB_ORACLE:
// Do nothing; Check CImage.php to see how to update BLOB data with ORACLE DB.
break;
}
}
}
}
}
/**
* @param string $str
* @param int $chunk_size
*
* @return array
*/
public static function chunkMultibyteStr(string $str, int $chunk_size): array {
$chunks = [];
$offset = 0;
$size = strlen($str);
while ($offset < $size) {
$chunk = mb_strcut($str, $offset, $chunk_size);
$chunks[] = $chunk;
$offset = strlen($chunk) + $offset;
}
return $chunks;
}
/**
* Returns the records that match the given criteria.
*
* @static
*
* @param string $tableName
* @param array $criteria An associative array of field-value pairs, where value can be either a single value
* or an array (IN)
*
* @return array
*/
public static function find($tableName, array $criteria = []) {
// build the WHERE part
$sqlWhere = [];
foreach ($criteria as $field => $value) {
// check if the table has this field
if (!self::hasField($tableName, $field)) {
self::exception(self::DBEXECUTE_ERROR, _s('Table "%1$s" doesn\'t have a field named "%2$s".', $tableName, $field));
}
$sqlWhere[] = dbConditionString($field, zbx_toArray($value));
}
// build query
$sql = 'SELECT * FROM '.$tableName;
if ($sqlWhere) {
$sql .= ' WHERE '.implode(' AND ', $sqlWhere);
}
return DBfetchArray(DBSelect($sql));
}
/**
* Insert data into DB.
*
* @param string $table
* @param array $values pair of fieldname => fieldvalue
* @param bool $getids
*
* @return array an array of ids with the keys preserved
*/
public static function insert($table, $values, $getids = true) {
$table_schema = self::getSchema($table);
$fields = array_reduce($values, 'array_merge', []);
$fields = array_intersect_key($fields, $table_schema['fields']);
foreach ($fields as $field => &$value) {
$value = array_key_exists('default', $table_schema['fields'][$field])
? $table_schema['fields'][$field]['default']
: null;
}
unset($value);
foreach ($values as $key => &$row) {
$row = array_merge($fields, $row);
}
unset($row);
return self::insertBatch($table, $values, $getids);
}
/**
* Returns the list of mandatory fields with default values for INSERT statements.
*
* @static
*
* @param array $table_schema
*
* @return array
*/
private static function getMandatoryFields(array $table_schema): array {
global $DB;
$mandatory_fields = [];
switch ($DB['TYPE']) {
case ZBX_DB_MYSQL:
foreach ($table_schema['fields'] as $name => $field) {
if ($field['type'] == self::FIELD_TYPE_TEXT || $field['type'] == self::FIELD_TYPE_NCLOB) {
$mandatory_fields += [$name => $field['default']];
}
}
break;
case ZBX_DB_ORACLE:
foreach ($table_schema['fields'] as $name => $field) {
if ($field['type'] == self::FIELD_TYPE_BLOB) {
$mandatory_fields += [$name => 'EMPTY_BLOB()'];
}
}
}
return $mandatory_fields;
}
/**
* Add IDs to inserted rows.
*
* @param string $table
* @param array $values
*
* @return array An array of IDs with the keys preserved.
*/
private static function addIds(string $table, array &$values): array {
$table_schema = self::getSchema($table);
$resultids = [];
if ($table_schema['fields'][$table_schema['key']]['type'] === DB::FIELD_TYPE_ID) {
$id = self::reserveIds($table, count($values));
}
foreach ($values as $key => &$row) {
switch ($table_schema['fields'][$table_schema['key']]['type']) {
case DB::FIELD_TYPE_ID:
$resultids[$key] = $id;
$row = [$table_schema['key'] => $id] + $row;
$id = bcadd($id, 1, 0);
break;
case DB::FIELD_TYPE_CUID:
$id = CCuid::generate();
$resultids[$key] = $id;
$row = [$table_schema['key'] => $id] + $row;
break;
}
}
unset($row);
return $resultids;
}
/**
* Insert batch data into DB.
*
* @param string $table
* @param array $values pair of fieldname => fieldvalue
* @param bool $getids
*
* @return array An array of IDs with the keys preserved.
*/
public static function insertBatch($table, $values, $getids = true) {
if (empty($values)) {
return true;
}
$resultids = [];
$table_schema = self::getSchema($table);
$mandatory_fields = self::getMandatoryFields($table_schema);
if ($getids) {
$resultids = self::addIds($table, $values);
}
foreach ($values as &$row) {
$row += $mandatory_fields;
self::checkValueTypes($table_schema, $row);
}
unset($row);
$sql = self::getDbBackend()->createInsertQuery($table, array_keys(reset($values)), $values);
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, _s('SQL statement execution has failed "%1$s".', $sql));
}
return $resultids;
}
/**
* Update data in DB.
*
* @param string $table
* @param array $data
* @param array $data[...]['values'] pair of fieldname => fieldvalue for SET clause
* @param array $data[...]['where'] pair of fieldname => fieldvalue for WHERE clause
*
* @return array of ids
*/
public static function update($table, $data) {
if (empty($data)) {
return true;
}
$tableSchema = self::getSchema($table);
$data = zbx_toArray($data);
foreach ($data as $row) {
// check
self::checkValueTypes($tableSchema, $row['values']);
if (empty($row['values'])) {
self::exception(self::DBEXECUTE_ERROR, _s('Cannot perform update statement on table "%1$s" without values.', $table));
}
// set creation
$sqlSet = '';
foreach ($row['values'] as $field => $value) {
if ($sqlSet !== '') {
$sqlSet .= ',';
}
$sqlSet .= $field.'='.$value;
}
if (!isset($row['where']) || empty($row['where']) || !is_array($row['where'])) {
self::exception(self::DBEXECUTE_ERROR, _s('Cannot perform update statement on table "%1$s" without where condition.', $table));
}
// where condition processing
$sqlWhere = [];
foreach ($row['where'] as $field => $values) {
if (!isset($tableSchema['fields'][$field]) || is_null($values)) {
self::exception(self::DBEXECUTE_ERROR, _s('Incorrect field "%1$s" name or value in where statement for table "%2$s".', $field, $table));
}
$values = zbx_toArray($values);
sort($values); // sorting ids to prevent deadlocks when two transactions depend on each other
$sqlWhere[] = dbConditionString($field, $values);
}
// sql execution
$sql = 'UPDATE '.$table.' SET '.$sqlSet.' WHERE '.implode(' AND ', $sqlWhere);
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, _s('SQL statement execution has failed "%1$s".', $sql));
}
}
return true;
}
/**
* Updates the values by the given PK.
*
* @static
*
* @param string $tableName
* @param string $pk
* @param array $values
*
* @return bool
*/
public static function updateByPk($tableName, $pk, array $values) {
return self::update($tableName, [
'where' => [self::getPk($tableName) => $pk],
'values' => $values
]);
}
/**
* Saves the given records to the database. If the record has the primary key set, it is updated, otherwise - a new
* record is inserted. For new records the newly generated PK is added to the result.
*
* @static
*
* @param $tableName
* @param $data
*
* @return array the same records, that have been passed with the primary keys set for new records
*/
public static function save($tableName, array $data) {
$pk = self::getPk($tableName);
$newRecords = [];
foreach ($data as $key => $record) {
// if the pk is set - update the record
if (isset($record[$pk])) {
self::updateByPk($tableName, $record[$pk], $record);
}
// if no pk is set, create the record later
else {
$newRecords[$key] = $data[$key];
}
}
// insert the new records
if ($newRecords) {
$newIds = self::insert($tableName, $newRecords);
foreach ($newIds as $key => $id) {
$data[$key][$pk] = $id;
}
}
return $data;
}
/**
* Replaces the records given in $oldRecords with the ones in $newRecords.
*
* If a record with the same primary key as a new one already exists in the old records, the record is updated
* only if they are different. For new records the newly generated PK is added to the result. Old records that are
* not present in the new records are deleted.
*
* All of the records must have the primary key defined.
*
* @static
*
* @param $tableName
* @param array $oldRecords
* @param array $newRecords
*
* @return array the new records, that have been passed with the primary keys set for newly inserted records
*/
public static function replace($tableName, array $oldRecords, array $newRecords) {
$pk = self::getPk($tableName);
$oldRecords = zbx_toHash($oldRecords, $pk);
$modifiedRecords = [];
foreach ($newRecords as $key => $record) {
// if it's a new or modified record - save it later
if (!isset($record[$pk]) || self::recordModified($tableName, $oldRecords[$record[$pk]], $record)) {
$modifiedRecords[$key] = $record;
}
// remove the existing records from the collection, the remaining ones will be deleted
if(isset($record[$pk])) {
unset($oldRecords[$record[$pk]]);
}
}
// save modified records
if ($modifiedRecords) {
$modifiedRecords = self::save($tableName, $modifiedRecords);
// add the new IDs to the new records
foreach ($modifiedRecords as $key => $record) {
$newRecords[$key][$pk] = $record[$pk];
}
}
// delete remaining records
if ($oldRecords) {
DB::delete($tableName, [
$pk => array_keys($oldRecords)
]);
}
return $newRecords;
}
/**
* Replaces the records given in $groupedOldRecords with the ones given in $groupedNewRecords.
*
* This method can be used to replace related objects in one-to-many relations. Both old and new records
* must be grouped by the ID of the record they belong to. The records will be matched by position, instead of
* the primary key as in DB::replace(). That is, the first new record will update the first old one, second new
* record - the second old one, etc. Since the records are matched by position, the new records should not contain
* primary keys.
*
* Example 1:
* $old = array(2 => array( array('gitemid' => 1, 'color' => 'FF0000') ));
* $new = array(2 => array( array('color' => '00FF00') ));
* var_dump(DB::replaceByPosition('items', $old, $new));
* // array(array('gitemid' => 1, 'color' => '00FF00'))
*
* The new record updated the old one.
*
* Example 2:
* $old = array(2 => array( array('gitemid' => 1, 'color' => 'FF0000') ));
* $new = array(
* 2 => array(
* array('color' => '00FF00'),
* array('color' => '0000FF')
* )
* );
* var_dump(DB::replaceByPosition('items', $old, $new));
* // array(array('gitemid' => 1, 'color' => '00FF00'), array('gitemid' => 2, 'color' => '0000FF'))
*
* The first record was updated, the second one - created.
*
* Example 3:
* $old = array(
* 2 => array(
* array('gitemid' => 1, 'color' => 'FF0000'),
* array('gitemid' => 2, 'color' => '0000FF')
* )
* );
* $new = array(2 => array( array('color' => '00FF00') ));
* var_dump(DB::replaceByPosition('items', $old, $new));
* // array(array('gitemid' => 1, 'color' => '00FF00'))
*
* The first record was updated, the second one - deleted.
*
* @param string $tableName table to update
* @param array $groupedOldRecords grouped old records
* @param array $groupedNewRecords grouped new records
*
* @return array array of new records not grouped (!).
*/
public static function replaceByPosition($tableName, array $groupedOldRecords, array $groupedNewRecords) {
$pk = self::getPk($tableName);
$allOldRecords = [];
$allNewRecords = [];
foreach ($groupedNewRecords as $key => $newRecords) {
// if records exist for the parent object - replace them, otherwise create new records
if (isset($groupedOldRecords[$key])) {
$oldRecords = $groupedOldRecords[$key];
// updated the records by position
$newRecords = self::mergeRecords($oldRecords, $newRecords, $pk);
foreach ($oldRecords as $record) {
$allOldRecords[] = $record;
}
}
foreach ($newRecords as $record) {
$allNewRecords[] = $record;
}
}
// replace the old records with the new ones
return self::replace($tableName, $allOldRecords, $allNewRecords);
}
/**
* Compares the fields, that are present in both records, and returns true if any of the values differ.
*
* @static
* @param $tableName
* @param array $oldRecord
* @param array $newRecord
*
* @return bool
*/
public static function recordModified($tableName, array $oldRecord, array $newRecord) {
foreach ($oldRecord as $field => $value) {
if (self::hasField($tableName, $field)
&& isset($newRecord[$field])
&& (string) $value !== (string) $newRecord[$field]) {
return true;
}
}
return false;
}
/**
* Replace each record in $oldRecords with a corresponding record in $newRecords, but keep the old record IDs.
* The records are match by position, that is, the first new record, replaces the first old record and etc.
* If there are less $newRecords than $oldRecords, the remaining old records will be discarded.
*
* @param array $oldRecords array of old records
* @param array $newRecords array of new records
* @param string $pk name of the private key column
*
* @return array array of new records with the primary keys from the old ones
*/
protected static function mergeRecords(array $oldRecords, array $newRecords, $pk) {
$result = [];
foreach ($newRecords as $i => $record) {
if (isset($oldRecords[$i])) {
$record[$pk] = $oldRecords[$i][$pk];
}
$result[] = $record;
}
return $result;
}
/**
* Delete data from DB.
*
* Example:
* DB::delete('items', ['itemid' => [1, 8, 6]]);
* DELETE FROM items WHERE itemid IN (1, 8, 6)
*
* DB::delete('items', ['itemid' => [1], 'templateid' => [10]]);
* DELETE FROM items WHERE itemid IN (1) AND templateid IN (10)
*
* @param string $table
* @param array $wheres pair of fieldname => fieldvalues
* @param bool $use_or
*
* @return bool
*/
public static function delete($table, $wheres, $use_or = false) {
if (empty($wheres) || !is_array($wheres)) {
self::exception(self::DBEXECUTE_ERROR, _s('Cannot perform delete statement on table "%1$s" without where condition.', $table));
}
$table_schema = self::getSchema($table);
$sqlWhere = [];
foreach ($wheres as $field => $values) {
if (!isset($table_schema['fields'][$field]) || is_null($values)) {
self::exception(self::DBEXECUTE_ERROR, _s('Incorrect field "%1$s" name or value in where statement for table "%2$s".', $field, $table));
}
$values = zbx_toArray($values);
sort($values); // sorting ids to prevent deadlocks when two transactions depends from each other
$sqlWhere[] = dbConditionString($field, $values);
}
$sql = 'DELETE FROM '.$table.' WHERE '.implode(($use_or ? ' OR ' : ' AND '), $sqlWhere);
if (!DBexecute($sql)) {
self::exception(self::DBEXECUTE_ERROR, _s('SQL statement execution has failed "%1$s"', $sql));
}
return true;
}
/**
* @param string $table_name
* @param array $options
* @param string $table_alias
*
* @return string
*/
public static function makeSql($table_name, array &$options, $table_alias = null) {
$defaults = [
'output' => [],
'countOutput' => false,
'filter' => [],
'search' => [],
'startSearch' => false,
'searchByAny' => false,
'sortfield' => [],
'sortorder' => [],
'limit' => null,
'preservekeys' => false
];
if ($array_diff = array_diff_key($options, $defaults)) {
unset($array_diff[self::getPk($table_name).'s']);
if ($array_diff) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: unsupported option "%s".', [__FUNCTION__, key($array_diff)])
);
}
}
$options = zbx_array_merge($defaults, $options);
$sql_parts = self::createSelectQueryParts($table_name, $options, $table_alias);
return 'SELECT '.implode(',', $sql_parts['select']).
' FROM '.implode(',', $sql_parts['from']).
($sql_parts['where'] ? ' WHERE '.implode(' AND ', $sql_parts['where']) : '').
($sql_parts['order'] ? ' ORDER BY '.implode(',', $sql_parts['order']) : '');
}
/**
* @param string $table_name
* @param array $options
* @param string $table_alias
*
* @return array
*/
public static function select($table_name, array $options, $table_alias = null) {
$db_result = DBSelect(self::makeSql($table_name, $options, $table_alias), $options['limit']);
if ($options['countOutput']) {
return DBfetch($db_result)['rowscount'];
}
$result = [];
$field_names = array_flip($options['output']);
if ($options['preservekeys']) {
$pk = self::getPk($table_name);
while ($db_row = DBfetch($db_result)) {
$result[$db_row[$pk]] = array_intersect_key($db_row, $field_names);
}
}
else {
while ($db_row = DBfetch($db_result)) {
$result[] = array_intersect_key($db_row, $field_names);
}
}
return $result;
}
/**
* Returns the table name with the table alias.
*
* @param string $table_name
* @param string $table_alias
*
* @return string
*/
private static function tableId($table_name, $table_alias = null) {
return($table_alias !== null) ? $table_name.' '.$table_alias : $table_name;
}
/**
* Prepends the table alias to the given field name.
*
* @param string $field_name
* @param string $table_alias
*
* @return string
*/
private static function fieldId($field_name, $table_alias = null) {
return ($table_alias !== null) ? $table_alias.'.'.$field_name : $field_name;
}
/**
* Builds an SQL parts array from the given options.
*
* @param string $table_name
* @param array $options
* @param string $table_alias
*
* @return array The resulting SQL parts array
*/
private static function createSelectQueryParts($table_name, array $options, $table_alias = null) {
$sql_parts = [
'select' => [],
'from' => [self::tableId($table_name, $table_alias)],
'where' => [],
'order' => []
];
// add output options
$sql_parts = self::applyQueryOutputOptions($table_name, $options, $table_alias, $sql_parts);
// add filter options
$sql_parts = self::applyQueryFilterOptions($table_name, $options, $table_alias, $sql_parts);
// add search options
$sql_parts = self::applyQuerySearchOptions($table_name, $options, $table_alias, $sql_parts);
// add sort options
$sql_parts = self::applyQuerySortOptions($table_name, $options, $table_alias, $sql_parts);
return $sql_parts;
}
/**
* Modifies the SQL parts to implement all of the output related options.
*
* @param string $table_name
* @param array $options
* @param string $table_alias
* @param array $sql_parts
*
* @return array
*/
private static function applyQueryOutputOptions($table_name, array $options, $table_alias = null,
array $sql_parts) {
if ($options['countOutput']) {
$sql_parts['select'][] = 'COUNT('.self::fieldId('*', $table_alias).') AS rowscount';
}
else {
$table_schema = self::getSchema($table_name);
$select = [];
$select[self::fieldId(self::getPk($table_name), $table_alias)] = true;
foreach ($options['output'] as $field_name) {
if (!array_key_exists($field_name, $table_schema['fields'])) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" does not exist.', [__FUNCTION__, $table_name, $field_name])
);
}
$select[self::fieldId($field_name, $table_alias)] = true;
}
$sql_parts['select'] = array_keys($select);
}
return $sql_parts;
}
/**
* Modifies the SQL parts to implement all of the filter related options.
*
* @param string $table_name
* @param array $options
* @param string $table_alias
* @param array $sql_parts
*
* @return array
*/
private static function applyQueryFilterOptions($table_name, array $options, $table_alias = null,
array $sql_parts) {
$table_schema = self::getSchema($table_name);
$pk = self::getPk($table_name);
$pk_option = $pk.'s';
// pks
if (array_key_exists($pk_option, $options)) {
if (!is_array($options[$pk_option])) {
$options[$pk_option] = [$options[$pk_option]];
}
$field_schema = $table_schema['fields'][$pk];
$field_name = self::fieldId($pk, $table_alias);
switch ($field_schema['type']) {
case self::FIELD_TYPE_ID:
$sql_parts['where'][] = dbConditionId($field_name, $options[$pk_option]);
break;
case self::FIELD_TYPE_INT:
case self::FIELD_TYPE_UINT:
$sql_parts['where'][] = dbConditionInt($field_name, $options[$pk_option]);
break;
default:
$sql_parts['where'][] = dbConditionString($field_name, $options[$pk_option]);
}
}
// filters
if (is_array($options['filter'])) {
$sql_parts = self::dbFilter($table_name, $options, $table_alias, $sql_parts);
}
return $sql_parts;
}
/**
* Modifies the SQL parts to implement all of the search related options.
*
* @param string $table_name
* @param array $options
* @param array $options['search']
* @param bool $options['startSearch']
* @param bool $options['searchByAny']
* @param string $table_alias
* @param array $sql_parts
*
* @return array
*/
private static function applyQuerySearchOptions($table_name, array $options, $table_alias = null,
array $sql_parts) {
global $DB;
$table_schema = DB::getSchema($table_name);
$unsupported_types = [self::FIELD_TYPE_INT, self::FIELD_TYPE_ID, self::FIELD_TYPE_FLOAT, self::FIELD_TYPE_UINT,
self::FIELD_TYPE_BLOB
];
$start = $options['startSearch'] ? '' : '%';
$glue = $options['searchByAny'] ? ' OR ' : ' AND ';
$search = [];
foreach ($options['search'] as $field_name => $patterns) {
if (!array_key_exists($field_name, $table_schema['fields'])) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" does not exist.', [__FUNCTION__, $table_name, $field_name])
);
}
$field_schema = $table_schema['fields'][$field_name];
if (in_array($field_schema['type'], $unsupported_types)) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" has an unsupported type.', [__FUNCTION__, $table_name, $field_name])
);
}
if ($patterns === null) {
continue;
}
foreach ((array) $patterns as $pattern) {
// escaping parameter that is about to be used in LIKE statement
$pattern = mb_strtoupper(strtr($pattern, ['!' => '!!', '%' => '!%', '_' => '!_']));
$pattern = $start.$pattern.'%';
if ($DB['TYPE'] == ZBX_DB_ORACLE && $field_schema['type'] === DB::FIELD_TYPE_NCLOB
&& strlen($pattern) > ORACLE_MAX_STRING_SIZE) {
$chunks = zbx_dbstr(DB::chunkMultibyteStr($pattern, ORACLE_MAX_STRING_SIZE));
$pattern = 'TO_NCLOB('.implode(') || TO_NCLOB(', $chunks).')';
}
else {
$pattern = zbx_dbstr($pattern);
}
$search[] = 'UPPER('.self::fieldId($field_name, $table_alias).') LIKE '.$pattern." ESCAPE '!'";
}
}
if ($search) {
$sql_parts['where'][] = ($options['searchByAny'] && count($search) > 1)
? '('.implode($glue, $search).')'
: implode($glue, $search);
}
return $sql_parts;
}
/**
* Apply filter conditions to sql built query.
*
* @param string $table_name
* @param array $options
* @param string $table_alias
* @param array $sql_parts
*
* @return bool
*/
private static function dbFilter($table_name, $options, $table_alias = null, $sql_parts) {
$table_schema = self::getSchema($table_name);
$filter = [];
foreach ($options['filter'] as $field_name => $value) {
if (!array_key_exists($field_name, $table_schema['fields'])) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" does not exist.', [__FUNCTION__, $table_name, $field_name])
);
}
$field_schema = $table_schema['fields'][$field_name];
if ($field_schema['type'] == self::FIELD_TYPE_TEXT || $field_schema['type'] == self::FIELD_TYPE_NCLOB) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" has an unsupported type.', [__FUNCTION__, $table_name, $field_name])
);
}
if ($value === null) {
continue;
}
if (!is_array($value)) {
$value = [$value];
}
switch ($field_schema['type']) {
case self::FIELD_TYPE_ID:
$filter[] = dbConditionId(self::fieldId($field_name, $table_alias), $value);
break;
case self::FIELD_TYPE_INT:
case self::FIELD_TYPE_UINT:
$filter[] = dbConditionInt(self::fieldId($field_name, $table_alias), $value);
break;
default:
$filter[] = dbConditionString(self::fieldId($field_name, $table_alias), $value);
}
}
if ($filter) {
$sql_parts['where'][] = implode(' AND ', $filter);
}
return $sql_parts;
}
/**
* Modifies the SQL parts to implement all of the sorting related options.
*
* @param string $table_name
* @param array $options
* @param string $table_alias
* @param array $sql_parts
*
* @return array
*/
private static function applyQuerySortOptions($table_name, array $options, $table_alias = null, array $sql_parts) {
$table_schema = self::getSchema($table_name);
foreach ($options['sortfield'] as $index => $field_name) {
if (!array_key_exists($field_name, $table_schema['fields'])) {
self::exception(self::SCHEMA_ERROR,
vsprintf('%s: field "%s.%s" does not exist.', [__FUNCTION__, $table_name, $field_name])
);
}
$sortorder = '';
if (array_key_exists($index, $options['sortorder']) && $options['sortorder'][$index] == ZBX_SORT_DOWN) {
$sortorder = ' '.ZBX_SORT_DOWN;
}
$sql_parts['order'][] = self::fieldId($field_name, $table_alias).$sortorder;
}
return $sql_parts;
}
}
|