mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Set Statement Timeout For All Postgres Connections as a rails til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_1087 TILs and counting..._
|
||||
_1088 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -711,6 +711,7 @@ _1087 TILs and counting..._
|
||||
- [Set A Timestamp Field To The Current Time](rails/set-a-timestamp-field-to-the-current-time.md)
|
||||
- [Set default_url_options For Entire Application](rails/set-default-url-options-for-entire-application.md)
|
||||
- [Set Schema Search Path](rails/set-schema-search-path.md)
|
||||
- [Set Statement Timeout For All Postgres Connections](rails/set-statement-timeout-for-all-postgres-connections.md)
|
||||
- [Set The Default Development Port](rails/set-the-default-development-port.md)
|
||||
- [Show Pending Migrations](rails/show-pending-migrations.md)
|
||||
- [Show Rails Models With Pry](rails/show-rails-models-with-pry.md)
|
||||
|
||||
39
rails/set-statement-timeout-for-all-postgres-connections.md
Normal file
39
rails/set-statement-timeout-for-all-postgres-connections.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Set Statement Timeout For All Postgres Connections
|
||||
|
||||
The
|
||||
[`statement_timeout`](postgres/set-a-statement-timeout-threshold-for-a-session.md)
|
||||
setting in PostgreSQL allows you to head off long running queries and
|
||||
migrations that could break your deploys and lock up your production tables.
|
||||
|
||||
This value can be set to a sensible default across all the connections your
|
||||
Rails app makes to PostgreSQL. To set it, open up your `config/database.yml`
|
||||
file and add a `variables` element to the default section.
|
||||
|
||||
```yaml
|
||||
default: &default
|
||||
adapter: postgresql
|
||||
encoding: unicode
|
||||
# For details on connection pooling, see Rails configuration guide
|
||||
# https://guides.rubyonrails.org/configuring.html#database-pooling
|
||||
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
|
||||
variables:
|
||||
statement_timeout: 60000
|
||||
```
|
||||
|
||||
That's 60 seconds in milliseconds. You can avoid the mental math by using a
|
||||
string argument with a unit such as `s` for seconds.
|
||||
|
||||
```yaml
|
||||
variables:
|
||||
statement_timeout: '60s'
|
||||
```
|
||||
|
||||
If you then execute a long running query, such as:
|
||||
|
||||
```ruby
|
||||
ActiveRecord::Base.connection.execute('select pg_sleep(62)')
|
||||
```
|
||||
|
||||
It will terminate 2 seconds early because of the statement timeout.
|
||||
|
||||
[source](https://til.hashrocket.com/posts/b44baf657d-railspg-statement-timeout-)
|
||||
Reference in New Issue
Block a user