Skip to content

Database schema ​

The framework's migrations create the tables below. Use this page when you write reports or support queries, plan a backup, or check what a table holds before you touch it. Your own tables live next to them in the same database.

rustcms migrate runs the framework's migrations before yours: an application's migrator starts from rustcms::migration::framework():

rs
pub struct Migrator;

impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        let mut migrations = rustcms::migration::framework();
        let app: Vec<Box<dyn MigrationTrait>> = vec![
            Box::new(m20261011_155203_create_posts_table::Migration),
            Box::new(m20261012_000001_create_categories_and_post_content::Migration),
            Box::new(m20261013_000001_add_deleted_at_to_posts::Migration),
            Box::new(m20261014_000001_add_media_to_posts::Migration),
            Box::new(m20261014_000002_add_color_to_categories::Migration),
            Box::new(m20261015_000001_add_attributes_to_posts::Migration),
            Box::new(m20261022_000001_create_tags::Migration),
            Box::new(m20261101_000001_create_integrations::Migration),
            Box::new(m20261118_000001_add_kind_to_tags::Migration),
            Box::new(m20261119_000001_add_layout_to_categories::Migration),
            Box::new(m20261124_000001_add_parent_to_tags::Migration),
            Box::new(m20261201_000001_create_category_highlights::Migration),
            // rustcms:migrations
        ];
        migrations.extend(app);
        migrations
    }
}

Column types are shown portably:

  • instant: TIMESTAMPTZ on PostgreSQL, DATETIME(6) in UTC on MySQL, text on SQLite;
  • bigint id: auto-increment BIGINT;
  • uuid: UUID on PostgreSQL, the database's UUID mapping elsewhere;
  • json: JSON (JSONB is not used).

Never write the access-control tables yourself: every change to roles, permissions and their assignments goes through RbacService (Roles & permissions), which checks the actor, locks, audits and invalidates the permission cache.

Users and access ​

text
                          ┌──────────────────────────┐
                          │ users                    │
                          │ id, email (unique), …    │
                          │ auth_version, is_active  │
                          └───────────┬──────────────┘
         (model_type = 'user', model_id = users.id as text)
              ┌───────────────────────┼──────────────────────────────┐
              ▼                       ▼                              ▼
┌──────────────────────────┐ ┌───────────────────────────┐ ┌───────────────────────────┐
│ model_has_roles          │ │ model_has_permissions     │ │ sessions / tokens / JWT   │
│ role_id, model_type,     │ │ permission_id, model_type,│ │ personal_access_tokens    │
│ model_id                 │ │ model_id   (direct grants)│ │ jwt_families → jwt_refresh│
└───────────┬──────────────┘ └─────────────┬─────────────┘ │ user_tokens (reset/invite)│
            ▼                              ▼               └───────────────────────────┘
┌──────────────────────────┐ ┌───────────────────────────┐
│ roles                    │ │ permissions               │
│ name + guard_name unique │ │ name + guard_name unique  │
│ is_system, is_privileged │ │ group, orphaned           │
└───────────┬──────────────┘ └─────────────▲─────────────┘
            └──────► role_has_permissions ─┘
                     (role_id, permission_id)

A user's permissions in a guard are those of their roles in that guard, plus their direct grants. Orphaned permissions are left out. super_admin passes every check of its guard.

users ​

ColumnTypeNotes
idbigint idprimary key
namevarchar(255)
emailvarchar(255)unique (users_email_key); stored trimmed and lowercased
passwordvarchar(255)Argon2id hash, never the password
is_activeboolean, default truefalse: cannot sign in, every session and token stops at once
auth_versionbigint, default 0bumped by account changes (password, email, sign-out everywhere, …): sessions and JWT sign-ins issued for an older version stop working (revocation). Role and permission changes do not bump it: they apply from the next request through auth_generations
email_verified_atinstant, null
localevarchar(35), nulladmin language chosen by the user; null follows the browser
invitation_pendingboolean, default falseinvited, password not chosen yet: cannot sign in or reset
invited_atinstant, null
invited_bybigint, nullthe inviting user's id, without a foreign key (that user may be deleted)
created_at, updated_atinstant

Deleting a user cascades to their tokens, JWT families and one-time tokens. Their role and permission assignments are removed by RbacService in the same transaction: model_has_* hold no foreign key to users.

roles ​

ColumnTypeNotes
idbigint id
namevarchar(255)unique together with guard_name (roles_name_guard_key)
guard_namevarchar(64)admin (the panel) or api (tokens and JWT); the guards never mix
is_systembooleanmade by the migrations: never renamed or deleted
is_privilegedbooleanmanaged by super admins only
created_atinstant

The migrations seed super_admin in each guard (is_system and is_privileged). Other roles are yours: created in the panel (admin guard), by seeders, or from code (RbacService::create_role).

permissions ​

ColumnTypeNotes
idbigint id
namevarchar(255)posts.update, users.invite, …; unique with guard_name (permissions_name_guard_key)
guard_namevarchar(64)as for roles
groupvarchar(255), nullfor display, usually the resource slug
orphanedboolean, default falseno longer declared by the application: kept, grants nothing
created_atinstant

Rows come from the permissions the application declares (resources, AuthProvider::permission). rustcms permission:sync adds the new ones and marks the undeclared ones orphaned. It never renames or deletes, so a typo cannot silently drop a grant.

role_has_permissions, model_has_roles, model_has_permissions ​

TablePrimary keyForeign keys
role_has_permissions(role_id, permission_id)both, ON DELETE CASCADE
model_has_roles(role_id, model_type, model_id)role_id → roles, cascade
model_has_permissions(permission_id, model_type, model_id)permission_id → permissions, cascade
  • model_type is user and model_id is the user's id as text: the Spatie-style shape leaves room for other holders.
  • model_has_* are indexed on (model_type, model_id) for "what does this user hold".
  • Direct grants (model_has_permissions) exist for exceptions; roles are the usual way.

auth_generations ​

ColumnTypeNotes
namevarchar(32)primary key; rbac
valuebigintadvanced inside every RBAC transaction

Instances cache resolved permissions per generation. A change anywhere advances it, and every instance reloads (several instances).

Credentials ​

TableHoldsStored secretNotes
sessionsadmin sign-ins (and anonymous CSRF sessions)id varchar(128) = HMAC-SHA-256 of the cookie's random value, keyed by APP_KEYdata (JSON text), expires_at (indexed, pruned hourly), lineage varchar(64), null (the first session of a re-issued chain: sign-out ends all of it; indexed)
personal_access_tokensAPI tokens (rcms_…)token_hash varchar(64) = SHA-256id bigint, user_id → users (cascade, indexed), name, abilities (JSON list, ["*"] = all of the user's permissions), last_used_at, expires_at, revoked_at, created_at
jwt_familiesone JWT sign-in and its refresh chainnoneid varchar(32), user_id → users (cascade), abilities, auth_version at issue, created_at, expires_at, revoked_at
jwt_refresh_tokenseach refresh token of a familytoken_hash varchar(64) = HMAC-SHA-256 under a key derived from APP_KEYid bigint, family_id → jwt_families (cascade), created_at, expires_at, used_at: reusing a used token revokes the family
user_tokenspassword-reset and invitation linkstoken_hash varchar(64) under a key derived from APP_KEYsee below

user_tokens ​

ColumnTypeNotes
iduuidprimary key; the public half of the token
user_idbigint→ users, ON DELETE CASCADE
purposevarchar(32)password_reset or invitation; unique with user_id (user_tokens_user_purpose_key): one live link per user and purpose
emailvarchar(255)the user's email when it was issued: a change of email kills the link
auth_versionbigintthe user's auth_version when it was issued: a change kills the link
token_hashvarchar(64)hex HMAC-SHA-256 of purpose, id and secret
request_iduuidthe request (a queued mail job) the link answers: a retried job sends nothing new, an older request never replaces a newer link
requested_atinstantwhen that request was made
issued_atinstantwhen this secret was made
expires_atinstantwhen it stops working; indexed, expired rows pruned hourly
sent_atinstant, nullwhen its mail was sent (a retry then sends nothing)

A copy of these tables gives nobody a working credential: only hashes are stored. Restoring a backup still requires ending every sign-in (backup and restore).

Reading them ​

For reports or support, read-only SQL is fine. For example, everyone holding a permission in the admin guard:

sql
SELECT DISTINCT u.id, u.email
FROM users u
JOIN model_has_roles mr ON mr.model_type = 'user' AND mr.model_id = CAST(u.id AS CHAR(20))
JOIN roles r ON r.id = mr.role_id AND r.guard_name = 'admin'
LEFT JOIN role_has_permissions rp ON rp.role_id = r.id
LEFT JOIN permissions p ON p.id = rp.permission_id AND p.orphaned = FALSE
WHERE p.name = 'posts.update' OR r.name = 'super_admin';

(Direct grants: the same through model_has_permissions. On PostgreSQL, use CAST(u.id AS TEXT).) Writes go through RbacService or the System pages.

Other framework tables ​

TableForPage
seaql_migrationsapplied migrations (SeaORM's own table)Database & migrations
rustcms_locksnamed transaction locks on MySQL (below)Database & migrations
idempotency_keysstored results of writes sent with Idempotency-Key, kept 24 hoursAdmin API, Retention
media, media_uploads, media_deletionsthe media library; uploads being stored; files to delete from storage, with retriesMedia, Retention
audit_logswho changed whatAudit log
settingssettings groupsSettings
jobs, job_receiptsthe database queue; receipts of effects applied onceQueues
job_runsone row per finished job, kept queue.history_retention_daysQueues
schedule_states, schedule_slotsone state row per schedule (never pruned); each claimed slot, kept 7 daysScheduling
schedule_runsone row per schedule run, kept schedule.history_retention_daysScheduling
exports, export_objectsbackground CSV exports and every file a run may have writtenImport and export
imports, import_rowsCSV imports, their mapping and report; what each row didImport and export

Ids made by the framework are UUID v7 (time-ordered) unless noted. Messages stored as errors (last_error, error) are safe texts, never the raw error.

rustcms_locks ​

ColumnTypeNotes
namevarchar(64)primary key

The migration inserts every row up front: rbac, and lineage:0 … lineage:1023 and idem:0 … idem:1023 (names are hashed into 1,024 slots). On MySQL, rustcms::db::xact_lock(txn, name) locks the row with FOR UPDATE until the transaction ends; a name without a row is an error, so on MySQL only these names work. PostgreSQL takes an advisory lock on a hash of the name and SQLite already holds its write lock: the table exists there only so every database has the same schema.

idempotency_keys ​

ColumnTypeNotes
idvarchar(64)primary key: SHA-256 of the user (guard and id), the resource, the operation and the key
ownervarchar(255)<guard>:<user id> (indexed): at most 1,000 live keys per owner
request_hashvarchar(64)hash of the canonical request: a different request with the same key is refused
resulttext, nullthe stored outcome, replayed to a retry; committed with the write
created_at, expires_atinstantexpires_at indexed; idempotency:prune deletes expired rows

Media ​

TableColumns
mediaid uuid, disk varchar(16), key varchar(128), name varchar(255), mime varchar(64), size bigint, sha256 varchar(64), width, height (int, null), alt varchar(500) null, collection varchar(64) null (indexed with created_at), owner_id bigint (indexed, no foreign key), created_at, deleted_at (null; set: in the trash)
media_uploadsid uuid, disk, key, created_at: an intent committed before the object is written and removed with the media row, so a crash in between leaves a record of what to clean up
media_deletionsid uuid, disk, key, attempts int, next_at instant (indexed): objects to delete, retried until done

audit_logs ​

ColumnTypeNotes
iduuid
atinstant
eventvarchar(64)created, updated, …
subject_type, subject_keyvarchar(64), varchar(255) nullwhat changed
actor_kindvarchar(16)user, system, guest or job
actor_user_idbigint, nullno foreign key: entries outlive deleted users
actor_guardvarchar(32), null
credentialvarchar(96), nullsession, token:<id>, jwt:<family> or console:<command>: never a secret
ip, user_agent, request_idvarchar(45), varchar(255), varchar(64), null
changes, metajson, nullencrypted fields are always redacted

Indexed on (subject_type, subject_key, at), (actor_user_id, at) and (at, id).

settings ​

ColumnTypeNotes
namevarchar(32)primary key: the group
valuejsonthe group's values, without its secrets
secretsjson, nullsecret fields, encrypted under a key derived from APP_KEY
versionbigintadvanced by every save; a PUT sends the version it read, and a stale one is refused
updated_atinstant
updated_bybigint, nullthe user who saved

jobs ​

ColumnTypeNotes
iduuid
queuevarchar(64)queue name
kindvarchar(64)Job::KIND
versionintJob::VERSION of the payload
payloadjsonthe job, serialized
attemptsintclaims so far (each run counts when it starts)
max_attemptsintmost runs
available_atinstantnot run before this
reserved_byvarchar(64), nullowner token of the run in progress
reserved_untilinstant, nullthe run in progress owns the job until then (indexed)
started_atinstant, nullwhen the current or last attempt started
descriptionvarchar(200), nullJob::describe, shown in the panel
last_errorvarchar(500), nullwhy the last run failed
initiated_bybigint, nullthe user who asked for it, if any
created_atinstantwhen it was dispatched (indexed with id)
failed_atinstant, nullset when it will not run again

A job's row is deleted when it finishes; a failed job stays (with failed_at) until it is retried or forgotten, or until the workers delete it after queue.failed_retention_days (30 by default). Indexed on (queue, failed_at, available_at) for claiming.

job_receipts: key varchar(191) primary key, created_at (indexed). A job records a receipt in the transaction of its effect (rustcms::queue::once), so the effect applies once even when the job runs again, as long as the receipt is kept: receipts are deleted after queue.failed_retention_days (30 by default).

job_runs ​

ColumnTypeNotes
iduuidthis row
job_iduuidthe job (a retried job finishes more than once)
queue, kindvarchar(64)
descriptionvarchar(200), null
statusvarchar(16)done, failed or cancelled
attemptsintclaims used
created_atinstantwhen the job was dispatched
started_atinstant, nullwhen its last attempt started
finished_atinstant
duration_msbigint, nullhow long its last attempt ran
last_errorvarchar(500), null
initiated_bybigint, null

Indexed on (finished_at, id), (job_id, finished_at) and (kind, finished_at, id).

schedule_states, schedule_slots ​

TableColumns
schedule_statesname varchar(64) primary key, active_job_id uuid null (the job of the last claimed slot, for without_overlapping), last_slot_at instant null, updated_at. Locked by every claim; never pruned
schedule_slotsprimary key (name, slot_at): a slot is claimed once, by one instance. claimed_at (indexed), instance varchar(64) (who claimed it), job_id uuid null. Kept 7 days, pruned hourly while the scheduler runs

schedule_runs ​

ColumnTypeNotes
iduuidalso the task's run_id
namevarchar(64)the schedule
slot_atinstant, nullthe slot it ran for; null for a manual run
triggervarchar(16)schedule or manual
started_at, finished_atinstant, instant null
statusvarchar(16)running, dispatched, succeeded, failed, skipped, cancelled or unknown
job_iduuid, nullthe job that runs it
duration_msbigint, null
summaryvarchar(200), nulla task's summary
errorvarchar(500), null
initiated_bybigint, nullwho ran it, for a manual run

Indexed on (name, started_at, id), (started_at, id) and (job_id).

exports, export_objects ​

Column of exportsTypeNotes
iduuid
user_idbigintwho asked for it (indexed)
auth_versionbiginttheir credential version then: the export stops if it changes
resourcevarchar(64)resource slug
query, columnsjsonthe list query (canonical, no page) and the fields, fixed at creation
keysjson, nullkeys of the records exported, in order: checked again at download
statusvarchar(16)pending, running, done or failed
rowsint, default 0rows written
disk, storage_keyvarchar(16), varchar(128), nullthe file
errorvarchar(255), nulla message safe to show its owner
created_at, expires_atinstantthe row and the file are deleted after expires_at (indexed)

export_objects: storage_key varchar(128) primary key, export_id uuid (indexed), disk, created_at. Every object an export run may have written, so pruning finds the files of a run that crashed.

imports, import_rows ​

Column of importsTypeNotes
iduuid
user_idbigintwho uploaded it (indexed)
auth_versionbiginttheir credential version then: the import stops if it changes
resourcevarchar(64)resource slug
disk, storage_keyvarchar(16), varchar(128)the uploaded file
sha256varchar(64)of the file, hex
headerjsoncolumn names of the file
rowsintrows of the file, header excluded
mappingjson, nullcolumn → field, fixed when it runs
statusvarchar(16)uploaded, running, done or failed
created, updated, failedint, default 0records created and updated, rows that failed
reportjson, nullthe failed rows: [{row, field?, message, code, params?}] (no field: the whole row), never the values
errorvarchar(255), nullwhy it stopped, safe to show its owner
created_atinstantwhen it was uploaded
started_atinstant, nullwhen it started running
expires_atinstantthe row and the file are deleted after it (indexed)

import_rows: primary key (import_id → imports cascade, row int), outcome varchar(16), record_key varchar(255). One receipt per row written, committed with the row, so a resumed import never writes a row twice.

Your tables ​

Your migrations add tables next to these, in the same database. Keep your data in your own tables and reference users.id (bigint) when you need a user: framework migrations may change their tables in later releases, and the access-control and credential tables are written only through the framework (RbacService, the auth routes). Secrets in your tables use rustcms::crypto::Encrypted<T> in a Text column (Encrypted columns).

RustCMS 0.17.0 · source cfb82fa33fab · MIT OR Apache-2.0