surrealdb_sql/
uuid.rs

1use crate::{escape::quote_str, strand::Strand};
2use revision::revisioned;
3use serde::{Deserialize, Serialize};
4use std::fmt::{self, Display, Formatter};
5use std::ops::Deref;
6use std::str;
7use std::str::FromStr;
8
9pub(crate) const TOKEN: &str = "$surrealdb::private::crate::Uuid";
10
11#[derive(
12	Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize, Hash,
13)]
14#[serde(rename = "$surrealdb::private::crate::Uuid")]
15#[revisioned(revision = 1)]
16pub struct Uuid(pub uuid::Uuid);
17
18impl From<uuid::Uuid> for Uuid {
19	fn from(v: uuid::Uuid) -> Self {
20		Uuid(v)
21	}
22}
23
24impl From<Uuid> for uuid::Uuid {
25	fn from(s: Uuid) -> Self {
26		s.0
27	}
28}
29
30impl FromStr for Uuid {
31	type Err = ();
32	fn from_str(s: &str) -> Result<Self, Self::Err> {
33		Self::try_from(s)
34	}
35}
36
37impl TryFrom<String> for Uuid {
38	type Error = ();
39	fn try_from(v: String) -> Result<Self, Self::Error> {
40		Self::try_from(v.as_str())
41	}
42}
43
44impl TryFrom<Strand> for Uuid {
45	type Error = ();
46	fn try_from(v: Strand) -> Result<Self, Self::Error> {
47		Self::try_from(v.as_str())
48	}
49}
50
51impl TryFrom<&str> for Uuid {
52	type Error = ();
53	fn try_from(v: &str) -> Result<Self, Self::Error> {
54		match uuid::Uuid::try_parse(v) {
55			Ok(v) => Ok(Self(v)),
56			Err(_) => Err(()),
57		}
58	}
59}
60
61impl Deref for Uuid {
62	type Target = uuid::Uuid;
63	fn deref(&self) -> &Self::Target {
64		&self.0
65	}
66}
67
68impl Uuid {
69	/// Generate a new UUID
70	pub fn new() -> Self {
71		Self(uuid::Uuid::now_v7())
72	}
73	/// Generate a new V4 UUID
74	pub fn new_v4() -> Self {
75		Self(uuid::Uuid::new_v4())
76	}
77	/// Generate a new V7 UUID
78	pub fn new_v7() -> Self {
79		Self(uuid::Uuid::now_v7())
80	}
81	/// Convert the Uuid to a raw String
82	pub fn to_raw(&self) -> String {
83		self.0.to_string()
84	}
85}
86
87impl Display for Uuid {
88	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
89		Display::fmt(&quote_str(&self.0.to_string()), f)
90	}
91}