Skip to content

Schema doctor

The schema doctor reviews your database structure for problems you can spot without ever reading a row: a table with no primary key, a foreign key with no index, duplicate or redundant indexes, a foreign key whose type does not match the key it references, money stored as a float, and more. It is deterministic and structure-only, with no AI and no network call, so it is safe to run in CI.

There are two front ends for one engine: the php artisan truss:doctor command in the terminal and CI, and the Health panel in the dashboard (the heart icon in the toolbar). The command is called “doctor” and the panel is labelled “Health”, but they are the same feature running the same rules over the same snapshot, so they always report the same findings.

The command

Terminal window
# Review the default connection
php artisan truss:doctor
# A specific connection, as JSON for tooling
php artisan truss:doctor --connection=mysql --format=json
# Be stricter, and fail on warnings too
php artisan truss:doctor --preset=strict --fail-on=warning

truss:doctor (aliased truss:check) prints the findings as a table grouped by table, then exits:

  • 0 when clean (nothing at or above the fail level),
  • 1 when a finding is at or above --fail-on (default error),
  • 2 on a bad option, a connection problem, or a missing snapshot.

So a migration that introduces a problem can fail the build. Point a commit hook or a CI step at it and a new unindexed foreign key stops being something you find in production.

Presets and confidence

Every rule declares a confidence (high or heuristic) that is kept separate from its severity. High-confidence rules are certain from the structure alone (a table genuinely has no primary key). Heuristic rules are name-based guesses (a *_id column that looks like a foreign key but has none, a column called price stored as a float): often right, sometimes a deliberate choice.

  • recommended (the default) runs high-confidence rules only, so the first run is quiet and trustworthy. A heuristic finding still fires at its real severity when you turn it on: confidence and severity are independent.
  • strict runs everything, heuristics included.
  • none runs nothing but the rules you explicitly enable.

Every rule can be enabled, disabled, re-severitied, or ignored per pattern in config, so you tune the signal to your project.

Engine awareness

A rule can adapt to the database driver. The clearest case is a foreign key with no index: on PostgreSQL and SQLite, which do not auto-index foreign keys, it is an error; on MySQL and MariaDB, which do, it is only info. You get the right severity for the database you actually run.

In the dashboard

The dashboard shows the same findings the command does, under the name Health (there is no “doctor” button; the heart icon is it). Open the dashboard (php artisan truss:open) and the heart button in the toolbar opens a Health panel that lists them grouped by table, with the heuristic ones marked as such. Click a table to focus the diagram on it; click the button again to close.

You do not have to open the panel to know something is wrong: every table with a finding carries a small severity badge on the diagram, and the offending column is marked on the table itself. Click a marked column to read the finding for that field. The panel can be maximized when a report gets long.

Two switches under doctor in config/truss.php control the dashboard side:

'doctor' => [
// ...preset, rules, ignore, fail_on, exclude...
'dashboard' => (bool) env('TRUSS_DOCTOR_DASHBOARD', true),
'flag_tables' => (bool) env('TRUSS_DOCTOR_FLAG_TABLES', true),
],
  • dashboard (default true) shows the Health panel at all. When false, the dashboard receives no findings and the panel never appears; the CLI is untouched.
  • flag_tables (default true) badges tables with findings on the diagram even when the panel is closed. Set it false to keep the diagram clean and surface findings only when you open the panel.

The report rides the schema endpoint the diagram already loads, so there is no extra request, and it is gated by the same viewTruss authorization as the rest of the dashboard.

Try it on the live demo: open the Health panel and you will see a handful of foreign keys flagged for a missing index, and users.email flagged (heuristically) for having no unique constraint.

Configuration

Everything lives under doctor in config/truss.php:

'doctor' => [
'preset' => env('TRUSS_DOCTOR_PRESET', 'recommended'), // recommended | strict | none
'rules' => [
// 'TRUSS-INT-002' => true, // turn a heuristic rule on
// 'TRUSS-IDX-001' => ['severity' => 'error'], // change a severity
],
'ignore' => [
// 'TRUSS-IDX-001' => ['audit_log.actor_id'], // silence a known case (fnmatch)
],
'fail_on' => env('TRUSS_DOCTOR_FAIL_ON', 'error'), // error | warning | info | never
'exclude' => [], // extra tables, on top of excluded_tables
'dashboard' => (bool) env('TRUSS_DOCTOR_DASHBOARD', true),
'flag_tables' => (bool) env('TRUSS_DOCTOR_FLAG_TABLES', true),
],

See the configuration reference for the full key list.

Rules

Every finding carries a stable code (e.g. TRUSS-INT-003), shown in both the command output and the Health panel, so you can look it up here, silence it, or change its severity in config. There are seventeen rules across three categories. Heuristic rules are name-based guesses and are off under recommended (on under strict).

CodeChecksSeverityConfidence
TRUSS-INT-001Table has no primary keyerrorhigh
TRUSS-INT-002A *_id column matches a table but declares no foreign key, polymorphic columns excludedwarningheuristic
TRUSS-INT-003A foreign key column’s type differs from the key it referenceserrorhigh
TRUSS-INT-004The same foreign key is declared more than once on a tablewarninghigh
TRUSS-INT-007A pivot table has no unique constraint on its key pairwarninghigh
TRUSS-INT-008A foreign key references columns that are neither the primary key nor a unique key *errorhigh
TRUSS-INT-009A polymorphic pair (*_type, *_id) has no composite indexwarningheuristic
TRUSS-INT-010A foreign key references one table while a table named after its column exists and is a different oneerrorhigh
TRUSS-IDX-001A foreign key column has no supporting indexerror *high
TRUSS-IDX-002Two indexes cover the same columnswarninghigh
TRUSS-IDX-003An index is a left prefix of another, so it is redundantwarninghigh
TRUSS-IDX-004An index duplicates the primary keywarninghigh
TRUSS-IDX-005A deleted_at column is not indexedwarningheuristic
TRUSS-IDX-006An email / slug / uuid / token column has no unique constraintwarningheuristic
TRUSS-TYP-001A money-looking column is stored as float or doubleerrorheuristic
TRUSS-TYP-002An is_* / has_* column is stored as varcharwarningheuristic
TRUSS-TYP-009A uuid or ulid column, or a *_uuid or *_ulid foreign key column, is stored as a varchar wider than the identifier *warningheuristic

* These rules behave differently per database driver:

  • TRUSS-IDX-001 is an error on PostgreSQL and SQLite, which do not auto-index foreign keys, and only info on MySQL and MariaDB, which do.
  • TRUSS-INT-008 runs everywhere but can only fire where the database accepts the key: MySQL up to 8.3 (or 8.4 with restrict_fk_on_non_standard_key off), MariaDB and SQLite. PostgreSQL, and MySQL 8.4 with default settings, refuse to create such a foreign key, so there it finds nothing.
  • TRUSS-TYP-009 checks a column named exactly uuid or ulid, and a *_uuid or *_ulid column that is part of a foreign key, composite keys included. A plain *_uuid column that is not a foreign key is left alone, because it often holds an external identifier that is not a UUID. It flags a varchar longer than 36 characters for a UUID or 26 for a ULID, so varchar(191) from Schema::defaultStringLength(191) counts too. varchar(36), varchar(26) and any char(n) are not flagged. For a UUID it suggests the native uuid type on PostgreSQL and on MariaDB 10.7 and later (or char(36) on MariaDB), and char(36) on MySQL. For a ULID it suggests char(26) on every driver. It is skipped on SQLite, which reads every string column back without a length.

What TRUSS-INT-007 counts as a pivot

Two single-column foreign keys are necessary but not sufficient, or every entity table with two relationships would be flagged. A profile table with a user_id and a plan_id is not a many-to-many join, and the composite unique key the rule suggests would be wrong there.

So Truss also asks whether the table carries its key pair and little else. It counts the columns that are not the pair, not id, and not created_at / updated_at / deleted_at. A table whose primary key is the pair, or which has no primary key at all, may carry one such column. A table with its own id primary key must carry none, because a table with its own identity is treated as an entity unless it has nothing else in it. Any other primary key is never a pivot.

The rule also stays quiet when a unique index already covers any part of the pair, since a unique user_id makes (user_id, plan_id) unique on its own. Nullable columns do not count, because most engines allow repeated NULLs in a unique index.

A genuine pivot carrying two payload columns is missed on purpose. A finding you never see costs you nothing, and a wrong one here recommends a migration that loses rows.

Why TRUSS-INT-010 ignores most name mismatches

An author_id column referencing users is not a mistake, it is an alias, and aliases are ordinary. So the rule does not ask whether the column name and the referenced table differ. It asks whether the name names a table that actually exists, and the key points somewhere else.

author_id survives because there is no authors table for its name to name. cart_line_id is flagged because cart_lines does exist and the key references carts instead, which means the constraint validates against the wrong parent: an insert only succeeds when the id happens to exist in both tables, and ON DELETE CASCADE fires when the wrong row is deleted.

That distinction is the whole rule. On Lunar 1.5.0, six of the seven name mismatches among 83 foreign keys were deliberate aliases, so a rule that flagged every mismatch would have been wrong 86% of the time.

Three further cases produce silence rather than a guess:

  • Ambiguity. A candidate name resolves plural first, then singular, and only when exactly one table matches. More than one match reports nothing.
  • Morph targets. A *_id with a sibling *_type column points at whichever table the type names, so its own name is not a claim about one table. TRUSS-INT-009 owns that shape.
  • Composite keys. A multi-column key is not named after one table, so there is no name to test.

A prefixed schema is matched through the prefix the referenced table already carries, so lunar_cart_lines is found for a key that references lunar_carts, and a table belonging to a different prefix is never treated as the match.

What TRUSS-INT-004 treats as the same foreign key

Two constraints are duplicates when they reference the same table with the same column pairs. Composite keys are compared as a set of pairs, so the same constraint written with its columns in another order still counts. Where constraints have names (MySQL, MariaDB and PostgreSQL), the first one declared is kept and each extra copy is reported under its own constraint name, so you know which one to drop. SQLite gives foreign keys no name, so there the copies cannot be told apart and the duplicated key is reported once, under its columns. A duplicate is usually two migrations that each add the same key, or a copy-paste. It is checked twice on every write and makes schema diffs harder to read.

Why TRUSS-INT-008 is an error

A foreign key should reference exactly a primary key or a unique key. What goes wrong when it does not depends on the database and on the columns:

  • On MySQL and MariaDB, with referenced columns that are not unique, one child row can match several parent rows. The relationship is not the one-to-many it looks like.
  • On SQLite, the database accepts the key, then fails every write to the child table with “foreign key mismatch” while foreign keys are enforced, which is the Laravel default.
  • When the referenced columns contain a unique key but are wider than it, such as a key on (code, tenant_id) where code alone is unique, each child row still matches one parent. The key is still wrong: PostgreSQL and MySQL 8.4 refuse it, and SQLite fails writes to the child table. The hint suggests a reference to the unique key alone, or a unique index on exactly those columns.

The columns are compared as a set, so a unique index on (b, a) covers a key on (a, b). A unique expression index such as lower(email) does not make the plain email column unique. A single-column key is reported on its column. A composite key is reported under its constraint name, or under its columns on SQLite, which gives foreign keys no name. The rule is skipped when the referenced table is excluded or lives in another database, since Truss cannot see its keys.

Use these codes in doctor.rules (to enable, disable, or re-severity a rule) and doctor.ignore (to silence a known case per table or table.column). More rules land in later phases.

Caveats

  • Structure only. The doctor reads the same cached snapshot the diagram uses and never queries row data. It cannot know selectivity or query patterns, so it reviews structure, not performance.
  • Heuristics are guesses. They are off by default for a reason. Turn them on when you want them, and ignore the deliberate exceptions per pattern.
  • Deterministic, for a given version. No AI, no network. The same schema and the same version of Truss always yield the same findings, so a diff in CI output is a real structural change. Across an upgrade it may not be: a rule that gets narrower reports less on a schema nobody touched. See Upgrading below.

Upgrading, and a changed rule

Rules are calibrated against real schemas, so a release can change what the doctor reports on a database nobody touched. The first run after an upgrade is the one to read carefully: a smaller report is usually Truss having got quieter, not your schema having improved.

v1.16 added three rules. TRUSS-INT-004 and TRUSS-INT-008 are high confidence, so they run under the default recommended preset. TRUSS-INT-008 is an error, so a CI job on --fail-on=error can go red on a schema nobody has touched, on MySQL up to 8.3, MariaDB or SQLite. TRUSS-INT-004 is a warning, so it fails a job only on --fail-on=warning or info. TRUSS-TYP-009 is heuristic and runs only under strict.

v1.15.4 made index rules compare the full key. An index that mixes a column and an expression, such as (tenant_id, lower(email)), used to look like a plain index on tenant_id. Seven index and integrity rules could then report a duplicate that did not exist. They could also treat a pair as covered when it was not. These rules are the duplicate, redundant-prefix, primary-key, unindexed foreign key, soft-delete, polymorphic and pivot rules. They now read every part of the key. On an unchanged schema, a report can lose a false finding or gain a finding that the old key hid.

v1.11 added TRUSS-INT-010. It is high confidence and an error, so it runs under the default recommended preset, and a new rule can only add findings. A CI job on --fail-on=error can therefore go red on a schema nobody has touched. Read the finding before silencing it: the rule fires only where a foreign key points at one table while a table named after its column exists and is a different one, which is usually a constrained() call that named the wrong table years ago and has been quietly validating against the wrong parent ever since.

v1.10 narrowed TRUSS-INT-007. Two single-column foreign keys stopped being enough to call a table a pivot. Measured across the twelve real Laravel applications that could run both versions, the rule fired 69 times before and 14 times after, and 56 of those 69 were wrong: profile tables, settings tables and one-to-one joins that are not many-to-many at all. One of them recommended a unique constraint that would have capped a user at a single budget. Those twelve schemas are also the ones the new rule was tuned on, so read the counts as a measure of what changed, not as a forecast of what your own report will do.

What that means for you:

  • A CI job on --fail-on=error may now pass where it failed, on a schema you have not changed. That is the intended outcome, not a regression.
  • Findings you had suppressed in doctor.ignore may no longer fire. A stale ignore entry is harmless, but it is worth pruning so the next real finding is not silently covered by it.
  • Some genuine pivots are now missed on purpose. A pivot carrying two payload columns escapes the rule. A finding you never see costs you nothing; a wrong one recommends a migration that loses rows.

The same release stopped TRUSS-INT-002 asking for a foreign key on polymorphic columns, which contradicted TRUSS-INT-009 inside the same report, so a morph-heavy schema also gets a shorter report than it did.

Findings and counts are only comparable between runs of the same version. If you track them over time, record the Truss version alongside the number.