Proposal: Emit SQL notification with Arel query builder

We have a use case in which we would like to have access to the relation of emitted queries for further inspection. Similar to sql.active_record but with access to the query builder (Arel). Even Arel being a private API would this be desirable ?

One work around that we looked at was to patch the to_sql_binds method in DatabaseStatements and emit a custom notification from there passing the arel object, however this seems a fragile approach.

Can you describe the use case?

I’d like to have the ability to inspect queries to verify if certain attributes are being used. This will help us validate that a given attribute is not being used and serve as input to safely remove it.

(I’m on the same team as Elson)

Receiving the raw SQL alone, without the query builder object, means that one has to parse the SQL to understand what it might be doing.

Instead of using the Arel object, we considered pattern matching on the raw SQL, but we run into the blind spot that Active Record often introduces aliases, making it unreliable.

We could go the route of using an actual SQL parser, but:

  • There doesn’t seem to be many SQL parsers in ruby that are well maintained
  • All the gems that I could find require a java or C binding, making it heavier than I would prefer.
  • It feels wasteful when we already have a perfectly good query builder will all the right information already.
1 Like

Thank you for the examples. Having a builder is probably better than a raw sql, but the query can theoretically be built in a different ways and even via raw SQL using something like Arel.sql(some part of sql), so this still can have complications when trying to get something useful from it.

1 Like

That’s true. We’d still not be able to cover the usage of Arel for raw queries, but we have very limited cases of that in our app, so this wouldn’t be a problem.