How to Beautify SQL with the https://github.com/pingcap/parser Package

Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: https://github.com/pingcap/parser这个包如何美化SQL

| username: 大飞飞呀

How to beautify SQL using the package GitHub - pingcap/parser: A MySQL Compatible SQL Parser
stmt, _, err := p.ParseSQL(sql)
||var sb strings.Builder|
||ctx := format.NewRestoreCtx(format.DefaultRestoreFlags, &sb)|
||err = stmt[0].Restore(ctx)|
After executing the above code, there are no line breaks.
Executed SQL:
select supplier_name, city from
(select * from suppliers join addresses on suppliers.address_id=addresses.id)
as suppliers
where supplier_id > 500
order by supplier_name asc, city desc;
Result:
SELECT supplier_name, city FROM (SELECT * FROM suppliers JOIN addresses ON suppliers.address_id = addresses.id) AS suppliers WHERE supplier_id > 500 ORDER BY supplier_name, city DESC
Desired SQL:

| username: tidb狂热爱好者 | Original post link

Use yearning

| username: 人如其名 | Original post link

The parser should not have the beautification function of line breaks.

| username: 大飞飞呀 | Original post link

What is yearning?

| username: system | Original post link

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.