fix format bug

This commit is contained in:
Looly 2023-08-04 15:38:42 +08:00
parent 9a82679dd9
commit 790161264b
3 changed files with 28 additions and 1 deletions

View File

@ -615,6 +615,15 @@ public class SqlBuilder implements Builder<String> {
return this.paramValues.toArray(new Object[0]); return this.paramValues.toArray(new Object[0]);
} }
/**
* 格式化SQL语句
* @return SqlBuilder
*/
public SqlBuilder format() {
this.sql.replace(0, this.sql.length(), SqlFormatter.format(this.sql.toString()));
return this;
}
/** /**
* 构建默认打印SQL日志 * 构建默认打印SQL日志
* *

View File

@ -122,6 +122,12 @@ public class SqlFormatter {
t = this.tokens.nextToken(); t = this.tokens.nextToken();
this.token += t; this.token += t;
} while (!"\"".equals(t)); } while (!"\"".equals(t));
} else if ("`".equals(this.token)) {
String t;
do {
t = this.tokens.nextToken();
this.token += t;
} while (!"`".equals(t));
} }
if ((this.afterByOrSetOrFromOrSelect) && (",".equals(this.token))) { if ((this.afterByOrSetOrFromOrSelect) && (",".equals(this.token))) {
@ -320,7 +326,7 @@ public class SqlFormatter {
} }
private static boolean isFunctionName(final String tok) { private static boolean isFunctionName(final String tok) {
if(StrUtil.isEmpty(tok)){ if (StrUtil.isEmpty(tok)) {
return true; return true;
} }
final char begin = tok.charAt(0); final char begin = tok.charAt(0);

View File

@ -1,5 +1,6 @@
package org.dromara.hutool.db.sql; package org.dromara.hutool.db.sql;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class SqlFormatterTest { public class SqlFormatterTest {
@ -11,4 +12,15 @@ public class SqlFormatterTest {
final String sql = "(select 1 from dual) union all (select 1 from dual)"; final String sql = "(select 1 from dual) union all (select 1 from dual)";
SqlFormatter.format(sql); SqlFormatter.format(sql);
} }
@Test
public void issue3246Test() {
final String sql = "select * from `order`";
final String format = SqlFormatter.format(sql);
Assertions.assertEquals(
"select\n" +
" * \n" +
" from\n" +
" `order`", format);
}
} }