Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Schema Format Reference

RustF schemas are YAML files that describe your data model. They are the single source of truth: the CLI generates both Rust models (schema generate models) and full SQL DDL (schema generate sql) from them. SQL is a standard, but this YAML format is RustF-specific — this page is its complete specification.

This reference is derived from the actual parser (rustf-schema). Keys not listed here are ignored by the parser; a few keys are accepted for forward-compatibility but have no effect yet — those are marked (accepted, ignored).

schema generate sql is experimental. The DDL generator is verified on representative schemas across all three dialects, but has not yet been exercised at scale. Review the generated SQL before applying it. Model generation (schema generate models) is stable.

File layout

schemas/
├── _meta.yaml        # optional global metadata (see below)
├── users.yaml        # one file per table (or group several tables per file)
└── orders.yaml

Each table file maps a logical table name to a table definition. You may put several tables in one file.

# schemas/users.yaml
Users:                  # logical name (used for the generated model)
  table: users          # physical table name
  version: 1
  fields:
    id:
      type: mediumint
      primary_key: true
      auto: true

fields is a map, not a list. Each field is a key (id:), not a - name: id list item. List form does not parse.

Table definition

KeyTypeRequiredPurpose
tablestringyesPhysical table name used in generated SQL/queries.
versionintegeryesSchema version for change tracking and consistency checks.
namestringnoOverride for the generated model name (defaults to the YAML key).
descriptionstringnoHuman-readable description (emitted as a SQL comment).
database_typestringnomysql | postgres | sqlite (per-table override of _meta).
database_namestringnoSource database instance name (informational).
element_typestringnotable | view | materialized_view. Defaults to table.
viewmapnoView body — required when element_type is a view (see Views).
tagsstring[]noFree-form categorization.
ai_contextstringnoExtra guidance for AI code assistants.
fieldsmapyes¹Field definitions (see below). Optional for views.
relationsmapnoRelationships to other tables (see below).
indexeslistnoIndex definitions (see below).
constraintslistnoTable-level constraints. (reserved — parsed but not yet enforced)

¹ Required for tables. For views fields is optional and only drives typed, read-only model generation; omit it for an untyped view.

Views

A view is a Table entry with element_type: view (or materialized_view) and a view: block holding the SQL body. The body is raw, dialect-native SQL — the SELECT … statement without the leading CREATE VIEW <name> AS.

ActiveUserOrders:
  table: active_user_orders
  database_type: postgres
  element_type: view          # or: materialized_view
  version: 1
  description: "Open orders joined to their user."
  view:
    or_replace: true          # emit CREATE OR REPLACE VIEW (plain views only)
    sql: |
      SELECT o.id,
             o.user_id,
             u.email,
             o.total_cents
      FROM orders o
      JOIN users u ON u.id = o.user_id
      WHERE o.status = 'open'
  # Optional: typed output columns → read-only model with no insert/update/delete.
  fields:
    id:          { type: int }
    user_id:     { type: int }
    email:       { type: string(255) }
    total_cents: { type: int }

view keys

KeyTypeRequiredPurpose
sqlstringyesRaw SELECT body. Emitted verbatim into CREATE VIEW … AS <sql>.
or_replaceboolnoEmit CREATE OR REPLACE VIEW. Ignored for materialized views (they are dropped and recreated).

Behavior

  • SQL generation emits CREATE [OR REPLACE] VIEW / CREATE MATERIALIZED VIEW, never CREATE TABLE. Views are always emitted after all tables, and a view that references another view is emitted after its dependency, so generation never hits a “relation does not exist” error.
  • Models generated for views are read-only: insert / create / update / delete are omitted.
  • Validation requires a non-empty view.sql; a view does not need a primary key or any fields.
  • Introspection (db introspect / db generate-schemas) detects views and fills view.sql from pg_get_viewdef (PostgreSQL) or information_schema.VIEWS (MySQL), so an introspected view round-trips back to valid CREATE VIEW DDL.

A structured view form (select / from / where) for simple views is planned. Raw sql remains the escape hatch for anything non-trivial (CTEs, window functions, dialect specifics).

Field definition

A field maps a column name to its type and constraints.

email:
  type: string(150)
  required: true
  unique: true
  description: User's primary email

Field keys

The Effect column says where a key actually changes output:

  • DDL — emitted in the generated SQL schema.
  • model — changes the generated Rust struct/types.
  • metadata — parsed and exposed to tooling and AI assistants (via the CLI), but not enforced at runtime or in SQL. Validation keys live here today: they document intent but the generated model does not check them.
KeyTypeEffectPurpose
typestringDDL + modelColumn type. See Type system. Required.
valuesstring[]DDL + modelAllowed values — required when type: enum.
primary_keyboolDDL + modelMarks the primary key.
autoboolDDL + modelAuto-increment (SERIAL / AUTO_INCREMENT / AUTOINCREMENT).
requiredboolDDL + modelEmits NOT NULL; checked by the model builder.
nullableboolDDL + modelnullable: false also emits NOT NULL; otherwise Option<T>.
uniqueboolDDLEmits a UNIQUE constraint.
defaultscalarDDL + modelColumn default (string/number/bool).
foreign_keystringDDL"table.column" (or "table", defaulting to id).
on_deleteenumDDLFK action: cascade, restrict, set_null, set_default, no_action.
on_updateenumDDLSame actions as on_delete.
lang_typestringmodelOverride the generated Rust type (e.g. Option<u8>).
min / maxnumbermetadataIntended numeric range — not enforced.
min_length / max_lengthintegermetadataIntended string length — not enforced.
patternstringmetadataIntended regex — not enforced.
validationstring | mapmetadataNamed validator (email) or rule map — not enforced.
computedstringmetadataMarks a derived field — not generated.
hiddenboolmetadataIntended to hide from serialization — not enforced.
postgres_type_namestringmetadataNamed Postgres enum type hint.
transitionsmapmetadataIntended enum state transitions — not enforced.
aistringmetadataAI hint, emitted as a doc comment.
exampleanymetadataExample value (documentation).
enum, index, indexed, search_weight, column_comment—ignored(accepted, parsed, no effect)

NOT NULL is emitted when required: true, nullable: false, or the field is the primary key.

Validation is not yet enforced. min, max, min_length, max_length, pattern, and validation are recorded as schema metadata and surfaced to tooling, but the generated models do not validate against them at runtime. Enforce these in your own code (e.g. a controller before hook) until runtime validation lands.

Type system

type is a string. Three forms are supported.

Simple types

These map to dialect-correct SQL (see the per-dialect table in the Database guide):

Schema typeNotes
tinyint, smallint, mediumint, int / integer, bigintInteger family; width preserved on MySQL, widened sensibly elsewhere.
serialAuto-increment integer.
boolean / boolTINYINT(1) on MySQL, BOOLEAN elsewhere.
decimal / numericFixed-point (prefer the parameterized form below).
float, doubleFloating point.
string / text, mediumtext, longtext, tinytextText.
date, time, datetime, timestampTemporal.
json, jsonbJSONB on Postgres, JSON on MySQL, TEXT on SQLite.
uuidUUID on Postgres, CHAR(36) on MySQL, TEXT on SQLite.
blob / binaryBinary data.

Native database type names produced by db generate-schema (e.g. mediumint) are accepted directly, so round-tripping an existing database works.

Parameterized types

username: { type: string(150) }     # VARCHAR(150)
code:     { type: char(8) }         # CHAR(8)
price:    { type: decimal(10,2) }   # DECIMAL(10,2)

Enum types

Enums require a sibling values list:

status:
  type: enum
  values: [active, inactive, pending]
  default: pending

This generates a native ENUM(...) on MySQL and a TEXT CHECK (status IN (...)) constraint on Postgres and SQLite.

Relations

relations:
  has_many:
    posts:
      model: Posts
      local_field: id
      foreign_field: author_id
  belongs_to:
    company:
      model: Companies
      local_field: company_id
      foreign_field: id
      on_delete: set_null
RelationRequired fieldsOptional
has_manymodel, local_field, foreign_fieldcascade, ai
has_onemodel, local_field, foreign_fieldcascade, ai
belongs_tomodel, local_field, foreign_fieldon_delete, on_update, ai
many_to_manymodel, through, local_through_field, foreign_through_field, local_field, foreign_fieldai

Relations drive model generation. Foreign-key DDL comes from a field’s foreign_key key, not from relations.

Indexes

Three forms:

indexes:
  - email                              # single-column
  - [last_name, first_name]            # composite
  - fields: [email]                    # detailed
    unique: true
    type: btree

Table-level constraints

A constraints: key is accepted by the parser but does nothing today — it is ignored by both SQL and model generation. In particular there is no raw-SQL CHECK support: a sql: "price >= 0" entry produces no SQL and no validation. The key exists only as a reserved slot for a future release.

For checks today, use field-level keys (which still record metadata) and enforce rules in your own code (e.g. a controller before hook) — see the validation note above.

Global metadata (_meta.yaml)

Optional. Provides defaults and informational metadata for the schema set. Only these keys are honored:

version: "1.0"
database_type: mysql          # default dialect for SQL generation
database_name: myapp
description: "Application schema"
ai_context: "Guidance for AI assistants working with this schema"

The SQL generator detects the target dialect from description / database_type. Set database_type (or mention the dialect in description) so the right SQL flavour is produced. Any other keys in _meta.yaml are ignored.

Complete example

# schemas/users.yaml
Users:
  table: users
  version: 1
  description: Application user accounts
  fields:
    id:
      type: mediumint
      primary_key: true
      auto: true
      required: true

    email:
      type: string(150)
      required: true
      unique: true
      validation: email

    password_hash:
      type: string(255)
      required: true
      hidden: true

    role:
      type: enum
      values: [admin, user, moderator]
      default: user
      required: true

    manager_id:
      type: mediumint
      foreign_key: users.id
      on_delete: set_null

    is_active:
      type: boolean
      default: true

    created_at:
      type: timestamp

  relations:
    belongs_to:
      manager:
        model: Users
        local_field: manager_id
        foreign_field: id

  indexes:
    - email

Generate from it:

rustf-cli schema generate models       # -> src/models/base/users.inc.rs
rustf-cli schema generate sql          # -> sql/schema.sql