cli/data/export_v2/schema.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
15//! Minimal schema index structures for Export/Import V2.
16//!
17//! The canonical schema representation is the per-schema DDL file under
18//! `schema/ddl/`. `schemas.json` only records which schemas exist in a snapshot.
19
20use std::collections::HashMap;
21
22use serde::{Deserialize, Serialize};
23
24/// Schema directory name within snapshot.
25pub const SCHEMA_DIR: &str = "schema";
26
27/// DDL directory name within schema directory.
28pub const DDL_DIR: &str = "ddl";
29
30/// Schema definition file name.
31pub const SCHEMAS_FILE: &str = "schemas.json";
32
33/// Schema (database) definition.
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35pub struct SchemaDefinition {
36 /// Catalog name.
37 pub catalog: String,
38 /// Schema (database) name.
39 pub name: String,
40 /// Schema options (if any).
41 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
42 pub options: HashMap<String, String>,
43}
44
45/// Minimal schema index stored in a snapshot.
46#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
47pub struct SchemaSnapshot {
48 /// Schema (database) definitions.
49 pub schemas: Vec<SchemaDefinition>,
50}
51
52impl SchemaSnapshot {
53 /// Creates an empty schema snapshot.
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 /// Adds a schema definition.
59 pub fn add_schema(&mut self, schema: SchemaDefinition) {
60 self.schemas.push(schema);
61 }
62
63 /// Filters the snapshot to only include specified schemas.
64 pub fn filter_schemas(&self, schemas: &[String]) -> Self {
65 Self {
66 schemas: self
67 .schemas
68 .iter()
69 .filter(|s| schemas.contains(&s.name))
70 .cloned()
71 .collect(),
72 }
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn test_schema_snapshot_filter() {
82 let mut snapshot = SchemaSnapshot::new();
83 snapshot.add_schema(SchemaDefinition {
84 catalog: "greptime".to_string(),
85 name: "public".to_string(),
86 options: HashMap::new(),
87 });
88 snapshot.add_schema(SchemaDefinition {
89 catalog: "greptime".to_string(),
90 name: "private".to_string(),
91 options: HashMap::new(),
92 });
93
94 let filtered = snapshot.filter_schemas(&["public".to_string()]);
95 assert_eq!(filtered.schemas.len(), 1);
96 assert_eq!(filtered.schemas[0].name, "public");
97 }
98}