Skip to main content

google_cloud_spanner/
from_row.rs

1// Copyright 2026 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::Error;
16use crate::Result;
17use crate::from_value::FromValue;
18use crate::row::Row;
19
20/// Converts a query [`Row`] into a Rust data structure.
21///
22/// # Example
23///
24/// ```
25/// use google_cloud_spanner::Error;
26/// use google_cloud_spanner::result::{FromRow, Row};
27///
28/// struct UserRecord {
29///     id: String,
30///     age: i64,
31///     nickname: Option<String>,
32/// }
33///
34/// impl FromRow for UserRecord {
35///     fn from_row(mut row: Row) -> Result<Self, Error> {
36///         Ok(Self {
37///             id: row.take("id")?,
38///             age: row.take("age")?,
39///             nickname: row.take("nickname")?,
40///         })
41///     }
42/// }
43///
44/// // Implementing `TryFrom<Row>` is optional, and enables standard `row.try_into()` conversion:
45/// impl TryFrom<Row> for UserRecord {
46///     type Error = Error;
47///
48///     fn try_from(row: Row) -> Result<Self, Self::Error> {
49///         Self::from_row(row)
50///     }
51/// }
52///
53/// # fn run(row: Row) -> Result<(), Error> {
54/// // A row can be converted into the record using `Row::into_record`:
55/// let user: UserRecord = row.into_record()?;
56/// println!("User: {}, age: {}", user.id, user.age);
57/// # Ok(())
58/// # }
59/// ```
60///
61/// This trait is designed for zero-copy row consumption. The implementing method
62/// takes ownership of [`Row`], allowing callers to move heap-allocated types
63/// (such as [`String`], `Vec<T>`, and `Vec<u8>`) using [`Row::take`]
64/// without cloning.
65///
66/// `FromRow` is also implemented for [`Row`] (identity) and standard tuples up to
67/// 12 elements (positional indexing). Single-column scalar queries (such as
68/// `SELECT COUNT(*)`) can be read using a 1-tuple `(T,)` (e.g. `(i64,)`).
69///
70/// # Example: Tuples and Scalar Queries
71///
72/// Standard tuples up to 12 elements implement [`FromRow`] using positional indexing:
73///
74/// ```
75/// # use google_cloud_spanner::Error;
76/// # use google_cloud_spanner::result::Row;
77/// # fn run(row: Row) -> Result<(), Error> {
78/// // Multi-column positional query:
79/// let (name, age): (String, i64) = row.into_record()?;
80/// println!("Name: {name}, Age: {age}");
81/// # Ok(())
82/// # }
83/// # fn scalar(row: Row) -> Result<(), Error> {
84/// // Single-column scalar query (e.g. `SELECT COUNT(*)`):
85/// let (count,): (i64,) = row.into_record()?;
86/// println!("Count: {count}");
87/// # Ok(())
88/// # }
89/// ```
90pub trait FromRow: Sized {
91    /// Converts a Spanner [`Row`] into the target type.
92    ///
93    /// # Errors
94    ///
95    /// Returns an [`Error`] if:
96    /// - A required column name or positional index does not exist in the row.
97    /// - A column value cannot be converted into the target type.
98    /// - A column is `NULL` but the target field is not an [`Option`].
99    fn from_row(row: Row) -> Result<Self>;
100}
101
102impl FromRow for Row {
103    fn from_row(row: Row) -> Result<Self> {
104        Ok(row)
105    }
106}
107
108impl FromRow for () {
109    fn from_row(_row: Row) -> Result<Self> {
110        Ok(())
111    }
112}
113
114impl TryFrom<Row> for () {
115    type Error = Error;
116
117    fn try_from(row: Row) -> Result<Self> {
118        Self::from_row(row)
119    }
120}
121
122// Implements `FromRow` and `TryFrom<Row>` for standard tuples from 1 to 12 elements.
123// Each tuple element is extracted positionally from the row using `row.take(index)`.
124macro_rules! impl_from_row_for_tuple {
125    ( $( $idx:tt => $T:ident ),+ ) => {
126        impl<$($T),+> FromRow for ($($T,)+)
127        where
128            $($T: FromValue,)+
129        {
130            fn from_row(mut row: Row) -> Result<Self> {
131                Ok((
132                    $(
133                        row.take($idx as usize)?,
134                    )+
135                ))
136            }
137        }
138
139        impl<$($T),+> TryFrom<Row> for ($($T,)+)
140        where
141            $($T: FromValue,)+
142        {
143            type Error = Error;
144
145            fn try_from(row: Row) -> Result<Self> {
146                Self::from_row(row)
147            }
148        }
149    };
150}
151
152impl_from_row_for_tuple!(0 => T0);
153impl_from_row_for_tuple!(0 => T0, 1 => T1);
154impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2);
155impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3);
156impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4);
157impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5);
158impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6);
159impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7);
160impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8);
161impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9);
162impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9, 10 => T10);
163impl_from_row_for_tuple!(0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9, 10 => T10, 11 => T11);
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::Error;
169    use crate::error::RowError;
170    use crate::result_set_metadata::ResultSetMetadata;
171    use crate::to_value::ToValue;
172    use crate::types::{self, Type};
173    use crate::value::Value;
174    use std::collections::BTreeMap;
175    use std::fmt::Debug;
176    use std::sync::Arc;
177    use wkt::Timestamp;
178
179    #[derive(Debug, PartialEq)]
180    struct UserRecord {
181        id: String,
182        age: i64,
183        active: bool,
184        nickname: Option<String>,
185        created_at: Timestamp,
186    }
187
188    impl FromRow for UserRecord {
189        fn from_row(mut row: Row) -> Result<Self> {
190            Ok(Self {
191                id: row.take("id")?,
192                age: row.take("age")?,
193                active: row.take("active")?,
194                nickname: row.take("nickname")?,
195                created_at: row.take("created_at")?,
196            })
197        }
198    }
199
200    impl TryFrom<Row> for UserRecord {
201        type Error = Error;
202
203        fn try_from(row: Row) -> Result<Self> {
204            Self::from_row(row)
205        }
206    }
207
208    #[derive(Debug, PartialEq)]
209    struct Coordinates(f64, f64);
210
211    impl FromRow for Coordinates {
212        fn from_row(mut row: Row) -> Result<Self> {
213            Ok(Self(row.take(0usize)?, row.take(1usize)?))
214        }
215    }
216
217    impl TryFrom<Row> for Coordinates {
218        type Error = Error;
219
220        fn try_from(row: Row) -> Result<Self> {
221            Self::from_row(row)
222        }
223    }
224
225    fn create_row(columns: Vec<(&str, Type, Value)>) -> Row {
226        let mut names = Vec::with_capacity(columns.len());
227        let mut column_types = Vec::with_capacity(columns.len());
228        let mut values = Vec::with_capacity(columns.len());
229
230        for (name, column_type, value) in columns {
231            names.push(name.to_string());
232            column_types.push(column_type);
233            values.push(value);
234        }
235
236        Row {
237            values,
238            metadata: ResultSetMetadata {
239                column_names: Arc::new(names),
240                column_types: Arc::new(column_types),
241                undeclared_parameters: Arc::new(BTreeMap::new()),
242            },
243        }
244    }
245
246    #[test]
247    fn traits() {
248        static_assertions::assert_impl_all!(UserRecord: FromRow, TryFrom<Row>, Debug, PartialEq, Send, Sync);
249        static_assertions::assert_impl_all!(Coordinates: FromRow, TryFrom<Row>, Debug, PartialEq, Send, Sync);
250        static_assertions::assert_impl_all!(Row: FromRow, TryFrom<Row>);
251        static_assertions::assert_impl_all!((): FromRow, TryFrom<Row>);
252        static_assertions::assert_impl_all!((String,): FromRow, TryFrom<Row>);
253        static_assertions::assert_impl_all!((String, i64): FromRow, TryFrom<Row>);
254        static_assertions::assert_impl_all!((String, i64, bool, f64): FromRow, TryFrom<Row>);
255    }
256
257    #[test]
258    fn row_identity() -> Result<()> {
259        let row = create_row(vec![(
260            "name",
261            types::string(),
262            "alice".to_string().to_value(),
263        )]);
264        let extracted_row = Row::from_row(row.clone())?;
265        assert_eq!(
266            extracted_row, row,
267            "Row::from_row must return the row unmodified"
268        );
269        Ok(())
270    }
271
272    #[test]
273    fn unit_tuple() -> Result<()> {
274        let row = create_row(vec![("col", types::int64(), 100_i64.to_value())]);
275        assert_eq!(
276            <()>::from_row(row.clone())?,
277            (),
278            "()::from_row must return ()"
279        );
280
281        let unit_try_from: Result<()> = row.try_into();
282        assert!(unit_try_from.is_ok(), "row.try_into() for () must succeed");
283        Ok(())
284    }
285
286    #[test]
287    fn tuple_1_from_row() -> Result<()> {
288        let row = create_row(vec![(
289            "name",
290            types::string(),
291            "test-name".to_string().to_value(),
292        )]);
293        let (name,) = <(String,)>::from_row(row)?;
294        assert_eq!(name, "test-name", "1-tuple must extract first column");
295        Ok(())
296    }
297
298    #[test]
299    fn tuple_2_from_row() -> Result<()> {
300        let row = create_row(vec![
301            ("first", types::string(), "val1".to_string().to_value()),
302            ("second", types::int64(), 42_i64.to_value()),
303        ]);
304        let (first, second) = <(String, i64)>::from_row(row)?;
305        assert_eq!(first, "val1", "first element must match index 0");
306        assert_eq!(second, 42, "second element must match index 1");
307        Ok(())
308    }
309
310    #[test]
311    fn tuple_3_with_option() -> Result<()> {
312        let row = create_row(vec![
313            ("str", types::string(), "hello".to_string().to_value()),
314            ("opt", types::int64(), Value::null()),
315            ("flag", types::bool(), true.to_value()),
316        ]);
317        let (text, maybe_number, flag) = <(String, Option<i64>, bool)>::from_row(row)?;
318        assert_eq!(text, "hello", "text column must match");
319        assert_eq!(
320            maybe_number, None,
321            "null column must deserialize to None in tuple"
322        );
323        assert!(flag, "boolean flag must be true");
324        Ok(())
325    }
326
327    #[test]
328    fn tuple_12_from_row() -> Result<()> {
329        let row = create_row(vec![
330            ("c0", types::int64(), 0_i64.to_value()),
331            ("c1", types::int64(), 1_i64.to_value()),
332            ("c2", types::int64(), 2_i64.to_value()),
333            ("c3", types::int64(), 3_i64.to_value()),
334            ("c4", types::int64(), 4_i64.to_value()),
335            ("c5", types::int64(), 5_i64.to_value()),
336            ("c6", types::int64(), 6_i64.to_value()),
337            ("c7", types::int64(), 7_i64.to_value()),
338            ("c8", types::int64(), 8_i64.to_value()),
339            ("c9", types::int64(), 9_i64.to_value()),
340            ("c10", types::int64(), 10_i64.to_value()),
341            ("c11", types::int64(), 11_i64.to_value()),
342        ]);
343        type TwelveTuple = (i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64);
344        let result = TwelveTuple::from_row(row)?;
345        assert_eq!(
346            result,
347            (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
348            "12-element tuple must extract all 12 positional columns"
349        );
350        Ok(())
351    }
352
353    #[test]
354    fn tuple_try_from() -> Result<()> {
355        let row = create_row(vec![
356            ("first", types::string(), "alice".to_string().to_value()),
357            ("second", types::int64(), 100_i64.to_value()),
358        ]);
359        let (first, second): (String, i64) = row.try_into()?;
360        assert_eq!(first, "alice", "first element must match via TryInto");
361        assert_eq!(second, 100, "second element must match via TryInto");
362        Ok(())
363    }
364
365    #[test]
366    fn tuple_index_out_of_range() {
367        let row = create_row(vec![(
368            "only_one",
369            types::string(),
370            "val".to_string().to_value(),
371        )]);
372        let error = <(String, i64)>::from_row(row)
373            .expect_err("tuple extraction must fail if row has fewer columns than tuple elements");
374        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
375        match row_error {
376            RowError::IndexOutOfRange { index, len } => {
377                assert_eq!(*index, 1, "expected index 1 to be out of range");
378                assert_eq!(*len, 1, "expected row length to be 1");
379            }
380            other => panic!("expected RowError::IndexOutOfRange, got: {other:?}"),
381        }
382    }
383
384    #[test]
385    fn tuple_type_mismatch() {
386        let row = create_row(vec![
387            ("str", types::string(), "abc".to_string().to_value()),
388            (
389                "not_int",
390                types::string(),
391                "not-a-number".to_string().to_value(),
392            ),
393        ]);
394        let error = <(String, i64)>::from_row(row)
395            .expect_err("tuple extraction must fail when column type mismatches");
396        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
397        match row_error {
398            RowError::TypeConversion { column, .. } => {
399                assert_eq!(
400                    column, "not_int",
401                    "expected conversion error on column 'not_int'"
402                );
403            }
404            other => panic!("expected RowError::TypeConversion, got: {other:?}"),
405        }
406    }
407
408    #[test]
409    fn manual_struct_from_row() -> Result<()> {
410        let timestamp = Timestamp::clamp(1_700_000_000, 0);
411        let row = create_row(vec![
412            ("id", types::string(), "user-123".to_string().to_value()),
413            ("age", types::int64(), 32_i64.to_value()),
414            ("active", types::bool(), true.to_value()),
415            ("nickname", types::string(), "ace".to_string().to_value()),
416            ("created_at", types::timestamp(), timestamp.to_value()),
417        ]);
418
419        let record = UserRecord::from_row(row)?;
420        assert_eq!(
421            record,
422            UserRecord {
423                id: "user-123".to_string(),
424                age: 32,
425                active: true,
426                nickname: Some("ace".to_string()),
427                created_at: timestamp,
428            },
429            "UserRecord parsed via FromRow::from_row must match expected values"
430        );
431        Ok(())
432    }
433
434    #[test]
435    fn manual_struct_with_null_optional() -> Result<()> {
436        let timestamp = Timestamp::clamp(1_700_000_000, 0);
437        let row = create_row(vec![
438            ("id", types::string(), "user-456".to_string().to_value()),
439            ("age", types::int64(), 28_i64.to_value()),
440            ("active", types::bool(), false.to_value()),
441            ("nickname", types::string(), Value::null()),
442            ("created_at", types::timestamp(), timestamp.to_value()),
443        ]);
444
445        let record = UserRecord::from_row(row)?;
446        assert_eq!(
447            record.nickname, None,
448            "null column must deserialize to None for Option field"
449        );
450        assert_eq!(record.id, "user-456", "id must match");
451        Ok(())
452    }
453
454    #[test]
455    fn manual_struct_try_from() -> Result<()> {
456        let timestamp = Timestamp::clamp(1_700_000_000, 0);
457        let row = create_row(vec![
458            ("id", types::string(), "user-789".to_string().to_value()),
459            ("age", types::int64(), 45_i64.to_value()),
460            ("active", types::bool(), true.to_value()),
461            ("nickname", types::string(), Value::null()),
462            ("created_at", types::timestamp(), timestamp.to_value()),
463        ]);
464
465        let record: UserRecord = row.try_into()?;
466        assert_eq!(record.id, "user-789", "id must match via TryInto");
467        assert_eq!(record.age, 45, "age must match via TryInto");
468        assert!(record.active, "active must be true via TryInto");
469        assert_eq!(record.nickname, None, "nickname must be None via TryInto");
470        Ok(())
471    }
472
473    #[test]
474    fn tuple_struct_from_row() -> Result<()> {
475        let row = create_row(vec![
476            ("latitude", types::float64(), 37.7749_f64.to_value()),
477            ("longitude", types::float64(), (-122.4194_f64).to_value()),
478        ]);
479
480        let coordinates = Coordinates::from_row(row)?;
481        assert_eq!(
482            coordinates,
483            Coordinates(37.7749, -122.4194),
484            "Coordinates parsed positionally via FromRow must match expected values"
485        );
486        Ok(())
487    }
488
489    #[test]
490    fn tuple_struct_try_from() -> Result<()> {
491        let row = create_row(vec![
492            ("latitude", types::float64(), 37.7749_f64.to_value()),
493            ("longitude", types::float64(), (-122.4194_f64).to_value()),
494        ]);
495
496        let coordinates: Coordinates = row.try_into()?;
497        assert_eq!(
498            coordinates,
499            Coordinates(37.7749, -122.4194),
500            "Coordinates parsed positionally via TryInto must match expected values"
501        );
502        Ok(())
503    }
504
505    #[test]
506    fn manual_struct_out_of_order_columns() -> Result<()> {
507        let timestamp = Timestamp::clamp(1_700_000_000, 0);
508        let row = create_row(vec![
509            ("nickname", types::string(), "ace".to_string().to_value()),
510            ("age", types::int64(), 32_i64.to_value()),
511            ("active", types::bool(), true.to_value()),
512            ("id", types::string(), "user-123".to_string().to_value()),
513            ("created_at", types::timestamp(), timestamp.to_value()),
514        ]);
515
516        let record = UserRecord::from_row(row)?;
517        assert_eq!(
518            record,
519            UserRecord {
520                id: "user-123".to_string(),
521                age: 32,
522                active: true,
523                nickname: Some("ace".to_string()),
524                created_at: timestamp,
525            },
526            "UserRecord parsed via FromRow must resolve columns by name regardless of order"
527        );
528        Ok(())
529    }
530
531    #[test]
532    fn missing_column_error() {
533        let timestamp = Timestamp::clamp(1_700_000_000, 0);
534        let row = create_row(vec![
535            ("id", types::string(), "user-123".to_string().to_value()),
536            ("age", types::int64(), 32_i64.to_value()),
537            // "active" column is intentionally omitted
538            ("nickname", types::string(), "ace".to_string().to_value()),
539            ("created_at", types::timestamp(), timestamp.to_value()),
540        ]);
541
542        let error = UserRecord::from_row(row)
543            .expect_err("from_row must fail when a required column is missing");
544        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
545        match row_error {
546            RowError::ColumnNotFound(column) => {
547                assert_eq!(
548                    column, "active",
549                    "expected missing column name to be 'active'"
550                );
551            }
552            other => panic!("expected RowError::ColumnNotFound, got: {other:?}"),
553        }
554    }
555
556    #[test]
557    fn type_mismatch_error() {
558        let timestamp = Timestamp::clamp(1_700_000_000, 0);
559        let row = create_row(vec![
560            ("id", types::string(), "user-123".to_string().to_value()),
561            // "age" is given as STRING instead of INT64
562            (
563                "age",
564                types::string(),
565                "not-a-number".to_string().to_value(),
566            ),
567            ("active", types::bool(), true.to_value()),
568            ("nickname", types::string(), "ace".to_string().to_value()),
569            ("created_at", types::timestamp(), timestamp.to_value()),
570        ]);
571
572        let error =
573            UserRecord::from_row(row).expect_err("from_row must fail when column type mismatches");
574        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
575        match row_error {
576            RowError::TypeConversion { column, .. } => {
577                assert_eq!(column, "age", "expected conversion error on column 'age'");
578            }
579            other => panic!("expected RowError::TypeConversion, got: {other:?}"),
580        }
581    }
582
583    #[test]
584    fn null_for_non_optional_field_error() {
585        let timestamp = Timestamp::clamp(1_700_000_000, 0);
586        let row = create_row(vec![
587            // "id" is NULL but UserRecord::id is String (not Option<String>)
588            ("id", types::string(), Value::null()),
589            ("age", types::int64(), 32_i64.to_value()),
590            ("active", types::bool(), true.to_value()),
591            ("nickname", types::string(), "ace".to_string().to_value()),
592            ("created_at", types::timestamp(), timestamp.to_value()),
593        ]);
594
595        let error = UserRecord::from_row(row)
596            .expect_err("from_row must fail when non-optional column is null");
597        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
598        match row_error {
599            RowError::TypeConversion { column, .. } => {
600                assert_eq!(column, "id", "expected conversion error on column 'id'");
601            }
602            other => panic!("expected RowError::TypeConversion, got: {other:?}"),
603        }
604    }
605
606    #[test]
607    fn positional_index_out_of_range_error() {
608        // Only 1 column provided, but Coordinates expects 2 positional columns (0 and 1)
609        let row = create_row(vec![("latitude", types::float64(), 37.7749_f64.to_value())]);
610
611        let error = Coordinates::from_row(row)
612            .expect_err("from_row must fail when positional index is out of bounds");
613        let row_error = RowError::extract(&error).expect("error chain must contain a RowError");
614        match row_error {
615            RowError::IndexOutOfRange { index, len } => {
616                assert_eq!(*index, 1, "expected index 1 to be out of range");
617                assert_eq!(*len, 1, "expected row length to be 1");
618            }
619            other => panic!("expected RowError::IndexOutOfRange, got: {other:?}"),
620        }
621    }
622
623    #[test]
624    fn struct_ignores_extra_columns() -> Result<()> {
625        let timestamp = Timestamp::clamp(1_700_000_000, 0);
626        let row = create_row(vec![
627            ("id", types::string(), "user-123".to_string().to_value()),
628            ("age", types::int64(), 32_i64.to_value()),
629            ("active", types::bool(), true.to_value()),
630            ("nickname", types::string(), "ace".to_string().to_value()),
631            ("created_at", types::timestamp(), timestamp.to_value()),
632            (
633                "extra_column_1",
634                types::string(),
635                "unused".to_string().to_value(),
636            ),
637            ("extra_column_2", types::int64(), 999_i64.to_value()),
638        ]);
639
640        let record = UserRecord::from_row(row)?;
641        assert_eq!(
642            record.id, "user-123",
643            "id should match despite extra columns"
644        );
645        assert_eq!(record.age, 32, "age should match despite extra columns");
646        assert!(record.active, "active should match despite extra columns");
647        Ok(())
648    }
649}