README 7.2 KB

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