【问题标题】:SQL string formatter [closed]SQL字符串格式化程序[关闭]
【发布时间】:2010-09-28 08:46:53
【问题描述】:

有没有人知道一个程序、实用程序或一些程序库,最好是用于 Linux,它采用未格式化的 SQL 字符串并漂亮地打印出来?

例如,我想要以下内容

select * from users where name = 'Paul'

改成这样的

select * 
from users
where
   name = 'Paul'

确切的格式并不重要。 我只需要一些东西来获取一个大的 SQL 字符串并将其分解成更易读的东西。

【问题讨论】:

    标签: sql linux formatting code-formatting


    【解决方案1】:

    fsqlf (http://sourceforge.net/projects/fsqlf/) 是一个命令行或 GUI 程序,开源,用于格式化 SQL。它支持有一个formatting.conf 文件,这让您在最终产品的外观上有很大的灵活性。

    例子:

    ☺  [wwalker@speedy:~] 
    $ echo "select f1, f2, fname, lName from tblName where f1 = true and fname is not null order by lName asc" | fsqlf 
    
    SELECT
      f1
    , f2
    , fname
    , lName
    FROM tblName
    WHERE f1=true
    AND fname is not null
    ORDER BY lName asc
    ☺  [wwalker@speedy:~] 
    $ vim formatting.conf # 2 character change
    ☺  [wwalker@speedy:~] 
    $ echo "select f1, f2, fname, lName from tblName where f1 = true and fname is not null order by lName asc" | fsqlf 
    
    SELECT
     f1 ,
     f2 ,
     fname ,
     lName
    FROM tblName
    WHERE f1=true
    AND fname is not null
    ORDER BY lName asc
    ☺  [wwalker@speedy:~] 
    $ vim formatting.conf # 1 character change
    ☺  [wwalker@speedy:~] 
    $ echo "select f1, f2, fname, lName from tblName where f1 = true and fname is not null order by lName asc" | fsqlf 
    
    SELECT
     f1 , f2 , fname , lName
    FROM tblName
    WHERE f1=true
    AND fname is not null
    ORDER BY lName asc
    ☺  [wwalker@speedy:~] 
    $ 
    

    【讨论】:

    • 这是最好的答案!因为您可以使用开源工具在自己的机器上格式化 SQL 查询,而无需使用第三方网站或专有工具!带有可疑的数据保留和隐私政策!
    • 任何 PPA 可以轻松安装在类似 Ubuntu 的设备上?
    【解决方案2】:

    查看sqlparse。它是一个安装命令sqlformat 的Python 模块。用法很简单,例如:

    sqlformat --reindent --keywords upper --identifiers lower my_file.sql
    

    我尝试了上述 CLI 替代方案,但是:

    • sqlinform 出来了,因为我想要一个开源 CLI 应用程序。
    • fsqlf 只有很少的功能(例如缺少create view)。

    感谢sqlformat,我什至了解到“REF”是reserved keyword in SQL:2011 and SQL:2008

    【讨论】:

    • 这完全搞砸了我想要的格式(缩进),无论提供什么参数。
    • 相同。即使只有 -r,顺便说一下,只是在 ORDER BY 子句之后,它开始为提供的每个新字段行逐渐缩进近 40 个字符。
    • 该工具由Apache Superset自动安装。我认为这是 Superset 的某种形式的认可。
    • 它似乎不支持管道|STDIN 读取数据。
    • @cprn 你可以在版本 0.1.2 ---“根据选项格式化文件。使用“-”作为文件从标准输入读取。”
    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2022-01-22
    • 2013-09-24
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多