Skip to content
Closed
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
52 changes: 51 additions & 1 deletion tests/sqlite/derives.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use sqlx::Sqlite;
use sqlx_test::test_type;
use sqlx_test::{new, test_type};

#[derive(Debug, PartialEq, sqlx::Type)]
#[repr(u32)]
Expand Down Expand Up @@ -32,3 +32,53 @@ test_type!(transparent_named<TransparentNamed>(Sqlite,
"0" == TransparentNamed { field: 0 },
"23523" == TransparentNamed { field: 23523 },
));

// SQLite stores JSON as TEXT. The `#[sqlx(json)]` field attribute lets a struct
// read such a column into a `serde_json::Value` (or any `Deserialize` type),
// deserializing it with `serde_json` during decode.
#[derive(Debug, PartialEq, sqlx::FromRow)]
struct JsonRow {
id: i64,
#[sqlx(json)]
data: serde_json::Value,
}

#[sqlx_macros::test]
async fn it_reads_json_from_text_column() -> anyhow::Result<()> {
let mut conn = new::<Sqlite>().await?;

let row: JsonRow = sqlx::query_as(
r#"SELECT 1 AS id, '{"key": "value"}' AS data"#,
)
.fetch_one(&mut conn)
.await?;

assert_eq!(
row,
JsonRow {
id: 1,
data: serde_json::json!({ "key": "value" }),
}
);

Ok(())
}

#[sqlx_macros::test]
async fn it_surfaces_invalid_json_as_column_decode_error() -> anyhow::Result<()> {
let mut conn = new::<Sqlite>().await?;

let result: Result<JsonRow, sqlx::Error> =
sqlx::query_as(r#"SELECT 1 AS id, 'not valid json' AS data"#)
.fetch_one(&mut conn)
.await;

match result {
Err(sqlx::Error::ColumnDecode { index, .. }) => {
assert_eq!(index, "\"data\"");
}
other => panic!("expected ColumnDecode error, got {other:?}"),
}

Ok(())
}
Loading