Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ JOIN 继续通过 `query.join(...)` 声明。FROM、JOIN、条件、投影和排
没有绑定时沿用原查找行为。绑定只保留在查询操作和其 clone 中,不进入 `QueryParam.context`,
普通 context 赋值不会安装映射或改变 JOIN。绑定不授权访问、不执行 DDL,调用方负责权限及映射生命周期。

追加查询结构时,可通过 `query.getTableReferences()` 的不可变快照避让 FROM、JOIN 和已有绑定的引用名,
使用 `query.getTableBindings().merge(additional)` 保留已有映射;同名不同映射的合并明确失败。
`bindTables(...)` 仍是显式替换,传 null 仍清除绑定,不修改既有查询参数或共享 schema。

1. 轻SQL,重java.
2. 动态表单: 动态维护表结构,增删改查.
3. 参数驱动动态条件, 前端也能透传动态条件,无SQL注入.
Expand Down Expand Up @@ -66,6 +70,8 @@ JPA 实体属性从属性描述符、getter 返回类型和 setter 参数类型
`@JsonCodec(includeNulls = true)` 为当前列保留显式嵌套 null;配置使用当前 codec 的独立 mapper,不修改共享默认配置。默认 false 保持原行为。JSON 编解码与物理列类型独立,可组合标准 LONGVARCHAR。
`@JsonCodec(useBigDecimalForFloats = true)` 将无具体 Java 数字类型的 JSON 小数解码为 BigDecimal,避免高精度正文读回时变成 Double;默认 false 保留原解码行为,可与 includeNulls 组合。

标准列 codec 提供只读配置,供映射检查或描述工具读取实际安装的实例:日期格式/目标类型、数字目标类型、布尔 SQL 类型、枚举类型/属性,以及 JSON 泛型/目标类型/null 与小数选项。数字函数构造器的 `getJavaType()` 为 null;JSON 的 `isCustomMapper()` 标明显式设置的外部 mapper,标准选项派生副本仍继承共享默认配置。这些配置不包含可执行函数、任意 Jackson 模块或共享 mapper 的完整状态,不能替代调用方对可重建范围的判断。

枚举位集合的 `in$any` 判断 `(M & Q) <> 0`,新增 `in$all` 判断 `(M & Q) = Q`(存储集合包含全部查询项),`nin` 使用对应否定。没有 any/all 的原 `in` 仍是 `(M & Q) = M`(存储集合是查询集合的子集)。通用 EnumInFragmentBuilder 同时接受枚举和已编码的 BIGINT mask,不要求业务选项映射到 Java ordinal。
`EnumInFragmentBuilder.of/ofNot` 统一选择数据库实现,包括 H2 的参数化 `BITAND`;调用方无需自行判断方言。

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.hswebframework.ezorm.rdb.codec;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.hswebframework.ezorm.core.ValueCodec;

import java.sql.JDBCType;
Expand All @@ -9,6 +10,7 @@
@AllArgsConstructor
public class BooleanValueCodec implements ValueCodec<Object, Boolean> {

@Getter
private SQLType sqlType;

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.hswebframework.ezorm.rdb.codec;

import lombok.NoArgsConstructor;
import lombok.Getter;
import org.hswebframework.ezorm.core.ValueCodec;
import org.hswebframework.utils.DateTimeUtils;
import org.hswebframework.utils.time.DateFormatter;
Expand All @@ -21,8 +22,10 @@
@NoArgsConstructor
public class DateTimeCodec implements ValueCodec {

@Getter
private String format;

@Getter
private Class<?> toType;

public DateTimeCodec(String format, Class<?> toType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class EnumValueCodec implements ValueCodec<Object, Object> {
PROPERTY_ORDINAL = EnumCodec.ORDINAL;

@SuppressWarnings("all")
@Getter
private final Class type;
@SuppressWarnings("all")
private final Object[] values;
Expand All @@ -36,6 +37,7 @@ public class EnumValueCodec implements ValueCodec<Object, Object> {
@Getter
private boolean toMask;

@Getter
private final String property;

public EnumValueCodec(Class<?> type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream;
import lombok.Setter;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.ezorm.core.ValueCodec;
Expand Down Expand Up @@ -45,13 +45,32 @@ public class JsonValueCodec implements ValueCodec<Object, Object> {
.setTimeZone(TimeZone.getDefault());
}

@Getter
private final JavaType jacksonType;

@Getter
private final Class<?> targetType;

@Setter
private ObjectMapper mapper = defaultMapper;

/** 是否显式使用了共享默认配置之外的 mapper;标准选项派生的副本不属于自定义 mapper。 */
@Getter
private boolean customMapper;

public void setMapper(ObjectMapper mapper) {
this.mapper = mapper;
this.customMapper = mapper != defaultMapper;
}

/** 当前 mapper 是否使用 ALWAYS 作为默认值包含策略。 */
public boolean isIncludeNulls() {
return mapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion() == JsonInclude.Include.ALWAYS;
}

public boolean isUseBigDecimalForFloats() {
return mapper.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
}

/**
* Configures this codec at mapping time. A private mapper configuration preserves the shared
* codec defaults; encoding and decoding never mutate that configuration.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.hswebframework.ezorm.rdb.codec;

import lombok.SneakyThrows;
import lombok.Getter;
import org.hswebframework.ezorm.core.ValueCodec;
import org.hswebframework.ezorm.core.utils.StringUtils;
import org.hswebframework.ezorm.rdb.executor.NullValue;
Expand All @@ -19,12 +20,18 @@ public class NumberValueCodec implements ValueCodec<Object, Object> {

private final Function<Number, Object> converter;

/** 标准类型转换的目标;通过任意函数构造时为 null,不能据此重建转换行为。 */
@Getter
private final Class<?> javaType;

public NumberValueCodec(Function<Number, Object> converter) {
this.converter = converter;
this.javaType = null;
}

@SneakyThrows
public NumberValueCodec(Class<?> javaType) {
this.javaType = javaType;
if (javaType == int.class || javaType == Integer.class) {
converter = Number::intValue;
} else if (javaType == double.class || javaType == Double.class) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -287,6 +288,16 @@ public QueryOperator bindTables(QueryTableBindings bindings) {
throw new UnsupportedOperationException("query table bindings are not supported");
}

/** 当前显式绑定的不可变配置;未绑定时返回空配置,供查询贡献者安全合并映射。 */
public QueryTableBindings getTableBindings() {
throw new UnsupportedOperationException("query table binding inspection is not supported");
}

/** FROM、JOIN 目标/别名及显式绑定已使用的引用名快照,供追加查询结构时避让名称。 */
public Set<String> getTableReferences() {
throw new UnsupportedOperationException("query table reference inspection is not supported");
}

/**
* 获取SQL请求
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.function.Consumer;

import static org.hswebframework.ezorm.rdb.operator.dml.query.SortOrder.asc;
Expand Down Expand Up @@ -172,6 +174,27 @@ public QueryOperator bindTables(QueryTableBindings bindings) {
return this;
}

@Override
public QueryTableBindings getTableBindings() {
QueryTableBindings bindings = parameter.getTableBindings();
return bindings == null ? QueryTableBindings.EMPTY : bindings;
}

@Override
public Set<String> getTableReferences() {
Set<String> names = new LinkedHashSet<>(getTableBindings().getTableNames());
names.add(parameter.getFrom());
names.add(parameter.getFromAlias());
if (parameter.getJoins() != null) {
for (Join join : parameter.getJoins()) {
names.add(join.getTarget());
names.add(join.getAlias());
}
}
names.remove(null);
return Set.copyOf(names);
}

@Override
public SqlRequest getSql() {
throw new UnsupportedOperationException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.LinkedHashMap;
import org.hswebframework.ezorm.rdb.metadata.TableOrViewMetadata;

/**
Expand All @@ -12,6 +14,7 @@
* @since 4.2.3
*/
public final class QueryTableBindings {
public static final QueryTableBindings EMPTY = new QueryTableBindings(Map.of());
private final Map<String, TableOrViewMetadata> tables;

public QueryTableBindings(Map<String, TableOrViewMetadata> tables) {
Expand All @@ -20,4 +23,19 @@ public QueryTableBindings(Map<String, TableOrViewMetadata> tables) {

/** 按查询引用名称解析显式绑定,适用于 FROM 和 JOIN;未绑定时由原 schema 解析。 */
public Optional<TableOrViewMetadata> find(String name) { return Optional.ofNullable(tables.get(name)); }

/** 当前绑定引用名的不可变集合,不暴露可变映射。 */
public Set<String> getTableNames() { return tables.keySet(); }

/** 合并独立贡献的映射;同名不同映射明确拒绝,不能静默改变已有 FROM/JOIN。 */
public QueryTableBindings merge(QueryTableBindings other) {
Map<String, TableOrViewMetadata> merged = new LinkedHashMap<>(tables);
other.tables.forEach((name, table) -> {
TableOrViewMetadata previous = merged.putIfAbsent(name, table);
if (previous != null && previous != table) {
throw new IllegalArgumentException("conflicting query table binding: " + name);
}
});
return new QueryTableBindings(merged);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package org.hswebframework.ezorm.rdb.codec;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.math.BigDecimal;
import java.sql.JDBCType;
import java.util.Collections;
import java.util.Map;

import static org.junit.Assert.*;

public class CodecConfigurationTest {

enum State { first, second }

@Test
public void standardConfigurationDescribesInstalledBehavior() {
DateTimeCodec date = new DateTimeCodec("yyyyMMdd", String.class);
assertEquals("yyyyMMdd", date.getFormat());
assertSame(String.class, date.getToType());
assertEquals("19700101", date.decode(date.encode("19700101")));

BooleanValueCodec bool = new BooleanValueCodec(JDBCType.INTEGER);
assertSame(JDBCType.INTEGER, bool.getSqlType());
assertEquals(1, bool.encode(true));

EnumValueCodec enumeration = new EnumValueCodec(State[].class, "ordinal", true);
assertSame(State.class, enumeration.getType());
assertEquals("ordinal", enumeration.getProperty());
assertTrue(enumeration.isArray());
assertTrue(enumeration.isToMask());
}

@Test
public void arbitraryNumberFunctionHasNoReconstructableTarget() {
NumberValueCodec standard = new NumberValueCodec(BigDecimal.class);
assertSame(BigDecimal.class, standard.getJavaType());
assertEquals(new BigDecimal("12.25"), standard.decode("12.25"));
NumberValueCodec function = new NumberValueCodec(number -> number.doubleValue() / 100);
assertNull(function.getJavaType());
assertEquals(0.12D, function.decode(12));
}

@Test
public void jsonConfigurationRetainsGenericTypeAndEffectiveOptions() {
boolean sharedDecimals = JsonValueCodec.defaultMapper.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
JsonInclude.Value sharedInclusion = JsonValueCodec.defaultMapper.getSerializationConfig().getDefaultPropertyInclusion();
JsonValueCodec codec = JsonValueCodec.ofMap(Map.class, String.class, BigDecimal.class)
.includeNulls(true).useBigDecimalForFloats(true);
assertSame(Map.class, codec.getTargetType());
assertSame(BigDecimal.class, codec.getJacksonType().getContentType().getRawClass());
assertTrue(codec.isIncludeNulls());
assertTrue(codec.isUseBigDecimalForFloats());
assertFalse(codec.isCustomMapper());
assertEquals("{\"empty\":null}", codec.encode(Collections.singletonMap("empty", null)));
assertEquals(BigDecimal.ONE, ((Map<?, ?>) codec.decode("{\"amount\":1}")).get("amount"));
assertEquals(sharedDecimals, JsonValueCodec.defaultMapper.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS));
assertEquals(sharedInclusion, JsonValueCodec.defaultMapper.getSerializationConfig().getDefaultPropertyInclusion());
}

@Test
public void standardOptionsDoNotEraseCustomMapperProvenance() {
JsonValueCodec codec = JsonValueCodec.of(Map.class);
codec.setMapper(new ObjectMapper());
codec.includeNulls(true).useBigDecimalForFloats(true);
assertTrue(codec.isCustomMapper());
codec.setMapper(JsonValueCodec.defaultMapper);
assertFalse(codec.isCustomMapper());
assertEquals(JsonValueCodec.defaultMapper.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS),
codec.isUseBigDecimalForFloats());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,49 @@
import java.sql.JDBCType;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.*;

public class QueryTableBindingsTest {
@Test
public void compositionKeepsExistingBindingsAndReadOnlyReferenceSnapshots() {
RDBSchemaMetadata schema = MetadataHelper.createMockSchema();
RDBTableMetadata main = schema.getTable("test").orElseThrow(IllegalStateException::new);
RDBTableMetadata remote = schema.newTable("remote");
RDBTableMetadata additional = schema.newTable("additional");
QueryOperatorParameter parameter = new QueryOperatorParameter();
parameter.setFrom("test");
parameter.setFromAlias("main");
Join join = new Join();
join.setTarget("remote");
join.setAlias("ext");
parameter.getJoins().add(join);
QueryOperator query = new org.hswebframework.ezorm.rdb.operator.dml.query.BuildParameterQueryOperator(parameter);
assertSame(QueryTableBindings.EMPTY, query.getTableBindings());
query.bindTables(new QueryTableBindings(Map.of("test", main, "remote", remote)));
Set<String> original = query.getTableReferences();
assertEquals(Set.of("test", "main", "remote", "ext"), original);
assertThrows(UnsupportedOperationException.class, original::clear);
assertThrows(UnsupportedOperationException.class, query.getTableBindings().getTableNames()::clear);
query.bindTables(query.getTableBindings().merge(new QueryTableBindings(Map.of("additional", additional))));
assertSame(main, query.getTableBindings().find("test").orElse(null));
assertSame(remote, query.getTableBindings().find("remote").orElse(null));
assertTrue(query.getTableReferences().contains("additional"));
assertFalse(original.contains("additional"));
QueryOperator copy = query.clone();
assertEquals(query.getTableReferences(), copy.getTableReferences());
copy.bindTables(null);
assertFalse(copy.getTableReferences().contains("additional"));
assertTrue(query.getTableReferences().contains("additional"));
assertThrows(IllegalArgumentException.class, () -> query.getTableBindings()
.merge(new QueryTableBindings(Map.of("remote", additional))));
assertSame(remote, query.getTableBindings().find("remote").orElse(null));
parameter.setJoins(null);
assertFalse(query.getTableReferences().contains("ext"));
assertTrue(original.contains("ext"));
}

@Test
public void boundSqlBuildFailuresAreDeferredUntilSubscription() {
RDBSchemaMetadata schema = MetadataHelper.createMockSchema();
Expand Down
Loading