Skip to content

Commit

Permalink
Merge pull request #4395 from xuehaonan27/add_sqlite_json_pretty
Browse files Browse the repository at this point in the history
Add SQLite function `json_pretty`
  • Loading branch information
weiznich authored Dec 19, 2024
2 parents 9861bcb + 31d2f1c commit 569639d
Show file tree
Hide file tree
Showing 4 changed files with 349 additions and 3 deletions.
15 changes: 13 additions & 2 deletions diesel/src/sqlite/expression/expression_methods.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Sqlite specific expression methods.
pub(in crate::sqlite) use self::private::{
BinaryOrNullableBinary, MaybeNullableValue, TextOrNullableText,
BinaryOrNullableBinary, JsonOrNullableJsonOrJsonbOrNullableJsonb, MaybeNullableValue,
TextOrNullableText,
};
use super::operators::*;
use crate::dsl;
Expand Down Expand Up @@ -87,7 +88,7 @@ pub trait SqliteExpressionMethods: Expression + Sized {
impl<T: Expression> SqliteExpressionMethods for T {}

pub(in crate::sqlite) mod private {
use crate::sql_types::{Binary, MaybeNullableType, Nullable, SingleValue, Text};
use crate::sql_types::{Binary, Json, Jsonb, MaybeNullableType, Nullable, SingleValue, Text};

#[diagnostic::on_unimplemented(
message = "`{Self}` is neither `diesel::sql_types::Text` nor `diesel::sql_types::Nullable<Text>`",
Expand All @@ -107,6 +108,16 @@ pub(in crate::sqlite) mod private {
impl BinaryOrNullableBinary for Binary {}
impl BinaryOrNullableBinary for Nullable<Binary> {}

#[diagnostic::on_unimplemented(
message = "`{Self}` is neither `diesel::sql_types::Json`, `diesel::sql_types::Jsonb`, `diesel::sql_types::Nullable<Json>` nor `diesel::sql_types::Nullable<Jsonb>`",
note = "try to provide an expression that produces one of the expected sql types"
)]
pub trait JsonOrNullableJsonOrJsonbOrNullableJsonb {}
impl JsonOrNullableJsonOrJsonbOrNullableJsonb for Json {}
impl JsonOrNullableJsonOrJsonbOrNullableJsonb for Nullable<Json> {}
impl JsonOrNullableJsonOrJsonbOrNullableJsonb for Jsonb {}
impl JsonOrNullableJsonOrJsonbOrNullableJsonb for Nullable<Jsonb> {}

pub trait MaybeNullableValue<T>: SingleValue {
type Out: SingleValue;
}
Expand Down
317 changes: 317 additions & 0 deletions diesel/src/sqlite/expression/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use crate::expression::functions::define_sql_function;
use crate::sql_types::*;
use crate::sqlite::expression::expression_methods::BinaryOrNullableBinary;
use crate::sqlite::expression::expression_methods::JsonOrNullableJsonOrJsonbOrNullableJsonb;
use crate::sqlite::expression::expression_methods::MaybeNullableValue;
use crate::sqlite::expression::expression_methods::TextOrNullableText;

Expand Down Expand Up @@ -105,3 +106,319 @@ define_sql_function! {
/// ```
fn jsonb<E: BinaryOrNullableBinary + MaybeNullableValue<Jsonb>>(e: E) -> E::Out;
}

#[cfg(feature = "sqlite")]
define_sql_function! {
/// Converts the given json value to pretty-printed, indented text
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// #
/// # fn main() {
/// # #[cfg(feature = "serde_json")]
/// # run_test().unwrap();
/// # }
/// #
/// # #[cfg(feature = "serde_json")]
/// # fn run_test() -> QueryResult<()> {
/// # use diesel::dsl::{sql, json_pretty};
/// # use serde_json::{json, Value};
/// # use diesel::sql_types::{Text, Json, Jsonb, Nullable};
/// # let connection = &mut establish_connection();
///
/// let version = diesel::select(sql::<Text>("sqlite_version();"))
/// .get_result::<String>(connection)?;
///
/// // Querying SQLite version should not fail.
/// let version_components: Vec<&str> = version.split('.').collect();
/// let major: u32 = version_components[0].parse().unwrap();
/// let minor: u32 = version_components[1].parse().unwrap();
/// let patch: u32 = version_components[2].parse().unwrap();
///
/// if major > 3 || (major == 3 && minor >= 46) {
/// /* Valid sqlite version, do nothing */
/// } else {
/// println!("SQLite version is too old, skipping the test.");
/// return Ok(());
/// }
///
/// let result = diesel::select(json_pretty::<Json, _>(json!([{"f1":1,"f2":null},2,null,3])))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!({"a": 1, "b": "cd"})))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{
/// "a": 1,
/// "b": "cd"
/// }"#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!("abc")))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#""abc""#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!(22)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"22"#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!(false)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"false"#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!(null)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"null"#, result);
///
/// let result = diesel::select(json_pretty::<Json, _>(json!({})))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{}"#, result);
///
/// let result = diesel::select(json_pretty::<Nullable<Json>, _>(None::<Value>))
/// .get_result::<Option<String>>(connection)?;
///
/// assert!(result.is_none());
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!([{"f1":1,"f2":null},2,null,3])))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!({"a": 1, "b": "cd"})))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{
/// "a": 1,
/// "b": "cd"
/// }"#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!("abc")))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#""abc""#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!(22)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"22"#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!(false)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"false"#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!(null)))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"null"#, result);
///
/// let result = diesel::select(json_pretty::<Jsonb, _>(json!({})))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{}"#, result);
///
/// let result = diesel::select(json_pretty::<Nullable<Jsonb>, _>(None::<Value>))
/// .get_result::<Option<String>>(connection)?;
///
/// assert!(result.is_none());
/// # Ok(())
/// # }
/// ```
fn json_pretty<J: JsonOrNullableJsonOrJsonbOrNullableJsonb + MaybeNullableValue<Text>>(j: J) -> J::Out;
}

#[cfg(feature = "sqlite")]
define_sql_function! {
/// Converts the given json value to pretty-printed, indented text
///
/// # Example
///
/// ```rust
/// # include!("../../doctest_setup.rs");
/// #
/// # fn main() {
/// # #[cfg(feature = "serde_json")]
/// # run_test().unwrap();
/// # }
/// #
/// # #[cfg(feature = "serde_json")]
/// # fn run_test() -> QueryResult<()> {
/// # use diesel::dsl::{sql, json_pretty_with_indentation};
/// # use serde_json::{json, Value};
/// # use diesel::sql_types::{Text, Json, Jsonb, Nullable};
/// # let connection = &mut establish_connection();
///
/// let version = diesel::select(sql::<Text>("sqlite_version();"))
/// .get_result::<String>(connection)?;
///
/// // Querying SQLite version should not fail.
/// let version_components: Vec<&str> = version.split('.').collect();
/// let major: u32 = version_components[0].parse().unwrap();
/// let minor: u32 = version_components[1].parse().unwrap();
/// let patch: u32 = version_components[2].parse().unwrap();
///
/// if major > 3 || (major == 3 && minor >= 46) {
/// /* Valid sqlite version, do nothing */
/// } else {
/// println!("SQLite version is too old, skipping the test.");
/// return Ok(());
/// }
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!([{"f1":1,"f2":null},2,null,3]), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!([{"f1":1,"f2":null},2,null,3]), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!({"a": 1, "b": "cd"}), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{
/// "a": 1,
/// "b": "cd"
/// }"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!("abc"), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#""abc""#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!(22), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"22"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!(false), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"false"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!(null), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"null"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Json, _, _>(json!({}), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{}"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Nullable<Json>, _, _>(None::<Value>, None::<&str>))
/// .get_result::<Option<String>>(connection)?;
///
/// assert!(result.is_none());
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!([{"f1":1,"f2":null},2,null,3]), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!([{"f1":1,"f2":null},2,null,3]), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"[
/// {
/// "f1": 1,
/// "f2": null
/// },
/// 2,
/// null,
/// 3
/// ]"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!({"a": 1, "b": "cd"}), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{
/// "a": 1,
/// "b": "cd"
/// }"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!("abc"), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#""abc""#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!(22), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"22"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!(false), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"false"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!(null), None::<&str>))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"null"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Jsonb, _, _>(json!({}), " "))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{}"#, result);
///
/// let result = diesel::select(json_pretty_with_indentation::<Nullable<Jsonb>, _, _>(None::<Value>, None::<&str>))
/// .get_result::<Option<String>>(connection)?;
///
/// assert!(result.is_none());
///
/// # Ok(())
/// # }
/// ```
#[sql_name = "json_pretty"]
fn json_pretty_with_indentation<J: JsonOrNullableJsonOrJsonbOrNullableJsonb + MaybeNullableValue<Text>>(j: J, indentation: Nullable<Text>) -> J::Out;
}
11 changes: 11 additions & 0 deletions diesel/src/sqlite/expression/helper_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,14 @@ pub type json<E> = super::functions::json<SqlTypeOf<E>, E>;
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type jsonb<E> = super::functions::jsonb<SqlTypeOf<E>, E>;

/// Return type of [`json_pretty(json)`](super::functions::json_pretty())
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type json_pretty<E> = super::functions::json_pretty<SqlTypeOf<E>, E>;

/// Return type of [`json_pretty(json, indent)`](super::functions::json_pretty_with_indentation())
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type json_pretty_with_indentation<J, I> =
super::functions::json_pretty_with_indentation<SqlTypeOf<J>, J, I>;
9 changes: 8 additions & 1 deletion diesel_derives/tests/auto_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,14 @@ fn postgres_functions() -> _ {
#[cfg(feature = "sqlite")]
#[auto_type]
fn sqlite_functions() -> _ {
(json(sqlite_extras::text), jsonb(sqlite_extras::blob))
(
json(sqlite_extras::text),
jsonb(sqlite_extras::blob),
json_pretty(sqlite_extras::json),
json_pretty(sqlite_extras::jsonb),
json_pretty_with_indentation(sqlite_extras::json, " "),
json_pretty_with_indentation(sqlite_extras::jsonb, " "),
)
}

#[auto_type]
Expand Down

0 comments on commit 569639d

Please sign in to comment.