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
  
1541
  
1542
  
1543
  
1544
  
1545
  
1546
  
1547
  
1548
  
1549
  
1550
  
1551
  
1552
  
1553
  
1554
  
1555
  
1556
  
1557
  
1558
  
1559
  
1560
  
1561
  
1562
  
1563
  
1564
  
1565
  
1566
  
1567
  
1568
  
1569
  
1570
  
1571
  
1572
  
1573
  
1574
  
1575
  
1576
  
1577
  
1578
  
1579
  
1580
  
1581
  
1582
  
1583
  
1584
  
1585
  
1586
  
1587
  
1588
  
1589
  
1590
  
1591
  
1592
  
1593
  
1594
  
1595
  
1596
  
1597
  
1598
  
1599
  
1600
  
1601
  
1602
  
1603
  
1604
  
1605
  
1606
  
1607
  
1608
  
1609
  
1610
  
1611
  
1612
  
1613
  
1614
  
1615
  
1616
  
1617
  
1618
  
1619
  
1620
  
1621
  
1622
  
1623
  
1624
  
1625
  
1626
  
1627
  
1628
  
1629
  
1630
  
1631
  
1632
  
1633
  
1634
  
1635
  
1636
  
1637
  
1638
  
1639
  
1640
  
1641
  
1642
  
1643
  
1644
  
1645
  
1646
  
1647
  
1648
  
1649
  
1650
  
1651
  
1652
  
1653
  
1654
  
1655
  
1656
  
1657
  
1658
  
1659
  
1660
  
1661
  
1662
  
1663
  
1664
  
1665
  
1666
  
1667
  
1668
  
1669
  
1670
  
1671
  
1672
  
1673
  
1674
  
1675
  
1676
  
1677
  
1678
  
1679
  
1680
  
1681
  
1682
  
1683
  
1684
  
1685
  
1686
  
1687
  
1688
  
1689
  
1690
  
1691
  
1692
  
1693
  
1694
  
1695
  
1696
  
1697
  
1698
  
1699
  
1700
  
1701
  
1702
  
1703
  
1704
  
1705
  
1706
  
1707
  
1708
  
1709
  
1710
  
1711
  
1712
  
1713
  
1714
  
1715
  
1716
  
1717
  
1718
  
1719
  
1720
  
1721
  
1722
  
1723
  
1724
  
1725
  
1726
  
1727
  
1728
  
1729
  
1730
  
1731
  
1732
  
1733
  
1734
  
1735
  
1736
  
1737
  
1738
  
1739
  
1740
  
1741
  
1742
  
1743
  
1744
  
1745
  
1746
  
1747
  
1748
  
1749
  
1750
  
1751
  
1752
  
1753
  
1754
  
1755
  
1756
  
1757
  
1758
  
1759
  
1760
  
1761
  
1762
  
1763
  
1764
  
1765
  
1766
  
1767
  
1768
  
1769
  
1770
  
1771
  
1772
  
1773
  
1774
  
1775
  
1776
  
1777
  
1778
  
1779
  
1780
  
1781
  
1782
  
1783
  
1784
  
1785
  
1786
  
1787
  
1788
  
1789
  
1790
  
1791
  
1792
  
1793
  
1794
  
1795
  
1796
  
1797
  
1798
  
1799
  
1800
  
1801
  
1802
  
1803
  
1804
  
1805
  
1806
  
1807
  
1808
  
1809
  
1810
  
1811
  
1812
  
1813
  
1814
  
// Symbolic DB handling.  
// 
// $Id$ 
 
//! Manages database aliases and permissions 
 
#include <roxen.h> 
#include <config.h> 
 
 
// FIXME: There should be mutexes here! 
 
 
#define CN(X) string_to_utf8( X ) 
#define NC(X) utf8_to_string( X ) 
 
 
constant NONE  = 0; 
//! No permissions. Used in @[set_permission] and @[get_permission_map] 
 
constant READ  = 1; 
//! Read permission. Used in @[set_permission] and @[get_permission_map] 
 
constant WRITE = 2; 
//! Write permission. Used in @[set_permission] and @[get_permission_map] 
 
 
private 
{ 
  mixed query( mixed ... args ) 
  { 
    return connect_to_my_mysql( 0, "roxen" )->query( @args ); 
  } 
 
  Sql.sql_result big_query( mixed ... args ) 
  { 
    return connect_to_my_mysql( 0, "roxen" )->big_query( @args ); 
  } 
 
  string short( string n ) 
  { 
    return lower_case(sprintf("%s%4x", CN(n)[..6],(hash( n )&65535) )); 
  } 
 
  void clear_sql_caches() 
  { 
#if DBMANAGER_DEBUG 
    werror("DBManager: clear_sql_caches():\n" 
           "  dead_sql_cache: %O\n" 
           "  sql_cache: %O\n" 
           "  connection_cache: %O\n", 
           dead_sql_cache, 
           sql_cache, 
           connection_cache); 
#endif /* DMBMANAGER_DEBUG */ 
    /* Rotate the sql_caches. 
     * 
     * Perform the rotation first, to avoid thread-races. 
     */ 
    sql_url_cache = ([]); 
    user_db_permissions = ([]); 
    connection_user_cache = ([]); 
    restricted_user_cache = ([]); 
    clear_connect_to_my_mysql_cache(); 
  } 
   
  array changed_callbacks = ({}); 
  void changed() 
  { 
    changed_callbacks-=({0}); 
    clear_sql_caches(); 
 
    foreach( changed_callbacks, function cb ) 
      if (mixed err = catch( cb() )) 
        report_error ("Error from dblist changed callback %O: %s", 
                      cb, describe_backtrace (err)); 
  } 
 
  int check_db_user (string user, string host) 
  { 
    return connect_to_my_mysql (0, "mysql")-> 
      big_query ("SELECT 1 FROM user WHERE Host=%s AND User=%s LIMIT 1", 
                 host, user)-> 
      num_rows(); 
  } 
 
  protected void low_ensure_has_users( Sql.Sql db, string short_name, 
                                       string host, string|void password ) 
  { 
    if( password ) 
    { 
      // According to the documentation MySQL is 4.1 or newer is required 
      // for OLD_PASWORD(). There does however seem to exist versions of 
      // at least 4.0 that know of OLD_PASSWORD(). 
      if (db->server_info() >= "mysql/4.1") { 
        db->query( "REPLACE INTO user (Host,User,Password) " 
                   "VALUES (%s, %s, OLD_PASSWORD(%s)), " 
                   "       (%s, %s, OLD_PASSWORD(%s))", 
                   host, short_name + "_rw", password, 
                   host, short_name + "_ro", password); 
      } else { 
        db->query( "REPLACE INTO user (Host,User,Password) " 
                   "VALUES (%s, %s, PASSWORD(%s)), " 
                   "       (%s, %s, PASSWORD(%s))", 
                   host, short_name + "_rw", password, 
                   host, short_name + "_ro", password); 
      } 
    } 
    else 
    { 
      db->query( "REPLACE INTO user (Host,User,Password) " 
                 "VALUES (%s, %s, ''), (%s, %s, '')", 
                 host, short_name + "_rw", 
                 host, short_name + "_ro" ); 
    } 
  } 
 
  void set_perms_in_db_table (Sql.Sql db, string host, array(string) dbs, 
                              string user, int level) 
  { 
    function(string:string) q = db->quote; 
 
    switch (level) { 
      case NONE: 
        db->big_query ("DELETE FROM db WHERE" 
                       " Host='" + q (host) + "'" 
                       " AND Db IN ('" + (map (dbs, q) * "','") + "')" 
                       " AND User='" + q (user) + "'"); 
        break; 
 
      case READ: 
        db->big_query ("REPLACE INTO db (Host, Db, User, Select_priv, " 
                       "Execute_priv) " 
                       "VALUES " + 
                       map (dbs, lambda (string db_name) { 
                                   return "(" 
                                     "'" + q (host) + "'," 
                                     "'" + q (db_name) + "'," 
                                     "'" + q (user) + "'," 
                                     "'Y','Y')"; 
                                 }) * ","); 
        break; 
 
      case WRITE: 
        // Current as of MySQL 5.0.70. 
        db->big_query ("REPLACE INTO db (Host, Db, User," 
                       " Select_priv, Insert_priv, Update_priv, Delete_priv," 
                       " Create_priv, Drop_priv, Grant_priv, References_priv," 
                       " Index_priv, Alter_priv, Create_tmp_table_priv," 
                       " Lock_tables_priv, Create_view_priv, Show_view_priv," 
                       " Create_routine_priv, Alter_routine_priv," 
                       " Execute_priv) " 
                       "VALUES " + 
                       map (dbs, lambda (string db_name) { 
                                   return "(" 
                                     "'" + q (host) + "'," 
                                     "'" + q (db_name) + "'," 
                                     "'" + q (user) + "'," 
                                     "'Y','Y','Y','Y'," 
                                     "'Y','Y','N','Y'," 
                                     "'Y','Y','Y'," 
                                     "'Y','Y','Y'," 
                                     "'Y','Y'," 
                                     "'Y')"; 
                                 }) * ","); 
        break; 
 
      case -1: 
        // Special case to create a record for a user that got no access. 
        db->big_query ("REPLACE INTO db (Host, Db, User) " 
                       "VALUES " + 
                       map (dbs, lambda (string db_name) { 
                                   return "(" 
                                     "'" + q (host) + "'," 
                                     "'" + q (db_name) + "'," 
                                     "'" + q (user) + "')"; 
                                 }) * ","); 
        break; 
 
      default: 
        error ("Invalid level %d.\n", level); 
    } 
  } 
 
  protected void check_upgrade_mysql() 
  { 
    Sql.Sql db = connect_to_my_mysql(0, "mysql"); 
 
    mapping(string:string) mysql_location = roxenloader->parse_mysql_location(); 
    string update_mysql; 
    if ((mysql_location->basedir) &&  
        (update_mysql = 
         Stdio.read_bytes(combine_path(mysql_location->basedir, 
                                       "share/mysql", 
                                       "mysql_fix_privilege_tables.sql")))) { 
      // Split on semi-colon, but not inside strings... 
      array(string) queries = 
        map(Parser.C.split(update_mysql)/({";"}), `*, ""); 
      foreach(queries[..sizeof(queries)-2], string q) { 
        // Don't complain about failures here, they're expected... 
        catch {db->query(q);}; 
      } 
    } 
 
    multiset(string) missing_privs = (< 
      // Current as of MySQL 5.0.70. 
      "Select", "Insert", "Update", "Delete", "Create", "Drop", "Grant", 
      "References", "Index", "Alter", "Create_tmp_table", "Lock_tables", 
      "Create_view", "Show_view", "Create_routine", "Alter_routine", 
      "Execute", 
    >); 
    foreach(db->query("DESCRIBE db"), mapping(string:string) row) { 
      string field = row->Field || row->field; 
      if (!field) { 
        werror("DBManager: Failed to analyse privileges table mysql.db.\n" 
               "row: %O\n", row); 
        return; 
      } 
      if (has_suffix(field, "_priv")) { 
        // Note the extra space below. 
        missing_privs[field[..sizeof(field)-sizeof(" _priv")]] = 0; 
      } 
    } 
    if (sizeof(missing_privs)) { 
      werror("DBManager: Updating priviliges table mysql.db with the fields\n" 
             "           %s...", indices(missing_privs)*", "); 
      foreach(indices(missing_privs), string priv) { 
        db->query("ALTER TABLE db " 
                  "  ADD COLUMN " + priv+ "_priv " 
                  "      ENUM('N','Y') DEFAULT 'N' NOT NULL"); 
      } 
    } 
 
    if (db_version != mysql_version) { 
      // Make sure no table is broken after the upgrade. 
      foreach(db->list_dbs(), string dbname) { 
        if (lower_case(dbname) == "information_schema") { 
          // This is a virtual read-only db containing metadata 
          // about the other tables, etc. Attempting to repair 
          // any tables in it will cause errors to be thrown. 
          continue; 
        } 
        werror("DBManager: Repairing tables in the local db %O...\n", dbname); 
        Sql.Sql sql = connect_to_my_mysql(0, dbname); 
        foreach(sql->list_tables(), string table) { 
          // NB: Any errors from the repair other than access 
          //     permission errors are in the return value. 
          // 
          // We ignore them for now. 
          mixed err = catch { 
              sql->query("REPAIR TABLE `" + table + "`"); 
            }; 
          if (err && has_value(describe_error(err), 
                               "Incompatible key or row definition between " 
                               "the MariaDB .frm file")) { 
            // Errors 185 and 190: 
            // "Incompatible key or row definition between the MariaDB .frm " 
            // "file and the information in the storage engine. You have to " 
            // "dump and restore the table to fix this" 
            werror("DBManager: Basic repair of table %O failed:\n" 
                   "%s\n" 
                   "DBManager: Retrying with forced use of .frm file.\n", 
                   table, describe_error(err)); 
            sql->query("REPAIR TABLE `" + table + "` USE_FRM"); 
          } else if (err) { 
            throw(err); 
          } 
        } 
      } 
      werror("DBManager: MySQL upgrade done.\n"); 
    } 
  } 
 
  void synch_mysql_perms() 
  { 
    Sql.Sql db = connect_to_my_mysql (0, "mysql"); 
 
    mapping(string:int(1..1)) old_perms = ([]); 
 
    Sql.sql_result sqlres = 
      db->big_query ("SELECT Db, User FROM db WHERE Host='localhost'"); 
    while (array(string) ent = sqlres->fetch_row()) 
      if (has_suffix (ent[1], "_rw") || has_suffix (ent[1], "_ro")) 
        old_perms[ent[0] + "\0" + ent[1]] = 1; 
 
    mapping(string:int(1..1)) checked_users = ([]); 
 
    sqlres = big_query ("SELECT db, config, permission FROM db_permissions "); 
    while (array(string) ent = sqlres->fetch_row()) { 
      [string db_name, string config, string perm] = ent; 
      string short_name = short (NC (config)); 
 
      if (!checked_users[short_name]) { 
        low_ensure_has_users (db, short_name, "localhost"); 
        checked_users[short_name] = 1; 
      } 
 
      switch (perm) { 
        case "read": 
          set_perms_in_db_table (db, "localhost", ({db_name}), 
                                 short_name + "_ro", READ); 
          set_perms_in_db_table (db, "localhost", ({db_name}), 
                                 short_name + "_rw", READ); 
          m_delete (old_perms, db_name + "\0" + short_name + "_ro"); 
          m_delete (old_perms, db_name + "\0" + short_name + "_rw"); 
          break; 
 
        case "write": 
          set_perms_in_db_table (db, "localhost", ({db_name}), 
                                 short_name + "_ro", READ); 
          set_perms_in_db_table (db, "localhost", ({db_name}), 
                                 short_name + "_rw", WRITE); 
          m_delete (old_perms, db_name + "\0" + short_name + "_ro"); 
          m_delete (old_perms, db_name + "\0" + short_name + "_rw"); 
          break; 
      } 
    } 
 
    foreach (old_perms; string key;) { 
      sscanf (key, "%s\0%s", string db_name, string user); 
      set_perms_in_db_table (db, "localhost", ({db_name}), user, NONE); 
    } 
 
    db->big_query ("FLUSH PRIVILEGES"); 
  } 
 
  string make_autouser_name (int level, multiset(string) want_dbs, 
                             Configuration conf) 
  // Returns the name for a user which wants the given access to the 
  // given databases, subject to the permission settings of the given 
  // configuration (optional). The name begins with "?" if level is 
  // READ or "!" if level is WRITE, then follows a 15 char hash 
  // (without whitespace) based on want_dbs and conf->name. Only the 
  // name is generated; fix_autouser must be called to ensure the user 
  // exists. 
  { 
    if (level < READ) return 0; 
    string s = encode_value_canonic (({want_dbs, conf->name})); 
    s = MIME.encode_base64 (Crypto.SHA1()->update (s)->digest()); 
    return (level == READ ? "?" : "!") + s[..14]; 
  } 
 
  void fix_autouser (string autouser, multiset(string) write_dbs, 
                     multiset(string) read_dbs, multiset(string) none_dbs) 
  // If the given autouser doesn't exist, it's created with access to 
  // the stated databases. none_dbs is used for databases that the 
  // user wants access to but isn't allowed. It's to make 
  // invalidate_autousers properly detect this user if access is 
  // granted on one of those dbs later. 
  { 
    Sql.Sql db = connect_to_my_mysql (0, "mysql"); 
 
    // If the user exists at all we assume it got the right perms. 
    if (check_db_user (autouser, "localhost")) return; 
 
    if (sizeof (write_dbs)) 
      set_perms_in_db_table (db, "localhost", 
                             indices (write_dbs), autouser, WRITE); 
    if (sizeof (read_dbs)) 
      set_perms_in_db_table (db, "localhost", 
                             indices (read_dbs), autouser, READ); 
    if (sizeof (none_dbs)) 
      set_perms_in_db_table (db, "localhost", 
                             indices (none_dbs), autouser, -1); 
 
    db->big_query ("REPLACE INTO user (Host, User, Password) " 
                   "VALUES ('localhost', %s, '')", autouser); 
    db->big_query ("FLUSH PRIVILEGES"); 
  } 
 
  void invalidate_autousers (string db_name) 
  // Invalidates the autousers that have any access on the given 
  // database. Invalidates all autousers if db_name is zero. 
  { 
    Sql.Sql db = connect_to_my_mysql (0, "mysql"); 
 
    if (db_name) { 
      array(string) users = ({}); 
      Sql.sql_result sqlres = 
        db->big_query ("SELECT User FROM db " 
                       "WHERE Host='localhost' AND Db=%s AND " 
                       "(User LIKE '!_______________' OR" 
                       " User LIKE '?_______________')", db_name); 
      while (array(string) ent = sqlres->fetch_row()) 
        users += ({ent[0]}); 
 
      // We have to delete all affected autousers completely from the 
      // db table to make get_autouser regenerate them. 
      if (sizeof (users)) { 
        string user_list = "('" + map (users, db->quote) * "','" + "')"; 
        db->big_query ("DELETE FROM db WHERE User IN " + user_list); 
        db->big_query ("DELETE FROM user WHERE User IN " + user_list); 
      } 
    } 
    else { 
      db->big_query ("DELETE FROM db " 
                     "WHERE Host='localhost' AND " 
                       "(User LIKE '!_______________' OR" 
                       " User LIKE '?_______________')"); 
      db->big_query ("DELETE FROM user " 
                     "WHERE Host='localhost' AND " 
                       "(User LIKE '!_______________' OR" 
                       " User LIKE '?_______________')"); 
    } 
 
    restricted_user_cache = ([]); 
  } 
 
  void low_set_user_permissions( Sql.Sql db, Configuration c, 
                                 string db_name, int level, 
                                 string host, string|void password ) 
  { 
    string short_name = short (c->name); 
    low_ensure_has_users( db, short_name, host, password ); 
    set_perms_in_db_table (db, host, ({db_name}), 
                           short_name + "_ro", min (level, READ)); 
    set_perms_in_db_table (db, host, ({db_name}), 
                           short_name + "_rw", level); 
  } 
   
  void set_user_permissions( Configuration c, string db_name, int level ) 
  { 
    Sql.Sql db = connect_to_my_mysql( 0, "mysql" ); 
    low_set_user_permissions( db, c, db_name, level, "localhost" ); 
    invalidate_autousers (db_name); 
    db->query( "FLUSH PRIVILEGES" ); 
  } 
   
  void set_external_user_permissions( Configuration c, string db_name, int level, 
                                      string password ) 
  { 
    Sql.Sql db = connect_to_my_mysql( 0, "mysql" ); 
    low_set_user_permissions( db, c, db_name, level, "127.0.0.1", password ); 
    db->query( "FLUSH PRIVILEGES" ); 
  } 
 
 
  class ROWrapper( protected Sql.Sql sql ) 
  { 
    protected int pe; 
    protected array(mapping(string:mixed)) query( string query, mixed ... args ) 
    { 
      // Get rid of any initial whitespace. 
      query = String.trim_all_whites(query); 
      if( has_prefix( lower_case(query), "select" ) || 
          has_prefix( lower_case(query), "show" ) || 
          has_prefix( lower_case(query), "describe" )) 
        return sql->query( query, @args ); 
      pe = 1; 
      throw( ({ "Permission denied\n", backtrace()}) ); 
    } 
    protected Sql.sql_result big_query( string query, mixed ... args ) 
    { 
      // Get rid of any initial whitespace. 
      query = String.trim_all_whites(query); 
      if( has_prefix( lower_case(query), "select" ) || 
          has_prefix( lower_case(query), "show" ) || 
          has_prefix( lower_case(query), "describe" )) 
        return sql->big_query( query, @args ); 
      pe = 1; 
      throw( ({ "Permission denied\n", backtrace()}) ); 
    } 
    protected string error() 
    { 
      if( pe ) 
      { 
        pe = 0; 
        return "Permission denied"; 
      } 
      return sql->error(); 
    } 
 
    protected string host_info() 
    { 
      return sql->host_info()+" (read only)"; 
    } 
 
    protected mixed `[]( string i ) 
    { 
      switch( i ) 
      { 
       case "query": return query; 
       case "big_query": return big_query; 
       case "host_info": return host_info; 
       case "error": return error; 
       default: 
         return sql[i]; 
      } 
    } 
    protected mixed `->( string i ) 
    { 
      return `[](i); 
    } 
  } 
 
  mapping(string:mapping(string:string)) sql_url_cache = ([]); 
}; 
 
Sql.Sql low_get( string user, string db, void|int reuse_in_thread, 
                 void|string charset) 
{ 
  if( !user ) 
    return 0; 
 
#ifdef MODULE_DEBUG 
  if (!reuse_in_thread) 
    if (mapping(string:TableLockInfo) dbs = table_locks->get()) 
      if (TableLockInfo lock_info = dbs[db]) 
        werror ("Warning: Another connection was requested to %O " 
                "in a thread that has locked tables %s.\n" 
                "It's likely that this will result in a deadlock - " 
                "consider using the reuse_in_thread flag.\n", 
                db, 
                String.implode_nicely (indices (lock_info->locked_for_read & 
                                                lock_info->locked_for_write))); 
#endif 
 
  mixed res; 
  mapping(string:mixed) d = sql_url_cache[ db ]; 
  if( !d ) 
  { 
    res = query("SELECT path, local, default_charset " 
                "  FROM dbs WHERE name=%s", db ); 
    if( !sizeof( res ) ) 
      return 0; 
    sql_url_cache[db] = d = res[0]; 
  } 
 
  if( (int)d->local ) 
    return connect_to_my_mysql( user, db, reuse_in_thread, 
                                charset || d->default_charset ); 
 
  // Otherwise it's a tad more complex...   
  if( has_suffix (user, "_ro") ) 
    // The ROWrapper object really has all member functions Sql.Sql 
    // has, but they are hidden behind an overloaded index operator. 
    // Thus, we have to fool the typechecker. 
    return [object(Sql.Sql)](object) 
      ROWrapper( sql_cache_get( d->path, reuse_in_thread, 
                                charset || d->default_charset) ); 
  return sql_cache_get( d->path, reuse_in_thread, 
                        charset || d->default_charset); 
} 
 
Sql.Sql get_sql_handler(string db_url) 
{ 
#ifdef USE_EXTSQL_ORACLE 
  if(has_prefix(db_url, "oracle:")) 
    return ExtSQL.sql(db_url); 
#endif 
  return Sql.Sql(db_url); 
} 
 
Sql.Sql sql_cache_get(string what, void|int reuse_in_thread, 
                      void|string charset) 
{ 
  Thread.MutexKey key = roxenloader.sq_cache_lock(); 
  string i = replace(what,":",";")+":-"; 
  Sql.Sql res = roxenloader.sq_cache_get(i, reuse_in_thread, charset); 
  if (res) return res; 
  // Release the lock during the call to get_sql_handler(), 
  // since it may take quite a bit of time... 
  destruct(key); 
  if (res = get_sql_handler(what)) { 
    // Now we need the lock again... 
    key = roxenloader.sq_cache_lock(); 
    res = roxenloader.sq_cache_set(i, res, reuse_in_thread, charset); 
    // Fool the optimizer so that key is not released prematurely 
    if( res ) 
      return res;  
  } 
} 
 
void add_dblist_changed_callback( function(void:void) callback ) 
//! Add a function to be called when the database list has been 
//! changed. This function will be called after all @[create_db] and 
//! @[drop_db] calls. 
{ 
  changed_callbacks |= ({ callback }); 
} 
 
int remove_dblist_changed_callback( function(void:void) callback ) 
//! Remove a function previously added with @[add_dblist_changed_callback]. 
//! Returns non-zero if the function was in the callback list. 
{ 
  int s = sizeof( changed_callbacks ); 
  changed_callbacks -= ({ callback }); 
  return s-sizeof( changed_callbacks ); 
} 
 
array(string) list( void|Configuration c ) 
//! List all database aliases. 
//! 
//! If @[c] is specified, only databases that the given configuration can 
//! access will be visible. 
{ 
  if( c ) 
    return  query( "SELECT " 
                   " dbs.name AS name " 
                   "FROM " 
                   " dbs,db_permissions " 
                   "WHERE" 
                   " dbs.name=db_permissions.db" 
                   " AND db_permissions.config=%s" 
                   " AND db_permissions.permission!='none'", 
                   CN(c->name))->name 
#ifndef YES_I_KNOW_WHAT_I_AM_DOING 
      -({"roxen","mysql"}) 
#endif 
      ; 
  return query( "SELECT name FROM dbs" )->name 
#ifndef YES_I_KNOW_WHAT_I_AM_DOING 
      -({"roxen","mysql"}) 
#endif 
    ; 
} 
 
mapping(string:mapping(string:int)) get_permission_map( ) 
//! Get a list of all permissions for all databases. 
//! 
//! @returns 
//!   Return format: 
//!           @mapping 
//!             @member mapping(string:int) dbname 
//!               @mapping 
//!                 @member int configname 
//!                   Access level same as for @[set_permission()] et al. 
//!               @endmapping 
//!           @endmapping 
{ 
  mapping(string:mapping(string:int)) res = ([]); 
 
  foreach( list(), string n ) 
  { 
    mixed m = query( "SELECT * FROM db_permissions WHERE db=%s", n ); 
    if( sizeof( m ) ) 
      foreach( m, m ) 
      { 
        if( !res[m->db] )res[m->db] = ([]); 
        switch( m->permission ) 
        { 
         case "none":    res[m->db][NC(m->config)] = NONE; break; 
         case "read":    res[m->db][NC(m->config)] = READ; break; 
         case "write":   res[m->db][NC(m->config)] = WRITE; break; 
        } 
      } 
    else 
      res[n] = ([]); 
  } 
  foreach( indices(res), string q ) 
    foreach( roxenp()->configurations, Configuration c ) 
      if( zero_type( res[q][c->name] ) ) 
        res[q][c->name] = 0; 
  return res; 
} 
 
string db_driver( string db ) 
//! Returns the name of the protocol used to connect to the database 'db'. 
//! This is the part before :// in the database URL.   
{ 
  if( !(db = db_url( db )) ) return "mysql"; 
  sscanf( db, "%[^:]:", db ); 
  return db; 
} 
 
int is_mysql( string db ) 
//! Returns true if the specified database is a MySQL database. 
{ 
  return !(db = db_url( db )) || has_prefix( db, "mysql://" ); 
} 
 
array(mapping(string:mixed)) db_table_fields( string name, string table ) 
//! Returns a mapping of fields in the database, if it's supported by 
//! the protocol handler. Otherwise returns 0. 
{ 
  Sql.Sql db = cached_get( name ); 
#if 0 
  // fetch_fields provides more info. 
  catch { 
    if( db->list_fields ) 
    { 
      mixed res = db->list_fields( table ); 
      if( res ) return res; 
    } 
  }; 
#endif 
 
  object q; 
  if (mixed err = catch ( 
        q = db->big_query ("SELECT * FROM `" + table + "` LIMIT 0"))) { 
    report_debug ("Error listing fields in %O: %s", 
                  table, describe_error (err)); 
    return 0; 
  } 
  return q->fetch_fields(); 
} 
 
array(string) db_tables( string name ) 
//! Attempt to list all tables in the specified DB, and then return 
//! the list. 
{ 
  object db = get(name); 
  if (!db) return ({}); 
  array(string) res; 
  if( db->list_tables ) 
  { 
    catch { 
      if( res =  db->list_tables() ) 
        return res; 
    }; 
  } 
 
  // Well, let's try some specific solutions then. The main problem if 
  // we reach this stage is probably that we are using a ODBC driver 
  // which does not support the table enumeration interface, this 
  // causing list_tables to throw an error. 
 
  switch( db_driver( name ) ) 
  { 
    case "mysql": 
      return ({}); 
 
    case "odbc": 
      // Oracle. 
      catch { 
        res = db->query( "select TNAME from tab")->TNAME; 
        return res; 
      }; 
      // fallthrough. 
 
      // Microsoft SQL (7.0 or newer) 
      catch { 
        res = ({}); 
        foreach( db->query("SELECT * FROM information_schema.tables"), 
                 mapping row ) 
          if( has_prefix( lower_case(row->TABLE_TYPE), "base" ) ) 
            res += ({ row->TABLE_NAME }); 
        return res; 
      }; 
 
       
    case "postgres": 
      // Postgres 
      catch { 
        res = db->query("SELECT a.relname AS name FROM pg_class a, " 
                        "pg_user b WHERE ( relkind = 'r') and " 
                        "relname !~ '^pg_' " 
                        "AND relname !~ '^xin[vx][0-9]+' AND " 
                        "b.usesysid = a.relowner AND " 
                        "NOT (EXISTS (SELECT viewname FROM pg_views " 
                        "WHERE viewname=a.relname)) ")->name; 
        return res; 
      }; 
  } 
 
  return ({}); 
} 
 
mapping db_table_information( string db, string table ) 
//! Return a mapping with at least the indices rows, data_length 
//! and index_length, if possible. Otherwise returns 0. 
{ 
  switch( db_driver( db ) ) 
  { 
    case "mysql": 
    { 
      foreach( get(db)->query( "SHOW TABLE STATUS" ), mapping r ) 
      { 
        if( r->Name == table ) 
          return ([ "rows":(int)r->Rows, 
                    "data_length":(int)r->Data_length, 
                    "index_length":(int)r->Index_length ]); 
      } 
    } 
    default: 
#if 0 
      mixed err = catch{ 
        return ([ 
          "rows": 
          (int)(get(db)->query( "SELECT COUNT(*) AS C FROM `"+table+"`" )[0]->C), 
        ]); 
      }; 
#endif 
  } 
  return 0; 
} 
 
 
mapping(string:int) db_stats( string name ) 
//! Return statistics for the specified database (such as the number 
//! of tables and their total size). If the database is not an 
//! internal database, or the database does not exist, 0 is returned 
{ 
  mapping(string:int) res = (["size": 0, "tables": 0, "rows": 0]); 
  Sql.Sql db = cached_get( name ); 
  array d; 
 
  switch( db_driver( name ) ) 
  { 
    case "mysql": 
      if( !catch( d = db->query( "SHOW TABLE STATUS" ) ) ) 
      { 
        foreach( d, mapping r ) 
        { 
          res->size += (int)r->Data_length+(int)r->Index_length; 
          res->tables++; 
          res->rows += (int)r->Rows; 
        } 
        return res; 
      } 
 
      // fallthrough to generic interface. 
    default: 
      catch 
      { 
        foreach( db_tables( name ), string n ) 
        { 
          mapping i  = db_table_information( name, n ); 
          res->tables++; 
          if( i ) 
          { 
            res->rows += i->rows; 
            res->size += i->data_length+i->index_length; 
          } 
        } 
        return res; 
      }; 
  } 
  return 0; 
} 
 
 
int is_internal( string name ) 
//! Return true if the DB @[name] is an internal database 
{ 
  array(mapping(string:mixed)) d = 
    query("SELECT local FROM dbs WHERE name=%s", name ); 
  if( !sizeof( d ) ) return 0; 
  return (int)d[0]["local"]; 
} 
 
string db_url( string name, 
               int|void force ) 
//! Returns the URL of the db, or 0 if the DB @[name] is an internal 
//! database and @[force] is not specified. If @[force] is specified, 
//! a URL is always returned unless the database does not exist. 
{ 
  array(mapping(string:mixed)) d = 
    query("SELECT path,local FROM dbs WHERE name=%s", name ); 
 
  if( !sizeof( d ) ) 
    return 0; 
 
  if( (int)d[0]["local"] ) 
  { 
    if( force ) 
      return replace( roxenloader->my_mysql_path, 
                      ([ 
                        "%user%":"rw", 
                        "%db%":name 
                      ]) ); 
    return 0; 
  } 
  return d[0]->path; 
} 
 
protected mapping(string:multiset(string)) user_db_permissions = ([]); 
 
multiset(string) config_db_access (Configuration conf, int read_only) 
//! Returns the set of databases that the given configuration has 
//! access to. If @[read_only] is set then the set includes both read 
//! and write permissions, otherwise only databases with write access 
//! are returned. Don't be destructive on the returned multisets. 
{ 
  string key = conf->name + "|" + read_only; 
  if (multiset(string) res = user_db_permissions[key]) 
    return res; 
 
  string q; 
  if (read_only) 
    q = "SELECT db FROM db_permissions " 
      "WHERE config=%s AND (permission='read' OR permission='write')"; 
  else 
    q = "SELECT db FROM db_permissions " 
      "WHERE config=%s AND permission='write'"; 
 
  multiset(string) res = (<>); 
  Sql.sql_result sqlres = big_query (q, CN (conf->name)); 
  while (array(string) ent = sqlres->fetch_row()) 
    res[ent[0]] = 1; 
 
  return user_db_permissions[key] = res; 
} 
 
protected mapping connection_user_cache  = ([]); 
 
string get_db_user( string db_name, Configuration conf, int read_only ) 
//! Returns the name of a MySQL user which has the requested access. 
//! This user is suitable to pass to @[low_get]. 
//! 
//! If @[conf] is zero then a user with global read or read/write 
//! access (according to @[read_only]) is returned. 
//! 
//! Otherwise, if @[db_name] is zero then a user is returned that has 
//! read or read/write access (depending on @[read_only]) to the 
//! databases for @[conf] according to its permission settings. 
//! 
//! Otherwise, a check is done that @[conf] has the requested access 
//! on @[db_name], and if it does then a user is returned that can 
//! access all databases for @[conf] according to its permission 
//! settings. 
{ 
  if (!conf) return read_only ? "ro" : "rw"; 
 
  string key = db_name+"|"+(conf&&conf->name)+"|"+read_only; 
  if( !zero_type( connection_user_cache[ key ] ) ) 
    return connection_user_cache[ key ]; 
 
  if (!db_name) 
    return connection_user_cache[key] = 
      short (conf->name) + (read_only ? "_ro" : "_rw"); 
 
  array(mapping(string:mixed)) res = 
    query( "SELECT permission FROM db_permissions " 
           "WHERE db=%s AND config=%s",  db_name, CN(conf->name)); 
  if( sizeof( res ) && res[0]->permission != "none" ) 
    return connection_user_cache[ key ]=short(conf->name) + 
      ((read_only || res[0]->permission!="write")?"_ro":"_rw"); 
 
  return connection_user_cache[ key ] = 0; 
} 
 
protected mapping restricted_user_cache = ([]); 
 
string get_restricted_db_user (multiset(string) dbs, Configuration conf, 
                               int read_only) 
//! Returns the name of a MySQL user which has read or read/write 
//! access (depending on @[read_only]) to the databases listed in 
//! @[dbs]. This user is suitable to pass to @[low_get]. 
//! 
//! If @[conf] is given then the access is restricted according to the 
//! permission settings for that configuration. Zero is returned if 
//! @[conf] doesn't have any access on any of the specified databases. 
//! 
//! @note 
//! Returned users can get zapped if db permissions change. Validity 
//! should always be checked with @[is_valid_db_user] before use. 
{ 
  multiset(string) conf_ro_dbs = conf && config_db_access (conf, 1); 
  multiset(string) allowed_ro_dbs = conf_ro_dbs ? dbs & conf_ro_dbs : dbs; 
  if (!sizeof (allowed_ro_dbs)) return 0; 
 
  string key = make_autouser_name (read_only ? READ : WRITE, dbs, conf); 
  { 
    string val = restricted_user_cache[key]; 
    if (!zero_type (val)) return val; 
  } 
 
  if (equal (dbs, conf_ro_dbs)) { 
    string nonautouser = short (conf->name) + (read_only ? "_ro" : "_rw"); 
    return restricted_user_cache[key] = 
      restricted_user_cache[nonautouser] = nonautouser; 
  } 
 
  multiset(string) denied_dbs = dbs - allowed_ro_dbs; 
  multiset(string) allowed_rw_dbs; 
  if (read_only) 
    allowed_rw_dbs = (<>); 
  else { 
    if (conf) { 
      allowed_rw_dbs = dbs & config_db_access (conf, 0); 
      allowed_ro_dbs -= allowed_rw_dbs; 
    } 
    else { 
      allowed_rw_dbs = dbs; 
      allowed_ro_dbs = (<>); 
    } 
  } 
 
  fix_autouser (key, allowed_rw_dbs, allowed_ro_dbs, denied_dbs); 
  return restricted_user_cache[key] = key; 
} 
 
int is_valid_db_user (string user) 
//! Returns true if @[user] is a valid local access MySQL user. 
{ 
  if (restricted_user_cache[user]) return 1; 
  return check_db_user (user, "localhost"); 
} 
 
Sql.Sql get( string name, void|Configuration conf, 
             int|void read_only, void|int reuse_in_thread, 
             void|string charset) 
//! Returns an SQL connection object for a database named under the 
//! "DB" tab in the administration interface. 
//! 
//! @param name 
//!   The name of the database. 
//! 
//! @param conf 
//!   If this isn't zero, only return the database if this 
//!   configuration has at least read access. 
//! 
//! @param read_only 
//!   Return a read-only connection if this is set. A read-only 
//!   connection is also returned if @[conf] is specified and only has 
//!   read access (regardless of @[read_only]). 
//! 
//! @param reuse_in_thread 
//!   If this is nonzero then the SQL connection is reused within the 
//!   current thread. I.e. other calls to this function from this 
//!   thread with the same @[name] and @[read_only] and a nonzero 
//!   @[reuse_in_thread] will return the same object. However, the 
//!   connection won't be reused while a result object from 
//!   @[Sql.Sql.big_query] or similar exists. 
//! 
//!   Using this flag is a good way to cut down on the amount of 
//!   simultaneous connections, and to avoid deadlocks when 
//!   transactions or locked tables are used (other problems can occur 
//!   instead though, if transactions or table locking is done 
//!   recursively). However, the caller has to ensure that the 
//!   connection never becomes in use by another thread. The safest 
//!   way to ensure that is to always keep it on the stack, i.e. only 
//!   assign it to variables declared inside functions or pass it in 
//!   arguments to functions. 
//! 
//! @param charset 
//!   If this is nonzero then the returned connection is configured to 
//!   use the specified charset for queries and returned text strings. 
//! 
//!   The valid values and their meanings depend on the type of 
//!   database connection. However, the special value 
//!   @expr{"unicode"@} configures the connection to accept and return 
//!   unencoded (possibly wide) unicode strings (provided the 
//!   connection supports this). 
//! 
//!   An error is thrown if the database connection doesn't support 
//!   the given charset, but the argument is ignored if the database 
//!   doesn't have any charset support at all, i.e. no @[set_charset] 
//!   function. 
//! 
//!   See @[Sql.Sql.set_charset] for more information. 
//! 
//! @note 
//! A charset being set through the @[charset] argument or 
//! @[Sql.Sql.set_charset] is tracked and reset properly when a 
//! connection is reused. If the charset (or any other context info, 
//! for that matter) is changed some other way then it must be 
//! restored before the connection is released. 
{ 
  return low_get( get_db_user( name, conf, read_only), name, reuse_in_thread, 
                  charset); 
} 
 
Sql.Sql cached_get( string name, void|Configuration c, void|int read_only, 
                    void|string charset) 
{ 
  return get (name, c, read_only, 0, charset); 
} 
 
protected Thread.Local table_locks = Thread.Local(); 
protected class TableLockInfo ( 
  Sql.Sql db, 
  int count, 
  multiset(string) locked_for_read, 
  multiset(string) locked_for_write, 
) {} 
 
class MySQLTablesLock 
//! This class is a helper to do MySQL style LOCK TABLES in a safer 
//! way: 
//! 
//! o  It avoids nested LOCK TABLES which would implicitly release the 
//!    previous lock. Instead it checks that the outermost lock 
//!    encompasses all tables. 
//! o  It ensures UNLOCK TABLES always gets executed on exit through 
//!    the refcount garb strategy (i.e. put it in a local variable 
//!    just like a @[Thread.MutexKey]). 
//! o  It checks that the @[reuse_in_thread] flag was used to 
//!    @[DBManager.get] to ensure that a thread doesn't outlock itself 
//!    by using different connections. 
//! 
//! Note that atomic queries and updates don't require 
//! @[MySQLTablesLock] stuff even when it's used in other places at 
//! the same time. They should however use a connection retrieved with 
//! @[reuse_in_thread] set to avoid deadlocks. 
{ 
  protected TableLockInfo lock_info; 
 
  protected void create (Sql.Sql db, 
                         array(string) read_tables, 
                         array(string) write_tables) 
  //! @[read_tables] and @[write_tables] contain the tables to lock 
  //! for reading and writing, respectively. A table string may be 
  //! written as @expr{"foo AS bar"@} to specify an alias. 
  { 
    if (!db->db_name) 
      error ("db was not retrieved with DBManager.get().\n"); 
    if (!db->reuse_in_thread) 
      error ("db was not retrieved with DBManager.get(x,y,z,1).\n"); 
 
    multiset(string) read_tbl = (<>); 
    foreach (read_tables || ({}), string tbl) { 
      sscanf (tbl, "%[^ \t]", tbl); 
      read_tbl[tbl] = 1; 
    } 
 
    multiset(string) write_tbl = (<>); 
    foreach (write_tables || ({}), string tbl) { 
      sscanf (tbl, "%[^ \t]", tbl); 
      write_tbl[tbl] = 1; 
    } 
 
    mapping(string:TableLockInfo) dbs = table_locks->get(); 
    if (!dbs) table_locks->set (dbs = ([])); 
 
    if ((lock_info = dbs[db->db_name])) { 
      if (lock_info->db != db) 
        error ("Tables %s are already locked by this thread through " 
               "a different connection.\nResult objects from " 
               "db->big_query or similar might be floating around, " 
               "or normal and read-only access might be mixed.\n", 
               indices (lock_info->locked_for_read & 
                        lock_info->locked_for_write) * ", "); 
      if (sizeof (read_tbl - lock_info->locked_for_read - 
                  lock_info->locked_for_write)) 
        error ("Cannot read lock more tables %s " 
               "due to already held locks on %s.\n", 
               indices (read_tbl - lock_info->locked_for_read - 
                        lock_info->locked_for_write) * ", ", 
               indices (lock_info->locked_for_read & 
                        lock_info->locked_for_write) * ", "); 
      if (sizeof (write_tbl - lock_info->locked_for_write)) 
        error ("Cannot write lock more tables %s " 
               "due to already held locks on %s.\n", 
               indices (write_tbl - lock_info->locked_for_write) * ", ", 
               indices (lock_info->locked_for_read & 
                        lock_info->locked_for_write) * ", "); 
#ifdef TABLE_LOCK_DEBUG 
      werror ("[%O, %O] MySQLTablesLock.create(): Tables already locked: " 
              "read: [%{%O, %}], write: [%{%O, %}]\n", 
              this_thread(), db, 
              indices (lock_info->locked_for_read), 
              indices (lock_info->locked_for_write)); 
#endif 
      lock_info->count++; 
    } 
 
    else { 
      string query = "LOCK TABLES " + 
        ({ 
          sizeof (read_tbl) && (read_tables * " READ, " + " READ"), 
          sizeof (write_tbl) && (write_tables * " WRITE, " + " WRITE") 
        }) * ", "; 
#ifdef TABLE_LOCK_DEBUG 
      werror ("[%O, %O] MySQLTablesLock.create(): %s\n", 
              this_thread(), db, query); 
#endif 
      db->query (query); 
      dbs[db->db_name] = lock_info = 
        TableLockInfo (db, 1, read_tbl, write_tbl); 
    } 
  } 
 
  int topmost_lock() 
  { 
    return lock_info->count == 1; 
  } 
 
  Sql.Sql get_db() 
  { 
    return lock_info->db; 
  } 
 
  protected void destroy() 
  { 
    if (!--lock_info->count) { 
#ifdef TABLE_LOCK_DEBUG 
      werror ("[%O, %O] MySQLTablesLock.destroy(): UNLOCK TABLES\n", 
              this_thread(), lock_info->db); 
#endif 
      lock_info->db->query ("UNLOCK TABLES"); 
      m_delete (table_locks->get(), lock_info->db->db_name); 
    } 
#ifdef TABLE_LOCK_DEBUG 
    else 
      werror ("[%O, %O] MySQLTablesLock.destroy(): %d locks left\n", 
              this_thread(), lock_info->db, lock_info->count); 
#endif 
  } 
} 
 
void drop_db( string name ) 
//! Drop the database @[name]. If the database is internal, the actual 
//! tables will be deleted as well. 
{ 
  if( (< "local", "mysql", "roxen"  >)[ name ] ) 
    error( "Cannot drop the '%s' database\n", name ); 
 
  array q = query( "SELECT name,local FROM dbs WHERE name=%s", name ); 
  if(!sizeof( q ) ) 
    error( "The database "+name+" does not exist\n" ); 
  if( sizeof( q ) && (int)q[0]["local"] ) { 
    invalidate_autousers (name); 
    query( "DROP DATABASE `"+name+"`" ); 
    Sql.Sql db = connect_to_my_mysql (0, "mysql"); 
    db->big_query ("DELETE FROM db WHERE Db=%s", name); 
    db->big_query ("FLUSH PRIVILEGES"); 
  } 
  query( "DELETE FROM dbs WHERE name=%s", name ); 
  query( "DELETE FROM db_groups WHERE db=%s", name ); 
  query( "DELETE FROM db_permissions WHERE db=%s", name ); 
  changed(); 
} 
 
void set_url( string db, string url, int is_internal ) 
//! Set the URL for the specified database. 
//! No data is copied. 
//! This function call only works for external databases.  
{ 
  query( "UPDATE dbs SET path=%s, local=%d WHERE name=%s", 
         url, is_internal, db ); 
  changed(); 
} 
 
void set_db_default_charset( string db, string default_charset ) 
//! Set the default character set for the specified database. 
//! No data is recoded. 
{ 
  if (default_charset && (default_charset != "")) { 
    query( "UPDATE dbs SET default_charset=%s WHERE name=%s", 
           default_charset, db ); 
  } else { 
    query( "UPDATE dbs SET default_charset=NULL WHERE name=%s", db ); 
  } 
  changed(); 
} 
 
string get_db_default_charset( string db) 
//! Get the default character set for the specified database. 
//! Returns @tt{0@} (zero) if no default has been set. 
{ 
  array(mapping(string:string)) res = 
    query( "SELECT default_charset FROM dbs WHERE name=%s", 
           db ); 
  if (sizeof(res)) return res[0]->default_charset; 
  return 0; 
} 
 
void copy_db_md( string oname, string nname ) 
//! Copy the metadata from oname to nname. Both databases must exist 
//! prior to this call. 
{ 
  mapping m = get_permission_map( )[oname]; 
  foreach( indices( m ), string s ) 
    if( Configuration c = roxenp()->find_configuration( s ) ) 
      set_permission( nname, c, m[s] ); 
  changed(); 
} 
 
array(mapping) backups( string dbname ) 
{ 
  if( dbname ) 
    return query( "SELECT * FROM db_backups WHERE db=%s", dbname ); 
  return query("SELECT * FROM db_backups");  
} 
 
array(mapping) restore( string dbname, string directory, string|void todb, 
                        array|void tables ) 
//! Restore the contents of the database dbname from the backup 
//! directory. New tables will not be deleted. 
//! 
//! The format of the result is as for the second element in the 
//! return array from @[backup]. If todb is specified, the backup will 
//! be restored in todb, not in dbname. 
{ 
  Sql.Sql db = cached_get( todb || dbname ); 
 
  if( !directory ) 
    error("Illegal directory\n"); 
 
  if( !db ) 
    error("Illegal database\n"); 
 
  directory = combine_path( getcwd(), directory ); 
 
  array q = 
    tables || 
    query( "SELECT tbl FROM db_backups WHERE db=%s AND directory=%s", 
           dbname, directory )->tbl; 
 
  array res = ({}); 
  foreach( q, string table ) 
  { 
    db->query( "DROP TABLE IF EXISTS "+table); 
    directory = combine_path( getcwd(), directory ); 
    res += db->query( "RESTORE TABLE "+table+" FROM %s", directory ); 
  } 
  return res; 
} 
 
void delete_backup( string dbname, string directory ) 
//! Delete a backup previously done with @[backup]. 
{ 
  // 1: Delete all backup files. 
  directory = combine_path( getcwd(), directory ); 
 
  foreach( query( "SELECT tbl FROM db_backups WHERE db=%s AND directory=%s", 
                  dbname, directory )->tbl, string table ) 
  { 
    rm( directory+"/"+table+".frm" ); 
    rm( directory+"/"+table+".MYD" ); 
  } 
  // 2: Delete the information about this backup. 
  query( "DELETE FROM db_backups WHERE db=%s AND directory=%s", 
         dbname, directory ); 
} 
 
array(string|array(mapping)) backup( string dbname, string directory ) 
//! Make a backup of all data in the specified database. 
//! If a directory is not specified, one will be created in $VARDIR. 
//! 
//! @returns 
//!   Returns an array with the following structure: 
//!   @array 
//!           @elem string directory 
//!             Name of the directory. 
//!           @elem array(mapping(string:string)) db_info 
//!           @array 
//!             @elem mapping(string:string) table_info 
//!               @mapping 
//!                 @member string "Table" 
//!                   Table name. 
//!                 @member string "Msg_type" 
//!                   one of: 
//!                   @string 
//!                     @value "status" 
//!                     @value "error" 
//!                     @value "info" 
//!                     @value "warning" 
//!                   @endstring 
//!                 @member string "Msg_text" 
//!                   The message. 
//!               @endmapping 
//!           @endarray 
//!   @endarray 
//! 
//! @note 
//!   Currently this function only works for internal databases. 
{ 
  Sql.Sql db = cached_get( dbname ); 
 
  if( !db ) 
    error("Illegal database\n"); 
 
  if( !directory ) 
    directory = roxen_path( "$VARDIR/"+dbname+"-"+isodate(time(1)) ); 
  directory = combine_path( getcwd(), directory ); 
 
  if( is_internal( dbname ) ) 
  { 
    mkdirhier( directory+"/" ); 
    array tables = db_tables( dbname ); 
    array res = ({}); 
    foreach( tables, string table ) 
    { 
      query( "DELETE FROM db_backups WHERE " 
             "db=%s AND directory=%s AND tbl=%s", 
             dbname, directory, table ); 
      query( "INSERT INTO db_backups (db,tbl,directory,whn) " 
             "VALUES (%s,%s,%s,%d)", 
             dbname, table, directory, time() ); 
      res += db->query( "BACKUP TABLE "+table+" TO %s",directory); 
    } 
    return ({ directory,res }); 
  } 
  else 
  { 
    error("Currently only handles internal databases\n"); 
    // Harder. :-) 
  } 
} 
 
 
void rename_db( string oname, string nname ) 
//! Rename a database. Please note that the actual data (in the case of 
//! internal database) is not copied. The old database is deleted, 
//! however. For external databases, only the metadata is modified, no 
//! attempt is made to alter the external database. 
{ 
  query( "UPDATE dbs SET name=%s WHERE name=%s", oname, nname ); 
  query( "UPDATE db_permissions SET db=%s WHERE db=%s", oname, nname ); 
  if( is_internal( oname ) ) 
  { 
    Sql.Sql db = connect_to_my_mysql( 0, "mysql" ); 
    db->query("CREATE DATABASE IF NOT EXISTS %s",nname); 
    db->query("UPDATE db SET Db=%s WHERE Db=%s",oname, nname ); 
    db->query("DROP DATABASE IF EXISTS %s",oname); 
    query( "FLUSH PRIVILEGES" ); 
  } 
  changed(); 
} 
 
mapping get_group( string name ) 
{ 
  array r= query( "SELECT * FROM groups WHERE name=%s", name ); 
  if( sizeof( r ) ) 
    return r[0]; 
} 
 
array(string) list_groups() 
{ 
  return query( "SELECT name FROM groups" )->name; 
} 
 
int create_group( string name,    string lname, 
                     string comment, string pattern ) 
{ 
  if( get_group( name ) ) 
  { 
    query( "UPDATE groups SET comment=%s, pattern=%s, lname=%s " 
           "WHERE name=%s",  comment, pattern, lname, name ); 
  } 
  else 
  { 
    query("INSERT INTO groups (comment,pattern,lname,name) " 
          "VALUES (%s,%s,%s,%s)", comment, pattern, lname, name ); 
  } 
} 
 
int delete_group( string name ) 
{ 
  if( !get_group( name ) ) 
    return 0; 
  if( sizeof(group_dbs( name )) ) 
    return 0; 
  query( "DELETE FROM groups WHERE name=%s", name ); 
  return 1; 
} 
 
array(string) group_dbs( string group ) 
{ 
  return query( "SELECT db FROM db_groups WHERE groupn=%s", group ) 
    ->db 
#ifndef YES_I_KNOW_WHAT_I_AM_DOING 
      -({"roxen","mysql"}) 
#endif 
    ; 
} 
 
string db_group( string db ) 
{ 
  array q =query( "SELECT groupn FROM db_groups WHERE db=%s", db ); 
  if( sizeof( q )  ) 
    return q[0]->groupn; 
  return "internal"; 
} 
 
string get_group_path( string db, string group ) 
{ 
  mapping m = get_group( group ); 
  if( !m ) 
    error("The group %O does not exist.", group ); 
  if( strlen( m->pattern ) ) 
  { 
    catch 
    { 
      Sql.Sql sq = Sql.Sql( m->pattern+"mysql" ); 
      sq->query( "CREATE DATABASE "+db ); 
    }; 
    return m->pattern+db; 
  } 
  return 0; 
} 
 
void set_db_group( string db, string group ) 
{ 
  query("DELETE FROM db_groups WHERE db=%s", db); 
  query("INSERT INTO db_groups (db,groupn) VALUES (%s,%s)", 
        db, group ); 
} 
 
void create_db( string name, string path, int is_internal, 
                string|void group, string|void default_charset ) 
//! Create a new symbolic database alias. 
//! 
//! If @[is_internal] is specified, the database will be automatically 
//! created if it does not exist, and the @[path] argument is ignored. 
//! 
//! If the database @[name] already exists, an error will be thrown 
//! 
//! If group is specified, the @[path] will be generated 
//! automatically using the groups defined by @[create_group] 
{ 
  if( get( name ) ) 
    error("The database "+name+" already exists\n"); 
  if( sizeof((array)name & ({ '@', ' ', '-', '&', '%', '\t', 
                              '\n', '\r', '\\', '/', '\'', '"', 
                              '(', ')', '*', '+', }) ) ) 
    error("Please do not use any of the characters @, -, &, /, \\ " 
          "or %% in database names.\nAlso avoid whitespace characters\n"); 
  if( has_value( name, "-" ) ) 
    name = replace( name, "-", "_" ); 
  if( group ) 
  { 
    set_db_group( name, group ); 
    if( is_internal ) 
    { 
      path = get_group_path( name, group ); 
      if( path ) 
        is_internal = 0; 
    } 
  } 
  else 
    query("INSERT INTO db_groups (db,groupn) VALUES (%s,%s)", 
          name, "internal" ); 
 
  if (default_charset) { 
    query( "INSERT INTO dbs (name, path, local, default_charset) " 
           "VALUES (%s, %s, %s, %s)", name, 
           (is_internal?name:path), (is_internal?"1":"0"), default_charset ); 
  } else { 
    query( "INSERT INTO dbs (name, path, local) VALUES (%s, %s, %s)", 
           name, (is_internal?name:path), (is_internal?"1":"0") ); 
  } 
  if( is_internal ) 
    catch(query( "CREATE DATABASE `"+name+"`")); 
  changed(); 
} 
 
int set_external_permission( string name, Configuration c, int level, 
                             string password ) 
//! Set the permission for the configuration @[c] on the database 
//! @[name] to @[level] for an external tcp connection from 127.0.0.1 
//! authenticated via password @[password]. 
//! 
//! Levels: 
//!  @int 
//!    @value DBManager.NONE 
//!      No access 
//!    @value DBManager.READ 
//!      Read access 
//!    @value DBManager.WRITE 
//!      Write access 
//!  @endint 
//! 
//! @returns 
//!  This function returns 0 if it fails. The only reason for it to 
//!  fail is if there is no database with the specified @[name]. 
//! 
//! @note 
//!  This function is only valid for local databases. 
//! 
//! @seealso 
//!  @[set_permission()], @[get_db_user()] 
{ 
  array(mapping(string:mixed)) d = 
           query("SELECT path,local FROM dbs WHERE name=%s", name ); 
 
  if( !sizeof( d ) ) 
      return 0; 
 
  if( (int)d[0]["local"] ) 
    set_external_user_permissions( c, name, level, password ); 
   
  return 1; 
} 
 
int set_permission( string name, Configuration c, int level ) 
//! Set the permission for the configuration @[c] on the database 
//! @[name] to @[level]. 
//! 
//! Levels: 
//!  @int 
//!    @value DBManager.NONE 
//!      No access 
//!    @value DBManager.READ 
//!      Read access 
//!    @value DBManager.WRITE 
//!      Write access 
//!  @endint 
//! 
//!  Please note that for non-local databases, it's not really 
//!  possible to differentiate between read and write permissions, 
//!  roxen does try to do that anyway by checking the requests and 
//!  disallowing anything but 'select' and 'show' from read only 
//!  databases. Please note that this is not really all that secure. 
//! 
//!  From local (in the mysql used by Roxen) databases, the 
//!  permissions are enforced by using different users, and should be 
//!  secure as long as the permission system in mysql is not modified 
//!  directly by the administrator. 
//! 
//! @returns 
//!  This function returns 0 if it fails. The only reason for it to 
//!  fail is if there is no database with the specified @[name]. 
{ 
  array(mapping(string:mixed)) d = 
           query("SELECT path,local FROM dbs WHERE name=%s", name ); 
 
  if( !sizeof( d ) ) 
      return 0; 
 
  query( "DELETE FROM db_permissions WHERE db=%s AND config=%s", 
         name,CN(c->name) ); 
 
  query( "INSERT INTO db_permissions (db,config,permission) " 
         "VALUES (%s,%s,%s)", name,CN(c->name), 
         (level?level==2?"write":"read":"none") ); 
   
  if( (int)d[0]["local"] ) 
    set_user_permissions( c, name, level ); 
 
  clear_sql_caches(); 
 
  return 1; 
} 
 
mapping(string:string) module_table_info( string db, string table ) 
{ 
  array(mapping(string:string)) td; 
  mapping(string:string) res1; 
  if( sizeof(td=query("SELECT * FROM module_tables WHERE db=%s AND tbl=%s", 
                      db, table ) ) ) { 
    res1 = td[0]; 
    if (table != "" || 
        (res1->conf && sizeof (res1->conf) && 
         res1->module && sizeof (res1->module))) 
      return res1; 
  } 
  else 
    res1 = ([]); 
 
  // Many modules don't set the conf and module on the database but 
  // only on the individual tables, so do some more effort to find a 
  // common conf and module if table == "". 
 
  if (table == "" && 
      sizeof (td = query ("SELECT DISTINCT conf, module, db FROM module_tables " 
                          "WHERE db=%s AND tbl!=\"\"", db))) { 
    if (sizeof (td) == 1 && 
        (td[0]->conf && sizeof (td[0]->conf) && 
         td[0]->module && sizeof (td[0]->module))) 
      return res1 + td[0]; 
    res1->module_varies = "yes"; 
 
    string conf; 
    foreach (td, mapping(string:string) ent) 
      if (ent->conf) { 
        if (!conf) conf = ent->conf; 
        else if (conf != ent->conf) { 
          conf = 0; 
          break; 
        } 
      } 
    if (conf) res1->conf = conf; 
    else res1->conf_varies = "yes"; 
 
    return res1; 
  } 
 
  return res1; 
} 
 
string insert_statement( string db, string table, mapping row ) 
//! Convenience function. 
{ 
  function q = cached_get( db )->quote; 
  string res = "INSERT INTO "+table+" "; 
  array(string) vi = ({}); 
  array(string) vv = ({}); 
  foreach( indices( row ), string r ) 
    if( !has_value( r, "." ) ) 
    { 
      vi += ({r}); 
      vv += ({"'"+q(row[r])+"'"}); 
    } 
  return res + "("+vi*","+") VALUES ("+vv*","+")"; 
} 
 
void is_module_table( RoxenModule module, string db, string table, 
                   string|void comment ) 
//! Tell the system that the table 'table' in the database 'db' 
//! belongs to the module 'module'. The comment is optional, and will 
//! be shown in the configuration interface if present. 
{ 
  string mn = module ? module->sname(): ""; 
  string cn = module ? module->my_configuration()->name : ""; 
  catch(query("DELETE FROM module_tables WHERE " 
              "module=%s AND conf=%s AND tbl=%s AND db=%s", 
              mn,cn,table,db )); 
 
  query("INSERT INTO module_tables (conf,module,db,tbl,comment) VALUES " 
        "(%s,%s,%s,%s,%s)", 
        cn,mn,db,table,comment||"" ); 
} 
 
void is_module_db( RoxenModule module, string db, string|void comment ) 
//! Tell the system that the databse 'db' belongs to the module 'module'. 
//! The comment is optional, and will be shown in the configuration 
//! interface if present. 
{ 
  is_module_table( module, db, "", comment ); 
} 
   
 
protected void create() 
{ 
  mixed err =  
  catch { 
    query("CREATE TABLE IF NOT EXISTS db_backups (" 
          " db varchar(80) not null, " 
          " tbl varchar(80) not null, " 
          " directory varchar(255) not null, " 
          " whn int unsigned not null, " 
          " INDEX place (db,directory))"); 
        
  query("CREATE TABLE IF NOT EXISTS db_groups (" 
        " db varchar(80) not null, " 
        " groupn varchar(80) not null)"); 
 
  query("CREATE TABLE IF NOT EXISTS groups ( " 
        "  name varchar(80) not null primary key, " 
        "  lname varchar(80) not null, " 
        "  comment blob not null, " 
        "  pattern varchar(255) not null default '')"); 
 
  catch(query("INSERT INTO groups (name,lname,comment,pattern) VALUES " 
      " ('internal','Uncategorized','Databases without any group','')")); 
 
  query("CREATE TABLE IF NOT EXISTS module_tables (" 
        "  conf varchar(80) not null, " 
        "  module varchar(80) not null, " 
        "  db   varchar(80) not null, " 
        "  tbl varchar(80) not null, " 
        "  comment blob not null, " 
        "  INDEX place (db,tbl), " 
        "  INDEX own (conf,module) " 
        ")"); 
     
  multiset q = (multiset)query( "SHOW TABLES" )->Tables_in_roxen; 
  if( !q->dbs ) 
  { 
    query( #" 
CREATE TABLE dbs ( 
 name VARCHAR(64) NOT NULL PRIMARY KEY, 
 path VARCHAR(100) NOT NULL,  
 local INT UNSIGNED NOT NULL, 
 default_charset VARCHAR(64) ) 
 " ); 
  } else if (catch { query("SELECT default_charset FROM dbs LIMIT 1"); }) { 
    // The default_charset field is missing. 
    // Upgraded Roxen? 
    query("ALTER TABLE dbs " 
          "  ADD default_charset VARCHAR(64)"); 
  } 
 
  if (!get ("local")) { 
    create_db( "local",  0, 1 ); 
    is_module_db( 0, "local", 
                  "The local database contains data that " 
                  "should not be shared between multiple-frontend servers" ); 
  } 
 
  if (!get ("roxen")) 
    create_db( "roxen",  0, 1 ); 
  if (!get ("mysql")) 
    create_db( "mysql",  0, 1 ); 
 
  if( !q->db_permissions ) 
  { 
    query(#" 
CREATE TABLE db_permissions ( 
 db VARCHAR(64) NOT NULL,  
 config VARCHAR(80) NOT NULL,  
 permission ENUM ('none','read','write') NOT NULL, 
 INDEX db_conf (db,config)) 
" ); 
    // Must be done from a call_out -- the configurations do not 
    // exist yet (this code is called before 'main' is called in 
    // roxen) 
    call_out( 
      lambda(){ 
        foreach( roxenp()->configurations, object c ) 
        { 
          set_permission( "local", c, WRITE ); 
        } 
      }, 0 ); 
  } 
 
  check_upgrade_mysql(); 
 
  synch_mysql_perms(); 
 
  if( file_stat( "etc/docs.frm" ) ) 
  { 
    if( !sizeof(query( "SELECT tbl FROM db_backups WHERE " 
                       "db=%s AND directory=%s", 
                       "docs", getcwd()+"/etc" ) ) ) 
      query("INSERT INTO db_backups (db,tbl,directory,whn) " 
            "VALUES ('docs','docs','"+getcwd()+"/etc','"+time()+"')"); 
  } 
   
  return; 
  }; 
 
  if (err) { 
    werror( describe_backtrace( err ) ); 
  } else { 
    werror("DBManager: Internal error; something threw a %O.\n", err); 
  } 
}