Skip to content

Commit

Permalink
!1192 新增 数据库 wrapper 支持反解
Browse files Browse the repository at this point in the history
Merge pull request !1192 from 蒋小小/v5-dev
  • Loading branch information
looly authored and gitee-org committed Mar 28, 2024
2 parents 1eb6e24 + e611019 commit c93e28d
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
30 changes: 30 additions & 0 deletions hutool-db/src/main/java/cn/hutool/db/sql/Wrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,36 @@ public String wrap(String field) {
return StrUtil.format("{}{}{}", preWrapQuote, field, sufWrapQuote);
}

/**
* 反解包装字段名<br>
*
* @param field 字段名
* @return 未包装的字段名
*/
public String unWrap(String field) {
if (preWrapQuote == null || sufWrapQuote == null || StrUtil.isBlank(field)) {
return field;
}

//如果已经包含包装的引号,返回原字符
if (!StrUtil.isSurround(field, preWrapQuote, sufWrapQuote)) {
return field;
}

//如果字段中包含通配符或者括号(字段通配符或者函数),不做包装
if (StrUtil.containsAnyIgnoreCase(field, "*", "(", " ", " as ")) {
return field;
}

//对于Oracle这类数据库,表名中包含用户名需要单独拆分包装
if (field.contains(StrUtil.DOT)) {
final Collection<String> target = CollUtil.edit(StrUtil.split(field, CharUtil.DOT, 2), t -> StrUtil.unWrap(t, preWrapQuote, sufWrapQuote));
return CollectionUtil.join(target, StrUtil.DOT);
}

return StrUtil.unWrap(field, preWrapQuote, sufWrapQuote);
}

/**
* 包装字段名<br>
* 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突
Expand Down
43 changes: 43 additions & 0 deletions hutool-db/src/test/java/cn/hutool/db/WrapperTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package cn.hutool.db;

import cn.hutool.db.sql.Wrapper;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

/**
* @author bwcx_jzy
* @since 24/3/28 028
*/
public class WrapperTest {

@Test
@Ignore
public void test() {
Wrapper wrapper = new Wrapper('`');
String originalName = "name";
String wrapName = wrapper.wrap(originalName);
String unWrapName = wrapper.unWrap(wrapName);
Assert.assertEquals(unWrapName, originalName);
}

@Test
@Ignore
public void testDotWrap() {
Wrapper wrapper = new Wrapper('`');
String originalName = "name.age";
String wrapName = wrapper.wrap(originalName);
String unWrapName = wrapper.unWrap(wrapName);
Assert.assertEquals(unWrapName, originalName);
}

@Test
@Ignore
public void testError() {
Wrapper wrapper = new Wrapper('`');
String originalName = "name.age*";
String wrapName = wrapper.wrap(originalName);
String unWrapName = wrapper.unWrap(wrapName);
Assert.assertEquals(unWrapName, originalName);
}
}

0 comments on commit c93e28d

Please sign in to comment.