使用Vscode插件SQLTools自动格式化SQL语句


使用 SQL Tools 自动格式化 SQL,
SQLTools 提供的一些功能:

  • 美化器/格式化器
  • 查询运行器、历史记录和书签
  • 连接浏览器
  • 查询生成器(仅限 INSERT)

首先点击标题下载此SQL 工具。
如果安装了 DB 驱动程序,则可以将 SQL 文件直接连接到 DB 并执行。SQLTools 支持的驱动程序
设置 SQL 工具:
SQLTools --设置属性

编辑.vscode/setting.json:
{
  
    "sqltools.connections": [
    {
        "name": "MySQL",
        "server": "localhost",
        "driver": "MySQL",
        "port": 3306,
        "database": "test_db",
        "username": "root",
        "askForPassword": false,
        "password": "root",
        "connectionTimeout": 15
    }
    ],
   
    "sqltools.format": {
        "language": "sql",
        "indentSize": 2,
        "reservedWordCase": "lower",
        "linesBetweenQueries": 1
    },
   
    "[sql]": {
        "editor.defaultFormatter": "mtxr.sqltools"
    },
    
    "editor.formatOnSave": true
}

在vscode保存SQL文件,原来:

SELECT a, b FROM t CROSS JOIN t2 on t.id = t2.id_t;

SELECT DISTINCT name, ROUND(age/7) field1, 18 + 20 AS field2, 'some string' FROM foo;

-- here is a comment
# another comment

UPDATE "log" SET "time" = '2020-02-01 09:00:00' WHERE "id" = 1 RETURNING "time";

CREATE TABLE foo (id INTEGER PRIMARY KEY,name VARCHAR(200) NOT NULL);

ALTER TABLE supplier MODIFY supplier_name char(100) NOT NULL;

select t.column1 Кириллица_cyrilic_alias
  , t.column2 Latin_alias
from db_table t
where a >= some_date1  -- from
and a <  some_date2  -- to
and b >= some_date3  -- and
and b <  some_date4  -- where, select etc.
and 1 = 1;

自动格式化以后:

select a,
    b
from t
    cross join t2 on t.id = t2.id_t;
select distinct name,
    ROUND(age / 7) field1,
    18 + 20 as field2,
    'some string'
from foo;
-- here is a comment
# another comment
update "log"
set
"time" = '2020-02-01 09:00:00'
where
"id" = 1
returning
"time";
create table foo (
    id INTEGER primary key,
    name VARCHAR(200) not null
);
alter table supplier
modify supplier_name char(100) not null;
select t.column1 Кириллица_cyrilic_alias,
    t.column2 Latin_alias
from db_table t
where a >= some_date1 -- from
    and a < some_date2 -- to
    and b >= some_date3 -- and
    and b < some_date4 -- where, select etc.
    and 1 = 1;