use std::fmt;
use std::str::FromStr;
use anyhow::{anyhow, Error};
use columnation::{Columnation, CopyRegion};
use mz_lowertest::MzReflect;
use mz_ore::id_gen::AtomicIdGen;
use mz_proto::{RustType, TryFromProtoError};
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use crate::CatalogItemId;
include!(concat!(env!("OUT_DIR"), "/mz_repr.global_id.rs"));
#[derive(
Arbitrary,
Clone,
Copy,
Debug,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
Serialize,
Deserialize,
MzReflect,
)]
pub enum GlobalId {
System(u64),
User(u64),
Transient(u64),
Explain,
}
impl GlobalId {
pub fn is_system(&self) -> bool {
matches!(self, GlobalId::System(_))
}
pub fn is_user(&self) -> bool {
matches!(self, GlobalId::User(_))
}
pub fn is_transient(&self) -> bool {
matches!(self, GlobalId::Transient(_))
}
}
impl FromStr for GlobalId {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() < 2 {
return Err(anyhow!("couldn't parse id {}", s));
}
if s == "Explained Query" {
return Ok(GlobalId::Explain);
}
let val: u64 = s[1..].parse()?;
match s.chars().next().unwrap() {
's' => Ok(GlobalId::System(val)),
'u' => Ok(GlobalId::User(val)),
't' => Ok(GlobalId::Transient(val)),
_ => Err(anyhow!("couldn't parse id {}", s)),
}
}
}
impl fmt::Display for GlobalId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
GlobalId::System(id) => write!(f, "s{}", id),
GlobalId::User(id) => write!(f, "u{}", id),
GlobalId::Transient(id) => write!(f, "t{}", id),
GlobalId::Explain => write!(f, "Explained Query"),
}
}
}
impl RustType<ProtoGlobalId> for GlobalId {
fn into_proto(&self) -> ProtoGlobalId {
use proto_global_id::Kind::*;
ProtoGlobalId {
kind: Some(match self {
GlobalId::System(x) => System(*x),
GlobalId::User(x) => User(*x),
GlobalId::Transient(x) => Transient(*x),
GlobalId::Explain => Explain(()),
}),
}
}
fn from_proto(proto: ProtoGlobalId) -> Result<Self, TryFromProtoError> {
use proto_global_id::Kind::*;
match proto.kind {
Some(System(x)) => Ok(GlobalId::System(x)),
Some(User(x)) => Ok(GlobalId::User(x)),
Some(Transient(x)) => Ok(GlobalId::Transient(x)),
Some(Explain(_)) => Ok(GlobalId::Explain),
None => Err(TryFromProtoError::missing_field("ProtoGlobalId::kind")),
}
}
}
impl Columnation for GlobalId {
type InnerRegion = CopyRegion<GlobalId>;
}
#[derive(Debug)]
pub struct TransientIdGen(AtomicIdGen);
impl TransientIdGen {
pub fn new() -> Self {
let inner = AtomicIdGen::default();
let _ = inner.allocate_id();
Self(inner)
}
pub fn allocate_id(&self) -> (CatalogItemId, GlobalId) {
let inner = self.0.allocate_id();
(CatalogItemId::Transient(inner), GlobalId::Transient(inner))
}
}