pg_static_cache_updater.rb

lib/sequel/extensions/pg_static_cache_updater.rb
Last Update: 2022-09-02 09:11:30 -0700

The pg_static_cache_updater extension is designed to automatically update the caches in the models using the static_cache plugin when changes to the underlying tables are detected.

Before using the extension in production, you have to add triggers to the tables for the classes where you want the caches updated automatically. You would generally do this during a migration:

Sequel.migration do
  up do
    extension :pg_static_cache_updater
    create_static_cache_update_function
    create_static_cache_update_trigger(:table_1)
    create_static_cache_update_trigger(:table_2)
  end
  down do
    extension :pg_static_cache_updater
    drop_trigger(:table_2, default_static_cache_update_name)
    drop_trigger(:table_1, default_static_cache_update_name)
    drop_function(default_static_cache_update_name)
  end
end

After the triggers have been added, in your application process, after setting up your models, you need to listen for changes to the underlying tables:

class Model1 < Sequel::Model(:table_1)
  plugin :static_cache
end
class Model2 < Sequel::Model(:table_2)
  plugin :static_cache
end

DB.extension :pg_static_cache_updater
DB.listen_for_static_cache_updates([Model1, Model2])

When an INSERT/UPDATE/DELETE happens on the underlying table, the trigger will send a notification with the table’s OID. The application(s) listening on that channel will receive the notification, check the oid to see if it matches one for the model tables it is interested in, and tell that model to reload the cache if there is a match.

Note that listen_for_static_cache_updates spawns a new thread which will reserve its own database connection. This thread runs until the application process is shutdown.

Also note that PostgreSQL does not send notifications to channels until after the transaction including the changes is committed. Also, because a separate thread is used to listen for notifications, there may be a slight delay between when the transaction is committed and when the cache is reloaded.

Requirements:

  • PostgreSQL 9.0+

  • Listening Database object must be using the postgres adapter with the pg driver (the model classes do not have to use the same Database).

  • Must be using a thread-safe connection pool (the default).

Related module: Sequel::Postgres::StaticCacheUpdater