How to Generate IDs in Macro Rust Code: UUIDv7 Patterns and Examples
Use macro_uuid::generate_uuid_v7() to create new time-ordered identifiers and macro_uuid::string_to_uuid() to parse string representations, as implemented across the macro-inc/macro repository.
The Macro codebase standardizes on UUID version 7 for all primary keys and entity identifiers. This approach ensures monotonic, sortable IDs that perform well in database indexes and distributed systems. The macro_uuid helper crate provides the canonical interface for all ID operations, abstracting away the underlying uuid crate details.
The Core macro_uuid API
The repository centralizes identifier generation through two primary functions exported by the macro_uuid crate. These functions guarantee consistent formatting and error handling across services.
Generating New UUIDs with generate_uuid_v7
The generate_uuid_v7() function returns a uuid::Uuid instance encoded as version 7. This variant embeds a Unix timestamp in the most significant bits, producing time-ordered values that sort naturally by creation time.
use macro_uuid::generate_uuid_v7;
// Creates a new, unique, time-ordered identifier
let new_entity_id = generate_uuid_v7();
According to the source analysis, this pattern appears in services/email_service/src/util/upload_attachment.rs at line 109:
let attachment_sfs_id = macro_uuid::generate_uuid_v7();
The function is also invoked in services/scheduled_action/src/outbound/tokio_dispatcher.rs and services/search_processing_service/src/process/document/raw_document.rs at line 301 for document processing workflows.
Parsing String IDs with string_to_uuid
When handling external input or seed data, use string_to_uuid() to convert string representations into typed UUIDs. This function returns a Result<Uuid, ParseError>, requiring explicit error handling.
In tooling/seed_cli/src/service/db/mod.rs at line 220, the codebase unwraps the result for trusted seed data:
¯o_uuid::string_to_uuid(item_id).unwrap(),
For production API endpoints, map the error to the application's error type:
let entity_uuid = macro_uuid::string_to_uuid(entity_id)
.map_err(|e| anyhow::anyhow!("entity id {entity_id} is not a uuid: {e:?}"))?;
Production Code Examples from the Macro Repository
The following file paths demonstrate the canonical patterns for ID generation in different contexts:
Attachment Creation — services/email_service/src/util/upload_attachment.rs
// Line 109: Generates a fresh ID for file storage references
let attachment_sfs_id = macro_uuid::generate_uuid_v7();
Database Seeding — tooling/seed_cli/src/service/db/mod.rs
// Line 220: Converts seed fixture IDs into database-compatible UUIDs
let parsed_id = macro_uuid::string_to_uuid(item_id).unwrap();
Team Repository — crates/teams/src/outbound/team_repo.rs
The codebase uses generate_uuid_v7() at line 99 when persisting new team records, ensuring time-ordered identifiers for pagination queries.
Scheduled Actions — services/scheduled_action/src/outbound/tokio_dispatcher.rs
Dispatches actions using generate_uuid_v7() to assign deterministic, traceable job IDs without external randomness overhead.
Database Integration and Error Handling
When inserting records with SQLx, pass the Uuid directly as a bind parameter. The macro_uuid functions return the standard uuid::Uuid type, compatible with SQLx's query! macro:
use macro_uuid::generate_uuid_v7;
use sqlx::query;
let new_id = generate_uuid_v7();
query!(
"INSERT INTO documents (id, title) VALUES ($1, $2)",
new_id,
title
)
.execute(&pool)
.await?;
For parsing user-supplied IDs in API handlers, always propagate parsing errors rather than unwrapping:
let thread_uuid = macro_uuid::string_to_uuid(&thread_id)
.map_err(|_| ApiError::InvalidIdFormat)?;
Summary
- Always use
macro_uuid::generate_uuid_v7()for new primary keys to ensure time-ordered, database-friendly identifiers. - Use
macro_uuid::string_to_uuid()when converting external string input to UUID types, handling theResultappropriately for the context. - Reference implementation files such as
services/email_service/src/util/upload_attachment.rsandtooling/seed_cli/src/service/db/mod.rsfor copy-paste patterns. - Avoid
uuid::Uuid::new_v4()in new code; the Macro codebase standardizes on v7 for performance and sortability benefits.
Frequently Asked Questions
What is the correct function to generate new IDs in Macro Rust code?
Use macro_uuid::generate_uuid_v7(). This function creates UUID version 7 values that include a timestamp component, making them naturally sortable by creation time. The repository uses this exclusively in crates/teams/src/outbound/team_repo.rs and services/email_service/src/util/upload_attachment.rs rather than random UUIDv4.
How do I convert a string ID to a UUID type in the Macro codebase?
Call macro_uuid::string_to_uuid(input_str). This returns a Result<Uuid, _> that you must handle. In seed scripts like tooling/seed_cli/src/service/db/mod.rs, developers often unwrap trusted data, while API endpoints should map errors to HTTP 400 responses.
Why does Macro Rust use UUIDv7 instead of UUIDv4?
UUIDv7 encodes a Unix timestamp in the high bits of the identifier, producing values that sort chronologically without additional timestamp columns. This improves database index locality and enables efficient time-based pagination, which is why services/search_processing_service/src/process/document/raw_document.rs relies on generate_uuid_v7().
Where can I find working examples of ID generation patterns?
Examine services/email_service/src/util/upload_attachment.rs for new ID creation, tooling/seed_cli/src/service/db/mod.rs for string-to-UUID conversion, and services/scheduled_action/src/outbound/tokio_dispatcher.rs for background job identifier assignment. These files demonstrate the production-ready patterns approved for the Macro codebase.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →