-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDbUtil.cpp
More file actions
executable file
·753 lines (613 loc) · 15.9 KB
/
Copy pathDbUtil.cpp
File metadata and controls
executable file
·753 lines (613 loc) · 15.9 KB
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
/*
Copyright (C) 2007, 2008 MySQL AB, 2008, 2009 Sun Microsystems, Inc.
All rights reserved. Use is subject to license terms.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* DbUtil.cpp: implementation of the database utilities class.*/
#include "DbUtil.hpp"
#include <NdbSleep.h>
#include <NdbAutoPtr.hpp>
/* Constructors */
DbUtil::DbUtil(const char* _dbname,
const char* _suffix):
m_mysql(NULL),
m_free_mysql(true),
m_connected(false),
m_user("root"),
m_pass(""),
m_dbname(_dbname),
m_silent(false)
{
const char* env= getenv("MYSQL_HOME");
if (env && strlen(env))
{
m_default_file.assfmt("%s/my.cnf", env);
}
if (_suffix != NULL){
m_default_group.assfmt("client%s", _suffix);
}
else {
m_default_group.assign("client.1.master");
}
ndbout << "default_file: " << m_default_file.c_str() << endl;
ndbout << "default_group: " << m_default_group.c_str() << endl;
}
DbUtil::DbUtil(MYSQL* mysql):
m_mysql(mysql),
m_free_mysql(false),
m_connected(true)
{
}
bool
DbUtil::isConnected(){
if (m_connected == true)
{
assert(m_mysql);
return true;
}
return connect();
}
bool
DbUtil::waitConnected(int timeout) {
timeout*= 10;
while(!isConnected()){
if (timeout-- == 0)
return false;
NdbSleep_MilliSleep(100);
}
return true;
}
void
DbUtil::disconnect(){
if (m_mysql != NULL){
if (m_free_mysql)
mysql_close(m_mysql);
m_mysql= NULL;
}
m_connected = false;
}
/* Destructor */
DbUtil::~DbUtil()
{
disconnect();
}
/* Database Login */
bool
DbUtil::databaseLogin(const char* system, const char* usr,
const char* password, unsigned int portIn,
const char* sockIn, bool transactional)
{
if (!(m_mysql = mysql_init(NULL)))
{
myerror("DB Login-> mysql_init() failed");
return false;
}
setUser(usr);
setHost(system);
setPassword(password);
setPort(portIn);
setSocket(sockIn);
m_dbname.assign("test");
if (!(mysql_real_connect(m_mysql,
m_host.c_str(),
m_user.c_str(),
m_pass.c_str(),
m_dbname.c_str(),
m_port,
m_socket.c_str(), 0)))
{
myerror("connection failed");
disconnect();
return false;
}
m_mysql->reconnect = TRUE;
/* set AUTOCOMMIT */
if(!transactional)
mysql_autocommit(m_mysql, TRUE);
else
mysql_autocommit(m_mysql, FALSE);
#ifdef DEBUG
printf("\n\tConnected to MySQL server version: %s (%lu)\n\n",
mysql_get_server_info(m_mysql),
(unsigned long) mysql_get_server_version(m_mysql));
#endif
selectDb();
m_connected= true;
return true;
}
/* Database Connect */
bool
DbUtil::connect()
{
if (!(m_mysql = mysql_init(NULL)))
{
myerror("DB connect-> mysql_init() failed");
return false;
}
/* Load connection parameters file and group */
if (mysql_options(m_mysql, MYSQL_READ_DEFAULT_FILE, m_default_file.c_str()) ||
mysql_options(m_mysql, MYSQL_READ_DEFAULT_GROUP, m_default_group.c_str()))
{
myerror("DB Connect -> mysql_options failed");
disconnect();
return false;
}
/*
Connect, read settings from my.cnf
NOTE! user and password can be stored there as well
*/
if (mysql_real_connect(m_mysql, NULL,
m_user.c_str(),
m_pass.c_str(),
m_dbname.c_str(),
0, NULL, 0) == NULL)
{
myerror("connection failed");
disconnect();
return false;
}
selectDb();
m_connected= true;
assert(m_mysql);
return true;
}
/* Database Logout */
void
DbUtil::databaseLogout()
{
if (m_mysql){
#ifdef DEBUG
printf("\n\tClosing the MySQL database connection ...\n\n");
#endif
mysql_close(m_mysql);
}
}
/* Prepare MySQL Statements Cont */
MYSQL_STMT *STDCALL
DbUtil::mysqlSimplePrepare(const char *query)
{
#ifdef DEBUG
printf("Inside DbUtil::mysqlSimplePrepare\n");
#endif
MYSQL_STMT *my_stmt= mysql_stmt_init(this->getMysql());
if (my_stmt && mysql_stmt_prepare(my_stmt, query, strlen(query))){
this->printStError(my_stmt,"Prepare Statement Failed");
mysql_stmt_close(my_stmt);
return NULL;
}
return my_stmt;
}
/* Close MySQL Statements Handle */
void
DbUtil::mysqlCloseStmHandle(MYSQL_STMT *my_stmt)
{
mysql_stmt_close(my_stmt);
}
/* Error Printing */
void
DbUtil::printError(const char *msg)
{
if (m_mysql && mysql_errno(m_mysql))
{
if (m_mysql->server_version)
printf("\n [MySQL-%s]", m_mysql->server_version);
else
printf("\n [MySQL]");
printf("[%d] %s\n", getErrorNumber(), getError());
}
else if (msg)
printf(" [MySQL] %s\n", msg);
}
void
DbUtil::printStError(MYSQL_STMT *stmt, const char *msg)
{
if (stmt && mysql_stmt_errno(stmt))
{
if (m_mysql && m_mysql->server_version)
printf("\n [MySQL-%s]", m_mysql->server_version);
else
printf("\n [MySQL]");
printf("[%d] %s\n", mysql_stmt_errno(stmt),
mysql_stmt_error(stmt));
}
else if (msg)
printf("[MySQL] %s\n", msg);
}
/* Select which database to use */
bool
DbUtil::selectDb()
{
if ((getDbName()) != NULL)
{
if(mysql_select_db(m_mysql, this->getDbName()))
{
//printError("mysql_select_db failed");
return false;
}
return true;
}
printError("getDbName() == NULL");
return false;
}
bool
DbUtil::selectDb(const char * m_db)
{
{
if(mysql_select_db(m_mysql, m_db))
{
printError("mysql_select_db failed");
return false;
}
return true;
}
}
bool
DbUtil::createDb(BaseString& m_db)
{
BaseString stm;
setDbName(m_db.c_str());
{
if(selectDb())
{
stm.assfmt("DROP DATABASE %s", m_db.c_str());
if(!doQuery(m_db.c_str()))
return false;
}
stm.assfmt("CREATE DATABASE %s", m_db.c_str());
if(!doQuery(m_db.c_str()))
return false;
return true;
}
}
/* Count Table Rows */
unsigned long long
DbUtil::selectCountTable(const char * table)
{
BaseString query;
SqlResultSet result;
query.assfmt("select count(*) as count from %s", table);
if (!doQuery(query, result)) {
printError("select count(*) failed");
return -1;
}
return result.columnAsLong("count");
}
/* Run Simple Queries */
bool
DbUtil::runQuery(const char* sql,
const Properties& args,
SqlResultSet& rows){
clear_error();
rows.clear();
if (!isConnected())
return false;
assert(m_mysql);
g_debug << "runQuery: " << endl
<< " sql: '" << sql << "'" << endl;
MYSQL_STMT *stmt= mysql_stmt_init(m_mysql);
if (mysql_stmt_prepare(stmt, sql, strlen(sql)))
{
report_error("Failed to prepare: ", m_mysql);
return false;
}
uint params= mysql_stmt_param_count(stmt);
MYSQL_BIND *bind_param = new MYSQL_BIND[params];
NdbAutoObjArrayPtr<MYSQL_BIND> _guard(bind_param);
memset(bind_param, 0, params * sizeof(MYSQL_BIND));
for(uint i= 0; i < mysql_stmt_param_count(stmt); i++)
{
BaseString name;
name.assfmt("%d", i);
// Parameters are named 0, 1, 2...
if (!args.contains(name.c_str()))
{
g_err << "param " << i << " missing" << endl;
assert(false);
}
PropertiesType t;
Uint32 val_i;
const char* val_s;
args.getTypeOf(name.c_str(), &t);
switch(t) {
case PropertiesType_Uint32:
args.get(name.c_str(), &val_i);
bind_param[i].buffer_type= MYSQL_TYPE_LONG;
bind_param[i].buffer= (char*)&val_i;
g_debug << " param" << name.c_str() << ": " << val_i << endl;
break;
case PropertiesType_char:
args.get(name.c_str(), &val_s);
bind_param[i].buffer_type= MYSQL_TYPE_STRING;
bind_param[i].buffer= (char*)val_s;
bind_param[i].buffer_length= strlen(val_s);
g_debug << " param" << name.c_str() << ": " << val_s << endl;
break;
default:
assert(false);
break;
}
}
if (mysql_stmt_bind_param(stmt, bind_param))
{
report_error("Failed to bind param: ", m_mysql);
mysql_stmt_close(stmt);
return false;
}
if (mysql_stmt_execute(stmt))
{
report_error("Failed to execute: ", m_mysql);
mysql_stmt_close(stmt);
return false;
}
/*
Update max_length, making it possible to know how big
buffers to allocate
*/
my_bool one= 1;
mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void*) &one);
if (mysql_stmt_store_result(stmt))
{
report_error("Failed to store result: ", m_mysql);
mysql_stmt_close(stmt);
return false;
}
uint row= 0;
MYSQL_RES* res= mysql_stmt_result_metadata(stmt);
if (res != NULL)
{
MYSQL_FIELD *fields= mysql_fetch_fields(res);
uint num_fields= mysql_num_fields(res);
MYSQL_BIND *bind_result = new MYSQL_BIND[num_fields];
NdbAutoObjArrayPtr<MYSQL_BIND> _guard1(bind_result);
memset(bind_result, 0, num_fields * sizeof(MYSQL_BIND));
for (uint i= 0; i < num_fields; i++)
{
unsigned long buf_len= sizeof(int);
switch(fields[i].type){
case MYSQL_TYPE_STRING:
buf_len = fields[i].length + 1;
break;
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
buf_len= fields[i].max_length + 1;
break;
case MYSQL_TYPE_LONGLONG:
buf_len= sizeof(long long);
break;
case MYSQL_TYPE_LONG:
buf_len = sizeof(long);
break;
default:
break;
}
bind_result[i].buffer_type= fields[i].type;
bind_result[i].buffer= malloc(buf_len);
bind_result[i].buffer_length= buf_len;
bind_result[i].is_null = (my_bool*)malloc(sizeof(my_bool));
* bind_result[i].is_null = 0;
}
if (mysql_stmt_bind_result(stmt, bind_result)){
report_error("Failed to bind result: ", m_mysql);
mysql_stmt_close(stmt);
return false;
}
while (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
{
Properties curr(true);
for (uint i= 0; i < num_fields; i++){
if (* bind_result[i].is_null)
continue;
switch(fields[i].type){
case MYSQL_TYPE_STRING:
((char*)bind_result[i].buffer)[fields[i].max_length] = 0;
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
curr.put(fields[i].name, (char*)bind_result[i].buffer);
break;
case MYSQL_TYPE_LONGLONG:
curr.put64(fields[i].name,
*(unsigned long long*)bind_result[i].buffer);
break;
default:
curr.put(fields[i].name, *(int*)bind_result[i].buffer);
break;
}
}
rows.put("row", row++, &curr);
}
mysql_free_result(res);
for (uint i= 0; i < num_fields; i++)
{
free(bind_result[i].buffer);
free(bind_result[i].is_null);
}
}
// Save stats in result set
rows.put("rows", row);
rows.put64("affected_rows", mysql_affected_rows(m_mysql));
rows.put("mysql_errno", mysql_errno(m_mysql));
rows.put("mysql_error", mysql_error(m_mysql));
rows.put("mysql_sqlstate", mysql_sqlstate(m_mysql));
rows.put64("insert_id", mysql_insert_id(m_mysql));
mysql_stmt_close(stmt);
return true;
}
bool
DbUtil::doQuery(const char* query){
const Properties args;
SqlResultSet result;
return doQuery(query, args, result);
}
bool
DbUtil::doQuery(const char* query, SqlResultSet& result){
Properties args;
return doQuery(query, args, result);
}
bool
DbUtil::doQuery(const char* query, const Properties& args,
SqlResultSet& result){
if (!runQuery(query, args, result))
return false;
result.get_row(0); // Load first row
return true;
}
bool
DbUtil::doQuery(const char* query, const Properties& args){
SqlResultSet result;
return doQuery(query, args, result);
}
bool
DbUtil::doQuery(BaseString& str){
return doQuery(str.c_str());
}
bool
DbUtil::doQuery(BaseString& str, SqlResultSet& result){
return doQuery(str.c_str(), result);
}
bool
DbUtil::doQuery(BaseString& str, const Properties& args,
SqlResultSet& result){
return doQuery(str.c_str(), args, result);
}
bool
DbUtil::doQuery(BaseString& str, const Properties& args){
return doQuery(str.c_str(), args);
}
/* Return MySQL Error String */
const char *
DbUtil::getError()
{
return mysql_error(this->getMysql());
}
/* Return MySQL Error Number */
int
DbUtil::getErrorNumber()
{
return mysql_errno(this->getMysql());
}
void
DbUtil::report_error(const char* message, MYSQL* mysql)
{
m_last_errno= mysql_errno(mysql);
m_last_error.assfmt("%d: %s", m_last_errno, mysql_error(mysql));
if (!m_silent)
g_err << message << m_last_error << endl;
}
/* DIE */
void
DbUtil::die(const char *file, int line, const char *expr)
{
printf("%s:%d: check failed: '%s'\n", file, line, expr);
abort();
}
/* SqlResultSet */
bool
SqlResultSet::get_row(int row_num){
if(!get("row", row_num, &m_curr_row)){
return false;
}
return true;
}
bool
SqlResultSet::next(void){
return get_row(++m_curr_row_num);
}
// Reset iterator
void SqlResultSet::reset(void){
m_curr_row_num= -1;
m_curr_row= 0;
}
// Remove row from resultset
void SqlResultSet::remove(){
BaseString row_name;
row_name.assfmt("row_%d", m_curr_row_num);
Properties::remove(row_name.c_str());
}
// Clear all rows and reset iterator
void SqlResultSet::clear(){
reset();
Properties::clear();
}
SqlResultSet::SqlResultSet(): m_curr_row(0), m_curr_row_num(-1){
}
SqlResultSet::~SqlResultSet(){
}
const char* SqlResultSet::column(const char* col_name){
const char* value;
if (!m_curr_row){
g_err << "ERROR: SqlResultSet::column("<< col_name << ")" << endl
<< "There is no row loaded, call next() before "
<< "acessing the column values" << endl;
assert(m_curr_row);
}
if (!m_curr_row->get(col_name, &value))
return NULL;
return value;
}
uint SqlResultSet::columnAsInt(const char* col_name){
uint value;
if (!m_curr_row){
g_err << "ERROR: SqlResultSet::columnAsInt("<< col_name << ")" << endl
<< "There is no row loaded, call next() before "
<< "acessing the column values" << endl;
assert(m_curr_row);
}
if (!m_curr_row->get(col_name, &value))
return (uint)-1;
return value;
}
unsigned long long SqlResultSet::columnAsLong(const char* col_name){
unsigned long long value;
if (!m_curr_row){
g_err << "ERROR: SqlResultSet::columnAsLong("<< col_name << ")" << endl
<< "There is no row loaded, call next() before "
<< "acessing the column values" << endl;
assert(m_curr_row);
}
if (!m_curr_row->get(col_name, &value))
return (uint)-1;
return value;
}
unsigned long long SqlResultSet::insertId(){
return get_long("insert_id");
}
unsigned long long SqlResultSet::affectedRows(){
return get_long("affected_rows");
}
uint SqlResultSet::numRows(void){
return get_int("rows");
}
uint SqlResultSet::mysqlErrno(void){
return get_int("mysql_errno");
}
const char* SqlResultSet::mysqlError(void){
return get_string("mysql_error");
}
const char* SqlResultSet::mysqlSqlstate(void){
return get_string("mysql_sqlstate");
}
uint SqlResultSet::get_int(const char* name){
uint value;
get(name, &value);
return value;
}
unsigned long long SqlResultSet::get_long(const char* name){
unsigned long long value;
get(name, &value);
return value;
}
const char* SqlResultSet::get_string(const char* name){
const char* value;
get(name, &value);
return value;
}
/* EOF */