My favorites | Sign in
Project Home Downloads Source
Checkout   Browse   Changes    
 
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
#include "MySql.h"

#ifndef flagNOMYSQL

NAMESPACE_UPP

class MySqlConnection : public SqlConnection {
protected:
virtual void SetParam(int i, const Value& r);
virtual bool Execute();
virtual int GetRowsProcessed() const;
virtual bool Fetch();
virtual void GetColumn(int i, Ref f) const;
virtual void Cancel();
virtual Value GetInsertedId() const;
virtual SqlSession& GetSession() const;
virtual String GetUser() const;
virtual String ToString() const;

private:
MySqlSession& session;
MYSQL *mysql;
Vector<String> param;
MYSQL_RES *result;
MYSQL_ROW row;
unsigned long *len;
int rows;
int lastid;
Buffer<bool> convert;

String MakeQuery() const;
void FreeResult();
String EscapeString(const String& v);

public:
MySqlConnection(MySqlSession& session, MYSQL *mysql);
virtual ~MySqlConnection() { Cancel(); }
};

bool MySqlSession::IsOpen() const { return mysql; }

static const char *sEmpNull(const char *s) {
return s && *s == '\0' ? NULL : s;
}

bool MySqlSession::Connect(const char *user, const char *password, const char *database,
const char *host, int port, const char *socket) {
mysql = mysql_init((MYSQL*) 0);
if(mysql && mysql_real_connect(mysql, sEmpNull(host), sEmpNull(user),
sEmpNull(password), sEmpNull(database), port,
sEmpNull(socket), 0)) {
Sql sql(*this);
username = sql.Select("substring_index(USER(),'@',1)");
mysql_set_character_set(mysql, "utf8");
sql.Execute("SET NAMES 'utf8'");
sql.Execute("SET CHARACTER SET utf8");
return true;
}
Close();
return false;
}

inline static const char *EmpNull(const String& s)
{
return *s ? (const char *)s : 0;
}

bool MySqlSession::Open(const char *connect) {
String user, pwd, socket;
String database = Null;
String host = Null;
int port = MYSQL_PORT;
level = 0;
const char *p = connect, *b;
for(b = p; *p && *p != '/' && *p != '@'; p++)
;
user = String(b, p);
if(*p == '/')
{
for(b = ++p; *p && *p != '@'; p++)
;
pwd = String(b, p);
}
if(*p == '@')
{
for(b = ++p; *p && *p != '/' && *p != ':' && *p != ','; p++)
;
if(*p == '/' || *p == 0)
{
database = String(b, p);
if(*p)
p++;
b = p;
}
while(*p && *p != ':' && *p != ',')
p++;
host = String(b, p);
if(*p == ':')
{ // port
if(!IsDigit(*++p))
throw Exc("Port number expected.");
port = stou(p, &p);
}
if(*p == ',') // socket
socket = p + 1;
}
return Connect(EmpNull(user), EmpNull(pwd),
EmpNull(database), EmpNull(host), port, EmpNull(socket));
}

void MySqlSession::Close() {
SessionClose();
if(mysql) {
mysql_close(mysql);
mysql = NULL;
level = 0;
}
}

void MySqlSession::Begin()
{
static const char btrans[] = "start transaction";
if(trace)
*trace << btrans << ";\n";
if(mysql_query(mysql, btrans))
SetError(mysql_error(mysql), btrans);
level++;
}

void MySqlSession::Commit()
{
static const char ctrans[] = "commit";
if(trace)
*trace << ctrans << ";\n";
if(mysql_query(mysql, ctrans))
SetError(mysql_error(mysql), ctrans);
level--;
}

void MySqlSession::Rollback()
{
static const char rtrans[] = "rollback";
if(trace)
*trace << rtrans << ";\n";
if(mysql_query(mysql, rtrans))
SetError(mysql_error(mysql), rtrans);
if(level > 0) level--;
}

int MySqlSession::GetTransactionLevel() const
{
return level;
}

static Vector<String> FetchList(Sql& cursor, bool upper = false)
{
Vector<String> out;
String s;
while(cursor.Fetch(s))
out.Add(upper ? ToUpper(s) : s);
return out;
}

Vector<String> MySqlSession::EnumUsers()
{
Vector<String> out;
Sql cursor(*this);
if(Select(SqlId("USER")).From(SqlId("MYSQL.USER")).Execute(cursor))
out = FetchList(cursor);
return out;
}

Vector<String> MySqlSession::EnumDatabases()
{
Vector<String> out;
Sql cursor(*this);
if(cursor.Execute("show databases"))
out = FetchList(cursor); // 06-09-12 cxl: was false; In Linux, names are case sensitive
return out;
}

Vector<String> MySqlSession::EnumTables(String database)
{
Vector<String> out;
Sql cursor(*this);
if(cursor.Execute("show tables from " + database))
out = FetchList(cursor); // 06-09-12 cxl: was false; In Linux, names are case sensitive
return out;
}

SqlConnection *MySqlSession::CreateConnection() {
return new MySqlConnection(*this, mysql);
}

MySqlConnection::MySqlConnection(MySqlSession& session, MYSQL *mysql)
: session(session), mysql(mysql) {
result = NULL;
lastid = 0;
}

String MySqlConnection::EscapeString(const String& v)
{
StringBuffer b(v.GetLength() * 2 + 3);
char *q = b;
*q = '\"';
int n = mysql_real_escape_string(mysql, q + 1, v, v.GetLength());
q[1 + n] = '\"';
b.SetCount(2 + n); //TODO - check this fix
return b;
}

void MySqlConnection::SetParam(int i, const Value& r) {
String p;
if(IsNull(r))
p = "NULL";
else
switch(r.GetType()) {
case 34:
p = EscapeString(SqlRaw(r));
break;
case WSTRING_V:
case STRING_V:
p = EscapeString(ToCharset(CHARSET_UTF8, r));
break;
case BOOL_V:
case INT_V:
p = Format("%d", int(r));
break;
case DOUBLE_V:
p = FormatDouble(double(r), 20);
break;
case DATE_V: {
Date d = r;
p = Format("\'%04d-%02d-%02d\'", d.year, d.month, d.day);
}
break;
case TIME_V: {
Time t = r;
p = Format("\'%04d-%02d-%02d %02d:%02d:%02d\'",
t.year, t.month, t.day, t.hour, t.minute, t.second);
}
break;
default:
NEVER();
}
param.At(i, p);
}

bool MySqlConnection::Execute() {
String query;
int pi = 0;
const char *s = statement;
while(s < statement.End())
if(*s == '\'' || *s == '\"')
s = MySqlReadString(s, query);
else {
if(*s == '?')
query.Cat(param[pi++]);
else
query.Cat(*s);
s++;
}
Cancel();
/* Stream *trace = session.GetTrace();
dword time;
if(session.IsTraceTime())
time = GetTickCount();*/
if(mysql_query(mysql, query)) {
session.SetError(mysql_error(mysql), query);
return false;
}
result = mysql_store_result(mysql);
rows = (int)mysql_affected_rows(mysql);
if(result) {
int fields = mysql_num_fields(result);
info.SetCount(fields);
convert.Alloc(fields, false);
for(int i = 0; i < fields; i++) {
MYSQL_FIELD *field = mysql_fetch_field_direct(result, i);
SqlColumnInfo& f = info[i];
f.name = field->name;
switch(field->type) {
case FIELD_TYPE_TINY:
case FIELD_TYPE_SHORT:
case FIELD_TYPE_LONG:
case FIELD_TYPE_INT24:
f.type = INT_V;
break;
case FIELD_TYPE_LONGLONG:
case FIELD_TYPE_DECIMAL:
case FIELD_TYPE_FLOAT:
case FIELD_TYPE_DOUBLE:
f.type = DOUBLE_V;
break;
case FIELD_TYPE_DATE:
f.type = DATE_V;
break;
case FIELD_TYPE_DATETIME:
case FIELD_TYPE_TIMESTAMP:
f.type = TIME_V;
break;
case FIELD_TYPE_VAR_STRING:
case FIELD_TYPE_STRING:
convert[i] = true;
default:
f.type = STRING_V;
break;
}
f.width = field->length;
f.scale = f.precision = 0;
}
}
else {
lastid = (int)mysql_insert_id(mysql);
if(lastid) {
SqlColumnInfo& f = info.Add();
f.width = f.scale = f.precision = 0;
f.binary = false;
f.type = DOUBLE_V;
f.name = "LAST_INSERT_ID";
rows = 1;
}
}
return true;
}

int MySqlConnection::GetRowsProcessed() const {
return rows;
}

Value MySqlConnection::GetInsertedId() const
{
return lastid;
}

bool MySqlConnection::Fetch() {
if(result) {
row = mysql_fetch_row(result);
if(row) {
len = mysql_fetch_lengths(result);
return true;
}
}
else
if(lastid && rows > 0) {
rows--;
return true;
}
FreeResult();
return false;
}

// 0123456789012345678
// YYYY-MM-DD HH-MM-SS

static Date sDate(const char *s) {
return Date(atoi(s), atoi(s + 5), atoi(s + 8));
}

void MySqlConnection::GetColumn(int i, Ref f) const {
if(lastid) {
f = lastid;
return;
}
const char *s = row[i];
if(s == NULL)
f = Null;
else {
switch(info[i].type) {
case INT_V:
f = atoi(s);
break;
case DOUBLE_V:
f = ScanDouble(s, NULL, true);
break;
case DATE_V:
f = Value(sDate(s));
break;
case TIME_V: {
Time t = ToTime(sDate(s));
t.hour = atoi(s + 11);
t.minute = atoi(s + 14);
t.second = atoi(s + 17);
f = Value(t);
}
break;
default:
if(convert[i])
f = Value(ToCharset(CHARSET_DEFAULT, String(s, len[i]), CHARSET_UTF8));
else
f = Value(String(s, len[i]));
break;
}
}
}

void MySqlConnection::FreeResult() {
lastid = 0;
if(result) {
mysql_free_result(result);
result = NULL;
}
}

void MySqlConnection::Cancel() {
param.Clear();
info.Clear();
rows = 0;
FreeResult();
}

SqlSession& MySqlConnection::GetSession() const { return session; }
String MySqlConnection::GetUser() const { return session.GetUser(); }
String MySqlConnection::ToString() const { return statement; }

String MySqlTextType(int n) {
return n < 256 ? Format("varchar(%d)", n) : String("text");
}

const char *MySqlReadString(const char *s, String& stmt) {
stmt.Cat(*s);
int c = *s++;
for(;;) {
if(*s == '\0') break;
else
if(*s == '\'' && s[1] == '\'') {
stmt.Cat('\'');
s += 2;
}
// else
// if(*s == '\"' && s[1] == '\"') {
// stmt.Cat('\"');
// s += 2;
// }
else
if(*s == c) {
stmt.Cat(c);
s++;
break;
}
else
if(*s == '\\') {
stmt.Cat('\\');
if(*++s)
stmt.Cat(*s++);
}
else
stmt.Cat(*s++);
}
return s;
}

bool MySqlPerformScript(const String& txt, StatementExecutor& se, Gate2<int, int> progress_canceled) {
const char *text = txt;
for(;;) {
String stmt;
while(*text <= 32 && *text > 0) text++;
if(*text == '\0') break;
for(;;) {
if(*text == '\0')
break;
if(*text == ';')
break;
else
if(*text == '\'')
text = MySqlReadString(text, stmt);
else
if(*text == '\"')
text = MySqlReadString(text, stmt);
else
stmt.Cat(*text++);
}
if(progress_canceled(text - txt.Begin(), txt.GetLength()))
return false;
if(!se.Execute(stmt))
return false;
if(*text) text++;
}
return true;
}

bool MySqlUpdateSchema(const SqlSchema& sch, int i, StatementExecutor& se) {
if(sch.UpdateNormalFile(i)) {
MySqlPerformScript(LoadFile(sch.NormalFileName(i + 1)), se);
sch.UpdateNormalFile(i + 1);
return MySqlPerformScript(sch.Script(i), se);
}
return true;
}

END_UPP_NAMESPACE

#endif

Change log

r4907 by cxl on May 4, 2012   Diff
.MySql: removed DDUMP
Go to: 
Project members, sign in to write a code review

Older revisions

r4627 by cxl on Feb 27, 2012   Diff
*MySql: Fixed GetRowsProcessed
r4290 by cxl on Dec 10, 2011   Diff
Sql: Refactored SQL 'default app
cursor', added per-thread SQL option,
added secondary SQLR 'default app
cursor'
r3357 by cxl on Apr 18, 2011   Diff
MySql: GetTransactionLevel
All revisions of this file

File info

Size: 10396 bytes, 493 lines

File properties

svn:eol-style
native
Powered by Google Project Hosting