001/* 002 * Copyright 2015-2022 Transmogrify LLC, 2022-2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.pyranid; 018 019import org.jspecify.annotations.NonNull; 020import org.jspecify.annotations.Nullable; 021 022import javax.annotation.concurrent.NotThreadSafe; 023import javax.annotation.concurrent.ThreadSafe; 024import java.time.ZoneId; 025import java.util.ArrayList; 026import java.util.Arrays; 027import java.util.Collections; 028import java.util.List; 029import java.util.Objects; 030import java.util.Optional; 031import java.util.Queue; 032import java.util.concurrent.ConcurrentLinkedQueue; 033import java.util.stream.Collectors; 034 035import static java.lang.String.format; 036import static java.util.Objects.requireNonNull; 037 038/** 039 * Data that represents a SQL statement. 040 * 041 * @author <a href="https://www.revetkn.com">Mark Allen</a> 042 * @since 2.0.0 043 */ 044@ThreadSafe 045public final class StatementContext<T> { 046 // Opaque execution-local optimization. The mapper's holder uses weak identities only; it is not context value state. 047 @Nullable 048 private volatile Object schemaSignatureMemo; 049 @NonNull 050 private final Statement statement; 051 @NonNull 052 private final List<@Nullable Object> parameters; 053 @NonNull 054 private final List<@Nullable String> parameterNames; 055 @Nullable 056 private final Class<T> resultSetRowType; 057 @NonNull 058 private final DatabaseType databaseType; 059 @NonNull 060 private final DatabaseDialect databaseDialect; 061 @NonNull 062 private final ZoneId timeZone; 063 @NonNull 064 private final AmbiguousTimestampBindingStrategy ambiguousTimestampBindingStrategy; 065 @NonNull 066 private final ParameterRedactor parameterRedactor; 067 private final boolean batchParameterGroups; 068 @Nullable 069 private final SpiOverrides spiOverrides; 070 @NonNull 071 private final Queue<@NonNull AutoCloseable> cleanupOperations; 072 073 /** 074 * Per-query overrides of the {@link Database}-wide mapping/binding SPIs, carried on the context so 075 * execution internals can resolve them without additional plumbing. Deliberately excluded from 076 * {@link #equals(Object)}/{@link #hashCode()}/{@link #toString()} - overrides are functional 077 * identity, not value identity. 078 */ 079 record SpiOverrides(@Nullable ResultSetMapper resultSetMapper, 080 @Nullable PreparedStatementBinder preparedStatementBinder) {} 081 082 StatementContext(@NonNull Builder builder) { 083 requireNonNull(builder); 084 085 this.statement = builder.statement; 086 this.parameters = builder.parameters == null 087 ? List.of() 088 : Collections.unmodifiableList(new ArrayList<>(builder.parameters)); 089 List<String> names = builder.parameterNames == null ? builder.statement.parameterNames() : builder.parameterNames; 090 int parameterCount = this.parameters.size(); 091 if (builder.batchParameterGroups) 092 parameterCount = this.parameters.isEmpty() || !(this.parameters.get(0) instanceof List<?> group) ? 0 : group.size(); 093 if (names != null) { 094 boolean matches = names.size() == parameterCount; 095 if (builder.batchParameterGroups) 096 for (Object parameterGroup : this.parameters) 097 if (!(parameterGroup instanceof List<?> group) || group.size() != names.size()) 098 matches = false; 099 if (!matches) { 100 if (builder.parameterNames != null) 101 throw new IllegalArgumentException("Parameter names must match the expanded JDBC parameter count of every parameter group"); 102 // A caller may reuse a captured Statement to build a different/manual diagnostic context. 103 // Optional inherited metadata must not make that formerly legal operation fail. 104 names = null; 105 } 106 } 107 this.parameterNames = names == null ? Collections.nCopies(parameterCount, null) 108 : Collections.unmodifiableList(new ArrayList<>(names)); 109 this.resultSetRowType = builder.resultSetRowType; 110 this.databaseType = builder.databaseType; 111 this.databaseDialect = builder.databaseDialect; 112 this.timeZone = builder.timeZone; 113 this.ambiguousTimestampBindingStrategy = builder.ambiguousTimestampBindingStrategy; 114 this.parameterRedactor = builder.parameterRedactor; 115 this.batchParameterGroups = builder.batchParameterGroups; 116 this.spiOverrides = builder.spiOverrides; 117 this.cleanupOperations = new ConcurrentLinkedQueue<>(); 118 } 119 120 @Nullable 121 ResultSetMapper getResultSetMapperOverride() { 122 return this.spiOverrides == null ? null : this.spiOverrides.resultSetMapper(); 123 } 124 125 @Nullable 126 PreparedStatementBinder getPreparedStatementBinderOverride() { 127 return this.spiOverrides == null ? null : this.spiOverrides.preparedStatementBinder(); 128 } 129 130 @Override 131 public int hashCode() { 132 return Objects.hash(getStatement(), getParameters(), getParameterNames(), getResultSetRowType(), getDatabaseType(), getTimeZone(), getAmbiguousTimestampBindingStrategy()); 133 } 134 135 @Override 136 public boolean equals(@Nullable Object object) { 137 if (this == object) 138 return true; 139 140 if (!(object instanceof StatementContext)) 141 return false; 142 143 StatementContext statementContext = (StatementContext) object; 144 145 return Objects.equals(statementContext.getStatement(), getStatement()) 146 && Objects.equals(statementContext.getParameters(), getParameters()) 147 && Objects.equals(statementContext.getParameterNames(), getParameterNames()) 148 && Objects.equals(statementContext.getResultSetRowType(), getResultSetRowType()) 149 && Objects.equals(statementContext.getDatabaseType(), getDatabaseType()) 150 && Objects.equals(statementContext.getTimeZone(), getTimeZone()) 151 && Objects.equals(statementContext.getAmbiguousTimestampBindingStrategy(), getAmbiguousTimestampBindingStrategy()); 152 } 153 154 @Override 155 @NonNull 156 public String toString() { 157 List<String> components = new ArrayList<>(3); 158 159 components.add(format("statement=%s", getStatement())); 160 161 if (getParameters().size() > 0) 162 components.add(format("parameters=%s", getRedactedParameters())); 163 164 Class<T> resultSetRowType = getResultSetRowType().orElse(null); 165 166 if (resultSetRowType != null) 167 components.add(format("resultSetRowType=%s", resultSetRowType)); 168 169 components.add(format("databaseType=%s", getDatabaseType().name())); 170 components.add(format("timeZone=%s", getTimeZone().getId())); 171 components.add(format("ambiguousTimestampBindingStrategy=%s", getAmbiguousTimestampBindingStrategy().name())); 172 173 return format("%s{%s}", getClass().getSimpleName(), components.stream().collect(Collectors.joining(", "))); 174 } 175 176 @NonNull 177 public Statement getStatement() { 178 return this.statement; 179 } 180 181 @NonNull 182 public List<@Nullable Object> getParameters() { 183 return this.parameters; 184 } 185 186 /** 187 * Gets original query binding names, without a leading colon, in expanded JDBC slot order. Repeated bindings and IN-list 188 * elements repeat their name; unknown names are {@code null}. The returned list is immutable. 189 * <p> 190 * For non-batch operations this aligns with {@link #getParameters()}. Batch parameters are grouped 191 * there, while this list describes the slots shared by each group. A batch slot has a {@code null} 192 * name if expansions assigned different original names to that slot across groups. Batch summaries 193 * continue to omit individual values and do not invoke the redactor. 194 * 195 * @return immutable expanded-slot names, with {@code null} for unknown or conflicting names 196 * @since 4.9.0 197 */ 198 @NonNull 199 public List<@Nullable String> getParameterNames() { 200 return this.parameterNames; 201 } 202 203 @Nullable 204 Object schemaSignatureMemo() { 205 return this.schemaSignatureMemo; 206 } 207 208 void schemaSignatureMemo(Object memo) { 209 this.schemaSignatureMemo = memo; 210 } 211 212 /** 213 * Gets this statement's parameters rendered for diagnostics. 214 * <p> 215 * {@link SecureParameter} values render as their masks. Other non-batch values are rendered through the configured 216 * {@link ParameterRedactor}; an empty Optional renders as {@code null} without removing its parameter slot. 217 * A null Optional violates the redactor contract and fails immediately. Batch executions render a bounded summary 218 * instead of individual group values. 219 * 220 * @return parameters rendered for diagnostics 221 * @since 4.4.0 222 */ 223 @NonNull 224 public List<@Nullable Object> getRedactedParameters() { 225 if (this.batchParameterGroups) 226 return List.of(batchParameterSummary()); 227 228 List<@Nullable Object> redactedParameters = new ArrayList<>(getParameters().size()); 229 230 for (int i = 0; i < getParameters().size(); ++i) { 231 Object parameter = getParameters().get(i); 232 SecureParameter secureParameter = SecureParameterSupport.displaySecureParameter(parameter); 233 234 if (secureParameter != null) 235 redactedParameters.add(SecureParameterSupport.maskOf(secureParameter)); 236 else 237 redactedParameters.add(requireNonNull(this.parameterRedactor.redactParameter(this, i, parameter), 238 "ParameterRedactor must return a non-null Optional").orElse(null)); 239 } 240 241 return Collections.unmodifiableList(redactedParameters); 242 } 243 244 @NonNull 245 private String batchParameterSummary() { 246 List<@Nullable Object> parameters = getParameters(); 247 int groupCount = parameters.size(); 248 249 if (groupCount == 0) 250 return "<batch: 0 groups x 0 parameters>"; 251 252 Integer expectedParameterCount = null; 253 boolean mixedParameterCounts = false; 254 255 for (Object parameterGroup : parameters) { 256 int parameterCount = parameterGroup instanceof List<?> list ? list.size() : 0; 257 258 if (expectedParameterCount == null) { 259 expectedParameterCount = parameterCount; 260 } else if (expectedParameterCount != parameterCount) { 261 mixedParameterCounts = true; 262 break; 263 } 264 } 265 266 if (mixedParameterCounts) 267 return format("<batch: %s groups x mixed parameter counts>", groupCount); 268 269 return format("<batch: %s groups x %s parameters>", groupCount, expectedParameterCount); 270 } 271 272 @NonNull 273 public Optional<Class<T>> getResultSetRowType() { 274 return Optional.ofNullable(this.resultSetRowType); 275 } 276 277 /** 278 * Gets the configured database type for this statement. 279 * 280 * @return the configured database type 281 * @since 3.0.0 282 */ 283 @NonNull 284 public DatabaseType getDatabaseType() { 285 return this.databaseType; 286 } 287 288 @NonNull 289 DatabaseDialect getDatabaseDialect() { 290 return this.databaseDialect; 291 } 292 293 @NonNull 294 public ZoneId getTimeZone() { 295 return this.timeZone; 296 } 297 298 /** 299 * How should Pyranid bind {@link java.time.Instant} and {@link java.time.OffsetDateTime} parameters when JDBC 300 * parameter metadata cannot identify whether the target is {@code TIMESTAMP} or {@code TIMESTAMP WITH TIME ZONE}? 301 * 302 * @return behavior to use when timestamp target metadata is unavailable or non-identifying 303 * @since 4.2.0 304 */ 305 @NonNull 306 public AmbiguousTimestampBindingStrategy getAmbiguousTimestampBindingStrategy() { 307 return this.ambiguousTimestampBindingStrategy; 308 } 309 310 void addCleanupOperation(@NonNull AutoCloseable cleanupOperation) { 311 requireNonNull(cleanupOperation); 312 this.cleanupOperations.add(cleanupOperation); 313 } 314 315 @NonNull 316 Queue<@NonNull AutoCloseable> getCleanupOperations() { 317 return this.cleanupOperations; 318 } 319 320 @NonNull 321 public static <T> Builder<T> with(@NonNull Statement statement, 322 @NonNull Database database) { 323 requireNonNull(statement); 324 requireNonNull(database); 325 326 return new Builder<>(statement, database); 327 } 328 329 /** 330 * Builder used to construct instances of {@link StatementContext}. 331 * <p> 332 * This class is intended for use by a single thread. 333 * <p> 334 * A {@link Statement} captured from an execution can carry original binding names, which this builder inherits 335 * when their count matches the supplied parameters. Names are not part of {@code Statement} equality, but 336 * effective names are part of {@code StatementContext} equality. Equal statements can therefore produce unequal 337 * contexts. Supply {@link #parameterNames(List)} to choose the context's names explicitly. 338 * 339 * @author <a href="https://www.revetkn.com">Mark Allen</a> 340 * @since 2.0.0 341 */ 342 @NotThreadSafe 343 public static class Builder<T> { 344 @NonNull 345 private final Statement statement; 346 @NonNull 347 private final DatabaseType databaseType; 348 @NonNull 349 private final DatabaseDialect databaseDialect; 350 @NonNull 351 private final ZoneId timeZone; 352 @NonNull 353 private final AmbiguousTimestampBindingStrategy ambiguousTimestampBindingStrategy; 354 @NonNull 355 private final ParameterRedactor parameterRedactor; 356 @Nullable 357 private List<@Nullable Object> parameters; 358 @Nullable 359 private List<@Nullable String> parameterNames; 360 @Nullable 361 private Class<T> resultSetRowType; 362 private boolean batchParameterGroups; 363 @Nullable 364 private SpiOverrides spiOverrides; 365 366 private Builder(@NonNull Statement statement, 367 @NonNull Database database) { 368 requireNonNull(statement); 369 requireNonNull(database); 370 371 this.statement = statement; 372 this.databaseType = database.getDatabaseType(); 373 this.databaseDialect = database.getDatabaseDialect(); 374 this.timeZone = database.getTimeZone(); 375 this.ambiguousTimestampBindingStrategy = database.getAmbiguousTimestampBindingStrategy(); 376 this.parameterRedactor = database.getParameterRedactor(); 377 } 378 379 @NonNull 380 public Builder parameters(@Nullable List<@Nullable Object> parameters) { 381 this.parameters = parameters; 382 return this; 383 } 384 385 @NonNull 386 public Builder parameters(@Nullable Object @Nullable ... parameters) { 387 this.parameters = parameters == null ? null : Arrays.asList(parameters); 388 return this; 389 } 390 391 /** 392 * Supplies expanded JDBC slot names for a manually built context. The count must match the number of 393 * supplied parameters, and individual unknown names may be {@code null}. Names have no leading colon. 394 * Passing {@code null} inherits compatible query metadata carried by the statement when present; 395 * incompatible or absent inherited names become unknown. An explicit list with an incompatible count 396 * causes {@link #build()} to throw {@link IllegalArgumentException}. The list is copied when built. 397 * 398 * @param parameterNames expanded-slot names, or {@code null} to inherit available metadata 399 * @return this builder 400 * @since 4.9.0 401 */ 402 @NonNull 403 public Builder parameterNames(@Nullable List<@Nullable String> parameterNames) { 404 this.parameterNames = parameterNames; 405 return this; 406 } 407 408 @NonNull 409 public Builder resultSetRowType(@Nullable Class<T> resultSetRowType) { 410 this.resultSetRowType = resultSetRowType; 411 return this; 412 } 413 414 @NonNull 415 Builder batchParameterGroups(boolean batchParameterGroups) { 416 this.batchParameterGroups = batchParameterGroups; 417 return this; 418 } 419 420 @NonNull 421 Builder spiOverrides(@Nullable SpiOverrides spiOverrides) { 422 this.spiOverrides = spiOverrides; 423 return this; 424 } 425 426 /** 427 * Builds a context with snapshots of the supplied parameters and effective binding names. 428 * 429 * @return the new context 430 * @throws IllegalArgumentException if an explicitly supplied non-null name list does not match the 431 * number of supplied parameters 432 */ 433 @NonNull 434 public StatementContext build() { 435 return new StatementContext<>(this); 436 } 437 } 438}