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
|
module Database.CDBI.Connection
(
SQLValue(..), SQLType(..), SQLResult, fromSQLResult, printSQLResults
, DBAction, DBError (..), DBErrorKind (..), Connection (..)
, runInTransaction, fail, ok, (>+), (>+=), executeRaw, execute, select
, executeMultipleTimes, getColumnNames, valueToString
, connectSQLite, disconnect, begin, commit, rollback, runWithDB
) where
import Char ( isDigit )
import Function ( on )
import Global ( Global, GlobalSpec(..), global, readGlobal, writeGlobal )
import IOExts ( connectToCommand )
import IO ( Handle, hPutStrLn, hGetLine, hFlush, hClose, stderr )
import List ( insertBy, isInfixOf, isPrefixOf, tails )
import ReadShowTerm ( readsQTerm )
import ReadNumeric ( readInt )
import System ( system )
import Time
dbDebug :: Bool
dbDebug = False
type SQLResult a = Either DBError a
fromSQLResult :: SQLResult a -> a
fromSQLResult (Left err) = error $ "Database connection error: " ++ show err
fromSQLResult (Right val) = val
printSQLResults :: Show a => SQLResult [a] -> IO ()
printSQLResults (Left err) = putStrLn $ show err
printSQLResults (Right res) = mapIO_ print res
data DBError = DBError DBErrorKind String
deriving (Eq,Show)
data DBErrorKind
= TableDoesNotExist
| ParameterError
| ConstraintViolation
| SyntaxError
| NoLineError
| LockedDBError
| UnknownError
deriving (Eq,Show)
data SQLValue
= SQLString String
| SQLInt Int
| SQLFloat Float
| SQLChar Char
| SQLBool Bool
| SQLDate ClockTime
| SQLNull
deriving Show
data SQLType
= SQLTypeString
| SQLTypeInt
| SQLTypeFloat
| SQLTypeChar
| SQLTypeBool
| SQLTypeDate
type DBAction a = Connection -> IO (SQLResult a)
runInTransaction :: DBAction a -> DBAction a
runInTransaction act conn = do
begin conn
res <- act conn
case res of
Left _ -> rollback conn >> return res
Right _ -> commit conn >> return res
(>+=) :: DBAction a -> (a -> DBAction b) -> DBAction b
m >+= f = \conn -> do
v1 <- m conn
case v1 of
Right val -> f val conn
Left err -> return (Left err)
(>+) :: DBAction a -> DBAction b -> DBAction b
(>+) x y = x >+= (\_ -> y)
fail :: DBError -> DBAction a
fail err _ = return (Left err)
ok :: a -> DBAction a
ok val _ = return (Right val)
select :: String -> [SQLValue] -> [SQLType] -> DBAction [[SQLValue]]
select query values types conn =
(executeRaw query (valuesToString values) >+=
(\a _ -> return (convertValues a types))) conn
execute :: String -> [SQLValue] -> DBAction ()
execute query values conn =
(executeRaw query (valuesToString values) >+
(\_ -> return (Right ()))) conn
executeMultipleTimes :: String -> [[SQLValue]] -> DBAction ()
executeMultipleTimes query values conn = do
result <- foldl (\res row -> (res >>= \x -> case x of
Right _ -> execute query row conn
error -> return error))
(return (Right ()))
values
return result
data Connection = SQLiteConnection Handle
connectSQLite :: String -> IO Connection
connectSQLite db = do
exsqlite3 <- system "which sqlite3 > /dev/null"
when (exsqlite3>0) $
error "Database interface `sqlite3' not found. Please install package `sqlite3'!"
h <- connectToCommand $ "sqlite3 " ++ db
hPutAndFlush h ".mode line"
hPutAndFlush h ".log stdout"
return $ SQLiteConnection h
disconnect :: Connection -> IO ()
disconnect (SQLiteConnection h) = hClose h
hPutAndFlush :: Handle -> String -> IO ()
hPutAndFlush h s = do
when dbDebug $ hPutStrLn stderr ("DB>>> " ++ s)
hPutStrLn h s >> hFlush h
writeConnection :: String -> Connection -> IO ()
writeConnection str (SQLiteConnection h) = hPutAndFlush h str
readRawConnection :: Connection -> IO String
readRawConnection (SQLiteConnection h) =
if dbDebug
then do inp <- hGetLine h
hPutStrLn stderr ("DB<<< " ++ inp)
return inp
else hGetLine h
begin :: Connection -> IO ()
begin conn@(SQLiteConnection _) = writeConnection "begin;" conn
commit :: Connection -> IO ()
commit conn@(SQLiteConnection _) = writeConnection "commit;" conn
rollback :: Connection -> IO ()
rollback conn@(SQLiteConnection _) = writeConnection "rollback;" conn
runWithDB :: String -> (Connection -> IO a) -> IO a
runWithDB dbname dbaction = ensureSQLiteConnection dbname >>= dbaction
runWithDB' :: String -> (Connection -> IO a) -> IO a
runWithDB' dbname dbaction = do
conn <- connectSQLite dbname
result <- dbaction conn
disconnect conn
return result
executeRaw :: String -> [String] -> DBAction [[String]]
executeRaw query para conn = do
let queryInserted = (insertParams query para)
case queryInserted of
Left err -> return $ Left err
Right qu -> do
writeConnection qu conn
parseLines conn
getColumnNames :: String -> DBAction [String]
getColumnNames table conn@(SQLiteConnection _) = do
writeConnection ("pragma table_info(" ++ table ++ ");") conn
result <- parseLines conn
case result of
Left err -> return (Left err)
Right xs -> return (Right (map retrieveColumnNames xs))
where retrieveColumnNames :: [String] -> String
retrieveColumnNames (_:y:_) = y
parseLines :: DBAction [[String]]
parseLines conn@(SQLiteConnection _) = do
random <- getRandom
case random of
Left err -> fail err conn
Right val -> do
writeConnection ("select '" ++ val ++ "';") conn
parseLinesUntil val conn
getRandom :: IO (SQLResult String)
getRandom = do
conn <- ensureSQLiteConnection ""
writeConnection "select hex(randomblob(8));" conn
result <- readConnection conn
return result
insertParams :: String -> [String] -> SQLResult String
insertParams qu xs =
if (length xs == (countPlaceholder qu))
then Right (insertParams' qu xs)
else Left (DBError ParameterError
"Amount of placeholders not equal to length of placeholder-list")
where
insertParams' sql [] = sql
insertParams' sql params@(p:ps) = case sql of
"" -> ""
'\'':'?':'\'':cs->p ++ insertParams' cs ps
c:cs -> c : insertParams' cs params
countPlaceholder qu2 = case qu2 of
"" -> 0
'\'':'?':'\'':cs->1 + (countPlaceholder cs)
_:cs -> countPlaceholder cs
parseLinesUntil :: String -> DBAction [[String]]
parseLinesUntil stop conn@(SQLiteConnection _) = next
where
next = do
value <- readConnection conn
case value of
Left (DBError NoLineError "") -> do
rest <- next
case rest of
Left err -> fail err conn
Right xs -> ok ([]:xs) conn
Left err -> readRawConnection conn >> fail err conn
Right val
| val == "index" -> next
| val == stop -> ok [[]] conn
| otherwise -> do
rest <- next
case rest of
Left err -> fail err conn
Right ([]:xs) -> ok ([val]:xs) conn
Right ((x:ys):xs) -> ok ((val:(x:ys)):xs) conn
readConnection :: DBAction String
readConnection conn@(SQLiteConnection _) = do check `liftIO` readRawConnection conn
where
check :: String -> SQLResult String
check str | null str = Left (DBError NoLineError "")
| "Error" `isPrefixOf` str = Left (DBError (getErrorKindSQLite str) str)
| '=' `elem` str = Right (getValue str)
| "automatic index on" `isInfixOf` str = Right "index"
| otherwise
= Left (DBError (getErrorKindSQLite str) str)
getValue :: String -> String
getValue s =
if "case" `isInfixOf` s
then getCaseValue s
else
let taileq = tail (snd (break (== '=') s))
in if null taileq then "" else let (' ':val) = taileq
in val
where getCaseValue str = getValue (readTilEnd str)
readTilEnd rest = head (filter (\ls -> "end" `isPrefixOf` ls) (tails rest))
getErrorKindSQLite :: String -> DBErrorKind
getErrorKindSQLite str
| "Error: UNIQUE constraint" `isPrefixOf` str = ConstraintViolation
| "no such table" `isInfixOf` str = TableDoesNotExist
| "syntax error" `isInfixOf` str = SyntaxError
| "Error: database is locked" `isInfixOf` str = LockedDBError
| otherwise = UnknownError
valuesToString :: [SQLValue] -> [String]
valuesToString xs = map valueToString xs
valueToString :: SQLValue -> String
valueToString x = replaceEmptyString $
case x of
SQLString a -> "'" ++ doubleApostrophes a ++ "'"
SQLChar a -> "'" ++doubleApostrophes [a] ++ "'"
SQLNull -> "NULL"
SQLDate a -> "'" ++ show (toUTCTime a) ++ "'"
SQLInt a -> show a
SQLFloat a -> show a
SQLBool a -> "'" ++ show a ++ "'"
replaceEmptyString :: String -> String
replaceEmptyString str = case str of
"''" -> "NULL"
st -> st
convertValues :: [[String]] -> [SQLType] -> SQLResult [[SQLValue]]
convertValues (s:str) types =
if((length s) == (length types))
then Right (map (\x -> map convertValuesHelp (zip x types)) (s:str))
else if ((length s) == 0)
then Right []
else Left (DBError ParameterError "Number of returned Parameters and Types not equal")
convertValuesHelp :: (String,SQLType) -> SQLValue
convertValuesHelp ([], SQLTypeString) = SQLNull
convertValuesHelp ((s:str), SQLTypeString) = (SQLString (s:str))
convertValuesHelp (s, SQLTypeInt) =
case (readInt s) of
Just (a,_) -> (SQLInt a)
Nothing -> SQLNull
convertValuesHelp (s, SQLTypeFloat) =
if isFloat s
then case (readsQTerm s) of
[] -> SQLNull
((a,_):_) -> SQLFloat a
else SQLNull
convertValuesHelp (s, SQLTypeBool) =
case (readsQTerm s) of
[(True,[])] -> SQLBool True
[(False,[])] -> SQLBool False
_ -> SQLNull
convertValuesHelp (s, SQLTypeDate) =
case (readsQTerm s) of
[((CalendarTime a b c d e f g),[])] -> SQLDate (toClockTime (CalendarTime a b c d e f g))
_ -> SQLNull
convertValuesHelp ("", SQLTypeChar) = SQLNull
convertValuesHelp (s:_, SQLTypeChar) = SQLChar s
doubleApostrophes :: String -> String
doubleApostrophes (s:str) =
if s == '\''
then ("''" ++ (doubleApostrophes str))
else (s : (doubleApostrophes str))
doubleApostrophes "" = ""
isFloat :: String -> Bool
isFloat [a] = isDigit a
isFloat (a:b:_) = (isDigit a) || (isDigit b && a == '-')
isFloat [] = False
openDBConnections :: Global [(String,Connection)]
openDBConnections = global [] Temporary
ensureSQLiteConnection :: String -> IO Connection
ensureSQLiteConnection db = do
dbConnections <- readGlobal openDBConnections
maybe (addNewConnection dbConnections) return (lookup db dbConnections)
where
addNewConnection dbConnections = do
dbcon <- connectSQLite db
writeGlobal openDBConnections $
insertBy ((<=) `on` fst) (db,dbcon) dbConnections
return dbcon
withAllDBConnections :: (Connection -> IO _) -> IO ()
withAllDBConnections f = readGlobal openDBConnections >>= mapIO_ (f . snd)
closeDBConnections :: IO ()
closeDBConnections = do
withAllDBConnections disconnect
writeGlobal openDBConnections []
|