Doctrine SqlFormatter

repository·1.5.x·Indexed 23 days ago

https://github.com/doctrine/sql-formatter

A lightweight PHP package for formatting SQL statements with indentation, line breaks, and syntax highlighting. It provides a SqlFormatter class with methods to format, highlight, or compress SQL queries, and includes a CLI tool for terminal-based formatting.

Tokens
607
Snippets
4
Records
5
Agent score
34%

What's inside doctrine-sql-formatter

  1. Format SQL statements with SqlFormatter

    1.5.x

    The SqlFormatter class provides a format method that takes an SQL string and returns a formatted block with automatic indentation, line breaks, and syntax highlighting. By default, when running in a CLI environment, it uses CliHighlighter. You can also pass specific Highlighter implementations (like HtmlHighlighter) to the constructor to change the highlighting output.

    <?php
    require_once 'vendor/autoload.php';
    
    use Doctrine\
    SqlFormatter\\SqlFormatter;
    
    $query = "SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1`\n    WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) )\n    GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10";
    
    echo (new SqlFormatter())->format($query);
  2. Format SQL without syntax highlighting

    1.5.x

    If you need only indentation and line breaks without HTML/syntax highlighting (e.g., for error logs or plain text files), instantiate SqlFormatter with a NullHighlighter as the second parameter.

    <?php
    
    use Doctrine\SqlFormatter\NullHighlighter;
    use Doctrine\SqlFormatter\SqlFormatter;
    
    echo (new SqlFormatter(new NullHighlighter()))->format($query);
  3. Compress an SQL query

    1.5.x

    The compress method removes all SQL comments (single-line and multi-line) and collapses whitespace. This is useful for creating compact queries suitable for command-line execution.

    <?php
    echo (new SqlFormatter())->compress($query);