Expand description
Postgres databases.
Databases are declared at module scope. Connection pools are initialized lazily on the first query and reused across calls.
use encore::storage::postgres::{self, Database};
static DB: Database = Database::new("hello").migrations("./migrations");
async fn rename(id: i64, name: &str) -> Result<Option<String>, postgres::Error> {
DB.execute("UPDATE users SET name = $2 WHERE id = $1", &[&id, &name])
.await?;
let row = DB
.query_opt("SELECT email FROM users WHERE id = $1", &[&id])
.await?;
Ok(row.map(|row| row.get("email")))
}§Queries
Query methods mirror tokio_postgres::Client (query, query_one,
query_opt, query_raw, execute, batch_execute, and so on) and return
this module’s Error. Supporting types (Row, Statement,
types::ToSql, etc.) match their tokio_postgres counterparts.
Calling query methods directly on Database uses read-write privileges.
Because calls appear directly on the static, Encore can analyze them
statically and grant each service only the permissions it uses.
Unlike a single tokio_postgres client, Database manages a connection
pool. Operations that require a dedicated connection—such as prepared
statements or COPY—are available on Connection (via
Database::acquire) and Transaction.
§References
Because Encore analyzes database usage statically, a Database cannot be
passed around by value. To pass a database to helper functions or libraries,
create a DatabaseRef with the privileges it needs—Database::read,
Database::write, or Database::admin—which grants that access level
to the service:
use encore::storage::postgres::{Database, Error, Queryable};
static DB: Database = Database::named("hello");
// Library code asks for something to query, as a trait.
async fn count(db: &impl Queryable) -> Result<i64, Error> {
let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
Ok(row.get(0))
}
async fn users() -> Result<i64, Error> {
count(&DB.read()).await
}Queryable is also implemented by Transaction and Connection, so
the same helper functions work inside transactions and on acquired
connections. Database itself does not implement Queryable:
async fn users() -> Result<i64, Error> {
count(&DB).await
}§Errors
Failed queries return this module’s Error:
Error::Database: aDatabaseErrorreported by Postgres (including its SQLSTATE, a typedErrorCodefor common cases, and optionalErrorDetailssuch as constraint or table name), orErrorCode::ConnectionFailureif the database could not be reached.Error::NoRows:query_onereturned no rows.Error::TooManyRows:query_oneorquery_optreturned more than one row.Error::Other: a client-side error, such as a parameter type mismatch or a value that could not be decoded.
Error does not automatically convert into
encore::Error. Match on it where the error kind matters:
use encore::storage::postgres::{Database, DatabaseError, Error, ErrorCode};
static DB: Database = Database::named("hello");
async fn email(id: i64) -> Result<Option<String>, Error> {
match DB.query_one("SELECT email FROM users WHERE id = $1", &[&id]).await {
Ok(row) => Ok(Some(row.get("email"))),
Err(Error::NoRows) => Ok(None),
Err(err) => Err(err),
}
}
async fn add(email: &str) -> Result<bool, Error> {
match DB.execute("INSERT INTO users (email) VALUES ($1)", &[&email]).await {
Ok(_) => Ok(true),
Err(Error::Database(DatabaseError {
code: ErrorCode::UniqueViolation,
..
})) => Ok(false),
Err(err) => Err(err),
}
}Where a function returns encore::Error, such as an API
endpoint or Pub/Sub handler, convert it with the appropriate error code:
async fn record(name: &str) -> Result<(), encore::Error> {
DB.execute("INSERT INTO users (name) VALUES ($1)", &[&name])
.await
.map_err(|e| encore::Error::internal(e.to_string()))?;
Ok(())
}Modules§
- types
- Conversions between Rust and Postgres values via
ToSql(for query parameters) andFromSql(for result columns).
Structs§
- Column
- Information about a column of a query.
- Connection
- A dedicated connection acquired from a database pool via
Database::acquire, returned to the pool when closed or dropped. - Copy
InSink - A sink for
COPY ... FROM STDINquery data. - Copy
OutStream - A stream of
COPY ... TO STDOUTquery data. - Database
- A Postgres database, backed by a lazily-built connection pool.
- Database
Error - An error reported by Postgres, or a connection failure.
- Database
Ref - A handle to a
Databasewith a fixed privilege level, created byDatabase::admin,Database::write,Database::read, orDatabase::read_primary. - Error
Details - The optional fields of a
DatabaseError: the server sends each only for some errors. - Row
- A row of data returned from the database by a query.
- RowStream
- A stream of rows, returned by the
_rawquery methods. Read it withRowStream::next, or as aStream. - Simple
Column - Information about a column of a single query row.
- Simple
Query Row - A row of data returned from the database by a simple query.
- Statement
- A prepared statement created by
prepareon aConnectionorTransaction. - Transaction
- An open transaction. Rolls back on drop unless
Transaction::commitis called. - Transaction
Builder - A builder for a transaction with its characteristics set, made by
build_transaction.
Enums§
- Error
- Errors returned by Postgres operations. See the module docs.
- Error
Code - Categorized Postgres error codes derived from SQLSTATE for common
application-handled errors. Unmapped SQLSTATE values use
ErrorCode::Other. - Isolation
Level - The isolation level of a database transaction.
- Simple
Query Message - Message returned by the
SimpleQuerystream.
Traits§
- Queryable
- A type that can execute Postgres queries:
DatabaseRef,Transaction, orConnection. - RowIndex
- A sealed trait for types that can index into a
Row:usize(zero-based column position) or&str(column name). - ToStatement
- A sealed trait for values accepted as a query: a SQL string (
str,String) or a preparedStatement.