Skip to main content

mz_repr/
query_policy_id.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::fmt;
11use std::str::FromStr;
12
13use anyhow::{Error, anyhow};
14#[cfg(any(test, feature = "proptest"))]
15use proptest_derive::Arbitrary;
16use serde::{Deserialize, Serialize};
17
18/// The identifier for a query policy in the environment-wide namespace.
19#[derive(
20    Clone,
21    Copy,
22    Debug,
23    Eq,
24    PartialEq,
25    Ord,
26    PartialOrd,
27    Hash,
28    Serialize,
29    Deserialize
30)]
31#[cfg_attr(any(test, feature = "proptest"), derive(Arbitrary))]
32pub enum QueryPolicyId {
33    System(u64),
34    User(u64),
35}
36
37impl QueryPolicyId {
38    pub fn is_system(&self) -> bool {
39        matches!(self, Self::System(_))
40    }
41
42    pub fn is_user(&self) -> bool {
43        matches!(self, Self::User(_))
44    }
45
46    pub fn is_builtin(&self) -> bool {
47        self.is_system()
48    }
49}
50
51impl FromStr for QueryPolicyId {
52    type Err = Error;
53
54    fn from_str(s: &str) -> Result<Self, Self::Err> {
55        let invalid = || anyhow!("couldn't parse query policy id '{s}'");
56        if let Some(id) = s.strip_prefix('s') {
57            Ok(Self::System(id.parse().map_err(|_| invalid())?))
58        } else if let Some(id) = s.strip_prefix('u') {
59            Ok(Self::User(id.parse().map_err(|_| invalid())?))
60        } else {
61            Err(invalid())
62        }
63    }
64}
65
66impl fmt::Display for QueryPolicyId {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::System(id) => write!(f, "s{id}"),
70            Self::User(id) => write!(f, "u{id}"),
71        }
72    }
73}