surrealdb_core/sql/
uuid.rs

1use crate::sql::{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
9use super::Datetime;
10
11pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Uuid";
12
13#[revisioned(revision = 1)]
14#[derive(
15	Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize, Hash,
16)]
17#[serde(rename = "$surrealdb::private::sql::Uuid")]
18#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
19#[non_exhaustive]
20pub struct Uuid(pub uuid::Uuid);
21
22impl From<uuid::Uuid> for Uuid {
23	fn from(v: uuid::Uuid) -> Self {
24		Uuid(v)
25	}
26}
27
28impl From<Uuid> for uuid::Uuid {
29	fn from(s: Uuid) -> Self {
30		s.0
31	}
32}
33
34impl FromStr for Uuid {
35	type Err = ();
36	fn from_str(s: &str) -> Result<Self, Self::Err> {
37		Self::try_from(s)
38	}
39}
40
41impl TryFrom<String> for Uuid {
42	type Error = ();
43	fn try_from(v: String) -> Result<Self, Self::Error> {
44		Self::try_from(v.as_str())
45	}
46}
47
48impl TryFrom<Strand> for Uuid {
49	type Error = ();
50	fn try_from(v: Strand) -> Result<Self, Self::Error> {
51		Self::try_from(v.as_str())
52	}
53}
54
55impl TryFrom<&str> for Uuid {
56	type Error = ();
57	fn try_from(v: &str) -> Result<Self, Self::Error> {
58		match uuid::Uuid::try_parse(v) {
59			Ok(v) => Ok(Self(v)),
60			Err(_) => Err(()),
61		}
62	}
63}
64
65impl Deref for Uuid {
66	type Target = uuid::Uuid;
67	fn deref(&self) -> &Self::Target {
68		&self.0
69	}
70}
71
72impl Uuid {
73	/// Generate a new UUID
74	pub fn new() -> Self {
75		Self(uuid::Uuid::now_v7())
76	}
77	/// Generate a new V4 UUID
78	pub fn new_v4() -> Self {
79		Self(uuid::Uuid::new_v4())
80	}
81	/// Generate a new V7 UUID
82	pub fn new_v7() -> Self {
83		Self(uuid::Uuid::now_v7())
84	}
85	/// Generate a new V7 UUID
86	pub fn new_v7_from_datetime(timestamp: Datetime) -> Self {
87		let ts = uuid::Timestamp::from_unix(
88			uuid::NoContext,
89			timestamp.0.timestamp() as u64,
90			timestamp.0.timestamp_subsec_nanos(),
91		);
92		Self(uuid::Uuid::new_v7(ts))
93	}
94	/// Convert the Uuid to a raw String
95	pub fn to_raw(&self) -> String {
96		self.0.to_string()
97	}
98}
99
100impl Display for Uuid {
101	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
102		write!(f, "u")?;
103		Display::fmt(&quote_str(&self.0.to_string()), f)
104	}
105}