Skip to content

feat(sqlite): Add json_extract and jsonb_extract functions #4530

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
196 changes: 195 additions & 1 deletion diesel/src/sqlite/expression/functions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! SQLite specific functions
use crate::expression::functions::declare_sql_function;
use crate::expression::{functions::declare_sql_function, AsExpression};
use crate::sql_types::*;
use crate::sqlite::expression::expression_methods::BinaryOrNullableBinary;
use crate::sqlite::expression::expression_methods::JsonOrNullableJson;
Expand Down Expand Up @@ -892,4 +892,198 @@ extern "SQL" {
j: J,
path: Text,
) -> Nullable<Text>;

/// The json_extract(X,P1,P2,...) extracts and returns one or more values from the well-formed JSON at X.
///
/// If only a single path P1 is provided, then the SQL datatype of the result is NULL for a JSON null,
/// INTEGER or REAL for a JSON numeric value, an INTEGER zero for a JSON false value, an INTEGER one for a JSON true value,
/// the dequoted text for a JSON string value, and a text representation for JSON object and array values.
Comment on lines +898 to +900
Copy link
Member

Choose a reason for hiding this comment

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

That means the signature as expressed below doesn't really match what is returned by the function. Given that is is essentially a runtime determined value I do not have any good recommendation how to make this work with diesels static checking.

I could imaging to expose just several variants of this function, so json_extract_as_text, json_extract_as_integer, json_extract_as_float and json_extract_as_json for the different return type variants and let the users chose the right one for their usecase. After all you can even convert any sql return value to any other type internally.

///
/// If there are multiple path arguments (P1, P2, and so forth) then this routine returns SQLite text
/// which is a well-formed JSON array holding the various values.
Comment on lines +902 to +903
Copy link
Member

Choose a reason for hiding this comment

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

This part is not possible with the function signature below. This refers to a use case where you would call json_extract(json_col, path_1, path_2) which is disallowed by the signature.

///
/// # 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_extract};
/// # use serde_json::{json, Value};
/// # use diesel::sql_types::{Text, Json, 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 >= 38) {
/// /* Valid sqlite version, do nothing */
/// } else {
/// println!("SQLite version is too old, skipping the test.");
/// return Ok(());
/// }
///
/// let json_obj = json!({"a": 2, "c": [4, 5, {"f": 7}]});
///
/// // Extract the entire JSON object
/// let result = diesel::select(json_extract::<Json, _>(json_obj.clone(), "$"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!({"a": 2, "c": [4, 5, {"f": 7}]}));
///
/// // Extract a nested array
/// let result = diesel::select(json_extract::<Json, _>(json_obj.clone(), "$.c"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!([4, 5, {"f": 7}]));
///
/// // Extract a nested object
/// let result = diesel::select(json_extract::<Json, _>(json_obj.clone(), "$.c[2]"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!({"f": 7}));
///
/// // Extract a numeric value
/// let result = diesel::select(json_extract::<Json, _>(json_obj.clone(), "$.c[2].f"))
/// .get_result::<i64>(connection)?;
/// assert_eq!(result, 7);
///
/// // Extract a non-existent path (returns NULL)
/// let result = diesel::select(json_extract::<Json, _>(json_obj.clone(), "$.x"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// // Extract a string value
/// let json_with_string = json!({"a": "xyz"});
/// let result = diesel::select(json_extract::<Json, _>(json_with_string, "$.a"))
/// .get_result::<String>(connection)?;
/// assert_eq!(result, "xyz");
///
/// // Extract a null value
/// let json_with_null = json!({"a": null});
/// let result = diesel::select(json_extract::<Json, _>(json_with_null, "$.a"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// // Test with NULL JSON input
/// let result = diesel::select(json_extract::<Nullable<Json>, _>(None::<Value>, "$.a"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sqlite")]
fn json_extract<
J: JsonOrNullableJsonOrJsonbOrNullableJsonb + SingleValue,
P: AsExpression<Text> + SingleValue,
>(
j: J,
path: P,
) -> Nullable<Text>;

/// The jsonb_extract() function works the same as the json_extract() function, except in cases
/// where json_extract() would normally return a text JSON array object, this routine returns
/// the array or object in the JSONB format.
///
/// For the common case where a text, numeric, null, or boolean JSON element is returned,
/// this routine works exactly the same as json_extract().
///
/// # 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, jsonb_extract};
/// # use serde_json::{json, Value};
/// # use diesel::sql_types::{Text, 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 >= 45) {
/// /* Valid sqlite version, do nothing */
/// } else {
/// println!("SQLite version is too old, skipping the test.");
/// return Ok(());
/// }
///
/// let json_obj = json!({"a": 2, "c": [4, 5, {"f": 7}]});
///
/// // Extract the entire JSON object
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_obj.clone(), "$"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!({"a": 2, "c": [4, 5, {"f": 7}]}));
///
/// // Extract a nested array
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_obj.clone(), "$.c"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!([4, 5, {"f": 7}]));
///
/// // Extract a nested object
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_obj.clone(), "$.c[2]"))
/// .get_result::<Value>(connection)?;
/// assert_eq!(result, json!({"f": 7}));
///
/// // Extract a numeric value
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_obj.clone(), "$.c[2].f"))
/// .get_result::<i64>(connection)?;
/// assert_eq!(result, 7);
///
/// // Extract a non-existent path (returns NULL)
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_obj.clone(), "$.x"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// // Extract a string value
/// let json_with_string = json!({"a": "xyz"});
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_with_string, "$.a"))
/// .get_result::<String>(connection)?;
/// assert_eq!(result, "xyz");
///
/// // Extract a null value
/// let json_with_null = json!({"a": null});
/// let result = diesel::select(jsonb_extract::<Jsonb, _>(json_with_null, "$.a"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// // Test with NULL JSON input
/// let result = diesel::select(jsonb_extract::<Nullable<Jsonb>, _>(None::<Value>, "$.a"))
/// .get_result::<Option<Value>>(connection)?;
/// assert_eq!(result, None);
///
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sqlite")]
fn jsonb_extract<
J: JsonOrNullableJsonOrJsonbOrNullableJsonb + SingleValue,
P: AsExpression<Text> + SingleValue,
>(
j: J,
path: P,
) -> Nullable<Text>;
}
10 changes: 10 additions & 0 deletions diesel/src/sqlite/expression/helper_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ pub type json_type<E> = super::functions::json_type<SqlTypeOf<E>, E>;
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type json_type_with_path<J, P> = super::functions::json_type_with_path<SqlTypeOf<J>, J, P>;

/// Return type of [`json_extract(json, path)`](super::functions::json_extract())
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type json_extract<J, P> = super::functions::json_extract<J, P, J, P>;
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
pub type json_extract<J, P> = super::functions::json_extract<J, P, J, P>;
pub type json_extract<J, P> = super::functions::json_extract<SqlTypeOf<J>, SqlTypeOf<P>, J, P>;

To fix the compilation errors


/// Return type of [`jsonb_extract(json, path)`](super::functions::jsonb_extract())
#[allow(non_camel_case_types)]
#[cfg(feature = "sqlite")]
pub type jsonb_extract<J, P> = super::functions::jsonb_extract<J, P, J, P>;
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
pub type jsonb_extract<J, P> = super::functions::jsonb_extract<J, P, J, P>;
pub type jsonb_extract<J, P> = super::functions::jsonb_extract<SqlTypeOf<J>, SqlTypeOf<P>, J, P>;

to fix the compilation errors

2 changes: 2 additions & 0 deletions diesel_derives/tests/auto_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,8 @@ fn sqlite_functions() -> _ {
json_valid(sqlite_extras::json),
json_type(sqlite_extras::json),
json_type_with_path(sqlite_extras::json, sqlite_extras::text),
json_extract(sqlite_extras::json, sqlite_extras::text),
jsonb_extract(sqlite_extras::jsonb, sqlite_extras::text),
)
}

Expand Down
Loading