PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

在 PHP 中格式化并高亮 SQL 语句

藏色散人
藏色散人 转载
2019-09-07 11:13:09 2999浏览

jdorn/sql-formatter 是一个轻量级的 php 类用于格式化 sql 语句。

它支持自动进行缩进、添加换行,甚至还支持语法高亮。

在命令行内使用

该扩展包包含一个 bin/sql-formatter 可执行文件,可直接用于命令行格式化 SQL。

使用 Composer 全局安装后便可使用该命令了:

composer global require jdorn/sql-formatter
sql-formatter "SELECT SOME QUERY;" // 直接格式化
// 或
echo "SELECT SOME QUERY;" | sql-formatter // 使用管道,更适合较大量的 SQL 语句

作为扩展包使用

SqlFormatter 类包含一个名为 format 的静态方法,它可以接收一个 SQL 语句字符串作为参数,并返回格式化后使用 pre 标签包裹的 HTML 代码。

例如:

<?php
require_once(&#39;SqlFormatter.php&#39;);
$query = "SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1`
    WHERE Column1 = &#39;testing&#39; AND ( (`Column2` = `Column3` OR Column4 >= NOW()) )
    GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10";
echo SqlFormatter::format($query);

输出:

82ab28c3a60a5d18d9171619bd31c2d.png

只格式化不高亮

若是不需要高亮,只需要添加缩进和换行,请将第二个参数设置为 false 即可。

适用于输出错误日志或者其它非 HTML 数据时。

<?php
echo SqlFormatter::format($query, false);

输出:

307f90c5eec48476d888b9d86b8884c.png

只高亮不格式化

有个单独的方法名为 highlight 能够保证原有的格式不被改动,只添加语法高亮。

适用于 SQL 已经被良好格式化,需让它更加易读时。

bd2f5222a86af107ad9540527466a7a.png

压缩查询语句

compress 方法可删除所有的 SQL 注释,并压缩不必要的空格。

适用于输出多条查询语句,并使其易于复制粘贴到命令行时。

-- 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 SqlFormatter::compress($query);

输出:

SELECT Id as temp, DateCreated as Created FROM MyTable;

删除注释

如果你需要保留原有格式,但仍需删除 SQL 注释,你可以使用 removeComments 方法来代替 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 SqlFormatter::removeComments($query);

输出:

    SELECT
    Id 
    as temp, DateCreated as Created FROM MyTable;

将多条 SQL 语句分割为数组

还有一个与格式化无关的特性,能够将多条 SQL 语句分离为数组。

例如:

DROP TABLE IF EXISTS MyTable;
CREATE TABLE MyTable ( id int );
INSERT INTO MyTable (id)
    VALUES
    (1),(2),(3),(4);
SELECT * FROM MyTable;
$queries = SqlFormatter::splitQuery($sql);

结果:

DROP TABLE IF EXISTS MyTable;
CREATE TABLE MyTable ( id int );
INSERT INTO MyTable (id) VALUES (1),(2),(3),(4);
SELECT * FROM MyTable;

为何不使用正则表达式?

去看看 README 吧~https://github.com/jdorn/sql-formatter#why...

声明:本文转载于:learnku,如有侵犯,请联系admin@php.cn删除