We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
When you want to pretty-print SQL statements using Elixir, the sql_fmt library is what you should be looking at.
Install it by adding this to your dependencies:
{:sql_fmt, "~> 0.3.0"}
To use it, you can do something like this:
iex(1)> {:ok, formatted_sql} = SqlFmt.format_query("select * from businesses where id in ('c6f5c5f1-a1fc-4c9a-91f7-6aa40f1e233d', 'f339d4ce-96b6-4440-a541-28a0fb611139');")
{:ok, "SELECT\n *\nFROM\n businesses\nWHERE\n id IN (\n 'c6f5c5f1-a1fc-4c9a-91f7-6aa40f1e233d',\n 'f339d4ce-96b6-4440-a541-28a0fb611139'\n );"}
iex(2)> IO.puts(formatted_sql)
SELECT
*
FROM
businesses
WHERE
id IN (
'c6f5c5f1-a1fc-4c9a-91f7-6aa40f1e233d',
'f339d4ce-96b6-4440-a541-28a0fb611139'
);
:ok
SqlFmt also provides you with the ~SQL
sigil that can be used to format SQL via Mix Formatter plugin. To set up the Mix Formatter plugin, simply install this package and add update your .formatter.exs
file as follows:
[
plugins: [SqlFmt.MixFormatter],
inputs: ["**/*.sql"],
# ...
]
With this configuration, the SqlFmt Mix Format plugin will now format all ~SQL
sigils and all files ending in .sql. This can be particularly useful in Ecto migrations where you have large execute
statements and you want to make sure that your code is readable. Check out the SqlFmt.MixFormatter
module docs for more information.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.