Skip to content

feat: Add support for custom sql - #4319

Closed
mathis6787 wants to merge 29 commits into
serverpod:mainfrom
mathis6787:feat/add-support-for-custom-sql
Closed

mathis6787 wants to merge 29 commits into
serverpod:mainfrom
mathis6787:feat/add-support-for-custom-sql

Conversation

@mathis6787

@mathis6787 mathis6787 commented Nov 27, 2025 •

Copy link
Copy Markdown
Contributor

This PR introduces a complete implementation of custom SQL support in Serverpod migrations, matching the design discussed in the issue. Closes: #1730

It adds four SQL hook files for every migration:
• pre_database_setup.sql
• post_database_setup.sql
• pre_migration.sql
• post_migration.sql

These files allow developers to inject custom SQL at every stage of the migration lifecycle.

Features

✅ 1. Custom SQL Execution Pipeline
Custom SQL is now executed in strict order during:

Fresh database creation

1.	pre_database_setup.sql
2.	definition.sql
3.	post_database_setup.sql

Migration

1.	pre_migration.sql
2.	migration.sql
3.	post_migration.sql

All custom SQL is executed in a single transaction, after being combined safely.

⸻

2. CLI Support — Files Are Auto-Generated and Accumulated

The CLI now:
• Automatically creates all four files for each migration
• Copies previous custom SQL forward when creating a new migration
• Accumulates migration SQL into the next setup SQL so fresh DB creation is consistent

This ensures feature-parity between:
• rolling forward migrations
• creating a fresh database

⸻

3. Warning Categorization for Schema Integrity

Database integrity verification now distinguishes:
• Informational warnings (e.g., custom indexes, triggers)
• Critical mismatches that must block server startup

Custom SQL can no longer wrongly trigger catastrophic schema mismatch failures.

⸻

4. Full Backward Compatibility

If the four custom SQL files are empty:
• Nothing changes
• The system behaves exactly as before
• No SQL is executed
• No informational warnings appear

No breaking changes for existing users.

⸻

Why this is needed

Serverpod currently lacks a clean way to support custom index:
• Custom indexes (BM25 (paradeDB, POSTGIST,Partial index…)

At the moment, adding these manually results in “the table is not like the protocol definition” warnings, and in debug mode Serverpod quits the process entirely, blocking development and causing migration problems.

⸻

##🧱 Implementation follows the design proposed by SandPod in #1730

About Modules (I need guidance)

I implemented safe behavior for modules during migration execution (their pre/post_migration.sql runs normally).

However, I am still not 100% certain how to tackle the module guideline and if it's actually needed.

⸻

Known Design Issue: Fresh Database Consistency

####❗ Problem

post_migration.sql and pre_migration.sql are only executed when rolling forward.

If a developer deletes the database and recreates it from scratch, custom SQL added in migration N (pre/post_migration.sql, is not applied until migration N+1 is created.

Example
1. Developer adds a Postgis index on a table inside post_migration.sql
2. --apply-migrations → Index created ✅
3. The database is dropped and recreated
4. --apply-migrations → the postgis index will be missing ❌
5. Only after creating the next migration does the index appear in post_database_setup.sql

🔍 Possible solutions (need maintainers feedback)
1. Dynamic accumulation at runtime (best DX)
• When creating a fresh DB, read all pre/post_migration.sql and inject them into setup
2. Runtime update of setup files
3. Keep current behavior + documentation
• Expected behavior: developers must create a new migration to propagate custom SQL
4. Add a CLI command
• Regenerates setup files from migration SQL

Any other ideas ?

I can implement any of these depending on feedback.

⸻

📦 Breaking Changes

None.

…tup SQL files when no previous version is provided
@coderabbitai

coderabbitai Bot commented Nov 27, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@mathis6787 mathis6787 changed the title feat/add support for custom sql feat: Add support for custom sql Nov 27, 2025
@FantaMagier

Copy link
Copy Markdown

@mathis6787 Great RP! I need a GIN Index so it could be also used for that

@mathis6787

Copy link
Copy Markdown
Contributor Author

@mathis6787 Great RP! I need a GIN Index so it could be also used for that

Hi @FantaMagier thanks for the comment , you should be able to use GIN index withouth my PR https://docs.serverpod.dev/concepts/database/indexing

@FantaMagier

Copy link
Copy Markdown

@mathis6787 Thanks. Yes but I need Indexes on List at best as JSONB Format for smart array search

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

Hi @mathis6787! 👋

Thanks for this great contribution! We are currently heads down on the release of Serverpod 3.0, but we will soon be able to review your PR.

There are also some concerns that we will have to review carefully with this feature regarding the database analyzer and how to deal with conflicts of objects created in the additional SQL files (like the mentioned custom indexes).

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

Hi @mathis6787! Now that we have released Serverpod 3.0, we are slowly getting back to PRs pending review. Regarding this one, we still have some discussions on the best approach to allow custom SQL commands, but without handling a footgun to users - that could seem to allow arbitrary commands, but would quickly end up in inconsistent database state and prevent server startup. This was an aspect that was still pending an answer on the issue and must be solved before we consider this feature complete.

As we are soon going to work on migration hooks for #3873, I'll propose for us to park this one for now and consider the needs for the parent issue of this PR on that development. Then, we will be able to perform a broader analysis on the best approach to solve both problems and come back here. Would you be ok with this approach?

@mathis6787

Copy link
Copy Markdown
Contributor Author

Hi @marcelomendoncasoares , thanks for the update, I am totally fine with it.

@mathis6787

mathis6787 commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Hey 👋 @marcelomendoncasoares

I noticed that issue #3873 was recently moved back in the roadmap, and I also went through the new migrations RFC (#4604). From what I understand, support for custom SQL hooks is currently out of scope for this iteration, and there are still some ongoing discussions around the broader migration architecture.

Given those changes, I wanted to check in regarding this PR and the original discussion around it.

Do you think this PR is still aligned with the current direction, or has the scope shifted enough that it would make more sense to close it and revisit the topic once the migration work is further along?

Additionally, do you have any rough timeframe in mind (even very approximate) for when custom SQL / migration hooks might be revisited? This would help me decide whether to wait for the framework support or plan a workaround on my side for now, as this is starting to become blocking for some use cases (e.g. custom indexes or extensions like pg_textsearch / ParadeDB).

Totally fine either way.
Thanks!

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

Hey 👋 @marcelomendoncasoares

I noticed that issue #3873 was recently moved back in the roadmap, and I also went through the new migrations RFC (#4604). From what I understand, support for custom SQL hooks is currently out of scope for this iteration, and there are still some ongoing discussions around the broader migration architecture.

Given those changes, I wanted to check in regarding this PR and the original discussion around it.

Hi @mathis6787! Sorry for the delay in getting back to you here. In fact, migration hooks are out of the migrations UX RFC, but our plan was to revisit them for #3873 that could be required for auth user migration. Turns out we'll probably not need to work on that now, given a change in the strategy for the user migration.

Do you think this PR is still aligned with the current direction, or has the scope shifted enough that it would make more sense to close it and revisit the topic once the migration work is further along?

The major issue with the current approach - the same proposed on the issue - is that it might end up putting a footgun in the hand of users. As one comment already states, if the extra files are used to create additional objects, the analyzer might flag the database state as inconsistent and prevent the server start. So we can't expose an official way for users to run custom SQL without being able to allow ignoring the created elements in the migration system.

Great RP! I need a GIN Index so it could be also used for that

This comment above already shows the exact expectation that such files would create. Even worst, if such objects are of custom types unknown to Serverpod, the migration system might not even be able to repair itself, leaving the database in a state that can only be repaired by manually destroying the custom objects.

Additionally, do you have any rough timeframe in mind (even very approximate) for when custom SQL / migration hooks might be revisited?

Unfortunately I can't give a timeline when we plan to work on it, but I can say that it should not be that soon. First we intend to enhance the migrations UX - executing part or most of the RFC - to then revisit other parts of the process. It is possible that these priorities change, but this is the current overview.

This would help me decide whether to wait for the framework support or plan a workaround on my side for now, as this is starting to become blocking for some use cases (e.g. custom indexes or extensions like pg_textsearch / ParadeDB).

If you know well what you're doing, you can always go by with changing the manually generated SQL files. But if what you need is just support for custom indexes or extensions, do open an issue that we can evaluate extending Serverpod to support it!

Given all above, I'll then close this PR to be revisited when we have a better solution for the migration system to support custom objects. Thanks for your contribution and comprehension!

@github-actions github-actions Bot locked and limited conversation to collaborators Feb 5, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Have Serverpod auto-add custom SQL commands on initial migration

3 participants