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 binary operators for Postgres' JSON traversal. #617

Merged
merged 1 commit into from
Mar 8, 2023
Merged
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
2 changes: 2 additions & 0 deletions src/backend/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ impl QueryBuilder for PostgresQueryBuilder {
PgBinOper::SimilarityDistance => "<->",
PgBinOper::WordSimilarityDistance => "<<->",
PgBinOper::StrictWordSimilarityDistance => "<<<->",
PgBinOper::GetJsonField => "->",
PgBinOper::CastJsonField => "->>",
}
)
.unwrap(),
Expand Down
4 changes: 4 additions & 0 deletions src/extension/postgres/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub enum PgBinOper {
SimilarityDistance,
WordSimilarityDistance,
StrictWordSimilarityDistance,
/// `->`. Retrieves JSON field as JSON value.
GetJsonField,
/// `->>`. Retrieves JSON field and casts it to an appropriate SQL type.
CastJsonField,
}

impl From<PgBinOper> for BinOper {
Expand Down
34 changes: 34 additions & 0 deletions tests/postgres/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1782,3 +1782,37 @@ fn sub_query_with_fn() {
r#"SELECT ARRAY((SELECT * FROM "character"))"#
);
}

#[test]
fn get_json_field_bin_oper() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where(
Expr::col(Char::Character).binary(PgBinOper::GetJsonField, Expr::val("test"))
)
.build(PostgresQueryBuilder),
(
r#"SELECT "character" FROM "character" WHERE "character" -> $1"#.to_owned(),
Values(vec!["test".into()])
)
);
}

#[test]
fn cast_json_field_bin_oper() {
assert_eq!(
Query::select()
.column(Char::Character)
.from(Char::Table)
.and_where(
Expr::col(Char::Character).binary(PgBinOper::CastJsonField, Expr::val("test"))
)
.build(PostgresQueryBuilder),
(
r#"SELECT "character" FROM "character" WHERE "character" ->> $1"#.to_owned(),
Values(vec!["test".into()])
)
);
}