Postgrex
PostgreSQL driver for Elixir.
Documentation: http://hexdocs.pm/postgrex/
Examples
iex> {:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")
{:ok, #PID<0.69.0>}
iex> Postgrex.query!(pid, "SELECT user_id, text FROM comments", [])
%Postgrex.Result{command: :select, empty?: false, columns: ["user_id", "text"], rows: [[3,"hey"],[4,"there"]], size: 2}}
iex> Postgrex.query!(pid, "INSERT INTO comments (user_id, text) VALUES (10, 'heya')", [])
%Postgrex.Result{command: :insert, columns: nil, rows: nil, num_rows: 1}}
Extensions
Extensions are used to extend Postgrex’ built-in type encoding/decoding.
The extensions directory in this project provides implementation for many Postgres’ built-in data types. It is also a great example of how to implement your own extensions. For example, you can look at the Date
extension as a starting point.
Once you defined your extensions, you should build custom type modules, passing all of your extensions as arguments:
Postgrex.Types.define(MyApp.PostgrexTypes, [MyApp.Postgis.Extensions], [])
Postgrex.Types.define/3
must be called on its own file, outside of any module and function, as it only needs to be defined once during compilation.
Once a type module is defined, you must specify it on start_link
:
Postgrex.start_link(types: MyApp.PostgrexTypes)
Fails since $1 is regclass not text.
query(“select nextval($1)”, [“some_sequence”])
Perform an explicit cast, this would happen automatically when using a
client library that uses the text protocol.
query(“select nextval($1::text::regclass)”, [“some_sequence”])
efficient way, since PostgreSQL only has to perform the lookup once. Client
PgBouncer
When using PgBouncer with transaction or statement pooling named prepared queries can not be used because the bouncer may route requests from the same postgrex connection to different PostgreSQL backend processes and discards named queries after the transactions closes. To force unnamed prepared queries:
Postgrex.start_link(prepare: :unnamed)