README 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. Erlang PostgreSQL Database Client
  2. Asynchronous fork of https://github.com/wg/epgsql
  3. Difference highlights (see CHANGES for full list):
  4. + 3 API sets: pgsql, apgsql and ipgsql:
  5. pgsql maintains backwards compatibility with original driver API,
  6. apgsql delivers complete results as regular erlang messages,
  7. ipgsql delivers results as messages incrementally (row by row)
  8. + internal queue of client requests, so you don't need to wait for response to send next request
  9. + single process to hold driver state and receive socket data
  10. + execute several prepared statements as a batch
  11. + bind timestamps in erlang:now() format
  12. * Known problems
  13. Timeout supplied at connect time works as socket connect timeout not query timeout. It passes all tests from original driver except 3 timeout tests.
  14. SSL performance can degrade if driver process has large inbox (thousands of messages).
  15. * Connect
  16. {ok, C} = pgsql:connect(Host, [Username], [Password], Opts).
  17. Host - host to connect to.
  18. Username - username to connect as, defaults to $USER.
  19. Password - optional password to authenticate with.
  20. Opts - property list of extra options. Supported properties:
  21. + {database, String}
  22. + {port, Integer}
  23. + {ssl, Atom} true | false | required
  24. + {ssl_opts, List} see ssl application docs in OTP
  25. + {timeout, Integer} milliseconds, defaults to 5000
  26. + {async, Pid} see Server Notifications section
  27. {ok, C} = pgsql:connect("localhost", "username", [{database, "test_db"}]).
  28. ok = pgsql:close(C).
  29. The timeout parameter will trigger an {error, timeout} result when the
  30. socket fails to connect within Timeout milliseconds.
  31. Asynchronous connect example (applies to ipgsql too):
  32. {ok, C} = apgsql:start_link(),
  33. Ref = apgsql:connect(C, "localhost", "username", [{database, "test_db"}]),
  34. receive
  35. {C, Ref, connected} ->
  36. {ok, C};
  37. {C, Ref, Error = {error, _}} ->
  38. Error;
  39. {'EXIT', C, _Reason} ->
  40. {error, closed}
  41. end.
  42. * Simple Query
  43. {ok, Columns, Rows} = pgsql:squery(C, "select ...").
  44. {ok, Count} = pgsql:squery(C, "update ...").
  45. {ok, Count, Columns, Rows} = pgsql:squery(C, "insert ... returning ...").
  46. {error, Error} = pgsql:squery(C, "invalid SQL").
  47. Columns - list of column records, see pgsql.hrl for definition.
  48. Rows - list of tuples, one for each row.
  49. Count - integer count of rows inserted/updated/etc
  50. The simple query protocol returns all columns as text (Erlang binaries)
  51. and does not support binding parameters.
  52. Several queries separated by semicolon can be executed by squery.
  53. [{ok, _, [{<<"1">>}]}, {ok, _, [{<<"2">>}]}] =
  54. pgsql:squery(C, "select 1; select 2").
  55. apgsql:squery returns result as a single message:
  56. Ref = apgsql:squery(C, Sql),
  57. receive
  58. {C, Ref, Result} -> Result
  59. end.
  60. Result has same format as return value of pgsql:squery.
  61. ipgsql:squery returns result incrementally for each query inside Sql and
  62. for each row:
  63. Ref = ipgsql:squery(C, Sql),
  64. receive
  65. {C, Ref, {columns, Columns}} ->
  66. %% columns description
  67. Columns;
  68. {C, Ref, {data, Row}} ->
  69. %% single data row
  70. Row;
  71. {C, Ref, {error, _E} = Error} ->
  72. Error;
  73. {C, Ref, {complete, {_Type, Count}}} ->
  74. %% execution of one insert/update/delete has finished
  75. {ok, Count}; % affected rows count
  76. {C, Ref, {complete, _Type}} ->
  77. %% execution of one select has finished
  78. ok;
  79. {C, Ref, done} ->
  80. %% execution of all queries from Sql has finished
  81. done;
  82. end.
  83. * Extended Query
  84. {ok, Columns, Rows} = pgsql:equery(C, "select ...", [Parameters]).
  85. {ok, Count} = pgsql:equery(C, "update ...", [Parameters]).
  86. {ok, Count, Columns, Rows} = pgsql:equery(C, "insert ... returning ...", [Parameters]).
  87. {error, Error} = pgsql:equery(C, "invalid SQL", [Parameters]).
  88. Parameters - optional list of values to be bound to $1, $2, $3, etc.
  89. The extended query protocol combines parse, bind, and execute using
  90. the unnamed prepared statement and portal. A "select" statement returns
  91. {ok, Columns, Rows}, "insert/update/delete" returns {ok, Count} or
  92. {ok, Count, Columns, Rows} when a "returning" clause is present. When
  93. an error occurs, all statements result in {error, #error{}}.
  94. PostgreSQL's binary format is used to return integers as Erlang
  95. integers, floats as floats, bytea/text/varchar columns as binaries,
  96. bools as true/false, etc. For details see pgsql_binary.erl and the
  97. Data Representation section below.
  98. Ref = apgsql:equery(C, Sql, [Parameters]),
  99. receive
  100. {C, Ref, Res} -> Res
  101. end.
  102. Res has same format as return value of pgsql:equery.
  103. ipgsql:equery(C, Sql, [Parameters]) sends same set of messages as squery
  104. including final {C, Ref, done}.
  105. * Parse/Bind/Execute
  106. {ok, Statement} = pgsql:parse(C, [StatementName], Sql, [ParameterTypes]).
  107. StatementName - optional, reusable, name for the prepared statement.
  108. ParameterTypes - optional list of PostgreSQL types for each parameter.
  109. For valid type names see pgsql_types.erl.
  110. apgsql:parse sends {C, Ref, {ok, Statement} | {error, Reason}}.
  111. ipgsql:parse sends:
  112. {C, Ref, {types, Types}}
  113. {C, Ref, {columns, Columns}}
  114. {C, Ref, no_data} if statement will not return rows
  115. {C, Ref, {error, Reason}}
  116. ok = pgsql:bind(C, Statement, [PortalName], ParameterValues).
  117. PortalName - optional name for the result portal.
  118. both apgsql:bind and ipgsql:bind send {C, Ref, ok | {error, Reason}}
  119. {ok | partial, Rows} = pgsql:execute(C, Statement, [PortalName], [MaxRows]).
  120. {ok, Count} = pgsql:execute(C, Statement, [PortalName]).
  121. {ok, Count, Rows} = pgsql:execute(C, Statement, [PortalName]).
  122. PortalName - optional portal name used in bind/4.
  123. MaxRows - maximum number of rows to return (0 for all rows).
  124. execute returns {partial, Rows} when more rows are available.
  125. apgsql:execute sends {C, Ref, Result} where Result has same format as
  126. return value of pgsql:execute.
  127. ipgsql:execute sends
  128. {C, Ref, {data, Row}}
  129. {C, Ref, {error, Reason}}
  130. {C, Ref, suspended} partial result was sent, more rows are available
  131. {C, Ref, {complete, {_Type, Count}}}
  132. {C, Ref, {complete, _Type}}
  133. ok = pgsql:close(C, Statement).
  134. ok = pgsql:close(C, statement | portal, Name).
  135. ok = pgsql:sync(C).
  136. All pgsql functions return {error, Error} when an error occurs.
  137. apgsql and ipgsql close and sync functions send {C, Ref, ok}.
  138. * Batch execution
  139. Batch execution is bind + execute for several prepared statements.
  140. It uses unnamed portals and MaxRows = 0.
  141. Results = pgsql:execute_batch(C, Batch).
  142. Batch - list of {Statement, ParameterValues}
  143. Results - list of {ok, Count} or {ok, Count, Rows}
  144. Example
  145. {ok, S1} = pgsql:parse(C, "one", "select $1", [int4]),
  146. {ok, S2} = pgsql:parse(C, "two", "select $1 + $2", [int4, int4]),
  147. [{ok, [{1}]}, {ok, [{3}]}] =
  148. pgsql:execute_batch(C, [{S1, [1]}, {S2, [1, 2]}]).
  149. apgsql:execute_batch sends {C, Ref, Results}
  150. ipgsql:execute_batch sends
  151. {C, Ref, {data, Row}}
  152. {C, Ref, {error, Reason}}
  153. {C, Ref, {complete, {_Type, Count}}}
  154. {C, Ref, {complete, _Type}}
  155. {C, Ref, done} - execution of all queries from Batch has finished
  156. * Data Representation
  157. null = null
  158. bool = true | false
  159. char = $A | binary
  160. intX = 1
  161. floatX = 1.0
  162. date = {Year, Month, Day}
  163. time = {Hour, Minute, Second.Microsecond}
  164. timetz = {time, Timezone}
  165. timestamp = {date, time}
  166. timestamptz = {date, time}
  167. interval = {time, Days, Months}
  168. text = <<"a">>
  169. varchar = <<"a">>
  170. bytea = <<1, 2>>
  171. array = [1, 2, 3]
  172. record = {int2, time, text, ...} (decode only)
  173. timestamp and timestamptz parameters can take erlang:now() format {MegaSeconds, Seconds, MicroSeconds}
  174. * Errors
  175. Errors originating from the PostgreSQL backend are returned as {error, #error{}},
  176. see pgsql.hrl for the record definition. epgsql functions may also return
  177. {error, What} where What is one of the following:
  178. {unsupported_auth_method, Method} - required auth method is unsupported
  179. timeout - request timed out
  180. closed - connection was closed
  181. sync_required - error occured and pgsql:sync must be called
  182. * Server Notifications
  183. PostgreSQL may deliver two types of asynchronous message: "notices" in response
  184. to notice and warning messages generated by the server, and "notifications" which
  185. are generated by the LISTEN/NOTIFY mechanism.
  186. Passing the {async, Pid} option to pgsql:connect will result in these async
  187. messages being sent to the specified process, otherwise they will be dropped.
  188. Message formats:
  189. {pgsql, Connection, {notification, Channel, Pid, Payload}}
  190. Connection - connection the notification occured on
  191. Channel - channel the notification occured on
  192. Pid - database session pid that sent notification
  193. Payload - optional payload, only available from PostgreSQL >= 9.0
  194. {pgsql, Connection, {notice, Error}}
  195. Connection - connection the notice occured on
  196. Error - an #error{} record, see pgsql.hrl