Defining Schemas
Learn how to define type-safe database schemas with the append-only log approach
Basic Schema Definition
Define your schema using the schema() function with a builder pattern:
import { schema, idColumn, column } from "@fragno-dev/db/schema";
export const commentSchema = schema((s) => {
return s.addTable("comment", (t) => {
return t
.addColumn("id", idColumn())
.addColumn("content", column("string"))
.addColumn(
"createdAt",
column("timestamp").defaultTo((b) => b.now()),
)
.addColumn("userId", column("string"))
.addColumn("postId", column("string"));
});
});Every Table Needs an ID
Every table must have exactly one idColumn(). This is the user-facing primary key (a CUID
string). The system also adds a hidden _internalId column for database-level joins.
Columns, Types & Indexes
Column Types
// Basic types
column("string"); // Short string, maps to VARCHAR(191)
column("text"); // Unbounded text; not indexable
column("integer");
column("boolean");
column("timestamp");
column("json");
column("bigint");
column("decimal");
column("date");
column("binary");
// Special types
idColumn(); // Auto-generated CUID primary key
referenceColumn({ table: "otherTable" }); // Foreign key reference (bigint)Not all types are indexable
Because of limitations in a number of database systems, not all types are indexable. json,
binary, and text are not indexable. column("string") is intended for indexable short
strings, while column("text") cannot be indexed.
Modifiers
column("string")
.nullable() // Allow NULL values
.defaultTo("active"); // Database-level static default valueDefault Values
defaultTo() - Database-Level
Database generates the default. Falls back to application code if unsupported.
// Static values
column("string").defaultTo("active");
column("integer").defaultTo(0);
column("boolean").defaultTo(true);
// Special functions
column("timestamp").defaultTo((b) => b.now()); // DEFAULT NOW() or equivalentdefaultTo$() - Runtime
Application generates the default.
column("string").defaultTo$((b) => b.cuid()); // Generate CUID
column("timestamp").defaultTo$((b) => b.now()); // Generate timestamp
column("integer").defaultTo$(42); // Static literal
column("integer").defaultTo$((b) => Math.random()); // Custom logicExample:
.addTable("posts", (t) => {
return t
// idColumn() automatically creates a runtime CUID and database-level serial id
.addColumn("id", idColumn())
// database-level static default value "draft"
.addColumn("status", column("string").defaultTo("draft"))
// database-level timestamp default value
.addColumn("createdAt", column("timestamp").defaultTo((b) => b.now()))
// runtime CUID default value
.addColumn("sessionId", column("string").defaultTo$((b) => b.cuid()));
// runtime timestamp default value
.addColumn("updatedAt", column("timestamp").defaultTo$((b) => b.now()));
});Indexes
In Fragno, indexes are required for most operations such as where and orderBy.
.addTable("comment", (t) => {
return t
.addColumn("postId", column("string"))
.addColumn("userId", column("string"))
.addColumn("email", column("string"))
// Single-column index
.createIndex("idx_post", ["postId"])
// Multi-column index
.createIndex("idx_user_post", ["userId", "postId"])
// Unique index
.createIndex("idx_email", ["email"], { unique: true });
})Index Your Query Columns
Create indexes for columns used in where() clauses. Multi-column indexes should list columns in
order of selectivity (most selective first).
Relations
Define foreign-key relationships directly on referenceColumn({ table }):
export const commentSchema = schema((s) => {
return s.addTable("comment", (t) => {
return t
.addColumn("id", idColumn())
.addColumn("content", column("string"))
.addColumn("parentId", referenceColumn({ table: "comment" }).nullable())
.createIndex("idx_comment_parent", ["parentId"]);
});
});Relation Types
// Many-to-one / foreign key: post -> author
.addColumn("userId", referenceColumn({ table: "users" }))
// One-to-many is derived automatically by code generators from FK-bearing columns.External References
For references to user data outside your Fragment, use regular string columns:
.addTable("comment", (t) => {
return t
.addColumn("id", idColumn())
.addColumn("content", column("string"))
// External references - NOT referenceColumn({ table: "..." })
.addColumn("userId", column("string"))
.addColumn("postId", column("string"));
})Use referenceColumn({ table: "..." }) only for internal relations between your Fragment's tables.
User data lives in separate tables outside your control, so no foreign key constraint is needed.
You may also chose not to have any external references in your schema. The user can define their own association table in their application's schema.
Schema Evolution
Fragno uses an append-only log approach where every schema change is recorded as an operation. This enables automatic migration generation.
How It Works
const mySchema = schema((s) => {
return s
.addTable("users", (t) => t.addColumn("id", idColumn()).addColumn("name", column("string")))
.addTable("posts", (t) => t.addColumn("id", idColumn()).addColumn("title", column("string")))
.alterTable("users", (t) => t.addColumn("email", column("string")));
});
// mySchema.version === 3 // Three operations = version 3Each operation (.addTable(), .alterTable(), .dropTable(), .noOp()) increments the version
by 1. The CLI uses this to generate migrations for users upgrading from older versions.
Using alterTable()
To evolve your schema over time, always use alterTable() to add columns or indexes:
export const commentSchema = schema((s) => {
return (
s
// Version 1: Initial table
.addTable("comment", (t) => {
return t.addColumn("id", idColumn()).addColumn("content", column("string"));
})
// Version 2: Add rating
.alterTable("comment", (t) => {
return t.addColumn("rating", column("integer").defaultTo(0));
})
// Version 3: Add index
.alterTable("comment", (t) => {
return t.createIndex("idx_rating", ["rating"]);
})
);
});
// commentSchema.version === 3When users upgrade your Fragment, the CLI generates migrations for only the versions they're missing.
Rules:
- Never modify existing
addTable()calls - always use
alterTable()to add columns - New columns must be nullable
Renaming columns and replacing indexes
alterTable() can also rename a column and drop an index, keeping the table's rows:
.alterTable("comment", (t) => {
return t
.renameColumn("rating", "score")
.dropIndex("idx_rating")
.createIndex("idx_rating", ["score", "id"]);
})- A rename keeps the column's data, and indexes on the column follow it under their old names.
- A dropped index's name can be used again in the same call, for example to recreate the index on other columns.
- Only regular columns of an existing table can be renamed: not ID, system, or reference columns, and not a column added in the same call.
Fragno has no data migrations, so a change that needs existing values rewritten has to avoid rewriting them. For example, add a column with a default that is right for every existing row.
Integrators who generate Drizzle or Prisma schemas and run migrations with their own tools see a rename as a dropped column and an added one, which loses the column's data. Tell them in your release notes to apply it as a rename.
Dropping tables
dropTable() drops a table and its rows. Keep its addTable() and every alterTable() of it in
place, so the history still says what the table was:
.dropTable("draft")- No other table may reference the dropped table.
- Its name stays taken. Clients that replay the outbox, such as Lofi, still receive the dropped table's old rows, and skip them because the schema says the table was dropped. A new table under that name would receive them instead.
- The migration drops the table only if it exists. If an earlier release removed the table by
replacing its
addTable()withnoOp(), put theaddTable()back and drop the table. Databases created after that release never held it.
System Columns
Fragno automatically adds hidden system columns to every table:
_internalId(bigint) - Database-native primary key for joins_version(integer) - Optimistic concurrency control
These are hidden from the user-facing API but used internally for foreign key relationships and optimistic locking.
Next Steps
- Learn about Querying with the DB
- See
Dependencies and Services
for using
dbin context - Check the example-fragments/fragno-db-library for a complete example