common_meta/ddl/
alter_database.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use async_trait::async_trait;
use common_procedure::error::{FromJsonSnafu, Result as ProcedureResult, ToJsonSnafu};
use common_procedure::{Context as ProcedureContext, LockKey, Procedure, Status};
use common_telemetry::tracing::info;
use serde::{Deserialize, Serialize};
use snafu::{ensure, ResultExt};
use strum::AsRefStr;

use super::utils::handle_retry_error;
use crate::cache_invalidator::Context;
use crate::ddl::DdlContext;
use crate::error::{Result, SchemaNotFoundSnafu};
use crate::instruction::CacheIdent;
use crate::key::schema_name::{SchemaName, SchemaNameKey, SchemaNameValue};
use crate::key::DeserializedValueWithBytes;
use crate::lock_key::{CatalogLock, SchemaLock};
use crate::rpc::ddl::UnsetDatabaseOption::{self};
use crate::rpc::ddl::{AlterDatabaseKind, AlterDatabaseTask, SetDatabaseOption};
use crate::ClusterId;

pub struct AlterDatabaseProcedure {
    pub context: DdlContext,
    pub data: AlterDatabaseData,
}

fn build_new_schema_value(
    mut value: SchemaNameValue,
    alter_kind: &AlterDatabaseKind,
) -> Result<SchemaNameValue> {
    match alter_kind {
        AlterDatabaseKind::SetDatabaseOptions(options) => {
            for option in options.0.iter() {
                match option {
                    SetDatabaseOption::Ttl(ttl) => {
                        value.ttl = Some(*ttl);
                    }
                }
            }
        }
        AlterDatabaseKind::UnsetDatabaseOptions(keys) => {
            for key in keys.0.iter() {
                match key {
                    UnsetDatabaseOption::Ttl => value.ttl = None,
                }
            }
        }
    }
    Ok(value)
}

impl AlterDatabaseProcedure {
    pub const TYPE_NAME: &'static str = "metasrv-procedure::AlterDatabase";

    pub fn new(
        cluster_id: ClusterId,
        task: AlterDatabaseTask,
        context: DdlContext,
    ) -> Result<Self> {
        Ok(Self {
            context,
            data: AlterDatabaseData::new(task, cluster_id)?,
        })
    }

    pub fn from_json(json: &str, context: DdlContext) -> ProcedureResult<Self> {
        let data = serde_json::from_str(json).context(FromJsonSnafu)?;

        Ok(Self { context, data })
    }

    pub async fn on_prepare(&mut self) -> Result<Status> {
        let value = self
            .context
            .table_metadata_manager
            .schema_manager()
            .get(SchemaNameKey::new(self.data.catalog(), self.data.schema()))
            .await?;

        ensure!(
            value.is_some(),
            SchemaNotFoundSnafu {
                table_schema: self.data.schema(),
            }
        );

        self.data.schema_value = value;
        self.data.state = AlterDatabaseState::UpdateMetadata;

        Ok(Status::executing(true))
    }

    pub async fn on_update_metadata(&mut self) -> Result<Status> {
        let schema_name = SchemaNameKey::new(self.data.catalog(), self.data.schema());

        // Safety: schema_value is not None.
        let current_schema_value = self.data.schema_value.as_ref().unwrap();

        let new_schema_value = build_new_schema_value(
            current_schema_value.get_inner_ref().clone(),
            &self.data.kind,
        )?;

        self.context
            .table_metadata_manager
            .schema_manager()
            .update(schema_name, current_schema_value, &new_schema_value)
            .await?;

        info!("Updated database metadata for schema {schema_name}");
        self.data.state = AlterDatabaseState::InvalidateSchemaCache;
        Ok(Status::executing(true))
    }

    pub async fn on_invalidate_schema_cache(&mut self) -> Result<Status> {
        let cache_invalidator = &self.context.cache_invalidator;
        cache_invalidator
            .invalidate(
                &Context::default(),
                &[CacheIdent::SchemaName(SchemaName {
                    catalog_name: self.data.catalog().to_string(),
                    schema_name: self.data.schema().to_string(),
                })],
            )
            .await?;

        Ok(Status::done())
    }
}

#[async_trait]
impl Procedure for AlterDatabaseProcedure {
    fn type_name(&self) -> &str {
        Self::TYPE_NAME
    }

    async fn execute(&mut self, _ctx: &ProcedureContext) -> ProcedureResult<Status> {
        match self.data.state {
            AlterDatabaseState::Prepare => self.on_prepare().await,
            AlterDatabaseState::UpdateMetadata => self.on_update_metadata().await,
            AlterDatabaseState::InvalidateSchemaCache => self.on_invalidate_schema_cache().await,
        }
        .map_err(handle_retry_error)
    }

    fn dump(&self) -> ProcedureResult<String> {
        serde_json::to_string(&self.data).context(ToJsonSnafu)
    }

    fn lock_key(&self) -> LockKey {
        let catalog = self.data.catalog();
        let schema = self.data.schema();

        let lock_key = vec![
            CatalogLock::Read(catalog).into(),
            SchemaLock::write(catalog, schema).into(),
        ];

        LockKey::new(lock_key)
    }
}

#[derive(Debug, Serialize, Deserialize, AsRefStr)]
enum AlterDatabaseState {
    Prepare,
    UpdateMetadata,
    InvalidateSchemaCache,
}

/// The data of alter database procedure.
#[derive(Debug, Serialize, Deserialize)]
pub struct AlterDatabaseData {
    cluster_id: ClusterId,
    state: AlterDatabaseState,
    kind: AlterDatabaseKind,
    catalog_name: String,
    schema_name: String,
    schema_value: Option<DeserializedValueWithBytes<SchemaNameValue>>,
}

impl AlterDatabaseData {
    pub fn new(task: AlterDatabaseTask, cluster_id: ClusterId) -> Result<Self> {
        Ok(Self {
            cluster_id,
            state: AlterDatabaseState::Prepare,
            kind: AlterDatabaseKind::try_from(task.alter_expr.kind.unwrap())?,
            catalog_name: task.alter_expr.catalog_name,
            schema_name: task.alter_expr.schema_name,
            schema_value: None,
        })
    }

    pub fn catalog(&self) -> &str {
        &self.catalog_name
    }

    pub fn schema(&self) -> &str {
        &self.schema_name
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use crate::ddl::alter_database::build_new_schema_value;
    use crate::key::schema_name::SchemaNameValue;
    use crate::rpc::ddl::{
        AlterDatabaseKind, SetDatabaseOption, SetDatabaseOptions, UnsetDatabaseOption,
        UnsetDatabaseOptions,
    };

    #[test]
    fn test_build_new_schema_value() {
        let set_ttl = AlterDatabaseKind::SetDatabaseOptions(SetDatabaseOptions(vec![
            SetDatabaseOption::Ttl(Duration::from_secs(10).into()),
        ]));
        let current_schema_value = SchemaNameValue::default();
        let new_schema_value =
            build_new_schema_value(current_schema_value.clone(), &set_ttl).unwrap();
        assert_eq!(new_schema_value.ttl, Some(Duration::from_secs(10).into()));

        let unset_ttl_alter_kind =
            AlterDatabaseKind::UnsetDatabaseOptions(UnsetDatabaseOptions(vec![
                UnsetDatabaseOption::Ttl,
            ]));
        let new_schema_value =
            build_new_schema_value(current_schema_value, &unset_ttl_alter_kind).unwrap();
        assert_eq!(new_schema_value.ttl, None);
    }
}