Skip to content
5 changes: 5 additions & 0 deletions hibernate-dialect/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 1.8.0 ##

- Support any YDB `Decimal(p, s)` through `@Column(precision = ..., scale = ...)`: values are bound with the column type. Defaults stay `Decimal(22, 9)` for `BigDecimal` and `Decimal(22, 0)` for `BigInteger`.
- **Breaking change:** removed `YdbJdbcCode.DECIMAL_22_9`, `DECIMAL_31_9`, `DECIMAL_35_0` and `DECIMAL_35_9`. Use `@Column(precision = ..., scale = ...)` instead.

## 1.7.1 ##

- Fixed default type mapping fop UInt32/Int64/UInt64
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.boot.model.FunctionContributions;
import org.hibernate.boot.model.TypeContributions;
import org.hibernate.dialect.Dialect;
Expand Down Expand Up @@ -64,9 +63,7 @@
import static org.hibernate.type.SqlTypes.VARCHAR;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.java.UUIDJavaType;
import org.hibernate.type.descriptor.jdbc.JdbcType;
import org.hibernate.type.descriptor.jdbc.UUIDJdbcType;
import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry;
import org.hibernate.type.descriptor.sql.internal.DdlTypeImpl;
import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry;
import org.hibernate.type.spi.TypeConfiguration;
Expand All @@ -92,7 +89,6 @@
public class YdbDialect extends Dialect {
@SuppressWarnings({"rawtypes"})
private static final Exporter EMPTY_EXPORTER = new EmptyExporter<>();
private static final ConcurrentHashMap<Integer, DecimalJdbcType> DECIMAL_JDBC_TYPE_CACHE = new ConcurrentHashMap<>();

public YdbDialect(DialectResolutionInfo dialectResolutionInfo) {
super(dialectResolutionInfo);
Expand Down Expand Up @@ -200,10 +196,8 @@ public void contributeTypes(TypeContributions typeContributions, ServiceRegistry
typeContributions.contributeJdbcType(new YdbJdbcType(YdbJdbcCode.INTERVAL, Duration.class));

typeContributions.contributeJavaType(BigDecimalJavaType.INSTANCE_22_9);
typeContributions.contributeJdbcType(new DecimalJdbcType(YdbJdbcCode.DECIMAL_22_9));
typeContributions.contributeJdbcType(new DecimalJdbcType(YdbJdbcCode.DECIMAL_31_9));
typeContributions.contributeJdbcType(new DecimalJdbcType(YdbJdbcCode.DECIMAL_35_0));
typeContributions.contributeJdbcType(new DecimalJdbcType(YdbJdbcCode.DECIMAL_35_9));
typeContributions.contributeJdbcType(new DecimalJdbcType(NUMERIC));
typeContributions.contributeJdbcType(new DecimalJdbcType(DECIMAL));
}

@Override
Expand All @@ -221,10 +215,6 @@ protected void registerColumnTypes(TypeContributions typeContributions, ServiceR
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.DATETIME_64, "Datetime64", "Datetime64", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.TIMESTAMP_64, "Timestamp64", "Timestamp64", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.INTERVAL_64, "Interval64", "Interval64", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.DECIMAL_22_9, "Decimal(22, 9)", "Decimal(22, 9)", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.DECIMAL_31_9, "Decimal(31, 9)", "Decimal(31, 9)", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.DECIMAL_35_0, "Decimal(35, 0)", "Decimal(35, 0)", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.DECIMAL_35_9, "Decimal(35, 9)", "Decimal(35, 9)", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.JSON, "Json", "Json", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.JSON_DOCUMENT, "JsonDocument", "JsonDocument", this));
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.BOOL, "Bool", "Bool", this));
Expand All @@ -247,22 +237,6 @@ protected void registerColumnTypes(TypeContributions typeContributions, ServiceR
ddlTypeRegistry.addDescriptor(new DdlTypeImpl(YdbJdbcCode.INTERVAL, "Interval", "Interval", this));
}

@Override
public JdbcType resolveSqlTypeDescriptor(
String columnTypeName,
int jdbcTypeCode,
int precision,
int scale,
JdbcTypeRegistry jdbcTypeRegistry) {
if ((jdbcTypeCode == NUMERIC || jdbcTypeCode == DECIMAL) && (precision != 0 || scale != 0)) {
int sqlCode = ydbDecimal(precision, scale);

return DECIMAL_JDBC_TYPE_CACHE.computeIfAbsent(sqlCode, DecimalJdbcType::new);
}

return super.resolveSqlTypeDescriptor(columnTypeName, jdbcTypeCode, precision, scale, jdbcTypeRegistry);
}

@Override
public int getDefaultDecimalPrecision() {
return 22;
Expand Down Expand Up @@ -530,8 +504,4 @@ public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
return null;
};
}

private static int ydbDecimal(int precision, int scale) {
return 1 << 14 + (precision << 6) + (scale & 0x111111);
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package tech.ydb.hibernate.dialect.code;

import org.hibernate.Internal;

/**
* That class contain custom YDB type codes
* @see <a href="https://github.com/ydb-platform/ydb-jdbc-driver/blob/3d74021/jdbc/src/main/java/tech/ydb/jdbc/YdbConst.java#L8-L9">JDBC Driver constants</a>
* @see <a href="https://github.com/ydb-platform/ydb-jdbc-driver/blob/3d74021/jdbc/src/main/java/tech/ydb/jdbc/impl/YdbTypes.java#L37-L66">Primitive types</a>
* @see <a href="https://github.com/ydb-platform/ydb-jdbc-driver/blob/3d74021/jdbc/src/main/java/tech/ydb/jdbc/impl/YdbTypes.java#L138-L144">Decimal type</a>
*
* @author Kirill Kurdyukov
*/
final class YdbConst {
public static final int SQL_KIND_PRIMITIVE = 10000;
public static final int SQL_KIND_DECIMAL = 1 << 14; // 16384
@Internal
public final class YdbConst {
static final int SQL_KIND_PRIMITIVE = 10000;
private static final int SQL_KIND_DECIMAL = 1 << 14;
private static final int DECIMAL_SCALE_BITS = 6;

private YdbConst() { };
}

/**
* Encodes the Decimal flag, precision, and scale expected by the YDB JDBC driver.
* Scale occupies the lowest six bits, followed by precision.
*
* @see <a href="https://github.com/ydb-platform/ydb-jdbc-driver/blob/6786ca21b86469723c658312b63f7a7393aa4824/jdbc/src/main/java/tech/ydb/jdbc/common/YdbTypes.java#L149-L155">JDBC Decimal decoding</a>
*/
public static int decimalJdbcTypeCode(int precision, int scale) {
return SQL_KIND_DECIMAL + (precision << DECIMAL_SCALE_BITS) + scale;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,18 +132,4 @@ public final class YdbJdbcCode {
public static final int TIMESTAMP_64 = YdbConst.SQL_KIND_PRIMITIVE + 27;

public static final int INTERVAL_64 = YdbConst.SQL_KIND_PRIMITIVE + 28;


// WARN! Attribute value must be constant!

/**
* <a href="https://github.com/ydb-platform/ydb-jdbc-driver/blob/v2.3.3/jdbc/src/main/java/tech/ydb/jdbc/impl/YdbTypes.java#L37-L66">link</a>
*/
public static final int DECIMAL_22_9 = YdbConst.SQL_KIND_DECIMAL + (22 << 6) + 9;

public static final int DECIMAL_31_9 = YdbConst.SQL_KIND_DECIMAL + (31 << 6) + 9;

public static final int DECIMAL_35_0 = YdbConst.SQL_KIND_DECIMAL + (35 << 6);

public static final int DECIMAL_35_9 = YdbConst.SQL_KIND_DECIMAL + (35 << 6) + 9;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,60 @@
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.MappingException;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.jdbc.AdjustableJdbcType;
import org.hibernate.type.descriptor.jdbc.JdbcType;
import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators;
import tech.ydb.hibernate.dialect.code.YdbConst;

/**
* @author Kirill Kurdyukov
*/
public class DecimalJdbcType extends org.hibernate.type.descriptor.jdbc.DecimalJdbcType {
public class DecimalJdbcType extends org.hibernate.type.descriptor.jdbc.DecimalJdbcType implements AdjustableJdbcType {
private final int sqlCode;
private final int defaultSqlCode;

public DecimalJdbcType(int sqlCode) {
this.sqlCode = sqlCode;
this.defaultSqlCode = sqlCode;
}

public DecimalJdbcType(int defaultSqlCode, int precision, int scale) {
this.sqlCode = jdbcTypeCode(precision, scale);
this.defaultSqlCode = defaultSqlCode;
}

@Override
public int getJdbcTypeCode() {
return sqlCode;
}

@Override
public int getDefaultSqlTypeCode() {
return defaultSqlCode;
}

@Override
public JdbcType resolveIndicatedType(JdbcTypeIndicators indicators, JavaType<?> javaType) {
if (sqlCode != Types.NUMERIC && sqlCode != Types.DECIMAL) {
return this;
}

int precision = indicators.getColumnPrecision();
int scale = indicators.getColumnScale();
if (precision == JdbcTypeIndicators.NO_COLUMN_PRECISION) {
precision = javaType.getDefaultSqlPrecision(indicators.getDialect(), this);
}
if (scale == JdbcTypeIndicators.NO_COLUMN_SCALE) {
scale = javaType.getDefaultSqlScale(indicators.getDialect(), this);
}
return new DecimalJdbcType(defaultSqlCode, precision, scale);
}

@Override
public <X> ValueBinder<X> getBinder(final JavaType<X> javaType) {
return new ValueBinder<>() {
Expand All @@ -37,4 +72,12 @@ public void bind(CallableStatement st, X value, String name, WrapperOptions opti
}
};
}

private static int jdbcTypeCode(int precision, int scale) {
if (precision < 1 || precision > 35 || scale < 0 || scale > precision) {
throw new MappingException("Invalid YDB Decimal(" + precision + ", " + scale
+ "): precision must be between 1 and 35 and scale between 0 and precision");
}
return YdbConst.decimalJdbcTypeCode(precision, scale);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package tech.ydb.hibernate.types;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static tech.ydb.hibernate.TestUtils.basedConfiguration;
import static tech.ydb.hibernate.TestUtils.jdbcUrl;
import tech.ydb.test.junit5.YdbHelperExtension;

public class DecimalPrecisionScaleTest {
@RegisterExtension
private static final YdbHelperExtension ydb = new YdbHelperExtension();

private static SessionFactory sessionFactory;

@BeforeAll
static void setUp() {
sessionFactory = basedConfiguration().addAnnotatedClass(DecimalEntity.class)
.setProperty(AvailableSettings.URL, jdbcUrl(ydb) + "?disablePrepareDataQuery=true")
.setProperty(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, "drop-and-create")
.setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, "3")
.buildSessionFactory();
}

@AfterAll
static void tearDown() {
if (sessionFactory != null) {
sessionFactory.close();
}
}

@Test
void createsColumnsWithDeclaredPrecisionAndScale() {
sessionFactory.inTransaction(session -> session.doWork(connection -> {
Map<String, String> types = new HashMap<>();
try (ResultSet columns = connection.getMetaData()
.getColumns(null, null, "decimal_precision_scale", null)) {
while (columns.next()) {
types.put(columns.getString("COLUMN_NAME"), columns.getString("TYPE_NAME"));
}
}
assertEquals(Map.of(
"id", "Int64",
"amount", "Decimal(18, 2)",
"largeAmount", "Decimal(35, 10)",
"fraction", "Decimal(35, 35)",
"integerAmount", "Decimal(35, 0)",
"defaultDecimal", "Decimal(22, 9)",
"defaultInteger", "Decimal(22, 0)"), types);
}));
}

@Test
void persistsBatchWithLargeValuesZerosAndNulls() {
DecimalEntity large = largeValues(1);
DecimalEntity zero = new DecimalEntity(2, new BigDecimal("0.00"), new BigDecimal("0.0000000000"),
new BigDecimal("0.00000000000000000000000000000000000"), BigDecimal.ZERO,
new BigDecimal("0.000000000"), BigInteger.ZERO);
DecimalEntity empty = new DecimalEntity(3, null, null, null, null, null, null);
sessionFactory.inTransaction(session -> {
session.persist(large);
session.persist(zero);
session.persist(empty);
});
sessionFactory.inTransaction(session -> {
assertEquals(large, session.find(DecimalEntity.class, 1L));
assertEquals(zero, session.find(DecimalEntity.class, 2L));
assertEquals(empty, session.find(DecimalEntity.class, 3L));
});
}

@Test
void updatesAndQueriesWithInferredParameters() {
DecimalEntity entity = largeValues(10);
sessionFactory.inTransaction(session -> session.persist(entity));
entity.setLargeAmount(new BigDecimal("-1234567890123456789012345.9876543210"));
entity.setFraction(new BigDecimal("-0.12345678901234567890123456789012345"));
sessionFactory.inTransaction(session -> session.createMutationQuery(
"update DecimalEntity e set e.largeAmount = :amount, e.fraction = :fraction where e.id = :id")
.setParameter("amount", entity.getLargeAmount())
.setParameter("fraction", entity.getFraction())
.setParameter("id", entity.getId())
.executeUpdate());
sessionFactory.inTransaction(session -> assertEquals(entity,
session.createQuery("from DecimalEntity e where e.largeAmount = :amount and e.fraction = :fraction",
DecimalEntity.class)
.setParameter("amount", entity.getLargeAmount())
.setParameter("fraction", entity.getFraction())
.getSingleResult()));
entity.setIntegerAmount(new BigDecimal("-12345678901234567890123456789012345"));
sessionFactory.inTransaction(session -> session.merge(entity));
sessionFactory.inTransaction(session -> assertEquals(entity, session.find(DecimalEntity.class, entity.getId())));
}

@Test
void readsDecimalValuesFromNativeQuery() {
DecimalEntity entity = largeValues(20);
sessionFactory.inTransaction(session -> session.persist(entity));
sessionFactory.inTransaction(session -> {
Object[] actual = session.createNativeQuery(
"SELECT amount, largeAmount, fraction, integerAmount FROM decimal_precision_scale WHERE id = :id",
Object[].class)
.setParameter("id", entity.getId())
.getSingleResult();
assertArrayEquals(new Object[]{entity.getAmount(), entity.getLargeAmount(), entity.getFraction(),
entity.getIntegerAmount()}, actual);
});
}

private static DecimalEntity largeValues(long id) {
return new DecimalEntity(id, new BigDecimal("1234567890123456.78"),
new BigDecimal("1234567890123456789012345.1234567890"),
new BigDecimal("0.12345678901234567890123456789012345"),
new BigDecimal("12345678901234567890123456789012345"),
new BigDecimal("1234567890123.123456789"), new BigInteger("1234567890123456789012"));
}

@Entity(name = "DecimalEntity")
@Table(name = "decimal_precision_scale")
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DecimalEntity {
@Id
private long id;
@Column(precision = 18, scale = 2)
private BigDecimal amount;
@Column(precision = 35, scale = 10)
private BigDecimal largeAmount;
@Column(precision = 35, scale = 35)
private BigDecimal fraction;
@Column(precision = 35, scale = 0)
private BigDecimal integerAmount;
private BigDecimal defaultDecimal;
private BigInteger defaultInteger;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,12 @@ public class TestEntity {
@Column
private BigDecimal default_bigDecimal;

@Column
@JdbcTypeCode(YdbJdbcCode.DECIMAL_31_9)
@Column(precision = 31, scale = 9)
private BigDecimal bigDecimal31_9;

@Column
@JdbcTypeCode(YdbJdbcCode.DECIMAL_35_0)
@Column(precision = 35, scale = 0)
private BigDecimal bigDecimal35_0;

@Column
@JdbcTypeCode(YdbJdbcCode.DECIMAL_35_9)
@Column(precision = 35, scale = 9)
private BigDecimal bigDecimal35_9;
}
Loading
Loading