arrow_schema/extension/canonical/
uuid.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! UUID
19//!
20//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#uuid>
21
22use crate::{extension::ExtensionType, ArrowError, DataType};
23
24/// The extension type for `UUID`.
25///
26/// Extension name: `arrow.uuid`.
27///
28/// The storage type of the extension is `FixedSizeBinary` with a length of
29/// 16 bytes.
30///
31/// Note:
32/// A specific UUID version is not required or guaranteed. This extension
33/// represents UUIDs as `FixedSizeBinary(16)` with big-endian notation and
34/// does not interpret the bytes in any way.
35///
36/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#uuid>
37#[derive(Debug, Default, Clone, Copy, PartialEq)]
38pub struct Uuid;
39
40impl ExtensionType for Uuid {
41    const NAME: &'static str = "arrow.uuid";
42
43    type Metadata = ();
44
45    fn metadata(&self) -> &Self::Metadata {
46        &()
47    }
48
49    fn serialize_metadata(&self) -> Option<String> {
50        None
51    }
52
53    fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
54        metadata.map_or_else(
55            || Ok(()),
56            |_| {
57                Err(ArrowError::InvalidArgumentError(
58                    "Uuid extension type expects no metadata".to_owned(),
59                ))
60            },
61        )
62    }
63
64    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
65        match data_type {
66            DataType::FixedSizeBinary(16) => Ok(()),
67            data_type => Err(ArrowError::InvalidArgumentError(format!(
68                "Uuid data type mismatch, expected FixedSizeBinary(16), found {data_type}"
69            ))),
70        }
71    }
72
73    fn try_new(data_type: &DataType, _metadata: Self::Metadata) -> Result<Self, ArrowError> {
74        Self.supports_data_type(data_type).map(|_| Self)
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    #[cfg(feature = "canonical_extension_types")]
81    use crate::extension::CanonicalExtensionType;
82    use crate::{
83        extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY},
84        Field,
85    };
86
87    use super::*;
88
89    #[test]
90    fn valid() -> Result<(), ArrowError> {
91        let mut field = Field::new("", DataType::FixedSizeBinary(16), false);
92        field.try_with_extension_type(Uuid)?;
93        field.try_extension_type::<Uuid>()?;
94        #[cfg(feature = "canonical_extension_types")]
95        assert_eq!(
96            field.try_canonical_extension_type()?,
97            CanonicalExtensionType::Uuid(Uuid)
98        );
99        Ok(())
100    }
101
102    #[test]
103    #[should_panic(expected = "Field extension type name missing")]
104    fn missing_name() {
105        let field = Field::new("", DataType::FixedSizeBinary(16), false);
106        field.extension_type::<Uuid>();
107    }
108
109    #[test]
110    #[should_panic(expected = "expected FixedSizeBinary(16), found FixedSizeBinary(8)")]
111    fn invalid_type() {
112        Field::new("", DataType::FixedSizeBinary(8), false).with_extension_type(Uuid);
113    }
114
115    #[test]
116    #[should_panic(expected = "Uuid extension type expects no metadata")]
117    fn with_metadata() {
118        let field = Field::new("", DataType::FixedSizeBinary(16), false).with_metadata(
119            [
120                (EXTENSION_TYPE_NAME_KEY.to_owned(), Uuid::NAME.to_owned()),
121                (EXTENSION_TYPE_METADATA_KEY.to_owned(), "".to_owned()),
122            ]
123            .into_iter()
124            .collect(),
125        );
126        field.extension_type::<Uuid>();
127    }
128}