Expand description
Postgres databases. Declared at module scope; the connection pool is built lazily from the runtime on first query and reused thereafter.
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
The query methods are those of tokio_postgres::Client, with the same
names, parameters and meaning — query, query_one, query_opt,
query_raw, execute, batch_execute, … — returning this module’s
Error. Their types (Row, Statement, types::ToSql, …) are
this module’s own, with the methods of their tokio_postgres counterparts.
Every query method is a method of the Database, and calling one there
uses it with read-write privileges. That is what lets Encore grant each
service exactly the access it uses: the operation is visible at the call,
so the parser can read it.
A Database is a pool of connections, where a tokio_postgres client is
one. What needs a connection of its own — a prepared statement, COPY — is
on a Connection (Database::acquire) or a Transaction.
§References
For the same reason, a database cannot be passed around as a value. To hand
it to other code, make a DatabaseRef with the privileges that code
needs — Database::read, Database::write or Database::admin —
which the service is then granted:
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 a Transaction and a
Connection, so the same library code runs inside either. It is not
implemented by the Database itself:
async fn users() -> Result<i64, Error> {
count(&DB).await
}§Errors
A query that fails returns this module’s Error:
Error::Database, aDatabaseError: what the database reported, with its SQLSTATE, anErrorCodefor the cases an app most often handles, and the server’s detail, constraint, table, … (in its boxedErrorDetails, whichDatabaseError::constraint_nameand the like read); or a failure to reach the database,ErrorCode::ConnectionFailure.Error::NoRows:query_onefound no row.Error::TooManyRows:query_oneorquery_optfound more than one.Error::Other: a mistake in the call itself, such as a parameter of the wrong type, or a value that could not be decoded.
The error is this module’s own, and doesn’t convert into
encore::Error. Match on it where the 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 an encore::Error, such as a
Pub/Sub handler, convert it there with the code that fits:
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: the traits a query’s
parameters (
ToSql) and a row’s columns (FromSql) go through.
Structs§
- Column
- Information about a column of a query.
- Connection
- A connection acquired from a database’s pool by
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 a database reported, or a failure to reach it.
- Database
Ref - A handle to a
Databasewith one level of privileges, made byDatabase::admin,Database::write,Database::readorDatabase::read_primary.Copy, and free to pass to other code. - 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, made by
prepareon aConnectionor aTransaction. - 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
- What a database operation fails with.
- Error
Code - What kind of error a database reported, by its SQLSTATE: the cases an
app most often handles.
ErrorCode::Otheris any other. - Isolation
Level - The isolation level of a database transaction.
- Simple
Query Message - Message returned by the
SimpleQuerystream.
Traits§
- Queryable
- Something queries run on: a
DatabaseRef, aTransactionor aConnection. Library code takes it —&impl Queryable— so it works with any of them. - RowIndex
- A type a
Rowis indexed by: ausize, for a column’s position, or a&str, for its name. Sealed: these are the only ones. - ToStatement
- What a query method runs: a query string (
str,String), or aStatementprepared earlier. Sealed: these are the only ones.