#4286·flyway

afterConnect SQL callback: session state changes (e.g. SET ROLE) do not persist to migration execution in Flyway 13.5.0

Author: imhiteshgargCreated Sep 23, 2026Updated Sep 23, 2026
Labelss: needs investigation

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

  1. Connect to PostgreSQL as a login role (deployer) that is a member of app_owner
  2. Remove flyway.initSql=SET ROLE app_owner; from flyway.conf
  3. Create afterConnect.sql in the migrations directory: SET ROLE app_owner;
  4. 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