pub enum SqlResult<T> {
Success(T),
SuccessWithInfo(T),
NoData,
NeedData,
StillExecuting,
Error {
function: &'static str,
},
}Expand description
Result of an ODBC function call. Variants hold the same meaning as the constants associated with
SqlReturn. This type may hold results, but it is still the responsibility of the user to
fetch and handle the diagnostics in case of an Error.
Variants§
Success(T)
The function has been executed successfully.
SuccessWithInfo(T)
The function has been executed successfully. There have been warnings.
NoData
Meaning depends on the function emitting NoData.
NeedData
Emmitted by execute in case delayed parameters have been bound and their input values are now required.
StillExecuting
The function was started asynchronously and is still executing.
Error
Fields
The function returned an error state. Check diagnostics.
Implementations§
source§impl SqlResult<()>
impl SqlResult<()>
sourcepub fn into_result_bool(self, handle: &impl Diagnostics) -> Result<bool, Error>
pub fn into_result_bool(self, handle: &impl Diagnostics) -> Result<bool, Error>
Use this instead of Self::into_result if you expect SqlResult::NoData to be a
valid value. SqlResult::NoData is mapped to Ok(false), all other success values are
Ok(true).
Examples found in repository?
53 54 55 56 57 58 59 60 61 62 63 64 65
fn next_row(&mut self) -> Result<Option<CursorRow<'_>>, Error> {
let row_available = unsafe {
self.as_stmt_ref()
.fetch()
.into_result_bool(&self.as_stmt_ref())?
};
let ret = if row_available {
Some(unsafe { CursorRow::new(self.as_stmt_ref()) })
} else {
None
};
Ok(ret)
}More examples
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
pub unsafe fn driver_connect_with_hwnd(
&self,
connection_string: &str,
completed_connection_string: &mut OutputStringBuffer,
driver_completion: DriverCompleteOption,
parent_window: HWnd,
) -> Result<Connection<'_>, Error> {
let mut connection = self.allocate_connection()?;
let connection_string = SqlText::new(connection_string);
let connection_string_is_complete = connection
.driver_connect(
&connection_string,
parent_window,
completed_connection_string,
driver_completion.as_sys(),
)
.into_result_bool(&connection)?;
if !connection_string_is_complete {
return Err(Error::AbortedConnectionStringCompletion);
}
Ok(Connection::new(connection))
}
/// Get information about available drivers. Only 32 or 64 Bit drivers will be listed, depending
/// on wether you are building a 32 Bit or 64 Bit application.
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new ()?;
/// for driver_info in env.drivers()? {
/// println!("{:#?}", driver_info);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn drivers(&self) -> Result<Vec<DriverInfo>, Error> {
let mut driver_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut desc_len, mut attr_len) = if let Some(res) = self
.environment
// Start with first so we are independent of state
.drivers_buffer_len(FetchOrientation::First)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are, let's loop over the remaining drivers
while let Some((candidate_desc_len, candidate_attr_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
desc_len = max(candidate_desc_len, desc_len);
attr_len = max(candidate_attr_len, attr_len);
}
// Allocate +1 character extra for terminating zero
let mut desc_buf = SzBuffer::with_capacity(desc_len as usize);
let mut attr_buf = SzBuffer::with_capacity(attr_len as usize);
while self
.environment
.drivers_buffer_fill(
FetchOrientation::Next,
desc_buf.mut_buf(),
attr_buf.mut_buf(),
)
.into_result_bool(&self.environment)?
{
let description = desc_buf.to_utf8();
let attributes = attr_buf.to_utf8();
let attributes = attributes_iter(&attributes).collect();
driver_info.push(DriverInfo {
description,
attributes,
});
}
}
Ok(driver_info)
}
/// User and system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new()?;
/// for data_source in env.data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::First)
}
/// Only system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new ()?;
/// for data_source in env.system_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn system_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstSystem)
}
/// Only user data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let mut env = unsafe { Environment::new () }?;
/// for data_source in env.user_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn user_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstUser)
}
fn data_sources_impl(&self, direction: FetchOrientation) -> Result<Vec<DataSourceInfo>, Error> {
let mut data_source_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut server_name_len, mut driver_len) = if let Some(res) = self
.environment
.data_source_buffer_len(direction)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are let's loop over the rest
while let Some((candidate_name_len, candidate_decs_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
server_name_len = max(candidate_name_len, server_name_len);
driver_len = max(candidate_decs_len, driver_len);
}
let mut server_name_buf = SzBuffer::with_capacity(server_name_len as usize);
let mut driver_buf = SzBuffer::with_capacity(driver_len as usize);
let mut not_empty = self
.environment
.data_source_buffer_fill(direction, server_name_buf.mut_buf(), driver_buf.mut_buf())
.into_result_bool(&self.environment)?;
while not_empty {
let server_name = server_name_buf.to_utf8();
let driver = driver_buf.to_utf8();
data_source_info.push(DataSourceInfo {
server_name,
driver,
});
not_empty = self
.environment
.data_source_buffer_fill(
FetchOrientation::Next,
server_name_buf.mut_buf(),
driver_buf.mut_buf(),
)
.into_result_bool(&self.environment)?;
}
}
Ok(data_source_info)
}source§impl<T> SqlResult<T>
impl<T> SqlResult<T>
sourcepub fn into_result(self, handle: &impl Diagnostics) -> Result<T, Error>
pub fn into_result(self, handle: &impl Diagnostics) -> Result<T, Error>
Self::Success and Self::SuccessWithInfo are mapped to Ok. In case of
Self::SuccessWithInfo any diagnostics are logged. Self::Error is mapped to error.
Examples found in repository?
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
unsafe fn bind_input_parameters_to(&self, stmt: &mut impl Statement) -> Result<(), Error> {
stmt.bind_input_parameter(1, self).into_result(stmt)
}
}
unsafe impl<T> InputParameterCollection for [T]
where
T: InputParameter,
{
fn parameter_set_size(&self) -> usize {
1
}
unsafe fn bind_input_parameters_to(&self, stmt: &mut impl Statement) -> Result<(), Error> {
for (index, parameter) in self.iter().enumerate() {
stmt.bind_input_parameter(index as u16 + 1, parameter)
.into_result(stmt)?;
}
Ok(())
}More examples
97 98 99 100 101 102 103 104 105 106 107 108 109 110
unsafe fn bind_parameters_to(&mut self, stmt: &mut impl Statement) -> Result<(), Error> {
stmt.bind_delayed_input_parameter(1, self).into_result(stmt)
}
}
unsafe impl ParameterTupleElement for &mut BlobParam<'_> {
unsafe fn bind_to(
&mut self,
parameter_number: u16,
stmt: &mut impl Statement,
) -> Result<(), Error> {
stmt.bind_delayed_input_parameter(parameter_number, *self)
.into_result(stmt)
}57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
pub fn describe_param(&mut self, parameter_number: u16) -> Result<ParameterDescription, Error> {
let stmt = self.as_stmt_ref();
stmt.describe_param(parameter_number).into_result(&stmt)
}
/// Number of placeholders which must be provided with [`Self::execute`] in order to execute
/// this statement. This is equivalent to the number of placeholders used in the SQL string
/// used to prepare the statement.
pub fn num_params(&mut self) -> Result<u16, Error> {
let stmt = self.as_stmt_ref();
stmt.num_params().into_result(&stmt)
}
/// Number of placeholders which must be provided with [`Self::execute`] in order to execute
/// this statement. This is equivalent to the number of placeholders used in the SQL string
/// used to prepare the statement.
///
/// ```
/// use odbc_api::{Connection, Error, handles::ParameterDescription};
///
/// fn collect_parameter_descriptions(
/// connection: Connection<'_>
/// ) -> Result<Vec<ParameterDescription>, Error>{
/// // Note the two `?` used as placeholders for the parameters.
/// let sql = "INSERT INTO NationalDrink (country, drink) VALUES (?, ?)";
/// let mut prepared = connection.prepare(sql)?;
///
/// let params: Vec<_> = prepared.parameter_descriptions()?.collect::<Result<_,_>>()?;
///
/// Ok(params)
/// }
/// ```
pub fn parameter_descriptions(
&mut self,
) -> Result<
impl DoubleEndedIterator<Item = Result<ParameterDescription, Error>>
+ ExactSizeIterator<Item = Result<ParameterDescription, Error>>
+ '_,
Error,
> {
Ok((1..=self.num_params()?).map(|index| self.describe_param(index)))
}
/// Unless you want to roll your own column buffer implementation users are encouraged to use
/// [`Self::into_text_inserter`] instead.
///
/// # Safety
///
/// * Parameters must all be valid for insertion. An example for an invalid parameter would be
/// a text buffer with a cell those indiactor value exceeds the maximum element length. This
/// can happen after when truncation occurs then writing into a buffer.
pub unsafe fn unchecked_bind_columnar_array_parameters<C>(
self,
parameter_buffers: Vec<C>,
) -> Result<ColumnarBulkInserter<S, C>, Error>
where
C: ColumnBuffer + HasDataType,
{
// We know that statement is a prepared statement.
ColumnarBulkInserter::new(self.into_statement(), parameter_buffers)
}
/// Use this to insert rows of string input into the database.
///
/// ```
/// use odbc_api::{Connection, Error};
///
/// fn insert_text<'e>(connection: Connection<'e>) -> Result<(), Error>{
/// // Insert six rows of text with two columns each into the database in batches of 3. In a
/// // real usecase you are likely to achieve a better results with a higher batch size.
///
/// // Note the two `?` used as placeholders for the parameters.
/// let prepared = connection.prepare("INSERT INTO NationalDrink (country, drink) VALUES (?, ?)")?;
/// // We assume both parameter inputs never exceed 50 bytes.
/// let mut prebound = prepared.into_text_inserter(3, [50, 50])?;
///
/// // A cell is an option to byte. We could use `None` to represent NULL but we have no
/// // need to do that in this example.
/// let as_cell = |s: &'static str| { Some(s.as_bytes()) } ;
///
/// // First batch of values
/// prebound.append(["England", "Tea"].into_iter().map(as_cell))?;
/// prebound.append(["Germany", "Beer"].into_iter().map(as_cell))?;
/// prebound.append(["Russia", "Vodka"].into_iter().map(as_cell))?;
///
/// // Execute statement using values bound in buffer.
/// prebound.execute()?;
/// // Clear buffer contents, otherwise the previous values would stay in the buffer.
/// prebound.clear();
///
/// // Second batch of values
/// prebound.append(["India", "Tea"].into_iter().map(as_cell))?;
/// prebound.append(["France", "Wine"].into_iter().map(as_cell))?;
/// prebound.append(["USA", "Cola"].into_iter().map(as_cell))?;
///
/// // Send second batch to the database
/// prebound.execute()?;
///
/// Ok(())
/// }
/// ```
pub fn into_text_inserter(
self,
capacity: usize,
max_str_len: impl IntoIterator<Item = usize>,
) -> Result<ColumnarBulkInserter<S, TextColumn<u8>>, Error> {
let max_str_len = max_str_len.into_iter();
let parameter_buffers = max_str_len
.map(|max_str_len| TextColumn::new(capacity, max_str_len))
.collect();
// Text Columns are created with NULL as default, which is valid for insertion.
unsafe { self.unchecked_bind_columnar_array_parameters(parameter_buffers) }
}
/// A [`crate::ColumnarBulkInserter`] which takes ownership of both the statement and the bound
/// array parameter buffers.
///
/// ```no_run
/// use odbc_api::{Connection, Error, IntoParameter, buffers::BufferDesc};
///
/// fn insert_birth_years(
/// conn: &Connection,
/// names: &[&str],
/// years: &[i16]
/// ) -> Result<(), Error> {
/// // All columns must have equal length.
/// assert_eq!(names.len(), years.len());
///
/// let prepared = conn.prepare("INSERT INTO Birthdays (name, year) VALUES (?, ?)")?;
///
/// // Create a columnar buffer which fits the input parameters.
/// let buffer_description = [
/// BufferDesc::Text { max_str_len: 255 },
/// BufferDesc::I16 { nullable: false },
/// ];
/// // The capacity must be able to hold at least the largest batch. We do everything in one
/// // go, so we set it to the length of the input parameters.
/// let capacity = names.len();
/// // Allocate memory for the array column parameters and bind it to the statement.
/// let mut prebound = prepared.into_column_inserter(capacity, buffer_description)?;
/// // Length of this batch
/// prebound.set_num_rows(capacity);
///
///
/// // Fill the buffer with values column by column
/// let mut col = prebound
/// .column_mut(0)
/// .as_text_view()
/// .expect("We know the name column to hold text.");
///
/// for (index, name) in names.iter().enumerate() {
/// col.set_cell(index, Some(name.as_bytes()));
/// }
///
/// let col = prebound
/// .column_mut(1)
/// .as_slice::<i16>()
/// .expect("We know the year column to hold i16.");
/// col.copy_from_slice(years);
///
/// prebound.execute()?;
/// Ok(())
/// }
/// ```
pub fn into_column_inserter(
self,
capacity: usize,
descriptions: impl IntoIterator<Item = BufferDesc>,
) -> Result<ColumnarBulkInserter<S, AnyBuffer>, Error> {
let parameter_buffers = descriptions
.into_iter()
.map(|desc| AnyBuffer::from_desc(capacity, desc))
.collect();
unsafe { self.unchecked_bind_columnar_array_parameters(parameter_buffers) }
}
/// A [`crate::ColumnarBulkInserter`] which has ownership of the bound array parameter buffers
/// and borrows the statement. For most usecases [`Self::into_any_column_inserter`] is what you
/// want to use, yet on some instances you may want to bind new paramater buffers to the same
/// prepared statement. E.g. to grow the capacity dynamicaly during insertions with several
/// chunks. In such usecases you may only want to borrow the prepared statemnt, so it can be
/// reused with a different set of parameter buffers.
pub fn column_inserter(
&mut self,
capacity: usize,
descriptions: impl IntoIterator<Item = BufferDesc>,
) -> Result<ColumnarBulkInserter<StatementRef<'_>, AnyBuffer>, Error> {
let stmt = self.statement.as_stmt_ref();
let parameter_buffers = descriptions
.into_iter()
.map(|desc| AnyBuffer::from_desc(capacity, desc))
.collect();
unsafe { ColumnarBulkInserter::new(stmt, parameter_buffers) }
}
/// Number of rows affected by the last `INSERT`, `UPDATE` or `DELETE` statment. May return
/// `None` if row count is not available. Some drivers may also allow to use this to determine
/// how many rows have been fetched using `SELECT`. Most drivers however only know how many rows
/// have been fetched after they have been fetched.
///
/// ```
/// use odbc_api::{Connection, Error, IntoParameter};
///
/// /// Deletes all comments for every user in the slice. Returns the number of deleted
/// /// comments.
/// pub fn delete_all_comments_from(
/// users: &[&str],
/// conn: Connection<'_>,
/// ) -> Result<usize, Error>
/// {
/// // Store prepared query for fast repeated execution.
/// let mut prepared = conn.prepare("DELETE FROM Comments WHERE user=?")?;
/// let mut total_deleted_comments = 0;
/// for user in users {
/// prepared.execute(&user.into_parameter())?;
/// total_deleted_comments += prepared
/// .row_count()?
/// .expect("Row count must always be available for DELETE statements.");
/// }
/// Ok(total_deleted_comments)
/// }
/// ```
pub fn row_count(&mut self) -> Result<Option<usize>, Error> {
let stmt = self.statement.as_stmt_ref();
stmt.row_count().into_result(&stmt).map(|count| {
// ODBC returns -1 in case a row count is not available
if count == -1 {
None
} else {
Some(count.try_into().unwrap())
}
})
}120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
pub fn set_connection_pooling_matching(&mut self, matching: AttrCpMatch) -> Result<(), Error> {
self.environment
.set_connection_pooling_matching(matching)
.into_result(&self.environment)
}
/// Entry point into this API. Allocates a new ODBC Environment and declares to the driver
/// manager that the Application wants to use ODBC version 3.8.
///
/// # Safety
///
/// There may only be one ODBC environment in any process at any time. Take care using this
/// function in unit tests, as these run in parallel by default in Rust. Also no library should
/// probably wrap the creation of an odbc environment into a safe function call. This is because
/// using two of these "safe" libraries at the same time in different parts of your program may
/// lead to race condition thus violating Rust's safety guarantees.
///
/// Creating one environment in your binary is safe however.
pub fn new() -> Result<Self, Error> {
let result = handles::Environment::new();
let environment = match result {
SqlResult::Success(env) => env,
SqlResult::SuccessWithInfo(env) => {
log_diagnostics(&env);
env
}
SqlResult::Error { .. } => return Err(Error::FailedAllocatingEnvironment),
other => panic!("Unexpected return value '{:?}'", other),
};
debug!("ODBC Environment created.");
let result = environment
.declare_version(ODBC_API_VERSION)
.into_result(&environment);
// Translate invalid attribute into a more meaningful error, provided the additional
// context that we know we tried to set version number.
result.provide_context_for_diagnostic(|record, function| match record.state {
// INVALID_STATE_TRANSACTION has been seen with some really old version of unixODBC on
// a CentOS used to build manylinux wheels, with the preinstalled ODBC version.
// INVALID_ATTRIBUTE_VALUE is the correct status code to emit for a driver manager if it
// does not know the version and has been seen with an unknown version of unixODBC on an
// Oracle Linux.
State::INVALID_STATE_TRANSACTION | State::INVALID_ATTRIBUTE_VALUE => {
Error::UnsupportedOdbcApiVersion(record)
}
_ => Error::Diagnostics { record, function },
})?;
Ok(Self {
environment,
internal_state: Mutex::new(()),
})
}
/// Allocates a connection handle and establishes connections to a driver and a data source.
///
/// * See [Connecting with SQLConnect][1]
/// * See [SQLConnectFunction][2]
///
/// # Arguments
///
/// * `data_source_name` - Data source name. The data might be located on the same computer as
/// the program, or on another computer somewhere on a network.
/// * `user` - User identifier.
/// * `pwd` - Authentication string (typically the password).
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new()?;
///
/// let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
/// # Ok::<(), odbc_api::Error>(())
/// ```
///
/// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function
/// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function
pub fn connect(
&self,
data_source_name: &str,
user: &str,
pwd: &str,
) -> Result<Connection<'_>, Error> {
let data_source_name = SqlText::new(data_source_name);
let user = SqlText::new(user);
let pwd = SqlText::new(pwd);
let mut connection = self.allocate_connection()?;
connection
.connect(&data_source_name, &user, &pwd)
.into_result(&connection)?;
Ok(Connection::new(connection))
}
/// Allocates a connection handle and establishes connections to a driver and a data source.
///
/// An alternative to `connect`. It supports data sources that require more connection
/// information than the three arguments in `connect` and data sources that are not defined in
/// the system information.
///
/// To find out your connection string try: <https://www.connectionstrings.com/>
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new()?;
///
/// let connection_string = "
/// Driver={ODBC Driver 17 for SQL Server};\
/// Server=localhost;\
/// UID=SA;\
/// PWD=My@Test@Password1;\
/// ";
///
/// let mut conn = env.connect_with_connection_string(connection_string)?;
/// # Ok::<(), odbc_api::Error>(())
/// ```
pub fn connect_with_connection_string(
&self,
connection_string: &str,
) -> Result<Connection<'_>, Error> {
let connection_string = SqlText::new(connection_string);
let mut connection = self.allocate_connection()?;
connection
.connect_with_connection_string(&connection_string)
.into_result(&connection)?;
Ok(Connection::new(connection))
}
/// Allocates a connection handle and establishes connections to a driver and a data source.
///
/// An alternative to `connect` and `connect_with_connection_string`. This method can be
/// provided with an incomplete or even empty connection string. If any additional information
/// is required, the driver manager/driver will attempt to create a prompt to allow the user to
/// provide the additional information.
///
/// If the connection is successful, the complete connection string (including any information
/// provided by the user through a prompt) is returned.
///
/// # Parameters
///
/// * `connection_string`: Connection string.
/// * `completed_connection_string`: Output buffer with the complete connection string. It is
/// recommended to choose a buffer with at least `1024` bytes length. **Note**: Some driver
/// implementation have poor error handling in case the provided buffer is too small. At the
/// time of this writing:
/// * Maria DB crashes with STATUS_TACK_BUFFER_OVERRUN
/// * SQLite does not change the output buffer at all and does not indicate truncation.
/// * `driver_completion`: Specifies how and if the driver manager uses a prompt to complete
/// the provided connection string. For arguments other than
/// [`crate::DriverCompleteOption::NoPrompt`] this method is going to create a message only
/// parent window for you on windows. On other platform this method is going to panic. In case
/// you want to provide your own parent window please use [`Self::driver_connect_with_hwnd`].
///
/// # Examples
///
/// In the first example, we intentionally provide a blank connection string so the user will be
/// prompted to select a data source to use. Note that this functionality is only available on
/// windows.
///
/// ```no_run
/// use odbc_api::{Environment, handles::OutputStringBuffer, DriverCompleteOption};
///
/// let env = Environment::new()?;
///
/// let mut output_buffer = OutputStringBuffer::with_buffer_size(1024);
/// let connection = env.driver_connect(
/// "",
/// &mut output_buffer,
/// DriverCompleteOption::Prompt,
/// )?;
///
/// // Check that the output buffer has been large enough to hold the entire connection string.
/// assert!(!output_buffer.is_truncated());
///
/// // Now `connection_string` will contain the data source selected by the user.
/// let connection_string = output_buffer.to_utf8();
/// # Ok::<_,odbc_api::Error>(())
/// ```
///
/// In the following examples we specify a DSN that requires login credentials, but the DSN does
/// not provide those credentials. Instead, the user will be prompted for a UID and PWD. The
/// returned `connection_string` will contain the `UID` and `PWD` provided by the user. Note
/// that this functionality is currently only available on windows targets.
///
/// ```
/// # use odbc_api::DriverCompleteOption;
/// # #[cfg(target_os = "windows")]
/// # fn f(
/// # mut output_buffer: odbc_api::handles::OutputStringBuffer,
/// # env: odbc_api::Environment,
/// # ) -> Result<(), odbc_api::Error> {
/// let without_uid_or_pwd = "DSN=SomeSharedDatabase;";
/// let connection = env.driver_connect(
/// &without_uid_or_pwd,
/// &mut output_buffer,
/// DriverCompleteOption::Complete,
/// )?;
/// let connection_string = output_buffer.to_utf8();
///
/// // Now `connection_string` might be something like
/// // `DSN=SomeSharedDatabase;UID=SA;PWD=My@Test@Password1;`
/// # Ok(()) }
/// ```
///
/// In this case, we use a DSN that is already sufficient and does not require a prompt. Because
/// a prompt is not needed, `window` is also not required. The returned `connection_string` will
/// be mostly the same as `already_sufficient` but the driver may append some extra attributes.
///
/// ```
/// # use odbc_api::DriverCompleteOption;
/// # fn f(
/// # mut output_buffer: odbc_api::handles::OutputStringBuffer,
/// # env: odbc_api::Environment,
/// # ) -> Result<(), odbc_api::Error> {
/// let already_sufficient = "DSN=MicrosoftAccessFile;";
/// let connection = env.driver_connect(
/// &already_sufficient,
/// &mut output_buffer,
/// DriverCompleteOption::NoPrompt,
/// )?;
/// let connection_string = output_buffer.to_utf8();
///
/// // Now `connection_string` might be something like
/// // `DSN=MicrosoftAccessFile;DBQ=C:\Db\Example.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;`
/// # Ok(()) }
/// ```
pub fn driver_connect(
&self,
connection_string: &str,
completed_connection_string: &mut OutputStringBuffer,
driver_completion: DriverCompleteOption,
) -> Result<Connection<'_>, Error> {
#[cfg(target_os = "windows")]
let parent_window = match driver_completion {
DriverCompleteOption::NoPrompt => None,
_ => {
if !cfg!(target_os = "windows") {
panic!("Prompt is not supported on non windows platforms. Use `NoPrompt`.")
}
// We need a parent window, let's provide a message only window.
Some(
WindowBuilder::new()
.with_visible(false)
.build(&EventLoop::new())
.unwrap(),
)
}
};
#[cfg(target_os = "windows")]
let hwnd = parent_window
.as_ref()
.map(|window| window.hwnd() as HWnd)
.unwrap_or(null_mut());
#[cfg(not(target_os = "windows"))]
let hwnd = null_mut();
unsafe {
self.driver_connect_with_hwnd(
connection_string,
completed_connection_string,
driver_completion,
hwnd,
)
}
}
/// Allows to call driver connect with a user supplied HWnd. Same as [`Self::driver_connect`],
/// but with the possibility to provide your own parent window handle in case you want to show
/// a prompt to the user.
///
/// # Safety
///
/// `parent_window` must be a valid window handle, to a window type supported by the ODBC driver
/// manager. On windows this is a plain window handle, which is of course understood by the
/// windows built in ODBC driver manager. Other working combinations are unknown to the author.
pub unsafe fn driver_connect_with_hwnd(
&self,
connection_string: &str,
completed_connection_string: &mut OutputStringBuffer,
driver_completion: DriverCompleteOption,
parent_window: HWnd,
) -> Result<Connection<'_>, Error> {
let mut connection = self.allocate_connection()?;
let connection_string = SqlText::new(connection_string);
let connection_string_is_complete = connection
.driver_connect(
&connection_string,
parent_window,
completed_connection_string,
driver_completion.as_sys(),
)
.into_result_bool(&connection)?;
if !connection_string_is_complete {
return Err(Error::AbortedConnectionStringCompletion);
}
Ok(Connection::new(connection))
}
/// Get information about available drivers. Only 32 or 64 Bit drivers will be listed, depending
/// on wether you are building a 32 Bit or 64 Bit application.
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new ()?;
/// for driver_info in env.drivers()? {
/// println!("{:#?}", driver_info);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn drivers(&self) -> Result<Vec<DriverInfo>, Error> {
let mut driver_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut desc_len, mut attr_len) = if let Some(res) = self
.environment
// Start with first so we are independent of state
.drivers_buffer_len(FetchOrientation::First)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are, let's loop over the remaining drivers
while let Some((candidate_desc_len, candidate_attr_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
desc_len = max(candidate_desc_len, desc_len);
attr_len = max(candidate_attr_len, attr_len);
}
// Allocate +1 character extra for terminating zero
let mut desc_buf = SzBuffer::with_capacity(desc_len as usize);
let mut attr_buf = SzBuffer::with_capacity(attr_len as usize);
while self
.environment
.drivers_buffer_fill(
FetchOrientation::Next,
desc_buf.mut_buf(),
attr_buf.mut_buf(),
)
.into_result_bool(&self.environment)?
{
let description = desc_buf.to_utf8();
let attributes = attr_buf.to_utf8();
let attributes = attributes_iter(&attributes).collect();
driver_info.push(DriverInfo {
description,
attributes,
});
}
}
Ok(driver_info)
}
/// User and system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new()?;
/// for data_source in env.data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::First)
}
/// Only system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new ()?;
/// for data_source in env.system_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn system_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstSystem)
}
/// Only user data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let mut env = unsafe { Environment::new () }?;
/// for data_source in env.user_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn user_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstUser)
}
fn data_sources_impl(&self, direction: FetchOrientation) -> Result<Vec<DataSourceInfo>, Error> {
let mut data_source_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut server_name_len, mut driver_len) = if let Some(res) = self
.environment
.data_source_buffer_len(direction)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are let's loop over the rest
while let Some((candidate_name_len, candidate_decs_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
server_name_len = max(candidate_name_len, server_name_len);
driver_len = max(candidate_decs_len, driver_len);
}
let mut server_name_buf = SzBuffer::with_capacity(server_name_len as usize);
let mut driver_buf = SzBuffer::with_capacity(driver_len as usize);
let mut not_empty = self
.environment
.data_source_buffer_fill(direction, server_name_buf.mut_buf(), driver_buf.mut_buf())
.into_result_bool(&self.environment)?;
while not_empty {
let server_name = server_name_buf.to_utf8();
let driver = driver_buf.to_utf8();
data_source_info.push(DataSourceInfo {
server_name,
driver,
});
not_empty = self
.environment
.data_source_buffer_fill(
FetchOrientation::Next,
server_name_buf.mut_buf(),
driver_buf.mut_buf(),
)
.into_result_bool(&self.environment)?;
}
}
Ok(data_source_info)
}
fn allocate_connection(&self) -> Result<handles::Connection, Error> {
// Hold lock diagnostics errors are consumed in this thread.
let _lock = self.internal_state.lock().unwrap();
self.environment
.allocate_connection()
.into_result(&self.environment)
}77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
unsafe fn bind_to(
&mut self,
parameter_number: u16,
stmt: &mut impl Statement,
) -> Result<(), Error> {
stmt.bind_input_parameter(parameter_number, *self)
.into_result(stmt)
}
}
/// Bind mutable references as input/output parameter.
unsafe impl<'a, T> ParameterTupleElement for InOut<'a, T>
where
T: OutputParameter,
{
unsafe fn bind_to(
&mut self,
parameter_number: u16,
stmt: &mut impl Statement,
) -> Result<(), Error> {
stmt.bind_parameter(parameter_number, odbc_sys::ParamType::InputOutput, self.0)
.into_result(stmt)
}
}
/// Mutable references wrapped in `Out` are bound as output parameters.
unsafe impl<'a, T> ParameterTupleElement for Out<'a, T>
where
T: OutputParameter,
{
unsafe fn bind_to(
&mut self,
parameter_number: u16,
stmt: &mut impl Statement,
) -> Result<(), Error> {
stmt.bind_parameter(parameter_number, odbc_sys::ParamType::Output, self.0)
.into_result(stmt)
}sourcepub fn into_result_option(
self,
handle: &impl Diagnostics
) -> Result<Option<T>, Error>
pub fn into_result_option(
self,
handle: &impl Diagnostics
) -> Result<Option<T>, Error>
Like Self::into_result, but SqlResult::NoData is mapped to None, and any success
is mapped to Some.
Examples found in repository?
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
pub fn drivers(&self) -> Result<Vec<DriverInfo>, Error> {
let mut driver_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut desc_len, mut attr_len) = if let Some(res) = self
.environment
// Start with first so we are independent of state
.drivers_buffer_len(FetchOrientation::First)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are, let's loop over the remaining drivers
while let Some((candidate_desc_len, candidate_attr_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
desc_len = max(candidate_desc_len, desc_len);
attr_len = max(candidate_attr_len, attr_len);
}
// Allocate +1 character extra for terminating zero
let mut desc_buf = SzBuffer::with_capacity(desc_len as usize);
let mut attr_buf = SzBuffer::with_capacity(attr_len as usize);
while self
.environment
.drivers_buffer_fill(
FetchOrientation::Next,
desc_buf.mut_buf(),
attr_buf.mut_buf(),
)
.into_result_bool(&self.environment)?
{
let description = desc_buf.to_utf8();
let attributes = attr_buf.to_utf8();
let attributes = attributes_iter(&attributes).collect();
driver_info.push(DriverInfo {
description,
attributes,
});
}
}
Ok(driver_info)
}
/// User and system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new()?;
/// for data_source in env.data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::First)
}
/// Only system data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let env = Environment::new ()?;
/// for data_source in env.system_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn system_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstSystem)
}
/// Only user data sources
///
/// # Example
///
/// ```no_run
/// use odbc_api::Environment;
///
/// let mut env = unsafe { Environment::new () }?;
/// for data_source in env.user_data_sources()? {
/// println!("{:#?}", data_source);
/// }
///
/// # Ok::<_, odbc_api::Error>(())
/// ```
pub fn user_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
self.data_sources_impl(FetchOrientation::FirstUser)
}
fn data_sources_impl(&self, direction: FetchOrientation) -> Result<Vec<DataSourceInfo>, Error> {
let mut data_source_info = Vec::new();
// Since we have exclusive ownership of the environment handle and we take the lock, we can
// guarantee that this method is currently the only one changing the state of the internal
// iterators of the environment.
let _lock = self.internal_state.lock().unwrap();
unsafe {
// Find required buffer size to avoid truncation.
let (mut server_name_len, mut driver_len) = if let Some(res) = self
.environment
.data_source_buffer_len(direction)
.into_result_option(&self.environment)?
{
res
} else {
// No drivers present
return Ok(Vec::new());
};
// If there are let's loop over the rest
while let Some((candidate_name_len, candidate_decs_len)) = self
.environment
.drivers_buffer_len(FetchOrientation::Next)
.into_result_option(&self.environment)?
{
server_name_len = max(candidate_name_len, server_name_len);
driver_len = max(candidate_decs_len, driver_len);
}
let mut server_name_buf = SzBuffer::with_capacity(server_name_len as usize);
let mut driver_buf = SzBuffer::with_capacity(driver_len as usize);
let mut not_empty = self
.environment
.data_source_buffer_fill(direction, server_name_buf.mut_buf(), driver_buf.mut_buf())
.into_result_bool(&self.environment)?;
while not_empty {
let server_name = server_name_buf.to_utf8();
let driver = driver_buf.to_utf8();
data_source_info.push(DataSourceInfo {
server_name,
driver,
});
not_empty = self
.environment
.data_source_buffer_fill(
FetchOrientation::Next,
server_name_buf.mut_buf(),
driver_buf.mut_buf(),
)
.into_result_bool(&self.environment)?;
}
}
Ok(data_source_info)
}sourcepub fn into_result_with(
self,
handle: &impl Diagnostics,
error_for_truncation: bool,
no_data: Option<T>,
need_data: Option<T>
) -> Result<T, Error>
pub fn into_result_with(
self,
handle: &impl Diagnostics,
error_for_truncation: bool,
no_data: Option<T>,
need_data: Option<T>
) -> Result<T, Error>
Most flexible way of converting an SqlResult to an idiomatic Result.
Parameters
handle: This handle is used to extract diagnostics in caseselfisSqlResult::SuccessWithInfoorSqlResult::Error.error_for_truncation: Intended to be used to be used after bulk fetching into a buffer. Iferror_for_truncationistrueany diagnostics are inspected for truncation. If any truncation is found an error is returned.no_data: Controls the behaviour forSqlResult::NoData.Noneindicates that the result is never expected to beSqlResult::NoDataand would panic in that case.Some(value)would causeSqlResult::NoDatato be mapped toOk(value).need_data: Controls the behaviour forSqlResult::NeedData.Noneindicates that the result is never expected to beSqlResult::NeedDataand would panic in that case.Some(value)would causeSqlResult::NeedDatato be mapped toOk(value).
Examples found in repository?
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
pub fn into_result_bool(self, handle: &impl Diagnostics) -> Result<bool, Error> {
self.on_success(|| true)
.into_result_with(handle, false, Some(false), None)
}
}
// Define that here rather than in `sql_result` mod to keep the `handles` module entirely agnostic
// about the top level `Error` type.
impl<T> SqlResult<T> {
/// [`Self::Success`] and [`Self::SuccessWithInfo`] are mapped to Ok. In case of
/// [`Self::SuccessWithInfo`] any diagnostics are logged. [`Self::Error`] is mapped to error.
pub fn into_result(self, handle: &impl Diagnostics) -> Result<T, Error> {
let error_for_truncation = false;
self.into_result_with(handle, error_for_truncation, None, None)
}
/// Like [`Self::into_result`], but [`SqlResult::NoData`] is mapped to `None`, and any success
/// is mapped to `Some`.
pub fn into_result_option(self, handle: &impl Diagnostics) -> Result<Option<T>, Error> {
let error_for_truncation = false;
self.map(Some)
.into_result_with(handle, error_for_truncation, Some(None), None)
}More examples
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
fn error_handling_for_fetch(
result: SqlResult<()>,
mut stmt: StatementRef,
error_for_truncation: bool,
) -> Result<bool, Error> {
let has_row = result
.on_success(|| true)
.into_result_with(&stmt.as_stmt_ref(), error_for_truncation, Some(false), None)
// Oracles ODBC driver does not support 64Bit integers. Furthermore, it does not
// tell the it to the user than binding parameters, but rather now then we fetch
// results. The error code retruned is `HY004` rather then `HY003` which should
// be used to indicate invalid buffer types.
.provide_context_for_diagnostic(|record, function| {
if record.state == State::INVALID_SQL_DATA_TYPE {
Error::OracleOdbcDriverDoesNotSupport64Bit(record)
} else {
Error::Diagnostics { record, function }
}
})?;
Ok(has_row)
}87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
pub unsafe fn execute<S>(
mut statement: S,
query: Option<&SqlText<'_>>,
) -> Result<Option<CursorImpl<S>>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
let result = if let Some(sql) = query {
// We execute an unprepared "one shot query"
stmt.exec_direct(sql)
} else {
// We execute a prepared query
stmt.execute()
};
// If delayed parameters (e.g. input streams) are bound we might need to put data in order to
// execute.
let need_data =
result
.on_success(|| false)
.into_result_with(&stmt, false, Some(false), Some(true))?;
if need_data {
// Check if any delayed parameters have been bound which stream data to the database at
// statement execution time. Loops over each bound stream.
while let Some(blob_ptr) = stmt.param_data().into_result(&stmt)? {
// The safe interfaces currently exclusively bind pointers to `Blob` trait objects
let blob_ptr: *mut &mut dyn Blob = transmute(blob_ptr);
let blob_ref = &mut *blob_ptr;
// Loop over all batches within each blob
while let Some(batch) = blob_ref.next_batch().map_err(Error::FailedReadingInput)? {
stmt.put_binary_batch(batch).into_result(&stmt)?;
}
}
}
// Check if a result set has been created.
if stmt.num_result_cols().into_result(&stmt)? == 0 {
Ok(None)
} else {
// Safe: `statement` is in cursor state.
let cursor = CursorImpl::new(statement);
Ok(Some(cursor))
}
}
/// # Safety
///
/// * Execute may dereference pointers to bound parameters, so these must guaranteed to be valid
/// then calling this function.
/// * Furthermore all bound delayed parameters must be of type `*mut &mut dyn Blob`.
pub async unsafe fn execute_polling<S>(
mut statement: S,
query: Option<&SqlText<'_>>,
mut sleep: impl Sleep,
) -> Result<Option<CursorPolling<S>>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
let result = if let Some(sql) = query {
// We execute an unprepared "one shot query"
wait_for(|| stmt.exec_direct(sql), &mut sleep).await
} else {
// We execute a prepared query
wait_for(|| stmt.execute(), &mut sleep).await
};
// If delayed parameters (e.g. input streams) are bound we might need to put data in order to
// execute.
let need_data =
result
.on_success(|| false)
.into_result_with(&stmt, false, Some(false), Some(true))?;
if need_data {
// Check if any delayed parameters have been bound which stream data to the database at
// statement execution time. Loops over each bound stream.
while let Some(blob_ptr) = stmt.param_data().into_result(&stmt)? {
// The safe interfaces currently exclusively bind pointers to `Blob` trait objects
let blob_ptr: *mut &mut dyn Blob = transmute(blob_ptr);
let blob_ref = &mut *blob_ptr;
// Loop over all batches within each blob
while let Some(batch) = blob_ref.next_batch().map_err(Error::FailedReadingInput)? {
let result = wait_for(|| stmt.put_binary_batch(batch), &mut sleep).await;
result.into_result(&stmt)?;
}
}
}
// Check if a result set has been created.
let num_result_cols = wait_for(|| stmt.num_result_cols(), &mut sleep)
.await
.into_result(&stmt)?;
if num_result_cols == 0 {
Ok(None)
} else {
// Safe: `statement` is in cursor state.
let cursor = CursorPolling::new(statement);
Ok(Some(cursor))
}
}source§impl SqlResult<()>
impl SqlResult<()>
sourcepub fn on_success<F, T>(self, f: F) -> SqlResult<T>where
F: FnOnce() -> T,
pub fn on_success<F, T>(self, f: F) -> SqlResult<T>where
F: FnOnce() -> T,
Append a return value a successful to Result
Examples found in repository?
More examples
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
fn num_result_cols(&self) -> SqlResult<i16> {
let mut out: i16 = 0;
unsafe { SQLNumResultCols(self.as_sys(), &mut out) }
.into_sql_result("SQLNumResultCols")
.on_success(|| out)
}
/// Number of placeholders of a prepared query.
fn num_params(&self) -> SqlResult<u16> {
let mut out: i16 = 0;
unsafe { SQLNumParams(self.as_sys(), &mut out) }
.into_sql_result("SQLNumParams")
.on_success(|| out.try_into().unwrap())
}
/// Sets the batch size for bulk cursors, if retrieving many rows at once.
///
/// # Safety
///
/// It is the callers responsibility to ensure that buffers bound using `bind_col` can hold the
/// specified amount of rows.
unsafe fn set_row_array_size(&mut self, size: usize) -> SqlResult<()> {
assert!(size > 0);
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::RowArraySize,
size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
/// Specifies the number of values for each parameter. If it is greater than 1, the data and
/// indicator buffers of the statement point to arrays. The cardinality of each array is equal
/// to the value of this field.
///
/// # Safety
///
/// The bound buffers must at least hold the number of elements specified in this call then the
/// statement is executed.
unsafe fn set_paramset_size(&mut self, size: usize) -> SqlResult<()> {
assert!(size > 0);
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::ParamsetSize,
size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
/// Sets the binding type to columnar binding for batch cursors.
///
/// Any Positive number indicates a row wise binding with that row length. `0` indicates a
/// columnar binding.
///
/// # Safety
///
/// It is the callers responsibility to ensure that the bound buffers match the memory layout
/// specified by this function.
unsafe fn set_row_bind_type(&mut self, row_size: usize) -> SqlResult<()> {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::RowBindType,
row_size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
fn set_metadata_id(&mut self, metadata_id: bool) -> SqlResult<()> {
unsafe {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::MetadataId,
metadata_id as usize as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
}
/// Enables or disables asynchronous execution for this statement handle. If asynchronous
/// execution is not enabled on connection level it is disabled by default and everything is
/// executed synchronously.
///
/// This is equivalent to stetting `SQL_ATTR_ASYNC_ENABLE` in the bare C API.
///
/// See
/// <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/executing-statements-odbc>
fn set_async_enable(&mut self, on: bool) -> SqlResult<()> {
unsafe {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::AsyncEnable,
on as usize as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
}
/// Binds a buffer holding an input parameter to a parameter marker in an SQL statement. This
/// specialized version takes a constant reference to parameter, but is therefore limited to
/// binding input parameters. See [`Statement::bind_parameter`] for the version which can bind
/// input and output parameters.
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_input_parameter(
&mut self,
parameter_number: u16,
parameter: &(impl HasDataType + CData + ?Sized),
) -> SqlResult<()> {
let parameter_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
ParamType::Input,
parameter.cdata_type(),
parameter_type.data_type(),
parameter_type.column_size(),
parameter_type.decimal_digits(),
// We cast const to mut here, but we specify the input_output_type as input.
parameter.value_ptr() as *mut c_void,
parameter.buffer_length(),
// We cast const to mut here, but we specify the input_output_type as input.
parameter.indicator_ptr() as *mut isize,
)
.into_sql_result("SQLBindParameter")
}
/// Binds a buffer holding a single parameter to a parameter marker in an SQL statement. To bind
/// input parameters using constant references see [`Statement::bind_input_parameter`].
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_parameter(
&mut self,
parameter_number: u16,
input_output_type: ParamType,
parameter: &mut (impl CDataMut + HasDataType),
) -> SqlResult<()> {
let parameter_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
input_output_type,
parameter.cdata_type(),
parameter_type.data_type(),
parameter_type.column_size(),
parameter_type.decimal_digits(),
parameter.value_ptr() as *mut c_void,
parameter.buffer_length(),
parameter.mut_indicator_ptr(),
)
.into_sql_result("SQLBindParameter")
}
/// Binds an input stream to a parameter marker in an SQL statement. Use this to stream large
/// values at statement execution time. To bind preallocated constant buffers see
/// [`Statement::bind_input_parameter`].
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_delayed_input_parameter(
&mut self,
parameter_number: u16,
parameter: &mut (impl DelayedInput + HasDataType),
) -> SqlResult<()> {
let paramater_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
ParamType::Input,
parameter.cdata_type(),
paramater_type.data_type(),
paramater_type.column_size(),
paramater_type.decimal_digits(),
parameter.stream_ptr(),
0,
// We cast const to mut here, but we specify the input_output_type as input.
parameter.indicator_ptr() as *mut isize,
)
.into_sql_result("SQLBindParameter")
}
/// `true` if a given column in a result set is unsigned or not a numeric type, `false`
/// otherwise.
///
/// `column_number`: Index of the column, starting at 1.
fn is_unsigned_column(&self, column_number: u16) -> SqlResult<bool> {
unsafe { self.numeric_col_attribute(Desc::Unsigned, column_number) }.map(|out| match out {
0 => false,
1 => true,
_ => panic!("Unsigned column attribute must be either 0 or 1."),
})
}
/// Returns a number identifying the SQL type of the column in the result set.
///
/// `column_number`: Index of the column, starting at 1.
fn col_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::Type, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}
/// The concise data type. For the datetime and interval data types, this field returns the
/// concise data type; for example, `TIME` or `INTERVAL_YEAR`.
///
/// `column_number`: Index of the column, starting at 1.
fn col_concise_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::ConciseType, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}
/// Returns the size in bytes of the columns. For variable sized types the maximum size is
/// returned, excluding a terminating zero.
///
/// `column_number`: Index of the column, starting at 1.
fn col_octet_length(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::OctetLength, column_number) }
}
/// Maximum number of characters required to display data from the column.
///
/// `column_number`: Index of the column, starting at 1.
fn col_display_size(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::DisplaySize, column_number) }
}
/// Precision of the column.
///
/// Denotes the applicable precision. For data types SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP, and all
/// the interval data types that represent a time interval, its value is the applicable
/// precision of the fractional seconds component.
fn col_precision(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::Precision, column_number) }
}
/// The applicable scale for a numeric data type. For DECIMAL and NUMERIC data types, this is
/// the defined scale. It is undefined for all other data types.
fn col_scale(&self, column_number: u16) -> SqlResult<Len> {
unsafe { self.numeric_col_attribute(Desc::Scale, column_number) }
}
/// The column alias, if it applies. If the column alias does not apply, the column name is
/// returned. If there is no column name or a column alias, an empty string is returned.
fn col_name(&self, column_number: u16, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i16 = 0;
// Let's utilize all of `buf`s capacity.
buffer.resize(buffer.capacity(), 0);
unsafe {
let mut res = sql_col_attribute(
self.as_sys(),
column_number,
Desc::Name,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
null_mut(),
)
.into_sql_result("SQLColAttribute");
if res.is_err() {
return res;
}
if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
// If we could rely on every ODBC driver sticking to the specifcation it would
// probably best to resize by `string_length_in_bytes / 2 + 1`. Yet e.g. SQLite
// seems to report the length in characters, so to work with a wide range of DB
// systems, and since buffers for names are not expected to become super large we
// ommit the division by two here.
buffer.resize((string_length_in_bytes + 1).try_into().unwrap(), 0);
res = sql_col_attribute(
self.as_sys(),
column_number,
Desc::Name,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
null_mut(),
)
.into_sql_result("SQLColAttribute");
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
res
}
}
/// # Safety
///
/// It is the callers responsibility to ensure that `attribute` refers to a numeric attribute.
unsafe fn numeric_col_attribute(&self, attribute: Desc, column_number: u16) -> SqlResult<Len> {
let mut out: Len = 0;
sql_col_attribute(
self.as_sys(),
column_number,
attribute,
null_mut(),
0,
null_mut(),
&mut out as *mut Len,
)
.into_sql_result("SQLColAttribute")
.on_success(|| out)
}
/// Sets the SQL_DESC_COUNT field of the APD to 0, releasing all parameter buffers set for the
/// given StatementHandle.
fn reset_parameters(&mut self) -> SqlResult<()> {
unsafe {
SQLFreeStmt(self.as_sys(), FreeStmtOption::ResetParams).into_sql_result("SQLFreeStmt")
}
}
/// Describes parameter marker associated with a prepared SQL statement.
///
/// # Parameters
///
/// * `parameter_number`: Parameter marker number ordered sequentially in increasing parameter
/// order, starting at 1.
fn describe_param(&self, parameter_number: u16) -> SqlResult<ParameterDescription> {
let mut data_type = SqlDataType::UNKNOWN_TYPE;
let mut parameter_size = 0;
let mut decimal_digits = 0;
let mut nullable = odbc_sys::Nullability::UNKNOWN;
unsafe {
SQLDescribeParam(
self.as_sys(),
parameter_number,
&mut data_type,
&mut parameter_size,
&mut decimal_digits,
&mut nullable,
)
}
.into_sql_result("SQLDescribeParam")
.on_success(|| ParameterDescription {
data_type: DataType::new(data_type, parameter_size, decimal_digits),
nullable: Nullability::new(nullable),
})
}
/// Use to check if which additional parameters need data. Should be called after binding
/// parameters with an indicator set to [`crate::sys::DATA_AT_EXEC`] or a value created with
/// [`crate::sys::len_data_at_exec`].
///
/// Return value contains a parameter identifier passed to bind parameter as a value pointer.
fn param_data(&mut self) -> SqlResult<Option<Pointer>> {
unsafe {
let mut param_id: Pointer = null_mut();
// Use cases for `PARAM_DATA_AVAILABLE` and `NO_DATA` not implemented yet.
match SQLParamData(self.as_sys(), &mut param_id as *mut Pointer) {
SqlReturn::NEED_DATA => SqlResult::Success(Some(param_id)),
other => other.into_sql_result("SQLParamData").on_success(|| None),
}
}
}
/// Executes a columns query using this statement handle.
fn columns(
&mut self,
catalog_name: &SqlText,
schema_name: &SqlText,
table_name: &SqlText,
column_name: &SqlText,
) -> SqlResult<()> {
unsafe {
sql_columns(
self.as_sys(),
catalog_name.ptr(),
catalog_name.len_char().try_into().unwrap(),
schema_name.ptr(),
schema_name.len_char().try_into().unwrap(),
table_name.ptr(),
table_name.len_char().try_into().unwrap(),
column_name.ptr(),
column_name.len_char().try_into().unwrap(),
)
.into_sql_result("SQLColumns")
}
}
/// Returns the list of table, catalog, or schema names, and table types, stored in a specific
/// data source. The driver returns the information as a result set.
///
/// The catalog, schema and table parameters are search patterns by default unless
/// [`Self::set_metadata_id`] is called with `true`. In that case they must also not be `None` since
/// otherwise a NulPointer error is emitted.
fn tables(
&mut self,
catalog_name: &SqlText,
schema_name: &SqlText,
table_name: &SqlText,
table_type: &SqlText,
) -> SqlResult<()> {
unsafe {
sql_tables(
self.as_sys(),
catalog_name.ptr(),
catalog_name.len_char().try_into().unwrap(),
schema_name.ptr(),
schema_name.len_char().try_into().unwrap(),
table_name.ptr(),
table_name.len_char().try_into().unwrap(),
table_type.ptr(),
table_type.len_char().try_into().unwrap(),
)
.into_sql_result("SQLTables")
}
}
/// To put a batch of binary data into the data source at statement execution time. May return
/// [`SqlResult::NeedData`]
///
/// Panics if batch is empty.
fn put_binary_batch(&mut self, batch: &[u8]) -> SqlResult<()> {
// Probably not strictly necessary. MSSQL returns an error than inserting empty batches.
// Still strikes me as a programming error. Maybe we could also do nothing instead.
if batch.is_empty() {
panic!("Attempt to put empty batch into data source.")
}
unsafe {
SQLPutData(
self.as_sys(),
batch.as_ptr() as Pointer,
batch.len().try_into().unwrap(),
)
.into_sql_result("SQLPutData")
}
}
/// Number of rows affected by an `UPDATE`, `INSERT`, or `DELETE` statement.
///
/// See:
///
/// <https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-api/sqlrowcount>
/// <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlrowcount-function>
fn row_count(&self) -> SqlResult<isize> {
let mut ret = 0isize;
unsafe {
SQLRowCount(self.as_sys(), &mut ret as *mut isize)
.into_sql_result("SQLRowCount")
.on_success(|| ret)
}
}
/// In polling mode can be used instead of repeating the function call. In notification mode
/// this completes the asynchronous operation. This method panics, in case asynchronous mode is
/// not enabled. [`SqlResult::NoData`] if no asynchronous operation is in progress, or (specific
/// to notification mode) the driver manager has not notified the application.
///
/// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlcompleteasync-function>
fn complete_async(&mut self, function_name: &'static str) -> SqlResult<SqlResult<()>> {
let mut ret = SqlReturn::ERROR;
unsafe {
// Possible return codes are (according to MS ODBC docs):
// * INVALID_HANDLE: The handle indicated by HandleType and Handle is not a valid
// handle. => Must not happen due self always being a valid statement handle.
// * ERROR: ret is NULL or asynchronous processing is not enabled on the handle. => ret
// is never NULL. User may choose not to enable asynchronous processing though.
// * NO_DATA: In notification mode, an asynchronous operation is not in progress or the
// Driver Manager has not notified the application. In polling mode, an asynchronous
// operation is not in progress.
SQLCompleteAsync(self.handle_type(), self.as_handle(), &mut ret.0 as *mut _)
.into_sql_result("SQLCompleteAsync")
}
.on_success(|| ret.into_sql_result(function_name))
}163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
pub fn allocate_statement(&self) -> SqlResult<StatementImpl<'_>> {
let mut out = null_mut();
unsafe {
SQLAllocHandle(HandleType::Stmt, self.as_handle(), &mut out)
.into_sql_result("SQLAllocHandle")
.on_success(|| StatementImpl::new(out as HStmt))
}
}
/// Specify the transaction mode. By default, ODBC transactions are in auto-commit mode (unless
/// SQLSetConnectAttr and SQLSetConnectOption are not supported, which is unlikely). Switching
/// from manual-commit mode to auto-commit mode automatically commits any open transaction on
/// the connection.
pub fn set_autocommit(&self, enabled: bool) -> SqlResult<()> {
let val = enabled as u32;
unsafe {
sql_set_connect_attr(
self.handle,
ConnectionAttribute::AutoCommit,
val as Pointer,
0, // will be ignored according to ODBC spec
)
.into_sql_result("SQLSetConnectAttr")
}
}
/// To commit a transaction in manual-commit mode.
pub fn commit(&self) -> SqlResult<()> {
unsafe {
SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Commit)
.into_sql_result("SQLEndTran")
}
}
/// Roll back a transaction in manual-commit mode.
pub fn rollback(&self) -> SqlResult<()> {
unsafe {
SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Rollback)
.into_sql_result("SQLEndTran")
}
}
/// Fetch the name of the database management system used by the connection and store it into
/// the provided `buf`.
pub fn fetch_database_management_system_name(&self, buf: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i16 = 0;
// Let's utilize all of `buf`s capacity.
buf.resize(buf.capacity(), 0);
unsafe {
let mut res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
// Call has been a success but let's check if the buffer had been large enough.
if is_truncated_bin(buf, string_length_in_bytes.try_into().unwrap()) {
// It seems we must try again with a large enough buffer.
resize_to_fit_with_tz(buf, string_length_in_bytes.try_into().unwrap());
res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buf, string_length_in_bytes.try_into().unwrap());
res
}
}
fn info_u16(&self, info_type: InfoType) -> SqlResult<u16> {
unsafe {
let mut value = 0u16;
sql_get_info(
self.handle,
info_type,
&mut value as *mut u16 as Pointer,
// Buffer length should not be required in this case, according to the ODBC
// documentation at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgetinfo-function?view=sql-server-ver15#arguments
// However, in practice some drivers (such as Microsoft Access) require it to be
// specified explicitly here, otherwise they return an error without diagnostics.
size_of::<*mut u16>() as i16,
null_mut(),
)
.into_sql_result("SQLGetInfo")
.on_success(|| value)
}
}
/// Maximum length of catalog names.
pub fn max_catalog_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxCatalogNameLen)
}
/// Maximum length of schema names.
pub fn max_schema_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxSchemaNameLen)
}
/// Maximum length of table names.
pub fn max_table_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxTableNameLen)
}
/// Maximum length of column names.
pub fn max_column_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxColumnNameLen)
}
/// Fetch the name of the current catalog being used by the connection and store it into the
/// provided `buf`.
pub fn fetch_current_catalog(&self, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i32 = 0;
// Let's utilize all of `buf`s capacity.
buffer.resize(buffer.capacity(), 0);
unsafe {
let mut res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
if res.is_err() {
return res;
}
if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
resize_to_fit_with_tz(buffer, string_length_in_bytes.try_into().unwrap());
res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
}
if res.is_err() {
return res;
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
res
}
}
/// Indicates the state of the connection. If `true` the connection has been lost. If `false`,
/// the connection is still active.
pub fn is_dead(&self) -> SqlResult<bool> {
unsafe {
self.attribute_u32(ConnectionAttribute::ConnectionDead)
.map(|v| match v {
0 => false,
1 => true,
other => panic!("Unexpected result value from SQLGetConnectAttr: {}", other),
})
}
}
/// # Safety
///
/// Caller must ensure connection attribute is numeric.
unsafe fn attribute_u32(&self, attribute: ConnectionAttribute) -> SqlResult<u32> {
let mut out: u32 = 0;
sql_get_connect_attr(
self.handle,
attribute,
&mut out as *mut u32 as *mut c_void,
IS_UINTEGER,
null_mut(),
)
.into_sql_result("SQLGetConnectAttr")
.on_success(|| out)
}623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
fn error_handling_for_fetch(
result: SqlResult<()>,
mut stmt: StatementRef,
error_for_truncation: bool,
) -> Result<bool, Error> {
let has_row = result
.on_success(|| true)
.into_result_with(&stmt.as_stmt_ref(), error_for_truncation, Some(false), None)
// Oracles ODBC driver does not support 64Bit integers. Furthermore, it does not
// tell the it to the user than binding parameters, but rather now then we fetch
// results. The error code retruned is `HY004` rather then `HY003` which should
// be used to indicate invalid buffer types.
.provide_context_for_diagnostic(|record, function| {
if record.state == State::INVALID_SQL_DATA_TYPE {
Error::OracleOdbcDriverDoesNotSupport64Bit(record)
} else {
Error::Diagnostics { record, function }
}
})?;
Ok(has_row)
}94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
pub fn new() -> SqlResult<Self> {
// After running a lot of unit tests in parallel on both linux and windows architectures and
// never seeing a race condition related to this I deem this save. In the past I feared
// concurrent construction of multiple Environments might race on shared state. Mostly due
// to <https://github.com/Koka/odbc-rs/issues/29> and
// <http://old.vk.pp.ru/docs/sybase-any/interfaces/00000034.htm>. Since however I since
// however official sources imply it is ok for an application to have multiple environments
// and I did not get it to race ever on my machine.
unsafe {
let mut handle = null_mut();
let result: SqlResult<()> = SQLAllocHandle(HandleType::Env, null_mut(), &mut handle)
.into_sql_result("SQLAllocHandle");
result.on_success(|| Environment {
handle: handle as HEnv,
})
}
}
/// Declares which Version of the ODBC API we want to use. This is the first thing that should
/// be done with any ODBC environment.
pub fn declare_version(&self, version: AttrOdbcVersion) -> SqlResult<()> {
unsafe {
SQLSetEnvAttr(
self.handle,
EnvironmentAttribute::OdbcVersion,
version.into(),
0,
)
.into_sql_result("SQLSetEnvAttr")
}
}
/// Allocate a new connection handle. The `Connection` must not outlive the `Environment`.
pub fn allocate_connection(&self) -> SqlResult<Connection<'_>> {
let mut handle = null_mut();
unsafe {
SQLAllocHandle(HandleType::Dbc, self.as_handle(), &mut handle)
.into_sql_result("SQLAllocHandle")
.on_success(|| Connection::new(handle as HDbc))
}
}
/// Provides access to the raw ODBC environment handle.
pub fn as_raw(&self) -> HEnv {
self.handle
}
/// List drivers descriptions and driver attribute keywords. Returns `NoData` to indicate the
/// end of the list.
///
/// # Safety
///
/// Callers need to make sure only one thread is iterating over driver information at a time.
/// Method changes environment state. This method would be safe to call via an exclusive `&mut`
/// reference, yet that would restrict usecases. E.g. requesting information would only be
/// possible before connections borrow a reference.
///
/// # Parameters
///
/// * `direction`: Determines whether the Driver Manager fetches the next driver in the list
/// ([`FetchOrientation::Next`]) or whether the search starts from the beginning of the list
/// ([`FetchOrientation::First`]).
/// * `buffer_description`: In case `true` is returned this buffer is filled with the
/// description of the driver.
/// * `buffer_attributes`: In case `true` is returned this buffer is filled with a list of
/// key value attributes. E.g.: `"key1=value1\0key2=value2\0\0"`.
///
/// Use [`Environment::drivers_buffer_len`] to determine buffer lengths.
///
/// See [SQLDrivers][1]
///
/// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldrivers-function
pub unsafe fn drivers_buffer_fill(
&self,
direction: FetchOrientation,
buffer_description: &mut [SqlChar],
buffer_attributes: &mut [SqlChar],
) -> SqlResult<()> {
sql_drivers(
self.handle,
direction,
buffer_description.as_mut_ptr(),
buffer_description.len().try_into().unwrap(),
null_mut(),
buffer_attributes.as_mut_ptr(),
buffer_attributes.len().try_into().unwrap(),
null_mut(),
)
.into_sql_result("SQLDrivers")
}
/// Use together with [`Environment::drivers_buffer_fill`] to list drivers descriptions and
/// driver attribute keywords.
///
/// # Safety
///
/// Callers need to make sure only one thread is iterating over driver information at a time.
/// Method changes environment state. This method would be safe to call via an exclusive `&mut`
/// reference, yet that would restrict usecases. E.g. requesting information would only be
/// possible before connections borrow a reference.
///
/// # Parameters
///
/// * `direction`: Determines whether the Driver Manager fetches the next driver in the list
/// ([`FetchOrientation::Next`]) or whether the search starts from the beginning of the list
/// ([`FetchOrientation::First`]).
///
/// # Return
///
/// `(driver description length, attribute length)`. Length is in characters minus terminating
/// terminating zero.
///
/// See [SQLDrivers][1]
///
/// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqldrivers-function
pub unsafe fn drivers_buffer_len(&self, direction: FetchOrientation) -> SqlResult<(i16, i16)> {
// Lengths in characters minus terminating zero
let mut length_description: i16 = 0;
let mut length_attributes: i16 = 0;
// Determine required buffer size
sql_drivers(
self.handle,
direction,
null_mut(),
0,
&mut length_description,
null_mut(),
0,
&mut length_attributes,
)
.into_sql_result("SQLDrivers")
.on_success(|| (length_description, length_attributes))
}
/// Use together with [`Environment::data_source_buffer_fill`] to list drivers descriptions and
/// driver attribute keywords.
///
/// # Safety
///
/// Callers need to make sure only one thread is iterating over data source information at a
/// time. Method changes environment state. This method would be safe to call via an exclusive
/// `&mut` reference, yet that would restrict usecases. E.g. requesting information would only
/// be possible before connections borrow a reference.
///
/// # Parameters
///
/// * `direction`: Determines whether the Driver Manager fetches the next driver in the list
/// ([`FetchOrientation::Next`]) or whether the search starts from the beginning of the list
/// ([`FetchOrientation::First`], [`FetchOrientation::FirstSystem`],
/// [`FetchOrientation::FirstUser`]).
///
/// # Return
///
/// `(server name length, description length)`. Length is in characters minus terminating zero.
pub unsafe fn data_source_buffer_len(
&self,
direction: FetchOrientation,
) -> SqlResult<(i16, i16)> {
// Lengths in characters minus terminating zero
let mut length_name: i16 = 0;
let mut length_description: i16 = 0;
// Determine required buffer size
sql_data_sources(
self.handle,
direction,
null_mut(),
0,
&mut length_name,
null_mut(),
0,
&mut length_description,
)
.into_sql_result("SQLDataSources")
.on_success(|| (length_name, length_description))
}87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
pub unsafe fn execute<S>(
mut statement: S,
query: Option<&SqlText<'_>>,
) -> Result<Option<CursorImpl<S>>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
let result = if let Some(sql) = query {
// We execute an unprepared "one shot query"
stmt.exec_direct(sql)
} else {
// We execute a prepared query
stmt.execute()
};
// If delayed parameters (e.g. input streams) are bound we might need to put data in order to
// execute.
let need_data =
result
.on_success(|| false)
.into_result_with(&stmt, false, Some(false), Some(true))?;
if need_data {
// Check if any delayed parameters have been bound which stream data to the database at
// statement execution time. Loops over each bound stream.
while let Some(blob_ptr) = stmt.param_data().into_result(&stmt)? {
// The safe interfaces currently exclusively bind pointers to `Blob` trait objects
let blob_ptr: *mut &mut dyn Blob = transmute(blob_ptr);
let blob_ref = &mut *blob_ptr;
// Loop over all batches within each blob
while let Some(batch) = blob_ref.next_batch().map_err(Error::FailedReadingInput)? {
stmt.put_binary_batch(batch).into_result(&stmt)?;
}
}
}
// Check if a result set has been created.
if stmt.num_result_cols().into_result(&stmt)? == 0 {
Ok(None)
} else {
// Safe: `statement` is in cursor state.
let cursor = CursorImpl::new(statement);
Ok(Some(cursor))
}
}
/// # Safety
///
/// * Execute may dereference pointers to bound parameters, so these must guaranteed to be valid
/// then calling this function.
/// * Furthermore all bound delayed parameters must be of type `*mut &mut dyn Blob`.
pub async unsafe fn execute_polling<S>(
mut statement: S,
query: Option<&SqlText<'_>>,
mut sleep: impl Sleep,
) -> Result<Option<CursorPolling<S>>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
let result = if let Some(sql) = query {
// We execute an unprepared "one shot query"
wait_for(|| stmt.exec_direct(sql), &mut sleep).await
} else {
// We execute a prepared query
wait_for(|| stmt.execute(), &mut sleep).await
};
// If delayed parameters (e.g. input streams) are bound we might need to put data in order to
// execute.
let need_data =
result
.on_success(|| false)
.into_result_with(&stmt, false, Some(false), Some(true))?;
if need_data {
// Check if any delayed parameters have been bound which stream data to the database at
// statement execution time. Loops over each bound stream.
while let Some(blob_ptr) = stmt.param_data().into_result(&stmt)? {
// The safe interfaces currently exclusively bind pointers to `Blob` trait objects
let blob_ptr: *mut &mut dyn Blob = transmute(blob_ptr);
let blob_ref = &mut *blob_ptr;
// Loop over all batches within each blob
while let Some(batch) = blob_ref.next_batch().map_err(Error::FailedReadingInput)? {
let result = wait_for(|| stmt.put_binary_batch(batch), &mut sleep).await;
result.into_result(&stmt)?;
}
}
}
// Check if a result set has been created.
let num_result_cols = wait_for(|| stmt.num_result_cols(), &mut sleep)
.await
.into_result(&stmt)?;
if num_result_cols == 0 {
Ok(None)
} else {
// Safe: `statement` is in cursor state.
let cursor = CursorPolling::new(statement);
Ok(Some(cursor))
}
}source§impl<T> SqlResult<T>
impl<T> SqlResult<T>
sourcepub fn is_err(&self) -> bool
pub fn is_err(&self) -> bool
True if variant is SqlResult::Error.
Examples found in repository?
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
fn describe_col(
&self,
column_number: u16,
column_description: &mut ColumnDescription,
) -> SqlResult<()> {
let name = &mut column_description.name;
// Use maximum available capacity.
name.resize(name.capacity(), 0);
let mut name_length: i16 = 0;
let mut data_type = SqlDataType::UNKNOWN_TYPE;
let mut column_size = 0;
let mut decimal_digits = 0;
let mut nullable = odbc_sys::Nullability::UNKNOWN;
let res = unsafe {
sql_describe_col(
self.as_sys(),
column_number,
mut_buf_ptr(name),
clamp_small_int(name.len()),
&mut name_length,
&mut data_type,
&mut column_size,
&mut decimal_digits,
&mut nullable,
)
.into_sql_result("SQLDescribeCol")
};
if res.is_err() {
return res;
}
column_description.nullability = Nullability::new(nullable);
if name_length + 1 > clamp_small_int(name.len()) {
// Buffer is to small to hold name, retry with larger buffer
name.resize(name_length as usize + 1, 0);
self.describe_col(column_number, column_description)
} else {
name.resize(name_length as usize, 0);
column_description.data_type = DataType::new(data_type, column_size, decimal_digits);
res
}
}
/// Executes a statement, using the current values of the parameter marker variables if any
/// parameters exist in the statement. SQLExecDirect is the fastest way to submit an SQL
/// statement for one-time execution.
///
/// # Safety
///
/// While `self` as always guaranteed to be a valid allocated handle, this function may
/// dereference bound parameters. It is the callers responsibility to ensure these are still
/// valid. One strategy is to reset potentially invalid parameters right before the call using
/// `reset_parameters`.
///
/// # Return
///
/// * [`SqlResult::NeedData`] if execution requires additional data from delayed parameters.
/// * [`SqlResult::NoData`] if a searched update or delete statement did not affect any rows at
/// the data source.
unsafe fn exec_direct(&mut self, statement: &SqlText) -> SqlResult<()> {
sql_exec_direc(
self.as_sys(),
statement.ptr(),
statement.len_char().try_into().unwrap(),
)
.into_sql_result("SQLExecDirect")
}
/// Close an open cursor.
fn close_cursor(&mut self) -> SqlResult<()> {
unsafe { SQLCloseCursor(self.as_sys()) }.into_sql_result("SQLCloseCursor")
}
/// Send an SQL statement to the data source for preparation. The application can include one or
/// more parameter markers in the SQL statement. To include a parameter marker, the application
/// embeds a question mark (?) into the SQL string at the appropriate position.
fn prepare(&mut self, statement: &SqlText) -> SqlResult<()> {
unsafe {
sql_prepare(
self.as_sys(),
statement.ptr(),
statement.len_char().try_into().unwrap(),
)
}
.into_sql_result("SQLPrepare")
}
/// Executes a statement prepared by `prepare`. After the application processes or discards the
/// results from a call to `execute`, the application can call SQLExecute again with new
/// parameter values.
///
/// # Safety
///
/// While `self` as always guaranteed to be a valid allocated handle, this function may
/// dereference bound parameters. It is the callers responsibility to ensure these are still
/// valid. One strategy is to reset potentially invalid parameters right before the call using
/// `reset_parameters`.
///
/// # Return
///
/// * [`SqlResult::NeedData`] if execution requires additional data from delayed parameters.
/// * [`SqlResult::NoData`] if a searched update or delete statement did not affect any rows at
/// the data source.
unsafe fn execute(&mut self) -> SqlResult<()> {
SQLExecute(self.as_sys()).into_sql_result("SQLExecute")
}
/// Number of columns in result set.
///
/// Can also be used to check, whether or not a result set has been created at all.
fn num_result_cols(&self) -> SqlResult<i16> {
let mut out: i16 = 0;
unsafe { SQLNumResultCols(self.as_sys(), &mut out) }
.into_sql_result("SQLNumResultCols")
.on_success(|| out)
}
/// Number of placeholders of a prepared query.
fn num_params(&self) -> SqlResult<u16> {
let mut out: i16 = 0;
unsafe { SQLNumParams(self.as_sys(), &mut out) }
.into_sql_result("SQLNumParams")
.on_success(|| out.try_into().unwrap())
}
/// Sets the batch size for bulk cursors, if retrieving many rows at once.
///
/// # Safety
///
/// It is the callers responsibility to ensure that buffers bound using `bind_col` can hold the
/// specified amount of rows.
unsafe fn set_row_array_size(&mut self, size: usize) -> SqlResult<()> {
assert!(size > 0);
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::RowArraySize,
size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
/// Specifies the number of values for each parameter. If it is greater than 1, the data and
/// indicator buffers of the statement point to arrays. The cardinality of each array is equal
/// to the value of this field.
///
/// # Safety
///
/// The bound buffers must at least hold the number of elements specified in this call then the
/// statement is executed.
unsafe fn set_paramset_size(&mut self, size: usize) -> SqlResult<()> {
assert!(size > 0);
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::ParamsetSize,
size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
/// Sets the binding type to columnar binding for batch cursors.
///
/// Any Positive number indicates a row wise binding with that row length. `0` indicates a
/// columnar binding.
///
/// # Safety
///
/// It is the callers responsibility to ensure that the bound buffers match the memory layout
/// specified by this function.
unsafe fn set_row_bind_type(&mut self, row_size: usize) -> SqlResult<()> {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::RowBindType,
row_size as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
fn set_metadata_id(&mut self, metadata_id: bool) -> SqlResult<()> {
unsafe {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::MetadataId,
metadata_id as usize as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
}
/// Enables or disables asynchronous execution for this statement handle. If asynchronous
/// execution is not enabled on connection level it is disabled by default and everything is
/// executed synchronously.
///
/// This is equivalent to stetting `SQL_ATTR_ASYNC_ENABLE` in the bare C API.
///
/// See
/// <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/executing-statements-odbc>
fn set_async_enable(&mut self, on: bool) -> SqlResult<()> {
unsafe {
sql_set_stmt_attr(
self.as_sys(),
StatementAttribute::AsyncEnable,
on as usize as Pointer,
0,
)
.into_sql_result("SQLSetStmtAttr")
}
}
/// Binds a buffer holding an input parameter to a parameter marker in an SQL statement. This
/// specialized version takes a constant reference to parameter, but is therefore limited to
/// binding input parameters. See [`Statement::bind_parameter`] for the version which can bind
/// input and output parameters.
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_input_parameter(
&mut self,
parameter_number: u16,
parameter: &(impl HasDataType + CData + ?Sized),
) -> SqlResult<()> {
let parameter_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
ParamType::Input,
parameter.cdata_type(),
parameter_type.data_type(),
parameter_type.column_size(),
parameter_type.decimal_digits(),
// We cast const to mut here, but we specify the input_output_type as input.
parameter.value_ptr() as *mut c_void,
parameter.buffer_length(),
// We cast const to mut here, but we specify the input_output_type as input.
parameter.indicator_ptr() as *mut isize,
)
.into_sql_result("SQLBindParameter")
}
/// Binds a buffer holding a single parameter to a parameter marker in an SQL statement. To bind
/// input parameters using constant references see [`Statement::bind_input_parameter`].
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_parameter(
&mut self,
parameter_number: u16,
input_output_type: ParamType,
parameter: &mut (impl CDataMut + HasDataType),
) -> SqlResult<()> {
let parameter_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
input_output_type,
parameter.cdata_type(),
parameter_type.data_type(),
parameter_type.column_size(),
parameter_type.decimal_digits(),
parameter.value_ptr() as *mut c_void,
parameter.buffer_length(),
parameter.mut_indicator_ptr(),
)
.into_sql_result("SQLBindParameter")
}
/// Binds an input stream to a parameter marker in an SQL statement. Use this to stream large
/// values at statement execution time. To bind preallocated constant buffers see
/// [`Statement::bind_input_parameter`].
///
/// See <https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlbindparameter-function>.
///
/// # Safety
///
/// * It is up to the caller to ensure the lifetimes of the bound parameters.
/// * Calling this function may influence other statements that share the APD.
unsafe fn bind_delayed_input_parameter(
&mut self,
parameter_number: u16,
parameter: &mut (impl DelayedInput + HasDataType),
) -> SqlResult<()> {
let paramater_type = parameter.data_type();
SQLBindParameter(
self.as_sys(),
parameter_number,
ParamType::Input,
parameter.cdata_type(),
paramater_type.data_type(),
paramater_type.column_size(),
paramater_type.decimal_digits(),
parameter.stream_ptr(),
0,
// We cast const to mut here, but we specify the input_output_type as input.
parameter.indicator_ptr() as *mut isize,
)
.into_sql_result("SQLBindParameter")
}
/// `true` if a given column in a result set is unsigned or not a numeric type, `false`
/// otherwise.
///
/// `column_number`: Index of the column, starting at 1.
fn is_unsigned_column(&self, column_number: u16) -> SqlResult<bool> {
unsafe { self.numeric_col_attribute(Desc::Unsigned, column_number) }.map(|out| match out {
0 => false,
1 => true,
_ => panic!("Unsigned column attribute must be either 0 or 1."),
})
}
/// Returns a number identifying the SQL type of the column in the result set.
///
/// `column_number`: Index of the column, starting at 1.
fn col_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::Type, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}
/// The concise data type. For the datetime and interval data types, this field returns the
/// concise data type; for example, `TIME` or `INTERVAL_YEAR`.
///
/// `column_number`: Index of the column, starting at 1.
fn col_concise_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::ConciseType, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}
/// Returns the size in bytes of the columns. For variable sized types the maximum size is
/// returned, excluding a terminating zero.
///
/// `column_number`: Index of the column, starting at 1.
fn col_octet_length(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::OctetLength, column_number) }
}
/// Maximum number of characters required to display data from the column.
///
/// `column_number`: Index of the column, starting at 1.
fn col_display_size(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::DisplaySize, column_number) }
}
/// Precision of the column.
///
/// Denotes the applicable precision. For data types SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP, and all
/// the interval data types that represent a time interval, its value is the applicable
/// precision of the fractional seconds component.
fn col_precision(&self, column_number: u16) -> SqlResult<isize> {
unsafe { self.numeric_col_attribute(Desc::Precision, column_number) }
}
/// The applicable scale for a numeric data type. For DECIMAL and NUMERIC data types, this is
/// the defined scale. It is undefined for all other data types.
fn col_scale(&self, column_number: u16) -> SqlResult<Len> {
unsafe { self.numeric_col_attribute(Desc::Scale, column_number) }
}
/// The column alias, if it applies. If the column alias does not apply, the column name is
/// returned. If there is no column name or a column alias, an empty string is returned.
fn col_name(&self, column_number: u16, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i16 = 0;
// Let's utilize all of `buf`s capacity.
buffer.resize(buffer.capacity(), 0);
unsafe {
let mut res = sql_col_attribute(
self.as_sys(),
column_number,
Desc::Name,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
null_mut(),
)
.into_sql_result("SQLColAttribute");
if res.is_err() {
return res;
}
if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
// If we could rely on every ODBC driver sticking to the specifcation it would
// probably best to resize by `string_length_in_bytes / 2 + 1`. Yet e.g. SQLite
// seems to report the length in characters, so to work with a wide range of DB
// systems, and since buffers for names are not expected to become super large we
// ommit the division by two here.
buffer.resize((string_length_in_bytes + 1).try_into().unwrap(), 0);
res = sql_col_attribute(
self.as_sys(),
column_number,
Desc::Name,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
null_mut(),
)
.into_sql_result("SQLColAttribute");
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
res
}
}More examples
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
pub fn fetch_database_management_system_name(&self, buf: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i16 = 0;
// Let's utilize all of `buf`s capacity.
buf.resize(buf.capacity(), 0);
unsafe {
let mut res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
// Call has been a success but let's check if the buffer had been large enough.
if is_truncated_bin(buf, string_length_in_bytes.try_into().unwrap()) {
// It seems we must try again with a large enough buffer.
resize_to_fit_with_tz(buf, string_length_in_bytes.try_into().unwrap());
res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buf, string_length_in_bytes.try_into().unwrap());
res
}
}
fn info_u16(&self, info_type: InfoType) -> SqlResult<u16> {
unsafe {
let mut value = 0u16;
sql_get_info(
self.handle,
info_type,
&mut value as *mut u16 as Pointer,
// Buffer length should not be required in this case, according to the ODBC
// documentation at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgetinfo-function?view=sql-server-ver15#arguments
// However, in practice some drivers (such as Microsoft Access) require it to be
// specified explicitly here, otherwise they return an error without diagnostics.
size_of::<*mut u16>() as i16,
null_mut(),
)
.into_sql_result("SQLGetInfo")
.on_success(|| value)
}
}
/// Maximum length of catalog names.
pub fn max_catalog_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxCatalogNameLen)
}
/// Maximum length of schema names.
pub fn max_schema_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxSchemaNameLen)
}
/// Maximum length of table names.
pub fn max_table_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxTableNameLen)
}
/// Maximum length of column names.
pub fn max_column_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxColumnNameLen)
}
/// Fetch the name of the current catalog being used by the connection and store it into the
/// provided `buf`.
pub fn fetch_current_catalog(&self, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i32 = 0;
// Let's utilize all of `buf`s capacity.
buffer.resize(buffer.capacity(), 0);
unsafe {
let mut res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
if res.is_err() {
return res;
}
if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
resize_to_fit_with_tz(buffer, string_length_in_bytes.try_into().unwrap());
res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
}
if res.is_err() {
return res;
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
res
}
}sourcepub fn map<U, F>(self, f: F) -> SqlResult<U>where
F: FnOnce(T) -> U,
pub fn map<U, F>(self, f: F) -> SqlResult<U>where
F: FnOnce(T) -> U,
Applies f to any value wrapped in Success or SuccessWithInfo.
Examples found in repository?
More examples
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
fn is_unsigned_column(&self, column_number: u16) -> SqlResult<bool> {
unsafe { self.numeric_col_attribute(Desc::Unsigned, column_number) }.map(|out| match out {
0 => false,
1 => true,
_ => panic!("Unsigned column attribute must be either 0 or 1."),
})
}
/// Returns a number identifying the SQL type of the column in the result set.
///
/// `column_number`: Index of the column, starting at 1.
fn col_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::Type, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}
/// The concise data type. For the datetime and interval data types, this field returns the
/// concise data type; for example, `TIME` or `INTERVAL_YEAR`.
///
/// `column_number`: Index of the column, starting at 1.
fn col_concise_type(&self, column_number: u16) -> SqlResult<SqlDataType> {
unsafe { self.numeric_col_attribute(Desc::ConciseType, column_number) }
.map(|ret| SqlDataType(ret.try_into().unwrap()))
}111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
pub fn connect_with_connection_string(&mut self, connection_string: &SqlText) -> SqlResult<()> {
unsafe {
let parent_window = null_mut();
let mut completed_connection_string = OutputStringBuffer::empty();
self.driver_connect(
connection_string,
parent_window,
&mut completed_connection_string,
DriverConnectOption::NoPrompt,
)
// Since we did pass NoPrompt we know the user can not abort the prompt.
.map(|_connection_string_is_complete| ())
}
}
/// An alternative to `connect` for connecting with a connection string. Allows for completing
/// a connection string with a GUI prompt on windows.
///
/// # Return
///
/// [`SqlResult::NoData`] in case the prompt completing the connection string has been aborted.
///
/// # Safety
///
/// `parent_window` must either be a valid window handle or `NULL`.
pub unsafe fn driver_connect(
&mut self,
connection_string: &SqlText,
parent_window: HWnd,
completed_connection_string: &mut OutputStringBuffer,
driver_completion: DriverConnectOption,
) -> SqlResult<()> {
sql_driver_connect(
self.handle,
parent_window,
connection_string.ptr(),
connection_string.len_char().try_into().unwrap(),
completed_connection_string.mut_buf_ptr(),
completed_connection_string.buf_len(),
completed_connection_string.mut_actual_len_ptr(),
driver_completion,
)
.into_sql_result("SQLDriverConnect")
}
/// Disconnect from an ODBC data source.
pub fn disconnect(&mut self) -> SqlResult<()> {
unsafe { SQLDisconnect(self.handle).into_sql_result("SQLDisconnect") }
}
/// Allocate a new statement handle. The `Statement` must not outlive the `Connection`.
pub fn allocate_statement(&self) -> SqlResult<StatementImpl<'_>> {
let mut out = null_mut();
unsafe {
SQLAllocHandle(HandleType::Stmt, self.as_handle(), &mut out)
.into_sql_result("SQLAllocHandle")
.on_success(|| StatementImpl::new(out as HStmt))
}
}
/// Specify the transaction mode. By default, ODBC transactions are in auto-commit mode (unless
/// SQLSetConnectAttr and SQLSetConnectOption are not supported, which is unlikely). Switching
/// from manual-commit mode to auto-commit mode automatically commits any open transaction on
/// the connection.
pub fn set_autocommit(&self, enabled: bool) -> SqlResult<()> {
let val = enabled as u32;
unsafe {
sql_set_connect_attr(
self.handle,
ConnectionAttribute::AutoCommit,
val as Pointer,
0, // will be ignored according to ODBC spec
)
.into_sql_result("SQLSetConnectAttr")
}
}
/// To commit a transaction in manual-commit mode.
pub fn commit(&self) -> SqlResult<()> {
unsafe {
SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Commit)
.into_sql_result("SQLEndTran")
}
}
/// Roll back a transaction in manual-commit mode.
pub fn rollback(&self) -> SqlResult<()> {
unsafe {
SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Rollback)
.into_sql_result("SQLEndTran")
}
}
/// Fetch the name of the database management system used by the connection and store it into
/// the provided `buf`.
pub fn fetch_database_management_system_name(&self, buf: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i16 = 0;
// Let's utilize all of `buf`s capacity.
buf.resize(buf.capacity(), 0);
unsafe {
let mut res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
// Call has been a success but let's check if the buffer had been large enough.
if is_truncated_bin(buf, string_length_in_bytes.try_into().unwrap()) {
// It seems we must try again with a large enough buffer.
resize_to_fit_with_tz(buf, string_length_in_bytes.try_into().unwrap());
res = sql_get_info(
self.handle,
InfoType::DbmsName,
mut_buf_ptr(buf) as Pointer,
binary_length(buf).try_into().unwrap(),
&mut string_length_in_bytes as *mut i16,
)
.into_sql_result("SQLGetInfo");
if res.is_err() {
return res;
}
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buf, string_length_in_bytes.try_into().unwrap());
res
}
}
fn info_u16(&self, info_type: InfoType) -> SqlResult<u16> {
unsafe {
let mut value = 0u16;
sql_get_info(
self.handle,
info_type,
&mut value as *mut u16 as Pointer,
// Buffer length should not be required in this case, according to the ODBC
// documentation at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgetinfo-function?view=sql-server-ver15#arguments
// However, in practice some drivers (such as Microsoft Access) require it to be
// specified explicitly here, otherwise they return an error without diagnostics.
size_of::<*mut u16>() as i16,
null_mut(),
)
.into_sql_result("SQLGetInfo")
.on_success(|| value)
}
}
/// Maximum length of catalog names.
pub fn max_catalog_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxCatalogNameLen)
}
/// Maximum length of schema names.
pub fn max_schema_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxSchemaNameLen)
}
/// Maximum length of table names.
pub fn max_table_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxTableNameLen)
}
/// Maximum length of column names.
pub fn max_column_name_len(&self) -> SqlResult<u16> {
self.info_u16(InfoType::MaxColumnNameLen)
}
/// Fetch the name of the current catalog being used by the connection and store it into the
/// provided `buf`.
pub fn fetch_current_catalog(&self, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
// String length in bytes, not characters. Terminating zero is excluded.
let mut string_length_in_bytes: i32 = 0;
// Let's utilize all of `buf`s capacity.
buffer.resize(buffer.capacity(), 0);
unsafe {
let mut res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
if res.is_err() {
return res;
}
if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
resize_to_fit_with_tz(buffer, string_length_in_bytes.try_into().unwrap());
res = sql_get_connect_attr(
self.handle,
ConnectionAttribute::CurrentCatalog,
mut_buf_ptr(buffer) as Pointer,
binary_length(buffer).try_into().unwrap(),
&mut string_length_in_bytes as *mut i32,
)
.into_sql_result("SQLGetConnectAttr");
}
if res.is_err() {
return res;
}
// Resize buffer to exact string length without terminal zero
resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
res
}
}
/// Indicates the state of the connection. If `true` the connection has been lost. If `false`,
/// the connection is still active.
pub fn is_dead(&self) -> SqlResult<bool> {
unsafe {
self.attribute_u32(ConnectionAttribute::ConnectionDead)
.map(|v| match v {
0 => false,
1 => true,
other => panic!("Unexpected result value from SQLGetConnectAttr: {}", other),
})
}
}sourcepub fn unwrap(self) -> T
pub fn unwrap(self) -> T
Examples found in repository?
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
pub fn execute_columns<S>(
mut statement: S,
catalog_name: &SqlText,
schema_name: &SqlText,
table_name: &SqlText,
column_name: &SqlText,
) -> Result<CursorImpl<S>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
stmt.columns(catalog_name, schema_name, table_name, column_name)
.into_result(&stmt)?;
// We assume columns always creates a result set, since it works like a SELECT statement.
debug_assert_ne!(stmt.num_result_cols().unwrap(), 0);
// Safe: `statement` is in cursor state
let cursor = unsafe { CursorImpl::new(statement) };
Ok(cursor)
}
/// Shared implementation for executing a tables query between [`crate::Connection`] and
/// [`crate::Preallocated`].
pub fn execute_tables<S>(
mut statement: S,
catalog_name: &SqlText,
schema_name: &SqlText,
table_name: &SqlText,
column_name: &SqlText,
) -> Result<CursorImpl<S>, Error>
where
S: AsStatementRef,
{
let mut stmt = statement.as_stmt_ref();
stmt.tables(catalog_name, schema_name, table_name, column_name)
.into_result(&stmt)?;
// We assume columns always creates a result set, since it works like a SELECT statement.
debug_assert_ne!(stmt.num_result_cols().unwrap(), 0);
// Safe: `statement` is in Cursor state.
let cursor = unsafe { CursorImpl::new(statement) };
Ok(cursor)
}