Append comments to SQL queries

Is there a way to prepend comments to SQL queries generated by Ecto?

I’d like to instrument my queries with Sqlcommenter in order to have more insights when I debug them.

For example:

SELECT * from USERS /*action='foo',
controller='bar'*/

I can’t find anything in the documentation, but I wonder if a workaround exists for that?

See:

3 Likes

Ability to “tag” queries using comments in Ecto would be quite convenient indeed :thinking:

First thing to check would be if this is even possible. I am assuming you use PostgreSQL since you linked to CloudSQL for postgres, and Ecto uses “binary” protocol to talk to it:

And this differs from other clients in several ways, for example in the way that timestamps are returned (always UTC). Being a binary protocol, it may not support comments at all. You should probably check if you can add a comment to MyApp.Repo.query!(...) and see if it even gets passed to PostgreSQL before you move any further.

1 Like

It seems to work as expected, see:

> Repo.query!("select exists (select from users) /* my comment */")
%Postgrex.Result{command: :select, columns: ["exists"], rows: [[true]], num_rows: 1, connection_id: 247, messages: []}

And the generated SQL:

select exists (select from users) /* my comment */

For PostgreSQL proper at least, Repo.query (and friends) should work fine.

I pass in some fairly gigantic DO blocks which include PostgreSQL single line comments, multi-line comments, “dollar-sign quoting”, nested dollar-sign quoting, etc. into individual Repo.query calls and I’ve had no issues.

I would expect that anything “within reason” in this regard shouldn’t cause problems.