pub struct SqlText<'a> { /* private fields */ }Expand description
Handles conversion from UTF-8 string slices to ODBC SQL char encoding. Depending on the conditional compiliation due to feature flags, the UTF-8 strings are either passed without conversion to narrow method calls, or they are converted to UTF-16, before passed to the wide methods.
Implementations§
source§impl<'a> SqlText<'a>
impl<'a> SqlText<'a>
sourcepub fn new(text: &'a str) -> Self
pub fn new(text: &'a str) -> Self
Create an SqlText buffer from an UTF-8 string slice
Examples found in repository?
src/preallocated.rs (line 90)
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
pub fn execute(
&mut self,
query: &str,
params: impl ParameterCollectionRef,
) -> Result<Option<CursorImpl<&mut StatementImpl<'o>>>, Error> {
let query = SqlText::new(query);
execute_with_parameters(move || Ok(&mut self.statement), Some(&query), params)
}
/// Transfer ownership to the underlying statement handle.
///
/// The resulting type is one level of indirection away from the raw pointer of the ODBC API. It
/// no longer has any guarantees about bound buffers, but is still guaranteed to be a valid
/// allocated statement handle. This serves together with
/// [`crate::handles::StatementImpl::into_sys`] or [`crate::handles::Statement::as_sys`] this
/// serves as an escape hatch to access the functionality provided by `crate::sys` not yet
/// accessible through safe abstractions.
pub fn into_statement(self) -> StatementImpl<'o> {
self.statement
}
/// List tables, schemas, views and catalogs of a datasource.
///
/// # Parameters
///
/// * `catalog_name`: Filter result by catalog name. Accept search patterns. Use `%` to match
/// any number of characters. Use `_` to match exactly on character. Use `\` to escape
/// characeters.
/// * `schema_name`: Filter result by schema. Accepts patterns in the same way as
/// `catalog_name`.
/// * `table_name`: Filter result by table. Accepts patterns in the same way as `catalog_name`.
/// * `table_type`: Filters results by table type. E.g: 'TABLE', 'VIEW'. This argument accepts a
/// comma separeted list of table types. Omit it to not filter the result by table type at
/// all.
pub fn tables(
&mut self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
table_type: &str,
) -> Result<CursorImpl<&mut StatementImpl<'o>>, Error> {
execute_tables(
&mut self.statement,
&SqlText::new(catalog_name),
&SqlText::new(schema_name),
&SqlText::new(table_name),
&SqlText::new(table_type),
)
}
/// A cursor describing columns of all tables matching the patterns. Patterns support as
/// placeholder `%` for multiple characters or `_` for a single character. Use `\` to escape.The
/// returned cursor has the columns:
/// `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `COLUMN_NAME`, `DATA_TYPE`, `TYPE_NAME`,
/// `COLUMN_SIZE`, `BUFFER_LENGTH`, `DECIMAL_DIGITS`, `NUM_PREC_RADIX`, `NULLABLE`,
/// `REMARKS`, `COLUMN_DEF`, `SQL_DATA_TYPE`, `SQL_DATETIME_SUB`, `CHAR_OCTET_LENGTH`,
/// `ORDINAL_POSITION`, `IS_NULLABLE`.
///
/// In addition to that there may be a number of columns specific to the data source.
pub fn columns(
&mut self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
column_name: &str,
) -> Result<CursorImpl<&mut StatementImpl<'o>>, Error> {
execute_columns(
&mut self.statement,
&SqlText::new(catalog_name),
&SqlText::new(schema_name),
&SqlText::new(table_name),
&SqlText::new(column_name),
)
}
/// 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};
///
/// /// Make everyone rich and return how many colleagues are happy now.
/// fn raise_minimum_salary(
/// conn: &Connection<'_>,
/// new_min_salary: i32
/// ) -> Result<usize, Error> {
/// // We won't use conn.execute directly, because we need a handle to ask about the number
/// // of changed rows. So let's allocate the statement explicitly.
/// let mut stmt = conn.preallocate()?;
/// stmt.execute(
/// "UPDATE Employees SET salary = ? WHERE salary < ?",
/// (&new_min_salary, &new_min_salary),
/// )?;
/// let number_of_updated_rows = stmt
/// .row_count()?
/// .expect("For UPDATE statements row count must always be available.");
/// Ok(number_of_updated_rows)
/// }
/// ```
pub fn row_count(&mut self) -> Result<Option<usize>, Error> {
self.statement
.row_count()
.into_result(&self.statement)
.map(|count| {
// ODBC returns -1 in case a row count is not available
if count == -1 {
None
} else {
Some(count.try_into().unwrap())
}
})
}
/// Call this method to enable asynchronous polling mode on the statement
pub fn into_polling(mut self) -> Result<PreallocatedPolling<'o>, Error> {
self.statement
.set_async_enable(true)
.into_result(&self.statement)?;
Ok(PreallocatedPolling::new(self.statement))
}
}
impl<'o> AsStatementRef for Preallocated<'o> {
fn as_stmt_ref(&mut self) -> StatementRef<'_> {
self.statement.as_stmt_ref()
}
}
/// Asynchronous sibling of [`Preallocated`] using polling mode for execution. Can be obtained using
/// [`Preallocated::into_polling`].
pub struct PreallocatedPolling<'open_connection> {
/// A valid statement handle in polling mode
statement: StatementImpl<'open_connection>,
}
impl<'o> PreallocatedPolling<'o> {
fn new(statement: StatementImpl<'o>) -> Self {
Self { statement }
}
/// Executes a statement. This is the fastest way to sequentially execute different SQL
/// Statements asynchronously.
///
/// # Parameters
///
/// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
/// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
/// represent no parameters. Check the [`crate::parameter`] module level documentation for
/// more information on how to pass parameters.
/// * `sleep`: Governs the polling intervals
///
/// # Return
///
/// Returns `Some` if a cursor is created. If `None` is returned no cursor has been created (
/// e.g. the query came back empty). Note that an empty query may also create a cursor with zero
/// rows. Since we want to reuse the statement handle a returned cursor will not take ownership
/// of it and instead burrow it.
///
/// # Example
///
/// ```
/// use odbc_api::{Connection, Error};
/// use std::{io::{self, stdin, Read}, time::Duration};
///
/// /// Execute many different queries sequentially.
/// async fn execute_all(conn: &Connection<'_>, queries: &[&str]) -> Result<(), Error>{
/// let mut statement = conn.preallocate()?.into_polling()?;
/// let sleep = || tokio::time::sleep(Duration::from_millis(20));
/// for query in queries {
/// println!("Executing {query}");
/// match statement.execute(&query, (), sleep).await {
/// Err(e) => println!("{}", e),
/// Ok(None) => println!("No results set generated."),
/// Ok(Some(cursor)) => {
/// // ...print cursor contents...
/// },
/// }
/// }
/// Ok(())
/// }
/// ```
pub async fn execute(
&mut self,
query: &str,
params: impl ParameterCollectionRef,
sleep: impl Sleep,
) -> Result<Option<CursorPolling<&mut StatementImpl<'o>>>, Error> {
let query = SqlText::new(query);
execute_with_parameters_polling(
move || Ok(&mut self.statement),
Some(&query),
params,
sleep,
)
.await
}More examples
src/connection.rs (line 118)
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 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
pub fn execute(
&self,
query: &str,
params: impl ParameterCollectionRef,
) -> Result<Option<CursorImpl<StatementImpl<'_>>>, Error> {
let query = SqlText::new(query);
let lazy_statement = move || self.allocate_statement();
execute_with_parameters(lazy_statement, Some(&query), params)
}
/// Asynchronous sibling of [`Self::execute`]. Uses polling mode to be asynchronous. `sleep`
/// does govern the behaviour of polling, by waiting for the future in between polling. Sleep
/// should not be implemented using a sleep which blocks the system thread, but rather utilize
/// the methods provided by your async runtime. E.g.:
///
/// ```
/// use odbc_api::{Connection, IntoParameter, Error};
/// use std::time::Duration;
///
/// async fn insert_post<'a>(
/// connection: &'a Connection<'a>,
/// user: &str,
/// post: &str,
/// ) -> Result<(), Error> {
/// // Poll every 50 ms.
/// let sleep = || tokio::time::sleep(Duration::from_millis(50));
/// let sql = "INSERT INTO POSTS (user, post) VALUES (?, ?)";
/// // Execute query using ODBC polling method
/// let params = (&user.into_parameter(), &post.into_parameter());
/// connection.execute_polling(&sql, params, sleep).await?;
/// Ok(())
/// }
/// ```
pub async fn execute_polling(
&self,
query: &str,
params: impl ParameterCollectionRef,
sleep: impl Sleep,
) -> Result<Option<CursorPolling<StatementImpl<'_>>>, Error> {
let query = SqlText::new(query);
let lazy_statement = move || self.allocate_statement();
execute_with_parameters_polling(lazy_statement, Some(&query), params, sleep).await
}
/// In some use cases there you only execute a single statement, or the time to open a
/// connection does not matter users may wish to choose to not keep a connection alive seperatly
/// from the cursor, in order to have an easier time withe the borrow checker.
///
/// ```no_run
/// use lazy_static::lazy_static;
/// use odbc_api::{Environment, Error, Cursor};
///
/// lazy_static! {
/// static ref ENV: Environment = unsafe { Environment::new().unwrap() };
/// }
///
/// const CONNECTION_STRING: &str =
/// "Driver={ODBC Driver 17 for SQL Server};\
/// Server=localhost;UID=SA;\
/// PWD=My@Test@Password1;";
///
/// fn execute_query(query: &str) -> Result<Option<impl Cursor>, Error> {
/// let conn = ENV.connect_with_connection_string(CONNECTION_STRING)?;
///
/// // connect.execute(&query, ()) // Compiler error: Would return local ref to `conn`.
///
/// conn.into_cursor(&query, ())
/// }
/// ```
pub fn into_cursor(
self,
query: &str,
params: impl ParameterCollectionRef,
) -> Result<Option<CursorImpl<StatementConnection<'c>>>, Error> {
let cursor = match self.execute(query, params) {
Ok(Some(cursor)) => cursor,
Ok(None) => return Ok(None),
Err(e) => return Err(e),
};
// The rust compiler needs some help here. It assumes otherwise that the lifetime of the
// resulting cursor would depend on the lifetime of `params`.
let mut cursor = ManuallyDrop::new(cursor);
let handle = cursor.as_sys();
// Safe: `handle` is a valid statement, and we are giving up ownership of `self`.
let statement = unsafe { StatementConnection::new(handle, self) };
// Safe: `statement is in the cursor state`.
let cursor = unsafe { CursorImpl::new(statement) };
Ok(Some(cursor))
}
/// Prepares an SQL statement. This is recommended for repeated execution of similar queries.
///
/// Should your use case require you to execute the same query several times with different
/// parameters, prepared queries are the way to go. These gives the database a chance to cache
/// the access plan associated with your SQL statement. It is not unlike compiling your program
/// once and executing it several times.
///
/// ```
/// use odbc_api::{Connection, Error, IntoParameter};
/// use std::io::{self, stdin, Read};
///
/// fn interactive(conn: &Connection) -> io::Result<()>{
/// let mut prepared = conn.prepare("SELECT * FROM Movies WHERE title=?;").unwrap();
/// let mut title = String::new();
/// stdin().read_line(&mut title)?;
/// while !title.is_empty() {
/// match prepared.execute(&title.as_str().into_parameter()) {
/// Err(e) => println!("{}", e),
/// // Most drivers would return a result set even if no Movie with the title is found,
/// // the result set would just be empty. Well, most drivers.
/// Ok(None) => println!("No result set generated."),
/// Ok(Some(cursor)) => {
/// // ...print cursor contents...
/// }
/// }
/// stdin().read_line(&mut title)?;
/// }
/// Ok(())
/// }
/// ```
///
/// # Parameters
///
/// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
/// may be used as a placeholder in the statement text, to be replaced with parameters during
/// execution.
pub fn prepare(&self, query: &str) -> Result<Prepared<StatementImpl<'_>>, Error> {
let query = SqlText::new(query);
let mut stmt = self.allocate_statement()?;
stmt.prepare(&query).into_result(&stmt)?;
Ok(Prepared::new(stmt))
}
/// Prepares an SQL statement which takes ownership of the connection. The advantage over
/// [`Self::prepare`] is, that you do not need to keep track of the lifetime of the connection
/// seperatly and can create types which do own the prepared query and only depend on the
/// lifetime of the environment. The downside is that you can not use the connection for
/// anything else anymore.
///
/// # Parameters
///
/// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
/// may be used as a placeholder in the statement text, to be replaced with parameters during
/// execution.
///
/// ```no_run
/// use lazy_static::lazy_static;
/// use odbc_api::{
/// Environment, Error, ColumnarBulkInserter, StatementConnection,
/// buffers::{BufferDesc, AnyBuffer},
/// };
///
/// lazy_static! {
/// static ref ENV: Environment = unsafe { Environment::new().unwrap() };
/// }
///
/// const CONNECTION_STRING: &str =
/// "Driver={ODBC Driver 17 for SQL Server};\
/// Server=localhost;UID=SA;\
/// PWD=My@Test@Password1;";
///
/// /// Supports columnar bulk inserts on a heterogenous schema (columns have different types),
/// /// takes ownership of a connection created using an environment with static lifetime.
/// type Inserter = ColumnarBulkInserter<StatementConnection<'static>, AnyBuffer>;
///
/// /// Creates an inserter which can be reused to bulk insert birthyears with static lifetime.
/// fn make_inserter(query: &str) -> Result<Inserter, Error> {
/// let conn = ENV.connect_with_connection_string(CONNECTION_STRING)?;
/// let prepared = conn.into_prepared("INSERT INTO Birthyear (name, year) VALUES (?, ?)")?;
/// let buffers = [
/// BufferDesc::Text { max_str_len: 255},
/// BufferDesc::I16 { nullable: false },
/// ];
/// let capacity = 400;
/// prepared.into_column_inserter(capacity, buffers)
/// }
/// ```
pub fn into_prepared(self, query: &str) -> Result<Prepared<StatementConnection<'c>>, Error> {
let query = SqlText::new(query);
let mut stmt = self.allocate_statement()?;
stmt.prepare(&query).into_result(&stmt)?;
// Safe: `handle` is a valid statement, and we are giving up ownership of `self`.
let stmt = unsafe { StatementConnection::new(stmt.into_sys(), self) };
Ok(Prepared::new(stmt))
}
/// Allocates an SQL statement handle. This is recommended if you want to sequentially execute
/// different queries over the same connection, as you avoid the overhead of allocating a
/// statement handle for each query.
///
/// Should you want to repeatedly execute the same query with different parameters try
/// [`Self::prepare`] instead.
///
/// # Example
///
/// ```
/// use odbc_api::{Connection, Error};
/// use std::io::{self, stdin, Read};
///
/// fn interactive(conn: &Connection) -> io::Result<()>{
/// let mut statement = conn.preallocate().unwrap();
/// let mut query = String::new();
/// stdin().read_line(&mut query)?;
/// while !query.is_empty() {
/// match statement.execute(&query, ()) {
/// Err(e) => println!("{}", e),
/// Ok(None) => println!("No results set generated."),
/// Ok(Some(cursor)) => {
/// // ...print cursor contents...
/// },
/// }
/// stdin().read_line(&mut query)?;
/// }
/// Ok(())
/// }
/// ```
pub fn preallocate(&self) -> Result<Preallocated<'_>, Error> {
let stmt = self.allocate_statement()?;
Ok(Preallocated::new(stmt))
}
/// Specify the transaction mode. By default, ODBC transactions are in auto-commit mode.
/// Switching from manual-commit mode to auto-commit mode automatically commits any open
/// transaction on the connection. There is no open or begin transaction method. Each statement
/// execution automatically starts a new transaction or adds to the existing one.
///
/// In manual commit mode you can use [`Connection::commit`] or [`Connection::rollback`]. Keep
/// in mind, that even `SELECT` statements can open new transactions. This library will rollback
/// open transactions if a connection goes out of SCOPE. This however will log an error, since
/// the transaction state is only discovered during a failed disconnect. It is preferable that
/// the application makes sure all transactions are closed if in manual commit mode.
pub fn set_autocommit(&self, enabled: bool) -> Result<(), Error> {
self.connection
.set_autocommit(enabled)
.into_result(&self.connection)
}
/// To commit a transaction in manual-commit mode.
pub fn commit(&self) -> Result<(), Error> {
self.connection.commit().into_result(&self.connection)
}
/// To rollback a transaction in manual-commit mode.
pub fn rollback(&self) -> Result<(), Error> {
self.connection.rollback().into_result(&self.connection)
}
/// 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) -> Result<bool, Error> {
self.connection.is_dead().into_result(&self.connection)
}
/// Allows sending this connection to different threads. This Connection will still be only be
/// used by one thread at a time, but it may be a different thread each time.
///
/// # Example
///
/// ```no_run
/// use std::thread;
/// use lazy_static::lazy_static;
/// use odbc_api::Environment;
/// lazy_static! {
/// static ref ENV: Environment = unsafe { Environment::new().unwrap() };
/// }
/// const MSSQL: &str =
/// "Driver={ODBC Driver 17 for SQL Server};\
/// Server=localhost;\
/// UID=SA;\
/// PWD=My@Test@Password1;\
/// ";
///
/// let conn = ENV.connect_with_connection_string("MSSQL").unwrap();
/// let conn = unsafe { conn.promote_to_send() };
/// let handle = thread::spawn(move || {
/// if let Some(cursor) = conn.execute("SELECT title FROM Movies ORDER BY year",())? {
/// // Use cursor to process results
/// }
/// Ok::<(), odbc_api::Error>(())
/// });
/// handle.join().unwrap()?;
/// # Ok::<(), odbc_api::Error>(())
/// ```
///
/// # Safety
///
/// According to the ODBC standard this should be safe. By calling this function you express your
/// trust in the implementation of the ODBC driver your application is using.
///
/// See: <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/multithreading?view=sql-server-ver15>
///
/// This function may be removed in future versions of this crate and connections would be
/// `Send` out of the Box. This will require sufficient testing in which a wide variety of
/// database drivers prove to be thread safe. For now this API tries to error on the side of
/// caution, and leaves the amount of trust you want to put in the driver implementation to the
/// user. I have seen this go wrong in the past, but time certainly improved the situation. At
/// one point this will be cargo cult and Connection can be `Send` by default (hopefully).
///
/// Note to users of `unixodbc`: You may configure the threading level to make unixodbc
/// synchronize access to the driver (and thereby making them thread safe if they are not thread
/// safe by themself. This may however hurt your performance if the driver would actually be
/// able to perform operations in parallel.
///
/// See: <https://stackoverflow.com/questions/4207458/using-unixodbc-in-a-multithreaded-concurrent-setting>
pub unsafe fn promote_to_send(self) -> force_send_sync::Send<Self> {
force_send_sync::Send::new(self)
}
/// Get the name of the database management system used by the connection.
pub fn database_management_system_name(&self) -> Result<String, Error> {
let mut buf = Vec::new();
self.connection
.fetch_database_management_system_name(&mut buf)
.into_result(&self.connection)?;
let name = slice_to_utf8(&buf).unwrap();
Ok(name)
}
/// Maximum length of catalog names.
pub fn max_catalog_name_len(&self) -> Result<u16, Error> {
self.connection
.max_catalog_name_len()
.into_result(&self.connection)
}
/// Maximum length of schema names.
pub fn max_schema_name_len(&self) -> Result<u16, Error> {
self.connection
.max_schema_name_len()
.into_result(&self.connection)
}
/// Maximum length of table names.
pub fn max_table_name_len(&self) -> Result<u16, Error> {
self.connection
.max_table_name_len()
.into_result(&self.connection)
}
/// Maximum length of column names.
pub fn max_column_name_len(&self) -> Result<u16, Error> {
self.connection
.max_column_name_len()
.into_result(&self.connection)
}
/// Get the name of the current catalog being used by the connection.
pub fn current_catalog(&self) -> Result<String, Error> {
let mut buf = Vec::new();
self.connection
.fetch_current_catalog(&mut buf)
.into_result(&self.connection)?;
let name = slice_to_utf8(&buf).expect("Return catalog must be correctly encoded");
Ok(name)
}
/// A cursor describing columns of all tables matching the patterns. Patterns support as
/// placeholder `%` for multiple characters or `_` for a single character. Use `\` to escape.The
/// returned cursor has the columns:
/// `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `COLUMN_NAME`, `DATA_TYPE`, `TYPE_NAME`,
/// `COLUMN_SIZE`, `BUFFER_LENGTH`, `DECIMAL_DIGITS`, `NUM_PREC_RADIX`, `NULLABLE`,
/// `REMARKS`, `COLUMN_DEF`, `SQL_DATA_TYPE`, `SQL_DATETIME_SUB`, `CHAR_OCTET_LENGTH`,
/// `ORDINAL_POSITION`, `IS_NULLABLE`.
///
/// In addition to that there may be a number of columns specific to the data source.
pub fn columns(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
column_name: &str,
) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
execute_columns(
self.allocate_statement()?,
&SqlText::new(catalog_name),
&SqlText::new(schema_name),
&SqlText::new(table_name),
&SqlText::new(column_name),
)
}
/// List tables, schemas, views and catalogs of a datasource.
///
/// # Parameters
///
/// * `catalog_name`: Filter result by catalog name. Accept search patterns. Use `%` to match
/// any number of characters. Use `_` to match exactly on character. Use `\` to escape
/// characeters.
/// * `schema_name`: Filter result by schema. Accepts patterns in the same way as
/// `catalog_name`.
/// * `table_name`: Filter result by table. Accepts patterns in the same way as `catalog_name`.
/// * `table_type`: Filters results by table type. E.g: 'TABLE', 'VIEW'. This argument accepts a
/// comma separeted list of table types. Omit it to not filter the result by table type at
/// all.
///
/// # Example
///
/// ```
/// use odbc_api::{Connection, Cursor, Error, ResultSetMetadata, buffers::TextRowSet};
///
/// fn print_all_tables(conn: &Connection<'_>) -> Result<(), Error> {
/// // Set all filters to an empty string, to really print all tables
/// let mut cursor = conn.tables("", "", "", "")?;
///
/// // The column are gonna be TABLE_CAT,TABLE_SCHEM,TABLE_NAME,TABLE_TYPE,REMARKS, but may
/// // also contain additional driver specific columns.
/// for (index, name) in cursor.column_names()?.enumerate() {
/// if index != 0 {
/// print!(",")
/// }
/// print!("{}", name?);
/// }
///
/// let batch_size = 100;
/// let mut buffer = TextRowSet::for_cursor(batch_size, &mut cursor, Some(4096))?;
/// let mut row_set_cursor = cursor.bind_buffer(&mut buffer)?;
///
/// while let Some(row_set) = row_set_cursor.fetch()? {
/// for row_index in 0..row_set.num_rows() {
/// if row_index != 0 {
/// print!("\n");
/// }
/// for col_index in 0..row_set.num_cols() {
/// if col_index != 0 {
/// print!(",");
/// }
/// let value = row_set
/// .at_as_str(col_index, row_index)
/// .unwrap()
/// .unwrap_or("NULL");
/// print!("{}", value);
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn tables(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
table_type: &str,
) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
let statement = self.allocate_statement()?;
execute_tables(
statement,
&SqlText::new(catalog_name),
&SqlText::new(schema_name),
&SqlText::new(table_name),
&SqlText::new(table_type),
)
}src/environment.rs (line 208)
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
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))
}sourcepub fn ptr(&self) -> *const u16
pub fn ptr(&self) -> *const u16
Examples found in repository?
src/handles/statement.rs (line 316)
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 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
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
}
}
/// # 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")
}
}More examples
src/handles/connection.rs (line 97)
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
pub fn connect(
&mut self,
data_source_name: &SqlText,
user: &SqlText,
pwd: &SqlText,
) -> SqlResult<()> {
unsafe {
sql_connect(
self.handle,
data_source_name.ptr(),
data_source_name.len_char().try_into().unwrap(),
user.ptr(),
user.len_char().try_into().unwrap(),
pwd.ptr(),
pwd.len_char().try_into().unwrap(),
)
.into_sql_result("SQLConnect")
}
}
/// 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.
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")
}sourcepub fn len_char(&self) -> usize
pub fn len_char(&self) -> usize
Length in characters
Examples found in repository?
src/handles/statement.rs (line 317)
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 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
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
}
}
/// # 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")
}
}More examples
src/handles/connection.rs (line 98)
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
pub fn connect(
&mut self,
data_source_name: &SqlText,
user: &SqlText,
pwd: &SqlText,
) -> SqlResult<()> {
unsafe {
sql_connect(
self.handle,
data_source_name.ptr(),
data_source_name.len_char().try_into().unwrap(),
user.ptr(),
user.len_char().try_into().unwrap(),
pwd.ptr(),
pwd.len_char().try_into().unwrap(),
)
.into_sql_result("SQLConnect")
}
}
/// 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.
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")
}