Repository navigation
Description
Problem to Solve
When using custom SQL (e.g. manually created indexes, generated columns, or extensions such as pg_textsearch / BM25), Serverpod fails to start in development mode due to strict schema validation.
Example error:
WARNING: The database does not match the target database:
- Table "location" is not like the target database:
- Missing Index "locations_search_idx".
- Table "product" is not like the target database:
- Missing Column "product_full_text".
- Missing Index "products_search_idx".
Hint: Did you forget to run `serverpod generate`, apply the migrations (--apply-migrations), or run a repair migration (--apply-repair-migration)?
In this case:
• The schema difference is intentional
• The objects were created manually (custom SQL)
• They are not represented in Serverpod’s migration model
• The server refuses to start
Proposal
Proposed improvement
Add a development-only flag such as:
--ignore-schema-mismatch
or configuration option:
development:
allowSchemaDrift: true
Behavior:
• Log warnings
• But do NOT prevent the server from starting
Documentation suggestion (if behavior is intentional)
If strict schema validation in development is the intended design, it would be very helpful to clearly document that custom SQL must won't work in development mode
This would prevent confusion and save time for developers who rely on custom SQL for advanced database features.
Use Case
• Adding full-text search with pg_textsearch / BM25
• Creating generated columns
• Creating expression indexes
• Using custom operator classes
• Using not supported postgres extension
• Creating indexes at runtime (e.g. for language-specific text search stemming in multilingual use cases), avoiding unnecessary index duplication and reducing storage overhead
Alternatives
Alternative
Currently, the only workaround in development is to run the server in staging or production mode, where the server will even if the schema has mismatches.
Additional context
No response
How experienced are you with this library?
Intermediate - Familiar with the basics or have used it in a few projects
Are you interested in working on a PR for this?
- I want to work on this
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog 🗂️
Activity
marcelomendoncasoares commentedon Feb 18, 2026
Hi @mathis6787! Sorry for the delay in responding to your comment on the issue #1730.
Your request to allow declaring custom SQL extensions without breaking the analyzer makes total sense, as there is much more available for Postgres than what is possible to cover in the ORM. However, a global ignore as the one you have proposed is very dangerous as can used to ignore proper inconsistencies between the models and the actual tables - specially considering AI-assisted development. Maybe the way to go is to implement a way for declaring specific ignores, so that it becomes a safe and intentional action.
The reason for having custom SQL forbidden in dev mode is to prevent generating inconsistencies that would break production. But we don't forbid the server to start in production to avoid disrupting the service completely, in case it could at least partially work with the mismatched schema.
Currently, it is possible to ignore errors by opting-out from migrations on a table with
managedMigration: false, but this might be too radical for only custom indexes or generated columns - which could be modified after the SQL for the table is generated.This clarification of the intended behavior is certainly needed, beside the possible implementation of a per-entry ignore system.
Do you mind if I convert this issue in a request for such system?
mathis6787 commentedon Feb 18, 2026
Hi @marcelomendoncasoares 👋
I don’t mind at all if you convert this issue into a request for a scoped ignore system.
You’re absolutely right — a global ignore would be very dangerous. A per-entry / scoped ignore mechanism would be much safer and more intentional.
Regarding managedMigration: false, I experimented with it in different ways, but it still throws validation errors and prevents the server from starting in development mode. Even if managed migration false would work for me as you said this is too radical. In general I still want to use the ORM and its migration system for tables, but I need to add specific PostgreSQL constructs that cannot be represented in the migration model.
A scoped ignore system would strike a good balance between safety and flexibility.
[-]Feature request: Allow disabling strict schema validation for custom SQL in development mode[/-][+]Allow ignoring specific elements created with custom SQL on the database schema validation[/+]Silfalion commentedon Mar 20, 2026
Hey everyone,
Strongly agreed that the scoped approach would be very helpful.
The way we're solving this right now is by injecting SQL on start from an SQL file with all that we want to add then as mentioned running it in staging.
We could have a property in yaml for example that takes in raw SQL and injects it surrounded by comment tags while instructing the analyzer to ignore those. In the same vein it could reference a local SQL file to get intellisense.
hamaney commentedon Aug 8, 2026
We hit this on a production schema and I want to add a concrete data point, since the examples in the thread so far are fairly abstract.
29 tables, Serverpod 4.0.0-beta.1. We are migrating to the ORM one table at a time, and the schema validation is the binding constraint on how far we can get. What blocks us:
UNIQUEand are enforcing real invariants, not performance: one active configuration per project, three scoped key-uniqueness rules, one work item per template, and two seed-idempotency keys onmetadata->>'seed_key'.ltreecolumn with a GiST index over it, driving a hierarchy. 38 uses of@>,<@,nlevel(), andsubpath()across 11 server files.Between them these block 11 of 29 tables outright, and the tables behind them transitively — a foreign key can only be declared as a relation, and a relation needs its target to already be a model, so one blocked table blocks its whole subtree. We got two tables migrated before the chain stopped.
Two things worth confirming from our testing, both matching what others have reported here:
managedMigration: falsedoes not help. It exempts a table from being created by Serverpod, not from being verified —getTargetTableDefinitions()does not filter onmanaged, so an unmanaged table's every live column, index, and foreign key must still be declared. We confirmed it empirically: adding a partial index to an unmanaged table producedMissing Index "..."and exit 1. This matches @mathis6787's report above. It is currently pointed at as the escape hatch in the docs, and for this class of problem it is not one.The comparison rejects extras in one direction only.
verifyDatabaseIntegritycallsliveTable.like(targetTable), which iterates the live table's columns, indexes, and foreign keys and requires each to exist in the model.CHECKconstraints and triggers are invisible to it and pass fine — we have 59 and 28 of those respectively, and they cause no trouble at all. So the mechanism for "things Postgres has that the model cannot express" already exists for two object kinds; the ask is really to extend that tolerance to indexes and columns, explicitly and per-element.On the safety concern about ignores being abused: an element-scoped ignore that has to name the exact index or column would be about as explicit as the
CHECK-constraint situation already is, and considerably safer than the alternative we are left with today, which is not adopting the ORM for those tables at all.Happy to test a prototype against this schema if that is useful.
marcelomendoncasoares commentedon Sep 18, 2026
Hi @hamaney! This is an inconsistency that should be fixed: tables excluded from migrations should at most have its fields validated (so we ensure they match the model schema), but skip all other integrity verifications. I filled #5730 to track this bug.
stohal commentedon Sep 19, 2026
Adding a concrete case in support of this, from a multi-tenant application on 4.0.0.
We deliberately enforce integrity in PostgreSQL (constraints, triggers, row-level security, grants) rather than in application code alone, so the live schema contains objects the model language cannot express. Two categories account for all of ours:
1. Multi-column ("composite") foreign keys, used for tenant scoping.
A single-column
parentId -> parent.idreference only proves the parent row exists. The composite form additionally proves it belongs to the same tenant, which makes a cross-tenant reference impossible in the database rather than merely unlikely. Modelling side is #5566.2. Partial unique indexes — "at most one row of a given kind per parent", i.e.
CREATE UNIQUE INDEX ... WHERE <predicate>. Index predicates are #716.Both are created by custom SQL injected into the generated migrations, so fresh and upgraded databases converge on the same schema. Runtime behaviour is correct. Validation is not: every boot logs 57 complaints across 29 tables (39 foreign keys, 18 indexes), and all 57 are false positives — each named object exists in the database and is intentional.
Three reasons this is worse than cosmetic noise:
create-repair-migrationbecomes hazardous. It reconciles the live database toward the target definition, so on a schema like ours it would schedule removal of precisely the constraints that enforce tenant isolation. In 4.0 that is also reachable as an MCP tool, i.e. something an agent can invoke directly.What would help, in order of preference:
The property that matters is that it stays narrow: silencing known external objects, not silencing validation.
Happy to test, or to put up a PR, if a maintainer indicates which shape would be acceptable.
mathis6787 commentedon Sep 26, 2026
Hi @marcelomendoncasoares 👋
I've been thinking about a possible approaches for this issue, and I'd be interested in working on a PR for it. Before starting an implementation, though, I'd really like to get your thoughts on the overall direction and whether something along these lines would fit with how you see Serverpod's schema and migration system evolving.
From a developer-experience perspective, I think it would be very useful to open a Serverpod model and immediately see the PostgreSQL-specific pieces that belong to it, instead of having to search through migration files.
I see two possible approaches for this.
Option 1: Simple custom SQL
For small pieces of SQL, a lightweight syntax could be enough:
This would provide a very simple escape hatch for PostgreSQL functionality that Serverpod's model language cannot represent.
Option 2: A more structured / typed form
Another approach would be to make the custom database object explicit:
For larger definitions, the same structured approach could reference an external SQL file instead:
The structured approach would not necessarily be limited to indexes. It could also represent other database objects that Serverpod's model language cannot currently express, such as custom columns.
For example, a PostgreSQL-specific column:
The structured approach gives Serverpod additional information about the database object.
For example, for a custom index:
or for a custom column:
This gives Serverpod enough metadata to know what kind of database object is intentional, without requiring it to fully parse and understand arbitrary PostgreSQL SQL.
That distinction could become especially useful for schema validation and repair migrations.
Repair migrations
One problem with simply telling the schema validator to ignore a mismatch is
create-repair-migration.If PostgreSQL contains:
but Serverpod's expected schema does not know that this object is intentional, a repair migration may interpret it as unwanted schema drift and attempt to remove it.
The same problem could apply to a custom column such as:
Ideally, declaring an object through custom SQL would mean something closer to:
This would allow Serverpod to continue strictly validating everything else.
The structured approach seems particularly useful here:
Serverpod would not need to understand what
USING bm25 (...)means.It would only need to know that
item_search_idxis an intentional custom index on this model. Likewise, ifpathis declared underdatabase.custom.columns, Serverpod would know that it is an intentional custom column.These objects should therefore not be reported as unexpected schema drift or removed by a repair migration.
This seems safer than either globally disabling schema validation or maintaining a completely separate list of ignored objects.
What happens when custom SQL changes?
I think this is probably the harder part of the feature.
Suppose the initial definition is:
Later, the developer changes the definition to:
Serverpod probably should not try to infer the required migration automatically.
For this particular example, the migration may appear obvious:
But custom SQL could contain almost anything PostgreSQL supports:
Automatically deriving a safe migration from arbitrary SQL could quickly become a SQL diff engine of its own.
One possible approach
Maybe Serverpod only needs to distinguish between the current custom definition and the custom definition that was present when the previous migration was created.
For example, it could store the definition or a hash of it.
When custom SQL is first introduced, it could be included in the generated migration.
For example, with the structured approach:
If that SQL is later modified, Serverpod could detect that:
but deliberately avoid trying to generate the transition.
Instead, the documented workflow could simply be:
and the developer manually provides the SQL required to migrate from the previous definition to the new one.
The same could apply when custom SQL is removed.
Serverpod could optionally warn:
That would give a fairly clean separation of responsibilities.
Serverpod would handle:
The developer would handle:
This is only one possible approach for handling changes to custom SQL, and I don't think the implementation necessarily has to rely on storing and comparing the previous SQL definition.
There are several possible ways this could be handled.
1. Explicit version / revision in the YAML
A custom object could have an explicit version that the developer increments whenever its SQL definition changes:
Serverpod could remember that the previous schema definition contained:
and detect:
At that point, it could require the developer to create an empty migration:
The advantage is that this would be relatively simple and explicit.
The downside is that the developer could modify the SQL and forget to increment the version.
2. Explicitly associate the custom definition with a migration
Instead of trying to detect that the SQL changed, the developer could explicitly indicate which migration introduced the current definition:
This would effectively mean:
Serverpod would not need to understand the difference between the old and new SQL.
This could be reliable, although it would make the model definition slightly more coupled to migration history and could be a bit heavier from a DX perspective.
3. Do not detect changes automatically
The simplest approach would be to not track custom SQL changes at all.
The documentation could simply state that once custom SQL has been migrated, changing or removing it requires a manual migration:
The developer would then write the transition explicitly:
In this model, Serverpod would only know that:
It would not try to determine whether:
changed to:
This would probably be the simplest implementation.
The obvious downside is that a developer could modify the custom SQL and forget to create the corresponding migration.
4. Compare against the actual PostgreSQL object
Another possibility would be to compare the declared custom object with what currently exists in PostgreSQL.
For example, for indexes Serverpod could query PostgreSQL metadata such as:
PostgreSQL might return:
while the model currently declares:
Serverpod could then detect:
without storing the previous SQL definition.
The main downside is complexity. PostgreSQL may normalize or rewrite definitions, so two SQL strings could be different while still representing equivalent objects.
It would also require object-specific logic for things such as indexes, columns, constraints, functions, triggers, policies, extensions, etc.
5. Store a signature for the custom object
Instead of storing the raw previous SQL, Serverpod could store a signature or definition ID for the object in something like
definition.json.For example:
{ "name": "item_search_idx", "type": "index", "customDefinitionId": "9f28a8..." }If the custom definition changes, the generated ID would change as well:
This is conceptually similar to hashing the SQL, but it would allow Serverpod's internal schema representation to track the custom object through a dedicated identifier rather than treating the raw SQL itself as part of the schema model.
6. Provide the migration SQL directly
A more advanced approach would be to allow the model to describe not only the desired custom object, but also the SQL needed to update an existing one:
This would make the transition explicit and could allow Serverpod to generate the migration without having to understand the SQL itself.
The main concern I see with this approach is that migration history would start leaking into the model definition, while Serverpod already has a dedicated migration system for representing database transitions.
One additional consideration with the structured approach is that it would probably also need to support a global custom SQL file, not only SQL attached to a specific application model.
Some custom SQL may need to target tables that do not belong to the application's own models, for example tables provided by Serverpod modules or other packages. In those cases, there is no local model YAML file where a
database.customdeclaration could naturally live.For example, an application may need to add a PostgreSQL-specific index, constraint, trigger, policy, or other database object to a table created by a Serverpod module.
Without a global custom SQL entry point, the structured per-model approach would make it impossible to declare these objects while still allowing Serverpod to know that they are intentional.
A possibly a dedicated project-level configuration/file for custom database objects.
The per-model form would still be preferable when an object clearly belongs to a specific application model, since it keeps the database definition close to the model. The global form would mainly cover database objects that cannot be associated with a local model, especially tables owned by Serverpod modules or external packages.
These are just some possible directions I thought about, and I'm sure there may be better approaches that fit Serverpod's architecture more naturally.
Since this would touch the schema validation and migration system quite deeply, I'd really appreciate guidance from the Serverpod team on the preferred direction before starting a PR.
stohal commentedon Sep 27, 2026
Following up on my earlier comment, with a view on the two shapes proposed above — from the 57-object case (4.0.2 now, same numbers).
Option 2 over Option 1, for the reason given: validation and repair only need the metadata.
TableDefinitioncarries columns, foreign keys and indexes (serverpod_database,table_definition.dart), so an object declared as "custom indexxon tablet" can be matched against what the live database reports without Serverpod parsing the SQL. That is what I was asking for with "by name or pattern"; a typed declaration is a better home for it than a bare name list.One kind is missing, and it is the larger half of my case. The examples cover
indexesandcolumns. Of my 57 false positives, 18 are indexes and 39 are foreign keys — multi-column, tenant-scoping ones of the shapeFOREIGN KEY ("tenantId", "parentId") REFERENCES "parent" ("tenantId", "id"). Aconstraintskind (foreign keys, and probablyCHECKconstraints, which the definition does not model at all today) is what makes the structured form cover the multi-tenant pattern. Without it, a structured declaration would clear 18 warnings and leave 39.The kinds the verifier cannot see today matter less for validation, but should not be excluded. Triggers, functions, policies and grants are outside
TableDefinition, so they are neither reported as drift nor touched by a repair migration; declaring them is documentation until the definition grows. Constraints and indexes are the ones that get reported and, worse, scheduled for removal bycreate-repair-migration— for me that would be the tenant-isolation constraints, which is why "not removed by a repair migration" is the property I care about most in the list above.On changes: the hash plus
create-migration --emptyroute is the one I would take. It matches how custom SQL is handled by hand today (injected into the generated migration when introduced, migrated by hand when it changes), it needs no SQL diff engine, and the warning text proposed reads clearly. A version field (option 1) has the failure mode that someone edits the SQL and forgets the bump, and then nothing warns; a hash cannot be forgotten.Verification level: the definition shape is read from the 4.0.2 source; the counts are observed at server boot on a real schema; nothing else here was executed. Happy to run a branch against that schema — 29 tables, 57 custom objects of the two kinds above — once there is one.
mathis6787 commentedon Oct 5, 2026
For those who rely heavily on custom SQL with Serverpod, I recently published two packages that might be useful:
postgresql_parser: https://pub.dev/packages/postgresql_parser
serverpod_sql_check: https://pub.dev/packages/serverpod_sql_check
The packages are still in alpha phase