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 java.time.Duration; 024import java.util.List; 025import java.util.Map; 026import java.util.Optional; 027import java.util.function.Function; 028import java.util.stream.Stream; 029 030/** 031 * Fluent builder for one logical SQL statement. 032 * <p> 033 * This is not a script runner. Driver behavior for multi-statement strings differs; use 034 * {@link Database#useRawConnection(RawConnectionOperation)} with complete, dialect-appropriate commands 035 * or a database migration tool for scripts. 036 * <p> 037 * Obtain instances via {@link Database#query(String)}. 038 * Positional parameters via {@code ?} are not supported; use named parameters (e.g. {@code :id}) and {@link #bind(String, Object)}. 039 * Parameter-looking text inside SQL string literals, quoted identifiers, comments, PostgreSQL dollar-quoted strings, 040 * and SQL Server-style bracket-quoted identifiers is ignored. For DuckDB, brackets are parsed as list/subscript syntax, 041 * so list literals can contain named parameters. PostgreSQL JSONB/hstore {@code ?}, {@code ?|}, and {@code ?&} 042 * operators are supported and are escaped automatically for pgjdbc when the {@link Database} is configured 043 * as PostgreSQL. 044 * <p> 045 * Example usage: 046 * <pre>{@code 047 * // Query returning one row 048 * Optional<Employee> employee = database.query("SELECT * FROM employee WHERE id = :id") 049 * .bind("id", 42) 050 * .fetchObject(Employee.class); 051 * 052 * // Query returning multiple rows 053 * List<Employee> employees = database.query("SELECT * FROM employee WHERE dept = :dept") 054 * .bind("dept", "Engineering") 055 * .fetchList(Employee.class); 056 * 057 * // DML with no result 058 * long rowsAffected = database.query("UPDATE employee SET active = :active WHERE id = :id") 059 * .bind("id", 42) 060 * .bind("active", false) 061 * .execute(); 062 * 063 * // DML with RETURNING clause 064 * Optional<Employee> updated = database.query("UPDATE employee SET salary = :salary WHERE id = :id RETURNING *") 065 * .bind("id", 42) 066 * .bind("salary", new BigDecimal("150000")) 067 * .executeForObject(Employee.class); 068 * }</pre> 069 * <p> 070 * Implementations of this interface are intended for use by a single thread. 071 * 072 * @author <a href="https://www.revetkn.com">Mark Allen</a> 073 * @see Database#query(String) 074 * @since 4.0.0 075 */ 076@NotThreadSafe 077public interface Query { 078 /** 079 * Binds a named parameter to a value. 080 * 081 * @param name the parameter name (without the leading {@code :}) 082 * @param value the value to bind (may be {@code null}). Raw {@link java.util.Collection} and array 083 * values are not expanded; use {@link Parameters#inList(java.util.Collection)}, 084 * {@link Parameters#sqlArrayOf(String, Object[])}, or {@link Parameters#arrayOf(Class, Object)} 085 * as appropriate. 086 * @return this builder, for chaining 087 */ 088 @NonNull 089 Query bind(@NonNull String name, 090 @Nullable Object value); 091 092 /** 093 * Binds all entries from the given map as named parameters. 094 * 095 * @param parameters map of parameter names to values 096 * @return this builder, for chaining 097 */ 098 @NonNull 099 Query bindAll(@NonNull Map<@NonNull String, @Nullable Object> parameters); 100 101 /** 102 * Associates an identifier with this query for logging/diagnostics. 103 * <p> 104 * If not called, a default ID will be generated. 105 * 106 * @param id the identifier 107 * @return this builder, for chaining 108 */ 109 @NonNull 110 Query id(@Nullable Object id); 111 112 /** 113 * Configures the JDBC query timeout for this query. 114 * <p> 115 * This maps to {@link java.sql.Statement#setQueryTimeout(int)}. {@code null} leaves the timeout unset so any 116 * {@link Database.Builder#queryTimeout(Duration)} default applies. {@link Duration#ZERO} disables the JDBC timeout. 117 * Positive sub-second durations are rounded up to one second because JDBC accepts whole seconds. 118 * 119 * @param queryTimeout timeout to apply, or {@code null} to inherit the database default 120 * @return this builder, for chaining 121 * @since 4.2.0 122 */ 123 @NonNull 124 default Query queryTimeout(@Nullable Duration queryTimeout) { 125 throw new UnsupportedOperationException("queryTimeout is not supported by this Query implementation"); 126 } 127 128 /** 129 * Configures the JDBC fetch size for this query. 130 * <p> 131 * This maps to {@link java.sql.Statement#setFetchSize(int)}. {@code null} leaves the fetch size unset so any 132 * {@link Database.Builder#fetchSize(Integer)} default applies. A value of {@code 0} uses the driver's default 133 * fetch-size behavior. 134 * Streaming queries also apply dialect rules: PostgreSQL and MariaDB default to 256 when no fetch size is 135 * configured; MySQL preserves positive hints only when Connector/J cursor fetching is positively enabled, 136 * otherwise retaining row streaming. An explicit per-query zero opts into driver-default behavior, which may buffer. 137 * 138 * @param fetchSize fetch size to apply, or {@code null} to inherit the database default 139 * @return this builder, for chaining 140 * @since 4.2.0 141 */ 142 @NonNull 143 default Query fetchSize(@Nullable Integer fetchSize) { 144 throw new UnsupportedOperationException("fetchSize is not supported by this Query implementation"); 145 } 146 147 /** 148 * Configures the JDBC maximum row count for this query. 149 * <p> 150 * This maps to {@link java.sql.Statement#setMaxRows(int)}. {@code null} leaves the maximum row count unset so any 151 * {@link Database.Builder#maxRows(Integer)} default applies. A value of {@code 0} disables the JDBC row limit. 152 * 153 * @param maxRows maximum rows to apply, or {@code null} to inherit the database default 154 * @return this builder, for chaining 155 * @since 4.2.0 156 */ 157 @NonNull 158 default Query maxRows(@Nullable Integer maxRows) { 159 throw new UnsupportedOperationException("maxRows is not supported by this Query implementation"); 160 } 161 162 /** 163 * Configures the maximum number of parameter groups to send in each JDBC batch execution. 164 * <p> 165 * This setting applies only to {@link #executeBatch(List)}. {@code null} leaves batch execution unchunked, 166 * preserving the default behavior of sending all parameter groups in one JDBC batch. A positive value causes 167 * Pyranid to execute multiple JDBC batches as needed and flatten the returned update counts in input order. If this 168 * setting is specified and a non-batch terminal operation is invoked, Pyranid throws {@link IllegalStateException}. 169 * <p> 170 * Chunking is performed by Pyranid. JDBC drivers still execute each chunk as a normal JDBC batch. 171 * If a later chunk fails outside an explicit transaction, earlier chunks may already be committed depending on 172 * autocommit and driver behavior. Wrap chunked batches in {@link Database#transaction(TransactionalOperation)} when 173 * all-or-nothing behavior is required. 174 * 175 * @param batchChunkSize maximum parameter groups per JDBC batch execution, or {@code null} to execute one batch 176 * @return this builder, for chaining 177 * @throws IllegalArgumentException if {@code batchChunkSize} is less than or equal to {@code 0} 178 * @since 4.2.0 179 */ 180 @NonNull 181 default Query batchChunkSize(@Nullable Integer batchChunkSize) { 182 throw new UnsupportedOperationException("batchChunkSize is not supported by this Query implementation"); 183 } 184 185 /** 186 * Overrides the {@link Database}-wide {@link ResultSetMapper} for this query only. 187 * <p> 188 * This enables per-query inline mapping - for example, projecting an ad-hoc join or computed columns - 189 * without configuring a database-wide mapper. Its generic mapping method requires an implementation 190 * rather than a lambda: <pre>{@code database.query("SELECT name, COUNT(*) AS total FROM employee GROUP BY name") 191 * .resultSetMapper(new ResultSetMapper() { 192 * @Override 193 * public <T> Optional<T> map(StatementContext<T> ctx, ResultSet rs, Class<T> type, 194 * InstanceProvider ip) throws SQLException { 195 * return Optional.of(type.cast(new NameCount(rs.getString(1), rs.getLong(2)))); 196 * } 197 * }) 198 * .fetchList(NameCount.class);}</pre> 199 * The override applies to every row this query maps (including {@link #fetchStream} rows and DML-returning 200 * results). Other queries on the same {@link Database} are unaffected. Metrics, statement logging, and 201 * exception diagnostics behave identically with an override present. 202 * 203 * @param resultSetMapper the mapper to use for this query, or {@code null} to inherit the database-wide mapper 204 * @return this builder, for chaining 205 * @since 4.5.0 206 */ 207 @NonNull 208 default Query resultSetMapper(@Nullable ResultSetMapper resultSetMapper) { 209 throw new UnsupportedOperationException("resultSetMapper is not supported by this Query implementation"); 210 } 211 212 /** 213 * Overrides the {@link Database}-wide {@link PreparedStatementBinder} for this query only. 214 * <p> 215 * The override receives every non-null parameter for this query - including expanded IN-list elements and 216 * each batch group's parameters. As with the database-wide SPI, {@link SecureParameter} and {@link java.util.Optional} 217 * wrappers are unwrapped by Pyranid <em>before</em> the binder is invoked, so custom binders receive bound-ready 218 * raw values and need no unwrap logic. {@code null} parameters never reach the binder; Pyranid binds them via 219 * {@link java.sql.PreparedStatement#setNull(int, int)} even when an override is present. 220 * <p> 221 * Other queries on the same {@link Database} are unaffected. 222 * 223 * @param preparedStatementBinder the binder to use for this query, or {@code null} to inherit the database-wide binder 224 * @return this builder, for chaining 225 * @since 4.5.0 226 */ 227 @NonNull 228 default Query preparedStatementBinder(@Nullable PreparedStatementBinder preparedStatementBinder) { 229 throw new UnsupportedOperationException("preparedStatementBinder is not supported by this Query implementation"); 230 } 231 232 /** 233 * Customizes the {@link java.sql.PreparedStatement} before execution. 234 * <p> 235 * If called multiple times, the most recent customizer wins. The customizer runs after database-wide statement 236 * settings and this query's {@link #queryTimeout(Duration)}, {@link #fetchSize(Integer)}, and 237 * {@link #maxRows(Integer)} settings, so it can override them when needed. It runs before Pyranid binds parameters. 238 * <p> 239 * For dialect-managed streams, Pyranid may apply driver-specific stream settings after this callback 240 * unless this query explicitly configured a fetch size. MySQL may still replace a positive hint with its 241 * row-streaming sentinel unless Connector/J cursor fetching is positively enabled. 242 * <p> 243 * For driver-specific cancellation beyond {@link #queryTimeout(Duration)}, application code may capture the 244 * {@link java.sql.PreparedStatement} here and call {@link java.sql.Statement#cancel()} from its own cancellation path. 245 * Cancellation behavior is JDBC-driver-specific. 246 * 247 * @param preparedStatementCustomizer customization callback 248 * @return this builder, for chaining 249 */ 250 @NonNull 251 Query customize(@NonNull PreparedStatementCustomizer preparedStatementCustomizer); 252 253 /** 254 * Acquires a result type token for fetching rows as insertion-ordered {@code Map<String, Object>} instances, 255 * usable anywhere a result type token is accepted. 256 * <p> 257 * Java's type erasure means there is no {@code Map<String, Object>.class} literal - a raw {@code Map.class} 258 * token can only ever infer the raw {@code Map} type at fetch sites. This method returns the same runtime 259 * {@code Map.class} token, statically typed as {@code Class<Map<String, Object>>} so results are properly 260 * parameterized without caller-side casts: 261 * <pre>{@code List<Map<String, Object>> rows = database.query("SELECT * FROM car") 262 * .fetchList(Query.mapRowType());}</pre> 263 * This is safe because Pyranid's default mapping produces {@code LinkedHashMap<String, Object>} rows for this 264 * token. Note that a custom {@link ResultSetMapper} receiving this token observes the raw {@code Map.class}. 265 * 266 * @return a {@code Map<String, Object>} result type token 267 * @since 4.5.0 268 */ 269 @NonNull 270 @SuppressWarnings("unchecked") 271 static Class<Map<String, Object>> mapRowType() { 272 return (Class<Map<String, Object>>) (Class<?>) Map.class; 273 } 274 275 /** 276 * Executes the query and returns a single result. 277 * 278 * @param resultType the type to marshal each row to 279 * @param <T> the result type 280 * @return the single result, or empty if no rows 281 * @throws DatabaseException if more than one row is returned 282 */ 283 @NonNull 284 <T> Optional<T> fetchObject(@NonNull Class<T> resultType); 285 286 /** 287 * Executes the query and returns all results as a list. 288 * 289 * @param resultType the type to marshal each row to 290 * @param <T> the result type 291 * @return list of results (empty if no rows) 292 */ 293 @NonNull 294 <T> List<@Nullable T> fetchList(@NonNull Class<T> resultType); 295 296 /** 297 * Executes the query and provides a {@link Stream} backed by the underlying {@link java.sql.ResultSet}. 298 * <p> 299 * This approach is useful for processing very large resultsets (e.g. millions of rows), where it's impractical to load all rows into memory at once. 300 * <p> 301 * JDBC resources are closed automatically when {@code streamFunction} returns (or throws), so the stream must be fully consumed 302 * within that callback. Do not escape the stream from the function. 303 * <p> 304 * The stream must be consumed within the scope of the transaction or connection that created it. 305 * If the stream participates in a Pyranid transaction, it must also be closed by the thread that opened it. 306 * <p> 307 * PostgreSQL streams default to a fetch size of 256 inside and outside Pyranid transactions. Outside a transaction, 308 * Pyranid temporarily disables autocommit to enable cursor fetching. MariaDB uses forward-only/read-only statements 309 * and a default fetch size of 256. MySQL uses row streaming unless a positive hint and Connector/J's 310 * {@code useCursorFetch=true} enable cursor fetching. Opaque wrappers retain row streaming when cursor mode 311 * cannot be established. Explicit per-query {@code fetchSize(0)} requests the driver default, which may buffer. A database-wide zero 312 * still receives the dialect streaming default. 313 * Fully consume or close a MySQL/MariaDB stream before another statement uses the same connection; early close 314 * may drain remaining rows. Streams bound driver buffering, but collecting the entire result still retains all values. 315 * 316 * @param resultType the type to marshal each row to 317 * @param streamFunction function that consumes the stream and returns a result 318 * @param <T> the result type 319 * @param <R> the return type 320 * @return the value returned by {@code streamFunction} 321 */ 322 @Nullable 323 <T, R> R fetchStream(@NonNull Class<T> resultType, 324 @NonNull Function<Stream<@Nullable T>, R> streamFunction); 325 326 327 /** 328 * Executes a DML statement (INSERT, UPDATE, DELETE) with no resultset. 329 * 330 * @return the driver's affected-row count, which may be negative when the driver supplies no count 331 */ 332 @NonNull 333 Long execute(); 334 335 /** 336 * Executes a DML statement and maps a single JDBC-generated key row. 337 * <p> 338 * This uses JDBC {@link java.sql.Statement#RETURN_GENERATED_KEYS}. It is intended for database-generated values such 339 * as identity/auto-increment primary keys. If your SQL returns rows directly via database syntax such as PostgreSQL 340 * {@code RETURNING} or SQL Server {@code OUTPUT}, use {@link #executeForObject(Class)} instead. 341 * <p> 342 * With its default settings, MariaDB Connector/J returns only the first generated ID for one multi-row 343 * {@code INSERT}. Receiving one generated-key row therefore does not establish that only one row was inserted. 344 * To retrieve every inserted ID on MariaDB, use {@code INSERT ... RETURNING} with {@link #executeForList(Class)}. 345 * Explicit key column names do not change this default driver behavior. 346 * <p> 347 * For SQL Server multi-row identity inserts, use {@code OUTPUT} with {@link #executeForList(Class)} instead of JDBC 348 * generated keys. MySQL {@code INSERT ... ON DUPLICATE KEY UPDATE} can produce extra JDBC-generated key rows 349 * derived from the affected-row count, even with {@code id = LAST_INSERT_ID(id)}. A single-key call can therefore 350 * throw after the update has executed, while a multiple-key call can include IDs of rows that were not changed. 351 * For a single-row upsert, use {@link #execute()} with {@code id = LAST_INSERT_ID(id)} in the update clause, then 352 * immediately query {@code SELECT LAST_INSERT_ID()} in the same {@link Database#transaction(ReturningTransactionalOperation)} 353 * callback so both statements use one connection. See the 354 * <a href="https://www.pyranid.com/docs/database-specific-recipes#retrieve-the-id-from-a-my-sql-upsert">MySQL upsert recipe</a>. 355 * <p> 356 * Oracle requires explicit generated-key column names; use {@link #executeReturningGeneratedKey(Class, String...)} 357 * instead. 358 * 359 * @param resultType the type to marshal the generated-key row to 360 * @param <T> the result type 361 * @return the single generated key row, or empty if the driver returns no generated keys 362 * @throws DatabaseException if more than one generated-key row is returned 363 * @since 4.2.0 364 */ 365 @NonNull 366 default <T> Optional<T> executeReturningGeneratedKey(@NonNull Class<T> resultType) { 367 throw new UnsupportedOperationException("executeReturningGeneratedKey is not supported by this Query implementation"); 368 } 369 370 /** 371 * Executes a DML statement and maps a single JDBC-generated key row. 372 * <p> 373 * This uses JDBC {@link java.sql.Connection#prepareStatement(String, String[])} with the supplied key column names. 374 * Some drivers require column names to return generated keys for specific columns, especially when more than one 375 * generated value is available. If {@code keyColumnNames} is empty, this behaves like 376 * {@link #executeReturningGeneratedKey(Class)}, except for dialects such as Oracle which require explicit names. 377 * <p> 378 * With its default settings, MariaDB Connector/J returns only the first generated ID for one multi-row 379 * {@code INSERT}. Receiving one generated-key row therefore does not establish that only one row was inserted. 380 * To retrieve every inserted ID on MariaDB, use {@code INSERT ... RETURNING} with {@link #executeForList(Class)}. 381 * Explicit key column names do not change this default driver behavior. 382 * <p> 383 * For SQL Server multi-row identity inserts, use {@code OUTPUT} with {@link #executeForList(Class)} instead of JDBC 384 * generated keys. MySQL {@code INSERT ... ON DUPLICATE KEY UPDATE} can produce extra JDBC-generated key rows 385 * derived from the affected-row count, even with {@code id = LAST_INSERT_ID(id)}. A single-key call can therefore 386 * throw after the update has executed, while a multiple-key call can include IDs of rows that were not changed. 387 * For a single-row upsert, use {@link #execute()} with {@code id = LAST_INSERT_ID(id)} in the update clause, then 388 * immediately query {@code SELECT LAST_INSERT_ID()} in the same {@link Database#transaction(ReturningTransactionalOperation)} 389 * callback so both statements use one connection. See the 390 * <a href="https://www.pyranid.com/docs/database-specific-recipes#retrieve-the-id-from-a-my-sql-upsert">MySQL upsert recipe</a>. 391 * 392 * @param resultType the type to marshal the generated-key row to 393 * @param keyColumnNames generated-key column names requested from the driver 394 * @param <T> the result type 395 * @return the single generated key row, or empty if the driver returns no generated keys 396 * @throws DatabaseException if more than one generated-key row is returned 397 * @since 4.2.0 398 */ 399 @NonNull 400 default <T> Optional<T> executeReturningGeneratedKey(@NonNull Class<T> resultType, 401 @NonNull String @NonNull ... keyColumnNames) { 402 throw new UnsupportedOperationException("executeReturningGeneratedKey is not supported by this Query implementation"); 403 } 404 405 /** 406 * Executes a DML statement and maps all JDBC-generated key rows. 407 * <p> 408 * This uses JDBC {@link java.sql.Statement#RETURN_GENERATED_KEYS}. It is intended for database-generated values such 409 * as identity/auto-increment primary keys. If your SQL returns rows directly via database syntax such as PostgreSQL 410 * {@code RETURNING} or SQL Server {@code OUTPUT}, use {@link #executeForList(Class)} instead. 411 * <p> 412 * With its default settings, MariaDB Connector/J returns only the first generated ID for one multi-row 413 * {@code INSERT}. Receiving one generated-key row therefore does not establish that only one row was inserted. 414 * To retrieve every inserted ID on MariaDB, use {@code INSERT ... RETURNING} with {@link #executeForList(Class)}. 415 * Explicit key column names do not change this default driver behavior. 416 * <p> 417 * For SQL Server multi-row identity inserts, use {@code OUTPUT} with {@link #executeForList(Class)} instead of JDBC 418 * generated keys. MySQL {@code INSERT ... ON DUPLICATE KEY UPDATE} can produce extra JDBC-generated key rows 419 * derived from the affected-row count, even with {@code id = LAST_INSERT_ID(id)}. A single-key call can therefore 420 * throw after the update has executed, while a multiple-key call can include IDs of rows that were not changed. 421 * For a single-row upsert, use {@link #execute()} with {@code id = LAST_INSERT_ID(id)} in the update clause, then 422 * immediately query {@code SELECT LAST_INSERT_ID()} in the same {@link Database#transaction(ReturningTransactionalOperation)} 423 * callback so both statements use one connection. See the 424 * <a href="https://www.pyranid.com/docs/database-specific-recipes#retrieve-the-id-from-a-my-sql-upsert">MySQL upsert recipe</a>. 425 * <p> 426 * Oracle requires explicit generated-key column names; use {@link #executeReturningGeneratedKeys(Class, String...)} 427 * instead. 428 * 429 * @param resultType the type to marshal each generated-key row to 430 * @param <T> the result type 431 * @return list of generated key rows 432 * @since 4.2.0 433 */ 434 @NonNull 435 default <T> List<@Nullable T> executeReturningGeneratedKeys(@NonNull Class<T> resultType) { 436 throw new UnsupportedOperationException("executeReturningGeneratedKeys is not supported by this Query implementation"); 437 } 438 439 /** 440 * Executes a DML statement and maps all JDBC-generated key rows. 441 * <p> 442 * This uses JDBC {@link java.sql.Connection#prepareStatement(String, String[])} with the supplied key column names. 443 * Some drivers require column names to return generated keys for specific columns, especially when more than one 444 * generated value is available. If {@code keyColumnNames} is empty, this behaves like 445 * {@link #executeReturningGeneratedKeys(Class)}, except for dialects such as Oracle which require explicit names. 446 * <p> 447 * With its default settings, MariaDB Connector/J returns only the first generated ID for one multi-row 448 * {@code INSERT}. Receiving one generated-key row therefore does not establish that only one row was inserted. 449 * To retrieve every inserted ID on MariaDB, use {@code INSERT ... RETURNING} with {@link #executeForList(Class)}. 450 * Explicit key column names do not change this default driver behavior. 451 * <p> 452 * For SQL Server multi-row identity inserts, use {@code OUTPUT} with {@link #executeForList(Class)} instead of JDBC 453 * generated keys. MySQL {@code INSERT ... ON DUPLICATE KEY UPDATE} can produce extra JDBC-generated key rows 454 * derived from the affected-row count, even with {@code id = LAST_INSERT_ID(id)}. A single-key call can therefore 455 * throw after the update has executed, while a multiple-key call can include IDs of rows that were not changed. 456 * For a single-row upsert, use {@link #execute()} with {@code id = LAST_INSERT_ID(id)} in the update clause, then 457 * immediately query {@code SELECT LAST_INSERT_ID()} in the same {@link Database#transaction(ReturningTransactionalOperation)} 458 * callback so both statements use one connection. See the 459 * <a href="https://www.pyranid.com/docs/database-specific-recipes#retrieve-the-id-from-a-my-sql-upsert">MySQL upsert recipe</a>. 460 * 461 * @param resultType the type to marshal each generated-key row to 462 * @param keyColumnNames generated-key column names requested from the driver 463 * @param <T> the result type 464 * @return list of generated key rows 465 * @since 4.2.0 466 */ 467 @NonNull 468 default <T> List<@Nullable T> executeReturningGeneratedKeys(@NonNull Class<T> resultType, 469 @NonNull String @NonNull ... keyColumnNames) { 470 throw new UnsupportedOperationException("executeReturningGeneratedKeys is not supported by this Query implementation"); 471 } 472 473 /** 474 * Executes a DML statement in batch over groups of named parameters. 475 * <p> 476 * Any parameters already bound on this {@code Query} apply to all groups; group values override them. 477 * Each group must provide a complete set of parameter values after merging; groups must be non-null and 478 * expand to the same number of JDBC parameters (for example, IN-list sizes must match). 479 * Batch statements must not return result rows, including through {@code RETURNING} or {@code OUTPUT}. 480 * To collect IDs from a multi-row insert, use a single returning statement with {@link #executeForList(Class)}, 481 * or perform a JDBC generated-key batch inside {@link Database#useRawConnection(RawConnectionOperation)}. 482 * This method returns update counts, not generated keys. 483 * 484 * @param parameterGroups groups of named parameter values (without the leading {@code :}) 485 * @return the number of rows affected by the SQL statement per-group 486 */ 487 @NonNull 488 List<Long> executeBatch(@NonNull List<@NonNull Map<@NonNull String, @Nullable Object>> parameterGroups); 489 490 /** 491 * Executes a DML statement that returns a single row (for example, with PostgreSQL/SQLite {@code RETURNING}, 492 * MariaDB {@code INSERT ... RETURNING}, or SQL Server {@code OUTPUT}). 493 * 494 * @param resultType the type to marshal the row to 495 * @param <T> the result type 496 * @return the single result, or empty if no rows 497 * @throws DatabaseException if more than one row is returned 498 */ 499 @NonNull 500 <T> Optional<T> executeForObject(@NonNull Class<T> resultType); 501 502 /** 503 * Executes a DML statement that returns multiple rows (for example, with PostgreSQL/SQLite {@code RETURNING}, 504 * MariaDB {@code INSERT ... RETURNING}, or SQL Server {@code OUTPUT}). 505 * 506 * @param resultType the type to marshal each row to 507 * @param <T> the result type 508 * @return list of results 509 */ 510 @NonNull 511 <T> List<@Nullable T> executeForList(@NonNull Class<T> resultType); 512}