SqlFmt - Format and pretty print SQL queries

Howdy howdy everyone!

After running into some issues formatting SQL for my EctoDbg library, I decided to go a new route and leverage the Rust SQL formatting library sqlformat in order to pretty print queries. That functionality was pulled out of EctoDbg and put into its own library as it has wider application than just my debugging library…so announcing SqlFmt!

SqlFmt is a precompiled Ruslter NIF that wraps the sqlformat Rust library so you can format SQL queries. It also provides a Mix Formatter plugin so you can format SQL files in your project. You can even format SQL statements in your code if you use the included ~SQL sigil. The Mix Formatter plugin takes care of both files and sigils for you and provides some customization options as well if you don’t like the defaults.

Simple example

I’m particularly excited to use this in my Ecto migrations because you can take queries like this:

    execute ~SQL"""
    insert into
      Test (Test_Date, Testno, Examno, Serialno, TYPE, Hours)
    select
      S.Test_Date,         E.Testno,    S.Examno,    S.Serialno,    'Non-Flight',
      (F.STARTED - F.ENDED) AS Hours
    FROM      Semester S,      TIME F,      TESTPAPERS e
    WHERE
      S.Testno = F.Testno
      AND E.Testno = 1
    """

and turn them into this by running mix format:

    execute ~SQL"""
    INSERT INTO
      Test (Test_Date, Testno, Examno, Serialno, TYPE, Hours)
    SELECT
      S.Test_Date,
      E.Testno,
      S.Examno,
      S.Serialno,
      'Non-Flight',
      (F.STARTED - F.ENDED) AS Hours
    FROM
      Semester S,
      TIME F,
      TESTPAPERS e
    WHERE
      S.Testno = F.Testno
      AND E.Testno = 1
    """

Enjoy!

Hex: sql_fmt | Hex
Github:

25 Likes