Skip to main content

session/
query_id.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::fmt::{Display, Formatter};
16use std::str::FromStr;
17
18use uuid::Uuid;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub struct QueryId(Uuid);
22
23impl QueryId {
24    pub fn new() -> Self {
25        Self(Uuid::now_v7())
26    }
27
28    pub fn as_uuid(&self) -> &Uuid {
29        &self.0
30    }
31}
32
33impl Default for QueryId {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38
39impl Display for QueryId {
40    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
41        self.0.fmt(f)
42    }
43}
44
45impl FromStr for QueryId {
46    type Err = uuid::Error;
47
48    fn from_str(s: &str) -> Result<Self, Self::Err> {
49        Ok(Self(Uuid::parse_str(s)?))
50    }
51}
52
53impl From<Uuid> for QueryId {
54    fn from(value: Uuid) -> Self {
55        Self(value)
56    }
57}
58
59impl From<QueryId> for Uuid {
60    fn from(value: QueryId) -> Self {
61        value.0
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn query_id_round_trips_through_string() {
71        let query_id = QueryId::new();
72        let encoded = query_id.to_string();
73
74        assert_eq!(encoded.parse::<QueryId>().unwrap(), query_id);
75    }
76}