Skip to main content

surrealdb_types/value/
uuid.rs

1use std::fmt::{self, Display};
2use std::ops::{Deref, DerefMut};
3use std::str::FromStr;
4
5use serde::{Deserialize, Serialize};
6
7use crate::Datetime;
8use crate::sql::{SqlFormat, ToSql};
9
10/// Represents a UUID value in SurrealDB
11///
12/// A UUID (Universally Unique Identifier) is a 128-bit identifier that is unique across space and
13/// time. This type wraps the `uuid::Uuid` type.
14#[derive(
15	Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
16)]
17#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
18pub struct Uuid(pub(crate) ::uuid::Uuid);
19
20impl ToSql for Uuid {
21	fn fmt_sql(&self, f: &mut String, _fmt: SqlFormat) {
22		f.push_str("u'");
23		f.push_str(&self.0.to_string());
24		f.push('\'');
25	}
26}
27
28impl Uuid {
29	/// Generate a new UUID
30	pub fn new() -> Self {
31		Self(uuid::Uuid::now_v7())
32	}
33
34	/// Generate a new V4 UUID
35	pub fn new_v4() -> Self {
36		Self(uuid::Uuid::new_v4())
37	}
38
39	/// Generate a new V7 UUID
40	pub fn new_v7() -> Self {
41		Self(uuid::Uuid::now_v7())
42	}
43
44	/// Generate a new V7 UUID
45	pub fn new_v7_from_datetime(timestamp: Datetime) -> Self {
46		let ts = uuid::Timestamp::from_unix(
47			uuid::NoContext,
48			timestamp.0.timestamp() as u64,
49			timestamp.0.timestamp_subsec_nanos(),
50		);
51		Self(uuid::Uuid::new_v7(ts))
52	}
53
54	/// Generate a new nil UUID
55	pub const fn nil() -> Self {
56		Self(uuid::Uuid::nil())
57	}
58
59	/// Generate a new max UUID
60	pub const fn max() -> Self {
61		Self(uuid::Uuid::max())
62	}
63
64	/// Convert into the inner uuid::Uuid
65	pub fn into_inner(self) -> uuid::Uuid {
66		self.0
67	}
68}
69
70impl From<uuid::Uuid> for Uuid {
71	fn from(v: uuid::Uuid) -> Self {
72		Uuid(v)
73	}
74}
75
76impl From<Uuid> for uuid::Uuid {
77	fn from(s: Uuid) -> Self {
78		s.0
79	}
80}
81
82impl TryFrom<String> for Uuid {
83	type Error = uuid::Error;
84
85	fn try_from(v: String) -> Result<Self, Self::Error> {
86		Ok(Self(uuid::Uuid::parse_str(&v)?))
87	}
88}
89
90impl FromStr for Uuid {
91	type Err = uuid::Error;
92
93	fn from_str(s: &str) -> Result<Self, Self::Err> {
94		uuid::Uuid::try_parse(s).map(Uuid)
95	}
96}
97
98impl Deref for Uuid {
99	type Target = uuid::Uuid;
100	fn deref(&self) -> &Self::Target {
101		&self.0
102	}
103}
104
105impl DerefMut for Uuid {
106	fn deref_mut(&mut self) -> &mut Self::Target {
107		&mut self.0
108	}
109}
110
111impl Display for Uuid {
112	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113		self.0.fmt(f)
114	}
115}