Skip to content

Commit f542675

Browse files
committed
Document pgdog.role connection parameter
1 parent 04ce381 commit f542675

1 file changed

Lines changed: 52 additions & 3 deletions

File tree

docs/features/load-balancer/index.md

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,18 +145,67 @@ COMMIT;
145145

146146
Read-only transactions are useful when queries depend on each other's results and need a consistent view of the database. Some Postgres database drivers allow this option to be set in the code, for example:
147147

148-
=== "Golang/pgx"
149-
```golang
148+
=== "pgx (go)"
149+
```go
150150
tx, err := conn.BeginTx(ctx, pgx.TxOptions{
151151
AccessMode: pgx.ReadOnly,
152152
})
153153
```
154-
=== "Node/Sequelize"
154+
=== "Sequelize (node)"
155155
```javascript
156156
const tx = await sequelize.transaction({
157157
readOnly: true,
158158
});
159159
```
160+
=== "SQLAlchemy (python)"
161+
Add `postgresql_readonly=True` to [execution options](https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Engine.execution_options), like so:
162+
```python
163+
engine = create_engine("postgresql://user:pw@pgdog:6432/prod")
164+
.execution_options(postgresql_readonly=True)
165+
```
166+
167+
#### Primary-only connections
168+
169+
If you need to override the load balancer routing decision and send a query (or all queries) to the primary, it's possible to do so by configuring the `pgdog.role` connection parameter.
170+
171+
Configuring this connection parameter can be done at connection creation:
172+
173+
=== "Connection URL"
174+
```bash
175+
postgres://pgdog:pgdog@10.0.0.0:6432/database?options=-c%20pgdog.role%3Dprimary
176+
```
177+
=== "asyncpg (Python)"
178+
```python
179+
conn = await asyncpg.connect(
180+
user="pgdog",
181+
password="pgdog",
182+
database="pgdog",
183+
host="10.0.0.0",
184+
port=6432,
185+
server_settings={
186+
"pgdog.role": "primary",
187+
}
188+
)
189+
```
190+
=== "SQLAlchemy (Python)"
191+
```python
192+
engine = create_async_engine(
193+
"postgresql+asyncpg://pgdog:pgdog@10.0.0.0:6432/pgdog",
194+
pool_size=20,
195+
max_overflow=30,
196+
pool_timeout=30,
197+
pool_recycle=3600,
198+
pool_pre_ping=True,
199+
connect_args={"server_settings": {"pgdog.role": "primary"}},
200+
)
201+
```
202+
203+
The following values are supported:
204+
205+
| Value | Routing decision |
206+
|-|-|
207+
| `primary` | Queries are sent to the primary database only. |
208+
| `replica` | Queries are load balanced between primary and replicas, depending on the value of the [`read_write_split`](../../configuration/pgdog.toml/general.md#read_write_split) setting. |
160209

161210

162211
## Using the load balancer

0 commit comments

Comments
 (0)