Developer's Guide to UUID Implementation
Choose a programming language from the sidebar to see how to implement UUID generation and handling in that specific language. Each guide includes standard library methods, popular third-party libraries, and best practices.
UUID in Python
Using the Standard Library
Python has built-in support for UUID generation through the uuid
module in the standard library:
import uuid
# Generate a random UUID (version 4)
random_uuid = uuid.uuid4()
print(random_uuid) # e.g., 550e8400-e29b-41d4-a716-446655440000
# Generate a UUID based on the host ID and current time (version 1)
time_based_uuid = uuid.uuid1()
print(time_based_uuid)
# Generate a name-based UUID using SHA-1 (version 5)
namespace_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, "example.com")
print(namespace_uuid)
# Convert UUID to string
uuid_str = str(random_uuid)
print(uuid_str)
# Create UUID from string
from_str = uuid.UUID("550e8400-e29b-41d4-a716-446655440000")
print(from_str)
UUID Versions in Python
The Python uuid
module supports all standard UUID versions:
uuid1()
: Generate a UUID based on the host ID and current timeuuid3(namespace, name)
: Generate a UUID based on the MD5 hash of a namespace ID and a nameuuid4()
: Generate a random UUIDuuid5(namespace, name)
: Generate a UUID based on the SHA-1 hash of a namespace ID and a name
For most applications, uuid4()
is recommended unless you have specific requirements for using other versions.
Working with UUIDs in Databases
When using UUIDs with databases in Python, you'll typically want to use an ORM like SQLAlchemy:
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import UUID
import uuid
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
# For PostgreSQL, which has a native UUID type
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String)
# For databases without a native UUID type, use a string instead
# id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
Best Practices
- Use
uuid4()
for most applications requiring random identifiers - Consider storage implications when using UUIDs as primary keys in databases
- When string representation is required, you can use
str(uuid_obj)
- For web applications, UUIDs are often safer than sequential IDs to prevent enumeration attacks
UUID in JavaScript
Using the Crypto API (Modern Browsers)
Modern browsers provide the Crypto API which can be used to generate UUID v4:
// Generate a UUID v4 using the crypto API
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
const myUUID = uuidv4();
console.log(myUUID); // e.g., "c7f76f50-d7d2-4e4b-8870-3d7e84125216"
Using UUID Libraries
For more complete UUID support, especially in Node.js or when browser compatibility is a concern, use the popular uuid
package:
// In Node.js
// First install: npm install uuid
// CommonJS import
const { v1, v4, v5, validate, version } = require('uuid');
// ES Module import
// import { v1, v4, v5, validate, version } from 'uuid';
// Generate a random UUID (v4)
const randomUUID = v4();
console.log(randomUUID);
// Generate a time-based UUID (v1)
const timeBasedUUID = v1();
console.log(timeBasedUUID);
// Generate a name-based UUID (v5)
const NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; // Some custom namespace
const nameBasedUUID = v5('Hello, World!', NAMESPACE);
console.log(nameBasedUUID);
// Validate a UUID
const isValid = validate(randomUUID); // true
console.log(isValid);
// Check the version of a UUID
const uuidVersion = version(randomUUID); // 4
console.log(uuidVersion);
Using UUID in the Browser
For browser usage, you can include the library via CDN:
<script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuid.min.js"></script>
<script>
const { v4: uuidv4 } = uuid;
// Generate a random UUID
const myUUID = uuidv4();
console.log(myUUID);
</script>
Best Practices
- Use v4 (random) UUIDs for most client-side applications
- For secure applications, ensure you're using a cryptographically strong source of randomness
- Consider using the
uuid
library instead of custom implementations for better compatibility and maintenance - In modern browsers, you can use the built-in Crypto API for better performance
UUID in Java
Using java.util.UUID
Java includes UUID support in the standard library with the java.util.UUID
class:
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
// Generate a random UUID (version 4)
UUID randomUUID = UUID.randomUUID();
System.out.println("Random UUID: " + randomUUID);
// Create a UUID from string
UUID fromString = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
System.out.println("From string: " + fromString);
// Get the most and least significant bits
long mostSigBits = randomUUID.getMostSignificantBits();
long leastSigBits = randomUUID.getLeastSignificantBits();
// Create a UUID from bits
UUID fromBits = new UUID(mostSigBits, leastSigBits);
System.out.println("From bits: " + fromBits);
// Get UUID version
int version = randomUUID.version();
System.out.println("Version: " + version);
// Get UUID variant
int variant = randomUUID.variant();
System.out.println("Variant: " + variant);
}
}
Using UUIDs in JPA/Hibernate
When using UUIDs as entity identifiers in JPA/Hibernate:
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
private UUID id;
private String name;
public User() {
this.id = UUID.randomUUID();
}
// Getters and setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UUID Version 1 (Time-based) in Java
Java's standard library doesn't directly support UUID v1 generation. For time-based UUIDs, you can use a library like com.fasterxml.uuid:java-uuid-generator
:
// Add this dependency to your pom.xml
// <dependency>
// <groupId>com.fasterxml.uuid</groupId>
// <artifactId>java-uuid-generator</artifactId>
// <version>4.0.1</version>
// </dependency>
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import java.util.UUID;
public class TimeBasedUUIDExample {
public static void main(String[] args) {
// Create a time-based generator
TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator();
// Generate a time-based UUID (v1)
UUID timeBasedUUID = timeBasedGenerator.generate();
System.out.println("Time-based UUID: " + timeBasedUUID);
}
}
Best Practices
- Use
UUID.randomUUID()
for most applications requiring random identifiers - Consider the performance implications when using UUIDs as database primary keys
- For time-ordered UUIDs (useful in some database scenarios), consider using a specialized library
- Store UUIDs efficiently in databases by using native UUID types when available
UUID in C# (.NET)
Using System.Guid
In .NET, UUIDs are implemented as the System.Guid
struct:
using System;
class Program
{
static void Main()
{
// Generate a new random GUID
Guid randomGuid = Guid.NewGuid();
Console.WriteLine($"Random GUID: {randomGuid}");
// Parse a GUID from string
Guid parsedGuid = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");
Console.WriteLine($"Parsed GUID: {parsedGuid}");
// TryParse example (safer parsing)
bool success = Guid.TryParse("550e8400-e29b-41d4-a716-446655440000", out Guid result);
if (success)
{
Console.WriteLine($"Successfully parsed: {result}");
}
// Convert to different string formats
Console.WriteLine($"As string: {randomGuid.ToString()}");
Console.WriteLine($"As 'N' format (no dashes): {randomGuid.ToString("N")}");
Console.WriteLine($"As 'B' format (with braces): {randomGuid.ToString("B")}");
Console.WriteLine($"As 'P' format (with parentheses): {randomGuid.ToString("P")}");
Console.WriteLine($"As 'X' format (with hex values): {randomGuid.ToString("X")}");
// Compare GUIDs
bool areEqual = randomGuid.Equals(parsedGuid);
Console.WriteLine($"GUIDs are equal: {areEqual}");
// Convert to byte array
byte[] bytes = randomGuid.ToByteArray();
// Create from byte array
Guid fromBytes = new Guid(bytes);
Console.WriteLine($"From bytes: {fromBytes}");
}
}
Using GUIDs in Entity Framework
Using GUIDs as primary keys in Entity Framework:
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
public class User
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public User()
{
Id = Guid.NewGuid();
}
}
public class ApplicationDbContext : DbContext
{
public DbSet Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// You can also configure the property here
modelBuilder.Entity()
.Property(u => u.Id)
.HasDefaultValueSql("NEWID()"); // SQL Server syntax
}
}
Best Practices
- Use
Guid.NewGuid()
for generating random UUIDs - Be aware that .NET's
Guid
implementation primarily supports version 4 UUIDs - For sequential GUIDs (better for database indexing), consider using specialized libraries like
NHibernate.Guid.Comb
- When storing GUIDs in SQL Server, consider using the
uniqueidentifier
data type - Be mindful of the string format when displaying or storing GUIDs as strings
UUID in PHP
Using ramsey/uuid Library
The most popular way to work with UUIDs in PHP is using the ramsey/uuid
library:
<?php
// Install with Composer: composer require ramsey/uuid
require 'vendor/autoload.php';
use Ramsey\Uuid\Uuid;
// Generate a version 4 (random) UUID
$uuid4 = Uuid::uuid4();
echo "UUID v4: " . $uuid4->toString() . "\n";
// Generate a version 1 (time-based) UUID
$uuid1 = Uuid::uuid1();
echo "UUID v1: " . $uuid1->toString() . "\n";
// Generate a version 3 (name-based, MD5) UUID
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'example.com');
echo "UUID v3: " . $uuid3->toString() . "\n";
// Generate a version 5 (name-based, SHA-1) UUID
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'example.com');
echo "UUID v5: " . $uuid5->toString() . "\n";
// Parse a UUID from string
$parsed = Uuid::fromString('550e8400-e29b-41d4-a716-446655440000');
echo "Parsed UUID: " . $parsed->toString() . "\n";
// Check if a string is a valid UUID
$isValid = Uuid::isValid('550e8400-e29b-41d4-a716-446655440000');
echo "Is valid UUID: " . ($isValid ? 'Yes' : 'No') . "\n";
// Get UUID version
echo "UUID version: " . $uuid4->getVersion() . "\n";
// Convert to bytes for database storage
$bytes = $uuid4->getBytes();
// Create from bytes
$fromBytes = Uuid::fromBytes($bytes);
echo "From bytes: " . $fromBytes->toString() . "\n";
?>
UUID Functions in PHP 7+
Since PHP 7.4, there's a random_bytes function that can be used to generate a version 4 UUID:
<?php
/**
* Generate a UUID v4
* @return string
*/
function generateUuidV4() {
// Generate 16 random bytes
$data = random_bytes(16);
// Set version to 4
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
$uuid = generateUuidV4();
echo "UUID v4: $uuid\n";
?>
Using UUIDs in Laravel
Laravel provides built-in support for UUIDs in models:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
class User extends Model
{
use HasUuids;
// By default, Laravel will assume 'id' is your primary UUID key
// If you need to use a different column name:
// protected $primaryKey = 'uuid';
// If your UUID is not auto-incrementing:
public $incrementing = false;
// If your UUID is stored as a string in the database:
protected $keyType = 'string';
}
?>
Best Practices
- Use the
ramsey/uuid
library for production applications - Store UUIDs as binary in databases when possible for better performance
- When using UUIDs as primary keys, remember to set
$incrementing = false
and$keyType = 'string'
in Laravel models - When displaying UUIDs to users, consider using a more user-friendly format or shortened versions when appropriate
UUID in Go
Using the google/uuid Package
The most popular way to work with UUIDs in Go is using the google/uuid
package:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
// Generate a random UUID (v4)
id := uuid.New()
fmt.Printf("UUID v4: %s\n", id.String())
// Parse a UUID from string
parsed, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
if err != nil {
fmt.Printf("Error parsing UUID: %v\n", err)
return
}
fmt.Printf("Parsed UUID: %s\n", parsed)
// Generate a UUID from a namespace and name (v5)
// First, we'll use a predefined namespace UUID (DNS)
ns := uuid.NameSpaceDNS
// Generate a v5 UUID based on the namespace and a name
v5UUID := uuid.NewSHA1(ns, []byte("example.com"))
fmt.Printf("UUID v5: %s\n", v5UUID)
// Get the binary representation
bytes, err := parsed.MarshalBinary()
if err != nil {
fmt.Printf("Error marshaling UUID: %v\n", err)
return
}
// Create UUID from binary
var fromBytes uuid.UUID
fromBytes.UnmarshalBinary(bytes)
fmt.Printf("From bytes: %s\n", fromBytes)
}
Working with UUIDs in SQL Databases
When using UUIDs with Go and SQL databases:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq" // PostgreSQL driver
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID
Name string
}
func main() {
// Connect to PostgreSQL database
db, err := sql.Open("postgres", "postgres://username:password@localhost/dbname?sslmode=disable")
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer db.Close()
// Create a table with UUID primary key
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
name TEXT NOT NULL
)
`)
if err != nil {
log.Fatalf("Failed to create table: %v", err)
}
// Insert a user with a UUID
userID := uuid.New()
_, err = db.Exec("INSERT INTO users (id, name) VALUES ($1, $2)", userID, "John Doe")
if err != nil {
log.Fatalf("Failed to insert user: %v", err)
}
// Query the user by UUID
var user User
err = db.QueryRow("SELECT id, name FROM users WHERE id = $1", userID).Scan(&user.ID, &user.Name)
if err != nil {
log.Fatalf("Failed to query user: %v", err)
}
fmt.Printf("Found user: %s, %s\n", user.ID, user.Name)
}
Best Practices
- Use the
google/uuid
package for a well-tested, maintained implementation - Store UUIDs in their binary form in databases when possible for efficiency
- For high-performance applications, consider using the
gofrs/uuid
package which offers some performance optimizations - When working with PostgreSQL, use the native UUID type for better query performance
- In distributed systems, consider using version 1 (time-based) UUIDs for better indexing performance
UUID in Ruby
Using the SecureRandom Standard Library
Ruby's standard library includes a simple way to generate UUIDs:
require 'securerandom'
# Generate a random UUID (v4)
uuid = SecureRandom.uuid
puts "UUID v4: #{uuid}"
Using the uuid Gem
For more comprehensive UUID features, you can use the uuid
gem:
# Install with: gem install uuid
require 'uuid'
# Create a UUID generator
generator = UUID.new
# Generate a random UUID (v4)
uuid4 = generator.generate
puts "UUID v4: #{uuid4}"
# Generate a time-based UUID (v1)
uuid1 = generator.generate(:compact)
puts "UUID v1 (compact): #{uuid1}"
# Generate a UUID with timestamp
uuid_with_time = generator.generate(:time)
puts "UUID with time: #{uuid_with_time}"
# Parse a UUID
parsed = UUID.parse("550e8400-e29b-41d4-a716-446655440000")
puts "Parsed UUID: #{parsed}"
Using UUIDs in Ruby on Rails
In Ruby on Rails applications, you can use UUIDs as primary keys for your models:
# In your migration
class CreateUsers < ActiveRecord::Migration[6.1]
def change
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
create_table :users, id: :uuid do |t|
t.string :name
t.timestamps
end
end
end
# In your model
class User < ApplicationRecord
# No additional setup needed if using Rails 6+ and PostgreSQL
# UUID is automatically generated for new records
end
# In your application.rb (to set UUIDs as default for all models)
config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
Best Practices
- For simple UUID generation, Ruby's built-in
SecureRandom.uuid
is sufficient - When using Rails with PostgreSQL, enable the
pgcrypto
extension for efficient UUID handling - Consider using UUIDs as primary keys for public-facing resources to avoid enumeration attacks
- In distributed systems, UUIDs help avoid ID conflicts when merging data from multiple sources
- Store UUIDs in their native type in PostgreSQL for better performance and indexing
UUID in Rust
Using the uuid Crate
In Rust, UUIDs are typically handled using the uuid
crate:
// In Cargo.toml:
// [dependencies]
// uuid = { version = "1.3", features = ["v4", "v5", "fast-rng", "macro", "serde"] }
use uuid::{Uuid, uuid};
fn main() {
// Generate a random UUID (v4)
let uuid4 = Uuid::new_v4();
println!("UUID v4: {}", uuid4);
// Generate a UUID from a namespace and name (v5)
let namespace = Uuid::NAMESPACE_DNS;
let name = "example.com".as_bytes();
let uuid5 = Uuid::new_v5(&namespace, name);
println!("UUID v5: {}", uuid5);
// Parse a UUID from a string
let parsed = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").expect("Invalid UUID string");
println!("Parsed UUID: {}", parsed);
// Create a UUID using the uuid! macro
let predefined = uuid!("550e8400-e29b-41d4-a716-446655440000");
println!("Predefined UUID: {}", predefined);
// Check if two UUIDs are equal
println!("UUIDs are equal: {}", parsed == predefined);
// Nil UUID (all zeros)
let nil = Uuid::nil();
println!("Nil UUID: {}", nil);
// Convert to different formats
println!("Hyphenated: {}", uuid4.hyphenated());
println!("Simple: {}", uuid4.simple());
println!("Urn: {}", uuid4.urn());
// Get the bytes
let bytes = uuid4.as_bytes();
println!("Bytes: {:?}", bytes);
// Create from bytes
let from_bytes = Uuid::from_bytes(*bytes);
println!("From bytes: {}", from_bytes);
}
Using UUIDs with Databases
When working with UUIDs in Rust and databases, you'll often use an ORM like Diesel:
// In Cargo.toml:
// [dependencies]
// diesel = { version = "2.0", features = ["postgres", "uuid"] }
// uuid = { version = "1.3", features = ["v4", "serde"] }
use diesel::prelude::*;
use uuid::Uuid;
// Schema definition
table! {
users (id) {
id -> Uuid,
name -> Text,
}
}
// Model definition
#[derive(Queryable, Insertable)]
#[diesel(table_name = users)]
struct User {
id: Uuid,
name: String,
}
fn main() -> Result<(), Box> {
use self::users::dsl::*;
// Connect to database
let database_url = "postgres://username:password@localhost/diesel_demo";
let mut conn = PgConnection::establish(&database_url)?;
// Create a new user with a UUID
let new_user = User {
id: Uuid::new_v4(),
name: "John Doe".to_string(),
};
// Insert the user
diesel::insert_into(users)
.values(&new_user)
.execute(&mut conn)?;
// Query for the user
let found_user = users
.find(new_user.id)
.first::(&mut conn)?;
println!("Found user: {} with ID: {}", found_user.name, found_user.id);
Ok(())
}
Best Practices
- Use the
uuid
crate with appropriate feature flags (e.g.,v4
,fast-rng
) - Enable the
serde
feature when serializing/deserializing UUIDs - For high performance applications, consider binary UUID representation
- When using the
diesel
ORM, enable its UUID feature for proper database type handling - Watch for allocation overhead with UUIDs - in performance-critical code, reuse UUID instances when possible
UUID in Swift
Using Foundation's UUID
Swift's Foundation framework includes built-in support for UUIDs:
import Foundation
// Generate a random UUID (v4)
let uuid = UUID()
print("UUID: \(uuid)")
// Convert UUID to string
let uuidString = uuid.uuidString
print("UUID as string: \(uuidString)")
// Create a UUID from a string
if let fromString = UUID(uuidString: "550e8400-e29b-41d4-a716-446655440000") {
print("Created from string: \(fromString)")
} else {
print("Invalid UUID string")
}
// Compare UUIDs
let anotherUUID = UUID()
print("UUIDs are equal: \(uuid == anotherUUID)")
// Get UUID bytes
var bytes = uuid.uuid
print("First byte: \(bytes.0)")
Using UUIDs in CoreData
When working with CoreData, you can use UUIDs as identifiers for your entities:
import Foundation
import CoreData
// Define a CoreData entity with UUID
class User: NSManagedObject {
@NSManaged var id: UUID
@NSManaged var name: String
// Add convenience initializer
convenience init(context: NSManagedObjectContext, name: String) {
self.init(context: context)
self.id = UUID()
self.name = name
}
}
// Usage example
func createUser(name: String, context: NSManagedObjectContext) {
let user = User(context: context, name: name)
do {
try context.save()
print("User created with UUID: \(user.id)")
} catch {
print("Failed to save: \(error)")
}
}
// Find user by UUID
func findUser(id: UUID, context: NSManagedObjectContext) -> User? {
let fetchRequest: NSFetchRequest = User.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "id == %@", id as CVarArg)
do {
let results = try context.fetch(fetchRequest)
return results.first
} catch {
print("Failed to fetch: \(error)")
return nil
}
}
Using UUIDs in SwiftUI
UUIDs are often used with SwiftUI's Identifiable
protocol:
import SwiftUI
// Define a model conforming to Identifiable
struct Task: Identifiable {
let id: UUID = UUID()
var title: String
var isCompleted: Bool = false
}
// Use in a SwiftUI view
struct TaskListView: View {
@State private var tasks: [Task] = [
Task(title: "Learn SwiftUI"),
Task(title: "Build an app"),
Task(title: "Publish to App Store")
]
var body: some View {
List {
ForEach(tasks) { task in
Text(task.title)
}
.onDelete(perform: deleteTasks)
}
}
func deleteTasks(at offsets: IndexSet) {
tasks.remove(atOffsets: offsets)
}
}
Best Practices
- Use Foundation's
UUID()
for generating UUIDs, which creates version 4 (random) UUIDs - Conform to
Identifiable
protocol when using UUIDs as identifiers in SwiftUI - When storing UUIDs in databases, consider using string representation for compatibility
- For model objects that need persistence, generate UUIDs at initialization time
- Remember that UUIDs are objects in Swift, so they're allocated on the heap - use them appropriately in performance-critical code
UUID in TypeScript
Using the uuid Package
The most common way to work with UUIDs in TypeScript is using the uuid
package:
// Install with: npm install uuid
// Then: npm install @types/uuid
import { v1, v4, v5, validate, version, parse, stringify } from 'uuid';
// Generate a random UUID (v4)
const randomUuid: string = v4();
console.log(`Random UUID: ${randomUuid}`);
// Generate a time-based UUID (v1)
const timeBasedUuid: string = v1();
console.log(`Time-based UUID: ${timeBasedUuid}`);
// Generate a name-based UUID (v5)
const NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const nameBasedUuid: string = v5('Hello, World!', NAMESPACE);
console.log(`Name-based UUID: ${nameBasedUuid}`);
// Type checking with interfaces
interface Entity {
id: string; // UUID string
name: string;
}
// Create an entity with a UUID
const entity: Entity = {
id: v4(),
name: 'Example Entity'
};
// Validate a UUID
const isValid: boolean = validate(entity.id);
console.log(`Is valid UUID: ${isValid}`);
// Get the UUID version
const uuidVersion: number = version(entity.id);
console.log(`UUID version: ${uuidVersion}`);
// Parse a UUID to get its components
const parsed = parse(entity.id);
console.log('Parsed UUID components:', parsed);
// Convert binary UUID back to string
const stringified = stringify(parsed);
console.log(`Stringified UUID: ${stringified}`);
Using UUIDs in TypeORM
When working with TypeScript and databases, TypeORM provides native support for UUIDs:
// Install: npm install typeorm reflect-metadata pg uuid @types/uuid
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm';
import { v4 } from 'uuid';
@Entity('users')
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
// Constructor with default UUID generation
constructor(name: string) {
super();
this.id = v4();
this.name = name;
}
}
// Usage example
async function createUser(name: string): Promise {
const user = new User(name);
await user.save();
return user;
}
// Find by UUID
async function findUserById(id: string): Promise {
return await User.findOne({ where: { id } });
}
Using UUIDs in Angular
UUIDs are commonly used in Angular applications for unique identifiers:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
})
export class AppModule {}
// task.model.ts
import { v4 as uuidv4 } from 'uuid';
export class Task {
id: string;
title: string;
completed: boolean;
constructor(title: string) {
this.id = uuidv4();
this.title = title;
this.completed = false;
}
}
// app.component.ts
import { Component } from '@angular/core';
import { Task } from './task.model';
@Component({
selector: 'app-root',
template: `
Task List
-
Titre par défaut
`,
styles: ['.completed { text-decoration: line-through; }']
})
export class AppComponent {
tasks: Task[] = [];
addTask(title: string): void {
if (title.trim()) {
this.tasks.push(new Task(title));
}
}
removeTask(id: string): void {
this.tasks = this.tasks.filter(task => task.id !== id);
}
}
Best Practices
- Always install the
@types/uuid
package to get proper TypeScript typings - Consider using UUIDs as primary keys for entities in distributed systems
- In TypeScript interfaces, type UUID fields as
string
for simplicity - For frontend applications, use v4 UUIDs to avoid information leakage that can happen with v1
- When generating UUIDs client-side, validate their format server-side before trusting them
UUID in SQL Databases
PostgreSQL UUID Support
PostgreSQL has native UUID support and provides functions for working with UUIDs:
-- Enable the UUID extension (if not already enabled)
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Create a table with UUID primary key
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
username VARCHAR(50) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert a record with auto-generated UUID
INSERT INTO users (username) VALUES ('johndoe');
-- Insert with a specific UUID
INSERT INTO users (id, username)
VALUES (uuid_generate_v4(), 'janedoe');
-- Query by UUID
SELECT * FROM users
WHERE id = '550e8400-e29b-41d4-a716-446655440000';
-- Generate different UUID versions
SELECT uuid_generate_v1(); -- v1 (time-based)
SELECT uuid_generate_v4(); -- v4 (random)
-- Check if string is a valid UUID
SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid; -- works if valid
SELECT 'not-a-uuid'::uuid; -- throws error
-- Create a UUID from parts
SELECT uuid_in(overlay(overlay(overlay(overlay(
'ffffffff-ffff-ffff-ffff-ffffffffffff' placing '00000000' from 1 for 8)
placing '0000' from 10 for 4)
placing '4000' from 15 for 4)
placing '0000' from 20 for 4));
MySQL UUID Support
MySQL/MariaDB provides functions for working with UUIDs:
-- Create a table with UUID primary key (as CHAR)
CREATE TABLE users (
id CHAR(36) PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- In MySQL 8.0+, you can use UUID_TO_BIN to store UUIDs more efficiently
CREATE TABLE users_optimized (
id BINARY(16) PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert with UUID function (MySQL 8.0+)
INSERT INTO users (id, username)
VALUES (UUID(), 'johndoe');
-- Insert with optimized binary storage (MySQL 8.0+)
INSERT INTO users_optimized (id, username)
VALUES (UUID_TO_BIN(UUID()), 'johndoe');
-- Query using UUID string (inefficient)
SELECT * FROM users
WHERE id = '550e8400-e29b-41d4-a716-446655440000';
-- Query using binary UUID (efficient)
SELECT * FROM users_optimized
WHERE id = UUID_TO_BIN('550e8400-e29b-41d4-a716-446655440000');
-- Convert binary UUID back to string
SELECT BIN_TO_UUID(id) as user_id, username
FROM users_optimized;
SQL Server UUID/UNIQUEIDENTIFIER
SQL Server uses the UNIQUEIDENTIFIER type for UUIDs:
-- Create a table with UNIQUEIDENTIFIER primary key
CREATE TABLE users (
id UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
username NVARCHAR(50) NOT NULL UNIQUE,
created_at DATETIME2 DEFAULT GETDATE()
);
-- Insert with auto-generated UNIQUEIDENTIFIER
INSERT INTO users (username) VALUES ('johndoe');
-- Insert with specific UNIQUEIDENTIFIER
INSERT INTO users (id, username)
VALUES (NEWID(), 'janedoe');
-- Time-ordered UNIQUEIDENTIFIER (better for indexing)
INSERT INTO users (id, username)
VALUES (NEWSEQUENTIALID(), 'sequential_user');
-- Query by UNIQUEIDENTIFIER
SELECT * FROM users
WHERE id = '550E8400-E29B-41D4-A716-446655440000';
-- Convert string to UNIQUEIDENTIFIER
SELECT CAST('550E8400-E29B-41D4-A716-446655440000' AS UNIQUEIDENTIFIER);
-- Convert UNIQUEIDENTIFIER to string
SELECT CAST(id AS NVARCHAR(36)) FROM users;
SQLite UUID Support
SQLite doesn't have a native UUID type, but you can use TEXT or BLOB:
-- Create a table with UUID primary key as TEXT
CREATE TABLE users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- UUID generation usually handled by application layer
-- For example, in Python:
-- import uuid
-- cursor.execute("INSERT INTO users (id, username) VALUES (?, ?)",
-- (str(uuid.uuid4()), "johndoe"))
-- If using a client tool, you'd typically insert a UUID string:
INSERT INTO users (id, username)
VALUES ('550e8400-e29b-41d4-a716-446655440000', 'johndoe');
-- Query by UUID
SELECT * FROM users
WHERE id = '550e8400-e29b-41d4-a716-446655440000';
Best Practices
- Use native UUID types when available (PostgreSQL, SQL Server) for better integration
- In MySQL 8.0+, store UUIDs as binary with
UUID_TO_BIN
/BIN_TO_UUID
for better performance - Consider indexing implications: UUIDs can fragment indexes more than sequential IDs
- For SQL Server,
NEWSEQUENTIALID()
can improve index performance - With PostgreSQL, the
uuid-ossp
extension provides multiple UUID generation algorithms - For SQLite, handle UUID generation in your application code