While .Net has fully native Postgres support using the Npgsql library, it requires using the approach of telling the connection that you require a read-write intent in code and not the connection string, so you end up with a normal connection string with a list of servers:-
Host=server1.example.org,server2.example.org;Username=myusername;Password=mypassword;Database=mydatabase
This connection string will use both server1 and server2 to handle all requests if used by default, however if you use the NpgsqlDataSourceBuilder and call CreateConnection, you can specify TargetSessionAttributes.ReadWrite as a parameter to guarantee you get a writeable master server:-
var dsBuilder = new NpgsqlDataSourceBuilder(Configuration.GetValue<string>("Database:ConnectionString"));
var ds = dsBuilder.BuildMultiHost().CreateConnection(TargetSessionAttributes.ReadWrite);
This will enable you to have read, and read-write intent on your applications connection to the database.
But what happens if you're not using .Net and want to interact with the writeable server first?
It turns out there's a target_session_attrs parameter:-
postgresql://server1.example.org,server2.example.org/mydatabase?target_session_attrs=any
postgresql://server1.example.org,server2.example.org/mydatabase?target_session_attrs=read-write
And this is an option on the ODBC driver too:-
Driver={PostgreSQL};Server=server1.example.org,server2.example.org;Port=5432;Database=mydatabase;Uid=myusername;Pwd=mypassword;target_session_attrs=read-write;
There are other parameters you can use here too:-
any
|
Connect to any server, this is the default |
read-write
|
Connect to any server that is writeable |
read-only
|
Connect to any server that is in read-only mode, you can either have a server set to standby or set to read-only explicitly |
primary
|
Connect to the primary server |
standby
|
Connect to any standby servers |
prefer-standby
|
Try to connect to a standby server first, and then use the primary if no connection could be made. I have read it falls back to any so if you have no replication it will still find a system. |