Copyright | Copyright (C) 2005-2011 John Goerzen |
---|---|
License | BSD3 |
Maintainer | John Goerzen <jgoerzen@complete.org> |
Stability | provisional |
Portability | portable |
Safe Haskell | Safe-Inferred |
Language | Haskell2010 |
Types for HDBC.
Please note: this module is intended for authors of database driver libraries
only. Authors of applications using HDBC should use HDBC
exclusively.
Written by John Goerzen, jgoerzen@complete.org
Synopsis
- class IConnection conn where
- disconnect :: conn -> IO ()
- commit :: conn -> IO ()
- rollback :: conn -> IO ()
- runRaw :: conn -> String -> IO ()
- run :: conn -> String -> [SqlValue] -> IO Integer
- prepare :: conn -> String -> IO Statement
- clone :: conn -> IO conn
- hdbcDriverName :: conn -> String
- hdbcClientVer :: conn -> String
- proxiedClientName :: conn -> String
- proxiedClientVer :: conn -> String
- dbServerVer :: conn -> String
- dbTransactionSupport :: conn -> Bool
- getTables :: conn -> IO [String]
- describeTable :: conn -> String -> IO [(String, SqlColDesc)]
- data Statement = Statement {
- execute :: [SqlValue] -> IO Integer
- executeRaw :: IO ()
- executeMany :: [[SqlValue]] -> IO ()
- finish :: IO ()
- fetchRow :: IO (Maybe [SqlValue])
- getColumnNames :: IO [String]
- originalQuery :: String
- describeResult :: IO [(String, SqlColDesc)]
- data SqlError = SqlError {
- seState :: String
- seNativeError :: Int
- seErrorMsg :: String
- nToSql :: Integral a => a -> SqlValue
- iToSql :: Int -> SqlValue
- posixToSql :: POSIXTime -> SqlValue
- fromSql :: Convertible SqlValue a => SqlValue -> a
- safeFromSql :: Convertible SqlValue a => SqlValue -> ConvertResult a
- toSql :: Convertible a SqlValue => a -> SqlValue
- data SqlValue
- = SqlString String
- | SqlByteString ByteString
- | SqlWord32 Word32
- | SqlWord64 Word64
- | SqlInt32 Int32
- | SqlInt64 Int64
- | SqlInteger Integer
- | SqlChar Char
- | SqlBool Bool
- | SqlDouble Double
- | SqlRational Rational
- | SqlLocalDate Day
- | SqlLocalTimeOfDay TimeOfDay
- | SqlZonedLocalTimeOfDay TimeOfDay TimeZone
- | SqlLocalTime LocalTime
- | SqlZonedTime ZonedTime
- | SqlUTCTime UTCTime
- | SqlDiffTime NominalDiffTime
- | SqlPOSIXTime POSIXTime
- | SqlEpochTime Integer
- | SqlTimeDiff Integer
- | SqlNull
- data ConnWrapper = forall conn.IConnection conn => ConnWrapper conn
- withWConn :: forall b. ConnWrapper -> (forall conn. IConnection conn => conn -> b) -> b
Documentation
class IConnection conn where Source #
Main database handle object.
An IConnection
object is created by specific functions in the module for an
individual database. That is, the connect function -- which creates
this object -- is not standardized through the HDBC interface.
A connection is closed by a call to disconnect
.
A call to commit
is required to make sure that your changes get committed
to the database. In other words, HDBC has no support for autocommit, which
we consider an outdated notion.
disconnect, commit, rollback, run, prepare, clone, hdbcDriverName, hdbcClientVer, proxiedClientName, proxiedClientVer, dbServerVer, dbTransactionSupport, getTables, describeTable
disconnect :: conn -> IO () Source #
Disconnect from the remote database.
You do not need to explicitly close an IConnection object, but you may do so if
you so desire. If you don't, the object will disconnect from the database
in a sane way when it is garbage-collected. However, a disconnection may
raise an error, so you are encouraged to explicitly call disconnect
. Also,
garbage collection may not run when the program terminates, and some databases
really like an explicit disconnect.
So, bottom line is, you're best off calling disconnect
directly, but the
world won't end if you forget.
This function discards any data not committed already. Database driver
implementators should explicitly call rollback
if their databases don't
do this automatically on disconnect.
Bad Things (TM) could happen if you call this while you have Statement
s
active. In more precise language, the results in such situations are undefined
and vary by database. So don't do it.
commit :: conn -> IO () Source #
Commit any pending data to the database.
Required to make any changes take effect.
rollback :: conn -> IO () Source #
runRaw :: conn -> String -> IO () Source #
Execute an SQL string, which may contain multiple queries. This is intended for situations where you need to run DML or DDL queries and aren't interested in results.
run :: conn -> String -> [SqlValue] -> IO Integer Source #
Execute a single SQL query. Returns the number
of rows modified (see execute
for details).
The second parameter is a list
of replacement values, if any.
prepare :: conn -> String -> IO Statement Source #
Prepares a statement for execution.
Question marks in the statement will be replaced by
positional parameters in a later call to execute
.
Please note that, depending on the database
and the driver, errors in your SQL may be raised
either here or by execute
. Make sure you
handle exceptions both places if necessary.
clone :: conn -> IO conn Source #
Create a new Connection
object, pointed at the same
server as this object is. This will generally establish
a separate physical connection.
When you wish to establish multiple connections to a single server, the correct way to do so is to establish the first connection with the driver-specific connection function, and then clone it for each additional connection.
This can be important when a database doesn't provide much thread support itself, and the HDBC driver module must serialize access to a particular database.
This can also be a handy utility function whenever you need a separate connection to whatever database you are connected to already.
hdbcDriverName :: conn -> String Source #
The name of the HDBC driver module for this connection. Ideally would be the same as the database name portion of the Cabal package name. For instance, "sqlite3" or "odbc". This is the layer that is bound most tightly to HDBC.
hdbcClientVer :: conn -> String Source #
The version of the C (or whatever) client library that the HDBC driver module is bound to. The meaning of this is driver-specific. For an ODBC or similar proxying driver, this should be the version of the ODBC library, not the eventual DB client driver.
proxiedClientName :: conn -> String Source #
In the case of a system such as ODBC, the name of
the database client/server in use, if available.
For others,
identical to hdbcDriverName
.
proxiedClientVer :: conn -> String Source #
In the case of a system such as ODBC, the version of
the database client in use, if available. For others,
identical to hdbcClientVer
. This is the next layer
out past the HDBC driver.
dbServerVer :: conn -> String Source #
The version of the database server, if available.
dbTransactionSupport :: conn -> Bool Source #
Whether or not the current database supports transactions.
If False, then commit
and rollback
should be expected
to raise errors.
MySQL is the only commonly-used database that is known to not support transactions entirely. Please see the MySQL notes in the ODBC driver for more information.
getTables :: conn -> IO [String] Source #
The names of all tables accessible by the current connection, excluding special meta-tables (system tables).
You should expect this to be returned in the same manner
as a result from fetchAllRows'
.
All results should be converted to lowercase for you before you see them.
describeTable :: conn -> String -> IO [(String, SqlColDesc)] Source #
Obtain information about the columns in a specific table. The String in the result set is the column name.
You should expect this to be returned in the same manner
as a result from fetchAllRows'
.
All results should be converted to lowercase for you before you see them.
Instances
IConnection ConnWrapper Source # | |
Defined in Database.HDBC.Types disconnect :: ConnWrapper -> IO () Source # commit :: ConnWrapper -> IO () Source # rollback :: ConnWrapper -> IO () Source # runRaw :: ConnWrapper -> String -> IO () Source # run :: ConnWrapper -> String -> [SqlValue] -> IO Integer Source # prepare :: ConnWrapper -> String -> IO Statement Source # clone :: ConnWrapper -> IO ConnWrapper Source # hdbcDriverName :: ConnWrapper -> String Source # hdbcClientVer :: ConnWrapper -> String Source # proxiedClientName :: ConnWrapper -> String Source # proxiedClientVer :: ConnWrapper -> String Source # dbServerVer :: ConnWrapper -> String Source # dbTransactionSupport :: ConnWrapper -> Bool Source # getTables :: ConnWrapper -> IO [String] Source # describeTable :: ConnWrapper -> String -> IO [(String, SqlColDesc)] Source # |
Statement | |
|
The main HDBC exception object. As much information as possible is passed from the database through to the application through this object.
Errors generated in the Haskell layer will have seNativeError set to -1.
SqlError | |
|
Instances
Eq SqlError Source # | |
Read SqlError Source # | |
Show SqlError Source # | |
Exception SqlError Source # | |
Defined in Database.HDBC.Statement toException :: SqlError -> SomeException # fromException :: SomeException -> Maybe SqlError # displayException :: SqlError -> String # |
nToSql :: Integral a => a -> SqlValue Source #
Converts any Integral type to a SqlValue
by using toInteger.
posixToSql :: POSIXTime -> SqlValue Source #
safeFromSql :: Convertible SqlValue a => SqlValue -> ConvertResult a Source #
Conversions to and from SqlValue
s and standard Haskell types.
This function converts from an SqlValue
to a Haskell value. Many people will use the simpler
fromSql
instead. This function is simply a restricted-type wrapper around
safeConvert
.
SqlValue
is the main type for expressing Haskell values to SQL databases.
INTRODUCTION TO SQLVALUE
This type is used to marshall Haskell data to and from database APIs. HDBC driver interfaces will do their best to use the most accurate and efficient way to send a particular value to the database server.
Values read back from the server are constructed with the most appropriate SqlValue
constructor. fromSql
or safeFromSql
can then be used to convert them into whatever type
is needed locally in Haskell.
Most people will use toSql
and fromSql
instead of manipulating
SqlValue
s directly.
EASY CONVERSIONS BETWEEN HASKELL TYPES
Conversions are powerful; for instance, you can call fromSql
on a SqlInt32
and get a String or a Double out of it. This class attempts to Do
The Right Thing whenever possible, and will raise an error when asked to
do something incorrect. In particular, when converting to any type
except a Maybe, SqlNull
as the input will cause an error to be raised.
Conversions are implemented in terms of the Data.Convertible module, part of the
convertible package. You can refer to its documentation, and import that module,
if you wish to parse the Left result from safeFromSql
yourself, or write your
own conversion instances.
Here are some notes about conversion:
- Fractions of a second are not preserved on time values
- There is no
safeToSql
becausetoSql
never fails.
See also toSql
, safeFromSql
, fromSql
, nToSql
, iToSql
, posixToSql
.
ERROR CONDITIONS
There may sometimes be an error during conversion. For instance, if you have a
SqlString
and are attempting to convert it to an Integer, but it doesn't parse as
an Integer, you will get an error. This will be indicated as an exception if using
fromSql
, or a Left result if using safeFromSql
.
SPECIAL NOTE ON POSIXTIME
Note that a NominalDiffTime
or POSIXTime
is converted to SqlDiffTime
by
toSql
. HDBC cannot differentiate between NominalDiffTime
and POSIXTime
since they are the same underlying type. You must construct SqlPOSIXTime
manually or via posixToSql
, or use SqlUTCTime
.
DETAILS ON SQL TYPES
HDBC database backends are expected to marshal date and time data back and forth using the appropriate representation for the underlying database engine. Databases such as PostgreSQL with builtin date and time types should see automatic conversion between these Haskell types to database types. Other databases will be presented with an integer or a string. Care should be taken to use the same type on the Haskell side as you use on the database side. For instance, if your database type lacks timezone information, you ought not to use ZonedTime, but instead LocalTime or UTCTime. Database type systems are not always as rich as Haskell. For instance, for data stored in a TIMESTAMP WITHOUT TIME ZONE column, HDBC may not be able to tell if it is intended as UTCTime or LocalTime data, and will happily convert it to both, upon your request. It is your responsibility to ensure that you treat timezone issues with due care.
This behavior also exists for other types. For instance, many databases do not have a Rational type, so they will just use the show function and store a Rational as a string.
The conversion between Haskell types and database types is complex, and generic code in HDBC or its backends cannot possibly accomodate every possible situation. In some cases, you may be best served by converting your Haskell type to a String, and passing that to the database.
UNICODE AND BYTESTRINGS
Beginning with HDBC v2.0, interactions with a database are presumed to occur in UTF-8.
To accomplish this, whenever a ByteString must be converted to or from a String,
the ByteString is assumed to be in UTF-8 encoding, and will be decoded or encoded
as appropriate. Database drivers will generally present text or string data they have
received from the database as a SqlValue holding a ByteString, which fromSql
will
automatically convert to a String, and thus automatically decode UTF-8, when
you need it. In the other direction, database drivers will generally convert
a SqlString
to a ByteString in UTF-8 encoding before passing it to the
database engine.
If you are handling some sort of binary data that is not in UTF-8, you can of course work with the ByteString directly, which will bypass any conversion.
Due to lack of support by database engines, lazy ByteStrings are not passed to database
drivers. When you use toSql
on a lazy ByteString, it will be converted to a strict
ByteString for storage. Similarly, fromSql
will convert a strict ByteString to
a lazy ByteString if you demand it.
EQUALITY OF SQLVALUE
Two SqlValues are considered to be equal if one of these hold. The first comparison that can be made is controlling; if none of these comparisons can be made, then they are not equal:
- Both are NULL
- Both represent the same type and the encapsulated values are considered equal by applying (==) to them
- The values of each, when converted to a string, are equal
STRING VERSIONS OF TIMES
Default string representations are given as comments below where such are non-obvious.
These are used for fromSql
when a String
is desired. They are also defaults for
representing data to SQL backends, though individual backends may override them
when a different format is demanded by the underlying database. Date and time formats
use ISO8601 date format, with HH:MM:SS added for time, and -HHMM added for timezone
offsets.
DEPRECATED CONSTRUCTORS
SqlEpochTime
and SqlTimeDiff
are no longer created automatically by any
toSql
or fromSql
functions or database backends. They may still be manually
constructed, but are
expected to be removed in a future version. Although these two constructures will
be removed, support for marshalling to and from the old System.Time data will be
maintained as long as System.Time is, simply using the newer data types for conversion.
SqlString String | |
SqlByteString ByteString | |
SqlWord32 Word32 | |
SqlWord64 Word64 | |
SqlInt32 Int32 | |
SqlInt64 Int64 | |
SqlInteger Integer | |
SqlChar Char | |
SqlBool Bool | |
SqlDouble Double | |
SqlRational Rational | |
SqlLocalDate Day | Local YYYY-MM-DD (no timezone). |
SqlLocalTimeOfDay TimeOfDay | Local HH:MM:SS (no timezone). |
SqlZonedLocalTimeOfDay TimeOfDay TimeZone | Local HH:MM:SS -HHMM. Converts to and from (TimeOfDay, TimeZone). |
SqlLocalTime LocalTime | Local YYYY-MM-DD HH:MM:SS (no timezone). |
SqlZonedTime ZonedTime | Local YYYY-MM-DD HH:MM:SS -HHMM. Considered equal if both convert to the same UTC time. |
SqlUTCTime UTCTime | UTC YYYY-MM-DD HH:MM:SS. |
SqlDiffTime NominalDiffTime | Calendar diff between seconds. Rendered as Integer when converted to String, but greater precision may be preserved for other types or to underlying database. |
SqlPOSIXTime POSIXTime | Time as seconds since midnight Jan 1 1970 UTC. Integer rendering as for |
SqlEpochTime Integer | DEPRECATED Representation of ClockTime or CalendarTime. Use SqlPOSIXTime instead. |
SqlTimeDiff Integer | DEPRECATED Representation of TimeDiff. Use SqlDiffTime instead. |
SqlNull | NULL in SQL or Nothing in Haskell. |
Instances
data ConnWrapper Source #
Sometimes, it is annoying to use typeclasses with Haskell's type system. In those situations, you can use a ConnWrapper. You can create one with:
let wrapped = ConnWrapper iconn
You can then use this directly, since a ConnWrapper is also an
IConnection
. However, you will not be able to use private database
functions on it.
Or, you can use withWConn
.
forall conn.IConnection conn => ConnWrapper conn |
Instances
IConnection ConnWrapper Source # | |
Defined in Database.HDBC.Types disconnect :: ConnWrapper -> IO () Source # commit :: ConnWrapper -> IO () Source # rollback :: ConnWrapper -> IO () Source # runRaw :: ConnWrapper -> String -> IO () Source # run :: ConnWrapper -> String -> [SqlValue] -> IO Integer Source # prepare :: ConnWrapper -> String -> IO Statement Source # clone :: ConnWrapper -> IO ConnWrapper Source # hdbcDriverName :: ConnWrapper -> String Source # hdbcClientVer :: ConnWrapper -> String Source # proxiedClientName :: ConnWrapper -> String Source # proxiedClientVer :: ConnWrapper -> String Source # dbServerVer :: ConnWrapper -> String Source # dbTransactionSupport :: ConnWrapper -> Bool Source # getTables :: ConnWrapper -> IO [String] Source # describeTable :: ConnWrapper -> String -> IO [(String, SqlColDesc)] Source # |
withWConn :: forall b. ConnWrapper -> (forall conn. IConnection conn => conn -> b) -> b Source #
Unwrap a ConnWrapper
and pass the embedded IConnection
to
a function. Example:
withWConn wrapped run $ "SELECT * from foo where bar = 1" []