Skip to main content

Crate id_effect_sql

Crate id_effect_sql 

Source
Expand description

SQL client traits for id_effect — driver-agnostic database access inspired by Effect.ts @effect/sql, on the 0.7 kernel.

Production PostgreSQL support is behind the pg feature (pg module, sqlx PgPool). See docs/platform/adrs/adr-sql-driver-choice.md.

§Example

use id_effect::Exit;
use id_effect::{Effect, fail, succeed};
use id_effect_sql::{
  SqlClientEnv, SqlError, SqlRow, TestSqlClient, params, query, sql_client_layer, transaction,
};

fn active_ids() -> Effect<Vec<i64>, SqlError, SqlClientEnv> {
  query("SELECT id FROM users WHERE active = $1", params![true])
    .flat_map(|rows| match rows.iter().map(|r| r.get::<i64>("id")).collect::<Result<_, _>>() {
      Ok(ids) => succeed(ids),
      Err(e) => fail(e),
    })
}

let test = TestSqlClient::new();
test.script_query(
  "SELECT id FROM users WHERE active = $1",
  vec![SqlRow::from_pairs([("id", 1i64)]), SqlRow::from_pairs([("id", 2i64)])],
);

// Connected while the program runs, closed after it.
let program = active_ids()
  .flat_map(|ids| {
    let n = ids.len() as i64;
    transaction(move |tx| tx.execute("UPDATE stats SET n = $1", &params![n]).narrow())
  })
  .provide_layer(sql_client_layer::<SqlError>(test.clone()));
assert!(matches!(program.block_on(), Exit::Success(0)));
assert_eq!((test.commits(), test.open_transactions(), test.closes()), (1, 0, 1));

Re-exports§

pub use client::SqlClient;
pub use client::SqlClientEnv;
pub use client::SqlClientService;
pub use client::TestSqlClient;
pub use client::execute;
pub use client::provide_sql_client;
pub use client::query;
pub use client::sql_client_env;
pub use client::sql_client_layer;
pub use error::SQLSTATE_UNIQUE_VIOLATION;
pub use error::SqlError;
pub use from_row::FromRow;
pub use from_row::query_as;
pub use from_row::query_one_as;
pub use from_row::query_opt_as;
pub use raw::RawSql;
pub use raw::RawSqlCapability;
pub use raw::RawSqlEnv;
pub use raw::Sql;
pub use raw::execute_raw;
pub use raw::query_raw;
pub use row::ColumnIndex;
pub use row::SqlColumn;
pub use row::SqlRow;
pub use value::FromSqlValue;
pub use value::Json;
pub use value::SqlType;
pub use value::SqlValue;
pub use value::ToSqlValue;
pub use value::ValueError;
pub use transaction::SqlTransaction;
pub use transaction::SqlTransactionEnv;
pub use transaction::SqlTransactionService;
pub use transaction::transaction;
pub use transaction::transaction_layer;
pub use transaction::with_transaction;
pub use transaction::with_transaction as transaction_scope;
pub use stream::query_stream;
pub use stream::query_stream_as;
pub use transaction::Isolation;
pub use transaction::SQLSTATE_DEADLOCK_DETECTED;
pub use transaction::SQLSTATE_SERIALIZATION_FAILURE;
pub use transaction::TransactionOptions;
pub use transaction::is_serialization_failure;
pub use transaction::retry_serialization_failures;
pub use transaction::savepoint;
pub use transaction::transaction_with;
pub use transaction::with_transaction_options;
pub use query_builder::BuildSql;
pub use query_builder::Dialect;
pub use query_builder::execute_query;
pub use query_builder::fetch_all_as;
pub use query_builder::fetch_one_as;
pub use query_builder::fetch_optional_as;
pub use routing::ReadRouting;
pub use routing::RoutingSqlClient;
pub use repository::BoundRepository;
pub use repository::CurrentTenant;
pub use repository::Entity;
pub use repository::Page;
pub use repository::Repository;
pub use repository::SqlExecutor;
pub use jiff;
pub use rust_decimal;
pub use serde_json;
pub use uuid;

Modules§

audit
Audit log (feature audit): who changed what, appended inside the caller’s transaction and hash-chained so that edits to stored records are detectable.
client
Driver-agnostic SQL client trait, its capability and layers, and an in-memory test double.
error
Structured errors for SQL client operations.
from_row
Typed rows: FromRow decodes an SqlRow into a struct (#[derive(FromRow)]) or a tuple, and query_as / query_one_as / query_opt_as run a query straight into them.
health
Health checks as effects: success is “up”, a SqlError is “down”.
metrics
Automatic database client metrics and spans: InstrumentedSqlClient wraps any SqlClient.
migrate
Migrations: versioned SQL scripts, applied in order and recorded in a tracking table, as Effects and as a startup Layer (feature migrate).
mysql
MySQL driver (feature mysql) — sqlx MySqlPool and MySqlSqlClient implementing SqlClient. Tested against MySQL 8.
pg
PostgreSQL driver (feature pg) — sqlx PgPool and PgSqlClient implementing SqlClient.
query_builder
Typed statements (feature query): build a SELECT / INSERT / UPDATE / DELETE with sea_query, render it for a Dialect with BuildSql::build_sql — SQL text plus its parameters as SqlValues (the bridge is ours, not sea-query-binder, so the SqlClient abstraction and sqlx’s version stay independent) — and run it with execute_query / fetch_all_as / fetch_one_as / fetch_optional_as, the statement counterparts of execute and query_as / query_one_as / query_opt_as.
raw
SQL text as a type (ADR 0013 R5, M16): Sql for the statements the effect-level functions accept, and the RawSqlCapability that query_raw / execute_raw need for SQL built at run time.
repository
Entities and repositories (feature repository): #[derive(Entity)] maps a struct to a table, and Repository<T> runs its CRUD statements — built with sea_query and rendered for a Dialect — over the SqlClient in the environment, or over any SqlExecutor (an open transaction) with Repository::on.
routing
RoutingSqlClient — read/write splitting over a primary and its read replicas.
row
Typed result rows: SqlRow (named, typed columns of SqlValues) and SqlColumn.
sqlite
SQLite driver (feature sqlite) — sqlx SqlitePool and SqliteSqlClient implementing SqlClient.
stream
Streaming query results: SqlClient::query_stream and the environment-reading query_stream / query_stream_as return a pull-based Stream of rows instead of collecting them.
testing
proptest strategies for SqlValue (feature proptest), built on id_effect::testing::property.
transaction
Transactions: the SqlTransaction handle, the with_transaction / transaction brackets and the scoped transaction_layer.
value
Typed SQL values: SqlValue (one bound parameter or column value), its SqlType, and the encoding traits ToSqlValue / FromSqlValue.

Macros§

params
A Vec<SqlValue> of the arguments, each encoded with ToSqlValue (by reference).

Derive Macros§

Entity
Derive Entity for a #[derive(FromRow)] struct (see repository). Derive id_effect_sql::Entity (map a #[derive(FromRow)] struct to a table for Repository<T>; id_effect_sql feature repository).
FromRow
Derive FromRow for a struct with named fields (see from_row). Derive id_effect_sql::FromRow (decode a struct with named fields from an SqlRow).