Skip to main content

bool_from_sql

Function bool_from_sql 

Source
pub fn bool_from_sql<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<bool, D::Error>
Expand description

Deserializes a SQLite boolean column (INTEGER 0/1) into bool.

Use it as #[serde(deserialize_with = "ocre::bool_from_sql")]. Any non-zero number is true; real booleans are accepted too, so the same struct also reads JSON bodies and cached rows.

§Errors

Fails with the deserializer’s error for anything but a boolean or a number (“expected a boolean or the integer 0 or 1”); Db queries report it as Error::Internal.

§Examples

use serde::Deserialize;

#[derive(Deserialize)]
struct Post {
    #[serde(deserialize_with = "ocre::bool_from_sql")]
    published: bool,
}

let post: Post = serde_json::from_str(r#"{"published": 1}"#).unwrap();
assert!(post.published);
let post: Post = serde_json::from_str(r#"{"published": false}"#).unwrap();
assert!(!post.published);
assert!(serde_json::from_str::<Post>(r#"{"published": "yes"}"#).is_err());