Versioning & Time-Travel
Track changes and query historical data with automatic versioning
Enable Versioning
Set versioned: true on your model:
models/Document.ts
import { defineModel, DataTypes } from "stabilize-orm";
export const Document = defineModel({ tableName: "documents", versioned: true, columns: { id: { type: DataTypes.STRING, required: true, unique: true }, title: { type: DataTypes.STRING, length: 255, required: true }, content: { type: DataTypes.TEXT }, status: { type: DataTypes.STRING, length: 50 }, },});Track Changes
Every create, update, and delete records a version:
examples/track-changes.ts
import { generateUUID } from "stabilize-orm";
const docRepo = orm.getRepository(Document);
// Create initial document (version 1)const doc = await docRepo.create({ id: generateUUID(), title: "My Document", content: "Initial content", status: "draft",});
// Update creates version 2await docRepo.update(doc.id, { content: "Updated content" });
// Another update creates version 3await docRepo.update(doc.id, { status: "published" });View History
Get all versions of a record using history(id):
examples/view-history.ts
const history = await docRepo.history(doc.id);
console.log(`Document has ${history.length} versions`);
history.forEach(version => { console.log(`Version ${version.version}:`); console.log(` Title: ${version.title}`); console.log(` Status: ${version.status}`); console.log(` Operation: ${version.operation}`); console.log(` Valid from: ${version.valid_from}`);});Time-Travel Queries
Query data as it existed at a specific point in time using asOf(id, date):
examples/time-travel.ts
// Get document as it was on a specific dateconst pastDate = new Date("2025-01-01T00:00:00Z");const docAsOf = await docRepo.asOf(doc.id, pastDate);
if (docAsOf) { console.log("Document on Jan 1, 2025:"); console.log(` Title: ${docAsOf.title}`); console.log(` Content: ${docAsOf.content}`);}Rollback Changes
Restore a previous version using rollback(id, version). This creates a new version with the old data:
examples/rollback-version.ts
// Rollback to version 2await docRepo.rollback(doc.id, 2);
// The rollback creates a NEW version (e.g., version 4) with version 2's dataconst currentDoc = await docRepo.findOne(doc.id);console.log("Current version:", currentDoc.version);console.log("Content restored from v2:", currentDoc.content);