forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_db.cpp
3356 lines (3136 loc) · 114 KB
/
sql_db.cpp
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
#include <stdio.h>
#include <iostream>
#include <syslog.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <sstream>
#include <mysql/mysqld_error.h>
#include <mysql/errmsg.h>
#include "voipmonitor.h"
#include "tools.h"
#include "sql_db.h"
extern int verbosity;
extern int opt_mysql_port;
extern char opt_match_header[128];
extern int terminating;
extern int opt_ipaccount;
extern int opt_id_sensor;
extern bool opt_cdr_partition;
extern int opt_cdr_sipport;
extern int opt_create_old_partitions;
extern bool opt_disable_partition_operations;
extern vector<dstring> opt_custom_headers_cdr;
extern vector<dstring> opt_custom_headers_message;
extern char get_customers_pn_query[1024];
extern int opt_dscp;
extern int opt_enable_lua_tables;
extern int opt_mysqlcompress;
extern pthread_mutex_t mysqlconnect_lock;
extern int opt_mos_lqo;
int sql_noerror = 0;
int sql_disable_next_attempt_if_error = 0;
string SqlDb_row::operator [] (const char *fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].content);
}
return("");
}
string SqlDb_row::operator [] (string fieldName) {
return((*this)[fieldName.c_str()]);
}
string SqlDb_row::operator [] (int indexField) {
return(row[indexField].content);
}
SqlDb_row::operator int() {
return(!this->isEmpty());
}
void SqlDb_row::add(const char *content, string fieldName) {
if(fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName);
return;
}
}
}
this->row.push_back(SqlDb_rowField(content, fieldName));
}
void SqlDb_row::add(string content, string fieldName) {
if(fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName);
return;
}
}
}
this->row.push_back(SqlDb_rowField(content, fieldName));
}
void SqlDb_row::add(int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%i", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(unsigned int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%u", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(long int content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%li", content);
this->add(str_content, fieldName);
}
}
void SqlDb_row::add(double content, string fieldName, bool null) {
if(!content && null) {
this->add((const char*)NULL, fieldName);
} else {
char str_content[100];
sprintf(str_content, "%lf", content);
this->add(str_content, fieldName);
}
}
int SqlDb_row::getIndexField(string fieldName) {
for(size_t i = 0; i < row.size(); i++) {
if(!strcasecmp(row[i].fieldName.c_str(), fieldName.c_str())) {
return(i);
}
}
if(this->sqlDb) {
return(this->sqlDb->getIndexField(fieldName));
}
return(-1);
}
bool SqlDb_row::isEmpty() {
return(!row.size());
}
bool SqlDb_row::isNull(string fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].null);
}
return(false);
}
string SqlDb_row::implodeFields(string separator, string border) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(i) { rslt += separator; }
rslt += border + /*'`' +*/ this->row[i].fieldName + /*'`' +*/ border;
}
return(rslt);
}
string SqlDb_row::implodeContent(string separator, string border, bool enableSqlString, bool escapeAll) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(i) { rslt += separator; }
if(this->row[i].null) {
rslt += "NULL";
} else if(enableSqlString && this->row[i].content.substr(0, 12) == "_\\_'SQL'_\\_:") {
rslt += this->row[i].content.substr(12);
} else {
rslt += border +
(escapeAll ? sqlEscapeString(this->row[i].content) : this->row[i].content) +
border;
}
}
return(rslt);
}
string SqlDb_row::keyvalList(string separator) {
string rslt;
for(size_t i = 0; i < this->row.size(); i++) {
if(this->row[i].null) {
rslt += this->row[i].fieldName + ":NULL\n";
} else {
rslt += this->row[i].fieldName + separator + this->row[i].content + "\n";
}
}
return(rslt);
}
SqlDb::SqlDb() {
this->clearLastError();
this->maxQueryPass = UINT_MAX;
this->loginTimeout = (ulong)NULL;
this->enableSqlStringInContent = false;
this->disableNextAttemptIfError = false;
}
SqlDb::~SqlDb() {
}
void SqlDb::setConnectParameters(string server, string user, string password, string database, bool showversion) {
this->conn_server = server;
this->conn_user = user;
this->conn_password = password;
this->conn_database = database;
this->conn_showversion = showversion;
}
void SqlDb::setLoginTimeout(ulong loginTimeout) {
this->loginTimeout = loginTimeout;
}
bool SqlDb::reconnect() {
this->disconnect();
return(this->connect());
}
void SqlDb::prepareQuery(string *query) {
size_t findPos;
if(this->getSubtypeDb() == "mssql") {
const char *substFce[][2] = {
{ "UNIX_TIMESTAMP", "dbo.unix_timestamp" },
{ "NOW", "dbo.now" },
{ "SUBTIME", "dbo.subtime" }
};
for(unsigned int i = 0; i < sizeof(substFce)/sizeof(substFce[0]); i++) {
while((findPos = query->find(substFce[i][0])) != string::npos) {
query->replace(findPos, strlen(substFce[i][0]), substFce[i][1]);
}
}
}
while((findPos = query->find("_LC_[")) != string::npos) {
size_t findPosEnd = query->find("]", findPos);
if(findPosEnd != string::npos) {
string lc = query->substr(findPos + 5, findPosEnd - findPos - 5);
if(this->getSubtypeDb() == "mssql") {
lc = "case when " + lc + " then 1 else 0 end";
}
query->replace(findPos, findPosEnd - findPos + 1, lc);
}
}
}
string SqlDb::insertQuery(string table, SqlDb_row row, bool enableSqlStringInContent, bool escapeAll, bool insertIgnore) {
string query =
string("INSERT ") + (insertIgnore ? "IGNORE " : "") + "INTO " + table + " ( " + row.implodeFields(this->getFieldSeparator(), this->getFieldBorder()) +
" ) VALUES ( " + row.implodeContent(this->getContentSeparator(), this->getContentBorder(), enableSqlStringInContent || this->enableSqlStringInContent, escapeAll) + " )";
return(query);
}
string SqlDb::insertQuery(string table, vector<SqlDb_row> *rows, bool enableSqlStringInContent, bool escapeAll, bool insertIgnore) {
if(!rows->size()) {
return("");
}
string values = "";
for(size_t i = 0; i < rows->size(); i++) {
values += "( " + (*rows)[i].implodeContent(this->getContentSeparator(), this->getContentBorder(), enableSqlStringInContent || this->enableSqlStringInContent, escapeAll) + " )";
if(i < rows->size() - 1) {
values += ",";
}
}
string query =
string("INSERT ") + (insertIgnore ? "IGNORE " : "") + "INTO " + table + " ( " + (*rows)[0].implodeFields(this->getFieldSeparator(), this->getFieldBorder()) +
" ) VALUES " + values;
return(query);
}
int SqlDb::insert(string table, SqlDb_row row) {
string query = this->insertQuery(table, row);
if(this->query(query)) {
return(this->getInsertId());
}
return(-1);
}
int SqlDb::insert(string table, vector<SqlDb_row> *rows) {
if(!rows->size()) {
return(-1);
}
string query = this->insertQuery(table, rows);
if(this->query(query)) {
return(this->getInsertId());
}
return(-1);
}
int SqlDb::getIdOrInsert(string table, string idField, string uniqueField, SqlDb_row row) {
string query =
"SELECT * FROM " + table + " WHERE " + uniqueField + " = " +
this->getContentBorder() + row[uniqueField] + this->getContentBorder();
if(this->query(query)) {
SqlDb_row rsltRow = this->fetchRow();
if(rsltRow) {
return(atoi(rsltRow[idField].c_str()));
}
}
return(this->insert(table, row));
}
int SqlDb::getIndexField(string fieldName) {
for(size_t i = 0; i < this->fields.size(); i++) {
if(this->fields[i] == fieldName) {
return(i);
}
}
return(-1);
}
void SqlDb::setLastErrorString(string lastErrorString, bool sysLog) {
this->lastErrorString = lastErrorString;
if(sysLog && lastErrorString != "") {
syslog(LOG_ERR, "%s", lastErrorString.c_str());
}
}
void SqlDb::setEnableSqlStringInContent(bool enableSqlStringInContent) {
this->enableSqlStringInContent = enableSqlStringInContent;
}
void SqlDb::setDisableNextAttemptIfError() {
this->disableNextAttemptIfError = true;
}
void SqlDb::setEnableNextAttemptIfError() {
this->disableNextAttemptIfError = false;
}
void SqlDb::cleanFields() {
this->fields.clear();
}
SqlDb_mysql::SqlDb_mysql() {
this->hMysql = NULL;
this->hMysqlConn = NULL;
this->hMysqlRes = NULL;
}
SqlDb_mysql::~SqlDb_mysql() {
this->clean();
}
bool SqlDb_mysql::connect(bool createDb, bool mainInit) {
pthread_mutex_lock(&mysqlconnect_lock);
this->hMysql = mysql_init(NULL);
if(this->hMysql) {
this->hMysqlConn = mysql_real_connect(
this->hMysql,
//this->conn_server.c_str(), this->conn_user.c_str(), this->conn_password.c_str(), this->conn_database.c_str(),
this->conn_server.c_str(), this->conn_user.c_str(), this->conn_password.c_str(), NULL,
//opt_mysql_port, NULL, CLIENT_MULTI_STATEMENTS);
//opt_mysql_port, NULL, 0);
opt_mysql_port, NULL, CLIENT_MULTI_RESULTS);
if(this->hMysqlConn) {
sql_disable_next_attempt_if_error = 1;
this->query("SET NAMES UTF8");
sql_noerror = 1;
this->query("SET GLOBAL innodb_stats_on_metadata=0"); // this will speedup "Slow query on information_schema.tables"
sql_noerror = 0;
this->query("SET sql_mode = ''");
char tmp[1024];
if(createDb) {
sprintf(tmp, "CREATE DATABASE IF NOT EXISTS `%s`", this->conn_database.c_str());
this->query(tmp);
}
sprintf(tmp, "USE `%s`", this->conn_database.c_str());
this->query(tmp);
if(mainInit) {
this->query("SHOW VARIABLES LIKE \"version\"");
SqlDb_row row;
if((row = this->fetchRow())) {
this->dbVersion = row[1];
}
while(this->fetchRow());
if(this->conn_showversion) {
syslog(LOG_INFO, "connect - db version %i.%i", this->getDbMajorVersion(), this->getDbMinorVersion());
}
}
sql_disable_next_attempt_if_error = 0;
pthread_mutex_unlock(&mysqlconnect_lock);
return(true);
} else {
this->checkLastError("connect error", true);
}
} else {
this->setLastErrorString("mysql_init failed - insufficient memory ?", true);
}
pthread_mutex_unlock(&mysqlconnect_lock);
return(false);
}
int SqlDb_mysql::multi_on() {
return mysql_set_server_option(this->hMysql, MYSQL_OPTION_MULTI_STATEMENTS_ON);
}
int SqlDb_mysql::multi_off() {
return mysql_set_server_option(this->hMysql, MYSQL_OPTION_MULTI_STATEMENTS_OFF);
}
int SqlDb_mysql::getDbMajorVersion() {
return(atoi(this->dbVersion.c_str()));
}
int SqlDb_mysql::getDbMinorVersion(int minorLevel) {
const char *pointToVersion = this->dbVersion.c_str();
for(int i = 0; i < minorLevel + 1 && pointToVersion; i++) {
const char *pointToSeparator = strchr(pointToVersion, '.');
if(pointToSeparator) {
pointToVersion = pointToSeparator + 1;
}
}
return(pointToVersion ? atoi(pointToVersion) : 0);
}
bool SqlDb_mysql::createRoutine(string routine, string routineName, string routineParamsAndReturn, eRoutineType routineType) {
bool missing = false;
bool diff = false;
this->query(string("select routine_definition from information_schema.routines where routine_schema='") + this->conn_database +
"' and routine_name='" + routineName +
"' and routine_type='" + (routineType == procedure ? "PROCEDURE" : "FUNCTION") + "'");
SqlDb_row row = this->fetchRow();
if(!row) {
missing = true;
} else if(row["routine_definition"] != routine) {
size_t i = 0, j = 0;
while(i < routine.length() &&
j < row["routine_definition"].length()) {
if(routine[i] == '\\' && i < routine.length() - 1) {
++i;
}
if(routine[i] != row["routine_definition"][j]) {
diff = true;
break;
}
++i;
++j;
}
if(!diff &&
(i < routine.length() || j < row["routine_definition"].length())) {
diff = true;
}
}
if(missing || diff) {
syslog(LOG_NOTICE, "create %s %s", (routineType == procedure ? "procedure" : "function"), routineName.c_str());
this->query(string("drop ") + (routineType == procedure ? "PROCEDURE" : "FUNCTION") +
" if exists " + routineName);
return(this->query(string("create ") + (routineType == procedure ? "PROCEDURE" : "FUNCTION") + " " +
routineName + routineParamsAndReturn + " " + routine));
} else {
return(true);
}
}
void SqlDb_mysql::disconnect() {
if(this->hMysqlRes) {
while(mysql_fetch_row(this->hMysqlRes));
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
}
if(this->hMysqlConn) {
mysql_close(this->hMysqlConn);
this->hMysqlConn = NULL;
}
/* disable dealloc hMysql - is it shared variable ?
this->hMysql = NULL;
}
else if(this->hMysql) {
mysql_close(this->hMysql);
this->hMysql = NULL;
}
*/
}
bool SqlDb_mysql::connected() {
return(this->hMysqlConn != NULL);
}
bool SqlDb_mysql::query(string query) {
this->prepareQuery(&query);
if(verbosity > 1) {
syslog(LOG_INFO, query.c_str());
}
bool rslt = false;
if(this->hMysqlRes) {
while(mysql_fetch_row(this->hMysqlRes));
mysql_free_result(this->hMysqlRes);
this->hMysqlRes = NULL;
}
this->cleanFields();
for(unsigned int pass = 0; pass < this->maxQueryPass; pass++) {
if(pass > 0) {
sleep(1);
}
if(!this->connected()) {
this->connect();
}
if(this->connected()) {
if(mysql_query(this->hMysqlConn, query.c_str())) {
if(!sql_noerror) {
this->checkLastError("query error in [" + query + "]", true);
}
if(this->getLastError() == CR_SERVER_GONE_ERROR) {
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
} else if(sql_noerror || sql_disable_next_attempt_if_error || this->disableNextAttemptIfError ||
this->getLastError() == ER_PARSE_ERROR) {
break;
} else {
if(pass < this->maxQueryPass - 5) {
pass = this->maxQueryPass - 5;
}
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
}
} else {
rslt = true;
break;
}
}
if(terminating) {
break;
}
}
return(rslt);
}
SqlDb_row SqlDb_mysql::fetchRow(bool assoc) {
SqlDb_row row(this);
if(this->hMysqlConn) {
if(!this->hMysqlRes) {
this->hMysqlRes = mysql_use_result(this->hMysqlConn);
if(this->hMysqlRes) {
MYSQL_FIELD *field;
for(int i = 0; (field = mysql_fetch_field(this->hMysqlRes)); i++) {
this->fields.push_back(field->name);
}
} else {
this->checkLastError("fetch row error in function mysql_use_result", true);
}
}
if(this->hMysqlRes) {
MYSQL_ROW mysqlRow = mysql_fetch_row(hMysqlRes);
if(mysqlRow) {
unsigned int numFields = mysql_num_fields(this->hMysqlRes);
for(unsigned int i = 0; i < numFields; i++) {
row.add(mysqlRow[i], assoc ? this->fields[i] : "");
}
} else {
this->checkLastError("fetch row error", true);
}
}
}
return(row);
}
int SqlDb_mysql::getInsertId() {
if(this->hMysqlConn) {
return(mysql_insert_id(this->hMysqlConn));
}
return(-1);
}
string SqlDb_mysql::escape(const char *inputString, int length) {
return sqlEscapeString(inputString, length, this->getTypeDb().c_str(), this);
}
bool SqlDb_mysql::checkLastError(string prefixError, bool sysLog, bool clearLastError) {
if(this->hMysql) {
unsigned int errno = mysql_errno(this->hMysql);
if(errno) {
this->setLastError(errno, (prefixError + ": " + mysql_error(this->hMysql)).c_str(), sysLog);
return(true);
} else if(clearLastError) {
this->clearLastError();
}
}
return(false);
}
void SqlDb_mysql::clean() {
this->disconnect();
this->cleanFields();
}
SqlDb_odbc_bindBufferItem::SqlDb_odbc_bindBufferItem(SQLUSMALLINT colNumber, string fieldName, SQLSMALLINT dataType, SQLULEN columnSize, SQLHSTMT hStatement) {
this->colNumber = colNumber;
this->fieldName = fieldName;
this->dataType = dataType;
this->columnSize = columnSize;
this->buffer = new char[this->columnSize + 100]; // 100 - reserve for convert binary to text
memset(this->buffer, 0, this->columnSize + 100);
if(hStatement) {
this->bindCol(hStatement);
}
}
SqlDb_odbc_bindBufferItem::~SqlDb_odbc_bindBufferItem() {
if(this->buffer) {
delete [] this->buffer;
}
}
void SqlDb_odbc_bindBufferItem::bindCol(SQLHSTMT hStatement) {
SQLBindCol(hStatement, this->colNumber, SQL_CHAR, this->buffer, this->columnSize, &this->ind);
}
string SqlDb_odbc_bindBufferItem::getContent() {
return(string(this->buffer));
}
char* SqlDb_odbc_bindBufferItem::getBuffer() {
return(this->buffer);
}
void SqlDb_odbc_bindBuffer::addItem(SQLUSMALLINT colNumber, string fieldName, SQLSMALLINT dataType, SQLULEN columnSize, SQLHSTMT hStatement) {
this->push_back(new SqlDb_odbc_bindBufferItem(colNumber, fieldName, dataType, columnSize, hStatement));
}
void SqlDb_odbc_bindBuffer::bindCols(SQLHSTMT hStatement) {
SQLCHAR columnName[255];
SQLSMALLINT nameLength;
SQLSMALLINT dataType;
SQLULEN columnSize;
SQLSMALLINT decimalDigits;
SQLSMALLINT nullable;
unsigned int columnIndex = 0;
while(!SQLDescribeCol(
hStatement, columnIndex + 1, columnName, sizeof(columnName)/sizeof(SQLCHAR),
&nameLength, &dataType, &columnSize, &decimalDigits, &nullable)) {
this->addItem(columnIndex + 1, (const char*)columnName, dataType, columnSize + 1, hStatement);
++columnIndex;
}
}
string SqlDb_odbc_bindBuffer::getColContent(string fieldName) {
int index = this->getIndexField(fieldName);
if(index >= 0) {
this->getColContent(index);
}
return("");
}
string SqlDb_odbc_bindBuffer::getColContent(unsigned int fieldIndex) {
return(fieldIndex < this->size() ?
(*this)[fieldIndex]->getContent() :
"");
}
char* SqlDb_odbc_bindBuffer::getColBuffer(unsigned int fieldIndex) {
return(fieldIndex < this->size() ?
(*this)[fieldIndex]->getBuffer() :
NULL);
}
int SqlDb_odbc_bindBuffer::getIndexField(string fieldName) {
for(size_t i = 0; i < this->size(); i++) {
if((*this)[i]->fieldName == fieldName) {
return(i);
}
}
return(-1);
}
SqlDb_odbc::SqlDb_odbc() {
this->odbcVersion = (ulong)NULL;
this->subtypeDb = "";
this->hEnvironment = NULL;
this->hConnection = NULL;
this->hStatement = NULL;
}
SqlDb_odbc::~SqlDb_odbc() {
this->clean();
}
void SqlDb_odbc::setOdbcVersion(ulong odbcVersion) {
this->odbcVersion = odbcVersion;
}
void SqlDb_odbc::setSubtypeDb(string subtypeDb) {
this->subtypeDb = subtypeDb;
}
bool SqlDb_odbc::connect(bool createDb, bool mainInit) {
SQLRETURN rslt;
this->clearLastError();
if(!this->hEnvironment) {
rslt = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &this->hEnvironment);
if(!this->okRslt(rslt)) {
this->setLastError(rslt, "odbc: error in allocate environment handle", true);
this->disconnect();
return(false);
}
if(this->odbcVersion) {
rslt = SQLSetEnvAttr(this->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER*)this->odbcVersion, 0);
if(!this->okRslt(rslt)) {
this->setLastError(rslt, "odbc: error in set environment attributes");
this->disconnect();
return(false);
}
}
}
if(!this->hConnection) {
rslt = SQLAllocHandle(SQL_HANDLE_DBC, this->hEnvironment, &this->hConnection);
if(!this->okRslt(rslt)) {
this->setLastError(rslt, "odbc: error in allocate connection handle");
this->disconnect();
return(false);
}
if(this->loginTimeout) {
SQLSetConnectAttr(this->hConnection, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)this->loginTimeout, 0);
}
rslt = SQLConnect(this->hConnection,
(SQLCHAR*)this->conn_server.c_str(), SQL_NTS,
(SQLCHAR*)this->conn_user.c_str(), SQL_NTS,
(SQLCHAR*)this->conn_password.c_str(), SQL_NTS);
if(!this->okRslt(rslt)) {
this->checkLastError("odbc: connect error", true);
this->disconnect();
return(false);
}
}
return(true);
}
void SqlDb_odbc::disconnect() {
if(this->hStatement) {
SQLFreeHandle(SQL_HANDLE_STMT, this->hStatement);
this->hStatement = NULL;
}
if(this->hConnection) {
SQLDisconnect(this->hConnection);
SQLFreeHandle(SQL_HANDLE_DBC, this->hConnection);
this->hConnection = NULL;
}
if(this->hEnvironment) {
SQLFreeHandle(SQL_HANDLE_ENV, this->hEnvironment);
this->hEnvironment = NULL;
}
}
bool SqlDb_odbc::connected() {
return(this->hConnection != NULL);
}
bool SqlDb_odbc::query(string query) {
this->prepareQuery(&query);
if(verbosity > 1) {
syslog(LOG_INFO, query.c_str());
}
SQLRETURN rslt = SQL_NULL_DATA;
if(this->hStatement) {
SQLFreeHandle(SQL_HANDLE_STMT, this->hStatement);
this->hStatement = NULL;
}
this->cleanFields();
for(unsigned int pass = 0; pass < this->maxQueryPass; pass++) {
if(pass > 0) {
sleep(1);
}
if(!this->connected()) {
this->connect();
}
if(this->connected()) {
rslt = SQLAllocHandle(SQL_HANDLE_STMT, hConnection, &hStatement);
if(!this->okRslt(rslt)) {
this->checkLastError("odbc: error in allocate statement handle", true);
if(terminating) {
break;
}
this->reconnect();
continue;
}
rslt = SQLExecDirect(this->hStatement, (SQLCHAR*)query.c_str(), SQL_NTS);
if(!this->okRslt(rslt) && rslt != SQL_NO_DATA) {
if(!sql_noerror) {
this->checkLastError("odbc query error", true);
}
if(sql_noerror || sql_disable_next_attempt_if_error || this->disableNextAttemptIfError) {
break;
}
else if(rslt == SQL_ERROR || rslt == SQL_INVALID_HANDLE) {
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
} else {
if(pass < this->maxQueryPass - 5) {
pass = this->maxQueryPass - 5;
}
if(pass < this->maxQueryPass - 1) {
this->reconnect();
}
}
} else {
break;
}
}
if(terminating) {
break;
}
}
return(this->okRslt(rslt) || rslt == SQL_NO_DATA);
}
SqlDb_row SqlDb_odbc::fetchRow(bool assoc) {
SqlDb_row row(this);
if(this->hConnection && this->hStatement) {
if(!this->bindBuffer.size()) {
this->bindBuffer.bindCols(this->hStatement);
}
SQLRETURN rslt = SQLFetch(hStatement);
if(this->okRslt(rslt) || rslt == SQL_NO_DATA) {
if(rslt != SQL_NO_DATA) {
for(unsigned int i = 0; i < this->bindBuffer.size(); i++) {
row.add(this->bindBuffer.getColBuffer(i),
assoc ? this->bindBuffer[i]->fieldName : "");
}
}
} else {
this->checkLastError("odbc fetch error", true);
}
}
return(row);
}
int SqlDb_odbc::getInsertId() {
SqlDb_row row;
if(this->query("select @@identity as last_insert_id") &&
(row = this->fetchRow()) != 0) {
return(atol(row["last_insert_id"].c_str()));
}
return(-1);
}
int SqlDb_odbc::getIndexField(string fieldName) {
for(size_t i = 0; i < this->bindBuffer.size(); i++) {
if(this->bindBuffer[i]->fieldName == fieldName) {
return(i);
}
}
return(-1);
}
string SqlDb_odbc::escape(const char *inputString, int length) {
return sqlEscapeString(inputString, length, this->getTypeDb().c_str());
}
bool SqlDb_odbc::checkLastError(string prefixError, bool sysLog, bool clearLastError) {
if(this->hConnection) {
SQLCHAR sqlState[10];
SQLINTEGER nativeError;
SQLCHAR messageText[1000];
SQLSMALLINT messageTextLength;
SQLRETURN rslt = SQLGetDiagRec(
this->hStatement ? SQL_HANDLE_STMT : SQL_HANDLE_DBC,
this->hStatement ? this->hStatement : this->hConnection,
1, sqlState, &nativeError, messageText, sizeof(messageText), &messageTextLength);
if(this->okRslt(rslt)) {
if(nativeError) {
this->setLastError(nativeError, (prefixError + ": " + string((char*)messageText)).c_str(), sysLog);
return(true);
} else {
this->clearLastError();
}
}
}
return(false);
}
void SqlDb_odbc::cleanFields() {
for(unsigned int i = 0; i < this->bindBuffer.size(); i++) {
delete this->bindBuffer[i];
}
this->bindBuffer.clear();
}
void SqlDb_odbc::clean() {
this->disconnect();
this->cleanFields();
}
void *MySqlStore_process_storing(void *storeProcess_addr) {
MySqlStore_process *storeProcess = (MySqlStore_process*)storeProcess_addr;
storeProcess->store();
return(NULL);
}
MySqlStore_process::MySqlStore_process(int id, const char *host, const char *user, const char *password, const char *database) {
this->id = id;
this->terminated = false;
this->ignoreTerminating = false;
this->sqlDb = new SqlDb_mysql();
this->sqlDb->setConnectParameters(host, user, password, database);
this->sqlDb->connect();
pthread_mutex_init(&this->lock_mutex, NULL);
pthread_create(&this->thread, NULL, MySqlStore_process_storing, this);
}
MySqlStore_process::~MySqlStore_process() {
while(!this->terminated) {
usleep(100000);
}
pthread_detach(this->thread);
if(this->sqlDb) {
delete this->sqlDb;
}
}
void MySqlStore_process::query(const char *query_str) {
this->query_buff.push(query_str);
}
void MySqlStore_process::store() {
char insert_funcname[20];
sprintf(insert_funcname, "__insert_%i", this->id);
if(opt_id_sensor > -1) {
sprintf(insert_funcname + strlen(insert_funcname), "S%i", opt_id_sensor);
}
while(1) {
int size = 0;
int msgs = 50;
string queryqueue = "";
while(1) {
this->lock();
if(this->query_buff.size() == 0) {
this->unlock();
if(queryqueue != "") {
this->sqlDb->query(string("drop procedure if exists ") + insert_funcname);
this->sqlDb->query(string("create procedure ") + insert_funcname + "()\nbegin\n" + queryqueue + "\nend");
this->sqlDb->query(string("call ") + insert_funcname + "();");
queryqueue = "";
if(verbosity > 1) {
syslog(LOG_INFO, "STORE id: %i", this->id);
}
}
break;
}
string query = this->query_buff.front();
this->query_buff.pop();
this->unlock();
queryqueue.append(query + "; ");
if(size < msgs) {
size++;
} else {
this->sqlDb->query(string("drop procedure if exists ") + insert_funcname);
this->sqlDb->query(string("create procedure ") + insert_funcname + "()\nbegin\n" + queryqueue + "\nend");
this->sqlDb->query(string("call ") + insert_funcname + "();");
queryqueue = "";
size = 0;
if(verbosity > 1) {
syslog(LOG_INFO, "STORE id: %i", this->id);
}
}
}
if(terminating && !this->ignoreTerminating) {
break;
}
sleep(1);
}
this->terminated = true;
}
void MySqlStore_process::lock() {
pthread_mutex_lock(&this->lock_mutex);
}
void MySqlStore_process::unlock() {
pthread_mutex_unlock(&this->lock_mutex);
}
void MySqlStore_process::setIgnoreTerminating(bool ignoreTerminating) {
this->ignoreTerminating = ignoreTerminating;
}
MySqlStore::MySqlStore(const char *host, const char *user, const char *password, const char *database) {
this->host = host;
this->user = user;
this->password = password;
this->database = database;
}
MySqlStore::~MySqlStore() {
map<int, MySqlStore_process*>::iterator iter;
for(iter = this->processes.begin(); iter != this->processes.end(); ++iter) {
delete iter->second;
}
}
void MySqlStore::query(const char *query_str, int id) {
MySqlStore_process* process = this->find(id);
process->query(query_str);
}
void MySqlStore::lock(int id) {
MySqlStore_process* process = this->find(id);
process->lock();
}