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

feat: add boolean test qual support #341

Merged
merged 1 commit into from
Sep 19, 2024
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
6 changes: 6 additions & 0 deletions supabase-wrappers/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ impl CellFormatter for DefaultFormatter {
format!("{}", cell)
}
}

/// A data row in a table
///
/// The row contains a column name list and cell list with same number of
Expand Down Expand Up @@ -353,6 +354,11 @@ pub struct Param {
/// ```
///
/// ```sql
/// where bool_col is true
/// -- [Qual { field: "bool_col", operator: "is", value: Cell(Bool(true)), use_or: false }]
/// ```
///
/// ```sql
/// where id > 1 and col = 'foo';
/// -- [
/// -- Qual { field: "id", operator: ">", value: Cell(I32(1)), use_or: false },
Expand Down
32 changes: 32 additions & 0 deletions supabase-wrappers/src/qual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,36 @@ pub(crate) unsafe fn extract_from_bool_expr(
Some(qual)
}

pub(crate) unsafe fn extract_from_boolean_test(
baserel_id: pg_sys::Oid,
expr: *mut pg_sys::BooleanTest,
) -> Option<Qual> {
let var = (*expr).arg as *mut pg_sys::Var;
if !is_a(var as _, pg_sys::NodeTag::T_Var) || (*var).varattno < 1 {
return None;
}

let field = pg_sys::get_attname(baserel_id, (*var).varattno, false);

let (opname, value) = match (*expr).booltesttype {
pg_sys::BoolTestType_IS_TRUE => ("is".to_string(), true),
pg_sys::BoolTestType_IS_FALSE => ("is".to_string(), false),
pg_sys::BoolTestType_IS_NOT_TRUE => ("is not".to_string(), true),
pg_sys::BoolTestType_IS_NOT_FALSE => ("is not".to_string(), false),
_ => return None,
};

let qual = Qual {
field: CStr::from_ptr(field).to_str().unwrap().to_string(),
operator: opname,
value: Value::Cell(Cell::Bool(value)),
use_or: false,
param: None,
};

Some(qual)
}

pub(crate) unsafe fn extract_quals(
root: *mut pg_sys::PlannerInfo,
baserel: *mut pg_sys::RelOptInfo,
Expand All @@ -323,6 +353,8 @@ pub(crate) unsafe fn extract_quals(
extract_from_var(root, baserel_id, (*baserel).relids, expr as _)
} else if is_a(expr, pg_sys::NodeTag::T_BoolExpr) {
extract_from_bool_expr(root, baserel_id, (*baserel).relids, expr as _)
} else if is_a(expr, pg_sys::NodeTag::T_BooleanTest) {
extract_from_boolean_test(baserel_id, expr as _)
} else {
if let Some(stm) = pgrx::nodes::node_to_string(expr) {
report_warning(&format!("unsupported qual: {}", stm));
Expand Down
1 change: 1 addition & 0 deletions wrappers/src/fdw/mssql_fdw/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ This is a foreign data wrapper for [Microsoft SQL Server](https://www.microsoft.

| Version | Date | Notes |
| ------- | ---------- | ---------------------------------------------------- |
| 0.1.1 | 2024-09-09 | Add boolean test qual support |
| 0.1.0 | 2023-12-27 | Initial version |

30 changes: 28 additions & 2 deletions wrappers/src/fdw/mssql_fdw/mssql_fdw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,20 @@ fn field_to_cell(src_row: &tiberius::Row, tgt_col: &Column) -> MssqlFdwResult<Op
Ok(ret)
}

struct MssqlCellFormatter {}

impl CellFormatter for MssqlCellFormatter {
fn fmt_cell(&mut self, cell: &Cell) -> String {
match cell {
// format boolean type to 0 or 1
Cell::Bool(v) => format!("{}", *v as u8),
_ => format!("{}", cell),
}
}
}

#[wrappers_fdw(
version = "0.1.0",
version = "0.1.1",
author = "Supabase",
website = "https://github.com/supabase/wrappers/tree/main/wrappers/src/fdw/mssql_fdw",
error_type = "MssqlFdwError"
Expand Down Expand Up @@ -120,7 +132,21 @@ impl MssqlFdw {
if !quals.is_empty() {
let cond = quals
.iter()
.map(|q| q.deparse())
.map(|q| {
let oper = q.operator.as_str();
let mut fmt = MssqlCellFormatter {};
if let Value::Cell(cell) = &q.value {
// deparse boolean test qual, e.g. "bool_col is true" => "bool_col = 1"
if let Cell::Bool(_) = cell {
if oper == "is" {
return format!("{} = {}", q.field, fmt.fmt_cell(cell));
} else if oper == "is not" {
return format!("{} <> {}", q.field, fmt.fmt_cell(cell));
}
}
}
q.deparse_with_fmt(&mut fmt)
})
.collect::<Vec<String>>()
.join(" and ");

Expand Down
19 changes: 16 additions & 3 deletions wrappers/src/fdw/mssql_fdw/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mod tests {
r#"CREATE TABLE users (
id bigint,
name varchar(30),
is_admin bit,
dt datetime2
)"#,
&[],
Expand All @@ -46,9 +47,9 @@ mod tests {
client
.execute(
r#"
INSERT INTO users(id, name, dt) VALUES (42, 'foo', '2023-12-28');
INSERT INTO users(id, name, dt) VALUES (43, 'bar', '2023-12-27');
INSERT INTO users(id, name, dt) VALUES (44, 'baz', '2023-12-26');
INSERT INTO users(id, name, is_admin, dt) VALUES (42, 'foo', 0, '2023-12-28');
INSERT INTO users(id, name, is_admin, dt) VALUES (43, 'bar', 1, '2023-12-27');
INSERT INTO users(id, name, is_admin, dt) VALUES (44, 'baz', 0, '2023-12-26');
"#,
&[],
)
Expand Down Expand Up @@ -79,6 +80,7 @@ mod tests {
CREATE FOREIGN TABLE mssql_users (
id bigint,
name text,
is_admin boolean,
dt timestamp
)
SERVER mssql_server
Expand Down Expand Up @@ -163,6 +165,17 @@ mod tests {
.filter_map(|r| r.get_by_name::<&str, _>("name").unwrap())
.collect::<Vec<_>>();
assert_eq!(results, vec!["foo", "bar"]);

let results = c
.select(
"SELECT name FROM mssql_users WHERE is_admin is true",
None,
None,
)
.unwrap()
.filter_map(|r| r.get_by_name::<&str, _>("name").unwrap())
.collect::<Vec<_>>();
assert_eq!(results, vec!["bar"]);
});

let result = std::panic::catch_unwind(|| {
Expand Down
Loading