Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sqlx support and test #9

Merged
merged 2 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ default = ["serde"]

[dev-dependencies]
serde_json = "1.0.91"
sqlx = { version = "0.8.2", features = ["sqlite", "runtime-tokio"] }
tokio = { version = "1.40.0", features = ["macros", "rt"] }
29 changes: 29 additions & 0 deletions src/fract_index.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::hex::{bytes_to_hex, hex_to_bytes};
use std::{
convert::TryFrom,
error::Error,
fmt::{self, Display},
ops::Deref,
};

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -249,6 +251,33 @@ impl FractionalIndex {
}
}

impl TryFrom<Vec<u8>> for FractionalIndex {
type Error = DecodeError;

fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
FractionalIndex::from_bytes(bytes)
}
}

impl TryFrom<Option<Vec<u8>>> for FractionalIndex {
type Error = DecodeError;

fn try_from(bytes: Option<Vec<u8>>) -> Result<Self, Self::Error> {
match bytes {
Some(bytes) => FractionalIndex::from_bytes(bytes),
None => Ok(FractionalIndex::default()),
}
}
}

impl Deref for FractionalIndex {
type Target = [u8];

fn deref(&self) -> &Self::Target {
&self.0
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
119 changes: 119 additions & 0 deletions tests/sqlx.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
use fractional_index::FractionalIndex;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::FromRow;

const CREATE_TABLE_QUERY: &str = r#"
create table item (
id integer primary key,
name text not null,
fractional_index blob not null,
nullable_fractional_index blob
)"#;

#[derive(FromRow, Debug)]
struct Item {
#[allow(unused)]
id: i64,
name: String,
#[sqlx(try_from = "Vec<u8>")]
fractional_index: FractionalIndex,
#[sqlx(try_from = "Option<Vec<u8>>")]
nullable_fractional_index: FractionalIndex,
}

#[tokio::test]
async fn sqlx_insert_select() {
let pool = SqlitePoolOptions::new()
.connect("sqlite::memory:")
.await
.unwrap();

// Create table.
sqlx::query(CREATE_TABLE_QUERY)
.execute(&pool)
.await
.unwrap();

let idx2 = FractionalIndex::new_after(&FractionalIndex::default());

// Insert an item.
sqlx::query("insert into item (name, fractional_index) values (?, ?)")
.bind("item1")
.bind(&*idx2)
.execute(&pool)
.await
.unwrap();

// Fetch all items
let mut items: Vec<Item> = sqlx::query_as("select * from item")
.fetch_all(&pool)
.await
.unwrap();

assert_eq!(items.len(), 1);
let item = items.pop().unwrap();

assert_eq!(item.name, "item1");
assert_eq!(item.fractional_index, idx2);
}

#[tokio::test]
async fn sqlx_insert_select_nullable() {
let pool = SqlitePoolOptions::new()
.connect("sqlite::memory:")
.await
.unwrap();

// Create table.
sqlx::query(CREATE_TABLE_QUERY)
.execute(&pool)
.await
.unwrap();

let idx2 = FractionalIndex::new_after(&FractionalIndex::default());
let idx3 = FractionalIndex::new_after(&idx2);

// Insert an item.
sqlx::query(
"insert into item (name, fractional_index, nullable_fractional_index) values (?, ?, ?)",
)
.bind("item1")
.bind(&*idx2)
.bind(&*idx3)
.execute(&pool)
.await
.unwrap();

sqlx::query(
"insert into item (name, fractional_index, nullable_fractional_index) values (?, ?, NULL)",
)
.bind("item2")
.bind(&*idx3)
.execute(&pool)
.await
.unwrap();

// Fetch all items
let items: Vec<Item> = sqlx::query_as("select * from item order by id asc")
.fetch_all(&pool)
.await
.unwrap();

let mut items = items.into_iter();

{
let item = items.next().unwrap();
assert_eq!(item.name, "item1");
assert_eq!(item.fractional_index, idx2);
assert_eq!(item.nullable_fractional_index, idx3);
}

{
let item = items.next().unwrap();
assert_eq!(item.name, "item2");
assert_eq!(item.fractional_index, idx3);
assert_eq!(item.nullable_fractional_index, FractionalIndex::default());
}

assert!(items.next().is_none());
}
Loading