Expand description
SQL client traits for id_effect — driver-agnostic database access inspired by
Effect.ts @effect/sql, on the
0.7 kernel.
-
SqlClientreturnsEffects; the capability isSqlClientService(SqlClientEnv), read byquery/execute/transaction. -
query/executetakeSql: a literal or aconst, never a run-timeString. SQL built at run time is aRawSqlforquery_raw/execute_raw, which need theRawSqlCapability(seeraw). -
The client is a scoped
Layer:sql_client_layerconnects it when built and closes it when the scope closes (pg::PgSqlClient::layeropens and closes a pool). -
A transaction is a bracket (
with_transaction,transaction) or a scopedLayer(transaction_layer): it commits on success and rolls back on failure, defect or interrupt. -
Parameters and column values are typed
SqlValues (params!encodes Rust values withToSqlValue); aSqlRowdecodes its columns by name or index withSqlRow::get(FromSqlValue), returning aSqlErrornaming the column.
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", ¶ms![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 tenant_routing::DEFAULT_MAX_TENANT_POOLS;pub use tenant_routing::TenantClientFactory;pub use tenant_routing::TenantConnector;pub use tenant_routing::TenantRouter;pub use tenant_routing::TenantSqlClient;pub use tenant_routing::tenant_database;pub use tenant_routing::tenant_database_from;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 repository::EagerRepository;pub use repository::FieldMeta;pub use repository::Loaded;pub use repository::Relation;pub use repository::RelationMeta;pub use repository::Keyset;pub use repository::PageCursor;pub use repository::Paged;pub use repository::SortOrder;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:
FromRowdecodes anSqlRowinto a struct (#[derive(FromRow)]) or a tuple, andquery_as/query_one_as/query_opt_asrun a query straight into them. - health
- Health checks as effects: success is “up”, a
SqlErroris “down”. - metrics
- Automatic database client metrics and spans:
InstrumentedSqlClientwraps anySqlClient. - migrate
- Migrations: versioned SQL scripts, applied in order and recorded in a tracking table, as
Effects and as a startupLayer(featuremigrate). - mysql
- MySQL driver (feature
mysql) — sqlxMySqlPoolandMySqlSqlClientimplementingSqlClient. Tested against MySQL 8. - pg
- PostgreSQL driver (feature
pg) — sqlxPgPoolandPgSqlClientimplementingSqlClient. - query_
builder - Typed statements (feature
query): build aSELECT/INSERT/UPDATE/DELETEwithsea_query, render it for aDialectwithBuildSql::build_sql— SQL text plus its parameters asSqlValues (the bridge is ours, notsea-query-binder, so theSqlClientabstraction and sqlx’s version stay independent) — and run it withexecute_query/fetch_all_as/fetch_one_as/fetch_optional_as, the statement counterparts ofexecuteandquery_as/query_one_as/query_opt_as. - raw
- SQL text as a type (ADR 0013 R5, M16):
Sqlfor the statements the effect-level functions accept, and theRawSqlCapabilitythatquery_raw/execute_rawneed for SQL built at run time. - repository
- Entities and repositories (feature
repository):#[derive(Entity)]maps a struct to a table, andRepository<T>runs its CRUD statements — built withsea_queryand rendered for aDialect— over theSqlClientin the environment, or over anySqlExecutor(an open transaction) withRepository::on. - routing
RoutingSqlClient— read/write splitting over a primary and its read replicas.- row
- Typed result rows:
SqlRow(named, typed columns ofSqlValues) andSqlColumn. - sqlite
- SQLite driver (feature
sqlite) — sqlxSqlitePoolandSqliteSqlClientimplementingSqlClient. - stream
- Streaming query results:
SqlClient::query_streamand the environment-readingquery_stream/query_stream_asreturn a pull-basedStreamof rows instead of collecting them. - tenant_
routing TenantRouter— one database per tenant (eco.tenancy #8, ADR 0015 D10).- testing
- proptest strategies for
SqlValue(featureproptest), built onid_effect::testing::property. - transaction
- Transactions: the
SqlTransactionhandle, thewith_transaction/transactionbrackets and the scopedtransaction_layer. - value
- Typed SQL values:
SqlValue(one bound parameter or column value), itsSqlType, and the encoding traitsToSqlValue/FromSqlValue.
Macros§
- params
- A
Vec<SqlValue>of the arguments, each encoded withToSqlValue(by reference).
Derive Macros§
- Entity
- Derive
Entityfor a#[derive(FromRow)]struct (seerepository). Deriveid_effect_sql::Entity(map a#[derive(FromRow)]struct to a table forRepository<T>;id_effect_sqlfeaturerepository). - FromRow
- Derive
FromRowfor a struct with named fields (seefrom_row). Deriveid_effect_sql::FromRow(decode a struct with named fields from anSqlRow).