-
Notifications
You must be signed in to change notification settings - Fork 3
/
mysqld.d
4484 lines (4202 loc) · 145 KB
/
mysqld.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
/*
* Copyright (C) 2009 Steve Teale
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.<p>
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.<p>
* 3. This notice may not be removed or altered from any source distribution.
*/
/**
* A D wrapper for the MySQL C API (libmysqlclient/libmysql) - MySQLD. Source file mysqld.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 depends on myqsl.d, which is, except for three typedefs, a straight translation into D of the relevant
* MySQL C API header files
*
* It does not aim to replace the latter. There's lots of stuff in there that is probably used rather infrequently.
* If you need it, it is there for the calling.
*
* Neither does this version pretend to be comprehensive. At present, explicit support for MySQL stored procedures,
* transactions, and multi-statement operations in general is missing.
*
* Its primary objects are:<ul>
* <li>Connection: <ul><li>Connection to the server, and querying and setting of server parameters.</li></ul></li>
* <li>Command: Handling of SQL requests/queries/commands, with principal methods:
* <ul><li>execSQL() - plain old SQL query.</li>
* <li>execTuple() - get a set of values from a result row into a matching tuple of D variables.</li>
* <li>execPrepared() - execute a prepared statement.</li>
* <li>execResult() - execute a raw SQL statement and get a complete result set.</li>
* <li>execSequence() - execute a raw SQL statement and handle the rows one at a time.</li>
* <li>execPreparedResult() - execute a prepared statement and get a complete result set.</li>
* <li>execPreparedSequence() - execute a prepared statement and handle the rows one at a time.</li>
* <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></ul>
* <li>ResultSet: <ul><li>A random access range of rows, where a Row is an array of variant.</li></ul>
* <li>ResultSequence: <ul><li>An input range of similar rows.</li></ul></li></ul>
* It has currently only been compiled and unit tested on Ubuntu with D2.055, and the MySQL 5.5 client library.
* The required MySQL header files were translated the hard way, since we don't have the benefit of an htod ln
* a Linux environment. In the case of relatively complex library header file this is a potential source of
* errors, since the fact that such a translation compiles is not a guarantee that it is correct. However, it seems to
* survived all the unit tests I have tried so far.
*
* 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. It seems that the MySQL client library embeds a description
* of the Unix socket to be used for communication with 'localhost' that does not agree with the one used even by
* some older servers which adopted a different path ages ago. This is currently hard coded into Connection.
*
* There is another issue with std.variant. This can not currently cope with structs of the size used by MySQL to
* describe dates and times. The current version defines a modified variant - MyVariant that includes these types.
*/
module mysqld;
import mysql;
import errmsg;
import std.stdio;
import std.string;
import std.conv;
import std.c.string;
import std.range;
import std.variant;
// Note: One time struct is used by MySQL to handle time, date, datetime, and timestamp. This makes
// some operations in mysqld difficult or imposible, so mysql.d contains an alias and four typedefs as follows:
/*
struct st_mysql_time
{
...
}
alias st_mysql_time MYSQL_TIME;
typedef st_mysql_time MYSQL_DATE;
typedef st_mysql_time MYSQL_DATETIME;
typedef st_mysql_time MYSQL_TIMESTAMP;
typedef st_mysql_time MYSQL_TIMEDIFF;
*/
// 'Classic' MySQL delivers column values as strings. This function provides for their conversion to
// MYSQL_TIME
MYSQL_TIME toMyTime(string s, enum_field_types specific)
{
MYSQL_TIME ts;
void parseDate()
{
ts.year = parse!(uint)(s);
munch(s, "-");
ts.month = parse!(uint)(s);
munch(s, "-");
ts.day = parse!(uint)(s);
}
void parseTime()
{
ts.hour = parse!(uint)(s);
munch(s, ":");
ts.minute = parse!(uint)(s);
munch(s, ":");
ts.second = parse!(uint)(s);
if (s.length)
{
munch(s, ":.");
ts.second_part = parse!(uint)(s);
}
}
switch (specific)
{
case enum_field_types.MYSQL_TYPE_DATE:
parseDate();
break;
case enum_field_types.MYSQL_TYPE_TIME:
parseTime();
break;
case enum_field_types.MYSQL_TYPE_DATETIME:
case enum_field_types.MYSQL_TYPE_TIMESTAMP:
parseDate();
munch(s, " ");
parseTime();
break;
default:
break;
}
return ts;
}
alias VariantN!(maxSize!(creal, char[], void delegate(),
st_mysql_time, MYSQL_DATE, MYSQL_DATETIME, MYSQL_TIMESTAMP, MYSQL_TIMEDIFF)) MyVariant;
/**
* An exception type for MySQLD
*
* If the module encounters a problem it will throw an exception of type MySQLDException.
*/
class MySQLDException : Exception
{
uint _errnum;
char[] _errmsg;
/**
* An exception constructor from MySQL API error information.
*/
this(MYSQL* h, string file, int line)
{
_errnum = mysql_errno(h);
const char* err = mysql_error(h);
_errmsg.length = strlen(err);
strcpy(_errmsg.ptr, err);
super(format("error #: (%d): %s", _errnum, _errmsg), file, line);
}
/**
* An exception constructor from a string - used when MySQLD sees a problem.
*/
this(string msg, string file, int line)
{
super(format("MySQLD Exception: %s", msg), file, line);
}
}
/// MySQLDException AKA MyX
alias MySQLDException MyX;
/**
* A class to encapsulate struct MYSQL and its associated functions and to allow connection to a database.
*
* It is likely that at some future stage of development, Connection will be an implementation of an interface
* DBConnection (or similar).
*
* This is very thin wrapper stuff, but it is pre-requisite, so wrapped to some extent.
*/
// Connection was going to be a struct so that its destructor could be called promptly when it went out of scope.
// However there appears to be a compiler bug that prevents this from being done. An issue has been filed -
class Connection
{
private:
MYSQL _mysql;
MYSQL* _handle;
alias _handle CH;
MY_CHARSET_INFO _csi; // Later - header file hell
bool _auto, _inited;
static string[] parseConnectionString(string cs)
{
string[] rv;
rv.length = 4;
string[] a = split(cs, ";");
foreach (s; a)
{
string[] a2 = split(s, "=");
if (a2.length != 2)
throw new Exception("Bad connection string: " ~ cs);
string name = strip(a2[0]);
string val = strip(a2[1]);
val ~= "\0";
switch (name)
{
case "host":
rv[0] = val;
break;
case "user":
rv[1] = val;
break;
case "pwd":
rv[2] = val;
break;
case "db":
rv[3] = val;
break;
default:
throw new Exception("Bad connection string: " ~ cs);
break;
}
}
return rv;
}
// Initialize the MySQL environment
static this()
{
mysql_server_init(0, null, null);
}
~this()
{
// Deallocate malloc'd memory provided by mysql_init()
mysql_close(CH);
}
// Clean up the MySQL environment
static ~this()
{
mysql_server_end();
}
public:
/**
* Default constructor - Initialize Connection object
*/
this()
{
if (_inited)
return;
_handle = &_mysql;
mysql_init(&_mysql);
_inited = true;
}
/**
* Constructor to create an opened Connection
*
* Params:
* connectionString = <host=hostname/IP>;user=username;pwd=password;db=database>
*/
this(string connectionString)
{
this();
open(connectionString);
}
/**
* Get connection handle
*
* Returns:
* Pointer to a MYSQL struct - used by many mysql_xxx_xx() calls.
*/
MYSQL* handle() { return CH; }
/**
* Change user.
*
* Params:
* user = user name
* password = password
* databse = database to use (optional)
*/
void switchUser(string user, string password, string database = null)
{
mysql_change_user(CH, cast(char*) toStringz(user), cast(char*) toStringz(password),
((database is null)? null: cast(char*) toStringz(database)));
}
/**
* Get current character set info.
*
* Currently there is no other support for character set operations.
*/
MY_CHARSET_INFO* charSetInfo()
{
mysql_get_character_set_info(CH, &_csi);
return &_csi;
}
/**
* Get a string showing the current server statistics.
*
* This and the following methods in the Connection class are MySQL specific, though several of them
* might well be available from other databas implementations. A general purpose interface could
* provide an LCD set, and a methos to populate a dictionary with implementation-specific stuff.
*
* Returns:
* A string like "Uptime: 6646 Threads: 2 Questions: 282 Slow queries: 0 Opens: 42 Flush tables: 1
* Open tables: 1 Queries * per second avg: 0.42"
*/
string stats()
{
char[] buf;
const char* s = mysql_stat(CH);
return s[0..strlen(s)].idup;
}
/**
* Query for the current database
*
* Returns:
* The name of the current database.
*/
string currentDB()
{
if (mysql_real_query(CH, cast(char*) "select DATABASE()\0".ptr, 17))
throw new MyX(&_mysql, __FILE__, __LINE__);
MYSQL_RES* res = mysql_store_result(CH);
MYSQL_ROW row = mysql_fetch_row(res);
string s = to!string(row[0]);
mysql_free_result(res);
return s;
}
/**
* Get rid of a query result.
*
* Pulls any outstanding data from the server, then frees it. Use if you have executed a query but are only interested
* in the status.
*/
void skipResult()
{
MYSQL_RES* res = mysql_store_result(CH);
if (res is null)
return;
mysql_free_result(res);
}
/**
* Ping the server to make sure it is still there
*
* Returns:
* true if all is well.
*/
bool serverOK()
{
int rv = mysql_ping(CH);
return (rv == 0);
}
/**
* Get the client version as a string.
*
* Returns:
* Version string.
*/
string clientVersion()
{
const char* s = mysql_get_client_info();
return to!string(s);
}
/**
* Get the client version as a number
*
* Returns:
* Version number.
*/
uint clientVersionNumber() { return mysql_get_client_version(); }
/**
* Determine what host we are connected to.
*
* Returns:
* A sring like "localhost via TCP/IP".
*/
string hostInfo()
{
const char* s = mysql_get_host_info(CH);
return to!string(s);
}
/**
* Get the server version as a string.
*
* Returns:
* Version string.
*/
string serverVersion()
{
const char* s = mysql_get_server_info(CH);
return to!string(s);
}
/**
* Get the server version as a number
*
* Returns:
* Version number.
*/
uint serverVersionNumber() { return mysql_get_server_version(CH); }
/**
* Get the protocol that is in use
*
* Returns:
* ? not documented
*/
uint protocol() { return mysql_get_proto_info(CH); }
/**
* Open a connection to a specified host.
*
* There's an outstanding issue here. It seems like the current client library and my server disagree about
* the Unix socket to use for a localhost connection. At present I'm fudging the isue with a hard-coded
* socket path. I'll maybe resolve this when I get round to upgrading my server, but it could well be a client
* library issue, since the Unix socket actually used by the server is the 'new' version. The one the client
* library says it can't find is the 'old' version.
*
* Params:
* cs = A connection string like host=hostname/IP;user=username;pwd=password;db=database;
*/
void open(string cs)
{
string[] a = parseConnectionString(cs);
MYSQL* rv = mysql_real_connect(CH, cast(char*) a[0].ptr, cast(char*) a[1].ptr, cast(char*) a[2].ptr, cast(char*) a[3].ptr,
0, "/var/run/mysqld/mysqld.sock\0".ptr, CLIENT_MULTI_RESULTS | CLIENT_REMEMBER_OPTIONS);
if (rv is null)
throw new MyX(CH, __FILE__, __LINE__);
}
/**
* Open a connection to a specified host/database.
*
* (Similar socket reservation)
*
* Params:
* host = Host name or IP address
* user = User name
* pwd = password
* db = Database name
*/
void open(string host, string user,string pwd, string db)
{
MYSQL* rv = mysql_real_connect(CH, cast(char*) host.toStringz, cast(char*) user.toStringz,
cast(char*) pwd.toStringz, cast(char*) db.toStringz,
0, "/var/run/mysqld/mysqld.sock\0".ptr, CLIENT_MULTI_RESULTS | CLIENT_REMEMBER_OPTIONS);
if (rv is null)
throw new MyX(CH, __FILE__, __LINE__);
}
/**
* Close the connection
*/
void close() { mysql_close(CH); }
/**
* Determine the auto-commit mode
*
* Returns:
* true if auto-commit is on.
*/
bool autoCommit() { return _auto; }
/**
* Set the auto-commit mode.
*
* Params:
* mode = true/false to set the new mode.
* Returns:
* The previous mode.
*/
bool autoCommit(bool mode) { bool old = _auto; mysql_autocommit(CH, mode? 1: 0); return old; }
/**
* Set a SQL command string to be executed on connection.
*
* See the MySQL documentation for mysql_options() for details of options that can be set.
*
* Params:
* sql = A SQL string.
*/
void initialCommand(string sql) { mysql_options(CH, mysql_option.MYSQL_INIT_COMMAND, cast(void*) toStringz(sql)); }
/**
* Tell the client to compress its communications.
*/
void compress() { mysql_options(CH, mysql_option.MYSQL_OPT_COMPRESS, null); }
/**
* Modify the connection time-out period.
*
* Params:
* seconds = New value in seconds.
*/
void connectTimeout(uint seconds) { mysql_options(CH, mysql_option.MYSQL_OPT_CONNECT_TIMEOUT, &seconds); }
/**
* Modify the time-out period for reads.
*
* Params:
* seconds = New value in seconds.
*/
void readTimeout(uint seconds) { mysql_options(CH, mysql_option.MYSQL_OPT_READ_TIMEOUT, &seconds); }
/**
* Modify the time-out period for writes.
*
* Params:
* New value in seconds.
*/
void writeTimeout(uint seconds) { mysql_options(CH, mysql_option.MYSQL_OPT_WRITE_TIMEOUT, &seconds); }
/**
* Tell the client to use a named pipe.
*
* A Windows option - named pipe is default for Linux
*/
void useNamedPipe() { mysql_options(CH, mysql_option.MYSQL_OPT_NAMED_PIPE, null); }
/**
* Tell the client to attempt to reconnect if the connection is lost.
*
*/
void reconnect(bool tryReconnect) { mysql_options(CH, mysql_option.MYSQL_OPT_RECONNECT, &tryReconnect); }
/**
* Tell the server to report truncation if the buffer provided for an out parameter is not big enough.
* Default in MySQL 5 is yes.
*
* Params:
* repoert = bool yes/no.
*/
void reportTruncation(bool report) { mysql_options(CH, mysql_option.MYSQL_REPORT_DATA_TRUNCATION, &report); }
}
unittest
{
immutable string host = "localhost";
immutable string user = "user";
immutable string pwd = "password";
immutable string constr = "host=localhost;user=user;pwd=password;db=mysqld";
Connection c1 = new Connection();
c1.open(host, user, pwd, "mysqld");
assert(c1.serverOK);
c1.close();
c1 = new Connection();
c1.open(constr);
assert(c1.serverOK);
c1.close();
// This is installation specific - alter as required
c1 = new Connection(constr);
assert(c1.serverOK());
assert(c1.currentDB == "mysqld");
assert(c1.clientVersion[0..4] == "5.5.");
assert(c1.hostInfo == "Localhost via UNIX socket");
assert(c1.serverVersion[0..4] == "5.1.");
assert(c1.stats[0..8] == "Uptime: ");
c1.reportTruncation(true);
}
/*
string[] GetDataBases()
string[] GetSchemas()
IColumns GetColumns()
string [] GetStoredPredures()
*/
/**
* A struct to hold column metadata
*
*/
struct MySQLColumn
{
/// The database that the table having this column belongs to.
string schema;
/// The table that this column belongs to.
string table;
/// The name of the column.
string name;
/// Zero based index of the column within a table row.
uint index;
/// Is the default value NULL?
bool defaultNull;
/// The default value as a string if not NULL
string defaultValue;
/// Can the column value be set to NULL
bool nullable;
/// What type is the column - tinyint, char, varchar, blob, date etc
string type; // varchar tinyint etc
/// Capacity in characters, -1L if not applicable
long charsMax;
/// Capacity in bytes - same as chars if not a unicode table definition, -1L if not applicable.
long octetsMax;
/// Presentation information for numerics, -1L if not applicable.
short numericPrecision;
/// Scale information for numerics or NULL, -1L if not applicable.
short numericScale;
/// Character set, "<NULL>" if not applicable.
string charSet;
/// Collation, "<NULL>" if not applicable.
string collation;
/// More detail about the column type, e.g. "int(10) unsigned".
string colType;
/// Information about the column's key status, blank if none.
string key;
/// Extra information.
string extra;
/// Privileges for logged in user.
string privileges;
/// Any comment that was set at table definition time.
string comment;
}
/**
* A struct to hold stored function metadata
*
*/
struct MySQLProcedure
{
string db;
string name;
string type;
string definer;
MYSQL_DATETIME modified;
MYSQL_DATETIME created;
string securityType;
string comment;
string charSetClient;
string collationConnection;
string collationDB;
}
/**
* Facilities to recover meta-data from a connection
*
* It is important to bear in mind that the methods provided will only return the
* information that is available to the connected user. This may well be quite limited.
*/
struct MetaData
{
private:
Connection _con;
MYSQL_RES* _pres;
MySQLProcedure[] stored(bool procs)
{
string query = procs? "show procedure status where db='": "show function status where db='";
query ~= _con.currentDB ~ "'";
if (mysql_real_query(_con.CH, query.ptr, query.length))
throw new MyX(_con.CH, __FILE__, __LINE__);
_pres = mysql_store_result(_con.CH);
if (_pres is null)
throw new MyX(_con.CH, __FILE__, __LINE__);
MySQLProcedure[] pa;
uint n = cast(uint) _pres.row_count;
pa.length = n;
for (uint i = 0; i < n; i++)
{
MySQLProcedure foo;
MYSQL_ROW r = mysql_fetch_row(_pres);
for (int j = 0; j < 11; j++)
{
string t;
bool isNull = (r[j] is null);
if (!isNull)
t = to!string(r[j]);
switch (j)
{
case 0:
foo.db = t;
break;
case 1:
foo.name = t;
break;
case 2:
foo.type = t;
break;
case 3:
foo.definer = t;
break;
case 4:
foo.modified = cast(MYSQL_DATETIME) toMyTime(t, enum_field_types.MYSQL_TYPE_DATETIME);
break;
case 5:
foo.created = cast(MYSQL_DATETIME) toMyTime(t, enum_field_types.MYSQL_TYPE_DATETIME);
break;
case 6:
foo.securityType = t;
break;
case 7:
foo.comment = t;
break;
case 8:
foo.charSetClient = t;
break;
case 9:
foo.collationConnection = t;
break;
case 10:
foo.collationDB = t;
break;
default:
break;
}
}
pa[i] = foo;
}
return pa;
}
public:
this(Connection con)
{
_con = con;
}
/**
* List the available databases
*
* Note that if you have connected using the credentials of a user with limited permissions
* you may not get many results.
*
* Params:
* like = A simple wildcard expression with '%' or '_' terms for a limited selection, or null for all.
*/
string[] databases(string like = null)
{
string[] rv;
_pres = mysql_list_dbs(_con.CH, toStringz(like));
if (_pres is null)
throw new MyX(_con.CH, __FILE__, __LINE__);
for (;;)
{
MYSQL_ROW r = mysql_fetch_row(_pres);
if (r is null)
break;
rv ~= to!string(r[0]);
}
return rv;
}
/**
* List the tables in the current database
*
* Params:
* like = A simple wildcard expression with '%' or '_' terms for a limited selection, or null for all.
*/
string[] tables(string like = null)
{
string[] rv;
_pres = mysql_list_tables(_con.CH, toStringz(like));
if (_pres is null)
throw new MyX(_con.CH, __FILE__, __LINE__);
for (;;)
{
MYSQL_ROW r = mysql_fetch_row(_pres);
if (r is null)
break;
rv ~= to!string(r[0]);
}
return rv;
}
/**
* Get column metadata for a table in the current database
*
* Params:
* table = The table name
* Returns:
* An array of MySQLColumn structs
*/
MySQLColumn[] columns(string table)
{
string query = "select * from information_schema.COLUMNS where table_name='" ~ table ~ "'";
if (mysql_real_query(_con.CH, query.ptr, query.length))
throw new MyX(_con.CH, __FILE__, __LINE__);
_pres = mysql_store_result(_con.CH);
if (_pres is null)
throw new MyX(_con.CH, __FILE__, __LINE__);
MySQLColumn[] ca;
uint n = cast(uint) _pres.row_count;
ca.length = n;
for (uint i = 0; i < n; i++)
{
MySQLColumn col;
MYSQL_ROW r = mysql_fetch_row(_pres);
for (int j = 1; j < 19; j++)
{
string t;
bool isNull = (r[j] is null);
if (!isNull)
t = to!string(r[j]);
switch (j)
{
case 1:
col.schema = t;
break;
case 2:
col.table = t;
break;
case 3:
col.name = t;
break;
case 4:
col.index = to!uint(t)-1;
break;
case 5:
if (isNull)
col.defaultNull = true;
else
col.defaultValue = t;
break;
case 6:
if (t == "YES")
col.nullable = true;
break;
case 7:
col.type = t;
break;
case 8:
col.charsMax = isNull? -1L: cast(long) to!uint(t);
break;
case 9:
col.octetsMax = isNull? -1L: cast(long) to!uint(t);
break;
case 10:
col.numericPrecision = isNull? -1: to!short(t);
break;
case 11:
col.numericScale = isNull? -1: to!short(t);
break;
case 12:
col.charSet = isNull? "<NULL>": t;
break;
case 13:
col.collation = isNull? "<NULL>": t;
break;
case 14:
col.colType = t;
break;
case 15:
col.key = t;
break;
case 16:
col.extra = t;
break;
case 17:
col.privileges = t;
break;
case 18:
col.comment = t;
break;
default:
break;
}
}
ca[i] = col;
}
return ca;
}
/**
* Get list of stored functions in the current database, and their properties
*
*/
MySQLProcedure[] functions()
{
return stored(false);
}
/**
* Get list of stored procedures in the current database, and their properties
*
*/
MySQLProcedure[] procedures()
{
return stored(true);
}
}
unittest
{
immutable string constr = "host=localhost;user=user;pwd=password;db=mysqld";
Connection con = new Connection(constr);
MetaData md = MetaData(con);
string[] dbList = md.databases();
int count = 0;
foreach (string db; dbList)
{
if (db == "mysqld" || db == "information_schema")
count++;
}
assert(count == 2);
dbList = md.databases("%_schema");
assert(dbList.length == 1);
string[] tList = md.tables();
count = 0;
foreach (string t; tList)
{
if (t == "basetest" || t == "tblob")
count++;
}
assert(count == 2);
MySQLColumn[] ca = md.columns("basetest");
assert(ca[0].schema == "mysqld" && ca[0].table == "basetest" && ca[0].name == "boolcol" && ca[0].index == 0 &&
ca[0].defaultNull && ca[0].nullable && ca[0].type == "bit" && ca[0].charsMax == -1 && ca[0].octetsMax == -1 &&
ca[0].numericPrecision == 1 && ca[0].numericScale == -1 && ca[0].charSet == "<NULL>" && ca[0].collation == "<NULL>" &&
ca[0].colType == "bit(1)");
assert(ca[1].schema == "mysqld" && ca[1].table == "basetest" && ca[1].name == "bytecol" && ca[1].index == 1 &&
ca[1].defaultNull && ca[1].nullable && ca[1].type == "tinyint" && ca[1].charsMax == -1 && ca[1].octetsMax == -1 &&
ca[1].numericPrecision == 3 && ca[1].numericScale == 0 && ca[1].charSet == "<NULL>" && ca[1].collation == "<NULL>" &&
ca[1].colType == "tinyint(4)");
assert(ca[2].schema == "mysqld" && ca[2].table == "basetest" && ca[2].name == "ubytecol" && ca[2].index == 2 &&
ca[2].defaultNull && ca[2].nullable && ca[2].type == "tinyint" && ca[2].charsMax == -1 && ca[2].octetsMax == -1 &&
ca[2].numericPrecision == 3 && ca[2].numericScale == 0 && ca[2].charSet == "<NULL>" && ca[2].collation == "<NULL>" &&
ca[2].colType == "tinyint(3) unsigned");
assert(ca[3].schema == "mysqld" && ca[3].table == "basetest" && ca[3].name == "shortcol" && ca[3].index == 3 &&
ca[3].defaultNull && ca[3].nullable && ca[3].type == "smallint" && ca[3].charsMax == -1 && ca[3].octetsMax == -1 &&
ca[3].numericPrecision == 5 && ca[3].numericScale == 0 && ca[3].charSet == "<NULL>" && ca[3].collation == "<NULL>" &&
ca[3].colType == "smallint(6)");
assert(ca[4].schema == "mysqld" && ca[4].table == "basetest" && ca[4].name == "ushortcol" && ca[4].index == 4 &&
ca[4].defaultNull && ca[4].nullable && ca[4].type == "smallint" && ca[4].charsMax == -1 && ca[4].octetsMax == -1 &&
ca[4].numericPrecision == 5 && ca[4].numericScale == 0 && ca[4].charSet == "<NULL>" && ca[4].collation == "<NULL>" &&
ca[4].colType == "smallint(5) unsigned");
assert(ca[5].schema == "mysqld" && ca[5].table == "basetest" && ca[5].name == "intcol" && ca[5].index == 5 &&
ca[5].defaultNull && ca[5].nullable && ca[5].type == "int" && ca[5].charsMax == -1 && ca[5].octetsMax == -1 &&
ca[5].numericPrecision == 10 && ca[5].numericScale == 0 && ca[5].charSet == "<NULL>" && ca[5].collation == "<NULL>" &&
ca[5].colType == "int(11)");
assert(ca[6].schema == "mysqld" && ca[6].table == "basetest" && ca[6].name == "uintcol" && ca[6].index == 6 &&
ca[6].defaultNull && ca[6].nullable && ca[6].type == "int" && ca[6].charsMax == -1 && ca[6].octetsMax == -1 &&
ca[6].numericPrecision == 10 && ca[6].numericScale == 0 && ca[6].charSet == "<NULL>" && ca[6].collation == "<NULL>" &&
ca[6].colType == "int(10) unsigned");
assert(ca[7].schema == "mysqld" && ca[7].table == "basetest" && ca[7].name == "longcol" && ca[7].index == 7 &&
ca[7].defaultNull && ca[7].nullable && ca[7].type == "bigint" && ca[7].charsMax == -1 && ca[7].octetsMax == -1 &&
ca[7].numericPrecision == 19 && ca[7].numericScale == 0 && ca[7].charSet == "<NULL>" && ca[7].collation == "<NULL>" &&
ca[7].colType == "bigint(20)");
assert(ca[8].schema == "mysqld" && ca[8].table == "basetest" && ca[8].name == "ulongcol" && ca[8].index == 8 &&
ca[8].defaultNull && ca[8].nullable && ca[8].type == "bigint" && ca[8].charsMax == -1 && ca[8].octetsMax == -1 &&
ca[8].numericPrecision == 20 && ca[8].numericScale == 0 && ca[8].charSet == "<NULL>" && ca[8].collation == "<NULL>" &&
ca[8].colType == "bigint(20) unsigned");
assert(ca[9].schema == "mysqld" && ca[9].table == "basetest" && ca[9].name == "charscol" && ca[9].index == 9 &&
ca[9].defaultNull && ca[9].nullable && ca[9].type == "char" && ca[9].charsMax == 10 && ca[9].octetsMax == 10 &&
ca[9].numericPrecision == -1 && ca[9].numericScale == -1 && ca[9].charSet == "latin1" && ca[9].collation == "latin1_swedish_ci" &&
ca[9].colType == "char(10)");
assert(ca[10].schema == "mysqld" && ca[10].table == "basetest" && ca[10].name == "stringcol" && ca[10].index == 10 &&
ca[10].defaultNull && ca[10].nullable && ca[10].type == "varchar" && ca[10].charsMax == 50 && ca[10].octetsMax == 50 &&
ca[10].numericPrecision == -1 && ca[10].numericScale == -1 && ca[10].charSet == "latin1" && ca[10].collation == "latin1_swedish_ci" &&
ca[10].colType == "varchar(50)");
assert(ca[11].schema == "mysqld" && ca[11].table == "basetest" && ca[11].name == "bytescol" && ca[11].index == 11 &&
ca[11].defaultNull && ca[11].nullable && ca[11].type == "tinyblob" && ca[11].charsMax == 255 && ca[11].octetsMax == 255 &&
ca[11].numericPrecision == -1 && ca[11].numericScale == -1 && ca[11].charSet == "<NULL>" && ca[11].collation == "<NULL>" &&
ca[11].colType == "tinyblob");
assert(ca[12].schema == "mysqld" && ca[12].table == "basetest" && ca[12].name == "datecol" && ca[12].index == 12 &&
ca[12].defaultNull && ca[12].nullable && ca[12].type == "date" && ca[12].charsMax == -1 && ca[12].octetsMax == -1 &&
ca[12].numericPrecision == -1 && ca[12].numericScale == -1 && ca[12].charSet == "<NULL>" && ca[12].collation == "<NULL>" &&
ca[12].colType == "date");
assert(ca[13].schema == "mysqld" && ca[13].table == "basetest" && ca[13].name == "timecol" && ca[13].index == 13 &&
ca[13].defaultNull && ca[13].nullable && ca[13].type == "time" && ca[13].charsMax == -1 && ca[13].octetsMax == -1 &&
ca[13].numericPrecision == -1 && ca[13].numericScale == -1 && ca[13].charSet == "<NULL>" && ca[13].collation == "<NULL>" &&
ca[13].colType == "time");
assert(ca[14].schema == "mysqld" && ca[14].table == "basetest" && ca[14].name == "dtcol" && ca[14].index == 14 &&
ca[14].defaultNull && ca[14].nullable && ca[14].type == "datetime" && ca[14].charsMax == -1 && ca[14].octetsMax == -1 &&
ca[14].numericPrecision == -1 && ca[14].numericScale == -1 && ca[14].charSet == "<NULL>" && ca[14].collation == "<NULL>" &&
ca[14].colType == "datetime");
assert(ca[15].schema == "mysqld" && ca[15].table == "basetest" && ca[15].name == "doublecol" && ca[15].index == 15 &&
ca[15].defaultNull && ca[15].nullable && ca[15].type == "double" && ca[15].charsMax == -1 && ca[15].octetsMax == -1 &&
ca[15].numericPrecision == 22 && ca[15].numericScale == -1 && ca[15].charSet == "<NULL>" && ca[15].collation == "<NULL>" &&
ca[15].colType == "double");
assert(ca[16].schema == "mysqld" && ca[16].table == "basetest" && ca[16].name == "floatcol" && ca[16].index == 16 &&
ca[16].defaultNull && ca[16].nullable && ca[16].type == "float" && ca[16].charsMax == -1 && ca[16].octetsMax == -1 &&
ca[16].numericPrecision == 12 && ca[16].numericScale == -1 && ca[16].charSet == "<NULL>" && ca[16].collation == "<NULL>" &&
ca[16].colType == "float");
assert(ca[17].schema == "mysqld" && ca[17].table == "basetest" && ca[17].name == "nullcol" && ca[17].index == 17 &&