tank 0.42.0

Tank (Table Abstraction and Navigation Kit): the Rust data layer. Simple and flexible ORM that allows to manage in a unified way data from different sources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# Cheat Sheet

## Connect

### Connection pool
```rust
use tank::{PoolConfig, Driver};
use tank_postgres::PostgresDriver;

let mut config = PoolConfig::new();
config.max_size = 4;
let pool = PostgresDriver::new()
    .connect_pool("postgres://user:pass@host:5432/db".into(), config)
    .await?;
let mut connection = pool.get().await?;
```

### Single connection
```rust
use tank::Connection;
use tank_sqlite::{SQLiteConnection, SQLiteDriver};

let driver = SQLiteDriver::new();
let mut connection = SQLiteConnection::connect(
    &driver,
    "sqlite:///path/to/db.sqlite?mode=rwc".into(),
).await?;
connection.disconnect().await?;
```

### Type-erased pool
```rust
use std::sync::Arc;
use tank::{Driver, ConnectionPool, PoolConfig};
use tank_mysql::MySQLDriver;

let pool: Arc<dyn ConnectionPool<MySQLDriver>> = MySQLDriver::mysql()
    .connect_pool("mysql://user:pass@host:3306/db".into(), PoolConfig::new())
    .await?
    .into_arc();
```

## Entity Definition

```rust
use std::collections::HashMap;
use tank::Entity;
use uuid::Uuid;

#[derive(Entity, Debug, PartialEq)]
#[tank(
    schema = "army",
    name = "deployments",
    primary_key = (Self::unit_id, Self::region),
)]
struct EntityExample {
    unit_id: Uuid,
    #[tank(clustering_key)]
    region: String,
    #[tank(name = "callsign")]
    callsign: String,
    casualties: i32,
    #[tank(conversion_type = NotesWrap)]
    metadata: Notes,
    #[tank(ignore)]
    transient_cache: HashMap<String, String>,
}
```

`primary_key` is composite: `unit_id` is the partition key and `region` is the clustering key (relevant for Scylla/Cassandra). `clustering_key` is ignored by SQL drivers.
The field transient_cache is ignored by the database (not stored in the table)

### Conversion Types

`conversion_type` lets you use any type as an entity field by routing reads and writes through a local wrapper that implements [`AsValue`](./05-types.md), the only requirement is that the type can be cloned:

```rust
use anyhow::anyhow;
use tank::{AsValue, Entity, Result, Value};

#[derive(Debug, PartialEq, Clone)]
pub struct Notes(pub String); // Third party type
pub struct NotesWrap(pub Notes); // Local wrapper

impl AsValue for NotesWrap {
    fn as_empty_value() -> Value {
        Value::Varchar(None)
    }
    fn as_value(self) -> Value {
        Value::Varchar(Some(self.0.0.into()))
    }
    fn try_from_value(value: Value) -> Result<Self> {
        match value.try_as(&Value::Varchar(None)) {
            Ok(Value::Varchar(Some(s))) => {
                Ok(NotesWrap(Notes(s.to_string())))
            }
            _ => Err(anyhow!("Expected Varchar for Notes")),
        }
    }
}
impl From<Notes> for NotesWrap {
    fn from(v: Notes) -> Self {
        NotesWrap(v)
    }
}
impl From<NotesWrap> for Notes {
    fn from(v: NotesWrap) -> Self {
        v.0
    }
}
```

Tank calls `NotesWrap::from(field_value)` when writing and reconstructs the field via `Notes::from(NotesWrap::try_from_value(db_value)?)` when reading. See [Types](./05-types.md) for full `AsValue` documentation and the built-in type table.

## Table setup

```rust
EntityExample::create_table(&mut connection, true, true).await?;
EntityExample::drop_table(&mut connection, true, false).await?;
```

## Transaction

```rust
use tank::{Entity, Transaction};

let mut tx = connection.begin().await?;
EntityExample::insert_one(&mut tx, &entity).await?;
entity.delete(&mut tx).await?;
tx.commit().await?;
```

Both transactions and connections can be provided as a executors to run the queries in methods like: `EntityExample::create_table(&mut tx, ...)`.

## Insert

```rust
EntityExample::insert_one(&mut connection, &entity).await?;
EntityExample::insert_many(&mut connection, [&entity2, ...]).await?;
connection.append([&entity3, ...]).await?;
```

Insert and append methods accept any container that can be turned into a iterator yielding either a entity value or reference.

## Save and Delete

```rust
entity.save(&mut connection).await?;
entity.delete(&mut connection).await?;
```

> [!NOTE]
> The Entity must have a primary key for this to work.

## Find

```rust
use std::pin::pin;
use tank::{Entity, expr, stream::TryStreamExt};

let entity = EntityExample::find_one(
    &mut connection,
    entity.primary_key_expr()
).await?;
{
    let uid = entity2.unit_id;
    let mut stream = pin!(EntityExample::find_many(
        &mut connection,
        expr!(EntityExample::unit_id == #uid),
        Some(100),
    ));
    while let Some(entity) = stream.try_next().await? {
        println!("{}", entity.callsign);
    }
}
let uid = Uuid::from_str("94f0cbcc-1fce-454e-a6e4-4e3587741808")?;
let entities: Vec<EntityExample> =
    EntityExample::find_many(
        &mut connection,
        expr!(EntityExample::unit_id == #uid),
        None
    )
    .try_collect()
    .await?;
```

## Delete Many

```rust
use tank::{Entity, expr};

let uid = entity2.unit_id;
EntityExample::delete_many(
    &mut connection,
    expr!(EntityExample::unit_id == #uid)
).await?;

let uid = entity3.unit_id;
EntityExample::delete_many(
    &mut connection,
    expr!(EntityExample::unit_id == #uid)
).await?;
```

## Expressions

```rust
use tank::expr;
use uuid::Uuid;

expr!(EntityExample::casualties == 0);
expr!(EntityExample::casualties >= 10);
expr!(EntityExample::region == "North" || EntityExample::region == "South");
expr!(EntityExample::callsign == "Alpha%" as LIKE);
expr!(EntityExample::callsign != "Alpha%" as LIKE);
expr!(EntityExample::casualties > ?);
let uid = Uuid::new_v4();;
expr!(EntityExample::unit_id == #uid);
```

## Prepared statement

```rust
use tank::{Entity, expr, stream::TryStreamExt};

let mut query = EntityExample::prepare_find(
    &mut connection,
    expr!(EntityExample::unit_id == ?),
    Some(50),
)
.await?;
query.bind(Uuid::from_str("2f4f97da-0278-4c99-bc22-2b3986aeee85")?)?;
let entities = connection
    .fetch(&mut query)
    .map_ok(|row| EntityExample::from_row(row).unwrap())
    .try_collect::<Vec<EntityExample>>()
    .await?;
query.clear_bindings()?;
query.bind(Uuid::from_str("962f2c1c-7caa-468d-a387-53ed9860c4bf")?)?;
```

## Query Builder

```rust
use tank::{cols, expr, stream::TryStreamExt, QueryBuilder};

let uid = entity.unit_id;
let results = connection.fetch(
    QueryBuilder::new()
        // Selecting fewer columns requires the entity to have the Default trait
        .select(cols!(EntityExample::callsign, EntityExample::casualties))
        .from(EntityExample::table())
        .where_expr(expr!(EntityExample::unit_id == #uid))
        .order_by(cols!(EntityExample::region ASC))
        .limit(Some(50))
        .build(&connection.driver()),
)
.map_ok(|row| EntityExample::from_row(row).unwrap())
.try_collect::<Vec<_>>()
.await?;
```

## Joins

The `join!` macro builds the `FROM` clause for `QueryBuilder`. Define a result struct that matches the selected columns, then pass the join tree to `.from()`.

Supported keywords: `JOIN`, `INNER JOIN`, `LEFT JOIN`, `LEFT OUTER JOIN`, `RIGHT JOIN`, `RIGHT OUTER JOIN`, `FULL OUTER JOIN`, `CROSS JOIN`, `NATURAL JOIN`.

```rust
use tank::{
    Entity, QueryBuilder, cols, expr, join, stream::StreamExt, stream::TryStreamExt,
};

#[derive(Entity, Debug)]
struct BookWithAuthor {
    title: String,
    author: String,
}

let rows: Vec<BookWithAuthor> = connection
    .fetch(
        QueryBuilder::new()
            .select(cols!(Book::title, Author::name as author))
            .from(join!(Book JOIN Author ON Book::author == Author::id))
            .where_expr(expr!(Book::year > 2000))
            .order_by(cols!(Book::title ASC))
            .build(&connection.driver()),
    )
    .map_ok(BookWithAuthor::from_row)
    .map(Result::flatten)
    .try_collect()
    .await?;

let rows: Vec<BookWithAuthor> = connection
    .fetch(
        QueryBuilder::new()
            .select(cols!(B.title, A.name as author))
            .from(join!(Book B LEFT JOIN Author A ON B.author == A.author_id))
            .where_expr(true)
            .build(&connection.driver()),
    )
    .map_ok(BookWithAuthor::from_row)
    .map(Result::flatten)
    .try_collect()
    .await?;

let dataset = join!(
    Book B
        LEFT JOIN Author A1 ON B.author == A1.author_id
        LEFT JOIN Author A2 ON B.co_author == A2.author_id
);
let rows = connection
    .fetch(
        QueryBuilder::new()
            .select(cols!(B.title, A1.name as author, A2.name as co_author))
            .from(dataset)
            .where_expr(true)
            .build(&connection.driver()),
    )
    .try_collect::<Vec<_>>()
    .await?;
```

## Raw SQL

### Simple query
```rust
use indoc::indoc;
use std::pin::pin;
use tank::{QueryResult, stream::TryStreamExt};

{
    let mut stream = pin!(connection.run(indoc! {r#"
    SELECT unit_id, callsign
    FROM army.deployments
    WHERE casualties > 0
"#}));
    while let Some(result) = stream.try_next().await? {
        match result {
            QueryResult::Row(row) => {
                println!("{:?}", row.values);
            }
            QueryResult::Affected(v) => {
                println!("affected: {:?}", v.rows_affected);
            }
        }
    }
}
let rows: Vec<_> = connection
    .fetch("SELECT * FROM army.deployments")
    .try_collect()
    .await?;
let affected = connection
    .execute(indoc! {r#"
        UPDATE army.deployments SET casualties = 0
        WHERE region = 'North'
    "#})
    .await?;
```

### Prepared
```rust
use indoc::indoc;
use tank::{Entity, stream::TryStreamExt};

let mut query = connection.prepare(indoc! {"
    SELECT unit_id, callsign
    FROM army.deployments
    WHERE unit_id = ?
    LIMIT ?
"}.into()
).await?;
query.bind(uid)?;
query.bind(25)?;

let rows = connection.fetch(&mut query).try_collect::<Vec<_>>().await?;
let entity = EntityExample::from_row(row)?;

#[derive(Entity)]
struct Slim { callsign: String, casualties: i32 }
let slim = Slim::from_row(row)?;
query.clear_bindings()?;
query.bind(other_uid)?;
query.bind(10)?;
```

### SqlWriter

```rust
use tank::{DynQuery, QueryBuilder, QueryResult, SqlWriter, stream::TryStreamExt};

let writer = connection.driver().sql_writer();
let mut query = DynQuery::default();

writer.write_create_table::<EntityExample>(&mut query, true);
writer.write_insert(&mut query, &[entity1, entity2], false);
writer.write_select(
    &mut query,
    &QueryBuilder::new()
        .select(EntityExample::columns())
        .from(EntityExample::table())
        .where_expr(true)
        .limit(Some(100)),
);

let results: Vec<QueryResult> = connection.run(query).try_collect().await?;
```