DEPRECATED: It's no longer possible to gain superuser access so this won't work on Supabase databases.
How to set up a read-only replica using PostgreSQL Logical Replication with Supabase
- Run
ALTER ROLE postgres SUPERUSERin the old project's SQL editor - Run
pg_dump --clean --if-exists --schema-only --quote-all-identifiers -h [OLD_DB_HOST] -U postgres > schema_dump.sqlfrom your terminal - Run
ALTER ROLE postgres NOSUPERUSERin the old project's SQL editor - Run
ALTER ROLE postgres SUPERUSERin the new project's SQL editor - Run
psql -h [NEW_DB_HOST] -U postgres -f schema_dump.sqlfrom your terminal - Run
ALTER ROLE postgres NOSUPERUSERin the new project's SQL editor
- You must use the Supabase Dashboard SQL Editor to change the postgres user from
NOSUPERUSERtoSUPERUSERand vice-versa. The dashboard runs with the proper privileges to do this. Connecting to the database with any other tool using thepostgresuser will not work. - To find
[OLD_DB_HOST]and[NEW_DB_HOST], go to your Supabase Settings Page and look under Connection Info / Host. It will have the format ofdb.zzzzzzzzzzzzzzzzzzzz.supabase.cowherezzzzzzzzzzzzzzzzzzzzis your project reference number. - It's important to use the
--schema-onlyoption here, as you only want to dump the schema, and not the data.
CREATE PUBLICATION my_publication FOR ALL TABLES;- If you only want to replicate specific tables, you can use:
CREATE PUBLICATION my_publication FOR TABLE table1, table2, table3; - The schema for each table in in your publication must exist in the replica database before you move on to create the subscription.
supabase_realtimeis a reserved publication name, and cannot be used.
CREATE SUBSCRIPTION my_subscription
CONNECTION 'postgresql://postgres:[PASSWORD]@[OLD_DB_HOST]:5432/postgres'
PUBLICATION my_publication;[PASSWORD]is yourpostgrespassword, i.e. the password you created when you set up your project. (You can also reset your password from the Supabase Dashboard underDashboard/Settings/Database/Reset Database Password)[OLD_DB_HOST]is your primary database host name, used in the steps above- be sure to use port 5432 to connect to your PostgreSQL server, and not 6543, which is the pg_bouncer connection pooling port.
See Debugging PostgreSQL Logical Replication
-
Be careful with schema changes, they don't propagate to the replicas automatically, and will cause the replica to stop syncing.
-
If you use
DROP CASCADEon thepublicschema when attempting to resync schemas, it can cause therealtime.subscriptionto drop.
Thanks to Colin from Zverse for pointing out some of these great debugging techniques that help solve issues related to database migrations.