-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | low-level binding to libpq
--   
--   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.
@package postgresql-libpq
@version 0.9.2.0


-- | This module exports the data constructor for the database connection
--   object so that people may create their own foreign bindings to libpq
--   functions that may not exist yet in vanilla postgresql-libpq.
module Database.PostgreSQL.LibPQ.Internal

-- | <a>Connection</a> encapsulates a connection to the backend.
data Connection
Conn :: {-# UNPACK #-} !(ForeignPtr PGconn) -> {-# UNPACK #-} !(MVar NoticeBuffer) -> Connection
withConn :: Connection -> (Ptr PGconn -> IO b) -> IO b
data PGconn
data CNoticeBuffer
type NoticeBuffer = Ptr CNoticeBuffer
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Internal.Connection


-- | 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
--   <a>finish</a> 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 <a>finish</a>ed connection.
--   
--   One possibility is to represent a connection in a higher-level
--   interface as <tt>MVar (Maybe Connection)</tt>, using <tt>Nothing</tt>
--   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.
module Database.PostgreSQL.LibPQ

-- | <a>Connection</a> encapsulates a connection to the backend.
data Connection

-- | 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
--   <a>connectStart</a> and <a>connectPoll</a>.
--   
--   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 :: ByteString -> IO Connection

-- | Make a connection to the database server in a nonblocking manner.
connectStart :: ByteString -> IO Connection

-- | If <a>connectStart</a> succeeds, the next stage is to poll libpq so
--   that it can proceed with the connection sequence. Use <a>socket</a> to
--   obtain the <a>Fd</a> of the socket underlying the database connection.
--   Loop thus: If <a>connectPoll</a> last returned <a>PollingReading</a>,
--   wait until the socket is ready to read (as indicated by select(),
--   poll(), or similar system function). Then call <a>connectPoll</a>
--   again. Conversely, if <a>connectPoll</a> last returned
--   <a>PollingWriting</a>, wait until the socket is ready to write, then
--   call <a>connectPoll</a> again. If you have yet to call
--   <a>connectPoll</a>, i.e., just after the call to <a>connectStart</a>,
--   behave as if it last returned <a>PollingWriting</a>. Continue this
--   loop until <a>connectPoll</a> returns <a>PollingFailed</a>, indicating
--   the connection procedure has failed, or <a>PollingOk</a>, indicating
--   the connection has been successfully made.
connectPoll :: Connection -> IO PollingStatus

-- | Allocate a Null Connection, which all libpq functions should safely
--   fail on.
newNullConnection :: IO Connection

-- | Test if a connection is the Null Connection.
isNullConnection :: Connection -> Bool

-- | 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 ()

-- | Reset the communication channel to the server, in a nonblocking
--   manner.
resetStart :: Connection -> IO Bool

-- | To initiate a connection reset, call <a>resetStart</a>. If it returns
--   <a>False</a>, the reset has failed. If it returns <a>True</a>, poll
--   the reset using <a>resetPoll</a> in exactly the same way as you would
--   create the connection using <a>connectPoll</a>.
resetPoll :: Connection -> IO PollingStatus
data PollingStatus
PollingFailed :: PollingStatus
PollingReading :: PollingStatus
PollingWriting :: PollingStatus
PollingOk :: PollingStatus

-- | Closes the connection to the server.
--   
--   Note that the <a>Connection</a> must not be used again after
--   <a>finish</a> has been called.
finish :: Connection -> IO ()

-- | Returns the database name of the connection.
db :: Connection -> IO (Maybe ByteString)

-- | Returns the user name of the connection.
user :: Connection -> IO (Maybe ByteString)

-- | Returns the password of the connection.
pass :: Connection -> IO (Maybe ByteString)

-- | Returns the server host name of the connection.
host :: Connection -> IO (Maybe ByteString)

-- | Returns the port of the connection.
port :: Connection -> IO (Maybe ByteString)

-- | Returns the command-line options passed in the connection request.
options :: Connection -> IO (Maybe ByteString)
data ConnStatus

-- | The <a>Connection</a> is ready.
ConnectionOk :: ConnStatus

-- | The connection procedure has failed.
ConnectionBad :: ConnStatus

-- | Waiting for connection to be made.
ConnectionStarted :: ConnStatus

-- | Connection OK; waiting to send.
ConnectionMade :: ConnStatus

-- | Waiting for a response from the server.
ConnectionAwaitingResponse :: ConnStatus

-- | Received authentication; waiting for backend start-up to finish.
ConnectionAuthOk :: ConnStatus

-- | Negotiating environment-driven parameter settings.
ConnectionSetEnv :: ConnStatus

-- | Negotiating SSL encryption.
ConnectionSSLStartup :: ConnStatus

-- | 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:
--   <a>ConnectionOk</a> and <a>ConnectionBad</a>. A good connection to the
--   database has the status <a>ConnectionOk</a>. A failed connection
--   attempt is signaled by status <a>ConnectionBad</a>. Ordinarily, an OK
--   status will remain so until <a>finish</a>, but a communications
--   failure might result in the status changing to <a>ConnectionBad</a>
--   prematurely. In that case the application could try to recover by
--   calling <a>reset</a>.
--   
--   See the entry for <a>connectStart</a> and <a>connectPoll</a> with
--   regards to other status codes that might be seen.
status :: Connection -> IO ConnStatus
data TransactionStatus

-- | currently idle
TransIdle :: TransactionStatus

-- | a command is in progress
TransActive :: TransactionStatus

-- | idle, in a valid transaction block
TransInTrans :: TransactionStatus

-- | idle, in a failed transaction block
TransInError :: TransactionStatus

-- | the connection is bad
TransUnknown :: TransactionStatus

-- | Returns the current in-transaction status of the server.
--   
--   <a>TransActive</a> is reported only when a query has been sent to the
--   server and not yet completed.
transactionStatus :: Connection -> IO TransactionStatus

-- | 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.
--   <a>parameterStatus</a> can be used to interrogate these settings. It
--   returns the current value of a parameter if known, or <a>Nothing</a>
--   if the parameter is not known.
parameterStatus :: Connection -> ByteString -> IO (Maybe ByteString)

-- | 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 -> IO Int

-- | 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 -> IO Int

-- | Returns the error message most recently generated by an operation on
--   the connection.
--   
--   Nearly all libpq functions will set a message for <a>errorMessage</a>
--   if they fail. Note that by libpq convention, a nonempty
--   <a>errorMessage</a> 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 <a>Connection</a>.
errorMessage :: Connection -> IO (Maybe ByteString)

-- | 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 (Maybe Fd)

-- | Returns the process <a>CPid</a> 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 -> IO CPid

-- | Returns <a>True</a> if the connection authentication method required a
--   password, but none was available. Returns <a>False</a> if not.
--   
--   This function can be applied after a failed connection attempt to
--   decide whether to prompt the user for a password.
connectionNeedsPassword :: Connection -> IO Bool

-- | Returns <a>True</a> if the connection authentication method used a
--   password. Returns <a>False</a> 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 -> IO Bool

-- | <a>Result</a> encapsulates the result of a query (or more precisely,
--   of a single SQL command --- a query string given to <a>sendQuery</a>
--   can contain multiple commands and thus return multiple instances of
--   <a>Result</a>.
data Result

-- | Submits a command to the server and waits for the result.
--   
--   Returns a <a>Result</a> or possibly <a>Nothing</a>. A <a>Result</a>
--   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 <a>Nothing</a> is returned, it should be treated like a
--   <a>FatalError</a> result. Use <a>errorMessage</a> 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
--   <a>exec</a> 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
--   <a>Result</a> 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 <a>Result</a> describes
--   the error condition.
exec :: Connection -> ByteString -> IO (Maybe Result)
data Format
Text :: Format
Binary :: Format
newtype Oid
Oid :: CUInt -> Oid
invalidOid :: Oid

-- | Submits a command to the server and waits for the result, with the
--   ability to pass parameters separately from the SQL command text.
--   
--   <a>execParams</a> is like <a>exec</a>, 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. <a>execParams</a> is supported only in protocol
--   3.0 and later connections; it will fail when using protocol 2.0.
--   
--   The primary advantage of <a>execParams</a> over <a>exec</a> is that
--   parameter values can be separated from the command string, thus
--   avoiding the need for tedious and error-prone quoting and escaping.
--   
--   Unlike <a>exec</a>, <a>execParams</a> 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 -> ByteString -> [Maybe (Oid, ByteString, Format)] -> Format -> IO (Maybe Result)

-- | Submits a request to create a prepared statement with the given
--   parameters, and waits for completion.
--   
--   <a>prepare</a> creates a prepared statement for later execution with
--   <a>execPrepared</a>. This feature allows commands that will be used
--   repeatedly to be parsed and planned just once, rather than each time
--   they are executed. <a>prepare</a> 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 <a>Oid</a>, the data types to be
--   assigned to the parameter symbols. If paramTypes is <a>Nothing</a>, 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 <a>describePrepared</a> for a
--   means to find out what data types were inferred.)
--   
--   As with <a>exec</a>, the result is normally a <a>Result</a> whose
--   contents indicate server-side success or failure. A <a>Nothing</a>
--   result indicates out-of-memory or inability to send the command at
--   all. Use <a>errorMessage</a> to get more information about such
--   errors.
--   
--   Prepared statements for use with <a>execPrepared</a> can also be
--   created by executing SQL PREPARE statements. (But <a>prepare</a> 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 -> ByteString -> ByteString -> Maybe [Oid] -> IO (Maybe Result)

-- | Sends a request to execute a prepared statement with given parameters,
--   and waits for the result.
--   
--   <a>execPrepared</a> is like <a>execParams</a>, 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. <a>execPrepared</a> is
--   supported only in protocol 3.0 and later connections; it will fail
--   when using protocol 2.0.
--   
--   The parameters are identical to <a>execParams</a>, 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 -> ByteString -> [Maybe (ByteString, Format)] -> Format -> IO (Maybe Result)

-- | Submits a request to obtain information about the specified prepared
--   statement, and waits for completion.
--   
--   <a>describePrepared</a> allows an application to obtain information
--   about a previously prepared statement. <a>describePrepared</a> 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
--   <a>Result</a> with status <a>CommandOk</a> is returned. The functions
--   <a>nparams</a> and <a>paramtype</a> can be applied to this
--   <a>Result</a> to obtain information about the parameters of the
--   prepared statement, and the functions <a>nfields</a>, <a>fname</a>,
--   <a>ftype</a>, etc provide information about the result columns (if
--   any) of the statement.
describePrepared :: Connection -> ByteString -> IO (Maybe Result)

-- | Submits a request to obtain information about the specified portal,
--   and waits for completion.
--   
--   <a>describePortal</a> 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.)
--   <a>describePortal</a> 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 <a>Result</a>
--   with status <a>CommandOk</a> is returned. The functions
--   <a>nfields</a>, <a>fname</a>, <a>ftype</a>, etc can be applied to the
--   <a>Result</a> to obtain information about the result columns (if any)
--   of the portal.
describePortal :: Connection -> ByteString -> IO (Maybe Result)
data ExecStatus

-- | The string sent to the server was empty.
EmptyQuery :: ExecStatus

-- | Successful completion of a command returning no data.
CommandOk :: ExecStatus

-- | Successful completion of a command returning data (such as a SELECT or
--   SHOW).
TuplesOk :: ExecStatus

-- | Copy Out (from server) data transfer started.
CopyOut :: ExecStatus

-- | Copy In (to server) data transfer started.
CopyIn :: ExecStatus

-- | The server's response was not understood.
BadResponse :: ExecStatus

-- | A nonfatal error (a notice or warning) occurred.
NonfatalError :: ExecStatus

-- | A fatal error occurred.
FatalError :: ExecStatus

-- | The PGresult contains a single result tuple from the current command.
--   This status occurs only when single-row mode has been selected for the
--   query.
SingleTuple :: ExecStatus

-- | Returns the result status of the command.
resultStatus :: Result -> IO ExecStatus

-- | Converts the <a>ExecStatus</a> returned by <a>resultStatus</a> into a
--   string describing the status code. The caller should not free the
--   result.
resStatus :: ExecStatus -> IO ByteString

-- | Returns the error message most recently generated by an operation on
--   the connection.
resultErrorMessage :: Result -> IO (Maybe ByteString)
data FieldCode

-- | 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.
DiagSeverity :: FieldCode

-- | 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.
DiagSqlstate :: FieldCode

-- | The primary human-readable error message (typically one line). Always
--   present.
DiagMessagePrimary :: FieldCode

-- | Detail: an optional secondary error message carrying more detail about
--   the problem. Might run to multiple lines.
DiagMessageDetail :: FieldCode

-- | 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.
DiagMessageHint :: FieldCode

-- | 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.
DiagStatementPosition :: FieldCode

-- | This is defined the same as the <a>DiagStatementPosition</a> field,
--   but it is used when the cursor position refers to an internally
--   generated command rather than the one submitted by the client. The
--   <a>DiagInternalQuery</a> field will always appear when this field
--   appears.
DiagInternalPosition :: FieldCode

-- | The text of a failed internally-generated command. This could be, for
--   example, a SQL query issued by a PL/pgSQL function.
DiagInternalQuery :: FieldCode

-- | 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.
DiagContext :: FieldCode

-- | The file name of the source-code location where the error was
--   reported.
DiagSourceFile :: FieldCode

-- | The line number of the source-code location where the error was
--   reported.
DiagSourceLine :: FieldCode

-- | The name of the source-code function reporting the error.
DiagSourceFunction :: FieldCode

-- | Returns an individual field of an error report.
--   
--   fieldcode is an error field identifier; see the symbols listed below.
--   <a>Nothing</a> 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 <a>Result</a> objects,
--   not <a>Connection</a> objects; there is no errorField function.
resultErrorField :: Result -> FieldCode -> IO (Maybe ByteString)

-- | 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 <a>getvalue</a>, 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 ()

-- | 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 -> IO Row

-- | Returns the number of columns (fields) in each row of the query
--   result.
nfields :: Result -> IO Column
newtype Row
Row :: CInt -> Row
newtype Column
Col :: CInt -> Column
toRow :: (Integral a) => a -> Row
toColumn :: (Integral a) => a -> Column

-- | Returns the column name associated with the given <a>Column</a>
--   number. Column numbers start at 0.
fname :: Result -> Column -> IO (Maybe ByteString)

-- | Returns the column number associated with the given column name.
fnumber :: Result -> ByteString -> IO (Maybe Column)

-- | Returns the OID of the table from which the given column was fetched.
--   Column numbers start at 0.
ftable :: Result -> Column -> IO Oid

-- | 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 -> IO Column

-- | Returns the <a>Format</a> of the given column. Column numbers start at
--   0.
fformat :: Result -> Column -> IO Format

-- | Returns the data type associated with the given column number. The
--   <a>Oid</a> 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<i>include</i>catalog/pg_type.h in
--   the source tree.
ftype :: Result -> Column -> IO Oid

-- | 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 -> IO Int

-- | Returns the size in bytes of the column associated with the given
--   column number. Column numbers start at 0.
--   
--   <a>fsize</a> 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 -> IO Int

-- | Returns a single field value of one row of a PGresult. Row and column
--   numbers start at 0.
--   
--   For convenience, this binding uses <a>getisnull</a> and
--   <a>getlength</a> to help construct the result.
--   
--   Note: The <tt>ByteString</tt> returned holds a reference to the
--   Result. As long as ByteString is live, the Result will not be garbage
--   collected. <a>getvalue'</a> returns a copy of the data.
getvalue :: Result -> Row -> Column -> IO (Maybe ByteString)

-- | 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 <a>getisnull</a> and
--   <a>getlength</a> to help construct the result.
getvalue' :: Result -> Row -> Column -> IO (Maybe ByteString)

-- | Tests a field for a null value. Row and column numbers start at 0.
getisnull :: Result -> Row -> Column -> IO Bool

-- | 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 <a>getvalue</a>. For text data
--   format this is the same as strlen(). For binary format this is
--   essential information. Note that one should not rely on <a>fsize</a>
--   to obtain the actual data length.
getlength :: Result -> Row -> Column -> IO Int

-- | 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 -> IO Int

-- | Returns the data type of the indicated statement parameter. Parameter
--   numbers start at 0.
--   
--   This function is only useful when inspecting the result of
--   <a>describePrepared</a>. For other types of queries it will return
--   zero.
paramtype :: Result -> Int -> IO Oid

-- | 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 (Maybe ByteString)

-- | 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 <a>Result</a>. 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 <a>Result</a> was
--   anything else, <a>cmdTuples</a> returns an empty string.
cmdTuples :: Result -> IO (Maybe ByteString)

-- | 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 -> ByteString -> IO (Maybe ByteString)

-- | Escapes binary data for use within an SQL command with the type bytea.
--   As with <a>escapeStringConn</a>, this is only used when inserting data
--   directly into an SQL command string.
escapeByteaConn :: Connection -> ByteString -> IO (Maybe ByteString)

-- | Converts a <tt>ByteString</tt> representation of binary data into
--   binary data - the reverse of <tt>PQescapeByteaConn</tt>. 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
--   <a>getvalue</a> when applied to a bytea column. <a>unescapeBytea</a>
--   converts this string representation into its binary representation. It
--   returns a <tt>ByteString</tt>, or <a>Nothing</a> on error.
--   
--   This conversion is not exactly the inverse of <a>escapeByteaConn</a>,
--   because the string is not expected to be "escaped" when received from
--   <a>getvalue</a>. In particular this means there is no need for string
--   quoting considerations, and so no need for a <a>Connection</a>
--   parameter.
unescapeBytea :: ByteString -> IO (Maybe ByteString)

-- | <tt>escapeIdentifier</tt> escapes a string for use as an SQL
--   identifier, such as a table, column, or function name. This is useful
--   when a user-supplied identifier might contain special characters that
--   would otherwise not be interpreted as part of the identifier by the
--   SQL parser, or when the identifier might contain upper case characters
--   whose case should be preserved.
--   
--   The return string has all special characters replaced so that it will
--   be properly processed as an SQL identifier. The return string will
--   also be surrounded by double quotes.
--   
--   On error, <tt>escapeIdentifier</tt> returns <a>Nothing</a> and a
--   suitable message is stored in the conn object.
escapeIdentifier :: Connection -> ByteString -> IO (Maybe ByteString)
data CopyInResult

-- | The data was sent.
CopyInOk :: CopyInResult

-- | An error occurred (use <a>errorMessage</a> to retrieve details).
CopyInError :: CopyInResult

-- | The data was not sent because the attempt would block (this case is
--   only possible if the connection is in nonblocking mode) Wait for
--   write-ready (e.g. by using <a>threadWaitWrite</a> on the
--   <a>socket</a>) and try again.
CopyInWouldBlock :: CopyInResult

-- | Send raw <tt>COPY</tt> data to the server during the <a>CopyIn</a>
--   state.
putCopyData :: Connection -> ByteString -> IO CopyInResult

-- | Send end-of-data indication to the server during the <a>CopyIn</a>
--   state.
--   
--   <ul>
--   <li><tt>putCopyEnd conn Nothing</tt> ends the <a>CopyIn</a> operation
--   successfully.</li>
--   <li><tt>putCopyEnd conn (Just errormsg)</tt> forces the <tt>COPY</tt>
--   to fail, with <tt>errormsg</tt> used as the error message.</li>
--   </ul>
--   
--   After <a>putCopyEnd</a> returns <tt>CopyOk</tt>, call <a>getResult</a>
--   to obtain the final result status of the <tt>COPY</tt> command. Then
--   return to normal operation.
putCopyEnd :: Connection -> Maybe ByteString -> IO CopyInResult
data CopyOutResult

-- | Data representing a single row of the result
CopyOutRow :: !ByteString -> CopyOutResult

-- | A complete row is not yet available. This case is only possible when
--   <a>getCopyData</a> is has the async parameter set to <a>True</a>.
CopyOutWouldBlock :: CopyOutResult

-- | No more rows are available
CopyOutDone :: CopyOutResult

-- | An error occurred (e.g. the connection is not in the <a>CopyOut</a>
--   state). Call <a>errorMessage</a> for more information.
CopyOutError :: CopyOutResult

-- | Receive raw <tt>COPY</tt> data from the server during the
--   <a>CopyOut</a> state. The boolean parameter determines whether or not
--   the call will block while waiting for data.
getCopyData :: Connection -> Bool -> IO CopyOutResult

-- | Submits a command to the server without waiting for the result(s).
--   <a>True</a> is returned if the command was successfully dispatched and
--   <a>False</a> if not (in which case, use <a>errorMessage</a> to get
--   more information about the failure).
sendQuery :: Connection -> ByteString -> IO Bool

-- | Submits a command and separate parameters to the server without
--   waiting for the result(s).
sendQueryParams :: Connection -> ByteString -> [Maybe (Oid, ByteString, Format)] -> Format -> IO Bool

-- | Sends a request to create a prepared statement with the given
--   parameters, without waiting for completion.
sendPrepare :: Connection -> ByteString -> ByteString -> Maybe [Oid] -> IO Bool

-- | Sends a request to execute a prepared statement with given parameters,
--   without waiting for the result(s).
sendQueryPrepared :: Connection -> ByteString -> [Maybe (ByteString, Format)] -> Format -> IO Bool

-- | Submits a request to obtain information about the specified prepared
--   statement, without waiting for completion.
--   
--   This is an asynchronous version of <a>describePrepared</a>: it returns
--   <a>True</a> if it was able to dispatch the request, and <a>False</a>
--   if not. After a successful call, call <a>getResult</a> to obtain the
--   results. The function's parameters are handled identically to
--   <a>describePrepared</a>. Like <a>describePrepared</a>, it will not
--   work on 2.0-protocol connections.
sendDescribePrepared :: Connection -> ByteString -> IO Bool

-- | Submits a request to obtain information about the specified portal,
--   without waiting for completion.
--   
--   This is an asynchronous version of <a>describePortal</a>: it returns
--   <a>True</a> if it was able to dispatch the request, and <a>False</a>
--   if not. After a successful call, call <a>getResult</a> to obtain the
--   results. The function's parameters are handled identically to
--   <a>describePortal</a>. Like <a>describePortal</a>, it will not work on
--   2.0-protocol connections.
sendDescribePortal :: Connection -> ByteString -> IO Bool

-- | Waits for the next result from a prior <a>sendQuery</a>,
--   <a>sendQueryParams</a>, <a>sendPrepare</a>, or
--   <a>sendQueryPrepared</a> call, and returns it. A null pointer is
--   returned when the command is complete and there will be no more
--   results.
getResult :: Connection -> IO (Maybe Result)

-- | If input is available from the server, consume it.
--   
--   <a>consumeInput</a> normally returns <a>True</a> indicating "no
--   error", but returns <a>False</a> if there was some kind of trouble (in
--   which case <a>errorMessage</a> can be consulted). Note that the result
--   does not say whether any input data was actually collected. After
--   calling <a>consumeInput</a>, the application can check <a>isBusy</a>
--   and/or <a>notifies</a> to see if their state has changed.
consumeInput :: Connection -> IO Bool

-- | 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.
--   
--   <a>isBusy</a> will not itself attempt to read data from the server;
--   therefore <a>consumeInput</a> must be invoked first, or the busy state
--   will never end.
isBusy :: Connection -> IO Bool

-- | Sets the nonblocking status of the connection.
setnonblocking :: Connection -> Bool -> IO Bool

-- | Returns the blocking status of the database connection.
isnonblocking :: Connection -> IO Bool

-- | Select single-row mode for the currently-executing query.
--   
--   This function can only be called immediately after PQsendQuery or one
--   of its sibling functions, before any other operation on the connection
--   such as PQconsumeInput or PQgetResult. If called at the correct time,
--   the function activates single-row mode for the current query and
--   returns 1. Otherwise the mode stays unchanged and the function returns
--   0. In any case, the mode reverts to normal after completion of the
--   current query.
setSingleRowMode :: Connection -> IO Bool
data FlushStatus
FlushOk :: FlushStatus
FlushFailed :: FlushStatus
FlushWriting :: FlushStatus

-- | Attempts to flush any queued output data to the server. Returns
--   <a>FlushOk</a> if successful (or if the send queue is empty),
--   <a>FlushFailed</a> if it failed for some reason, or
--   <a>FlushWriting</a> 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 -> IO FlushStatus

-- | Contains the information needed to cancel a command issued through a
--   particular database connection.
data Cancel

-- | Creates a data structure containing the information needed to cancel a
--   command issued through a particular database connection.
--   
--   <a>getCancel</a> creates a <a>Cancel</a> object given a
--   <a>Connection</a>. It will return <a>Nothing</a> if the given conn is
--   an invalid connection.
getCancel :: Connection -> IO (Maybe Cancel)

-- | 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 (Either ByteString ())
data Notify
Notify :: {-# UNPACK #-} !ByteString -> {-# UNPACK #-} !CPid -> {-# UNPACK #-} !ByteString -> Notify

-- | notification channel name
[notifyRelname] :: Notify -> {-# UNPACK #-} !ByteString

-- | process ID of notifying server process
[notifyBePid] :: Notify -> {-# UNPACK #-} !CPid

-- | notification payload string
[notifyExtra] :: Notify -> {-# UNPACK #-} !ByteString

-- | Returns the next notification from a list of unhandled notification
--   messages received from the server. It returns a <a>Nothing</a> 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 (Maybe Notify)

-- | Returns the client encoding.
clientEncoding :: Connection -> IO ByteString

-- | Sets the client encoding.
setClientEncoding :: Connection -> ByteString -> IO Bool
data Verbosity
ErrorsTerse :: Verbosity
ErrorsDefault :: Verbosity
ErrorsVerbose :: Verbosity

-- | Determines the verbosity of messages returned by <a>errorMessage</a>
--   and <a>resultErrorMessage</a>.
--   
--   <a>setErrorVerbosity</a> sets the verbosity mode, returning the
--   connection's previous setting. In <a>ErrorsTerse</a> 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 <a>ErrorsVerbose</a> mode includes all
--   available fields. Changing the verbosity does not affect the messages
--   available from already-existing <a>Result</a> objects, only
--   subsequently-created ones.
setErrorVerbosity :: Connection -> Verbosity -> IO Verbosity

-- | Upon connection initialization, any notices received from the server
--   are normally written to the console. Notices are akin to warnings, and
--   are distinct from notifications. This function suppresses notices. You
--   may later call <a>enableNoticeReporting</a> after calling this
--   function.
disableNoticeReporting :: Connection -> IO ()

-- | Upon connection initialization, any notices received from the server
--   are normally written to the console. Notices are akin to warnings, and
--   are distinct from notifications. This function enables notices to be
--   programmatically retreived using the <a>getNotice</a> function. You
--   may later call <a>disableNoticeReporting</a> after calling this
--   function.
enableNoticeReporting :: Connection -> IO ()

-- | This function retrieves any notices received from the backend. Because
--   multiple notices can be received at a time, you will typically want to
--   call this function in a loop until you get back a <a>Nothing</a>.
getNotice :: Connection -> IO (Maybe ByteString)

-- | LoFd is a Large Object (pseudo) File Descriptor. It is understood by
--   libpq but not by operating system calls.
newtype LoFd
LoFd :: CInt -> LoFd

-- | Creates a new large object, returns the Object ID of the newly created
--   object.
loCreat :: Connection -> IO (Maybe Oid)

-- | Creates a new large object with a particular Object ID. Returns
--   <a>Nothing</a> if the requested Object ID is already in use by some
--   other large object or other failure. If <a>invalidOid</a> is used as a
--   parameter, then <a>loCreate</a> will assign an unused <a>Oid</a>.
loCreate :: Connection -> Oid -> IO (Maybe Oid)

-- | 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 (Maybe Oid)

-- | Imports an operating system file as a large object with the given
--   Object ID. Combines the behavior of <a>loImport</a> and
--   <a>loCreate</a>
loImportWithOid :: Connection -> FilePath -> Oid -> IO (Maybe Oid)

-- | 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, <a>Nothing</a> on failure.
loExport :: Connection -> Oid -> FilePath -> IO (Maybe ())

-- | 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 <a>loRead</a>, <a>loWrite</a>, <a>loSeek</a>, <a>loTell</a>,
--   and <a>loClose</a>. The descriptor is only valid for the duration of
--   the current transation. On failure, <a>Nothing</a> is returned.
--   
--   The server currently does not distinguish between <a>WriteMode</a> and
--   <a>ReadWriteMode</a>; write-only modes are not enforced. However there
--   is a significant difference between <a>ReadMode</a> and the other
--   modes: with <a>ReadMode</a> 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
--   <a>loOpen</a> was executed, regardless of later writes by this or
--   other transactions. Reading from a descriptor opened in
--   <a>WriteMode</a>, <a>ReadWriteMode</a>, or <a>AppendMode</a> 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 <tt>REPEATABLE READ</tt> versus <tt>READ COMMITTED</tt>
--   transaction modes for ordinary SQL <tt>SELECT</tt> commands.
loOpen :: Connection -> Oid -> IOMode -> IO (Maybe LoFd)

-- | <tt>loWrite conn fd buf</tt> writes the bytestring <tt>buf</tt> to the
--   large object descriptor <tt>fd</tt>. The number of bytes actually
--   written is returned. In the event of an error, <a>Nothing</a> is
--   returned.
loWrite :: Connection -> LoFd -> ByteString -> IO (Maybe Int)

-- | <tt>loRead conn fd len</tt> reads up to <tt>len</tt> bytes from the
--   large object descriptor <tt>fd</tt>. In the event of an error,
--   <a>Nothing</a> is returned.
loRead :: Connection -> LoFd -> Int -> IO (Maybe ByteString)

-- | Changes the current read or write location associated with a large
--   object descriptor. The return value is the new location pointer, or
--   <a>Nothing</a> on error.
loSeek :: Connection -> LoFd -> SeekMode -> Int -> IO (Maybe Int)

-- | Obtains the current read or write location of a large object
--   descriptor.
loTell :: Connection -> LoFd -> IO (Maybe Int)

-- | 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.
--   
--   <a>loTruncate</a> is new as of PostgreSQL 8.3; if this function is run
--   against an older server version, it will fail and return
--   <a>Nothing</a>
loTruncate :: Connection -> LoFd -> Int -> IO (Maybe ())

-- | 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 ())

-- | Removes a large object from the database.
loUnlink :: Connection -> Oid -> IO (Maybe ())
instance GHC.Show.Show Database.PostgreSQL.LibPQ.LoFd
instance GHC.Classes.Ord Database.PostgreSQL.LibPQ.LoFd
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.LoFd
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Verbosity
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Verbosity
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Notify
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Cancel
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Cancel
instance GHC.Show.Show Database.PostgreSQL.LibPQ.FlushStatus
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.FlushStatus
instance GHC.Show.Show Database.PostgreSQL.LibPQ.CopyOutResult
instance GHC.Show.Show Database.PostgreSQL.LibPQ.CopyInResult
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.CopyInResult
instance GHC.Num.Num Database.PostgreSQL.LibPQ.Row
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.Row
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Row
instance GHC.Classes.Ord Database.PostgreSQL.LibPQ.Row
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Row
instance GHC.Num.Num Database.PostgreSQL.LibPQ.Column
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.Column
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Column
instance GHC.Classes.Ord Database.PostgreSQL.LibPQ.Column
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Column
instance GHC.Show.Show Database.PostgreSQL.LibPQ.FieldCode
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.FieldCode
instance GHC.Show.Show Database.PostgreSQL.LibPQ.ExecStatus
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.ExecStatus
instance Foreign.Storable.Storable Database.PostgreSQL.LibPQ.Oid
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Oid
instance GHC.Read.Read Database.PostgreSQL.LibPQ.Oid
instance GHC.Classes.Ord Database.PostgreSQL.LibPQ.Oid
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Oid
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.Format
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Format
instance GHC.Classes.Ord Database.PostgreSQL.LibPQ.Format
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Format
instance GHC.Show.Show Database.PostgreSQL.LibPQ.Result
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.Result
instance GHC.Show.Show Database.PostgreSQL.LibPQ.TransactionStatus
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.TransactionStatus
instance GHC.Show.Show Database.PostgreSQL.LibPQ.ConnStatus
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.ConnStatus
instance GHC.Show.Show Database.PostgreSQL.LibPQ.PollingStatus
instance GHC.Classes.Eq Database.PostgreSQL.LibPQ.PollingStatus
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.ExecStatus
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.FieldCode
instance Foreign.Storable.Storable Database.PostgreSQL.LibPQ.Notify
instance GHC.Enum.Enum Database.PostgreSQL.LibPQ.Verbosity
