Skip to main content

google_cloud_spanner/
from_value.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;
16pub use crate::types::{Type, TypeCode};
17use crate::value::Kind;
18use crate::value::SPANNER_DATE_FORMAT;
19use crate::value::Value;
20use base64::Engine;
21use base64::prelude::BASE64_STANDARD;
22use bytes::Bytes;
23use google_cloud_type::model::Date;
24use prost_types::ListValue as ProtoListValue;
25use prost_types::value::Kind as ProtoKind;
26use rust_decimal::Decimal;
27use serde_json::{Map as JsonMap, Number as JsonNumber, Value as JsonValue};
28use std::error::Error as StdError;
29use std::str::FromStr;
30use std::sync::Arc;
31use std::time::SystemTime;
32use time::Date as TimeDate;
33#[cfg(feature = "unstable-time")]
34use time::OffsetDateTime;
35#[cfg(feature = "unstable-time")]
36use time::format_description::well_known::Rfc3339;
37use uuid::Uuid;
38use wkt::Timestamp;
39
40/// Represent failures in converting a Spanner Value to a Rust type.
41///
42/// # Example
43/// ```
44/// # use google_cloud_spanner::error::ConvertError;
45/// # use google_cloud_spanner::types;
46/// # use google_cloud_spanner::value::{FromValue, Value};
47/// let value = Value::from("not-a-bool");
48/// let string_type = types::string();
49/// let error = bool::from_value(&value, &string_type).expect_err("string is not a bool");
50/// match error {
51///     ConvertError::TypeMismatch { want, got, .. } => {
52///         println!("Type mismatch: expected {want:?}, got {got:?}");
53///     }
54///     _ => {}
55/// }
56/// ```
57#[derive(thiserror::Error, Clone, Debug)]
58#[non_exhaustive]
59pub enum ConvertError {
60    /// The value kind is not as expected.
61    #[error("expected {want:?}, got {got:?}")]
62    #[non_exhaustive]
63    KindMismatch {
64        /// The expected Spanner value kind.
65        want: Kind,
66        /// The actual Spanner value kind.
67        got: Kind,
68    },
69
70    /// The column type does not match the requested type.
71    #[error("type mismatch, expected {want:?}, got {got:?}")]
72    #[non_exhaustive]
73    TypeMismatch {
74        /// The expected Spanner type code.
75        want: TypeCode,
76        /// The actual Spanner type code.
77        got: TypeCode,
78    },
79
80    /// The value is null, but the target type does not support nulls.
81    #[error("expected non-null value, got null")]
82    NotNull,
83
84    /// There was a problem during conversion.
85    #[error("cannot convert value, source={0}")]
86    Convert(#[source] SharedError),
87}
88
89impl ConvertError {
90    /// Creates a [`ConvertError::Convert`] wrapping a custom error.
91    ///
92    /// This constructor is useful when implementing [`FromValue`] for custom domain or wrapper types.
93    ///
94    /// # Example: Custom ID type
95    ///
96    /// ```
97    /// use google_cloud_spanner::types::Type;
98    /// use google_cloud_spanner::value::{ConvertError, FromValue, Value};
99    ///
100    /// #[derive(Debug, PartialEq)]
101    /// struct CustomerId(u32);
102    ///
103    /// impl FromValue for CustomerId {
104    ///     fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
105    ///         let raw_int = i64::from_value(value, spanner_type)?;
106    ///         let parsed = u32::try_from(raw_int).map_err(ConvertError::custom)?;
107    ///         Ok(CustomerId(parsed))
108    ///     }
109    /// }
110    /// ```
111    pub fn custom<E>(error: E) -> Self
112    where
113        E: StdError + Send + Sync + 'static,
114    {
115        Self::Convert(Arc::new(error))
116    }
117
118    /// Creates a [`ConvertError::Convert`] from a message string.
119    ///
120    /// This constructor is useful when implementing [`FromValue`] for custom validation,
121    /// domain enums, or parsing formatted strings.
122    ///
123    /// # Example: Validating numeric values
124    ///
125    /// A custom wrapper type can deserialize a Spanner `NUMERIC` column as a [`String`]
126    /// and apply custom business validation, returning [`ConvertError::message`] on failure:
127    ///
128    /// ```
129    /// use google_cloud_spanner::types::{Type, TypeCode};
130    /// use google_cloud_spanner::value::{ConvertError, FromValue, Value};
131    ///
132    /// /// A wrapper type that extracts a Spanner `NUMERIC` column, ensuring it is non-negative.
133    /// #[derive(Debug, PartialEq)]
134    /// struct PositiveNumeric(pub String);
135    ///
136    /// impl FromValue for PositiveNumeric {
137    ///     fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
138    ///         if spanner_type.code() != TypeCode::Numeric {
139    ///             return Err(ConvertError::type_mismatch(
140    ///                 TypeCode::Numeric,
141    ///                 spanner_type.code(),
142    ///             ));
143    ///         }
144    ///         let s = String::from_value(value, spanner_type)?;
145    ///         if s.starts_with('-') {
146    ///             return Err(ConvertError::message("numeric value must be non-negative"));
147    ///         }
148    ///         Ok(PositiveNumeric(s))
149    ///     }
150    /// }
151    /// ```
152    ///
153    /// # Example: Custom enum parsing
154    ///
155    /// ```
156    /// use google_cloud_spanner::types::Type;
157    /// use google_cloud_spanner::value::{ConvertError, FromValue, Value};
158    ///
159    /// #[derive(Debug, PartialEq)]
160    /// enum OrderStatus {
161    ///     Pending,
162    ///     Shipped,
163    /// }
164    ///
165    /// impl FromValue for OrderStatus {
166    ///     fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
167    ///         let raw_status = String::from_value(value, spanner_type)?;
168    ///         match raw_status.as_str() {
169    ///             "PENDING" => Ok(OrderStatus::Pending),
170    ///             "SHIPPED" => Ok(OrderStatus::Shipped),
171    ///             other => Err(ConvertError::message(format!("unknown order status: '{other}'"))),
172    ///         }
173    ///     }
174    /// }
175    /// ```
176    pub fn message(message: impl Into<String>) -> Self {
177        Self::Convert(Arc::new(MessageError(message.into())))
178    }
179
180    /// Creates a [`ConvertError::KindMismatch`] for the expected and actual value kinds.
181    ///
182    /// # Example
183    /// ```
184    /// use google_cloud_spanner::error::ConvertError;
185    /// use google_cloud_spanner::value::Kind;
186    ///
187    /// let error = ConvertError::kind_mismatch(Kind::String, Kind::Bool);
188    /// assert_eq!(error.to_string(), "expected String, got Bool");
189    /// ```
190    pub fn kind_mismatch(want: Kind, got: Kind) -> Self {
191        Self::KindMismatch { want, got }
192    }
193
194    /// Creates a [`ConvertError::TypeMismatch`] for the expected and actual type codes.
195    ///
196    /// This constructor is preferred when validating column schema types in custom
197    /// [`FromValue`] implementations.
198    ///
199    /// # Example
200    /// ```
201    /// use google_cloud_spanner::error::ConvertError;
202    /// use google_cloud_spanner::types::TypeCode;
203    ///
204    /// let error = ConvertError::type_mismatch(TypeCode::Int64, TypeCode::String);
205    /// assert_eq!(error.to_string(), "type mismatch, expected Int64, got String");
206    /// ```
207    pub fn type_mismatch(want: TypeCode, got: TypeCode) -> Self {
208        Self::TypeMismatch { want, got }
209    }
210
211    /// Extracts a `ConvertError` from a [`google_cloud_spanner::Error`][Error], if present.
212    ///
213    /// # Example
214    /// ```
215    /// # use google_cloud_spanner::client::Spanner;
216    /// # use google_cloud_spanner::error::ConvertError;
217    /// # use google_cloud_spanner::statement::Statement;
218    /// # async fn example(client: Spanner) -> Result<(), google_cloud_spanner::Error> {
219    /// let db_client = client.database_client("projects/p/instances/i/databases/d").build().await?;
220    /// let transaction = db_client.single_use().build();
221    /// let mut result_set = transaction
222    ///     .execute_query(Statement::builder("SELECT 'not-a-number' AS text").build())
223    ///     .await?;
224    ///
225    /// if let Some(row) = result_set.next().await {
226    ///     let result: Result<i64, _> = row?.get("text");
227    ///     if let Err(error) = result {
228    ///         if let Some(convert_error) = ConvertError::extract(&error) {
229    ///             println!("Conversion failed: {convert_error}");
230    ///         }
231    ///     }
232    /// }
233    /// # Ok(())
234    /// # }
235    /// ```
236    ///
237    /// Row deserialization returns [`Error`] with a source of [`RowError::TypeConversion`][crate::error::RowError::TypeConversion]
238    /// (wrapping [`ConvertError`]) or a direct [`ConvertError`] when value conversion fails.
239    /// This method traverses the error chain to extract the underlying [`ConvertError`].
240    pub fn extract(err: &Error) -> Option<&Self> {
241        let mut current = err.source();
242        while let Some(source) = current {
243            if let Some(convert_error) = source.downcast_ref::<Self>() {
244                return Some(convert_error);
245            }
246            current = source.source();
247        }
248        None
249    }
250}
251
252#[derive(Debug, thiserror::Error)]
253#[error("{0}")]
254struct MessageError(String);
255
256/// An error type representing a thread-safe error wrapped in an [`Arc`].
257pub type SharedError = Arc<dyn StdError + Send + Sync>;
258
259/// Converts a Spanner [Value] into a Rust type.
260///
261/// Implementations are provided for all standard types like `String`, primitive integer
262/// and float types, decimals, timestamps, dates, vectors, and options for nullable fields.
263///
264/// # Null Handling Contract
265/// Custom implementations of [`FromValue`] must return [`ConvertError::NotNull`] when given a null
266/// value ([`Value::is_null`]). This allows [`Option<T>`] to intercept the null value and return
267/// `Ok(None)` while still validating the column's schema [`Type`].
268///
269/// # Example: Custom converter for domain wrapper
270///
271/// An application can implement [`FromValue`] for custom domain or newtype wrappers:
272///
273/// ```
274/// use google_cloud_spanner::types::Type;
275/// use google_cloud_spanner::value::{ConvertError, FromValue, Value};
276///
277/// #[derive(Debug, PartialEq)]
278/// struct AccountNumber(pub String);
279///
280/// impl FromValue for AccountNumber {
281///     fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
282///         let s = String::from_value(value, spanner_type)?;
283///         Ok(AccountNumber(s))
284///     }
285/// }
286///
287/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
288/// let spanner_type = google_cloud_spanner::types::string();
289/// let val = Value::from("ACC-98765");
290/// let account = AccountNumber::from_value(&val, &spanner_type)?;
291/// assert_eq!(account.0, "ACC-98765");
292/// # Ok(())
293/// # }
294/// ```
295pub trait FromValue: Sized {
296    /// Converts a Spanner value into the target Rust type, using the provided
297    /// Spanner `Type` metadata for compatibility checks.
298    ///
299    /// # Errors
300    ///
301    /// Returns a [`ConvertError`] if the kind of the value does not match the expected kind,
302    /// if the value is null but the target type is not optional (e.g., `Option<T>`), or if
303    /// parsing or decoding the inner value format fails.
304    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError>;
305
306    /// Converts an owned Spanner value into the target Rust type, using the provided
307    /// Spanner `Type` metadata for compatibility checks.
308    ///
309    /// # Example
310    /// ```
311    /// # use google_cloud_spanner::types;
312    /// # use google_cloud_spanner::value::{FromValue, Value};
313    /// let value = Value::from("example");
314    /// let string = String::from_owned_value(value, &types::string())?;
315    /// assert_eq!(string, "example");
316    /// # Ok::<(), google_cloud_spanner::error::ConvertError>(())
317    /// ```
318    ///
319    /// The default implementation delegates to [`from_value`](FromValue::from_value)
320    /// using a reference to `value`. Types that contain heap allocations (such as
321    /// [`String`], [`Vec<T>`], [`serde_json::Value`], and [`Value`]) override this method
322    /// to move the underlying data directly without cloning.
323    ///
324    /// # Errors
325    ///
326    /// Returns a [`ConvertError`] if the kind of the value does not match the expected kind,
327    /// if the value is null but the target type is not optional (e.g., `Option<T>`), or if
328    /// parsing or decoding the inner value format fails.
329    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
330        Self::from_value(&value, spanner_type)
331    }
332}
333
334impl<T> FromValue for Option<T>
335where
336    T: FromValue,
337{
338    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
339        if value.is_null() {
340            return match T::from_value(value, spanner_type) {
341                Ok(_) | Err(ConvertError::NotNull) => Ok(None),
342                Err(error) => Err(error),
343            };
344        }
345        T::from_value(value, spanner_type).map(Some)
346    }
347
348    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
349        if value.is_null() {
350            return match T::from_owned_value(value, spanner_type) {
351                Ok(_) | Err(ConvertError::NotNull) => Ok(None),
352                Err(error) => Err(error),
353            };
354        }
355        T::from_owned_value(value, spanner_type).map(Some)
356    }
357}
358
359impl FromValue for Value {
360    fn from_value(value: &Value, _spanner_type: &Type) -> Result<Self, ConvertError> {
361        Ok(value.clone())
362    }
363
364    fn from_owned_value(value: Value, _spanner_type: &Type) -> Result<Self, ConvertError> {
365        Ok(value)
366    }
367}
368
369/// Converts any Spanner [`Value`] into a [`serde_json::Value`] using runtime [`Type`] metadata.
370///
371/// This enables dynamic deserialization of STRUCT, ARRAY, and nested
372/// `ARRAY<STRUCT<ARRAY<...>>>` columns without requiring predefined Rust types.
373///
374/// # Type mapping
375///
376/// | Spanner wire format | JSON output |
377/// |---------------------|-------------|
378/// | `NullValue` | `null` |
379/// | `BoolValue` | `true` / `false` |
380/// | `NumberValue` (finite) | JSON number |
381/// | `NumberValue` (NaN/±Infinity) | `null` |
382/// | `StringValue` ("NaN"/`±Infinity` on FLOAT columns) | `null` |
383/// | `StringValue` (standard) | JSON string (includes stringified `INT64`, `NUMERIC`, Base64 `BYTES`, `TIMESTAMP`, `DATE`) |
384/// | `StringValue` (+ `TypeCode::Json`) | Parsed JSON object/array/value |
385/// | `ListValue` + `TypeCode::Struct` | JSON object (positional → named via metadata) |
386/// | `ListValue` + `TypeCode::Array` | JSON array |
387///
388/// # Known limitations
389///
390/// - **Precision Safety**: Types such as `INT64`, `NUMERIC`, and temporal types (which
391///   Spanner transmits as `StringValue` on the wire) are preserved as JSON strings.
392///   This prevents precision loss (e.g. for integers exceeding $2^{53}-1$ or
393///   high-precision decimals) during deserialization.
394/// - **NaN/Infinity → null**: Non-finite floats become `null` when deserialized as
395///   `serde_json::Value` since standard JSON has no representation for NaN/Infinity.
396///   Callers cannot distinguish these from genuine SQL NULLs.
397/// - **Duplicate field names**: Spanner allows structs with duplicate field names
398///   (e.g., unnamed columns). Since JSON objects require unique keys, last-write-wins
399///   applies via `serde_json::Map::insert`.
400/// - **Missing struct metadata**: When `TypeCode::Struct` is indicated but no
401///   `struct_type` metadata is available, positional values are returned as a plain
402///   JSON array to avoid silent data loss.
403impl FromValue for JsonValue {
404    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
405        from_value_recursive(value, Some(spanner_type), 0)
406    }
407
408    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
409        value_to_json(value, Some(spanner_type), 0)
410    }
411}
412
413trait SpannerFloat: FromStr {
414    const NAN: Self;
415    const INFINITY: Self;
416    const NEG_INFINITY: Self;
417}
418
419impl SpannerFloat for f64 {
420    const NAN: Self = f64::NAN;
421    const INFINITY: Self = f64::INFINITY;
422    const NEG_INFINITY: Self = f64::NEG_INFINITY;
423}
424
425impl SpannerFloat for f32 {
426    const NAN: Self = f32::NAN;
427    const INFINITY: Self = f32::INFINITY;
428    const NEG_INFINITY: Self = f32::NEG_INFINITY;
429}
430
431fn parse_spanner_float<F>(string_value: &str) -> Result<F, ConvertError>
432where
433    F: SpannerFloat,
434    F::Err: StdError + Send + Sync + 'static,
435{
436    match string_value {
437        "NaN" => Ok(F::NAN),
438        "Infinity" => Ok(F::INFINITY),
439        "-Infinity" => Ok(F::NEG_INFINITY),
440        _ => string_value.parse::<F>().map_err(ConvertError::custom),
441    }
442}
443
444fn decode_borrowed_string_to_json(
445    string_value: &str,
446    target_type: Option<&Type>,
447) -> Result<JsonValue, ConvertError> {
448    let Some(target_type) = target_type else {
449        return Ok(JsonValue::String(string_value.to_string()));
450    };
451
452    match target_type.code() {
453        TypeCode::Json => serde_json::from_str(string_value).map_err(ConvertError::custom),
454        TypeCode::Float64 | TypeCode::Float32 => {
455            let float_value = parse_spanner_float::<f64>(string_value)?;
456            Ok(JsonNumber::from_f64(float_value)
457                .map(JsonValue::Number)
458                .unwrap_or(JsonValue::Null))
459        }
460        _ => Ok(JsonValue::String(string_value.to_string())),
461    }
462}
463
464fn from_value_recursive(
465    value: &Value,
466    spanner_type: Option<&Type>,
467    depth: usize,
468) -> Result<JsonValue, ConvertError> {
469    const MAX_RECURSION_DEPTH: usize = 64;
470    if depth > MAX_RECURSION_DEPTH {
471        return Err(ConvertError::message("maximum nesting depth exceeded"));
472    }
473
474    match &value.0.kind {
475        Some(ProtoKind::NullValue(_)) | None => Ok(JsonValue::Null),
476
477        Some(ProtoKind::NumberValue(number)) => Ok(JsonNumber::from_f64(*number)
478            .map(JsonValue::Number)
479            .unwrap_or(JsonValue::Null)),
480
481        Some(ProtoKind::StringValue(string_value)) => {
482            decode_borrowed_string_to_json(string_value, spanner_type)
483        }
484
485        Some(ProtoKind::BoolValue(boolean_value)) => Ok(JsonValue::Bool(*boolean_value)),
486
487        Some(ProtoKind::StructValue(_)) => Err(ConvertError::message(
488            "unexpected protobuf StructValue on wire; Spanner SQL STRUCT values are encoded as ListValue",
489        )),
490
491        Some(ProtoKind::ListValue(list_value)) => {
492            borrowed_list_value_to_json(list_value, spanner_type, depth + 1)
493        }
494    }
495}
496
497fn borrowed_list_value_to_json(
498    list_value: &ProtoListValue,
499    spanner_type: Option<&Type>,
500    depth: usize,
501) -> Result<JsonValue, ConvertError> {
502    let code = spanner_type.map_or(TypeCode::Unspecified, |target_type| target_type.code());
503    match code {
504        TypeCode::Struct => {
505            let Some(struct_type) = spanner_type.and_then(|target_type| target_type.struct_type())
506            else {
507                let mut array = Vec::with_capacity(list_value.values.len());
508                for proto_value in &list_value.values {
509                    let val = Value::from_ref(proto_value);
510                    array.push(from_value_recursive(val, None, depth)?);
511                }
512                return Ok(JsonValue::Array(array));
513            };
514
515            let mut map = JsonMap::new();
516            for (index, field) in struct_type.fields.iter().enumerate() {
517                let field_type = field.r#type.as_deref().map(Type::from_ref);
518                let value = if let Some(proto_value) = list_value.values.get(index) {
519                    let val = Value::from_ref(proto_value);
520                    from_value_recursive(val, field_type, depth)?
521                } else {
522                    JsonValue::Null
523                };
524                map.insert(field.name.clone(), value);
525            }
526            Ok(JsonValue::Object(map))
527        }
528
529        _ => {
530            let element_type = spanner_type.and_then(Type::array_element_type);
531            let mut array = Vec::with_capacity(list_value.values.len());
532            for proto_value in &list_value.values {
533                let val = Value::from_ref(proto_value);
534                array.push(from_value_recursive(val, element_type, depth)?);
535            }
536            Ok(JsonValue::Array(array))
537        }
538    }
539}
540
541fn decode_owned_string_to_json(
542    string_value: String,
543    target_type: Option<&Type>,
544) -> Result<JsonValue, ConvertError> {
545    let Some(target_type) = target_type else {
546        return Ok(JsonValue::String(string_value));
547    };
548
549    match target_type.code() {
550        TypeCode::Json => serde_json::from_str(&string_value).map_err(ConvertError::custom),
551        TypeCode::Float64 | TypeCode::Float32 => {
552            let float_value = parse_spanner_float::<f64>(&string_value)?;
553            Ok(JsonNumber::from_f64(float_value)
554                .map(JsonValue::Number)
555                .unwrap_or(JsonValue::Null))
556        }
557        _ => Ok(JsonValue::String(string_value)),
558    }
559}
560
561fn value_to_json(
562    value: Value,
563    spanner_type: Option<&Type>,
564    depth: usize,
565) -> Result<JsonValue, ConvertError> {
566    const MAX_RECURSION_DEPTH: usize = 64;
567    if depth > MAX_RECURSION_DEPTH {
568        return Err(ConvertError::message("maximum nesting depth exceeded"));
569    }
570
571    match value.0.kind {
572        Some(ProtoKind::NullValue(_)) | None => Ok(JsonValue::Null),
573
574        Some(ProtoKind::NumberValue(number)) => Ok(JsonNumber::from_f64(number)
575            .map(JsonValue::Number)
576            .unwrap_or(JsonValue::Null)),
577
578        Some(ProtoKind::StringValue(string_value)) => {
579            decode_owned_string_to_json(string_value, spanner_type)
580        }
581
582        Some(ProtoKind::BoolValue(boolean_value)) => Ok(JsonValue::Bool(boolean_value)),
583
584        Some(ProtoKind::StructValue(_)) => Err(ConvertError::message(
585            "unexpected protobuf StructValue on wire; Spanner SQL STRUCT values are encoded as ListValue",
586        )),
587
588        Some(ProtoKind::ListValue(list_value)) => {
589            list_value_to_json(list_value, spanner_type, depth + 1)
590        }
591    }
592}
593
594fn list_value_to_json(
595    list_value: ProtoListValue,
596    spanner_type: Option<&Type>,
597    depth: usize,
598) -> Result<JsonValue, ConvertError> {
599    let code = spanner_type.map_or(TypeCode::Unspecified, |target_type| target_type.code());
600    match code {
601        TypeCode::Struct => {
602            let Some(struct_type) = spanner_type.and_then(|target_type| target_type.struct_type())
603            else {
604                let mut array = Vec::with_capacity(list_value.values.len());
605                for proto_value in list_value.values {
606                    array.push(value_to_json(Value(proto_value), None, depth)?);
607                }
608                return Ok(JsonValue::Array(array));
609            };
610
611            let mut map = JsonMap::new();
612            let mut iterator = list_value.values.into_iter();
613            for field in &struct_type.fields {
614                let field_type = field.r#type.as_deref().map(Type::from_ref);
615                let value = if let Some(field_value) = iterator.next() {
616                    value_to_json(Value(field_value), field_type, depth)?
617                } else {
618                    JsonValue::Null
619                };
620                map.insert(field.name.clone(), value);
621            }
622            Ok(JsonValue::Object(map))
623        }
624
625        _ => {
626            let element_type = spanner_type.and_then(Type::array_element_type);
627            let mut array = Vec::with_capacity(list_value.values.len());
628            for proto_value in list_value.values {
629                array.push(value_to_json(Value(proto_value), element_type, depth)?);
630            }
631            Ok(JsonValue::Array(array))
632        }
633    }
634}
635
636/// Deserializes a string value from a Spanner [`Value`].
637///
638/// Supported Spanner types are:
639/// - Textual types: [`TypeCode::String`], [`TypeCode::Json`], [`TypeCode::Uuid`], and [`TypeCode::Interval`].
640/// - Temporal types: [`TypeCode::Date`] (formatted as `YYYY-MM-DD`) and [`TypeCode::Timestamp`] (formatted as RFC 3339).
641/// - Exact decimal types: [`TypeCode::Numeric`]. Retrieving `NUMERIC` as [`String`] preserves full 38-digit precision and handles special PostgreSQL values like `NaN` without loss or parsing errors.
642///
643/// Non-string types (such as `INT64`, `BYTES`, `FLOAT64`, `FLOAT32`, `BOOL`, `ARRAY`, and `STRUCT`)
644/// are rejected with [`ConvertError::TypeMismatch`].
645impl FromValue for String {
646    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
647        match spanner_type.code() {
648            TypeCode::String
649            | TypeCode::Json
650            | TypeCode::Uuid
651            | TypeCode::Interval
652            | TypeCode::Date
653            | TypeCode::Timestamp
654            | TypeCode::Numeric => {}
655            got => {
656                return Err(ConvertError::TypeMismatch {
657                    want: TypeCode::String,
658                    got,
659                });
660            }
661        }
662        match &value.0.kind {
663            Some(ProtoKind::StringValue(s)) => Ok(s.clone()),
664            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
665            _ => Err(ConvertError::KindMismatch {
666                want: Kind::String,
667                got: value.kind(),
668            }),
669        }
670    }
671
672    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
673        match spanner_type.code() {
674            TypeCode::String
675            | TypeCode::Json
676            | TypeCode::Uuid
677            | TypeCode::Interval
678            | TypeCode::Date
679            | TypeCode::Timestamp
680            | TypeCode::Numeric => {}
681            got => {
682                return Err(ConvertError::TypeMismatch {
683                    want: TypeCode::String,
684                    got,
685                });
686            }
687        }
688        match value.0.kind {
689            Some(ProtoKind::StringValue(string_value)) => Ok(string_value),
690            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
691            other => Err(ConvertError::KindMismatch {
692                want: Kind::String,
693                got: Kind::from(other),
694            }),
695        }
696    }
697}
698
699/// Deserializes a 64-bit integer from a Spanner [`Value`].
700///
701/// Accepts Spanner [`TypeCode::Int64`] and [`TypeCode::Enum`].
702impl FromValue for i64 {
703    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
704        match spanner_type.code() {
705            TypeCode::Int64 | TypeCode::Enum => {}
706            got => {
707                return Err(ConvertError::TypeMismatch {
708                    want: TypeCode::Int64,
709                    got,
710                });
711            }
712        }
713        match &value.0.kind {
714            Some(ProtoKind::StringValue(s)) => s.parse().map_err(ConvertError::custom),
715            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
716            _ => Err(ConvertError::KindMismatch {
717                want: Kind::String,
718                got: value.kind(),
719            }),
720        }
721    }
722}
723
724/// Deserializes a 32-bit integer from a Spanner [`Value`].
725///
726/// Accepts Spanner [`TypeCode::Int64`] and [`TypeCode::Enum`].
727impl FromValue for i32 {
728    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
729        match spanner_type.code() {
730            TypeCode::Int64 | TypeCode::Enum => {}
731            got => {
732                return Err(ConvertError::TypeMismatch {
733                    want: TypeCode::Int64,
734                    got,
735                });
736            }
737        }
738        match &value.0.kind {
739            Some(ProtoKind::StringValue(s)) => s.parse().map_err(ConvertError::custom),
740            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
741            _ => Err(ConvertError::KindMismatch {
742                want: Kind::String,
743                got: value.kind(),
744            }),
745        }
746    }
747}
748
749/// Converts a Spanner `TypeCode::Numeric` column into a `Decimal`.
750///
751/// Supports both standard fixed-point decimal notation (e.g., `"123.456"`) and
752/// scientific notation format (e.g., `"1e5"`, `"1.5e-3"`).
753///
754/// # Precision Limitations
755///
756/// Cloud Spanner `NUMERIC` supports up to 38 decimal digits of precision (up to 29
757/// digits before the decimal point and 9 digits after). However, [`Decimal`] uses a
758/// 96-bit unsigned integer mantissa, which can represent at most ~28–29 total decimal
759/// digits (and at most 19–20 digits before the decimal point when scale is 9).
760///
761/// If a Spanner numeric value exceeds the 96-bit limit of [`Decimal`], or if a PostgreSQL
762/// dialect database returns `"NaN"`, converting to [`Decimal`] will return a
763/// [`ConvertError::Convert`]. For values that exceed 96 bits or for PostgreSQL `"NaN"`,
764/// callers should read the column as a [`String`] instead (e.g., `let value: String = row.get(...)?;`).
765impl FromValue for Decimal {
766    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
767        if spanner_type.code() != TypeCode::Numeric {
768            return Err(ConvertError::TypeMismatch {
769                want: TypeCode::Numeric,
770                got: spanner_type.code(),
771            });
772        }
773        let string_value = match &value.0.kind {
774            Some(ProtoKind::StringValue(string_value)) => string_value,
775            Some(ProtoKind::NullValue(_)) | None => return Err(ConvertError::NotNull),
776            _ => {
777                return Err(ConvertError::KindMismatch {
778                    want: Kind::String,
779                    got: value.kind(),
780                });
781            }
782        };
783
784        match Decimal::from_str_exact(string_value) {
785            Ok(decimal) => Ok(decimal),
786            Err(_) if string_value.contains(['e', 'E']) => {
787                Decimal::from_scientific(string_value).map_err(ConvertError::custom)
788            }
789            Err(error) => Err(ConvertError::custom(error)),
790        }
791    }
792}
793
794impl FromValue for SystemTime {
795    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
796        let timestamp = Timestamp::from_value(value, spanner_type)?;
797        Self::try_from(timestamp).map_err(ConvertError::custom)
798    }
799}
800
801#[cfg(feature = "unstable-time")]
802#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
803impl FromValue for OffsetDateTime {
804    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
805        if spanner_type.code() != TypeCode::Timestamp {
806            return Err(ConvertError::TypeMismatch {
807                want: TypeCode::Timestamp,
808                got: spanner_type.code(),
809            });
810        }
811        match &value.0.kind {
812            Some(ProtoKind::StringValue(s)) => {
813                let date_time = Self::parse(s, &Rfc3339).map_err(ConvertError::custom)?;
814                Ok(date_time)
815            }
816            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
817            _ => Err(ConvertError::KindMismatch {
818                want: Kind::String,
819                got: value.kind(),
820            }),
821        }
822    }
823}
824
825impl FromValue for Timestamp {
826    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
827        if spanner_type.code() != TypeCode::Timestamp {
828            return Err(ConvertError::TypeMismatch {
829                want: TypeCode::Timestamp,
830                got: spanner_type.code(),
831            });
832        }
833        match &value.0.kind {
834            Some(ProtoKind::StringValue(s)) => {
835                Self::try_from(s.as_str()).map_err(ConvertError::custom)
836            }
837            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
838            _ => Err(ConvertError::KindMismatch {
839                want: Kind::String,
840                got: value.kind(),
841            }),
842        }
843    }
844}
845
846#[cfg(feature = "unstable-time")]
847#[cfg_attr(docsrs, doc(cfg(feature = "unstable-time")))]
848impl FromValue for TimeDate {
849    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
850        if spanner_type.code() != TypeCode::Date {
851            return Err(ConvertError::TypeMismatch {
852                want: TypeCode::Date,
853                got: spanner_type.code(),
854            });
855        }
856        match &value.0.kind {
857            Some(ProtoKind::StringValue(s)) => {
858                let date = Self::parse(s, SPANNER_DATE_FORMAT).map_err(ConvertError::custom)?;
859                Ok(date)
860            }
861            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
862            _ => Err(ConvertError::KindMismatch {
863                want: Kind::String,
864                got: value.kind(),
865            }),
866        }
867    }
868}
869
870impl FromValue for Date {
871    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
872        if spanner_type.code() != TypeCode::Date {
873            return Err(ConvertError::TypeMismatch {
874                want: TypeCode::Date,
875                got: spanner_type.code(),
876            });
877        }
878        match &value.0.kind {
879            Some(ProtoKind::StringValue(s)) => {
880                let date = TimeDate::parse(s, SPANNER_DATE_FORMAT).map_err(ConvertError::custom)?;
881                Ok(Self::new()
882                    .set_year(date.year())
883                    .set_month(u8::from(date.month()) as i32)
884                    .set_day(date.day() as i32))
885            }
886            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
887            _ => Err(ConvertError::KindMismatch {
888                want: Kind::String,
889                got: value.kind(),
890            }),
891        }
892    }
893}
894
895impl FromValue for bool {
896    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
897        if spanner_type.code() != TypeCode::Bool {
898            return Err(ConvertError::TypeMismatch {
899                want: TypeCode::Bool,
900                got: spanner_type.code(),
901            });
902        }
903        match &value.0.kind {
904            Some(ProtoKind::BoolValue(b)) => Ok(*b),
905            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
906            _ => Err(ConvertError::KindMismatch {
907                want: Kind::Bool,
908                got: value.kind(),
909            }),
910        }
911    }
912}
913
914/// Deserializes a 64-bit floating-point value from a Spanner [`Value`].
915///
916/// Accepts Spanner `TypeCode::Float64` and `TypeCode::Float32`.
917/// Values from `TypeCode::Float32` columns are widened to `f64` losslessly.
918impl FromValue for f64 {
919    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
920        if spanner_type.code() != TypeCode::Float64 && spanner_type.code() != TypeCode::Float32 {
921            return Err(ConvertError::TypeMismatch {
922                want: TypeCode::Float64,
923                got: spanner_type.code(),
924            });
925        }
926        match &value.0.kind {
927            Some(ProtoKind::NumberValue(n)) => Ok(*n),
928            Some(ProtoKind::StringValue(s)) => s.parse().map_err(ConvertError::custom),
929            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
930            _ => Err(ConvertError::KindMismatch {
931                want: Kind::Number,
932                got: value.kind(),
933            }),
934        }
935    }
936}
937
938fn is_infinity_literal(value: &str) -> bool {
939    let trimmed = value.trim();
940    let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
941    body.eq_ignore_ascii_case("inf") || body.eq_ignore_ascii_case("infinity")
942}
943
944/// Deserializes a 32-bit floating-point value from a Spanner [`Value`].
945///
946/// Accepts Spanner `TypeCode::Float32` and `TypeCode::Float64`.
947///
948/// # Precision & Range Limitations
949///
950/// When deserializing from a Spanner `TypeCode::Float64` column, 64-bit IEEE 754
951/// floating-point numbers are narrowed to 32-bit `f32`.
952///
953/// If a finite float value exceeds the representable range of `f32`
954/// (greater than [`f32::MAX`] or less than [`f32::MIN`] / `-f32::MAX`), this conversion
955/// returns a `ConvertError::Convert`. Non-finite values (`NaN`, `Infinity`,
956/// `+Infinity`, and `-Infinity`) are preserved.
957impl FromValue for f32 {
958    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
959        if spanner_type.code() != TypeCode::Float32 && spanner_type.code() != TypeCode::Float64 {
960            return Err(ConvertError::TypeMismatch {
961                want: TypeCode::Float32,
962                got: spanner_type.code(),
963            });
964        }
965        match &value.0.kind {
966            Some(ProtoKind::NumberValue(number_value)) => {
967                let converted_value = *number_value as f32;
968                if number_value.is_finite() && converted_value.is_infinite() {
969                    return Err(ConvertError::message(format!(
970                        "float value '{number_value}' exceeds f32 range"
971                    )));
972                }
973                Ok(converted_value)
974            }
975            Some(ProtoKind::StringValue(string_value)) => {
976                let parsed_value: f32 = string_value.parse().map_err(ConvertError::custom)?;
977                if parsed_value.is_infinite() && !is_infinity_literal(string_value) {
978                    return Err(ConvertError::message(format!(
979                        "float value '{string_value}' exceeds f32 range"
980                    )));
981                }
982                Ok(parsed_value)
983            }
984            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
985            _ => Err(ConvertError::KindMismatch {
986                want: Kind::Number,
987                got: value.kind(),
988            }),
989        }
990    }
991}
992
993impl FromValue for Vec<u8> {
994    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
995        if spanner_type.code() != TypeCode::Bytes && spanner_type.code() != TypeCode::Proto {
996            return Err(ConvertError::TypeMismatch {
997                want: TypeCode::Bytes,
998                got: spanner_type.code(),
999            });
1000        }
1001        match &value.0.kind {
1002            Some(ProtoKind::StringValue(string_value)) => BASE64_STANDARD
1003                .decode(string_value)
1004                .map_err(ConvertError::custom),
1005            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
1006            _ => Err(ConvertError::KindMismatch {
1007                want: Kind::String,
1008                got: value.kind(),
1009            }),
1010        }
1011    }
1012
1013    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1014        if spanner_type.code() != TypeCode::Bytes && spanner_type.code() != TypeCode::Proto {
1015            return Err(ConvertError::TypeMismatch {
1016                want: TypeCode::Bytes,
1017                got: spanner_type.code(),
1018            });
1019        }
1020        match value.0.kind {
1021            Some(ProtoKind::StringValue(string_value)) => BASE64_STANDARD
1022                .decode(string_value)
1023                .map_err(ConvertError::custom),
1024            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
1025            other => Err(ConvertError::KindMismatch {
1026                want: Kind::String,
1027                got: Kind::from(other),
1028            }),
1029        }
1030    }
1031}
1032
1033/// Deserializes a byte buffer from a Spanner [`Value`].
1034///
1035/// Accepts Spanner [`TypeCode::Bytes`] and [`TypeCode::Proto`].
1036/// Values are decoded from the wire base64-encoded string representation.
1037impl FromValue for Bytes {
1038    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1039        Vec::<u8>::from_value(value, spanner_type).map(Bytes::from)
1040    }
1041
1042    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1043        Vec::<u8>::from_owned_value(value, spanner_type).map(Bytes::from)
1044    }
1045}
1046
1047/// Deserializes a UUID from a Spanner [`Value`].
1048///
1049/// Accepts Spanner [`TypeCode::Uuid`] and [`TypeCode::String`].
1050/// Values are parsed from the wire 8-4-4-4-12 hex string representation.
1051impl FromValue for Uuid {
1052    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1053        match spanner_type.code() {
1054            TypeCode::Uuid | TypeCode::String => {}
1055            got => {
1056                return Err(ConvertError::TypeMismatch {
1057                    want: TypeCode::Uuid,
1058                    got,
1059                });
1060            }
1061        }
1062        match &value.0.kind {
1063            Some(ProtoKind::StringValue(string_value)) => {
1064                Uuid::parse_str(string_value).map_err(ConvertError::custom)
1065            }
1066            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
1067            _ => Err(ConvertError::KindMismatch {
1068                want: Kind::String,
1069                got: value.kind(),
1070            }),
1071        }
1072    }
1073}
1074
1075impl<T> FromValue for Vec<T>
1076where
1077    T: FromValue,
1078{
1079    fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1080        if spanner_type.code() != TypeCode::Array {
1081            return Err(ConvertError::TypeMismatch {
1082                want: TypeCode::Array,
1083                got: spanner_type.code(),
1084            });
1085        }
1086        let element_type = spanner_type
1087            .array_element_type()
1088            .ok_or_else(|| ConvertError::message("Array type missing element type"))?;
1089
1090        match &value.0.kind {
1091            Some(ProtoKind::ListValue(list)) => {
1092                let mut vec = Vec::with_capacity(list.values.len());
1093                for v in &list.values {
1094                    // `Value` is a `#[repr(transparent)]` wrapper around `ProtoValue`.
1095                    // We use `from_ref` to safely cast the pointer and avoid cloning elements.
1096                    let val = Value::from_ref(v);
1097                    vec.push(T::from_value(val, element_type)?);
1098                }
1099                Ok(vec)
1100            }
1101            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
1102            _ => Err(ConvertError::KindMismatch {
1103                want: Kind::List,
1104                got: value.kind(),
1105            }),
1106        }
1107    }
1108
1109    fn from_owned_value(value: Value, spanner_type: &Type) -> Result<Self, ConvertError> {
1110        if spanner_type.code() != TypeCode::Array {
1111            return Err(ConvertError::TypeMismatch {
1112                want: TypeCode::Array,
1113                got: spanner_type.code(),
1114            });
1115        }
1116        let element_type = spanner_type
1117            .array_element_type()
1118            .ok_or_else(|| ConvertError::message("Array type missing element type"))?;
1119
1120        match value.0.kind {
1121            Some(ProtoKind::ListValue(list_value)) => {
1122                let mut vector = Vec::with_capacity(list_value.values.len());
1123                for proto_value in list_value.values {
1124                    vector.push(T::from_owned_value(Value(proto_value), element_type)?);
1125                }
1126                Ok(vector)
1127            }
1128            Some(ProtoKind::NullValue(_)) | None => Err(ConvertError::NotNull),
1129            other => Err(ConvertError::KindMismatch {
1130                want: Kind::List,
1131                got: Kind::from(other),
1132            }),
1133        }
1134    }
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use super::*;
1140    use crate::generated::gapic_dataplane::model;
1141    use crate::row::RowError;
1142    use crate::to_value::ToValue;
1143    use crate::types;
1144    use prost_types::Value as ProtoValue;
1145    use serde_json::{Value as JsonValue, json};
1146    #[cfg(feature = "unstable-time")]
1147    use time::Month;
1148
1149    #[test]
1150    fn test_from_value_string() {
1151        let v = "hello".to_value();
1152        let s = String::from_value(&v, &types::string()).expect("valid string value");
1153        assert_eq!(s, "hello", "expected string content");
1154
1155        // String from JSON
1156        let v_json = "{\"key\":\"value\"}".to_string().to_value();
1157        let s_json = String::from_value(&v_json, &types::json()).expect("valid json value");
1158        assert_eq!(s_json, "{\"key\":\"value\"}", "expected json text");
1159
1160        // String from UUID
1161        let value_uuid = "123e4567-e89b-12d3-a456-426614174000"
1162            .to_string()
1163            .to_value();
1164        let string_uuid =
1165            String::from_value(&value_uuid, &types::uuid()).expect("valid uuid value");
1166        assert_eq!(
1167            string_uuid, "123e4567-e89b-12d3-a456-426614174000",
1168            "expected uuid text"
1169        );
1170
1171        // String from INTERVAL
1172        let value_interval = "P1Y2M3D".to_string().to_value();
1173        let string_interval =
1174            String::from_value(&value_interval, &types::interval()).expect("valid interval value");
1175        assert_eq!(string_interval, "P1Y2M3D", "expected interval text");
1176
1177        // String from DATE
1178        let date = Date::new().set_year(2023).set_month(10).set_day(27);
1179        let string_date =
1180            String::from_value(&date.to_value(), &types::date()).expect("valid date value");
1181        assert_eq!(string_date, "2023-10-27", "expected date text");
1182
1183        // String from TIMESTAMP
1184        let timestamp = Timestamp::clamp(1_698_400_800, 0);
1185        let string_timestamp = String::from_value(&timestamp.to_value(), &types::timestamp())
1186            .expect("valid timestamp value");
1187        assert_eq!(
1188            string_timestamp, "2023-10-27T10:00:00.000000000Z",
1189            "expected timestamp text"
1190        );
1191
1192        // String from NUMERIC
1193        let decimal = Decimal::from_str_exact("123.456").expect("valid decimal");
1194        let string_numeric = String::from_value(&decimal.to_value(), &types::numeric())
1195            .expect("valid numeric value");
1196        assert_eq!(string_numeric, "123.456", "expected numeric text");
1197    }
1198
1199    #[test]
1200    fn test_from_value_int() {
1201        let value_int = 42i64.to_value();
1202        let int64_value = i64::from_value(&value_int, &types::int64()).expect("valid i64");
1203        assert_eq!(int64_value, 42);
1204
1205        let int32_value = i32::from_value(&value_int, &types::int64()).expect("valid i32");
1206        assert_eq!(int32_value, 42);
1207
1208        // Enum support
1209        let enum_type = types::proto_enum("customer.Priority");
1210        let enum_value = 7i64.to_value();
1211        let int64_enum = i64::from_value(&enum_value, &enum_type).expect("valid i64 from ENUM");
1212        assert_eq!(int64_enum, 7);
1213
1214        let int32_enum = i32::from_value(&enum_value, &enum_type).expect("valid i32 from ENUM");
1215        assert_eq!(int32_enum, 7);
1216
1217        // Negative tests
1218        let invalid_int = "not an int".to_value();
1219        let error_i64 = i64::from_value(&invalid_int, &types::int64()).expect_err("invalid i64");
1220        assert!(format!("{error_i64}").contains("cannot convert value"));
1221
1222        let error_i32 = i32::from_value(&invalid_int, &types::int64()).expect_err("invalid i32");
1223        assert!(format!("{error_i32}").contains("cannot convert value"));
1224
1225        let bool_value = true.to_value();
1226        let error_kind_i64 = i64::from_value(&bool_value, &types::int64())
1227            .expect_err("reading bool value as i64 must fail with KindMismatch");
1228        assert_eq!(
1229            error_kind_i64.to_string(),
1230            "expected String, got Bool",
1231            "expected KindMismatch error message for i64"
1232        );
1233
1234        let error_kind_i32 = i32::from_value(&bool_value, &types::int64())
1235            .expect_err("reading bool value as i32 must fail with KindMismatch");
1236        assert_eq!(
1237            error_kind_i32.to_string(),
1238            "expected String, got Bool",
1239            "expected KindMismatch error message for i32"
1240        );
1241    }
1242
1243    #[test]
1244    fn test_from_value_float() {
1245        let v = 42.5f64.to_value();
1246        let f = f64::from_value(&v, &types::float64()).expect("valid float value");
1247        assert_eq!(f, 42.5, "expected 42.5");
1248
1249        let v = "Infinity".to_string().to_value();
1250        let f = f64::from_value(&v, &types::float64()).expect("valid infinity value");
1251        assert_eq!(f, f64::INFINITY, "expected Infinity");
1252
1253        let v = "invalid float".to_string().to_value();
1254        let err = f64::from_value(&v, &types::float64()).expect_err("invalid float must fail");
1255        assert!(
1256            format!("{}", err).contains("invalid float literal"),
1257            "expected invalid float literal error"
1258        );
1259    }
1260
1261    #[test]
1262    fn from_value_float_non_finite_and_type_checks() {
1263        // f64 non-finite strings
1264        let nan_val = "NaN".to_string().to_value();
1265        let f64_nan = f64::from_value(&nan_val, &types::float64()).expect("valid NaN f64");
1266        assert!(f64_nan.is_nan(), "expected NaN for f64");
1267
1268        let inf_val = "Infinity".to_string().to_value();
1269        let f64_inf = f64::from_value(&inf_val, &types::float64()).expect("valid Infinity f64");
1270        assert_eq!(f64_inf, f64::INFINITY, "expected Infinity for f64");
1271
1272        let neg_inf_val = "-Infinity".to_string().to_value();
1273        let f64_neginf =
1274            f64::from_value(&neg_inf_val, &types::float64()).expect("valid -Infinity f64");
1275        assert_eq!(f64_neginf, f64::NEG_INFINITY, "expected -Infinity for f64");
1276
1277        // f64 from FLOAT32 column (lossless widening)
1278        let f32_widened =
1279            f64::from_value(&42.5f32.to_value(), &types::float32()).expect("FLOAT32 widens to f64");
1280        assert_eq!(f32_widened, 42.5, "expected 42.5 from FLOAT32 to f64");
1281
1282        // f64 rejects STRING column even if it contains "NaN"
1283        let string_col_err =
1284            f64::from_value(&nan_val, &types::string()).expect_err("f64 must reject STRING column");
1285        assert_eq!(
1286            string_col_err.to_string(),
1287            "type mismatch, expected Float64, got String",
1288            "expected TypeMismatch when reading STRING column as f64"
1289        );
1290
1291        // f64 rejects non-numeric string in FLOAT64 column
1292        let invalid_str_err =
1293            f64::from_value(&"not-a-number".to_string().to_value(), &types::float64())
1294                .expect_err("f64 must reject arbitrary string representation");
1295        assert!(
1296            format!("{}", invalid_str_err).contains("invalid float literal"),
1297            "expected invalid float literal error"
1298        );
1299
1300        // f32 non-finite strings and numbers
1301        let f32_num = f32::from_value(&12.5f32.to_value(), &types::float32()).expect("valid f32");
1302        assert_eq!(f32_num, 12.5, "expected 12.5 for f32");
1303
1304        let f32_nan = f32::from_value(&nan_val, &types::float32()).expect("valid NaN f32");
1305        assert!(f32_nan.is_nan(), "expected NaN for f32");
1306
1307        let f32_inf = f32::from_value(&inf_val, &types::float32()).expect("valid Infinity f32");
1308        assert_eq!(f32_inf, f32::INFINITY, "expected Infinity for f32");
1309
1310        let f32_neginf =
1311            f32::from_value(&neg_inf_val, &types::float32()).expect("valid -Infinity f32");
1312        assert_eq!(f32_neginf, f32::NEG_INFINITY, "expected -Infinity for f32");
1313
1314        // f32 accepts NumberValue from FLOAT64 column
1315        let f32_from_f64 = f32::from_value(&42.5f64.to_value(), &types::float64())
1316            .expect("f32 accepts NumberValue from FLOAT64 column");
1317        assert_eq!(f32_from_f64, 42.5, "expected 42.5 from NumberValue for f32");
1318
1319        // f32 rejects STRING column
1320        let f32_str_err =
1321            f32::from_value(&nan_val, &types::string()).expect_err("f32 must reject STRING column");
1322        assert_eq!(
1323            f32_str_err.to_string(),
1324            "type mismatch, expected Float32, got String",
1325            "expected TypeMismatch when reading STRING column as f32"
1326        );
1327
1328        // f32 parses numeric string in FLOAT32 column
1329        let f32_from_str = f32::from_value(&"12.5".to_string().to_value(), &types::float32())
1330            .expect("valid f32 from numeric string");
1331        assert_eq!(f32_from_str, 12.5, "expected 12.5 from string for f32");
1332
1333        // f32 rejects non-numeric string in FLOAT32 column
1334        let invalid_f32_str_error =
1335            f32::from_value(&"not-a-number".to_string().to_value(), &types::float32())
1336                .expect_err("f32 must reject arbitrary string representation");
1337        assert!(
1338            format!("{invalid_f32_str_error}").contains("invalid float literal"),
1339            "expected invalid float literal error for f32"
1340        );
1341
1342        // String::from_value rejects FLOAT64 and FLOAT32 columns (even with non-finite string representation)
1343        let string_f64_nan_err = String::from_value(&nan_val, &types::float64())
1344            .expect_err("String must reject FLOAT64 column with NaN");
1345        assert_eq!(
1346            string_f64_nan_err.to_string(),
1347            "type mismatch, expected String, got Float64",
1348            "expected TypeMismatch when reading FLOAT64 column as String"
1349        );
1350
1351        let string_f32_inf_err = String::from_value(&inf_val, &types::float32())
1352            .expect_err("String must reject FLOAT32 column with Infinity");
1353        assert_eq!(
1354            string_f32_inf_err.to_string(),
1355            "type mismatch, expected String, got Float32",
1356            "expected TypeMismatch when reading FLOAT32 column as String"
1357        );
1358
1359        let string_f64_num_err = String::from_value(&42.5f64.to_value(), &types::float64())
1360            .expect_err("String must reject FLOAT64 column with NumberValue");
1361        assert_eq!(
1362            string_f64_num_err.to_string(),
1363            "type mismatch, expected String, got Float64",
1364            "expected TypeMismatch when reading FLOAT64 NumberValue as String"
1365        );
1366    }
1367
1368    #[test]
1369    fn from_value_f32_overflow_rejected() {
1370        let test_cases = [
1371            (
1372                Value::from(1e300_f64),
1373                types::float64(),
1374                "positive f64 overflow in NumberValue",
1375            ),
1376            (
1377                Value::from(-1e300_f64),
1378                types::float64(),
1379                "negative f64 overflow in NumberValue",
1380            ),
1381            (
1382                Value::from(1e39_f64),
1383                types::float64(),
1384                "moderate positive overflow in NumberValue",
1385            ),
1386            (
1387                Value::from(-1e39_f64),
1388                types::float64(),
1389                "moderate negative overflow in NumberValue",
1390            ),
1391            (
1392                Value::from(f64::MAX),
1393                types::float64(),
1394                "extreme positive boundary f64::MAX in NumberValue",
1395            ),
1396            (
1397                Value::from(f64::MIN),
1398                types::float64(),
1399                "extreme negative boundary f64::MIN in NumberValue",
1400            ),
1401            (
1402                Value::from(3.4028236e38_f64),
1403                types::float64(),
1404                "positive float just above f32::MAX",
1405            ),
1406            (
1407                Value::from(-3.4028236e38_f64),
1408                types::float64(),
1409                "negative float just below f32::MIN",
1410            ),
1411            (
1412                "1e300".to_string().to_value(),
1413                types::float32(),
1414                "positive overflow in StringValue for FLOAT32",
1415            ),
1416            (
1417                "-1e300".to_string().to_value(),
1418                types::float32(),
1419                "negative overflow in StringValue for FLOAT32",
1420            ),
1421            (
1422                "1e300".to_string().to_value(),
1423                types::float64(),
1424                "positive overflow in StringValue for FLOAT64",
1425            ),
1426            (
1427                "-1e300".to_string().to_value(),
1428                types::float64(),
1429                "negative overflow in StringValue for FLOAT64",
1430            ),
1431            (
1432                "3.4028236e38".to_string().to_value(),
1433                types::float32(),
1434                "StringValue just above f32::MAX for FLOAT32",
1435            ),
1436            (
1437                "-3.4028236e38".to_string().to_value(),
1438                types::float32(),
1439                "StringValue just below f32::MIN for FLOAT32",
1440            ),
1441            (
1442                "3.4028236e38".to_string().to_value(),
1443                types::float64(),
1444                "StringValue just above f32::MAX for FLOAT64",
1445            ),
1446            (
1447                "-3.4028236e38".to_string().to_value(),
1448                types::float64(),
1449                "StringValue just below f32::MIN for FLOAT64",
1450            ),
1451            (
1452                "1e500".to_string().to_value(),
1453                types::float32(),
1454                "extreme positive overflow in StringValue for FLOAT32",
1455            ),
1456            (
1457                "-1e500".to_string().to_value(),
1458                types::float32(),
1459                "extreme negative overflow in StringValue for FLOAT32",
1460            ),
1461            (
1462                "1e500".to_string().to_value(),
1463                types::float64(),
1464                "extreme positive overflow in StringValue for FLOAT64",
1465            ),
1466            (
1467                "-1e500".to_string().to_value(),
1468                types::float64(),
1469                "extreme negative overflow in StringValue for FLOAT64",
1470            ),
1471        ];
1472
1473        for (value, spanner_type, description) in test_cases {
1474            let error = f32::from_value(&value, &spanner_type)
1475                .expect_err(&format!("{description} must return ConvertError"));
1476            let error_message = error.to_string();
1477            assert!(
1478                error_message.contains("exceeds f32 range"),
1479                "expected 'exceeds f32 range' in error message for {description}, got: {error_message}"
1480            );
1481        }
1482
1483        // Verify boundary values within f32 range succeed
1484        let max_f32_as_f64 = Value::from(f32::MAX as f64);
1485        let parsed_max_f32 = f32::from_value(&max_f32_as_f64, &types::float64())
1486            .expect("f32::MAX as f64 must convert successfully");
1487        assert_eq!(parsed_max_f32, f32::MAX, "expected f32::MAX");
1488
1489        let min_f32_as_f64 = Value::from(f32::MIN as f64);
1490        let parsed_min_f32 = f32::from_value(&min_f32_as_f64, &types::float64())
1491            .expect("f32::MIN as f64 must convert successfully");
1492        assert_eq!(parsed_min_f32, f32::MIN, "expected f32::MIN");
1493
1494        let zero_f64 = Value::from(0.0_f64);
1495        let parsed_zero_f32 = f32::from_value(&zero_f64, &types::float64())
1496            .expect("0.0 as f64 must convert successfully");
1497        assert_eq!(parsed_zero_f32, 0.0_f32, "expected 0.0");
1498
1499        let negative_zero_f64 = Value::from(-0.0_f64);
1500        let parsed_negative_zero_f32 = f32::from_value(&negative_zero_f64, &types::float64())
1501            .expect("-0.0 as f64 must convert successfully");
1502        assert_eq!(parsed_negative_zero_f32, -0.0_f32, "expected -0.0");
1503        assert!(
1504            parsed_negative_zero_f32.is_sign_negative(),
1505            "expected negative zero to retain sign"
1506        );
1507
1508        let string_max_value = "3.4028234e38".to_string().to_value();
1509        let parsed_string_max = f32::from_value(&string_max_value, &types::float32())
1510            .expect("valid string at f32 upper boundary must succeed");
1511        assert_eq!(
1512            parsed_string_max, 3.4028234e38_f32,
1513            "expected valid f32 boundary representation for string max"
1514        );
1515
1516        let string_min_value = "-3.4028234e38".to_string().to_value();
1517        let parsed_string_min = f32::from_value(&string_min_value, &types::float32())
1518            .expect("valid string at f32 lower boundary must succeed");
1519        assert_eq!(
1520            parsed_string_min, -3.4028234e38_f32,
1521            "expected valid f32 boundary representation for string min"
1522        );
1523
1524        let string_max_f64_value = "3.4028234e38".to_string().to_value();
1525        let parsed_string_max_f64 = f32::from_value(&string_max_f64_value, &types::float64())
1526            .expect("valid string at f32 upper boundary on FLOAT64 column must succeed");
1527        assert_eq!(
1528            parsed_string_max_f64, 3.4028234e38_f32,
1529            "expected valid f32 upper boundary from FLOAT64 string"
1530        );
1531
1532        let string_min_f64_value = "-3.4028234e38".to_string().to_value();
1533        let parsed_string_min_f64 = f32::from_value(&string_min_f64_value, &types::float64())
1534            .expect("valid string at f32 lower boundary on FLOAT64 column must succeed");
1535        assert_eq!(
1536            parsed_string_min_f64, -3.4028234e38_f32,
1537            "expected valid f32 lower boundary from FLOAT64 string"
1538        );
1539
1540        // Verify gradual underflow to zero
1541        let underflow_f64 = Value::from(1e-50_f64);
1542        let parsed_underflow_f32 = f32::from_value(&underflow_f64, &types::float64())
1543            .expect("underflow f64 must convert to 0.0 without error");
1544        assert_eq!(parsed_underflow_f32, 0.0_f32, "expected 0.0 on underflow");
1545
1546        let string_underflow_value = "1e-50".to_string().to_value();
1547        let parsed_string_underflow = f32::from_value(&string_underflow_value, &types::float32())
1548            .expect("underflow string must convert to 0.0 without error");
1549        assert_eq!(
1550            parsed_string_underflow, 0.0_f32,
1551            "expected 0.0 on string underflow"
1552        );
1553
1554        let string_underflow_f64_value = "1e-50".to_string().to_value();
1555        let parsed_string_underflow_f64 =
1556            f32::from_value(&string_underflow_f64_value, &types::float64())
1557                .expect("underflow string on FLOAT64 column must convert to 0.0 without error");
1558        assert_eq!(
1559            parsed_string_underflow_f64, 0.0_f32,
1560            "expected 0.0 on string underflow from FLOAT64"
1561        );
1562    }
1563
1564    #[test]
1565    fn from_value_f32_non_finite_and_edge_cases() {
1566        // "+Infinity" explicitly accepted across FLOAT32 and FLOAT64
1567        let plus_infinity_value = "+Infinity".to_string().to_value();
1568        let f32_plus_infinity = f32::from_value(&plus_infinity_value, &types::float32())
1569            .expect("+Infinity must succeed for FLOAT32");
1570        assert_eq!(
1571            f32_plus_infinity,
1572            f32::INFINITY,
1573            "expected Infinity for +Infinity"
1574        );
1575
1576        let f32_plus_infinity_f64 = f32::from_value(&plus_infinity_value, &types::float64())
1577            .expect("+Infinity must succeed for FLOAT64");
1578        assert_eq!(
1579            f32_plus_infinity_f64,
1580            f32::INFINITY,
1581            "expected Infinity for +Infinity on FLOAT64"
1582        );
1583
1584        let f64_plus_infinity = f64::from_value(&plus_infinity_value, &types::float64())
1585            .expect("+Infinity must succeed for f64 on FLOAT64");
1586        assert_eq!(
1587            f64_plus_infinity,
1588            f64::INFINITY,
1589            "expected Infinity for +Infinity on f64 FLOAT64"
1590        );
1591
1592        let f64_plus_infinity_from_f32 = f64::from_value(&plus_infinity_value, &types::float32())
1593            .expect("+Infinity must succeed for f64 on FLOAT32");
1594        assert_eq!(
1595            f64_plus_infinity_from_f32,
1596            f64::INFINITY,
1597            "expected Infinity for +Infinity on f64 FLOAT32"
1598        );
1599
1600        // FLOAT64 column non-finite strings into f32
1601        let infinity_value = "Infinity".to_string().to_value();
1602        let f32_infinity_f64 = f32::from_value(&infinity_value, &types::float64())
1603            .expect("Infinity must succeed for FLOAT64");
1604        assert_eq!(
1605            f32_infinity_f64,
1606            f32::INFINITY,
1607            "expected Infinity for f32 on FLOAT64 column"
1608        );
1609
1610        let negative_infinity_value = "-Infinity".to_string().to_value();
1611        let f32_negative_infinity_f64 =
1612            f32::from_value(&negative_infinity_value, &types::float64())
1613                .expect("-Infinity must succeed for FLOAT64");
1614        assert_eq!(
1615            f32_negative_infinity_f64,
1616            f32::NEG_INFINITY,
1617            "expected -Infinity for f32 on FLOAT64 column"
1618        );
1619
1620        let nan_value = "NaN".to_string().to_value();
1621        let f32_nan_f64 =
1622            f32::from_value(&nan_value, &types::float64()).expect("NaN must succeed for FLOAT64");
1623        assert!(
1624            f32_nan_f64.is_nan(),
1625            "expected NaN for f32 on FLOAT64 column"
1626        );
1627
1628        // Non-finite ProtoKind::NumberValue passes through
1629        let number_infinity = Value(ProtoValue {
1630            kind: Some(ProtoKind::NumberValue(f64::INFINITY)),
1631        });
1632        let parsed_number_infinity = f32::from_value(&number_infinity, &types::float64())
1633            .expect("NumberValue(INFINITY) must pass through");
1634        assert_eq!(
1635            parsed_number_infinity,
1636            f32::INFINITY,
1637            "expected Infinity for NumberValue(f64::INFINITY)"
1638        );
1639
1640        let number_negative_infinity = Value(ProtoValue {
1641            kind: Some(ProtoKind::NumberValue(f64::NEG_INFINITY)),
1642        });
1643        let parsed_number_negative_infinity =
1644            f32::from_value(&number_negative_infinity, &types::float64())
1645                .expect("NumberValue(-INFINITY) must pass through");
1646        assert_eq!(
1647            parsed_number_negative_infinity,
1648            f32::NEG_INFINITY,
1649            "expected -Infinity for NumberValue(f64::NEG_INFINITY)"
1650        );
1651
1652        let number_nan = Value(ProtoValue {
1653            kind: Some(ProtoKind::NumberValue(f64::NAN)),
1654        });
1655        let parsed_number_nan = f32::from_value(&number_nan, &types::float64())
1656            .expect("NumberValue(NAN) must pass through");
1657        assert!(
1658            parsed_number_nan.is_nan(),
1659            "expected NaN for NumberValue(f64::NAN)"
1660        );
1661
1662        // Type mismatches
1663        let type_mismatch_int64 = f32::from_value(&42.5f32.to_value(), &types::int64())
1664            .expect_err("f32 must reject INT64 column");
1665        assert_eq!(
1666            type_mismatch_int64.to_string(),
1667            "type mismatch, expected Float32, got Int64",
1668            "expected type mismatch for Int64"
1669        );
1670
1671        let type_mismatch_numeric = f32::from_value(&42.5f32.to_value(), &types::numeric())
1672            .expect_err("f32 must reject NUMERIC column");
1673        assert_eq!(
1674            type_mismatch_numeric.to_string(),
1675            "type mismatch, expected Float32, got Numeric",
1676            "expected type mismatch for Numeric"
1677        );
1678
1679        let type_mismatch_bool = f32::from_value(&42.5f32.to_value(), &types::bool())
1680            .expect_err("f32 must reject BOOL column");
1681        assert_eq!(
1682            type_mismatch_bool.to_string(),
1683            "type mismatch, expected Float32, got Bool",
1684            "expected type mismatch for Bool"
1685        );
1686
1687        // Kind mismatch on FLOAT64 column
1688        let kind_mismatch_error = f32::from_value(&Value::from(true), &types::float64())
1689            .expect_err("f32 must reject boolean Value on FLOAT64 column");
1690        assert!(
1691            matches!(
1692                kind_mismatch_error,
1693                ConvertError::KindMismatch {
1694                    want: Kind::Number,
1695                    got: Kind::Bool,
1696                }
1697            ),
1698            "expected KindMismatch {{ want: Kind::Number, got: Kind::Bool }} for bool Value on FLOAT64, got: {kind_mismatch_error}"
1699        );
1700
1701        // Null checks: Value::null() (NullValue) and Value::default() (None kind)
1702        let not_null_error = f32::from_value(&Value::null(), &types::float64())
1703            .expect_err("f32 must reject null on FLOAT64 column");
1704        assert_eq!(
1705            not_null_error.to_string(),
1706            "expected non-null value, got null",
1707            "expected NotNull error for null on FLOAT64"
1708        );
1709
1710        let default_none_error = f32::from_value(&Value::default(), &types::float64())
1711            .expect_err("f32 must reject Value::default() with None kind on FLOAT64 column");
1712        assert_eq!(
1713            default_none_error.to_string(),
1714            "expected non-null value, got null",
1715            "expected NotNull error for default Value (None kind) on FLOAT64"
1716        );
1717
1718        // Alternative infinity strings across FLOAT32 and FLOAT64
1719        let alternative_infinities = vec![
1720            ("inf", f32::INFINITY, f64::INFINITY),
1721            ("+inf", f32::INFINITY, f64::INFINITY),
1722            ("-inf", f32::NEG_INFINITY, f64::NEG_INFINITY),
1723            ("infinity", f32::INFINITY, f64::INFINITY),
1724            ("+infinity", f32::INFINITY, f64::INFINITY),
1725            ("-infinity", f32::NEG_INFINITY, f64::NEG_INFINITY),
1726            ("INF", f32::INFINITY, f64::INFINITY),
1727            ("+INF", f32::INFINITY, f64::INFINITY),
1728            ("-INF", f32::NEG_INFINITY, f64::NEG_INFINITY),
1729            ("INFINITY", f32::INFINITY, f64::INFINITY),
1730            ("-INFINITY", f32::NEG_INFINITY, f64::NEG_INFINITY),
1731        ];
1732
1733        for (infinity_str, expected_f32, expected_f64) in alternative_infinities {
1734            let value = infinity_str.to_string().to_value();
1735            let parsed_f32_from_f32 = f32::from_value(&value, &types::float32())
1736                .expect("infinity string must parse to f32 on FLOAT32");
1737            assert_eq!(
1738                parsed_f32_from_f32, expected_f32,
1739                "expected {expected_f32} for '{infinity_str}' on FLOAT32"
1740            );
1741
1742            let parsed_f32_from_f64 = f32::from_value(&value, &types::float64())
1743                .expect("infinity string must parse to f32 on FLOAT64");
1744            assert_eq!(
1745                parsed_f32_from_f64, expected_f32,
1746                "expected {expected_f32} for '{infinity_str}' on FLOAT64"
1747            );
1748
1749            let parsed_f64_from_f64 = f64::from_value(&value, &types::float64())
1750                .expect("infinity string must parse to f64 on FLOAT64");
1751            assert_eq!(
1752                parsed_f64_from_f64, expected_f64,
1753                "expected {expected_f64} for '{infinity_str}' on FLOAT64"
1754            );
1755        }
1756
1757        // Non-numeric string on FLOAT64 column
1758        let invalid_string_error =
1759            f32::from_value(&"not-a-number".to_string().to_value(), &types::float64())
1760                .expect_err("f32 must reject arbitrary string representation");
1761        assert!(
1762            format!("{invalid_string_error}").contains("invalid float literal"),
1763            "expected invalid float literal error for f32 on FLOAT64"
1764        );
1765
1766        // Malformed infinity strings
1767        let invalid_inf_error =
1768            f32::from_value(&"invalid inf".to_string().to_value(), &types::float64())
1769                .expect_err("f32 must reject 'invalid inf'");
1770        assert!(
1771            format!("{invalid_inf_error}").contains("invalid float literal"),
1772            "expected invalid float literal error for 'invalid inf', got: {invalid_inf_error}"
1773        );
1774
1775        let inff_error = f32::from_value(&"inff".to_string().to_value(), &types::float64())
1776            .expect_err("f32 must reject 'inff'");
1777        assert!(
1778            format!("{inff_error}").contains("invalid float literal"),
1779            "expected invalid float literal error for 'inff', got: {inff_error}"
1780        );
1781    }
1782
1783    #[test]
1784    fn is_infinity_literal_cases() {
1785        let test_cases = [
1786            ("inf", true),
1787            ("INF", true),
1788            ("Inf", true),
1789            ("+inf", true),
1790            ("-inf", true),
1791            ("infinity", true),
1792            ("Infinity", true),
1793            ("INFINITY", true),
1794            ("+Infinity", true),
1795            ("-Infinity", true),
1796            ("  inf  ", true),
1797            ("  +infinity  ", true),
1798            ("1e300", false),
1799            ("-1e300", false),
1800            ("1e500", false),
1801            ("NaN", false),
1802            ("inff", false),
1803            ("invalid inf", false),
1804            ("0.0", false),
1805        ];
1806
1807        for (input_literal, expected_result) in test_cases {
1808            assert_eq!(
1809                is_infinity_literal(input_literal),
1810                expected_result,
1811                "mismatch for '{input_literal}'"
1812            );
1813        }
1814    }
1815
1816    #[test]
1817    fn from_value_non_finite_float_containers() {
1818        // Option<f64>
1819        let nan_val = "NaN".to_string().to_value();
1820        let opt_nan = Option::<f64>::from_value(&nan_val, &types::float64())
1821            .expect("parse Option<f64> containing NaN");
1822        assert!(
1823            opt_nan.is_some_and(|f| f.is_nan()),
1824            "expected Some(NaN) for Option<f64>"
1825        );
1826
1827        let opt_null = Option::<f64>::from_value(&Value::null(), &types::float64())
1828            .expect("parse Option<f64> containing null");
1829        assert_eq!(opt_null, None, "expected None for null Option<f64>");
1830
1831        // Vec<f64> with non-finite values
1832        let f64_vec = vec![f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 123.5];
1833        let v = f64_vec.to_value();
1834        let parsed_vec = Vec::<f64>::from_value(&v, &types::array(types::float64()))
1835            .expect("parse Vec<f64> with non-finite elements");
1836        assert_eq!(parsed_vec.len(), 4);
1837        assert!(parsed_vec[0].is_nan(), "expected NaN in Vec<f64>[0]");
1838        assert_eq!(
1839            parsed_vec[1],
1840            f64::INFINITY,
1841            "expected Infinity in Vec<f64>[1]"
1842        );
1843        assert_eq!(
1844            parsed_vec[2],
1845            f64::NEG_INFINITY,
1846            "expected -Infinity in Vec<f64>[2]"
1847        );
1848        assert_eq!(parsed_vec[3], 123.5, "expected 123.5 in Vec<f64>[3]");
1849
1850        // Vec<Option<f64>> with non-finite values and None
1851        let opt_f64_vec = vec![
1852            Some(f64::NAN),
1853            None,
1854            Some(f64::INFINITY),
1855            Some(f64::NEG_INFINITY),
1856        ];
1857        let v_opt = opt_f64_vec.to_value();
1858        let parsed_opt_vec =
1859            Vec::<Option<f64>>::from_value(&v_opt, &types::array(types::float64()))
1860                .expect("parse Vec<Option<f64>> with non-finite elements and null");
1861        assert_eq!(parsed_opt_vec.len(), 4);
1862        assert!(
1863            parsed_opt_vec[0].is_some_and(|f| f.is_nan()),
1864            "expected Some(NaN) in Vec<Option<f64>>[0]"
1865        );
1866        assert_eq!(
1867            parsed_opt_vec[1], None,
1868            "expected None in Vec<Option<f64>>[1]"
1869        );
1870        assert_eq!(
1871            parsed_opt_vec[2],
1872            Some(f64::INFINITY),
1873            "expected Some(Infinity) in Vec<Option<f64>>[2]"
1874        );
1875        assert_eq!(
1876            parsed_opt_vec[3],
1877            Some(f64::NEG_INFINITY),
1878            "expected Some(-Infinity) in Vec<Option<f64>>[3]"
1879        );
1880
1881        // Vec<f32> with non-finite values
1882        let f32_vec = vec![f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 12.5f32];
1883        let v_f32 = f32_vec.to_value();
1884        let parsed_f32_vec = Vec::<f32>::from_value(&v_f32, &types::array(types::float32()))
1885            .expect("parse Vec<f32> with non-finite elements");
1886        assert_eq!(parsed_f32_vec.len(), 4);
1887        assert!(parsed_f32_vec[0].is_nan(), "expected NaN in Vec<f32>[0]");
1888        assert_eq!(
1889            parsed_f32_vec[1],
1890            f32::INFINITY,
1891            "expected Infinity in Vec<f32>[1]"
1892        );
1893        assert_eq!(
1894            parsed_f32_vec[2],
1895            f32::NEG_INFINITY,
1896            "expected -Infinity in Vec<f32>[2]"
1897        );
1898        assert_eq!(parsed_f32_vec[3], 12.5, "expected 12.5 in Vec<f32>[3]");
1899    }
1900
1901    #[test]
1902    fn from_value_f32_containers_from_float64() {
1903        // Vec<f32> from ARRAY<FLOAT64>
1904        let float64_for_f32_vec = vec![1.5_f64, 2.5_f64];
1905        let value_float64_for_f32 = float64_for_f32_vec.to_value();
1906        let parsed_float32_from_float64 =
1907            Vec::<f32>::from_value(&value_float64_for_f32, &types::array(types::float64()))
1908                .expect("parse Vec<f32> from ARRAY<FLOAT64>");
1909        assert_eq!(
1910            parsed_float32_from_float64,
1911            vec![1.5_f32, 2.5_f32],
1912            "expected parsed Vec<f32> elements from FLOAT64"
1913        );
1914
1915        // Vec<f32> from ARRAY<FLOAT64> with non-finite values
1916        let float64_non_finite_vec = vec![f64::NAN, f64::INFINITY, f64::NEG_INFINITY];
1917        let value_non_finite = float64_non_finite_vec.to_value();
1918        let parsed_non_finite_f32 =
1919            Vec::<f32>::from_value(&value_non_finite, &types::array(types::float64()))
1920                .expect("parse Vec<f32> with non-finite values from ARRAY<FLOAT64>");
1921        assert_eq!(
1922            parsed_non_finite_f32.len(),
1923            3,
1924            "expected 3 non-finite elements"
1925        );
1926        assert!(
1927            parsed_non_finite_f32[0].is_nan(),
1928            "expected NaN in parsed non-finite Vec<f32>[0]"
1929        );
1930        assert_eq!(
1931            parsed_non_finite_f32[1],
1932            f32::INFINITY,
1933            "expected Infinity in parsed non-finite Vec<f32>[1]"
1934        );
1935        assert_eq!(
1936            parsed_non_finite_f32[2],
1937            f32::NEG_INFINITY,
1938            "expected -Infinity in parsed non-finite Vec<f32>[2]"
1939        );
1940
1941        // Vec<Option<f32>> from ARRAY<FLOAT64> containing null, finite, and non-finite floats
1942        let optional_float64_for_f32_vec = vec![
1943            Some(1.5_f64),
1944            None,
1945            Some(f64::NAN),
1946            Some(f64::INFINITY),
1947            Some(f64::NEG_INFINITY),
1948        ];
1949        let value_optional_float64_for_f32 = optional_float64_for_f32_vec.to_value();
1950        let parsed_optional_f32_from_f64 = Vec::<Option<f32>>::from_value(
1951            &value_optional_float64_for_f32,
1952            &types::array(types::float64()),
1953        )
1954        .expect("parse Vec<Option<f32>> from ARRAY<FLOAT64>");
1955        assert_eq!(
1956            parsed_optional_f32_from_f64.len(),
1957            5,
1958            "expected 5 elements in Vec<Option<f32>>"
1959        );
1960        assert_eq!(
1961            parsed_optional_f32_from_f64[0],
1962            Some(1.5_f32),
1963            "expected Some(1.5) in Vec<Option<f32>>[0]"
1964        );
1965        assert_eq!(
1966            parsed_optional_f32_from_f64[1], None,
1967            "expected None in Vec<Option<f32>>[1]"
1968        );
1969        assert!(
1970            parsed_optional_f32_from_f64[2].is_some_and(|value| value.is_nan()),
1971            "expected Some(NaN) in Vec<Option<f32>>[2]"
1972        );
1973        assert_eq!(
1974            parsed_optional_f32_from_f64[3],
1975            Some(f32::INFINITY),
1976            "expected Some(Infinity) in Vec<Option<f32>>[3]"
1977        );
1978        assert_eq!(
1979            parsed_optional_f32_from_f64[4],
1980            Some(f32::NEG_INFINITY),
1981            "expected Some(-Infinity) in Vec<Option<f32>>[4]"
1982        );
1983
1984        // Vec<Option<f32>> from ARRAY<FLOAT64> with overflowing value
1985        let optional_float64_overflow_vec = vec![Some(1.0_f64), Some(1e300_f64)];
1986        let value_optional_overflow = optional_float64_overflow_vec.to_value();
1987        let optional_overflow_error = Vec::<Option<f32>>::from_value(
1988            &value_optional_overflow,
1989            &types::array(types::float64()),
1990        )
1991        .expect_err("Vec<Option<f32>> must reject overflowing FLOAT64 element");
1992        assert!(
1993            optional_overflow_error
1994                .to_string()
1995                .contains("exceeds f32 range"),
1996            "expected 'exceeds f32 range' in Vec<Option<f32>> error, got: {optional_overflow_error}"
1997        );
1998
1999        // Option<Vec<f32>> from ARRAY<FLOAT64>
2000        let optional_vector_null =
2001            Option::<Vec<f32>>::from_value(&Value::null(), &types::array(types::float64()))
2002                .expect("Option<Vec<f32>> from null ARRAY<FLOAT64> must be Ok(None)");
2003        assert_eq!(
2004            optional_vector_null, None,
2005            "expected None for null Option<Vec<f32>>"
2006        );
2007
2008        let optional_vector_value =
2009            Option::<Vec<f32>>::from_value(&value_float64_for_f32, &types::array(types::float64()))
2010                .expect("Option<Vec<f32>> from populated ARRAY<FLOAT64> must succeed");
2011        assert_eq!(
2012            optional_vector_value,
2013            Some(vec![1.5_f32, 2.5_f32]),
2014            "expected Some([1.5, 2.5]) for Option<Vec<f32>>"
2015        );
2016
2017        // Vec<f32> from ARRAY<FLOAT64> with overflowing value
2018        let float64_overflow_vec = vec![1.0_f64, 1e300_f64];
2019        let value_overflow = float64_overflow_vec.to_value();
2020        let overflow_error =
2021            Vec::<f32>::from_value(&value_overflow, &types::array(types::float64()))
2022                .expect_err("Vec<f32> must reject overflowing FLOAT64 element");
2023        assert!(
2024            overflow_error.to_string().contains("exceeds f32 range"),
2025            "expected 'exceeds f32 range' in Vec<f32> error, got: {overflow_error}"
2026        );
2027
2028        // Option<f32> from FLOAT64
2029        let optional_f32_null = Option::<f32>::from_value(&Value::null(), &types::float64())
2030            .expect("Option<f32> from null FLOAT64 must be Ok(None)");
2031        assert_eq!(
2032            optional_f32_null, None,
2033            "expected None for null Option<f32> from FLOAT64"
2034        );
2035
2036        let optional_f32_value =
2037            Option::<f32>::from_value(&Value::from(42.5_f64), &types::float64())
2038                .expect("Option<f32> from 42.5 FLOAT64 must succeed");
2039        assert_eq!(
2040            optional_f32_value,
2041            Some(42.5_f32),
2042            "expected Some(42.5) for Option<f32> from FLOAT64"
2043        );
2044
2045        let optional_f32_overflow_error =
2046            Option::<f32>::from_value(&Value::from(1e300_f64), &types::float64())
2047                .expect_err("Option<f32> must propagate overflow error");
2048        assert!(
2049            optional_f32_overflow_error
2050                .to_string()
2051                .contains("exceeds f32 range"),
2052            "expected 'exceeds f32 range' in Option<f32> error, got: {optional_f32_overflow_error}"
2053        );
2054    }
2055
2056    #[test]
2057    fn test_from_value_bool() {
2058        let v = true.to_value();
2059        let b = bool::from_value(&v, &types::bool()).unwrap();
2060        assert!(b);
2061    }
2062
2063    #[test]
2064    fn test_from_value_array() {
2065        // String array
2066        let str_array = vec!["one".to_string(), "two".to_string()];
2067        let v = str_array.to_value();
2068        let res = Vec::<String>::from_value(&v, &types::array(types::string()))
2069            .expect("parsed string array");
2070        assert_eq!(res, str_array);
2071
2072        // Int array
2073        let int_array = vec![42i64, 100i64];
2074        let v = int_array.to_value();
2075        let res =
2076            Vec::<i64>::from_value(&v, &types::array(types::int64())).expect("parsed int array");
2077        assert_eq!(res, int_array);
2078
2079        // Bool array
2080        let bool_array = vec![true, false];
2081        let v = bool_array.to_value();
2082        let res =
2083            Vec::<bool>::from_value(&v, &types::array(types::bool())).expect("parsed bool array");
2084        assert_eq!(res, bool_array);
2085
2086        // Float array
2087        let float_array = vec![9.9f64, -2.5f64];
2088        let v = float_array.to_value();
2089        let res = Vec::<f64>::from_value(&v, &types::array(types::float64()))
2090            .expect("parsed float array");
2091        assert_eq!(res, float_array);
2092
2093        // Empty array
2094        let empty_array: Vec<f64> = vec![];
2095        let v = empty_array.to_value();
2096        let res = Vec::<f64>::from_value(&v, &types::array(types::float64()))
2097            .expect("parsed empty array");
2098        assert_eq!(res, empty_array);
2099
2100        // Array with nulls
2101        let opt_array: Vec<Option<i64>> = vec![Some(42), None, Some(100)];
2102        let v = opt_array.to_value();
2103        let res = Vec::<Option<i64>>::from_value(&v, &types::array(types::int64()))
2104            .expect("parsed optional array");
2105        assert_eq!(res, opt_array);
2106
2107        // Null array entirely
2108        let null_array: Option<Vec<i64>> = None;
2109        let v = null_array.to_value();
2110        let res = Option::<Vec<i64>>::from_value(&v, &types::array(types::int64()))
2111            .expect("parsed null array");
2112        assert_eq!(res, null_array);
2113
2114        // Wrong TypeCode test
2115        let err = Vec::<i64>::from_value(&int_array.to_value(), &types::int64())
2116            .expect_err("wrong type code should fail");
2117        assert_eq!(
2118            err.to_string(),
2119            "type mismatch, expected Array, got Int64",
2120            "expected exact TypeMismatch error message"
2121        );
2122
2123        // Array element TypeMismatch test (ARRAY<STRING> column decoded as Vec<i64>)
2124        let err = Vec::<i64>::from_value(&str_array.to_value(), &types::array(types::string()))
2125            .expect_err("element type mismatch should fail");
2126        assert_eq!(
2127            err.to_string(),
2128            "type mismatch, expected Int64, got String",
2129            "expected TypeMismatch for array element type"
2130        );
2131
2132        // Invalid array element values
2133        let err = Vec::<i64>::from_value(&str_array.to_value(), &types::array(types::int64()))
2134            .expect_err("invalid array element values should fail");
2135        assert!(format!("{}", err).contains("cannot convert value, source="));
2136    }
2137
2138    #[test]
2139    fn test_from_value_bytes() {
2140        let bytes: Vec<u8> = vec![1, 2, 3];
2141        let v = bytes.to_value();
2142        let b = Vec::<u8>::from_value(&v, &types::bytes()).unwrap();
2143        assert_eq!(b, bytes);
2144
2145        let v = "invalid base64".to_string().to_value();
2146        let err = Vec::<u8>::from_value(&v, &types::bytes()).unwrap_err();
2147        assert!(format!("{}", err).contains("cannot convert value"));
2148    }
2149
2150    #[test]
2151    fn from_value_decimal() -> Result<(), ConvertError> {
2152        let numeric_type = types::numeric();
2153
2154        let decimal = Decimal::from_str_exact("123.456").expect("valid decimal");
2155        let value = decimal.to_value();
2156        let result = Decimal::from_value(&value, &numeric_type)?;
2157        assert_eq!(result, decimal);
2158
2159        // Fixed-point sign and zero variations
2160        let valid_cases = [
2161            ("+123.456", "123.456"),
2162            ("-123.456", "-123.456"),
2163            ("+1", "1"),
2164            ("-1", "-1"),
2165            ("0", "0"),
2166            ("0.0", "0"),
2167            ("+0", "0"),
2168            ("-0", "0"),
2169            (".1", "0.1"),
2170            ("+.1", "0.1"),
2171            ("-.1", "-0.1"),
2172            ("1.", "1"),
2173            ("+1.", "1"),
2174            ("-1.", "-1"),
2175            ("100000000000000000000.1", "100000000000000000000.1"),
2176        ];
2177
2178        for (input_str, expected_str) in valid_cases {
2179            let value = input_str.to_string().to_value();
2180            let parsed = Decimal::from_value(&value, &numeric_type)
2181                .expect("valid decimal conversion from supported format");
2182            assert_eq!(
2183                parsed,
2184                Decimal::from_str_exact(expected_str).expect("valid decimal"),
2185                "mismatch for {input_str}"
2186            );
2187        }
2188
2189        let value = "invalid decimal".to_string().to_value();
2190        let error =
2191            Decimal::from_value(&value, &numeric_type).expect_err("invalid decimal should fail");
2192        assert!(format!("{error}").contains("cannot convert value"));
2193
2194        Ok(())
2195    }
2196
2197    #[test]
2198    fn from_value_decimal_scientific_notation() -> Result<(), ConvertError> {
2199        let numeric_type = types::numeric();
2200
2201        let valid_scientific_cases = [
2202            // Integer scientific notation
2203            ("1e5", "100000"),
2204            ("+1e5", "100000"),
2205            ("-1e5", "-100000"),
2206            // Positive exponent with explicit plus sign
2207            ("1E+1", "10"),
2208            ("1e+1", "10"),
2209            ("1E1", "10"),
2210            ("01e1", "10"),
2211            ("1e01", "10"),
2212            // Negative exponent
2213            ("1E-1", "0.1"),
2214            ("1e-1", "0.1"),
2215            ("01e-1", "0.1"),
2216            ("1e-01", "0.1"),
2217            // Fractional base with exponent
2218            ("1.e2", "100"),
2219            (".5e2", "50"),
2220            ("+.5e-2", "0.005"),
2221            ("-.5e-2", "-0.005"),
2222            // Fractional base with positive exponent plus sign
2223            (".5e+2", "50"),
2224            ("1.e+2", "100"),
2225            ("-1.e+2", "-100"),
2226            // Zero mantissa in scientific notation
2227            ("0e0", "0"),
2228            ("0e5", "0"),
2229            ("0e-5", "0"),
2230            ("-0e0", "0"),
2231            ("+0e0", "0"),
2232            // Zero exponent in scientific notation
2233            ("1e0", "1"),
2234            ("1E0", "1"),
2235            ("1e+0", "1"),
2236            ("1e-0", "1"),
2237        ];
2238
2239        for (input_str, expected_str) in valid_scientific_cases {
2240            let value = input_str.to_string().to_value();
2241            assert_eq!(
2242                Decimal::from_value(&value, &numeric_type)?,
2243                Decimal::from_str_exact(expected_str).expect("valid decimal"),
2244                "mismatch for {input_str}"
2245            );
2246        }
2247
2248        // Owned value conversion
2249        let value = "2.5e3".to_string().to_value();
2250        assert_eq!(
2251            Decimal::from_owned_value(value, &numeric_type)?,
2252            Decimal::from_str_exact("2500").expect("valid decimal")
2253        );
2254
2255        // Optional decimal with scientific notation and null
2256        let value = "1e5".to_string().to_value();
2257        assert_eq!(
2258            Option::<Decimal>::from_value(&value, &numeric_type)?,
2259            Some(Decimal::from_str_exact("100000").expect("valid decimal"))
2260        );
2261
2262        let value = None::<Decimal>.to_value();
2263        assert_eq!(Option::<Decimal>::from_value(&value, &numeric_type)?, None);
2264
2265        // Array with mixed scientific notation and null elements
2266        let array_type = types::array(types::numeric());
2267        let list_value = vec![Some("1e2".to_string()), None, Some("1e-1".to_string())].to_value();
2268        assert_eq!(
2269            Vec::<Option<Decimal>>::from_value(&list_value, &array_type)?,
2270            vec![
2271                Some(Decimal::from_str_exact("100").expect("valid decimal")),
2272                None,
2273                Some(Decimal::from_str_exact("0.1").expect("valid decimal")),
2274            ]
2275        );
2276
2277        Ok(())
2278    }
2279
2280    #[test]
2281    fn from_value_decimal_scientific_notation_errors() {
2282        let numeric_type = types::numeric();
2283
2284        let invalid_cases = [
2285            "1e",
2286            "1E",
2287            "1e+",
2288            "1e-",
2289            "e1",
2290            "1e5e5",
2291            "1e50",  // Overflow scale exceeds maximum precision
2292            "1e-50", // Underflow scale exceeds maximum precision
2293            // Values exceeding rust_decimal 96-bit mantissa limit (even if valid in Spanner NUMERIC)
2294            // (2^96 - 1 ≈ 7.9228e28, up to 28-29 digits total)
2295            "99999999999999999999999999999.999999999", // 38 digits (max Spanner NUMERIC)
2296            "100000000000000000000.123456789",         // 30 digits
2297            "100000000000000000000000000000",          // 30 integer digits
2298            "8e28",
2299            // PostgreSQL dialect PG_NUMERIC NaN
2300            "NaN",
2301        ];
2302
2303        for invalid_string in invalid_cases {
2304            let value = invalid_string.to_string().to_value();
2305            let error = Decimal::from_value(&value, &numeric_type)
2306                .expect_err("malformed or out-of-range scientific notation should fail");
2307            assert!(
2308                matches!(error, ConvertError::Convert(_)),
2309                "expected ConvertError::Convert for {invalid_string}, got {error:?}"
2310            );
2311        }
2312    }
2313
2314    #[test]
2315    fn test_from_value_date() {
2316        let date = Date::new().set_year(2023).set_month(10).set_day(27);
2317        let value = date.clone().to_value();
2318        let result = Date::from_value(&value, &types::date()).expect("valid date conversion");
2319        assert_eq!(result, date);
2320
2321        let value = "invalid date".to_string().to_value();
2322        let error = Date::from_value(&value, &types::date()).expect_err("invalid date should fail");
2323        assert!(format!("{}", error).contains("cannot convert value"));
2324    }
2325
2326    #[cfg(feature = "unstable-time")]
2327    #[test]
2328    fn test_from_value_time_date() {
2329        let date =
2330            TimeDate::from_calendar_date(2023, Month::October, 27).expect("valid calendar date");
2331        let value = date.to_value();
2332        let result =
2333            TimeDate::from_value(&value, &types::date()).expect("valid time date conversion");
2334        assert_eq!(result, date);
2335
2336        let value = "invalid date".to_string().to_value();
2337        let error =
2338            TimeDate::from_value(&value, &types::date()).expect_err("invalid date should fail");
2339        assert!(format!("{}", error).contains("cannot convert value"));
2340    }
2341
2342    #[cfg(feature = "unstable-time")]
2343    #[test]
2344    fn test_from_value_timestamp() {
2345        let date_time = OffsetDateTime::parse("2023-10-27T10:00:00Z", &Rfc3339)
2346            .expect("valid timestamp format");
2347        let value = date_time.to_value();
2348        let result = OffsetDateTime::from_value(&value, &types::timestamp())
2349            .expect("valid timestamp conversion");
2350        assert_eq!(result, date_time);
2351
2352        let value = "invalid timestamp".to_string().to_value();
2353        let error = OffsetDateTime::from_value(&value, &types::timestamp())
2354            .expect_err("invalid timestamp should fail");
2355        assert!(format!("{}", error).contains("cannot convert value"));
2356    }
2357
2358    #[test]
2359    fn test_from_value_null() {
2360        let v = Option::<i32>::None.to_value();
2361        let res = Option::<i32>::from_value(&v, &types::int64()).expect("valid none option");
2362        assert_eq!(res, None);
2363
2364        let v = Option::<i32>::None.to_value();
2365        let err = i32::from_value(&v, &types::int64()).expect_err("expected non-null error");
2366        assert!(format!("{}", err).contains("expected non-null value, got null"));
2367    }
2368
2369    #[test]
2370    fn test_from_value_system_time() {
2371        let timestamp = Timestamp::clamp(1_698_400_800, 0);
2372        let system_time = SystemTime::try_from(timestamp).expect("valid system time conversion");
2373        let value = system_time.to_value();
2374        let result = SystemTime::from_value(&value, &types::timestamp())
2375            .expect("valid system time conversion");
2376        assert_eq!(result, system_time);
2377
2378        let value = "invalid timestamp".to_string().to_value();
2379        let error = SystemTime::from_value(&value, &types::timestamp())
2380            .expect_err("invalid timestamp should fail");
2381        assert!(format!("{}", error).contains("cannot convert value"));
2382    }
2383
2384    #[test]
2385    fn test_from_value_wkt_timestamp() {
2386        let timestamp = Timestamp::clamp(1_698_400_800, 0);
2387        let value = timestamp.to_value();
2388        let result = Timestamp::from_value(&value, &types::timestamp())
2389            .expect("valid wkt timestamp decoding");
2390        assert_eq!(result, timestamp);
2391
2392        let value = "invalid timestamp".to_string().to_value();
2393        let error = Timestamp::from_value(&value, &types::timestamp())
2394            .expect_err("invalid timestamp should fail");
2395        assert!(format!("{}", error).contains("cannot convert value"));
2396    }
2397
2398    #[test]
2399    fn from_value_type_mismatch() {
2400        let decimal_value = Decimal::from(42).to_value();
2401        let decimal_error =
2402            Decimal::from_value(&decimal_value, &types::int64()).expect_err("type mismatch");
2403        assert_eq!(
2404            decimal_error.to_string(),
2405            "type mismatch, expected Numeric, got Int64",
2406            "expected exact error message for Decimal"
2407        );
2408
2409        let system_time_value = SystemTime::now().to_value();
2410        let system_time_error = SystemTime::from_value(&system_time_value, &types::string())
2411            .expect_err("type mismatch");
2412        assert_eq!(
2413            system_time_error.to_string(),
2414            "type mismatch, expected Timestamp, got String",
2415            "expected exact error message for SystemTime"
2416        );
2417
2418        #[cfg(feature = "unstable-time")]
2419        {
2420            let value = OffsetDateTime::now_utc().to_value();
2421            let error =
2422                OffsetDateTime::from_value(&value, &types::string()).expect_err("type mismatch");
2423            assert_eq!(
2424                error.to_string(),
2425                "type mismatch, expected Timestamp, got String",
2426                "expected exact error message for OffsetDateTime"
2427            );
2428
2429            let value = TimeDate::from_calendar_date(2023, Month::October, 27)
2430                .expect("valid calendar date")
2431                .to_value();
2432            let error = TimeDate::from_value(&value, &types::string()).expect_err("type mismatch");
2433            assert_eq!(
2434                error.to_string(),
2435                "type mismatch, expected Date, got String",
2436                "expected exact error message for TimeDate"
2437            );
2438        }
2439
2440        let date = Date::new()
2441            .set_year(2023)
2442            .set_month(10)
2443            .set_day(27)
2444            .to_value();
2445        let error = Date::from_value(&date, &types::string()).expect_err("type mismatch");
2446        assert_eq!(
2447            error.to_string(),
2448            "type mismatch, expected Date, got String",
2449            "expected exact error message for Date"
2450        );
2451
2452        let bytes_value = vec![1u8].to_value();
2453        let bytes_error =
2454            Vec::<u8>::from_value(&bytes_value, &types::string()).expect_err("type mismatch");
2455        assert_eq!(
2456            bytes_error.to_string(),
2457            "type mismatch, expected Bytes, got String",
2458            "expected exact error message for Vec<u8>"
2459        );
2460
2461        let bool_value = true.to_value();
2462        let bool_error =
2463            bool::from_value(&bool_value, &types::string()).expect_err("type mismatch");
2464        assert_eq!(
2465            bool_error.to_string(),
2466            "type mismatch, expected Bool, got String",
2467            "expected exact error message for bool"
2468        );
2469
2470        let int64_value = 42i64.to_value();
2471        let int64_error =
2472            i64::from_value(&int64_value, &types::string()).expect_err("type mismatch");
2473        assert_eq!(
2474            int64_error.to_string(),
2475            "type mismatch, expected Int64, got String",
2476            "expected exact error message for i64"
2477        );
2478
2479        let int32_error =
2480            i32::from_value(&int64_value, &types::string()).expect_err("type mismatch");
2481        assert_eq!(
2482            int32_error.to_string(),
2483            "type mismatch, expected Int64, got String",
2484            "expected exact error message for i32"
2485        );
2486
2487        // Option<T> must validate schema type even when value is NULL
2488        let null_value = Value(prost_types::Value {
2489            kind: Some(prost_types::value::Kind::NullValue(0)),
2490        });
2491        let error_optional_null = Option::<i64>::from_value(&null_value, &types::string())
2492            .expect_err("Option<i64> must reject STRING column even on NULL");
2493        assert_eq!(
2494            error_optional_null.to_string(),
2495            "type mismatch, expected Int64, got String",
2496            "expected TypeMismatch for Option<i64> on null STRING column"
2497        );
2498        let optional_int64_null = Option::<i64>::from_value(&null_value, &types::int64())
2499            .expect("Option<i64> must accept NULL on INT64 column");
2500        assert_eq!(optional_int64_null, None);
2501
2502        // Option<String> rejects non-string types even on NULL
2503        let error_null_string_on_int = Option::<String>::from_value(&null_value, &types::int64())
2504            .expect_err("Option<String> must reject INT64 column even on NULL");
2505        assert_eq!(
2506            error_null_string_on_int.to_string(),
2507            "type mismatch, expected String, got Int64",
2508            "expected TypeMismatch for Option<String> on null INT64 column"
2509        );
2510
2511        let result_null_string = Option::<String>::from_value(&null_value, &types::string())
2512            .expect("Option<String> accepts NULL on STRING column");
2513        assert_eq!(result_null_string, None);
2514
2515        let result_null_date = Option::<String>::from_value(&null_value, &types::date())
2516            .expect("Option<String> accepts NULL on DATE column");
2517        assert_eq!(result_null_date, None);
2518
2519        let result_null_timestamp = Option::<String>::from_value(&null_value, &types::timestamp())
2520            .expect("Option<String> accepts NULL on TIMESTAMP column");
2521        assert_eq!(result_null_timestamp, None);
2522
2523        let result_null_numeric = Option::<String>::from_value(&null_value, &types::numeric())
2524            .expect("Option<String> accepts NULL on NUMERIC column");
2525        assert_eq!(result_null_numeric, None);
2526
2527        // Option<i64> and Option<i32> accept NULL on ENUM columns
2528        let enum_type = types::proto_enum("customer.Priority");
2529        let result_null_enum_i64 = Option::<i64>::from_value(&null_value, &enum_type)
2530            .expect("Option<i64> accepts NULL on ENUM column");
2531        assert_eq!(result_null_enum_i64, None);
2532
2533        let result_null_enum_i32 = Option::<i32>::from_value(&null_value, &enum_type)
2534            .expect("Option<i32> accepts NULL on ENUM column");
2535        assert_eq!(result_null_enum_i32, None);
2536
2537        // Option<String> rejects ENUM even on NULL
2538        let error_null_string_on_enum = Option::<String>::from_value(&null_value, &enum_type)
2539            .expect_err("Option<String> must reject ENUM column even on NULL");
2540        assert_eq!(
2541            error_null_string_on_enum.to_string(),
2542            "type mismatch, expected String, got Enum",
2543            "expected TypeMismatch for Option<String> on null ENUM column"
2544        );
2545
2546        // Option<String> rejects non-text wire types even on NULL
2547        let error_null_float = Option::<String>::from_value(&null_value, &types::float64())
2548            .expect_err("Option<String> must reject FLOAT64 column even on NULL");
2549        assert_eq!(
2550            error_null_float.to_string(),
2551            "type mismatch, expected String, got Float64",
2552            "expected TypeMismatch for Option<String> on null FLOAT64 column"
2553        );
2554
2555        let error_null_bool = Option::<String>::from_value(&null_value, &types::bool())
2556            .expect_err("Option<String> must reject BOOL column even on NULL");
2557        assert_eq!(
2558            error_null_bool.to_string(),
2559            "type mismatch, expected String, got Bool",
2560            "expected TypeMismatch for Option<String> on null BOOL column"
2561        );
2562
2563        // String::from_value rejects non-string types with TypeMismatch
2564        let error_string_int = String::from_value(&int64_value, &types::int64())
2565            .expect_err("String::from_value rejects INT64 column");
2566        assert_eq!(
2567            error_string_int.to_string(),
2568            "type mismatch, expected String, got Int64",
2569            "expected TypeMismatch for INT64 column"
2570        );
2571
2572        let test_bytes_value = vec![1u8, 2, 3].to_value();
2573        let error_string_bytes = String::from_value(&test_bytes_value, &types::bytes())
2574            .expect_err("String::from_value rejects BYTES column");
2575        assert_eq!(
2576            error_string_bytes.to_string(),
2577            "type mismatch, expected String, got Bytes",
2578            "expected TypeMismatch for BYTES column"
2579        );
2580
2581        // String::from_value rejects non-text wire types like BOOL and FLOAT64 with TypeMismatch
2582        let error_string_bool = String::from_value(&bool_value, &types::bool())
2583            .expect_err("String::from_value rejects BOOL column");
2584        assert_eq!(
2585            error_string_bool.to_string(),
2586            "type mismatch, expected String, got Bool",
2587            "expected TypeMismatch for BOOL column"
2588        );
2589
2590        let float_value = 42.5f64.to_value();
2591        let error_string_float = String::from_value(&float_value, &types::float64())
2592            .expect_err("String::from_value rejects FLOAT64 column");
2593        assert_eq!(
2594            error_string_float.to_string(),
2595            "type mismatch, expected String, got Float64",
2596            "expected TypeMismatch for FLOAT64 column"
2597        );
2598
2599        // String::from_value rejects ENUM column with TypeMismatch
2600        let enum_value = 3i64.to_value();
2601        let error_string_enum = String::from_value(&enum_value, &enum_type)
2602            .expect_err("String::from_value rejects ENUM column");
2603        assert_eq!(
2604            error_string_enum.to_string(),
2605            "type mismatch, expected String, got Enum",
2606            "expected TypeMismatch for ENUM column as String"
2607        );
2608
2609        // i64 and i32 accept ENUM column
2610        let int64_from_enum =
2611            i64::from_value(&enum_value, &enum_type).expect("i64::from_value accepts ENUM column");
2612        assert_eq!(int64_from_enum, 3, "expected i64 value 3 from ENUM");
2613
2614        let int32_from_enum =
2615            i32::from_value(&enum_value, &enum_type).expect("i32::from_value accepts ENUM column");
2616        assert_eq!(int32_from_enum, 3, "expected i32 value 3 from ENUM");
2617
2618        // String::from_value accepts textual types (String, Json, Uuid, Interval)
2619        let string_from_json =
2620            String::from_value(&"{\"a\":1}".to_string().to_value(), &types::json())
2621                .expect("String::from_value accepts JSON column");
2622        assert_eq!(string_from_json, "{\"a\":1}", "expected JSON text");
2623
2624        let string_from_uuid = String::from_value(
2625            &"123e4567-e89b-12d3-a456-426614174000"
2626                .to_string()
2627                .to_value(),
2628            &types::uuid(),
2629        )
2630        .expect("String::from_value accepts UUID column");
2631        assert_eq!(
2632            string_from_uuid, "123e4567-e89b-12d3-a456-426614174000",
2633            "expected UUID text"
2634        );
2635
2636        let string_from_interval =
2637            String::from_value(&"P1Y2M3D".to_string().to_value(), &types::interval())
2638                .expect("String::from_value accepts INTERVAL column");
2639        assert_eq!(string_from_interval, "P1Y2M3D", "expected INTERVAL text");
2640
2641        // String::from_value accepts DATE, NUMERIC, and TIMESTAMP
2642        let string_from_date = String::from_value(&date, &types::date())
2643            .expect("String::from_value accepts DATE column");
2644        assert_eq!(string_from_date, "2023-10-27", "expected DATE string");
2645
2646        let decimal_value = Decimal::from(42).to_value();
2647        let string_from_decimal = String::from_value(&decimal_value, &types::numeric())
2648            .expect("String::from_value accepts NUMERIC column");
2649        assert_eq!(string_from_decimal, "42", "expected NUMERIC string");
2650
2651        let timestamp_value = Timestamp::clamp(1_698_400_800, 0).to_value();
2652        let string_from_timestamp = String::from_value(&timestamp_value, &types::timestamp())
2653            .expect("String::from_value accepts TIMESTAMP column");
2654        assert_eq!(
2655            string_from_timestamp, "2023-10-27T10:00:00.000000000Z",
2656            "expected TIMESTAMP string"
2657        );
2658    }
2659
2660    #[test]
2661    fn test_from_value_wrong_kind() {
2662        let v_bool = true.to_value();
2663        let err = String::from_value(&v_bool, &types::string())
2664            .expect_err("expected non-string kind mismatch for String");
2665        assert!(format!("{}", err).contains("expected String, got Bool"));
2666
2667        let err = Timestamp::from_value(&v_bool, &types::timestamp())
2668            .expect_err("expected non-string kind mismatch for Timestamp");
2669        assert!(format!("{}", err).contains("expected String, got Bool"));
2670
2671        let err = Date::from_value(&v_bool, &types::date())
2672            .expect_err("expected non-string kind mismatch for Date");
2673        assert!(format!("{}", err).contains("expected String, got Bool"));
2674
2675        #[cfg(feature = "unstable-time")]
2676        {
2677            let err = OffsetDateTime::from_value(&v_bool, &types::timestamp())
2678                .expect_err("expected non-string kind mismatch for OffsetDateTime");
2679            assert!(format!("{}", err).contains("expected String, got Bool"));
2680
2681            let err = TimeDate::from_value(&v_bool, &types::date())
2682                .expect_err("expected non-string kind mismatch for TimeDate");
2683            assert!(format!("{}", err).contains("expected String, got Bool"));
2684        }
2685
2686        let v_string = "hello".to_value();
2687        let err = i64::from_value(&v_string, &types::int64())
2688            .expect_err("expected cannot convert value for i64");
2689        assert!(format!("{}", err).contains("cannot convert value"));
2690
2691        let err = i64::from_value(&v_bool, &types::int64())
2692            .expect_err("expected non-string kind mismatch for i64");
2693        assert!(format!("{}", err).contains("expected String, got Bool"));
2694
2695        let err = f64::from_value(&v_bool, &types::float64())
2696            .expect_err("expected non-number kind mismatch for f64");
2697        assert!(format!("{}", err).contains("expected Number, got Bool"));
2698
2699        let err = bool::from_value(&v_string, &types::bool())
2700            .expect_err("expected non-bool kind mismatch for bool");
2701        assert!(format!("{}", err).contains("expected Bool, got String"));
2702    }
2703
2704    #[test]
2705    fn test_from_value_null_errors() {
2706        let v_null = Option::<i32>::None.to_value();
2707
2708        let err = String::from_value(&v_null, &types::string())
2709            .expect_err("expected non-null value, got null");
2710        assert!(format!("{}", err).contains("expected non-null value, got null"));
2711
2712        let err = i64::from_value(&v_null, &types::int64())
2713            .expect_err("expected non-null value, got null");
2714        assert!(format!("{}", err).contains("expected non-null value, got null"));
2715
2716        let err = f64::from_value(&v_null, &types::float64())
2717            .expect_err("expected non-null value, got null");
2718        assert!(format!("{}", err).contains("expected non-null value, got null"));
2719
2720        let err = f32::from_value(&v_null, &types::float32())
2721            .expect_err("expected non-null value, got null");
2722        assert!(format!("{}", err).contains("expected non-null value, got null"));
2723
2724        let err = bool::from_value(&v_null, &types::bool())
2725            .expect_err("expected non-null value, got null");
2726        assert!(format!("{}", err).contains("expected non-null value, got null"));
2727
2728        let err = Decimal::from_value(&v_null, &types::numeric())
2729            .expect_err("expected non-null value, got null");
2730        assert!(format!("{}", err).contains("expected non-null value, got null"));
2731
2732        let err = SystemTime::from_value(&v_null, &types::timestamp())
2733            .expect_err("expected non-null value, got null");
2734        assert!(format!("{}", err).contains("expected non-null value, got null"));
2735
2736        let err = wkt::Timestamp::from_value(&v_null, &types::timestamp())
2737            .expect_err("expected non-null value, got null");
2738        assert!(format!("{}", err).contains("expected non-null value, got null"));
2739
2740        #[cfg(feature = "unstable-time")]
2741        {
2742            let err = OffsetDateTime::from_value(&v_null, &types::timestamp())
2743                .expect_err("expected non-null value, got null");
2744            assert!(format!("{}", err).contains("expected non-null value, got null"));
2745
2746            let err = TimeDate::from_value(&v_null, &types::date())
2747                .expect_err("expected non-null value, got null");
2748            assert!(format!("{}", err).contains("expected non-null value, got null"));
2749        }
2750
2751        let err = Date::from_value(&v_null, &types::date())
2752            .expect_err("expected non-null value, got null");
2753        assert!(format!("{}", err).contains("expected non-null value, got null"));
2754
2755        let err = Vec::<u8>::from_value(&v_null, &types::bytes())
2756            .expect_err("expected non-null value, got null");
2757        assert!(format!("{}", err).contains("expected non-null value, got null"));
2758    }
2759
2760    #[test]
2761    fn from_value_option_missing_kind() {
2762        let value = Value(prost_types::Value { kind: None });
2763        let optional_int32 = Option::<i32>::from_value(&value, &types::int64())
2764            .expect("Option::<i32> on missing kind should produce None");
2765        assert_eq!(optional_int32, None, "expected None for missing kind");
2766
2767        let error = i32::from_value(&value, &types::int64())
2768            .expect_err("non-option i32 on missing kind should fail");
2769        assert!(
2770            matches!(error, ConvertError::NotNull),
2771            "expected NotNull error for missing kind on non-option type"
2772        );
2773    }
2774
2775    // ── JSON value conversion tests ──────────────────────────────────────
2776
2777    #[test]
2778    fn test_from_value_json_primitives() {
2779        // String → JSON string
2780        let v = "hello".to_value();
2781        let j = JsonValue::from_value(&v, &types::string()).unwrap();
2782        assert_eq!(j, JsonValue::String("hello".to_string()));
2783
2784        // INT64 is string-encoded on the wire → stays as JSON string
2785        // (preserves full i64 range without precision loss)
2786        let v = 42i64.to_value();
2787        let j = JsonValue::from_value(&v, &types::int64()).unwrap();
2788        assert_eq!(j, JsonValue::String("42".to_string()));
2789
2790        // Bool → JSON bool
2791        let v = true.to_value();
2792        let j = JsonValue::from_value(&v, &types::bool()).unwrap();
2793        assert_eq!(j, JsonValue::Bool(true));
2794
2795        // Float64 → JSON number
2796        let v = 1.5f64.to_value();
2797        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
2798        assert_eq!(j, serde_json::json!(1.5));
2799
2800        // Null → JSON null
2801        let v: Option<i64> = None;
2802        let j = JsonValue::from_value(&v.to_value(), &types::int64()).unwrap();
2803        assert_eq!(j, JsonValue::Null);
2804
2805        // Missing kind → JSON null
2806        let v = crate::value::Value(prost_types::Value { kind: None });
2807        let j = JsonValue::from_value(&v, &types::string()).unwrap();
2808        assert_eq!(j, JsonValue::Null);
2809    }
2810
2811    #[test]
2812    fn test_from_value_json_string_array() {
2813        let str_array = vec!["a".to_string(), "b".to_string()];
2814        let v = str_array.to_value();
2815        let j = JsonValue::from_value(&v, &types::array(types::string())).unwrap();
2816        assert_eq!(j, serde_json::json!(["a", "b"]));
2817    }
2818
2819    #[test]
2820    fn test_from_value_json_int_array() {
2821        // INT64 array — values are string-encoded
2822        let int_array = vec![10i64, 20i64];
2823        let v = int_array.to_value();
2824        let j = JsonValue::from_value(&v, &types::array(types::int64())).unwrap();
2825        assert_eq!(j, serde_json::json!(["10", "20"]));
2826    }
2827
2828    #[test]
2829    fn test_from_value_json_positional_struct() {
2830        // Type: STRUCT<name STRING, age INT64>
2831        let struct_type = types::create_type(TypeCode::Struct);
2832        let mut inner: model::Type = struct_type.0;
2833        inner.struct_type = Some(Box::new(model::StructType {
2834            fields: vec![
2835                model::struct_type::Field::new()
2836                    .set_name("name")
2837                    .set_type(model::Type {
2838                        code: model::TypeCode::String,
2839                        ..Default::default()
2840                    }),
2841                model::struct_type::Field::new()
2842                    .set_name("age")
2843                    .set_type(model::Type {
2844                        code: model::TypeCode::Int64,
2845                        ..Default::default()
2846                    }),
2847            ],
2848            _unknown_fields: Default::default(),
2849        }));
2850        let spanner_type = Type(inner);
2851
2852        // Wire value: positional ListValue ["Alice", "30"]
2853        let v = crate::value::Value(prost_types::Value {
2854            kind: Some(prost_types::value::Kind::ListValue(
2855                prost_types::ListValue {
2856                    values: vec![
2857                        prost_types::Value {
2858                            kind: Some(prost_types::value::Kind::StringValue("Alice".to_string())),
2859                        },
2860                        prost_types::Value {
2861                            kind: Some(prost_types::value::Kind::StringValue("30".to_string())),
2862                        },
2863                    ],
2864                },
2865            )),
2866        });
2867
2868        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
2869        assert_eq!(j, serde_json::json!({"name": "Alice", "age": "30"}));
2870    }
2871
2872    #[test]
2873    fn test_from_value_json_array_of_structs() {
2874        // Type: ARRAY<STRUCT<a STRING, b INT64>>
2875        let elem_struct = model::Type {
2876            code: model::TypeCode::Struct,
2877            struct_type: Some(Box::new(model::StructType {
2878                fields: vec![
2879                    model::struct_type::Field::new()
2880                        .set_name("a")
2881                        .set_type(model::Type {
2882                            code: model::TypeCode::String,
2883                            ..Default::default()
2884                        }),
2885                    model::struct_type::Field::new()
2886                        .set_name("b")
2887                        .set_type(model::Type {
2888                            code: model::TypeCode::Int64,
2889                            ..Default::default()
2890                        }),
2891                ],
2892                _unknown_fields: Default::default(),
2893            })),
2894            ..Default::default()
2895        };
2896        let array_type = model::Type {
2897            code: model::TypeCode::Array,
2898            array_element_type: Some(Box::new(elem_struct)),
2899            ..Default::default()
2900        };
2901        let spanner_type = Type(array_type);
2902
2903        // Wire: [[x, 1], [y, 2]] — positional structs inside an array
2904        let v = crate::value::Value(prost_types::Value {
2905            kind: Some(prost_types::value::Kind::ListValue(
2906                prost_types::ListValue {
2907                    values: vec![
2908                        prost_types::Value {
2909                            kind: Some(prost_types::value::Kind::ListValue(
2910                                prost_types::ListValue {
2911                                    values: vec![
2912                                        prost_types::Value {
2913                                            kind: Some(prost_types::value::Kind::StringValue(
2914                                                "x".to_string(),
2915                                            )),
2916                                        },
2917                                        prost_types::Value {
2918                                            kind: Some(prost_types::value::Kind::StringValue(
2919                                                "1".to_string(),
2920                                            )),
2921                                        },
2922                                    ],
2923                                },
2924                            )),
2925                        },
2926                        prost_types::Value {
2927                            kind: Some(prost_types::value::Kind::ListValue(
2928                                prost_types::ListValue {
2929                                    values: vec![
2930                                        prost_types::Value {
2931                                            kind: Some(prost_types::value::Kind::StringValue(
2932                                                "y".to_string(),
2933                                            )),
2934                                        },
2935                                        prost_types::Value {
2936                                            kind: Some(prost_types::value::Kind::StringValue(
2937                                                "2".to_string(),
2938                                            )),
2939                                        },
2940                                    ],
2941                                },
2942                            )),
2943                        },
2944                    ],
2945                },
2946            )),
2947        });
2948
2949        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
2950        assert_eq!(
2951            j,
2952            serde_json::json!([
2953                {"a": "x", "b": "1"},
2954                {"a": "y", "b": "2"},
2955            ])
2956        );
2957    }
2958
2959    #[test]
2960    fn test_from_value_json_unexpected_struct_value_errors() {
2961        let spanner_value = crate::value::Value(prost_types::Value {
2962            kind: Some(prost_types::value::Kind::StructValue(
2963                prost_types::Struct::default(),
2964            )),
2965        });
2966        let expected_error = JsonValue::from_value(&spanner_value, &Type::default())
2967            .expect_err("StructValue must produce error in JsonValue::from_value");
2968        assert!(
2969            format!("{expected_error}").contains("unexpected protobuf StructValue"),
2970            "error message should mention unexpected protobuf StructValue, got: {expected_error}"
2971        );
2972    }
2973
2974    #[test]
2975    fn test_from_owned_value_json_unexpected_struct_value_errors() {
2976        let spanner_value = crate::value::Value(prost_types::Value {
2977            kind: Some(prost_types::value::Kind::StructValue(
2978                prost_types::Struct::default(),
2979            )),
2980        });
2981        let expected_error = JsonValue::from_owned_value(spanner_value, &Type::default())
2982            .expect_err("StructValue must produce error in JsonValue::from_owned_value");
2983        assert!(
2984            format!("{expected_error}").contains("unexpected protobuf StructValue"),
2985            "error message should mention unexpected protobuf StructValue, got: {expected_error}"
2986        );
2987    }
2988
2989    #[test]
2990    fn test_from_value_json_spanner_json_column() {
2991        // Spanner JSON column: value arrives as a StringValue containing JSON text
2992        let json_str = r#"{"key": "value", "nested": [1, 2, 3]}"#;
2993        let v = crate::value::Value(prost_types::Value {
2994            kind: Some(prost_types::value::Kind::StringValue(json_str.to_string())),
2995        });
2996
2997        let j = JsonValue::from_value(&v, &types::json())
2998            .expect("parsing JSON string to JsonValue should succeed");
2999        assert_eq!(
3000            j,
3001            serde_json::json!({"key": "value", "nested": [1, 2, 3]}),
3002            "expected JSON object matching input string"
3003        );
3004    }
3005
3006    #[test]
3007    fn test_from_value_json_nested_struct_in_struct() {
3008        // Type: STRUCT<outer_field STRING, inner STRUCT<x INT64, y BOOL>>
3009        let inner_struct_type = model::Type {
3010            code: model::TypeCode::Struct,
3011            struct_type: Some(Box::new(model::StructType {
3012                fields: vec![
3013                    model::struct_type::Field::new()
3014                        .set_name("x")
3015                        .set_type(model::Type {
3016                            code: model::TypeCode::Int64,
3017                            ..Default::default()
3018                        }),
3019                    model::struct_type::Field::new()
3020                        .set_name("y")
3021                        .set_type(model::Type {
3022                            code: model::TypeCode::Bool,
3023                            ..Default::default()
3024                        }),
3025                ],
3026                _unknown_fields: Default::default(),
3027            })),
3028            ..Default::default()
3029        };
3030
3031        let outer_type = model::Type {
3032            code: model::TypeCode::Struct,
3033            struct_type: Some(Box::new(model::StructType {
3034                fields: vec![
3035                    model::struct_type::Field::new()
3036                        .set_name("outer_field")
3037                        .set_type(model::Type {
3038                            code: model::TypeCode::String,
3039                            ..Default::default()
3040                        }),
3041                    model::struct_type::Field::new()
3042                        .set_name("inner")
3043                        .set_type(inner_struct_type),
3044                ],
3045                _unknown_fields: Default::default(),
3046            })),
3047            ..Default::default()
3048        };
3049        let spanner_type = Type(outer_type);
3050
3051        // Wire: positional list ["hello", ["42", true]]
3052        let v = crate::value::Value(prost_types::Value {
3053            kind: Some(prost_types::value::Kind::ListValue(
3054                prost_types::ListValue {
3055                    values: vec![
3056                        prost_types::Value {
3057                            kind: Some(prost_types::value::Kind::StringValue("hello".to_string())),
3058                        },
3059                        prost_types::Value {
3060                            kind: Some(prost_types::value::Kind::ListValue(
3061                                prost_types::ListValue {
3062                                    values: vec![
3063                                        prost_types::Value {
3064                                            kind: Some(prost_types::value::Kind::StringValue(
3065                                                "42".to_string(),
3066                                            )),
3067                                        },
3068                                        prost_types::Value {
3069                                            kind: Some(prost_types::value::Kind::BoolValue(true)),
3070                                        },
3071                                    ],
3072                                },
3073                            )),
3074                        },
3075                    ],
3076                },
3077            )),
3078        });
3079
3080        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3081        assert_eq!(
3082            j,
3083            serde_json::json!({"outer_field": "hello", "inner": {"x": "42", "y": true}})
3084        );
3085    }
3086
3087    #[test]
3088    fn test_from_value_json_null_in_struct() {
3089        // Type: STRUCT<name STRING, value INT64>
3090        let struct_type_model = model::Type {
3091            code: model::TypeCode::Struct,
3092            struct_type: Some(Box::new(model::StructType {
3093                fields: vec![
3094                    model::struct_type::Field::new()
3095                        .set_name("name")
3096                        .set_type(model::Type {
3097                            code: model::TypeCode::String,
3098                            ..Default::default()
3099                        }),
3100                    model::struct_type::Field::new()
3101                        .set_name("value")
3102                        .set_type(model::Type {
3103                            code: model::TypeCode::Int64,
3104                            ..Default::default()
3105                        }),
3106                ],
3107                _unknown_fields: Default::default(),
3108            })),
3109            ..Default::default()
3110        };
3111        let spanner_type = Type(struct_type_model);
3112
3113        // Wire: ["test", null]
3114        let v = crate::value::Value(prost_types::Value {
3115            kind: Some(prost_types::value::Kind::ListValue(
3116                prost_types::ListValue {
3117                    values: vec![
3118                        prost_types::Value {
3119                            kind: Some(prost_types::value::Kind::StringValue("test".to_string())),
3120                        },
3121                        prost_types::Value {
3122                            kind: Some(prost_types::value::Kind::NullValue(0)),
3123                        },
3124                    ],
3125                },
3126            )),
3127        });
3128
3129        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3130        assert_eq!(j, serde_json::json!({"name": "test", "value": null}));
3131    }
3132
3133    #[test]
3134    fn test_from_value_json_nan_becomes_null() {
3135        // NumberValue representations
3136        let v = crate::value::Value(prost_types::Value {
3137            kind: Some(prost_types::value::Kind::NumberValue(f64::NAN)),
3138        });
3139        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3140        assert_eq!(j, JsonValue::Null);
3141
3142        let v = crate::value::Value(prost_types::Value {
3143            kind: Some(prost_types::value::Kind::NumberValue(f64::INFINITY)),
3144        });
3145        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3146        assert_eq!(j, JsonValue::Null);
3147
3148        let v = crate::value::Value(prost_types::Value {
3149            kind: Some(prost_types::value::Kind::NumberValue(f64::NEG_INFINITY)),
3150        });
3151        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3152        assert_eq!(j, JsonValue::Null);
3153
3154        // StringValue representations (as sent by Spanner wire format)
3155        let v = crate::value::Value(prost_types::Value {
3156            kind: Some(prost_types::value::Kind::StringValue("NaN".to_string())),
3157        });
3158        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3159        assert_eq!(j, JsonValue::Null);
3160
3161        let v = crate::value::Value(prost_types::Value {
3162            kind: Some(prost_types::value::Kind::StringValue(
3163                "Infinity".to_string(),
3164            )),
3165        });
3166        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3167        assert_eq!(j, JsonValue::Null);
3168
3169        let v = crate::value::Value(prost_types::Value {
3170            kind: Some(prost_types::value::Kind::StringValue(
3171                "-Infinity".to_string(),
3172            )),
3173        });
3174        let j = JsonValue::from_value(&v, &types::float64()).unwrap();
3175        assert_eq!(j, JsonValue::Null);
3176    }
3177
3178    #[test]
3179    fn from_value_json_float_strings() {
3180        // Valid numeric string representations (as sent by Spanner wire format for floats)
3181        let numeric_string_value = "42.5".to_string().to_value();
3182        let json_from_float64 = JsonValue::from_value(&numeric_string_value, &types::float64())
3183            .expect("valid float64 string to JsonValue");
3184        assert_eq!(
3185            json_from_float64,
3186            json!(42.5),
3187            "expected 42.5 JsonValue number from FLOAT64 string"
3188        );
3189
3190        let json_from_float32 = JsonValue::from_value(&numeric_string_value, &types::float32())
3191            .expect("valid float32 string to JsonValue");
3192        assert_eq!(
3193            json_from_float32,
3194            json!(42.5),
3195            "expected 42.5 JsonValue number from FLOAT32 string"
3196        );
3197
3198        // Invalid numeric string in float column
3199        let invalid_string_value = "not_a_float".to_string().to_value();
3200        let error_invalid_string = JsonValue::from_value(&invalid_string_value, &types::float64())
3201            .expect_err("invalid float string to JsonValue must fail");
3202        assert!(
3203            error_invalid_string
3204                .to_string()
3205                .contains("cannot convert value"),
3206            "expected conversion failure for invalid float string"
3207        );
3208    }
3209
3210    #[test]
3211    fn test_from_value_json_option_wrapping() {
3212        // Option<JsonValue> for a non-null value
3213        let v = "hello".to_value();
3214        let j = Option::<JsonValue>::from_value(&v, &types::string()).unwrap();
3215        assert_eq!(j, Some(JsonValue::String("hello".to_string())));
3216
3217        // Option<JsonValue> for a null value
3218        let v: Option<String> = None;
3219        let j = Option::<JsonValue>::from_value(&v.to_value(), &types::string()).unwrap();
3220        assert_eq!(j, None);
3221    }
3222
3223    #[test]
3224    fn test_from_value_json_empty_struct() {
3225        // Type: STRUCT<> (zero fields)
3226        let struct_type_model = model::Type {
3227            code: model::TypeCode::Struct,
3228            struct_type: Some(Box::new(model::StructType {
3229                fields: vec![],
3230                _unknown_fields: Default::default(),
3231            })),
3232            ..Default::default()
3233        };
3234        let spanner_type = Type(struct_type_model);
3235
3236        // Wire: empty positional list
3237        let v = crate::value::Value(prost_types::Value {
3238            kind: Some(prost_types::value::Kind::ListValue(
3239                prost_types::ListValue { values: vec![] },
3240            )),
3241        });
3242
3243        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3244        assert_eq!(j, serde_json::json!({}));
3245    }
3246
3247    #[test]
3248    fn test_from_value_json_unnamed_fields() {
3249        // Type: STRUCT with unnamed fields (empty string names)
3250        // This is valid in Spanner for SELECT expressions without aliases.
3251        let struct_type_model = model::Type {
3252            code: model::TypeCode::Struct,
3253            struct_type: Some(Box::new(model::StructType {
3254                fields: vec![
3255                    model::struct_type::Field::new()
3256                        .set_name("")
3257                        .set_type(model::Type {
3258                            code: model::TypeCode::String,
3259                            ..Default::default()
3260                        }),
3261                    model::struct_type::Field::new()
3262                        .set_name("")
3263                        .set_type(model::Type {
3264                            code: model::TypeCode::Int64,
3265                            ..Default::default()
3266                        }),
3267                ],
3268                _unknown_fields: Default::default(),
3269            })),
3270            ..Default::default()
3271        };
3272        let spanner_type = Type(struct_type_model);
3273
3274        // Wire: positional values
3275        let v = crate::value::Value(prost_types::Value {
3276            kind: Some(prost_types::value::Kind::ListValue(
3277                prost_types::ListValue {
3278                    values: vec![
3279                        prost_types::Value {
3280                            kind: Some(prost_types::value::Kind::StringValue("val".to_string())),
3281                        },
3282                        prost_types::Value {
3283                            kind: Some(prost_types::value::Kind::StringValue("99".to_string())),
3284                        },
3285                    ],
3286                },
3287            )),
3288        });
3289
3290        // Unnamed fields map to empty-string keys; last write wins for duplicates.
3291        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3292        assert!(j.is_object());
3293        // With duplicate empty keys, the map retains the last inserted value
3294        assert_eq!(
3295            j.as_object().unwrap().get("").unwrap(),
3296            &serde_json::json!("99")
3297        );
3298    }
3299
3300    #[test]
3301    fn test_from_value_json_vec_composition() {
3302        // Vec<JsonValue> uses the existing Vec<T>: FromValue impl
3303        let str_array = vec!["one".to_string(), "two".to_string()];
3304        let v = str_array.to_value();
3305        let res = Vec::<JsonValue>::from_value(&v, &types::array(types::string())).unwrap();
3306        assert_eq!(res.len(), 2);
3307        assert_eq!(res[0], JsonValue::String("one".to_string()));
3308        assert_eq!(res[1], JsonValue::String("two".to_string()));
3309    }
3310
3311    #[test]
3312    fn test_from_value_json_list_without_type_info() {
3313        // ListValue with no type context — falls back to plain array
3314        let v = crate::value::Value(prost_types::Value {
3315            kind: Some(prost_types::value::Kind::ListValue(
3316                prost_types::ListValue {
3317                    values: vec![
3318                        prost_types::Value {
3319                            kind: Some(prost_types::value::Kind::StringValue("a".to_string())),
3320                        },
3321                        prost_types::Value {
3322                            kind: Some(prost_types::value::Kind::BoolValue(false)),
3323                        },
3324                    ],
3325                },
3326            )),
3327        });
3328
3329        let j = JsonValue::from_value(&v, &Type::default()).unwrap();
3330        assert_eq!(j, serde_json::json!(["a", false]));
3331    }
3332
3333    #[test]
3334    fn test_from_value_json_invalid_json_column() {
3335        // Spanner JSON column with invalid JSON text → error
3336        let v = crate::value::Value(prost_types::Value {
3337            kind: Some(prost_types::value::Kind::StringValue(
3338                "not valid json{".to_string(),
3339            )),
3340        });
3341
3342        let err = JsonValue::from_value(&v, &types::json()).unwrap_err();
3343        assert!(format!("{}", err).contains("cannot convert value"));
3344    }
3345
3346    #[test]
3347    fn test_from_value_json_missing_positional_fields_become_null() {
3348        // Type declares 3 fields but wire only has 1 value
3349        let struct_type_model = model::Type {
3350            code: model::TypeCode::Struct,
3351            struct_type: Some(Box::new(model::StructType {
3352                fields: vec![
3353                    model::struct_type::Field::new()
3354                        .set_name("a")
3355                        .set_type(model::Type {
3356                            code: model::TypeCode::String,
3357                            ..Default::default()
3358                        }),
3359                    model::struct_type::Field::new()
3360                        .set_name("b")
3361                        .set_type(model::Type {
3362                            code: model::TypeCode::Int64,
3363                            ..Default::default()
3364                        }),
3365                    model::struct_type::Field::new()
3366                        .set_name("c")
3367                        .set_type(model::Type {
3368                            code: model::TypeCode::Bool,
3369                            ..Default::default()
3370                        }),
3371                ],
3372                _unknown_fields: Default::default(),
3373            })),
3374            ..Default::default()
3375        };
3376        let spanner_type = Type(struct_type_model);
3377
3378        // Wire: only one value present
3379        let v = crate::value::Value(prost_types::Value {
3380            kind: Some(prost_types::value::Kind::ListValue(
3381                prost_types::ListValue {
3382                    values: vec![prost_types::Value {
3383                        kind: Some(prost_types::value::Kind::StringValue("only_a".to_string())),
3384                    }],
3385                },
3386            )),
3387        });
3388
3389        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3390        assert_eq!(j, serde_json::json!({"a": "only_a", "b": null, "c": null}));
3391    }
3392
3393    #[test]
3394    fn test_from_value_json_array_of_json_columns() {
3395        // Type: ARRAY<JSON>
3396        let json_type = model::Type {
3397            code: model::TypeCode::Json,
3398            ..Default::default()
3399        };
3400        let array_type = model::Type {
3401            code: model::TypeCode::Array,
3402            array_element_type: Some(Box::new(json_type)),
3403            ..Default::default()
3404        };
3405        let spanner_type = Type(array_type);
3406
3407        // Wire: array of JSON strings
3408        let v = crate::value::Value(prost_types::Value {
3409            kind: Some(prost_types::value::Kind::ListValue(
3410                prost_types::ListValue {
3411                    values: vec![
3412                        prost_types::Value {
3413                            kind: Some(prost_types::value::Kind::StringValue(
3414                                r#"{"x":1}"#.to_string(),
3415                            )),
3416                        },
3417                        prost_types::Value {
3418                            kind: Some(prost_types::value::Kind::StringValue(
3419                                r#"{"y":2}"#.to_string(),
3420                            )),
3421                        },
3422                    ],
3423                },
3424            )),
3425        });
3426
3427        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3428        assert_eq!(j, serde_json::json!([{"x": 1}, {"y": 2}]));
3429    }
3430
3431    #[test]
3432    fn test_from_value_json_nested_array_in_struct() {
3433        // Type: STRUCT<tags ARRAY<STRING>, id INT64>
3434        let struct_type_model = model::Type {
3435            code: model::TypeCode::Struct,
3436            struct_type: Some(Box::new(model::StructType {
3437                fields: vec![
3438                    model::struct_type::Field::new()
3439                        .set_name("tags")
3440                        .set_type(model::Type {
3441                            code: model::TypeCode::Array,
3442                            array_element_type: Some(Box::new(model::Type {
3443                                code: model::TypeCode::String,
3444                                ..Default::default()
3445                            })),
3446                            ..Default::default()
3447                        }),
3448                    model::struct_type::Field::new()
3449                        .set_name("id")
3450                        .set_type(model::Type {
3451                            code: model::TypeCode::Int64,
3452                            ..Default::default()
3453                        }),
3454                ],
3455                _unknown_fields: Default::default(),
3456            })),
3457            ..Default::default()
3458        };
3459        let spanner_type = Type(struct_type_model);
3460
3461        // Wire: [["foo", "bar"], "42"]
3462        let v = crate::value::Value(prost_types::Value {
3463            kind: Some(prost_types::value::Kind::ListValue(
3464                prost_types::ListValue {
3465                    values: vec![
3466                        prost_types::Value {
3467                            kind: Some(prost_types::value::Kind::ListValue(
3468                                prost_types::ListValue {
3469                                    values: vec![
3470                                        prost_types::Value {
3471                                            kind: Some(prost_types::value::Kind::StringValue(
3472                                                "foo".to_string(),
3473                                            )),
3474                                        },
3475                                        prost_types::Value {
3476                                            kind: Some(prost_types::value::Kind::StringValue(
3477                                                "bar".to_string(),
3478                                            )),
3479                                        },
3480                                    ],
3481                                },
3482                            )),
3483                        },
3484                        prost_types::Value {
3485                            kind: Some(prost_types::value::Kind::StringValue("42".to_string())),
3486                        },
3487                    ],
3488                },
3489            )),
3490        });
3491
3492        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3493        assert_eq!(j, serde_json::json!({"tags": ["foo", "bar"], "id": "42"}));
3494    }
3495
3496    #[test]
3497    fn test_from_value_json_recursion_depth_limit() {
3498        // Build a deeply nested ListValue (65 levels deep) to exceed MAX_RECURSION_DEPTH
3499        let mut inner = prost_types::Value {
3500            kind: Some(prost_types::value::Kind::BoolValue(true)),
3501        };
3502        for _ in 0..65 {
3503            inner = prost_types::Value {
3504                kind: Some(prost_types::value::Kind::ListValue(
3505                    prost_types::ListValue {
3506                        values: vec![inner],
3507                    },
3508                )),
3509            };
3510        }
3511        let v = crate::value::Value(inner);
3512
3513        let err = JsonValue::from_value(&v, &Type::default()).unwrap_err();
3514        assert!(format!("{}", err).contains("nesting depth exceeded"));
3515    }
3516
3517    #[test]
3518    fn test_from_value_json_array_without_element_type() {
3519        // Type: ARRAY but array_element_type is None
3520        let array_type = model::Type {
3521            code: model::TypeCode::Array,
3522            array_element_type: None,
3523            ..Default::default()
3524        };
3525        let spanner_type = Type(array_type);
3526
3527        // Wire: array of strings
3528        let v = crate::value::Value(prost_types::Value {
3529            kind: Some(prost_types::value::Kind::ListValue(
3530                prost_types::ListValue {
3531                    values: vec![prost_types::Value {
3532                        kind: Some(prost_types::value::Kind::StringValue("hello".to_string())),
3533                    }],
3534                },
3535            )),
3536        });
3537
3538        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3539        assert_eq!(j, serde_json::json!(["hello"]));
3540    }
3541
3542    #[test]
3543    fn test_from_value_json_struct_with_missing_field_type() {
3544        // Type: STRUCT where field "a" has no type metadata
3545        let struct_type_model = model::Type {
3546            code: model::TypeCode::Struct,
3547            struct_type: Some(Box::new(model::StructType {
3548                fields: vec![
3549                    model::struct_type::Field::new().set_name("a"), // type is None
3550                ],
3551                _unknown_fields: Default::default(),
3552            })),
3553            ..Default::default()
3554        };
3555        let spanner_type = Type(struct_type_model);
3556
3557        // Wire: positional list ["hello"]
3558        let v = crate::value::Value(prost_types::Value {
3559            kind: Some(prost_types::value::Kind::ListValue(
3560                prost_types::ListValue {
3561                    values: vec![prost_types::Value {
3562                        kind: Some(prost_types::value::Kind::StringValue("hello".to_string())),
3563                    }],
3564                },
3565            )),
3566        });
3567
3568        let j = JsonValue::from_value(&v, &spanner_type).unwrap();
3569        assert_eq!(j, serde_json::json!({"a": "hello"}));
3570    }
3571
3572    #[test]
3573    fn convert_error_auto_traits() {
3574        use std::fmt::Debug;
3575        static_assertions::assert_impl_all!(ConvertError: Clone, Debug, Send, Sync);
3576    }
3577
3578    #[test]
3579    fn convert_error_extract() {
3580        let error = Error::deser(ConvertError::NotNull);
3581        let extracted = ConvertError::extract(&error).expect("should extract ConvertError");
3582        assert!(
3583            matches!(extracted, ConvertError::NotNull),
3584            "expected NotNull variant"
3585        );
3586
3587        let type_conversion_error = Error::deser(RowError::type_conversion(
3588            "col_a",
3589            TypeCode::String,
3590            ConvertError::type_mismatch(TypeCode::Int64, TypeCode::String),
3591        ));
3592        let extracted_from_type_conversion = ConvertError::extract(&type_conversion_error)
3593            .expect("should extract ConvertError from RowError::TypeConversion");
3594        assert_eq!(
3595            extracted_from_type_conversion.to_string(),
3596            "type mismatch, expected Int64, got String",
3597            "expected TypeMismatch extracted from TypeConversion"
3598        );
3599
3600        let other_error = Error::deser(RowError::column_not_found("col"));
3601        assert!(
3602            ConvertError::extract(&other_error).is_none(),
3603            "should return None for non-ConvertError"
3604        );
3605
3606        use google_cloud_rpc::model::Status;
3607        let no_source_error = Error::service(Status::default().into());
3608        assert!(
3609            ConvertError::extract(&no_source_error).is_none(),
3610            "should return None when error has no source"
3611        );
3612    }
3613
3614    #[test]
3615    fn from_value_for_value() {
3616        let original_value = 42i64.to_value();
3617        let converted = Value::from_value(&original_value, &types::int64())
3618            .expect("Value::from_value should succeed");
3619        assert_eq!(
3620            converted, original_value,
3621            "expected Value::from_value to clone value"
3622        );
3623    }
3624
3625    #[test]
3626    fn convert_error_traits_and_display() {
3627        let kind_error = ConvertError::KindMismatch {
3628            want: Kind::String,
3629            got: Kind::Bool,
3630        };
3631        assert_eq!(
3632            kind_error.to_string(),
3633            "expected String, got Bool",
3634            "expected kind mismatch display format"
3635        );
3636        let cloned_kind_error = kind_error.clone();
3637        assert_eq!(
3638            cloned_kind_error.to_string(),
3639            kind_error.to_string(),
3640            "expected cloned KindMismatch display to match original"
3641        );
3642
3643        let type_error = ConvertError::TypeMismatch {
3644            want: TypeCode::Int64,
3645            got: TypeCode::String,
3646        };
3647        assert_eq!(
3648            type_error.to_string(),
3649            "type mismatch, expected Int64, got String",
3650            "expected type mismatch display format"
3651        );
3652        let cloned_type_error = type_error.clone();
3653        assert_eq!(
3654            cloned_type_error.to_string(),
3655            type_error.to_string(),
3656            "expected cloned TypeMismatch display to match original"
3657        );
3658
3659        let not_null_error = ConvertError::NotNull;
3660        assert_eq!(
3661            not_null_error.to_string(),
3662            "expected non-null value, got null",
3663            "expected not null display format"
3664        );
3665        let cloned_not_null = not_null_error.clone();
3666        assert_eq!(
3667            cloned_not_null.to_string(),
3668            not_null_error.to_string(),
3669            "expected cloned NotNull display to match original"
3670        );
3671
3672        let message_str_error = ConvertError::message("custom string error");
3673        let message_string_error = ConvertError::message("custom string error".to_string());
3674        assert_eq!(
3675            message_str_error.to_string(),
3676            message_string_error.to_string(),
3677            "expected ConvertError::message(&str) display to match ConvertError::message(String)"
3678        );
3679        let cloned_message = message_str_error.clone();
3680        assert_eq!(
3681            cloned_message.to_string(),
3682            message_str_error.to_string(),
3683            "expected cloned Convert error display to match original"
3684        );
3685        assert!(
3686            message_str_error
3687                .to_string()
3688                .contains("custom string error"),
3689            "expected display to contain custom message"
3690        );
3691    }
3692
3693    #[test]
3694    fn convert_error_custom_downcast() {
3695        use std::io::Error as IoError;
3696
3697        #[derive(Debug, thiserror::Error, PartialEq, Eq)]
3698        #[error("custom validation code {code}")]
3699        struct CustomValidationError {
3700            code: u32,
3701        }
3702
3703        let original_error = CustomValidationError { code: 404 };
3704        let convert_error = ConvertError::custom(original_error);
3705
3706        // Verify downcasting via ConvertError::Convert variant pattern matching
3707        let extract_shared = |error: &ConvertError| match error {
3708            ConvertError::Convert(shared) => Some(Arc::clone(shared)),
3709            _ => None,
3710        };
3711        let shared_error =
3712            extract_shared(&convert_error).expect("expected ConvertError::Convert variant");
3713        let downcasted_from_shared = (*shared_error).downcast_ref::<CustomValidationError>();
3714        assert_eq!(
3715            downcasted_from_shared,
3716            Some(&CustomValidationError { code: 404 }),
3717            "expected downcast_ref on SharedError to recover CustomValidationError"
3718        );
3719
3720        let wrong_type_error = (*shared_error).downcast_ref::<IoError>();
3721        assert!(
3722            wrong_type_error.is_none(),
3723            "expected downcast_ref to return None for non-matching type"
3724        );
3725
3726        let non_convert_error = ConvertError::NotNull;
3727        assert!(
3728            extract_shared(&non_convert_error).is_none(),
3729            "expected None for non-Convert variant"
3730        );
3731    }
3732
3733    #[test]
3734    fn from_value_kind_mismatch_branches() {
3735        let bool_value = true.to_value();
3736
3737        let decimal_error = Decimal::from_value(&bool_value, &types::numeric())
3738            .expect_err("Decimal must reject bool wire kind with KindMismatch");
3739        assert_eq!(
3740            decimal_error.to_string(),
3741            "expected String, got Bool",
3742            "expected KindMismatch for Decimal on bool kind"
3743        );
3744
3745        let float32_error = f32::from_value(&bool_value, &types::float32())
3746            .expect_err("f32 must reject bool wire kind with KindMismatch");
3747        assert_eq!(
3748            float32_error.to_string(),
3749            "expected Number, got Bool",
3750            "expected KindMismatch for f32 on bool kind"
3751        );
3752
3753        let bytes_error = Vec::<u8>::from_value(&bool_value, &types::bytes())
3754            .expect_err("Vec<u8> must reject bool wire kind with KindMismatch");
3755        assert_eq!(
3756            bytes_error.to_string(),
3757            "expected String, got Bool",
3758            "expected KindMismatch for Vec<u8> on bool kind"
3759        );
3760
3761        let array_error = Vec::<String>::from_value(&bool_value, &types::array(types::string()))
3762            .expect_err("Vec<T> must reject bool wire kind with KindMismatch");
3763        assert_eq!(
3764            array_error.to_string(),
3765            "expected List, got Bool",
3766            "expected KindMismatch for Vec<T> on bool kind"
3767        );
3768    }
3769
3770    #[test]
3771    fn from_value_array_missing_element_type() {
3772        let malformed_type = Type::from(model::Type {
3773            code: model::TypeCode::Array,
3774            array_element_type: None,
3775            ..Default::default()
3776        });
3777        let list_value = Value(prost_types::Value {
3778            kind: Some(prost_types::value::Kind::ListValue(
3779                prost_types::ListValue {
3780                    values: vec![prost_types::Value {
3781                        kind: Some(prost_types::value::Kind::StringValue("test".to_string())),
3782                    }],
3783                },
3784            )),
3785        });
3786        let element_type_error = Vec::<String>::from_value(&list_value, &malformed_type)
3787            .expect_err("array missing element type must fail");
3788        assert!(
3789            element_type_error
3790                .to_string()
3791                .contains("Array type missing element type"),
3792            "expected 'Array type missing element type' in error message"
3793        );
3794    }
3795
3796    #[test]
3797    fn string_from_value_rejects_array_and_struct() {
3798        let array_type = types::array(types::string());
3799        let string_value = "hello".to_string().to_value();
3800        let array_error = String::from_value(&string_value, &array_type)
3801            .expect_err("String::from_value must reject Array column type");
3802        assert_eq!(
3803            array_error.to_string(),
3804            "type mismatch, expected String, got Array",
3805            "expected TypeMismatch when reading Array column as String"
3806        );
3807
3808        let struct_type = types::create_type(TypeCode::Struct);
3809        let struct_error = String::from_value(&string_value, &struct_type)
3810            .expect_err("String::from_value must reject Struct column type");
3811        assert_eq!(
3812            struct_error.to_string(),
3813            "type mismatch, expected String, got Struct",
3814            "expected TypeMismatch when reading Struct column as String"
3815        );
3816    }
3817
3818    #[test]
3819    fn from_value_none_kind_null_contract() {
3820        let none_kind_value = Value::default(); // kind: None
3821        assert!(none_kind_value.is_null(), "Value::default() must be null");
3822
3823        // Option<T> should succeed and return None for kind: None
3824        let optional_int64 = Option::<i64>::from_value(&none_kind_value, &types::int64())
3825            .expect("Option<i64> should succeed for kind: None");
3826        assert_eq!(optional_int64, None, "expected None for Option<i64>");
3827
3828        let optional_string = Option::<String>::from_value(&none_kind_value, &types::string())
3829            .expect("Option<String> should succeed for kind: None");
3830        assert_eq!(optional_string, None, "expected None for Option<String>");
3831
3832        // Non-Option types must return ConvertError::NotNull for kind: None
3833        let string_error = String::from_value(&none_kind_value, &types::string())
3834            .expect_err("String must reject kind: None with NotNull");
3835        assert!(
3836            matches!(string_error, ConvertError::NotNull),
3837            "expected NotNull for String"
3838        );
3839
3840        let int64_error = i64::from_value(&none_kind_value, &types::int64())
3841            .expect_err("i64 must reject kind: None with NotNull");
3842        assert!(
3843            matches!(int64_error, ConvertError::NotNull),
3844            "expected NotNull for i64"
3845        );
3846
3847        let int32_error = i32::from_value(&none_kind_value, &types::int64())
3848            .expect_err("i32 must reject kind: None with NotNull");
3849        assert!(
3850            matches!(int32_error, ConvertError::NotNull),
3851            "expected NotNull for i32"
3852        );
3853
3854        let bool_error = bool::from_value(&none_kind_value, &types::bool())
3855            .expect_err("bool must reject kind: None with NotNull");
3856        assert!(
3857            matches!(bool_error, ConvertError::NotNull),
3858            "expected NotNull for bool"
3859        );
3860
3861        let float64_error = f64::from_value(&none_kind_value, &types::float64())
3862            .expect_err("f64 must reject kind: None with NotNull");
3863        assert!(
3864            matches!(float64_error, ConvertError::NotNull),
3865            "expected NotNull for f64"
3866        );
3867
3868        let float32_error = f32::from_value(&none_kind_value, &types::float32())
3869            .expect_err("f32 must reject kind: None with NotNull");
3870        assert!(
3871            matches!(float32_error, ConvertError::NotNull),
3872            "expected NotNull for f32"
3873        );
3874
3875        let decimal_error = Decimal::from_value(&none_kind_value, &types::numeric())
3876            .expect_err("Decimal must reject kind: None with NotNull");
3877        assert!(
3878            matches!(decimal_error, ConvertError::NotNull),
3879            "expected NotNull for Decimal"
3880        );
3881
3882        let bytes_error = Vec::<u8>::from_value(&none_kind_value, &types::bytes())
3883            .expect_err("Vec<u8> must reject kind: None with NotNull");
3884        assert!(
3885            matches!(bytes_error, ConvertError::NotNull),
3886            "expected NotNull for Vec<u8>"
3887        );
3888
3889        let vector_error =
3890            Vec::<String>::from_value(&none_kind_value, &types::array(types::string()))
3891                .expect_err("Vec<T> must reject kind: None with NotNull");
3892        assert!(
3893            matches!(vector_error, ConvertError::NotNull),
3894            "expected NotNull for Vec<T>"
3895        );
3896
3897        let timestamp_error = Timestamp::from_value(&none_kind_value, &types::timestamp())
3898            .expect_err("Timestamp must reject kind: None with NotNull");
3899        assert!(
3900            matches!(timestamp_error, ConvertError::NotNull),
3901            "expected NotNull for Timestamp"
3902        );
3903
3904        let date_error = Date::from_value(&none_kind_value, &types::date())
3905            .expect_err("Date must reject kind: None with NotNull");
3906        assert!(
3907            matches!(date_error, ConvertError::NotNull),
3908            "expected NotNull for Date"
3909        );
3910    }
3911
3912    #[test]
3913    fn from_owned_value_string() {
3914        let value = "hello".to_value();
3915        let string_type = types::string();
3916        let string_value =
3917            String::from_owned_value(value, &string_type).expect("valid string value");
3918        assert_eq!(string_value, "hello", "expected string 'hello'");
3919
3920        // Null value check
3921        let null_value = Value::null();
3922        let null_error = String::from_owned_value(null_value, &string_type)
3923            .expect_err("null value must fail for String");
3924        assert!(
3925            matches!(null_error, ConvertError::NotNull),
3926            "expected NotNull error"
3927        );
3928
3929        // Kind mismatch check
3930        let bool_value = true.to_value();
3931        let mismatch_error = String::from_owned_value(bool_value, &string_type)
3932            .expect_err("bool value must fail for String");
3933        assert!(
3934            matches!(mismatch_error, ConvertError::KindMismatch { .. }),
3935            "expected KindMismatch error"
3936        );
3937
3938        // Float type check
3939        let float_string_value = "1.5".to_value();
3940        let float_type = types::float64();
3941        let float_error = String::from_owned_value(float_string_value, &float_type)
3942            .expect_err("float column must not decode as String");
3943        assert!(
3944            matches!(
3945                float_error,
3946                ConvertError::TypeMismatch {
3947                    want: TypeCode::String,
3948                    got: TypeCode::Float64,
3949                }
3950            ),
3951            "expected TypeMismatch error for float column"
3952        );
3953    }
3954
3955    #[test]
3956    fn from_owned_value_option() {
3957        let null_value = Value::null();
3958        let string_type = types::string();
3959        let optional_null: Option<String> =
3960            Option::from_owned_value(null_value, &string_type).expect("valid optional null");
3961        assert_eq!(optional_null, None, "expected None for null value");
3962
3963        let present_value = "present".to_value();
3964        let optional_present: Option<String> =
3965            Option::from_owned_value(present_value, &string_type).expect("valid optional string");
3966        assert_eq!(
3967            optional_present,
3968            Some("present".to_string()),
3969            "expected Some('present')"
3970        );
3971    }
3972
3973    #[test]
3974    fn from_owned_value_value() {
3975        let value = "raw".to_value();
3976        let string_type = types::string();
3977        let returned_value =
3978            Value::from_owned_value(value.clone(), &string_type).expect("valid Value conversion");
3979        assert_eq!(returned_value, value, "expected identical Value");
3980    }
3981
3982    #[test]
3983    fn from_owned_value_vector() {
3984        let array_type = types::array(types::string());
3985        let list_value = vec!["one".to_string(), "two".to_string()].to_value();
3986        let string_vector: Vec<String> =
3987            Vec::from_owned_value(list_value, &array_type).expect("valid Vec<String>");
3988        assert_eq!(
3989            string_vector,
3990            vec!["one".to_string(), "two".to_string()],
3991            "expected matching vector of strings"
3992        );
3993
3994        // Null value check
3995        let null_value = Value::null();
3996        let null_error = Vec::<String>::from_owned_value(null_value, &array_type)
3997            .expect_err("null value must fail for Vec<String>");
3998        assert!(
3999            matches!(null_error, ConvertError::NotNull),
4000            "expected NotNull error"
4001        );
4002
4003        // Not an array type
4004        let string_type = types::string();
4005        let non_array_value = vec!["one".to_string()].to_value();
4006        let type_error = Vec::<String>::from_owned_value(non_array_value, &string_type)
4007            .expect_err("non-array type must fail");
4008        assert!(
4009            matches!(
4010                type_error,
4011                ConvertError::TypeMismatch {
4012                    want: TypeCode::Array,
4013                    got: TypeCode::String,
4014                }
4015            ),
4016            "expected TypeMismatch for non-array type"
4017        );
4018    }
4019
4020    #[test]
4021    fn from_owned_value_json() {
4022        let json_type = types::json();
4023        let json_string_value = "{\"key\":\"value\"}".to_value();
4024        let parsed_json =
4025            JsonValue::from_owned_value(json_string_value, &json_type).expect("valid JSON value");
4026        assert_eq!(
4027            parsed_json,
4028            serde_json::json!({"key": "value"}),
4029            "expected parsed JSON object"
4030        );
4031    }
4032
4033    #[test]
4034    fn from_owned_value_default_delegation() {
4035        let int_value = 123_i64.to_value();
4036        let int_type = types::int64();
4037        let integer = i64::from_owned_value(int_value, &int_type).expect("valid i64");
4038        assert_eq!(integer, 123, "expected i64 value 123");
4039
4040        let bool_value = true.to_value();
4041        let bool_type = types::bool();
4042        let boolean = bool::from_owned_value(bool_value, &bool_type).expect("valid bool");
4043        assert!(boolean, "expected boolean value true");
4044    }
4045
4046    #[test]
4047    fn from_value_value() {
4048        let value = "raw".to_value();
4049        let string_type = types::string();
4050        let returned_value =
4051            Value::from_value(&value, &string_type).expect("valid Value conversion");
4052        assert_eq!(returned_value, value, "expected identical Value");
4053    }
4054
4055    #[test]
4056    fn from_owned_value_vector_kind_mismatch() {
4057        let array_type = types::array(types::string());
4058        let non_list_value = 42_i64.to_value();
4059        let type_error = Vec::<String>::from_owned_value(non_list_value, &array_type)
4060            .expect_err("non-list value with array type must fail with KindMismatch");
4061        assert!(
4062            matches!(type_error, ConvertError::KindMismatch { .. }),
4063            "expected KindMismatch for non-list value with array type"
4064        );
4065    }
4066
4067    #[test]
4068    fn from_owned_value_json_struct_without_metadata() {
4069        let struct_type_without_metadata = Type(model::Type {
4070            code: model::TypeCode::Struct,
4071            struct_type: None,
4072            ..Default::default()
4073        });
4074        let list_value = Value(prost_types::Value {
4075            kind: Some(prost_types::value::Kind::ListValue(
4076                prost_types::ListValue {
4077                    values: vec![prost_types::Value {
4078                        kind: Some(prost_types::value::Kind::StringValue(
4079                            "anonymous".to_string(),
4080                        )),
4081                    }],
4082                },
4083            )),
4084        });
4085        let json_value = JsonValue::from_owned_value(list_value, &struct_type_without_metadata)
4086            .expect("valid conversion to JSON array fallback");
4087        assert_eq!(
4088            json_value,
4089            serde_json::json!(["anonymous"]),
4090            "expected positional array fallback when struct metadata is missing"
4091        );
4092    }
4093
4094    #[test]
4095    fn from_owned_value_option_null() {
4096        let null_value = Value(prost_types::Value {
4097            kind: Some(ProtoKind::NullValue(0)),
4098        });
4099        let string_type = types::string();
4100        let optional_value: Option<String> = Option::from_owned_value(null_value, &string_type)
4101            .expect("sql null value should convert to None");
4102        assert_eq!(optional_value, None, "expected None for sql null");
4103    }
4104
4105    #[test]
4106    fn from_owned_value_option_missing_kind() {
4107        let missing_kind_value = Value(prost_types::Value { kind: None });
4108        let string_type = types::string();
4109        let optional_value: Option<String> =
4110            Option::from_owned_value(missing_kind_value, &string_type)
4111                .expect("Option::<String> on missing kind should produce None");
4112        assert_eq!(optional_value, None, "expected None for missing kind");
4113
4114        let missing_kind_value = Value(prost_types::Value { kind: None });
4115        let error = String::from_owned_value(missing_kind_value, &string_type)
4116            .expect_err("non-option String on missing kind should fail");
4117        assert!(
4118            matches!(error, ConvertError::NotNull),
4119            "expected NotNull error for missing kind on non-option type"
4120        );
4121    }
4122
4123    #[test]
4124    fn from_owned_value_option_error() {
4125        let bool_value = true.to_value();
4126        let string_type = types::string();
4127        let error = Option::<String>::from_owned_value(bool_value, &string_type)
4128            .expect_err("type mismatch inside Option must return error");
4129        assert!(
4130            matches!(error, ConvertError::KindMismatch { .. }),
4131            "expected KindMismatch error"
4132        );
4133    }
4134
4135    #[test]
4136    fn from_value_option_unexpected_struct_value_fails() {
4137        let struct_value = Value(prost_types::Value {
4138            kind: Some(ProtoKind::StructValue(prost_types::Struct::default())),
4139        });
4140        let string_type = types::string();
4141        let error = Option::<String>::from_value(&struct_value, &string_type)
4142            .expect_err("unexpected StructValue must fail for Option<String>");
4143        assert!(
4144            matches!(
4145                error,
4146                ConvertError::KindMismatch {
4147                    want: Kind::String,
4148                    got: Kind::Unknown,
4149                }
4150            ),
4151            "expected KindMismatch with got: Kind::Unknown, got: {error}"
4152        );
4153
4154        let json_err = Option::<JsonValue>::from_value(&struct_value, &Type::default())
4155            .expect_err("unexpected StructValue must fail for Option<JsonValue>");
4156        assert!(
4157            format!("{json_err}").contains("unexpected protobuf StructValue"),
4158            "expected error to mention unexpected protobuf StructValue"
4159        );
4160    }
4161
4162    #[test]
4163    fn from_owned_value_vector_element_error() {
4164        let array_type = types::array(types::int64());
4165        let list_value = Value(prost_types::Value {
4166            kind: Some(prost_types::value::Kind::ListValue(
4167                prost_types::ListValue {
4168                    values: vec![
4169                        prost_types::Value {
4170                            kind: Some(prost_types::value::Kind::StringValue("42".to_string())),
4171                        },
4172                        prost_types::Value {
4173                            kind: Some(prost_types::value::Kind::StringValue(
4174                                "not_a_number".to_string(),
4175                            )),
4176                        },
4177                    ],
4178                },
4179            )),
4180        });
4181        let error = Vec::<i64>::from_owned_value(list_value, &array_type)
4182            .expect_err("invalid inner element must fail vector conversion");
4183        assert!(
4184            matches!(error, ConvertError::Convert(_)),
4185            "expected Convert error for invalid integer element"
4186        );
4187    }
4188
4189    #[test]
4190    fn from_owned_value_json_list_struct() {
4191        let struct_type_model = model::Type {
4192            code: model::TypeCode::Struct,
4193            struct_type: Some(Box::new(model::StructType {
4194                fields: vec![
4195                    model::struct_type::Field::new()
4196                        .set_name("id")
4197                        .set_type(types::int64().0),
4198                    model::struct_type::Field::new()
4199                        .set_name("name")
4200                        .set_type(types::string().0),
4201                ],
4202                ..Default::default()
4203            })),
4204            ..Default::default()
4205        };
4206        let struct_type = Type(struct_type_model);
4207        // Spanner wire format sends structs as ListValue
4208        let wire_struct = Value(prost_types::Value {
4209            kind: Some(prost_types::value::Kind::ListValue(
4210                prost_types::ListValue {
4211                    values: vec![
4212                        prost_types::Value {
4213                            kind: Some(prost_types::value::Kind::StringValue("101".to_string())),
4214                        },
4215                        prost_types::Value {
4216                            kind: Some(prost_types::value::Kind::StringValue("Alice".to_string())),
4217                        },
4218                    ],
4219                },
4220            )),
4221        });
4222        let json_value = JsonValue::from_owned_value(wire_struct, &struct_type)
4223            .expect("valid conversion of wire-format struct to JSON object");
4224        assert_eq!(
4225            json_value,
4226            serde_json::json!({
4227                "id": "101",
4228                "name": "Alice",
4229            }),
4230            "expected JSON object matching wire struct fields"
4231        );
4232    }
4233
4234    #[test]
4235    fn from_value_vector_null() {
4236        let array_type = types::array(types::string());
4237        let null_value = Value::null();
4238        let error = Vec::<String>::from_value(&null_value, &array_type)
4239            .expect_err("null value for Vec must return NotNull");
4240        assert!(
4241            matches!(error, ConvertError::NotNull),
4242            "expected NotNull error"
4243        );
4244    }
4245
4246    #[test]
4247    fn from_value_vector_kind_mismatch() {
4248        let array_type = types::array(types::string());
4249        let non_list_value = "string".to_value();
4250        let error = Vec::<String>::from_value(&non_list_value, &array_type)
4251            .expect_err("non-list value for Vec must return KindMismatch");
4252        assert!(
4253            format!("{error}").contains("expected List, got String"),
4254            "expected KindMismatch error message"
4255        );
4256    }
4257
4258    #[test]
4259    fn from_value_bytes_kind_mismatch() {
4260        let bytes_type = types::bytes();
4261        let bool_value = true.to_value();
4262        let error = Vec::<u8>::from_value(&bool_value, &bytes_type)
4263            .expect_err("bool value for bytes must return KindMismatch");
4264        assert!(
4265            format!("{error}").contains("expected String, got Bool"),
4266            "expected KindMismatch error message"
4267        );
4268    }
4269
4270    #[test]
4271    fn from_owned_value_bytes() {
4272        let bytes_type = types::bytes();
4273        let bytes_value = b"test bytes".to_vec().to_value();
4274        let decoded = Vec::<u8>::from_owned_value(bytes_value, &bytes_type)
4275            .expect("should decode bytes from owned value");
4276        assert_eq!(decoded, b"test bytes", "expected matching bytes");
4277
4278        let null_value = Value::null();
4279        let null_error = Vec::<u8>::from_owned_value(null_value, &bytes_type)
4280            .expect_err("null bytes must return NotNull");
4281        assert!(
4282            format!("{null_error}").contains("expected non-null value, got null"),
4283            "expected NotNull error message"
4284        );
4285
4286        let bool_value = true.to_value();
4287        let mismatch_error = Vec::<u8>::from_owned_value(bool_value, &bytes_type)
4288            .expect_err("bool for bytes must return KindMismatch");
4289        assert!(
4290            format!("{mismatch_error}").contains("expected String, got Bool"),
4291            "expected KindMismatch error message"
4292        );
4293    }
4294
4295    #[test]
4296    fn from_value_json_borrowed_primitive_and_struct() {
4297        let json_type = types::json();
4298        let json_string_value = Value::from(r#"{"field":123}"#);
4299        let parsed = JsonValue::from_value(&json_string_value, &json_type)
4300            .expect("parsing JSON from borrowed Value");
4301        assert_eq!(
4302            parsed,
4303            json!({"field": 123}),
4304            "expected matching JSON object from borrowed Value"
4305        );
4306    }
4307
4308    #[test]
4309    fn from_owned_value_json_list_struct_fewer_values_than_fields() {
4310        let struct_type = Type(model::Type {
4311            code: model::TypeCode::Struct,
4312            struct_type: Some(Box::new(model::StructType {
4313                fields: vec![
4314                    model::struct_type::Field::new()
4315                        .set_name("first")
4316                        .set_type(model::Type {
4317                            code: model::TypeCode::String,
4318                            ..Default::default()
4319                        }),
4320                    model::struct_type::Field::new()
4321                        .set_name("second")
4322                        .set_type(model::Type {
4323                            code: model::TypeCode::String,
4324                            ..Default::default()
4325                        }),
4326                ],
4327                _unknown_fields: Default::default(),
4328            })),
4329            ..Default::default()
4330        });
4331
4332        let list_val = Value(prost_types::Value {
4333            kind: Some(prost_types::value::Kind::ListValue(
4334                prost_types::ListValue {
4335                    values: vec![prost_types::Value {
4336                        kind: Some(prost_types::value::Kind::StringValue(
4337                            "only_first".to_string(),
4338                        )),
4339                    }],
4340                },
4341            )),
4342        });
4343        let result = JsonValue::from_owned_value(list_val, &struct_type)
4344            .expect("should convert truncated list to JSON struct with null for missing fields");
4345        assert_eq!(
4346            result,
4347            json!({"first": "only_first", "second": null}),
4348            "expected missing field to be populated with null"
4349        );
4350    }
4351
4352    #[test]
4353    fn from_owned_value_json_float_string() {
4354        let float64_type = types::float64();
4355        let val64 = Value::from("12.5");
4356        let json64 = JsonValue::from_owned_value(val64, &float64_type)
4357            .expect("should decode float64 string to json number");
4358        assert_eq!(json64, json!(12.5), "expected JSON number 12.5 for float64");
4359
4360        let float32_type = types::float32();
4361        let val32 = Value::from("3.25");
4362        let json32 = JsonValue::from_owned_value(val32, &float32_type)
4363            .expect("should decode float32 string to json number");
4364        assert_eq!(json32, json!(3.25), "expected JSON number 3.25 for float32");
4365    }
4366
4367    #[test]
4368    fn from_owned_value_json_max_recursion_depth() {
4369        let mut inner = prost_types::Value {
4370            kind: Some(prost_types::value::Kind::BoolValue(true)),
4371        };
4372        for _ in 0..65 {
4373            inner = prost_types::Value {
4374                kind: Some(prost_types::value::Kind::ListValue(
4375                    prost_types::ListValue {
4376                        values: vec![inner],
4377                    },
4378                )),
4379            };
4380        }
4381        let v = Value(inner);
4382
4383        let err = JsonValue::from_owned_value(v, &Type::default())
4384            .expect_err("nested depth exceeding 64 must fail");
4385        assert!(
4386            format!("{}", err).contains("nesting depth exceeded"),
4387            "expected error to mention nesting depth exceeded"
4388        );
4389    }
4390
4391    #[test]
4392    fn from_value_json_borrowed_struct_without_metadata() {
4393        let struct_type_without_metadata = Type(model::Type {
4394            code: model::TypeCode::Struct,
4395            struct_type: None,
4396            ..Default::default()
4397        });
4398        let list_value = Value(prost_types::Value {
4399            kind: Some(prost_types::value::Kind::ListValue(
4400                prost_types::ListValue {
4401                    values: vec![prost_types::Value {
4402                        kind: Some(prost_types::value::Kind::StringValue(
4403                            "anonymous".to_string(),
4404                        )),
4405                    }],
4406                },
4407            )),
4408        });
4409        let json_value = JsonValue::from_value(&list_value, &struct_type_without_metadata)
4410            .expect("valid conversion to JSON array fallback for borrowed Value");
4411        assert_eq!(
4412            json_value,
4413            json!(["anonymous"]),
4414            "expected positional array fallback when struct metadata is missing"
4415        );
4416    }
4417
4418    #[test]
4419    fn from_owned_value_json_primitives_and_arrays() {
4420        // Null
4421        let null_json = JsonValue::from_owned_value(Value::null(), &Type::default())
4422            .expect("null to JSON should succeed");
4423        assert_eq!(null_json, JsonValue::Null, "expected JsonValue::Null");
4424
4425        // Missing kind (None)
4426        let missing_kind = Value(prost_types::Value { kind: None });
4427        let none_json = JsonValue::from_owned_value(missing_kind, &Type::default())
4428            .expect("missing kind to JSON should succeed");
4429        assert_eq!(
4430            none_json,
4431            JsonValue::Null,
4432            "expected JsonValue::Null for None"
4433        );
4434
4435        // Number
4436        let num_val = 42.5_f64.to_value();
4437        let num_json = JsonValue::from_owned_value(num_val, &types::float64())
4438            .expect("number to JSON should succeed");
4439        assert_eq!(num_json, json!(42.5), "expected JSON number 42.5");
4440
4441        // Bool
4442        let bool_val = true.to_value();
4443        let bool_json = JsonValue::from_owned_value(bool_val, &types::bool())
4444            .expect("bool to JSON should succeed");
4445        assert_eq!(bool_json, json!(true), "expected JSON bool true");
4446
4447        // Non-struct array
4448        let array_type = types::array(types::string());
4449        let list_val = Value::from(vec!["hello".to_string(), "world".to_string()]);
4450        let array_json = JsonValue::from_owned_value(list_val, &array_type)
4451            .expect("array to JSON should succeed");
4452        assert_eq!(
4453            array_json,
4454            json!(["hello", "world"]),
4455            "expected JSON array matching input list"
4456        );
4457    }
4458
4459    #[test]
4460    fn from_value_decimal_kind_mismatch() {
4461        let numeric_type = types::numeric();
4462        let bool_value = true.to_value();
4463        let error = Decimal::from_value(&bool_value, &numeric_type)
4464            .expect_err("non-string value for numeric must return KindMismatch");
4465        assert!(
4466            format!("{error}").contains("expected String, got Bool"),
4467            "expected KindMismatch error message"
4468        );
4469    }
4470
4471    #[test]
4472    fn from_value_string_from_numeric() -> Result<(), ConvertError> {
4473        let max_spanner_numeric = "99999999999999999999999999999.999999999";
4474        let min_spanner_numeric = "-99999999999999999999999999999.999999999";
4475        let pg_extreme_numeric =
4476            "12345678901234567890123456789012345678901234567890.1234567890123456789";
4477        let pg_negative_extreme_numeric =
4478            "-12345678901234567890123456789012345678901234567890.1234567890123456789";
4479
4480        let test_cases = [
4481            (types::numeric(), "123.456", "standard GoogleSQL NUMERIC"),
4482            (types::numeric(), "-123.456", "negative GoogleSQL NUMERIC"),
4483            (
4484                types::numeric(),
4485                max_spanner_numeric,
4486                "38-digit max GoogleSQL NUMERIC exceeding 96-bit Decimal mantissa",
4487            ),
4488            (
4489                types::numeric(),
4490                min_spanner_numeric,
4491                "38-digit negative max GoogleSQL NUMERIC",
4492            ),
4493            (
4494                types::numeric(),
4495                "100000000000000000000000000000",
4496                "30-digit integer NUMERIC exceeding Decimal limit",
4497            ),
4498            (types::numeric(), "0", "zero NUMERIC"),
4499            (types::numeric(), "0.000000000", "zero NUMERIC with scale"),
4500            (types::numeric(), "-0", "negative zero NUMERIC"),
4501            (types::numeric(), "1.5e3", "scientific notation NUMERIC"),
4502            (
4503                types::numeric(),
4504                "-1.5e-3",
4505                "negative scientific notation NUMERIC",
4506            ),
4507            (
4508                types::pg_numeric(),
4509                "NaN",
4510                "PostgreSQL dialect PG_NUMERIC NaN",
4511            ),
4512            (
4513                types::pg_numeric(),
4514                pg_extreme_numeric,
4515                "extreme arbitrary precision PG_NUMERIC",
4516            ),
4517            (
4518                types::pg_numeric(),
4519                pg_negative_extreme_numeric,
4520                "negative extreme arbitrary precision PG_NUMERIC",
4521            ),
4522            (types::pg_numeric(), "42.5", "standard PostgreSQL numeric"),
4523            (types::pg_numeric(), "-42.5", "negative PostgreSQL numeric"),
4524            (
4525                types::pg_numeric(),
4526                ".123",
4527                "PostgreSQL numeric without leading zero",
4528            ),
4529            (
4530                types::pg_numeric(),
4531                "42.",
4532                "PostgreSQL numeric with trailing decimal",
4533            ),
4534            (
4535                types::pg_numeric(),
4536                "+123.456",
4537                "PostgreSQL numeric with explicit positive sign",
4538            ),
4539            (
4540                types::pg_numeric(),
4541                "1.5E-3",
4542                "PostgreSQL numeric scientific notation with capital E",
4543            ),
4544            (
4545                types::pg_numeric(),
4546                "0.00000000000000000000000000000000000000000000000001",
4547                "extreme scale PG_NUMERIC",
4548            ),
4549        ];
4550
4551        for (column_type, text_content, description) in test_cases {
4552            // Borrowed conversion: from_value (using borrowed string slice directly)
4553            let value = text_content.to_value();
4554            let parsed_string = String::from_value(&value, &column_type)?;
4555            assert_eq!(
4556                parsed_string, text_content,
4557                "mismatch in borrowed String::from_value for {description}"
4558            );
4559
4560            // Owned zero-copy conversion: from_owned_value
4561            let owned_value = text_content.to_string().to_value();
4562            let owned_parsed_string = String::from_owned_value(owned_value, &column_type)?;
4563            assert_eq!(
4564                owned_parsed_string, text_content,
4565                "mismatch in owned String::from_owned_value for {description}"
4566            );
4567
4568            // Option<String> conversion
4569            let optional_parsed_string = Option::<String>::from_value(&value, &column_type)?;
4570            assert_eq!(
4571                optional_parsed_string,
4572                Some(text_content.to_string()),
4573                "mismatch in Option::<String>::from_value for {description}"
4574            );
4575        }
4576
4577        // Null Option<String> handling across NUMERIC and PG_NUMERIC
4578        let null_cases = [
4579            (types::numeric(), "null NUMERIC"),
4580            (types::pg_numeric(), "null PG_NUMERIC"),
4581        ];
4582
4583        for (column_type, description) in null_cases {
4584            let null_value = Value::default();
4585            let null_result = Option::<String>::from_value(&null_value, &column_type)?;
4586            assert_eq!(
4587                null_result, None,
4588                "expected None for Option::<String> on {description}"
4589            );
4590
4591            let not_null_error = String::from_value(&null_value, &column_type)
4592                .expect_err("non-optional String must reject null value");
4593            assert!(
4594                matches!(not_null_error, ConvertError::NotNull),
4595                "expected ConvertError::NotNull for {description}"
4596            );
4597        }
4598
4599        // Decimal conversion behavior on PG_NUMERIC
4600        let valid_pg_decimal = "42.5".to_value();
4601        let decimal = Decimal::from_value(&valid_pg_decimal, &types::pg_numeric())
4602            .expect("standard PG_NUMERIC must convert to Decimal");
4603        assert_eq!(
4604            decimal,
4605            Decimal::from_str_exact("42.5").expect("valid decimal"),
4606            "expected parsed Decimal from PG_NUMERIC"
4607        );
4608
4609        let nan_pg = "NaN".to_value();
4610        let nan_error = Decimal::from_value(&nan_pg, &types::pg_numeric())
4611            .expect_err("Decimal must reject NaN PG_NUMERIC");
4612        assert!(
4613            matches!(nan_error, ConvertError::Convert(_)),
4614            "expected ConvertError::Convert for NaN PG_NUMERIC"
4615        );
4616
4617        let extreme_pg = pg_extreme_numeric.to_value();
4618        let extreme_error = Decimal::from_value(&extreme_pg, &types::pg_numeric())
4619            .expect_err("Decimal must reject extreme PG_NUMERIC exceeding 96 bits");
4620        assert!(
4621            matches!(extreme_error, ConvertError::Convert(_)),
4622            "expected ConvertError::Convert for extreme PG_NUMERIC"
4623        );
4624
4625        // GoogleSQL ARRAY<NUMERIC> into Vec<String>
4626        let numeric_array_type = types::array(types::numeric());
4627        let numeric_list = vec!["123.456", max_spanner_numeric].to_value();
4628        let parsed_numeric_vec = Vec::<String>::from_value(&numeric_list, &numeric_array_type)?;
4629        assert_eq!(
4630            parsed_numeric_vec,
4631            vec!["123.456".to_string(), max_spanner_numeric.to_string()],
4632            "mismatch in decoded ARRAY<NUMERIC>"
4633        );
4634
4635        // PostgreSQL ARRAY<PG_NUMERIC> into Vec<Option<String>>
4636        let pg_numeric_array_type = types::array(types::pg_numeric());
4637        let pg_numeric_list = vec![
4638            Some("NaN".to_string()),
4639            None,
4640            Some(pg_extreme_numeric.to_string()),
4641        ]
4642        .to_value();
4643
4644        let parsed_pg_numeric_vec =
4645            Vec::<Option<String>>::from_value(&pg_numeric_list, &pg_numeric_array_type)?;
4646        assert_eq!(
4647            parsed_pg_numeric_vec,
4648            vec![
4649                Some("NaN".to_string()),
4650                None,
4651                Some(pg_extreme_numeric.to_string()),
4652            ],
4653            "mismatch in decoded ARRAY<PG_NUMERIC>"
4654        );
4655
4656        // Non-optional Vec<String> rejects null elements in numeric arrays
4657        let null_element_error =
4658            Vec::<String>::from_value(&pg_numeric_list, &pg_numeric_array_type)
4659                .expect_err("Vec::<String> must reject array containing null element");
4660        assert!(
4661            matches!(null_element_error, ConvertError::NotNull),
4662            "expected ConvertError::NotNull for null array element"
4663        );
4664        Ok(())
4665    }
4666
4667    #[test]
4668    fn from_value_string_from_interval() -> Result<(), ConvertError> {
4669        let test_cases = [
4670            ("P1Y2M3D", "standard INTERVAL duration"),
4671            (
4672                "P1Y2M10DT2H30M15.5S",
4673                "detailed date-time INTERVAL duration",
4674            ),
4675            ("P0Y0M0DT0H0M0S", "full zero INTERVAL"),
4676            (
4677                "P-1Y2M-3DT-4H5M6.78912345S",
4678                "mixed sign INTERVAL components",
4679            ),
4680            ("P-1Y-2M-3DT-12H-12M-6S", "all negative INTERVAL components"),
4681            ("-P1Y2M3D", "negative prefixed ISO duration"),
4682            ("PT12H30M15S", "time-only INTERVAL"),
4683            ("PT0.000000001S", "subsecond nanosecond precision INTERVAL"),
4684            (
4685                "P1Y2M3DT12H12M6.789000123S",
4686                "full 9-digit fractional second INTERVAL",
4687            ),
4688            ("P2W", "weeks only INTERVAL"),
4689        ];
4690
4691        let interval_type = types::interval();
4692
4693        for (text_content, description) in test_cases {
4694            // Borrowed conversion: from_value (using borrowed string slice directly)
4695            let value = text_content.to_value();
4696            let parsed_string = String::from_value(&value, &interval_type)?;
4697            assert_eq!(
4698                parsed_string, text_content,
4699                "mismatch in borrowed String::from_value for {description}"
4700            );
4701
4702            // Owned zero-copy conversion: from_owned_value
4703            let owned_value = text_content.to_string().to_value();
4704            let owned_parsed_string = String::from_owned_value(owned_value, &interval_type)?;
4705            assert_eq!(
4706                owned_parsed_string, text_content,
4707                "mismatch in owned String::from_owned_value for {description}"
4708            );
4709
4710            // Option<String> conversion
4711            let optional_parsed_string = Option::<String>::from_value(&value, &interval_type)?;
4712            assert_eq!(
4713                optional_parsed_string,
4714                Some(text_content.to_string()),
4715                "mismatch in Option::<String>::from_value for {description}"
4716            );
4717        }
4718
4719        // Null Option<String> handling for INTERVAL
4720        let null_value = Value::default();
4721        let null_result = Option::<String>::from_value(&null_value, &interval_type)?;
4722        assert_eq!(
4723            null_result, None,
4724            "expected None for Option::<String> on null INTERVAL"
4725        );
4726
4727        let not_null_error = String::from_value(&null_value, &interval_type)
4728            .expect_err("non-optional String must reject null value");
4729        assert!(
4730            matches!(not_null_error, ConvertError::NotNull),
4731            "expected ConvertError::NotNull for null INTERVAL"
4732        );
4733
4734        // Non-string types reject INTERVAL columns with TypeMismatch
4735        let interval_value = "P1Y2M3D".to_value();
4736        let int64_error =
4737            i64::from_value(&interval_value, &interval_type).expect_err("i64 must reject INTERVAL");
4738        assert_eq!(
4739            int64_error.to_string(),
4740            "type mismatch, expected Int64, got Interval",
4741            "expected TypeMismatch for i64 on INTERVAL"
4742        );
4743
4744        let decimal_error = Decimal::from_value(&interval_value, &interval_type)
4745            .expect_err("Decimal must reject INTERVAL");
4746        assert_eq!(
4747            decimal_error.to_string(),
4748            "type mismatch, expected Numeric, got Interval",
4749            "expected TypeMismatch for Decimal on INTERVAL"
4750        );
4751
4752        let float64_error =
4753            f64::from_value(&interval_value, &interval_type).expect_err("f64 must reject INTERVAL");
4754        assert_eq!(
4755            float64_error.to_string(),
4756            "type mismatch, expected Float64, got Interval",
4757            "expected TypeMismatch for f64 on INTERVAL"
4758        );
4759
4760        let bool_error = bool::from_value(&interval_value, &interval_type)
4761            .expect_err("bool must reject INTERVAL");
4762        assert_eq!(
4763            bool_error.to_string(),
4764            "type mismatch, expected Bool, got Interval",
4765            "expected TypeMismatch for bool on INTERVAL"
4766        );
4767
4768        // ARRAY<INTERVAL> into Vec<String>
4769        let interval_array_type = types::array(types::interval());
4770        let interval_list = vec!["P1Y2M3D", "P2Y"].to_value();
4771        let parsed_interval_vec = Vec::<String>::from_value(&interval_list, &interval_array_type)?;
4772        assert_eq!(
4773            parsed_interval_vec,
4774            vec!["P1Y2M3D".to_string(), "P2Y".to_string()],
4775            "mismatch in decoded ARRAY<INTERVAL>"
4776        );
4777
4778        // ARRAY<INTERVAL> into Vec<Option<String>> with nulls
4779        let interval_nullable_list = vec![Some("P1Y2M3D"), None, Some("PT5M")].to_value();
4780        let parsed_nullable_vec =
4781            Vec::<Option<String>>::from_value(&interval_nullable_list, &interval_array_type)?;
4782        assert_eq!(
4783            parsed_nullable_vec,
4784            vec![Some("P1Y2M3D".to_string()), None, Some("PT5M".to_string())],
4785            "mismatch in decoded nullable ARRAY<INTERVAL>"
4786        );
4787
4788        // Vec<String> rejects null elements in ARRAY<INTERVAL>
4789        let null_element_error =
4790            Vec::<String>::from_value(&interval_nullable_list, &interval_array_type)
4791                .expect_err("Vec::<String> must reject ARRAY<INTERVAL> with null element");
4792        assert!(
4793            matches!(null_element_error, ConvertError::NotNull),
4794            "expected ConvertError::NotNull for null INTERVAL array element"
4795        );
4796        Ok(())
4797    }
4798
4799    use prost::{Enumeration, Message};
4800
4801    #[derive(Clone, PartialEq, Message)]
4802    struct TestAddress {
4803        #[prost(string, tag = "1")]
4804        street: String,
4805        #[prost(string, tag = "2")]
4806        city: String,
4807    }
4808
4809    impl FromValue for TestAddress {
4810        fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
4811            let bytes = Vec::<u8>::from_value(value, spanner_type)?;
4812            Self::decode(bytes.as_slice()).map_err(ConvertError::custom)
4813        }
4814    }
4815
4816    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Enumeration)]
4817    #[repr(i32)]
4818    enum TestOrderStatus {
4819        Unspecified = 0,
4820        Pending = 1,
4821        Shipped = 2,
4822        Delivered = 3,
4823    }
4824
4825    impl FromValue for TestOrderStatus {
4826        fn from_value(value: &Value, spanner_type: &Type) -> Result<Self, ConvertError> {
4827            let raw_value = i32::from_value(value, spanner_type)?;
4828            Self::try_from(raw_value).map_err(ConvertError::custom)
4829        }
4830    }
4831
4832    #[test]
4833    fn from_value_proto() {
4834        let sample_address = TestAddress {
4835            street: "1600 Amphitheatre Pkwy".to_string(),
4836            city: "Mountain View".to_string(),
4837        };
4838        let raw_payload = sample_address.encode_to_vec();
4839        let proto_type = types::proto("examples.shipping.Address");
4840        let encoded_string = BASE64_STANDARD.encode(&raw_payload);
4841        let proto_value = Value::from(encoded_string);
4842
4843        // Borrowed deserialization
4844        let decoded_bytes = Vec::<u8>::from_value(&proto_value, &proto_type)
4845            .expect("borrowed Vec<u8> from_value should succeed for proto type");
4846        let decoded_address = TestAddress::decode(decoded_bytes.as_slice())
4847            .expect("decode TestAddress from borrowed bytes");
4848        assert_eq!(
4849            decoded_address, sample_address,
4850            "decoded proto message must match original struct"
4851        );
4852
4853        // Custom type FromValue direct deserialization
4854        let direct_address = TestAddress::from_value(&proto_value, &proto_type)
4855            .expect("direct TestAddress from_value should succeed");
4856        assert_eq!(
4857            direct_address, sample_address,
4858            "direct TestAddress must match original struct"
4859        );
4860
4861        // Owned deserialization
4862        let decoded_owned = Vec::<u8>::from_owned_value(proto_value.clone(), &proto_type)
4863            .expect("owned Vec<u8> from_owned_value should succeed for proto type");
4864        let decoded_address_owned = TestAddress::decode(decoded_owned.as_slice())
4865            .expect("decode TestAddress from owned bytes");
4866        assert_eq!(
4867            decoded_address_owned, sample_address,
4868            "decoded proto message from owned bytes must match original struct"
4869        );
4870
4871        // Option<Vec<u8>> with value
4872        let some_proto = Option::<Vec<u8>>::from_value(&proto_value, &proto_type)
4873            .expect("present Option<Vec<u8>> should succeed for proto type");
4874        assert_eq!(
4875            some_proto,
4876            Some(raw_payload.to_vec()),
4877            "expected Some(payload) for proto type"
4878        );
4879
4880        // Option<Vec<u8>> with null
4881        let null_proto = Option::<Vec<u8>>::from_value(&Value::null(), &proto_type)
4882            .expect("null Option<Vec<u8>> should succeed for proto type");
4883        assert_eq!(
4884            null_proto, None,
4885            "expected None for null Option<Vec<u8>> on proto type"
4886        );
4887
4888        // Array of proto
4889        let array_proto_type = types::array(proto_type.clone());
4890        let address_1 = TestAddress {
4891            street: "1 Market St".to_string(),
4892            city: "San Francisco".to_string(),
4893        };
4894        let address_2 = TestAddress {
4895            street: "111 8th Ave".to_string(),
4896            city: "New York".to_string(),
4897        };
4898        let list_value = Value::from(vec![
4899            Value::from(BASE64_STANDARD.encode(address_1.encode_to_vec())),
4900            Value::from(BASE64_STANDARD.encode(address_2.encode_to_vec())),
4901        ]);
4902        let decoded_list = Vec::<Vec<u8>>::from_value(&list_value, &array_proto_type)
4903            .expect("Vec<Vec<u8>> should succeed for ARRAY<PROTO>");
4904        let decoded_addresses: Vec<TestAddress> = decoded_list
4905            .iter()
4906            .map(|bytes| {
4907                TestAddress::decode(bytes.as_slice()).expect("decode TestAddress from list element")
4908            })
4909            .collect();
4910        assert_eq!(
4911            decoded_addresses,
4912            vec![address_1.clone(), address_2],
4913            "expected decoded list of proto addresses"
4914        );
4915
4916        // Array of proto containing NULL elements
4917        let nullable_list_value = Value::from(vec![
4918            Value::from(BASE64_STANDARD.encode(address_1.encode_to_vec())),
4919            Value::null(),
4920        ]);
4921        let decoded_nullable_list =
4922            Vec::<Option<Vec<u8>>>::from_value(&nullable_list_value, &array_proto_type)
4923                .expect("Vec<Option<Vec<u8>>> should succeed for ARRAY<PROTO> with nulls");
4924        assert_eq!(
4925            decoded_nullable_list.len(),
4926            2,
4927            "decoded_nullable_list length must be 2"
4928        );
4929        assert_eq!(
4930            TestAddress::decode(
4931                decoded_nullable_list[0]
4932                    .as_ref()
4933                    .expect("element 0 must exist")
4934                    .as_slice()
4935            )
4936            .expect("decode element 0"),
4937            address_1,
4938            "element 0 must match address_1"
4939        );
4940        assert!(
4941            decoded_nullable_list[1].is_none(),
4942            "expected element 1 in nullable list to be None"
4943        );
4944
4945        // Error: non-nullable null
4946        let null_error = Vec::<u8>::from_value(&Value::null(), &proto_type)
4947            .expect_err("null value for non-optional Vec<u8> must return NotNull");
4948        assert!(
4949            matches!(null_error, ConvertError::NotNull),
4950            "expected NotNull error"
4951        );
4952
4953        // Error: invalid base64
4954        let invalid_base64_value = Value::from("not-valid-base64!!!");
4955        let base64_error = Vec::<u8>::from_value(&invalid_base64_value, &proto_type)
4956            .expect_err("invalid base64 must return Convert error");
4957        assert!(
4958            matches!(base64_error, ConvertError::Convert(_)),
4959            "expected Convert error for invalid base64"
4960        );
4961
4962        // Error: type mismatch (e.g. String type instead of Proto)
4963        let type_mismatch_error = Vec::<u8>::from_value(&proto_value, &types::string())
4964            .expect_err("String type for Vec<u8> must return TypeMismatch");
4965        assert!(
4966            matches!(
4967                type_mismatch_error,
4968                ConvertError::TypeMismatch {
4969                    want: TypeCode::Bytes,
4970                    got: TypeCode::String,
4971                }
4972            ),
4973            "expected TypeMismatch error"
4974        );
4975
4976        // Error: kind mismatch (e.g. boolean value)
4977        let kind_mismatch_error = Vec::<u8>::from_value(&true.to_value(), &proto_type)
4978            .expect_err("boolean value for Vec<u8> must return KindMismatch");
4979        assert!(
4980            matches!(
4981                kind_mismatch_error,
4982                ConvertError::KindMismatch {
4983                    want: Kind::String,
4984                    got: Kind::Bool,
4985                }
4986            ),
4987            "expected KindMismatch error"
4988        );
4989
4990        // Error: invalid proto decode for custom FromValue struct
4991        let malformed_proto_value = Value::from(BASE64_STANDARD.encode([0xFF, 0xFF, 0xFF]));
4992        let decode_error = TestAddress::from_value(&malformed_proto_value, &proto_type)
4993            .expect_err("malformed proto bytes must return Convert error for TestAddress");
4994        assert!(
4995            matches!(decode_error, ConvertError::Convert(_)),
4996            "expected Convert error for malformed proto bytes"
4997        );
4998    }
4999
5000    #[test]
5001    fn from_value_proto_enum() {
5002        let enum_type = types::proto_enum("examples.shipping.OrderStatus");
5003        let enum_value = Value::from("2");
5004
5005        // i64 borrowed & owned
5006        let int64_borrowed = i64::from_value(&enum_value, &enum_type)
5007            .expect("borrowed i64 from_value should succeed for enum type");
5008        assert_eq!(int64_borrowed, 2_i64, "expected enum int64 value 2");
5009        let order_status = TestOrderStatus::try_from(int64_borrowed as i32)
5010            .expect("convert i64 to TestOrderStatus");
5011        assert_eq!(
5012            order_status,
5013            TestOrderStatus::Shipped,
5014            "expected Shipped enum variant"
5015        );
5016
5017        // Custom type FromValue direct deserialization
5018        let direct_status = TestOrderStatus::from_value(&enum_value, &enum_type)
5019            .expect("direct TestOrderStatus from_value should succeed");
5020        assert_eq!(
5021            direct_status,
5022            TestOrderStatus::Shipped,
5023            "expected direct Shipped enum variant"
5024        );
5025
5026        let int64_owned = i64::from_owned_value(enum_value.clone(), &enum_type)
5027            .expect("owned i64 from_owned_value should succeed for enum type");
5028        assert_eq!(int64_owned, 2_i64, "expected owned enum int64 value 2");
5029
5030        // i32 borrowed & owned
5031        let int32_borrowed = i32::from_value(&enum_value, &enum_type)
5032            .expect("borrowed i32 from_value should succeed for enum type");
5033        assert_eq!(int32_borrowed, 2_i32, "expected enum int32 value 2");
5034        let order_status_32 =
5035            TestOrderStatus::try_from(int32_borrowed).expect("convert i32 to TestOrderStatus");
5036        assert_eq!(
5037            order_status_32,
5038            TestOrderStatus::Shipped,
5039            "expected Shipped enum variant"
5040        );
5041
5042        let int32_owned = i32::from_owned_value(enum_value.clone(), &enum_type)
5043            .expect("owned i32 from_owned_value should succeed for enum type");
5044        assert_eq!(int32_owned, 2_i32, "expected owned enum int32 value 2");
5045
5046        // Option<i64> with value & null
5047        let some_enum = Option::<i64>::from_value(&enum_value, &enum_type)
5048            .expect("present Option<i64> should succeed for enum type");
5049        assert_eq!(some_enum, Some(2_i64), "expected Some(2) for enum type");
5050
5051        let null_enum = Option::<i64>::from_value(&Value::null(), &enum_type)
5052            .expect("null Option<i64> should succeed for enum type");
5053        assert_eq!(
5054            null_enum, None,
5055            "expected None for null Option<i64> on enum type"
5056        );
5057
5058        // Array of enums
5059        let array_enum_type = types::array(enum_type.clone());
5060        let list_value = Value::from(vec![Value::from("1"), Value::from("3")]);
5061        let decoded_list = Vec::<i64>::from_value(&list_value, &array_enum_type)
5062            .expect("Vec<i64> should succeed for ARRAY<ENUM>");
5063        assert_eq!(
5064            decoded_list,
5065            vec![1_i64, 3_i64],
5066            "expected decoded list of enum integers"
5067        );
5068        let decoded_statuses: Vec<TestOrderStatus> = decoded_list
5069            .iter()
5070            .map(|&val| {
5071                TestOrderStatus::try_from(val as i32)
5072                    .expect("convert array element to TestOrderStatus")
5073            })
5074            .collect();
5075        assert_eq!(
5076            decoded_statuses,
5077            vec![TestOrderStatus::Pending, TestOrderStatus::Delivered],
5078            "expected decoded enum statuses"
5079        );
5080
5081        // Array of enums containing NULL elements
5082        let nullable_list_value = Value::from(vec![Value::from("1"), Value::null()]);
5083        let decoded_nullable_list =
5084            Vec::<Option<i64>>::from_value(&nullable_list_value, &array_enum_type)
5085                .expect("Vec<Option<i64>> should succeed for ARRAY<ENUM> with nulls");
5086        assert_eq!(
5087            decoded_nullable_list,
5088            vec![Some(1_i64), None],
5089            "expected decoded nullable enum list with Some(1) and None"
5090        );
5091
5092        // Error: non-nullable null
5093        let null_error = i64::from_value(&Value::null(), &enum_type)
5094            .expect_err("null value for non-optional i64 must return NotNull");
5095        assert!(
5096            matches!(null_error, ConvertError::NotNull),
5097            "expected NotNull error"
5098        );
5099
5100        // Error: non-numeric string
5101        let invalid_enum_value = Value::from("PENDING");
5102        let parse_error = i64::from_value(&invalid_enum_value, &enum_type)
5103            .expect_err("non-numeric string for enum must return Convert error");
5104        assert!(
5105            matches!(parse_error, ConvertError::Convert(_)),
5106            "expected parse error for non-numeric enum string"
5107        );
5108
5109        // Error: type mismatch (e.g. String type instead of Enum)
5110        let type_mismatch_error = i64::from_value(&enum_value, &types::string())
5111            .expect_err("String type for i64 must return TypeMismatch");
5112        assert!(
5113            matches!(
5114                type_mismatch_error,
5115                ConvertError::TypeMismatch {
5116                    want: TypeCode::Int64,
5117                    got: TypeCode::String,
5118                }
5119            ),
5120            "expected TypeMismatch error"
5121        );
5122
5123        // Error: kind mismatch (e.g. boolean value)
5124        let kind_mismatch_error = i64::from_value(&true.to_value(), &enum_type)
5125            .expect_err("boolean value for i64 must return KindMismatch");
5126        assert!(
5127            matches!(
5128                kind_mismatch_error,
5129                ConvertError::KindMismatch {
5130                    want: Kind::String,
5131                    got: Kind::Bool,
5132                }
5133            ),
5134            "expected KindMismatch error"
5135        );
5136
5137        // Error: invalid enum variant integer
5138        let invalid_variant_value = Value::from("99");
5139        let invalid_variant_error = TestOrderStatus::from_value(&invalid_variant_value, &enum_type)
5140            .expect_err("unknown enum integer must return Convert error for TestOrderStatus");
5141        assert!(
5142            matches!(invalid_variant_error, ConvertError::Convert(_)),
5143            "expected Convert error for invalid enum variant"
5144        );
5145    }
5146
5147    #[test]
5148    fn from_value_bytes_crate() {
5149        let bytes_type = types::bytes();
5150        let proto_type = types::proto("com.example.CustomerProto");
5151        let raw_bytes = b"hello binary world";
5152        let encoded_value = raw_bytes.to_vec().to_value();
5153
5154        let decoded_borrowed = Bytes::from_value(&encoded_value, &bytes_type)
5155            .expect("borrowed Bytes from_value should succeed");
5156        assert_eq!(
5157            decoded_borrowed,
5158            Bytes::from_static(raw_bytes),
5159            "borrowed Bytes content must match"
5160        );
5161
5162        let decoded_proto = Bytes::from_value(&encoded_value, &proto_type)
5163            .expect("borrowed Bytes from proto type should succeed");
5164        assert_eq!(
5165            decoded_proto,
5166            Bytes::from_static(raw_bytes),
5167            "proto Bytes content must match"
5168        );
5169
5170        let decoded_owned = Bytes::from_owned_value(encoded_value, &bytes_type)
5171            .expect("owned Bytes from_owned_value should succeed");
5172        assert_eq!(
5173            decoded_owned,
5174            Bytes::from_static(raw_bytes),
5175            "owned Bytes content must match"
5176        );
5177
5178        let null_error = Bytes::from_value(&Value::null(), &bytes_type)
5179            .expect_err("null Bytes must return NotNull");
5180        assert!(
5181            matches!(null_error, ConvertError::NotNull),
5182            "expected NotNull error"
5183        );
5184
5185        let type_mismatch_error =
5186            Bytes::from_value(&raw_bytes.to_vec().to_value(), &types::string())
5187                .expect_err("string type for Bytes must return TypeMismatch");
5188        assert!(
5189            matches!(
5190                type_mismatch_error,
5191                ConvertError::TypeMismatch {
5192                    want: TypeCode::Bytes,
5193                    got: TypeCode::String
5194                }
5195            ),
5196            "expected TypeMismatch error"
5197        );
5198
5199        let kind_mismatch_error = Bytes::from_value(&true.to_value(), &bytes_type)
5200            .expect_err("bool value for Bytes must return KindMismatch");
5201        assert!(
5202            matches!(
5203                kind_mismatch_error,
5204                ConvertError::KindMismatch {
5205                    want: Kind::String,
5206                    got: Kind::Bool
5207                }
5208            ),
5209            "expected KindMismatch error"
5210        );
5211
5212        let invalid_base64_value = Value::from("not-valid-base64!@#$");
5213        let decode_error = Bytes::from_value(&invalid_base64_value, &bytes_type)
5214            .expect_err("invalid base64 must return Convert error");
5215        assert!(
5216            matches!(decode_error, ConvertError::Convert(_)),
5217            "expected Convert error for invalid base64"
5218        );
5219
5220        let empty_bytes = Bytes::from_static(b"");
5221        let empty_value = empty_bytes.clone().to_value();
5222        let decoded_empty = Bytes::from_value(&empty_value, &bytes_type)
5223            .expect("empty Bytes from_value should succeed");
5224        assert_eq!(decoded_empty, empty_bytes, "empty Bytes must match");
5225
5226        let owned_type_mismatch =
5227            Bytes::from_owned_value(raw_bytes.to_vec().to_value(), &types::string())
5228                .expect_err("owned string type for Bytes must return TypeMismatch");
5229        assert!(
5230            matches!(
5231                owned_type_mismatch,
5232                ConvertError::TypeMismatch {
5233                    want: TypeCode::Bytes,
5234                    got: TypeCode::String
5235                }
5236            ),
5237            "expected TypeMismatch error for owned Bytes"
5238        );
5239
5240        let owned_null_error = Bytes::from_owned_value(Value::null(), &bytes_type)
5241            .expect_err("owned null Bytes must return NotNull");
5242        assert!(
5243            matches!(owned_null_error, ConvertError::NotNull),
5244            "expected NotNull error for owned Bytes"
5245        );
5246
5247        let owned_kind_mismatch = Bytes::from_owned_value(true.to_value(), &bytes_type)
5248            .expect_err("owned bool value for Bytes must return KindMismatch");
5249        assert!(
5250            matches!(
5251                owned_kind_mismatch,
5252                ConvertError::KindMismatch {
5253                    want: Kind::String,
5254                    got: Kind::Bool
5255                }
5256            ),
5257            "expected KindMismatch error for owned Bytes"
5258        );
5259
5260        let owned_decode_error =
5261            Bytes::from_owned_value(Value::from("not-valid-base64!@#$"), &bytes_type)
5262                .expect_err("owned invalid base64 must return Convert error");
5263        assert!(
5264            matches!(owned_decode_error, ConvertError::Convert(_)),
5265            "expected Convert error for owned invalid base64"
5266        );
5267    }
5268
5269    #[test]
5270    fn from_value_uuid() {
5271        let uuid_type = types::uuid();
5272        let string_type = types::string();
5273        let uuid_string = "123e4567-e89b-12d3-a456-426614174000";
5274        let expected_uuid = Uuid::parse_str(uuid_string).expect("valid uuid string");
5275        let uuid_value = Value::from(uuid_string);
5276
5277        let decoded_borrowed = Uuid::from_value(&uuid_value, &uuid_type)
5278            .expect("borrowed Uuid from_value should succeed with uuid type");
5279        assert_eq!(decoded_borrowed, expected_uuid, "borrowed Uuid must match");
5280
5281        let decoded_from_string_type = Uuid::from_value(&uuid_value, &string_type)
5282            .expect("borrowed Uuid from_value should succeed with string type");
5283        assert_eq!(
5284            decoded_from_string_type, expected_uuid,
5285            "Uuid from string type must match"
5286        );
5287
5288        let decoded_owned = Uuid::from_owned_value(uuid_value, &uuid_type)
5289            .expect("owned Uuid from_owned_value should succeed");
5290        assert_eq!(decoded_owned, expected_uuid, "owned Uuid must match");
5291
5292        let null_error = Uuid::from_value(&Value::null(), &uuid_type)
5293            .expect_err("null Uuid must return NotNull");
5294        assert!(
5295            matches!(null_error, ConvertError::NotNull),
5296            "expected NotNull error"
5297        );
5298
5299        let kind_none_error = Uuid::from_value(&Value(ProtoValue { kind: None }), &uuid_type)
5300            .expect_err("kind None for Uuid must return NotNull");
5301        assert!(
5302            matches!(kind_none_error, ConvertError::NotNull),
5303            "expected NotNull error for kind None"
5304        );
5305
5306        let type_mismatch_error = Uuid::from_value(&Value::from(uuid_string), &types::int64())
5307            .expect_err("int64 type for Uuid must return TypeMismatch");
5308        assert!(
5309            matches!(
5310                type_mismatch_error,
5311                ConvertError::TypeMismatch {
5312                    want: TypeCode::Uuid,
5313                    got: TypeCode::Int64
5314                }
5315            ),
5316            "expected TypeMismatch error"
5317        );
5318
5319        let kind_mismatch_error = Uuid::from_value(&true.to_value(), &uuid_type)
5320            .expect_err("bool kind for Uuid must return KindMismatch");
5321        assert!(
5322            matches!(
5323                kind_mismatch_error,
5324                ConvertError::KindMismatch {
5325                    want: Kind::String,
5326                    got: Kind::Bool
5327                }
5328            ),
5329            "expected KindMismatch error"
5330        );
5331
5332        let invalid_uuid_value = Value::from("not-a-valid-uuid");
5333        let parse_error = Uuid::from_value(&invalid_uuid_value, &uuid_type)
5334            .expect_err("malformed uuid string must return Convert error");
5335        assert!(
5336            matches!(parse_error, ConvertError::Convert(_)),
5337            "expected Convert error for invalid uuid format"
5338        );
5339    }
5340
5341    #[test]
5342    fn from_value_bytes_and_uuid_in_collections() {
5343        let uuid_type = types::uuid();
5344        let bytes_type = types::bytes();
5345        let uuid_string = "123e4567-e89b-12d3-a456-426614174000";
5346        let expected_uuid = Uuid::parse_str(uuid_string).expect("valid uuid string");
5347
5348        // Option<Uuid>
5349        let present_uuid = Option::<Uuid>::from_value(&Value::from(uuid_string), &uuid_type)
5350            .expect("present Option<Uuid> should succeed");
5351        assert_eq!(present_uuid, Some(expected_uuid), "expected Some(uuid)");
5352
5353        let null_uuid = Option::<Uuid>::from_value(&Value::null(), &uuid_type)
5354            .expect("null Option<Uuid> should succeed");
5355        assert_eq!(null_uuid, None, "expected None for null Option<Uuid>");
5356
5357        // Option<Bytes>
5358        let raw_bytes = b"sample bytes";
5359        let encoded_bytes = raw_bytes.to_vec().to_value();
5360        let present_bytes = Option::<Bytes>::from_value(&encoded_bytes, &bytes_type)
5361            .expect("present Option<Bytes> should succeed");
5362        assert_eq!(
5363            present_bytes,
5364            Some(Bytes::from_static(raw_bytes)),
5365            "expected Some(Bytes)"
5366        );
5367
5368        let null_bytes = Option::<Bytes>::from_value(&Value::null(), &bytes_type)
5369            .expect("null Option<Bytes> should succeed");
5370        assert_eq!(null_bytes, None, "expected None for null Option<Bytes>");
5371
5372        // Vec<Uuid>
5373        let array_uuid_type = types::array(types::uuid());
5374        let uuid_list_value = Value::from(vec![uuid_string.to_string(), uuid_string.to_string()]);
5375        let uuid_vector = Vec::<Uuid>::from_value(&uuid_list_value, &array_uuid_type)
5376            .expect("Vec<Uuid> from_value should succeed");
5377        assert_eq!(
5378            uuid_vector,
5379            vec![expected_uuid, expected_uuid],
5380            "expected matching uuid vector"
5381        );
5382
5383        let invalid_uuid_list_value = Value::from(vec!["not-a-uuid".to_string()]);
5384        let uuid_collection_error =
5385            Vec::<Uuid>::from_value(&invalid_uuid_list_value, &array_uuid_type)
5386                .expect_err("invalid uuid element in collection must error");
5387        assert!(
5388            matches!(uuid_collection_error, ConvertError::Convert(_)),
5389            "expected Convert error in Vec<Uuid>"
5390        );
5391
5392        // Vec<Bytes>
5393        let array_bytes_type = types::array(types::bytes());
5394        let bytes_list_value = Value::from(vec![
5395            raw_bytes.to_vec().to_value(),
5396            raw_bytes.to_vec().to_value(),
5397        ]);
5398        let bytes_vector = Vec::<Bytes>::from_value(&bytes_list_value, &array_bytes_type)
5399            .expect("Vec<Bytes> from_value should succeed");
5400        assert_eq!(
5401            bytes_vector,
5402            vec![Bytes::from_static(raw_bytes), Bytes::from_static(raw_bytes)],
5403            "expected matching bytes vector"
5404        );
5405
5406        let invalid_bytes_list_value = Value::from(vec![Value::from("invalid-base64!#%")]);
5407        let bytes_collection_error =
5408            Vec::<Bytes>::from_value(&invalid_bytes_list_value, &array_bytes_type)
5409                .expect_err("invalid base64 element in collection must error");
5410        assert!(
5411            matches!(bytes_collection_error, ConvertError::Convert(_)),
5412            "expected Convert error in Vec<Bytes>"
5413        );
5414    }
5415}