Elixir
Use the configured address for your client. See connection addresses and security. The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.
Use Postgrex, the standard Elixir PostgreSQL driver, over the SQL client interface (port 5432). Ecto uses Postgrex underneath.
The Postgrex query and transaction examples below were executed against ParticleDB. Ecto uses additional schema and migration queries; validate your application migrations separately.
Install
Section titled “Install”defp deps do [ {:postgrex, "~> 0.19.0"} # with Ecto: {:ecto_sql, "~> 3.12"} ]endConnect and query
Section titled “Connect and query”The examples connect as postgres with the password secret, for a server started with
particledb start --auth-method scram-sha-256 --pg-password secret. With the server’s default
--auth-method password, pass ssl: true; see
TLS and authentication.
{:ok, pid} = Postgrex.start_link( hostname: "localhost", port: 5432, database: "particledb", username: "postgres", password: "secret")
Postgrex.query!(pid, "CREATE TABLE products (id BIGINT PRIMARY KEY, name TEXT, price DOUBLE PRECISION)", [])
Postgrex.query!(pid, "INSERT INTO products (id, name, price) VALUES ($1, $2, $3)", [1, "Webcam", 79.99])
result = Postgrex.query!(pid, "SELECT name, price FROM products WHERE price > $1", [50.0])for [name, price] <- result.rows, do: IO.puts("#{name}: #{price}")Transactions
Section titled “Transactions”Postgrex.query!(pid, "CREATE TABLE accounts (id BIGINT PRIMARY KEY, balance BIGINT)", [])Postgrex.query!(pid, "INSERT INTO accounts VALUES (1, 500), (2, 0)", [])
Postgrex.transaction(pid, fn conn -> Postgrex.query!(conn, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", [100, 1]) Postgrex.query!(conn, "UPDATE accounts SET balance = balance + $1 WHERE id = $2", [100, 2])end)# {:ok, _} on commit; an exception inside the function rolls the transaction backErrors
Section titled “Errors”Server errors carry PostgreSQL SQLSTATEs, which Postgrex maps to atoms:
case Postgrex.query(pid, "INSERT INTO products (id, name, price) VALUES ($1, $2, $3)", [1, "Duplicate", 10.0]) do {:ok, _} -> :inserted {:error, %Postgrex.Error{postgres: %{code: :unique_violation}}} -> :duplicate {:error, %Postgrex.Error{postgres: %{code: :undefined_table}}} -> :no_tableendConfigure an Ecto repo with the Postgres adapter as usual:
config :my_app, MyApp.Repo, hostname: "localhost", port: 5432, database: "particledb", username: "postgres", password: "secret", pool_size: 10Next steps
Section titled “Next steps”- SQL Reference. SQL syntax and examples
- ORM compatibility. other ORMs and drivers
- SQL client connections. connection settings and compatibility
This site uses Google Analytics cookies to count visits. Privacy · License