documentSQL Formatter

README.md

SQL Formatter

License: MIT Docs PHP Version Ask DeepWiki

SQL Formatter formats MySQL, PostgreSQL, and SQLite statements with the Compact, Expanded, Tabular, or River layout. It reads each statement with the lossless parser of sql-parser, which is built from the official grammar of the selected database version, Expanded, Tabular, and River change only layout whitespace and keep keywords, identifiers, literals, and comments as written; Compact writes a canonical single form of the statement, without comments or optional whitespace. Every output is parsed again to confirm that its syntax is unchanged. No schema or database connection is needed.

Requirements

  • PHP 8.1+ with the zlib extension

Support Syntax

The following grammar versions are supported. Pass the version tag to the parser given to the formatter; omitting it uses the default for that database.

MySQL

VersionVersion tagDefault
5.6.51mysql-5.6.51
5.7.44mysql-5.7.44
8.0.44mysql-8.0.44
8.1.0mysql-8.1.0
8.2.0mysql-8.2.0
8.3.0mysql-8.3.0
8.4.7mysql-8.4.7Yes
9.0.1mysql-9.0.1
9.1.0mysql-9.1.0

PostgreSQL

VersionVersion tagDefault
17.2pg-17.2Yes

SQLite

VersionVersion tagDefault
3.47.2sqlite-3.47.2Yes

Installation

composer require k-kinzal/sql-formatter

Usage

use SqlFormatter\Core\FormatOptions;
use SqlFormatter\Core\Style;
use SqlFormatter\Facade\Formatter;
use SqlParser\MySql\MySqlParser;

$formatter = new Formatter(
    new MySqlParser('mysql-8.4.7'),
    new FormatOptions(style: Style::Expanded, indentWidth: 4),
);

echo $formatter->format('SELECT id,name FROM users WHERE active=1 AND age>=18 ORDER BY name;');
SELECT
    id,
    name
FROM
    users
WHERE
    active = 1
    AND age >= 18
ORDER BY
    name;

License

MIT License. See LICENSE for details.