Skip to main content

Module postgres

Module postgres 

Source
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 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) and FromSql (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.
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 reported by Postgres, or a connection failure.
DatabaseRef
A handle to a Database with a fixed privilege level, created by Database::admin, Database::write, Database::read, or Database::read_primary.
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 created by prepare on a Connection or 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
Errors returned by Postgres operations. See the module docs.
ErrorCode
Categorized Postgres error codes derived from SQLSTATE for common application-handled errors. Unmapped SQLSTATE values use ErrorCode::Other.
IsolationLevel
The isolation level of a database transaction.
SimpleQueryMessage
Message returned by the SimpleQuery stream.

Traits§

Queryable
A type that can execute Postgres queries: DatabaseRef, Transaction, or Connection.
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 prepared Statement.