1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 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 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
use std::fmt::Debug;
use thiserror::Error;
use uuid::Uuid;
use scylla_cql::frame::frame_errors::ResultMetadataAndRowsCountParseError;
use scylla_cql::frame::response::result::{
ColumnSpec, ColumnType, DeserializedMetadataAndRawRows, RawMetadataAndRawRows, Row, TableSpec,
};
use scylla_cql::types::deserialize::result::TypedRowIterator;
use scylla_cql::types::deserialize::row::DeserializeRow;
use scylla_cql::types::deserialize::{DeserializationError, TypeCheckError};
#[allow(deprecated)]
use super::legacy_query_result::{IntoLegacyQueryResultError, LegacyQueryResult};
/// A view over specification of a table in the database.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct TableSpecView<'res> {
table_name: &'res str,
ks_name: &'res str,
}
impl<'res> TableSpecView<'res> {
pub(crate) fn new_from_table_spec(spec: &'res TableSpec) -> Self {
Self {
table_name: spec.table_name(),
ks_name: spec.ks_name(),
}
}
/// The name of the table.
#[inline]
pub fn table_name(&self) -> &'res str {
self.table_name
}
/// The name of the keyspace the table resides in.
#[inline]
pub fn ks_name(&self) -> &'res str {
self.ks_name
}
}
/// A view over specification of a column returned by the database.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct ColumnSpecView<'res> {
table_spec: TableSpecView<'res>,
name: &'res str,
typ: &'res ColumnType<'res>,
}
impl<'res> ColumnSpecView<'res> {
pub(crate) fn new_from_column_spec(spec: &'res ColumnSpec) -> Self {
Self {
table_spec: TableSpecView::new_from_table_spec(spec.table_spec()),
name: spec.name(),
typ: spec.typ(),
}
}
/// Returns a view over specification of the table the column is part of.
#[inline]
pub fn table_spec(&self) -> TableSpecView<'res> {
self.table_spec
}
/// The column's name.
#[inline]
pub fn name(&self) -> &'res str {
self.name
}
/// The column's CQL type.
#[inline]
pub fn typ(&self) -> &'res ColumnType {
self.typ
}
}
/// A view over specification of columns returned by the database.
#[derive(Debug, Clone, Copy)]
pub struct ColumnSpecs<'res> {
specs: &'res [ColumnSpec<'res>],
}
impl<'res> ColumnSpecs<'res> {
pub(crate) fn new(specs: &'res [ColumnSpec<'res>]) -> Self {
Self { specs }
}
pub(crate) fn inner(&self) -> &'res [ColumnSpec<'res>] {
self.specs
}
/// Returns number of columns.
#[allow(clippy::len_without_is_empty)]
#[inline]
pub fn len(&self) -> usize {
self.specs.len()
}
/// Returns specification of k-th column returned from the database.
#[inline]
pub fn get_by_index(&self, k: usize) -> Option<ColumnSpecView<'res>> {
self.specs.get(k).map(ColumnSpecView::new_from_column_spec)
}
/// Returns specification of the column with given name returned from the database.
#[inline]
pub fn get_by_name(&self, name: &str) -> Option<(usize, ColumnSpecView<'res>)> {
self.specs
.iter()
.enumerate()
.find(|(_idx, spec)| spec.name() == name)
.map(|(idx, spec)| (idx, ColumnSpecView::new_from_column_spec(spec)))
}
/// Returns iterator over specification of columns returned from the database,
/// ordered by column order in the response.
#[inline]
pub fn iter(&self) -> impl Iterator<Item = ColumnSpecView<'res>> {
self.specs.iter().map(ColumnSpecView::new_from_column_spec)
}
}
/// Result of a single request to the database. It represents any kind of Result frame.
///
/// The received rows and metadata, which are present if the frame is of Result:Rows kind,
/// are kept in a raw binary form. To deserialize and access them, transform `QueryResult`
/// to [QueryRowsResult] by calling [QueryResult::into_rows_result].
///
/// NOTE: this is a result of a single CQL request. If you use paging for your query,
/// this will contain exactly one page.
#[derive(Debug, Clone)]
pub struct QueryResult {
raw_metadata_and_rows: Option<RawMetadataAndRawRows>,
tracing_id: Option<Uuid>,
warnings: Vec<String>,
}
impl QueryResult {
pub(crate) fn new(
raw_rows: Option<RawMetadataAndRawRows>,
tracing_id: Option<Uuid>,
warnings: Vec<String>,
) -> Self {
Self {
raw_metadata_and_rows: raw_rows,
tracing_id,
warnings,
}
}
// Preferred to implementing Default, because users shouldn't be able to create
// an empty QueryResult.
//
// For now unused, but it will be used once Session's API is migrated
// to the new QueryResult.
#[allow(dead_code)]
pub(crate) fn mock_empty() -> Self {
Self {
raw_metadata_and_rows: None,
tracing_id: None,
warnings: Vec::new(),
}
}
pub(crate) fn raw_metadata_and_rows(&self) -> Option<&RawMetadataAndRawRows> {
self.raw_metadata_and_rows.as_ref()
}
/// Warnings emitted by the database.
#[inline]
pub fn warnings(&self) -> impl Iterator<Item = &str> {
self.warnings.iter().map(String::as_str)
}
/// Tracing ID associated with this CQL request.
#[inline]
pub fn tracing_id(&self) -> Option<Uuid> {
self.tracing_id
}
/// Returns a bool indicating the current response is of Rows type.
#[inline]
pub fn is_rows(&self) -> bool {
self.raw_metadata_and_rows.is_some()
}
/// Returns `Ok` for a request's result that shouldn't contain any rows.\
/// Will return `Ok` for `INSERT` result, but a `SELECT` result, even an empty one, will cause an error.\
/// Opposite of [QueryResult::into_rows_result].
#[inline]
pub fn result_not_rows(&self) -> Result<(), ResultNotRowsError> {
match &self.raw_metadata_and_rows {
Some(_) => Err(ResultNotRowsError),
None => Ok(()),
}
}
/// Transforms itself into the Rows result type to enable deserializing rows.
/// Deserializes result metadata and allocates it.
///
/// Returns an error if the response is not of Rows kind or metadata deserialization failed.
///
/// ```rust
/// # use scylla::transport::query_result::{QueryResult, QueryRowsResult};
/// # fn example(query_result: QueryResult) -> Result<(), Box<dyn std::error::Error>> {
/// let rows_result = query_result.into_rows_result()?;
///
/// let mut rows_iter = rows_result.rows::<(i32, &str)>()?;
/// while let Some((num, text)) = rows_iter.next().transpose()? {
/// // do something with `num` and `text``
/// }
///
/// Ok(())
/// # }
///
/// ```
///
/// If the response is not of Rows kind, the original [`QueryResult`] (self) is
/// returned back to the user in the error type. See [`IntoRowsResultError`] documentation.
///
/// ```rust
/// # use scylla::transport::query_result::{QueryResult, QueryRowsResult, IntoRowsResultError};
/// # fn example(non_rows_query_result: QueryResult) -> Result<(), Box<dyn std::error::Error>> {
/// let err = non_rows_query_result.into_rows_result().unwrap_err();
///
/// match err {
/// IntoRowsResultError::ResultNotRows(query_result) => {
/// // do something with original `query_result`
/// }
/// _ => {
/// // deserialization failed - query result is not recovered
/// }
/// }
///
/// Ok(())
/// # }
/// ```
pub fn into_rows_result(self) -> Result<QueryRowsResult, IntoRowsResultError> {
let Some(raw_metadata_and_rows) = self.raw_metadata_and_rows else {
return Err(IntoRowsResultError::ResultNotRows(self));
};
let tracing_id = self.tracing_id;
let warnings = self.warnings;
let raw_rows_with_metadata = raw_metadata_and_rows.deserialize_metadata()?;
Ok(QueryRowsResult {
raw_rows_with_metadata,
warnings,
tracing_id,
})
}
/// Transforms itself into the legacy result type, by eagerly deserializing rows
/// into the Row type. This is inefficient, and should only be used during transition
/// period to the new API.
#[deprecated(
since = "0.15.0",
note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
pub fn into_legacy_result(self) -> Result<LegacyQueryResult, IntoLegacyQueryResultError> {
if let Some(raw_rows) = self.raw_metadata_and_rows {
let raw_rows_with_metadata = raw_rows.deserialize_metadata()?;
let deserialized_rows = raw_rows_with_metadata
.rows_iter::<Row>()?
.collect::<Result<Vec<_>, DeserializationError>>()?;
let serialized_size = raw_rows_with_metadata.rows_bytes_size();
let metadata = raw_rows_with_metadata.into_metadata();
Ok(LegacyQueryResult {
rows: Some(deserialized_rows),
warnings: self.warnings,
tracing_id: self.tracing_id,
metadata: Some(metadata),
serialized_size,
})
} else {
Ok(LegacyQueryResult {
rows: None,
warnings: self.warnings,
tracing_id: self.tracing_id,
metadata: None,
serialized_size: 0,
})
}
}
}
/// Enables deserialization of rows received from the database in a [`QueryResult`].
///
/// Upon creation, it deserializes result metadata and allocates it.
///
/// This struct provides generic methods which enable typed access to the data,
/// by deserializing rows on the fly to the type provided as a type parameter.
/// Those methods are:
/// - [rows()](QueryRowsResult::rows) - for iterating through rows,
/// - [first_row()](QueryRowsResult::first_row) and
/// [maybe_first_row()](QueryRowsResult::maybe_first_row) -
/// for accessing the first row,
/// - [single_row()](QueryRowsResult::single_row) - for accessing the first row,
/// additionally asserting that it's the only one in the response.
///
/// ```rust
/// # use scylla::transport::query_result::QueryResult;
/// # fn example(query_result: QueryResult) -> Result<(), Box<dyn std::error::Error>> {
/// let rows_result = query_result.into_rows_result()?;
///
/// let mut rows_iter = rows_result.rows::<(i32, &str)>()?;
/// while let Some((num, text)) = rows_iter.next().transpose()? {
/// // do something with `num` and `text``
/// }
///
/// Ok(())
/// # }
///
/// ```
#[derive(Debug)]
pub struct QueryRowsResult {
raw_rows_with_metadata: DeserializedMetadataAndRawRows,
tracing_id: Option<Uuid>,
warnings: Vec<String>,
}
impl QueryRowsResult {
/// Warnings emitted by the database.
#[inline]
pub fn warnings(&self) -> impl Iterator<Item = &str> {
self.warnings.iter().map(String::as_str)
}
/// Tracing ID associated with this CQL request.
#[inline]
pub fn tracing_id(&self) -> Option<Uuid> {
self.tracing_id
}
/// Returns the number of received rows.
#[inline]
pub fn rows_num(&self) -> usize {
self.raw_rows_with_metadata.rows_count()
}
/// Returns the size of the serialized rows.
#[inline]
pub fn rows_bytes_size(&self) -> usize {
self.raw_rows_with_metadata.rows_bytes_size()
}
/// Returns column specifications.
#[inline]
pub fn column_specs(&self) -> ColumnSpecs {
ColumnSpecs::new(self.raw_rows_with_metadata.metadata().col_specs())
}
/// Returns an iterator over the received rows.
///
/// Returns an error if the rows in the response are of incorrect type.
#[inline]
pub fn rows<'frame, R: DeserializeRow<'frame, 'frame>>(
&'frame self,
) -> Result<TypedRowIterator<'frame, 'frame, R>, RowsError> {
self.raw_rows_with_metadata
.rows_iter()
.map_err(RowsError::TypeCheckFailed)
}
/// Returns `Option<R>` containing the first row of the result.
///
/// Fails when the the rows in the response are of incorrect type,
/// or when the deserialization fails.
pub fn maybe_first_row<'frame, R: DeserializeRow<'frame, 'frame>>(
&'frame self,
) -> Result<Option<R>, MaybeFirstRowError> {
self.rows::<R>()
.map_err(|err| match err {
RowsError::TypeCheckFailed(typck_err) => {
MaybeFirstRowError::TypeCheckFailed(typck_err)
}
})?
.next()
.transpose()
.map_err(MaybeFirstRowError::DeserializationFailed)
}
/// Returns the first row of the received result.
///
/// When the first row is not available, returns an error.
/// Fails when the the rows in the response are of incorrect type,
/// or when the deserialization fails.
pub fn first_row<'frame, R: DeserializeRow<'frame, 'frame>>(
&'frame self,
) -> Result<R, FirstRowError> {
match self.maybe_first_row::<R>() {
Ok(Some(row)) => Ok(row),
Ok(None) => Err(FirstRowError::RowsEmpty),
Err(MaybeFirstRowError::TypeCheckFailed(err)) => {
Err(FirstRowError::TypeCheckFailed(err))
}
Err(MaybeFirstRowError::DeserializationFailed(err)) => {
Err(FirstRowError::DeserializationFailed(err))
}
}
}
/// Returns the only received row.
///
/// Fails if the result is anything else than a single row.
/// Fails when the the rows in the response are of incorrect type,
/// or when the deserialization fails.
pub fn single_row<'frame, R: DeserializeRow<'frame, 'frame>>(
&'frame self,
) -> Result<R, SingleRowError> {
match self.rows::<R>() {
Ok(mut rows) => match rows.next() {
Some(Ok(row)) => {
if rows.rows_remaining() != 0 {
return Err(SingleRowError::UnexpectedRowCount(
rows.rows_remaining() + 1,
));
}
Ok(row)
}
Some(Err(err)) => Err(SingleRowError::DeserializationFailed(err)),
None => Err(SingleRowError::UnexpectedRowCount(0)),
},
Err(RowsError::TypeCheckFailed(err)) => Err(SingleRowError::TypeCheckFailed(err)),
}
}
#[cfg(cpp_rust_unstable)]
pub fn into_inner(self) -> (DeserializedMetadataAndRawRows, Option<Uuid>, Vec<String>) {
let Self {
raw_rows_with_metadata,
tracing_id,
warnings,
} = self;
(raw_rows_with_metadata, tracing_id, warnings)
}
}
/// An error returned by [`QueryResult::into_rows_result`]
///
/// The `ResultNotRows` variant contains original [`QueryResult`],
/// which otherwise would be consumed and lost.
#[derive(Debug, Error, Clone)]
pub enum IntoRowsResultError {
/// Result is not of Rows kind
#[error("Result is not of Rows kind")]
ResultNotRows(QueryResult),
// transparent because the underlying error provides enough context.
/// Failed to lazily deserialize result metadata.
#[error(transparent)]
ResultMetadataLazyDeserializationError(#[from] ResultMetadataAndRowsCountParseError),
}
/// An error returned by [`QueryRowsResult::rows`].
#[derive(Debug, Error)]
pub enum RowsError {
/// Type check failed
#[error("Type check failed: {0}")]
TypeCheckFailed(#[from] TypeCheckError),
}
/// An error returned by [`QueryRowsResult::maybe_first_row`].
#[derive(Debug, Error)]
pub enum MaybeFirstRowError {
/// Type check failed
#[error("Type check failed: {0}")]
TypeCheckFailed(#[from] TypeCheckError),
/// Deserialization failed
#[error("Deserialization failed: {0}")]
DeserializationFailed(#[from] DeserializationError),
}
/// An error returned by [`QueryRowsResult::first_row`].
#[derive(Debug, Error)]
pub enum FirstRowError {
/// The request response was of Rows type, but no rows were returned
#[error("The request response was of Rows type, but no rows were returned")]
RowsEmpty,
/// Type check failed
#[error("Type check failed: {0}")]
TypeCheckFailed(#[from] TypeCheckError),
/// Deserialization failed
#[error("Deserialization failed: {0}")]
DeserializationFailed(#[from] DeserializationError),
}
/// An error returned by [`QueryRowsResult::single_row`].
#[derive(Debug, Error, Clone)]
pub enum SingleRowError {
/// Expected one row, but got a different count
#[error("Expected a single row, but got {0} rows")]
UnexpectedRowCount(usize),
/// Type check failed
#[error("Type check failed: {0}")]
TypeCheckFailed(#[from] TypeCheckError),
/// Deserialization failed
#[error("Deserialization failed: {0}")]
DeserializationFailed(#[from] DeserializationError),
}
/// An error returned by [`QueryResult::result_not_rows`].
///
/// It indicates that response to the request was, unexpectedly, of Rows kind.
#[derive(Debug, Error)]
#[error("The request response was, unexpectedly, of Rows kind")]
pub struct ResultNotRowsError;
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use bytes::{Bytes, BytesMut};
use itertools::Itertools as _;
use scylla_cql::frame::response::result::ResultMetadata;
use scylla_cql::frame::types;
use super::*;
const TABLE_SPEC: TableSpec<'static> = TableSpec::borrowed("ks", "tbl");
fn column_spec_infinite_iter() -> impl Iterator<Item = ColumnSpec<'static>> {
(0..).map(|k| {
ColumnSpec::owned(
format!("col_{}", k),
match k % 3 {
0 => ColumnType::Ascii,
1 => ColumnType::Boolean,
2 => ColumnType::Float,
_ => unreachable!(),
},
TABLE_SPEC,
)
})
}
#[test]
fn test_query_result() {
fn serialize_cells(cells: impl IntoIterator<Item = Option<impl AsRef<[u8]>>>) -> Bytes {
let mut bytes = BytesMut::new();
for cell in cells {
types::write_bytes_opt(cell, &mut bytes).unwrap();
}
bytes.freeze()
}
fn sample_result_metadata(cols: usize) -> ResultMetadata<'static> {
ResultMetadata::new_for_test(cols, column_spec_infinite_iter().take(cols).collect())
}
fn sample_raw_rows(cols: usize, rows: usize) -> RawMetadataAndRawRows {
let metadata = sample_result_metadata(cols);
static STRING: &[u8] = "MOCK".as_bytes();
static BOOLEAN: &[u8] = &(true as i8).to_be_bytes();
static FLOAT: &[u8] = &12341_i32.to_be_bytes();
let cells = metadata.col_specs().iter().map(|spec| match spec.typ() {
ColumnType::Ascii => STRING,
ColumnType::Boolean => BOOLEAN,
ColumnType::Float => FLOAT,
_ => unreachable!(),
});
let bytes = serialize_cells(cells.map(Some));
RawMetadataAndRawRows::new_for_test(None, Some(metadata), false, rows, &bytes).unwrap()
}
// Used to trigger DeserializationError.
fn sample_raw_rows_invalid_bytes(cols: usize, rows: usize) -> RawMetadataAndRawRows {
let metadata = sample_result_metadata(cols);
RawMetadataAndRawRows::new_for_test(None, Some(metadata), false, rows, &[]).unwrap()
}
// Check tracing ID
for tracing_id in [None, Some(Uuid::from_u128(0x_feed_dead))] {
for raw_rows in [None, Some(sample_raw_rows(7, 6))] {
let qr = QueryResult::new(raw_rows, tracing_id, vec![]);
assert_eq!(qr.tracing_id(), tracing_id);
}
}
// Check warnings
for raw_rows in [None, Some(sample_raw_rows(7, 6))] {
let warnings = &["Ooops", "Meltdown..."];
let qr = QueryResult::new(
raw_rows,
None,
warnings.iter().copied().map(String::from).collect(),
);
assert_eq!(qr.warnings().collect_vec(), warnings);
}
// Check col specs
{
// Not RESULT::Rows response -> no column specs
{
let rqr = QueryResult::new(None, None, Vec::new());
let qr = rqr.into_rows_result();
assert_matches!(qr, Err(IntoRowsResultError::ResultNotRows(_)));
}
// RESULT::Rows response -> some column specs
{
let n = 5;
let metadata = sample_result_metadata(n);
let rr = RawMetadataAndRawRows::new_for_test(None, Some(metadata), false, 0, &[])
.unwrap();
let rqr = QueryResult::new(Some(rr), None, Vec::new());
let qr = rqr.into_rows_result().unwrap();
let column_specs = qr.column_specs();
assert_eq!(column_specs.len(), n);
// By index
{
for (i, expected_col_spec) in column_spec_infinite_iter().enumerate().take(n) {
let expected_view =
ColumnSpecView::new_from_column_spec(&expected_col_spec);
assert_eq!(column_specs.get_by_index(i), Some(expected_view));
}
assert_matches!(column_specs.get_by_index(n), None);
}
// By name
{
for (idx, expected_col_spec) in column_spec_infinite_iter().enumerate().take(n)
{
let name = expected_col_spec.name();
let expected_view =
ColumnSpecView::new_from_column_spec(&expected_col_spec);
assert_eq!(column_specs.get_by_name(name), Some((idx, expected_view)));
}
assert_matches!(column_specs.get_by_name("ala ma kota"), None);
}
// By iter
{
for (got_view, expected_col_spec) in
column_specs.iter().zip(column_spec_infinite_iter())
{
let expected_view =
ColumnSpecView::new_from_column_spec(&expected_col_spec);
assert_eq!(got_view, expected_view);
}
}
}
}
// rows(), maybe_rows(), result_not_rows(), first_row(), maybe_first_row(), single_row()
// All errors are checked.
{
// Not RESULT::Rows
{
let rqr = QueryResult::new(None, None, Vec::new());
let qr = rqr.into_rows_result();
assert_matches!(qr, Err(IntoRowsResultError::ResultNotRows(_)));
}
// RESULT::Rows with 0 rows
{
let rr = sample_raw_rows(1, 0);
let rqr = QueryResult::new(Some(rr), None, Vec::new());
assert_matches!(rqr.result_not_rows(), Err(ResultNotRowsError));
let qr = rqr.into_rows_result().unwrap();
// Type check error
{
assert_matches!(qr.rows::<(i32,)>(), Err(RowsError::TypeCheckFailed(_)));
assert_matches!(
qr.first_row::<(i32,)>(),
Err(FirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.maybe_first_row::<(i32,)>(),
Err(MaybeFirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.single_row::<(i32,)>(),
Err(SingleRowError::TypeCheckFailed(_))
);
}
// Correct type
{
assert_matches!(qr.rows::<(&str,)>(), Ok(_));
assert_matches!(qr.first_row::<(&str,)>(), Err(FirstRowError::RowsEmpty));
assert_matches!(qr.maybe_first_row::<(&str,)>(), Ok(None));
assert_matches!(
qr.single_row::<(&str,)>(),
Err(SingleRowError::UnexpectedRowCount(0))
);
}
}
// RESULT::Rows with 1 row
{
let rr_good_data = sample_raw_rows(2, 1);
let rr_bad_data = sample_raw_rows_invalid_bytes(2, 1);
let rqr_good_data = QueryResult::new(Some(rr_good_data), None, Vec::new());
let rqr_bad_data = QueryResult::new(Some(rr_bad_data), None, Vec::new());
for rqr in [&rqr_good_data, &rqr_bad_data] {
assert_matches!(rqr.result_not_rows(), Err(ResultNotRowsError));
}
let qr_good_data = rqr_good_data.into_rows_result().unwrap();
let qr_bad_data = rqr_bad_data.into_rows_result().unwrap();
for qr in [&qr_good_data, &qr_bad_data] {
// Type check error
{
assert_matches!(
qr.rows::<(i32, i32)>(),
Err(RowsError::TypeCheckFailed(_))
);
assert_matches!(
qr.first_row::<(i32, i32)>(),
Err(FirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.maybe_first_row::<(i32, i32)>(),
Err(MaybeFirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.single_row::<(i32, i32)>(),
Err(SingleRowError::TypeCheckFailed(_))
);
}
}
// Correct type
{
assert_matches!(qr_good_data.rows::<(&str, bool)>(), Ok(_));
assert_matches!(qr_bad_data.rows::<(&str, bool)>(), Ok(_));
assert_matches!(qr_good_data.first_row::<(&str, bool)>(), Ok(_));
assert_matches!(
qr_bad_data.first_row::<(&str, bool)>(),
Err(FirstRowError::DeserializationFailed(_))
);
assert_matches!(qr_good_data.maybe_first_row::<(&str, bool)>(), Ok(_));
assert_matches!(
qr_bad_data.maybe_first_row::<(&str, bool)>(),
Err(MaybeFirstRowError::DeserializationFailed(_))
);
assert_matches!(qr_good_data.single_row::<(&str, bool)>(), Ok(_));
assert_matches!(
qr_bad_data.single_row::<(&str, bool)>(),
Err(SingleRowError::DeserializationFailed(_))
);
}
}
// RESULT::Rows with 2 rows
{
let rr = sample_raw_rows(2, 2);
let rqr = QueryResult::new(Some(rr), None, Vec::new());
assert_matches!(rqr.result_not_rows(), Err(ResultNotRowsError));
let qr = rqr.into_rows_result().unwrap();
// Type check error
{
assert_matches!(qr.rows::<(i32, i32)>(), Err(RowsError::TypeCheckFailed(_)));
assert_matches!(
qr.first_row::<(i32, i32)>(),
Err(FirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.maybe_first_row::<(i32, i32)>(),
Err(MaybeFirstRowError::TypeCheckFailed(_))
);
assert_matches!(
qr.single_row::<(i32, i32)>(),
Err(SingleRowError::TypeCheckFailed(_))
);
}
// Correct type
{
assert_matches!(qr.rows::<(&str, bool)>(), Ok(_));
assert_matches!(qr.first_row::<(&str, bool)>(), Ok(_));
assert_matches!(qr.maybe_first_row::<(&str, bool)>(), Ok(_));
assert_matches!(
qr.single_row::<(&str, bool)>(),
Err(SingleRowError::UnexpectedRowCount(2))
);
}
}
}
}
#[test]
fn test_query_result_returns_self_if_not_rows() {
// Check tracing ID
for tracing_id in [None, Some(Uuid::from_u128(0x_feed_dead))] {
let qr = QueryResult::new(None, tracing_id, vec![]);
let err = qr.into_rows_result().unwrap_err();
match err {
IntoRowsResultError::ResultNotRows(query_result) => {
assert_eq!(query_result.tracing_id, tracing_id)
}
IntoRowsResultError::ResultMetadataLazyDeserializationError(_) => {
panic!("Expected ResultNotRows error")
}
}
}
// Check warnings
{
let warnings = &["Ooops", "Meltdown..."];
let qr = QueryResult::new(
None,
None,
warnings.iter().copied().map(String::from).collect(),
);
let err = qr.into_rows_result().unwrap_err();
match err {
IntoRowsResultError::ResultNotRows(query_result) => {
assert_eq!(query_result.warnings().collect_vec(), warnings)
}
IntoRowsResultError::ResultMetadataLazyDeserializationError(_) => {
panic!("Expected ResultNotRows error")
}
}
}
}
}