Expand description
Core primitives for the tank ORM / query toolkit.
This crate exposes a thin, async-first abstraction layer over SQL backends. The goal is portability – the same entity and query building code should compile and run against multiple SQL engines with minimal (ideally zero) changes.
§Design Highlights
- “Bring your own runtime” – traits return
impl Future/impl Stream. You can use Tokio, async-std, or any executor capable of drivingfuturesstreams. This varies from driver to driver. - Streaming results (
Executor::run/fetch) to avoid buffering entire result sets. - A rich
Valueenum representing typed SQL values (including arrays, maps, structs, intervals, decimals) with conversion helpers viaAsValue. - Declarative entity definition through the
Entitytrait + derive macro. - Dialect pluggability: the
Driversupplies aSqlWriterthat renders the appropriate SQL for its backend. - Composability: expressions / datasets build larger statements (SELECT, INSERT, DELETE) without stringly-typed concatenation.
§Quick Start
use tank::{Entity, Executor};
use uuid::Uuid;
#[derive(tank::Entity)]
#[tank(schema = "operations")]
struct Operator {
#[tank(primary_key)]
id: Uuid,
callsign: String,
#[tank(name = "rank")]
service_rank: String,
}
async fn demo<E: Executor>(exec: &mut E, id: Uuid) -> anyhow::Result<Option<Operator>> {
// Ensure table exists (idempotent when supported by driver)
Operator::create_table(exec, true, true).await?;
// Upsert an operator
Operator { id, callsign: "Red-One".into(), service_rank: "LT".into() }
.save(exec).await?;
// Fetch it back
let op = Operator::find_one(exec, &true).await?; // bool implements Expression
Ok(op)
}§Error Handling
All fallible operations use crate-level Result<T> (anyhow::Result<T>).
For detailed context attachers prefer ErrorContext.
§Futures & Streams MUST be driven
Any method returning a future or stream performs no guaranteed side-effect until it is awaited / fully consumed. Never drop them silently.
§Feature Flags
Drivers may expose feature flags (e.g. disabling 128-bit integers). This crate itself is mostly feature-free; consult driver crates for details.
§Modules
The public surface re-exports most modules. Common entry points:
Entity– declare and persist typed rows.Executor– run queries, fetch streams.Query,QueryResult– represent prepared/raw statements & results.Value,AsValue– value type system & conversions.SqlWriter– backend SQL generation.Interval– time span type usable as SQL INTERVAL.Join,Expression– build complex predicates / SELECT trees.
For more elaborate examples inspect the tank-tests crate in the
repository (src/simple.rs, src/transaction1.rs, etc.).
§Macros
Supporting macros like truncate_long!, possibly_parenthesized! and
take_until! assist with SQL / token generation. They are re-exported at
crate root for macro expansion within derives.
§Safety & Portability Notes
- Do not rely on side-effects before awaiting returned futures.
- Always exhaust streams if the driver might hold transactional or cursor resources.
- When mapping
Valueconversions preferAsValue::try_from_valuefor graceful errors.
§Contributing Docs
When adding new traits or types ensure they carry /// rustdoc including:
- Purpose & invariants
- Example snippet (consider pulling from tests)
- Error semantics
Re-exports§
pub use ::indoc;
Modules§
Macros§
- impl_
executor_ transaction - Implement the
Executortrait for a transaction wrapper type by delegating each operation to an underlying connection object. - month_
to_ number - number_
to_ month - possibly_
parenthesized - Conditionally wrap a generated fragment in parentheses.
- send_
value - Sends the value through the channel and logs in case of error.
- truncate_
long - Truncate long strings for logging and error messages purpose.
Structs§
- Binary
Op - Column
Def - Declarative specification of a table column.
- Column
Ref - Reference to a table column.
- Context
- Context
Updater - Declare
Table Ref - Wrapper used when declaring table references in generated macros.
- Fixed
Decimal - Decimal wrapper enforcing compile-time width/scale.
- Generic
SqlWriter - Fallback generic SQL writer (closest to PostgreSQL / DuckDB conventions).
- Interval
- Join
- Binary join of two datasets with optional ON predicate.
- Ordered
- References
- Foreign key reference to another Entity’s columns.
- RowLabeled
- A result row with its corresponding column labels.
- Rows
Affected - Metadata about modify operations (INSERT/UPDATE/DELETE).
- Table
Ref - Reference to a table (schema-qualified + optional alias).
- Type
Decoded - Intermediate decoded type information used by derive macros.
- UnaryOp
Enums§
- Action
- Referential action for foreign key updates or deletes.
- Binary
OpType - Either
Iterator - Polymorphic iterator adapter returning items from either variant.
- Fragment
- Interval
Unit - Join
Type - Supported SQL join variants.
- Operand
- Order
- Passive
- Wrapper marking whether a column should be considered set or skipped (passive) on INSERT.
- Primary
KeyType - Indicates if and how a column participates in the primary key.
- Query
- A query ready to be executed by an [
Executor]. - Query
Result - Heterogeneous items emitted by
Executor::runcombining rows and modify results. - Unary
OpType - Value
- Strongly-typed, nullable SQL value representation used across Tank.
Traits§
- AsQuery
- AsValue
- Value conversion and simple parsing utilities. It is the central conversion and
parsing abstraction used throughout
tankto move between native Rust types and the dynamically typedValuerepresentation that backs query parameters and row decoding. - Column
Trait - Helper trait for types that expose an underlying column definition and reference.
- Connection
- A live database handle capable of executing queries and spawning transactions.
- DataSet
- Queryable data source (table or join tree).
- Driver
- A backend implementation providing connection + SQL dialect services.
- Entity
- Represents a database-backed record with schema and persistence behavior.
- Error
Context - Provides the
contextmethod forResult. - Executor
- Async query executor bound to a concrete
Driver. - Expression
- A renderable SQL expression node.
- OpPrecedence
- Provides numeric precedence for expressions allowing sql writers to insert parentheses.
- Prepared
- A parameterized, backend-prepared query handle.
- SqlWriter
- Dialect printer converting semantic constructs into concrete SQL strings.
- Transaction
- A mutable transactional context implementing
Executor.
Functions§
- as_
c_ string - Convenience wrapper converting into a
CString, panicking on interior NUL. - consume_
while - Consume a prefix of
inputwhile the predicate returns true, returning that slice. - extract_
number - matches_
path - Determine if the trailing segments of a
syn::Pathmatch the expected identifiers. - print_
timer - quote_
btree_ map - Quote a
BTreeMap<K, V>into tokens. - quote_
cow - Quote a
Cow<T>preserving borrowed vs owned status for generated code. - quote_
option - Quote an
Option<T>into tokens. - separated_
by - Write an iterator of items separated by a delimiter into a string.
Type Aliases§
- Check
Passive - Error
- Crate-wide error alias using
anyhow. - Result
- Crate-wide result alias using
anyhowfor flexible error context. - Row
- Owned row value slice matching
RowNameslength. - RowNames
- Shared reference-counted column name list.