summaryrefslogtreecommitdiffstats
path: root/config-db/OpenSLX/MetaDB/DBI.pm
blob: a5a8e68eab14d4877006d930f01030986184aee1 (plain) (blame)
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
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
# Copyright (c) 2006, 2007 - OpenSLX GmbH
#
# This program is free software distributed under the GPL version 2.
# See http://openslx.org/COPYING
#
# If you have any feedback please consult http://openslx.org/feedback and
# send your suggestions, praise, or complaints to feedback@openslx.org
#
# General information about OpenSLX can be found at http://openslx.org/
# -----------------------------------------------------------------------------
# DBI.pm
#    - provides DBI-based implementation of the OpenSLX MetaDB API.
# -----------------------------------------------------------------------------
package OpenSLX::MetaDB::DBI;

use strict;
use warnings;

use base qw(OpenSLX::MetaDB::Base);

use DBI;
use OpenSLX::Basics;
use OpenSLX::Utils;

################################################################################
### basics
################################################################################
sub new
{
    confess "Don't call OpenSLX::MetaDB::DBI::new directly!";
}

sub disconnect
{
    my $self = shift;

    $self->{'dbh'}->disconnect;
    $self->{'dbh'} = undef;
    return;
}

sub quote
{   # default implementation quotes any given values through the DBI
    my $self = shift;

    return $self->{'dbh'}->quote(@_);
}

sub startTransaction
{   # default implementation passes on the request to the DBI
    my $self = shift;

    return $self->{'dbh'}->begin_work();
}

sub commitTransaction
{   # default implementation passes on the request to the DBI
    my $self = shift;

    return $self->{'dbh'}->commit();
}

sub rollbackTransaction
{   # default implementation passes on the request to the DBI
    my $self = shift;

    return $self->{'dbh'}->rollback();
}

################################################################################
### data access
################################################################################
sub _trim
{
    my $s = shift;
    $s =~ s[^\s*(.*?)\s*$][$1];
    return $s;
}

sub _buildFilterClause
{
    my $self         = shift;
    my $filter       = shift || {};
    my $filterClause = shift || '';

    my ($connector, $quotedVal);
    foreach my $col (keys %$filter) {
        $connector = !length($filterClause) ? 'WHERE' : 'AND';
        if (defined $filter->{$col}) {
            $quotedVal = $self->{dbh}->quote($filter->{$col});
            $filterClause .= unshiftHereDoc(<<"            End-of-Here");
                $connector $col = $quotedVal
            End-of-Here
        } else {
            $filterClause .= unshiftHereDoc(<<"            End-of-Here");
                $connector $col IS NULL
            End-of-Here
        }
    }
    
    return $filterClause || '';
}

sub _buildAttrFilterClause
{
    my $self         = shift;
    my $attrFilter   = shift || {};
    my $table        = shift;
    my $filterClause = shift || '';

    my %tableMap = (
        'client' => 'client',
        'group'  => 'groups',
        'system' => 'system',
    );

    my ($connector, $quotedName, $quotedValue);
    foreach my $name (keys %$attrFilter) {
        $connector = !length($filterClause) ? 'WHERE' : 'AND';
        $quotedName = $self->{dbh}->quote($name);
        if (defined $attrFilter->{$name}) {
            $quotedValue = $self->{dbh}->quote($attrFilter->{$name});
            $filterClause .= unshiftHereDoc(<<"            End-of-Here");
                $connector EXISTS (
                    SELECT name FROM ${table}_attr
                    WHERE name = $quotedName 
                    AND value = $quotedValue
                    AND ${table}_id = $tableMap{$table}.id
                )
            End-of-Here
        } else {
            $filterClause .= unshiftHereDoc(<<"            End-of-Here");
                $connector NOT EXISTS (
                    SELECT name FROM ${table}_attr
                    WHERE name = $quotedName 
                    AND ${table}_id = $tableMap{$table}.id
                )
            End-of-Here
        }
    }

    return $filterClause;
}

sub _doSelect
{
    my $self      = shift;
    my $sql       = shift;
    my $resultCol = shift;

    my $dbh = $self->{'dbh'};

    vlog(3, _trim($sql));
    my $sth = $dbh->prepare($sql)
        or croak _tr(
            q[Can't prepare SQL-statement <%s> (%s)], $sql, $dbh->errstr
        );
    $sth->execute()
        or croak _tr(
            q[Can't execute SQL-statement <%s> (%s)], $sql, $dbh->errstr
        );
    my @vals;
    while (my $row = $sth->fetchrow_hashref()) {
        if (defined $resultCol) {
            return $row->{$resultCol} unless wantarray();
            push @vals, $row->{$resultCol};
        } else {
            return $row unless wantarray();
            push @vals, $row;
        }
    }

    # return undef if there's no result in scalar context
    return if !wantarray();        

    return @vals;
}

sub fetchVendorOSByFilter
{
    my $self       = shift;
    my $filter     = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $filterClause = $self->_buildFilterClause($filter);
    my $sql = "SELECT $resultCols FROM vendor_os $filterClause";
    return $self->_doSelect($sql);
}

sub fetchVendorOSByID
{
    my $self       = shift;
    my $ids        = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $idStr = join ',', @$ids;
    return if !length($idStr);
    my $sql = "SELECT $resultCols FROM vendor_os WHERE id IN ($idStr)";
    return $self->_doSelect($sql);
}

sub fetchInstalledPlugins
{
    my $self       = shift;
    my $vendorOSID = shift;
    my $pluginName = shift;
    my $fullInfo   = shift || 0;

    return if !defined $vendorOSID;
    my $nameClause 
        = defined $pluginName 
            ? "AND plugin_name = '$pluginName'" 
            : '';
    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT * FROM installed_plugin
        WHERE vendor_os_id = '$vendorOSID'
        $nameClause
    End-of-Here
    my @pluginInfos = $self->_doSelect($sql);
    return if !@pluginInfos;
    
    @pluginInfos = map {
        my $pluginInfo = $_;
        my $sql = unshiftHereDoc(<<"        End-of-Here");
            SELECT * FROM installed_plugin_attr
            WHERE installed_plugin_id = '$pluginInfo->{id}'
        End-of-Here
        my @attrs = $self->_doSelect($sql);
        $pluginInfo->{attrs} = {
            map { 
                ( $_->{name}, $fullInfo ? $_ : $_->{value} ) 
            } @attrs
        };
        $pluginInfo;
    }
    @pluginInfos;
    
    return wantarray() ? @pluginInfos : $pluginInfos[0];
}

sub fetchExportByFilter
{
    my $self       = shift;
    my $filter     = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $filterClause = $self->_buildFilterClause($filter);
    my $sql = "SELECT $resultCols FROM export $filterClause";
    return $self->_doSelect($sql);
}

sub fetchExportByID
{
    my $self       = shift;
    my $ids        = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $idStr = join ',', @$ids;
    return if !length($idStr);
    my $sql = "SELECT $resultCols FROM export WHERE id IN ($idStr)";
    return $self->_doSelect($sql);
}

sub fetchExportIDsOfVendorOS
{
    my $self       = shift;
    my $vendorOSID = shift;

    my $sql = qq[
        SELECT id FROM export WHERE vendor_os_id = '$vendorOSID'
    ];
    return $self->_doSelect($sql, 'id');
}

sub fetchGlobalInfo
{
    my $self = shift;
    my $id   = shift;

    return if !length($id);
    my $sql = "SELECT value FROM global_info WHERE id = " . $self->quote($id);
    return $self->_doSelect($sql, 'value');
}

sub fetchSystemByFilter
{
    my $self       = shift;
    my $filter     = shift;
    my $resultCols = shift;
    my $attrFilter = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $filterClause = $self->_buildFilterClause($filter);
    $filterClause = $self->_buildAttrFilterClause(
        $attrFilter, 'system', $filterClause
    );
    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT $resultCols FROM system
        $filterClause
    End-of-Here
    return $self->_doSelect($sql);
}

sub fetchSystemByID
{
    my $self       = shift;
    my $ids        = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $idStr = join ',', @$ids;
    return if !length($idStr);
    my $sql = "SELECT $resultCols FROM system WHERE id IN ($idStr)";
    return $self->_doSelect($sql);
}

sub fetchSystemAttrs
{
    my $self     = shift;
    my $systemID = $self->{dbh}->quote(shift);

    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT name, value FROM system_attr
        WHERE system_id = $systemID
    End-of-Here
    my @attrs = $self->_doSelect($sql);
    my $Result = {};
    foreach my $attr (@attrs) {
        $Result->{$attr->{name}} = $attr->{value};
    }
    return $Result;
}

sub fetchSystemIDsOfExport
{
    my $self     = shift;
    my $exportID = shift;

    my $sql = qq[
        SELECT id FROM system WHERE export_id = '$exportID'
    ];
    return $self->_doSelect($sql, 'id');
}

sub fetchSystemIDsOfClient
{
    my $self     = shift;
    my $clientID = shift;

    my $sql = qq[
        SELECT system_id FROM client_system_ref WHERE client_id = '$clientID'
    ];
    return $self->_doSelect($sql, 'system_id');
}

sub fetchSystemIDsOfGroup
{
    my $self    = shift;
    my $groupID = shift;

    my $sql = qq[
        SELECT system_id FROM group_system_ref WHERE group_id = '$groupID'
    ];
    return $self->_doSelect($sql, 'system_id');
}

sub fetchClientByFilter
{
    my $self       = shift;
    my $filter     = shift;
    my $resultCols = shift;
    my $attrFilter = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $filterClause = $self->_buildFilterClause($filter);
    $filterClause = $self->_buildAttrFilterClause(
        $attrFilter, 'client', $filterClause
    );
    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT $resultCols FROM client
        $filterClause
    End-of-Here
    return $self->_doSelect($sql);
}

sub fetchClientByID
{
    my $self       = shift;
    my $ids        = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $idStr = join ',', @$ids;
    return if !length($idStr);
    my $sql = "SELECT $resultCols FROM client WHERE id IN ($idStr)";
    return $self->_doSelect($sql);
}

sub fetchClientAttrs
{
    my $self     = shift;
    my $clientID = $self->{dbh}->quote(shift);

    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT name, value FROM client_attr
        WHERE client_id = $clientID
    End-of-Here
    my @attrs = $self->_doSelect($sql);
    my $Result = {};
    foreach my $attr (@attrs) {
        $Result->{$attr->{name}} = $attr->{value};
    }
    return $Result;
}

sub fetchClientIDsOfSystem
{
    my $self     = shift;
    my $systemID = shift;

    my $sql = qq[
        SELECT client_id FROM client_system_ref WHERE system_id = '$systemID'
    ];
    return $self->_doSelect($sql, 'client_id');
}

sub fetchClientIDsOfGroup
{
    my $self    = shift;
    my $groupID = shift;

    my $sql = qq[
        SELECT client_id FROM group_client_ref WHERE group_id = '$groupID'
    ];
    return $self->_doSelect($sql, 'client_id');
}

sub fetchGroupByFilter
{
    my $self       = shift;
    my $filter     = shift;
    my $resultCols = shift;
    my $attrFilter = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $filterClause = $self->_buildFilterClause($filter);
    $filterClause = $self->_buildAttrFilterClause(
        $attrFilter, 'group', $filterClause
    );
    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT $resultCols FROM groups
        $filterClause
    End-of-Here
    return $self->_doSelect($sql);
}

sub fetchGroupByID
{
    my $self       = shift;
    my $ids        = shift;
    my $resultCols = shift;

    $resultCols = '*' unless (defined $resultCols);
    my $idStr = join ',', @$ids;
    return if !length($idStr);
    my $sql = "SELECT $resultCols FROM groups WHERE id IN ($idStr)";
    return $self->_doSelect($sql);
}

sub fetchGroupAttrs
{
    my $self    = shift;
    my $groupID = $self->{dbh}->quote(shift);

    my $sql = unshiftHereDoc(<<"    End-of-Here");
        SELECT name, value FROM group_attr
        WHERE group_id = $groupID
    End-of-Here
    my @attrs = $self->_doSelect($sql);
    my $Result = {};
    foreach my $attr (@attrs) {
        $Result->{$attr->{name}} = $attr->{value};
    }
    return $Result;
}

sub fetchGroupIDsOfSystem
{
    my $self     = shift;
    my $systemID = shift;

    my $sql = qq[
        SELECT group_id FROM group_system_ref WHERE system_id = '$systemID'
    ];
    return $self->_doSelect($sql, 'group_id');
}

sub fetchGroupIDsOfClient
{
    my $self     = shift;
    my $clientID = shift;

    my $sql = qq[
        SELECT group_id FROM group_client_ref WHERE client_id = '$clientID'
    ];
    return $self->_doSelect($sql, 'group_id');
}

################################################################################
### data manipulation functions
################################################################################
sub _doInsert
{
    my $self      = shift;
    my $table     = shift;
    my $valRows   = shift;
    my $ignoreIDs = shift;

    my $dbh    = $self->{'dbh'};
    my $valRow = (@$valRows)[0];
    return if !defined $valRow || !scalar keys %$valRow;

    if ($table =~ m[_ref$]) {
        # reference tables do not have IDs:
        $ignoreIDs = 1;
    }

    my $needToGenerateIDs = $self->generateNextIdForTable(undef);
    if (!$ignoreIDs && $needToGenerateIDs) {
        # DB requires pre-specified IDs, so we add the 'id' column:
        $valRow->{id} = undef unless exists $valRow->{id};
    }
    my @ids;
    foreach my $valRow (@$valRows) {
        if (!defined $valRow->{id} && !$ignoreIDs && $needToGenerateIDs) {
            # let DB-backend pre-specify ID, as current DB can't generate IDs:
            $valRow->{id} = $self->generateNextIdForTable($table);
            vlog(3, "generated id for <$table> is <$valRow->{id}>");
        }
        my $cols = join ', ', keys %$valRow;
        my $values = join ', ',
          map { $self->quote($valRow->{$_}) } keys %$valRow;
        my $sql = "INSERT INTO $table ( $cols ) VALUES ( $values )";
        vlog(3, $sql);
        my $sth = $dbh->prepare($sql)
          or croak _tr(q[Can't insert into table <%s> (%s)], $table,
            $dbh->errstr);
        $sth->execute()
          or croak _tr(q[Can't insert into table <%s> (%s)], $table,
            $dbh->errstr);
        if (!$ignoreIDs) {
            my $lastID = $dbh->last_insert_id(undef, undef, $table, 'id');
            if (!defined $valRow->{id}) {
                # id has not been pre-specified, we need to fetch it from DB:
                $valRow->{'id'} = $lastID;
                vlog(3, "DB-generated id for <$table> is <$valRow->{id}>");
            }
            elsif ($valRow->{'id'} ne $lastID) {
                # id has been pre-specified, but DB changed it, so we update
                # it with the pre-specified value
                my $sql2 = unshiftHereDoc(<<"                End-of-Here");
                    UPDATE $table SET id='$valRow->{'id'}' WHERE id='$lastID'
                End-of-Here
                vlog(3, $sql2);
                $dbh->do($sql2) or croak _tr(
                    q[Can't update table <%s> (%s)], $table, $dbh->errstr
                );
            }
        }
        push @ids, $valRow->{'id'};
    }
    return wantarray() ? @ids : shift @ids;
}

sub _doDelete
{
    my $self                  = shift;
    my $table                 = shift;
    my $IDs                   = shift;
    my $idCol                 = shift;
    my $additionalWhereClause = shift;

    my $dbh = $self->{'dbh'};

    $IDs   = [undef] unless defined $IDs;
    $idCol = 'id'    unless defined $idCol;
    foreach my $id (@$IDs) {
        my $sql = "DELETE FROM $table";
        if (defined $id) {
            $sql .= " WHERE $idCol = " . $self->quote($id);
            if (defined $additionalWhereClause) {
                $sql .= $additionalWhereClause;
            }
        }
        vlog(3, $sql);
        my $sth = $dbh->prepare($sql)
          or croak _tr(q[Can't delete from table <%s> (%s)], $table,
            $dbh->errstr);
        $sth->execute()
          or croak _tr(q[Can't delete from table <%s> (%s)], $table,
            $dbh->errstr);
    }
    return 1;
}

sub _doUpdate
{
    my $self    = shift;
    my $table   = shift;
    my $IDs     = shift;
    my $valRows = shift;

    my $dbh    = $self->{'dbh'};
    my $valRow = (@$valRows)[0];
    return 1 if !defined $valRow || !scalar keys %$valRow;

    my $idx = 0;
    foreach my $valRow (@$valRows) {
        my $id      = $IDs->[$idx++];
        my %valData = %$valRow;
        # fail if asked to change the column 'id', as that is bogus
        return if exists $valData{id} && $valData{id} ne $id;
        # filter column 'id' if present, as we don't want to write it
        delete $valData{id};
        my @cols = map { "$_ = " . $self->quote($valRow->{$_}) }
          grep { $_ ne 'id' }
          # filter column 'id' if present, as we don't want
          # to update it!
          keys %$valRow;
        next if !@cols;
        my $cols = join ', ', @cols;
        my $sql = "UPDATE $table SET $cols";
        if (defined $id) {
            $sql .= " WHERE id = " . $self->quote($id);
        }
        vlog(3, $sql);
        my $sth = $dbh->prepare($sql)
          or croak _tr(q[Can't update table <%s> (%s)], $table, $dbh->errstr);
        $sth->execute()
          or croak _tr(q[Can't update table <%s> (%s)], $table, $dbh->errstr);
    }
    return 1;
}

sub _updateRefTable
{
    my $self        = shift;
    my $table       = shift;
    my $keyID       = shift;
    my $newValueIDs = shift;
    my $keyCol      = shift;
    my $valueCol    = shift;
    my $oldValueIDs = shift;

    my %lastValueIDs;
    @lastValueIDs{@$oldValueIDs} = ();

    foreach my $valueID (@$newValueIDs) {
        if (!exists $lastValueIDs{$valueID}) {
            # value-ID is new, create it
            my $valRow = {
                $keyCol   => $keyID,
                $valueCol => $valueID,
            };
            $self->_doInsert($table, [$valRow]);
        } else {
            # value-ID already exists, leave as is, but remove from hash:
            delete $lastValueIDs{$valueID};
        }
    }

    # all the remaining value-IDs need to be removed:
    if (scalar keys %lastValueIDs) {
        $self->_doDelete($table, [keys %lastValueIDs],
            $valueCol, " AND $keyCol='$keyID'");
    }
    return 1;
}

sub _updateOneToManyRefAttr
{
    my $self       = shift;
    my $table      = shift;
    my $oneID      = shift;
    my $newManyIDs = shift;
    my $fkCol      = shift;
    my $oldManyIDs = shift;

    my %lastManyIDs;
    @lastManyIDs{@$oldManyIDs} = ();

    foreach my $id (@$newManyIDs) {
        if (!exists $lastManyIDs{$id}) {
            # ID has changed, update it
            $self->_doUpdate($table, $id, [{$fkCol => $oneID}]);
        } else {
            # ID hasn't changed, leave as is, but remove from hash:
            delete $lastManyIDs{$id};
        }
    }

    # all the remaining many-IDs need to be set to 0:
    foreach my $id (scalar keys %lastManyIDs) {
        $self->_doUpdate($table, $id, [{$fkCol => '0'}]);
    }
    return 1;
}

sub addVendorOS
{
    my $self    = shift;
    my $valRows = shift;

    return $self->_doInsert('vendor_os', $valRows);
}

sub removeVendorOS
{
    my $self        = shift;
    my $vendorOSIDs = shift;

    return $self->_doDelete('vendor_os', $vendorOSIDs);
}

sub changeVendorOS
{
    my $self        = shift;
    my $vendorOSIDs = shift;
    my $valRows     = shift;

    return $self->_doUpdate('vendor_os', $vendorOSIDs, $valRows);
}

sub addInstalledPlugin
{
    my $self        = shift;
    my $vendorOSID  = shift;
    my $pluginName  = shift;
    my $newAttrs    = shift;

    return if !defined $vendorOSID || !$pluginName;

    my $installedPlugin 
        = $self->fetchInstalledPlugins($vendorOSID, $pluginName, 1);
    if (!$installedPlugin) {
        return if !$self->_doInsert('installed_plugin', [ {
            vendor_os_id => $vendorOSID,
            plugin_name  => $pluginName,
        } ] );
        $installedPlugin 
            = $self->fetchInstalledPlugins($vendorOSID, $pluginName, 1);
    }
    return if !$installedPlugin;

    # determine the required attribute actions ...
    my $oldAttrs = $installedPlugin->{attrs} || {};
    my @attrsToBeInserted
        = grep { 
            exists $newAttrs->{$_} && !exists $oldAttrs->{$_}
        } keys %$newAttrs;
    my @attrsToBeDeleted = grep { !exists $newAttrs->{$_} } keys %$oldAttrs;
    my @attrsToBeUpdated
        = grep { 
            exists $newAttrs->{$_} && exists $oldAttrs->{$_}
            && ($oldAttrs->{$_}->{value} || '-') ne ($newAttrs->{$_} || '-')
        } keys %$newAttrs;

    # ... insert the new ones ...
    my @attrData 
        =   map {
                {
                    installed_plugin_id => $installedPlugin->{id},
                    name                => $_,
                    value               => $newAttrs->{$_},
                }
            }
            @attrsToBeInserted;
    $self->_doInsert('installed_plugin_attr', \@attrData);

    # ... delete the old ones ...
    my @oldIDs = map { $oldAttrs->{$_}->{id} } @attrsToBeDeleted;
    $self->_doDelete('installed_plugin_attr', \@oldIDs);

    # ... and update the changed ones ...
    my @IDs   = map { $oldAttrs->{$_}->{id} } @attrsToBeUpdated;
    @attrData = map { { value => $newAttrs->{$_} } } @attrsToBeUpdated;
    $self->_doUpdate('installed_plugin_attr', \@IDs, \@attrData);

    return 1;
}

sub removeInstalledPlugin
{
    my $self       = shift;
    my $vendorOSID = shift;
    my $pluginName = shift;

    return if !defined $vendorOSID || !$pluginName;

    my $plugin = $self->fetchInstalledPlugins($vendorOSID, $pluginName);
    return if !$plugin;
    return if !$self->_doDelete(
        'installed_plugin_attr', [ $plugin->{id} ], 'installed_plugin_id' 
    );
    return $self->_doDelete('installed_plugin', [ $plugin->{id} ] );
}

sub addExport
{
    my $self    = shift;
    my $valRows = shift;

    return $self->_doInsert('export', $valRows);
}

sub removeExport
{
    my $self      = shift;
    my $exportIDs = shift;

    return $self->_doDelete('export', $exportIDs);
}

sub changeExport
{
    my $self      = shift;
    my $exportIDs = shift;
    my $valRows   = shift;

    return $self->_doUpdate('export', $exportIDs, $valRows);
}

sub changeGlobalInfo
{
    my $self  = shift;
    my $id    = shift;
    my $value = shift;

    return $self->_doUpdate('global_info', [$id], [{'value' => $value}]);
}

sub addSystem
{
    my $self        = shift;
    my $valRows     = shift;
    my $attrValRows = shift;

    # ... store the systems to get the IDs ...
    my @systemIDs = $self->_doInsert('system', $valRows);

    # ... finally store the individual attribute sets
    foreach my $id (@systemIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setSystemAttrs($id, $attrs);
    }

    return @systemIDs;
}

sub removeSystem
{
    my $self      = shift;
    my $systemIDs = shift;

    return $self->_doDelete('system', $systemIDs);
}

sub changeSystem
{
    my $self      = shift;
    my $systemIDs = shift;
    my $valRows   = shift;
    my $attrValRows = shift;

    # store the attribute hashes individually
    foreach my $id (@$systemIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setSystemAttrs($id, $attrs);
    }

    # finally update all systems in one go
    return $self->_doUpdate('system', $systemIDs, $valRows);
}

sub setSystemAttrs
{
    my $self     = shift;
    my $systemID = shift;
    my $newAttrs = shift;

    # fetch info about existing attrs
    my $sql = "SELECT * FROM system_attr WHERE system_id = $systemID";
    my %oldAttrs = map { ($_->{name}, $_) } $self->_doSelect($sql);

    # We write undefined attributes for the default system only, such that
    # it shows all existing attributes. All other systems never write undefined 
    # attributes (if they have not defined a specific attribute, it is 
    # inherited from "above"). We encapsulate that decision in the following
    # delegate
    my $valueIsOK = sub {
        my $value = shift;
        return $systemID == 0 || defined $value;
    };

    # determine the required actions ...
    my @attrsToBeInserted
        = grep { 
            $valueIsOK->($newAttrs->{$_}) && !exists $oldAttrs{$_}
        } keys %$newAttrs;
    my @attrsToBeDeleted 
        = grep { 
            !exists $newAttrs->{$_} || !$valueIsOK->($newAttrs->{$_}) 
        } keys %oldAttrs;
    my @attrsToBeUpdated
        = grep { 
            $valueIsOK->($newAttrs->{$_}) && exists $oldAttrs{$_}
            && ((defined($oldAttrs{$_}->{value}) xor defined($newAttrs->{$_}))
                || (defined($oldAttrs{$_}->{value}) && defined($newAttrs->{$_})
                    && $oldAttrs{$_}->{value} ne $newAttrs->{$_}))
        } keys %$newAttrs;

    # ... insert the new ones ...
    my @attrData 
        =   map {
                {
                    system_id => $systemID,
                    name      => $_,
                    value     => $newAttrs->{$_},
                }
            }
            @attrsToBeInserted;
    $self->_doInsert('system_attr', \@attrData);

    # ... delete the old ones ...
    my @oldIDs = map { $oldAttrs{$_}->{id} } @attrsToBeDeleted;
    $self->_doDelete('system_attr', \@oldIDs);

    # ... and update the changed ones ...
    my @IDs   = map { $oldAttrs{$_}->{id} } @attrsToBeUpdated;
    @attrData = map { { value => $newAttrs->{$_} } } @attrsToBeUpdated;
    $self->_doUpdate('system_attr', \@IDs, \@attrData);

    return 1;
}

sub setClientIDsOfSystem
{
    my $self      = shift;
    my $systemID  = shift;
    my $clientIDs = shift;

    my @currClients = $self->fetchClientIDsOfSystem($systemID);
    return $self->_updateRefTable(
        'client_system_ref', $systemID, $clientIDs, 'system_id', 'client_id', 
        \@currClients
    );
}

sub setGroupIDsOfSystem
{
    my $self     = shift;
    my $systemID = shift;
    my $groupIDs = shift;

    my @currGroups = $self->fetchGroupIDsOfSystem($systemID);
    return $self->_updateRefTable(
        'group_system_ref', $systemID, $groupIDs, 'system_id', 'group_id', 
        \@currGroups
    );
}

sub addClient
{
    my $self    = shift;
    my $valRows = shift;
    my $attrValRows = shift;

    # ... store the clients to get the IDs ...
    my @clientIDs = $self->_doInsert('client', $valRows);

    # ... finally store the individual attribute sets
    foreach my $id (@clientIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setClientAttrs($id, $attrs);
    }

    return @clientIDs;
}

sub removeAttributeByName
{
    my $self     = shift;
    my $attrName = shift;

    return $self->_doDelete('system_attr', [ $attrName ], 'name')
        && $self->_doDelete('client_attr', [ $attrName ], 'name')
        && $self->_doDelete('group_attr', [ $attrName ], 'name');
}

sub removeClient
{
    my $self      = shift;
    my $clientIDs = shift;

    return $self->_doDelete('client', $clientIDs);
}

sub changeClient
{
    my $self        = shift;
    my $clientIDs   = shift;
    my $valRows     = shift;
    my $attrValRows = shift;

    # store the attribute hashes individually
    foreach my $id (@$clientIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setClientAttrs($id, $attrs);
    }

    # finally update all systems in one go
    return $self->_doUpdate('client', $clientIDs, $valRows);
}

sub setClientAttrs
{
    my $self     = shift;
    my $clientID = shift;
    my $newAttrs = shift;

    # fetch info about existing attrs
    my $sql = "SELECT * FROM client_attr WHERE client_id = $clientID";
    my %oldAttrs = map { ($_->{name}, $_) } $self->_doSelect($sql);

    # determine the required actions ...
    my @attrsToBeInserted
        = grep { 
            defined $newAttrs->{$_} && !exists $oldAttrs{$_}
        } keys %$newAttrs;
    my @attrsToBeDeleted = grep { !defined $newAttrs->{$_} } keys %oldAttrs;
    my @attrsToBeUpdated
        = grep { 
            defined $newAttrs->{$_} && exists $oldAttrs{$_}
            && ($oldAttrs{$_}->{value} || '') ne ($newAttrs->{$_} || '')
        } keys %$newAttrs;

    # ... insert the new ones ...
    my @attrData 
        =   map {
                {
                    client_id => $clientID,
                    name      => $_,
                    value     => $newAttrs->{$_},
                }
            }
            @attrsToBeInserted;
    $self->_doInsert('client_attr', \@attrData);

    # ... delete the old ones ...
    my @oldIDs = map { $oldAttrs{$_}->{id} } @attrsToBeDeleted;
    $self->_doDelete('client_attr', \@oldIDs);

    # ... and update the changed ones ...
    my @IDs   = map { $oldAttrs{$_}->{id} } @attrsToBeUpdated;
    @attrData = map { { value => $newAttrs->{$_} } } @attrsToBeUpdated;
    $self->_doUpdate('client_attr', \@IDs, \@attrData);

    return 1;
}

sub setSystemIDsOfClient
{
    my $self      = shift;
    my $clientID  = shift;
    my $systemIDs = shift;

    my @currSystems = $self->fetchSystemIDsOfClient($clientID);
    return $self->_updateRefTable(
        'client_system_ref', $clientID, $systemIDs, 'client_id', 'system_id', 
        \@currSystems
    );
}

sub setGroupIDsOfClient
{
    my $self     = shift;
    my $clientID = shift;
    my $groupIDs = shift;

    my @currGroups = $self->fetchGroupIDsOfClient($clientID);
    return $self->_updateRefTable(
        'group_client_ref', $clientID, $groupIDs, 'client_id', 'group_id', 
        \@currGroups
    );
}

sub addGroup
{
    my $self        = shift;
    my $valRows     = shift;
    my $attrValRows = shift;

    # ... store the groups to get the IDs ...
    my @groupIDs = $self->_doInsert('groups', $valRows);

    # ... finally store the individual attribute sets
    foreach my $id (@groupIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setGroupAttrs($id, $attrs);
    }

    return @groupIDs;
}

sub removeGroup
{
    my $self     = shift;
    my $groupIDs = shift;

    return $self->_doDelete('groups', $groupIDs);
}

sub changeGroup
{
    my $self        = shift;
    my $groupIDs    = shift;
    my $valRows     = shift;
    my $attrValRows = shift;

    # store the attribute hashes individually
    foreach my $id (@$groupIDs) {
        my $attrs = shift @$attrValRows;
        next if !defined $attrs;
        return if !$self->setGroupAttrs($id, $attrs);
    }

    # finally update all groups in one go
    return $self->_doUpdate('groups', $groupIDs, $valRows);
}

sub setGroupAttrs
{
    my $self     = shift;
    my $groupID = shift;
    my $newAttrs = shift;

    # fetch info about existing attrs
    my $sql = "SELECT * FROM group_attr WHERE group_id = $groupID";
    my %oldAttrs = map { ($_->{name}, $_) } $self->_doSelect($sql);

    # determine the required actions ...
    my @attrsToBeInserted
        = grep { 
            defined $newAttrs->{$_} && !exists $oldAttrs{$_}
        } keys %$newAttrs;
    my @attrsToBeDeleted = grep { !defined $newAttrs->{$_} } keys %oldAttrs;
    my @attrsToBeUpdated
        = grep { 
            defined $newAttrs->{$_} && exists $oldAttrs{$_}
            && ($oldAttrs{$_}->{value} || '') ne ($newAttrs->{$_} || '')
        } keys %$newAttrs;

    # ... insert the new ones ...
    my @attrData 
        =   map {
                {
                    group_id => $groupID,
                    name     => $_,
                    value    => $newAttrs->{$_},
                }
            }
            @attrsToBeInserted;
    $self->_doInsert('group_attr', \@attrData);

    # ... delete the old ones ...
    my @oldIDs = map { $oldAttrs{$_}->{id} } @attrsToBeDeleted;
    $self->_doDelete('group_attr', \@oldIDs);

    # ... and update the changed ones ...
    my @IDs   = map { $oldAttrs{$_}->{id} } @attrsToBeUpdated;
    @attrData = map { { value => $newAttrs->{$_} } } @attrsToBeUpdated;
    $self->_doUpdate('group_attr', \@IDs, \@attrData);

    return 1;
}

sub setClientIDsOfGroup
{
    my $self      = shift;
    my $groupID   = shift;
    my $clientIDs = shift;

    my @currClients = $self->fetchClientIDsOfGroup($groupID);
    return $self->_updateRefTable(
        'group_client_ref', $groupID, $clientIDs, 'group_id', 'client_id', 
        \@currClients
    );
}

sub setSystemIDsOfGroup
{
    my $self      = shift;
    my $groupID   = shift;
    my $systemIDs = shift;

    my @currSystems = $self->fetchSystemIDsOfGroup($groupID);
    return $self->_updateRefTable(
        'group_system_ref', $groupID, $systemIDs, 'group_id', 'system_id', 
        \@currSystems
    );
}

################################################################################
### schema related functions
################################################################################
sub _convertColDescrsToDBNativeString
{
    my $self      = shift;
    my $colDescrs = shift;

    my $colDescrString = join ', ', map {
        # convert each column description into database native format
        # (e.g. convert 'name:s.45' to 'name char(45)'):
        if (!m[^\s*(\S+?)\s*:\s*(\S+?)\s*$]) {
            croak _tr('UnknownDbSchemaColumnDescr', $_);
        }
        "$1 " . $self->schemaConvertTypeDescrToNative($2);
    } @$colDescrs;
    return $colDescrString;
}

sub _convertColDescrsToColNames
{
    my $self      = shift;
    my $colDescrs = shift;

    return map {
        # convert each column description into database native format
        # (e.g. convert 'name:s.45' to 'name char(45)'):
        if (!m[^\s*(\S+?)\s*:.+$]) {
            croak _tr('UnknownDbSchemaColumnDescr', $_);
        }
        $1;
    } @$colDescrs;
}

sub _convertColDescrsToColNamesString
{
    my $self      = shift;
    my $colDescrs = shift;

    return join ', ', $self->_convertColDescrsToColNames($colDescrs);
}

sub schemaFetchDBVersion
{
    my $self = shift;

    my $dbh = $self->{dbh};
    local $dbh->{RaiseError} = 1;
    my $row =
      eval { $dbh->selectrow_hashref('SELECT schema_version FROM meta'); };
    return 0 if $@;
    # no database access possible
    return unless defined $row;
    # no entry in meta-table
    return $row->{schema_version};
}

sub schemaSetDBVersion
{
    my $self      = shift;
    my $dbVersion = shift;

    $self->{dbh}->do("UPDATE meta SET schema_version = '$dbVersion'")
        or croak _tr('Unable to set DB-schema version to %s!', $dbVersion);

    return 1;
}

sub schemaFetchPluginInfoHashVal
{
    my $self = shift;

    my $row 
        = $self->{dbh}->selectrow_hashref('SELECT plugin_info_hash FROM meta');

    return $row->{plugin_info_hash};
}

sub schemaSetPluginInfoHashVal
{
    my $self              = shift;
    my $pluginInfoHashVal = shift;

    $self->{dbh}->do("UPDATE meta SET plugin_info_hash = '$pluginInfoHashVal'")
        or croak _tr(
            'Unable to set plugin-info-hash-value to %s!', $pluginInfoHashVal
        );

    return 1;
}

sub schemaConvertTypeDescrToNative
{   # a default implementation, many DBs need to override...
    my $self      = shift;
    my $typeDescr = lc(shift);

    if ($typeDescr eq 'b') {
        return 'integer';
    } elsif ($typeDescr eq 'i') {
        return 'integer';
    } elsif ($typeDescr eq 'pk') {
        return 'integer primary key';
    } elsif ($typeDescr eq 'fk') {
        return 'integer';
    } elsif ($typeDescr =~ m[^s\.(\d+)$]i) {
        return "varchar($1)";
    } else {
        croak _tr('UnknownDbSchemaTypeDescr', $typeDescr);
    }
}

sub schemaAddTable
{
    my $self        = shift;
    my $table       = shift;
    my $colDescrs   = shift;
    my $initialVals = shift;
    my $isSubCmd    = shift;

    my $dbh = $self->{'dbh'};
    vlog(1, "adding table <$table> to schema...") unless $isSubCmd;
    my $colDescrString = $self->_convertColDescrsToDBNativeString($colDescrs);
    my $sql            = "CREATE TABLE $table ($colDescrString)";
    vlog(3, $sql);
    $dbh->do($sql)
      or croak _tr(q[Can't create table <%s> (%s)], $table, $dbh->errstr);
    if (defined $initialVals) {
        # don't care about IDs if there's no 'id' column in this table
        my $ignoreIDs = ($colDescrString !~ m[\bid\b]);
        $self->_doInsert($table, $initialVals, $ignoreIDs);
    }
    return;
}

sub schemaDropTable
{
    my $self     = shift;
    my $table    = shift;
    my $isSubCmd = shift;

    my $dbh = $self->{'dbh'};
    vlog(1, "dropping table <$table> from schema...") unless $isSubCmd;
    my $sql = "DROP TABLE $table";
    vlog(3, $sql);
    $dbh->do($sql)
      or croak _tr(q[Can't drop table <%s> (%s)], $table, $dbh->errstr);
    return;
}

sub schemaRenameTable
{   # a rather simple-minded implementation that renames a table in several
    # steps:
    #     - create the new table
    #     - copy the data over from the old one
    #     - drop the old table
    # This should be overriden for advanced DBs, as these more often than not
    # implement the 'ALTER TABLE <old> RENAME TO <new>' SQL-command (which
    # is much more efficient).
    my $self      = shift;
    my $oldTable  = shift;
    my $newTable  = shift;
    my $colDescrs = shift;
    my $isSubCmd  = shift;

    my $dbh = $self->{'dbh'};
    vlog(1, "renaming table <$oldTable> to <$newTable>...") unless $isSubCmd;
    my $colDescrString = $self->_convertColDescrsToDBNativeString($colDescrs);
    my $sql            = "CREATE TABLE $newTable ($colDescrString)";
    vlog(3, $sql);
    $dbh->do($sql)
      or croak _tr(q[Can't create table <%s> (%s)], $oldTable, $dbh->errstr);
    my $colNamesString = $self->_convertColDescrsToColNamesString($colDescrs);
    my @dataRows = $self->_doSelect("SELECT $colNamesString FROM $oldTable");
    $self->_doInsert($newTable, \@dataRows);
    $sql = "DROP TABLE $oldTable";
    vlog(3, $sql);
    $dbh->do($sql)
      or croak _tr(q[Can't drop table <%s> (%s)], $oldTable, $dbh->errstr);
    return;
}

sub schemaAddColumns
{   # a rather simple-minded implementation that adds columns to a table
    # in several steps:
    #     - create a temp table with the new layout
    #     - copy the data from the old table into the new one
    #     - drop the old table
    #     - rename the temp table to the original name
    # This should be overriden for advanced DBs, as these more often than not
    # implement the 'ALTER TABLE <table> ADD COLUMN <col>' SQL-command (which
    # is much more efficient).
    my $self              = shift;
    my $table             = shift;
    my $newColDescrs      = shift;
    my $newColDefaultVals = shift;
    my $colDescrs         = shift;
    my $isSubCmd          = shift;

    my $dbh         = $self->{'dbh'};
    my $tempTable   = "${table}_temp";
    my @newColNames = $self->_convertColDescrsToColNames($newColDescrs);
    my $newColStr   = join ', ', @newColNames;
    vlog(1, "adding columns <$newColStr> to table <$table>...")
      unless $isSubCmd;
    $self->schemaAddTable($tempTable, $colDescrs, undef, 1);

    # copy the data from the old table to the new:
    my @dataRows = $self->_doSelect("SELECT * FROM $table");
    $self->_doInsert($tempTable, \@dataRows);
    # N.B.: for the insert, we rely on the caller having added the new
    # columns to the end of the table (if that isn't the case, things
    # break here!)

    if (defined $newColDefaultVals) {
        # default values have been provided, we apply them now:
        $self->_doUpdate($tempTable, undef, $newColDefaultVals);
    }

    $self->schemaDropTable($table, 1);
    $self->schemaRenameTable($tempTable, $table, $colDescrs, 1);
    return;
}

sub schemaDropColumns
{   # a rather simple-minded implementation that drops columns from a table
    # in several steps:
    #     - create a temp table with the new layout
    #     - copy the data from the old table into the new one
    #     - drop the old table
    #     - rename the temp table to the original name
    # This should be overriden for advanced DBs, as these sometimes
    # implement the 'ALTER TABLE <table> DROP COLUMN <col>' SQL-command (which
    # is much more efficient).
    my $self         = shift;
    my $table        = shift;
    my $dropColNames = shift;
    my $colDescrs    = shift;
    my $isSubCmd     = shift;

    my $dbh        = $self->{'dbh'};
    my $tempTable  = "${table}_temp";
    my $dropColStr = join ', ', @$dropColNames;
    vlog(1, "dropping columns <$dropColStr> from table <$table>...")
      unless $isSubCmd;
    $self->schemaAddTable($tempTable, $colDescrs, undef, 1);

    # copy the data from the old table to the new:
    my $colNamesString = $self->_convertColDescrsToColNamesString($colDescrs);
    my @dataRows       = $self->_doSelect("SELECT $colNamesString FROM $table");
    $self->_doInsert($tempTable, \@dataRows);

    $self->schemaDropTable($table, 1);
    $self->schemaRenameTable($tempTable, $table, $colDescrs, 1);
    return;
}

sub schemaChangeColumns
{   # a rather simple-minded implementation that changes columns
    # in several steps:
    #     - create a temp table with the new layout
    #     - copy the data from the old table into the new one
    #     - drop the old table
    #     - rename the temp table to the original name
    # This should be overriden for advanced DBs, as these sometimes
    # implement the 'ALTER TABLE <table> CHANGE COLUMN <col>' SQL-command (which
    # is much more efficient).
    my $self       = shift;
    my $table      = shift;
    my $colChanges = shift;
    my $colDescrs  = shift;
    my $isSubCmd   = shift;

    my $dbh          = $self->{'dbh'};
    my $tempTable    = "${table}_temp";
    my $changeColStr = join ', ', keys %$colChanges;
    vlog(1, "changing columns <$changeColStr> of table <$table>...")
      unless $isSubCmd;
    $self->schemaAddTable($tempTable, $colDescrs, undef, 1);

    # copy the data from the old table to the new:
    my $colNamesString = $self->_convertColDescrsToColNamesString($colDescrs);
    my @dataRows       = $self->_doSelect("SELECT * FROM $table");
    foreach my $oldCol (keys %$colChanges) {
        my $newCol =
          $self->_convertColDescrsToColNamesString([$colChanges->{$oldCol}]);
        # rename current column in all data-rows:
        foreach my $row (@dataRows) {
            $row->{$newCol} = $row->{$oldCol};
            delete $row->{$oldCol};
        }
    }
    $self->_doInsert($tempTable, \@dataRows);

    $self->schemaDropTable($table, 1);
    $self->schemaRenameTable($tempTable, $table, $colDescrs, 1);
    return;
}

1;

=head1 NAME

DBI.pm - provides DBI-based implementation of the OpenSLX MetaDB API.

=head1 SYNOPSIS

This class is the base for all DBI-related metaDB variants.
It provides a default implementation for every method, such that
each DB-specific implementation needs to override only the methods
that require a different implementation than the one provided here.

=head1 NOTES

In case you ask yourself why none of the SQL-statements in this
file make use of SQL bind params (?), the answer is that at least
one DBD-driver didn't like them at all. As the performance gains
from bound params are not really necessary here, we simply do
not use them.