Skip to content
Open
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
7 changes: 7 additions & 0 deletions spring-data-r2dbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,13 @@

<!-- R2DBC Drivers -->

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>r2dbc-postgresql</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,25 @@
*/
package org.springframework.data.r2dbc.dialect;

import org.h2.api.Interval;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.relational.core.dialect.ArrayColumns;
import org.springframework.data.relational.core.dialect.ObjectArrayColumns;
import org.springframework.data.relational.core.sql.SqlIdentifier;
import org.springframework.data.util.Lazy;
import org.springframework.r2dbc.core.binding.BindMarkersFactory;
import org.springframework.util.ClassUtils;

/**
* R2DBC dialect for H2.
Expand All @@ -28,19 +42,63 @@
* @author Jens Schauder
* @author Diego Krupitza
* @author Kurt Niemi
* @author YeongJae Min
*/
public class H2Dialect extends org.springframework.data.relational.core.dialect.H2Dialect implements R2dbcDialect {

private static final Set<Class<?>> SIMPLE_TYPES;

private static final boolean H2_INTERVAL_PRESENT = ClassUtils.isPresent("org.h2.api.Interval",
H2Dialect.class.getClassLoader());

static {

Set<Class<?>> simpleTypes = new HashSet<>(
org.springframework.data.relational.core.dialect.H2Dialect.INSTANCE.simpleTypes());

// conditional H2 Interval support.
ifClassPresent("org.h2.api.Interval", simpleTypes::add);

SIMPLE_TYPES = simpleTypes;
}

/**
* Singleton instance.
*/
public static final H2Dialect INSTANCE = new H2Dialect();

private static final BindMarkersFactory INDEXED = BindMarkersFactory.indexed("$", 1);

private static final List<Object> CONVERTERS = List.copyOf(createConverters());

private final Lazy<ArrayColumns> arrayColumns = Lazy
.of(() -> new SimpleTypeArrayColumns(ObjectArrayColumns.INSTANCE, getSimpleTypeHolder()));

private static List<Object> createConverters() {

List<Object> converters = new ArrayList<>();

if (H2_INTERVAL_PRESENT) {
converters.add(H2IntervalToDurationConverter.INSTANCE);
converters.add(DurationToH2IntervalConverter.INSTANCE);
}

return converters;
}

/**
* If the class is present on the class path, invoke the specified consumer {@code action} with the class object,
* otherwise do nothing.
*
* @param action block to be executed if a value is present.
*/
private static void ifClassPresent(String className, Consumer<Class<?>> action) {

if (ClassUtils.isPresent(className, H2Dialect.class.getClassLoader())) {
action.accept(ClassUtils.resolveClassName(className, H2Dialect.class.getClassLoader()));
}
}

@Override
public ArrayColumns getArraySupport() {
return this.arrayColumns.get();
Expand All @@ -56,4 +114,57 @@ public String renderForGeneratedValues(SqlIdentifier identifier) {
return identifier.getReference();
}

@Override
public Collection<Object> getConverters() {
return CONVERTERS;
}

@Override
public Set<Class<?>> simpleTypes() {
return SIMPLE_TYPES;
}

@ReadingConverter
private enum H2IntervalToDurationConverter implements Converter<Interval, Duration> {

INSTANCE;

@Override
public Duration convert(Interval source) {

if (source.getQualifier().isYearMonth()) {
throw new IllegalArgumentException("Year-month intervals cannot be represented as Duration");
}

return Duration.ZERO //
.plusDays(source.getDays()) //
.plusHours(source.getHours()) //
.plusMinutes(source.getMinutes()) //
.plusSeconds(source.getSeconds()) //
.plusNanos(source.getNanosOfSecond());
}
}

@WritingConverter
private enum DurationToH2IntervalConverter implements Converter<Duration, Interval> {

INSTANCE;

private static final int NANOS_PER_SECOND = 1_000_000_000;

@Override
public Interval convert(Duration source) {

long seconds = source.getSeconds();
int nanos = source.getNano();

if (seconds < 0 && nanos > 0) {
seconds++;
nanos -= NANOS_PER_SECOND;
}

return Interval.ofSeconds(seconds, nanos);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@
*/
package org.springframework.data.r2dbc.config;

import static org.assertj.core.api.Assertions.*;

import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.time.Duration;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -28,6 +32,8 @@
import org.springframework.context.annotation.FilterType;
import org.springframework.dao.DataAccessException;
import org.springframework.data.annotation.Id;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.dialect.H2Dialect;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.data.r2dbc.testing.H2TestSupport;
Expand All @@ -42,6 +48,7 @@
* Integration test for {@link DatabaseClient} and repositories using H2.
*
* @author Mark Paluch
* @author YeongJae Min
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
Expand Down Expand Up @@ -85,6 +92,29 @@ void shouldSelectCountWithRepository() {
.verifyComplete();
}

@Test // GH-502
void shouldReadAndWriteDurationAsInterval() {

jdbc.execute("DROP TABLE IF EXISTS \"duration_holder\"");
jdbc.execute("CREATE TABLE \"duration_holder\" (" //
+ "\"ID\" integer PRIMARY KEY," //
+ "\"DURATION\" INTERVAL SECOND(18, 9)" //
+ ")");

DurationHolder durationHolder = new DurationHolder();
durationHolder.id = 1;
durationHolder.duration = Duration.ofSeconds(42, 123_000_000);

R2dbcEntityTemplate template = new R2dbcEntityTemplate(databaseClient, H2Dialect.INSTANCE);

template.insert(durationHolder) //
.thenMany(template.select(org.springframework.data.relational.core.query.Query.empty(),
DurationHolder.class)) //
.as(StepVerifier::create) //
.consumeNextWith(actual -> assertThat(actual.duration).isEqualTo(durationHolder.duration)) //
.verifyComplete();
}

@Configuration
@EnableR2dbcRepositories(considerNestedRepositories = true,
includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = H2Repository.class),
Expand All @@ -109,4 +139,11 @@ static class LegoSet {
String name;
Integer manual;
}

@Table("duration_holder")
static class DurationHolder {

@Id Integer id;
Duration duration;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@

import static org.assertj.core.api.Assertions.*;

import org.h2.api.Interval;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import org.springframework.data.annotation.Id;
import org.springframework.data.r2dbc.dialect.H2Dialect;
import org.springframework.data.r2dbc.mapping.OutboundRow;
import org.springframework.data.r2dbc.testing.OutboundRowAssert;
import org.springframework.data.relational.core.mapping.Embedded;
import org.springframework.data.relational.core.sql.SqlIdentifier;

/**
* Unit tests for {@link DefaultReactiveDataAccessStrategy}.
*
* @author Jens Schauder
* @author YeongJae Min
*/
class DefaultReactiveDataAccessStrategyUnitTests {

Expand All @@ -33,6 +40,15 @@ void shouldReportAllColumns(Fixture fixture) {
.containsExactlyInAnyOrder(sqlIdentifiers.toArray(new SqlIdentifier[0]));
}

@Test // GH-502
void shouldWriteDurationAsH2Interval() {

OutboundRow outboundRow = dataAccessStrategy.getOutboundRow(new WithDuration(Duration.ofMillis(-500)));

OutboundRowAssert.assertThat(outboundRow).withColumn(SqlIdentifier.quoted("DURATION"))
.hasValue(Interval.ofSeconds(0, -500_000_000)).hasType(Interval.class);
}

static Stream<Fixture> fixtures() {
return Stream.of(new Fixture(SimpleEntity.class, "ID", "NAME"),
new Fixture(WithEmbedded.class, "ID", "L1_NAME", "L1_L2_NAME", "L1_L2_NUMBER"),
Expand Down Expand Up @@ -62,4 +78,7 @@ record Level2(String name, Integer number) {
record WithEmbeddedId(@Id @Embedded.Empty(prefix = "ID_") Level2 id, String name) {
}

record WithDuration(Duration duration) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2026-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.r2dbc.dialect;

import static org.assertj.core.api.Assertions.*;

import org.h2.api.Interval;

import java.time.Duration;
import java.util.LinkedHashSet;

import org.junit.jupiter.api.Test;

import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.mapping.model.SimpleTypeHolder;

/**
* Unit tests for {@link H2Dialect}.
*
* @author YeongJae Min
*/
class H2DialectUnitTests {

@Test // GH-502
void shouldConsiderIntervalSimpleType() {

SimpleTypeHolder holder = H2Dialect.INSTANCE.getSimpleTypeHolder();

assertThat(holder.isSimpleType(Interval.class)).isTrue();
}

@Test // GH-502
void shouldConvertDayTimeIntervalToDuration() {

Interval interval = Interval.ofDaysHoursMinutesNanos(1, 2, 3, 4_500_000_000L);
Duration converted = conversionService().convert(interval, Duration.class);

assertThat(converted).isEqualTo(Duration.ofDays(1).plusHours(2).plusMinutes(3).plusSeconds(4)
.plusNanos(500_000_000));
}

@Test // GH-502
void shouldRejectYearMonthIntervalToDurationConversion() {

assertThatThrownBy(() -> conversionService().convert(Interval.ofYearsMonths(1, 2), Duration.class))
.isInstanceOf(ConversionFailedException.class)
.hasRootCauseInstanceOf(IllegalArgumentException.class);
}

@Test // GH-502
void shouldConvertNegativeDurationToInterval() {

Duration duration = Duration.ofMillis(-500);
Interval interval = conversionService().convert(duration, Interval.class);

assertThat(interval).isEqualTo(Interval.ofSeconds(0, -500_000_000));
assertThat(conversionService().convert(interval, Duration.class)).isEqualTo(duration);
}

private static GenericConversionService conversionService() {

GenericConversionService conversionService = new GenericConversionService();
ConversionServiceFactory.registerConverters(new LinkedHashSet<>(H2Dialect.INSTANCE.getConverters()),
conversionService);

return conversionService;
}
}
Loading