#postgresql #sql #compile-time #queries #write #checked #how

sqlm-postgres

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

1 unstable release

0.1.0 Jun 7, 2024

#1042 in Database interfaces

Download history 111/week @ 2024-06-06 4/week @ 2024-06-13

115 downloads per month

MIT/Apache

46KB
981 lines

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.

Dependencies

~21–32MB
~592K SLoC