Add functionality to generate different Record IDs

Closes #1353
This commit is contained in:
Tobie Morgan Hitchcock 2023-01-17 09:53:30 +00:00
parent 996b9c1375
commit bb0b10e38a
2 changed files with 23 additions and 1 deletions

View file

@ -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 {

View file

@ -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 {