Skip to content

Commit

Permalink
Add binary operators for Postgres' JSON traversal.
Browse files Browse the repository at this point in the history
  • Loading branch information
TannerRogalsky committed Mar 7, 2023
1 parent b0d1a40 commit 8ce29cd
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
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()])
)
);
}

0 comments on commit 8ce29cd

Please sign in to comment.