001/* 002 * Copyright 2015-2022 Transmogrify LLC, 2022-2026 Revetware LLC. 003 * Licensed under the Apache License, Version 2.0 (the "License"); 004 * you may not use this file except in compliance with the License. 005 * You may obtain a copy of the License at 006 * https://www.apache.org/licenses/LICENSE-2.0 007 */ 008package com.pyranid; 009 010import org.jspecify.annotations.NonNull; 011import org.jspecify.annotations.Nullable; 012 013import javax.annotation.concurrent.Immutable; 014import java.time.DateTimeException; 015import java.time.Duration; 016import java.time.Period; 017 018import static java.util.Objects.requireNonNull; 019 020/** 021 * An immutable SQL interval with independent calendar-month, calendar-day and elapsed-time components. 022 * Months and days are never converted into a guessed elapsed length, and elapsed hours are never carried 023 * into calendar days. Each component may have its own sign. 024 * <p> 025 * Equality compares these fields exactly: one calendar day differs from 24 elapsed hours, and one month 026 * differs from 30 days. Database interval equality can use different rules. This type has no natural ordering 027 * and does not implement {@code TemporalAmount}: applying calendar fields to a zoned timestamp requires an 028 * explicit application policy, which can differ from the database's daylight-saving resolution. 029 * <p> 030 * Binding and reading depend on the configured database's interval families, precision and range. Column 031 * qualifiers, rounding and other SQL coercions can change the stored fields. 032 * <p> 033 * Oracle and generic drivers need target-family metadata to bind {@link #ZERO}, because the value does not 034 * remember which factory created it. Computed values such as {@code SqlInterval.of(Duration.between(a, a))} 035 * are also {@code ZERO}. Oracle exposes that metadata for direct assignment/comparison with an interval column 036 * and supported explicit interval casts, such as {@code CAST(:value AS INTERVAL DAY TO SECOND)}. Uncast 037 * expressions, {@code MERGE}, PL/SQL blocks and {@code INSERT ... SELECT} can lack identifying metadata; 038 * {@code ZERO} then fails even though nonzero values bind. A cast must select the schema's actual interval 039 * family and is not a universal workaround; PL/SQL can still lack metadata. A {@link CustomParameterBinder} 040 * that handles only {@code ZERO} and returns {@code fallback()} otherwise can choose the family explicitly. 041 * 042 * @since 4.9.0 043 */ 044@Immutable 045public final class SqlInterval { 046 /** The zero interval, without a YEAR-MONTH or DAY-SECOND family preference. */ 047 @NonNull 048 public static final SqlInterval ZERO = new SqlInterval(0, 0, Duration.ZERO); 049 050 private final int months; 051 private final int days; 052 @NonNull 053 private final Duration time; 054 055 private SqlInterval(int months, int days, @NonNull Duration time) { 056 this.months = months; 057 this.days = days; 058 this.time = time; 059 } 060 061 /** 062 * Creates an elapsed-only interval. {@code Duration.ofDays(1)} remains 24 elapsed hours, not a calendar day. 063 * 064 * @param time elapsed time 065 * @return an interval with no calendar components 066 */ 067 @NonNull 068 public static SqlInterval of(@NonNull Duration time) { 069 return of(0, 0, time); 070 } 071 072 /** 073 * Creates a calendar-only interval, folding years into total months while retaining calendar days. 074 * The period's year/month decomposition is not retained. 075 * 076 * @param period calendar period 077 * @return a calendar interval 078 * @throws DateTimeException if total months do not fit a signed 32-bit integer 079 */ 080 @NonNull 081 public static SqlInterval of(@NonNull Period period) { 082 return of(period, Duration.ZERO); 083 } 084 085 /** 086 * Creates an interval from calendar and elapsed components without combining days and hours. 087 * 088 * @param period calendar period, with years folded into total months 089 * @param time elapsed time 090 * @return an interval retaining the independent components 091 * @throws DateTimeException if total months do not fit a signed 32-bit integer 092 */ 093 @NonNull 094 public static SqlInterval of(@NonNull Period period, @NonNull Duration time) { 095 requireNonNull(period); 096 requireNonNull(time); 097 try { 098 return of(Math.toIntExact(period.toTotalMonths()), period.getDays(), time); 099 } catch (ArithmeticException failure) { 100 throw new DateTimeException("SqlInterval total months exceed the signed 32-bit range", failure); 101 } 102 } 103 104 /** 105 * Creates an interval without normalizing its three fields. Precision and database-specific range checks 106 * happen when binding; a value may retain nanoseconds even when a particular database supports only microseconds. 107 * 108 * @param months total calendar months 109 * @param days calendar days 110 * @param time elapsed time 111 * @return an interval retaining all three fields 112 */ 113 @NonNull 114 public static SqlInterval of(@NonNull Integer months, @NonNull Integer days, @NonNull Duration time) { 115 requireNonNull(months); 116 requireNonNull(days); 117 requireNonNull(time); 118 return months == 0 && days == 0 && time.isZero() ? ZERO : new SqlInterval(months, days, time); 119 } 120 121 /** {@return total calendar months, with years already folded in} */ 122 @NonNull 123 public Integer getMonths() { return this.months; } 124 125 /** {@return calendar days, independent of elapsed hours} */ 126 @NonNull 127 public Integer getDays() { return this.days; } 128 129 /** {@return elapsed time, independent of calendar months and days} */ 130 @NonNull 131 public Duration getTime() { return this.time; } 132 133 /** 134 * Returns the elapsed component only when there are no calendar components. Calendar days are deliberately 135 * not assumed to be 24 hours; use {@link Duration#between(java.time.temporal.Temporal, java.time.temporal.Temporal)} 136 * on original instant-compatible timestamps to calculate elapsed time. 137 * 138 * @return elapsed time 139 * @throws DateTimeException if months or days are nonzero 140 */ 141 @NonNull 142 public Duration toDuration() { 143 if (this.months != 0 || this.days != 0) 144 throw new DateTimeException("SqlInterval calendar months and days have no fixed elapsed length; " 145 + "use Duration.between(...) on the original instants"); 146 return this.time; 147 } 148 149 /** 150 * Returns a normalized calendar period only when the elapsed component is zero. Normalization splits total 151 * months into years and months, retaining the day component unchanged. 152 * 153 * @return calendar period 154 * @throws DateTimeException if elapsed time is nonzero 155 */ 156 @NonNull 157 public Period toPeriod() { 158 if (!this.time.isZero()) 159 throw new DateTimeException("SqlInterval elapsed time cannot be converted to a calendar Period"); 160 return Period.of(0, this.months, this.days).normalized(); 161 } 162 163 @Override 164 public boolean equals(@Nullable Object other) { 165 return this == other || other instanceof SqlInterval interval 166 && this.months == interval.months && this.days == interval.days && this.time.equals(interval.time); 167 } 168 169 @Override 170 public int hashCode() { 171 return 31 * (31 * Integer.hashCode(this.months) + Integer.hashCode(this.days)) + this.time.hashCode(); 172 } 173 174 /** 175 * Returns an ISO-style field representation with independent component signs, for example 176 * {@code P14M-3DT4H5M6.789S}. This is a value display, not portable SQL literal syntax. No public parser 177 * or text-storage convention is implied. 178 * 179 * @return a representation retaining all components 180 */ 181 @Override 182 @NonNull 183 public String toString() { 184 if (this.months == 0 && this.days == 0) return this.time.toString(); 185 StringBuilder result = new StringBuilder("P"); 186 if (this.months != 0) result.append(this.months).append('M'); 187 if (this.days != 0) result.append(this.days).append('D'); 188 if (!this.time.isZero()) { 189 String renderedTime = this.time.toString(); 190 result.append(renderedTime, 1, renderedTime.length()); 191 } 192 return result.toString(); 193 } 194}