pub enum DataType {
Show 23 variants
Unknown,
Char {
length: usize,
},
WChar {
length: usize,
},
Numeric {
precision: usize,
scale: i16,
},
Decimal {
precision: usize,
scale: i16,
},
Integer,
SmallInt,
Float {
precision: usize,
},
Real,
Double,
Varchar {
length: usize,
},
WVarchar {
length: usize,
},
LongVarchar {
length: usize,
},
LongVarbinary {
length: usize,
},
Date,
Time {
precision: i16,
},
Timestamp {
precision: i16,
},
BigInt,
TinyInt,
Bit,
Varbinary {
length: usize,
},
Binary {
length: usize,
},
Other {
data_type: SqlDataType,
column_size: usize,
decimal_digits: i16,
},
}Expand description
The relational type of the column. Think of it as the type used in the CREATE TABLE statement
then creating the database.
There might be a mismatch between the types supported by your database and the types defined in ODBC. E.g. ODBC does not have a timestamp with timezone type, theras Postgersql and Microsoft SQL Server both have one. In such cases it is up to the specific ODBC driver what happens. Microsoft SQL Server return a custom type, with its meaning specific to that driver. PostgreSQL identifies that column as an ordinary ODBC timestamp. Enumeration over valid SQL Data Types supported by ODBC
Variants§
Unknown
The type is not known.
Char
Char(n). Character string of fixed length.
WChar
NChar(n). Character string of fixed length.
Numeric
`Numeric(p,s). Signed, exact, numeric value with a precision p and scale s (1 <= p <= 15; s <= p)
Decimal
Decimal(p,s). Signed, exact, numeric value with a precision of at least p and scale s.
The maximum precision is driver-defined. (1 <= p <= 15; s <= p)
Integer
Integer. 32 Bit Integer
SmallInt
Smallint. 16 Bit Integer
Float
Float(p). Signed, approximate, numeric value with a binary precision of at least p. The
maximum precision is driver-defined.
Depending on the implementation binary precision is either 24 (f32) or 53 (f64).
Real
Real. Signed, approximate, numeric value with a binary precision 24 (zero or absolute
value 10^-38] to 10^38).
Double
Double Precision. Signed, approximate, numeric value with a binary precision 53 (zero or
absolute value 10^-308 to 10^308).
Varchar
Fields
length: usizeMaximum length of the character string (excluding terminating zero). Wether this length is to be interpreted as bytes or Codepoints is ambigious and depends on the datasource.
E.g. For Microsoft SQL Server this is the binary length, theras for a MariaDB this refers to codepoints in case of UTF-8 encoding. If you need the binary size query the octet length for that column instead.
To find out how to interpret this value for a particular datasource you can use the
odbcsv command line tool list-columns subcommand and query a Varchar column. If the
buffer/octet length matches the column size, you can interpret this as the byte length.
Varchar(n). Variable length character string.
WVarchar
NVARCHAR(n). Variable length character string. Indicates the use of wide character strings
and use of UCS2 encoding on the side of the database.
LongVarchar
Fields
TEXT. Variable length characeter string for long text objects.
LongVarbinary
Fields
BLOB. Variable length data for long binary objects.
Date
Date. Year, month, and day fields, conforming to the rules of the Gregorian calendar.
Time
Fields
Time. Hour, minute, and second fields, with valid values for hours of 00 to 23, valid
values for minutes of 00 to 59, and valid values for seconds of 00 to 61. Precision p
indicates the seconds precision.
Timestamp
Fields
Timestamp. Year, month, day, hour, minute, and second fields, with valid values as
defined for the Date and Time variants.
BigInt
BIGINT. Exact numeric value with precision 19 (if signed) or 20 (if unsigned) and scale 0
(signed: -2^63 <= n <= 2^63 - 1, unsigned: 0 <= n <= 2^64 - 1). Has no corresponding
type in SQL-92.
TinyInt
TINYINT. Exact numeric value with precision 3 and scale 0 (signed: -128 <= n <= 127,
unsigned: 0 <= n <= 255)
Bit
BIT. Single bit binary data.
Varbinary
VARBINARY(n). Type for variable sized binary data.
Binary
BINARY(n). Type for fixed sized binary data.
Other
Fields
data_type: SqlDataTypeType of the column
The driver returned a type, but it is not among the other types of these enumeration. This is a catchall, in case the library is incomplete, or the data source supports custom or non-standard types.
Implementations§
source§impl DataType
impl DataType
sourcepub fn new(
data_type: SqlDataType,
column_size: usize,
decimal_digits: i16
) -> Self
pub fn new(
data_type: SqlDataType,
column_size: usize,
decimal_digits: i16
) -> Self
This constructor is useful to create an instance of the enumeration using values returned by
ODBC Api calls like SQLDescribeCol, rather than just initializing a variant directly.
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 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
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
}
}
/// # 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),
})
}sourcepub fn data_type(&self) -> SqlDataType
pub fn data_type(&self) -> SqlDataType
The associated data_type discriminator for this variant.
Examples found in repository?
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
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")
}sourcepub fn column_size(&self) -> usize
pub fn column_size(&self) -> usize
Return the column size, as it is required to bind the data type as a parameter. This implies
Examples found in repository?
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
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")
}More examples
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
fn col_data_type(&mut self, column_number: u16) -> Result<DataType, Error> {
let stmt = self.as_stmt_ref();
let kind = stmt.col_concise_type(column_number).into_result(&stmt)?;
let dt = match kind {
SqlDataType::UNKNOWN_TYPE => DataType::Unknown,
SqlDataType::EXT_VAR_BINARY => DataType::Varbinary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_LONG_VAR_BINARY => DataType::LongVarbinary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_BINARY => DataType::Binary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_W_VARCHAR => DataType::WVarchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_W_CHAR => DataType::WChar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_LONG_VARCHAR => DataType::LongVarchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::CHAR => DataType::Char {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::VARCHAR => DataType::Varchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::NUMERIC => DataType::Numeric {
precision: self.col_precision(column_number)?.try_into().unwrap(),
scale: self.col_scale(column_number)?.try_into().unwrap(),
},
SqlDataType::DECIMAL => DataType::Decimal {
precision: self.col_precision(column_number)?.try_into().unwrap(),
scale: self.col_scale(column_number)?.try_into().unwrap(),
},
SqlDataType::INTEGER => DataType::Integer,
SqlDataType::SMALLINT => DataType::SmallInt,
SqlDataType::FLOAT => DataType::Float {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::REAL => DataType::Real,
SqlDataType::DOUBLE => DataType::Double,
SqlDataType::DATE => DataType::Date,
SqlDataType::TIME => DataType::Time {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::TIMESTAMP => DataType::Timestamp {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_BIG_INT => DataType::BigInt,
SqlDataType::EXT_TINY_INT => DataType::TinyInt,
SqlDataType::EXT_BIT => DataType::Bit,
other => {
let mut column_description = ColumnDescription::default();
self.describe_col(column_number, &mut column_description)?;
DataType::Other {
data_type: other,
column_size: column_description.data_type.column_size(),
decimal_digits: column_description.data_type.decimal_digits(),
}
}
};
Ok(dt)
}sourcepub fn decimal_digits(&self) -> i16
pub fn decimal_digits(&self) -> i16
Return the number of decimal digits as required to bind the data type as a parameter.
Examples found in repository?
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
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")
}More examples
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
fn col_data_type(&mut self, column_number: u16) -> Result<DataType, Error> {
let stmt = self.as_stmt_ref();
let kind = stmt.col_concise_type(column_number).into_result(&stmt)?;
let dt = match kind {
SqlDataType::UNKNOWN_TYPE => DataType::Unknown,
SqlDataType::EXT_VAR_BINARY => DataType::Varbinary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_LONG_VAR_BINARY => DataType::LongVarbinary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_BINARY => DataType::Binary {
length: self.col_octet_length(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_W_VARCHAR => DataType::WVarchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_W_CHAR => DataType::WChar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_LONG_VARCHAR => DataType::LongVarchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::CHAR => DataType::Char {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::VARCHAR => DataType::Varchar {
length: self.col_display_size(column_number)?.try_into().unwrap(),
},
SqlDataType::NUMERIC => DataType::Numeric {
precision: self.col_precision(column_number)?.try_into().unwrap(),
scale: self.col_scale(column_number)?.try_into().unwrap(),
},
SqlDataType::DECIMAL => DataType::Decimal {
precision: self.col_precision(column_number)?.try_into().unwrap(),
scale: self.col_scale(column_number)?.try_into().unwrap(),
},
SqlDataType::INTEGER => DataType::Integer,
SqlDataType::SMALLINT => DataType::SmallInt,
SqlDataType::FLOAT => DataType::Float {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::REAL => DataType::Real,
SqlDataType::DOUBLE => DataType::Double,
SqlDataType::DATE => DataType::Date,
SqlDataType::TIME => DataType::Time {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::TIMESTAMP => DataType::Timestamp {
precision: self.col_precision(column_number)?.try_into().unwrap(),
},
SqlDataType::EXT_BIG_INT => DataType::BigInt,
SqlDataType::EXT_TINY_INT => DataType::TinyInt,
SqlDataType::EXT_BIT => DataType::Bit,
other => {
let mut column_description = ColumnDescription::default();
self.describe_col(column_number, &mut column_description)?;
DataType::Other {
data_type: other,
column_size: column_description.data_type.column_size(),
decimal_digits: column_description.data_type.decimal_digits(),
}
}
};
Ok(dt)
}sourcepub fn display_size(&self) -> Option<usize>
pub fn display_size(&self) -> Option<usize>
The maximum number of characters needed to display data in character form.
See: https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/display-size
Examples found in repository?
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
pub fn utf8_len(&self) -> Option<usize> {
match self {
// One character may need up to four bytes to be represented in utf-8.
DataType::Varchar { length }
| DataType::WVarchar { length }
| DataType::WChar { length }
| DataType::Char { length } => Some(length * 4),
other => other.display_size(),
}
}
/// The maximum length of the UTF-16 representation in 2-Byte characters.
///
/// ```
/// use odbc_api::DataType;
/// // Character set data types length is multiplied by two.
/// assert_eq!(DataType::Varchar { length: 10 }.utf16_len(), Some(20));
/// assert_eq!(DataType::Char { length: 10 }.utf16_len(), Some(20));
/// assert_eq!(DataType::WVarchar { length: 10 }.utf16_len(), Some(20));
/// assert_eq!(DataType::WChar { length: 10 }.utf16_len(), Some(20));
/// // For other types return value is identical to display size as they are assumed to be
/// // entirely representable with ASCII characters.
/// assert_eq!(DataType::Numeric { precision: 10, scale: 3}.utf16_len(), Some(10 + 2));
/// ```
pub fn utf16_len(&self) -> Option<usize> {
match self {
// One character may need up to two u16 to be represented in utf-16.
DataType::Varchar { length }
| DataType::WVarchar { length }
| DataType::WChar { length }
| DataType::Char { length } => Some(length * 2),
other => other.display_size(),
}
}More examples
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
pub fn from_data_type(data_type: DataType, nullable: bool) -> Option<Self> {
let buffer_desc = match data_type {
DataType::Numeric { precision, scale }
| DataType::Decimal { precision, scale } if scale == 0 && precision < 3 => BufferDesc::I8 { nullable },
DataType::Numeric { precision, scale }
| DataType::Decimal { precision, scale } if scale == 0 && precision < 10 => BufferDesc::I32 { nullable },
DataType::Numeric { precision, scale }
| DataType::Decimal { precision, scale } if scale == 0 && precision < 19 => BufferDesc::I64 { nullable },
DataType::Integer => BufferDesc::I32 { nullable },
DataType::SmallInt => BufferDesc::I16 { nullable },
DataType::Float { precision: 0..=24 } | DataType::Real => BufferDesc::F32 { nullable },
DataType::Float { precision: 25..=53 } |DataType::Double => BufferDesc::F64 { nullable },
DataType::Date => BufferDesc::Date { nullable },
DataType::Time { precision: 0 } => BufferDesc::Time { nullable },
DataType::Timestamp { precision: _ } => BufferDesc::Timestamp { nullable },
DataType::BigInt => BufferDesc::I64 { nullable },
DataType::TinyInt => BufferDesc::I8 { nullable },
DataType::Bit => BufferDesc::Bit { nullable },
DataType::Varbinary { length }
| DataType::Binary { length }
| DataType::LongVarbinary { length } => BufferDesc::Binary { length },
DataType::Varchar { length }
| DataType::WVarchar { length }
// Currently no special buffers for fixed lengths text implemented.
| DataType::WChar {length }
| DataType::Char { length }
| DataType::LongVarchar { length } => BufferDesc::Text { max_str_len : length },
// Specialized buffers for Numeric and decimal are not yet supported.
| DataType::Numeric { precision: _, scale: _ }
| DataType::Decimal { precision: _, scale: _ }
| DataType::Time { precision: _ } => BufferDesc::Text { max_str_len: data_type.display_size().unwrap() },
DataType::Unknown
| DataType::Float { precision: _ }
| DataType::Other { data_type: _, column_size: _, decimal_digits: _ } => return None,
};
Some(buffer_desc)
}sourcepub fn utf8_len(&self) -> Option<usize>
pub fn utf8_len(&self) -> Option<usize>
The maximum length of the UTF-8 representation in bytes.
use odbc_api::DataType;
// Character set data types length is multiplied by four.
assert_eq!(DataType::Varchar { length: 10 }.utf8_len(), Some(40));
assert_eq!(DataType::Char { length: 10 }.utf8_len(), Some(40));
assert_eq!(DataType::WVarchar { length: 10 }.utf8_len(), Some(40));
assert_eq!(DataType::WChar { length: 10 }.utf8_len(), Some(40));
// For other types return value is identical to display size as they are assumed to be
// entirely representable with ASCII characters.
assert_eq!(DataType::Numeric { precision: 10, scale: 3}.utf8_len(), Some(10 + 2));Examples found in repository?
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
pub fn utf8_display_sizes(
metadata: &mut impl ResultSetMetadata,
) -> Result<impl Iterator<Item = Result<usize, Error>> + '_, Error> {
let num_cols: u16 = metadata.num_result_cols()?.try_into().unwrap();
let it = (1..(num_cols + 1)).map(move |col_index| {
// Ask driver for buffer length
let max_str_len = if let Some(encoded_len) = metadata.col_data_type(col_index)?.utf8_len() {
encoded_len
} else {
metadata.col_display_size(col_index)? as usize
};
Ok(max_str_len)
});
Ok(it)
}sourcepub fn utf16_len(&self) -> Option<usize>
pub fn utf16_len(&self) -> Option<usize>
The maximum length of the UTF-16 representation in 2-Byte characters.
use odbc_api::DataType;
// Character set data types length is multiplied by two.
assert_eq!(DataType::Varchar { length: 10 }.utf16_len(), Some(20));
assert_eq!(DataType::Char { length: 10 }.utf16_len(), Some(20));
assert_eq!(DataType::WVarchar { length: 10 }.utf16_len(), Some(20));
assert_eq!(DataType::WChar { length: 10 }.utf16_len(), Some(20));
// For other types return value is identical to display size as they are assumed to be
// entirely representable with ASCII characters.
assert_eq!(DataType::Numeric { precision: 10, scale: 3}.utf16_len(), Some(10 + 2));