Skip to main content

datatypes/extension/
json.rs

1// Copyright 2023 Greptime Team
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//     http://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 std::collections::HashMap;
16use std::sync::Arc;
17
18use arrow_array::ArrayRef;
19use arrow_schema::extension::{
20    EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY, ExtensionType,
21};
22use arrow_schema::{ArrowError, DataType, Field, FieldRef, Schema, SchemaRef};
23use parquet_variant_compute::VariantType;
24use serde::{Deserialize, Serialize};
25use snafu::{ResultExt, ensure};
26
27use crate::error::{InvalidJson2LayoutSnafu, SerializeSnafu};
28pub use crate::json::JSON2_REMAINDER_FIELD_NAME;
29use crate::json::JsonSettings;
30use crate::schema::Metadata;
31
32/// Aligns JSON2 field types with their built arrays while preserving field and schema metadata.
33pub fn align_schema_with_json_array(schema: SchemaRef, columns: &[ArrayRef]) -> SchemaRef {
34    if schema.fields().iter().all(|f| !is_json2_extension_type(f)) {
35        return schema;
36    }
37
38    let mut fields = Vec::with_capacity(schema.fields().len());
39    for (field, array) in schema.fields().iter().zip(columns) {
40        if !is_json2_extension_type(field) {
41            fields.push(field.clone());
42            continue;
43        }
44
45        let mut field = field.as_ref().clone();
46        field.set_data_type(array.data_type().clone());
47        fields.push(Arc::new(field));
48    }
49
50    Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone()))
51}
52
53const LEGACY_JSON_STRUCTURE_SETTINGS_KEY: &str = "json_structure_settings";
54const JSON2_LAYOUT_V1: u8 = 1;
55const JSON2_LAYOUT_V2: u8 = 2;
56
57/// Parsed physical layout of a JSON2 Arrow root field.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Json2PhysicalLayout {
60    version: u8,
61}
62
63impl Json2PhysicalLayout {
64    /// Parses the JSON2 layout version from a root field.
65    ///
66    /// The version is read from the extension metadata; missing metadata
67    /// defaults to V1.
68    ///
69    /// Supported versions:
70    /// - V1
71    /// - V2
72    ///
73    /// Errors when the field is not a JSON2 extension or the version is not
74    /// one of the supported versions.
75    pub fn try_from_root(field: &Field) -> crate::error::Result<Self> {
76        ensure!(
77            is_json2_extension_type(field),
78            InvalidJson2LayoutSnafu {
79                reason: format!("field '{}' is not a JSON2 extension", field.name()),
80            }
81        );
82
83        let version = match field.extension_type_name() {
84            Some(Json2ExtensionType::NAME) => field
85                .metadata()
86                .get(EXTENSION_TYPE_METADATA_KEY)
87                .map(|x| parse_version(x))
88                .transpose()?
89                .flatten()
90                .unwrap_or(JSON2_LAYOUT_V1),
91            _ => JSON2_LAYOUT_V1,
92        };
93        ensure!(
94            matches!(version, JSON2_LAYOUT_V1 | JSON2_LAYOUT_V2),
95            InvalidJson2LayoutSnafu {
96                reason: format!("unsupported JSON2 layout version: {version}"),
97            }
98        );
99        Ok(Self { version })
100    }
101
102    /// Returns whether this is the JSON2 physical layout version 2.
103    pub fn is_version_2(&self) -> bool {
104        self.version == JSON2_LAYOUT_V2
105    }
106}
107
108fn parse_version(metadata: &str) -> crate::error::Result<Option<u8>> {
109    serde_json::from_str::<JsonMetadata>(metadata)
110        .map(|x| x.layout_version)
111        .map_err(|e| {
112            InvalidJson2LayoutSnafu {
113                reason: format!(r#"invalid extension metadata: "{metadata}", error: {e}"#),
114            }
115            .build()
116        })
117}
118
119/// Returns the remainder field of a JSON2 v2 root.
120/// Validates the layout version and remainder type, returning `None` for legacy layouts.
121pub fn json2_remainder_field(field: &Field) -> crate::error::Result<Option<&FieldRef>> {
122    let layout = Json2PhysicalLayout::try_from_root(field)?;
123    if !layout.is_version_2() {
124        return Ok(None);
125    }
126
127    let remainder = if let DataType::Struct(fields) = field.data_type() {
128        fields
129            .iter()
130            .find(|x| x.name() == JSON2_REMAINDER_FIELD_NAME)
131    } else {
132        None
133    };
134
135    if let Some(remainder) = remainder {
136        let _ = remainder.try_extension_type::<VariantType>().map_err(|e| {
137            InvalidJson2LayoutSnafu {
138                reason: e.to_string(),
139            }
140            .build()
141        })?;
142    }
143    Ok(remainder)
144}
145
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct JsonMetadata {
148    /// JSON2 settings stored in Arrow extension metadata.
149    json_settings: JsonSettings,
150    /// Physical JSON2 layout used by this Arrow field.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    layout_version: Option<u8>,
153}
154
155impl JsonMetadata {
156    /// Creates metadata for the latest JSON2 layout (currently V2).
157    pub fn new(json_settings: JsonSettings) -> Self {
158        Self {
159            json_settings,
160            layout_version: Some(JSON2_LAYOUT_V2),
161        }
162    }
163
164    /// Creates metadata for the legacy JSON2 layout.
165    pub fn new_v1(json_settings: JsonSettings) -> Self {
166        Self {
167            json_settings,
168            layout_version: None,
169        }
170    }
171
172    /// Returns the JSON2 settings.
173    pub fn json_settings(&self) -> &JsonSettings {
174        &self.json_settings
175    }
176
177    /// Consumes the metadata and returns its JSON2 settings.
178    pub fn into_json_settings(self) -> JsonSettings {
179        self.json_settings
180    }
181
182    /// Returns whether this metadata describes JSON2 layout version 2.
183    pub fn is_version_2(&self) -> bool {
184        self.layout_version == Some(JSON2_LAYOUT_V2)
185    }
186}
187
188impl Default for JsonMetadata {
189    fn default() -> Self {
190        Self::new(JsonSettings::default())
191    }
192}
193
194/// Arrow extension type for legacy JSONB columns.
195#[derive(Debug, Clone, Default)]
196pub struct JsonExtensionType;
197
198impl ExtensionType for JsonExtensionType {
199    const NAME: &'static str = "greptime.json";
200    type Metadata = ();
201
202    fn metadata(&self) -> &Self::Metadata {
203        &()
204    }
205
206    fn serialize_metadata(&self) -> Option<String> {
207        None
208    }
209
210    fn deserialize_metadata(_metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
211        Ok(())
212    }
213
214    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
215        match data_type {
216            DataType::Binary | DataType::Null => Ok(()),
217            t => Err(ArrowError::InvalidArgumentError(format!(
218                "Unexpected data type {t} for JsonExtensionType"
219            ))),
220        }
221    }
222
223    fn try_new(data_type: &DataType, _metadata: Self::Metadata) -> Result<Self, ArrowError> {
224        Self.supports_data_type(data_type).map(|_| Self)
225    }
226}
227
228/// Arrow extension type for JSON2 columns and concretized projections.
229#[derive(Debug, Clone, Default)]
230pub struct Json2ExtensionType(Arc<JsonMetadata>);
231
232impl Json2ExtensionType {
233    /// Creates a JSON2 extension type with the given metadata.
234    pub fn new(metadata: Arc<JsonMetadata>) -> Self {
235        Self(metadata)
236    }
237}
238
239impl ExtensionType for Json2ExtensionType {
240    const NAME: &'static str = "greptime.json2";
241    type Metadata = Arc<JsonMetadata>;
242
243    fn metadata(&self) -> &Self::Metadata {
244        &self.0
245    }
246
247    fn serialize_metadata(&self) -> Option<String> {
248        serde_json::to_string(self.metadata()).ok()
249    }
250
251    fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
252        if let Some(metadata) = metadata {
253            let metadata = serde_json::from_str(metadata).map_err(|e| {
254                ArrowError::ParseError(format!("Failed to deserialize JSON metadata: {}", e))
255            })?;
256            Ok(Arc::new(metadata))
257        } else {
258            Ok(Arc::new(JsonMetadata::new_v1(JsonSettings::default())))
259        }
260    }
261
262    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
263        match data_type {
264            // object
265            DataType::Struct(_)
266            // array
267            | DataType::List(_)
268            | DataType::ListView(_)
269            | DataType::LargeList(_)
270            | DataType::LargeListView(_)
271            // string
272            | DataType::Utf8
273            | DataType::Utf8View
274            | DataType::LargeUtf8
275            // number
276            | DataType::Int8
277            | DataType::Int16
278            | DataType::Int32
279            | DataType::Int64
280            | DataType::UInt8
281            | DataType::UInt16
282            | DataType::UInt32
283            | DataType::UInt64
284            | DataType::Float32
285            | DataType::Float64
286            // boolean
287            | DataType::Boolean
288            // null
289            | DataType::Null
290            // legacy json type
291            | DataType::Binary => Ok(()),
292            dt => Err(ArrowError::SchemaError(format!(
293                "Unexpected data type {dt}"
294            ))),
295        }
296    }
297
298    fn try_new(data_type: &DataType, metadata: Self::Metadata) -> Result<Self, ArrowError> {
299        let json = Self(metadata);
300        json.supports_data_type(data_type)?;
301        Ok(json)
302    }
303}
304
305/// Returns JSON2 column metadata with updated settings and the latest layout.
306///
307/// Existing SSTs retain their own physical layout metadata.
308pub fn json2_metadata_with_updated_settings(
309    current_metadata: &Metadata,
310    settings: JsonSettings,
311) -> crate::error::Result<Metadata> {
312    let json_metadata = JsonMetadata::new(settings);
313
314    let mut metadata = current_metadata.clone();
315    metadata.insert(
316        EXTENSION_TYPE_NAME_KEY.to_string(),
317        Json2ExtensionType::NAME.to_string(),
318    );
319    metadata.insert(
320        EXTENSION_TYPE_METADATA_KEY.to_string(),
321        serde_json::to_string(&json_metadata).context(SerializeSnafu)?,
322    );
323    Ok(metadata)
324}
325
326/// Checks whether this field is either a legacy JSONB or JSON2 extension type.
327pub fn is_any_json_extension_type<T: AsRef<Field>>(field: T) -> bool {
328    let name = field.as_ref().extension_type_name();
329    name == Some(JsonExtensionType::NAME) || name == Some(Json2ExtensionType::NAME)
330}
331
332/// Parses JSON2 settings stored by the historical `greptime.json` extension.
333pub fn parse_legacy_json2_settings(
334    metadata: &HashMap<String, String>,
335) -> crate::error::Result<Option<JsonSettings>> {
336    #[derive(Deserialize)]
337    struct LegacyJsonMetadata {
338        #[serde(default)]
339        json_settings: Option<JsonSettings>,
340    }
341
342    if metadata.get(EXTENSION_TYPE_NAME_KEY).map(String::as_str) != Some(JsonExtensionType::NAME) {
343        return Ok(None);
344    }
345
346    metadata
347        .get(EXTENSION_TYPE_METADATA_KEY)
348        .map(|json| {
349            serde_json::from_str::<LegacyJsonMetadata>(json)
350                .map(|x| x.json_settings)
351                .context(crate::error::DeserializeSnafu { json })
352        })
353        .transpose()
354        .map(Option::flatten)
355}
356
357/// Checks whether this field uses the JSON2 extension layout from before type hints.
358///
359/// That layout used the same `greptime.json` extension name and
360/// `json_structure_settings` metadata as legacy JSONB. Its structured Arrow data type is
361/// therefore required to distinguish JSON2 from Binary JSONB.
362pub fn is_legacy_json2_extension_type<T: AsRef<Field>>(field: T) -> bool {
363    let field = field.as_ref();
364    if field.extension_type_name() != Some(JsonExtensionType::NAME)
365        || !matches!(field.data_type(), DataType::Struct(_))
366    {
367        return false;
368    }
369
370    field
371        .metadata()
372        .get(EXTENSION_TYPE_METADATA_KEY)
373        .and_then(|json| serde_json::from_str::<serde_json::Value>(json).ok())
374        .is_some_and(|metadata| metadata.get(LEGACY_JSON_STRUCTURE_SETTINGS_KEY).is_some())
375}
376
377/// Check if this field is a JSON2 extension type.
378///
379/// New schemas use [`Json2ExtensionType`]. For compatibility, old fields using
380/// [`JsonExtensionType`] with JSON settings or the pre-type-hint structured layout are also
381/// recognized as JSON2.
382pub fn is_json2_extension_type<T: AsRef<Field>>(field: T) -> bool {
383    let field = field.as_ref();
384    field.extension_type_name() == Some(Json2ExtensionType::NAME)
385        || parse_legacy_json2_settings(field.metadata()).is_ok_and(|x| x.is_some())
386        || is_legacy_json2_extension_type(field)
387}
388
389#[cfg(test)]
390mod tests {
391    use std::collections::HashMap;
392
393    use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
394    use arrow_schema::{Field, Fields};
395
396    use super::*;
397    use crate::vectors::json::variant::variant_field;
398
399    #[test]
400    fn test_json2_extension_type_detection() {
401        let extension = Json2ExtensionType::new(Arc::new(JsonMetadata::default()));
402        let json2 = Field::new("j", DataType::Struct(Fields::empty()), true)
403            .with_extension_type(extension.clone());
404        // "projection" is the special hack for selecting the whole column of json2
405        let projection = Field::new("j", DataType::Binary, true).with_extension_type(extension);
406        let legacy_json2 = Field::new("j", DataType::Struct(Fields::empty()), true).with_metadata(
407            HashMap::from([
408                (
409                    EXTENSION_TYPE_NAME_KEY.to_string(),
410                    JsonExtensionType::NAME.to_string(),
411                ),
412                (
413                    EXTENSION_TYPE_METADATA_KEY.to_string(),
414                    serde_json::json!({ "json_settings": JsonSettings::default() }).to_string(),
415                ),
416            ]),
417        );
418        // Before type hints, JSON2 and JSONB shared extension metadata and were distinguished by
419        // their physical Arrow data types.
420        let legacy_structure_metadata = HashMap::from([
421            (
422                EXTENSION_TYPE_NAME_KEY.to_string(),
423                JsonExtensionType::NAME.to_string(),
424            ),
425            (
426                EXTENSION_TYPE_METADATA_KEY.to_string(),
427                serde_json::json!({
428                    (LEGACY_JSON_STRUCTURE_SETTINGS_KEY): { "Structured": null }
429                })
430                .to_string(),
431            ),
432        ]);
433        let pre_type_hint_json2 = Field::new("j", DataType::Struct(Fields::empty()), true)
434            .with_metadata(legacy_structure_metadata.clone());
435        let legacy_jsonb =
436            Field::new("j", DataType::Binary, true).with_metadata(legacy_structure_metadata);
437
438        assert!(is_json2_extension_type(&json2));
439        assert!(is_json2_extension_type(&projection));
440        assert!(is_json2_extension_type(&legacy_json2));
441        assert!(is_legacy_json2_extension_type(&pre_type_hint_json2));
442        assert!(is_json2_extension_type(&pre_type_hint_json2));
443        assert_eq!(
444            Some(JsonSettings::default()),
445            parse_legacy_json2_settings(legacy_json2.metadata()).unwrap()
446        );
447        assert!(!is_legacy_json2_extension_type(&legacy_jsonb));
448        assert!(!is_json2_extension_type(&legacy_jsonb));
449        assert!(JsonExtensionType::try_new(&DataType::Binary, ()).is_ok());
450        assert!(JsonExtensionType::try_new(&DataType::Null, ()).is_ok());
451        assert!(JsonExtensionType::try_new(&DataType::Struct(Fields::empty()), ()).is_err());
452    }
453
454    #[test]
455    fn test_json_metadata_layout_version_compatibility() -> serde_json::Result<()> {
456        let legacy: JsonMetadata = serde_json::from_str(r#"{"json_settings":{}}"#)?;
457        assert!(!legacy.is_version_2());
458
459        let metadata = JsonMetadata::new(JsonSettings::default());
460        assert!(metadata.is_version_2());
461        let serialized = serde_json::to_string(&metadata)?;
462        let deserialized: JsonMetadata = serde_json::from_str(&serialized)?;
463        assert!(deserialized.is_version_2());
464        assert_eq!(deserialized, metadata);
465        Ok(())
466    }
467
468    #[test]
469    fn test_json2_metadata_with_updated_settings_upgrades_layout() -> crate::error::Result<()> {
470        for (name, json) in [
471            (JsonExtensionType::NAME, r#"{"json_settings":{}}"#),
472            (Json2ExtensionType::NAME, r#"{"json_settings":{}}"#),
473            (
474                Json2ExtensionType::NAME,
475                r#"{"json_settings":{},"layout_version":2}"#,
476            ),
477        ] {
478            let metadata = HashMap::from([
479                (EXTENSION_TYPE_NAME_KEY.to_string(), name.to_string()),
480                (EXTENSION_TYPE_METADATA_KEY.to_string(), json.to_string()),
481                ("other".to_string(), "kept".to_string()),
482            ]);
483            let settings = JsonSettings::try_new(vec![], Some(10))?;
484            let updated = json2_metadata_with_updated_settings(&metadata, settings.clone())?;
485            assert_eq!(Some("kept"), updated.get("other").map(String::as_str));
486            assert_eq!(
487                Some(Json2ExtensionType::NAME),
488                updated.get(EXTENSION_TYPE_NAME_KEY).map(String::as_str)
489            );
490            let json_metadata: JsonMetadata =
491                serde_json::from_str(updated.get(EXTENSION_TYPE_METADATA_KEY).unwrap()).unwrap();
492            assert_eq!(JsonMetadata::new(settings), json_metadata);
493        }
494        Ok(())
495    }
496
497    #[test]
498    fn test_parse_json2_physical_layout() -> crate::error::Result<()> {
499        let legacy = Field::new("data", DataType::Struct(Fields::empty()), true)
500            .with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata::new_v1(
501                JsonSettings::default(),
502            ))));
503        assert!(!Json2PhysicalLayout::try_from_root(&legacy)?.is_version_2());
504
505        let v2 = Field::new(
506            "data",
507            DataType::Struct(
508                vec![
509                    Arc::new(variant_field(JSON2_REMAINDER_FIELD_NAME, true)),
510                    Arc::new(Field::new("count", DataType::Int64, true)),
511                ]
512                .into(),
513            ),
514            true,
515        )
516        .with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata::new(
517            JsonSettings::default(),
518        ))));
519        assert!(Json2PhysicalLayout::try_from_root(&v2)?.is_version_2());
520        let remainder = json2_remainder_field(&v2)?.unwrap();
521        assert_eq!(JSON2_REMAINDER_FIELD_NAME, remainder.name());
522        Ok(())
523    }
524
525    #[test]
526    fn test_reject_invalid_json2_physical_layout() {
527        let field = Field::new("data", DataType::Struct(Fields::empty()), true);
528        assert!(Json2PhysicalLayout::try_from_root(&field).is_err());
529
530        let metadata =
531            Json2ExtensionType::new(Arc::new(JsonMetadata::new(JsonSettings::default())));
532        let missing = Field::new("data", DataType::Struct(Fields::empty()), true)
533            .with_extension_type(metadata.clone());
534        assert!(json2_remainder_field(&missing).is_ok_and(|x| x.is_none()));
535
536        let invalid = Field::new(
537            "data",
538            DataType::Struct(
539                vec![Arc::new(Field::new(
540                    JSON2_REMAINDER_FIELD_NAME,
541                    DataType::Binary,
542                    true,
543                ))]
544                .into(),
545            ),
546            true,
547        )
548        .with_extension_type(metadata);
549        assert!(json2_remainder_field(&invalid).is_err());
550
551        let future = Field::new("data", DataType::Struct(Fields::empty()), true)
552            .with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata {
553                json_settings: JsonSettings::default(),
554                layout_version: Some(JSON2_LAYOUT_V2 + 1),
555            })));
556        assert!(Json2PhysicalLayout::try_from_root(&future).is_err());
557    }
558}