File: mysql_connection.cpp

package info (click to toggle)
mysql-connector-c%2B%2B 1.1.12-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 4,904 kB
  • sloc: cpp: 44,895; ansic: 2,114; php: 528; sql: 403; xml: 109; sh: 33; makefile: 11
file content (1686 lines) | stat: -rw-r--r-- 55,316 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2.0, as
 * published by the Free Software Foundation.
 *
 * This program is also distributed with certain software (including
 * but not limited to OpenSSL) that is licensed under separate terms,
 * as designated in a particular file or component or in included license
 * documentation.  The authors of MySQL hereby grant you an
 * additional permission to link the program and your derivative works
 * with the separately licensed software that they have included with
 * MySQL.
 *
 * Without limiting anything contained in the foregoing, this file,
 * which is part of MySQL Connector/C++, is also subject to the
 * Universal FOSS Exception, version 1.0, a copy of which can be found at
 * http://oss.oracle.com/licenses/universal-foss-exception.
 *
 * 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, version 2.0, 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
 */



#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <stdlib.h>
#include <memory>
#include <sstream>
#include <stdio.h>
#include <map>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <mysqld_error.h>
#include <cppconn/exception.h>

#include "nativeapi/native_connection_wrapper.h"
#include "nativeapi/native_statement_wrapper.h"

#include "mysql_connection_options.h"
#include "mysql_util.h"
#include "mysql_uri.h"
#include "mysql_error.h"
#include "cppconn/version_info.h"

/*
 * _WIN32 is defined by 64bit compiler too
 * (see http://msdn.microsoft.com/en-us/library/aa489554.aspx)
 * So no need to check for _WIN64 too
 */
#ifdef _WIN32
/* MySQL 5.1 might have defined it before in include/config-win.h */
#ifdef strncasecmp
#undef strncasecmp
#endif

#define strncasecmp(s1,s2,n) _strnicmp(s1,s2,n)

#else
#include <string.h>
#endif

#include "mysql_connection.h"
#include "mysql_connection_data.h"
#include "mysql_prepared_statement.h"
#include "mysql_statement.h"
#include "mysql_metadata.h"
#include "mysql_resultset.h"
#include "mysql_warning.h"
#include "mysql_debug.h"

#ifndef ER_MUST_CHANGE_PASSWORD_LOGIN
# define ER_MUST_CHANGE_PASSWORD_LOGIN 1820
#endif

namespace sql
{
namespace mysql
{

/* {{{ MySQL_Savepoint::MySQL_Savepoint() -I- */
MySQL_Savepoint::MySQL_Savepoint(const sql::SQLString &savepoint):
  name(savepoint)
{
}
/* }}} */


/* {{{ MySQL_Savepoint::getSavepointId() -I- */
int
MySQL_Savepoint::getSavepointId()
{
  throw sql::InvalidArgumentException("Only named savepoints are supported.");
  return 0; // fool compilers
}
/* }}} */


/* {{{ MySQL_Savepoint::getSavepointName() -I- */
sql::SQLString
MySQL_Savepoint::getSavepointName()
{
  return name;
}
/* }}} */


/* {{{ MySQL_Connection::createServiceStmt() */
MySQL_Statement *
MySQL_Connection::createServiceStmt() {

  /* We need to have it storing results, not using */
  return new MySQL_Statement(this, proxy,
                 sql::ResultSet::TYPE_SCROLL_INSENSITIVE,
                 intern->logger);
}

/* {{{ MySQL_Connection::MySQL_Connection() -I- */
MySQL_Connection::MySQL_Connection(Driver * _driver,
                                   ::sql::mysql::NativeAPI::NativeConnectionWrapper& _proxy,
                                   const sql::SQLString& hostName,
                                   const sql::SQLString& userName,
                                   const sql::SQLString& password)
                                   :  driver (_driver),
                                      proxy  (&_proxy),
                                      intern (NULL)
{
  sql::ConnectOptionsMap connection_properties;
  connection_properties["hostName"] = hostName;
  connection_properties["userName"] = userName;
  connection_properties["password"] = password;

  boost::shared_ptr< MySQL_DebugLogger > tmp_logger(new MySQL_DebugLogger());
  intern.reset(new MySQL_ConnectionData(tmp_logger));

  service.reset(createServiceStmt());
  init(connection_properties);
}
/* }}} */


/* {{{ MySQL_Connection::MySQL_Connection() -I- */
MySQL_Connection::MySQL_Connection(Driver * _driver,
                   ::sql::mysql::NativeAPI::NativeConnectionWrapper& _proxy,
                   sql::ConnectOptionsMap & properties)
  : driver(_driver), proxy(&_proxy), intern(NULL)
{
  boost::shared_ptr<MySQL_DebugLogger> tmp_logger(new MySQL_DebugLogger());
  intern.reset(new MySQL_ConnectionData(tmp_logger));

  service.reset(createServiceStmt());
  init(properties);
}
/* }}} */


/* {{{ MySQL_Connection::~MySQL_Connection() -I- */
MySQL_Connection::~MySQL_Connection()
{
  /*
    We need this outter block, because the on-stack object
    created by CPP_ENTER references `intern->logger`. And if there is no block
    the on-stack object will be destructed after `delete intern->logger` leading
    to a faulty memory access.
  */
  {
    CPP_ENTER_WL(intern->logger, "MySQL_Connection::~MySQL_Connection");
  }
}
/* }}} */

/* A struct to keep const reference data for mapping string value to int */
struct String2IntMap
{
  const char * key;
  int          value;
  bool         skip_list;
};

static const String2IntMap flagsOptions[]=
  {
    {"CLIENT_COMPRESS",			CLIENT_COMPRESS, false},
    {"CLIENT_FOUND_ROWS",		CLIENT_FOUND_ROWS, false},
    {"CLIENT_IGNORE_SIGPIPE",	CLIENT_IGNORE_SIGPIPE, false},
    {"CLIENT_IGNORE_SPACE",		CLIENT_IGNORE_SPACE, false},
    {"CLIENT_INTERACTIVE",		CLIENT_INTERACTIVE, false},
    {"CLIENT_LOCAL_FILES",		CLIENT_LOCAL_FILES, false},
    {"CLIENT_MULTI_STATEMENTS",	CLIENT_MULTI_STATEMENTS, false},
    {"CLIENT_NO_SCHEMA",		CLIENT_NO_SCHEMA, false}
  };

/* {{{ readFlag(::sql::SQLString, int= 0) -I- */
/** Check if connection option pointed by map iterator defines a connection
    flag */
static bool read_connection_flag(ConnectOptionsMap::const_iterator &cit, int &flags)
{
  const bool * value;

  for (size_t i = 0; i < sizeof(flagsOptions)/sizeof(String2IntMap); ++i) {

    if (!cit->first.compare(flagsOptions[i].key)) {

      try {
        value = (cit->second).get< bool >();
      } catch (sql::InvalidArgumentException&) {
        std::ostringstream msg;
        msg << "Wrong type passed for " << flagsOptions[i].key <<
            " expected bool";
        throw sql::InvalidArgumentException(msg.str());
      }
      if (!value) {
        sql::SQLString err("No bool value passed for ");
        err.append(flagsOptions[i].key);
        throw sql::InvalidArgumentException(err);
      }
      if (*value) {
        flags |= flagsOptions[i].value;
      }
      return true;
    }
  }
  return false;
}
/* }}} */

/* Array for mapping of boolean connection options to mysql_options call */
static const String2IntMap booleanOptions[]=
  {
    {"OPT_REPORT_DATA_TRUNCATION",  MYSQL_REPORT_DATA_TRUNCATION, false},
    {"OPT_ENABLE_CLEARTEXT_PLUGIN", MYSQL_ENABLE_CLEARTEXT_PLUGIN, false},
    {"OPT_CAN_HANDLE_EXPIRED_PASSWORDS", MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, true},
    {"OPT_CONNECT_ATTR_RESET",      MYSQL_OPT_CONNECT_ATTR_RESET, true},
    {"OPT_RECONNECT",               MYSQL_OPT_RECONNECT, true},
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID < 80000 || defined(MYCPPCONN_MARIADB_BUILD)
    {"sslVerify",                   MYSQL_OPT_SSL_VERIFY_SERVER_CERT, false}, // Deprecated
    {"sslEnforce",                  MYSQL_OPT_SSL_ENFORCE, false} // Deprecated
#else
    {"sslVerify",                   MYSQL_OPT_SSL_MODE, true}, // Deprecated
    {"sslEnforce",                  MYSQL_OPT_SSL_MODE, true}, // Deprecated
    {"OPT_GET_SERVER_PUBLIC_KEY",   MYSQL_OPT_GET_SERVER_PUBLIC_KEY, false},
    {"OPT_OPTIONAL_RESULTSET_METADATA", MYSQL_OPT_OPTIONAL_RESULTSET_METADATA, false},
#endif

  };
/* Array for mapping of integer connection options to mysql_options call */
static const String2IntMap intOptions[]=
  {
    {"OPT_CONNECT_TIMEOUT",     MYSQL_OPT_CONNECT_TIMEOUT, false},
    {"OPT_READ_TIMEOUT",        MYSQL_OPT_READ_TIMEOUT, false},
    {"OPT_WRITE_TIMEOUT",       MYSQL_OPT_WRITE_TIMEOUT, false},
    {"OPT_LOCAL_INFILE",        MYSQL_OPT_LOCAL_INFILE, false},
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 50700
    {"OPT_MAX_ALLOWED_PACKET",  MYSQL_OPT_MAX_ALLOWED_PACKET, false},
    {"OPT_NET_BUFFER_LENGTH",   MYSQL_OPT_NET_BUFFER_LENGTH, false},
#endif
    //{"OPT_SSL_MODE",            MYSQL_OPT_SSL_MODE    , false},
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 80000 && !defined(MYCPPCONN_MARIADB_BUILD)
    {"OPT_RETRY_COUNT",         MYSQL_OPT_RETRY_COUNT, false},
#endif
  };
/* Array for mapping of string connection options to mysql_options call */
static const String2IntMap stringOptions[]=
  {
    {"preInit",          MYSQL_INIT_COMMAND, false},
    {"sslKey",           MYSQL_OPT_SSL_KEY, true},
    {"sslCert",          MYSQL_OPT_SSL_CERT, true},
    {"sslCA",            MYSQL_OPT_SSL_CA, true},
    {"sslCAPath",        MYSQL_OPT_SSL_CAPATH, true},
    {"sslCipher",        MYSQL_OPT_SSL_CIPHER, true},
    {"sslCRL",           MYSQL_OPT_SSL_CRL, false},
    {"sslCRLPath",       MYSQL_OPT_SSL_CRLPATH, false},
    {"rsaKey",           MYSQL_SERVER_PUBLIC_KEY, false},
    {"charsetDir",       MYSQL_SET_CHARSET_DIR, false},
    {"pluginDir",        MYSQL_PLUGIN_DIR, false},
    {"defaultAuth",      MYSQL_DEFAULT_AUTH, false},
    {"OPT_CONNECT_ATTR_DELETE",  MYSQL_OPT_CONNECT_ATTR_DELETE, false},
    {"readDefaultGroup", MYSQL_READ_DEFAULT_GROUP, false},
    {"readDefaultFile",  MYSQL_READ_DEFAULT_FILE, false},
    {"OPT_CHARSET_NAME", MYSQL_SET_CHARSET_NAME, true},
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID >= 50700
    {"OPT_TLS_VERSION",  MYSQL_OPT_TLS_VERSION, false},
#endif
  };

template<class T>
bool process_connection_option(ConnectOptionsMap::const_iterator &option,
                const String2IntMap options_map[],
                size_t map_size,
                boost::shared_ptr< NativeAPI::NativeConnectionWrapper > &proxy)
{
  const T * value;

  for (size_t i = 0; i < map_size; ++i) {

    if (!option->first.compare(options_map[i].key) && !options_map[i].skip_list) {
      try {
        value = (option->second).get<T>();
      } catch (sql::InvalidArgumentException&) {
        std::ostringstream msg;
        msg << "Wrong type passed for " << options_map[i].key <<
            " expected " << typeid(value).name();
        throw sql::InvalidArgumentException(msg.str());
      }

      if (!value) {
        sql::SQLString err("Option ");
        err.append(option->first).append(" is not of expected type");
        throw sql::InvalidArgumentException(err);
      }

      try {
        proxy->options(static_cast<sql::mysql::MySQL_Connection_Options>(options_map[i].value),
              *value);
      } catch (sql::InvalidArgumentException& e) {
        std::string errorOption(options_map[i].key);
        throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
      }
      return true;
    }
  }

  return false;
}


bool get_connection_option(const sql::SQLString optionName,
                void *optionValue,
                const String2IntMap options_map[],
                size_t map_size,
                boost::shared_ptr< NativeAPI::NativeConnectionWrapper > &proxy)
{
  for (size_t i = 0; i < map_size; ++i) {
    if (!optionName.compare(options_map[i].key)) {
      try {
        proxy->get_option(static_cast<sql::mysql::MySQL_Connection_Options>(options_map[i].value),
                          optionValue);
      } catch (sql::InvalidArgumentException& e) {
        std::string errorOption(options_map[i].key);
        throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
      }
      return true;
    }
  }
  return false;
}


/*
  We support :
  - hostName
  - userName
  - password
  - port
  - socket
  - pipe
  - characterSetResults
  - schema
  - sslKey
  - sslCert
  - sslCA
  - sslCAPath
  - sslCipher
  - sslEnforce (deprecated)
  - sslVerify (deprecated)
  - sslCRL
  - sslCRLPath
  - useLegacyAuth
  - defaultStatementResultType
  - defaultPreparedStatementResultType
  - CLIENT_COMPRESS
  - CLIENT_FOUND_ROWS
  - CLIENT_IGNORE_SIGPIPE
  - CLIENT_IGNORE_SPACE
  - CLIENT_INTERACTIVE
  - CLIENT_LOCAL_FILES
  - CLIENT_MULTI_RESULTS
  - CLIENT_MULTI_STATEMENTS
  - CLIENT_NO_SCHEMA
  - CLIENT_COMPRESS
  - OPT_CONNECT_TIMEOUT
  - OPT_NAMED_PIPE
  - OPT_READ_TIMEOUT
  - OPT_WRITE_TIMEOUT
  - OPT_RECONNECT
  - OPT_CHARSET_NAME
  - OPT_REPORT_DATA_TRUNCATION
  - OPT_CAN_HANDLE_EXPIRED_PASSWORDS
  - OPT_ENABLE_CLEARTEXT_PLUGIN
  - OPT_LOCAL_INFILE
  - OPT_CONNECT_ATTR_ADD
  - OPT_CONNECT_ATTR_DELETE
  - OPT_CONNECT_ATTR_RESET
  - OPT_RETRY_COUNT,
  - OPT_GET_SERVER_PUBLIC_KEY,
  - OPT_OPTIONAL_RESULTSET_METADATA
  - OPT
  - preInit
  - postInit
  - rsaKey
  - charsetDir
  - pluginDir
  - defaultAuth
  - readDefaultGroup
  - readDefaultFile

  To add new connection option that maps to a myql_options call, only add its
  mapping to sql::mysql::MySQL_Connection_Options value to one of arrays above
  - booleanOptions, intOptions, stringOptions. You might need to add new member
  to the sql::mysql::MySQL_Connection_Options enum
*/

/* {{{ MySQL_Connection::init() -I- */
void MySQL_Connection::init(ConnectOptionsMap & properties)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::init");

  intern->is_valid = true;

  MySQL_Uri uri;

  sql::SQLString userName;
  sql::SQLString password;
  sql::SQLString defaultCharset("utf8mb4");
  sql::SQLString characterSetResults("utf8mb4");

  sql::SQLString sslKey, sslCert, sslCA, sslCAPath, sslCipher, postInit;
  bool ssl_used = false;
  int flags = CLIENT_MULTI_RESULTS;

  const int * p_i;
  const bool * p_b;
  const sql::SQLString * p_s;
  bool opt_reconnect = false;
  int  client_exp_pwd = false;
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID < 80000
  bool secure_auth= true;
#endif


  /* Values set in properties individually should have priority over those
     we restore from Uri */
  sql::ConnectOptionsMap::const_iterator it = properties.find("hostName");

  if (it != properties.end())	{
    try {
      p_s = (it->second).get< sql::SQLString >();
    } catch (sql::InvalidArgumentException&) {
      throw sql::InvalidArgumentException("Wrong type passed for userName expected sql::SQLString");
    }
    if (p_s) {
      /*
        Parsing uri prior to processing all parameters, so indivudually
        specified parameters precede over those in the uri
      */
      parseUri(*p_s, uri);
    } else {
      throw sql::InvalidArgumentException("No string value passed for hostName");
    }
  }

#define PROCESS_CONN_OPTION(option_type, options_map) process_connection_option< option_type >(it, options_map, sizeof(options_map)/sizeof(String2IntMap), proxy)

    for (it = properties.begin(); it != properties.end(); ++it) {
    if (!it->first.compare("userName")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for userName expected sql::SQLString");
      }
      if (p_s) {
        userName = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for userName");
      }
    } else if (!it->first.compare("password")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for password expected sql::SQLString");
      }
      if (p_s) {
        password = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for password");
      }
    } else if (!it->first.compare("port")) {
      try {
        p_i = (it->second).get< int >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for port expected int");
      }
      if (p_i) {
        uri.setPort(static_cast<unsigned int>(*p_i));
      } else {
        throw sql::InvalidArgumentException("No long long value passed for port");
      }
    } else if (!it->first.compare("socket")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for socket expected sql::SQLString");
      }
      if (p_s) {
        uri.setSocket(*p_s);
      } else {
        throw sql::InvalidArgumentException("No string value passed for socket");
      }
    } else if (!it->first.compare("pipe")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for pipe expected sql::SQLString");
      }
      if (p_s) {
        uri.setPipe(*p_s);
      } else {
        throw sql::InvalidArgumentException("No string value passed for pipe");
      }
    } else if (!it->first.compare("schema")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for schema expected sql::SQLString");
      }
      if (p_s) {
        uri.setSchema(*p_s);
      } else {
        throw sql::InvalidArgumentException("No string value passed for schema");
      }
    } else if (!it->first.compare("characterSetResults")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for characterSetResults expected sql::SQLString");
      }
      if (p_s) {
        characterSetResults = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for characterSetResults");
      }
    } else if (!it->first.compare("sslKey")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for sslKey expected sql::SQLString");
      }
      if (p_s) {
        sslKey = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for sslKey");
      }
      ssl_used = true;
    } else if (!it->first.compare("sslCert")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for sslCert expected sql::SQLString");
      }
      if (p_s) {
        sslCert = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for sslCert");
      }
      ssl_used = true;
    } else if (!it->first.compare("sslCA")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for sslCA expected sql::SQLString");
      }
      if (p_s) {
        sslCA = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for sslCA");
      }
      ssl_used = true;
    } else if (!it->first.compare("sslCAPath")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for sslCAPath expected sql::SQLString");
      }
      if (p_s) {
        sslCAPath = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for sslCAPath");
      }
      ssl_used = true;
    } else if (!it->first.compare("sslCipher")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for sslCipher expected sql::SQLString");
      }
      if (p_s) {
        sslCipher = *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for sslCipher");
      }
      ssl_used = true;
    } else if (!it->first.compare("defaultStatementResultType")) {
      try {
        p_i = (it->second).get< int >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for defaultStatementResultType expected sql::SQLString");
      }
      if (!p_i) {
        throw sql::InvalidArgumentException("No long long value passed for defaultStatementResultType");
      }
      do {
        if (static_cast< int >(sql::ResultSet::TYPE_FORWARD_ONLY) == *p_i) break;
        if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_INSENSITIVE) == *p_i) break;
        if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_SENSITIVE) == *p_i) {
          std::ostringstream msg;
          msg << "Invalid value " << *p_i <<
            " for option defaultStatementResultType. TYPE_SCROLL_SENSITIVE is not supported";
          throw sql::InvalidArgumentException(msg.str());
        }
        std::ostringstream msg;
        msg << "Invalid value (" << *p_i << " for option defaultStatementResultType";
        throw sql::InvalidArgumentException(msg.str());
      } while (0);
      intern->defaultStatementResultType = static_cast< sql::ResultSet::enum_type >(*p_i);
    /* The connector is not ready for unbuffered as we need to refetch */
    } else if (!it->first.compare("defaultPreparedStatementResultType")) {
#if WE_SUPPORT_USE_RESULT_WITH_PS
      try {
        p_i = (it->second).get< int >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for defaultPreparedStatementResultType expected sql::SQLString");
      }
      if (!(p_i)) {
        throw sql::InvalidArgumentException("No long long value passed for defaultPreparedStatementResultType");
      }
      do {
        if (static_cast< int >(sql::ResultSet::TYPE_FORWARD_ONLY) == *p_i) break;
        if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_INSENSITIVE) == *p_i) break;
        if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_SENSITIVE) == *p_i) {
          std::ostringstream msg;
          msg << "Invalid value " << *p_i <<
            " for option defaultPreparedStatementResultType. TYPE_SCROLL_SENSITIVE is not supported";
          throw sql::InvalidArgumentException(msg.str());
        }
        std::ostringstream msg;
        msg << "Invalid value (" << *p_i << " for option defaultPreparedStatementResultType";
        throw sql::InvalidArgumentException(msg.str());
      } while (0);
      intern->defaultPreparedStatementResultType = static_cast< sql::ResultSet::enum_type >(*p_i);
#else
      throw SQLException("defaultPreparedStatementResultType parameter still not implemented");

#endif
    } else if (!it->first.compare("metadataUseInfoSchema")) {
      try {
        p_b = (it->second).get<bool>();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for metadataUseInfoSchema expected bool");
      }
      if (p_b) {
        intern->metadata_use_info_schema = *p_b;
      } else {
        throw sql::InvalidArgumentException("No bool value passed for metadataUseInfoSchema");
      }
    } else if (!it->first.compare("OPT_RECONNECT")) {
      try {
        p_b = (it->second).get<bool>();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for OPT_RECONNECT expected bool");
      }
      if (!(p_b)) {
        throw sql::InvalidArgumentException("No bool value passed for OPT_RECONNECT");
      }
      opt_reconnect = true;
      intern->reconnect= *p_b;
    } else if (!it->first.compare("OPT_CHARSET_NAME")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for OPT_CHARSET_NAME expected sql::SQLString");
      }
      if (!p_s) {
        throw sql::InvalidArgumentException("No SQLString value passed for OPT_CHARSET_NAME");
      }
      defaultCharset = *p_s;
    } else if (!it->first.compare("OPT_NAMED_PIPE")) {
      /* Not sure it is really needed */
      uri.setProtocol(NativeAPI::PROTOCOL_PIPE);
    } else if (!it->first.compare("OPT_CAN_HANDLE_EXPIRED_PASSWORDS")) {
      try {
        p_b = (it->second).get<bool>();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for OPT_CAN_HANDLE_EXPIRED_PASSWORDS expected bool");
      }
      if (!(p_b)) {
        throw sql::InvalidArgumentException("No bool value passed for "
                          "OPT_CAN_HANDLE_EXPIRED_PASSWORDS");
      }
      try {
        client_exp_pwd= proxy->options(MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, (const char*)p_b);
      } catch (sql::InvalidArgumentException& e) {
        std::string errorOption("MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS");
        throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
      }
    } else if (!it->first.compare("postInit")) {
      try {
        p_s = (it->second).get< sql::SQLString >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for postInit expected sql::SQLString");
      }
      if (p_s) {
        postInit= *p_s;
      } else {
        throw sql::InvalidArgumentException("No string value passed for postInit");
      }
    } else if (!it->first.compare("useLegacyAuth")) {
      try {
        p_b = (it->second).get< bool >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for useLegacyAuth expected sql::SQLString");
      }
#if MYCPPCONN_STATIC_MYSQL_VERSION_ID < 80000
      if (p_b) {
        secure_auth= !*p_b;
      } else {
        throw sql::InvalidArgumentException("No bool value passed for useLegacyAuth");
      }
#endif
    } else if (!it->first.compare("OPT_CONNECT_ATTR_ADD")) {
      const std::map< sql::SQLString, sql::SQLString > *conVal;
      try {
        conVal= (it->second).get< std::map< sql::SQLString, sql::SQLString > >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for OPT_CONNECT_ATTR_ADD expected std::map< sql::SQLString, sql::SQLString >");
      }
      std::map< sql::SQLString, sql::SQLString >::const_iterator conn_attr_it;
      for (conn_attr_it = conVal->begin(); conn_attr_it != conVal->end(); conn_attr_it++) {
        try {
          proxy->options(sql::mysql::MYSQL_OPT_CONNECT_ATTR_ADD, conn_attr_it->first, conn_attr_it->second);
        } catch (sql::InvalidArgumentException& e) {
          std::string errorOption("MYSQL_OPT_CONNECT_ATTR_ADD");
          throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
        }
      }
    } else if (!it->first.compare("OPT_CONNECT_ATTR_DELETE")) {
      const std::list< sql::SQLString > *conVal;
      try {
        conVal= (it->second).get< std::list< sql::SQLString > >();
      } catch (sql::InvalidArgumentException&) {
        throw sql::InvalidArgumentException("Wrong type passed for OPT_CONNECT_ATTR_DELETE expected std::list< sql::SQLString >");
      }
      std::list< sql::SQLString >::const_iterator conn_attr_it;
      for (conn_attr_it = conVal->begin(); conn_attr_it != conVal->end(); conn_attr_it++) {
        try {
          proxy->options(MYSQL_OPT_CONNECT_ATTR_DELETE, *conn_attr_it);
        } catch (sql::InvalidArgumentException& e) {
          std::string errorOption("MYSQL_OPT_CONNECT_ATTR_DELETE");
          throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
        }
      }
    } else if (!it->first.compare("OPT_CONNECT_ATTR_RESET")) {
      proxy->options(MYSQL_OPT_CONNECT_ATTR_RESET, 0);

#if MYCPPCONN_STATIC_MYSQL_VERSION_ID > 80000 && !defined(MYCPPCONN_MARIADB_BUILD)

    } else if (!it->first.compare("sslVerify")) {

      ssl_mode ssl_mode_val = (it->second).get< bool >() ? SSL_MODE_VERIFY_CA
                                           : SSL_MODE_PREFERRED;
      proxy->options(MYSQL_OPT_SSL_MODE, &ssl_mode_val);


    } else if (!it->first.compare("sslEnforce")) {
      ssl_mode ssl_mode_val = (it->second).get< bool >() ? SSL_MODE_REQUIRED
                                                         : SSL_MODE_PREFERRED;
      proxy->options(MYSQL_OPT_SSL_MODE, &ssl_mode_val);

#endif


    /* If you need to add new integer connection option that should result in
       calling mysql_optiong - add its mapping to the intOptions array
     */
    } else if (PROCESS_CONN_OPTION(int, intOptions)) {
      // Nothing to do here

    /* For boolean coonection option - add mapping to booleanOptions array */
    } else if (PROCESS_CONN_OPTION(bool, booleanOptions)) {
      // Nothing to do here

    /* For string coonection option - add mapping to stringOptions array */
    } else if (PROCESS_CONN_OPTION(sql::SQLString, stringOptions)) {
      // Nothing to do here
    } else if (read_connection_flag(it, flags)) {
      // Nothing to do here
    } else {
      // TODO: Shouldn't we really create a warning here? as soon as we are able to
      //       create a warning
    }

  } /* End of cycle on connection options map */


#undef PROCESS_CONNSTR_OPTION

// Throwing in case of wrong protocol
#ifdef _WIN32
  if (uri.Protocol() == NativeAPI::PROTOCOL_SOCKET) {
    throw sql::InvalidArgumentException("Invalid for this platform protocol requested(MYSQL_PROTOCOL_SOCKET)");
  }
#else
  if (uri.Protocol() == NativeAPI::PROTOCOL_PIPE) {
    throw sql::InvalidArgumentException("Invalid for this platform protocol requested(MYSQL_PROTOCOL_PIPE)");
  }
#endif

  proxy->use_protocol(uri.Protocol());

#if MYCPPCONN_STATIC_MYSQL_VERSION_ID < 80000
  try {
    proxy->options(MYSQL_SECURE_AUTH, &secure_auth);
  } catch (sql::InvalidArgumentException& e) {
    std::string errorOption("MYSQL_SECURE_AUTH");
    throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
  }
#endif

  try {
    proxy->options(MYSQL_SET_CHARSET_NAME, defaultCharset.c_str());
  } catch (sql::InvalidArgumentException& e) {
    std::string errorOption("MYSQL_SET_CHARSET_NAME");
    throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
  }


  if (ssl_used) {
    /* According to the docs, always returns 0 */
    proxy->ssl_set(sslKey, sslCert, sslCA, sslCAPath, sslCipher.c_str());
  }

  /*
    Workaround for libmysqlclient... if OPT_TLS_VERSION or ssl_set is used,
    it overwrites OPT_SSL_MODE... setting it again.
  */

  it = properties.find("OPT_SSL_MODE");

  if (it != properties.end())
  {
     PROCESS_CONN_OPTION(int, intOptions);
  }

  CPP_INFO_FMT("hostName=%s", uri.Host().c_str());
  CPP_INFO_FMT("user=%s", userName.c_str());
  CPP_INFO_FMT("port=%d", uri.Port());
  CPP_INFO_FMT("schema=%s", uri.Schema().c_str());
  CPP_INFO_FMT("socket/pipe=%s", uri.SocketOrPipe().c_str());
  if (!proxy->connect(uri.Host(),
            userName,
            password,
            uri.Schema() /* schema */,
            uri.Port(),
            uri.SocketOrPipe() /*socket or named pipe */,
            flags))
  {
    CPP_ERR_FMT("Couldn't connect : %d", proxy->errNo());
    CPP_ERR_FMT("Couldn't connect : (%s)", proxy->sqlstate().c_str());
    CPP_ERR_FMT("Couldn't connect : %s", proxy->error().c_str());
    CPP_ERR_FMT("Couldn't connect : %d:(%s) %s", proxy->errNo(), proxy->sqlstate().c_str(), proxy->error().c_str());

    /* If error is "Password has expired" and application supports it while
       mysql client lib does not */
    std::string error_message;
    int native_error= proxy->errNo();

    if (native_error == ER_MUST_CHANGE_PASSWORD_LOGIN
      && client_exp_pwd) {

      native_error= deCL_CANT_HANDLE_EXP_PWD;
      error_message= "Your password has expired, but your instance of"
        " Connector/C++ is not linked against mysql client library that"
        " allows to reset it. To resolve this you either need to change"
        " the password with mysql client that is capable to do that,"
        " or rebuild your instance of Connector/C++ against mysql client"
        " library that supports resetting of an expired password.";
    } else {
      error_message= proxy->error();
    }

    sql::SQLException e(error_message, proxy->sqlstate(), native_error);
    proxy.reset();
    throw e;
  }

  if (opt_reconnect) {
    try {
      proxy->options(MYSQL_OPT_RECONNECT, (const char *) &intern->reconnect);
    } catch (sql::InvalidArgumentException& e) {
      std::string errorOption("MYSQL_OPT_RECONNECT");
      throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
    }
  }

  setAutoCommit(true);
  setTransactionIsolation(sql::TRANSACTION_REPEATABLE_READ);
  // Different Values means we have to set different result set encoding
  if (characterSetResults.compare(defaultCharset)) {
    setSessionVariable("character_set_results", characterSetResults.length() ? characterSetResults:"NULL");
  }
  intern->meta.reset(new MySQL_ConnectionMetaData(service.get(), proxy, intern->logger));

  if (postInit.length() > 0) {
    service->executeUpdate(postInit);
  }
}
/* }}} */


/* {{{ MySQL_Connection::clearWarnings() -I- */
void
MySQL_Connection::clearWarnings()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::clearWarnings");

  intern->warnings.reset();
}
/* }}} */


/* {{{ MySQL_Connection::checkClosed() -I- */
void
MySQL_Connection::checkClosed()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::checkClosed");
  if (!intern->is_valid) {
    throw sql::SQLException("Connection has been closed");
  }
}
/* }}} */


/* {{{ MySQL_Connection::close() -I- */
void
MySQL_Connection::close()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::close");
  checkClosed();
  proxy.reset();
  clearWarnings();
  intern->is_valid = false;
}
/* }}} */


/* {{{ MySQL_Connection::commit() -I- */
void
MySQL_Connection::commit()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::commit");
  checkClosed();
  proxy->commit();
}
/* }}} */


/* {{{ MySQL_Connection::createStatement() -I- */
sql::Statement * MySQL_Connection::createStatement()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::createStatement");
  checkClosed();
  return new MySQL_Statement(this, proxy, intern->defaultStatementResultType, intern->logger);
}
/* }}} */


/* {{{ MySQL_Connection::escapeString() -I- */
sql::SQLString MySQL_Connection::escapeString(const sql::SQLString & s)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::escapeString");
  checkClosed();
  return proxy->escapeString(s);
}
/* }}} */


/* {{{ MySQL_Connection::getAutoCommit() -I- */
bool
MySQL_Connection::getAutoCommit()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getAutoCommit");
  checkClosed();
  return intern->autocommit;
}
/* }}} */


/* {{{ MySQL_Connection::getCatalog() -I- */
sql::SQLString
MySQL_Connection::getCatalog()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getCatalog");
  checkClosed();
  return proxy->get_server_version() > 60006 ? "def" : "";
}
/* }}} */


/* {{{ MySQL_Connection::getDriver() -I- */
Driver * MySQL_Connection::getDriver()
{
  return driver;
}
/* }}} */


/**
  Added for consistency. Not present in jdbc interface. Is still subject for discussion.
*/
/* {{{ MySQL_Connection::getSchema() -I- */
sql::SQLString
MySQL_Connection::getSchema()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getSchema");
  checkClosed();
  boost::scoped_ptr< sql::Statement > stmt(createStatement());
  boost::scoped_ptr< sql::ResultSet > rset(stmt->executeQuery("SELECT DATABASE()")); //SELECT SCHEMA()
  rset->next();
  return rset->getString(1);
}
/* }}} */


/* {{{ MySQL_Connection::getClientInfo() -I- */
sql::SQLString
MySQL_Connection::getClientInfo()
{
  const sql::SQLString clientInfo("cppconn");
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientInfo");
  return clientInfo;
}
/* }}} */

#define GET_CONN_OPTION(option_type, option_value, options_map) \
get_connection_option(option_type, option_value, options_map, sizeof(options_map)/sizeof(String2IntMap), proxy)

/* {{{ MySQL_Connection::getClientOption() -I- */
void
MySQL_Connection::getClientOption(const sql::SQLString & optionName, void * optionValue)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientOption");
  if (!optionName.compare("metadataUseInfoSchema")) {
    *(static_cast<bool *>(optionValue)) = intern->metadata_use_info_schema;
  } else if (!optionName.compare("defaultStatementResultType")) {
    *(static_cast<int *>(optionValue)) = intern->defaultStatementResultType;
  } else if (!optionName.compare("defaultPreparedStatementResultType")) {
    *(static_cast<int *>(optionValue)) = intern->defaultPreparedStatementResultType;
  } else if (!optionName.compare("multiByteMinLength")) {
    MY_CHARSET_INFO cs;
    proxy->get_character_set_info(&cs);
    *(static_cast<int *>(optionValue)) = cs.mbminlen;
  } else if (!optionName.compare("multiByteMaxLength")) {
    MY_CHARSET_INFO cs;
    proxy->get_character_set_info(&cs);
    *(static_cast<int *>(optionValue)) = cs.mbmaxlen;
  /* mysql_get_option() was added in mysql 5.7.3 version */
  } else if ( proxy->get_server_version() >= 50703 ) {
    try {
      if (GET_CONN_OPTION(optionName, optionValue, intOptions)) {
        return;
      } else if (GET_CONN_OPTION(optionName, optionValue, booleanOptions)) {
        return;
      } else if (GET_CONN_OPTION(optionName, optionValue, stringOptions)) {
        return;
      }
    } catch (sql::SQLUnsupportedOptionException& e) {
      CPP_ERR_FMT("Unsupported option : %d:(%s) %s", proxy->errNo(), proxy->sqlstate().c_str(), proxy->error().c_str());
      throw e;
    }
  }
}
/* }}} */


/* {{{ MySQL_Connection::getClientOption() -I- */
sql::SQLString
MySQL_Connection::getClientOption(const sql::SQLString & optionName)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientOption");

  if (!optionName.compare("characterSetResults")) {
    return sql::SQLString(getSessionVariable("character_set_results"));
  } else if (!optionName.compare("characterSetDirectory")) {
    MY_CHARSET_INFO cs;
    proxy->get_character_set_info(&cs);
    return cs.dir ? sql::SQLString(cs.dir) : "";
  } else if ( proxy->get_server_version() >= 50703 ) {
    const char* optionValue= NULL;
    if (GET_CONN_OPTION(optionName, &optionValue, stringOptions)) {
      return optionValue ? sql::SQLString(optionValue) : "";
    }
  }
  return "";
}
/* }}} */


/* {{{ MySQL_Connection::getMetaData() -I- */
DatabaseMetaData *
MySQL_Connection::getMetaData()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getMetaData");
  checkClosed();
  return intern->meta.get();
}
/* }}} */


/* {{{ MySQL_Connection::getTransactionIsolation() -I- */
enum_transaction_isolation
MySQL_Connection::getTransactionIsolation()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getTransactionIsolation");
  checkClosed();
  return intern->txIsolationLevel;
}
/* }}} */


/* {{{ MySQL_Connection::getWarnings() -I- */
const SQLWarning *
MySQL_Connection::getWarnings()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getWarnings");
  checkClosed();

  clearWarnings();

  intern->warnings.reset(loadMysqlWarnings(this));

  return intern->warnings.get();
}
/* }}} */


/* {{{ MySQL_Connection::isClosed() -I- */
bool
MySQL_Connection::isClosed()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::isClosed");
  if (intern->is_valid) {
    return false;
  }
  return true;
}
/* }}} */


/* {{{ MySQL_Connection::isReadOnly() -U- */
bool
MySQL_Connection::isReadOnly()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::isReadOnly");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::isReadOnly");
  return false; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::nativeSQL() -I- */
sql::SQLString
MySQL_Connection::nativeSQL(const sql::SQLString& sql)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::nativeSQL");
  checkClosed();
  return sql::SQLString(sql.c_str());
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -I- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& sql)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  CPP_INFO_FMT("query=%s", sql.c_str());
  checkClosed();
  boost::shared_ptr< NativeAPI::NativeStatementWrapper > stmt;

  //TODO change - probably no need to catch and throw here. Logging can be done inside proxy
  try {
     stmt.reset(&proxy->stmt_init());
  } catch (sql::SQLException& e) {
    CPP_ERR_FMT("No statement : %d:(%s) %s", proxy->errNo(), proxy->sqlstate().c_str(), proxy->error().c_str());
    throw e;
  }

  if (stmt->prepare(sql)) {
    CPP_ERR_FMT("Cannot prepare %d:(%s) %s", stmt->errNo(), stmt->sqlstate().c_str(), stmt->error().c_str());
    sql::SQLException e(stmt->error(), stmt->sqlstate(), stmt->errNo());
    stmt.reset();
    throw e;
  }

  return new MySQL_Prepared_Statement(stmt, this, intern->defaultPreparedStatementResultType, intern->logger);
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -U- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& /* sql */, int /* autoGeneratedKeys */)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::prepareStatement(const sql::SQLString& sql, int autoGeneratedKeys)");
  return NULL; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -U- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& /* sql */, int /* columnIndexes */ [])
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::prepareStatement(const sql::SQLString& sql, int* columnIndexes)");
  return NULL; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -U- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& /* sql */, int /* resultSetType */, int /* resultSetConcurrency */)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency)");
  return NULL; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -U- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& /* sql */, int /* resultSetType */, int /* resultSetConcurrency */, int /* resultSetHoldability */)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)");
  return NULL; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::prepareStatement() -U- */
sql::PreparedStatement *
MySQL_Connection::prepareStatement(const sql::SQLString& /* sql */, sql::SQLString /* columnNames*/ [])
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::prepareStatement");
  checkClosed();
  throw sql::MethodNotImplementedException("MySQL_Connection::prepareStatement(const sql::SQLString& sql, sql::SQLString columnNames[])");
  return NULL; // fool compiler
}
/* }}} */


/* {{{ MySQL_Connection::releaseSavepoint() -I- */
void
MySQL_Connection::releaseSavepoint(Savepoint * savepoint)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::releaseSavepoint");
  checkClosed();
  if (proxy->get_server_version() < 50001) {
    throw sql::MethodNotImplementedException("releaseSavepoint not available in this server version");
  }
  if (getAutoCommit()) {
    throw sql::InvalidArgumentException("The connection is in autoCommit mode");
  }
  sql::SQLString sql("RELEASE SAVEPOINT ");
  sql.append(savepoint->getSavepointName());

  boost::scoped_ptr<sql::Statement> stmt(createStatement());
  stmt->execute(sql);
}
/* }}} */


/* {{{ MySQL_Connection::rollback() -I- */
void
MySQL_Connection::rollback()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::rollback");
  checkClosed();
  proxy->rollback();
}
/* }}} */


/* {{{ MySQL_Connection::rollback() -I- */
void
MySQL_Connection::rollback(Savepoint * savepoint)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::rollback");
  checkClosed();
  if (getAutoCommit()) {
    throw sql::InvalidArgumentException("The connection is in autoCommit mode");
  }
  sql::SQLString sql("ROLLBACK TO SAVEPOINT ");
  sql.append(savepoint->getSavepointName());

  boost::scoped_ptr< sql::Statement > stmt(createStatement());
  stmt->execute(sql);
}
/* }}} */


/* {{{ MySQL_Connection::setCatalog() -I- */
void
MySQL_Connection::setCatalog(const sql::SQLString&)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setCatalog");
  checkClosed();
}
/* }}} */


/* {{{ MySQL_Connection::setSchema() -I- (not part of JDBC) */
void
MySQL_Connection::setSchema(const sql::SQLString& catalog)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setCatalog");
  checkClosed();
  sql::SQLString sql("USE `");
  sql.append(catalog).append("`");

  boost::scoped_ptr< sql::Statement > stmt(createStatement());
  stmt->execute(sql);
}
/* }}} */


/* {{{ MySQL_Connection::setClientOption() -I- */
sql::Connection *
MySQL_Connection::setClientOption(const sql::SQLString & optionName, const void * optionValue)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setClientOption");
  if (!optionName.compare("libmysql_debug")) {
    proxy->debug(static_cast<const char *>(optionValue));
  } else if (!optionName.compare("clientTrace")) {
    if (*(static_cast<const bool *>(optionValue))) {
      intern->logger->enableTracing();
      CPP_INFO("Tracing enabled");
    } else {
      intern->logger->disableTracing();
      CPP_INFO("Tracing disabled");
    }
  } else if (!optionName.compare("metadataUseInfoSchema")) {
    intern->metadata_use_info_schema = *(static_cast<const bool *>(optionValue));
  } else if (!optionName.compare("defaultStatementResultType")) {
    int int_value =  *static_cast<const int *>(optionValue);
    do {
      if (static_cast< int >(sql::ResultSet::TYPE_FORWARD_ONLY) == int_value) break;
      if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_INSENSITIVE) == int_value) break;
      if (static_cast< int >(sql::ResultSet::TYPE_SCROLL_SENSITIVE) == int_value) {
        std::ostringstream msg;
        msg << "Invalid value " << int_value <<
          " for option defaultStatementResultType. TYPE_SCROLL_SENSITIVE is not supported";
        throw sql::InvalidArgumentException(msg.str());
      }
      std::ostringstream msg;
      msg << "Invalid value (" << int_value << " for option defaultStatementResultType";
      throw sql::InvalidArgumentException(msg.str());
    } while (0);
    intern->defaultStatementResultType = static_cast< sql::ResultSet::enum_type >(int_value);
  } else if (!optionName.compare("defaultPreparedStatementResultType")) {
#if WE_SUPPORT_USE_RESULT_WITH_PS
    /* The connector is not ready for unbuffered as we need to refetch */
    intern->defaultPreparedStatementResultType = *(static_cast<const bool *>(optionValue));
#else
    throw MethodNotImplementedException("MySQL_Prepared_Statement::setResultSetType");
#endif
  }
  return this;
}
/* }}} */


/* {{{ MySQL_Connection::setClientOption() -I- */
sql::Connection *
MySQL_Connection::setClientOption(const sql::SQLString & optionName, const sql::SQLString & optionValue)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setClientOption");
  if (!optionName.compare("characterSetResults")) {
    setSessionVariable("character_set_results", optionValue);
  }
  return this;
}
/* }}} */


/* {{{ MySQL_Connection::setHoldability() -U- */
void
MySQL_Connection::setHoldability(int /* holdability */)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setHoldability");
  throw sql::MethodNotImplementedException("MySQL_Connection::setHoldability()");
}
/* }}} */


/* {{{ MySQL_Connection::setReadOnly() -U- */
void
MySQL_Connection::setReadOnly(bool /* readOnly */)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setReadOnly");
  throw sql::MethodNotImplementedException("MySQL_Connection::setReadOnly()");
}
/* }}} */


/* {{{ MySQL_Connection::setSavepoint() -U- */
Savepoint *
MySQL_Connection::setSavepoint()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setSavepoint");
  checkClosed();
  throw sql::MethodNotImplementedException("Please use MySQL_Connection::setSavepoint(const sql::SQLString& name)");
  return NULL;
}
/* }}} */


/* {{{ MySQL_Connection::setSavepoint() -I- */
sql::Savepoint *
MySQL_Connection::setSavepoint(const sql::SQLString& name)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setSavepoint");
  checkClosed();
  if (getAutoCommit()) {
    throw sql::InvalidArgumentException("The connection is in autoCommit mode");
  }
  if (!name.length()) {
    throw sql::InvalidArgumentException("Savepoint name cannot be empty string");
  }
  sql::SQLString sql("SAVEPOINT ");
  sql.append(name);

  boost::scoped_ptr< sql::Statement > stmt(createStatement());
  stmt->execute(sql);

  return new MySQL_Savepoint(name);
}
/* }}} */


/* {{{ MySQL_Connection::setAutoCommit() -I- */
void
MySQL_Connection::setAutoCommit(bool autoCommit)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setAutoCommit");
  checkClosed();
  proxy->autocommit(autoCommit);
  intern->autocommit = autoCommit;
}
/* }}} */


/* {{{ MySQL_Connection::setTransactionIsolation() -I- */
void
MySQL_Connection::setTransactionIsolation(enum_transaction_isolation level)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setTransactionIsolation");
  checkClosed();
  const char * q;
  switch (level) {
    case TRANSACTION_SERIALIZABLE:
      q = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";
      break;
    case TRANSACTION_REPEATABLE_READ:
      q =  "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
      break;
    case TRANSACTION_READ_COMMITTED:
      q = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
      break;
    case TRANSACTION_READ_UNCOMMITTED:
      q = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
      break;
    default:
      throw sql::InvalidArgumentException("MySQL_Connection::setTransactionIsolation()");
  }
  intern->txIsolationLevel = level;

  service->executeUpdate(q);
}
/* }}} */


/* {{{ MySQL_Connection::getLastStatementInfo() -I- */
sql::SQLString
MySQL_Connection::getLastStatementInfo()
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getLastStatementInfo");
  checkClosed();

  return proxy->info();
}
/* }}} */


/* {{{ MySQL_Connection::getSessionVariable() -I- */
sql::SQLString
MySQL_Connection::getSessionVariable(const sql::SQLString & varname)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::getSessionVariable");
  checkClosed();

  if (intern->cache_sql_mode && intern->sql_mode_set == true && !varname.compare("sql_mode")) {
    CPP_INFO_FMT("sql_mode=%s", intern->sql_mode.c_str());
    return intern->sql_mode;
  }
  sql::SQLString q("SHOW SESSION VARIABLES LIKE '");
  q.append(varname).append("'");

  boost::scoped_ptr< sql::ResultSet > rset(service->executeQuery(q));

  if (rset->next()) {
    if (intern->cache_sql_mode && intern->sql_mode_set == false && !varname.compare("sql_mode")) {
      intern->sql_mode = rset->getString(2);
      intern->sql_mode_set = true;
    }
    return rset->getString(2);
  }
  return "";
}
/* }}} */


/* {{{ MySQL_Connection::setSessionVariable() -I- */
void
MySQL_Connection::setSessionVariable(const sql::SQLString & varname, const sql::SQLString & value)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setSessionVariable");
  checkClosed();

  sql::SQLString query("SET SESSION ");
  query.append(varname).append("=");

  if (!value.compare("NULL")) {
    query.append("NULL");
  } else {
    query.append("'").append(value).append("'");
  }

  service->executeUpdate(query);
  if (intern->cache_sql_mode && !strncasecmp(varname.c_str(), "sql_mode", sizeof("sql_mode") - 1)) {
    intern->sql_mode= value;
  }
}
/* }}} */


/* {{{ MySQL_Connection::setSessionVariable() -I- */
void
MySQL_Connection::setSessionVariable(const sql::SQLString & varname, unsigned int value)
{
  CPP_ENTER_WL(intern->logger, "MySQL_Connection::setSessionVariable");
  checkClosed();

  sql::SQLString query("SET SESSION ");
  query.append(varname).append("=");

  if (!value) {
    query.append("0");
  } else {
    std::ostringstream qstr;
    qstr << value;
    query.append(qstr.str());
  }

  service->executeUpdate(query);
}
/* }}} */


/* {{{ MySQL_Connection::isValid() -I- */
bool
MySQL_Connection::isValid()
{
   CPP_ENTER_WL(intern->logger, "MySQL_Connection::isValid");
   bool is_active= false;
   if (intern->is_valid) {
     if (intern->reconnect) {
       bool opt_reconnect_value= false;
       try {
           proxy->options(MYSQL_OPT_RECONNECT, (const char *) &opt_reconnect_value);
       } catch (sql::InvalidArgumentException& e) {
           std::string errorOption("MYSQL_OPT_RECONNECT");
           throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
       }

       is_active= proxy->ping();

       opt_reconnect_value= true;
       try {
           proxy->options(MYSQL_OPT_RECONNECT, (const char *) &opt_reconnect_value);
       } catch (sql::InvalidArgumentException& e) {
           std::string errorOption("MYSQL_OPT_RECONNECT");
           throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
       }

       if (is_active == 0) {
           return true;
       }
     } else {
       if (!proxy->ping()) {
           return true;
       }
     }
   }
   return false;
}
/* }}} */


/* {{{ MySQL_Connection::reconnect() -I- */
bool
MySQL_Connection::reconnect()
{
   CPP_ENTER_WL(intern->logger, "MySQL_Connection::reconnect");
   bool is_active= false;
   if (intern->is_valid) {
     if (intern->reconnect) {
       if (!proxy->ping()) {
           return true;
       }
     } else {
       bool opt_reconnect_value= true;
       try {
         proxy->options(MYSQL_OPT_RECONNECT, (const char *) &opt_reconnect_value);
       } catch (sql::InvalidArgumentException& e) {
         std::string errorOption("MYSQL_OPT_RECONNECT");
         throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
       }

       is_active= proxy->ping();

       opt_reconnect_value= false;
       try {
         proxy->options(MYSQL_OPT_RECONNECT, (const char *) &opt_reconnect_value);
       } catch (sql::InvalidArgumentException& e) {
         std::string errorOption("MYSQL_OPT_RECONNECT");
         throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
       }

       if (is_active == 0) {
           return true;
       }
     }
   }
   return false;
}
/* }}} */


} /* namespace mysql */
} /* namespace sql */
/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */