forked from IsNull/ahkDBA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBAExampleOOP.ahk
378 lines (275 loc) · 7.92 KB
/
DBAExampleOOP.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
#NoEnv
#Warn, LocalSameAsGlobal, Off
SetWorkingDir %A_ScriptDir%
#Include <DBA>
global initialSQL := "SELECT * FROM Test"
global databaseType := ""
global currentDB := null ; current db connection
connectionStrings := A_ScriptDir "\Test\TestDB.sqlite||Server=localhost;Port=3306;Database=test;Uid=root;Pwd=toor;|Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" A_ScriptDir "\Test\TestDB.mdb"
Gui, +LastFound +OwnDialogs
Gui, Margin, 10, 10
Gui, Add, Text, x10 w100 h20 0x200 , DB Connection,
Gui, Add, ComboBox, x+0 ym w400 vddDatabaseConnection, % connectionStrings
Gui, Add, DropDownList, yp xp+420 w100 vddDatabaseType, % ArrayToGuiString(DBA.DataBaseFactory.AvailableTypes, true)
Gui, Add, Button, gReConnect yp xp+140 w80, .connect
Gui, Add, Text, x10 yp+35 w100 h20 0x200 vTX, SQL statement:
Gui, Add, ComboBox, x+0 w520 vSQL Sort, %initialSQL%||
Gui, Add, Button, yp xp+560 w80 hp vRun gRunSQL Default, .run
Gui, Add, Text, xm h20 w100 0x200, Table name:
Gui, Add, GroupBox, xm w780 h330 , Results
Gui, Add, ListView, xp+10 yp+18 w760 h300 vResultsLV,
Gui, Add, Button, gTestRecordSetClick, [Test RecordSet]
Gui, Add, Button, gTestInsertClick, [Test Insert]
Gui, Add, Button, gTestBinaryBlobClick, [Test Insert Binary Blob]
Gui, Add, StatusBar,
Gui, Show, , sqlite test oop
return
ReConnect:
Gui, submit, NoHide
DoTestInserts := true
databaseType := ddDatabaseType
connectionString := ddDatabaseConnection
try {
currentDB := DBA.DataBaseFactory.OpenDataBase(databaseType, connectionString)
if(DoTestInserts)
{
try {
if(databaseType = "SQLite"){
CreateTestDataSQLite(currentDB)
}else if(databaseType = "mySQL"){
CreateTestDataMySQL(currentDB)
}
}catch e
MsgBox,16, Error, % "Failed to create Test Data.`n`n" ExceptionDetail(e)
}
} catch e
MsgBox,16, Error, % "Failed to create connection. Check your Connection string and DB Settings!`n`n" ExceptionDetail(e)
GoSub, RunSQL
return
TestRecordSetClick:
Gui, submit, NoHide
if(IsEnsureConnection())
{
TestRecordSet(currentDB, SQL)
}
return
TestBinaryBlobClick:
Gui, submit, NoHide
if(IsEnsureConnection())
{
TestBinaryBLob(currentDB)
}
return
TestInsertClick:
if(IsEnsureConnection())
{
try {
TestInsert(currentDB)
}catch e
MsgBox,16, Error, % "Test of Recordset Insert failed!`n`nException Detail:`n" e.What "`n" e.Message
}
return
GuiClose:
if(IsObject(currentDB))
currentDB.Close()
Exitapp
;=======================================================================================================================
; Execute SQL-Statement
;=======================================================================================================================
RunSQL:
GuiControlGet, SQL
RunSQL(SQL)
return
RunSQL(SQL){
if(IsObject(currentDB))
{
state := ""
if(Trim(SQL) == "")
{
SB_SetText("No SQL entered")
Return
}
try {
rs := currentDB.OpenRecordSet(SQL)
if(IsObject(rs))
ShowRecordSet("ResultsLV", rs)
} catch e {
MsgBox,16, Error, % "OpenRecordSet Failed.`n`n" ExceptionDetail(e) ;state := "!# " e.What " " e.Message
}
if(state != "")
SB_SetText(state)
}else {
MsgBox,16, Error, No Connection avaiable. Please connect to a db first!
}
}
IsEnsureConnection( dialogue=1 ){
connected := (currentDB != null)
if(dialogue && !connected){
MsgBox,64, No Connection, You must connect to a DB to use this command.
}
return connected
}
TestInsert(mydb){
;Table Layout: Name, Fname, Phone, Room
record := {}
record.Name := "Yutini_" RandomChars(5)
record.Fname := "Wayland"
record.Phone := "1337"
record.Room := "No idea for what this is good for"
mydb.Insert(record, "Test") ; insert a single record into table test
/*
* Test inserting multiple values
* this is normaly faster than calling Insert for each element individually
*/
records := new Collection()
record := {}
record.Name := "Hans_" RandomChars(5)
record.Fname := "Meier"
record.Phone := "93737337"
record.Room := "wtf is room!? :D"
record2 := {}
record2.Name := "Marta_" RandomChars(5)
record2.Fname := "Heilia"
record2.Phone := "1234111"
record2.Room := "Don't be that strange!"
records.Add(record)
records.Add(record2)
mydb.InsertMany(records, "Test")
RunSQL("SELECT * FROM Test")
}
TestBinaryBLob(db){
static imagePath := A_scriptdir "\Test\boom.png"
if(!IsObject(db))
throw Exception("ArgumentException: db must be a DBA DataBase Object")
imgBuffer := MemoryBuffer.CreateFromFile(imagePath)
MsgBox % imgBuffer.ToString()
record := {}
record.Name := "SuperTest"
record.Image := imgBuffer
db.Insert(record, "TestImage") ; Insert this record into Table 'ImageTest'
imgBuffer.Free()
TestReadBinaryBlobAndWriteToDisk(db)
}
TestReadBinaryBlobAndWriteToDisk(db){
static imagePath2 := A_scriptdir "\Test\boomFromDb.png"
FileDelete, % imagePath2
record := db.QueryRow("Select * from TestImage WHERE Name = 'SuperTest'")
if(IsObject(record))
{
/*
* All binary BLOBs are wrapped automatically into a MemoryBuffer.
* The record.Image is therefore an Instance of a MemoryBuffer
*/
; write the binary blob data into a new file
record.Image.WriteToFile(imagePath2) ; write the buffer into a file - we get a valid png again :)
run, % imagePath2
}else
MsgBox,16, no such record, cant find 'SuperTest' in TestImage
}
TestRecordSet(db, sQry){
rs := db.OpenRecordSet(sQry)
while(!rs.EOF){
name := rs["Name"]
phone := rs["Phone"]
MsgBox, % (4 | 0x40), Showing record Nr %A_Index%, %name% %phone%`n`n`nDo you want to display the next record?
IfMsgBox, No
break
rs.MoveNext()
}
rs.Close()
MsgBox done :)
}
/*
* Show all records in the recordSet in the given ListView
*/
ShowRecordSet( LVname, resultSet ){
GuiControl, -ReDraw, %LVname%
Gui, ListView, %LVname%
if(!is(resultSet, DBA.RecordSet))
throw Exception("RecordSet Object expected! resultSet was of type: " typeof(resultSet) ,-1)
; Delete existing data
LV_Delete()
Loop, % LV_GetCount("Column")
LV_DeleteCol(1)
; fetch new data
columns := resultSet.getColumnNames()
columnCount := columns.Count()
for each, colName in columns
LV_InsertCol(A_Index,"", colName)
while(!resultSet.EOF){
rowNum := LV_Add("", "")
Loop, % columnCount
LV_Modify(rowNum, "Col" . A_index, resultSet[A_index])
resultSet.MoveNext()
}
LV_ModifyCol()
GuiControl, +ReDraw, %LVname%
SB_SetText("Displaying " rowNum " Rows")
}
CreateTestDataSQLite(db){
try
{
SB_SetText("Create Test Data")
db.Query("CREATE TABLE Test (Name, Fname, Phone, Room, PRIMARY KEY(Name ASC, FName ASC));")
db.Query("CREATE TABLE TestImage (Name, Image BLOB, PRIMARY KEY(Name ASC));")
InsertTestData(db)
}catch{
;// ignore
}
}
CreateTestDataMySQL(db){
try
{
SB_SetText("Create Test Data")
createTableSQL =
(Ltrim
CREATE TABLE IF NOT EXISTS Test (
Name VARCHAR(250),
Fname VARCHAR(250),
Phone VARCHAR(250),
Room VARCHAR(250),
PRIMARY KEY (Name, Fname)
`)
)
db.Query(createTableSQL)
InsertTestData(db)
}catch e{
; // if there where already test data
; // we ignore the duplicate key exception.
}
}
InsertTestData(db)
{
db.BeginTransaction()
{
_SQL := "('Name#', 'Fname#', 'Phone#', 'Room#')"
sQry := "INSERT INTO Test (Name, Fname, Phone, Room)`nVALUES`n"
i := 1
Loop, 500 {
StringReplace, cSQL, _SQL, #, %i%, All
sQry .= cSQL ",`n"
i++
}
sQry := substr(sQry,1,StrLen(sQry)-2) ";"
if (!db.Query(sQry)) {
Msg := "ErrorLevel: " . ErrorLevel . "`n" . SQLite_LastError() "`n`n" sQry
FileAppend, %Msg%, sqliteTestQuery.log
throw Exception("Query failed: " Msg)
; MsgBox, 0, Query failed, %Msg%
}
}db.EndTransaction()
}
ArrayToGuiString(items , bSelectFirst){
str := ""
for each, item in items
str .= item "|" ((bSelectFirst && A_Index == 1) ? "|" : "")
return str
}
RandomChars(count, str=""){
loop % count
{
Random, asc, 0x61, 0x7A
str .= chr(asc)
}
return str
}