0 | module Postgres.DB.Core
 1 |
 2 | import Postgres.FFI.Utility
 3 | import Postgres.Data.Conn
 4 | import Postgres.Data.ConnectionStatus
 5 |
 6 | --
 7 | -- Open Connection
 8 | --
 9 | %foreign libpq "PQconnectdb"
10 |          nLibpq "PQconnectdb"
11 | prim__dbOpen : String -> PrimIO (Ptr PGconn)
12 |
13 | ||| Open a connection to a Postgres database.
14 | ||| This connection must be closed using `pgClose`.
15 | |||
16 | ||| You can check the status of the connection
17 | ||| (including failure to connect) with the
18 | ||| `pgStatus` function.
19 | export
20 | pgOpen : HasIO io => (pgUrl: String) -> io Conn
21 | pgOpen url = (map MkConn (primIO $ prim__dbOpen url))
22 |
23 | --
24 | -- Close Connection
25 | --
26 | %foreign libpq "PQfinish"
27 |          nLibpq "PQfinish"
28 | prim__dbClose : Ptr PGconn -> PrimIO ()
29 |
30 | ||| Close a connection to a Postgres database.
31 | export
32 | pgClose : HasIO io => Conn -> io ()
33 | pgClose (MkConn conn) = primIO $ prim__dbClose conn
34 |                 
35 | --
36 | -- Get Connection Status
37 | --
38 | %foreign libpq "PQstatus"
39 |          nLibpq "PQstatus"
40 | prim__dbStatus : Ptr PGconn -> Int
41 |
42 | connectionStatus: Int -> ConnectionStatus
43 | connectionStatus i
44 |     = case i of
45 |         0 => OK
46 |         1 => BAD
47 |         2 => STARTED
48 |         3 => MADE
49 |         4 => AWAITING_RESPONSE
50 |         5 => AUTH_OK
51 |         6 => SETENV
52 |         7 => SSL_STARTUP
53 |         8 => NEEDED
54 |         _ => OTHER i
55 |
56 | ||| Get the status of a Postgres database connection.
57 | export
58 | pgStatus : Conn -> ConnectionStatus
59 | pgStatus (MkConn conn) = connectionStatus $ prim__dbStatus conn
60 |
61 | %foreign cHelper "connErrorMessage"
62 |          nLibpq "PQerrorMessage"
63 | prim__dbErrorMessage : Ptr PGconn -> PrimIO String
64 |
65 | ||| Get an error message from Postgres when something goes wrong.
66 | export
67 | pgErrorMessage : HasIO io => Conn -> io String
68 | pgErrorMessage (MkConn conn) = primIO $ prim__dbErrorMessage conn
69 |
70 | --
71 | -- Consume Input from Server
72 | --
73 |
74 | %foreign libpq "PQconsumeInput"
75 |          nLibpq "PQconsumeInput"
76 | prim__dbConsumeInput : Ptr PGconn -> PrimIO Int
77 |
78 | ||| Consume any input the server has delivered
79 | ||| since the last time we ran a command that
80 | ||| otherwise consumed server input.
81 | |||
82 | ||| It can be useful to explicitly call upon
83 | ||| `libpq` to consume input when doing something
84 | ||| like listening for notifications that does
85 | ||| not otherwise require making any calls to
86 | ||| execute anything on the server.
87 | |||
88 | ||| Returns True if successfuly and False
89 | ||| otherwise.
90 | export pgConsumeInput : Conn -> IO Bool
91 | pgConsumeInput (MkConn conn) = (map intToBool (primIO $ prim__dbConsumeInput conn))
92 |
93 |