Skip to main content

tank_tests/
binary.rs

1use crate::silent_logs;
2use std::sync::LazyLock;
3use tank::{Entity, Executor, Result, expr, stream::TryStreamExt};
4use tokio::sync::Mutex;
5
6static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
7
8#[derive(Entity, PartialEq, Debug)]
9struct BinaryFields {
10    #[tank(primary_key)]
11    id: i32,
12    data: Box<[u8]>,
13}
14
15/// A payload with every kind of byte, including invalid UTF-8 sequences.
16fn payload() -> Box<[u8]> {
17    vec![0x00, 0xFF, 0xDE, 0xAD, 0xBE, 0xEF, 0x80, 0x7F, 0xC3].into_boxed_slice()
18}
19
20pub async fn binary(executor: &mut impl Executor) -> Result<()> {
21    let _lock = MUTEX.lock().await;
22
23    // Setup
24    silent_logs! {
25        BinaryFields::drop_table(executor, true, false).await?;
26    }
27    BinaryFields::create_table(executor, true, true).await?;
28
29    // Literal insert must preserve every byte.
30    BinaryFields::insert_one(
31        executor,
32        &BinaryFields {
33            id: 1,
34            data: payload(),
35        },
36    )
37    .await?;
38    let loaded = BinaryFields::find_one(executor, expr!(BinaryFields::id == 1))
39        .await?
40        .expect("Failed to find the binary payload");
41    assert_eq!(
42        loaded.data,
43        payload(),
44        "Binary literal round-trip lost bytes"
45    );
46
47    // A bound parameter must preserve every byte too.
48    let mut query =
49        BinaryFields::prepare_find(executor, expr!(BinaryFields::data == ?), None).await?;
50    query.bind(payload())?;
51    let loaded = {
52        let rows = executor.fetch(&mut query).try_collect::<Vec<_>>().await?;
53        assert_eq!(rows.len(), 1, "Expected exactly one match for the payload");
54        BinaryFields::from_row(rows.into_iter().next().unwrap())?
55    };
56    assert_eq!(loaded.data, payload(), "Binary bound round-trip lost bytes");
57
58    Ok(())
59}