Skip to content

Allow ignoring specific elements created with custom SQL on the database schema validation #4743

Open

Description

@mathis6787

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

Activity

  1. added
    enhancement
    on Feb 18, 2026
  2. marcelomendoncasoares commented on Feb 18, 2026

    @marcelomendoncasoares
    Collaborator

    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.

    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

    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.

    Documentation suggestion (if behavior is intentional)

    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?

  3. added
    in triage
    area: migrations
    on Feb 18, 2026
  4. mathis6787 commented on Feb 18, 2026

    @mathis6787
    ContributorAuthor

    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.

  5. changed the title [-]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[/+] on Feb 18, 2026
  6. added
    area: database
    and removed
    in triage
    on Feb 18, 2026
  7. moved this from Inbox 📫 to Backlog 🗂️ in Serverpod Frameworkson Feb 18, 2026
  8. Silfalion commented on Mar 20, 2026

    @Silfalion

    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.

  9. hamaney commented on Aug 8, 2026

    @hamaney

    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:

    • 20 partial or expression indexes. Seven of them are UNIQUE and 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 on metadata->>'seed_key'.
    • One ltree column with a GiST index over it, driving a hierarchy. 38 uses of @>, <@, nlevel(), and subpath() across 11 server files.
    • One two-column foreign key (filed separately).

    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: false does not help. It exempts a table from being created by Serverpod, not from being verified — getTargetTableDefinitions() does not filter on managed, 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 produced Missing 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. verifyDatabaseIntegrity calls liveTable.like(targetTable), which iterates the live table's columns, indexes, and foreign keys and requires each to exist in the model. CHECK constraints 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.

  10. marcelomendoncasoares commented on Sep 18, 2026

    @marcelomendoncasoares
    Collaborator

    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.

  11. stohal commented on Sep 19, 2026

    @stohal

    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.

    -- on the parent: the composite target. This part IS declarable in the model.
    UNIQUE ("tenantId", "id")
    
    -- on the child: this part is not.
    FOREIGN KEY ("tenantId", "parentId") REFERENCES "parent" ("tenantId", "id")

    A single-column parentId -> parent.id reference 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:

    • Real drift becomes invisible. A genuine mismatch would arrive as complaint 58 in a wall of 57 expected ones. The validator is effectively switched off for us, which is the opposite of its purpose.
    • create-repair-migration becomes 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.
    • It trains people to ignore the validator, which is a poor reflex to build into a team.

    What would help, in order of preference:

    1. Declare specific objects as externally owned, by name or pattern, so validation skips exactly those and still reports everything else — e.g. a list of constraint and index names.
    2. The same thing, but declared per table.
    3. A global opt-out. Better than nothing, but it discards the signal entirely, which is the problem I am trying to avoid.

    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.

  12. mathis6787 commented on Sep 26, 2026

    @mathis6787
    ContributorAuthor

    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:

    class: Item
    table: item
    
    fields:
      name: String
      sku: String
      description: String?
    
    indexes:
      item_sku_idx:
        fields: sku
        unique: true
    
    customSql:
      - |
          CREATE INDEX item_search_idx
          ON item USING bm25 (
            id,
            name,
            description
          )
          WITH (
            key_field = 'id'
          );

    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:

    class: Item
    table: item
    
    fields:
      name: String
      sku: String
      description: String?
    
    database:
      custom:
        indexes:
          item_search_idx:
            sql: |
              CREATE INDEX item_search_idx
              ON item USING bm25 (
                id,
                name,
                description
              )
              WITH (
                key_field = 'id'
              );

    For larger definitions, the same structured approach could reference an external SQL file instead:

    class: Item
    table: item
    
    fields:
      name: String
      sku: String
      description: String?
    
    database:
      custom:
        indexes:
          item_search_idx:
            sqlFile: sql/item_search_idx.sql

    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:

    database:
      custom:
        columns:
          path:
            sql: |
              ALTER TABLE item
              ADD COLUMN path ltree;

    The structured approach gives Serverpod additional information about the database object.

    For example, for a custom index:

    type: index
    name: item_search_idx
    table: item
    

    or for a custom column:

    type: column
    name: path
    table: item
    

    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:

    CREATE INDEX item_search_idx ...

    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:

    ALTER TABLE item
    ADD COLUMN path ltree;

    Ideally, declaring an object through custom SQL would mean something closer to:

    This database object intentionally belongs to the expected schema, even though Serverpod cannot represent its implementation through the normal model syntax.

    This would allow Serverpod to continue strictly validating everything else.

    The structured approach seems particularly useful here:

    database:
      custom:
        indexes:
          item_search_idx:
            sqlFile: sql/item_search_idx.sql

    Serverpod would not need to understand what USING bm25 (...) means.

    It would only need to know that item_search_idx is an intentional custom index on this model. Likewise, if path is declared under database.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:

    CREATE INDEX item_search_idx
    ON item USING bm25 (
      id,
      name
    );

    Later, the developer changes the definition to:

    CREATE INDEX item_search_idx
    ON item USING bm25 (
      id,
      name,
      description
    );

    Serverpod probably should not try to infer the required migration automatically.

    For this particular example, the migration may appear obvious:

    DROP INDEX item_search_idx;
    
    CREATE INDEX item_search_idx
    ON item USING bm25 (
      id,
      name,
      description
    );

    But custom SQL could contain almost anything PostgreSQL supports:

    • extension-specific indexes
    • partial or expression indexes
    • custom columns or unsupported PostgreSQL column types
    • generated columns
    • functions
    • triggers
    • policies
    • custom constraints
    • multiple SQL statements

    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:

    database:
      custom:
        indexes:
          item_search_idx:
            sqlFile: sql/item_search_idx.sql

    If that SQL is later modified, Serverpod could detect that:

    previous custom SQL != current custom SQL
    

    but deliberately avoid trying to generate the transition.

    Instead, the documented workflow could simply be:

    serverpod create-migration --empty

    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:

    Custom SQL for Item.item_search_idx has changed.
    
    Serverpod cannot automatically determine how arbitrary custom SQL
    should be migrated.
    
    Create an empty migration and provide the migration SQL manually:
    
      serverpod create-migration --empty
    

    That would give a fairly clean separation of responsibilities.

    Serverpod would handle:

    • knowing that a custom database object is intentional
    • including newly introduced custom SQL in migrations
    • keeping it from being reported as schema drift
    • preventing repair migrations from removing declared custom objects
    • detecting when a custom SQL definition has changed

    The developer would handle:

    • the SQL required to migrate an already existing custom object from one definition to another

    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:

    database:
      custom:
        indexes:
          item_search_idx:
            version: 2
            sql: |
              CREATE INDEX item_search_idx
              ON item USING bm25 (
                id,
                name,
                description
              );

    Serverpod could remember that the previous schema definition contained:

    item_search_idx: version 1
    

    and detect:

    version 1 -> version 2
    

    At that point, it could require the developer to create an empty migration:

    serverpod create-migration --empty

    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:

    database:
      custom:
        indexes:
          item_search_idx:
            sqlFile: sql/item_search_idx.sql
            migration: 20260926-update-item-search

    This would effectively mean:

    The current definition of this custom object is already accounted for by this migration.

    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:

    serverpod create-migration --empty

    The developer would then write the transition explicitly:

    DROP INDEX item_search_idx;
    
    CREATE INDEX item_search_idx
    ON item USING bm25 (
      id,
      name,
      description
    );

    In this model, Serverpod would only know that:

    item_search_idx = intentional custom object
    

    It would not try to determine whether:

    (id, name)
    

    changed to:

    (id, name, description)
    

    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:

    SELECT indexdef
    FROM pg_indexes
    WHERE indexname = 'item_search_idx';

    PostgreSQL might return:

    CREATE INDEX item_search_idx
    ON public.item
    USING bm25 (id, name)

    while the model currently declares:

    CREATE INDEX item_search_idx
    ON item
    USING bm25 (id, name, description)

    Serverpod could then detect:

    actual database object != desired custom object
    

    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:

    previous customDefinitionId != current customDefinitionId
    

    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:

    database:
      custom:
        indexes:
          item_search_idx:
            sql: |
              CREATE INDEX item_search_idx
              ON item USING bm25 (
                id,
                name,
                description
              );
    
            migration:
              update: |
                DROP INDEX item_search_idx;
    
                CREATE INDEX item_search_idx
                ON item USING bm25 (
                  id,
                  name,
                  description
                );

    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.custom declaration 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.

  13. stohal commented on Sep 27, 2026

    @stohal

    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. TableDefinition carries columns, foreign keys and indexes (serverpod_database, table_definition.dart), so an object declared as "custom index x on table t" 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 indexes and columns. Of my 57 false positives, 18 are indexes and 39 are foreign keys — multi-column, tenant-scoping ones of the shape FOREIGN KEY ("tenantId", "parentId") REFERENCES "parent" ("tenantId", "id"). A constraints kind (foreign keys, and probably CHECK constraints, 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 by create-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 --empty route 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.

  14. mathis6787 commented on Oct 5, 2026

    @mathis6787
    ContributorAuthor

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: databasearea: migrationsenhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions