Jump to…
snowinitial commitqoxwzsukwmkx1mo
Matt W1//! UUIDv7 identifiers.
Matt W2//!
Matt W3//! Spec §5: "UUIDv7 primary keys throughout — time-ordered, index-friendly, and
Matt W4//! they don't leak counts." Generated in the application rather than by the
Matt W5//! database so an id is known before insert.
Matt W6
Matt W7use uuid::Uuid;
Matt W8
Matt W9/// Mint a new time-ordered identifier.
Matt W10pub fn new_id() -> Uuid {
Matt W11 Uuid::now_v7()
Matt W12}
Matt W13
Matt W14#[cfg(test)]
Matt W15mod tests {
Matt W16 use super::*;
Matt W17
Matt W18 #[test]
Matt W19 fn ids_are_version_7() {
Matt W20 assert_eq!(new_id().get_version_num(), 7);
Matt W21 }
Matt W22
Matt W23 #[test]
Matt W24 fn ids_are_time_ordered() {
Matt W25 // The property that makes these index-friendly: successive ids sort in
Matt W26 // creation order, so btree inserts stay at the right edge of the tree.
Matt W27 let mut prev = new_id();
Matt W28 for _ in 0..1000 {
Matt W29 let next = new_id();
Matt W30 assert!(
Matt W31 next > prev,
Matt W32 "uuidv7 must be monotonically increasing: {prev} then {next}"
Matt W33 );
Matt W34 prev = next;
Matt W35 }
Matt W36 }
Matt W37
Matt W38 #[test]
Matt W39 fn ids_are_unique() {
Matt W40 use std::collections::HashSet;
Matt W41 let set: HashSet<Uuid> = (0..10_000).map(|_| new_id()).collect();
Matt W42 assert_eq!(set.len(), 10_000);
Matt W43 }
Matt W44}

44 lines · Rust