Skip to main content

google_cloud_spanner/
types.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::generated::gapic_dataplane::model;
16use crate::generated::gapic_dataplane::model::TypeAnnotationCode;
17use crate::google::spanner::v1::Type as ProtoType;
18use std::sync::LazyLock;
19
20/// Spanner type definition.
21#[derive(Clone, Debug, PartialEq, Default)]
22#[repr(transparent)]
23pub struct Type(pub(crate) model::Type);
24
25macro_rules! define_type_code {
26    ($($variant:ident = $val:expr),* $(,)?) => {
27        /// Spanner type code.
28        ///
29        /// Maps directly to the gRPC type codes defined in
30        /// [`crate::generated::gapic_dataplane::model::TypeCode`].
31        #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Default)]
32        #[repr(i32)]
33        #[non_exhaustive]
34        pub enum TypeCode {
35            /// Not specified.
36            #[default]
37            Unspecified = 0,
38            $(
39                #[doc = concat!("Spanner `", stringify!($variant), "` data type.")]
40                $variant = $val
41            ),*,
42            /// An unknown or unsupported type code value.
43            Unknown(i32),
44        }
45
46        impl From<i32> for TypeCode {
47            fn from(value: i32) -> Self {
48                match value {
49                    0 => TypeCode::Unspecified,
50                    $($val => TypeCode::$variant),*,
51                    v => TypeCode::Unknown(v),
52                }
53            }
54        }
55
56        impl From<TypeCode> for i32 {
57            fn from(value: TypeCode) -> Self {
58                match value {
59                    TypeCode::Unspecified => 0,
60                    $(TypeCode::$variant => $val),*,
61                    TypeCode::Unknown(v) => v,
62                }
63            }
64        }
65
66        impl From<crate::generated::gapic_dataplane::model::TypeCode> for TypeCode {
67            fn from(value: crate::generated::gapic_dataplane::model::TypeCode) -> Self {
68                 match value.value() {
69                    Some(v) => v.into(),
70                    None => TypeCode::Unspecified,
71                }
72            }
73        }
74
75        impl From<TypeCode> for crate::generated::gapic_dataplane::model::TypeCode {
76            fn from(value: TypeCode) -> Self {
77                let v: i32 = value.into();
78                v.into()
79            }
80        }
81    };
82}
83
84// The values here must match the values in the `google.spanner.v1.TypeCode` enum.
85// We cannot use the generated constants directly because they are not exposed as public constants.
86// See https://github.com/googleapis/googleapis/blob/master/google/spanner/v1/type.proto
87define_type_code!(
88    Bool = 1,
89    Int64 = 2,
90    Float64 = 3,
91    Float32 = 15,
92    Timestamp = 4,
93    Date = 5,
94    String = 6,
95    Bytes = 7,
96    Array = 8,
97    Struct = 9,
98    Numeric = 10,
99    Json = 11,
100    Proto = 13,
101    Enum = 14,
102    Interval = 16,
103    Uuid = 17,
104);
105
106impl From<model::Type> for Type {
107    fn from(value: model::Type) -> Self {
108        Type(value)
109    }
110}
111
112impl From<Type> for model::Type {
113    fn from(value: Type) -> Self {
114        value.0
115    }
116}
117
118impl Type {
119    pub(crate) fn from_proto(value: ProtoType) -> Self {
120        use gaxi::prost::FromProto;
121        value.cnv().unwrap_or_default().into()
122    }
123
124    /// Returns the type code.
125    pub fn code(&self) -> TypeCode {
126        self.0.code.clone().into()
127    }
128
129    /// Returns the element type of the array, or `None` if this type is not an array.
130    ///
131    /// # Example
132    ///
133    /// ```
134    /// use google_cloud_spanner::types::{array, int64};
135    ///
136    /// let array_type = array(int64());
137    /// assert_eq!(array_type.array_element_type(), Some(&int64()));
138    /// ```
139    pub fn array_element_type(&self) -> Option<&Type> {
140        self.0.array_element_type.as_deref().map(Type::from_ref)
141    }
142
143    /// Returns the struct type metadata, or `None` if this type is not a struct.
144    ///
145    /// When `code() == TypeCode::Struct`, this provides the field names and
146    /// their types. This is essential for reconstructing named fields from the
147    /// positional `ListValue` wire format that Spanner uses for STRUCT values.
148    pub fn struct_type(&self) -> Option<&model::StructType> {
149        self.0.struct_type.as_deref()
150    }
151
152    /// Returns the fully qualified name of the proto or enum type, or an empty string if not applicable.
153    ///
154    /// # Example
155    ///
156    /// ```
157    /// use google_cloud_spanner::types::proto;
158    ///
159    /// let proto_type = proto("examples.shipping.Address");
160    /// assert_eq!(proto_type.proto_type_fqn(), "examples.shipping.Address");
161    /// ```
162    pub fn proto_type_fqn(&self) -> &str {
163        &self.0.proto_type_fqn
164    }
165
166    /// Safely reinterprets a reference to the inner model type as a reference to Type.
167    /// Logical safety is guaranteed by #[repr(transparent)].
168    pub(crate) fn from_ref(v: &model::Type) -> &Self {
169        // SAFETY: Type is #[repr(transparent)] wrapper around model::Type.
170        unsafe { &*(v as *const model::Type as *const Type) }
171    }
172}
173
174static TYPE_INT64: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Int64));
175static TYPE_STRING: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::String));
176static TYPE_BOOL: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Bool));
177static TYPE_FLOAT32: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Float32));
178static TYPE_FLOAT64: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Float64));
179static TYPE_JSON: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Json));
180static TYPE_BYTES: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Bytes));
181static TYPE_TIMESTAMP: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Timestamp));
182static TYPE_DATE: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Date));
183static TYPE_NUMERIC: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Numeric));
184static TYPE_UUID: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Uuid));
185static TYPE_INTERVAL: LazyLock<Type> = LazyLock::new(|| create_type(TypeCode::Interval));
186static TYPE_PG_NUMERIC: LazyLock<Type> = LazyLock::new(|| {
187    let mut t = create_type(TypeCode::Numeric);
188    t.0.type_annotation = TypeAnnotationCode::PgNumeric;
189    t
190});
191static TYPE_PG_JSONB: LazyLock<Type> = LazyLock::new(|| {
192    let mut t = create_type(TypeCode::Json);
193    t.0.type_annotation = TypeAnnotationCode::PgJsonb;
194    t
195});
196static TYPE_PG_OID: LazyLock<Type> = LazyLock::new(|| {
197    let mut t = create_type(TypeCode::Int64);
198    t.0.type_annotation = TypeAnnotationCode::PgOid;
199    t
200});
201
202/// Returns a `Type` representing `INT64` (GoogleSQL) or `bigint` (PostgreSQL).
203pub fn int64() -> Type {
204    TYPE_INT64.clone()
205}
206
207/// Returns a `Type` representing `STRING` (GoogleSQL) or `character varying` (PostgreSQL).
208pub fn string() -> Type {
209    TYPE_STRING.clone()
210}
211
212/// Returns a `Type` representing `BOOL` (GoogleSQL) or `boolean` (PostgreSQL).
213pub fn bool() -> Type {
214    TYPE_BOOL.clone()
215}
216
217/// Returns a `Type` representing `FLOAT32` (GoogleSQL) or `real` (PostgreSQL).
218pub fn float32() -> Type {
219    TYPE_FLOAT32.clone()
220}
221
222/// Returns a `Type` representing `FLOAT64` (GoogleSQL) or `double precision` (PostgreSQL).
223pub fn float64() -> Type {
224    TYPE_FLOAT64.clone()
225}
226
227/// Returns a `Type` representing `JSON` (GoogleSQL).
228pub fn json() -> Type {
229    TYPE_JSON.clone()
230}
231
232/// Returns a `Type` representing `BYTES` (GoogleSQL) or `bytea` (PostgreSQL).
233pub fn bytes() -> Type {
234    TYPE_BYTES.clone()
235}
236
237/// Returns a `Type` representing `TIMESTAMP` (GoogleSQL) or `timestamp with time zone` (PostgreSQL).
238pub fn timestamp() -> Type {
239    TYPE_TIMESTAMP.clone()
240}
241
242/// Returns a `Type` representing `DATE` (GoogleSQL) or `date` (PostgreSQL).
243pub fn date() -> Type {
244    TYPE_DATE.clone()
245}
246
247/// Returns a `Type` representing `NUMERIC` (GoogleSQL) or `numeric` (PostgreSQL).
248pub fn numeric() -> Type {
249    TYPE_NUMERIC.clone()
250}
251
252/// Returns a `Type` representing `UUID` (GoogleSQL) or `uuid` (PostgreSQL).
253pub fn uuid() -> Type {
254    TYPE_UUID.clone()
255}
256
257/// Returns a `Type` representing `INTERVAL` (GoogleSQL) or `interval` (PostgreSQL).
258pub fn interval() -> Type {
259    TYPE_INTERVAL.clone()
260}
261
262/// Returns a `Type` representing `numeric` (PostgreSQL).
263pub fn pg_numeric() -> Type {
264    TYPE_PG_NUMERIC.clone()
265}
266
267/// Returns a `Type` representing `jsonb` (PostgreSQL).
268pub fn pg_jsonb() -> Type {
269    TYPE_PG_JSONB.clone()
270}
271
272/// Returns a `Type` representing `oid` (PostgreSQL).
273pub fn pg_oid() -> Type {
274    TYPE_PG_OID.clone()
275}
276
277/// Returns a `Type` representing `ARRAY<t>` (GoogleSQL) or `t[]` (PostgreSQL).
278pub fn array(element_type: Type) -> Type {
279    let mut t = create_type(TypeCode::Array);
280    t.0.array_element_type = Some(Box::new(element_type.0));
281    t
282}
283
284/// Returns a `Type` representing `PROTO` (GoogleSQL) with the given fully qualified proto type name.
285///
286/// Spanner uses the fully qualified proto type name to resolve the message schema from the
287/// database's proto bundle when binding query parameters.
288///
289/// # Example
290///
291/// ```
292/// use google_cloud_spanner::statement::Statement;
293/// use google_cloud_spanner::types::proto;
294///
295/// // Protobuf message serialized to bytes (e.g. from `address_proto.encode_to_vec()`)
296/// let address_payload = b"serialized-proto-address".to_vec();
297///
298/// let statement = Statement::builder(
299///     "SELECT OrderId, ShippingAddress.city FROM Orders WHERE ShippingAddress = @address",
300/// )
301/// .add_typed_param("address", address_payload, proto("examples.shipping.Address"))
302/// .build();
303/// ```
304pub fn proto(proto_type_fqn: impl Into<String>) -> Type {
305    let mut proto_type = create_type(TypeCode::Proto);
306    proto_type.0.proto_type_fqn = proto_type_fqn.into();
307    proto_type
308}
309
310/// Returns a `Type` representing `ENUM` (GoogleSQL) with the given fully qualified proto type name.
311///
312/// Spanner stores protobuf enum values as integers corresponding to their tag numbers in the
313/// proto definition. When binding enum parameters, provide the integer value and specify the
314/// fully qualified enum type name.
315///
316/// # Example
317///
318/// ```
319/// use google_cloud_spanner::statement::Statement;
320/// use google_cloud_spanner::types::proto_enum;
321///
322/// // Enum value corresponding to the protobuf tag number (e.g. `OrderStatus::Shipped as i32 as i64`)
323/// const STATUS_SHIPPED: i64 = 2;
324///
325/// let statement = Statement::builder("SELECT OrderId FROM Orders WHERE Status = @status")
326///     .add_typed_param(
327///         "status",
328///         STATUS_SHIPPED,
329///         proto_enum("examples.shipping.OrderStatus"),
330///     )
331///     .build();
332/// ```
333pub fn proto_enum(proto_type_fqn: impl Into<String>) -> Type {
334    let mut enum_type = create_type(TypeCode::Enum);
335    enum_type.0.proto_type_fqn = proto_type_fqn.into();
336    enum_type
337}
338
339pub(crate) fn create_type(code: TypeCode) -> Type {
340    Type(crate::generated::gapic_dataplane::model::Type {
341        code: code.into(),
342        array_element_type: None,
343        struct_type: None,
344        type_annotation: TypeAnnotationCode::Unspecified,
345        proto_type_fqn: String::new(),
346        _unknown_fields: Default::default(),
347    })
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use std::hash::Hash;
354
355    #[test]
356    fn test_type_code_round_trip() {
357        let codes = vec![
358            TypeCode::Unspecified,
359            TypeCode::Bool,
360            TypeCode::Int64,
361            TypeCode::Float64,
362            TypeCode::Float32,
363            TypeCode::Timestamp,
364            TypeCode::Date,
365            TypeCode::String,
366            TypeCode::Bytes,
367            TypeCode::Array,
368            TypeCode::Struct,
369            TypeCode::Numeric,
370            TypeCode::Json,
371            TypeCode::Proto,
372            TypeCode::Enum,
373            TypeCode::Interval,
374            TypeCode::Uuid,
375        ];
376
377        for code in codes {
378            let i: i32 = code.into();
379            let c: TypeCode = i.into();
380            assert_eq!(code, c);
381
382            let generated: crate::generated::gapic_dataplane::model::TypeCode = code.into();
383            let back: TypeCode = generated.into();
384            assert_eq!(code, back);
385        }
386    }
387
388    #[test]
389    fn test_unknown_type_code() {
390        let i = 999;
391        let code: TypeCode = i.into();
392        assert_eq!(code, TypeCode::Unknown(i));
393        assert_eq!(i32::from(code), i);
394    }
395
396    #[test]
397    fn test_unknown_type_code_from_generated() {
398        use crate::generated::gapic_dataplane::model::type_code::UnknownValue;
399        use wkt::internal::UnknownEnumValue;
400
401        let i = 999;
402        let unknown = UnknownValue(UnknownEnumValue::Integer(i));
403        let generated = crate::generated::gapic_dataplane::model::TypeCode::UnknownValue(unknown);
404        let code: TypeCode = generated.into();
405        assert_eq!(code, TypeCode::Unknown(i));
406    }
407
408    #[test]
409    fn test_simple_types() {
410        assert_eq!(int64().code(), TypeCode::Int64);
411        assert_eq!(string().code(), TypeCode::String);
412        assert_eq!(bool().code(), TypeCode::Bool);
413        assert_eq!(float64().code(), TypeCode::Float64);
414        assert_eq!(bytes().code(), TypeCode::Bytes);
415        assert_eq!(timestamp().code(), TypeCode::Timestamp);
416        assert_eq!(date().code(), TypeCode::Date);
417        assert_eq!(numeric().code(), TypeCode::Numeric);
418        assert_eq!(json().code(), TypeCode::Json);
419        assert_eq!(float32().code(), TypeCode::Float32);
420        assert_eq!(uuid().code(), TypeCode::Uuid);
421        assert_eq!(interval().code(), TypeCode::Interval);
422        // PG types are tested in test_pg_types
423    }
424
425    #[test]
426    fn test_default_type() {
427        let t = Type::default();
428        assert_eq!(t.code(), TypeCode::Unspecified);
429        assert_eq!(
430            t.0.code,
431            crate::generated::gapic_dataplane::model::TypeCode::Unspecified
432        );
433    }
434
435    #[test]
436    fn test_type_code_conversions() {
437        let code = TypeCode::Int64;
438        let integer_code: i32 = code.into();
439        assert_eq!(
440            integer_code, 2,
441            "TypeCode::Int64 converted to i32 should equal 2"
442        );
443
444        let internal_code: crate::generated::gapic_dataplane::model::TypeCode = code.into();
445        assert_eq!(
446            internal_code,
447            crate::generated::gapic_dataplane::model::TypeCode::Int64,
448            "TypeCode::Int64 converted to model::TypeCode should match"
449        );
450    }
451
452    #[test]
453    fn test_from_type_traits() {
454        let internal_type = crate::generated::gapic_dataplane::model::Type {
455            code: crate::generated::gapic_dataplane::model::TypeCode::Bool,
456            ..Default::default()
457        };
458        let converted_type: Type = internal_type.clone().into();
459        assert_eq!(
460            converted_type.code(),
461            TypeCode::Bool,
462            "converted Type should have Bool code"
463        );
464
465        let back: crate::generated::gapic_dataplane::model::Type = converted_type.into();
466        assert_eq!(
467            back.code, internal_type.code,
468            "roundtripped model::Type code should match original"
469        );
470    }
471
472    #[test]
473    fn test_array_type() {
474        let array_type = array(int64());
475        assert_eq!(
476            array_type.code(),
477            TypeCode::Array,
478            "array type should have Array code"
479        );
480        assert_eq!(
481            array_type
482                .array_element_type()
483                .expect("array element type must be present")
484                .code(),
485            TypeCode::Int64,
486            "array element type code should be Int64"
487        );
488    }
489
490    #[test]
491    fn test_pg_types() {
492        assert_eq!(pg_numeric().code(), TypeCode::Numeric);
493        assert_eq!(
494            pg_numeric().0.type_annotation,
495            TypeAnnotationCode::PgNumeric
496        );
497
498        assert_eq!(pg_jsonb().code(), TypeCode::Json);
499        assert_eq!(pg_jsonb().0.type_annotation, TypeAnnotationCode::PgJsonb);
500
501        assert_eq!(pg_oid().code(), TypeCode::Int64);
502        assert_eq!(pg_oid().0.type_annotation, TypeAnnotationCode::PgOid);
503    }
504
505    #[test]
506    fn array_element_type() {
507        let expected_element_type = int64();
508        let array_type = array(expected_element_type.clone());
509        assert_eq!(
510            array_type.array_element_type(),
511            Some(&expected_element_type),
512            "array element type should match the configured element type"
513        );
514
515        // Non-array types should return None
516        assert_eq!(
517            int64().array_element_type(),
518            None,
519            "int64 should not have an array element type"
520        );
521        assert_eq!(
522            string().array_element_type(),
523            None,
524            "string should not have an array element type"
525        );
526        assert_eq!(
527            Type::default().array_element_type(),
528            None,
529            "default Type should not have an array element type"
530        );
531    }
532
533    #[test]
534    fn test_auto_traits() {
535        static_assertions::assert_impl_all!(Type: Send, Sync, Clone, std::fmt::Debug);
536        static_assertions::assert_impl_all!(
537            TypeCode: Send,
538            Sync,
539            Clone,
540            Copy,
541            std::fmt::Debug,
542            PartialEq,
543            Eq,
544            Hash
545        );
546    }
547
548    #[test]
549    fn proto_and_enum_types() {
550        let proto_column = proto("google.example.Customer");
551        assert_eq!(
552            proto_column.code(),
553            TypeCode::Proto,
554            "expected TypeCode::Proto for proto"
555        );
556        assert_eq!(
557            proto_column.proto_type_fqn(),
558            "google.example.Customer",
559            "expected fully qualified proto type name"
560        );
561
562        let enum_column = proto_enum("google.example.CustomerStatus");
563        assert_eq!(
564            enum_column.code(),
565            TypeCode::Enum,
566            "expected TypeCode::Enum for proto_enum"
567        );
568        assert_eq!(
569            enum_column.proto_type_fqn(),
570            "google.example.CustomerStatus",
571            "expected fully qualified enum type name"
572        );
573
574        // Non-proto/enum types should return an empty string
575        assert_eq!(
576            int64().proto_type_fqn(),
577            "",
578            "expected empty string for non-proto/enum types"
579        );
580        assert_eq!(
581            Type::default().proto_type_fqn(),
582            "",
583            "expected empty string for default Type"
584        );
585    }
586}