/
sql_db.h
1608 lines (1570 loc) · 56.7 KB
/
sql_db.h
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
#ifndef SQL_DB_H
#define SQL_DB_H
#include <stdlib.h>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <mysql.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sys/file.h>
#include "tools.h"
#include "cloud_router/cloud_router_client.h"
#include "sql_db_global.h"
#define MYSQL_ROW_FORMAT_COMPRESSED "ROW_FORMAT=COMPRESSED"
#define MARIADB_PAGE_COMPRESSED "PAGE_COMPRESSED=1"
#define NULL_CHAR_PTR (const char*)NULL
#define LIMIT_DAY_PARTITIONS 3
#define LIMIT_DAY_PARTITIONS_INIT 2
#define LIMIT_TINYINT_UNSIGNED(value) (min(0xFFu, (unsigned)(value)))
#define LIMIT_SMALLINT_UNSIGNED(value) (min(0xFFFFu, (unsigned)(value)))
#define LIMIT_MEDIUMINT_UNSIGNED(value) (min(0xFFFFFFu, (unsigned)(value)))
#define LIMIT_TINYINT_SIGNED(value) ((value) > 127 ? 127 : ((value) < -128 ? -128 : (value)))
#define LIMIT_SMALLINT_SIGNED(value) ((value) > 32767 ? 32767 : ((value) < -32768 ? -32768 : (value)))
#define LIMIT_MEDIUMINT_SIGNED(value) ((value) > 8388607 ? 8388607 : ((value) < -8388608 ? -8388608 : (value)))
#define LIMIT_TINYINT_SIGNED_TO_UNSIGNED(value) (unsigned)((value) > 0XFF ? 0xFF : ((value) < 0 ? 0 : (value)))
#define LIMIT_SMALLINT_SIGNED_TO_UNSIGNED(value) (unsigned)((value) > 0xFFFF ? 0xFFFF : ((value) < 0 ? 0 : (value)))
#define LIMIT_MEDIUMINT_SIGNED_TO_UNSIGNED(value) (unsigned)((value) > 0xFFFFFF ? 0xFFFFFF : ((value) < 0 ? 0 : (value)))
using namespace std;
class SqlDb;
class SqlDb_row : public SqlDb_row_def {
public:
struct sInternalFieldValue {
int type;
union {
int64_t _int;
u_int64_t _int_u;
double _double;
} v;
vmIP v_ip;
int cb_type;
};
struct SqlDb_rowField {
SqlDb_rowField(const char *content, string fieldName = "", int type = 0, unsigned long length = 0, eInternalFieldType ift = _ift_na) {
if(content) {
if(type == MYSQL_TYPE_VAR_STRING) {
this->content = string(content, length);
} else {
this->content = content;
}
}
this->fieldName = fieldName;
this->null = !content;
this->type = type;
this->ifv.type = ift | (!content ? _ift_null : 0);
this->length = length;
}
SqlDb_rowField(string content, string fieldName = "", bool null = false, int type = 0, unsigned long length = 0, eInternalFieldType ift = _ift_na) {
this->content = content;
this->fieldName = fieldName;
this->null = null;
this->type = type;
this->ifv.type = ift | (null ? _ift_null : 0);
this->length = length;
}
string getContentForCsv();
string content;
string fieldName;
bool null;
int type;
sInternalFieldValue ifv;
unsigned long length;
};
SqlDb_row(SqlDb *sqlDb = NULL) {
this->sqlDb = sqlDb;
ignoreCheckExistsField = false;
}
void setIgnoreCheckExistsField(bool ignoreCheckExistsField = true) {
this->ignoreCheckExistsField = ignoreCheckExistsField;
}
string operator [] (const char *fieldName);
string operator [] (string fieldName);
string operator [] (int indexField);
operator int();
bool setContent(const char *fieldName, const char *newContent);
SqlDb_rowField *add(const char *content, string fieldName = "", int type = 0, unsigned long length = 0, eInternalFieldType ift = _ift_string) {
if(!ignoreCheckExistsField && fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName, type, length, ift);
return(&row[i]);
}
}
}
row.push_back(SqlDb_rowField(content, fieldName, type, length, ift));
return(&row[row.size() - 1]);
}
SqlDb_rowField *add(string content, string fieldName = "", bool null = false, eInternalFieldType ift = _ift_string) {
if(!ignoreCheckExistsField && fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(content, fieldName, null, 0, 0, ift);
return(&row[i]);
}
}
}
row.push_back(SqlDb_rowField(content, fieldName, null, 0, 0, ift));
return(&row[row.size() - 1]);
}
SqlDb_rowField *add(string content, unsigned limitLength ,string fieldName = "", bool null = false, eInternalFieldType ift = _ift_string) {
if(!ignoreCheckExistsField && fieldName != "") {
for(size_t i = 0; i < row.size(); i++) {
if(row[i].fieldName == fieldName) {
row[i] = SqlDb_rowField(limitLength > 0 && content.length() > limitLength ?
content.substr(limitLength) :
content,
fieldName, null, 0, 0, ift);
return(&row[i]);
}
}
}
row.push_back(SqlDb_rowField(limitLength > 0 && content.length() > limitLength ?
content.substr(limitLength) :
content,
fieldName, null, 0, 0, ift));
return(&row[row.size() - 1]);
}
SqlDb_rowField *add(int content, string fieldName, bool null = false) {
SqlDb_rowField *f;
if(!content && null) {
f = this->add((const char*)NULL, fieldName, 0, 0, _ift_int);
f->ifv.v._int = content;
} else {
char str_content[100];
intToString(content, str_content);
f = this->add(str_content, fieldName, 0, 0, _ift_int);
f->ifv.v._int = content;
}
return(f);
}
SqlDb_rowField *add(unsigned int content, string fieldName, bool null = false) {
SqlDb_rowField *f;
if(!content && null) {
f = this->add((const char*)NULL, fieldName, 0, 0, _ift_int_u);
f->ifv.v._int_u = content;
} else {
char str_content[100];
intToString(content, str_content);
f = this->add(str_content, fieldName, 0, 0, _ift_int_u);
f->ifv.v._int_u = content;
}
return(f);
}
void add(long int content, string fieldName, bool null = false) {
if(!content && null) {
this->add((const char*)NULL, fieldName, 0, 0, _ift_int)
->ifv.v._int = content;
} else {
char str_content[100];
intToString(content, str_content);
this->add(str_content, fieldName, 0, 0, _ift_int)
->ifv.v._int = content;
}
}
void add(unsigned long int content, string fieldName, bool null = false) {
if(!content && null) {
this->add((const char*)NULL, fieldName, 0, 0, _ift_int_u)
->ifv.v._int_u = content;
} else {
char str_content[100];
intToString(content, str_content);
this->add(str_content, fieldName, 0, 0, _ift_int_u)
->ifv.v._int_u = content;
}
}
void add(long long int content, string fieldName, bool null = false) {
if(!content && null) {
this->add((const char*)NULL, fieldName, 0, 0, _ift_int)
->ifv.v._int = content;
} else {
char str_content[100];
intToString(content, str_content);
this->add(str_content, fieldName, 0, 0, _ift_int)
->ifv.v._int = content;
}
}
void add(unsigned long long int content, string fieldName, bool null = false) {
if(!content && null) {
this->add((const char*)NULL, fieldName, 0, 0, _ift_int_u)
->ifv.v._int_u = content;
} else {
char str_content[100];
intToString(content, str_content);
this->add(str_content, fieldName, 0, 0, _ift_int_u)
->ifv.v._int_u = content;
}
}
void add(double content, string fieldName, bool null = false) {
if(!content && null) {
this->add((const char*)NULL, fieldName, 0, 0, _ift_double)
->ifv.v._double = content;
} else {
char str_content[100];
floatToString(content, str_content);
this->add(str_content, fieldName, 0, 0, _ift_double)
->ifv.v._double = content;
}
}
void add(vmIP content, string fieldName, bool null, SqlDb *sqlDb, const char *table);
void add_calldate(u_int64_t calldate_us, string fieldName, bool use_ms);
void add_duration(u_int64_t duration_us, string fieldName, bool use_ms, bool round_s = false, u_int64_t limit = 0);
void add_duration(int64_t duration_us, string fieldName, bool use_ms, bool round_s = false, int64_t limit = 0);
void add_cb_string(string content, string fieldName, int cb_type);
void add_null(string fieldName) {
row.push_back(SqlDb_rowField(NULL, fieldName));
}
int 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(_getIndexField(fieldName));
}
return(-1);
}
int _getIndexField(string fieldName);
string getNameField(int indexField) {
if((unsigned)indexField < row.size()) {
if(!row[indexField].fieldName.empty()) {
return(row[indexField].fieldName);
}
if(this->sqlDb) {
return(_getNameField(indexField));
}
}
return("");
}
string _getNameField(int indexField);
unsigned long getLengthField(string fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].length);
}
return(0);
}
int getTypeField(string fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].type);
}
return(0);
}
SqlDb_rowField *getField(string fieldName, int *_indexField = NULL) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
if(_indexField) {
*_indexField = indexField;
}
return(&row[indexField]);
}
return(NULL);
}
bool isEmpty() {
return(!row.size());
}
bool isNull(string fieldName) {
int indexField = this->getIndexField(fieldName);
if(indexField >= 0) {
return(row[indexField].null);
}
return(false);
}
string implodeFields(string separator = ",", string border = "");
string implodeFieldsToCsv();
string implodeContent(string separator = ",", string border = "'", bool enableSqlString = false, bool escapeAll = false);
string implodeFieldContent(string separator = ",", string fieldBorder = "`", string contentBorder = "'", bool enableSqlString = false, bool escapeAll = false);
string implodeContentTypeToCsv(bool enableSqlString = false);
string keyvalList(string separator);
size_t getCountFields();
void removeFieldsIfNotContainIn(map<string, int> *fields);
void clearSqlDb();
void clear() {
row.clear();
}
private:
SqlDb *sqlDb;
vector<SqlDb_rowField> row;
bool ignoreCheckExistsField;
};
class SqlDb_rows {
public:
SqlDb_rows();
~SqlDb_rows();
void push(SqlDb_row *row);
SqlDb_row &fetchRow();
void initFetch();
unsigned countRow();
operator unsigned();
void clear();
private:
list<SqlDb_row> rows;
list<SqlDb_row>::iterator *iter_rows;
friend class SqlDb;
};
class SqlDb {
public:
enum eSupportPartitions {
_supportPartitions_na,
_supportPartitions_ok,
_supportPartitions_oldver
};
enum eTypeQuery {
_tq_std,
_tq_store,
_tq_redirect
};
enum eTypePartition {
_tp_na,
_tp_day,
_tp_hour,
_tp_month
};
struct sPartition {
sPartition() {
file_size = -1;
/*
part_size = -1;
*/
type = _tp_na;
is_prev = false;
}
string name;
string table;
string file;
int64_t file_size;
/* irrelevant - inaccurate results
int64_t part_size;
*/
eTypePartition type;
string time;
bool is_prev;
bool operator < (const sPartition& other) const {
return(strcasecmp(this->name.c_str(), other.name.c_str()) < 0);
}
};
public:
SqlDb();
virtual ~SqlDb();
void setConnectParameters(string server, string user, string password, string database = "", u_int16_t port = 0, string socket = "",
bool showversion = true,
mysqlSSLOptions *sslOpt = NULL);
void setCloudParameters(string cloud_host, string cloud_token, bool cloud_router);
void setLoginTimeout(ulong loginTimeout);
void setDisableSecureAuth(bool disableSecureAuth = true);
virtual bool connect(bool craeteDb = false, bool mainInit = false) = 0;
virtual void disconnect() = 0;
virtual bool connected() = 0;
bool reconnect();
void setCsvInRemoteResult(bool useCsvInRemoteResult = true);
virtual bool query(string query, bool callFromStoreProcessWithFixDeadlock = false, const char *dropProcQuery = NULL) = 0;
bool queryByCurl(string query, bool callFromStoreProcessWithFixDeadlock = false);
bool queryByRemoteSocket(string query, bool callFromStoreProcessWithFixDeadlock = false, const char *dropProcQuery = NULL);
int _queryByRemoteSocket(string query, unsigned int pass);
int processResponseFromQueryBy(const char *response, const char *query, unsigned pass);
int processResponseFromCsv(const char *response);
virtual string prepareQuery(string query, bool nextPass);
virtual SqlDb_row fetchRow() = 0;
string fetchValue(int indexField = 0);
string fetchValue(const char *nameField);
bool fetchValues(vector<string> *values, list<int> *indexFields);
bool fetchValues(vector<string> *values, list<string> *nameFields);
unsigned fetchRows(SqlDb_rows *rows);
virtual string getJsonResult() { return(""); }
virtual string getCsvResult() { return(""); }
virtual string getJsonError() { return(""); }
virtual string getFieldsStr(list<SqlDb_field> *fields);
virtual string getCondStr(list<SqlDb_condField> *cond, bool forceLatin1 = false);
virtual string selectQuery(string table, list<SqlDb_field> *fields = NULL, list<SqlDb_condField> *cond = NULL, unsigned limit = 0, bool forceLatin1 = false);
virtual string selectQuery(string table, const char *field, const char *condField = NULL, const char *condValue = NULL, unsigned limit = 0, bool forceLatin1 = false);
virtual string insertQuery(string table, SqlDb_row row, bool enableSqlStringInContent = false, bool escapeAll = false, bool insertIgnore = false, SqlDb_row *row_on_duplicate = NULL);
virtual string insertOrUpdateQuery(string table, SqlDb_row row, SqlDb_row row_on_duplicate, bool enableSqlStringInContent = false, bool escapeAll = false, bool insertIgnore = false);
virtual string insertQuery(string table, vector<SqlDb_row> *rows, bool enableSqlStringInContent = false, bool escapeAll = false, bool insertIgnore = false);
virtual string insertQueryWithLimitMultiInsert(string table, vector<SqlDb_row> *rows, unsigned limitMultiInsert, const char *queriesSeparator = NULL, const char *queriesSeparatorSubst = NULL,
bool enableSqlStringInContent = false, bool escapeAll = false, bool insertIgnore = false);
virtual string updateQuery(string table, SqlDb_row row, const char *whereCond, bool enableSqlStringInContent = false, bool escapeAll = false);
virtual string updateQuery(string table, SqlDb_row row, SqlDb_row whereCond, bool enableSqlStringInContent = false, bool escapeAll = false);
virtual bool select(string table, list<SqlDb_field> *fields = NULL, list<SqlDb_condField> *cond = NULL, unsigned limit = 0, bool forceLatin1 = false);
virtual bool select(string table, const char *field, const char *condField = NULL, const char *condValue = NULL, unsigned limit = 0, bool forceLatin1 = false);
virtual int64_t insert(string table, SqlDb_row row);
virtual int64_t insert(string table, vector<SqlDb_row> *rows);
virtual bool update(string table, SqlDb_row row, const char *whereCond);
virtual bool update(string table, SqlDb_row row, SqlDb_row whereCond);
virtual int getIdOrInsert(string table, string idField, string uniqueField, SqlDb_row row, const char *uniqueField2 = NULL);
virtual int64_t getInsertId() = 0;
string getQueryRsltStringValue(string query, int indexRslt);
int64_t getQueryRsltIntValue(string query, int indexRslt, int64_t failedResult);
virtual bool existsDatabase() = 0;
virtual bool existsTable(const char *table) = 0;
bool existsTable(string table) { return(existsTable(table.c_str())); }
virtual bool existsColumn(const char *table, const char *column, string *type = NULL) = 0;
bool existsColumn(string table, string column, string *type = NULL) { return(existsColumn(table.c_str(), column.c_str(), type)); }
bool existsMultipleColumns(const char *table, ...);
void startExistsColumnCache();
void stopExistsColumnCache();
void suspendExistsColumnCache();
void resumeExistsColumnCache();
bool isEnableExistColumnCache();
int existsColumnInCache(const char *table, const char *column, string *type = NULL);
void addColumnToCache(const char *table, const char *column, const char *type);
void removeTableFromColumnCache(const char *table);
virtual string getTypeColumn(const char *table, const char *column, bool toLower = true, bool useCache = false) = 0;
string getTypeColumn(string table, string column, bool toLower = true, bool useCache = false) { return(getTypeColumn(table.c_str(), column.c_str(), toLower, useCache)); }
virtual bool existsColumnInTypeCache(const char *table, const char *column) = 0;
bool existsColumnInTypeCache(string table, string column) {
return(existsColumnInCache(table.c_str(), column.c_str()));
}
virtual bool existsIndex(const char *table, const char *indexColumn, int seqInIndex = 0) = 0;
bool isIPv6Column(string table, string column, bool useCache = true);
bool isIPv4Column(string table, string column, bool useCache = true) {
return(!isIPv6Column(table, column, useCache));
}
static bool _isIPv6Column(string table, string column);
static bool _isIPv4Column(string table, string column) {
return(!_isIPv6Column(table, column));
}
virtual int getPartitions(const char *datadir, const char *database, const char *table, list<sPartition> *partitions = NULL, bool useCache = true) = 0;
int getPartitions(string table, list<sPartition> *partitions, bool useCache) { return(getPartitions(NULL, NULL, table.c_str(), partitions, useCache)); }
int getPartitions(const char *table, vector<sPartition> *partitions, bool useCache = true);
int getPartitions(string table, vector<sPartition> *partitions, bool useCache) { return(getPartitions(table.c_str(), partitions, useCache)); }
virtual bool existsPartition(const char *table, const char *partition, bool useCache = true) = 0;
bool existsPartition(string table, string partition, bool useCache) { return(existsPartition(table.c_str(), partition.c_str(), useCache)); }
bool existsDayPartition(string table, unsigned addDaysToNow, bool useCache = true);
bool existsHourPartition(string table, unsigned addHoursToNow, bool checkDayPartition = true, bool useCache = true);
virtual bool emptyTable(const char *table, bool viaTableStatus = false) = 0;
bool emptyTable(string table, bool viaTableStatus = false) { return(emptyTable(table.c_str(), viaTableStatus)); }
virtual int64_t rowsInTable(const char *table, bool viaTableStatus = false) = 0;
int64_t rowsInTable(string table, bool viaTableStatus = false) { return(rowsInTable(table.c_str(), viaTableStatus)); }
virtual int64_t sizeOfTable(const char *table) = 0;
int64_t sizeOfTable(string table) { return(sizeOfTable(table.c_str())); }
virtual bool isOldVerPartition(const char *table) { return(false); }
bool isOldVerPartition(string table) { return(isOldVerPartition(table.c_str())); }
virtual int getIndexField(string fieldName);
virtual string getNameField(int indexField);
virtual string escape(const char *inputString, int length = 0) = 0;
virtual string getFieldBorder() {
return("");
}
virtual string getFieldSeparator() {
return(",");
}
virtual string getContentBorder() {
return("'");
}
virtual string getContentSeparator() {
return(",");
}
virtual string escapeTableName(string tableName) {
return(tableName);
}
virtual bool checkLastError(string /*prefixError*/, bool /*sysLog*/ = false, bool /*clearLastError*/ = false) {
return(false);
}
virtual void evError(int pass) {
}
void setLastError(unsigned int lastError, const char *lastErrorString, bool sysLog = false) {
this->lastError = lastError;
if(lastErrorString) {
this->setLastErrorString(lastErrorString, sysLog);
}
}
void setLastError(unsigned int lastError, string lastErrorString, bool sysLog = false) {
this->setLastError(lastError, lastErrorString.c_str(), sysLog);
}
unsigned int getLastError() {
return(this->lastError);
}
void setLastErrorString(string lastErrorString, bool sysLog = false);
string getLastErrorString() {
return(this->lastErrorString);
}
bool isError() {
return(this->lastError ||
this->lastErrorString != "");
}
void clearLastError() {
this->lastError = 0;
this->lastErrorString = "";
}
bool ignoreLastError();
void setMaxQueryPass(unsigned int maxQueryPass) {
this->maxQueryPass = maxQueryPass;
}
unsigned int getMaxQueryPass() {
return(this->maxQueryPass);
}
void setIgnoreErrorCode(unsigned int errorCode) {
this->ignoreErrorCodes.push_back(errorCode);
}
void clearIgnoreErrorCodes() {
this->ignoreErrorCodes.clear();
}
virtual void cleanFields();
virtual void clean() = 0;
virtual bool createSchema(int connectId = 0) = 0;
virtual void createTable(const char *tableName) = 0;
virtual void checkDbMode() = 0;
virtual void checkSchema(int connectId = 0, bool checkColumnsSilentLog = false) = 0;
virtual void updateSensorState() = 0;
virtual string getTypeDb() = 0;
virtual string getSubtypeDb() = 0;
virtual int multi_on() {
return(1);
}
virtual int multi_off() {
return(1);
}
virtual int getDbVersion() {
return(getDbMajorVersion() * 10000 +
getDbMinorVersion() * 100 +
getDbMinorVersion(1));
}
virtual string getDbVersionString() {
return(intToString(getDbMajorVersion()) + "." +
intToString(getDbMinorVersion()) + "." +
intToString(getDbMinorVersion(1)));
}
virtual int getDbMajorVersion() {
return(0);
}
virtual int getDbMinorVersion(int /*minorLevel*/ = 0) {
return(0);
}
virtual string getDbName() {
return("");
}
virtual string getDbDatadir() {
return("");
}
virtual bool getDbDatadirStats(const char */*datadir*/, const char */*database*/, double */*total_MB*/, double */*free_MB*/, double */*free_perc*/, double */*files_sum_size_MB*/) {
return(false);
}
string getDatadirTab(const char *datadir, const char *database);
virtual int getMaximumPartitions() {
return(0);
}
void setEnableSqlStringInContent(bool enableSqlStringInContent);
void setDisableNextAttemptIfError();
void setEnableNextAttemptIfError();
void setDisableLogError();
void setEnableLogError();
void setDisableLogError(bool disableLogError);
bool getDisableLogError();
void setSilentConnect();
bool isCloud() {
return(cloud_host[0] && cloud_token[0] && cloud_router);
}
inline static void addDelayQuery(u_int32_t delay_ms, eTypeQuery typeQuery = _tq_std) {
__SYNC_ADD(delayQuery_sum_ms[typeQuery], delay_ms);
__SYNC_INC(delayQuery_count[typeQuery]);
}
inline static u_int32_t getAvgDelayQuery(eTypeQuery typeQuery = _tq_std) {
return(delayQuery_count[typeQuery] ? delayQuery_sum_ms[typeQuery] / delayQuery_count[typeQuery] : 0);
}
inline static u_int32_t getCountQuery(eTypeQuery typeQuery = _tq_std) {
return(delayQuery_count[typeQuery]);
}
inline static void resetDelayQuery(eTypeQuery typeQuery = _tq_std) {
delayQuery_sum_ms[typeQuery] = 0;
delayQuery_count[typeQuery] = 0;
}
inline static void addCountInsert(u_int32_t qc) {
__SYNC_ADD(insert_count, qc);
}
inline static u_int32_t getCountInsert() {
return(insert_count);
}
inline static void resetCountInsert() {
insert_count = 0;
}
bool logNeedAlter(string table, string reason, string alter,
bool log, map<string, u_int64_t> *tableSize, bool *existsColumnFlag);
int checkNeedAlterAdd(string table, string reason, bool tryAlter,
bool log, map<string, u_int64_t> *tableSize, bool *existsColumnFlag,
...);
bool logNeedAlter(string table, string reason, vector<string> alters,
bool log, map<string, u_int64_t> *tableSize, bool *existsColumnFlag);
protected:
string conn_server;
string conn_user;
string conn_password;
string conn_database;
u_int16_t conn_port;
string conn_socket;
char *conn_sslkey;
char *conn_sslcert;
char *conn_sslcacert;
char *conn_sslcapath;
string conn_sslciphers;
bool conn_disable_secure_auth;
string cloud_host;
string cloud_redirect;
string cloud_token;
bool cloud_router;
bool conn_showversion;
ulong loginTimeout;
unsigned int maxQueryPass;
list<unsigned int> ignoreErrorCodes;
vector<string> fields;
vector<int> fields_type;
bool enableSqlStringInContent;
bool disableNextAttemptIfError;
bool disableLogError;
bool silentConnect;
bool connecting;
vector<string> response_data_columns;
vector<int> response_data_columns_types;
vector<vector<string_null> > response_data;
size_t response_data_rows;
size_t response_data_index;
unsigned long maxAllowedPacket;
string prevQuery;
bool useCsvInRemoteResult;
map<string, map<string, string> > existsColumn_cache;
bool existsColumn_cache_enable;
bool existsColumn_cache_suspend;
volatile int existsColumn_cache_sync;
static map<string, map<string, string> > typeColumn_cache;
static volatile int typeColumn_cache_sync;
map<string, list<sPartition> > partitions_cache;
volatile int partitions_cache_sync;
private:
unsigned int lastError;
string lastErrorString;
static volatile u_int64_t delayQuery_sum_ms[3];
static volatile u_int32_t delayQuery_count[3];
static volatile u_int32_t insert_count;
cSocketBlock *remote_socket;
friend class MySqlStore_process;
};
class SqlDb_mysql : public SqlDb {
public:
enum eRoutineType {
procedure,
function
};
enum eTypeTables {
tt_minor = 1,
tt_main = 2,
tt_child = 4,
tt_all = 7
};
enum eTypeTables2 {
tt2_na = 0,
tt2_cdr_static = 1 << 0,
tt2_cdr_dynamic = 1 << 1,
tt2_cdr = (1 << 0) | (1 << 1),
tt2_message_static = 1 << 2,
tt2_message_dynamic = 1 << 3,
tt2_message = (1 << 2) | (1 << 3),
tt2_register = 1 << 4,
tt2_sip_msg_static = 1 << 5,
tt2_sip_msg_dynamic = 1 << 6,
tt2_sip_msg = (1 << 5) | (1 << 6),
tt2_http_enum = (1 << 7),
tt2_webrtc = (1 << 8),
tt2_static = tt2_cdr_static |
tt2_message_static |
tt2_register |
tt2_sip_msg_static |
tt2_http_enum |
tt2_webrtc
};
public:
SqlDb_mysql();
~SqlDb_mysql();
bool connect(bool craeteDb = false, bool mainInit = false);
void disconnect();
bool connected();
bool query(string query, bool callFromStoreProcessWithFixDeadlock = false, const char *dropProcQuery = NULL);
SqlDb_row fetchRow();
bool fetchQueryResult(vector<string> *fields, vector<int> *fields_types, vector<map<string, string_null> > *rows);
string getJsonResult(vector<string> *fields, vector<int> *fields_types, vector<map<string, string_null> > *rows);
string getJsonResult();
string getCsvResult();
string getJsonError();
int64_t getInsertId();
bool existsDatabase();
bool existsTable(const char *table);
list<string> getAllTables();
bool existsTable(string table) { return(existsTable(table.c_str())); }
bool existsColumn(const char *table, const char *column, string *type = NULL);
string getTypeColumn(const char *table, const char *column, bool toLower = true, bool useCache = false);
bool existsColumnInTypeCache(const char *table, const char *column);
static bool existsColumnInTypeCache_static(const char *table, const char *column);
bool existsIndex(const char *table, const char *indexColumn, int seqInIndex = 0);
int getPartitions(const char *datadir, const char *database, const char *table, list<sPartition> *partitions = NULL, bool useCache = true);
bool existsPartition(const char *table, const char *partition, bool useCache = true);
bool emptyTable(const char *table, bool viaTableStatus = false);
int64_t rowsInTable(const char *table, bool viaTableStatus = false);
int64_t sizeOfTable(const char *table);
bool isOldVerPartition(const char *table);
string escape(const char *inputString, int length = 0);
string getFieldBorder() {
return("`");
}
string escapeTableName(string tableName);
bool isReservedWord(string word);
bool checkLastError(string prefixError, bool sysLog = false,bool clearLastError = false);
void evError(int pass);
void clean();
bool createSchema(int connectId = 0);
bool createSchema_tables_other(int connectId);
bool createSchema_tables_billing_agregation();
bool createSchema_table_http_jj(int connectId);
bool createSchema_table_webrtc(int connectId);
bool createSchema_alter_other(int connectId);
bool createSchema_alter_http_jj(int connectId);
bool createSchema_procedures_other(int connectId);
bool createSchema_procedure_partition(int connectId, bool abortIfFailed = true);
bool createSchema_init_cdr_partitions(int connectId);
string getPartMonthName(string *limitDay_str, int next = 0);
string getPartDayName(string *limitDay_str, int next = 0);
string getPartHourName(string *limitHour_str, int next = 0);
string getPartHourName(string *limitHour_str, int next_day, int hour);
void fillPartitionData(sPartition *partition, const char *datadir, const char *database, const char *table, const char *partition_name, bool last);
string getPartitionFile(const char *datadir, const char *database, const char *table, const char *partition_name);
int64_t getPartitionSize(const char *database, const char *table, const char *partition_name);
eTypePartition getPartitionType(const char *partition_name);
string getPartitionTime(const char *partition_name);
void saveTimezoneInformation();
void createTable(const char *tableName);
void checkDbMode();
void checkSchema(int connectId = 0, bool checkColumnsSilentLog = false);
void updateSensorState();
void checkColumns_cdr(bool log = false);
void checkColumns_cdr_next(bool log = false);
void checkColumns_cdr_next_branches(bool log = false);
void checkColumns_cdr_sdp(bool log = false);
void checkColumns_cdr_rtp(bool log = false);
void checkColumns_cdr_dtmf(bool log = false);
void checkColumns_cdr_conference(bool log = false);
void checkColumns_cdr_child(bool log = false);
void checkColumns_cdr_stat(bool log = false);
void checkColumns_ss7(bool log = false);
void checkColumns_message(bool log = false);
void checkColumns_message_child(bool log = false);
void checkColumns_register(bool log = false);
void checkColumns_sip_msg(bool log = false);
void checkColumns_other(bool log = false);
bool existsExtPrecissionBilling();
string column_type_datetime_ms();
string column_type_datetime_child_ms();
string column_type_duration_ms(const char *base_type = NULL);
bool checkSourceTables();
void copyFromSourceTablesMinor(SqlDb_mysql *sqlDbSrc,
cSqlDbCodebooks *cb_src = NULL, cSqlDbCodebooks *cb_dst = NULL);
void copyFromSourceTablesMain(SqlDb_mysql *sqlDbSrc,
unsigned long limit = 0, bool descDir = false,
bool skipRegister = false,
bool skipMissingTables = false,
cSqlDbCodebooks *cb_src = NULL, cSqlDbCodebooks *cb_dst = NULL);
void copyFromSourceTable(SqlDb_mysql *sqlDbSrc,
const char *tableName,
unsigned long limit, bool descDir = false,
cSqlDbCodebooks *cb_src = NULL, cSqlDbCodebooks *cb_dst = NULL);
void copyFromSourceTableSlave(SqlDb_mysql *sqlDbSrc,
const char *masterTableName, const char *slaveTableName,
const char *slaveIdToMasterColumn,
const char *masterCalldateColumn, const char *slaveCalldateColumn,
u_int64_t useMinIdMaster, u_int64_t useMaxIdMaster,
unsigned long limit, bool descDir = false, u_int64_t limitMaxId = 0,
cSqlDbCodebooks *cb_src = NULL, cSqlDbCodebooks *cb_dst = NULL);
vector<string> getSourceTables(int typeTables = tt_all, int typeTables2 = tt2_na);
bool getReferenceTablesMap(const char *table, map<string, cSqlDbCodebook::eTypeCodebook> *reftable_map);
bool convId(SqlDb_row *row, const char *table,
cSqlDbCodebooks *cb_src, cSqlDbCodebooks *cb_dst,
map<string, cSqlDbCodebook::eTypeCodebook> *reftable_map);
bool convId(SqlDb_row *row, const char *table, const char *column,
cSqlDbCodebook::eTypeCodebook cb_type, cSqlDbCodebooks *cb_src, cSqlDbCodebooks *cb_dst);
unsigned convId(unsigned id,
cSqlDbCodebook *cb_src, cSqlDbCodebook *cb_dst);
string getTypeDb() {
return("mysql");
}
string getSubtypeDb() {
return("");
}
int multi_on();
int multi_off();
int getDbMajorVersion();
int getDbMinorVersion(int minorLevel = 0);
string getDbName();
static int getDbVersion_static();
static int getDbMajorVersion_static();
static int getDbMinorVersion_static(int minorLevel = 0);
static string getDbName_static();
static int _getDbMajorVersion(const char *db_version);
static int _getDbMinorVersion(const char *db_version, int minorLevel = 0);
static string _getDbName(const char *db_version);
string getDbDatadir();
bool getDbDatadirStats(const char *datadir, const char *database, double *total_MB, double *free_MB, double *free_perc, double *files_sum_size_MB);
int getMaximumPartitions();
bool isSupportForDatetimeMs();
bool _getDbVersion();
bool createRoutine(string routine, string routineName, string routineParamsAndReturn, eRoutineType routineType, bool abortIfFailed = false);
bool createFunction(string routine, string routineName, string routineParamsAndReturn, bool abortIfFailed = false) {
return(this->createRoutine(routine, routineName, routineParamsAndReturn, function, abortIfFailed));
}
bool createProcedure(string routine, string routineName, string routineParamsAndReturn, bool abortIfFailed = false) {
return(this->createRoutine(routine, routineName, routineParamsAndReturn, procedure, abortIfFailed));
}
MYSQL *getH_Mysql() {
return(this->hMysql);
}
string getOptimalCompressType(bool memoryEngine = false, bool useCache = true);
string getOptimalCompressType_mysql(bool memoryEngine, bool useCache);
string getOptimalCompressType_mariadb(bool memoryEngine, bool useCache);
bool testCreateTable(bool memoryEngine, const char *compressType);
void setSelectedCompressType(bool memoryEngine, const char *type, const char *subtype = NULL);
private:
MYSQL *hMysql;
MYSQL *hMysqlConn;
MYSQL_RES *hMysqlRes;
string dbVersion;
static string dbVersion_static;
static volatile int dbVersion_static_sync;
string dbDatadir;
unsigned long mysqlThreadId;
string selectedCompressType;
string selectedCompressSubtype;
string selectedCompressType_memoryEngine;
string selectedCompressSubtype_memoryEngine;
};
class SqlDb_odbc_bindBufferItem {
public:
SqlDb_odbc_bindBufferItem(SQLUSMALLINT colNumber, string fieldName, SQLSMALLINT dataType, SQLULEN columnSize, SQLHSTMT hStatement = NULL);
SqlDb_odbc_bindBufferItem(const SqlDb_odbc_bindBufferItem &other);
~SqlDb_odbc_bindBufferItem();
void bindCol(SQLHSTMT hStatement);
string getContent();
char *getBuffer();
private:
SQLUSMALLINT colNumber;
string fieldName;
SQLSMALLINT dataType;
SQLULEN columnSize;
char *buffer;
SQLLEN ind;
friend class SqlDb_odbc;
friend class SqlDb_odbc_bindBuffer;
};
class SqlDb_odbc_bindBuffer : public vector<SqlDb_odbc_bindBufferItem*> {
public:
void addItem(SQLUSMALLINT colNumber, string fieldName, SQLSMALLINT dataType, SQLULEN columnSize, SQLHSTMT hStatement = NULL);
void bindCols(SQLHSTMT hStatement);
string getColContent(string fieldName);
string getColContent(unsigned int fieldIndex);
char *getColBuffer(unsigned int fieldIndex);
int getIndexField(string fieldName);
};
class SqlDb_odbc : public SqlDb {
public:
SqlDb_odbc();
~SqlDb_odbc();
void setOdbcVersion(ulong odbcVersion);
void setSubtypeDb(string subtypeDb);
bool connect(bool craeteDb = false, bool mainInit = false);
void disconnect();
bool connected();
bool query(string query, bool callFromStoreProcessWithFixDeadlock = false, const char *dropProcQuery = NULL);
SqlDb_row fetchRow();
int64_t getInsertId();
bool existsDatabase();
bool existsTable(const char *table);
bool existsColumn(const char *table, const char *column, string *type = NULL);
string getTypeColumn(const char *table, const char *column, bool toLower = true, bool useCache = false);
bool existsColumnInTypeCache(const char *table, const char *column);
bool existsIndex(const char *table, const char *indexColumn, int seqInIndex = 0);
int getPartitions(const char *datadir, const char *database, const char *table, list<sPartition> *partitions = NULL, bool useCache = true);
bool existsPartition(const char *table, const char *partition, bool useCache = true);
bool emptyTable(const char *table, bool viaTableStatus = false);
int64_t rowsInTable(const char *table, bool viaTableStatus = false);
int64_t sizeOfTable(const char *table);
int getIndexField(string fieldName);
string escape(const char *inputString, int length = 0);
bool checkLastError(string prefixError, bool sysLog = false,bool clearLastError = false);
void evError(int pass);
void cleanFields();
void clean();
bool createSchema(int connectId = 0);
void createTable(const char *tableName);
void checkDbMode();
void checkSchema(int connectId = 0, bool checkColumnsSilentLog = false);
void updateSensorState();
string getTypeDb() {
return("odbc");
}
string getSubtypeDb() {
return(this->subtypeDb);
}
private:
bool okRslt(SQLRETURN rslt) {
return rslt == SQL_SUCCESS || rslt == SQL_SUCCESS_WITH_INFO;
}
private:
ulong odbcVersion;
string subtypeDb;
SQLHANDLE hEnvironment;
SQLHANDLE hConnection;
SQLHANDLE hStatement;
SqlDb_odbc_bindBuffer bindBuffer;
};
class MySqlStore_process {
public:
MySqlStore_process(int id_main, int id_2, class MySqlStore *parentStore,
const char *host, const char *user, const char *password, const char *database, u_int16_t port, const char *socket,
const char *cloud_host, const char *cloud_token, bool cloud_router, int concatLimit, mysqlSSLOptions *mySSLOpt);
~MySqlStore_process();
void connect();
void disconnect();
bool connected();
void query(const char *query_str);
void queryByRemoteSocket(const char *query_str);
void queryByServiceConnection(const char *query_str);
void store();
void _store(string beginProcedure, string endProcedure, list<string> *queries);
void __store(list<string> *queries);
void __store(string beginProcedure, string endProcedure, string &queries);
void exportToFile(FILE *file, bool sqlFormat, bool cleanAfterExport);
void _exportToFileSqlFormat(FILE *file, string queries);
void lock() {
__SYNC_LOCK_USLEEP(lock_sync, 10);
}
void unlock() {
__SYNC_UNLOCK(lock_sync);
}
void setEnableTerminatingDirectly(bool enableTerminatingDirectly);
void setEnableTerminatingIfEmpty(bool enableTerminatingIfEmpty);
void setEnableTerminatingIfSqlError(bool enableTerminatingIfSqlError);
void setEnableAutoDisconnect(bool enableAutoDisconnect = true);
void setConcatLimit(int concatLimit);
int getConcatLimit();
void setEnableTransaction(bool enableTransaction = true);
void setEnableFixDeadlock(bool enableFixDeadlock = true);
void setQueryBuffLimit(int queryBuffLimit);
int getIdMain() {
return(this->id_main);
}
int getId2() {
return(this->id_2);
}
size_t getSize() {
return(this->query_buff.size());
}
void waitForTerminate();
void waitForFullQueue();
private:
string getInsertFuncName();
private:
int id_main;
int id_2;
MySqlStore *parentStore;
int concatLimit;
bool enableTransaction;
bool enableFixDeadlock;
int queryBuffLimit;
pthread_t thread;
volatile u_int64_t threadRunningCounter;
u_int64_t lastThreadRunningCounterCheck;
u_long lastThreadRunningTimeCheck;
volatile int lock_sync;
SqlDb *sqlDb;
deque<string> query_buff;