README 9.7 KB

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