elkdata / sql-formatter
一个PHP SQL高亮库
Requires
- php: ^7.1 || ^8.0
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-26 12:41:46 UTC
README
一个用于格式化SQL语句的轻量级PHP包。
除了语法高亮外,它还可以自动缩进和添加换行。
历史记录
此包是从https://github.com/jdorn/sql-formatter派生出来的。以下是原始历史记录部分的内容
我发现自己经常需要调试自动生成的SQL语句,并希望有一种简单的方法来输出格式化的HTML,而无需包含庞大的库或将内容复制粘贴到在线格式化器中。
我最初计划从PhpMyAdmin中提取格式化代码,但那是10,000多行代码,使用了全局变量。
我看到其他人也有同样的问题,并以此作为起点使用了Stack Overflow用户losif的回答。http://stackoverflow.com/a/3924147
— @jdorn
用法
SqlFormatter
类有一个format
方法,它接受一个SQL字符串作为输入并返回一个格式化块。
示例用法
<?php require_once 'vendor/autoload.php'; use Doctrine\SqlFormatter\SqlFormatter; $query = "SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10"; echo (new SqlFormatter())->format($query);
输出
当在命令行下运行php并实例化SqlFormatter
而不带参数时,会用CliHighlighter
进行高亮。
SqlFormatter构造函数接受Highlighter
实现。例如HtmlHighlighter
等。
仅格式化
如果您不希望语法高亮,只想添加缩进和换行,请将NullHighlighter
实例作为第二个参数传入。
这对于输出到错误日志或其他非HTML格式非常有用。
<?php use Doctrine\SqlFormatter\NullHighlighter; use Doctrine\SqlFormatter\SqlFormatter; echo (new SqlFormatter(new NullHighlighter()))->format($query);
输出
SELECT
count(*),
`Column1`,
`Testing`,
`Testing Three`
FROM
`Table1`
WHERE
Column1 = 'testing'
AND (
(
`Column2` = `Column3`
OR Column4 >= NOW()
)
)
GROUP BY
Column1
ORDER BY
Column3 DESC
LIMIT
5, 10
仅语法高亮
有一个单独的highlight
方法,它保留所有原始空白并仅添加语法高亮。
这对于已经格式化良好的SQL语句非常有用,只需稍微易于阅读即可。
<?php echo (new SqlFormatter())->highlight($query);
输出
压缩查询
compress
方法删除所有注释并压缩空白。
这对于可以轻松复制粘贴到命令行的查询非常有用。
-- This is a comment SELECT /* This is another comment On more than one line */ Id #This is one final comment as temp, DateCreated as Created FROM MyTable;
echo (new SqlFormatter())->compress($query);
输出
SELECT Id as temp, DateCreated as Created FROM MyTable;