pub struct StatementImpl<'s> { /* private fields */ }
Expand description

An owned valid (i.e. successfully allocated) ODBC statement handle.

Implementations§

Safety

handle must be a valid (successfully allocated) statement handle.

Examples found in repository?
src/handles/connection.rs (line 168)
163
164
165
166
167
168
169
170
    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))
        }
    }

Transfer ownership of this statement to a raw system handle. It is the users responsibility to call crate::sys::SQLFreeHandle.

Examples found in repository?
src/connection.rs (line 295)
290
291
292
293
294
295
296
297
    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))
    }

Special wrapper to a borrowed statement. Acts like a mutable reference to an owned statement, but allows the lifetime of the tracked connection to stay covariant.

Examples found in repository?
src/handles/statement.rs (line 130)
129
130
131
132
133
134
135
136
137
    fn as_stmt_ref(&mut self) -> StatementRef<'_> {
        self.as_stmt_ref()
    }
}

impl<'o> AsStatementRef for &mut StatementImpl<'o> {
    fn as_stmt_ref(&mut self) -> StatementRef<'_> {
        (*self).as_stmt_ref()
    }
More examples
Hide additional examples
src/preallocated.rs (line 211)
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
    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
    }
}

impl<'o> AsStatementRef for PreallocatedPolling<'o> {
    fn as_stmt_ref(&mut self) -> StatementRef<'_> {
        self.statement.as_stmt_ref()
    }

Trait Implementations§

The raw underlying ODBC handle used to talk to the ODBC C API. The handle must be valid.
The type of the ODBC handle returned by as_handle. This is a method rather than a constant in order to make the type object safe.
Get an exclusive reference to the underlying statement handle. This method is used to implement other more higher level methods on top of it. It is not intended to be called by users of this crate directly, yet it may serve as an escape hatch for low level usecases.
Get an exclusive reference to the underlying statement handle. This method is used to implement other more higher level methods on top of it. It is not intended to be called by users of this crate directly, yet it may serve as an escape hatch for low level usecases.
Executes the destructor for this type. Read more

Gain access to the underlying statement handle without transferring ownership to it.

Binds application data buffers to columns in the result set. Read more
Returns the next row set in the result set. Read more
Retrieves data for a single column in the result set or for a single parameter.
Release all column buffers bound by bind_col. Except bookmark column.
Bind an integer to hold the number of rows retrieved with fetch in the current row set. Passing None for num_rows is going to unbind the value from the statement. Read more
Fetch a column description using the column index. Read more
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. Read more
Close an open cursor.
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.
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. Read more
Number of columns in result set. Read more
Number of placeholders of a prepared query.
Sets the batch size for bulk cursors, if retrieving many rows at once. Read more
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. Read more
Sets the binding type to columnar binding for batch cursors. Read more
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. Read more
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. Read more
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. Read more
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. Read more
true if a given column in a result set is unsigned or not a numeric type, false otherwise. Read more
Returns a number identifying the SQL type of the column in the result set. Read more
The concise data type. For the datetime and interval data types, this field returns the concise data type; for example, TIME or INTERVAL_YEAR. Read more
Returns the size in bytes of the columns. For variable sized types the maximum size is returned, excluding a terminating zero. Read more
Maximum number of characters required to display data from the column. Read more
Precision of the column. Read more
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.
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.
Safety Read more
Sets the SQL_DESC_COUNT field of the APD to 0, releasing all parameter buffers set for the given StatementHandle.
Describes parameter marker associated with a prepared SQL statement. Read more
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. Read more
Executes a columns query using this statement handle.
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. Read more
To put a batch of binary data into the data source at statement execution time. May return SqlResult::NeedData Read more
Number of rows affected by an UPDATE, INSERT, or DELETE statement. Read more
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. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.