-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathInternal.hs
1343 lines (1200 loc) · 45.7 KB
/
Internal.hs
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
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ForeignFunctionInterface #-}
-- | ODBC database API.
--
-- WARNING: This API is meant as a base for more high-level APIs, such
-- as the one provided in "Database.ODBC.SQLServer". The commands here
-- are all vulerable to SQL injection attacks. See
-- <https://en.wikipedia.org/wiki/SQL_injection> for more information.
--
-- Don't use this module if you don't know what you're doing.
module Database.ODBC.Internal
( -- * Connect/disconnect
connect
, close
, withConnection
, Connection
-- * Executing queries
, exec
, query
, Value(..)
, Binary(..)
, Column(..)
-- * Streaming results
, stream
, Step(..)
-- * Parameters
, execWithParams
, queryWithParams
, streamWithParams
, Param(..)
-- * Exceptions
, ODBCException(..)
) where
import Control.Concurrent.Async
import Control.Concurrent.MVar
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.IO.Unlift
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Unsafe as S
import Data.Coerce
import Data.Data
import Data.Hashable
import Data.Int
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Foreign as T
import Data.Time
import Foreign hiding (void)
import Foreign.C
import GHC.Generics
--------------------------------------------------------------------------------
-- Public types
-- | Connection to a database. Use of this connection is
-- thread-safe. When garbage collected, the connection will be closed
-- if not done already.
newtype Connection = Connection
{connectionMVar :: MVar (Maybe (ForeignPtr EnvAndDbc))}
-- | A database exception. Any of the functions in this library may
-- throw this exception type.
data ODBCException
= UnsuccessfulReturnCode !String
!Int16
!String
-- ^ An ODBC operation failed with the given return code.
| AllocationReturnedNull !String
-- ^ Allocating an ODBC resource failed.
| UnknownDataType !String
!Int16
-- ^ An unsupported/unknown data type was returned from the ODBC
-- driver.
| DatabaseIsClosed !String
-- ^ You tried to use the database connection after it was closed.
| DatabaseAlreadyClosed
-- ^ You attempted to 'close' the database twice.
| NoTotalInformation !Int
-- ^ No total length information for column.
| DataRetrievalError !String
-- ^ There was a general error retrieving data. String will
-- contain the reason why.
deriving (Typeable, Show, Eq)
instance Exception ODBCException
-- | A value used for input/output with the database.
data Value
= TextValue !Text
-- ^ A Unicode text value. This maps to nvarchar in SQL
-- Server. Use this for text.
| BinaryValue !Binary
-- ^ Only a vector of bytes. Intended for binary data, not for
-- ASCII text. This maps to varbinary or binary in SQL Server.
| ByteStringValue !ByteString
-- ^ A vector of bytes. It might be binary, or a string, but we
-- don't know the encoding. It maps to @varchar@ in the database
-- in SQL Server.
--
-- DO NOT USE THIS TYPE IF YOU CAN AVOID IT: This type does not
-- have a reliable transmission via parameters, and therefore is
-- encoded within the query as @CHAR(x) + ...@ where x is a
-- character outside of alphanumeric characters.
--
-- If you must: Use 'Data.Text.Encoding.decodeUtf8' if the string
-- is UTF-8 encoded, or 'Data.Text.Encoding.decodeUtf16LE' if it
-- is UTF-16 encoded. For other encodings, see the Haskell
-- text-icu package. For raw binary, see 'BinaryValue'.
| BoolValue !Bool
-- ^ A simple boolean.
| DoubleValue !Double
-- ^ Floating point values that fit in a 'Double'.
| FloatValue !Float
-- ^ Floating point values that fit in a 'Float'.
| IntValue !Int
-- ^ Integer values that fit in an 'Int'.
| ByteValue !Word8
-- ^ Values that fit in one byte.
| DayValue !Day
-- ^ Date (year, month, day) values.
| TimeOfDayValue !TimeOfDay
-- ^ Time of day (hh, mm, ss + fractional) values.
| LocalTimeValue !LocalTime
-- ^ Local date and time.
| NullValue
-- ^ SQL null value.
deriving (Eq, Show, Typeable, Ord, Generic, Data)
instance NFData Value
instance Hashable Value where
hashWithSalt salt =
\case
TextValue x -> hashWithSalt salt x
ByteStringValue x -> hashWithSalt salt x
BinaryValue !(Binary b) -> hashWithSalt salt b
BoolValue x -> hashWithSalt salt x
DoubleValue x -> hashWithSalt salt x
FloatValue x -> hashWithSalt salt x
IntValue x -> hashWithSalt salt x
ByteValue x -> hashWithSalt salt x
-- TODO: faster versions of these?
DayValue x -> hashWithSalt salt (show x)
TimeOfDayValue !x -> hashWithSalt salt (show x)
LocalTimeValue x -> hashWithSalt salt (show x)
NullValue -> hashWithSalt salt ()
-- | A parameter to a query that corresponds to a ?.
--
-- Presently we only support variable sized values like text and byte
-- vectors.
--
-- @since 0.2.4
data Param
= TextParam !Text -- ^ See docs for 'TextValue'.
| BinaryParam !Binary -- ^ See docs for 'BinaryValue'.
deriving (Eq, Show, Typeable, Ord, Generic, Data)
instance NFData Param
-- | A simple newtype wrapper around the 'ByteString' type to use when
-- you want to mean the @binary@ type of SQL, and render to binary
-- literals e.g. @0xFFEF01@.
--
-- The 'ByteString' type is already mapped to the non-Unicode 'text'
-- type.
newtype Binary = Binary
{ unBinary :: ByteString
} deriving (Show, Eq, Ord, Data, Generic, Typeable, NFData)
-- | A step in the streaming process for the 'stream' function.
data Step a
= Stop !a -- ^ Stop with this value.
| Continue !a -- ^ Continue with this value.
deriving (Show)
--------------------------------------------------------------------------------
-- Internal types
-- | A column description.
data Column = Column
{ columnType :: !SQLSMALLINT
, columnSize :: !SQLULEN
, columnDigits :: !SQLSMALLINT
, columnNull :: !SQLSMALLINT
, columnName :: !Text
} deriving (Show)
--------------------------------------------------------------------------------
-- Exposed functions
-- | Connect using the given connection string.
connect ::
MonadIO m
=> Text -- ^ An ODBC connection string.
-> m Connection
-- ^ A connection to the database. You should call 'close' on it
-- when you're done. If you forget to, then the connection will only
-- be closed when there are no more references to the 'Connection'
-- value in your program, which might never happen. So take care.
-- Use e.g. 'bracket' from "Control.Exception" to do the open/close
-- pattern, which will handle exceptions.
connect string =
withBound
(do (ptr, envAndDbc) <-
uninterruptibleMask_
(do ptr <- assertNotNull "odbc_AllocEnvAndDbc" odbc_AllocEnvAndDbc
fmap (ptr, ) (newForeignPtr odbc_FreeEnvAndDbc (coerce ptr)))
-- Above: Allocate the environment.
-- Below: Try to connect to the database.
withCStringLen
(T.unpack string)
(\(wstring,len) ->
uninterruptibleMask_
(do assertSuccess
ptr
"odbc_SQLDriverConnect"
(withForeignPtr
envAndDbc
(\dbcPtr ->
odbc_SQLDriverConnect
dbcPtr
(coerce wstring)
(fromIntegral len)))
addForeignPtrFinalizer odbc_SQLDisconnect envAndDbc))
-- Below: Keep the environment and the database handle in an mvar.
mvar <- newMVar (Just envAndDbc)
pure (Connection mvar))
-- | Close the connection. Further use of the 'Connection' will throw
-- an exception. Double closes also throw an exception to avoid
-- architectural mistakes.
close ::
MonadIO m
=> Connection -- ^ A connection to the database.
-> m ()
close conn =
withBound
(do mstate <- modifyMVar (connectionMVar conn) (pure . (Nothing, ))
-- If an async exception comes after here, that's a pity
-- because we wanted to free the connection now. But with
-- regards to safety, the finalizers will take care of closing
-- the connection and the env.
maybe (throwIO DatabaseAlreadyClosed) finalizeForeignPtr mstate)
-- | Memory bracket around 'connect' and 'close'.
withConnection :: MonadUnliftIO m =>
Text -- ^ An ODBC connection string.
-> (Connection -> m a) -- ^ Program that uses the ODBC connection.
-> m a
withConnection str inner = withRunInIO $ \io ->
withBound $ bracket (connect str) close (\h -> io (inner h))
-- | Execute a statement on the database.
exec ::
MonadIO m
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL statement.
-> m ()
exec conn string = execWithParams conn string mempty
-- | Same as 'exec' but with parameters.
--
-- @since 0.2.4
execWithParams ::
MonadIO m
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL query with ? inside.
-> [Param] -- ^ Params matching the ? in the query string.
-> m ()
execWithParams conn string params =
withBound
(withHDBC
conn
"exec"
(\dbc -> withExecDirect dbc string params (fetchAllResults dbc)))
-- | Query and return a list of rows.
query ::
MonadIO m
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL query.
-> m [[(Column, Value)]]
-- ^ A strict list of rows. This list is not lazy, so if you are
-- retrieving a large data set, be aware that all of it will be
-- loaded into memory.
query conn string = queryWithParams conn string mempty
-- | Same as 'query' but with parameters.
--
-- @since 0.2.4
queryWithParams ::
MonadIO m
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL query with ? inside.
-> [Param] -- ^ Params matching the ? in the query string.
-> m [[(Column, Value)]]
-- ^ A strict list of rows. This list is not lazy, so if you are
-- retrieving a large data set, be aware that all of it will be
-- loaded into memory.
queryWithParams conn string params =
withBound
(withHDBC
conn
"query"
(\dbc -> withExecDirect dbc string params (fetchStatementRows dbc)))
-- | Stream results like a fold with the option to stop at any time.
stream ::
(MonadIO m, MonadUnliftIO m)
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL query.
-> (state -> [(Column, Value)] -> m (Step state))
-- ^ A stepping function that gets as input the current @state@ and
-- a row, returning either a new @state@ or a final @result@.
-> state
-- ^ A state that you can use for the computation. Strictly
-- evaluated each iteration.
-> m state
-- ^ Final result, produced by the stepper function.
stream conn string step state = streamWithParams conn string mempty step state
-- | Same as 'stream' but with parameters.
--
-- @since 0.2.4
streamWithParams ::
(MonadIO m, MonadUnliftIO m)
=> Connection -- ^ A connection to the database.
-> Text -- ^ SQL query with ? inside.
-> [Param] -- ^ Params matching the ? in the query string.
-> (state -> [(Column, Value)] -> m (Step state))
-- ^ A stepping function that gets as input the current @state@ and
-- a row, returning either a new @state@ or a final @result@.
-> state
-- ^ A state that you can use for the computation. Strictly
-- evaluated each iteration.
-> m state
-- ^ Final result, produced by the stepper function.
streamWithParams conn string params step state = do
unlift <- askUnliftIO
withBound
(withHDBC
conn
"stream"
(\dbc ->
withExecDirect
dbc
string
params
(fetchIterator dbc unlift step state)))
--------------------------------------------------------------------------------
-- Internal wrapper functions
-- | Thread-safely access the connection pointer.
withHDBC :: Connection -> String -> (Ptr EnvAndDbc -> IO a) -> IO a
withHDBC conn label f =
withMVar
(connectionMVar conn)
(\mfptr ->
case mfptr of
Nothing -> throwIO (DatabaseIsClosed label)
Just envAndDbc -> do
v <- withForeignPtr envAndDbc f
touchForeignPtr envAndDbc
pure v)
-- | Execute a query directly without preparation.
withExecDirect :: Ptr EnvAndDbc -> Text -> [Param] -> (forall s. SQLHSTMT s -> IO a) -> IO a
withExecDirect dbc string params cont =
withStmt
dbc
(withBindParameters
dbc
params
(\stmt -> do
void
(assertSuccessOrNoData
dbc
"odbc_SQLExecDirectW"
(T.useAsPtr
string
(\wstring len ->
odbc_SQLExecDirectW
dbc
stmt
(coerce wstring)
(fromIntegral len))))
cont stmt))
-- | Run the function with a statement.
withStmt :: Ptr EnvAndDbc -> (forall s. SQLHSTMT s -> IO a) -> IO a
withStmt hdbc cont =
bracket
(assertNotNull "odbc_SQLAllocStmt" (odbc_SQLAllocStmt hdbc))
odbc_SQLFreeStmt
cont
-- | Run an action in a bound thread. This is neccessary due to the
-- interaction with signals in ODBC and GHC's runtime.
withBound :: MonadIO m => IO a -> m a
withBound = liftIO . flip withAsyncBound wait
--------------------------------------------------------------------------------
-- Binding params
-- | With parameters bounded. The fold is needed because the malloc'd
-- lengths passed in as the last parameter to SQLBindParameter is used
-- after calling SQLBindParameter, otherwise we could've just had a
-- loop.
withBindParameters ::
Ptr EnvAndDbc -> [Param] -> (SQLHSTMT s -> IO a) -> (SQLHSTMT s -> IO a)
withBindParameters dbc ps cont =
foldr
(\(parameter_number, param) -> withBindParameter dbc parameter_number param)
cont
(zip [1 ..] ps)
-- | Bind a param to the statement, throwing on failure.
withBindParameter ::
Ptr EnvAndDbc
-> SQLUSMALLINT
-> Param
-> (SQLHSTMT s -> IO a)
-> SQLHSTMT s -> IO a
withBindParameter dbc parameter_number param cont statement_handle = go param
where
go =
\case
TextParam text ->
T.useAsPtr -- Pass as wide char UTF-16.
text
(\ptr len_in_chars ->
runBind
(coerce sql_c_wchar)
(coerce sql_wlongvarchar)
(fromIntegral len_in_chars) -- This is the length in chars.
(coerce ptr)
(fromIntegral len_in_chars * 2))
-- Note the doubling here for length as bytes, for UTF-16.
BinaryParam (Binary binary) ->
S.useAsCStringLen -- Pass as "raw binary".
binary
(\(ptr, len) ->
runBind
(coerce sql_c_binary)
sql_varbinary
sql_ss_length_unlimited -- Note the unlimited column size here.
(coerce ptr)
(fromIntegral len))
runBind value_type parameter_type column_size parameter_value_ptr buffer_length =
withMalloc
(\buffer_length_ptr -> do
poke buffer_length_ptr buffer_length
assertSuccess
dbc
"odbc_SQLBindParameter"
(odbc_SQLBindParameter
dbc
statement_handle
parameter_number
value_type
parameter_type
column_size
parameter_value_ptr
buffer_length
buffer_length_ptr)
cont statement_handle)
--------------------------------------------------------------------------------
-- Internal data retrieval functions
-- | Iterate over the rows in the statement.
fetchIterator ::
Ptr EnvAndDbc
-> UnliftIO m
-> (state -> [(Column, Value)] -> m (Step state))
-> state
-> SQLHSTMT s
-> IO state
fetchIterator dbc (UnliftIO runInIO) step state0 stmt = do
SQLSMALLINT cols <-
liftIO
(withMalloc
(\sizep -> do
assertSuccess
dbc
"odbc_SQLNumResultCols"
(odbc_SQLNumResultCols stmt sizep)
peek sizep))
types <- mapM (describeColumn dbc stmt) [1 .. cols]
let loop state = do
do retcode0 <- odbc_SQLFetch dbc stmt
if | retcode0 == sql_no_data ->
do retcode <- odbc_SQLMoreResults dbc stmt
if retcode == sql_success || retcode == sql_success_with_info
then loop state
else pure state
| retcode0 == sql_success || retcode0 == sql_success_with_info ->
do row <-
sequence
(zipWith (getData dbc stmt) [SQLUSMALLINT 1 ..] types)
!state' <- runInIO (step state row)
case state' of
Stop state'' -> pure state''
Continue state'' -> loop state''
| otherwise ->
throwIO
(UnsuccessfulReturnCode
"odbc_SQLFetch"
(coerce retcode0)
"Unexpected return code")
if cols > 0
then loop state0
else pure state0
-- | Fetch all results from possible multiple statements.
fetchAllResults :: Ptr EnvAndDbc -> SQLHSTMT s -> IO ()
fetchAllResults dbc stmt = do
retcode <-
assertSuccessOrNoData
dbc
"odbc_SQLMoreResults"
(odbc_SQLMoreResults dbc stmt)
when
(retcode == sql_success || retcode == sql_success_with_info)
(fetchAllResults dbc stmt)
-- | Fetch all rows from a statement.
fetchStatementRows :: Ptr EnvAndDbc -> SQLHSTMT s -> IO [[(Column,Value)]]
fetchStatementRows dbc stmt = do
SQLSMALLINT cols <-
withMalloc
(\sizep -> do
assertSuccess
dbc
"odbc_SQLNumResultCols"
(odbc_SQLNumResultCols stmt sizep)
peek sizep)
types <- mapM (describeColumn dbc stmt) [1 .. cols]
let loop rows = do
do retcode0 <- odbc_SQLFetch dbc stmt
if | retcode0 == sql_no_data ->
do retcode <- odbc_SQLMoreResults dbc stmt
if retcode == sql_success || retcode == sql_success_with_info
then loop rows
else pure (rows [])
| retcode0 == sql_success || retcode0 == sql_success_with_info ->
do fields <-
sequence
(zipWith (getData dbc stmt) [SQLUSMALLINT 1 ..] types)
loop (rows . (fields :))
| otherwise ->
throwIO
(UnsuccessfulReturnCode
"odbc_SQLFetch"
(coerce retcode0)
"Unexpected return code")
if cols > 0
then loop id
else pure []
-- | Describe the given column by its integer index.
describeColumn :: Ptr EnvAndDbc -> SQLHSTMT s -> Int16 -> IO Column
describeColumn dbPtr stmt i =
T.useAsPtr
(T.replicate 1000 (fromString "0"))
(\namep namelen ->
(withMalloc
(\namelenp ->
(withMalloc
(\typep ->
withMalloc
(\sizep ->
withMalloc
(\digitsp ->
withMalloc
(\nullp -> do
assertSuccess
dbPtr
"odbc_SQLDescribeColW"
(odbc_SQLDescribeColW
stmt
(SQLUSMALLINT (fromIntegral i))
(coerce namep)
(SQLSMALLINT (fromIntegral namelen))
namelenp
typep
sizep
digitsp
nullp)
typ <- peek typep
size <- peek sizep
digits <- peek digitsp
isnull <- peek nullp
namelen' <- peek namelenp
name <- T.fromPtr namep (fromIntegral namelen')
evaluate
Column
{ columnType = typ
, columnSize = size
, columnDigits = digits
, columnNull = isnull
, columnName = name
}))))))))
-- | Pull data for the given column.
getData :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLUSMALLINT -> Column -> IO (Column, Value)
getData dbc stmt i col = fmap (col, ) $
if | colType == sql_longvarchar -> getBytesData dbc stmt i
| colType == sql_varchar -> getBytesData dbc stmt i
| colType == sql_char -> getBytesData dbc stmt i
| colType == sql_wvarchar -> getTextData dbc stmt i
| colType == sql_wchar -> getTextData dbc stmt i
| colType == sql_wlongvarchar -> getTextData dbc stmt i
| colType == sql_binary -> getBinaryData dbc stmt i
| colType == sql_varbinary -> getBinaryData dbc stmt i
| colType == sql_bit ->
withMalloc
(\bitPtr -> do
mlen <- getTypedData dbc stmt sql_c_bit i (coerce bitPtr) (SQLLEN 1)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap (BoolValue . (/= (0 :: Word8))) (peek bitPtr))
| colType == sql_double ->
withMalloc
(\doublePtr -> do
mlen <-
getTypedData dbc stmt sql_c_double i (coerce doublePtr) (SQLLEN 8)
-- float is 8 bytes: https://technet.microsoft.com/en-us/library/ms172424(v=sql.110).aspx
case mlen of
Nothing -> pure NullValue
Just {} -> do
!d <- fmap DoubleValue (peek doublePtr)
pure d)
| colType == sql_float ->
withMalloc
(\floatPtr -> do
mlen <-
getTypedData dbc stmt sql_c_double i (coerce floatPtr) (SQLLEN 8)
-- SQLFLOAT is covered by SQL_C_DOUBLE: https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
-- Float is 8 bytes: https://technet.microsoft.com/en-us/library/ms172424(v=sql.110).aspx
case mlen of
Nothing -> pure NullValue
Just {} -> do
!d <- fmap DoubleValue (peek floatPtr)
pure d)
| colType == sql_real ->
withMalloc
(\floatPtr -> do
mlen <-
getTypedData dbc stmt sql_c_double i (coerce floatPtr) (SQLLEN 8)
-- SQLFLOAT is covered by SQL_C_DOUBLE: https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/c-data-types
-- Float is 8 bytes: https://technet.microsoft.com/en-us/library/ms172424(v=sql.110).aspx
case mlen of
Nothing -> pure NullValue
Just {} -> do
!d <-
fmap
(FloatValue . (realToFrac :: Double -> Float))
(peek floatPtr)
pure d)
| colType == sql_numeric || colType == sql_decimal ->
withMalloc
(\floatPtr -> do
mlen <-
getTypedData dbc stmt sql_c_double i (coerce floatPtr) (SQLLEN 8)
-- NUMERIC/DECIMAL can be read as FLOAT
-- Float is 8 bytes: https://technet.microsoft.com/en-us/library/ms172424(v=sql.110).aspx
case mlen of
Nothing -> pure NullValue
Just {} -> do
!d <- fmap DoubleValue (peek floatPtr)
pure d)
| colType == sql_integer ->
withMalloc
(\intPtr -> do
mlen <-
getTypedData dbc stmt sql_c_long i (coerce intPtr) (SQLLEN 4)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
(IntValue . fromIntegral)
(peek (intPtr :: Ptr Int32)))
| colType == sql_bigint ->
withMalloc
(\intPtr -> do
mlen <-
getTypedData dbc stmt sql_c_bigint i (coerce intPtr) (SQLLEN 8)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
(IntValue . fromIntegral)
(peek (intPtr :: Ptr Int64)))
| colType == sql_smallint ->
withMalloc
(\intPtr -> do
mlen <-
getTypedData dbc stmt sql_c_short i (coerce intPtr) (SQLLEN 2)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
(IntValue . fromIntegral)
(peek (intPtr :: Ptr Int16)))
| colType == sql_tinyint ->
withMalloc
(\intPtr -> do
mlen <-
getTypedData dbc stmt sql_c_short i (coerce intPtr) (SQLLEN 1)
case mlen of
Nothing -> pure NullValue
Just {} -> fmap ByteValue (peek (intPtr :: Ptr Word8)))
| colType == sql_type_date ->
withMallocBytes
3
(\datePtr -> do
mlen <-
getTypedData dbc stmt sql_c_date i (coerce datePtr) (SQLLEN 3)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
DayValue
(fromGregorian <$>
(fmap fromIntegral (odbc_DATE_STRUCT_year datePtr)) <*>
(fmap fromIntegral (odbc_DATE_STRUCT_month datePtr)) <*>
(fmap fromIntegral (odbc_DATE_STRUCT_day datePtr))))
| colType == sql_ss_time2 ->
withCallocBytes
12 -- This struct is padded to 12 bytes on both 32-bit and 64-bit operating systems.
-- https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-date-time/data-type-support-for-odbc-date-and-time-improvements
(\datePtr -> do
mlen <-
getTypedData
dbc
stmt
sql_c_time
i
(coerce datePtr)
(SQLLEN 12)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
TimeOfDayValue
(TimeOfDay <$>
(fmap fromIntegral (odbc_TIME_STRUCT_hour datePtr)) <*>
(fmap fromIntegral (odbc_TIME_STRUCT_minute datePtr)) <*>
(fmap fromIntegral (odbc_TIME_STRUCT_second datePtr))))
| colType == sql_type_timestamp ->
withMallocBytes
16
(\timestampPtr -> do
mlen <-
getTypedData
dbc
stmt
sql_c_type_timestamp
i
(coerce timestampPtr)
(SQLLEN 16)
case mlen of
Nothing -> pure NullValue
Just {} ->
fmap
LocalTimeValue
(LocalTime <$>
(fromGregorian <$>
(fmap fromIntegral (odbc_TIMESTAMP_STRUCT_year timestampPtr)) <*>
(fmap
fromIntegral
(odbc_TIMESTAMP_STRUCT_month timestampPtr)) <*>
(fmap fromIntegral (odbc_TIMESTAMP_STRUCT_day timestampPtr))) <*>
(TimeOfDay <$>
(fmap fromIntegral (odbc_TIMESTAMP_STRUCT_hour timestampPtr)) <*>
(fmap
fromIntegral
(odbc_TIMESTAMP_STRUCT_minute timestampPtr)) <*>
((+) <$>
(fmap
fromIntegral
(odbc_TIMESTAMP_STRUCT_second timestampPtr)) <*>
(fmap
(\frac -> fromIntegral frac / 1000000000)
(odbc_TIMESTAMP_STRUCT_fraction timestampPtr))))))
| colType == sql_guid -> getGuid dbc stmt i
| otherwise ->
throwIO
(UnknownDataType
"getData"
(let SQLSMALLINT n = colType
in n))
where
colType = columnType col
-- | Get a GUID as a binary value.
getGuid :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLUSMALLINT -> IO Value
getGuid dbc stmt column = do
uninterruptibleMask_
(do bufferp <- callocBytes odbcGuidBytes
copiedBytes <-
getTypedData
dbc
stmt
sql_c_binary
column
(coerce bufferp)
(SQLLEN odbcGuidBytes)
case copiedBytes of
Nothing -> do
free bufferp
pure NullValue
Just {} -> do
!bs <- S.unsafePackMallocCStringLen (bufferp, odbcGuidBytes)
evaluate (BinaryValue (Binary bs)))
-- | Get the column's data as a vector of CHAR.
getBytesData :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLUSMALLINT -> IO Value
getBytesData dbc stmt column = do
mavailableBytes <- getSize dbc stmt sql_c_binary column
case mavailableBytes of
Just 0 -> pure (ByteStringValue mempty)
Just availableBytes ->
uninterruptibleMask_
(do let allocBytes = availableBytes + 1
bufferp <- callocBytes (fromIntegral allocBytes)
void
(getTypedData
dbc
stmt
sql_c_binary
column
(coerce bufferp)
(SQLLEN (fromIntegral allocBytes)))
bs <-
S.unsafePackMallocCStringLen
(bufferp, fromIntegral availableBytes)
evaluate (ByteStringValue bs))
Nothing -> pure NullValue
-- | Get the column's data as raw binary.
getBinaryData :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLUSMALLINT -> IO Value
getBinaryData dbc stmt column = do
mavailableBinary <- getSize dbc stmt sql_c_binary column
case mavailableBinary of
Just 0 -> pure (BinaryValue (Binary mempty))
Just availableBinary ->
uninterruptibleMask_
(do let allocBinary = availableBinary
bufferp <- callocBytes (fromIntegral allocBinary)
void
(getTypedData
dbc
stmt
sql_c_binary
column
(coerce bufferp)
(SQLLEN (fromIntegral allocBinary)))
bs <-
S.unsafePackMallocCStringLen
(bufferp, fromIntegral availableBinary)
evaluate (BinaryValue (Binary bs)))
Nothing -> pure NullValue
-- | Get the column's data as a text string.
getTextData :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLUSMALLINT -> IO Value
getTextData dbc stmt column = do
mavailableChars <- getSize dbc stmt sql_c_wchar column
case mavailableChars of
Just 0 -> pure (TextValue mempty)
Nothing -> pure NullValue
Just availableBytes -> do
let allocBytes = availableBytes + 2
withMallocBytes
(fromIntegral allocBytes)
(\bufferp -> do
void
(getTypedData
dbc
stmt
sql_c_wchar
column
(coerce bufferp)
(SQLLEN (fromIntegral allocBytes)))
t <- T.fromPtr bufferp (fromIntegral (div availableBytes 2))
let !v = TextValue t
pure v)
-- | Get some data into the given pointer.
getTypedData ::
Ptr EnvAndDbc
-> SQLHSTMT s
-> SQLCTYPE
-> SQLUSMALLINT
-> SQLPOINTER
-> SQLLEN
-> IO (Maybe Int64)
getTypedData dbc stmt ty column bufferp bufferlen =
withMalloc
(\copiedPtr -> do
assertSuccess
dbc
("getTypedData ty=" ++ show ty)
(odbc_SQLGetData dbc stmt column ty bufferp bufferlen copiedPtr)
copiedBytes <- peek copiedPtr
if copiedBytes == sql_null_data
then pure Nothing
else pure (Just (coerce copiedBytes :: Int64)))
-- | Get only the size of the data, no copying.
getSize :: Ptr EnvAndDbc -> SQLHSTMT s -> SQLCTYPE -> SQLUSMALLINT -> IO (Maybe Int64)
getSize dbc stmt ty column =
withMalloc
(\availablePtr -> do
withMalloc
(\bufferp ->
assertSuccess
dbc
"getSize"
(odbc_SQLGetData
dbc
stmt
column
ty
(coerce (bufferp :: Ptr CChar))
0
availablePtr))
availableBytes <- peek availablePtr
if availableBytes == sql_null_data
then pure Nothing
else if availableBytes == sql_no_total
then throwIO
(NoTotalInformation
(let SQLUSMALLINT i = column
in fromIntegral i))
else pure (Just (coerce availableBytes :: Int64)))
--------------------------------------------------------------------------------
-- Correctness checks
-- | Check that the RETCODE is successful.
assertNotNull :: (Coercible a (Ptr ())) => String -> IO a -> IO a
assertNotNull label m = do
val <- m
if coerce val == nullPtr
then throwIO (AllocationReturnedNull label)
else pure val
-- | Check that the RETCODE is successful.
assertSuccess :: Ptr EnvAndDbc -> String -> IO RETCODE -> IO ()
assertSuccess dbc label m = do
retcode <- m
if retcode == sql_success || retcode == sql_success_with_info
then pure ()
else do
ptr <- odbc_error dbc
string <-
if nullPtr == ptr
then pure "No error message given from ODBC."
else peekCString ptr
throwIO (UnsuccessfulReturnCode label (coerce retcode) string)
-- | Check that the RETCODE is successful or no data.
assertSuccessOrNoData :: Ptr EnvAndDbc -> String -> IO RETCODE -> IO RETCODE
assertSuccessOrNoData dbc label m = do
retcode <- m
if retcode == sql_success ||
retcode == sql_success_with_info || retcode == sql_no_data
then pure retcode
else do
ptr <- odbc_error dbc
string <-
if nullPtr == ptr
then pure ""
else peekCString ptr
throwIO (UnsuccessfulReturnCode label (coerce retcode) string)
--------------------------------------------------------------------------------
-- Foreign types