afterConnect SQL callback: session state changes (e.g. SET ROLE) do not persist to migration execution in Flyway 13.5.0
Flyway version: 13.5.0 OSS (CLI) Database: Aurora PostgreSQL 18.3 OS: Windows
Summary
The afterConnect SQL callback is documented as firing "Immediately after Flyway connects to the database" and is recommended as the replacement for the deprecated initSql configuration property. However, session state changes made in afterConnect.sql (specifically SET ROLE) do not appear to persist when migrations subsequently execute, despite both supposedly running on the same connection.
Background
We connect to the database as a low-privilege login role (deployer) that is a member of an owner role (app_owner). All schema objects must be owned by app_owner. We use SET ROLE app_owner to switch roles before migrations run.
Previously we used flyway.initSql=SET ROLE app_owner; in flyway.conf. This worked correctly but we got a deprecation warning recommending afterConnect as the replacement.
Steps to reproduce
- Connect to PostgreSQL as a login role (
deployer) that is a member ofapp_owner - Remove
flyway.initSql=SET ROLE app_owner;fromflyway.conf - Create
afterConnect.sqlin the migrations directory:SET ROLE app_owner; - Run
flyway migrate
Expected behaviour
SET ROLE app_owner runs on the database connection immediately after connecting. All subsequent migrations run on the same connection and therefore execute as app_owner.
Actual behaviour
Flyway confirms the callback ran: Executing SQL callback: afterConnect -
But the first migration fails because current_role is still deployer: ERROR: current_role is deployer, not app_owner
The SET ROLE in afterConnect.sql had no effect on the migration execution.
Workaround
Using beforeEachMigrate.sql instead of afterConnect.sql works correctly.i.e. SET ROLE app_owner persists for each migration when placed in beforeEachMigrate.sql. However this runs SET ROLE once per migration rather than once per session, which is inefficient compared to the intended afterConnect behaviour.
The deprecated flyway.initSql=SET ROLE app_owner; also continues to work correctly.
Question
Is afterConnect intentionally executed on a different connection than the migration connection? If so, the documentation should clarify this and the deprecation warning for initSql should not recommend afterConnect as a direct replacement for session-level state changes like SET ROLE.
If this is a bug, afterConnect should run on the same connection as the migrations so that session state changes persist.
References
- Flyway V13 blog recommending afterConnect as initSql replacement
- afterConnect callback documentation — "Immediately after Flyway connects to the database"
Source: flyway/flyway