Quick Example
Here’s a complete schema definition from the zbugs reference app:Tables
Defining Tables
Tables are defined using a fluent builder API:Creates a table builder with the specified name. The name should match your PostgreSQL table name.
Defines the columns for the table. Returns a new builder with the columns set.
Specifies the primary key column(s). Required before passing to
createSchema.Column Types
Zero supports the following column types:- string
- number
- boolean
- enumeration
- json
TEXT, VARCHAR, or CHAR.TypeScript type: string or string | undefined (if optional)Optional Columns
Mark columns as optional with.optional():
In the type system, optional columns are explicitly
type | undefined, not just type?. This ensures proper handling of null vs undefined.Composite Primary Keys
Tables can have multi-column primary keys:Server Name Mapping
If your PostgreSQL table or column name differs from your client-side name:Relationships
Relationships enable querying related data across tables.One-to-One Relationships
One-to-Many Relationships
Many-to-Many (Junction) Relationships
For many-to-many relationships through a junction table:Composite Foreign Keys
Relationships can use multiple columns:Multi-Hop Relationships
Chain relationships for deeper traversals:Creating the Schema
Once tables and relationships are defined, create the schema:Array of table definitions created with
table().Array of relationship definitions created with
relationships().Type Augmentation
Register your schema with Zero’s type system for full type safety:- Type-safe query building
- Autocomplete for table and column names
- Correct return types for queries
- Compile-time errors for invalid queries
Schema Validation
Zero validates your schema at runtime:Common Validation Errors
Missing primary key
Missing primary key
Relationship to non-existent table
Relationship to non-existent table
Invalid relationship field
Invalid relationship field
Name conflict
Name conflict
Schema Migrations
Zero doesn’t manage PostgreSQL schema migrations. Use your preferred migration tool:- Drizzle
- Prisma
- node-pg-migrate
- Raw SQL
After updating your PostgreSQL schema, update your Zero schema definition to match. The Zero schema should mirror your PostgreSQL structure.
Best Practices
Keep schema and database in sync
Keep schema and database in sync
Your Zero schema should accurately reflect your PostgreSQL schema. Mismatches will cause runtime errors.
Use enumerations for literal unions
Use enumerations for literal unions
Explicit optional fields
Explicit optional fields
Name relationships meaningfully
Name relationships meaningfully
Use composite keys when appropriate
Use composite keys when appropriate
Example: Complete Schema
Here’s the full schema from the zbugs app:Next Steps
Queries
Learn how to query your schema
Relationships
Query related data efficiently
Permissions
Control access to your data
Mutations
Write data with type-safe mutators