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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
|
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Copyright (C) 2008 Sun Microsystems
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Function with list databases, tables or fields */
#include <drizzled/server_includes.h>
#include <drizzled/sql_select.h>
#include <drizzled/show.h>
#include <drizzled/gettext.h>
#include <drizzled/util/convert.h>
#include <drizzled/error.h>
#include <drizzled/tztime.h>
#include <drizzled/data_home.h>
#include <drizzled/item/blob.h>
#include <drizzled/item/cmpfunc.h>
#include <drizzled/item/return_int.h>
#include <drizzled/item/empty_string.h>
#include <drizzled/item/return_date_time.h>
#include <drizzled/sql_base.h>
#include <drizzled/db.h>
#include <drizzled/field/timestamp.h>
#include <drizzled/field/decimal.h>
#include <drizzled/lock.h>
#include <drizzled/item/return_date_time.h>
#include <drizzled/item/empty_string.h>
#include "drizzled/plugin_registry.h"
#include <drizzled/info_schema.h>
#include <drizzled/message/schema.pb.h>
#include <mysys/cached_directory.h>
#include <sys/stat.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
extern "C"
int show_var_cmp(const void *var1, const void *var2);
inline const char *
str_or_nil(const char *str)
{
return str ? str : "<nil>";
}
/* Match the values of enum ha_choice */
static const char *ha_choice_values[] = {"", "0", "1"};
static void store_key_options(String *packet, Table *table, KEY *key_info);
static vector<InfoSchemaTable *> all_schema_tables;
void add_infoschema_table(InfoSchemaTable *schema_table)
{
if (schema_table->getFirstColumnIndex() == 0)
schema_table->setFirstColumnIndex(-1);
if (schema_table->getSecondColumnIndex() == 0)
schema_table->setSecondColumnIndex(-1);
all_schema_tables.push_back(schema_table);
}
void remove_infoschema_table(InfoSchemaTable *table)
{
all_schema_tables.erase(remove_if(all_schema_tables.begin(),
all_schema_tables.end(),
bind2nd(equal_to<InfoSchemaTable *>(),
table)),
all_schema_tables.end());
}
int wild_case_compare(const CHARSET_INFO * const cs, const char *str,const char *wildstr)
{
register int flag;
while (*wildstr)
{
while (*wildstr && *wildstr != wild_many && *wildstr != wild_one)
{
if (*wildstr == wild_prefix && wildstr[1])
wildstr++;
if (my_toupper(cs, *wildstr++) != my_toupper(cs, *str++))
return (1);
}
if (! *wildstr )
return (*str != 0);
if (*wildstr++ == wild_one)
{
if (! *str++)
return (1); /* One char; skip */
}
else
{ /* Found '*' */
if (! *wildstr)
return (0); /* '*' as last char: OK */
flag=(*wildstr != wild_many && *wildstr != wild_one);
do
{
if (flag)
{
char cmp;
if ((cmp= *wildstr) == wild_prefix && wildstr[1])
cmp= wildstr[1];
cmp= my_toupper(cs, cmp);
while (*str && my_toupper(cs, *str) != cmp)
str++;
if (! *str)
return (1);
}
if (wild_case_compare(cs, str, wildstr) == 0)
return (0);
} while (*str++);
return (1);
}
}
return (*str != '\0');
}
/**
* @brief
* Find subdirectories (schemas) in a given directory (datadir).
*
* @param[in] session Thread handler
* @param[out] files Put found entries in this list
* @param[in] path Path to database
* @param[in] wild Filter for found entries
*
* @retval false Success
* @retval true Error
*/
static bool find_schemas(Session *session, vector<LEX_STRING*> &files,
const char *path, const char *wild)
{
if (wild && (wild[0] == '\0'))
wild= 0;
CachedDirectory directory(path);
if (directory.fail())
{
my_errno= directory.getError();
my_error(ER_CANT_READ_DIR, MYF(0), path, my_errno);
return(true);
}
CachedDirectory::Entries entries= directory.getEntries();
CachedDirectory::Entries::iterator entry_iter= entries.begin();
while (entry_iter != entries.end())
{
uint32_t file_name_len;
char uname[NAME_LEN + 1]; /* Unencoded name */
struct stat entry_stat;
CachedDirectory::Entry *entry= *entry_iter;
if ((entry->filename == ".") || (entry->filename == ".."))
{
++entry_iter;
continue;
}
if (stat(entry->filename.c_str(), &entry_stat))
{
my_errno= errno;
my_error(ER_CANT_GET_STAT, MYF(0), entry->filename.c_str(), my_errno);
return(true);
}
if (! S_ISDIR(entry_stat.st_mode))
{
++entry_iter;
continue;
}
file_name_len= filename_to_tablename(entry->filename.c_str(), uname,
sizeof(uname));
if (wild && wild_compare(uname, wild, 0))
{
++entry_iter;
continue;
}
LEX_STRING *file_name= 0;
file_name= session->make_lex_string(file_name, uname, file_name_len, true);
if (file_name == NULL)
return(true);
files.push_back(file_name);
++entry_iter;
}
return(false);
}
bool drizzled_show_create(Session *session, TableList *table_list)
{
Protocol *protocol= session->protocol;
char buff[2048];
String buffer(buff, sizeof(buff), system_charset_info);
/* Only one table for now, but VIEW can involve several tables */
if (session->openTables(table_list))
{
if (session->is_error())
return true;
/*
Clear all messages with 'error' level status and
issue a warning with 'warning' level status in
case of invalid view and last error is ER_VIEW_INVALID
*/
drizzle_reset_errors(session, true);
session->clear_error();
}
buffer.length(0);
if (store_create_info(table_list, &buffer, NULL))
return true;
List<Item> field_list;
{
field_list.push_back(new Item_empty_string("Table",NAME_CHAR_LEN));
// 1024 is for not to confuse old clients
field_list.push_back(new Item_empty_string("Create Table",
max(buffer.length(),(uint32_t)1024)));
}
if (protocol->sendFields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
{
return true;
}
protocol->prepareForResend();
{
if (table_list->schema_table)
protocol->store(table_list->schema_table->getTableName().c_str());
else
protocol->store(table_list->table->alias);
}
protocol->store(buffer.ptr(), buffer.length());
if (protocol->write())
return true;
session->my_eof();
return false;
}
/**
Get a CREATE statement for a given database.
The database is identified by its name, passed as @c dbname parameter.
The name should be encoded using the system character set (UTF8 currently).
Resulting statement is stored in the string pointed by @c buffer. The string
is emptied first and its character set is set to the system character set.
If HA_LEX_CREATE_IF_NOT_EXISTS flag is set in @c create_info->options, then
the resulting CREATE statement contains "IF NOT EXISTS" clause. Other flags
in @c create_options are ignored.
@param session The current thread instance.
@param dbname The name of the database.
@param buffer A String instance where the statement is stored.
@param create_info If not NULL, the options member influences the resulting
CRATE statement.
@returns true if errors are detected, false otherwise.
*/
static bool store_db_create_info(const char *dbname, String *buffer, bool if_not_exists)
{
drizzled::message::Schema schema;
if (!my_strcasecmp(system_charset_info, dbname,
INFORMATION_SCHEMA_NAME.c_str()))
{
dbname= INFORMATION_SCHEMA_NAME.c_str();
}
else
{
int r= get_database_metadata(dbname, &schema);
if(r < 0)
return true;
}
buffer->length(0);
buffer->free();
buffer->set_charset(system_charset_info);
buffer->append(STRING_WITH_LEN("CREATE DATABASE "));
if (if_not_exists)
buffer->append(STRING_WITH_LEN("IF NOT EXISTS "));
buffer->append_identifier(dbname, strlen(dbname));
if (schema.has_collation() && strcmp(schema.collation().c_str(),
default_charset_info->name))
{
buffer->append(" COLLATE = ");
buffer->append(schema.collation().c_str());
}
return false;
}
bool mysqld_show_create_db(Session *session, char *dbname, bool if_not_exists)
{
char buff[2048];
String buffer(buff, sizeof(buff), system_charset_info);
Protocol *protocol=session->protocol;
if (store_db_create_info(dbname, &buffer, if_not_exists))
{
/*
This assumes that the only reason for which store_db_create_info()
can fail is incorrect database name (which is the case now).
*/
my_error(ER_BAD_DB_ERROR, MYF(0), dbname);
return true;
}
List<Item> field_list;
field_list.push_back(new Item_empty_string("Database",NAME_CHAR_LEN));
field_list.push_back(new Item_empty_string("Create Database",1024));
if (protocol->sendFields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
return true;
protocol->prepareForResend();
protocol->store(dbname, strlen(dbname));
protocol->store(buffer.ptr(), buffer.length());
if (protocol->write())
return true;
session->my_eof();
return false;
}
/****************************************************************************
Return only fields for API mysql_list_fields
Use "show table wildcard" in mysql instead of this
****************************************************************************/
void
mysqld_list_fields(Session *session, TableList *table_list, const char *wild)
{
Table *table;
if (session->openTables(table_list))
return;
table= table_list->table;
List<Item> field_list;
Field **ptr,*field;
for (ptr=table->field ; (field= *ptr); ptr++)
{
if (!wild || !wild[0] ||
!wild_case_compare(system_charset_info, field->field_name,wild))
{
field_list.push_back(new Item_field(field));
}
}
table->restoreRecordAsDefault(); // Get empty record
table->use_all_columns();
if (session->protocol->sendFields(&field_list, Protocol::SEND_DEFAULTS))
return;
session->my_eof();
}
/*
Get the quote character for displaying an identifier.
SYNOPSIS
get_quote_char_for_identifier()
IMPLEMENTATION
Force quoting in the following cases:
- name is empty (for one, it is possible when we use this function for
quoting user and host names for DEFINER clause);
- name is a keyword;
- name includes a special character;
Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE
is set.
RETURN
EOF No quote character is needed
# Quote character
*/
int get_quote_char_for_identifier()
{
return '`';
}
/* Append directory name (if exists) to CREATE INFO */
static void append_directory(String *packet, const char *dir_type,
const char *filename)
{
if (filename)
{
uint32_t length= dirname_length(filename);
packet->append(' ');
packet->append(dir_type);
packet->append(STRING_WITH_LEN(" DIRECTORY='"));
packet->append(filename, length);
packet->append('\'');
}
}
#define LIST_PROCESS_HOST_LEN 64
static bool get_field_default_value(Field *timestamp_field,
Field *field, String *def_value,
bool quoted)
{
bool has_default;
bool has_now_default;
/*
We are using CURRENT_TIMESTAMP instead of NOW because it is
more standard
*/
has_now_default= (timestamp_field == field &&
field->unireg_check != Field::TIMESTAMP_UN_FIELD);
has_default= (field->type() != DRIZZLE_TYPE_BLOB &&
!(field->flags & NO_DEFAULT_VALUE_FLAG) &&
field->unireg_check != Field::NEXT_NUMBER);
def_value->length(0);
if (has_default)
{
if (has_now_default)
def_value->append(STRING_WITH_LEN("CURRENT_TIMESTAMP"));
else if (!field->is_null())
{ // Not null by default
char tmp[MAX_FIELD_WIDTH];
String type(tmp, sizeof(tmp), field->charset());
field->val_str(&type);
if (type.length())
{
String def_val;
uint32_t dummy_errors;
/* convert to system_charset_info == utf8 */
def_val.copy(type.ptr(), type.length(), field->charset(),
system_charset_info, &dummy_errors);
if (quoted)
append_unescaped(def_value, def_val.ptr(), def_val.length());
else
def_value->append(def_val.ptr(), def_val.length());
}
else if (quoted)
def_value->append(STRING_WITH_LEN("''"));
}
else if (field->maybe_null() && quoted)
def_value->append(STRING_WITH_LEN("NULL")); // Null as default
else
return false;
}
return has_default;
}
/*
Build a CREATE TABLE statement for a table.
SYNOPSIS
store_create_info()
table_list A list containing one table to write statement
for.
packet Pointer to a string where statement will be
written.
create_info_arg Pointer to create information that can be used
to tailor the format of the statement. Can be
NULL, in which case only SQL_MODE is considered
when building the statement.
NOTE
Currently always return 0, but might return error code in the
future.
RETURN
0 OK
*/
int store_create_info(TableList *table_list, String *packet, HA_CREATE_INFO *create_info_arg)
{
List<Item> field_list;
char tmp[MAX_FIELD_WIDTH], *for_str, def_value_buf[MAX_FIELD_WIDTH];
const char *alias;
string buff;
String type(tmp, sizeof(tmp), system_charset_info);
String def_value(def_value_buf, sizeof(def_value_buf), system_charset_info);
Field **ptr,*field;
uint32_t primary_key;
KEY *key_info;
Table *table= table_list->table;
handler *file= table->file;
TableShare *share= table->s;
HA_CREATE_INFO create_info;
bool show_table_options= false;
my_bitmap_map *old_map;
table->restoreRecordAsDefault(); // Get empty record
if (share->tmp_table)
packet->append(STRING_WITH_LEN("CREATE TEMPORARY TABLE "));
else
packet->append(STRING_WITH_LEN("CREATE TABLE "));
if (create_info_arg &&
(create_info_arg->options & HA_LEX_CREATE_IF_NOT_EXISTS))
packet->append(STRING_WITH_LEN("IF NOT EXISTS "));
if (table_list->schema_table)
alias= table_list->schema_table->getTableName().c_str();
else
alias= share->table_name.str;
packet->append_identifier(alias, strlen(alias));
packet->append(STRING_WITH_LEN(" (\n"));
/*
We need this to get default values from the table
We have to restore the read_set if we are called from insert in case
of row based replication.
*/
old_map= table->use_all_columns(table->read_set);
for (ptr=table->field ; (field= *ptr); ptr++)
{
uint32_t flags = field->flags;
if (ptr != table->field)
packet->append(STRING_WITH_LEN(",\n"));
packet->append(STRING_WITH_LEN(" "));
packet->append_identifier(field->field_name, strlen(field->field_name));
packet->append(' ');
// check for surprises from the previous call to Field::sql_type()
if (type.ptr() != tmp)
type.set(tmp, sizeof(tmp), system_charset_info);
else
type.set_charset(system_charset_info);
field->sql_type(type);
packet->append(type.ptr(), type.length(), system_charset_info);
if (field->has_charset())
{
if (field->charset() != share->table_charset)
{
packet->append(STRING_WITH_LEN(" CHARACTER SET "));
packet->append(field->charset()->csname);
}
/*
For string types dump collation name only if
collation is not primary for the given charset
*/
if (!(field->charset()->state & MY_CS_PRIMARY))
{
packet->append(STRING_WITH_LEN(" COLLATE "));
packet->append(field->charset()->name);
}
}
if (flags & NOT_NULL_FLAG)
packet->append(STRING_WITH_LEN(" NOT NULL"));
else if (field->type() == DRIZZLE_TYPE_TIMESTAMP)
{
/*
TIMESTAMP field require explicit NULL flag, because unlike
all other fields they are treated as NOT NULL by default.
*/
packet->append(STRING_WITH_LEN(" NULL"));
}
{
/*
Add field flags about FIELD FORMAT (FIXED or DYNAMIC)
and about STORAGE (DISK or MEMORY).
*/
enum column_format_type column_format= (enum column_format_type)
((flags >> COLUMN_FORMAT_FLAGS) & COLUMN_FORMAT_MASK);
if (column_format)
{
packet->append(STRING_WITH_LEN(" /*!"));
packet->append(STRING_WITH_LEN(" COLUMN_FORMAT"));
if (column_format == COLUMN_FORMAT_TYPE_FIXED)
packet->append(STRING_WITH_LEN(" FIXED */"));
else
packet->append(STRING_WITH_LEN(" DYNAMIC */"));
}
}
if (get_field_default_value(table->timestamp_field, field, &def_value, 1))
{
packet->append(STRING_WITH_LEN(" DEFAULT "));
packet->append(def_value.ptr(), def_value.length(), system_charset_info);
}
if (table->timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD)
packet->append(STRING_WITH_LEN(" ON UPDATE CURRENT_TIMESTAMP"));
if (field->unireg_check == Field::NEXT_NUMBER)
packet->append(STRING_WITH_LEN(" AUTO_INCREMENT"));
if (field->comment.length)
{
packet->append(STRING_WITH_LEN(" COMMENT "));
append_unescaped(packet, field->comment.str, field->comment.length);
}
}
key_info= table->key_info;
memset(&create_info, 0, sizeof(create_info));
/* Allow update_create_info to update row type */
create_info.row_type= share->row_type;
file->update_create_info(&create_info);
primary_key= share->primary_key;
for (uint32_t i=0 ; i < share->keys ; i++,key_info++)
{
KEY_PART_INFO *key_part= key_info->key_part;
bool found_primary=0;
packet->append(STRING_WITH_LEN(",\n "));
if (i == primary_key && is_primary_key(key_info))
{
found_primary=1;
/*
No space at end, because a space will be added after where the
identifier would go, but that is not added for primary key.
*/
packet->append(STRING_WITH_LEN("PRIMARY KEY"));
}
else if (key_info->flags & HA_NOSAME)
packet->append(STRING_WITH_LEN("UNIQUE KEY "));
else
packet->append(STRING_WITH_LEN("KEY "));
if (!found_primary)
packet->append_identifier(key_info->name, strlen(key_info->name));
packet->append(STRING_WITH_LEN(" ("));
for (uint32_t j=0 ; j < key_info->key_parts ; j++,key_part++)
{
if (j)
packet->append(',');
if (key_part->field)
packet->append_identifier(key_part->field->field_name,
strlen(key_part->field->field_name));
if (key_part->field &&
(key_part->length !=
table->field[key_part->fieldnr-1]->key_length()))
{
buff.assign("(");
buff.append(to_string((int32_t) key_part->length /
key_part->field->charset()->mbmaxlen));
buff.append(")");
packet->append(buff.c_str(), buff.length());
}
}
packet->append(')');
store_key_options(packet, table, key_info);
}
/*
Get possible foreign key definitions stored in InnoDB and append them
to the CREATE TABLE statement
*/
if ((for_str= file->get_foreign_key_create_info()))
{
packet->append(for_str, strlen(for_str));
file->free_foreign_key_create_info(for_str);
}
packet->append(STRING_WITH_LEN("\n)"));
{
show_table_options= true;
/*
Get possible table space definitions and append them
to the CREATE TABLE statement
*/
/*
IF check_create_info
THEN add ENGINE only if it was used when creating the table
*/
if (!create_info_arg ||
(create_info_arg->used_fields & HA_CREATE_USED_ENGINE))
{
packet->append(STRING_WITH_LEN(" ENGINE="));
packet->append(file->engine->getName().c_str());
}
/*
Add AUTO_INCREMENT=... if there is an AUTO_INCREMENT column,
and NEXT_ID > 1 (the default). We must not print the clause
for engines that do not support this as it would break the
import of dumps, but as of this writing, the test for whether
AUTO_INCREMENT columns are allowed and wether AUTO_INCREMENT=...
is supported is identical, !(file->table_flags() & HA_NO_AUTO_INCREMENT))
Because of that, we do not explicitly test for the feature,
but may extrapolate its existence from that of an AUTO_INCREMENT column.
*/
if (create_info.auto_increment_value > 1)
{
packet->append(STRING_WITH_LEN(" AUTO_INCREMENT="));
buff= to_string(create_info.auto_increment_value);
packet->append(buff.c_str(), buff.length());
}
if (share->min_rows)
{
packet->append(STRING_WITH_LEN(" MIN_ROWS="));
buff= to_string(share->min_rows);
packet->append(buff.c_str(), buff.length());
}
if (share->max_rows && !table_list->schema_table)
{
packet->append(STRING_WITH_LEN(" MAX_ROWS="));
buff= to_string(share->max_rows);
packet->append(buff.c_str(), buff.length());
}
if (share->avg_row_length)
{
packet->append(STRING_WITH_LEN(" AVG_ROW_LENGTH="));
buff= to_string(share->avg_row_length);
packet->append(buff.c_str(), buff.length());
}
if (share->db_create_options & HA_OPTION_PACK_KEYS)
packet->append(STRING_WITH_LEN(" PACK_KEYS=1"));
if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
packet->append(STRING_WITH_LEN(" PACK_KEYS=0"));
/* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */
if (share->db_create_options & HA_OPTION_CHECKSUM)
packet->append(STRING_WITH_LEN(" CHECKSUM=1"));
if (share->page_checksum != HA_CHOICE_UNDEF)
{
packet->append(STRING_WITH_LEN(" PAGE_CHECKSUM="));
packet->append(ha_choice_values[(uint32_t) share->page_checksum], 1);
}
if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
packet->append(STRING_WITH_LEN(" DELAY_KEY_WRITE=1"));
if (create_info.row_type != ROW_TYPE_DEFAULT)
{
packet->append(STRING_WITH_LEN(" ROW_FORMAT="));
packet->append(ha_row_type[(uint32_t) create_info.row_type]);
}
if (table->s->key_block_size)
{
packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
buff= to_string(table->s->key_block_size);
packet->append(buff.c_str(), buff.length());
}
if (share->block_size)
{
packet->append(STRING_WITH_LEN(" BLOCK_SIZE="));
buff= to_string(share->block_size);
packet->append(buff.c_str(), buff.length());
}
table->file->append_create_info(packet);
if (share->comment.length)
{
packet->append(STRING_WITH_LEN(" COMMENT="));
append_unescaped(packet, share->comment.str, share->comment.length);
}
if (share->connect_string.length)
{
packet->append(STRING_WITH_LEN(" CONNECTION="));
append_unescaped(packet, share->connect_string.str, share->connect_string.length);
}
append_directory(packet, "DATA", create_info.data_file_name);
append_directory(packet, "INDEX", create_info.index_file_name);
}
table->restore_column_map(old_map);
return(0);
}
static void store_key_options(String *packet, Table *table, KEY *key_info)
{
char *end, buff[32];
if (key_info->algorithm == HA_KEY_ALG_BTREE)
packet->append(STRING_WITH_LEN(" USING BTREE"));
if (key_info->algorithm == HA_KEY_ALG_HASH)
packet->append(STRING_WITH_LEN(" USING HASH"));
if ((key_info->flags & HA_USES_BLOCK_SIZE) &&
table->s->key_block_size != key_info->block_size)
{
packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
end= int64_t10_to_str(key_info->block_size, buff, 10);
packet->append(buff, (uint32_t) (end - buff));
}
assert(test(key_info->flags & HA_USES_COMMENT) ==
(key_info->comment.length > 0));
if (key_info->flags & HA_USES_COMMENT)
{
packet->append(STRING_WITH_LEN(" COMMENT "));
append_unescaped(packet, key_info->comment.str,
key_info->comment.length);
}
}
/****************************************************************************
Return info about all processes
returns for each thread: thread id, user, host, db, command, info
****************************************************************************/
class thread_info :public ilink {
public:
static void *operator new(size_t size)
{
return (void*) sql_alloc((uint32_t) size);
}
static void operator delete(void *, size_t)
{ TRASH(ptr, size); }
my_thread_id thread_id;
time_t start_time;
uint32_t command;
const char *user,*host,*db,*proc_info,*state_info;
char *query;
};
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
template class I_List<thread_info>;
#endif
void mysqld_list_processes(Session *session,const char *user, bool)
{
Item *field;
List<Item> field_list;
I_List<thread_info> thread_infos;
Protocol *protocol= session->protocol;
field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS));
field_list.push_back(new Item_empty_string("User",16));
field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN));
field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN));
field->maybe_null= true;
field_list.push_back(new Item_empty_string("Command",16));
field_list.push_back(new Item_return_int("Time",7, DRIZZLE_TYPE_LONG));
field_list.push_back(field=new Item_empty_string("State",30));
field->maybe_null= true;
field_list.push_back(field=new Item_empty_string("Info", PROCESS_LIST_WIDTH));
field->maybe_null= true;
if (protocol->sendFields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
return;
pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
if (!session->killed)
{
Session *tmp;
for( vector<Session*>::iterator it= session_list.begin(); it != session_list.end(); ++it )
{
tmp= *it;
Security_context *tmp_sctx= &tmp->security_ctx;
struct st_my_thread_var *mysys_var;
if (tmp->protocol->isConnected() && (!user || (tmp_sctx->user.c_str() && !strcmp(tmp_sctx->user.c_str(), user))))
{
thread_info *session_info= new thread_info;
session_info->thread_id=tmp->thread_id;
session_info->user= session->strdup(tmp_sctx->user.c_str() ? tmp_sctx->user.c_str() : "unauthenticated user");
session_info->host= session->strdup(tmp_sctx->ip.c_str());
if ((session_info->db=tmp->db)) // Safe test
session_info->db=session->strdup(session_info->db);
session_info->command=(int) tmp->command;
if ((mysys_var= tmp->mysys_var))
pthread_mutex_lock(&mysys_var->mutex);
if (tmp->killed == Session::KILL_CONNECTION)
session_info->proc_info= (char*) "Killed";
else
session_info->proc_info= command_name[session_info->command].str;
session_info->state_info= (char*) (tmp->protocol->isWriting() ?
"Writing to net" :
tmp->protocol->isReading() ?
(session_info->command == COM_SLEEP ?
NULL : "Reading from net") :
tmp->get_proc_info() ? tmp->get_proc_info() :
tmp->mysys_var &&
tmp->mysys_var->current_cond ?
"Waiting on cond" : NULL);
if (mysys_var)
pthread_mutex_unlock(&mysys_var->mutex);
session_info->start_time= tmp->start_time;
session_info->query= NULL;
if (tmp->process_list_info[0])
session_info->query= session->strdup(tmp->process_list_info);
thread_infos.append(session_info);
}
}
}
pthread_mutex_unlock(&LOCK_thread_count);
thread_info *session_info;
time_t now= time(NULL);
while ((session_info=thread_infos.get()))
{
protocol->prepareForResend();
protocol->store((uint64_t) session_info->thread_id);
protocol->store(session_info->user);
protocol->store(session_info->host);
protocol->store(session_info->db);
protocol->store(session_info->proc_info);
if (session_info->start_time)
protocol->store((uint32_t) (now - session_info->start_time));
else
protocol->store();
protocol->store(session_info->state_info);
protocol->store(session_info->query);
if (protocol->write())
break; /* purecov: inspected */
}
session->my_eof();
return;
}
/*****************************************************************************
Status functions
*****************************************************************************/
static vector<SHOW_VAR *> all_status_vars;
static bool status_vars_inited= 0;
int show_var_cmp(const void *var1, const void *var2)
{
return strcmp(((SHOW_VAR*)var1)->name, ((SHOW_VAR*)var2)->name);
}
class show_var_cmp_functor
{
public:
show_var_cmp_functor() { }
inline bool operator()(const SHOW_VAR *var1, const SHOW_VAR *var2) const
{
int val= strcmp(var1->name, var2->name);
return (val < 0);
}
};
class show_var_remove_if
{
public:
show_var_remove_if() { }
inline bool operator()(const SHOW_VAR *curr) const
{
return (curr->type == SHOW_UNDEF);
}
};
SHOW_VAR *getFrontOfStatusVars()
{
return all_status_vars.front();
}
/*
Adds an array of SHOW_VAR entries to the output of SHOW STATUS
SYNOPSIS
add_status_vars(SHOW_VAR *list)
list - an array of SHOW_VAR entries to add to all_status_vars
the last entry must be {0,0,SHOW_UNDEF}
NOTE
The handling of all_status_vars[] is completely internal, it's allocated
automatically when something is added to it, and deleted completely when
the last entry is removed.
As a special optimization, if add_status_vars() is called before
init_status_vars(), it assumes "startup mode" - neither concurrent access
to the array nor SHOW STATUS are possible (thus it skips locks and qsort)
*/
int add_status_vars(SHOW_VAR *list)
{
int res= 0;
if (status_vars_inited)
pthread_mutex_lock(&LOCK_status);
while (list->name)
all_status_vars.insert(all_status_vars.begin(), list++);
if (status_vars_inited)
sort(all_status_vars.begin(), all_status_vars.end(),
show_var_cmp_functor());
if (status_vars_inited)
pthread_mutex_unlock(&LOCK_status);
return res;
}
/*
Make all_status_vars[] usable for SHOW STATUS
NOTE
See add_status_vars(). Before init_status_vars() call, add_status_vars()
works in a special fast "startup" mode. Thus init_status_vars()
should be called as late as possible but before enabling multi-threading.
*/
void init_status_vars()
{
status_vars_inited= 1;
sort(all_status_vars.begin(), all_status_vars.end(),
show_var_cmp_functor());
}
void reset_status_vars()
{
vector<SHOW_VAR *>::iterator p= all_status_vars.begin();
while (p != all_status_vars.end())
{
/* Note that SHOW_LONG_NOFLUSH variables are not reset */
if ((*p)->type == SHOW_LONG)
(*p)->value= 0;
++p;
}
}
/*
catch-all cleanup function, cleans up everything no matter what
DESCRIPTION
This function is not strictly required if all add_to_status/
remove_status_vars are properly paired, but it's a safety measure that
deletes everything from the all_status_vars vector even if some
remove_status_vars were forgotten
*/
void free_status_vars()
{
all_status_vars.clear();
}
/*
Removes an array of SHOW_VAR entries from the output of SHOW STATUS
SYNOPSIS
remove_status_vars(SHOW_VAR *list)
list - an array of SHOW_VAR entries to remove to all_status_vars
the last entry must be {0,0,SHOW_UNDEF}
NOTE
there's lots of room for optimizing this, especially in non-sorted mode,
but nobody cares - it may be called only in case of failed plugin
initialization in the mysqld startup.
*/
void remove_status_vars(SHOW_VAR *list)
{
if (status_vars_inited)
{
pthread_mutex_lock(&LOCK_status);
SHOW_VAR *all= all_status_vars.front();
int a= 0, b= all_status_vars.size(), c= (a+b)/2;
for (; list->name; list++)
{
int res= 0;
for (a= 0, b= all_status_vars.size(); b-a > 1; c= (a+b)/2)
{
res= show_var_cmp(list, all+c);
if (res < 0)
b= c;
else if (res > 0)
a= c;
else
break;
}
if (res == 0)
all[c].type= SHOW_UNDEF;
}
/* removes all the SHOW_UNDEF elements from the vector */
all_status_vars.erase(std::remove_if(all_status_vars.begin(),
all_status_vars.end(),show_var_remove_if()),
all_status_vars.end());
pthread_mutex_unlock(&LOCK_status);
}
else
{
SHOW_VAR *all= all_status_vars.front();
uint32_t i;
for (; list->name; list++)
{
for (i= 0; i < all_status_vars.size(); i++)
{
if (show_var_cmp(list, all+i))
continue;
all[i].type= SHOW_UNDEF;
break;
}
}
/* removes all the SHOW_UNDEF elements from the vector */
all_status_vars.erase(std::remove_if(all_status_vars.begin(),
all_status_vars.end(),show_var_remove_if()),
all_status_vars.end());
}
}
/* collect status for all running threads */
void calc_sum_of_all_status(STATUS_VAR *to)
{
/* Ensure that thread id not killed during loop */
pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
/* Get global values as base */
*to= global_status_var;
/* Add to this status from existing threads */
for( vector<Session*>::iterator it= session_list.begin(); it != session_list.end(); ++it )
{
add_to_status(to, &((*it)->status_var));
}
pthread_mutex_unlock(&LOCK_thread_count);
return;
}
/*
Store record to I_S table, convert HEAP table
to MyISAM if necessary
SYNOPSIS
schema_table_store_record()
session thread handler
table Information schema table to be updated
RETURN
0 success
1 error
*/
bool schema_table_store_record(Session *session, Table *table)
{
int error;
if ((error= table->file->ha_write_row(table->record[0])))
{
Tmp_Table_Param *param= table->pos_in_table_list->schema_table_param;
if (create_myisam_from_heap(session, table, param->start_recinfo,
¶m->recinfo, error, 0))
return true;
}
return false;
}
static int make_table_list(Session *session, Select_Lex *sel,
LEX_STRING *db_name, LEX_STRING *table_name)
{
Table_ident *table_ident;
table_ident= new Table_ident(session, *db_name, *table_name, 1);
sel->init_query();
if (!sel->add_table_to_list(session, table_ident, 0, 0, TL_READ))
return 1;
return 0;
}
/**
@brief Get lookup value from the part of 'WHERE' condition
@details This function gets lookup value from
the part of 'WHERE' condition if it's possible and
fill appropriate lookup_field_vals struct field
with this value.
@param[in] session thread handler
@param[in] item_func part of WHERE condition
@param[in] table I_S table
@param[in, out] lookup_field_vals Struct which holds lookup values
@return
0 success
1 error, there can be no matching records for the condition
*/
static bool get_lookup_value(Session *session, Item_func *item_func,
TableList *table,
LOOKUP_FIELD_VALUES *lookup_field_vals)
{
InfoSchemaTable *schema_table= table->schema_table;
const char *field_name1= schema_table->getFirstColumnIndex() >= 0 ?
schema_table->getColumnName(schema_table->getFirstColumnIndex()).c_str() : "";
const char *field_name2= schema_table->getSecondColumnIndex() >= 0 ?
schema_table->getColumnName(schema_table->getSecondColumnIndex()).c_str() : "";
if (item_func->functype() == Item_func::EQ_FUNC ||
item_func->functype() == Item_func::EQUAL_FUNC)
{
int idx_field, idx_val;
char tmp[MAX_FIELD_WIDTH];
String *tmp_str, str_buff(tmp, sizeof(tmp), system_charset_info);
Item_field *item_field;
const CHARSET_INFO * const cs= system_charset_info;
if (item_func->arguments()[0]->type() == Item::FIELD_ITEM &&
item_func->arguments()[1]->const_item())
{
idx_field= 0;
idx_val= 1;
}
else if (item_func->arguments()[1]->type() == Item::FIELD_ITEM &&
item_func->arguments()[0]->const_item())
{
idx_field= 1;
idx_val= 0;
}
else
return 0;
item_field= (Item_field*) item_func->arguments()[idx_field];
if (table->table != item_field->field->table)
return 0;
tmp_str= item_func->arguments()[idx_val]->val_str(&str_buff);
/* impossible value */
if (!tmp_str)
return 1;
/* Lookup value is database name */
if (!cs->coll->strnncollsp(cs, (unsigned char *) field_name1, strlen(field_name1),
(unsigned char *) item_field->field_name,
strlen(item_field->field_name), 0))
{
session->make_lex_string(&lookup_field_vals->db_value, tmp_str->ptr(),
tmp_str->length(), false);
}
/* Lookup value is table name */
else if (!cs->coll->strnncollsp(cs, (unsigned char *) field_name2,
strlen(field_name2),
(unsigned char *) item_field->field_name,
strlen(item_field->field_name), 0))
{
session->make_lex_string(&lookup_field_vals->table_value, tmp_str->ptr(),
tmp_str->length(), false);
}
}
return 0;
}
/**
@brief Calculates lookup values from 'WHERE' condition
@details This function calculates lookup value(database name, table name)
from 'WHERE' condition if it's possible and
fill lookup_field_vals struct fields with these values.
@param[in] session thread handler
@param[in] cond WHERE condition
@param[in] table I_S table
@param[in, out] lookup_field_vals Struct which holds lookup values
@return
0 success
1 error, there can be no matching records for the condition
*/
bool calc_lookup_values_from_cond(Session *session, COND *cond, TableList *table,
LOOKUP_FIELD_VALUES *lookup_field_vals)
{
if (!cond)
return 0;
if (cond->type() == Item::COND_ITEM)
{
if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
{
List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
Item *item;
while ((item= li++))
{
if (item->type() == Item::FUNC_ITEM)
{
if (get_lookup_value(session, (Item_func*)item, table, lookup_field_vals))
return 1;
}
else
{
if (calc_lookup_values_from_cond(session, item, table, lookup_field_vals))
return 1;
}
}
}
return 0;
}
else if (cond->type() == Item::FUNC_ITEM &&
get_lookup_value(session, (Item_func*) cond, table, lookup_field_vals))
return 1;
return 0;
}
static bool uses_only_table_name_fields(Item *item, TableList *table)
{
if (item->type() == Item::FUNC_ITEM)
{
Item_func *item_func= (Item_func*)item;
for (uint32_t i=0; i<item_func->argument_count(); i++)
{
if (!uses_only_table_name_fields(item_func->arguments()[i], table))
return 0;
}
}
else if (item->type() == Item::FIELD_ITEM)
{
Item_field *item_field= (Item_field*)item;
const CHARSET_INFO * const cs= system_charset_info;
InfoSchemaTable *schema_table= table->schema_table;
const char *field_name1= schema_table->getFirstColumnIndex() >= 0 ?
schema_table->getColumnName(schema_table->getFirstColumnIndex()).c_str() : "";
const char *field_name2= schema_table->getSecondColumnIndex() >= 0 ?
schema_table->getColumnName(schema_table->getSecondColumnIndex()).c_str() : "";
if (table->table != item_field->field->table ||
(cs->coll->strnncollsp(cs, (unsigned char *) field_name1, strlen(field_name1),
(unsigned char *) item_field->field_name,
strlen(item_field->field_name), 0) &&
cs->coll->strnncollsp(cs, (unsigned char *) field_name2, strlen(field_name2),
(unsigned char *) item_field->field_name,
strlen(item_field->field_name), 0)))
return 0;
}
else if (item->type() == Item::REF_ITEM)
return uses_only_table_name_fields(item->real_item(), table);
if (item->type() == Item::SUBSELECT_ITEM && !item->const_item())
return 0;
return 1;
}
static COND * make_cond_for_info_schema(COND *cond, TableList *table)
{
if (!cond)
return (COND*) 0;
if (cond->type() == Item::COND_ITEM)
{
if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
{
/* Create new top level AND item */
Item_cond_and *new_cond=new Item_cond_and;
if (!new_cond)
return (COND*) 0;
List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
Item *item;
while ((item=li++))
{
Item *fix= make_cond_for_info_schema(item, table);
if (fix)
new_cond->argument_list()->push_back(fix);
}
switch (new_cond->argument_list()->elements) {
case 0:
return (COND*) 0;
case 1:
return new_cond->argument_list()->head();
default:
new_cond->quick_fix_field();
return new_cond;
}
}
else
{ // Or list
Item_cond_or *new_cond=new Item_cond_or;
if (!new_cond)
return (COND*) 0;
List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
Item *item;
while ((item=li++))
{
Item *fix=make_cond_for_info_schema(item, table);
if (!fix)
return (COND*) 0;
new_cond->argument_list()->push_back(fix);
}
new_cond->quick_fix_field();
new_cond->top_level_item();
return new_cond;
}
}
if (!uses_only_table_name_fields(cond, table))
return (COND*) 0;
return cond;
}
/**
@brief Calculate lookup values(database name, table name)
@details This function calculates lookup values(database name, table name)
from 'WHERE' condition or wild values (for 'SHOW' commands only)
from LEX struct and fill lookup_field_vals struct field
with these values.
@param[in] session thread handler
@param[in] cond WHERE condition
@param[in] tables I_S table
@param[in, out] lookup_field_values Struct which holds lookup values
@return
0 success
1 error, there can be no matching records for the condition
*/
bool get_lookup_field_values(Session *session, COND *cond, TableList *tables,
LOOKUP_FIELD_VALUES *lookup_field_values)
{
LEX *lex= session->lex;
const char *wild= lex->wild ? lex->wild->ptr() : NULL;
memset(lookup_field_values, 0, sizeof(LOOKUP_FIELD_VALUES));
switch (lex->sql_command) {
case SQLCOM_SHOW_DATABASES:
if (wild)
{
lookup_field_values->db_value.str= (char*) wild;
lookup_field_values->db_value.length= strlen(wild);
lookup_field_values->wild_db_value= 1;
}
return 0;
case SQLCOM_SHOW_TABLES:
case SQLCOM_SHOW_TABLE_STATUS:
lookup_field_values->db_value.str= lex->select_lex.db;
lookup_field_values->db_value.length=strlen(lex->select_lex.db);
if (wild)
{
lookup_field_values->table_value.str= (char*)wild;
lookup_field_values->table_value.length= strlen(wild);
lookup_field_values->wild_table_value= 1;
}
return 0;
default:
/*
The "default" is for queries over I_S.
All previous cases handle SHOW commands.
*/
return calc_lookup_values_from_cond(session, cond, tables, lookup_field_values);
}
}
/**
* Function used for sorting with std::sort within make_db_list.
*
* @returns true if a < b, false otherwise
*/
static bool lex_string_sort(const LEX_STRING *a, const LEX_STRING *b)
{
return (strcmp(a->str, b->str) < 0);
}
/**
* @brief
* Create db names list. Information schema name always is first in list
*
* @param[in] session Thread handler
* @param[out] files List of db names
* @param[in] wild Wild string
* @param[in] idx_field_vals idx_field_vals->db_name contains db name or
* wild string
* @param[out] with_i_schema Returns 1 if we added 'IS' name to list
* otherwise returns 0
*
* @retval 0 Success
* @retval 1 Error
*/
int make_db_list(Session *session, vector<LEX_STRING*> &files,
LOOKUP_FIELD_VALUES *lookup_field_vals,
bool *with_i_schema)
{
LEX_STRING *i_s_name_copy= 0;
i_s_name_copy= session->make_lex_string(i_s_name_copy,
INFORMATION_SCHEMA_NAME.c_str(),
INFORMATION_SCHEMA_NAME.length(), true);
*with_i_schema= 0;
if (lookup_field_vals->wild_db_value)
{
/*
This part of code is only for SHOW DATABASES command.
idx_field_vals->db_value can be 0 when we don't use
LIKE clause (see also get_index_field_values() function)
*/
if (!lookup_field_vals->db_value.str ||
!wild_case_compare(system_charset_info,
INFORMATION_SCHEMA_NAME.c_str(),
lookup_field_vals->db_value.str))
{
*with_i_schema= 1;
files.push_back(i_s_name_copy);
}
if (find_schemas(session, files, drizzle_data_home,
lookup_field_vals->db_value.str) == true)
{
return 1;
}
sort(files.begin()+1, files.end(), lex_string_sort);
return 0;
}
/*
If we have db lookup vaule we just add it to list and
exit from the function
*/
if (lookup_field_vals->db_value.str)
{
if (!my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.c_str(),
lookup_field_vals->db_value.str))
{
*with_i_schema= 1;
files.push_back(i_s_name_copy);
return 0;
}
files.push_back(&lookup_field_vals->db_value);
return 0;
}
/*
Create list of existing databases. It is used in case
of select from information schema table
*/
files.push_back(i_s_name_copy);
*with_i_schema= 1;
if (find_schemas(session, files, drizzle_data_home, NULL) == true)
{
return 1;
}
sort(files.begin()+1, files.end(), lex_string_sort);
return 0;
}
class AddSchemaTable : public unary_function<InfoSchemaTable *, bool>
{
Session *session;
const char *wild;
vector<LEX_STRING*> &files;
public:
AddSchemaTable(Session *session_arg, vector<LEX_STRING*> &files_arg, const char *wild_arg)
: session(session_arg), wild(wild_arg), files(files_arg)
{}
result_type operator() (argument_type schema_table)
{
if (schema_table->isHidden())
{
return false;
}
const string &schema_table_name= schema_table->getTableName();
if (wild && wild_case_compare(files_charset_info, schema_table_name.c_str(), wild))
{
return false;
}
LEX_STRING *file_name= 0;
file_name= session->make_lex_string(file_name, schema_table_name.c_str(),
schema_table_name.length(), true);
if (file_name == NULL)
{
return true;
}
files.push_back(file_name);
return false;
}
};
static int schema_tables_add(Session *session, vector<LEX_STRING*> &files, const char *wild)
{
vector<InfoSchemaTable *>::iterator iter= find_if(all_schema_tables.begin(),
all_schema_tables.end(),
AddSchemaTable(session, files, wild));
if (iter != all_schema_tables.end())
{
return 1;
}
return 0;
}
/**
@brief Create table names list
@details The function creates the list of table names in
database
@param[in] session thread handler
@param[in] table_names List of table names in database
@param[in] lex pointer to LEX struct
@param[in] lookup_field_vals pointer to LOOKUP_FIELD_VALUE struct
@param[in] with_i_schema true means that we add I_S tables to list
@param[in] db_name database name
@return Operation status
@retval 0 ok
@retval 1 fatal error
@retval 2 Not fatal error; Safe to ignore this file list
*/
static int
make_table_name_list(Session *session, vector<LEX_STRING*> &table_names, LEX *lex,
LOOKUP_FIELD_VALUES *lookup_field_vals,
bool with_i_schema, LEX_STRING *db_name)
{
char path[FN_REFLEN];
build_table_filename(path, sizeof(path), db_name->str, "", false);
if (!lookup_field_vals->wild_table_value &&
lookup_field_vals->table_value.str)
{
if (with_i_schema)
{
if (find_schema_table(lookup_field_vals->table_value.str))
{
table_names.push_back(&lookup_field_vals->table_value);
}
}
else
{
table_names.push_back(&lookup_field_vals->table_value);
}
return 0;
}
/*
This call will add all matching the wildcards (if specified) IS tables
to the list
*/
if (with_i_schema)
return (schema_tables_add(session, table_names,
lookup_field_vals->table_value.str));
string db(db_name->str);
TableNameIterator tniter(db);
int err= 0;
string table_name;
do {
err= tniter.next(&table_name);
if (err == 0)
{
LEX_STRING *file_name= NULL;
file_name= session->make_lex_string(file_name, table_name.c_str(),
table_name.length(), true);
const char* wild= lookup_field_vals->table_value.str;
if (wild && wild_compare(table_name.c_str(), wild, 0))
continue;
table_names.push_back(file_name);
}
} while (err == 0);
if (err > 0)
{
/* who knows what this error condition really does...
anyway, we're keeping behaviour from days of yore */
if (lex->sql_command != SQLCOM_SELECT)
return 1;
session->clear_error();
return 2;
}
return 0;
}
/**
@brief Fill I_S table for SHOW COLUMNS|INDEX commands
@param[in] session thread handler
@param[in] tables TableList for I_S table
@param[in] schema_table pointer to I_S structure
@param[in] open_tables_state_backup pointer to Open_tables_state object
which is used to save|restore original
status of variables related to
open tables state
@return Operation status
@retval 0 success
@retval 1 error
*/
static int
fill_schema_show_cols_or_idxs(Session *session, TableList *tables,
InfoSchemaTable *schema_table,
Open_tables_state *open_tables_state_backup)
{
LEX *lex= session->lex;
bool res;
LEX_STRING tmp_lex_string, tmp_lex_string1, *db_name, *table_name;
enum_sql_command save_sql_command= lex->sql_command;
TableList *show_table_list= (TableList*) tables->schema_select_lex->
table_list.first;
Table *table= tables->table;
int error= 1;
lex->all_selects_list= tables->schema_select_lex;
/*
Restore session->temporary_tables to be able to process
temporary tables(only for 'show index' & 'show columns').
This should be changed when processing of temporary tables for
I_S tables will be done.
*/
session->temporary_tables= open_tables_state_backup->temporary_tables;
/*
Let us set fake sql_command so views won't try to merge
themselves into main statement. If we don't do this,
SELECT * from information_schema.xxxx will cause problems.
SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()'
*/
lex->sql_command= SQLCOM_SHOW_FIELDS;
res= session->openTables(show_table_list, DRIZZLE_LOCK_IGNORE_FLUSH);
lex->sql_command= save_sql_command;
/*
get_all_tables() returns 1 on failure and 0 on success thus
return only these and not the result code of ::process_table()
We should use show_table_list->alias instead of
show_table_list->table_name because table_name
could be changed during opening of I_S tables. It's safe
to use alias because alias contains original table name
in this case(this part of code is used only for
'show columns' & 'show statistics' commands).
*/
table_name= session->make_lex_string(&tmp_lex_string1, show_table_list->alias,
strlen(show_table_list->alias), false);
db_name= session->make_lex_string(&tmp_lex_string, show_table_list->db,
show_table_list->db_length, false);
table->setWriteSet();
error= test(schema_table->processTable(session, show_table_list,
table, res, db_name,
table_name));
session->temporary_tables= 0;
session->close_tables_for_reopen(&show_table_list);
return(error);
}
/**
@brief Fill I_S table for SHOW Table NAMES commands
@param[in] session thread handler
@param[in] table Table struct for I_S table
@param[in] db_name database name
@param[in] table_name table name
@param[in] with_i_schema I_S table if true
@return Operation status
@retval 0 success
@retval 1 error
*/
static int fill_schema_table_names(Session *session, Table *table,
LEX_STRING *db_name, LEX_STRING *table_name,
bool with_i_schema)
{
if (with_i_schema)
{
table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"),
system_charset_info);
}
else
{
char path[FN_REFLEN];
(void) build_table_filename(path, sizeof(path), db_name->str,
table_name->str, false);
table->field[3]->store(STRING_WITH_LEN("BASE Table"),
system_charset_info);
if (session->is_error() && session->main_da.sql_errno() == ER_NO_SUCH_TABLE)
{
session->clear_error();
return 0;
}
}
if (schema_table_store_record(session, table))
return 1;
return 0;
}
/**
@brief Get open table method
@details The function calculates the method which will be used
for table opening:
SKIP_OPEN_TABLE - do not open table
OPEN_FRM_ONLY - open FRM file only
OPEN_FULL_TABLE - open FRM, data, index files
@param[in] tables I_S table table_list
@param[in] schema_table I_S table struct
@return return a set of flags
@retval SKIP_OPEN_TABLE | OPEN_FRM_ONLY | OPEN_FULL_TABLE
*/
static uint32_t get_table_open_method(TableList *tables,
InfoSchemaTable *schema_table)
{
/*
determine which method will be used for table opening
*/
if (schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
{
Field **ptr, *field;
int table_open_method= 0, field_indx= 0;
for (ptr= tables->table->field; (field= *ptr) ; ptr++)
{
if (field->isReadSet())
table_open_method|= schema_table->getColumnOpenMethod(field_indx);
field_indx++;
}
return table_open_method;
}
/* I_S tables which use get_all_tables but can not be optimized */
return (uint32_t) OPEN_FULL_TABLE;
}
/**
@brief Fill I_S table with data from FRM file only
@param[in] session thread handler
@param[in] table Table struct for I_S table
@param[in] schema_table I_S table struct
@param[in] db_name database name
@param[in] table_name table name
@return Operation status
@retval 0 Table is processed and we can continue
with new table
@retval 1 It's view and we have to use
open_tables function for this table
*/
static int fill_schema_table_from_frm(Session *session,TableList *tables,
InfoSchemaTable *schema_table,
LEX_STRING *db_name,
LEX_STRING *table_name)
{
Table *table= tables->table;
TableShare *share;
Table tbl;
TableList table_list;
uint32_t res= 0;
int error;
char key[MAX_DBKEY_LENGTH];
uint32_t key_length;
memset(&tbl, 0, sizeof(Table));
table_list.table_name= table_name->str;
table_list.db= db_name->str;
key_length= table_list.create_table_def_key(key);
pthread_mutex_lock(&LOCK_open); /* Locking to get table share when filling schema table from FRM */
share= TableShare::getShare(session, &table_list, key, key_length, 0, &error);
if (!share)
{
res= 0;
goto err;
}
{
tbl.s= share;
table_list.table= &tbl;
res= schema_table->processTable(session, &table_list, table,
res, db_name, table_name);
}
/* For the moment we just set everything to read */
table->setReadSet();
TableShare::release(share);
err:
pthread_mutex_unlock(&LOCK_open);
session->clear_error();
return res;
}
/**
@brief Fill I_S tables whose data are retrieved
from frm files and storage engine
@details The information schema tables are internally represented as
temporary tables that are filled at query execution time.
Those I_S tables whose data are retrieved
from frm files and storage engine are filled by the function
InfoSchemaMethods::fillTable().
@param[in] session thread handler
@param[in] tables I_S table
@param[in] cond 'WHERE' condition
@return Operation status
@retval 0 success
@retval 1 error
*/
int InfoSchemaMethods::fillTable(Session *session, TableList *tables, COND *cond)
{
LEX *lex= session->lex;
Table *table= tables->table;
Select_Lex *old_all_select_lex= lex->all_selects_list;
enum_sql_command save_sql_command= lex->sql_command;
Select_Lex *lsel= tables->schema_select_lex;
InfoSchemaTable *schema_table= tables->schema_table;
Select_Lex sel;
LOOKUP_FIELD_VALUES lookup_field_vals;
bool with_i_schema;
vector<LEX_STRING*> db_names, table_names;
COND *partial_cond= 0;
uint32_t derived_tables= lex->derived_tables;
int error= 1;
Open_tables_state open_tables_state_backup;
Query_tables_list query_tables_list_backup;
uint32_t table_open_method;
bool old_value= session->no_warnings_for_error;
/*
We should not introduce deadlocks even if we already have some
tables open and locked, since we won't lock tables which we will
open and will ignore possible name-locks for these tables.
*/
session->reset_n_backup_open_tables_state(&open_tables_state_backup);
tables->table_open_method= table_open_method=
get_table_open_method(tables, schema_table);
/*
this branch processes SHOW FIELDS, SHOW INDEXES commands.
see sql_parse.cc, prepare_schema_table() function where
this values are initialized
*/
if (lsel && lsel->table_list.first)
{
error= fill_schema_show_cols_or_idxs(session, tables, schema_table,
&open_tables_state_backup);
goto err;
}
if (get_lookup_field_values(session, cond, tables, &lookup_field_vals))
{
error= 0;
goto err;
}
if (!lookup_field_vals.wild_db_value && !lookup_field_vals.wild_table_value)
{
/*
if lookup value is empty string then
it's impossible table name or db name
*/
if ((lookup_field_vals.db_value.str && !lookup_field_vals.db_value.str[0]) ||
(lookup_field_vals.table_value.str && !lookup_field_vals.table_value.str[0]))
{
error= 0;
goto err;
}
}
if (lookup_field_vals.db_value.length &&
!lookup_field_vals.wild_db_value)
tables->has_db_lookup_value= true;
if (lookup_field_vals.table_value.length &&
!lookup_field_vals.wild_table_value)
tables->has_table_lookup_value= true;
if (tables->has_db_lookup_value && tables->has_table_lookup_value)
partial_cond= 0;
else
partial_cond= make_cond_for_info_schema(cond, tables);
if (lex->describe)
{
/* EXPLAIN SELECT */
error= 0;
goto err;
}
table->setWriteSet();
if (make_db_list(session, db_names, &lookup_field_vals, &with_i_schema))
goto err;
for (vector<LEX_STRING*>::iterator db_name= db_names.begin(); db_name != db_names.end(); ++db_name )
{
session->no_warnings_for_error= 1;
table_names.clear();
int res= make_table_name_list(session, table_names, lex,
&lookup_field_vals,
with_i_schema, *db_name);
if (res == 2) /* Not fatal error, continue */
continue;
if (res)
goto err;
for (vector<LEX_STRING*>::iterator table_name= table_names.begin(); table_name != table_names.end(); ++table_name)
{
table->restoreRecordAsDefault();
table->field[schema_table->getFirstColumnIndex()]->
store((*db_name)->str, (*db_name)->length, system_charset_info);
table->field[schema_table->getSecondColumnIndex()]->
store((*table_name)->str, (*table_name)->length, system_charset_info);
if (!partial_cond || partial_cond->val_int())
{
/*
If table is I_S.tables and open_table_method is 0 (eg SKIP_OPEN)
we can skip table opening and we don't have lookup value for
table name or lookup value is wild string(table name list is
already created by make_table_name_list() function).
*/
if (! table_open_method &&
schema_table->getTableName().compare("TABLES") == 0 &&
(! lookup_field_vals.table_value.length ||
lookup_field_vals.wild_table_value))
{
if (schema_table_store_record(session, table))
goto err; /* Out of space in temporary table */
continue;
}
/* SHOW Table NAMES command */
if (schema_table->getTableName().compare("TABLE_NAMES") == 0)
{
if (fill_schema_table_names(session, tables->table, *db_name,
*table_name, with_i_schema))
continue;
}
else
{
if (!(table_open_method & ~OPEN_FRM_ONLY) &&
!with_i_schema)
{
if (!fill_schema_table_from_frm(session, tables, schema_table, *db_name,
*table_name))
continue;
}
LEX_STRING tmp_lex_string, orig_db_name;
/*
Set the parent lex of 'sel' because it is needed by
sel.init_query() which is called inside make_table_list.
*/
session->no_warnings_for_error= 1;
sel.parent_lex= lex;
/* db_name can be changed in make_table_list() func */
if (!session->make_lex_string(&orig_db_name, (*db_name)->str,
(*db_name)->length, false))
goto err;
if (make_table_list(session, &sel, *db_name, *table_name))
goto err;
TableList *show_table_list= (TableList*) sel.table_list.first;
lex->all_selects_list= &sel;
lex->derived_tables= 0;
lex->sql_command= SQLCOM_SHOW_FIELDS;
show_table_list->i_s_requested_object=
schema_table->getRequestedObject();
res= session->openTables(show_table_list, DRIZZLE_LOCK_IGNORE_FLUSH);
lex->sql_command= save_sql_command;
/*
XXX-> show_table_list has a flag i_is_requested,
and when it's set, openTables()
can return an error without setting an error message
in Session, which is a hack. This is why we have to
check for res, then for session->is_error() only then
for session->main_da.sql_errno().
*/
if (res && session->is_error() &&
session->main_da.sql_errno() == ER_NO_SUCH_TABLE)
{
/*
Hide error for not existing table.
This error can occur for example when we use
where condition with db name and table name and this
table does not exist.
*/
res= 0;
session->clear_error();
}
else
{
/*
We should use show_table_list->alias instead of
show_table_list->table_name because table_name
could be changed during opening of I_S tables. It's safe
to use alias because alias contains original table name
in this case.
*/
session->make_lex_string(&tmp_lex_string, show_table_list->alias,
strlen(show_table_list->alias), false);
res= schema_table->processTable(session, show_table_list, table,
res, &orig_db_name,
&tmp_lex_string);
session->close_tables_for_reopen(&show_table_list);
}
assert(!lex->query_tables_own_last);
if (res)
goto err;
}
}
}
/*
If we have information schema its always the first table and only
the first table. Reset for other tables.
*/
with_i_schema= 0;
}
error= 0;
err:
session->restore_backup_open_tables_state(&open_tables_state_backup);
lex->derived_tables= derived_tables;
lex->all_selects_list= old_all_select_lex;
lex->sql_command= save_sql_command;
session->no_warnings_for_error= old_value;
return(error);
}
/**
@brief Store field characteristics into appropriate I_S table columns
@param[in] table I_S table
@param[in] field processed field
@param[in] cs I_S table charset
@param[in] offset offset from beginning of table
to DATE_TYPE column in I_S table
@return void
*/
static void store_column_type(Table *table, Field *field,
const CHARSET_INFO * const cs,
uint32_t offset)
{
bool is_blob;
int decimals, field_length;
const char *tmp_buff;
char column_type_buff[MAX_FIELD_WIDTH];
String column_type(column_type_buff, sizeof(column_type_buff), cs);
field->sql_type(column_type);
/* DTD_IDENTIFIER column */
table->field[offset + 7]->store(column_type.ptr(), column_type.length(), cs);
table->field[offset + 7]->set_notnull();
tmp_buff= strchr(column_type.ptr(), '(');
/* DATA_TYPE column */
table->field[offset]->store(column_type.ptr(),
(tmp_buff ? tmp_buff - column_type.ptr() :
column_type.length()), cs);
is_blob= (field->type() == DRIZZLE_TYPE_BLOB);
if (field->has_charset() || is_blob ||
field->real_type() == DRIZZLE_TYPE_VARCHAR) // For varbinary type
{
uint32_t octet_max_length= field->max_display_length();
if (is_blob && octet_max_length != (uint32_t) 4294967295U)
octet_max_length /= field->charset()->mbmaxlen;
int64_t char_max_len= is_blob ?
(int64_t) octet_max_length / field->charset()->mbminlen :
(int64_t) octet_max_length / field->charset()->mbmaxlen;
/* CHARACTER_MAXIMUM_LENGTH column*/
table->field[offset + 1]->store(char_max_len, true);
table->field[offset + 1]->set_notnull();
/* CHARACTER_OCTET_LENGTH column */
table->field[offset + 2]->store((int64_t) octet_max_length, true);
table->field[offset + 2]->set_notnull();
}
/*
Calculate field_length and decimals.
They are set to -1 if they should not be set (we should return NULL)
*/
decimals= field->decimals();
switch (field->type()) {
case DRIZZLE_TYPE_NEWDECIMAL:
field_length= ((Field_new_decimal*) field)->precision;
break;
case DRIZZLE_TYPE_LONG:
case DRIZZLE_TYPE_LONGLONG:
field_length= field->max_display_length() - 1;
break;
case DRIZZLE_TYPE_DOUBLE:
field_length= field->field_length;
if (decimals == NOT_FIXED_DEC)
decimals= -1; // return NULL
break;
default:
field_length= decimals= -1;
break;
}
/* NUMERIC_PRECISION column */
if (field_length >= 0)
{
table->field[offset + 3]->store((int64_t) field_length, true);
table->field[offset + 3]->set_notnull();
}
/* NUMERIC_SCALE column */
if (decimals >= 0)
{
table->field[offset + 4]->store((int64_t) decimals, true);
table->field[offset + 4]->set_notnull();
}
if (field->has_charset())
{
/* CHARACTER_SET_NAME column*/
tmp_buff= field->charset()->csname;
table->field[offset + 5]->store(tmp_buff, strlen(tmp_buff), cs);
table->field[offset + 5]->set_notnull();
/* COLLATION_NAME column */
tmp_buff= field->charset()->name;
table->field[offset + 6]->store(tmp_buff, strlen(tmp_buff), cs);
table->field[offset + 6]->set_notnull();
}
}
int InfoSchemaMethods::processTable(Session *session, TableList *tables,
Table *table, bool res,
LEX_STRING *db_name,
LEX_STRING *table_name) const
{
LEX *lex= session->lex;
const char *wild= lex->wild ? lex->wild->ptr() : NULL;
const CHARSET_INFO * const cs= system_charset_info;
Table *show_table;
TableShare *show_table_share;
Field **ptr, *field, *timestamp_field;
int count;
if (res)
{
if (lex->sql_command != SQLCOM_SHOW_FIELDS)
{
/*
I.e. we are in SELECT FROM INFORMATION_SCHEMA.COLUMS
rather than in SHOW COLUMNS
*/
if (session->is_error())
push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
session->main_da.sql_errno(), session->main_da.message());
session->clear_error();
res= 0;
}
return(res);
}
show_table= tables->table;
show_table_share= show_table->s;
count= 0;
if (tables->schema_table)
{
ptr= show_table->field;
timestamp_field= show_table->timestamp_field;
}
else
{
ptr= show_table_share->field;
timestamp_field= show_table_share->timestamp_field;
}
/* For the moment we just set everything to read */
if (!show_table->read_set)
{
bitmap_set_all(&show_table->def_read_set);
show_table->read_set= &show_table->def_read_set;
}
show_table->use_all_columns(); // Required for default
for (; (field= *ptr) ; ptr++)
{
unsigned char *pos;
char tmp[MAX_FIELD_WIDTH];
String type(tmp,sizeof(tmp), system_charset_info);
char *end;
/* to satisfy 'field->val_str' ASSERTs */
field->table= show_table;
show_table->in_use= session;
if (wild && wild[0] &&
wild_case_compare(system_charset_info, field->field_name,wild))
continue;
count++;
/* Get default row, with all NULL fields set to NULL */
table->restoreRecordAsDefault();
table->field[1]->store(db_name->str, db_name->length, cs);
table->field[2]->store(table_name->str, table_name->length, cs);
table->field[3]->store(field->field_name, strlen(field->field_name),
cs);
table->field[4]->store((int64_t) count, true);
if (get_field_default_value(timestamp_field, field, &type, 0))
{
table->field[5]->store(type.ptr(), type.length(), cs);
table->field[5]->set_notnull();
}
pos=(unsigned char*) ((field->flags & NOT_NULL_FLAG) ? "NO" : "YES");
table->field[6]->store((const char*) pos,
strlen((const char*) pos), cs);
store_column_type(table, field, cs, 7);
pos=(unsigned char*) ((field->flags & PRI_KEY_FLAG) ? "PRI" :
(field->flags & UNIQUE_KEY_FLAG) ? "UNI" :
(field->flags & MULTIPLE_KEY_FLAG) ? "MUL":"");
table->field[15]->store((const char*) pos,
strlen((const char*) pos), cs);
end= tmp;
if (field->unireg_check == Field::NEXT_NUMBER)
table->field[16]->store(STRING_WITH_LEN("auto_increment"), cs);
if (timestamp_field == field &&
field->unireg_check != Field::TIMESTAMP_DN_FIELD)
table->field[16]->store(STRING_WITH_LEN("on update CURRENT_TIMESTAMP"),
cs);
table->field[18]->store(field->comment.str, field->comment.length, cs);
{
enum column_format_type column_format= (enum column_format_type)
((field->flags >> COLUMN_FORMAT_FLAGS) & COLUMN_FORMAT_MASK);
pos=(unsigned char*)"Default";
table->field[19]->store((const char*) pos,
strlen((const char*) pos), cs);
pos=(unsigned char*)(column_format == COLUMN_FORMAT_TYPE_DEFAULT ? "Default" :
column_format == COLUMN_FORMAT_TYPE_FIXED ? "Fixed" :
"Dynamic");
table->field[20]->store((const char*) pos,
strlen((const char*) pos), cs);
}
if (schema_table_store_record(session, table))
return(1);
}
return(0);
}
class FindSchemaTableByName : public unary_function<InfoSchemaTable *, bool>
{
const char *table_name;
public:
FindSchemaTableByName(const char *table_name_arg)
: table_name(table_name_arg) {}
result_type operator() (argument_type schema_table)
{
return ! my_strcasecmp(system_charset_info,
schema_table->getTableName().c_str(),
table_name);
}
};
/*
Find schema_tables elment by name
SYNOPSIS
find_schema_table()
table_name table name
RETURN
0 table not found
# pointer to 'schema_tables' element
*/
InfoSchemaTable *find_schema_table(const char* table_name)
{
vector<InfoSchemaTable *>::iterator iter=
find_if(all_schema_tables.begin(), all_schema_tables.end(),
FindSchemaTableByName(table_name));
if (iter != all_schema_tables.end())
{
return *iter;
}
return NULL;
}
Table *InfoSchemaMethods::createSchemaTable(Session *session, TableList *table_list)
const
{
int field_count= 0;
Item *item;
Table *table;
List<Item> field_list;
const CHARSET_INFO * const cs= system_charset_info;
const InfoSchemaTable::Columns &columns= table_list->schema_table->getColumns();
InfoSchemaTable::Columns::const_iterator iter= columns.begin();
while (iter != columns.end())
{
const ColumnInfo *column= *iter;
switch (column->getType()) {
case DRIZZLE_TYPE_LONG:
case DRIZZLE_TYPE_LONGLONG:
if (!(item= new Item_return_int(column->getName().c_str(),
column->getLength(),
column->getType(),
column->getValue())))
{
return(0);
}
item->unsigned_flag= (column->getFlags() & MY_I_S_UNSIGNED);
break;
case DRIZZLE_TYPE_DATE:
case DRIZZLE_TYPE_TIMESTAMP:
case DRIZZLE_TYPE_DATETIME:
if (!(item=new Item_return_date_time(column->getName().c_str(),
column->getType())))
{
return(0);
}
break;
case DRIZZLE_TYPE_DOUBLE:
if ((item= new Item_float(column->getName().c_str(), 0.0, NOT_FIXED_DEC,
column->getLength())) == NULL)
return NULL;
break;
case DRIZZLE_TYPE_NEWDECIMAL:
if (!(item= new Item_decimal((int64_t) column->getValue(), false)))
{
return(0);
}
item->unsigned_flag= (column->getFlags() & MY_I_S_UNSIGNED);
item->decimals= column->getLength() % 10;
item->max_length= (column->getLength()/100)%100;
if (item->unsigned_flag == 0)
item->max_length+= 1;
if (item->decimals > 0)
item->max_length+= 1;
item->set_name(column->getName().c_str(),
column->getName().length(), cs);
break;
case DRIZZLE_TYPE_BLOB:
if (!(item= new Item_blob(column->getName().c_str(),
column->getLength())))
{
return(0);
}
break;
default:
if (!(item= new Item_empty_string("", column->getLength(), cs)))
{
return(0);
}
item->set_name(column->getName().c_str(),
column->getName().length(), cs);
break;
}
field_list.push_back(item);
item->maybe_null= (column->getFlags() & MY_I_S_MAYBE_NULL);
field_count++;
++iter;
}
Tmp_Table_Param *tmp_table_param =
(Tmp_Table_Param*) (session->alloc(sizeof(Tmp_Table_Param)));
tmp_table_param->init();
tmp_table_param->table_charset= cs;
tmp_table_param->field_count= field_count;
tmp_table_param->schema_table= 1;
Select_Lex *select_lex= session->lex->current_select;
if (!(table= create_tmp_table(session, tmp_table_param,
field_list, (order_st*) 0, 0, 0,
(select_lex->options | session->options |
TMP_TABLE_ALL_COLUMNS),
HA_POS_ERROR, table_list->alias)))
return(0);
my_bitmap_map* bitmaps=
(my_bitmap_map*) session->alloc(bitmap_buffer_size(field_count));
bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count);
table->read_set= &table->def_read_set;
bitmap_clear_all(table->read_set);
table_list->schema_table_param= tmp_table_param;
return(table);
}
/*
For old SHOW compatibility. It is used when
old SHOW doesn't have generated column names
Make list of fields for SHOW
SYNOPSIS
InfoSchemaMethods::oldFormat()
session thread handler
schema_table pointer to 'schema_tables' element
RETURN
1 error
0 success
*/
int InfoSchemaMethods::oldFormat(Session *session, InfoSchemaTable *schema_table)
const
{
Name_resolution_context *context= &session->lex->select_lex.context;
const InfoSchemaTable::Columns columns= schema_table->getColumns();
InfoSchemaTable::Columns::const_iterator iter= columns.begin();
while (iter != columns.end())
{
const ColumnInfo *column= *iter;
if (column->getOldName().length() != 0)
{
Item_field *field= new Item_field(context,
NULL, NULL,
column->getName().c_str());
if (field)
{
field->set_name(column->getOldName().c_str(),
column->getOldName().length(),
system_charset_info);
if (session->add_item_to_list(field))
return 1;
}
}
++iter;
}
return 0;
}
/*
Create information_schema table
SYNOPSIS
mysql_schema_table()
session thread handler
lex pointer to LEX
table_list pointer to table_list
RETURN
true on error
*/
bool mysql_schema_table(Session *session, LEX *, TableList *table_list)
{
Table *table;
if (!(table= table_list->schema_table->createSchemaTable(session, table_list)))
return true;
table->s->tmp_table= SYSTEM_TMP_TABLE;
/*
This test is necessary to make
case insensitive file systems +
upper case table names(information schema tables) +
views
working correctly
*/
if (table_list->schema_table_name)
table->alias_name_used= my_strcasecmp(table_alias_charset,
table_list->schema_table_name,
table_list->alias);
table_list->table_name= table->s->table_name.str;
table_list->table_name_length= table->s->table_name.length;
table_list->table= table;
table->next= session->derived_tables;
session->derived_tables= table;
table_list->select_lex->options |= OPTION_SCHEMA_TABLE;
return false;
}
/*
Generate select from information_schema table
SYNOPSIS
make_schema_select()
session thread handler
sel pointer to Select_Lex
schema_table_name name of 'schema_tables' element
RETURN
true on error
*/
bool make_schema_select(Session *session, Select_Lex *sel,
const string& schema_table_name)
{
InfoSchemaTable *schema_table= find_schema_table(schema_table_name.c_str());
LEX_STRING db, table;
/*
We have to make non const db_name & table_name
because of lower_case_table_names
*/
session->make_lex_string(&db, INFORMATION_SCHEMA_NAME.c_str(),
INFORMATION_SCHEMA_NAME.length(), 0);
session->make_lex_string(&table, schema_table->getTableName().c_str(),
schema_table->getTableName().length(), 0);
if (schema_table->oldFormat(session, schema_table) || /* Handle old syntax */
!sel->add_table_to_list(session, new Table_ident(session, db, table, 0),
0, 0, TL_READ))
{
return true;
}
return false;
}
/*
Fill temporary schema tables before SELECT
SYNOPSIS
get_schema_tables_result()
join join which use schema tables
executed_place place where I_S table processed
RETURN
false success
true error
*/
bool get_schema_tables_result(JOIN *join,
enum enum_schema_table_state executed_place)
{
JoinTable *tmp_join_tab= join->join_tab+join->tables;
Session *session= join->session;
LEX *lex= session->lex;
bool result= 0;
session->no_warnings_for_error= 1;
for (JoinTable *tab= join->join_tab; tab < tmp_join_tab; tab++)
{
if (!tab->table || !tab->table->pos_in_table_list)
break;
TableList *table_list= tab->table->pos_in_table_list;
if (table_list->schema_table)
{
bool is_subselect= (&lex->unit != lex->current_select->master_unit() &&
lex->current_select->master_unit()->item);
/* skip I_S optimizations specific to get_all_tables */
if (session->lex->describe &&
(table_list->schema_table->isOptimizationPossible() != true))
{
continue;
}
/*
If schema table is already processed and
the statement is not a subselect then
we don't need to fill this table again.
If schema table is already processed and
schema_table_state != executed_place then
table is already processed and
we should skip second data processing.
*/
if (table_list->schema_table_state &&
(!is_subselect || table_list->schema_table_state != executed_place))
continue;
/*
if table is used in a subselect and
table has been processed earlier with the same
'executed_place' value then we should refresh the table.
*/
if (table_list->schema_table_state && is_subselect)
{
table_list->table->file->extra(HA_EXTRA_NO_CACHE);
table_list->table->file->extra(HA_EXTRA_RESET_STATE);
table_list->table->file->ha_delete_all_rows();
table_list->table->free_io_cache();
table_list->table->filesort_free_buffers(true);
table_list->table->null_row= 0;
}
else
table_list->table->file->stats.records= 0;
if (table_list->schema_table->fillTable(session, table_list,
tab->select_cond))
{
result= 1;
join->error= 1;
tab->read_record.file= table_list->table->file;
table_list->schema_table_state= executed_place;
break;
}
tab->read_record.file= table_list->table->file;
table_list->schema_table_state= executed_place;
}
}
session->no_warnings_for_error= 0;
return(result);
}
|