{-# LINE 1 "Database/PostgreSQL/LibPQ.hsc" #-}-----------------------------------------------------------------------------{-# LINE 2 "Database/PostgreSQL/LibPQ.hsc" #-}-- |-- Module : Database.PostgreSQL.LibPQ-- Copyright : (c) 2010 Grant Monroe,-- (c) 2011 Leon P Smith-- License : BSD3---- Maintainer : leon@melding-monads.com-- Stability : experimental---- This is a binding to libpq: the C application programmer's-- interface to PostgreSQL. libpq is a set of library functions that-- allow client programs to pass queries to the PostgreSQL backend-- server and to receive the results of these queries.---- This is intended to be a very low-level interface to libpq. It-- provides memory management and a somewhat more consistent interface-- to error conditions. Application code should typically use a-- higher-level PostgreSQL binding.---- This interface is not safe, because libpq unfortunately conflates-- explicit disconnects with memory management. A use-after-free memory-- fault will result if a connection is used in any way after 'finish' is-- called. This will likely cause a segfault, or return an error if memory-- has not yet been reused. Other more bizarre behaviors are possible,-- though unlikely by chance. Higher-level bindings need to be aware of-- this issue and need to ensure that application code cannot cause the-- functions in this module to be called on an 'finish'ed connection.---- One possibility is to represent a connection in a higher-level interface-- as @MVar (Maybe Connection)@, using @Nothing@ to represent an explicitly-- disconnected state. This was done in an earlier incarnation of this-- library, however this was removed because a higher level binding is-- likely to use a similar construct to deal with other issues. Thus-- incorporating that in this module results in extra layers of indirection-- for relatively little functionality.-------------------------------------------------------------------------------{-# LANGUAGE ForeignFunctionInterface #-}{-# LANGUAGE EmptyDataDecls #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE BangPatterns #-}{-# LANGUAGE GeneralizedNewtypeDeriving #-}moduleDatabase.PostgreSQL.LibPQ(-- * Database Connection Control Functions-- $dbconnConnection,connectdb,connectStart,connectPoll,newNullConnection,isNullConnection--, conndefaults--, conninfoParse,reset,resetStart,resetPoll,PollingStatus(..),finish-- * Connection Status Functions-- $connstatus,db,user,pass,host,port,options,ConnStatus(..),status,TransactionStatus(..),transactionStatus,parameterStatus,protocolVersion,serverVersion,errorMessage,socket,backendPID,connectionNeedsPassword,connectionUsedPassword--, getssl-- * Command Execution Functions-- $commandexec,Result,exec,Format(..),Oid(..),invalidOid,execParams,prepare,execPrepared,describePrepared,describePortal,ExecStatus(..),resultStatus,resStatus,resultErrorMessage,FieldCode(..),resultErrorField,unsafeFreeResult-- * Retrieving Query Result Information-- $queryresultinfo,ntuples,nfields,Row(..),Column(..),toRow,toColumn,fname,fnumber,ftable,ftablecol,fformat,ftype,fmod,fsize,getvalue,getvalue',getisnull,getlength,nparams,paramtype,PrintOpt(..),defaultPrintOpt-- Retrieving Result Information for Other Commands-- $othercommands,cmdStatus,cmdTuples,oidValue-- * Escaping Strings for Inclusion in SQL Commands,escapeStringConn-- * Escaping Binary Strings for Inclusion in SQL Commands,escapeByteaConn,unescapeBytea-- * Asynchronous Command Processing-- $asynccommand,sendQuery,sendQueryParams,sendPrepare,sendQueryPrepared,sendDescribePrepared,sendDescribePortal,getResult,consumeInput,isBusy,setnonblocking,isnonblocking,FlushStatus(..),flush-- * Cancelling Queries in Progress-- $cancel,Cancel,getCancel,cancel-- * Asynchronous Notification-- $asyncnotification,Notify(..),notifies-- * Control Functions-- $control,clientEncoding,setClientEncoding,Verbosity(..),setErrorVerbosity-- * Large Objects-- $largeobjects,LoFd(..),loCreat,loCreate,loImport,loImportWithOid,loExport,loOpen,loWrite,loRead,loSeek,loTell,loTruncate,loClose,loUnlink)where{-# LINE 200 "Database/PostgreSQL/LibPQ.hsc" #-}{-# LINE 201 "Database/PostgreSQL/LibPQ.hsc" #-}importPreludehiding(print)importForeignimportForeign.C.TypesimportForeign.C.StringimportqualifiedForeign.ConcurrentasFCimportSystem.Posix.Types(Fd(..))importData.List(foldl')importSystem.IO(IOMode(..),SeekMode(..)){-# LINE 212 "Database/PostgreSQL/LibPQ.hsc" #-}importGHC.Conc(closeFdWith)-- Won't work with GHC 7.0.1{-# LINE 214 "Database/PostgreSQL/LibPQ.hsc" #-}importSystem.Posix.Types(CPid)importData.ByteString.Char8()importqualifiedData.ByteString.UnsafeasBimportqualifiedData.ByteString.InternalasB(fromForeignPtr,c_strlen)importqualifiedData.ByteStringasB-- $dbconn-- The following functions deal with making a connection to a-- PostgreSQL backend server. An application program can have several-- backend connections open at one time. (One reason to do that is to-- access more than one database.) Each connection is represented by a-- 'Connection', which is obtained from the function 'connectdb', or-- 'connectStart'. The 'status' function should be called to check-- whether a connection was successfully made before queries are sent-- via the connection object.-- | 'Connection' encapsulates a connection to the backend.newtypeConnection=Conn(ForeignPtrPGconn)derivingEqdataPGconn-- | Makes a new connection to the database server.---- This function opens a new database connection using the parameters-- taken from the string conninfo. Its nonblocking analogues are-- 'connectStart' and 'connectPoll'.---- The passed string can be empty to use all default parameters, or it-- can contain one or more parameter settings separated by-- whitespace. Each parameter setting is in the form keyword =-- value. Spaces around the equal sign are optional. To write an empty-- value or a value containing spaces, surround it with single quotes,-- e.g., keyword = 'a value'. Single quotes and backslashes within the-- value must be escaped with a backslash, i.e., \' and \\.connectdb::B.ByteString-- ^ Connection Info->IOConnectionconnectdbconninfo=doconnPtr<-B.useAsCStringconninfoc_PQconnectdbifconnPtr==nullPtrthenfail"libpq failed to allocate a PGconn structure"{-# LINE 257 "Database/PostgreSQL/LibPQ.hsc" #-}elseConn`fmap`FC.newForeignPtrconnPtr(pqfinishconnPtr){-# LINE 261 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Make a connection to the database server in a nonblocking manner.connectStart::B.ByteString-- ^ Connection Info->IOConnectionconnectStartconnStr=doconnPtr<-B.useAsCStringconnStrc_PQconnectStartifconnPtr==nullPtrthenfail"libpq failed to allocate a PGconn structure"{-# LINE 270 "Database/PostgreSQL/LibPQ.hsc" #-}elseConn`fmap`FC.newForeignPtrconnPtr(pqfinishconnPtr){-# LINE 274 "Database/PostgreSQL/LibPQ.hsc" #-}{-# LINE 276 "Database/PostgreSQL/LibPQ.hsc" #-}pqfinish::PtrPGconn->IO()pqfinishconn=domfd<-c_PQsocketconncasemfdof-1->-- This can happen if the connection is bad/lost-- This case may be worth investigating furtherc_PQfinishconnfd->closeFdWith(\_->c_PQfinishconn)(Fdfd){-# LINE 285 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Allocate a Null Connection, which all libpq functions-- should safely fail on.newNullConnection::IOConnectionnewNullConnection=Conn`fmap`newForeignPtr_nullPtr-- | Test if a connection is the Null Connection.isNullConnection::Connection->BoolisNullConnection(Connx)=unsafeForeignPtrToPtrx==nullPtr{-# INLINE isNullConnection #-}-- | If 'connectStart' succeeds, the next stage is to poll libpq so-- that it can proceed with the connection sequence. Use 'socket' to-- obtain the 'Fd' of the socket underlying the database-- connection. Loop thus: If 'connectPoll' last returned-- 'PollingReading', wait until the socket is ready to read (as-- indicated by select(), poll(), or similar system function). Then-- call 'connectPoll' again. Conversely, if 'connectPoll' last-- returned 'PollingWriting', wait until the socket is ready to write,-- then call 'connectPoll' again. If you have yet to call-- 'connectPoll', i.e., just after the call to 'connectStart', behave-- as if it last returned 'PollingWriting'. Continue this loop until-- 'connectPoll' returns 'PollingFailed', indicating the connection-- procedure has failed, or 'PollingOk', indicating the connection has-- been successfully made.connectPoll::Connection->IOPollingStatusconnectPoll=pollHelperc_PQconnectPoll-- PQconndefaults-- Returns the default connection options.-- PQconninfoOption *PQconndefaults(void);-- typedef struct-- {-- char *keyword; /* The keyword of the option */-- char *envvar; /* Fallback environment variable name */-- char *compiled; /* Fallback compiled in default value */-- char *val; /* Option's current value, or NULL */-- char *label; /* Label for field in connect dialog */-- char *dispchar; /* Indicates how to display this field-- in a connect dialog. Values are:-- "" Display entered value as is-- "*" Password field - hide value-- "D" Debug option - don't show by default */-- int dispsize; /* Field size in characters for dialog */-- } PQconninfoOption;-- Returns a connection options array. This can be used to determine all possible PQconnectdb options and their current default values. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer. The null pointer is returned if memory could not be allocated. Note that the current default values (val fields) will depend on environment variables and other context. Callers must treat the connection options data as read-only.-- After processing the options array, free it by passing it to PQconninfoFree. If this is not done, a small amount of memory is leaked for each call to PQconndefaults.-- PQconninfoParse-- Returns parsed connection options from the provided connection string.-- PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);-- Parses a connection string and returns the resulting options as an array; or returns NULL if there is a problem with the connection string. This can be used to determine the PQconnectdb options in the provided connection string. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer.-- Note that only options explicitly specified in the string will have values set in the result array; no defaults are inserted.-- If errmsg is not NULL, then *errmsg is set to NULL on success, else to a malloc'd error string explaining the problem. (It is also possible for *errmsg to be set to NULL even when NULL is returned; this indicates an out-of-memory situation.)-- After processing the options array, free it by passing it to PQconninfoFree. If this is not done, some memory is leaked for each call to PQconninfoParse. Conversely, if an error occurs and errmsg is not NULL, be sure to free the error string using PQfreemem.-- | Resets the communication channel to the server.---- This function will close the connection to the server and attempt-- to reestablish a new connection to the same server, using all the-- same parameters previously used. This might be useful for error-- recovery if a working connection is lost.reset::Connection->IO()resetconnection=withConnconnectionc_PQreset-- | Reset the communication channel to the server, in a nonblocking manner.resetStart::Connection->IOBoolresetStartconnection=enumFromConnconnectionc_PQresetStart-- | To initiate a connection reset, call 'resetStart'. If it returns-- 'False', the reset has failed. If it returns 'True', poll the reset-- using 'resetPoll' in exactly the same way as you would create the-- connection using 'connectPoll'.resetPoll::Connection->IOPollingStatusresetPoll=pollHelperc_PQresetPolldataPollingStatus=PollingFailed|PollingReading|PollingWriting|PollingOkderiving(Eq,Show)pollHelper::(PtrPGconn->IOCInt)->Connection->IOPollingStatuspollHelperpollerconnection=docode<-withConnconnectionpollercasecodeof(1)->returnPollingReading{-# LINE 390 "Database/PostgreSQL/LibPQ.hsc" #-}(3)->returnPollingOk{-# LINE 391 "Database/PostgreSQL/LibPQ.hsc" #-}(2)->returnPollingWriting{-# LINE 392 "Database/PostgreSQL/LibPQ.hsc" #-}(0)->returnPollingFailed{-# LINE 393 "Database/PostgreSQL/LibPQ.hsc" #-}_->error$"unexpected polling status "++showcode-- | Closes the connection to the server.---- Note that the 'Connection' must not be used again after 'finish'-- has been called.finish::Connection->IO()finish(Connfp)=dofinalizeForeignPtrfp-- $connstatus-- These functions can be used to interrogate the status of an-- existing database connection object.-- | Returns the database name of the connection.db::Connection->IO(MaybeB.ByteString)db=statusStringc_PQdb-- | Returns the user name of the connection.user::Connection->IO(MaybeB.ByteString)user=statusStringc_PQuser-- | Returns the password of the connection.pass::Connection->IO(MaybeB.ByteString)pass=statusStringc_PQpass-- | Returns the server host name of the connection.host::Connection->IO(MaybeB.ByteString)host=statusStringc_PQhost-- | Returns the port of the connection.port::Connection->IO(MaybeB.ByteString)port=statusStringc_PQport-- | Returns the command-line options passed in the connection request.options::Connection->IO(MaybeB.ByteString)options=statusStringc_PQoptions-- | Helper function that checks for nullPtrs and returns the empty-- string.statusString::(PtrPGconn->IOCString)->Connection->IO(MaybeB.ByteString)statusStringfconnection=withConnconnection$\ptr->docstr<-fptrifcstr==nullPtrthenreturnNothingelseJust`fmap`B.packCStringcstrdataConnStatus=ConnectionOk-- ^ The 'Connection' is ready.|ConnectionBad-- ^ The connection procedure has failed.|ConnectionStarted-- ^ Waiting for connection to be made.|ConnectionMade-- ^ Connection OK; waiting to send.|ConnectionAwaitingResponse-- ^ Waiting for a response from the server.|ConnectionAuthOk-- ^ Received authentication;-- waiting for backend start-up to-- finish.|ConnectionSetEnv-- ^ Negotiating environment-driven-- parameter settings.|ConnectionSSLStartup-- ^ Negotiating SSL encryption.deriving(Eq,Show)-- | Returns the status of the connection.---- The status can be one of a number of values. However, only two of-- these are seen outside of an asynchronous connection procedure:-- 'ConnectionOk' and 'ConnectionBad'. A good connection to the-- database has the status 'ConnectionOk'. A failed connection attempt-- is signaled by status 'ConnectionBad'. Ordinarily, an OK status-- will remain so until 'finish', but a communications failure might-- result in the status changing to 'ConnectionBad' prematurely. In-- that case the application could try to recover by calling 'reset'.---- See the entry for 'connectStart' and 'connectPoll' with regards to-- other status codes that might be seen.status::Connection->IOConnStatusstatusconnection=dostat<-withConnconnectionc_PQstatusreturn$casestatof(0)->ConnectionOk{-# LINE 494 "Database/PostgreSQL/LibPQ.hsc" #-}(1)->ConnectionBad{-# LINE 495 "Database/PostgreSQL/LibPQ.hsc" #-}(2)->ConnectionStarted{-# LINE 496 "Database/PostgreSQL/LibPQ.hsc" #-}(3)->ConnectionMade{-# LINE 497 "Database/PostgreSQL/LibPQ.hsc" #-}(4)->ConnectionAwaitingResponse{-# LINE 498 "Database/PostgreSQL/LibPQ.hsc" #-}(5)->ConnectionAuthOk{-# LINE 499 "Database/PostgreSQL/LibPQ.hsc" #-}(6)->ConnectionSetEnv{-# LINE 500 "Database/PostgreSQL/LibPQ.hsc" #-}(7)->ConnectionSSLStartup{-# LINE 501 "Database/PostgreSQL/LibPQ.hsc" #-}--(#const CONNECTION_NEEDED) -> ConnectionNeededc->error$"Unknown connection status "++showcdataTransactionStatus=TransIdle-- ^ currently idle|TransActive-- ^ a command is in progress|TransInTrans-- ^ idle, in a valid transaction block|TransInError-- ^ idle, in a failed transaction block|TransUnknown-- ^ the connection is bad-- | Returns the current in-transaction status of the server.---- 'TransActive' is reported only when a query has been sent to the-- server and not yet completed.transactionStatus::Connection->IOTransactionStatustransactionStatusconnection=dostat<-withConnconnectionc_PQtransactionStatusreturn$casestatof(0)->TransIdle{-# LINE 521 "Database/PostgreSQL/LibPQ.hsc" #-}(1)->TransActive{-# LINE 522 "Database/PostgreSQL/LibPQ.hsc" #-}(2)->TransInTrans{-# LINE 523 "Database/PostgreSQL/LibPQ.hsc" #-}(3)->TransInError{-# LINE 524 "Database/PostgreSQL/LibPQ.hsc" #-}(4)->TransUnknown{-# LINE 525 "Database/PostgreSQL/LibPQ.hsc" #-}c->error$"Unknown transaction status "++showc-- | Looks up a current parameter setting of the server.---- Certain parameter values are reported by the server automatically-- at connection startup or whenever their values-- change. 'parameterStatus' can be used to interrogate these-- settings. It returns the current value of a parameter if known, or-- 'Nothing' if the parameter is not known.parameterStatus::Connection->B.ByteString-- ^ paramName->IO(MaybeB.ByteString)parameterStatusconnectionparamName=withConnconnection$\connPtr->B.useAsCStringparamName$\paramNamePtr->docstr<-c_PQparameterStatusconnPtrparamNamePtrifcstr==nullPtrthenreturnNothingelseJust`fmap`B.packCStringcstr-- | Interrogates the frontend/backend protocol being used.---- Applications might wish to use this to determine whether certain-- features are supported. Currently, the possible values are 2 (2.0-- protocol), 3 (3.0 protocol), or zero (connection bad). This will-- not change after connection startup is complete, but it could-- theoretically change during a connection reset. The 3.0 protocol-- will normally be used when communicating with PostgreSQL 7.4 or-- later servers; pre-7.4 servers support only protocol 2.0. (Protocol-- 1.0 is obsolete and not supported by libpq.)protocolVersion::Connection->IOIntprotocolVersionconnection=fmapfromIntegral$withConnconnectionc_PQprotocolVersion-- | Returns an integer representing the backend version.---- Applications might use this to determine the version of the-- database server they are connected to. The number is formed by-- converting the major, minor, and revision numbers into-- two-decimal-digit numbers and appending them together. For example,-- version 8.1.5 will be returned as 80105, and version 8.2 will be-- returned as 80200 (leading zeroes are not shown). Zero is returned-- if the connection is bad.serverVersion::Connection->IOIntserverVersionconnection=fmapfromIntegral$withConnconnectionc_PQserverVersion-- | Returns the error message most recently generated by an operation-- on the connection.---- Nearly all libpq functions will set a message for 'errorMessage' if-- they fail. Note that by libpq convention, a nonempty 'errorMessage'-- result can be multiple lines, and will include a trailing-- newline. The result string should not be expected to remain the-- same across operations on the 'Connection'.errorMessage::Connection->IO(MaybeB.ByteString)errorMessage=flipmaybeBsFromConnc_PQerrorMessage-- | Obtains the file descriptor number of the connection socket to-- the server. (This will not change during normal operation, but-- could change during connection setup or reset.)socket::Connection->IO(MaybeFd)socketconnection=docFd<-withConnconnectionc_PQsocketreturn$casecFdof-1->Nothing_->Just$FdcFd-- | Returns the process 'CPid' of the backend server process-- handling this connection.---- The backend PID is useful for debugging purposes and for comparison-- to NOTIFY messages (which include the PID of the notifying backend-- process). Note that the PID belongs to a process executing on the-- database server host, not the local host!backendPID::Connection->IOCPidbackendPIDconnection=fmapfromIntegral$withConnconnectionc_PQbackendPID-- | Returns 'True' if the connection authentication method required a-- password, but none was available. Returns 'False' if not.---- This function can be applied after a failed connection attempt to-- decide whether to prompt the user for a password.connectionNeedsPassword::Connection->IOBoolconnectionNeedsPasswordconnection=enumFromConnconnectionc_PQconnectionNeedsPassword-- | Returns 'True' if the connection authentication method used a-- password. Returns 'False' if not.---- This function can be applied after either a failed or successful-- connection attempt to detect whether the server demanded a-- password.connectionUsedPassword::Connection->IOBoolconnectionUsedPasswordconnection=enumFromConnconnectionc_PQconnectionUsedPassword-- TODO: getSSL :: Connection -> IO SSL-- $commandexec-- Once a connection to a database server has been successfully-- established, the functions described here are used to perform SQL-- queries and commands.-- | 'Result' encapsulates the result of a query (or more precisely,-- of a single SQL command --- a query string given to 'sendQuery' can-- contain multiple commands and thus return multiple instances of-- 'Result'.newtypeResult=Result(ForeignPtrPGresult)deriving(Eq,Show)dataPGresultdataFormat=Text|Binaryderiving(Eq,Ord,Show,Enum)newtypeOid=OidCUIntderiving(Eq,Ord,Read,Show,Storable)invalidOid::OidinvalidOid=Oid(0){-# LINE 660 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Submits a command to the server and waits for the result.---- Returns a 'Result' or possibly 'Nothing'. A 'Result' will generally-- be returned except in out-of-memory conditions or serious errors-- such as inability to send the command to the server. If a 'Nothing'-- is returned, it should be treated like a 'FatalError' result. Use-- 'errorMessage' to get more information about such errors.---- It is allowed to include multiple SQL commands (separated by-- semicolons) in the command string. Multiple queries sent in a-- single 'exec' call are processed in a single transaction, unless-- there are explicit BEGIN/COMMIT commands included in the query-- string to divide it into multiple transactions. Note however that-- the returned 'Result' structure describes only the result of the-- last command executed from the string. Should one of the commands-- fail, processing of the string stops with it and the returned-- 'Result' describes the error condition.exec::Connection-- ^ connection->B.ByteString-- ^ statement->IO(MaybeResult)-- ^ resultexecconnectionquery=resultFromConnconnection$\p->B.useAsCStringquery$c_PQexecp-- | Submits a command to the server and waits for the result, with-- the ability to pass parameters separately from the SQL command-- text.---- 'execParams' is like 'exec', but offers additional functionality:-- parameter values can be specified separately from the command-- string proper, and query results can be requested in either text or-- binary format. 'execParams' is supported only in protocol 3.0 and-- later connections; it will fail when using protocol 2.0.---- The primary advantage of 'execParams' over 'exec' is that parameter-- values can be separated from the command string, thus avoiding the-- need for tedious and error-prone quoting and escaping.---- Unlike 'exec', 'execParams' allows at most one SQL command in the-- given string. (There can be semicolons in it, but not more than one-- nonempty command.) This is a limitation of the underlying protocol,-- but has some usefulness as an extra defense against SQL-injection-- attacks.---- Tip: Specifying parameter types via OIDs is tedious, particularly-- if you prefer not to hard-wire particular OID values into your-- program. However, you can avoid doing so even in cases where the-- server by itself cannot determine the type of the parameter, or-- chooses a different type than you want. In the SQL command text,-- attach an explicit cast to the parameter symbol to show what data-- type you will send. For example:-- SELECT * FROM mytable WHERE x = $1::bigint;-- This forces parameter $1 to be treated as bigint, whereas by-- default it would be assigned the same type as x. Forcing the-- parameter type decision, either this way or by specifying a numeric-- type OID, is strongly recommended when sending parameter values in-- binary format, because binary format has less redundancy than text-- format and so there is less chance that the server will detect a-- type mismatch mistake for you.execParams::Connection-- ^ connection->B.ByteString-- ^ statement->[Maybe(Oid,B.ByteString,Format)]-- ^ parameters->Format-- ^ result format->IO(MaybeResult)-- ^ resultexecParamsconnectionstatementparamsrFmt=dolet(oids,values,lengths,formats)=foldl'accum([],[],[],[])$reverseparamsc_lengths=maptoEnumlengths::[CInt]n=toEnum$lengthparamsf=toEnum$fromEnumrFmtresultFromConnconnection$\c->B.useAsCStringstatement$\s->withArrayoids$\ts->withMany(maybeWithB.useAsCString)values$\c_values->withArrayc_values$\vs->withArrayc_lengths$\ls->withArrayformats$\fs->c_PQexecParamscsntsvslsfsfwhereaccum(!a,!b,!c,!d)Nothing=(invalidOid:a,Nothing:b,0:c,0:d)accum(!a,!b,!c,!d)(Just(t,v,f))=(t:a,(Justv):b,(B.lengthv):c,(toEnum$fromEnumf):d)-- | Submits a request to create a prepared statement with the given-- parameters, and waits for completion.---- 'prepare' creates a prepared statement for later execution with-- 'execPrepared'. This feature allows commands that will be used-- repeatedly to be parsed and planned just once, rather than each-- time they are executed. 'prepare' is supported only in protocol 3.0-- and later connections; it will fail when using protocol 2.0.---- The function creates a prepared statement named stmtName from the-- query string, which must contain a single SQL command. stmtName can-- be \"\" to create an unnamed statement, in which case any-- pre-existing unnamed statement is automatically replaced; otherwise-- it is an error if the statement name is already defined in the-- current session. If any parameters are used, they are referred to-- in the query as $1, $2, etc. paramTypes specifies, by 'Oid', the-- data types to be assigned to the parameter symbols. If paramTypes-- is 'Nothing', or any particular element in the array is zero, the-- server assigns a data type to the parameter symbol in the same way-- it would do for an untyped literal string. Also, the query can use-- parameter symbols with numbers higher than the length of-- paramTypes; data types will be inferred for these symbols as-- well. (See 'describePrepared' for a means to find out what data-- types were inferred.)---- As with 'exec', the result is normally a 'Result' whose contents-- indicate server-side success or failure. A 'Nothing' result-- indicates out-of-memory or inability to send the command at-- all. Use 'errorMessage' to get more information about such errors.---- Prepared statements for use with 'execPrepared' can also be created-- by executing SQL PREPARE statements. (But 'prepare' is more-- flexible since it does not require parameter types to be-- pre-specified.) Also, although there is no libpq function for-- deleting a prepared statement, the SQL DEALLOCATE statement can be-- used for that purpose.prepare::Connection-- ^ connection->B.ByteString-- ^ stmtName->B.ByteString-- ^ query->Maybe[Oid]-- ^ paramTypes->IO(MaybeResult)-- ^ resultprepareconnectionstmtNamequerymParamTypes=resultFromConnconnection$\c->B.useAsCStringstmtName$\s->B.useAsCStringquery$\q->maybeWithwithArraymParamTypes$\o->letl=maybe0(toEnum.length)mParamTypesinc_PQpreparecsqlo-- | Sends a request to execute a prepared statement with given-- parameters, and waits for the result.---- 'execPrepared' is like 'execParams', but the command to be executed-- is specified by naming a previously-prepared statement, instead of-- giving a query string. This feature allows commands that will be-- used repeatedly to be parsed and planned just once, rather than-- each time they are executed. The statement must have been prepared-- previously in the current session. 'execPrepared' is supported only-- in protocol 3.0 and later connections; it will fail when using-- protocol 2.0.---- The parameters are identical to 'execParams', except that the name-- of a prepared statement is given instead of a query string, and the-- paramTypes parameter is not present (it is not needed since the-- prepared statement's parameter types were determined when it was-- created).execPrepared::Connection-- ^ connection->B.ByteString-- ^ stmtName->[Maybe(B.ByteString,Format)]-- ^ parameters->Format-- ^ result format->IO(MaybeResult)-- ^ resultexecPreparedconnectionstmtNamemPairsrFmt=dolet(values,lengths,formats)=foldl'accum([],[],[])$reversemPairsc_lengths=maptoEnumlengths::[CInt]n=toEnum$lengthmPairsf=toEnum$fromEnumrFmtresultFromConnconnection$\c->B.useAsCStringstmtName$\s->withMany(maybeWithB.useAsCString)values$\c_values->withArrayc_values$\vs->withArrayc_lengths$\ls->withArrayformats$\fs->c_PQexecPreparedcsnvslsfsfwhereaccum(!a,!b,!c)Nothing=(Nothing:a,0:b,0:c)accum(!a,!b,!c)(Just(v,f))=((Justv):a,(B.lengthv):b,(toEnum$fromEnumf):c)-- | Submits a request to obtain information about the specified-- prepared statement, and waits for completion.---- 'describePrepared' allows an application to obtain information-- about a previously prepared statement. 'describePrepared' is-- supported only in protocol 3.0 and later connections; it will fail-- when using protocol 2.0.---- stmtName can be empty to reference the unnamed statement, otherwise-- it must be the name of an existing prepared statement. On success,-- a 'Result' with status 'CommandOk' is returned. The functions-- 'nparams' and 'paramtype' can be applied to this 'Result' to obtain-- information about the parameters of the prepared statement, and the-- functions 'nfields', 'fname', 'ftype', etc provide information-- about the result columns (if any) of the statement.describePrepared::Connection->B.ByteString-- ^ stmtName->IO(MaybeResult)describePreparedconnectionstmtName=resultFromConnconnection$\c->B.useAsCStringstmtName$\s->c_PQdescribePreparedcs-- | Submits a request to obtain information about the specified-- portal, and waits for completion.---- 'describePortal' allows an application to obtain information about-- a previously created portal. (libpq does not provide any direct-- access to portals, but you can use this function to inspect the-- properties of a cursor created with a DECLARE CURSOR SQL command.)-- 'describePortal' is supported only in protocol 3.0 and later-- connections; it will fail when using protocol 2.0.---- portalName can be empty to reference the unnamed portal, otherwise-- it must be the name of an existing portal. On success, a 'Result'-- with status 'CommandOk' is returned. The functions 'nfields',-- 'fname', 'ftype', etc can be applied to the 'Result' to obtain-- information about the result columns (if any) of the portal.describePortal::Connection->B.ByteString-- ^ portalName->IO(MaybeResult)describePortalconnectionportalName=resultFromConnconnection$\c->B.useAsCStringportalName$\p->c_PQdescribePortalcpdataExecStatus=EmptyQuery-- ^ The string sent to the server was empty.|CommandOk-- ^ Successful completion of a-- command returning no data.|TuplesOk-- ^ Successful completion of a-- command returning data (such as a-- SELECT or SHOW).|CopyOut-- ^ Copy Out (from server) data-- transfer started.|CopyIn-- ^ Copy In (to server) data transfer-- started.|BadResponse-- ^ The server's response was not understood.|NonfatalError-- ^ A nonfatal error (a notice or-- warning) occurred.|FatalError-- ^ A fatal error occurred.deriving(Eq,Show)instanceEnumExecStatuswheretoEnum(0)=EmptyQuery{-# LINE 915 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(1)=CommandOk{-# LINE 916 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(2)=TuplesOk{-# LINE 917 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(3)=CopyOut{-# LINE 918 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(4)=CopyIn{-# LINE 919 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(5)=BadResponse{-# LINE 920 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(6)=NonfatalError{-# LINE 921 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(7)=FatalError{-# LINE 922 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum_=error"Database.PQ.Enum.ExecStatus.toEnum: bad argument"fromEnumEmptyQuery=(0){-# LINE 925 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumCommandOk=(1){-# LINE 926 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumTuplesOk=(2){-# LINE 927 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumCopyOut=(3){-# LINE 928 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumCopyIn=(4){-# LINE 929 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumBadResponse=(5){-# LINE 930 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumNonfatalError=(6){-# LINE 931 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumFatalError=(7){-# LINE 932 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Returns the result status of the command.resultStatus::Result->IOExecStatusresultStatusresult=enumFromResultresultc_PQresultStatus-- | Converts the 'ExecStatus' returned by 'resultStatus' into a-- string describing the status code. The caller should not-- free the result.resStatus::ExecStatus->IOB.ByteStringresStatuses=docstr<-c_PQresStatus$fromIntegral$fromEnumeslen<-B.c_strlencstrfp<-newForeignPtr_$castPtrcstrreturn$B.fromForeignPtrfp0$fromIntegrallen-- | Returns the error message most recently generated by an operation-- on the connection.resultErrorMessage::Result->IO(MaybeB.ByteString)resultErrorMessage=flipmaybeBsFromResultc_PQresultErrorMessage-- | Frees the memory associated with a result. Note that using this-- function correctly is especially tricky; you need to ensure that-- no references to the result. This means no references to a value-- returned by 'getvalue', no references hiding inside an unevaluated-- thunk, etc. Improper use of this function is likely to cause a-- segfault. Also, the use of this function is not strictly necessary;-- the memory will get freed by the garbage collector when there are no-- more references to the result.unsafeFreeResult::Result->IO()unsafeFreeResult(Resultx)=finalizeForeignPtrxdataFieldCode=DiagSeverity-- ^ The severity; the field contents are ERROR, FATAL,-- or PANIC (in an error message), or WARNING, NOTICE,-- DEBUG, INFO, or LOG (in a notice message), or a-- localized translation of one of these. Always-- present.|DiagSqlstate-- ^ The SQLSTATE code for the error. The SQLSTATE code-- identifies the type of error that has occurred; it-- can be used by front-end applications to perform-- specific operations (such as error handling) in-- response to a particular database error. For a list-- of the possible SQLSTATE codes, see Appendix A. This-- field is not localizable, and is always present.|DiagMessagePrimary-- ^ The primary human-readable error message-- (typically one line). Always present.|DiagMessageDetail-- ^ Detail: an optional secondary error message-- carrying more detail about the problem. Might run to-- multiple lines.|DiagMessageHint-- ^ Hint: an optional suggestion what to do about the-- problem. This is intended to differ from detail in-- that it offers advice (potentially inappropriate)-- rather than hard facts. Might run to multiple lines.|DiagStatementPosition-- ^ A string containing a decimal integer indicating-- an error cursor position as an index into the-- original statement string. The first character has-- index 1, and positions are measured in characters-- not bytes.|DiagInternalPosition-- ^ This is defined the same as the-- 'DiagStatementPosition' field, but it is used when-- the cursor position refers to an internally-- generated command rather than the one submitted by-- the client. The 'DiagInternalQuery' field will-- always appear when this field appears.|DiagInternalQuery-- ^ The text of a failed internally-generated-- command. This could be, for example, a SQL query-- issued by a PL/pgSQL function.|DiagContext-- ^ An indication of the context in which the error-- occurred. Presently this includes a call stack-- traceback of active procedural language functions-- and internally-generated queries. The trace is one-- entry per line, most recent first.|DiagSourceFile-- ^ The file name of the source-code location where-- the error was reported.|DiagSourceLine-- ^ The line number of the source-code location where-- the error was reported.|DiagSourceFunction-- ^ The name of the source-code function reporting the-- error.instanceEnumFieldCodewheretoEnum(83)=DiagSeverity{-# LINE 1043 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(67)=DiagSqlstate{-# LINE 1044 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(77)=DiagMessagePrimary{-# LINE 1045 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(68)=DiagMessageDetail{-# LINE 1046 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(72)=DiagMessageHint{-# LINE 1047 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(80)=DiagStatementPosition{-# LINE 1048 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(112)=DiagInternalPosition{-# LINE 1049 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(113)=DiagInternalQuery{-# LINE 1050 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(87)=DiagContext{-# LINE 1051 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(70)=DiagSourceFile{-# LINE 1052 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(76)=DiagSourceLine{-# LINE 1053 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(82)=DiagSourceFunction{-# LINE 1054 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum_=error"Database.PQ.Enum.FieldCode.toEnum: bad argument"fromEnumDiagSeverity=(83){-# LINE 1057 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagSqlstate=(67){-# LINE 1058 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagMessagePrimary=(77){-# LINE 1059 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagMessageDetail=(68){-# LINE 1060 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagMessageHint=(72){-# LINE 1061 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagStatementPosition=(80){-# LINE 1062 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagInternalPosition=(112){-# LINE 1063 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagInternalQuery=(113){-# LINE 1064 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagContext=(87){-# LINE 1065 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagSourceFile=(70){-# LINE 1066 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagSourceLine=(76){-# LINE 1067 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumDiagSourceFunction=(82){-# LINE 1068 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Returns an individual field of an error report.---- fieldcode is an error field identifier; see the symbols listed-- below. 'Nothing' is returned if the PGresult is not an error or-- warning result, or does not include the specified field. Field-- values will normally not include a trailing newline.---- The client is responsible for formatting displayed information to-- meet its needs; in particular it should break long lines as-- needed. Newline characters appearing in the error message fields-- should be treated as paragraph breaks, not line breaks.---- Errors generated internally by libpq will have severity and primary-- message, but typically no other fields. Errors returned by a-- pre-3.0-protocol server will include severity and primary message,-- and sometimes a detail message, but no other fields.---- Note that error fields are only available from 'Result' objects,-- not 'Connection' objects; there is no errorField function.resultErrorField::Result->FieldCode->IO(MaybeB.ByteString)resultErrorField(Resultfp)fieldcode=maybeBsFromForeignPtrfp$\res->c_PQresultErrorFieldres$fromIntegral$fromEnumfieldcode-- $queryresultinfo-- These functions are used to extract information from a 'Result'-- that represents a successful query result (that is, one that has-- status 'TuplesOk'). They can also be used to extract information-- from a successful Describe operation: a Describe's result has all-- the same column information that actual execution of the query-- would provide, but it has zero rows. For objects with other status-- values, these functions will act as though the result has zero rows-- and zero columns.-- | Returns the number of rows (tuples) in the query result. Because-- it returns an integer result, large result sets might overflow the-- return value on 32-bit operating systems.ntuples::Result->IORowntuples(Resultres)=withForeignPtrres(return.toRow.c_PQntuples)-- | Returns the number of columns (fields) in each row of the query-- result.nfields::Result->IOColumnnfields(Resultres)=withForeignPtrres(return.toColumn.c_PQnfields)newtypeColumn=ColCIntderiving(Eq,Ord,Show,Enum,Num)newtypeRow=RowCIntderiving(Eq,Ord,Show,Enum,Num)toColumn::(Integrala)=>a->ColumntoColumn=Col.fromIntegraltoRow::(Integrala)=>a->RowtoRow=Row.fromIntegral-- | Returns the column name associated with the given 'Column'-- number. Column numbers start at 0.fname::Result->Column->IO(MaybeB.ByteString)fnameresult(ColcolNum)=maybeBsFromResultresult$\fp->c_PQfnamefpcolNum-- | Returns the column number associated with the given column name.fnumber::Result->B.ByteString->IO(MaybeColumn)fnumber(Resultres)columnName=donum<-withForeignPtrres$\resPtr->B.useAsCStringcolumnName$\columnNamePtr->c_PQfnumberresPtrcolumnNamePtrreturn$ifnum==-1thenNothingelseJust$toColumnnum-- | Returns the OID of the table from which the given column was-- fetched. Column numbers start at 0.ftable::Result->Column->IOOidftableresult(ColcolNum)=withResultresult$\ptr->c_PQftableptrcolNum-- | Returns the column number (within its table) of the column making-- up the specified query result column. Query-result column numbers-- start at 0, but table columns have nonzero numbers.ftablecol::Result->Column->IOColumnftablecolresult(ColcolNum)=fmapCol$withResultresult$\p->c_PQftablecolpcolNum-- | Returns the 'Format' of the given column. Column numbers start at-- 0.fformat::Result->Column->IOFormatfformatresult(ColcolNum)=enumFromResultresult$\ptr->c_PQfformatptrcolNum-- | Returns the data type associated with the given column-- number. The 'Oid' returned is the internal OID number of the-- type. Column numbers start at 0.---- You can query the system table pg_type to obtain the names and-- properties of the various data types. The OIDs of the built-in data-- types are defined in the file src/include/catalog/pg_type.h in the-- source tree.ftype::Result->Column->IOOidftyperesult(ColcolNum)=withResultresult$\ptr->c_PQftypeptrcolNum-- | Returns the type modifier of the column associated with the given-- column number. Column numbers start at 0.---- The interpretation of modifier values is type-specific; they-- typically indicate precision or size limits. The value -1 is used-- to indicate "no information available". Most data types do not use-- modifiers, in which case the value is always -1.fmod::Result->Column->IOIntfmodresult(ColcolNum)=numFromResultresult$\ptr->c_PQfmodptrcolNum-- | Returns the size in bytes of the column associated with the given-- column number. Column numbers start at 0.---- 'fsize' returns the space allocated for this column in a database-- row, in other words the size of the server's internal-- representation of the data type. (Accordingly, it is not really-- very useful to clients.) A negative value indicates the data type-- is variable-length.fsize::Result->Column->IOIntfsizeresult(ColcolNum)=numFromResultresult$\ptr->c_PQfsizeptrcolNum-- | Returns a single field value of one row of a PGresult. Row and-- column numbers start at 0.---- For convenience, this binding uses 'getisnull' and 'getlength' to-- help construct the result.---- Note: The 'ByteString' returned holds a reference to the Result. As-- long as ByteString is live, the Result will not be garbage-- collected. 'getvalue'' returns a copy of the data.getvalue::Result->Row->Column->IO(MaybeB.ByteString)getvalue(Resultfp)(RowrowNum)(ColcolNum)=withForeignPtrfp$\ptr->doisnull<-c_PQgetisnullptrrowNumcolNumiftoEnum$fromIntegralisnullthenreturn$Nothingelsedocstr<-c_PQgetvalueptrrowNumcolNuml<-c_PQgetlengthptrrowNumcolNumfp'<-FC.newForeignPtr(castPtrcstr)finalizerreturn$Just$B.fromForeignPtrfp'0$fromIntegrallwherefinalizer=touchForeignPtrfp-- | Returns a copy of a single field value of one row of a-- PGresult. Row and column numbers start at 0.---- For convenience, this binding uses 'getisnull' and 'getlength' to-- help construct the result.getvalue'::Result->Row->Column->IO(MaybeB.ByteString)getvalue'(Resultfp)(RowrowNum)(ColcolNum)=withForeignPtrfp$\ptr->doisnull<-c_PQgetisnullptrrowNumcolNumiftoEnum$fromIntegralisnullthenreturn$Nothingelsedocstr<-c_PQgetvalueptrrowNumcolNuml<-fromIntegral`fmap`c_PQgetlengthptrrowNumcolNumJust`fmap`B.packCStringLen(cstr,l)-- | Tests a field for a null value. Row and column numbers start at-- 0.getisnull::Result->Row->Column->IOBoolgetisnullresult(RowrowNum)(ColcolNum)=enumFromResultresult$\ptr->c_PQgetisnullptrrowNumcolNum-- | Returns the actual length of a field value in bytes. Row and-- column numbers start at 0.---- This is the actual data length for the particular data value, that-- is, the size of the object pointed to by 'getvalue'. For text data-- format this is the same as strlen(). For binary format this is-- essential information. Note that one should not rely on 'fsize' to-- obtain the actual data length.getlength::Result->Row->Column->IOIntgetlengthresult(RowrowNum)(ColcolNum)=numFromResultresult$\ptr->c_PQgetlengthptrrowNumcolNum-- | Returns the number of parameters of a prepared statement.---- This function is only useful when inspecting the result of-- PQdescribePrepared. For other types of queries it will return zero.nparams::Result->IOIntnparamsresult=numFromResultresultc_PQnparams-- | Returns the data type of the indicated statement-- parameter. Parameter numbers start at 0.---- This function is only useful when inspecting the result of-- 'describePrepared'. For other types of queries it will return zero.paramtype::Result->Int-- ^ param_number->IOOidparamtyperesultparam_number=withResultresult$\p->c_PQparamtypep$fromIntegralparam_numberdataPrintOpt=PrintOpt{poHeader::Bool-- ^ print output field headings and row count,poAlign::Bool-- ^ fill align the fields,poStandard::Bool-- ^ old brain dead format,poHtml3::Bool-- ^ output HTML tables,poExpanded::Bool-- ^ expand tables,poPager::Bool-- ^ use pager for output if needed,poFieldSep::B.ByteString-- ^ field separator,poTableOpt::B.ByteString-- ^ attributes for HTML table element,poCaption::B.ByteString-- ^ HTML table caption,poFieldName::[B.ByteString]-- ^ list of replacement field names}defaultPrintOpt::PrintOptdefaultPrintOpt=PrintOptTrueTrueFalseFalseFalseFalse"|"""""[]{-# LINE 1339 "Database/PostgreSQL/LibPQ.hsc" #-}instanceStorablePrintOptwheresizeOf_=(24){-# LINE 1341 "Database/PostgreSQL/LibPQ.hsc" #-}alignment_=4{-# LINE 1343 "Database/PostgreSQL/LibPQ.hsc" #-}peekptr=doa<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr0)ptr{-# LINE 1346 "Database/PostgreSQL/LibPQ.hsc" #-}b<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr1)ptr{-# LINE 1347 "Database/PostgreSQL/LibPQ.hsc" #-}c<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr2)ptr{-# LINE 1348 "Database/PostgreSQL/LibPQ.hsc" #-}d<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr3)ptr{-# LINE 1349 "Database/PostgreSQL/LibPQ.hsc" #-}e<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr4)ptr{-# LINE 1350 "Database/PostgreSQL/LibPQ.hsc" #-}f<-fmappqbool$(\hsc_ptr->peekByteOffhsc_ptr5)ptr{-# LINE 1351 "Database/PostgreSQL/LibPQ.hsc" #-}g<-B.packCString=<<(\hsc_ptr->peekByteOffhsc_ptr8)ptr{-# LINE 1352 "Database/PostgreSQL/LibPQ.hsc" #-}h<-B.packCString=<<(\hsc_ptr->peekByteOffhsc_ptr12)ptr{-# LINE 1353 "Database/PostgreSQL/LibPQ.hsc" #-}i<-B.packCString=<<(\hsc_ptr->peekByteOffhsc_ptr16)ptr{-# LINE 1354 "Database/PostgreSQL/LibPQ.hsc" #-}j<-(\hsc_ptr->peekByteOffhsc_ptr20)ptr{-# LINE 1355 "Database/PostgreSQL/LibPQ.hsc" #-}j'<-peekArray0nullPtrjj''<-mapMB.packCStringj'return$PrintOptabcdefghij''wherepqbool::CChar->Boolpqbool=toEnum.fromIntegralpokeptr(PrintOptabcdefghij)=B.useAsCStringg$\g'->doB.useAsCStringh$\h'->doB.useAsCStringi$\i'->dowithManyB.useAsCStringj$\j'->withArray0nullPtrj'$\j''->doleta'=(fromIntegral$fromEnuma)::CCharb'=(fromIntegral$fromEnumb)::CCharc'=(fromIntegral$fromEnumc)::CChard'=(fromIntegral$fromEnumd)::CChare'=(fromIntegral$fromEnume)::CCharf'=(fromIntegral$fromEnumf)::CChar(\hsc_ptr->pokeByteOffhsc_ptr0)ptra'{-# LINE 1375 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr1)ptrb'{-# LINE 1376 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr2)ptrc'{-# LINE 1377 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr3)ptrd'{-# LINE 1378 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr4)ptre'{-# LINE 1379 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr5)ptrf'{-# LINE 1380 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr8)ptrg'{-# LINE 1381 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr12)ptrh'{-# LINE 1382 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr16)ptri'{-# LINE 1383 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr20)ptrj''{-# LINE 1384 "Database/PostgreSQL/LibPQ.hsc" #-}-- $othercommands-- These functions are used to extract other information from PGresult-- objects.-- | Returns the command status tag from the SQL command that-- generated the PGresult.---- Commonly this is just the name of the command, but it might include-- additional data such as the number of rows processed.cmdStatus::Result->IO(MaybeB.ByteString)cmdStatus=flipmaybeBsFromResultc_PQcmdStatus-- | Returns the number of rows affected by the SQL command.---- This function returns a string containing the number of rows-- affected by the SQL statement that generated the 'Result'. This-- function can only be used following the execution of a SELECT,-- CREATE TABLE AS, INSERT, UPDATE, DELETE, MOVE, FETCH, or COPY-- statement, or an EXECUTE of a prepared query that contains an-- INSERT, UPDATE, or DELETE statement. If the command that generated-- the 'Result' was anything else, 'cmdTuples' returns an empty-- string.cmdTuples::Result->IO(MaybeB.ByteString)cmdTuples=flipmaybeBsFromResultc_PQcmdTuples-- | Returns the 'Oid' of the inserted row, if the SQL command was an-- INSERT that inserted exactly one row into a table that has OIDs, or-- a EXECUTE of a prepared query containing a suitable INSERT-- statement. Otherwise, this function returns 'Nothing'. This-- function will also return 'Nothing' if the table affected by the-- INSERT statement does not contain OIDs.oidValue::Result->IO(MaybeOid)oidValueresult=withResultresult$\ptr->dooid<-c_PQoidValueptrreturn$toMaybeOidoid-- | Escapes a string for use within an SQL command. This is useful-- when inserting data values as literal constants in SQL-- commands. Certain characters (such as quotes and backslashes) must-- be escaped to prevent them from being interpreted specially by the-- SQL parser.escapeStringConn::Connection->B.ByteString->IO(MaybeB.ByteString)escapeStringConnconnectionbs=withConnconnection$\conn->B.unsafeUseAsCStringLenbs$\(from,bslen)->alloca$\err->doto<-mallocBytes(bslen*2+1)num<-c_PQescapeStringConnconntofrom(fromIntegralbslen)errstat<-peekerrcasestatof0->doleti=fromIntegralnumtore<-reallocBytestoitofp<-newForeignPtrfinalizerFreetorereturn$Just$B.fromForeignPtrtofp0i_->dofreetoreturnNothing-- | Escapes binary data for use within an SQL command with the type-- bytea. As with 'escapeStringConn', this is only used when inserting-- data directly into an SQL command string.escapeByteaConn::Connection->B.ByteString->IO(MaybeB.ByteString)escapeByteaConnconnectionbs=withConnconnection$\conn->B.unsafeUseAsCStringLenbs$\(from,bslen)->alloca$\to_length->doto<-c_PQescapeByteaConnconnfrom(fromIntegralbslen)to_lengthifto==nullPtrthenreturnNothingelsedotofp<-newForeignPtrp_PQfreememtol<-peekto_lengthreturn$Just$B.fromForeignPtrtofp0((fromIntegrall)-1)-- | Converts a 'ByteString' representation of binary data into binary-- data - the reverse of 'PQescapeByteaConn'. This is needed when-- retrieving bytea data in text format, but not when retrieving it in-- binary format.---- The parameter points to a string such as might be returned by-- 'getvalue' when applied to a bytea column. 'unescapeBytea' converts-- this string representation into its binary representation. It-- returns a 'ByteString', or 'Nothing' on error.---- This conversion is not exactly the inverse of 'escapeByteaConn',-- because the string is not expected to be "escaped" when received-- from 'getvalue'. In particular this means there is no need for-- string quoting considerations, and so no need for a 'Connection'-- parameter.unescapeBytea::B.ByteString->IO(MaybeB.ByteString)unescapeByteabs=B.useAsCStringbs$\from->alloca$\to_length->doto<-c_PQunescapeByteafromto_lengthifto==nullPtrthenreturnNothingelsedotofp<-newForeignPtrp_PQfreememtol<-peekto_lengthreturn$Just$B.fromForeignPtrtofp0$fromIntegrall-- $asynccommand-- The 'exec' function is adequate for submitting commands in normal,-- synchronous applications. It has a couple of deficiencies, however,-- that can be of importance to some users:---- * 'exec' waits for the command to be completed. The application-- might have other work to do (such as maintaining a user-- interface), in which case it won't want to block waiting for the-- response.---- * Since the execution of the client application is suspended-- while it waits for the result, it is hard for the application to-- decide that it would like to try to cancel the ongoing-- command. (It can be done from a signal handler, but not-- otherwise.)---- * 'exec' can return only one 'Result'. If the submitted command-- string contains multiple SQL commands, all but the last 'Result'-- are discarded by 'exec'.---- Applications that do not like these limitations can instead use the-- underlying functions that 'exec' is built from: 'sendQuery' and-- 'getResult'. There are also 'sendQueryParams', 'sendPrepare',-- 'sendQueryPrepared', 'sendDescribePrepared', and-- 'sendDescribePortal', which can be used with 'getResult' to-- duplicate the functionality of 'execParams', 'prepare',-- 'execPrepared', 'describePrepared', and 'describePortal'-- respectively.-- | Submits a command to the server without waiting for the-- result(s). 'True' is returned if the command was successfully-- dispatched and 'False' if not (in which case, use 'errorMessage' to-- get more information about the failure).sendQuery::Connection->B.ByteString->IOBoolsendQueryconnectionquery=enumFromConnconnection$\p->B.useAsCStringquery$c_PQsendQueryp-- | Submits a command and separate parameters to the server without-- waiting for the result(s).sendQueryParams::Connection->B.ByteString->[Maybe(Oid,B.ByteString,Format)]->Format->IOBoolsendQueryParamsconnectionstatementparamsrFmt=dolet(oids,values,lengths,formats)=foldl'accum([],[],[],[])$reverseparamsc_lengths=maptoEnumlengths::[CInt]n=toEnum$lengthparamsf=toEnum$fromEnumrFmtenumFromConnconnection$\c->B.useAsCStringstatement$\s->withArrayoids$\ts->withMany(maybeWithB.useAsCString)values$\c_values->withArrayc_values$\vs->withArrayc_lengths$\ls->withArrayformats$\fs->c_PQsendQueryParamscsntsvslsfsfwhereaccum(!a,!b,!c,!d)Nothing=(invalidOid:a,Nothing:b,0:c,0:d)accum(!a,!b,!c,!d)(Just(t,v,f))=(t:a,(Justv):b,(B.lengthv):c,(toEnum$fromEnumf):d)-- | Sends a request to create a prepared statement with the given-- parameters, without waiting for completion.sendPrepare::Connection->B.ByteString->B.ByteString->Maybe[Oid]->IOBoolsendPrepareconnectionstmtNamequerymParamTypes=enumFromConnconnection$\c->B.useAsCStringstmtName$\s->B.useAsCStringquery$\q->maybeWithwithArraymParamTypes$\o->letl=maybe0(toEnum.length)mParamTypesinc_PQsendPreparecsqlo-- | Sends a request to execute a prepared statement with given-- parameters, without waiting for the result(s).sendQueryPrepared::Connection->B.ByteString->[Maybe(B.ByteString,Format)]->Format->IOBoolsendQueryPreparedconnectionstmtNamemPairsrFmt=dolet(values,lengths,formats)=foldl'accum([],[],[])$reversemPairsc_lengths=maptoEnumlengths::[CInt]n=toEnum$lengthmPairsf=toEnum$fromEnumrFmtenumFromConnconnection$\c->B.useAsCStringstmtName$\s->withMany(maybeWithB.useAsCString)values$\c_values->withArrayc_values$\vs->withArrayc_lengths$\ls->withArrayformats$\fs->c_PQsendQueryPreparedcsnvslsfsfwhereaccum(!a,!b,!c)Nothing=(Nothing:a,0:b,0:c)accum(!a,!b,!c)(Just(v,f))=((Justv):a,(B.lengthv):b,(toEnum$fromEnumf):c)-- | Submits a request to obtain information about the specified-- prepared statement, without waiting for completion.---- This is an asynchronous version of 'describePrepared': it returns-- 'True' if it was able to dispatch the request, and 'False' if-- not. After a successful call, call 'getResult' to obtain the-- results. The function's parameters are handled identically to-- 'describePrepared'. Like 'describePrepared', it will not work on-- 2.0-protocol connections.sendDescribePrepared::Connection->B.ByteString-- ^ stmtName->IOBoolsendDescribePreparedconnectionstmtName=enumFromConnconnection$\c->B.useAsCStringstmtName$\s->c_PQsendDescribePreparedcs-- | Submits a request to obtain information about the specified-- portal, without waiting for completion.---- This is an asynchronous version of 'describePortal': it returns-- 'True' if it was able to dispatch the request, and 'False' if-- not. After a successful call, call 'getResult' to obtain the-- results. The function's parameters are handled identically to-- 'describePortal'. Like 'describePortal', it will not work on-- 2.0-protocol connections.sendDescribePortal::Connection->B.ByteString-- ^ portalName->IOBoolsendDescribePortalconnectionportalName=enumFromConnconnection$\c->B.useAsCStringportalName$\p->c_PQsendDescribePortalcp-- | Waits for the next result from a prior 'sendQuery',-- 'sendQueryParams', 'sendPrepare', or 'sendQueryPrepared' call, and-- returns it. A null pointer is returned when the command is complete-- and there will be no more results.getResult::Connection->IO(MaybeResult)getResultconnection=doresPtr<-withConnconnectionc_PQgetResultifresPtr==nullPtrthenreturnNothingelse(Just.Result)`fmap`newForeignPtrp_PQclearresPtr-- | If input is available from the server, consume it.---- 'consumeInput' normally returns 'True' indicating "no error", but-- returns 'False' if there was some kind of trouble (in which case-- 'errorMessage' can be consulted). Note that the result does not say-- whether any input data was actually collected. After calling-- 'consumeInput', the application can check 'isBusy' and/or-- 'notifies' to see if their state has changed.consumeInput::Connection->IOBoolconsumeInputconnection=enumFromConnconnectionc_PQconsumeInput-- | Returns True if a command is busy, that is, getResult would block-- waiting for input. A False return indicates that getResult can be-- called with assurance of not blocking.---- 'isBusy' will not itself attempt to read data from the server;-- therefore 'consumeInput' must be invoked first, or the busy state-- will never end.isBusy::Connection->IOBoolisBusyconnection=enumFromConnconnectionc_PQisBusy-- | Sets the nonblocking status of the connection.setnonblocking::Connection->Bool->IOBoolsetnonblockingconnectionblocking=doletarg=fromIntegral$fromEnumblockingstat<-withConnconnection$\ptr->c_PQsetnonblockingptrargreturn$stat==0-- | Returns the blocking status of the database connection.isnonblocking::Connection->IOBoolisnonblockingconnection=enumFromConnconnectionc_PQisnonblockingdataFlushStatus=FlushOk|FlushFailed|FlushWriting-- | Attempts to flush any queued output data to the server. Returns-- 'FlushOk' if successful (or if the send queue is empty),-- 'FlushFailed' if it failed for some reason, or 'FlushWriting' if it-- was unable to send all the data in the send queue yet (this case-- can only occur if the connection is nonblocking).flush::Connection->IOFlushStatusflushconnection=dostat<-withConnconnectionc_PQflushreturn$casestatof0->FlushOk1->FlushWriting_->FlushFailed-- $cancel-- A client application can request cancellation of a command that is-- still being processed by the server, using the functions described-- in this section.-- | Contains the information needed to cancel a command issued-- through a particular database connection.newtypeCancel=Cancel(ForeignPtrPGcancel)deriving(Eq,Show)dataPGcancel-- | Creates a data structure containing the information needed to-- cancel a command issued through a particular database connection.---- 'getCancel' creates a 'Cancel' object given a 'Connection'. It will-- return 'Nothing' if the given conn is an invalid connection.getCancel::Connection->IO(MaybeCancel)getCancelconnection=withConnconnection$\conn->doptr<-c_PQgetCancelconnifptr==nullPtrthenreturnNothingelsedofp<-newForeignPtrp_PQfreeCancelptrreturn$Just$Cancelfp-- | Requests that the server abandon processing of the current-- command.---- The return value is 'Right ()' if the cancel request was-- successfully dispatched and if not, 'Left B.ByteString' containing-- an error message explaining why not.---- Successful dispatch is no guarantee that the request will have any-- effect, however. If the cancellation is effective, the current-- command will terminate early and return an error result. If the-- cancellation fails (say, because the server was already done-- processing the command), then there will be no visible result at-- all.cancel::Cancel->IO(EitherB.ByteString())cancel(Cancelfp)=withForeignPtrfp$\ptr->doerrbuf<-mallocByteserrbufsizeres<-c_PQcancelptrerrbuf$fromIntegralerrbufsizecaseresof1->dofreeerrbufreturn$Right()_->dol<-fromIntegral`fmap`B.c_strlenerrbuffp'<-newForeignPtrfinalizerFree$castPtrerrbufreturn$Left$B.fromForeignPtrfp'0lwhereerrbufsize=256-- $asyncnotification-- PostgreSQL offers asynchronous notification via the LISTEN and-- NOTIFY commands. A client session registers its interest in a-- particular notification channel with the LISTEN command (and can-- stop listening with the UNLISTEN command). All sessions listening-- on a particular channel will be notified asynchronously when a-- NOTIFY command with that channel name is executed by any session. A-- \"payload\" string can be passed to communicate additional data to-- the listeners.---- libpq applications submit LISTEN, UNLISTEN, and NOTIFY commands as-- ordinary SQL commands. The arrival of NOTIFY messages can-- subsequently be detected by calling 'notifies'.dataNotify=Notify{notifyRelname::B.ByteString-- ^ notification channel name,notifyBePid::CPid-- ^ process ID of notifying server process,notifyExtra::B.ByteString-- ^ notification payload string}instanceStorableNotifywheresizeOf_=(16){-# LINE 1812 "Database/PostgreSQL/LibPQ.hsc" #-}alignment_=4{-# LINE 1814 "Database/PostgreSQL/LibPQ.hsc" #-}peekptr=dorelname<-B.packCString=<<(\hsc_ptr->peekByteOffhsc_ptr0)ptr{-# LINE 1817 "Database/PostgreSQL/LibPQ.hsc" #-}extra<-B.packCString=<<(\hsc_ptr->peekByteOffhsc_ptr8)ptr{-# LINE 1818 "Database/PostgreSQL/LibPQ.hsc" #-}be_pid<-fmapf$(\hsc_ptr->peekByteOffhsc_ptr4)ptr{-# LINE 1819 "Database/PostgreSQL/LibPQ.hsc" #-}return$Notifyrelnamebe_pidextrawheref::CInt->CPidf=fromIntegralpokeptr(Notifyabc)=B.useAsCStringa$\a'->B.useAsCStringc$\c'->do(\hsc_ptr->pokeByteOffhsc_ptr0)ptra'{-# LINE 1828 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr4)ptr(fromIntegralb::CInt){-# LINE 1829 "Database/PostgreSQL/LibPQ.hsc" #-}(\hsc_ptr->pokeByteOffhsc_ptr8)ptrc'{-# LINE 1830 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Returns the next notification from a list of unhandled-- notification messages received from the server. It returns a-- 'Nothing' if there are no pending notifications. Once a-- notification is returned from notifies, it is considered handled-- and will be removed from the list of notifications.notifies::Connection->IO(MaybeNotify)notifiesconnection=withConnconnection$\ptr->domn<-c_PQnotifiesptrifmn==nullPtrthenreturnNothingelsedoresult<-Just`fmap`peekmnc_PQfreememmnreturnresult-- $control-- These functions control miscellaneous details of libpq's behavior.-- | Returns the client encoding.clientEncoding::Connection->IOB.ByteStringclientEncodingconnection=withConnconnection$\ptr->doi<-c_PQclientEncodingptrcstr<-c_pg_encoding_to_charilen<-B.c_strlencstrfp<-newForeignPtr_$castPtrcstrreturn$B.fromForeignPtrfp0$fromIntegrallen-- | Sets the client encoding.setClientEncoding::Connection->B.ByteString->IOBoolsetClientEncodingconnectionenc=dostat<-withConnconnection$\c->B.useAsCStringenc$\s->c_PQsetClientEncodingcsreturn$stat==0dataVerbosity=ErrorsTerse|ErrorsDefault|ErrorsVerbosederiving(Eq,Show)instanceEnumVerbositywheretoEnum(0)=ErrorsTerse{-# LINE 1881 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(1)=ErrorsDefault{-# LINE 1882 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum(2)=ErrorsVerbose{-# LINE 1883 "Database/PostgreSQL/LibPQ.hsc" #-}toEnum_=error"Database.PQ.Enum.Verbosity.toEnum: bad argument"fromEnumErrorsTerse=(0){-# LINE 1886 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumErrorsDefault=(1){-# LINE 1887 "Database/PostgreSQL/LibPQ.hsc" #-}fromEnumErrorsVerbose=(2){-# LINE 1888 "Database/PostgreSQL/LibPQ.hsc" #-}-- | Determines the verbosity of messages returned by 'errorMessage'-- and 'resultErrorMessage'.---- 'setErrorVerbosity' sets the verbosity mode, returning the-- connection's previous setting. In 'ErrorsTerse' mode, returned-- messages include severity, primary text, and position only; this-- will normally fit on a single line. The default mode produces-- messages that include the above plus any detail, hint, or context-- fields (these might span multiple lines). The 'ErrorsVerbose' mode-- includes all available fields. Changing the verbosity does not-- affect the messages available from already-existing 'Result'-- objects, only subsequently-created ones.setErrorVerbosity::Connection->Verbosity->IOVerbositysetErrorVerbosityconnectionverbosity=enumFromConnconnection$\p->c_PQsetErrorVerbosityp$fromIntegral$fromEnumverbositywithConn::Connection->(PtrPGconn->IOb)->IObwithConnconnectionf=withConn'connection$flipwithForeignPtrfwithConn'::Connection->(ForeignPtrPGconn->IOb)->IObwithConn'(Connfp)f=ffpenumFromConn::(Integrala,Enumb)=>Connection->(PtrPGconn->IOa)->IObenumFromConnconnectionf=fmap(toEnum.fromIntegral)$withConnconnectionfresultFromConn::Connection->(PtrPGconn->IO(PtrPGresult))->IO(MaybeResult)resultFromConnconnectionf=doresPtr<-withConnconnectionfifresPtr==nullPtrthenreturnNothingelse(Just.Result)`fmap`newForeignPtrp_PQclearresPtrwithResult::Result->(PtrPGresult->IOb)->IObwithResult(Resultfp)f=withForeignPtrfpfnumFromResult::(Integrala,Numb)=>Result->(PtrPGresult->IOa)->IObnumFromResultresultf=fmapfromIntegral$withResultresultfenumFromResult::(Integrala,Enumb)=>Result->(PtrPGresult->IOa)->IObenumFromResultresultf=fmap(toEnum.fromIntegral)$withResultresultf-- | Returns a ByteString with a finalizer that touches the ForeignPtr-- PGconn that \"owns\" the CString to keep it alive.---- The CString must be a null terminated c string. nullPtrs are-- treated as 'Nothing'.maybeBsFromConn::Connection->(PtrPGconn->IOCString)->IO(MaybeB.ByteString)maybeBsFromConnconnectionf=withConn'connection$\fp->maybeBsFromForeignPtrfpf-- | Returns a ByteString with a finalizer that touches the ForeignPtr-- PGresult that \"owns\" the CString to keep it alive.---- The CString must be a null terminated c string. nullPtrs are-- treated as 'Nothing'.maybeBsFromResult::Result->(PtrPGresult->IOCString)->IO(MaybeB.ByteString)maybeBsFromResult(Resultres)f=maybeBsFromForeignPtrresf-- | Returns a ByteString with a finalizer that touches the ForeignPtr-- that \"owns\" the CString to keep it alive.---- The CString must be a null terminated c string. nullPtrs are-- treated as 'Nothing'.maybeBsFromForeignPtr::ForeignPtra->(Ptra->IOCString)->IO(MaybeB.ByteString)maybeBsFromForeignPtrfpf=withForeignPtrfp$\p->docstr<-fpifcstr==nullPtrthenreturnNothingelsedol<-fromIntegral`fmap`B.c_strlencstrfp'<-FC.newForeignPtr(castPtrcstr)finalizerreturn$Just$B.fromForeignPtrfp'0lwherefinalizer=touchForeignPtrfp-- -- | Returns a ByteString with a finalizer that touches the ForeignPtr-- -- that \"owns\" the CStringLen to keep it alive.-- bsFromForeignPtrLen :: ForeignPtr a-- -> (Ptr a -> IO CStringLen)-- -> IO B.ByteString-- bsFromForeignPtrLen fp f =-- withForeignPtr fp $ \p ->-- do (cstr, l) <- f p-- if cstr == nullPtr-- then return ""-- else do fp' <- FC.newForeignPtr (castPtr cstr) finalizer-- return $ B.fromForeignPtr fp' 0 l-- where-- finalizer = touchForeignPtr fp-- $largeobjects-- | LoFd is a Large Object (pseudo) File Descriptor. It is understood by-- libpq but not by operating system calls.newtypeLoFd=LoFdCIntderiving(Eq,Ord,Show)loMode::IOMode->CIntloModemode=casemodeofReadMode->(262144){-# LINE 2022 "Database/PostgreSQL/LibPQ.hsc" #-}WriteMode->(131072){-# LINE 2023 "Database/PostgreSQL/LibPQ.hsc" #-}ReadWriteMode->(262144).|.(131072){-# LINE 2024 "Database/PostgreSQL/LibPQ.hsc" #-}AppendMode->(131072){-# LINE 2025 "Database/PostgreSQL/LibPQ.hsc" #-}toMaybeOid::Oid->MaybeOidtoMaybeOidoid|oid==invalidOid=Nothing|otherwise=Justoid{-# INLINE toMaybeOid #-}nonnegInt::CInt->MaybeIntnonnegIntx=ifx<0thenNothingelseJust(fromIntegralx){-# INLINE nonnegInt #-}negError::CInt->Maybe()negErrorx=ifx<0thenNothingelseJust(){-# INLINE negError #-}-- | Creates a new large object, returns the Object ID of the newly created-- object.loCreat::Connection->IO(MaybeOid)loCreatconnection=withConnconnection$\c->dotoMaybeOid`fmap`c_lo_creatc(loModeReadMode)-- | Creates a new large object with a particular Object ID. Returns-- 'Nothing' if the requested Object ID is already in use by some other-- large object or other failure. If 'invalidOid' is used as a parameter,-- then 'loCreate' will assign an unused 'Oid'.loCreate::Connection->Oid->IO(MaybeOid)loCreateconnectionoid=withConnconnection$\c->dotoMaybeOid`fmap`c_lo_createcoid-- | Imports an operating system file as a large object. Note that the-- file is read by the client interface library, not by the server; so it-- must exist in the client file system and be readable by the client-- application.loImport::Connection->FilePath->IO(MaybeOid)loImportconnectionfilepath=withConnconnection$\c->dowithCStringfilepath$\f->dotoMaybeOid`fmap`c_lo_importcf-- | Imports an operating system file as a large object with the given-- Object ID. Combines the behavior of 'loImport' and 'loCreate'loImportWithOid::Connection->FilePath->Oid->IO(MaybeOid)loImportWithOidconnectionfilepathoid=withConnconnection$\c->dowithCStringfilepath$\f->dotoMaybeOid`fmap`c_lo_import_with_oidcfoid-- | Exports a large object into a operating system file. Note that-- the file is written by the client interface library, not the server.-- Returns 'Just ()' on success, 'Nothing' on failure.loExport::Connection->Oid->FilePath->IO(Maybe())loExportconnectionoidfilepath=withConnconnection$\c->dowithCStringfilepath$\f->donegError`fmap`c_lo_exportcoidf-- | Opens an existing large object for reading or writing. The Oid specifies-- the large object to open. A large object cannot be opened before it is-- created. A large object descriptor is returned for later use in 'loRead',-- 'loWrite', 'loSeek', 'loTell', and 'loClose'. The descriptor is only valid-- for the duration of the current transation. On failure, 'Nothing' is-- returned.---- The server currently does not distinguish between 'WriteMode' and-- 'ReadWriteMode'; write-only modes are not enforced. However there-- is a significant difference between 'ReadMode' and the other modes:-- with 'ReadMode' you cannot write on the descriptor, and the data read-- from it will reflect the contents of the large object at the time of-- the transaction snapshot that was active when 'loOpen' was executed,-- regardless of later writes by this or other transactions. Reading from-- a descriptor opened in 'WriteMode', 'ReadWriteMode', or 'AppendMode'-- returns data that reflects all writes of other committed transactions-- as well as the writes of the current transaction. This is similar to-- the behavior of @REPEATABLE READ@ versus @READ COMMITTED@ transaction-- modes for ordinary SQL @SELECT@ commands.loOpen::Connection->Oid->IOMode->IO(MaybeLoFd)loOpenconnectionoidmode=withConnconnection$\c->dofd<-c_lo_opencoid(loModemode)casefdof-1->returnNothing_|mode/=AppendMode->return(Just(LoFdfd))|otherwise->do-- The Large Object API does not directly support AppendMode,-- so we emulate it.-- FIXME: review this emulation as it and/or the error-- handling is likely to be slightly wrong. Start by-- reading the source of lo_open, lo_lseek, and-- lo_close.err<-c_lo_lseekcfd0(2){-# LINE 2123 "Database/PostgreSQL/LibPQ.hsc" #-}caseerrof-1->do-- the lo_lseek failed, so we try to close the fd-- I'm not sure what to do if lo_close fails so I am-- ignoring it. This might obscure the error message-- available from PQerrorMessage_<-c_lo_closecfdreturnNothing_->return(Just(LoFdfd))-- | @loWrite conn fd buf@ writes the bytestring @buf@ to the large object-- descriptor @fd@. The number of bytes actually written is returned.-- In the event of an error, 'Nothing' is returned.loWrite::Connection->LoFd->B.ByteString->IO(MaybeInt)loWriteconnection(LoFdfd)bytes=withConnconnection$\c->doB.unsafeUseAsCStringLenbytes$\(byteptr,len)->dononnegInt`fmap`c_lo_writecfdbyteptr(fromIntegrallen)-- | @loRead conn fd len@ reads up to @len@ bytes from the large object-- descriptor @fd@. In the event of an error, 'Nothing' is returned.loRead::Connection->LoFd->Int->IO(MaybeB.ByteString)loReadconnection(LoFd!fd)!maxlen=withConnconnection$\c->dobuf<-mallocBytesmaxlenlen_<-c_lo_readcfdbuf(fromIntegralmaxlen)letlen=fromIntegrallen_iflen<0thendofreebufreturnNothingelsedobufre<-reallocBytesbuflenbuffp<-newForeignPtrfinalizerFreebufrereturn(Just(B.fromForeignPtrbuffp0len))-- | Changes the current read or write location associated with-- a large object descriptor. The return value is the new location-- pointer, or 'Nothing' on error.loSeek::Connection->LoFd->SeekMode->Int->IO(MaybeInt)loSeekconnection(LoFdfd)seekmodedelta=withConnconnection$\c->doletd=fromIntegraldeltapos<-c_lo_lseekcfdd$caseseekmodeofAbsoluteSeek->0{-# LINE 2172 "Database/PostgreSQL/LibPQ.hsc" #-}RelativeSeek->1{-# LINE 2173 "Database/PostgreSQL/LibPQ.hsc" #-}SeekFromEnd->2{-# LINE 2174 "Database/PostgreSQL/LibPQ.hsc" #-}return(nonnegIntpos)-- | Obtains the current read or write location of a large object descriptor.loTell::Connection->LoFd->IO(MaybeInt)loTellconnection(LoFdfd)=withConnconnection$\c->dononnegInt`fmap`c_lo_tellcfd-- | Truncates a large object to a given length. If the length is greater-- than the current large object, then the large object is extended with-- null bytes. ('\x00')---- The file offest is not changed.---- 'loTruncate' is new as of PostgreSQL 8.3; if this function is run against-- an older server version, it will fail and return 'Nothing'loTruncate::Connection->LoFd->Int->IO(Maybe())loTruncateconnection(LoFdfd)size=withConnconnection$\c->donegError`fmap`c_lo_truncatecfd(fromIntegralsize)-- | Closes a large object descriptor. Any large object descriptors that-- remain open at the end of a transaction will be closed automatically.loClose::Connection->LoFd->IO(Maybe())loCloseconnection(LoFdfd)=withConnconnection$\c->donegError`fmap`c_lo_closecfd-- | Removes a large object from the database.loUnlink::Connection->Oid->IO(Maybe())loUnlinkconnectionoid=withConnconnection$\c->donegError`fmap`c_lo_unlinkcoidforeignimportccall"libpq-fe.h PQconnectdb"c_PQconnectdb::CString->IO(PtrPGconn)foreignimportccall"libpq-fe.h PQconnectStart"c_PQconnectStart::CString->IO(PtrPGconn)foreignimportccall"libpq-fe.h PQconnectPoll"c_PQconnectPoll::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQdb"c_PQdb::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQuser"c_PQuser::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQpass"c_PQpass::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQhost"c_PQhost::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQport"c_PQport::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQoptions"c_PQoptions::PtrPGconn->IOCStringforeignimportccallunsafe"libpq-fe.h PQbackendPID"c_PQbackendPID::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQconnectionNeedsPassword"c_PQconnectionNeedsPassword::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQconnectionUsedPassword"c_PQconnectionUsedPassword::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQstatus"c_PQstatus::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQtransactionStatus"c_PQtransactionStatus::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQparameterStatus"c_PQparameterStatus::PtrPGconn->CString->IOCStringforeignimportccallunsafe"libpq-fe.h PQprotocolVersion"c_PQprotocolVersion::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQserverVersion"c_PQserverVersion::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQsocket"c_PQsocket::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQerrorMessage"c_PQerrorMessage::PtrPGconn->IOCString{-# LINE 2270 "Database/PostgreSQL/LibPQ.hsc" #-}foreignimportccall"libpq-fe.h PQfinish"c_PQfinish::PtrPGconn->IO(){-# LINE 2276 "Database/PostgreSQL/LibPQ.hsc" #-}foreignimportccall"libpq-fe.h PQreset"c_PQreset::PtrPGconn->IO()foreignimportccall"libpq-fe.h PQresetStart"c_PQresetStart::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQresetPoll"c_PQresetPoll::PtrPGconn->IOCIntforeignimportccallunsafe"libpq-fe.h PQclientEncoding"c_PQclientEncoding::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h pg_encoding_to_char"c_pg_encoding_to_char::CInt->IOCStringforeignimportccall"libpq-fe.h PQsetClientEncoding"c_PQsetClientEncoding::PtrPGconn->CString->IOCInttypePGVerbosity=CIntforeignimportccallunsafe"libpq-fe.h PQsetErrorVerbosity"c_PQsetErrorVerbosity::PtrPGconn->PGVerbosity->IOPGVerbosityforeignimportccall"libpq-fe.h PQsendQuery"c_PQsendQuery::PtrPGconn->CString->IOCIntforeignimportccall"libpq-fe.h PQsendQueryParams"c_PQsendQueryParams::PtrPGconn->CString->CInt->PtrOid->PtrCString->PtrCInt->PtrCInt->CInt->IOCIntforeignimportccall"libpq-fe.h PQsendPrepare"c_PQsendPrepare::PtrPGconn->CString->CString->CInt->PtrOid->IOCIntforeignimportccall"libpq-fe.h PQsendQueryPrepared"c_PQsendQueryPrepared::PtrPGconn->CString->CInt->PtrCString->PtrCInt->PtrCInt->CInt->IOCIntforeignimportccall"libpq-fe.h PQsendDescribePrepared"c_PQsendDescribePrepared::PtrPGconn->CString->IOCIntforeignimportccall"libpq-fe.h PQsendDescribePortal"c_PQsendDescribePortal::PtrPGconn->CString->IOCIntforeignimportccall"libpq-fe.h PQflush"c_PQflush::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQgetCancel"c_PQgetCancel::PtrPGconn->IO(PtrPGcancel)foreignimportccall"libpq-fe.h &PQfreeCancel"p_PQfreeCancel::FunPtr(PtrPGcancel->IO())foreignimportccall"libpq-fe.h PQcancel"c_PQcancel::PtrPGcancel->CString->CInt->IOCIntforeignimportccall"libpq-fe.h PQnotifies"c_PQnotifies::PtrPGconn->IO(PtrNotify)foreignimportccall"libpq-fe.h PQconsumeInput"c_PQconsumeInput::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQisBusy"c_PQisBusy::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQsetnonblocking"c_PQsetnonblocking::PtrPGconn->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQisnonblocking"c_PQisnonblocking::PtrPGconn->IOCIntforeignimportccall"libpq-fe.h PQgetResult"c_PQgetResult::PtrPGconn->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQexec"c_PQexec::PtrPGconn->CString->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQexecParams"c_PQexecParams::PtrPGconn->CString->CInt->PtrOid->PtrCString->PtrCInt->PtrCInt->CInt->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQprepare"c_PQprepare::PtrPGconn->CString->CString->CInt->PtrOid->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQexecPrepared"c_PQexecPrepared::PtrPGconn->CString->CInt->PtrCString->PtrCInt->PtrCInt->CInt->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQdescribePrepared"c_PQdescribePrepared::PtrPGconn->CString->IO(PtrPGresult)foreignimportccall"libpq-fe.h PQdescribePortal"c_PQdescribePortal::PtrPGconn->CString->IO(PtrPGresult)foreignimportccall"libpq-fe.h &PQclear"p_PQclear::FunPtr(PtrPGresult->IO())foreignimportccallunsafe"libpq-fe.h PQresultStatus"c_PQresultStatus::PtrPGresult->IOCIntforeignimportccallunsafe"libpq-fe.h PQresStatus"c_PQresStatus::CInt->IOCStringforeignimportccallunsafe"libpq-fe.h PQresultErrorMessage"c_PQresultErrorMessage::PtrPGresult->IOCStringforeignimportccall"libpq-fe.h PQresultErrorField"c_PQresultErrorField::PtrPGresult->CInt->IOCStringforeignimportccallunsafe"libpq-fe.h PQntuples"c_PQntuples::PtrPGresult->CIntforeignimportccallunsafe"libpq-fe.h PQnfields"c_PQnfields::PtrPGresult->CIntforeignimportccallunsafe"libpq-fe.h PQfname"c_PQfname::PtrPGresult->CInt->IOCStringforeignimportccall"libpq-fe.h PQfnumber"c_PQfnumber::PtrPGresult->CString->IOCIntforeignimportccallunsafe"libpq-fe.h PQftable"c_PQftable::PtrPGresult->CInt->IOOidforeignimportccallunsafe"libpq-fe.h PQftablecol"c_PQftablecol::PtrPGresult->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQfformat"c_PQfformat::PtrPGresult->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQftype"c_PQftype::PtrPGresult->CInt->IOOidforeignimportccallunsafe"libpq-fe.h PQfmod"c_PQfmod::PtrPGresult->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQfsize"c_PQfsize::PtrPGresult->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQgetvalue"c_PQgetvalue::PtrPGresult->CInt->CInt->IOCStringforeignimportccallunsafe"libpq-fe.h PQgetisnull"c_PQgetisnull::PtrPGresult->CInt->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQgetlength"c_PQgetlength::PtrPGresult->CInt->CInt->IOCIntforeignimportccallunsafe"libpq-fe.h PQnparams"c_PQnparams::PtrPGresult->IOCIntforeignimportccallunsafe"libpq-fe.h PQparamtype"c_PQparamtype::PtrPGresult->CInt->IOOidforeignimportccallunsafe"libpq-fe.h PQcmdStatus"c_PQcmdStatus::PtrPGresult->IOCStringforeignimportccallunsafe"libpq-fe.h PQcmdTuples"c_PQcmdTuples::PtrPGresult->IOCStringforeignimportccallunsafe"libpq-fe.h PQoidValue"c_PQoidValue::PtrPGresult->IOOidforeignimportccall"libpq-fe.h PQescapeStringConn"c_PQescapeStringConn::PtrPGconn->PtrWord8-- Actually (CString)->CString->CSize->PtrCInt->IOCSizeforeignimportccall"libpq-fe.h PQescapeByteaConn"c_PQescapeByteaConn::PtrPGconn->CString-- Actually (Ptr CUChar)->CSize->PtrCSize->IO(PtrWord8)-- Actually (IO (Ptr CUChar))foreignimportccall"libpq-fe.h PQunescapeBytea"c_PQunescapeBytea::CString-- Actually (Ptr CUChar)->PtrCSize->IO(PtrWord8)-- Actually (IO (Ptr CUChar))foreignimportccallunsafe"libpq-fe.h &PQfreemem"p_PQfreemem::FunPtr(Ptra->IO())foreignimportccallunsafe"libpq-fe.h PQfreemem"c_PQfreemem::Ptra->IO()typeCFd=CIntforeignimportccall"libpq-fs.h lo_creat"c_lo_creat::PtrPGconn->CInt->IOOidforeignimportccall"libpq-fs.h lo_create"c_lo_create::PtrPGconn->Oid->IOOidforeignimportccall"libpq-fs.h lo_import"c_lo_import::PtrPGconn->CString->IOOidforeignimportccall"libpq-fs.h lo_import_with_oid"c_lo_import_with_oid::PtrPGconn->CString->Oid->IOOidforeignimportccall"libpq-fs.h lo_export"c_lo_export::PtrPGconn->Oid->CString->IOCIntforeignimportccall"libpq-fs.h lo_open"c_lo_open::PtrPGconn->Oid->CInt->IOCFdforeignimportccall"libpq-fs.h lo_write"c_lo_write::PtrPGconn->CFd->CString->CSize->IOCIntforeignimportccall"libpq-fs.h lo_read"c_lo_read::PtrPGconn->CFd->PtrWord8->CSize->IOCIntforeignimportccall"libpq-fs.h lo_lseek"c_lo_lseek::PtrPGconn->CFd->CInt->CInt->IOCIntforeignimportccall"libpq-fs.h lo_tell"c_lo_tell::PtrPGconn->CFd->IOCIntforeignimportccall"libpq-fs.h lo_truncate"c_lo_truncate::PtrPGconn->CFd->CSize->IOCIntforeignimportccall"libpq-fs.h lo_close"c_lo_close::PtrPGconn->CFd->IOCIntforeignimportccall"libpq-fs.h lo_unlink"c_lo_unlink::PtrPGconn->Oid->IOCInt