-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmysql.d
4364 lines (4168 loc) · 141 KB
/
mysql.d
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
/**
* A native D driver for the MySQL database system. Source file mysql.d.
*
* This module attempts to provide composite objects and methods that will allow a wide range of common database
* operations, but be relatively easy to use. The design is a first attempt to illustrate the structure of a set of modules
* to cover popular database systems and ODBC.
*
* It has no dependecies on GPL header files or libraries, instead communicating directly with the server via the
* published client/server protocol.
*
* $(LINK http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol)$(BR)
* $(LINK http://forge.mysql.com/w/index.php?title=MySQL_Internals_ClientServer_Protocol&diff=5078&oldid=4374)
*
* This version is not by any means comprehensive, and there is still a good deal of work to do. As a general design
* position it avoids providing wrappers for operations that can be accomplished by simple SQL sommands, unless
* the command produces a result set. There are some instances of the latter category to provide simple meta-data
* for the database,
*
* Its primary objects are:
* $(UL
* $(LI Connection: $(UL $(LI Connection to the server, and querying and setting of server parameters.)))
* $(LI Command: Handling of SQL requests/queries/commands, with principal methods:
* $(UL
$(LI execSQL() - plain old SQL query.)
* $(LI execTuple() - get a set of values from a select or similar query into a matching tuple of D variables.)
* $(LI execPrepared() - execute a prepared statement.)
* $(LI execResult() - execute a raw SQL statement and get a complete result set.)
* $(LI execSequence() - execute a raw SQL statement and handle the rows one at a time.)
* $(LI execPreparedResult() - execute a prepared statement and get a complete result set.)
* $(LI execPreparedSequence() - execute a prepared statement and handle the rows one at a time.)
* $(LI execFunction() - execute a stored function with D variables as input and output.)
* $(LI execProcedure() - execute a stored procedure with D variables as input.)
* )
* )
* $(LI ResultSet: $(UL $(LI A random access range of rows, where a Row is basically an array of variant.)))
* $(LI ResultSequence: $(UL $(LIAn input range of similar rows.)))
* )
*
* It has currently only been compiled and unit tested on Ubuntu with D2.055 using a TCP loopback connection
* to a server on the local machine.
*
* There are numerous examples of usage in the unittest sections.
*
* The file mysqld.sql, included with the module source code, can be used to generate the tables required by the unit tests.
*
* There is an outstanding issue with Connections. Normally MySQL clients sonnect to a server on the same machine
* via a Unix socket on *nix systems, and through a named pipe on Windows. Neither of these conventions is
* currently supported. TCP must be used for all connections.
*
* Since there is currently no SHA1 support on Phobos, a simple translation of the NIST example C code for SHA1
* is also included with this module.
*
* Copyright: Copyright 2011
* License: $(LINK www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Author: Steve Teale
*/
module mysql;
import sha1;
import std.socket;
import std.exception;
import std.stdio;
import std.string;
import std.conv;
import std.variant;
import std.datetime;
/**
* An exception type to distinguish exceptions thrown by this module.
*/
class MySQLException: Exception
{
this(string msg, string file, uint line) { super(msg, file, line); }
}
alias MySQLException MYX;
/**
* A simple struct to represent time difference.
*
* D's std.datetime does not have a type that is closely compatible with the MySQL
* interpretation of a time difference, so we define a struct here to hold such
* values.
*
*/
struct TimeDiff
{
bool negative;
int days;
ubyte hours, minutes, seconds;
}
/**
* Function to extract a time difference from a binary encoded row.
*
* Time/date structures are packed by the server into a byte sub-packet
* with a leading length byte, and a minimal number of bytes to embody the data.
*
* Params: a = slice of a protocol packet beginning at the length byte for a chunk of time data
*
* Returns: A populated or default initialized TimeDiff struct.
*/
TimeDiff toTimeDiff(ubyte[] a)
{
enforceEx!MYX(a.length, "Supplied byte array is zero length");
TimeDiff td;
uint l = a[0];
enforceEx!MYX(l == 0 || l == 5 || l == 8 || l == 12, "Bad Time length in binary row.");
if (l == 5)
{
td.negative = (a[1] != 0);
td.days = (a[5] << 24) + (a[4] << 16) + (a[3] << 8) + a[2];
}
else if (l > 5)
{
td.negative = (a[1] != 0);
td.days = (a[5] << 24) + (a[4] << 16) + (a[3] << 8) + a[2];
td.hours = a[6];
td.minutes = a[7];
td.seconds = a[8];
}
// Note that the fractional seconds part is not stored by MtSQL
return td;
}
/**
* Function to extract a time difference from a text encoded column value.
*
* Text representations of a time difference are like -750:12:02 - 750 hours
* 12 minutes and two seconds ago.
*
* Params: s = A string representation of the time difference.
* Returns: A populated or default initialized TimeDiff struct.
*/
TimeDiff toTimeDiff(string s)
{
TimeDiff td;
int t = parse!int(s);
if (t < 0)
{
td.negative = true;
t = -t;
}
td.hours = t%24;
td.days = t/24;
munch(s, ":");
td.minutes = parse!ubyte(s);
munch(s, ":");
td.seconds = parse!ubyte(s);
return td;
}
/**
* Function to extract a TimeOfDay from a binary encoded row.
*
* Time/date structures are packed by the server into a byte sub-packet
* with a leading length byte, and a minimal number of bytes to embody the data.
*
* Params: a = slice of a protocol packet beginning at the length byte for a chunk of time data
* Returns: A populated or default initialized std.datetime.TimeOfDay struct.
*/
TimeOfDay toTimeOfDay(ubyte[] a)
{
enforceEx!MYX(a.length, "Supplied byte array is zero length");
TimeOfDay tod;
uint l = a[0];
enforceEx!MYX(l == 0 || l == 5 || l == 8 || l == 12, "Bad Time length in binary row.");
enforceEx!MYX(l >= 8, "Time column value is not in a time-of-day format");
tod.hour = a[6];
tod.minute = a[7];
tod.second = a[8];
return tod;
}
/**
* Function to extract a TimeOfDay from a text encoded column value.
*
* Text representations of a time of day are as in 14:22:02
*
* Params: s = A string representation of the time.
* Returns: A populated or default initialized std.datetine.TimeOfDay struct.
*/
TimeOfDay toTimeOfDay(string s)
{
TimeOfDay tod;
tod.hour = parse!int(s);
enforceEx!MYX(tod.hour <= 24 && tod.hour >= 0, "Time column value is in time difference form");
munch(s, ":");
tod.minute = parse!ubyte(s);
munch(s, ":");
tod.second = parse!ubyte(s);
return tod;
}
/**
* Function to pack a TimeOfDay into a binary encoding for transmission to the server.
*
* Time/date structures are packed into a string of bytes with a leading length byte,
* and a minimal number of bytes to embody the data.
*
* Params: tod = TimeOfDay struct.
* Returns: Packed ubyte[].
*/
ubyte[] pack(TimeOfDay tod)
{
ubyte[] rv;
if (tod == TimeOfDay.init)
{
rv.length = 1;
rv[0] = 0;
return rv;
}
rv.length = 9;
rv[0] = 8;
rv[6] = tod.hour;
rv[7] = tod.minute;
rv[8] = tod.second;
return rv;
}
/**
* Function to extract a Date from a binary encoded row.
*
* Time/date structures are packed by the server into a byte sub-packet
* with a leading length byte, and a minimal number of bytes to embody the data.
*
* Params: a = slice of a protocol packet beginning at the length byte for a chunk of Date data
* Returns: A populated or default initialized std.datetime.Date struct.
*/
Date toDate(ubyte[] a)
{
enforceEx!MYX(a.length, "Supplied byte array is zero length");
if (a[0] == 0)
return Date(0,0,0);
enforceEx!MYX(a[0] >= 4, "Binary date representation is too short");
int year = (a[2] << 8) + a[1];
int month = cast(int) a[3];
int day = cast(int) a[4];
return Date(year, month, day);
}
/**
* Function to extract a Date from a text encoded column value.
*
* Text representations of a Date are as in 2011-11-11
*
* Params: a = A string representation of the time difference.
* Returns: A populated or default initialized std.datetime.Date struct.
*/
Date toDate(string s)
{
int year = parse!(ushort)(s);
munch(s, "-");
int month = parse!(ubyte)(s);
munch(s, "-");
int day = parse!(ubyte)(s);
return Date(year, month, day);
}
/**
* Function to pack a Date into a binary encoding for transmission to the server.
*
* Time/date structures are packed into a string of bytes with a leading length byte,
* and a minimal number of bytes to embody the data.
*
* Params: dt = std.datetime.Date struct.
* Returns: Packed ubyte[].
*/
ubyte[] pack(Date dt)
{
ubyte[] rv;
if (dt.year < 0)
{
rv.length = 1;
rv[0] = 0;
return rv;
}
rv.length = 4;
rv[1] = cast(ubyte) (dt.year & 0xff);
rv[2] = cast(ubyte) ((dt.year >> 8) & 0xff);
rv[3] = cast(ubyte) dt.month;
rv[4] = cast(ubyte) dt.day;
rv[0] = 4;
return rv;
}
/**
* Function to extract a DateTime from a binary encoded row.
*
* Time/date structures are packed by the server into a byte sub-packet
* with a leading length byte, and a minimal number of bytes to embody the data.
*
* Params: a = slice of a protocol packet beginning at the length byte for a chunk of
* DateTime data
* Returns: A populated or default initialized std.datetime.DateTime struct.
*/
DateTime toDateTime(ubyte[] a)
{
enforceEx!MYX(a.length, "Supplied byte array is zero length");
DateTime dt;
if (a[0] == 0)
return dt;
enforceEx!MYX(a[0] >= 4, "Supplied ubyte[] is not long enough");
int year = (a[2] << 8) + a[1];
int month = a[3];
int day = a[4];
if (a[0] == 4)
{
dt = DateTime(year, month, day);
return dt;
}
enforceEx!MYX(a[0] >= 7, "Supplied ubyte[] is not long enough");
int hour = a[5];
int minute = a[6];
int second = a[7];
dt = DateTime(year, month, day, hour, minute, second);
return dt;
}
/**
* Function to extract a DateTime from a text encoded column value.
*
* Text representations of a DateTime are as in 2011-11-11 12:20:02
*
* Params: a = A string representation of the time difference.
* Returns: A populated or default initialized std.datetime.DateTime struct.
*/
DateTime toDateTime(string s)
{
int year = parse!(ushort)(s);
munch(s, "-");
int month = parse!(ubyte)(s);
munch(s, "-");
int day = parse!(ubyte)(s);
munch(s, " ");
int hour = parse!(ubyte)(s);
munch(s, ":");
int minute = parse!(ubyte)(s);
munch(s, ":");
int second = parse!(ubyte)(s);
return DateTime(year, month, day, hour, minute, second);
}
/**
* Function to extract a DateTime from a ulong.
*
* This is used to support the TimeStamp struct.
*
* Params: x = A ulong e.g. 20111111122002UL.
* Returns: A populated std.datetime.DateTime struct.
*/
DateTime toDateTime(ulong x)
{
int second = cast(int) x%100;
x /= 100;
int minute = cast(int) x%100;
x /=100;
int hour = cast(int) x%100;
x /=100;
int day = cast(int) x%100;
x /=100;
int month = cast(int) x%100;
x /=100;
int year = cast(int) x%10000;
// 2038-01-19 03:14:07
enforceEx!MYX(year >= 1970 && year < 2039, "Date/time out of range for 2 bit timestamp");
enforceEx!MYX(year == 2038 && (month > 1 || day > 19 || hour > 3 || minute > 14 || second > 7),
"Date/time out of range for 2 bit timestamp");
return DateTime(year, month, day, hour, minute, second);
}
/**
* Function to pack a DateTime into a binary encoding for transmission to the server.
*
* Time/date structures are packed into a string of bytes with a leading length byte,
* and a minimal number of bytes to embody the data.
*
* Params: dt = std.datetime.DateTime struct.
* Returns: Packed ubyte[].
*/
ubyte[] pack(DateTime dt)
{
uint len = 1;
if (dt.year || dt.month || dt.day) len = 5;
if (dt.hour || dt.minute|| dt.second) len = 8;
ubyte[] rv;
rv.length = len;
if (len == 1)
{
rv[0] = 0;
return rv;
}
rv[1] = cast(ubyte) (dt.year & 0xff);
rv[2] = cast(ubyte) ((dt.year >> 8) & 0xff);
rv[3] = cast(ubyte) dt.month;
rv[4] = cast(ubyte) dt.day;
if (len == 5)
{
rv[0] = 4;
return rv;
}
rv[5] = cast(ubyte) dt.hour;
rv[6] = cast(ubyte) dt.minute;
rv[7] = cast(ubyte) dt.second;
rv[0] = 7;
return rv;
}
/**
* A D struct to stand for a TIMESTAMP
*
* It is assumed that insertion of TIMESTAMP values will not be common, since in general,
* such columns are used for recording the time of a row insertion, and are filled in
* automatically by the server. If you want to force a timestamp value in a prepared insert,
* set it into a timestamp struct as an unsigned long in the format YYYYMMDDHHMMSS
* and use that for the approriate parameter. When TIMESTAMPs are retrieved as part of
* a result set it will be as DateTime structs.
*/
struct Timestamp
{
ulong rep;
}
/**
* Server capability flags.
*
* During the connection handshake process, the server sends a uint of flags describing its
* capabilities
*/
enum SvrCapFlags: uint
{
SECURE_PWD = 1, /// Long passwords
FOUND_NOT_AFFECTED = 2, /// Report rows found rather than rows affected
ALL_COLUMN_FLAGS = 4, /// Send all column flags
WITH_DB = 8, /// Can take database as part of login
NO_SCHEMA = 16, /// Can disallow database name as part of column name database.table.column
CAN_COMPRESS = 32, /// Can compress packets
ODBC = 64, /// Can handle ODBC
LOCAL_FILES = 128, /// Can use LOAD DATA LOCAL
IGNORE_SPACE = 256, /// Can ignore spaces before '('
PROTOCOL41 = 512, /// Can use 4.1+ protocol
INTERACTIVE = 1024, /// Interactive client?
SSL = 2048, /// Can switch to SSL after handshake
IGNORE_SIGPIPE = 4096, /// Ignore sigpipes?
TRANSACTIONS = 8192, /// Transaction support
RESERVED = 16384,
SECURE_CONNECTION = 32768, /// 4.1+ authentication
MULTI_STATEMENTS = 65536, /// Multiple statement support
MULTI_RESULTS = 131072 /// Multiple result set support
}
// 000000001111011111111111
immutable uint defaultClientFlags =
SvrCapFlags.SECURE_PWD | SvrCapFlags.ALL_COLUMN_FLAGS |
SvrCapFlags.WITH_DB | SvrCapFlags.PROTOCOL41 |
SvrCapFlags.SECURE_CONNECTION;// | SvrCapFlags.MULTI_STATEMENTS |
//SvrCapFlags.MULTI_RESULTS;
/**
* Column type codes
*
* DEFAULT means infer parameter type or column type from D variable type.
*
*/
enum SQLType
{
DEFAULT = -1,
DECIMAL = 0x00,
TINY = 0x01,
SHORT = 0x02,
INT = 0x03,
FLOAT = 0x04,
DOUBLE = 0x05,
NULL = 0x06,
TIMESTAMP = 0x07,
LONGLONG = 0x08,
INT24 = 0x09,
DATE = 0x0a,
TIME = 0x0b,
DATETIME = 0x0c,
YEAR = 0x0d,
NEWDATE = 0x0e,
VARCHAR = 0x0f, // new in MySQL 5.0
BIT = 0x10, // new in MySQL 5.0
NEWDECIMAL = 0xf6, // new in MYSQL 5.0
ENUM = 0xf7,
SET = 0xf8,
TINYBLOB = 0xf9,
MEDIUMBLOB = 0xfa,
LONGBLOB = 0xfb,
BLOB = 0xfc,
VARSTRING = 0xfd,
STRING = 0xfe,
GEOMETRY = 0xff
}
/**
* Server refresh flags
*/
enum RefreshFlags
{
GRANT = 1,
LOG = 2,
TABLES = 4,
HOSTS = 8,
STATUS = 16,
THREADS = 32,
SLAVE = 64,
MASTER = 128
}
ushort getShort(ref ubyte* ubp)
{
ushort us;
us |= ubp[1];
us <<= 8;
us |= ubp[0];
ubp += 2;
return us;
}
uint getInt(ref ubyte* ubp)
{
uint rv = (ubp[3] << 24) + (ubp[2] << 16) + (ubp[1] << 8) + ubp[0];
ubp += 4;
return rv;
}
uint getInt24(ref ubyte* ubp)
{
uint rv = (ubp[2] << 16) + (ubp[1] << 8) + ubp[0];
ubp += 3;
return rv;
}
ulong parseLCB(ref ubyte* ubp, out bool nullFlag)
{
nullFlag = false;
if (*ubp < 251)
{
return cast(ulong) *ubp++;
}
ulong t;
switch (*ubp)
{
case 251:
nullFlag = true;
ubp++;
return 0;
case 252:
t |= ubp[2];
t <<= 8;
t |= ubp[1];
ubp += 3;
return t;
case 253:
t |= ubp[3];
t <<= 8;
t |= ubp[2];
t <<= 8;
t |= ubp[1];
ubp += 4;
return t;
case 254:
t |= ubp[8];
t <<= 8;
t |= ubp[7];
t <<= 8;
t |= ubp[6];
t <<= 8;
t |= ubp[5];
t <<= 8;
t |= ubp[4];
t <<= 8;
t |= ubp[3];
t <<= 8;
t |= ubp[2];
t <<= 8;
t |= ubp[1];
ubp += 9;
return t;
case 255:
default:
throw new MYX("The input value corresponds to an error packet.", __FILE__, __LINE__);
}
}
ubyte[] parseLCS(ref ubyte* ubp, out bool nullFlag)
{
ubyte[] mt;
ulong ul = parseLCB(ubp, nullFlag);
if (nullFlag)
return null;
if (ul == 0)
return mt;
enforceEx!MYX(ul <= uint.max, "Protocol Length Coded String is too long");
uint len = cast(uint) ul;
ubyte* t = ubp;
ubp += len;
return t[0..len].dup;
}
ubyte[] packLength(uint l, out uint offset)
{
ubyte[] t;
if (!l)
{
t.length = 1;
t[0] = 0;
return t;
}
if (l <= 250)
{
t.length = 1+l;
t[0] = cast(ubyte) l;
offset = 1;
return t;
}
else if (l <= 0xffff)
{
t.length = 3+l;
t[0] = 252;
t[1] = cast(ubyte) (l & 0xff);
t[2] = cast(ubyte) ((l >> 8) & 0xff);
offset = 3;
return t;
}
else if (l < 0xffffff)
{
t.length = 4+l;
t[0] = 253;
t[1] = cast(ubyte) (l & 0xff);
t[2] = cast(ubyte) ((l >> 8) & 0xff);
t[3] = cast(ubyte) ((l >> 16) & 0xff);
offset = 4;
return t;
}
else
{
ulong u = cast(ulong) l;
t.length = 9+l;
t[0] = 254;
t[1] = cast(ubyte) (u & 0xff);
t[2] = cast(ubyte) ((u >> 8) & 0xff);
t[3] = cast(ubyte) ((u >> 16) & 0xff);
t[4] = cast(ubyte) ((u >> 24) & 0xff);
t[5] = cast(ubyte) ((u >> 32) & 0xff);
t[6] = cast(ubyte) ((u >> 40) & 0xff);
t[7] = cast(ubyte) ((u >> 48) & 0xff);
t[8] = cast(ubyte) ((u >> 56) & 0xff);
offset = 9;
return t;
}
}
ubyte[] packLCS(void[] a)
{
uint offset;
ubyte[] t = packLength(a.length, offset);
if (t[0])
t[offset..$] = (cast(ubyte[]) a)[0..$];
return t;
}
unittest
{
bool isnull;
ubyte[] uba = [ 0xde, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x01, 0x00 ];
ubyte* ps = uba.ptr;
ubyte* ubp = uba.ptr;
ulong ul = parseLCB(ubp, isnull);
assert(ul == 0xde && !isnull && ubp == ps+1);
ubp = ps;
uba[0] = 251;
ul = parseLCB(ubp, isnull);
assert(ul == 0 && isnull && ubp == ps+1);
ubp = ps;
uba[0] = 252;
ul = parseLCB(ubp, isnull);
assert(ul == 0xbbcc && !isnull && ubp == ps+3);
ubp = ps;
uba[0] = 253;
ul = parseLCB(ubp, isnull);
assert(ul == 0xaabbcc && !isnull && ubp == ps+4);
ubp = ps;
uba[0] = 254;
ul = parseLCB(ubp, isnull);
assert(ul == 0x5566778899aabbcc && !isnull && ubp == ps+9);
ubyte[] buf;
buf.length = 0x2000200;
buf[] = '\x01';
buf[0] = 250;
buf[1] = '<';
buf[249] = '!';
buf[250] = '>';
ubp = buf.ptr;
ubyte[] x = parseLCS(ubp, isnull);
assert(x.length == 250 && x[0] == '<' && x[249] == '>');
buf[] = '\x01';
buf[0] = 252;
buf[1] = 0xff;
buf[2] = 0xff;
buf[3] = '<';
buf[0x10000] = '*';
buf[0x10001] = '>';
ubp = buf.ptr;
x = parseLCS(ubp, isnull);
assert(x.length == 0xffff && x[0] == '<' && x[0xfffe] == '>');
buf[] = '\x01';
buf[0] = 253;
buf[1] = 0xff;
buf[2] = 0xff;
buf[3] = 0xff;
buf[4] = '<';
buf[0x1000001] = '*';
buf[0x1000002] = '>';
ubp = buf.ptr;
x = parseLCS(ubp, isnull);
assert(x.length == 0xffffff && x[0] == '<' && x[0xfffffe] == '>');
buf[] = '\x01';
buf[0] = 254;
buf[1] = 0xff;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = 0x02;
buf[5] = 0x00;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = 0x00;
buf[9] = '<';
buf[0x2000106] = '!';
buf[0x2000107] = '>';
ubp = buf.ptr;
x = parseLCS(ubp, isnull);
assert(x.length == 0x20000ff && x[0] == '<' && x[0x20000fe] == '>');
}
/**
* A struct representing an OK or Error packet
*
* OK packets begin with a zero byte - Error packets with 0xff
*
*/
struct OKPacket
{
bool error;
bool nullFlag;
ulong affected;
ulong insertID;
ushort serverStatus;
ushort warnings;
char[5] sqlState;
char[] message;
this(ubyte* ubp, uint length)
{
ubyte* ps = ubp; // note packet start
ubyte* pe = ps+length;
if (*ubp)
{
error = true;
// it's not OK
enforceEx!MYX(*ubp == 255, "Malformed OK/Error packet");
ubp++;
enforceEx!MYX(ubp+2 < pe, "Malformed OK/Error packet");
serverStatus = getShort(ubp); // error code into server state
if (*ubp == cast(ubyte) '#')
{
//4.1+ error packet
ubp++;
enforceEx!MYX(ubp+5 < pe, "Malformed OK/Error packet");
sqlState[] = cast(char[]) ubp[0..5];
ubp += 5;
}
uint rem = pe-ubp;
if (rem)
{
message.length = rem;
message[] = cast(char[]) ubp[0..rem];
}
}
else
{
// It's OK - get supplied data
bool gash;
enforceEx!MYX(ubp+1 < pe, "Malformed OK/Error packet");
ubp++;
affected = parseLCB(ubp, gash);
enforceEx!MYX(ubp+1 < pe, "Malformed OK/Error packet");
insertID = parseLCB(ubp, gash);
enforceEx!MYX(ubp+2 < pe, "Malformed OK/Error packet");
serverStatus = getShort(ubp);
enforceEx!MYX(ubp+2 <= pe, "Malformed OK/Error packet");
warnings = getShort(ubp);
uint rem = pe-ubp;
if (rem)
{
message.length = rem;
message[] = cast(char[]) ubp[0..rem];
}
}
}
}
/**
* A struct representing a field (column) description packet
*
* These packets, one for each column are sent before the data of a result set,
* followed by an EOF packet.
*/
struct FieldDescription
{
private:
string _db;
string _table;
string _originalTable;
string _name;
string _originalName;
ushort _charSet;
uint _length;
uint _actualLength;
ushort _type;
ushort _flags;
ubyte _scale;
ulong _deflt;
uint chunkSize;
void delegate(ubyte[], bool) chunkDelegate;
public:
/**
* Construct a FieldDescription from the raw data packet
*
* Parameters: packet = The packet contents excluding the 4 byte packet header
*/
this(ubyte[] packet)
{
ubyte* sp = packet.ptr;
ubyte* ep = sp+packet.length;
ubyte* ubp = sp+4; // Skip catalog - it's always 'def'
bool isnull;
_db = cast(string) parseLCS(ubp, isnull);
_table = cast(string) parseLCS(ubp, isnull);
_originalTable = cast(string) parseLCS(ubp, isnull);
_name = cast(string) parseLCS(ubp, isnull);
_originalName = cast(string) parseLCS(ubp, isnull);
enforceEx!MYX(ep-ubp >= 13, "Malformed field specification packet");
ubp++; // one byte of filler here
_charSet = getShort(ubp);
_length = getInt(ubp);
_type = *ubp++;
_flags = getShort(ubp);
_scale = *ubp++;
ubp += 2; // 2 bytes filler here
if (ubp < ep)
{
ubp++; // one byte filler
_deflt = parseLCB(ubp, isnull);
}
}
/// Database name for column as string
@property string db() { return _db; }
/// Table name for column as string - this could be an alias as in 'from tablename as foo'
@property string table() { return _table; }
/// Real table name for column as string
@property string originalTable() { return _originalTable; }
/// Column name as string - this could be an alias
@property string name() { return _name; }
/// Real column name as string
@property string originalName() { return _originalName; }
/// The character set in force
@property ushort charSet() { return _charSet; }
/// The 'length' of the column as defined at table creation
@property uint length() { return _length; }
/// The type of the column hopefully (but not always) corresponding to enum SQLType. Only the low byte currently used
@property ushort type() { return _type; }
/// Column flags - unsigned, binary, null and so on
@property ushort flags() { return _flags; }
/// Precision for floating point values
@property ubyte scale() { return _scale; }
/// NotNull from flags
@property bool notNull() { return (_flags & 1) != 0; }
/// Unsigned from flags
@property bool unsigned() { return (_flags & 0x20) != 0; }
/// Binary from flags
@property bool binary() { return (_flags & 0x80) != 0; }
/// Is-enum from flags
@property bool isenum() { return (_flags & 0x100) != 0; }
/// Is-set (a SET column that is) from flags
@property bool isset() { return (_flags & 0x800) != 0; }
void show()
{
writefln("%s %d %x %016b", _name, _length, _type, _flags);
}
}
/**
* A struct representing a prepared statement parameter description packet
*
* These packets, one for each parameter are sent in response to the prepare command,
* followed by an EOF packet.
*
* Sadly it seems that this facility is only a stub. The correct number of packets is sent,
* but they contain no useful information and are all the same.
*/
struct ParamDescription
{
private:
ushort _type;
ushort _flags;
ubyte _scale;
uint _length;
public:
this(ubyte[] packet)
{
ubyte* ubp = packet.ptr;
_type = getShort(ubp);
_flags = getShort(ubp);
_scale = *ubp++;
_length = getInt(ubp);
}
@property uint length() { return _length; }
@property ushort type() { return _type; }
@property ushort flags() { return _flags; }
@property ubyte scale() { return _scale; }
@property bool notNull() { return (_flags & 1) != 0; }
@property bool unsigned() { return (_flags & 0x20) != 0; }
}
/**
* A struct representing an EOF packet
*
* an EOF packet is sent after each sequence of field description and parameter description
* packets, and after a sequence of result set row packets.
*
* These EOF packets contain a server status and a warning count.
*/
struct EOFPacket
{
private:
ushort _warnings;
ushort _serverStatus;
public:
/**
* Construct an EOFPacket struct from the raw data packet
*
* Parameters: packet = The packet contents excluding the 4 byte packet header
*/
this(ubyte[] packet)
{
ubyte* ubp = packet.ptr;
ubyte* ep = ubp+packet.length;
assert(*ubp == 0xfe && ep-ubp == 5);
_warnings = getShort(ubp);
_serverStatus = getShort(ubp);
}
/// Retrieve the warning count
@property ushort warnings() { return _warnings; }
/// Retrieve the server status
@property ushort serverStatus() { return _serverStatus; }
}
/**
* A struct representing the collation of a sequence of FieldDescription packets.
*
* This data gets filled in after a query (prepared or otherwise) that creates a result set completes.
* All the FD packets, and an EOF packet must be eaten before the row data packets can be read.
*/
struct ResultSetHeaders
{
private:
uint _fieldCount;
FieldDescription[] _fieldDescriptions;
string[] _fieldNames;
ushort _warnings;
public:
/**
* Construct a ResultSetHeaders struct from a sequence of FieldDescription packets and an EOF packet.
*
* Parameters:
* con = A Connection via which the packets are read
* fieldCount = the number of fields/columns generated by the query
*/
this(Connection con, uint fieldCount)
{
ubyte[] packet;
ubyte* ubp;
uint pl, n;
ubyte pn;
_fieldCount = fieldCount;
_fieldDescriptions.length = _fieldCount;
_fieldNames.length = _fieldCount;
foreach (uint i; 0.._fieldCount)