新增 数据库 wrapper 支持反解

This commit is contained in:
bwcx_jzy 2024-03-28 10:09:11 +08:00
parent 1eb6e24124
commit e611019659
No known key found for this signature in database
GPG Key ID: E187D6E9DDDE8C53
2 changed files with 73 additions and 0 deletions

View File

@ -120,6 +120,36 @@ public class Wrapper implements Serializable {
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出错因此需要将字段名用单引号或者反引号包装起来避免冲突

View File

@ -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);
}
}