前言
今天给大家分享一个在平时开发中会用得到的工具,主要是用来对SQL语句进行检查、优化和改写,从而对后台查数据库的性能有一定的提升。
主要功能特点
- 目前只支持 MySQL 语法族协议的SQL优化
- 支持基于启发式算法的语句优化
- 支持复杂查询的多列索引优化(UPDATE, INSERT, DELETE, SELECT)
- 支持EXPLAIN信息丰富解读
- 支持SQL指纹、压缩和美化
- 支持同一张表多条ALTER请求合并
- 支持自定义规则的SQL改写
安装使用
- 下载二进制包
wget https://github.com/XiaoMi/soar/releases/download/${tag}/soar.${OS}-amd64 -O soar
chmod a+x soar
如:
wget https://github.com/XiaoMi/soar/releases/download/0.9.0/soar.linux-amd64 -O soar
chmod a+x soar
- 安装后验证
echo 'select * from film' | ./soar
常用命令
- 基本语法
echo "select title from sakila.film" | ./soar -log-output=soar.log
- 指定输入源
# 从文件读取SQL
./soar -query file.sql
# 从管道读取SQL
cat file.sql | ./soar
- 指定配置文件
vi soar.yaml
# yaml format config file
online-dsn:
addr: 127.0.0.1:3306
schema: sakila
user: root
password: "1t'sB1g3rt"
disable: false
test-dsn:
addr: 127.0.0.1:3306
schema: sakila
user: root
password: "1t'sB1g3rt"
disable: false
echo "select title from sakila.film" | ./soar -test-dsn="root:1t'sB1g3rt@127.0.0.1:3306/sakila" -allow-online-as-test -log-output=soar.log
- 语法检查
echo "select * from tb" | soar -only-syntax-check
echo $?
0
echo "select * frm tb" | soar -only-syntax-check
At SQL 1 : syntax error at position 13 near 'frm'
echo $?
1
- 慢日志进行分析
pt-query-digest slow.log > slow.log.digest
# parse pt-query-digest's output which example script
python2.7 doc/example/digest_pt.py slow.log.digest > slow.md
- 将 UPDATE/DELETE/INSERT 语法转为 SELECT
echo "update film set title = 'abc'" | soar -rewrite-rules dml2select,delimiter -report-type rewrite
# 执行以上命令,会输出以下:
select * from film;
- 合并多条ALTER语句
echo "alter table tb add column a int; alter table tb add column b int;" | soar -report-type rewrite -rewrite-rules mergealter
# 执行以上命令,会输出以下:
ALTER TABLE `tb` add column a int, add column b int ;
具体示例
- 普通sql分析
echo "SELECT Faftersale_id,Fdeal_id,Fbuyer_id,Fseller_id,Fseller_pro_id,Fitem_num,Faftersale_type,Fseller_coop_id,Faftersale_state,Faftersale_fee,Flast_aftersale_record_id,Ftrade_id,Fitem_return_back_type,Frefund_detail_id,Fexchange_id,Fproperty FROM md_deal.t_aftersale WHERE Fseller_pro_id!=100500 AND Fseller_coop_id not in(361500,361488,364193) AND Flast_update_time>'2020-11-24 00:00:00' AND Flast_update_time<'2021-01-23 15:00:00'" | ./soar
输出结果如下图所示:
- 连接数据库sql分析,通过此种方式会给出建议的优化后的sql
echo "SELECT Faftersale_id,Fdeal_id,Fbuyer_id,Fseller_id,Fseller_pro_id,Fitem_num,Faftersale_type,Fseller_coop_id,Faftersale_state,Faftersale_fee,Flast_aftersale_record_id,Ftrade_id,Fitem_return_back_type,Frefund_detail_id,Fexchange_id,Fproperty FROM md_deal.t_aftersale WHERE Fseller_pro_id!=100500 AND Fseller_coop_id not in(361500,361488,364193) AND Flast_update_time>'2020-11-24 00:00:00' AND Flast_update_time<'2021-01-23 15:00:00'" | ./soar -test-dsn="username:pwd@host:3306/my_db" -show-warnings -allow-online-as-test -log-output=soar.log
输出结果如下图所示:
更多技术文章,尽在公众号“
Go键盘侠
”,欢迎关注~
版权声明:本文为qq_24858249原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。