From bb0b10e38ae35e5c5853aeac0bade0962c0c0f0d Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Tue, 17 Jan 2023 09:53:30 +0000 Subject: [PATCH] Add functionality to generate different Record IDs Closes #1353 --- lib/src/sql/id.rs | 15 +++++++++++++++ lib/src/sql/thing.rs | 9 ++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/src/sql/id.rs b/lib/src/sql/id.rs index 4bc2ec0a..b399bbf9 100644 --- a/lib/src/sql/id.rs +++ b/lib/src/sql/id.rs @@ -18,6 +18,7 @@ use nom::branch::alt; use nom::combinator::map; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display, Formatter}; +use ulid::Ulid; #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)] pub enum Id { @@ -116,6 +117,20 @@ impl Id { pub fn rand() -> Self { Self::String(nanoid!(20, &ID_CHARS)) } + /// Generate a new random ULID + pub fn ulid() -> Self { + Self::String(Ulid::new().to_string()) + } + /// Generate a new random UUID + #[cfg(uuid_unstable)] + pub fn uuid() -> Self { + Self::String(Uuid::new_v7().to_raw()) + } + /// Generate a new random UUID + #[cfg(not(uuid_unstable))] + pub fn uuid() -> Self { + Self::String(Uuid::new_v4().to_raw()) + } /// Convert the Id to a raw String pub fn to_raw(&self) -> String { match self { diff --git a/lib/src/sql/thing.rs b/lib/src/sql/thing.rs index 967323f7..8127a27d 100644 --- a/lib/src/sql/thing.rs +++ b/lib/src/sql/thing.rs @@ -10,7 +10,9 @@ use crate::sql::serde::is_internal_serialization; use crate::sql::value::Value; use derive::Store; use nom::branch::alt; +use nom::bytes::complete::tag; use nom::character::complete::char; +use nom::combinator::map; use nom::sequence::delimited; use serde::ser::SerializeStruct; use serde::{Deserialize, Serialize}; @@ -103,7 +105,12 @@ fn thing_double(i: &str) -> IResult<&str, Thing> { fn thing_raw(i: &str) -> IResult<&str, Thing> { let (i, t) = ident_raw(i)?; let (i, _) = char(':')(i)?; - let (i, v) = id(i)?; + let (i, v) = alt(( + map(tag("rand()"), |_| Id::rand()), + map(tag("ulid()"), |_| Id::ulid()), + map(tag("uuid()"), |_| Id::uuid()), + id, + ))(i)?; Ok(( i, Thing {