surrealdb_sql/
id.rs

1use crate::cnf::ID_CHARS;
2use crate::ctx::Context;
3use crate::dbs::{Options, Transaction};
4use crate::doc::CursorDoc;
5use crate::err::Error;
6use crate::{escape::escape_rid, Array, Number, Object, Strand, Thing, Uuid, Value};
7use nanoid::nanoid;
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::fmt::{self, Display, Formatter};
12use ulid::Ulid;
13
14#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
15#[revisioned(revision = 1)]
16pub enum Gen {
17	Rand,
18	Ulid,
19	Uuid,
20}
21
22#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
23#[revisioned(revision = 1)]
24pub enum Id {
25	Number(i64),
26	String(String),
27	Array(Array),
28	Object(Object),
29	Generate(Gen),
30}
31
32impl From<i64> for Id {
33	fn from(v: i64) -> Self {
34		Self::Number(v)
35	}
36}
37
38impl From<i32> for Id {
39	fn from(v: i32) -> Self {
40		Self::Number(v as i64)
41	}
42}
43
44impl From<u64> for Id {
45	fn from(v: u64) -> Self {
46		Self::Number(v as i64)
47	}
48}
49
50impl From<String> for Id {
51	fn from(v: String) -> Self {
52		Self::String(v)
53	}
54}
55
56impl From<Array> for Id {
57	fn from(v: Array) -> Self {
58		Self::Array(v)
59	}
60}
61
62impl From<Object> for Id {
63	fn from(v: Object) -> Self {
64		Self::Object(v)
65	}
66}
67
68impl From<Uuid> for Id {
69	fn from(v: Uuid) -> Self {
70		Self::String(v.to_raw())
71	}
72}
73
74impl From<Strand> for Id {
75	fn from(v: Strand) -> Self {
76		Self::String(v.as_string())
77	}
78}
79
80impl From<&str> for Id {
81	fn from(v: &str) -> Self {
82		Self::String(v.to_owned())
83	}
84}
85
86impl From<&String> for Id {
87	fn from(v: &String) -> Self {
88		Self::String(v.to_owned())
89	}
90}
91
92impl From<Vec<&str>> for Id {
93	fn from(v: Vec<&str>) -> Self {
94		Id::Array(v.into())
95	}
96}
97
98impl From<Vec<String>> for Id {
99	fn from(v: Vec<String>) -> Self {
100		Id::Array(v.into())
101	}
102}
103
104impl From<Vec<Value>> for Id {
105	fn from(v: Vec<Value>) -> Self {
106		Id::Array(v.into())
107	}
108}
109
110impl From<BTreeMap<String, Value>> for Id {
111	fn from(v: BTreeMap<String, Value>) -> Self {
112		Id::Object(v.into())
113	}
114}
115
116impl From<Number> for Id {
117	fn from(v: Number) -> Self {
118		match v {
119			Number::Int(v) => v.into(),
120			Number::Float(v) => v.to_string().into(),
121			Number::Decimal(v) => v.to_string().into(),
122		}
123	}
124}
125
126impl From<Thing> for Id {
127	fn from(v: Thing) -> Self {
128		v.id
129	}
130}
131
132impl Id {
133	/// Generate a new random ID
134	pub fn rand() -> Self {
135		Self::String(nanoid!(20, &ID_CHARS))
136	}
137	/// Generate a new random ULID
138	pub fn ulid() -> Self {
139		Self::String(Ulid::new().to_string())
140	}
141	/// Generate a new random UUID
142	pub fn uuid() -> Self {
143		Self::String(Uuid::new_v7().to_raw())
144	}
145	/// Convert the Id to a raw String
146	pub fn to_raw(&self) -> String {
147		match self {
148			Self::Number(v) => v.to_string(),
149			Self::String(v) => v.to_string(),
150			Self::Array(v) => v.to_string(),
151			Self::Object(v) => v.to_string(),
152			Self::Generate(v) => match v {
153				Gen::Rand => "rand()".to_string(),
154				Gen::Ulid => "ulid()".to_string(),
155				Gen::Uuid => "uuid()".to_string(),
156			},
157		}
158	}
159}
160
161impl Display for Id {
162	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
163		match self {
164			Self::Number(v) => Display::fmt(v, f),
165			Self::String(v) => Display::fmt(&escape_rid(v), f),
166			Self::Array(v) => Display::fmt(v, f),
167			Self::Object(v) => Display::fmt(v, f),
168			Self::Generate(v) => match v {
169				Gen::Rand => Display::fmt("rand()", f),
170				Gen::Ulid => Display::fmt("ulid()", f),
171				Gen::Uuid => Display::fmt("uuid()", f),
172			},
173		}
174	}
175}
176
177impl Id {
178	/// Process this type returning a computed simple Value
179	pub(crate) async fn compute(
180		&self,
181		ctx: &Context<'_>,
182		opt: &Options,
183		txn: &Transaction,
184		doc: Option<&CursorDoc<'_>>,
185	) -> Result<Id, Error> {
186		match self {
187			Id::Number(v) => Ok(Id::Number(*v)),
188			Id::String(v) => Ok(Id::String(v.clone())),
189			Id::Array(v) => match v.compute(ctx, opt, txn, doc).await? {
190				Value::Array(v) => Ok(Id::Array(v)),
191				_ => unreachable!(),
192			},
193			Id::Object(v) => match v.compute(ctx, opt, txn, doc).await? {
194				Value::Object(v) => Ok(Id::Object(v)),
195				_ => unreachable!(),
196			},
197			Id::Generate(v) => match v {
198				Gen::Rand => Ok(Self::rand()),
199				Gen::Ulid => Ok(Self::ulid()),
200				Gen::Uuid => Ok(Self::uuid()),
201			},
202		}
203	}
204}