-
Notifications
You must be signed in to change notification settings - Fork 71
/
mySQL.ahk
431 lines (329 loc) · 11 KB
/
mySQL.ahk
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
/*============================================================
mysql.ahk
Provides a set of functions to connect and query a mysql database
Based upon the published lib of panofish
http://www.autohotkey.com/forum/topic67280.html
Offical Documentation of the C-API
http://dev.mysql.com/doc/refman/5.0/en/c.html
============================================================
*/
/*
Parses the given Connectionstring to a ConnectionData
An typical Connectionstring looks like:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Further Info: http://www.connectionstrings.com/mysql
*/
MySQL_CreateConnectionData(connectionString){
connectionData := {}
StringSplit, connstr, connectionString, `;
Loop, % connstr0
{
StringSplit, segment, connstr%a_index%, =
connectionData[segment1] := segment2
}
return connectionData
}
MySQL_StartUp(){
global MySQL_ExternDir
MySQL_ExternDir := A_WorkingDir
libDllpath := MySQL_DLLPath()
if(!FileExist(libDllpath))
{
msg := "MySQL Libaray not found!`n" libDllpath " (file missing)"
OutputDebug, %msg%
throw Exception(msg,-1)
}
hModule := DllCall("LoadLibrary", "Str", libDllpath)
if (hModule == 0)
{
msg := "LoadLibrary failed, can't load module:`n" libDllpath
OutputDebug, %msg%
throw Exception(msg, -1)
}else
return hModule
}
MySQL_DLLPath(forcedPath = "") {
static DLLPath := ""
static dllname := "libmySQL.dll"
if(DLLPath == ""){
; search the dll
prefix := (A_PtrSize == 8) ? "x64\" : ""
dllpath := prefix . dllname
if (FileExist(A_ScriptDir . "\" . dllpath))
DLLPath := A_ScriptDir . "\" . dllpath
else
DLLPath := A_ScriptDir . "\Lib\" . dllpath
}
if (forcedPath != "")
DLLPath := forcedPath
return DLLPath
}
/*****************************************************************
Connect to mysql database and return db handle
host:
user:
password:
database:
port: 3306(default)
******************************************************************
*/
MySQL_Connect(host, user, password, database, port = 3306){
db := DllCall("libmySQL.dll\mysql_init", "ptr", 0)
if (db = 0)
throw Exception("MySQL Error 445, Not enough memory to connect to MySQL", -1)
connection := DllCall("libmySQL.dll\mysql_real_connect"
, "ptr", db
, "AStr", host ; host name
, "AStr", user ; user name
, "AStr", password ; password
, "AStr", database ; database name
, "UInt", port ; port
, "UInt", 0 ; unix_socket
, "UInt", 0) ; client_flag
If (connection == 0)
throw Exception(BuildMySQLErrorStr(db, "Cannot connect to database"), -1)
;debugging only:
;MsgBox % "Ping database: " . MySQL_Ping(db) . "`nServer version: " . MySQL_GetVersion(db)
return db
}
MySQL_Close(db){
DllCall("libmySQL.dll\mysql_close", "ptr", db)
}
MySQL_GetVersion(db){
serverVersion := DllCall("libmySQL.dll\mysql_get_server_info", "ptr", db, "AStr")
return serverVersion
}
MySQL_Ping(db){
return DllCall("libmySQL.dll\mysql_ping", "ptr", db)
}
MySQL_GetLastErrorNo(db){
return DllCall("libmySQL.dll\mysql_errno", "ptr", db)
}
MySQL_GetLastErrorMsg(db){
return DllCall("libmySQL.dll\mysql_error", "ptr", db, "AStr")
}
/*
Retrieves a complete result set to the client.
*/
MySQL_Store_Result(db) {
return DllCall("libmySQL.dll\mysql_store_result", "ptr", db)
}
/*
Retrieves the resultset row-by-row
*/
MySQL_Use_Result(db) {
return DllCall("libmySQL.dll\mysql_use_result", "ptr", db)
}
/*
Returns a requestResult for the given query
*/
MySQL_Query(db, query){
return DllCall("libmySQL.dll\mysql_query", "ptr", db , "AStr", query)
}
MySQL_free_result(requestResult){
return DllCall("libmySQL.dll\mysql_free_result", "ptr", requestResult)
}
/*
Returns the number of columns in a result set.
*/
MySQL_num_fields(requestResult) {
Return DllCall("libmySQL.dll\mysql_num_fields", "ptr", requestResult)
}
/*
Returns the lengths of all columns in the current row.
*/
MySQL_fetch_lengths(requestResult) {
Return , DllCall("libmySQL.dll\mysql_fetch_lengths", "ptr", requestResult)
}
/*
Fetches the next row from the result set.
*/
MySQL_fetch_row(requestResult) {
Return , DllCall("libmySQL.dll\mysql_fetch_row", "ptr", requestResult)
}
/*
Fetches given Field
*/
Mysql_fetch_field_direct(requestResult, fieldnum) {
return DllCall("libmySQL.dll\mysql_fetch_field_direct", "ptr", requestResult, "Uint", fieldnum)
}
/*
Fetches the next field from the result set.
*/
Mysql_fetch_field(requestResult) {
return DllCall("libmySQL.dll\mysql_fetch_field", "ptr", requestResult)
}
/*
Fetches all fields of the resultSet
*/
MySQL_fetch_fields(requestResult){
global MySQL_Field
fields := []
fieldCount := MySQL_num_fields(requestResult)
Loop, % fieldCount
{
fptr := Mysql_fetch_field(requestResult)
fields[A_index] := new MySQL_Field(fptr)
}
return fields
}
/*
; mysql error handling
*/
BuildMySQLErrorStr(db, message, query="") {
errorCode := DllCall("libmySQL.dll\mysql_errno", "UInt", db)
errorStr := DllCall("libmySQL.dll\mysql_error", "UInt", db, "AStr")
Return, "MySQL Error: " message "Error " errorCode ": " errorStr "`n`n" query
}
;============================================================
; mysql get address
;============================================================
GetUIntAtAddress(_addr, _offset)
{
return NumGet(_addr+0,_offset * 4, "uint")
}
GetPtrAtAddress(_addr, _offset)
{
return NumGet(_addr+0,_offset * A_PtrSize, "ptr")
}
;============================================================
; internal: dump resultset from given Query to string
;============================================================
__MySQL_Query_Dump(_db, _query)
{
local resultString, result, requestResult, fieldCount
local row, lengths, length, fieldPointer, field
result := DllCall("libmySQL.dll\mysql_query", "UInt", _db , "AStr", _query)
If (result != 0)
throw new Exception(BuildMySQLErrorStr(_db, "dbQuery Fail", RegExReplace(_query , "\t", " ")), -1)
requestResult := MySql_Store_Result(_db)
if (requestResult = 0) { ; call must have been an insert or delete ... a select would return results to pass back
return
}
fieldCount := MySQL_num_fields(requestResult)
myfields := MySQL_fetch_fields(requestResult)
for each, fifi in myfields
{
MsgBox % "name: " fifi.Name() "`n org name: " fifi.OrgName() "`ntable: " fifi.Table() "`norg table: " fifi.OrgTable()
}
Loop
{
row := MySQL_fetch_row(requestResult)
if (!row)
break
; Get a pointer on a table of lengths (unsigned long)
lengths := MySQL_fetch_lengths(requestResult)
Loop %fieldCount%
{
length := GetUIntAtAddress(lengths, A_Index - 1)
fieldPointer := GetPtrAtAddress(row, A_Index - 1)
field := StrGet(fieldPointer, length, "CP0")
resultString := resultString . field
if (A_Index < fieldCount)
resultString := resultString . "|" ; seperator for fields
}
resultString := resultString . "`n" ; seperator for records
}
MySQL_free_result(requestResult)
resultString := RegExReplace(resultString , "`n$", "")
return resultString
}
;============================================================
; Escape mysql special characters
; This must be done to sql insert columns where the characters might contain special characters, such as user input fields
;
; Escape Sequence Character Represented by Sequence
; \' A single quote (“'”) character.
; \" A double quote (“"”) character.
; \n A newline (linefeed) character.
; \r A carriage return character.
; \t A tab character.
; \\ A backslash (“\”) character.
; \% A “%” character. Usually indicates a wildcard character
; \_ A “_” character. Usually indicates a wildcard character
; \b A backspace character.
;
; these 2 have not yet been included yet
; \Z ASCII 26 (Control+Z). Stands for END-OF-FILE on Windows
; \0 An ASCII NUL (0x00) character.
;
; example call:
; description := mysql_escape_string(description)
;============================================================
Mysql_escape_string(unescaped_string)
{
escaped_string := RegExReplace(unescaped_string, "\\", "\\") ; \
escaped_string := RegExReplace(escaped_string, "'", "\'") ; '
escaped_string := RegExReplace(escaped_string, "`t", "\t") ; \t
escaped_string := RegExReplace(escaped_string, "`n", "\n") ; \n
escaped_string := RegExReplace(escaped_string, "`r", "\r") ; \r
escaped_string := RegExReplace(escaped_string, "`b", "\b") ; \b
; these characters appear to insert fine in mysql
;escaped_string := RegExReplace(escaped_string, "%", "\%") ; %
;escaped_string := RegExReplace(escaped_string, "_", "\_") ; _
;escaped_string := RegExReplace(escaped_string, """", "\""") ; "
return escaped_string
}
/*
typedef struct st_mysql_field {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column (create length) */
unsigned long max_length; /* Max width for selected set */
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
unsigned int charsetnr; /* Character set */
enum enum_field_types type; /* Type of field. See mysql_com.h for types */
void *extension;
} MYSQL_FIELD;
*/
/*
'mysql_port is a long
'mysql_unix port is a long (pointer)
'sizeof(MYSQL_FIELD)=32
Public Type API_MYSQL_FIELD
name As Long
table As Long
def As Long
type As API_enum_field_types
length As Long
max_length As Long
flags As Long
decimals As Long
End Type
*/
class MySQL_Field
{
ptr := 0
__new(ptr){
this.ptr := ptr
}
Name(){
adr := GetPtrAtAddress(this.ptr, 0)
return StrGet(adr, 255, "CP0")
}
OrgName(){
adr := GetPtrAtAddress(this.ptr, 4)
return StrGet(adr, 255, "CP0")
}
Table(){
adr := GetPtrAtAddress(this.ptr, 8)
return StrGet(adr, 255, "CP0")
}
OrgTable(){
adr := GetPtrAtAddress(this.ptr, 12)
return StrGet(adr, 255, "CP0")
}
}