forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvtkMySQLQuery.cxx
1171 lines (981 loc) · 31 KB
/
vtkMySQLQuery.cxx
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
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMySQLQuery.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkMySQLQuery.h"
#include "vtkMySQLDatabase.h"
#include "vtkMySQLDatabasePrivate.h"
#include "vtkObjectFactory.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include <mysql.h>
#include <errmsg.h>
#if defined(WIN32)
# include <string.h>
# include <locale.h>
# define LOWERCASE_COMPARE _stricmp
#else
# include <strings.h>
# define LOWERCASE_COMPARE strcasecmp
#endif
#include <assert.h>
#include <vtksys/ios/sstream>
#include <vtksys/stl/vector>
/*
* Bound Parameters and MySQL
*
* MySQL handles prepared statements using a MYSQL_STMT struct.
* Parameters are bound to placeholders using a MYSQL_BIND struct.
* The MYSQL_BIND contains a pointer to a data buffer. That buffer
* needs to be freed somehow when it's no longer needed.
*
* I'm going to handle this by using my own class
* (vtkMySQLBoundParameter) to hold all the information the user
* passes in. At execution time, I'll take those parameters and
* assemble the array of MYSQL_BIND objects that
* mysql_stmt_bind_param() expects. The vtkMySQLBoundParameter
* instances will each own the buffers for their data.
*
* This is slightly inefficient in that it will generate
* a few tiny little new[] requests. If this ever becomes a problem,
* we can allocate a fixed-size buffer (8 or 16 bytes) inside
* vtkMySQLBoundParameter and use that for the data storage by
* default. That will still require special-case handling for blobs
* and strings.
*
* The vtkMySQLQueryInternals class will handle the bookkeeping for
* which parameters are and aren't bound at any given time.
*/
// ----------------------------------------------------------------------
class vtkMySQLBoundParameter
{
public:
vtkMySQLBoundParameter() :
IsNull(true), Data(NULL), BufferSize(0), DataLength(0), HasError(false)
{
}
~vtkMySQLBoundParameter()
{
delete [] this->Data;
}
void SetData(char *data, unsigned long size)
{
delete [] this->Data;
this->BufferSize = size;
this->Data = new char[size];
memcpy(this->Data, data, size);
}
MYSQL_BIND BuildParameterStruct()
{
MYSQL_BIND output;
output.buffer_type = this->DataType;
output.buffer = this->Data;
output.buffer_length = this->BufferSize;
output.length = &(this->DataLength);
output.is_null = &(this->IsNull);
output.is_unsigned = this->IsUnsigned;
output.error = NULL;
return output;
}
public:
my_bool IsNull; // Is this parameter NULL?
my_bool IsUnsigned; // For integer types, is it unsigned?
char *Data; // Buffer holding actual data
unsigned long BufferSize; // Buffer size
unsigned long DataLength; // Size of the data in the buffer (must
// be less than or equal to BufferSize)
my_bool HasError; // for the server to report truncation
enum enum_field_types DataType; // MySQL data type for the contained data
};
// ----------------------------------------------------------------------
MYSQL_BIND BuildNullParameterStruct()
{
MYSQL_BIND output;
output.buffer_type = MYSQL_TYPE_NULL;
return output;
}
// ----------------------------------------------------------------------
#define VTK_MYSQL_TYPENAME_MACRO(type,return_type) \
enum enum_field_types vtkMySQLTypeName(type) \
{ return return_type; }
VTK_MYSQL_TYPENAME_MACRO(signed char, MYSQL_TYPE_TINY);
VTK_MYSQL_TYPENAME_MACRO(unsigned char, MYSQL_TYPE_TINY);
VTK_MYSQL_TYPENAME_MACRO(signed short, MYSQL_TYPE_SHORT);
VTK_MYSQL_TYPENAME_MACRO(unsigned short, MYSQL_TYPE_SHORT);
VTK_MYSQL_TYPENAME_MACRO(signed int, MYSQL_TYPE_LONG);
VTK_MYSQL_TYPENAME_MACRO(unsigned int, MYSQL_TYPE_LONG);
VTK_MYSQL_TYPENAME_MACRO(signed long, MYSQL_TYPE_LONG);
VTK_MYSQL_TYPENAME_MACRO(unsigned long, MYSQL_TYPE_LONG);
VTK_MYSQL_TYPENAME_MACRO(float, MYSQL_TYPE_FLOAT);
VTK_MYSQL_TYPENAME_MACRO(double, MYSQL_TYPE_DOUBLE);
VTK_MYSQL_TYPENAME_MACRO(vtkTypeInt64, MYSQL_TYPE_LONGLONG);
VTK_MYSQL_TYPENAME_MACRO(vtkTypeUInt64, MYSQL_TYPE_LONGLONG);
VTK_MYSQL_TYPENAME_MACRO(const char *, MYSQL_TYPE_STRING);
VTK_MYSQL_TYPENAME_MACRO(char *, MYSQL_TYPE_STRING);
VTK_MYSQL_TYPENAME_MACRO(void *, MYSQL_TYPE_BLOB);
template<typename T>
bool vtkMySQLIsTypeUnsigned(T)
{
return false;
}
template<>
bool vtkMySQLIsTypeUnsigned<unsigned char>(unsigned char)
{
return true;
}
template<>
bool vtkMySQLIsTypeUnsigned<unsigned short>(unsigned short)
{
return true;
}
template<>
bool vtkMySQLIsTypeUnsigned<unsigned int>(unsigned int)
{
return true;
}
template<>
bool vtkMySQLIsTypeUnsigned<unsigned long>(unsigned long)
{
return true;
}
template<>
bool vtkMySQLIsTypeUnsigned<vtkTypeUInt64>(vtkTypeUInt64)
{
return true;
}
// ----------------------------------------------------------------------
// Description:
// This function will build and populate a vtkMySQLBoundParameter
// struct. The default implementation works for POD data types (char,
// int, long, etc). I'll need to special-case strings and blobs.
template<typename T>
vtkMySQLBoundParameter *vtkBuildBoundParameter(T data_value)
{
vtkMySQLBoundParameter *param = new vtkMySQLBoundParameter;
param->IsNull = false;
param->IsUnsigned = vtkMySQLIsTypeUnsigned(data_value);
param->DataType = vtkMySQLTypeName(data_value);
param->BufferSize = sizeof(T);
param->DataLength = sizeof(T);
param->SetData(new char[sizeof(T)], sizeof(T));
memcpy(param->Data, &data_value, sizeof(T));
return param;
}
// Description:
// Specialization of vtkBuildBoundParameter for NULL-terminated
// strings (i.e. CHAR and VARCHAR fields)
template<>
vtkMySQLBoundParameter *vtkBuildBoundParameter<const char *>(const char *data_value)
{
vtkMySQLBoundParameter *param = new vtkMySQLBoundParameter;
param->IsNull = false;
param->IsUnsigned = false;
param->DataType = MYSQL_TYPE_STRING;
param->BufferSize = strlen(data_value);
param->DataLength = strlen(data_value);
param->SetData(new char[param->BufferSize], param->BufferSize);
memcpy(param->Data, data_value, param->BufferSize);
return param;
}
// Description:
// Alternate signature for vtkBuildBoundParameter to handle blobs
vtkMySQLBoundParameter *vtkBuildBoundParameter(const char *data,
unsigned long length,
bool is_blob)
{
vtkMySQLBoundParameter *param = new vtkMySQLBoundParameter;
param->IsNull = false;
param->IsUnsigned = false;
param->BufferSize = length;
param->DataLength = length;
param->SetData(new char[length], length);
memcpy(param->Data, data, param->BufferSize);
if (is_blob)
{
param->DataType = MYSQL_TYPE_BLOB;
}
else
{
param->DataType = MYSQL_TYPE_STRING;
}
return param;
}
// ----------------------------------------------------------------------
class vtkMySQLQueryInternals
{
public:
vtkMySQLQueryInternals();
~vtkMySQLQueryInternals();
void FreeResult();
void FreeStatement();
void FreeUserParameterList();
void FreeBoundParameters();
bool SetQuery(const char *queryString, MYSQL *db, vtkStdString &error_message);
bool SetBoundParameter(int index, vtkMySQLBoundParameter *param);
bool BindParametersToStatement();
// Description:
// MySQL can only handle certain statements as prepared statements:
// CALL, CREATE TABLE, DELETE, DO, INSERT, REPLACE, SELECT, SET,
// UPDATE and some SHOW statements. This function checks for those.
// If we can't use a prepared statement then we have to do the query
// the old-fashioned way.
bool ValidPreparedStatementSQL(const char *query);
public:
MYSQL_STMT *Statement;
MYSQL_RES *Result;
MYSQL_BIND *BoundParameters;
MYSQL_ROW CurrentRow;
unsigned long *CurrentLengths;
typedef vtksys_stl::vector<vtkMySQLBoundParameter *> ParameterList;
ParameterList UserParameterList;
};
// ----------------------------------------------------------------------
vtkMySQLQueryInternals::vtkMySQLQueryInternals()
: Statement(NULL),
Result(NULL),
BoundParameters(NULL),
CurrentLengths(NULL)
{
}
// ----------------------------------------------------------------------
vtkMySQLQueryInternals::~vtkMySQLQueryInternals()
{
this->FreeResult();
this->FreeStatement();
this->FreeUserParameterList();
this->FreeBoundParameters();
}
// ----------------------------------------------------------------------
void vtkMySQLQueryInternals::FreeResult()
{
if (this->Result)
{
mysql_free_result(this->Result);
this->Result = NULL;
}
}
// ----------------------------------------------------------------------
void vtkMySQLQueryInternals::FreeStatement()
{
if (this->Statement)
{
mysql_stmt_close(this->Statement);
this->Statement = NULL;
}
}
// ----------------------------------------------------------------------
bool vtkMySQLQueryInternals::SetQuery(const char *queryString,
MYSQL *db,
vtkStdString &error_message)
{
this->FreeStatement();
this->FreeUserParameterList();
this->FreeBoundParameters();
if (this->ValidPreparedStatementSQL(queryString) == false)
{
return true; // we'll have to handle this query in immediate mode
}
this->Statement = mysql_stmt_init(db);
if (this->Statement == NULL)
{
error_message = vtkStdString("vtkMySQLQuery: mysql_stmt_init returned out of memory error");
return false;
}
int status = mysql_stmt_prepare(this->Statement,
queryString,
strlen(queryString));
if (status == 0)
{
this->UserParameterList.resize(mysql_stmt_param_count(this->Statement), NULL);
return true;
}
else
{
error_message = vtkStdString(mysql_stmt_error(this->Statement));
return false;
}
}
// ----------------------------------------------------------------------
void vtkMySQLQueryInternals::FreeUserParameterList()
{
for (unsigned int i = 0; i < this->UserParameterList.size(); ++i)
{
if (this->UserParameterList[i] != NULL)
{
delete this->UserParameterList[i];
this->UserParameterList[i] = NULL;
}
}
this->UserParameterList.clear();
}
// ----------------------------------------------------------------------
void vtkMySQLQueryInternals::FreeBoundParameters()
{
delete [] this->BoundParameters;
}
// ----------------------------------------------------------------------
bool vtkMySQLQueryInternals::SetBoundParameter(int index, vtkMySQLBoundParameter *param)
{
if (index >= static_cast<int>(this->UserParameterList.size()))
{
vtkGenericWarningMacro(<<"ERROR: Illegal parameter index "
<<index << ". Did you forget to set the query?");
return false;
}
else
{
if (this->UserParameterList[index] != NULL)
{
delete this->UserParameterList[index];
}
this->UserParameterList[index] = param;
return true;
}
}
// ----------------------------------------------------------------------
bool vtkMySQLQueryInternals::BindParametersToStatement()
{
if (this->Statement == NULL)
{
vtkGenericWarningMacro(<<"BindParametersToStatement: No prepared statement available");
return false;
}
this->FreeBoundParameters();
unsigned long numParams = mysql_stmt_param_count(this->Statement);
this->BoundParameters = new MYSQL_BIND[numParams];
for (unsigned int i = 0; i < numParams; ++i)
{
if (this->UserParameterList[i])
{
this->BoundParameters[i] = this->UserParameterList[i]->BuildParameterStruct();
}
else
{
this->BoundParameters[i] = BuildNullParameterStruct();
}
}
return mysql_stmt_bind_param(this->Statement, this->BoundParameters);
}
// ----------------------------------------------------------------------
bool vtkMySQLQueryInternals::ValidPreparedStatementSQL(const char *query)
{
if ( ! query )
return false;
if (!LOWERCASE_COMPARE("call", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("create table", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("delete", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("do", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("insert", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("replace", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("select", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("set", query))
{
return true;
}
else if (!LOWERCASE_COMPARE("update", query))
{
return true;
}
return false;
}
// ----------------------------------------------------------------------
vtkStandardNewMacro(vtkMySQLQuery);
// ----------------------------------------------------------------------
vtkMySQLQuery::vtkMySQLQuery()
{
this->Internals = new vtkMySQLQueryInternals;
this->InitialFetch = true;
this->LastErrorText = NULL;
}
// ----------------------------------------------------------------------
vtkMySQLQuery::~vtkMySQLQuery()
{
this->SetLastErrorText(NULL);
delete this->Internals;
}
// ----------------------------------------------------------------------
void
vtkMySQLQuery::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
bool
vtkMySQLQuery::Execute()
{
this->Active = false;
if (this->Query == NULL)
{
vtkErrorMacro(<<"Cannot execute before a query has been set.");
return false;
}
this->Internals->FreeResult();
vtkMySQLDatabase *dbContainer =
static_cast<vtkMySQLDatabase *>(this->Database);
assert(dbContainer != NULL);
if (!dbContainer->IsOpen())
{
vtkErrorMacro(<<"Cannot execute query. Database is closed.");
return false;
}
vtkDebugMacro(<<"Execute(): Query ready to execute.");
if (this->Query != NULL && this->Internals->Statement == NULL)
{
MYSQL *db = dbContainer->Private->Connection;
assert(db != NULL);
int result = mysql_query(db, this->Query);
if (result == 0)
{
// The query probably succeeded.
this->Internals->Result = mysql_store_result(db);
// Statements like INSERT are supposed to return empty result sets,
// but sometimes it is an error for mysql_store_result to return null.
// If Result is null, but mysql_field_count is non-zero, it is an error.
// See: http://dev.mysql.com/doc/refman/5.0/en/null-mysql-store-result.html
if (this->Internals->Result || mysql_field_count(db) == 0)
{
// The query definitely succeeded.
this->SetLastErrorText(NULL);
this->Active = true;
return true;
}
else
{
// There was an error in mysql_query or mysql_store_result
this->Active = false;
this->SetLastErrorText(mysql_error(db));
vtkErrorMacro(<<"Query returned an error: "
<< this->GetLastErrorText());
return false;
}
}
else
{
// result != 0; the query failed
this->Active = false;
this->SetLastErrorText(mysql_error(db));
vtkErrorMacro(<<"Query returned an error: " << this->GetLastErrorText());
return false;
}
}
else
{
vtkDebugMacro(<<"Binding parameters immediately prior to execution.");
bool bindStatus = this->Internals->BindParametersToStatement();
if (!bindStatus)
{
this->SetLastErrorText(mysql_stmt_error(this->Internals->Statement));
vtkErrorMacro(<<"Error binding parameters: "
<<this->GetLastErrorText());
return false;
}
int result = mysql_stmt_execute(this->Internals->Statement);
if (result == 0)
{
// The query succeeded.
this->SetLastErrorText(NULL);
this->Active = true;
this->Internals->Result = mysql_stmt_result_metadata(this->Internals->Statement);
return true;
}
else
{
this->Active = false;
this->SetLastErrorText(mysql_stmt_error(this->Internals->Statement));
vtkErrorMacro(<<"Query returned an error: "
<< this->GetLastErrorText());
return false;
}
}
}
// ----------------------------------------------------------------------
bool vtkMySQLQuery::BeginTransaction()
{
this->SetQuery( "START TRANSACTION" );
return this->Execute();
}
bool vtkMySQLQuery::CommitTransaction()
{
this->SetQuery( "COMMIT" );
return this->Execute();
}
bool vtkMySQLQuery::RollbackTransaction()
{
this->SetQuery( "ROLLBACK" );
return this->Execute();
}
// ----------------------------------------------------------------------
int
vtkMySQLQuery::GetNumberOfFields()
{
if (! this->Active)
{
vtkErrorMacro(<<"GetNumberOfFields(): Query is not active!");
return 0;
}
else
{
return static_cast<int>(mysql_num_fields(this->Internals->Result));
}
}
// ----------------------------------------------------------------------
const char *
vtkMySQLQuery::GetFieldName(int column)
{
if (! this->Active)
{
vtkErrorMacro(<<"GetFieldName(): Query is not active!");
return NULL;
}
else if (column < 0 || column >= this->GetNumberOfFields())
{
vtkErrorMacro(<<"GetFieldName(): Illegal field index "
<< column);
return NULL;
}
else
{
MYSQL_FIELD *field = mysql_fetch_field_direct(this->Internals->Result, column);
if (field == NULL)
{
vtkErrorMacro(<<"GetFieldName(): MySQL returned null field for column "
<< column );
return NULL;
}
else
{
return field->name;
}
}
}
// ----------------------------------------------------------------------
int
vtkMySQLQuery::GetFieldType(int column)
{
if (! this->Active)
{
vtkErrorMacro(<<"GetFieldType(): Query is not active!");
return VTK_VOID;
}
else if (column < 0 || column >= this->GetNumberOfFields())
{
vtkErrorMacro(<<"GetFieldType(): Illegal field index "
<< column);
return VTK_VOID;
}
else
{
vtkMySQLDatabase *dbContainer =
static_cast<vtkMySQLDatabase *>(this->Database);
assert(dbContainer != NULL);
if (!dbContainer->IsOpen())
{
vtkErrorMacro(<<"Cannot get field type. Database is closed.");
return VTK_VOID;
}
MYSQL *db = dbContainer->Private->Connection;
assert(db != NULL);
MYSQL_FIELD *field = mysql_fetch_field_direct(this->Internals->Result,
column);
if (field == NULL)
{
vtkErrorMacro(<<"GetFieldType(): MySQL returned null field for column "
<< column );
return -1;
}
else
{
switch (field->type)
{
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_YEAR:
return VTK_INT;
case MYSQL_TYPE_SHORT:
return VTK_SHORT;
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
return VTK_LONG;
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_NEWDATE:
return VTK_STRING; // Just return the raw string.
#if MYSQL_VERSION_ID >= 50000
case MYSQL_TYPE_BIT:
return VTK_BIT;
#endif
case MYSQL_TYPE_FLOAT:
return VTK_FLOAT;
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_DECIMAL:
#if MYSQL_VERSION_ID >= 50000
case MYSQL_TYPE_NEWDECIMAL:
#endif
return VTK_DOUBLE;
case MYSQL_TYPE_NULL:
return VTK_VOID;
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
return VTK_STRING; // MySQL treats text fields as blobs
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
#if MYSQL_VERSION_ID >= 50000
case MYSQL_TYPE_VARCHAR:
#endif
return VTK_STRING;
case MYSQL_TYPE_SET:
case MYSQL_TYPE_GEOMETRY:
default:
{
vtkErrorMacro( <<"GetFieldType(): Unknown data type "
<< field->type );
return VTK_VOID;
}
}
}
}
}
// ----------------------------------------------------------------------
bool
vtkMySQLQuery::NextRow()
{
if (! this->IsActive())
{
vtkErrorMacro(<<"NextRow(): Query is not active!");
return false;
}
MYSQL_ROW row = mysql_fetch_row(this->Internals->Result);
this->Internals->CurrentRow = row;
this->Internals->CurrentLengths = mysql_fetch_lengths(this->Internals->Result);
if (!row)
{
// A null row will come back in one of two situations. The first
// is when there's an error, in which case mysql_errno will return
// some nonzero error code. The second is when there are no more
// rows to fetch. Discriminate between the two by checking the
// errno.
this->Active = false;
vtkMySQLDatabase *dbContainer =
static_cast<vtkMySQLDatabase *>(this->Database);
assert(dbContainer != NULL);
if (!dbContainer->IsOpen())
{
vtkErrorMacro(<<"Cannot get field type. Database is closed.");
this->SetLastErrorText("Database is closed.");
return VTK_VOID;
}
MYSQL *db = dbContainer->Private->Connection;
assert(db != NULL);
if (mysql_errno(db) != 0)
{
this->SetLastErrorText(mysql_error(db));
vtkErrorMacro(<<"NextRow(): MySQL returned error message "
<< this->GetLastErrorText());
}
else
{
// Nothing's wrong. We're just out of results.
this->SetLastErrorText(NULL);
}
return false;
}
else
{
this->SetLastErrorText(NULL);
return true;
}
}
// ----------------------------------------------------------------------
vtkVariant
vtkMySQLQuery::DataValue(vtkIdType column)
{
if (this->IsActive() == false)
{
vtkWarningMacro(<<"DataValue() called on inactive query");
return vtkVariant();
}
else if (column < 0 || column >= this->GetNumberOfFields())
{
vtkWarningMacro(<<"DataValue() called with out-of-range column index "
<< column);
return vtkVariant();
}
else
{
assert(this->Internals->CurrentRow);
vtkVariant result;
// Initialize base as a VTK_VOID value... only populate with
// data when a column value is non-NULL.
vtkVariant base;
if ( this->Internals->CurrentRow[column] )
{
// Make a string holding the data, including possible embedded null characters.
vtkStdString s( this->Internals->CurrentRow[column],
static_cast<size_t>(this->Internals->CurrentLengths[column]) );
base = vtkVariant( s );
}
// It would be a royal pain to try to convert the string to each
// different value in turn. Fortunately, there is already code in
// vtkVariant to do exactly that using the C++ standard library
// sstream. We'll exploit that.
switch (this->GetFieldType(column))
{
case VTK_INT:
case VTK_SHORT:
case VTK_BIT:
return vtkVariant(base.ToInt());
case VTK_LONG:
case VTK_UNSIGNED_LONG:
return vtkVariant(base.ToLong());
case VTK_FLOAT:
return vtkVariant(base.ToFloat());
case VTK_DOUBLE:
return vtkVariant(base.ToDouble());
case VTK_STRING:
return base; // it's already a string
case VTK_VOID:
return vtkVariant();
default:
{
vtkWarningMacro(<<"Unhandled type " << this->GetFieldType(column)
<<" in DataValue().");
return vtkVariant();
}
}
}
}
// ----------------------------------------------------------------------
const char *
vtkMySQLQuery::GetLastErrorText()
{
return this->LastErrorText;
}
// ----------------------------------------------------------------------
bool
vtkMySQLQuery::HasError()
{
return (this->GetLastErrorText() != NULL);
}
vtkStdString vtkMySQLQuery::EscapeString( vtkStdString src, bool addSurroundingQuotes )
{
vtkStdString dst;
vtkMySQLDatabase* dbContainer =
static_cast<vtkMySQLDatabase*>( this->Database );
assert( dbContainer != NULL );
MYSQL* db;
if ( ( ! dbContainer->IsOpen() ) || ! ( db = dbContainer->Private->Connection ) )
{ // fall back to superclass implementation
dst = this->Superclass::EscapeString( src, addSurroundingQuotes );
return dst;
}
unsigned long ssz = src.size();
char* dstarr = new char[2 * ssz + (addSurroundingQuotes ? 3 : 1)];
char* end = dstarr;
if ( addSurroundingQuotes )
{
* ( end ++ ) = '\'';
}
end += mysql_real_escape_string( db, end, src.c_str(), ssz );
if ( addSurroundingQuotes )
{
* ( end ++ ) = '\'';
* ( end ++ ) = '\0';
}
dst = dstarr;
delete [] dstarr;
return dst;
}
// ----------------------------------------------------------------------
bool
vtkMySQLQuery::SetQuery(const char *newQuery)
{
vtkDebugMacro(<< this->GetClassName()
<< " (" << this << "): setting Query to "
<< (newQuery?newQuery:"(null)") );
if (this->Query == NULL && newQuery == NULL)
{
return true;
}
if (this->Query && newQuery && (!strcmp(this->Query, newQuery)))
{
return true; // we've already got that query
}
if (this->Query)
{
delete [] this->Query;
}
if (newQuery)
{
// Keep a local copy of the query - this is from vtkSetGet.h
size_t n = strlen(newQuery) + 1;
char *cp1 = new char[n];
const char *cp2 = (newQuery);
this->Query = cp1;
do { *cp1++ = *cp2++; } while ( --n );
}
else
{
this->Query = NULL;
}