This repository was archived by the owner on Aug 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysql.lua
More file actions
1304 lines (1123 loc) · 37.5 KB
/
mysql.lua
File metadata and controls
1304 lines (1123 loc) · 37.5 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
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
--MySQL client library ffi binding.
--Written by Cosmin Apreutesei. Public domain.
--Supports MySQL Connector/C 6.1.
--Based on MySQL 5.7 manual.
if not ... then require'mysql_test'; return end
local ffi = require'ffi'
local bit = require'bit'
require'mysql_h'
local C
local M = {}
--select a mysql client library implementation.
local function bind(lib)
if not C then
if not lib or lib == 'mysql' then
C = ffi.load(ffi.abi'win' and 'libmysql' or 'mysqlclient')
elseif lib == 'mariadb' then
C = ffi.load'mariadb'
elseif type(lib) == 'string' then
C = ffi.load(lib)
else
C = lib
end
M.C = C
end
return M
end
M.bind = bind
--we compare NULL pointers against NULL instead of nil for compatibility with luaffi.
local NULL = ffi.cast('void*', nil)
local function ptr(p) --convert NULLs to nil
if p == NULL then return nil end
return p
end
local function cstring(data) --convert null-term non-empty C strings to lua strings
if data == NULL or data[0] == 0 then return nil end
return ffi.string(data)
end
--error reporting
local function myerror(mysql, stacklevel)
local err = cstring(C.mysql_error(mysql))
if not err then return end
error(string.format('mysql error: %s', err), stacklevel or 3)
end
local function checkz(mysql, ret)
if ret == 0 then return end
myerror(mysql, 4)
end
local function checkh(mysql, ret)
if ret ~= NULL then return ret end
myerror(mysql, 4)
end
local function enum(e, prefix)
local v = type(e) == 'string' and (prefix and C[prefix..e] or C[e]) or e
return assert(v, 'invalid enum value')
end
--client library info
function M.thread_safe()
bind()
return C.mysql_thread_safe() == 1
end
function M.client_info()
bind()
return cstring(C.mysql_get_client_info())
end
function M.client_version()
bind()
return tonumber(C.mysql_get_client_version())
end
--connections
local function bool_ptr(b)
return ffi.new('my_bool[1]', b or false)
end
local function uint_bool_ptr(b)
return ffi.new('uint32_t[1]', b or false)
end
local function uint_ptr(i)
return ffi.new('uint32_t[1]', i)
end
local function proto_ptr(proto) --proto is 'MYSQL_PROTOCOL_*' or mysql.C.MYSQL_PROTOCOL_*
return ffi.new('uint32_t[1]', enum(proto))
end
local function ignore_arg()
return nil
end
local option_encoders = {
MYSQL_ENABLE_CLEARTEXT_PLUGIN = bool_ptr,
MYSQL_OPT_LOCAL_INFILE = uint_bool_ptr,
MYSQL_OPT_PROTOCOL = proto_ptr,
MYSQL_OPT_READ_TIMEOUT = uint_ptr,
MYSQL_OPT_WRITE_TIMEOUT = uint_ptr,
MYSQL_OPT_USE_REMOTE_CONNECTION = ignore_arg,
MYSQL_OPT_USE_EMBEDDED_CONNECTION = ignore_arg,
MYSQL_OPT_GUESS_CONNECTION = ignore_arg,
MYSQL_SECURE_AUTH = bool_ptr,
MYSQL_REPORT_DATA_TRUNCATION = bool_ptr,
MYSQL_OPT_RECONNECT = bool_ptr,
MYSQL_OPT_SSL_VERIFY_SERVER_CERT = bool_ptr,
MYSQL_ENABLE_CLEARTEXT_PLUGIN = bool_ptr,
MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS = bool_ptr,
}
function M.connect(t, ...)
bind()
local host, user, pass, db, charset, port
local unix_socket, flags, options, attrs
local key, cert, ca, capath, cipher
if type(t) == 'string' then
host, user, pass, db, charset, port = t, ...
else
host, user, pass, db, charset, port = t.host, t.user, t.pass, t.db, t.charset, t.port
unix_socket, flags, options, attrs = t.unix_socket, t.flags, t.options, t.attrs
key, cert, ca, capath, cipher = t.key, t.cert, t.ca, t.capath, t.cipher
end
port = port or 0
local client_flag = 0
if type(flags) == 'number' then
client_flag = flags
elseif flags then
for k,v in pairs(flags) do
local flag = enum(k, 'MYSQL_') --'CLIENT_*' or mysql.C.MYSQL_CLIENT_* enum
client_flag = v and bit.bor(client_flag, flag) or bit.band(client_flag, bit.bnot(flag))
end
end
local mysql = assert(C.mysql_init(nil))
ffi.gc(mysql, C.mysql_close)
if options then
for k,v in pairs(options) do
local opt = enum(k) --'MYSQL_OPT_*' or mysql.C.MYSQL_OPT_* enum
local encoder = option_encoders[k]
if encoder then v = encoder(v) end
assert(C.mysql_options(mysql, opt, ffi.cast('const void*', v)) == 0, 'invalid option')
end
end
if attrs then
for k,v in pairs(attrs) do
assert(C.mysql_options4(mysql, C.MYSQL_OPT_CONNECT_ATTR_ADD, k, v) == 0)
end
end
if key then
checkz(mysql, C.mysql_ssl_set(mysql, key, cert, ca, capath, cipher))
end
checkh(mysql, C.mysql_real_connect(mysql, host, user, pass, db, port, unix_socket, client_flag))
if charset then mysql:set_charset(charset) end
return mysql
end
local conn = {} --connection methods
function conn.close(mysql)
C.mysql_close(mysql)
ffi.gc(mysql, nil)
end
function conn.set_charset(mysql, charset)
checkz(mysql, C.mysql_set_character_set(mysql, charset))
end
function conn.select_db(mysql, db)
checkz(mysql, C.mysql_select_db(mysql, db))
end
function conn.change_user(mysql, user, pass, db)
checkz(mysql, C.mysql_change_user(mysql, user, pass, db))
end
function conn.set_multiple_statements(mysql, yes)
checkz(mysql, C.mysql_set_server_option(mysql, yes and C.MYSQL_OPTION_MULTI_STATEMENTS_ON or
C.MYSQL_OPTION_MULTI_STATEMENTS_OFF))
end
--connection info
function conn.charset(mysql)
return cstring(C.mysql_character_set_name(mysql))
end
function conn.charset_info(mysql)
local info = ffi.new'MY_CHARSET_INFO'
checkz(C.mysql_get_character_set_info(mysql, info))
assert(info.name ~= NULL)
assert(info.csname ~= NULL)
return {
number = info.number,
state = info.state,
name = cstring(info.csname), --csname and name are inverted from the spec
collation = cstring(info.name),
comment = cstring(info.comment),
dir = cstring(info.dir),
mbminlen = info.mbminlen,
mbmaxlen = info.mbmaxlen,
}
end
function conn.ping(mysql)
local ret = C.mysql_ping(mysql)
if ret == 0 then
return true
elseif C.mysql_error(mysql) == C.MYSQL_CR_SERVER_GONE_ERROR then
return false
end
myerror(mysql)
end
function conn.thread_id(mysql)
return C.mysql_thread_id(mysql) --NOTE: result is cdata on x64!
end
function conn.stat(mysql)
return cstring(checkh(mysql, C.mysql_stat(mysql)))
end
function conn.server_info(mysql)
return cstring(checkh(mysql, C.mysql_get_server_info(mysql)))
end
function conn.host_info(mysql)
return cstring(checkh(mysql, C.mysql_get_host_info(mysql)))
end
function conn.server_version(mysql)
return tonumber(C.mysql_get_server_version(mysql))
end
function conn.proto_info(...)
return C.mysql_get_proto_info(...)
end
function conn.ssl_cipher(mysql)
return cstring(C.mysql_get_ssl_cipher(mysql))
end
--transactions
function conn.commit(mysql) checkz(mysql, C.mysql_commit(mysql)) end
function conn.rollback(mysql) checkz(mysql, C.mysql_rollback(mysql)) end
function conn.set_autocommit(mysql, yes)
checkz(mysql, C.mysql_autocommit(mysql, yes == nil or yes))
end
--queries
function conn.escape_tobuffer(mysql, data, size, buf, sz)
size = size or #data
assert(sz >= size * 2 + 1)
return tonumber(C.mysql_real_escape_string(mysql, buf, data, size))
end
function conn.escape(mysql, data, size)
size = size or #data
local sz = size * 2 + 1
local buf = ffi.new('uint8_t[?]', sz)
sz = conn.escape_tobuffer(mysql, data, size, buf, sz)
return ffi.string(buf, sz)
end
function conn.query(mysql, data, size)
checkz(mysql, C.mysql_real_query(mysql, data, size or #data))
end
--query info
function conn.field_count(...)
return C.mysql_field_count(...)
end
local minus1_uint64 = ffi.cast('uint64_t', ffi.cast('int64_t', -1))
function conn.affected_rows(mysql)
local n = C.mysql_affected_rows(mysql)
if n == minus1_uint64 then myerror(mysql) end
return tonumber(n)
end
function conn.insert_id(...)
return C.mysql_insert_id(...) --NOTE: result is cdata on x64!
end
function conn.errno(conn)
local err = C.mysql_errno(conn)
if err == 0 then return end
return err
end
function conn.sqlstate(mysql)
return cstring(C.mysql_sqlstate(mysql))
end
function conn.warning_count(...)
return C.mysql_warning_count(...)
end
function conn.info(mysql)
return cstring(C.mysql_info(mysql))
end
--query results
function conn.next_result(mysql) --multiple statement queries return multiple results
local ret = C.mysql_next_result(mysql)
if ret == 0 then return true end
if ret == -1 then return false end
myerror(mysql)
end
function conn.more_results(mysql)
return C.mysql_more_results(mysql) == 1
end
local function result_function(func)
return function(mysql)
local res = checkh(mysql, C[func](mysql))
return ffi.gc(res, C.mysql_free_result)
end
end
conn.store_result = result_function'mysql_store_result'
conn.use_result = result_function'mysql_use_result'
local res = {} --result methods
function res.free(res)
C.mysql_free_result(res)
ffi.gc(res, nil)
end
function res.row_count(res)
return tonumber(C.mysql_num_rows(res))
end
function res.field_count(...)
return C.mysql_num_fields(...)
end
function res.eof(res)
return C.mysql_eof(res) ~= 0
end
--field info
local field_type_names = {
[ffi.C.MYSQL_TYPE_DECIMAL] = 'decimal', --DECIMAL or NUMERIC
[ffi.C.MYSQL_TYPE_TINY] = 'tinyint',
[ffi.C.MYSQL_TYPE_SHORT] = 'smallint',
[ffi.C.MYSQL_TYPE_LONG] = 'int',
[ffi.C.MYSQL_TYPE_FLOAT] = 'float',
[ffi.C.MYSQL_TYPE_DOUBLE] = 'double', --DOUBLE or REAL
[ffi.C.MYSQL_TYPE_NULL] = 'null',
[ffi.C.MYSQL_TYPE_TIMESTAMP] = 'timestamp',
[ffi.C.MYSQL_TYPE_LONGLONG] = 'bigint',
[ffi.C.MYSQL_TYPE_INT24] = 'mediumint',
[ffi.C.MYSQL_TYPE_DATE] = 'date', --pre mysql 5.0, storage = 4 bytes
[ffi.C.MYSQL_TYPE_TIME] = 'time',
[ffi.C.MYSQL_TYPE_DATETIME] = 'datetime',
[ffi.C.MYSQL_TYPE_YEAR] = 'year',
[ffi.C.MYSQL_TYPE_NEWDATE] = 'date', --mysql 5.0+, storage = 3 bytes
[ffi.C.MYSQL_TYPE_VARCHAR] = 'varchar',
[ffi.C.MYSQL_TYPE_BIT] = 'bit',
[ffi.C.MYSQL_TYPE_TIMESTAMP2] = 'timestamp', --mysql 5.6+, can store fractional seconds
[ffi.C.MYSQL_TYPE_DATETIME2] = 'datetime', --mysql 5.6+, can store fractional seconds
[ffi.C.MYSQL_TYPE_TIME2] = 'time', --mysql 5.6+, can store fractional seconds
[ffi.C.MYSQL_TYPE_NEWDECIMAL] = 'decimal', --mysql 5.0+, Precision math DECIMAL or NUMERIC
[ffi.C.MYSQL_TYPE_ENUM] = 'enum',
[ffi.C.MYSQL_TYPE_SET] = 'set',
[ffi.C.MYSQL_TYPE_TINY_BLOB] = 'tinyblob',
[ffi.C.MYSQL_TYPE_MEDIUM_BLOB] = 'mediumblob',
[ffi.C.MYSQL_TYPE_LONG_BLOB] = 'longblob',
[ffi.C.MYSQL_TYPE_BLOB] = 'text', --TEXT or BLOB
[ffi.C.MYSQL_TYPE_VAR_STRING] = 'varchar', --VARCHAR or VARBINARY
[ffi.C.MYSQL_TYPE_STRING] = 'char', --CHAR or BINARY
[ffi.C.MYSQL_TYPE_GEOMETRY] = 'spatial', --Spatial field
}
local binary_field_type_names = {
[ffi.C.MYSQL_TYPE_BLOB] = 'blob',
[ffi.C.MYSQL_TYPE_VAR_STRING] = 'varbinary',
[ffi.C.MYSQL_TYPE_STRING] = 'binary',
}
local field_flag_names = {
[ffi.C.MYSQL_NOT_NULL_FLAG] = 'not_null',
[ffi.C.MYSQL_PRI_KEY_FLAG] = 'pri_key',
[ffi.C.MYSQL_UNIQUE_KEY_FLAG] = 'unique_key',
[ffi.C.MYSQL_MULTIPLE_KEY_FLAG] = 'key',
[ffi.C.MYSQL_BLOB_FLAG] = 'is_blob',
[ffi.C.MYSQL_UNSIGNED_FLAG] = 'unsigned',
[ffi.C.MYSQL_ZEROFILL_FLAG] = 'zerofill',
[ffi.C.MYSQL_BINARY_FLAG] = 'is_binary',
[ffi.C.MYSQL_ENUM_FLAG] = 'is_enum',
[ffi.C.MYSQL_AUTO_INCREMENT_FLAG] = 'autoincrement',
[ffi.C.MYSQL_TIMESTAMP_FLAG] = 'is_timestamp',
[ffi.C.MYSQL_SET_FLAG] = 'is_set',
[ffi.C.MYSQL_NO_DEFAULT_VALUE_FLAG] = 'no_default',
[ffi.C.MYSQL_ON_UPDATE_NOW_FLAG] = 'on_update_now',
[ffi.C.MYSQL_NUM_FLAG] = 'is_number',
}
local function field_type_name(info)
local type_flag = tonumber(info.type)
local field_type = field_type_names[type_flag]
--charsetnr 63 changes CHAR into BINARY, VARCHAR into VARBYNARY, TEXT into BLOB
field_type = info.charsetnr == 63 and binary_field_type_names[type_flag] or field_type
return field_type
end
--convenience field type fetcher (less garbage)
function res.field_type(res, i)
assert(i >= 1 and i <= res:field_count(), 'index out of range')
local info = C.mysql_fetch_field_direct(res, i-1)
local unsigned = bit.bor(info.flags, C.MYSQL_UNSIGNED_FLAG) ~= 0
return field_type_name(info), tonumber(info.length), unsigned, info.decimals
end
function res.field_info(res, i)
assert(i >= 1 and i <= res:field_count(), 'index out of range')
local info = C.mysql_fetch_field_direct(res, i-1)
local t = {
name = cstring(info.name, info.name_length),
org_name = cstring(info.org_name, info.org_name_length),
table = cstring(info.table, info.table_length),
org_table = cstring(info.org_table, info.org_table_length),
db = cstring(info.db, info.db_length),
catalog = cstring(info.catalog, info.catalog_length),
def = cstring(info.def, info.def_length),
length = tonumber(info.length),
max_length = tonumber(info.max_length),
decimals = info.decimals,
charsetnr = info.charsetnr,
type_flag = tonumber(info.type),
type = field_type_name(info),
flags = info.flags,
extension = ptr(info.extension),
}
for flag, name in pairs(field_flag_names) do
t[name] = bit.band(flag, info.flags) ~= 0
end
return t
end
--convenience field name fetcher (less garbage)
function res.field_name(res, i)
assert(i >= 1 and i <= res:field_count(), 'index out of range')
local info = C.mysql_fetch_field_direct(res, i-1)
return cstring(info.name, info.name_length)
end
--convenience field iterator, shortcut for: for i=1,res:field_count() do local field = res:field_info(i) ... end
function res.fields(res)
local n = res:field_count()
local i = 0
return function()
if i == n then return end
i = i + 1
return i, res:field_info(i)
end
end
--row data fetching and parsing
ffi.cdef('double strtod(const char*, char**);')
local function parse_int(data, sz) --using strtod to avoid string creation
return ffi.C.strtod(data, nil)
end
local function parse_float(data, sz)
return tonumber(ffi.cast('float', ffi.C.strtod(data, nil))) --because windows is missing strtof()
end
local function parse_double(data, sz)
return ffi.C.strtod(data, nil)
end
ffi.cdef('int64_t strtoll(const char*, char**, int) ' ..(ffi.os == 'Windows' and ' asm("_strtoi64")' or '') .. ';')
local function parse_int64(data, sz)
return ffi.C.strtoll(data, nil, 10)
end
ffi.cdef('uint64_t strtoull(const char*, char**, int) ' ..(ffi.os == 'Windows' and ' asm("_strtoui64")' or '') .. ';')
local function parse_uint64(data, sz)
return ffi.C.strtoull(data, nil, 10)
end
local function parse_bit(data, sz)
data = ffi.cast('uint8_t*', data) --force unsigned
local n = data[0] --this is the msb: bit fields always come in big endian byte order
if sz > 6 then --we can cover up to 6 bytes with only Lua numbers
n = ffi.new('uint64_t', n)
end
for i=1,sz-1 do
n = n * 256 + data[i]
end
return n
end
local function parse_date_(data, sz)
assert(sz >= 10)
local z = ('0'):byte()
local year = (data[0] - z) * 1000 + (data[1] - z) * 100 + (data[2] - z) * 10 + (data[3] - z)
local month = (data[5] - z) * 10 + (data[6] - z)
local day = (data[8] - z) * 10 + (data[9] - z)
return year, month, day
end
local function parse_time_(data, sz)
assert(sz >= 8)
local z = ('0'):byte()
local hour = (data[0] - z) * 10 + (data[1] - z)
local min = (data[3] - z) * 10 + (data[4] - z)
local sec = (data[6] - z) * 10 + (data[7] - z)
local frac = 0
for i = 9, sz-1 do
frac = frac * 10 + (data[i] - z)
end
return hour, min, sec, frac
end
local function format_date(year, month, day)
return string.format('%04d-%02d-%02d', year, month, day)
end
local function format_time(hour, min, sec, frac)
if frac and frac ~= 0 then
return string.format('%02d:%02d:%02d.%d', hour, min, sec, frac)
else
return string.format('%02d:%02d:%02d', hour, min, sec)
end
end
local function datetime_tostring(t)
local date, time
if t.year then
date = format_date(t.year, t.month, t.day)
end
if t.sec then
time = format_time(t.hour, t.min, t.sec, t.frac)
end
if date and time then
return date .. ' ' .. time
else
return assert(date or time)
end
end
local datetime_meta = {__tostring = datetime_tostring}
local function datetime(t)
return setmetatable(t, datetime_meta)
end
local function parse_date(data, sz)
local year, month, day = parse_date_(data, sz)
return datetime{year = year, month = month, day = day}
end
local function parse_time(data, sz)
local hour, min, sec, frac = parse_time_(data, sz)
return datetime{hour = hour, min = min, sec = sec, frac = frac}
end
local function parse_datetime(data, sz)
local year, month, day = parse_date_(data, sz)
local hour, min, sec, frac = parse_time_(data + 11, sz - 11)
return datetime{year = year, month = month, day = day, hour = hour, min = min, sec = sec, frac = frac}
end
local field_decoders = { --other field types not present here are returned as strings, unparsed
[ffi.C.MYSQL_TYPE_TINY] = parse_int,
[ffi.C.MYSQL_TYPE_SHORT] = parse_int,
[ffi.C.MYSQL_TYPE_LONG] = parse_int,
[ffi.C.MYSQL_TYPE_FLOAT] = parse_float,
[ffi.C.MYSQL_TYPE_DOUBLE] = parse_double,
[ffi.C.MYSQL_TYPE_TIMESTAMP] = parse_datetime,
[ffi.C.MYSQL_TYPE_LONGLONG] = parse_int64,
[ffi.C.MYSQL_TYPE_INT24] = parse_int,
[ffi.C.MYSQL_TYPE_DATE] = parse_date,
[ffi.C.MYSQL_TYPE_TIME] = parse_time,
[ffi.C.MYSQL_TYPE_DATETIME] = parse_datetime,
[ffi.C.MYSQL_TYPE_NEWDATE] = parse_date,
[ffi.C.MYSQL_TYPE_TIMESTAMP2] = parse_datetime,
[ffi.C.MYSQL_TYPE_DATETIME2] = parse_datetime,
[ffi.C.MYSQL_TYPE_TIME2] = parse_time,
[ffi.C.MYSQL_TYPE_YEAR] = parse_int,
[ffi.C.MYSQL_TYPE_BIT] = parse_bit,
}
local unsigned_decoders = {
[ffi.C.MYSQL_TYPE_LONGLONG] = parse_uint64,
}
local function mode_flags(mode)
local assoc = mode and mode:find'a'
local numeric = not mode or not assoc or mode:find'n'
local decode = not mode or not mode:find's'
local packed = mode and mode:find'[an]'
local fetch_fields = assoc or decode --if assoc we need field_name, if decode we need field_type
return numeric, assoc, decode, packed, fetch_fields
end
local function fetch_row(res, numeric, assoc, decode, field_count, fields, t)
local values = C.mysql_fetch_row(res)
if values == NULL then
if res.conn ~= NULL then --buffered read: check for errors
myerror(res.conn, 4)
end
return nil
end
local sizes = C.mysql_fetch_lengths(res)
for i=0,field_count-1 do
local v = values[i]
if v ~= NULL then
local decoder
if decode then
local ftype = tonumber(fields[i].type)
local unsigned = bit.bor(fields[i].flags, C.MYSQL_UNSIGNED_FLAG) ~= 0
decoder = unsigned and unsigned_decoders[ftype] or field_decoders[ftype] or ffi.string
else
decoder = ffi.string
end
v = decoder(values[i], tonumber(sizes[i]))
if numeric then
t[i+1] = v
end
if assoc then
local k = ffi.string(fields[i].name, fields[i].name_length)
t[k] = v
end
end
end
return t
end
function res.fetch(res, mode, t)
local numeric, assoc, decode, packed, fetch_fields = mode_flags(mode)
local field_count = C.mysql_num_fields(res)
local fields = fetch_fields and C.mysql_fetch_fields(res)
local row = fetch_row(res, numeric, assoc, decode, field_count, fields, t or {})
if not row then return nil end
if packed then
return row
else
return true, unpack(row)
end
end
function res.rows(res, mode, t)
local numeric, assoc, decode, packed, fetch_fields = mode_flags(mode)
local field_count = C.mysql_num_fields(res)
local fields = fetch_fields and C.mysql_fetch_fields(res)
local i = 0
res:seek(1)
return function()
local row = fetch_row(res, numeric, assoc, decode, field_count, fields, t or {})
if not row then return nil end
i = i + 1
if packed then
return i, row
else
return i, unpack(row)
end
end
end
function res.tell(...)
return C.mysql_row_tell(...)
end
function res.seek(res, where) --use in conjunction with res:row_count()
if type(where) == 'number' then
C.mysql_data_seek(res, where-1)
else
C.mysql_row_seek(res, where)
end
end
--reflection
local function list_function(func)
return function(mysql, wild)
local res = checkh(mysql, C[func](mysql, wild))
return ffi.gc(res, C.mysql_free_result)
end
end
conn.list_dbs = list_function'mysql_list_dbs'
conn.list_tables = list_function'mysql_list_tables'
conn.list_processes = result_function'mysql_list_processes'
--remote control
function conn.kill(mysql, pid)
checkz(mysql, C.mysql_kill(mysql, pid))
end
function conn.shutdown(mysql, level)
checkz(mysql, C.mysql_shutdown(mysql, enum(level or C.MYSQL_SHUTDOWN_DEFAULT, 'MYSQL_')))
end
function conn.refresh(mysql, t) --options are 'REFRESH_*' or mysql.C.MYSQL_REFRESH_* enums
local options = 0
if type(t) == 'number' then
options = t
else
for k,v in pairs(t) do
if v then
options = bit.bor(options, enum(k, 'MYSQL_'))
end
end
end
checkz(mysql, C.mysql_refresh(mysql, options))
end
function conn.dump_debug_info(mysql)
checkz(mysql, C.mysql_dump_debug_info(mysql))
end
--prepared statements
local function sterror(stmt, stacklevel)
local err = cstring(C.mysql_stmt_error(stmt))
if not err then return end
error(string.format('mysql error: %s', err), stacklevel or 3)
end
local function stcheckz(stmt, ret)
if ret == 0 then return end
sterror(stmt, 4)
end
local function stcheckbool(stmt, ret)
if ret == 1 then return end
sterror(stmt, 4)
end
local function stcheckh(stmt, ret)
if ret ~= NULL then return ret end
sterror(stmt, 4)
end
function conn.prepare(mysql, query)
local stmt = checkh(mysql, C.mysql_stmt_init(mysql))
ffi.gc(stmt, C.mysql_stmt_close)
stcheckz(stmt, C.mysql_stmt_prepare(stmt, query, #query))
return stmt
end
local stmt = {} --statement methods
function stmt.close(stmt)
stcheckbool(stmt, C.mysql_stmt_close(stmt))
ffi.gc(stmt, nil)
end
function stmt.exec(stmt)
stcheckz(stmt, C.mysql_stmt_execute(stmt))
end
function stmt.next_result(stmt)
local ret = C.mysql_stmt_next_result(stmt)
if ret == 0 then return true end
if ret == -1 then return false end
sterror(stmt)
end
function stmt.store_result(stmt)
stcheckz(stmt, C.mysql_stmt_store_result(stmt))
end
function stmt.free_result(stmt)
stcheckbool(stmt, C.mysql_stmt_free_result(stmt))
end
function stmt.row_count(stmt)
return tonumber(C.mysql_stmt_num_rows(stmt))
end
function stmt.affected_rows(stmt)
local n = C.mysql_stmt_affected_rows(stmt)
if n == minus1_uint64 then sterror(stmt) end
return tonumber(n)
end
function stmt.insert_id(...)
return C.mysql_stmt_insert_id(...)
end
function stmt.field_count(stmt)
return tonumber(C.mysql_stmt_field_count(stmt))
end
function stmt.param_count(stmt)
return tonumber(C.mysql_stmt_param_count(stmt))
end
function stmt.errno(stmt)
local err = C.mysql_stmt_errno(stmt)
if err == 0 then return end
return err
end
function stmt.sqlstate(stmt)
return cstring(C.mysql_stmt_sqlstate(stmt))
end
function stmt.result_metadata(stmt)
local res = stcheckh(stmt, C.mysql_stmt_result_metadata(stmt))
return res and ffi.gc(res, C.mysql_free_result)
end
function stmt.fields(stmt)
local res = stmt:result_metadata()
if not res then return nil end
local fields = res:fields()
return function()
local i, info = fields()
if not i then
res:free()
end
return i, info
end
end
function stmt.fetch(stmt)
local ret = C.mysql_stmt_fetch(stmt)
if ret == 0 then return true end
if ret == C.MYSQL_NO_DATA then return false end
if ret == C.MYSQL_DATA_TRUNCATED then return true, 'truncated' end
sterror(stmt)
end
function stmt.reset(stmt)
stcheckz(stmt, C.mysql_stmt_reset(stmt))
end
function stmt.tell(...)
return C.mysql_stmt_row_tell(...)
end
function stmt.seek(stmt, where) --use in conjunction with stmt:row_count()
if type(where) == 'number' then
C.mysql_stmt_data_seek(stmt, where-1)
else
C.mysql_stmt_row_seek(stmt, where)
end
end
function stmt.write(stmt, param_number, data, size)
stcheckz(stmt, C.mysql_stmt_send_long_data(stmt, param_number, data, size or #data))
end
function stmt.update_max_length(stmt)
local attr = ffi.new'my_bool[1]'
stcheckz(stmt, C.mysql_stmt_attr_get(stmt, C.STMT_ATTR_UPDATE_MAX_LENGTH, attr))
return attr[0] == 1
end
function stmt.set_update_max_length(stmt, yes)
local attr = ffi.new('my_bool[1]', yes == nil or yes)
stcheckz(stmt, C.mysql_stmt_attr_set(stmt, C.STMT_ATTR_CURSOR_TYPE, attr))
end
function stmt.cursor_type(stmt)
local attr = ffi.new'uint32_t[1]'
stcheckz(stmt, C.mysql_stmt_attr_get(stmt, C.STMT_ATTR_CURSOR_TYPE, attr))
return attr[0]
end
function stmt.set_cursor_type(stmt, cursor_type)
local attr = ffi.new('uint32_t[1]', enum(cursor_type, 'MYSQL_'))
stcheckz(stmt, C.mysql_stmt_attr_set(stmt, C.STMT_ATTR_CURSOR_TYPE, attr))
end
function stmt.prefetch_rows(stmt)
local attr = ffi.new'uint32_t[1]'
stcheckz(stmt, C.mysql_stmt_attr_get(stmt, C.STMT_ATTR_PREFETCH_ROWS, attr))
return attr[0]
end
function stmt.set_prefetch_rows(stmt, n)
local attr = ffi.new('uint32_t[1]', n)
stcheckz(stmt, C.mysql_stmt_attr_set(stmt, C.STMT_ATTR_PREFETCH_ROWS, attr))
end
--prepared statements / bind buffers
--see http://dev.mysql.com/doc/refman/5.7/en/c-api-prepared-statement-type-codes.html
local bb_types_input = {
--conversion-free types
tinyint = ffi.C.MYSQL_TYPE_TINY,
smallint = ffi.C.MYSQL_TYPE_SHORT,
int = ffi.C.MYSQL_TYPE_LONG,
integer = ffi.C.MYSQL_TYPE_LONG, --alias of int
bigint = ffi.C.MYSQL_TYPE_LONGLONG,
float = ffi.C.MYSQL_TYPE_FLOAT,
double = ffi.C.MYSQL_TYPE_DOUBLE,
time = ffi.C.MYSQL_TYPE_TIME,
date = ffi.C.MYSQL_TYPE_DATE,
datetime = ffi.C.MYSQL_TYPE_DATETIME,
timestamp = ffi.C.MYSQL_TYPE_TIMESTAMP,
text = ffi.C.MYSQL_TYPE_STRING,
char = ffi.C.MYSQL_TYPE_STRING,
varchar = ffi.C.MYSQL_TYPE_STRING,
blob = ffi.C.MYSQL_TYPE_BLOB,
binary = ffi.C.MYSQL_TYPE_BLOB,
varbinary = ffi.C.MYSQL_TYPE_BLOB,
null = ffi.C.MYSQL_TYPE_NULL,
--conversion types (can only use one of the above C types)
mediumint = ffi.C.MYSQL_TYPE_LONG,
real = ffi.C.MYSQL_TYPE_DOUBLE,
decimal = ffi.C.MYSQL_TYPE_BLOB,
numeric = ffi.C.MYSQL_TYPE_BLOB,
year = ffi.C.MYSQL_TYPE_SHORT,
tinyblob = ffi.C.MYSQL_TYPE_BLOB,
tinytext = ffi.C.MYSQL_TYPE_BLOB,
mediumblob = ffi.C.MYSQL_TYPE_BLOB,
mediumtext = ffi.C.MYSQL_TYPE_BLOB,
longblob = ffi.C.MYSQL_TYPE_BLOB,
longtext = ffi.C.MYSQL_TYPE_BLOB,
bit = ffi.C.MYSQL_TYPE_LONGLONG, --MYSQL_TYPE_BIT is not available for input params
set = ffi.C.MYSQL_TYPE_BLOB,
enum = ffi.C.MYSQL_TYPE_BLOB,
}
local bb_types_output = {
--conversion-free types
tinyint = ffi.C.MYSQL_TYPE_TINY,
smallint = ffi.C.MYSQL_TYPE_SHORT,
mediumint = ffi.C.MYSQL_TYPE_INT24, --int32
int = ffi.C.MYSQL_TYPE_LONG,
integer = ffi.C.MYSQL_TYPE_LONG, --alias of int
bigint = ffi.C.MYSQL_TYPE_LONGLONG,
float = ffi.C.MYSQL_TYPE_FLOAT,
double = ffi.C.MYSQL_TYPE_DOUBLE,
real = ffi.C.MYSQL_TYPE_DOUBLE,
decimal = ffi.C.MYSQL_TYPE_NEWDECIMAL, --char[]
numeric = ffi.C.MYSQL_TYPE_NEWDECIMAL, --char[]
year = ffi.C.MYSQL_TYPE_SHORT,
time = ffi.C.MYSQL_TYPE_TIME,
date = ffi.C.MYSQL_TYPE_DATE,
datetime = ffi.C.MYSQL_TYPE_DATETIME,
timestamp = ffi.C.MYSQL_TYPE_TIMESTAMP,
char = ffi.C.MYSQL_TYPE_STRING,
binary = ffi.C.MYSQL_TYPE_STRING,
varchar = ffi.C.MYSQL_TYPE_VAR_STRING,
varbinary = ffi.C.MYSQL_TYPE_VAR_STRING,
tinyblob = ffi.C.MYSQL_TYPE_TINY_BLOB,
tinytext = ffi.C.MYSQL_TYPE_TINY_BLOB,
blob = ffi.C.MYSQL_TYPE_BLOB,
text = ffi.C.MYSQL_TYPE_BLOB,
mediumblob = ffi.C.MYSQL_TYPE_MEDIUM_BLOB,
mediumtext = ffi.C.MYSQL_TYPE_MEDIUM_BLOB,
longblob = ffi.C.MYSQL_TYPE_LONG_BLOB,
longtext = ffi.C.MYSQL_TYPE_LONG_BLOB,
bit = ffi.C.MYSQL_TYPE_BIT,
--conversion types (can only use one of the above C types)
null = ffi.C.MYSQL_TYPE_TINY,
set = ffi.C.MYSQL_TYPE_BLOB,
enum = ffi.C.MYSQL_TYPE_BLOB,
}
local number_types = {
[ffi.C.MYSQL_TYPE_TINY] = 'int8_t[1]',
[ffi.C.MYSQL_TYPE_SHORT] = 'int16_t[1]',
[ffi.C.MYSQL_TYPE_LONG] = 'int32_t[1]',
[ffi.C.MYSQL_TYPE_INT24] = 'int32_t[1]',
[ffi.C.MYSQL_TYPE_LONGLONG] = 'int64_t[1]',
[ffi.C.MYSQL_TYPE_FLOAT] = 'float[1]',
[ffi.C.MYSQL_TYPE_DOUBLE] = 'double[1]',
}