/temporal-data:temporal-datafrom temporal-data
Provides patterns for system-time versioned (temporal) tables: append-only writes, contiguous timelines, far-future sentinels, sub-second precision, deduplication, and universal temporality.
Ships in temporal-data. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill covers system time (transaction time) only. For valid time and bitemporal patterns, see the Liftwizard temporal docs and the Klass DSL.
system_to.system_from equals the old row's system_to, forming an unbroken chain of versions per entity.9999-12-31 23:59:59.999, or 253402300799999 as epoch milliseconds) for open-ended records. This allows NOT NULL constraints, composite primary keys, and uniform queries.system_from and system_to with millisecond precision or finer. Two versions of one entity within the same unit of precision share a system_from and collide on the unique index, and upstream timestamps such as JavaScript's Date.now() and Reladomo's TIMESTAMP are already in milliseconds. Whole seconds are acceptable only when writes to one entity are guaranteed to be at least a second apart.system_from/system_to it writes with that identical value, even when the ORM splits the unit across several transactions (a self-referential hierarchy, a bulk update). The database does not issue timestamps.max(now, last + 1)) to make it unique or monotonic.system_from, never add 1 ms, 1 ns or any other offset, and never use a clock that returns max(now, last + 1). A shifted timestamp records an instant at which nothing happened, breaks the rule that system_from is when the database learned the fact, and drifts ahead of the wall clock under bursts. A collision is information: either one logical change was split into several units of work (merge them into one), a caller or test wrote the same entity twice in one clock tick (fix the caller), or the encoding is too coarse (store finer precision). Let the unique index fail loudly until the cause is fixed.Temporal tables are bigger than plain tables, but used well they are cheaper to keep in sync, because work scales with what changed rather than with how much data exists. Used badly, they cost far more. On stores that bill per row read or written, such as Cloudflare Durable Objects and D1, DynamoDB, Firestore and most serverless databases, that difference is the bill, and index rows usually count as rows written.
system_from (or system_to, for phase-outs) is newer than the last one seen, as in the temporal-data:temporal-caching skill's global watermark. A run with nothing new reads an index range and writes nothing. Re-downloading or rescanning the full data set on a schedule to find changes costs every row, every run.system_to = <sentinel>. A partial index on current rows keeps them from scanning history. Some engines, including SQLite, use a partial index only when the query states the sentinel as a literal, not as a bound parameter.There are two legitimate exceptions. Anything else is temporal, including reference data that merely never changes in practice. A table such as a game-version list is better temporal than exempt: it costs two columns, and relying on an upstream never mutating its identifiers is a promise this schema cannot enforce.
A table whose rows are computed from other temporal tables, such as a per-entity count of current child rows, may be a plain table. It is a cache, rebuilt on demand and never a source of truth. This holds only while every query asks about now. If the value must also be queryable as of an earlier instant, the cache is part of the history and must be temporal like everything else. Before building one, measure whether a view or a query over the temporal tables is already fast enough.
A composite whose identity is a hash of its content is immutable by construction: the same key can never hold different content, so there is no version to record and nothing to phase out. A blueprint string keyed by the SHA-1 of the string is one, and the tables derived by parsing it (parsed game data, icons, recipes, entities) belong to the same composite and are exempt with it. Rows of a content-addressed composite are only inserted, never updated. Anything that merely references the composite by hash, such as the blueprint that points at a string, is an ordinary temporal table.
Every temporal table has system_from (when this version became current, set by the application) and system_to (when it was superseded, defaulting to the far-future sentinel), both NOT NULL.
(id, system_to) or (id, system_from), unique index on the otherEither works, and they are equivalent as long as the other pair has a unique index. The (id, system_to) constraint is the one that catches a bug that creates two current rows for one ID: all current rows share system_to = FAR_FUTURE_DATE, so the second insert fails immediately. Reladomo puts the PK on (id, system_to). The (id, system_to) index also serves the most common query, finding the current version.
Pick one encoding for every temporal table, with millisecond precision or finer:
| Encoding | Column type | Sentinel | Notes |
|---|---|---|---|
| Epoch milliseconds | INTEGER | 253402300799999 | Cheapest to compare, index and bind, and identical to JavaScript Date.now(). Unreadable in raw queries unless paired with the derived columns below. |
| Epoch nanoseconds | INTEGER | 9223372036854775807 | The finest integer encoding; the 64-bit maximum (year 2262) is the sentinel. Precision is only as fine as the clock: Node's process.hrtime.bigint() resolves nanoseconds, but browsers and Cloudflare Workers expose milliseconds (Workers also freeze the clock while code runs), so there the values are milliseconds times 1,000,000. |
| ISO text with fraction | TEXT | 9999-12-31 23:59:59.999 | Readable as stored and sorts correctly, provided every value has the same width and fraction digits. |
The query and DDL examples below use the whole-second text form 9999-12-31 23:59:59 to keep them short. Substitute your encoding's sentinel and comparison values.
With epoch milliseconds, add generated VIRTUAL columns that render each timestamp as text. They cost no storage, they appear in SELECT * and in the database console, and the application never writes them.
CREATE TABLE nodes (
id TEXT NOT NULL,
name TEXT,
system_from INTEGER NOT NULL, -- set by the application, once per unit of work
system_to INTEGER NOT NULL DEFAULT 253402300799999,
system_from_text TEXT GENERATED ALWAYS AS (strftime('%Y-%m-%d %H:%M:%f', system_from / 1000.0, 'unixepoch')) VIRTUAL,
system_to_text TEXT GENERATED ALWAYS AS (strftime('%Y-%m-%d %H:%M:%f', system_to / 1000.0, 'unixepoch')) VIRTUAL,
PRIMARY KEY (id, system_to)
);
The sentinel renders as 9999-12-31 23:59:59.999. SQLite rejects an INSERT or UPDATE that names a generated column, so a writer cannot set them by mistake. Never filter or join on them; compare the integer columns. Columns added later with ALTER TABLE ... ADD COLUMN must be VIRTUAL.
An ORM can ignore them by leaving them out of its table definition, in which case they need a hand-written migration. Or it can declare them so migrations create them. In Drizzle:
systemFromText: text('system_from_text').generatedAlwaysAs(
sql`strftime('%Y-%m-%d %H:%M:%f', system_from / 1000.0, 'unixepoch')`,
{mode: 'virtual'},
),
Drizzle's SQLite generated-column support needs drizzle-orm 0.32 or later and drizzle-kit 0.23 or later. Cloudflare D1 supports generated columns, but verify that drizzle-kit emits VIRTUAL ones for D1 with your versions. An alternative with no schema footprint is a read-only view that adds the text columns.
CREATE TABLE nodes (
id TEXT NOT NULL,
name TEXT,
system_from TEXT NOT NULL, -- set by the application, once per unit of work
system_to TEXT NOT NULL DEFAULT '9999-12-31 23:59:59',
PRIMARY KEY (id, system_to)
);
CREATE UNIQUE INDEX nodes_system_from_idx ON nodes(id, system_from);
SQLite requires recreating the table to change the primary key:
CREATE TABLE my_table_new (
id TEXT NOT NULL,
-- existing columns...
system_from TEXT NOT NULL,
system_to TEXT NOT NULL DEFAULT '9999-12-31 23:59:59',
PRIMARY KEY (id, system_to)
);
INSERT INTO my_table_new
SELECT *, strftime('%Y-%m-%d %H:%M:%f', 'now'), '9999-12-31 23:59:59.999'
FROM my_table;
DROP TABLE my_table;
ALTER TABLE my_table_new RENAME TO my_table;
CREATE INDEX my_table_system_from_idx ON my_table(id, system_from);
For databases that support ALTER TABLE ... ADD PRIMARY KEY, this is simpler:
ALTER TABLE my_table ADD COLUMN system_from TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE my_table ADD COLUMN system_to TIMESTAMP NOT NULL DEFAULT '9999-12-31 23:59:59';
ALTER TABLE my_table DROP PRIMARY KEY;
ALTER TABLE my_table ADD PRIMARY KEY (id, system_to);
CREATE INDEX my_table_system_from_idx ON my_table(id, system_from);
After migration, update application code to add WHERE system_to = '9999-12-31 23:59:59' to all existing queries.
SELECT * FROM nodes WHERE system_to = '9999-12-31 23:59:59';
-- For a specific entity
SELECT * FROM nodes WHERE id = ? AND system_to = '9999-12-31 23:59:59';
Use system_from <= T AND system_to > T:
SELECT * FROM nodes
WHERE id = ?
AND system_from <= '2024-06-15 14:30:00'
AND system_to > '2024-06-15 14:30:00';
Exactly one row matches at any instant. Never use BETWEEN for as-of queries: with contiguous timestamps it matches two rows at each boundary.
SELECT * FROM nodes WHERE id = ? ORDER BY system_from DESC;
SELECT DISTINCT id FROM nodes
WHERE system_from >= '2024-01-01' AND system_from <= '2024-12-31';
-- Step 1: Close the current version
UPDATE nodes
SET system_to = '2024-06-15 14:30:00'
WHERE id = 'node-1' AND system_to = '9999-12-31 23:59:59';
-- Step 2: Insert the new version
INSERT INTO nodes (id, name, system_from, system_to)
VALUES ('node-1', 'New Name', '2024-06-15 14:30:00', '9999-12-31 23:59:59');
The new row's system_from must equal the old row's system_to to maintain a contiguous timeline. Both statements must run in the same transaction.
Phase out without inserting a replacement:
UPDATE nodes
SET system_to = '2024-06-15 14:30:00'
WHERE id = 'node-1' AND system_to = '9999-12-31 23:59:59';
When syncing from an external source into a temporal cache, implement all three legs:
External Source Cache (temporal)
+-------------+ +-------------+
| A (updated) | | A (old) | <- LEG 1: Update
| B (same) | | B (same) | <- LEG 1: Leave untouched
| C (new) | | D (deleted) | <- LEG 2: Insert C
+-------------+ +-------------+ <- LEG 3: Phase out D
system_from = now, system_to = FAR_FUTURE_DATE.UPDATE nodes
SET system_to = @now
WHERE system_to = '9999-12-31 23:59:59'
AND id NOT IN (SELECT id FROM source_ids);
Leg 3 is the most commonly forgotten. Without it, deleted items stay in the cache forever, the cache grows unbounded, and stale data causes errors when writing back to the source.
Wrap all three legs in one transaction, and make sure an empty source list phases out every cached record.
Bulk imports use the same compare-before-cut logic, and can report each record as added, updated, unchanged, or deleted.
Each temporal table tracks its own system_from/system_to. Don't derive a child's system_to by joining on the parent's system_from: with deduplication, the parent row may not change when only child data changes, and vice versa.
All tables edited in one transaction use the same timestamp, so an as-of query at that timestamp returns a coherent snapshot.
Each new version copies the unchanged columns. Consider splitting very wide, rarely changing columns into a separate table to reduce duplication.
Apply both operations to every table, including settings and account state, so the whole database returns to the same instant:
-- 1. Purge: Delete rows created after the rollback point
DELETE FROM nodes WHERE system_from > @target_timestamp;
-- 2. Restore: Re-open rows that were current at the rollback point
UPDATE nodes
SET system_to = '9999-12-31 23:59:59'
WHERE system_from <= @target_timestamp
AND system_to > @target_timestamp;
This is destructive and violates immutability. Use it only for disaster recovery.
Data rebuilt entirely from temporal tables (full-text search indexes, caches, materialized views) may be non-temporal. Rebuild it after a rollback instead of rolling it back. Framework bookkeeping such as a migrations table is not data and is exempt.
A composite is an entity spanning multiple tables, e.g. a Blueprint composite of Blueprint, BlueprintTag, and ImgurImage.
Ownership direction matters. BlueprintTag belongs to the Blueprint composite, not the Tag composite: a tag is standalone, and BlueprintTag is a join table owned by Blueprint. Editing any part of a composite bumps the whole composite's version once, so a BlueprintTag change bumps the Blueprint version, not the Tag version. Ownership determines which version table a write updates and which tables participate in as-of-by-version queries.
A separate version table tracks version numbers with their own system_from/system_to:
CREATE TABLE question_version (
question_id BIGINT NOT NULL,
number INTEGER NOT NULL,
system_from TIMESTAMP NOT NULL,
system_to TIMESTAMP NOT NULL DEFAULT '9999-12-31 23:59:59',
PRIMARY KEY (question_id, system_to)
);
The version table is the entry point for as-of-by-version queries: look up the version's system_from, then run as-of queries at that timestamp on every table in the composite.
-- Step 1: Find the timestamp for version 1
SELECT system_from FROM question_version
WHERE question_id = ? AND number = 1;
-- Step 2: Use that timestamp for as-of queries on all related tables
SELECT * FROM question
WHERE id = ? AND system_from <= @version_timestamp AND system_to > @version_timestamp;
SELECT * FROM question_tag
WHERE question_id = ? AND system_from <= @version_timestamp AND system_to > @version_timestamp;
Auditing records who made each change, and builds on temporal support.
CREATE TABLE question (
id BIGINT NOT NULL,
title TEXT,
body TEXT,
created_by_id TEXT NOT NULL,
created_on TIMESTAMP NOT NULL,
last_updated_by_id TEXT NOT NULL,
system_from TIMESTAMP NOT NULL,
system_to TIMESTAMP NOT NULL DEFAULT '9999-12-31 23:59:59',
PRIMARY KEY (id, system_to)
);
created_by_id and created_on are set once on creation. last_updated_by_id changes with each version. Put these columns on both the main table and the version table.
Edit APIs take the version number as input and reject the edit with a conflict error when it doesn't match the current version.
The Klass DSL uses classifier modifiers as compiler macros:
class Question
systemTemporal
versioned
audited
{
id : Long key;
title: String;
body : String;
}
systemTemporal infers system/systemFrom/systemTo properties. versioned infers a version class. audited infers createdById/createdOn/lastUpdatedById properties.
Liftwizard uses Reladomo for temporal support. Reladomo manages system_from/system_to through AsOfAttribute declarations in XML object definitions, and handles phase-out / phase-in, contiguous timelines, and as-of queries.
See Liftwizard temporal documentation for non-destructive updates, as-of queries, versioning, auditing, optimistic locking, diffs, and maker/checker workflows.
import {sqliteTable, text, primaryKey, uniqueIndex} from 'drizzle-orm/sqlite-core';
export const nodes = sqliteTable(
'nodes',
{
id: text('id').notNull(),
name: text('name'),
systemFrom: text('system_from').notNull(),
systemTo: text('system_to').notNull().default('9999-12-31 23:59:59'),
},
(table) => ({
pk: primaryKey({columns: [table.id, table.systemTo]}),
systemFromIdx: uniqueIndex('nodes_system_from_idx').on(table.id, table.systemFrom),
}),
);
Take the timestamp in application code once per unit of work (for example new Date() formatted as UTC) and pass it to every insert and update in that unit. Do not keep a clock table or let the database default system_from.
Test as-of queries at version boundaries; off-by-one errors there are common.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub motlin/claude-code-plugins --plugin temporal-data2 skills in this plugin
Other plugins' skills for the same job