Skip to main content

Module postgres

Module postgres 

Source
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:

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.
CopyInSink
A sink for COPY ... FROM STDIN query data.
CopyOutStream
A stream of COPY ... TO STDOUT query data.
Database
A Postgres database, backed by a lazily-built connection pool.
DatabaseError
An error a database reported, or a failure to reach it.
DatabaseRef
A handle to a Database with one level of privileges, made by Database::admin, Database::write, Database::read or Database::read_primary. Copy, and free to pass to other code.
ErrorDetails
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 _raw query methods. Read it with RowStream::next, or as a Stream.
SimpleColumn
Information about a column of a single query row.
SimpleQueryRow
A row of data returned from the database by a simple query.
Statement
A prepared statement, made by prepare on a Connection or a Transaction.
Transaction
An open transaction. Rolls back on drop unless Transaction::commit is called.
TransactionBuilder
A builder for a transaction with its characteristics set, made by build_transaction.

Enums§

Error
What a database operation fails with.
ErrorCode
What kind of error a database reported, by its SQLSTATE: the cases an app most often handles. ErrorCode::Other is any other.
IsolationLevel
The isolation level of a database transaction.
SimpleQueryMessage
Message returned by the SimpleQuery stream.

Traits§

Queryable
Something queries run on: a DatabaseRef, a Transaction or a Connection. Library code takes it — &impl Queryable — so it works with any of them.
RowIndex
A type a Row is indexed by: a usize, 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 a Statement prepared earlier. Sealed: these are the only ones.