File: results.c

package info (click to toggle)
myodbc 5.1.10-2%2Bdeb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,988 kB
  • sloc: ansic: 33,649; cpp: 1,360; xml: 1,261; sh: 353; makefile: 264; perl: 43
file content (1734 lines) | stat: -rw-r--r-- 51,497 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
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
/*
  Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

  The MySQL Connector/ODBC is licensed under the terms of the GPLv2
  <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
  MySQL Connectors. There are special exceptions to the terms and
  conditions of the GPLv2 as it is applied to this software, see the
  FLOSS License Exception
  <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
  
  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
*/

/**
  @file  results.c
  @brief Result set and related information functions.
*/

#include "driver.h"
#include <errmsg.h>
#include <ctype.h>
#include <locale.h>

#define SQL_MY_PRIMARY_KEY 1212


void reset_getdata_position(STMT *stmt)
{
  stmt->getdata.column= (uint) ~0L;
  stmt->getdata.source= NULL;
  stmt->getdata.dst_bytes= (ulong) ~0L;
  stmt->getdata.dst_offset= (ulong) ~0L;
  stmt->getdata.src_offset= (ulong) ~0L;
  stmt->getdata.latest_bytes= stmt->getdata.latest_used= 0;
}


/* Verifies if C type is suitable for copying SQL_BINARY data
   http://msdn.microsoft.com/en-us/library/ms713559%28VS.85%29.aspx */
my_bool is_binary_ctype( SQLSMALLINT cType)
{
  return (cType == SQL_C_CHAR
       || cType == SQL_C_BINARY
       || cType == SQL_C_WCHAR);
}


/* Converts binary(currently used for bit field only) to long long number.*/
void binary2numeric(long long *dst, char *src, uint srcLen)
{
  *dst= 0;

  while (srcLen)
  {
    /* if source binary data is longer than 8 bytes(size of long long)
       we consider only minor 8 bytes */
    if (srcLen > sizeof(long long))
          continue;
    *dst+= (0xff & *src) << (--srcLen)*8;
    ++src;
  }
}


/* Function that verifies if conversion from given sql type to c type supported.
   Based on http://msdn.microsoft.com/en-us/library/ms709280%28VS.85%29.aspx
   and underlying pages.
   Currently checks conversions for MySQL BIT(n) field(SQL_BIT or SQL_BINARY)
*/
my_bool odbc_supported_conversion(SQLSMALLINT sqlType, SQLSMALLINT cType)
{
  switch (sqlType)
  {
  case SQL_BIT:
    {
      switch (cType)
      {
      case SQL_C_DATE:
      case SQL_C_TYPE_DATE:
      case SQL_C_TIME:
      case SQL_C_TYPE_TIME:
      case SQL_C_TIMESTAMP:
      case SQL_C_TYPE_TIMESTAMP:
        return FALSE;
      }
    }
  case SQL_BINARY:
    {
      return is_binary_ctype(cType);
    }
  }

  return TRUE;
}


 /* Conversion supported by driver as exception to odbc specs
    (i.e. to odbc_supported_conversion() results).
    e.g. we map bit(n>1) to SQL_BINARY, but provide its conversion to numeric
    types */
 my_bool driver_supported_conversion(MYSQL_FIELD * field, SQLSMALLINT cType)
 {
   switch(field->type)
   {
   case MYSQL_TYPE_BIT:
     {
       switch (cType)
       {
       case SQL_C_BIT:
       case SQL_C_TINYINT:
       case SQL_C_STINYINT:
       case SQL_C_UTINYINT:
       case SQL_C_SHORT:
       case SQL_C_SSHORT:
       case SQL_C_USHORT:
       case SQL_C_LONG:
       case SQL_C_SLONG:
       case SQL_C_ULONG:
       case SQL_C_FLOAT:
       case SQL_C_DOUBLE:
       case SQL_C_SBIGINT:
       case SQL_C_UBIGINT:
         return TRUE;

       /* SQL_BIT should be converted SQL_C_NUMERIC, while SQL_BINARY should not
        */
       case SQL_C_NUMERIC:
         return TRUE;
       }
     }
   }

   return FALSE;
 }


 SQLUSMALLINT sqlreturn2row_status(SQLRETURN res)
 {
   switch (res)
   {
     case SQL_SUCCESS:            return SQL_ROW_SUCCESS;
     case SQL_SUCCESS_WITH_INFO:  return SQL_ROW_SUCCESS_WITH_INFO;
   }

   return SQL_ROW_ERROR;
 }

/**
  Retrieve the data from a field as a specified ODBC C type.

  TODO arrec->indicator_ptr could be different than pcbValue
  ideally, two separate pointers would be passed here

  @param[in]  stmt        Handle of statement
  @param[in]  fCType      ODBC C type to return data as
  @param[in]  field       Field describing the type of the data
  @param[out] rgbValue    Pointer to buffer for returning data
  @param[in]  cbValueMax  Length of buffer
  @param[out] pcbValue    Bytes used in the buffer, or SQL_NULL_DATA
  @param[out] value       The field data to be converted and returned
  @param[in]  length      Length of value
  @param[in]  arrec       ARD record for this column (can be NULL)
*/
static SQLRETURN SQL_API
sql_get_data(STMT *stmt, SQLSMALLINT fCType, MYSQL_FIELD *field,
             SQLPOINTER rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue,
             char *value, uint length, DESCREC *arrec)
{
  SQLLEN    tmp;
  long long numericValue;
  my_bool   convert= 1;

  /* get the exact type if we don't already have it */
  if (fCType == SQL_C_DEFAULT)
  {
    fCType= unireg_to_c_datatype(field);
    if (!cbValueMax)
      cbValueMax= bind_length(fCType, 0);
  }
  else if (fCType == SQL_ARD_TYPE)
  {
    if (!arrec)
      return set_stmt_error(stmt, "07009", "Invalid descriptor index", 0);
    fCType= arrec->concise_type;
  }

  /* set prec and scale for numeric */
  if (fCType == SQL_C_NUMERIC && rgbValue)
  {
    SQL_NUMERIC_STRUCT *sqlnum= (SQL_NUMERIC_STRUCT *) rgbValue;
    if (arrec) /* normally set via ard */
    {
      sqlnum->precision= (SQLSCHAR) arrec->precision;
      sqlnum->scale= (SQLCHAR) arrec->scale;
    }
    else /* just take the defaults */
    {
      sqlnum->precision= 38;
      sqlnum->scale= 0;
    }
  }

  if (!value)
  {
    /* pcbValue must be available if its NULL */
    if (!pcbValue)
      return set_stmt_error(stmt,"22002",
                            "Indicator variable required but not supplied",0);

    *pcbValue= SQL_NULL_DATA;
  }
  else
  {
    if (!odbc_supported_conversion(get_sql_data_type(stmt, field, 0), fCType)
     && !driver_supported_conversion(field,fCType))
    {
      return set_stmt_error(stmt, "07009", "Conversion is not possible", 0);
    }

    if (!pcbValue)
      pcbValue= &tmp; /* Easier code */

    if (field->type == MYSQL_TYPE_BIT)
    {
      if (is_binary_ctype(fCType))
      {
        return copy_binary_result(stmt, (SQLCHAR *)rgbValue, cbValueMax
          , pcbValue, field , value , length);
      }
      else
      {
        binary2numeric(&numericValue, value, length);
        convert= 0;
      }
    }

    switch (fCType) {
    case SQL_C_CHAR:
      /* Handle BLOB -> CHAR conversion */
      if ((field->flags & (BLOB_FLAG|BINARY_FLAG)) == (BLOB_FLAG|BINARY_FLAG))
        return copy_binhex_result(stmt,
                                  (SQLCHAR *)rgbValue, cbValueMax, pcbValue,
                                  field, value, length);
      /* fall through */

    case SQL_C_BINARY:
      {
        char buff[21];
        if (field->type == MYSQL_TYPE_TIMESTAMP && length != 19)
        {
          /* Convert MySQL timestamp to full ANSI timestamp format. */
          char *pos;
          uint i;
          if (length == 6 || length == 10 || length == 12)
          {
            /* For two-digit year, < 60 is considered after Y2K */
            if (value[0] <= '6')
            {
              buff[0]= '2';
              buff[1]= '0';
            }
            else
            {
              buff[0]= '1';
              buff[1]= '9';
            }
          }
          else
          {
            buff[0]= value[0];
            buff[1]= value[1];
            value+= 2;
            length-= 2;
          }
          buff[2]= *value++;
          buff[3]= *value++;
          buff[4]= '-';
          if (value[0] == '0' && value[1] == '0')
          {
            /* Month was 0, which ODBC can't handle. */
            *pcbValue= SQL_NULL_DATA;
            break;
          }
          pos= buff+5;
          length&= 30;  /* Ensure that length is ok */
          for (i= 1, length-= 2; (int)length > 0; length-= 2, ++i)
          {
            *pos++= *value++;
            *pos++= *value++;
            *pos++= i < 2 ? '-' : (i == 2) ? ' ' : ':';
          }
          for ( ; pos != buff + 20; ++i)
          {
            *pos++= '0';
            *pos++= '0';
            *pos++= i < 2 ? '-' : (i == 2) ? ' ' : ':';
          }
          value= buff;
          length= 19;
        }

        if (fCType == SQL_C_BINARY)
          return copy_binary_result(stmt, (SQLCHAR *)rgbValue, cbValueMax,
                                    pcbValue, field, value, length);
        else
          return copy_ansi_result(stmt, (SQLCHAR *)rgbValue, cbValueMax,
                                  pcbValue, field, value, length);
      }

    case SQL_C_WCHAR:
      return copy_wchar_result(stmt,
                               (SQLWCHAR *)rgbValue,
                               (SQLINTEGER)(cbValueMax / sizeof(SQLWCHAR)), pcbValue,
                               field, value, length);

    case SQL_C_BIT:
      if (rgbValue)
      {
        /* for MySQL bit(n>1) 1st byte may be '\0'. So testing already converted
           to a number value or atoi for other types. */
        if (!convert)
          *((char *)rgbValue)= numericValue > 0 ? '\1' : '\0';
        else
          *((char *)rgbValue)= atoi(value) > 0 ? '\1' : '\0';
      }
      *pcbValue= 1;
      break;

    case SQL_C_TINYINT:
    case SQL_C_STINYINT:
      if (rgbValue)
        *((SQLSCHAR *)rgbValue)= (SQLSCHAR)(convert
                                            ? atoi(value)
                                            : (numericValue & (SQLSCHAR)(-1)));
      *pcbValue= 1;
      break;

    case SQL_C_UTINYINT:
      if (rgbValue)
        *((SQLCHAR *)rgbValue)= (SQLCHAR)(unsigned int)(convert
                                             ? atoi(value)
                                             : (numericValue & (SQLCHAR)(-1)));
      *pcbValue= 1;
      break;

    case SQL_C_SHORT:
    case SQL_C_SSHORT:
      if (rgbValue)
        *((SQLSMALLINT *)rgbValue)= (SQLSMALLINT)(convert
                                         ? atoi(value)
                                         : (numericValue & (SQLUSMALLINT)(-1)));
      *pcbValue= sizeof(SQLSMALLINT);
      break;

    case SQL_C_USHORT:
      if (rgbValue)
        *((SQLUSMALLINT *)rgbValue)= (SQLUSMALLINT)(uint)(convert
                                          ? atol(value)
                                          : (numericValue & (SQLUSMALLINT)(-1)));
      *pcbValue= sizeof(SQLUSMALLINT);
      break;

    case SQL_C_LONG:
    case SQL_C_SLONG:
      if (rgbValue)
      {
        /* Check if it could be a date...... :) */
        if (convert)
          if (length >= 10 && value[4] == '-' && value[7] == '-' &&
               (!value[10] || value[10] == ' '))
          {
            *((SQLINTEGER *)rgbValue)= ((SQLINTEGER) atol(value) * 10000L +
                                        (SQLINTEGER) atol(value + 5) * 100L +
                                        (SQLINTEGER) atol(value + 8));
          }
          else
            *((SQLINTEGER *)rgbValue)= (SQLINTEGER) atol(value);
        else
          *((SQLINTEGER *)rgbValue)= (SQLINTEGER)(numericValue
                                                  & (SQLUINTEGER)(-1));
      }
      *pcbValue= sizeof(SQLINTEGER);
      break;

    case SQL_C_ULONG:
      if (rgbValue)
        *((SQLUINTEGER *)rgbValue)= (SQLUINTEGER)(convert
                                            ? strtoul(value, NULL, 10)
                                            : numericValue & (SQLUINTEGER)(-1));
      *pcbValue= sizeof(SQLUINTEGER);
      break;

    case SQL_C_FLOAT:
      if (rgbValue)
        *((float *)rgbValue)= (float)(convert ? atof(value)
                                              : numericValue & (int)(-1));
      *pcbValue= sizeof(float);
      break;

    case SQL_C_DOUBLE:
      if (rgbValue)
        *((double *)rgbValue)= (double)(convert ? strtod(value, NULL)
                                                : numericValue);
      *pcbValue= sizeof(double);
      break;

    case SQL_C_DATE:
    case SQL_C_TYPE_DATE:
      {
        SQL_DATE_STRUCT tmp_date;
        if (!rgbValue)
          rgbValue= (char *)&tmp_date;
        if (!str_to_date((SQL_DATE_STRUCT *)rgbValue, value,
                         length, stmt->dbc->ds->zero_date_to_min))
          *pcbValue= sizeof(SQL_DATE_STRUCT);
        else
          *pcbValue= SQL_NULL_DATA;  /* ODBC can't handle 0000-00-00 dates */
        break;
      }

    case SQL_C_TIME:
    case SQL_C_TYPE_TIME:
      if (field->type == MYSQL_TYPE_TIMESTAMP ||
          field->type == MYSQL_TYPE_DATETIME)
      {
        SQL_TIMESTAMP_STRUCT ts;
        if (str_to_ts(&ts, value, stmt->dbc->ds->zero_date_to_min))
          *pcbValue= SQL_NULL_DATA;
        else
        {
          SQL_TIME_STRUCT *time_info= (SQL_TIME_STRUCT *)rgbValue;

          if (time_info)
          {
            time_info->hour=   ts.hour;
            time_info->minute= ts.minute;
            time_info->second= ts.second;
          }
          *pcbValue= sizeof(TIME_STRUCT);
        }
      }
      else if (field->type == MYSQL_TYPE_DATE)
      {
        SQL_TIME_STRUCT *time_info= (SQL_TIME_STRUCT *)rgbValue;

        if (time_info)
        {
          time_info->hour=   0;
          time_info->minute= 0;
          time_info->second= 0;
        }
        *pcbValue= sizeof(TIME_STRUCT);
      }
      else
      {
        SQL_TIME_STRUCT ts;
        if (str_to_time_st(&ts, value))
          *pcbValue= SQL_NULL_DATA;
        else
        {
          SQL_TIME_STRUCT *time_info= (SQL_TIME_STRUCT *)rgbValue;

          if (time_info)
          {
            time_info->hour=   ts.hour;
            time_info->minute= ts.minute;
            time_info->second= ts.second;
          }
          *pcbValue= sizeof(TIME_STRUCT);
        }
      }
      break;

    case SQL_C_TIMESTAMP:
    case SQL_C_TYPE_TIMESTAMP:
      if (field->type == MYSQL_TYPE_TIME)
      {
        SQL_TIME_STRUCT ts;

        if (str_to_time_st(&ts, value))
          *pcbValue= SQL_NULL_DATA;
        else
        {
          SQL_TIMESTAMP_STRUCT *timestamp_info=
            (SQL_TIMESTAMP_STRUCT *)rgbValue;
          time_t sec_time= time(NULL);
          struct tm cur_tm;
          localtime_r(&sec_time, &cur_tm);

          timestamp_info->year=   1900 + cur_tm.tm_year;
          timestamp_info->month=  1 + cur_tm.tm_mon; /* January is 0 in tm */
          timestamp_info->day=    cur_tm.tm_mday;
          timestamp_info->hour=   ts.hour;
          timestamp_info->minute= ts.minute;
          timestamp_info->second= ts.second;
          timestamp_info->fraction= 0;
          *pcbValue= sizeof(SQL_TIMESTAMP_STRUCT);
        }
      }
      else
      {
        if (str_to_ts((SQL_TIMESTAMP_STRUCT *)rgbValue, value,
                      stmt->dbc->ds->zero_date_to_min))
          *pcbValue= SQL_NULL_DATA;
        else
          *pcbValue= sizeof(SQL_TIMESTAMP_STRUCT);
      }
      break;

    case SQL_C_SBIGINT:
      /** @todo This is not right. SQLBIGINT is not always longlong. */
      if (rgbValue)
        *((longlong *)rgbValue)= (longlong)(convert ? strtoll(value, NULL, 10)
                                                    : numericValue);
      *pcbValue= sizeof(longlong);
      break;

    case SQL_C_UBIGINT:
      /** @todo This is not right. SQLUBIGINT is not always ulonglong.  */
      if (rgbValue)
          *((ulonglong *)rgbValue)= (ulonglong)(convert
                                                ? strtoull(value, NULL, 10)
                                                : numericValue);
      *pcbValue= sizeof(ulonglong);
      break;

    case SQL_C_NUMERIC:
      {
        int overflow= 0;
        SQL_NUMERIC_STRUCT *sqlnum= (SQL_NUMERIC_STRUCT *) rgbValue;
        if (rgbValue)
        {
          if (convert)
            sqlnum_from_str(value, sqlnum, &overflow);
          else /* bit field */
          {
            /* Lazy way - converting number we have to a string.
               If it couldn't happen we have to scale/unscale number - we would
               just reverse binary data */
            char _value[21]; /* max string length of 64bit number */
            sprintf(_value, "%llu", numericValue);

            sqlnum_from_str(_value, sqlnum, &overflow);
          }

        }
        *pcbValue= sizeof(ulonglong);
        if (overflow)
          return set_stmt_error(stmt, "22003",
                                "Numeric value out of range", 0);
      }
      break;

    default:
      return set_error(stmt,MYERR_07006,
                       "Restricted data type attribute violation",0);
      break;
    }
  }

  if (stmt->getdata.source)  /* Second call to getdata */
    return SQL_NO_DATA_FOUND;

  stmt->getdata.source= NULL;         /* All data is retrieved */

  return SQL_SUCCESS;
}


/*!
    \brief  Returns true if we are dealing with a statement which
            is likely to result in reading only (SELECT || SHOW).

            Some ODBC calls require knowledge about a statement
            which we can not determine until we have executed 
            the statement. This is because we do not parse the SQL
            - the server does.

            However if we silently execute a pending statement we
            may insert rows.

            So we do a very crude check of the SQL here to reduce 
            the chance of a problem.

    \sa     BUG 5778            
*/
BOOL isStatementForRead( STMT FAR *stmt )
{
    char *pCursor;
    int n = 0;
    char szToken[55];

    if ( !stmt )
        return FALSE;

    if ( !stmt->query )
        return FALSE;

    /* eat up any space */
    for ( pCursor = stmt->query; pCursor != stmt->query_end && isspace( *pCursor ); )
    {
        ++pCursor; 
    }

    /* continue while alpha-numeric */
    for ( ; pCursor != stmt->query_end && !isspace( *pCursor ) && n < 50; )
    {
        szToken[n] = toupper( *pCursor );
        ++pCursor; 
        ++n;
    }

    szToken[n] = '\0';

    /* Took from Jess' "ssps rsmd" patch - "CALL" was missing here */
    if (!strcmp(szToken, "SELECT") || !strcmp(szToken, "SHOW") ||
        !strcmp(szToken, "CALL"))
        return TRUE;

    return FALSE;
}

/*
  @type    : myodbc3 internal
  @purpose : execute the query if it is only prepared. This is needed
  because the ODBC standard allows calling some functions
  before SQLExecute().
*/

static SQLRETURN check_result(STMT FAR *stmt )
{
    SQLRETURN error= 0;

    switch ( stmt->state )
    {
        case ST_UNKNOWN:
            error= set_stmt_error(stmt,"24000","Invalid cursor state",0);
            break;
        case ST_PREPARED:
            if ( isStatementForRead( stmt ) )
            {
                SQLULEN real_max_rows= stmt->stmt_options.max_rows;
                stmt->stmt_options.max_rows= 1;
                /* select limit will be restored back to max_rows before real execution */
                if ( (error= my_SQLExecute(stmt)) == SQL_SUCCESS )
                {
                    stmt->state= ST_PRE_EXECUTED;  /* mark for execute */
                }
                else
                {
                    set_sql_select_limit(stmt->dbc, real_max_rows);
                }
                stmt->stmt_options.max_rows= real_max_rows;
            }
            else
                error = SQL_SUCCESS;
            break;
        case ST_PRE_EXECUTED:
        case ST_EXECUTED:
            error= SQL_SUCCESS;
    }
    return(error);
}

/*
  @type    : myodbc3 internal
  @purpose : does the any open param binding
*/

SQLRETURN do_dummy_parambind(SQLHSTMT hstmt)
{
    SQLRETURN rc;
    STMT FAR *stmt= (STMT FAR *)hstmt;
    uint     nparam;

    for ( nparam= 0; nparam < stmt->param_count; ++nparam )
    {
        DESCREC *aprec= desc_get_rec(stmt->apd, nparam, TRUE);
        if (!aprec->par.real_param_done)
        {
            /* do the dummy bind temporarily to get the result set
               and once everything is done, remove it */
            if (!SQL_SUCCEEDED(rc= my_SQLBindParameter(hstmt, nparam+1,
                                                       SQL_PARAM_INPUT,
                                                       SQL_C_CHAR,
                                                       SQL_VARCHAR, 0, 0,
                                                       "NULL", SQL_NTS, NULL)))
                return rc;
            /* reset back to false (this is the *dummy* param bind) */
            aprec->par.real_param_done= FALSE;
        }
    }
    stmt->dummy_state= ST_DUMMY_PREPARED;
    return(SQL_SUCCESS);
}

/*
  @type    : ODBC 1.0 API
  @purpose : returns the number of columns in a result set
*/

SQLRETURN SQL_API SQLNumResultCols(SQLHSTMT  hstmt, SQLSMALLINT FAR *pccol)
{
    SQLRETURN error;
    STMT FAR *stmt= (STMT FAR*) hstmt;

    if ( stmt->param_count > 0 && stmt->dummy_state == ST_DUMMY_UNKNOWN &&
         (stmt->state != ST_PRE_EXECUTED || stmt->state != ST_EXECUTED) )
    {
        if ( do_dummy_parambind(hstmt) != SQL_SUCCESS )
            return SQL_ERROR;
    }
    if ( (error= check_result(stmt)) != SQL_SUCCESS )
        return error;

    if ( !stmt->result )
        *pccol= 0;      /* Not a select */
    else
        *pccol= stmt->result->field_count;

    return SQL_SUCCESS;
}


/**
  Get some basic properties of a column.

  @param[in]  hstmt      Statement handle
  @param[in]  column     Column number (starting with 1)
  @param[out] name       Pointer to column name
  @param[out] need_free  Whether the column name needs to be freed.
  @param[out] type       Column SQL type
  @param[out] size       Column size
  @param[out] scale      Scale
  @param[out] nullable   Whether the column is nullable
*/
SQLRETURN SQL_API
MySQLDescribeCol(SQLHSTMT hstmt, SQLUSMALLINT column,
                 SQLCHAR **name, SQLSMALLINT *need_free, SQLSMALLINT *type,
                 SQLULEN *size, SQLSMALLINT *scale, SQLSMALLINT *nullable)
{
  SQLRETURN error;
  STMT *stmt= (STMT *)hstmt;
  DESCREC* irrec;

  /* SQLDescribeCol can be called before SQLExecute. Thus we need make sure that
     all parameters have been bound */
  if ( stmt->param_count > 0 && stmt->dummy_state == ST_DUMMY_UNKNOWN &&
    (stmt->state != ST_PRE_EXECUTED || stmt->state != ST_EXECUTED) )
  {
    if ( do_dummy_parambind(hstmt) != SQL_SUCCESS )
      return SQL_ERROR;
  }

  if ((error= check_result(stmt)) != SQL_SUCCESS)
    return error;
  if (!stmt->result)
    return set_stmt_error(stmt, "07005", "No result set", 0);
  if (column == 0 || column > stmt->ird->count)
    return set_stmt_error(stmt, "07009", "Invalid descriptor index", 0);

  irrec= desc_get_rec(stmt->ird, column - 1, FALSE);
  assert(irrec);

  if (type)
    *type= irrec->concise_type;
  if (size)
    *size= irrec->length;
  if (scale)
    *scale= irrec->scale;
  if (nullable)
    *nullable= irrec->nullable;

  *need_free= 0;

  if (stmt->dbc->ds->return_table_names_for_SqlDescribeCol && irrec->table_name)
  {
    char *tmp= my_malloc(strlen((char *)irrec->name) +
                         strlen((char *)irrec->table_name) + 2,
                         MYF(0));
    if (!tmp)
    {
      *need_free= -1;
      *name= NULL;
    }
    else
    {
      strxmov(tmp, (char *)irrec->table_name, ".", (char *)irrec->name, NullS);
      *name= (SQLCHAR *)tmp;
      *need_free= 1;
    }
  }
  else
    *name= (SQLCHAR *)irrec->name;

  return SQL_SUCCESS;
}


/*
  Retrieve an attribute of a column in a result set.

  @param[in]  hstmt          Handle to statement
  @param[in]  column         The column to retrieve data for, indexed from 1
  @param[in]  attrib         The attribute to be retrieved
  @param[out] char_attr      Pointer to a string pointer for returning strings
                             (caller must make their own copy)
  @param[out] num_attr       Pointer to an integer to return the value if the
                             @a attrib corresponds to a numeric type

  @since ODBC 1.0
*/
SQLRETURN SQL_API
MySQLColAttribute(SQLHSTMT hstmt, SQLUSMALLINT column,
                  SQLUSMALLINT attrib, SQLCHAR **char_attr, SQLLEN *num_attr)
{
  STMT *stmt= (STMT *)hstmt;
  SQLLEN nparam= 0;
  SQLRETURN error= SQL_SUCCESS;
  DESCREC *irrec;

  /* MySQLColAttribute can be called before SQLExecute. Thus we need make sure that
  all parameters have been bound */
  if ( stmt->param_count > 0 && stmt->dummy_state == ST_DUMMY_UNKNOWN &&
    (stmt->state != ST_PRE_EXECUTED || stmt->state != ST_EXECUTED) )
  {
    if ( do_dummy_parambind(hstmt) != SQL_SUCCESS )
      return SQL_ERROR;
  }

  if (check_result(stmt) != SQL_SUCCESS)
    return SQL_ERROR;

  if (!stmt->result)
    return set_stmt_error(stmt, "07005", "No result set", 0);

  /* we report bookmark type if requested, nothing else */
  if (attrib == SQL_DESC_TYPE && column == 0)
  {
    *(SQLINTEGER *)num_attr= SQL_INTEGER;
    return SQL_SUCCESS;
  }

  if (column == 0 || column > stmt->ird->count)
    return set_error(hstmt,  MYERR_07009, NULL, 0);

  if (!num_attr)
    num_attr= &nparam;

  if ((error= check_result(stmt)) != SQL_SUCCESS)
    return error;

  if (attrib == SQL_DESC_COUNT || attrib == SQL_COLUMN_COUNT)
  {
    *num_attr= stmt->ird->count;
    return SQL_SUCCESS;
  }

  irrec= desc_get_rec(stmt->ird, column - 1, FALSE);
  assert(irrec);

  /*
     Map to descriptor fields. This approach is only valid
     for ODBC 3.0 API applications.

     @todo Add additional logic to properly handle these fields
           for ODBC 2.0 API applications.
  */
  switch (attrib)
  {
  case SQL_COLUMN_SCALE:
    attrib= SQL_DESC_SCALE;
    break;
  case SQL_COLUMN_PRECISION:
    attrib= SQL_DESC_PRECISION;
    break;
  case SQL_COLUMN_NULLABLE:
    attrib= SQL_DESC_NULLABLE;
    break;
  case SQL_COLUMN_LENGTH:
    attrib= SQL_DESC_OCTET_LENGTH;
    break;
  case SQL_COLUMN_NAME:
    attrib= SQL_DESC_NAME;
    break;
  }

  switch (attrib)
  {
  case SQL_DESC_AUTO_UNIQUE_VALUE:
  case SQL_DESC_CASE_SENSITIVE:
  case SQL_DESC_FIXED_PREC_SCALE:
  case SQL_DESC_NULLABLE:
  case SQL_DESC_NUM_PREC_RADIX:
  case SQL_DESC_PRECISION:
  case SQL_DESC_SCALE:
  case SQL_DESC_SEARCHABLE:
  case SQL_DESC_TYPE:
  case SQL_DESC_CONCISE_TYPE:
  case SQL_DESC_UNNAMED:
  case SQL_DESC_UNSIGNED:
  case SQL_DESC_UPDATABLE:
    error= stmt_SQLGetDescField(stmt, stmt->ird, column, attrib,
#ifdef USE_SQLCOLATTRIBUTE_SQLLEN_PTR
                                (SQLPOINTER)num_attr,SQL_IS_LEN,
#else
                                num_attr, SQL_IS_INTEGER,
#endif
               NULL);
    break;

  case SQL_DESC_DISPLAY_SIZE:
  case SQL_DESC_LENGTH:
  case SQL_DESC_OCTET_LENGTH:
    error= stmt_SQLGetDescField(stmt, stmt->ird, column, attrib,
                                num_attr, SQL_IS_LEN, NULL);
    break;

  /* We need support from server, when aliasing is there */
  case SQL_DESC_BASE_COLUMN_NAME:
    *char_attr= irrec->base_column_name ? irrec->base_column_name :
                                          (SQLCHAR *) "";
    break;

  case SQL_DESC_LABEL:
  case SQL_DESC_NAME:
    *char_attr= irrec->name;
    break;

  case SQL_DESC_BASE_TABLE_NAME:
    *char_attr= irrec->base_table_name ? irrec->base_table_name :
                                         (SQLCHAR *) "";
    break;

  case SQL_DESC_TABLE_NAME:
    *char_attr= irrec->table_name ? irrec->table_name : (SQLCHAR *) "";
    break;

  case SQL_DESC_CATALOG_NAME:
    *char_attr= irrec->catalog_name;
    break;

  case SQL_DESC_LITERAL_PREFIX:
    *char_attr= irrec->literal_prefix;
    break;

  case SQL_DESC_LITERAL_SUFFIX:
    *char_attr= irrec->literal_suffix;
    break;

  case SQL_DESC_SCHEMA_NAME:
    *char_attr= irrec->schema_name;
    break;

  case SQL_DESC_TYPE_NAME:
    *char_attr= irrec->type_name;
    break;

  /*
    Hack : Fix for the error from ADO 'rs.resync' "Key value for this row
    was changed or deleted at the data store.  The local row is now deleted.
    This should also fix some Multi-step generated error cases from ADO
  */
  case SQL_MY_PRIMARY_KEY: /* MSSQL extension !! */
    *(SQLINTEGER *)num_attr= ((irrec->row.field->flags & PRI_KEY_FLAG) ?
                              SQL_TRUE : SQL_FALSE);
    break;

  default:
    return set_stmt_error(stmt, "HY091",
                          "Invalid descriptor field identifier",0);
  }

  return error;
}


/*
  @type    : ODBC 1.0 API
  @purpose : binds application data buffers to columns in the result set
*/

SQLRETURN SQL_API SQLBindCol(SQLHSTMT      StatementHandle, 
                             SQLUSMALLINT  ColumnNumber,
                             SQLSMALLINT   TargetType, 
                             SQLPOINTER    TargetValuePtr,
                             SQLLEN        BufferLength, 
                             SQLLEN *      StrLen_or_IndPtr)
{
  SQLRETURN rc;
  STMT FAR *stmt= (STMT FAR*) StatementHandle;
  DESCREC *arrec;
  /* TODO if this function fails, the SQL_DESC_COUNT should be unchanged in ard */

  CLEAR_STMT_ERROR(stmt);

  if (!TargetValuePtr && !StrLen_or_IndPtr) /* Handling unbinding */
  {
    /*
       If unbinding the last bound column, we reduce the
       ARD records until the highest remaining bound column.
    */
    if (ColumnNumber == stmt->ard->count)
    {
      int i;
      --stmt->ard->count;
      for (i= (int)stmt->ard->count - 1; i >= 0; --i)
      {
        arrec= desc_get_rec(stmt->ard, i, FALSE);
        if (ARD_IS_BOUND(arrec))
          break;
        else
          --stmt->ard->count;
      }
    }
    else
    {
      arrec= desc_get_rec(stmt->ard, ColumnNumber - 1, FALSE);
      if (arrec)
      {
        arrec->data_ptr= NULL;
        arrec->octet_length_ptr= NULL;
      }
    }
    return SQL_SUCCESS;
  }

  if (ColumnNumber == 0 || (stmt->state == ST_EXECUTED &&
                            ColumnNumber > stmt->ird->count))
  {
    return set_stmt_error(stmt, "07009", "Invalid descriptor index",
                          MYERR_07009);
  }

  arrec= desc_get_rec(stmt->ard, ColumnNumber - 1, TRUE);

  if ((rc= stmt_SQLSetDescField(stmt, stmt->ard, ColumnNumber,
                                SQL_DESC_CONCISE_TYPE,
                                (SQLPOINTER)(SQLINTEGER) TargetType,
                                SQL_IS_SMALLINT)) != SQL_SUCCESS)
    return rc;
  if ((rc= stmt_SQLSetDescField(stmt, stmt->ard, ColumnNumber,
                                SQL_DESC_OCTET_LENGTH,
                                (SQLPOINTER) bind_length(TargetType,
                                                         BufferLength),
                                SQL_IS_LEN)) != SQL_SUCCESS)
    return rc;
  if ((rc= stmt_SQLSetDescField(stmt, stmt->ard, ColumnNumber,
                                SQL_DESC_DATA_PTR, TargetValuePtr,
                                SQL_IS_POINTER)) != SQL_SUCCESS)
    return rc;
  if ((rc= stmt_SQLSetDescField(stmt, stmt->ard, ColumnNumber,
                                SQL_DESC_INDICATOR_PTR, StrLen_or_IndPtr,
                                SQL_IS_POINTER)) != SQL_SUCCESS)
    return rc;
  if ((rc= stmt_SQLSetDescField(stmt, stmt->ard, ColumnNumber,
                                SQL_DESC_OCTET_LENGTH_PTR, StrLen_or_IndPtr,
                                SQL_IS_POINTER)) != SQL_SUCCESS)
    return rc;

  return SQL_SUCCESS;
}


/*
  @type    : myodbc3 internal
  @purpose : returns the latest resultset(dynamic)
*/

my_bool set_dynamic_result(STMT FAR *stmt)
{
  SQLRETURN rc;
  long row= stmt->current_row;
  uint rows= stmt->rows_found_in_set;

  rc= my_SQLExecute(stmt);

  stmt->current_row= row;
  stmt->rows_found_in_set= rows;

  if (SQL_SUCCEEDED(rc))
    set_current_cursor_data(stmt,0);

  return rc != 0;
}


/*
  @type    : ODBC 1.0 API
  @purpose : retrieves data for a single column in the result set. It can
  be called multiple times to retrieve variable-length data
  in parts
*/

SQLRETURN SQL_API SQLGetData(SQLHSTMT      StatementHandle,
                             SQLUSMALLINT  ColumnNumber,
                             SQLSMALLINT   TargetType,
                             SQLPOINTER    TargetValuePtr,
                             SQLLEN        BufferLength,
                             SQLLEN *      StrLen_or_IndPtr)
{
    STMT *stmt= (STMT *) StatementHandle;
    SQLRETURN result;
    uint length= 0;
    DESCREC *irrec;

    if (!stmt->result || !stmt->current_values)
    {
      set_stmt_error(stmt,"24000","SQLGetData without a preceding SELECT",0);
      return SQL_ERROR;
    }

    if (ColumnNumber < 1 || ColumnNumber > stmt->ird->count)
    {
      return set_stmt_error(stmt, "07009", "Invalid descriptor index",
                            MYERR_07009);
    }
    --ColumnNumber;     /* Easier code if start from 0 */
    if (ColumnNumber != stmt->getdata.column)
    {
      /* New column. Reset old offset */
      reset_getdata_position(stmt);
      stmt->getdata.column= ColumnNumber;
    }

    irrec= desc_get_rec(stmt->ird, ColumnNumber, FALSE);
    assert(irrec);

    /* catalog functions with "fake" results won't have lengths */
    length= irrec->row.datalen;
    if (!length && stmt->current_values[ColumnNumber])
      length= strlen(stmt->current_values[ColumnNumber]);

    if (!stmt->dbc->ds->dont_use_set_locale)
      setlocale(LC_NUMERIC, "C");

    result= sql_get_data(stmt, TargetType, irrec->row.field,
                         TargetValuePtr, BufferLength, StrLen_or_IndPtr,
                         stmt->current_values[ColumnNumber], length,
                         desc_get_rec(stmt->ard, ColumnNumber, FALSE));

    if (!stmt->dbc->ds->dont_use_set_locale)
        setlocale(LC_NUMERIC,default_locale);

    return result;
}


/*
  @type    : ODBC 1.0 API
  @purpose : determines whether more results are available on a statement
  containing SELECT, UPDATE, INSERT, or DELETE statements and,
  if so, initializes processing for those results
*/

SQLRETURN SQL_API SQLMoreResults( SQLHSTMT hStmt )
{
    STMT FAR *  pStmt   = (STMT FAR*)hStmt;
    int         nRetVal;
    SQLRETURN   nReturn = SQL_SUCCESS;

    pthread_mutex_lock( &pStmt->dbc->lock );

    CLEAR_STMT_ERROR( pStmt );

    if (!mysql_more_results(&pStmt->dbc->mysql))
    {
      nReturn= SQL_NO_DATA;
      goto exitSQLMoreResults;
    }

    /* SQLExecute or SQLExecDirect need to be called first */
    if ( pStmt->state != ST_EXECUTED )
    {
        nReturn = set_stmt_error( pStmt, "HY010", NULL, 0 );
        goto exitSQLMoreResults;
    }

    /* try to get next resultset */
    nRetVal = mysql_next_result( &pStmt->dbc->mysql );

    /* call to mysql_next_result() failed */
    if ( nRetVal > 0 )
    {
        nRetVal = mysql_errno( &pStmt->dbc->mysql );
        switch ( nRetVal )
        {
            case CR_SERVER_GONE_ERROR:
            case CR_SERVER_LOST:
                nReturn = set_stmt_error( pStmt, "08S01", mysql_error( &pStmt->dbc->mysql ), nRetVal );
                goto exitSQLMoreResults;
            case CR_COMMANDS_OUT_OF_SYNC:
            case CR_UNKNOWN_ERROR:
                nReturn = set_stmt_error( pStmt, "HY000", mysql_error( &pStmt->dbc->mysql ), nRetVal );
                goto exitSQLMoreResults;
            default:
                nReturn = set_stmt_error( pStmt, "HY000", "unhandled error from mysql_next_result()", nRetVal );
                goto exitSQLMoreResults;
        }
    }

    /* no more resultsets */
    if ( nRetVal < 0 )
    {
        nReturn = SQL_NO_DATA;
        goto exitSQLMoreResults;
    }

    /* cleanup existing resultset */
    nReturn = my_SQLFreeStmtExtended((SQLHSTMT)pStmt,SQL_CLOSE,0);
    if ( !SQL_SUCCEEDED( nReturn ) )
        goto exitSQLMoreResults;

    /* start using the new resultset */
    if ( if_forward_cache( pStmt ) )
        pStmt->result = mysql_use_result( &pStmt->dbc->mysql );
    else
        pStmt->result = mysql_store_result( &pStmt->dbc->mysql );

    if ( !pStmt->result )
    {
        /* no fields means; INSERT, UPDATE or DELETE so no resultset is fine */
        if ( !mysql_field_count( &pStmt->dbc->mysql ) )
        {
            pStmt->state = ST_EXECUTED;
            pStmt->affected_rows = mysql_affected_rows( &pStmt->dbc->mysql );
            goto exitSQLMoreResults;
        }
        /* we have fields but no resultset (not even an empty one) - this is bad */
        nReturn = set_stmt_error( pStmt, "HY000", mysql_error( &pStmt->dbc->mysql ), mysql_errno( &pStmt->dbc->mysql ) );
        goto exitSQLMoreResults;
    }
    fix_result_types( pStmt );

exitSQLMoreResults:
    pthread_mutex_unlock( &pStmt->dbc->lock );
    return nReturn;
}


/*
  @type    : ODBC 1.0 API
  @purpose : returns the number of rows affected by an UPDATE, INSERT,
  or DELETE statement;an SQL_ADD, SQL_UPDATE_BY_BOOKMARK,
  or SQL_DELETE_BY_BOOKMARK operation in SQLBulkOperations;
  or an SQL_UPDATE or SQL_DELETE operation in SQLSetPos
*/

SQLRETURN SQL_API SQLRowCount( SQLHSTMT hstmt, 
                               SQLLEN * pcrow )
{
    STMT FAR *stmt= (STMT FAR*) hstmt;

    if ( stmt->result )
    {
        *pcrow= (SQLLEN) mysql_affected_rows(&stmt->dbc->mysql);
    }
    else
    {
        *pcrow= (SQLLEN) stmt->affected_rows;
    }
    return SQL_SUCCESS;
}


/**
  Populate the data lengths in the IRD for the current row

  @param[in]  ird         IRD to populate
  @param[in]  lengths     Data lengths from mysql_fetch_lengths()
  @param[in]  fields      Number of fields
*/
static void fill_ird_data_lengths(DESC *ird, ulong *lengths, uint fields)
{
  uint i;
  DESCREC *irrec;

  assert(fields == ird->count);

  /* This will be NULL for catalog functions with "fake" results */
  if (!lengths)
    return;

  for (i= 0; i < fields; ++i)
  {
    irrec= desc_get_rec(ird, i, FALSE);
    assert(irrec);

    irrec->row.datalen= lengths[i];
  }
}


/**
  Populate a single row of fetch buffers

  @param[in]  stmt        Handle of statement
  @param[in]  values      Row buffers from libmysql
  @param[in]  rownum      Row number of current fetch block
*/
static SQLRETURN
fill_fetch_buffers(STMT *stmt, MYSQL_ROW values, uint rownum)
{
  SQLRETURN res= SQL_SUCCESS, tmp_res;
  int i;
  uint length= 0;
  DESCREC *irrec, *arrec;

  for (i= 0; i < myodbc_min(stmt->ird->count, stmt->ard->count); ++i, ++values)
  {
    irrec= desc_get_rec(stmt->ird, i, FALSE);
    arrec= desc_get_rec(stmt->ard, i, FALSE);
    assert(irrec && arrec);

    if (ARD_IS_BOUND(arrec))
    {
      SQLLEN offset, pcb_offset;
      SQLLEN *pcbValue= NULL;
      SQLPOINTER TargetValuePtr= NULL;

      if (stmt->ard->bind_type == SQL_BIND_BY_COLUMN)
      {
        offset= arrec->octet_length * rownum;
        pcb_offset= sizeof(SQLLEN) * rownum;
      }
      else
        pcb_offset= offset= stmt->ard->bind_type * rownum;

      /* apply SQL_ATTR_ROW_BIND_OFFSET_PTR */
      if (stmt->ard->bind_offset_ptr)
      {
        offset     += *stmt->ard->bind_offset_ptr;
        pcb_offset += *stmt->ard->bind_offset_ptr;
      }

      reset_getdata_position(stmt);

      if (arrec->data_ptr)
        TargetValuePtr= ((char*) arrec->data_ptr) + offset;

      /* catalog functions with "fake" results won't have lengths */
      length= irrec->row.datalen;
      if (!length && *values)
        length= strlen(*values);

      /* We need to pass that pointer to the sql_get_data so it could detect
         22002 error - for NULL values that pointer has to be supplied by user.
       */
      if (arrec->octet_length_ptr)
      {
        pcbValue= arrec->octet_length_ptr + (pcb_offset / sizeof(SQLLEN));
      }

      tmp_res= sql_get_data(stmt, arrec->concise_type, irrec->row.field,
                            TargetValuePtr, arrec->octet_length, pcbValue,
                            *values, length, arrec);
      if (tmp_res != SQL_SUCCESS)
      {
        if (tmp_res == SQL_SUCCESS_WITH_INFO)
        {
          if (res == SQL_SUCCESS)
            res= tmp_res;
        }
        else
          res= SQL_ERROR;
      }
    }
  }

  return res;
}


/*
  @type    : myodbc3 internal
  @purpose : fetches the specified rowset of data from the result set and
  returns data for all bound columns. Rowsets can be specified
  at an absolute or relative position
*/
SQLRETURN SQL_API my_SQLExtendedFetch( SQLHSTMT             hstmt,
                                       SQLUSMALLINT         fFetchType,
                                       SQLLEN               irow,
                                       SQLULEN             *pcrow,
                                       SQLUSMALLINT FAR    *rgfRowStatus,
                                       my_bool              upd_status )
{
    SQLULEN           rows_to_fetch;
    long              cur_row, max_row;
    SQLULEN           i;
    SQLRETURN         row_res, res;
    STMT FAR          *stmt= (STMT FAR*) hstmt;
    MYSQL_ROW         values= 0;
    MYSQL_ROW_OFFSET  save_position;
    SQLULEN           dummy_pcrow;
    BOOL              disconnected= FALSE;

    LINT_INIT(save_position);

    if ( !stmt->result )
        return set_stmt_error(stmt, "24000", "Fetch without a SELECT", 0);

    cur_row = stmt->current_row;

    if ( stmt->stmt_options.cursor_type == SQL_CURSOR_FORWARD_ONLY )
    {
        if ( fFetchType != SQL_FETCH_NEXT && !stmt->dbc->ds->safe )
            return  set_error(stmt,MYERR_S1106,
                              "Wrong fetchtype with FORWARD ONLY cursor", 0);
    }

    if ( if_dynamic_cursor(stmt) && set_dynamic_result(stmt) )
        return set_error(stmt,MYERR_S1000,
                         "Driver Failed to set the internal dynamic result", 0);

    if ( !pcrow )
        pcrow= &dummy_pcrow;

    max_row= (long) mysql_num_rows(stmt->result);
    reset_getdata_position(stmt);
    stmt->current_values= 0;          /* For SQLGetData */

    switch ( fFetchType )
    {
        case SQL_FETCH_NEXT:
            cur_row= (stmt->current_row < 0 ? 0 :
                      stmt->current_row+stmt->rows_found_in_set);
            break;
        case SQL_FETCH_PRIOR:
            cur_row= (stmt->current_row <= 0 ? -1 :
                      (long)(stmt->current_row - stmt->ard->array_size));
            break;
        case SQL_FETCH_FIRST:
            cur_row= 0L;
            break;
        case SQL_FETCH_LAST:
            cur_row= max_row - stmt->ard->array_size;
            break;
        case SQL_FETCH_ABSOLUTE:
            if ( irow < 0 )
            {
                /* Fetch from end of result set */
                if ( max_row+irow < 0 && -irow <= (long) stmt->ard->array_size )
                {
                    /*
                      | FetchOffset | > LastResultRow AND
                      | FetchOffset | <= RowsetSize
                    */
                    cur_row= 0;     /* Return from beginning */
                }
                else
                    cur_row= max_row+irow;     /* Ok if max_row <= -irow */
            }
            else
                cur_row= (long) irow-1;
            break;

        case SQL_FETCH_RELATIVE:
            cur_row= stmt->current_row + irow;
            if ( stmt->current_row > 0 && cur_row < 0 &&
                 (long)-irow <= (long)stmt->ard->array_size )
                cur_row= 0;
            break;

        default:
            return set_error(stmt, MYERR_S1106, "Fetch type out of range", 0);
    }

    if ( cur_row < 0 )
    {
        stmt->current_row= -1;  /* Before first row */
        stmt->rows_found_in_set= 0;
        mysql_data_seek(stmt->result,0L);
        return SQL_NO_DATA_FOUND;
    }
    if ( cur_row > max_row )
        cur_row= max_row;

    if ( !stmt->result_array && !if_forward_cache(stmt) )
    {
        /*
          If Dynamic, it loses the stmt->end_of_set, so
          seek to desired row, might have new data or
          might be deleted
        */
        if ( stmt->stmt_options.cursor_type != SQL_CURSOR_DYNAMIC &&
             cur_row && cur_row == (long)(stmt->current_row +
                                          stmt->rows_found_in_set) )
            mysql_row_seek(stmt->result,stmt->end_of_set);
        else
            mysql_data_seek(stmt->result,cur_row);
    }
    stmt->current_row= cur_row;

    if (if_forward_cache(stmt) && !stmt->result_array)
      rows_to_fetch= stmt->ard->array_size;
    else
      rows_to_fetch= myodbc_min(max_row-cur_row,
                                (long)stmt->ard->array_size);

    if ( !rows_to_fetch )
    {
        *pcrow= 0;
        stmt->rows_found_in_set= 0;
        if ( upd_status && stmt->ird->rows_processed_ptr )
        {
            *stmt->ird->rows_processed_ptr= 0;
        }
        return SQL_NO_DATA_FOUND;
    }

    if (!stmt->dbc->ds->dont_use_set_locale)
    {
      setlocale(LC_NUMERIC, "C");
    }

    res= SQL_SUCCESS;
    for (i= 0 ; i < rows_to_fetch ; ++i)
    {
        if ( stmt->result_array )
        {
            values= stmt->result_array+cur_row*stmt->result->field_count;
            if ( i == 0 )
            {
                stmt->current_values= values;
            }
        }
        else
        {
            /* This code will ensure that values is always set */
            if ( i == 0 )
            {
                save_position= mysql_row_tell(stmt->result);
            }
            if ( !(values= mysql_fetch_row(stmt->result)) )
            {
                break;
            }
            if ( stmt->fix_fields )
            {
                values= (*stmt->fix_fields)(stmt,values);
            }
            stmt->current_values= values;
        }

        if (!stmt->fix_fields)
        {
          /* lengths contains lengths for all rows. Alternate use could be
             filling ird buffers in the (fix_fields) function. In this case
             lengths could contain just one array with rules for lengths
             calculating(it can work out in many cases like in catalog functions
             there some fields from results of auxiliary query are simply mixed
             somehow and constant fields added ).
             Another approach could be using of "array" and "order" arrays
             and special fix_fields callback, that will fix array and set
             lengths in ird*/
          if (stmt->lengths)
            fill_ird_data_lengths(stmt->ird, stmt->lengths + cur_row*stmt->result->field_count,
                                  stmt->result->field_count);
          else
            fill_ird_data_lengths(stmt->ird, mysql_fetch_lengths(stmt->result),
                                  stmt->result->field_count);
        }
        row_res= fill_fetch_buffers(stmt, values, i);

        /* For SQL_SUCCESS we need all rows to be SQL_SUCCESS */
        if (res != row_res)
        {
          /* Any successful row makes overall result SQL_SUCCESS_WITH_INFO */
          if (SQL_SUCCEEDED(row_res))
          {
            res= SQL_SUCCESS_WITH_INFO;
          }
          /* Else error */
          else if (i == 0)
          {
            /* SQL_ERROR only if all rows fail */
            res= SQL_ERROR;
          }
          else
          {
            res= SQL_SUCCESS_WITH_INFO;
          }
        }

        /* "Fetching" includes buffers filling. I think errors in that 
           have to affect row status */

        if (rgfRowStatus)
        {
          rgfRowStatus[i]= sqlreturn2row_status(row_res);
        }
        /*
          No need to update rowStatusPtr_ex, it's the same as rgfRowStatus.
        */
        if (upd_status && stmt->ird->array_status_ptr)
        {
          stmt->ird->array_status_ptr[i]= sqlreturn2row_status(row_res);
        }

        ++cur_row;
    }   /* fetching cycle end*/

    stmt->rows_found_in_set= i;
    *pcrow= i;

    disconnected= is_connection_lost(mysql_errno(&stmt->dbc->mysql))
        && handle_connection_error(stmt);

    if ( upd_status && stmt->ird->rows_processed_ptr )
    {
        *stmt->ird->rows_processed_ptr= i;
    }

    /* It is possible that both rgfRowStatus and array_status_ptr are set
    (and upp_status is TRUE) */
    for ( ; i < stmt->ard->array_size ; ++i )
    {
        if ( rgfRowStatus )
        {
          rgfRowStatus[i]= disconnected ? SQL_ROW_ERROR : SQL_ROW_NOROW;
        }
        /*
          No need to update rowStatusPtr_ex, it's the same as rgfRowStatus.
        */
        if ( upd_status && stmt->ird->array_status_ptr )
        {
          stmt->ird->array_status_ptr[i]= disconnected? SQL_ROW_ERROR
                                                      : SQL_ROW_NOROW;
        }
    }

    if (SQL_SUCCEEDED(res) && !stmt->result_array && !if_forward_cache(stmt))
    {
        /* reset result position */
        stmt->end_of_set= mysql_row_seek(stmt->result,save_position);
    }

    if (!stmt->dbc->ds->dont_use_set_locale)

        setlocale(LC_NUMERIC,default_locale);

    if (SQL_SUCCEEDED(res)
      && stmt->rows_found_in_set < stmt->ard->array_size)
    {
      if (disconnected)
      {
        return SQL_ERROR;
      }
      else if (stmt->rows_found_in_set == 0)
      {
        return SQL_NO_DATA_FOUND;
      }
    }

    return res;
}


/*
  @type    : ODBC 1.0 API
  @purpose : fetches the specified rowset of data from the result set and
  returns data for all bound columns. Rowsets can be specified
  at an absolute or relative position
*/

SQLRETURN SQL_API SQLExtendedFetch( SQLHSTMT        hstmt,
                                    SQLUSMALLINT    fFetchType,
                                    SQLLEN          irow,
                                    SQLULEN        *pcrow,
                                    SQLUSMALLINT FAR *rgfRowStatus )
{
    SQLRETURN rc;
    SQLULEN rows;
    STMT_OPTIONS *options= &((STMT FAR *)hstmt)->stmt_options;

    options->rowStatusPtr_ex= rgfRowStatus;

    rc= my_SQLExtendedFetch(hstmt, fFetchType, irow, &rows, rgfRowStatus, 1);
    if (pcrow)
      *pcrow= (SQLULEN) rows;

    return rc;
}


/*
  @type    : ODBC 3.0 API
  @purpose : fetches the specified rowset of data from the result set and
  returns data for all bound columns. Rowsets can be specified
  at an absolute or relative position
*/

SQLRETURN SQL_API SQLFetchScroll( SQLHSTMT      StatementHandle,
                                  SQLSMALLINT   FetchOrientation,
                                  SQLLEN        FetchOffset )
{
    STMT *stmt = (STMT *)StatementHandle;
    STMT_OPTIONS *options= &stmt->stmt_options;

    options->rowStatusPtr_ex= NULL;

    return my_SQLExtendedFetch(StatementHandle, FetchOrientation, FetchOffset,
                               stmt->ird->rows_processed_ptr, stmt->ird->array_status_ptr,
                               0);
}

/*
  @type    : ODBC 1.0 API
  @purpose : fetches the next rowset of data from the result set and
  returns data for all bound columns
*/

SQLRETURN SQL_API SQLFetch(SQLHSTMT StatementHandle)
{
    STMT *stmt = (STMT *)StatementHandle;
    STMT_OPTIONS *options= &stmt->stmt_options;

    options->rowStatusPtr_ex= NULL;

    return my_SQLExtendedFetch(StatementHandle, SQL_FETCH_NEXT, 0,
                               stmt->ird->rows_processed_ptr, stmt->ird->array_status_ptr,
                               0);
}