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 SQLite function json_pretty #4395

Merged
merged 5 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
11 changes: 11 additions & 0 deletions diesel/src/sqlite/expression/expression_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub(in crate::sqlite) use self::private::{
BinaryOrNullableBinary, MaybeNullableValue, TextOrNullableText,
TextOrNullableTextOrBinaryOrNullableBinary,
};
use super::operators::*;
use crate::dsl;
Expand Down Expand Up @@ -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 not `diesel::sql_types::Text`, `diesel::sql_types::Nullable<Text>`, `diesel::sql_types::Binary` or `diesel::sql_types::Nullable<Binary>`",
note = "try to provide an expression that produces one of the expected sql types"
)]
pub trait TextOrNullableTextOrBinaryOrNullableBinary {}
impl TextOrNullableTextOrBinaryOrNullableBinary for Text {}
impl TextOrNullableTextOrBinaryOrNullableBinary for Nullable<Text> {}
impl TextOrNullableTextOrBinaryOrNullableBinary for Binary {}
impl TextOrNullableTextOrBinaryOrNullableBinary for Nullable<Binary> {}

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

#[cfg(feature = "sqlite")]
define_sql_function! {
Expand Down Expand Up @@ -105,3 +106,110 @@ 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, Binary, 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::<Text, _>(r#"[{"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::<Binary, _>(br#"[{"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::<Text, _>(r#"{"a": 1, "b": "cd"}"#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{
/// "a": 1,
/// "b": "cd"
/// }"#, result);
///
/// let result = diesel::select(json_pretty::<Text, _>(r#""abc""#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#""abc""#, result);
///
/// let result = diesel::select(json_pretty::<Text, _>(r#"22"#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"22"#, result);
///
/// let result = diesel::select(json_pretty::<Text, _>(r#"false"#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"false"#, result);
///
/// let result = diesel::select(json_pretty::<Text, _>(r#"null"#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"null"#, result);
///
/// let result = diesel::select(json_pretty::<Text, _>(r#"{}"#))
/// .get_result::<String>(connection)?;
///
/// assert_eq!(r#"{}"#, result);
///
/// let result = diesel::select(json_pretty::<Nullable<Text>, _>(None::<&str>))
/// .get_result::<Option<String>>(connection)?;
///
/// assert!(result.is_none());
///
/// # Ok(())
/// # }
/// ```
fn json_pretty<E: TextOrNullableTextOrBinaryOrNullableBinary + MaybeNullableValue<Text>>(e: E) -> E::Out;
Copy link
Member

@weiznich weiznich Dec 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this signature is unfortunately not correct yet. The sqlite documentation says:

The json_pretty() function works like json() except that it adds extra whitespace to make the JSON result easier for humans to read. The first argument is the JSON or JSONB that is to be pretty-printed. The optional second argument is a text string that is used for indentation. If the second argument is omitted or is NULL, then indentation is four spaces per level.

which would translate to

fn json_pretty<J: JsonOrJsonbOrNullableJson + MaybeNullableValue<Text>>(j: J) -> J::Out;

this then would require users to call it that way: select(json_pretty(json("your_json_text")) or select(json_pretty(jsonb(b"your_json_blob"))

As for the optional second argument: We normally deal with that by having a second function definition for this for that.

So something like:

#[sql_name = "json_pretty"]
fn json_pretty_with_indentation<J: JsonOrJsonbOrNullableJson + MaybeNullableValue<Text>>(j: J, indentation: Nullable<Text>) -> J::Out;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very helpful for me since I'm new to diesel ! Well, are you sure we should use JsonOrJsonbOrNullableJson ? I found JsonOrNullableJsonOrJsonbOrNullableJsonb in the PostgreSQL implementation, which adds nullable JSONB implementation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are correct we want to use JsonOrNullableJsonOrJsonbOrNullableJsonb there (any likely also for most of the other sqlite json functions).

}
5 changes: 5 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,8 @@ 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>;
7 changes: 6 additions & 1 deletion diesel_derives/tests/auto_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,12 @@ 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::text),
json_pretty(sqlite_extras::blob),
)
}

#[auto_type]
Expand Down
Loading