diff --git a/hibernate-dialect/CHANGELOG.md b/hibernate-dialect/CHANGELOG.md index dc9e2abd..beb686c7 100644 --- a/hibernate-dialect/CHANGELOG.md +++ b/hibernate-dialect/CHANGELOG.md @@ -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 diff --git a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java index 4cf18c24..c517c0f0 100644 --- a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java +++ b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java @@ -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; @@ -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; @@ -92,7 +89,6 @@ public class YdbDialect extends Dialect { @SuppressWarnings({"rawtypes"}) private static final Exporter EMPTY_EXPORTER = new EmptyExporter<>(); - private static final ConcurrentHashMap DECIMAL_JDBC_TYPE_CACHE = new ConcurrentHashMap<>(); public YdbDialect(DialectResolutionInfo dialectResolutionInfo) { super(dialectResolutionInfo); @@ -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 @@ -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)); @@ -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; @@ -530,8 +504,4 @@ public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return null; }; } - - private static int ydbDecimal(int precision, int scale) { - return 1 << 14 + (precision << 6) + (scale & 0x111111); - } } diff --git a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbConst.java b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbConst.java index 06831caf..54d18fbb 100644 --- a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbConst.java +++ b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbConst.java @@ -1,16 +1,29 @@ package tech.ydb.hibernate.dialect.code; +import org.hibernate.Internal; + /** * That class contain custom YDB type codes * @see JDBC Driver constants * @see Primitive types - * @see Decimal type * * @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() { }; -} \ No newline at end of file + + /** + * Encodes the Decimal flag, precision, and scale expected by the YDB JDBC driver. + * Scale occupies the lowest six bits, followed by precision. + * + * @see JDBC Decimal decoding + */ + public static int decimalJdbcTypeCode(int precision, int scale) { + return SQL_KIND_DECIMAL + (precision << DECIMAL_SCALE_BITS) + scale; + } +} diff --git a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbJdbcCode.java b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbJdbcCode.java index 45bfa45a..cd31b277 100644 --- a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbJdbcCode.java +++ b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/code/YdbJdbcCode.java @@ -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! - - /** - * link - */ - 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; } diff --git a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/types/DecimalJdbcType.java b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/types/DecimalJdbcType.java index a0da6926..9db2bb86 100644 --- a/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/types/DecimalJdbcType.java +++ b/hibernate-dialect/src/main/java/tech/ydb/hibernate/dialect/types/DecimalJdbcType.java @@ -4,18 +4,31 @@ 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 @@ -23,6 +36,28 @@ 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 ValueBinder getBinder(final JavaType javaType) { return new ValueBinder<>() { @@ -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); + } } diff --git a/hibernate-dialect/src/test/java/tech/ydb/hibernate/types/DecimalPrecisionScaleTest.java b/hibernate-dialect/src/test/java/tech/ydb/hibernate/types/DecimalPrecisionScaleTest.java new file mode 100644 index 00000000..188ba071 --- /dev/null +++ b/hibernate-dialect/src/test/java/tech/ydb/hibernate/types/DecimalPrecisionScaleTest.java @@ -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 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; + } +} diff --git a/hibernate-dialect/src/test/java/tech/ydb/hibernate/ydb_jdbc_code/TestEntity.java b/hibernate-dialect/src/test/java/tech/ydb/hibernate/ydb_jdbc_code/TestEntity.java index c5c3cc03..f370fb9a 100644 --- a/hibernate-dialect/src/test/java/tech/ydb/hibernate/ydb_jdbc_code/TestEntity.java +++ b/hibernate-dialect/src/test/java/tech/ydb/hibernate/ydb_jdbc_code/TestEntity.java @@ -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; } diff --git a/keycloak-ydb-extension/test/pom.xml b/keycloak-ydb-extension/test/pom.xml index b6ca97b6..5e02d222 100644 --- a/keycloak-ydb-extension/test/pom.xml +++ b/keycloak-ydb-extension/test/pom.xml @@ -97,7 +97,7 @@ org.testcontainers testcontainers - 1.20.6 + 2.0.3 test diff --git a/liquibase-dialect/CHANGELOG.md b/liquibase-dialect/CHANGELOG.md index 2ee209b6..2d2222d8 100644 --- a/liquibase-dialect/CHANGELOG.md +++ b/liquibase-dialect/CHANGELOG.md @@ -1,3 +1,8 @@ +## 1.1.3 ## + +* Support explicit `Decimal(p, s)` (1 <= p <= 35, 0 <= s <= p) in schema changes, inserts, `loadData`/`loadUpdateData` and changelog generation. Previously explicit parameters were replaced with `(22, 9)`. +* `decimal(p)` is created as `Decimal(p, 0)`; `decimal` without parameters stays `Decimal(22, 9)`. + ## 1.1.2 ## * Fixed the `liquibase tag` command failing on YDB due to an unsupported generic `UPDATE` query ([#236](https://github.com/ydb-platform/ydb-java-dialects/issues/236)). diff --git a/liquibase-dialect/src/main/java/tech/ydb/liquibase/type/DecimalTypeYdb.java b/liquibase-dialect/src/main/java/tech/ydb/liquibase/type/DecimalTypeYdb.java index f407cb9f..86affc1e 100644 --- a/liquibase-dialect/src/main/java/tech/ydb/liquibase/type/DecimalTypeYdb.java +++ b/liquibase-dialect/src/main/java/tech/ydb/liquibase/type/DecimalTypeYdb.java @@ -4,6 +4,7 @@ import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; +import liquibase.exception.UnexpectedLiquibaseException; /** * @author Kirill Kurdyukov @@ -11,7 +12,7 @@ @DataTypeInfo( name = "Decimal", aliases = {"java.sql.Types.DECIMAL", "java.math.BigDecimal"}, - minParameters = 2, + minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DATABASE ) @@ -19,17 +20,41 @@ public class DecimalTypeYdb extends BaseTypeYdb { @Override public boolean validate(Database database) { - return super.validate(database) && - getParameters()[0].equals(22) && getParameters()[1].equals(9); // Fixed Decimal(22,9) + decimalType(); + return true; } @Override public DatabaseDataType toDatabaseDataType(Database database) { - return new DatabaseDataType("DECIMAL(22,9)"); + return new DatabaseDataType(decimalType()); } @Override protected String objectToSql(Object value) { - return "CAST('" + value + "' AS DECIMAL(22,9))"; + return "CAST('" + value + "' AS " + decimalType() + ")"; + } + + private String decimalType() { + Object[] parameters = getParameters(); + if (parameters.length == 0) { + return "DECIMAL(22,9)"; + } + if (parameters.length > 2) { + throw new UnexpectedLiquibaseException("YDB Decimal accepts at most precision and scale"); + } + + int precision; + int scale; + try { + precision = Integer.parseInt(parameters[0].toString()); + scale = parameters.length == 2 ? Integer.parseInt(parameters[1].toString()) : 0; + } catch (NumberFormatException e) { + throw new UnexpectedLiquibaseException("YDB Decimal precision and scale must be integers", e); + } + if (precision < 1 || precision > 35 || scale < 0 || scale > precision) { + throw new UnexpectedLiquibaseException( + "YDB Decimal requires 1 <= precision <= 35 and 0 <= scale <= precision"); + } + return "DECIMAL(" + precision + "," + scale + ")"; } } diff --git a/liquibase-dialect/src/test/java/tech/ydb/liquibase/YdbDatabaseDecimalTest.java b/liquibase-dialect/src/test/java/tech/ydb/liquibase/YdbDatabaseDecimalTest.java new file mode 100644 index 00000000..ee80abaa --- /dev/null +++ b/liquibase-dialect/src/test/java/tech/ydb/liquibase/YdbDatabaseDecimalTest.java @@ -0,0 +1,105 @@ +package tech.ydb.liquibase; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.LinkedHashMap; +import java.util.Map; +import liquibase.Contexts; +import liquibase.Liquibase; +import liquibase.command.CommandScope; +import liquibase.database.jvm.JdbcConnection; +import liquibase.resource.DirectoryResourceAccessor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class YdbDatabaseDecimalTest extends BaseTest { + + @Test + void migrateLoadAndRegenerateParameterizedDecimals(@TempDir Path tempDir) throws Exception { + migrateChangeFile("./changelogs/decimal.xml"); + + try (Connection connection = DriverManager.getConnection(jdbcUrl())) { + assertDecimalTypes(connection); + try (Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT * FROM decimal_values ORDER BY id")) { + for (int id = 1; id <= 5; id++) { + assertTrue(rows.next()); + assertEquals(id, rows.getInt("id")); + if (id == 4) { + assertNull(rows.getBigDecimal("amount")); + assertNull(rows.getBigDecimal("whole_amount")); + assertNull(rows.getBigDecimal("fraction")); + assertNull(rows.getBigDecimal("default_amount")); + assertNull(rows.getBigDecimal("small_amount")); + assertNull(rows.getBigDecimal("precision_only")); + } else { + String sign = id == 2 || id == 3 ? "-" : ""; + assertEquals(new BigDecimal(sign + "1234567890123456789012345.1234567890"), + rows.getBigDecimal("amount")); + assertEquals(new BigDecimal(sign + "12345678901234567890123456789012345"), + rows.getBigDecimal("whole_amount")); + assertEquals(new BigDecimal(sign + "0.12345678901234567890123456789012345"), + rows.getBigDecimal("fraction")); + assertEquals(new BigDecimal(sign + "1234567890123.123456789"), + rows.getBigDecimal("default_amount")); + assertEquals(new BigDecimal(sign + "9"), rows.getBigDecimal("small_amount")); + assertEquals(new BigDecimal(sign + "1234567890"), rows.getBigDecimal("precision_only")); + } + } + assertFalse(rows.next()); + } + } + + Path changelogFile = tempDir.resolve("decimal-generated.xml"); + new CommandScope("generateChangelog") + .addArgumentValue("url", jdbcUrl()) + .addArgumentValue("changelogFile", changelogFile.toString()) + .addArgumentValue("includeObjects", "table:decimal_values") + .execute(); + String changelog = new String(Files.readAllBytes(changelogFile), StandardCharsets.UTF_8); + assertTrue(changelog.contains("type=\"DECIMAL(35,10)\"")); + assertTrue(changelog.contains("type=\"DECIMAL(35,0)\"")); + assertTrue(changelog.contains("type=\"DECIMAL(35,35)\"")); + assertTrue(changelog.contains("type=\"DECIMAL(22,9)\"")); + assertTrue(changelog.contains("type=\"DECIMAL(1,0)\"")); + assertTrue(changelog.contains("type=\"DECIMAL(10,0)\"")); + + try (Connection connection = DriverManager.getConnection(jdbcUrl()); + Statement statement = connection.createStatement()) { + statement.execute("DROP TABLE decimal_values"); + } + try (Connection connection = DriverManager.getConnection(jdbcUrl()); + DirectoryResourceAccessor accessor = new DirectoryResourceAccessor(tempDir); + Liquibase liquibase = new Liquibase(changelogFile.getFileName().toString(), accessor, + new JdbcConnection(connection))) { + liquibase.update(new Contexts()); + assertDecimalTypes(connection); + } + } + + private static void assertDecimalTypes(Connection connection) throws Exception { + Map types = new LinkedHashMap<>(); + try (ResultSet columns = connection.getMetaData().getColumns(null, null, "decimal_values", null)) { + while (columns.next()) { + types.put(columns.getString("COLUMN_NAME"), columns.getString("TYPE_NAME")); + } + } + assertEquals("Decimal(35, 10)", types.get("amount")); + assertEquals("Decimal(35, 0)", types.get("whole_amount")); + assertEquals("Decimal(35, 35)", types.get("fraction")); + assertEquals("Decimal(22, 9)", types.get("default_amount")); + assertEquals("Decimal(1, 0)", types.get("small_amount")); + assertEquals("Decimal(10, 0)", types.get("precision_only")); + } +} diff --git a/liquibase-dialect/src/test/resources/changelogs/csv/decimal-insert.csv b/liquibase-dialect/src/test/resources/changelogs/csv/decimal-insert.csv new file mode 100644 index 00000000..be2398de --- /dev/null +++ b/liquibase-dialect/src/test/resources/changelogs/csv/decimal-insert.csv @@ -0,0 +1,3 @@ +id,amount,whole_amount,fraction,default_amount,small_amount,precision_only +3,1234567890123456789012345.1234567890,12345678901234567890123456789012345,0.12345678901234567890123456789012345,1234567890123.123456789,9,1234567890 +4,null,null,null,null,null,null diff --git a/liquibase-dialect/src/test/resources/changelogs/csv/decimal-upsert.csv b/liquibase-dialect/src/test/resources/changelogs/csv/decimal-upsert.csv new file mode 100644 index 00000000..2df3a0e0 --- /dev/null +++ b/liquibase-dialect/src/test/resources/changelogs/csv/decimal-upsert.csv @@ -0,0 +1,3 @@ +id,amount,whole_amount,fraction,default_amount,small_amount,precision_only +3,-1234567890123456789012345.1234567890,-12345678901234567890123456789012345,-0.12345678901234567890123456789012345,-1234567890123.123456789,-9,-1234567890 +5,1234567890123456789012345.1234567890,12345678901234567890123456789012345,0.12345678901234567890123456789012345,1234567890123.123456789,9,1234567890 diff --git a/liquibase-dialect/src/test/resources/changelogs/decimal.xml b/liquibase-dialect/src/test/resources/changelogs/decimal.xml new file mode 100644 index 00000000..935be619 --- /dev/null +++ b/liquibase-dialect/src/test/resources/changelogs/decimal.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +