Skip to content

Commit

Permalink
safely handle missing parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
Mause committed Jan 2, 2024
1 parent 9539419 commit 588e4d4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
21 changes: 18 additions & 3 deletions src/vtab/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,18 @@ impl BindInfo {
/// * `index`: The index of the parameter to get
///
/// returns: The value of the parameter
///
/// # Panics
/// If requested parameter is out of range for function definition
pub fn get_parameter(&self, param_index: u64) -> Value {
unsafe { Value::from(duckdb_bind_get_parameter(self.ptr, param_index)) }
unsafe {
let ptr = duckdb_bind_get_parameter(self.ptr, param_index);
if ptr.is_null() {
panic!("{} is out of range for function definition", param_index);
} else {
Value::from(ptr)
}
}
}

/// Retrieves the named parameter with the given name.
Expand All @@ -75,10 +85,15 @@ impl BindInfo {
/// * `name`: The name of the parameter to get
///
/// returns: The value of the parameter
pub fn get_named_parameter(&self, name: &str) -> Value {
pub fn get_named_parameter(&self, name: &str) -> Option<Value> {
unsafe {
let name = &CString::new(name).unwrap();
Value::from(duckdb_bind_get_named_parameter(self.ptr, name.as_ptr()))
let ptr = duckdb_bind_get_named_parameter(self.ptr, name.as_ptr());
if ptr.is_null() {
None
} else {
Some(Value::from(ptr))
}
}
}

Expand Down
7 changes: 2 additions & 5 deletions src/vtab/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,6 @@ mod test {
fn parameters() -> Option<Vec<LogicalType>> {
Some(vec![LogicalType::new(LogicalTypeId::Varchar)])
}

fn named_parameters() -> Option<Vec<(std::string::String, logical_type::LogicalType)>> {
Some(vec![("name".to_string(), LogicalType::new(LogicalTypeId::Varchar))])
}
}

struct HelloWithNamedVTab {}
Expand All @@ -251,7 +247,8 @@ mod test {

fn bind(bind: &BindInfo, data: *mut HelloBindData) -> Result<(), Box<dyn Error>> {
bind.add_result_column("column0", LogicalType::new(LogicalTypeId::Varchar));
let param = bind.get_named_parameter("name").to_string();
let param = bind.get_named_parameter("name").unwrap().to_string();
assert!(bind.get_named_parameter("unknown_name").is_none());
unsafe {
(*data).name = CString::new(param).unwrap().into_raw();
}
Expand Down

0 comments on commit 588e4d4

Please sign in to comment.