Skip to content

Create Arel subscription #119

@mvgijssel

Description

@mvgijssel

Using Arel middleware and the enhanced AST, it's possible to create a mechanism which "listens" to changes being sent to the database before they are executed.

All UPDATE, INSERT and DELETE statements can be parsed to figure out which tables will be affected which in turn can be used to trigger callbacks interested in certain changes.

In code it could look something like this:

subscription = Arel::Subscription.new

# The query "SELECT * FROM posts" listens to the posts table, as
# changes to the posts table will result in a different outcome for the SQL.
subscription.add("SELECT * FROM posts") do |result|
  puts "The posts table updated"

  # The result variable contains the data from "SELECT * FROM posts"
  # after the change to the table has been made.
  puts result
end

Arel.middleware.apply([subscription]) do
  # This statement will trigger the subscription in the middleware
  # because it will generate an INSERT statement for the posts table.
  Post.create! text: 'some content', title: 'Some catchy title'
end

A setup like this probably means that the Arel middleware needs to have access to the result of the SQL statement it sends to the database, which means refactoring the way middleware currently works.


UPDATE, INSERT and DELETE in postgres have support for a RETURNING clause, which can be used to return the affected rows. It might also be possible to include the subscription SQL in that clause to make it a single SQL statement.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions