cli/metadata/control/
utils.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 common_error::ext::BoxedError;
16use common_meta::error::Result as CommonMetaResult;
17use common_meta::key::table_name::{TableNameKey, TableNameManager};
18use common_meta::rpc::KeyValue;
19use serde::Serialize;
20use store_api::storage::TableId;
21
22/// Decodes a key-value pair into a string.
23pub fn decode_key_value(kv: KeyValue) -> CommonMetaResult<(String, String)> {
24    let key = String::from_utf8_lossy(&kv.key).to_string();
25    let value = String::from_utf8_lossy(&kv.value).to_string();
26    Ok((key, value))
27}
28
29/// Formats a value as a JSON string.
30pub fn json_fromatter<T>(pretty: bool, value: &T) -> String
31where
32    T: Serialize,
33{
34    if pretty {
35        serde_json::to_string_pretty(value).unwrap()
36    } else {
37        serde_json::to_string(value).unwrap()
38    }
39}
40
41/// Gets the table id by table name.
42pub async fn get_table_id_by_name(
43    table_name_manager: &TableNameManager,
44    catalog_name: &str,
45    schema_name: &str,
46    table_name: &str,
47) -> Result<Option<TableId>, BoxedError> {
48    let table_name_key = TableNameKey::new(catalog_name, schema_name, table_name);
49    let Some(table_name_value) = table_name_manager
50        .get(table_name_key)
51        .await
52        .map_err(BoxedError::new)?
53    else {
54        return Ok(None);
55    };
56    Ok(Some(table_name_value.table_id()))
57}