Crate sqlm_postgres

source ·
Expand description

An sql! macro to write compile-time checked database queries similar to how format! works.

§Example

use sqlm_postgres::{sql, Enum, FromRow, FromSql, ToSql};

let id: i64 = 1;
let user: User = sql!("SELECT * FROM users WHERE id = {id}").await?;

#[derive(Debug, FromRow)]
struct User {
    id: i64,
    name: String,
    role: Role,
}

#[derive(Debug, Default, FromSql, ToSql, Enum)]
#[postgres(name = "role")]
enum Role {
    #[default]
    #[postgres(name = "user")]
    User,
    #[postgres(name = "admin")]
    Admin,
}

§Usage

  • Add sqlm-postgres to your dependencies
  • Make the DATABASE_URL env variable available during compile time (e.g. via adding an .env file)
  • Start using the sql! macro (no further setup necessary; a connection pool is automatically created for you)

§Caveats

  • Automatically creates a global connection pool for you with no way to opt out
  • Compile-time checks cannot be disabled. Thus also requires database access on your CI.
  • Does not know whether rows returned from Postgres are nullable and consequentially requires all types to implement Default::default, which it falls back to if Postgres returns null.

Re-exports§

Macros§

  • Creates a parameterized, compile-time checked database query that accepts parameters similar to the format! macro.

Structs§

  • An error communicating with the Postgres server.
  • A row of data returned from Postgres.
  • The struct created by sql!; executed by calling .await.
  • A future for executing an sql query.

Traits§

  • A trait used to allow functions to accept connections without having to explicit about whether it’s a transaction or not.
  • A trait for types that can be created from a Row (a postgres row containing columns as constraint by Cols).
  • A trait for types that can be created from a Postgres value.
  • A trait used to which Rust type a Postgres type is read into.
  • A trait for types that can be converted into Postgres values.

Functions§

  • Establish a database connection.

Type Aliases§

  • An asynchronous PostgreSQL client (basically a non-transactional connection).
  • A database transaction.

Derive Macros§

  • A derive necessary to support compile checks between Postgres and Rust enums.
  • Derive FromRow for a struct, required read a query result into a struct.