-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathMysql.cpp
More file actions
561 lines (471 loc) · 13.8 KB
/
Mysql.cpp
File metadata and controls
561 lines (471 loc) · 13.8 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
/*
* Copyright (C)2005-2012 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <hxcpp.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include "mysql.h"
#include <string.h>
#ifdef HX_ANDROID
#define atof(x) strtod((x),0)
#endif
/**
<doc>
<h1>MySQL</h1>
<p>
API to connect and use MySQL database
</p>
</doc>
**/
#define HXTHROW(x) hx::Throw(HX_CSTRING(x))
namespace
{
struct Connection : public hx::Object
{
HX_IS_INSTANCE_OF enum { _hx_ClassId = hx::clsIdMysql };
MYSQL *m;
void create(MYSQL *inM)
{
m = inM;
_hx_set_finalizer(this, finalize);
}
void destroy()
{
if (m)
{
mysql_close(m);
m = 0;
}
}
static void finalize(Dynamic obj)
{
((Connection *)(obj.mPtr))->destroy();
}
};
Connection *getConnection(Dynamic o)
{
Connection *connection = dynamic_cast<Connection *>(o.mPtr);
if (!connection || !connection->m)
hx::Throw( HX_CSTRING("Invalid Connection") );
return connection;
}
static void error( MYSQL *m, const char *msg )
{
hx::Throw( String(msg) + HX_CSTRING(" ") + String(mysql_error(m)) );
}
// ---------------------------------------------------------------
// Result
/**
<doc><h2>Result</h2></doc>
**/
#undef CONV_FLOAT
typedef enum {
CONV_INT,
CONV_STRING,
CONV_FLOAT,
CONV_BINARY,
CONV_DATE,
CONV_DATETIME,
CONV_BOOL
} CONV;
struct Result : public hx::Object
{
HX_IS_INSTANCE_OF enum { _hx_ClassId = hx::clsIdMysqlResult };
MYSQL_RES *r;
int nfields;
CONV *fields_convs;
String *field_names;
MYSQL_ROW current;
void create(MYSQL_RES *inR)
{
r = inR;
fields_convs = 0;
field_names = 0;
nfields = 0;
_hx_set_finalizer(this, finalize);
}
void destroy()
{
if (r)
{
if (fields_convs)
free(fields_convs);
if (field_names)
free(field_names);
fields_convs = 0;
field_names = 0;
mysql_free_result(r);
r = 0;
}
}
int numRows() { return mysql_num_rows(r); }
static void finalize(Dynamic obj)
{
((Result *)(obj.mPtr))->destroy();
}
};
Result *getResult(Dynamic o)
{
Result *result = dynamic_cast<Result *>(o.mPtr);
if (!result)
HXTHROW("Invalid result");
return result;
}
cpp::Function< Dynamic(Dynamic) > gDataToBytes;
cpp::Function< Dynamic(Float) > gDateFromSeconds;
}
void _hx_mysql_set_conversion(
cpp::Function< Dynamic(Dynamic) > inDataToBytes,
cpp::Function< Dynamic(Float) > inDateFromSeconds )
{
gDataToBytes = inDataToBytes;
gDateFromSeconds = inDateFromSeconds;
}
/**
result_get_length : 'result -> int
<doc>Return the number of rows returned or affected</doc>
**/
int _hx_mysql_result_get_length(Dynamic handle)
{
if( handle->__GetType() == vtInt )
return handle;
return getResult(handle)->numRows();
}
/**
result_get_nfields : 'result -> int
<doc>Return the number of fields in a result row</doc>
**/
int _hx_mysql_result_get_nfields(Dynamic handle)
{
if( handle->__GetType() == vtInt )
return 0;
return getResult(handle)->nfields;
}
/**
result_get_fields_names : 'result -> string array
<doc>Return the fields names corresponding results columns</doc>
**/
Array<String> _hx_mysql_result_get_fields_names(Dynamic handle)
{
Result *r = getResult(handle);
MYSQL_FIELD *fields = mysql_fetch_fields(r->r);
int count = r->nfields;
Array<String> output = Array_obj<String>::__new(count);
for(int k=0;k<count;k++)
output[k] = String(fields[k].name);
return output;
}
/**
result_next : 'result -> object?
<doc>
Return the next row if available. A row is represented
as an object, which fields have been converted to the
corresponding Neko value (int, float or string). For
Date and DateTime you can specify your own conversion
function using [result_set_conv_date]. By default they're
returned as plain strings. Additionally, the TINYINT(1) will
be converted to either true or false if equal to 0.
</doc>
**/
Dynamic _hx_mysql_result_next(Dynamic handle)
{
Result *r = getResult(handle);
MYSQL_ROW row = mysql_fetch_row(r->r);
if( !row )
return null();
int count = r->nfields;
hx::Anon cur = hx::Anon_obj::Create(0);
r->current = row;
unsigned long *lengths = 0;
for(int i=0;i<r->nfields;i++)
{
if( row[i] )
{
Dynamic v;
switch( r->fields_convs[i] )
{
case CONV_INT:
v = atoi(row[i]);
break;
case CONV_STRING:
v = String(row[i]);
break;
case CONV_BOOL:
v = *row[i] != '0';
break;
case CONV_FLOAT:
v = atof(row[i]);
break;
case CONV_BINARY:
{
if( lengths == NULL )
{
lengths = mysql_fetch_lengths(r->r);
if( lengths == NULL )
HXTHROW("mysql_fetch_lengths");
}
Array<unsigned char> buf = Array_obj<unsigned char>::__new(lengths[i],lengths[i]);
memcpy(&buf[0],row[i],lengths[i]);
v = gDataToBytes.call(buf);
}
break;
case CONV_DATE:
{
struct tm t;
sscanf(row[i],"%4d-%2d-%2d",&t.tm_year,&t.tm_mon,&t.tm_mday);
t.tm_hour = 0;
t.tm_min = 0;
t.tm_sec = 0;
t.tm_isdst = -1;
t.tm_year -= 1900;
t.tm_mon--;
v = gDateFromSeconds.call((int)mktime(&t));
}
break;
case CONV_DATETIME:
{
struct tm t;
sscanf(row[i],"%4d-%2d-%2d %2d:%2d:%2d",&t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
t.tm_isdst = -1;
t.tm_year -= 1900;
t.tm_mon--;
v = gDateFromSeconds.call(mktime(&t));
}
break;
default:
break;
}
cur->__SetField(r->field_names[i],v, hx::paccDynamic );
}
}
return cur;
}
/**
result_get : 'result -> n:int -> string
<doc>Return the [n]th field of the current row</doc>
**/
String _hx_mysql_result_get(Dynamic handle,int n)
{
Result *r = getResult(handle);
if( n < 0 || n >= r->nfields )
HXTHROW("Invalid index");
if( !r->current )
{
_hx_mysql_result_next(handle);
if( !r->current )
HXTHROW("No more results");
}
return String(r->current[n]);
}
/**
result_get_int : 'result -> n:int -> int
<doc>Return the [n]th field of the current row as an integer (or 0)</doc>
**/
int _hx_mysql_result_get_int(Dynamic handle,int n)
{
Result *r = getResult(handle);
if( n < 0 || n >= r->nfields )
HXTHROW("Invalid index");
if( !r->current )
{
_hx_mysql_result_next(handle);
if( !r->current )
HXTHROW("No more results");
}
const char *s = r->current[n];
return s?atoi(s):0;
}
/**
result_get_float : 'result -> n:int -> float
<doc>Return the [n]th field of the current row as a float (or 0)</doc>
**/
Float _hx_mysql_result_get_float(Dynamic handle,int n)
{
Result *r = getResult(handle);
if( n < 0 || n >= r->nfields )
HXTHROW("Invalid index");
if( !r->current )
{
_hx_mysql_result_next(handle);
if( !r->current )
HXTHROW("No more results");
}
const char *s = r->current[n];
return s?atof(s):0;
}
static CONV convert_type( enum enum_field_types t, int flags, unsigned int length ) {
// FIELD_TYPE_TIME
// FIELD_TYPE_YEAR
// FIELD_TYPE_NEWDATE
// FIELD_TYPE_NEWDATE + 2: // 5.0 MYSQL_TYPE_BIT
switch( t ) {
case FIELD_TYPE_TINY:
if( length == 1 )
return CONV_BOOL;
case FIELD_TYPE_SHORT:
case FIELD_TYPE_LONG:
case FIELD_TYPE_INT24:
return CONV_INT;
case FIELD_TYPE_LONGLONG:
case FIELD_TYPE_DECIMAL:
case FIELD_TYPE_FLOAT:
case FIELD_TYPE_DOUBLE:
case 246: // 5.0 MYSQL_NEW_DECIMAL
return CONV_FLOAT;
case FIELD_TYPE_BLOB:
case FIELD_TYPE_TINY_BLOB:
case FIELD_TYPE_MEDIUM_BLOB:
case FIELD_TYPE_LONG_BLOB:
if( (flags & BINARY_FLAG) != 0 )
return CONV_BINARY;
return CONV_STRING;
case FIELD_TYPE_DATETIME:
case FIELD_TYPE_TIMESTAMP:
return CONV_DATETIME;
case FIELD_TYPE_DATE:
return CONV_DATE;
case FIELD_TYPE_NULL:
case FIELD_TYPE_ENUM:
case FIELD_TYPE_SET:
//case FIELD_TYPE_VAR_STRING:
//case FIELD_TYPE_GEOMETRY:
// 5.0 MYSQL_TYPE_VARCHAR
default:
if( (flags & BINARY_FLAG) != 0 )
return CONV_BINARY;
return CONV_STRING;
}
}
static Result *alloc_result( Connection *c, MYSQL_RES *r )
{
Result *res = new Result();
res->create(r);
int num_fields = mysql_num_fields(r);
int i,j;
MYSQL_FIELD *fields = mysql_fetch_fields(r);
res->current = 0;
res->nfields = num_fields;
res->field_names = (String *)malloc(sizeof(String)*num_fields);
res->fields_convs = (CONV*)malloc(sizeof(CONV)*num_fields);
for(i=0;i<num_fields;i++)
{
String name;
if( strchr(fields[i].name,'(') )
name = String::createPermanent("???",3); // looks like an inner request : prevent hashing + cashing it
else
name = String::createPermanent(fields[i].name, -1);
res->field_names[i] = name;
res->fields_convs[i] = convert_type(fields[i].type,fields[i].flags,fields[i].length);
}
return res;
}
// ---------------------------------------------------------------
// Connection
/** <doc><h2>Connection</h2></doc> **/
/**
close : 'connection -> void
<doc>Close the connection. Any subsequent operation will fail on it</doc>
**/
Dynamic _hx_mysql_close(Dynamic handle)
{
Connection *connection = getConnection(handle);
connection->destroy();
return true;
}
/**
select_db : 'connection -> string -> void
<doc>Select the database</doc>
**/
void _hx_mysql_select_db(Dynamic handle,String db)
{
Connection *connection = getConnection(handle);
if( mysql_select_db(connection->m,db.utf8_str()) != 0 )
error(connection->m,"Failed to select database :");
}
/**
request : 'connection -> string -> 'result
<doc>Execute an SQL request. Exception on error</doc>
**/
Dynamic _hx_mysql_request(Dynamic handle,String req)
{
Connection *connection = getConnection(handle);
Array< unsigned char > bytes = Array_obj< unsigned char >::__new();
__hxcpp_bytes_of_string(bytes, req);
if( mysql_real_query(connection->m,req.utf8_str(),bytes.__length()) != 0 )
error(connection->m,req);
MYSQL_RES *res = mysql_store_result(connection->m);
if( !res )
{
if( mysql_field_count(connection->m) == 0 )
return mysql_affected_rows(connection->m);
else
error(connection->m,req);
}
return alloc_result(connection,res);
}
/**
escape : 'connection -> string -> string
<doc>Escape the string for inserting into a SQL request</doc>
**/
struct AutoBuf
{
AutoBuf(int inLen) { buffer = new char[inLen]; }
~AutoBuf() { delete [] buffer; }
char *buffer;
};
String _hx_mysql_escape(Dynamic handle,String str)
{
Connection *connection = getConnection(handle);
int len = str.length * 2 + 1;
AutoBuf sout(len);
Array< unsigned char > bytes = Array_obj< unsigned char >::__new();
__hxcpp_bytes_of_string(bytes, str);
int finalLen = mysql_real_escape_string(connection->m,sout.buffer,str.utf8_str(),bytes.__length());
if( finalLen < 0 )
hx::Throw( HX_CSTRING("Unsupported charset : ") + String(mysql_character_set_name(connection->m)) );
return String::create(sout.buffer,finalLen);
}
// ---------------------------------------------------------------
// Sql
/**
connect : { host => string, port => int, user => string, pass => string, socket => string? } -> 'connection
<doc>Connect to a database using the connection informations</doc>
**/
Dynamic _hx_mysql_connect(Dynamic params)
{
String host = params->__Field(HX_CSTRING("host"), hx::paccDynamic );
int port = params->__Field(HX_CSTRING("port"), hx::paccDynamic);
String user = params->__Field(HX_CSTRING("user"), hx::paccDynamic);
String pass = params->__Field(HX_CSTRING("pass"), hx::paccDynamic);
String socket = params->__Field(HX_CSTRING("socket"), hx::paccDynamic );
MYSQL *cnx = mysql_init(NULL);
if( mysql_real_connect(cnx,host.utf8_str(),user.utf8_str(),pass.utf8_str(),NULL,port,socket.utf8_str(),0) == NULL )
{
String error = HX_CSTRING("Failed to connect to mysql server : ") + String(mysql_error(cnx));
mysql_close(cnx);
hx::Throw(error);
}
Connection *connection = new Connection();
connection->create(cnx);
return connection;
}