or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bean-override-framework.mdindex.mdjdbc-testing.mdjunit-integration.mdmock-objects.mdtestcontext-framework.mdtesting-annotations.mdweb-testing.md

jdbc-testing.mddocs/

0

# JDBC Testing Support

1

2

Spring Test provides comprehensive database testing utilities including SQL script execution, JDBC test utilities, and transaction management for data-driven testing scenarios. These features enable developers to test database-dependent code with proper data setup and cleanup.

3

4

## Capabilities

5

6

### SQL Script Execution

7

8

Annotations and utilities for executing SQL scripts during test execution.

9

10

```java { .api }

11

/**

12

* @Sql is used to annotate a test class or test method to configure SQL scripts

13

* to be executed during integration tests.

14

*/

15

@Target({ElementType.TYPE, ElementType.METHOD})

16

@Retention(RetentionPolicy.RUNTIME)

17

@Documented

18

@Inherited

19

@Repeatable(SqlGroup.class)

20

public @interface Sql {

21

22

/**

23

* Alias for scripts().

24

* @return an array of SQL script resource paths

25

*/

26

@AliasFor("scripts")

27

String[] value() default {};

28

29

/**

30

* The paths to the SQL scripts to execute.

31

* @return an array of SQL script resource paths

32

*/

33

@AliasFor("value")

34

String[] scripts() default {};

35

36

/**

37

* Inline SQL statements to execute.

38

* @return an array of SQL statements

39

*/

40

String[] statements() default {};

41

42

/**

43

* When the SQL scripts and statements should be executed.

44

* @return the execution phase

45

*/

46

ExecutionPhase executionPhase() default ExecutionPhase.BEFORE_TEST_METHOD;

47

48

/**

49

* Configuration for the SQL scripts.

50

* @return the SqlConfig annotation

51

*/

52

SqlConfig config() default @SqlConfig;

53

54

/**

55

* Enumeration of phases that dictate when SQL scripts are executed.

56

*/

57

enum ExecutionPhase {

58

59

/**

60

* The configured SQL scripts and statements will be executed before the corresponding test method.

61

*/

62

BEFORE_TEST_METHOD,

63

64

/**

65

* The configured SQL scripts and statements will be executed after the corresponding test method.

66

*/

67

AFTER_TEST_METHOD,

68

69

/**

70

* The configured SQL scripts and statements will be executed before the corresponding test class.

71

*/

72

BEFORE_TEST_CLASS,

73

74

/**

75

* The configured SQL scripts and statements will be executed after the corresponding test class.

76

*/

77

AFTER_TEST_CLASS

78

}

79

}

80

81

/**

82

* @SqlConfig defines metadata that is used to determine how to parse and execute

83

* SQL scripts configured via @Sql.

84

*/

85

@Target({})

86

@Retention(RetentionPolicy.RUNTIME)

87

@Documented

88

public @interface SqlConfig {

89

90

/**

91

* The bean name of the DataSource against which the scripts should be executed.

92

* @return the DataSource bean name

93

*/

94

String dataSource() default "";

95

96

/**

97

* The bean name of the PlatformTransactionManager that should be used to drive transactions.

98

* @return the transaction manager bean name

99

*/

100

String transactionManager() default "";

101

102

/**

103

* The mode to use when determining whether SQL scripts should be executed within a transaction.

104

* @return the transaction mode

105

*/

106

TransactionMode transactionMode() default TransactionMode.DEFAULT;

107

108

/**

109

* The encoding for the supplied SQL scripts, if different from the platform encoding.

110

* @return the script encoding

111

*/

112

String encoding() default "";

113

114

/**

115

* The character string used to separate individual statements within each script.

116

* @return the statement separator

117

*/

118

String separator() default ScriptUtils.DEFAULT_STATEMENT_SEPARATOR;

119

120

/**

121

* The prefix that identifies single-line comments within the SQL scripts.

122

* @return the comment prefix

123

*/

124

String commentPrefix() default ScriptUtils.DEFAULT_COMMENT_PREFIX;

125

126

/**

127

* The start delimiter that identifies block comments within the SQL scripts.

128

* @return the block comment start delimiter

129

*/

130

String blockCommentStartDelimiter() default ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER;

131

132

/**

133

* The end delimiter that identifies block comments within the SQL scripts.

134

* @return the block comment end delimiter

135

*/

136

String blockCommentEndDelimiter() default ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER;

137

138

/**

139

* The error mode to use when an error is encountered executing a SQL script.

140

* @return the error mode

141

*/

142

ErrorMode errorMode() default ErrorMode.DEFAULT;

143

144

/**

145

* Enumeration of transaction modes for executing SQL scripts.

146

*/

147

enum TransactionMode {

148

149

/**

150

* Use the default transaction mode: execute scripts in a transaction if a transaction manager is available.

151

*/

152

DEFAULT,

153

154

/**

155

* Execute scripts in isolated transactions that will be immediately committed.

156

*/

157

ISOLATED,

158

159

/**

160

* Execute scripts without a transaction.

161

*/

162

INFERRED

163

}

164

165

/**

166

* Enumeration of error modes for SQL script execution.

167

*/

168

enum ErrorMode {

169

170

/**

171

* Use the default error mode: fail fast and abort further processing on error.

172

*/

173

DEFAULT,

174

175

/**

176

* Ignore failed SQL statements and continue processing.

177

*/

178

IGNORE_FAILED_DROPS,

179

180

/**

181

* Continue processing and log failed SQL statements.

182

*/

183

CONTINUE_ON_ERROR,

184

185

/**

186

* Fail fast and abort further processing on error.

187

*/

188

FAIL_ON_ERROR

189

}

190

}

191

192

/**

193

* @SqlGroup is a container annotation that aggregates several @Sql annotations.

194

*/

195

@Target({ElementType.TYPE, ElementType.METHOD})

196

@Retention(RetentionPolicy.RUNTIME)

197

@Documented

198

@Inherited

199

public @interface SqlGroup {

200

201

/**

202

* An array of @Sql annotations.

203

* @return the array of @Sql annotations

204

*/

205

Sql[] value();

206

}

207

208

/**

209

* @SqlMergeMode is used to annotate a test class to configure whether method-level

210

* @Sql declarations are merged with class-level @Sql declarations.

211

*/

212

@Target(ElementType.TYPE)

213

@Retention(RetentionPolicy.RUNTIME)

214

@Documented

215

@Inherited

216

public @interface SqlMergeMode {

217

218

/**

219

* The merge mode to use.

220

* @return the merge mode

221

*/

222

MergeMode value();

223

224

/**

225

* Enumeration of modes that dictate whether method-level @Sql annotations should be merged with class-level @Sql annotations.

226

*/

227

enum MergeMode {

228

229

/**

230

* Method-level @Sql annotations will be merged with class-level @Sql annotations.

231

*/

232

MERGE,

233

234

/**

235

* Method-level @Sql annotations will override class-level @Sql annotations.

236

*/

237

OVERRIDE

238

}

239

}

240

```

241

242

### JDBC Test Utilities

243

244

Utility class providing convenience methods for common database testing operations.

245

246

```java { .api }

247

/**

248

* JdbcTestUtils is a collection of JDBC related utility functions

249

* intended to simplify standard database testing scenarios.

250

*/

251

public abstract class JdbcTestUtils {

252

253

/**

254

* Count the rows in the given table.

255

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

256

* @param tableName name of the table to count rows in

257

* @return the number of rows in the table

258

*/

259

public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName);

260

261

/**

262

* Count the rows in the given table, using the provided WHERE clause.

263

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

264

* @param tableName name of the table to count rows in

265

* @param whereClause the WHERE clause to append to the query

266

* @return the number of rows in the table that match the provided WHERE clause

267

*/

268

public static int countRowsInTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause);

269

270

/**

271

* Delete all rows from the specified tables.

272

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

273

* @param tableNames the names of the tables from which to delete

274

* @return the total number of rows deleted from all specified tables

275

*/

276

public static int deleteFromTables(JdbcTemplate jdbcTemplate, String... tableNames);

277

278

/**

279

* Delete rows from the given table, using the provided WHERE clause.

280

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

281

* @param tableName the name of the table from which to delete

282

* @param whereClause the WHERE clause to append to the query

283

* @return the number of rows deleted from the table

284

*/

285

public static int deleteFromTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause);

286

287

/**

288

* Drop the specified tables.

289

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

290

* @param tableNames the names of the tables to drop

291

*/

292

public static void dropTables(JdbcTemplate jdbcTemplate, String... tableNames);

293

294

/**

295

* Execute the given SQL script.

296

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

297

* @param resource the resource (potentially associated with a specific encoding) to load the SQL script from

298

* @param continueOnError whether or not to continue without throwing an exception in the event of an error

299

* @throws DataAccessException if there is an error executing a statement and continueOnError was false

300

*/

301

public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError)

302

throws DataAccessException;

303

304

/**

305

* Execute the given SQL script using default settings for statement separators,

306

* comment delimiters, and exception handling flags.

307

* @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations

308

* @param resource the resource (potentially associated with a specific encoding) to load the SQL script from

309

* @throws DataAccessException if there is an error executing a statement

310

*/

311

public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource) throws DataAccessException;

312

313

/**

314

* Read the given SQL script and return its contents as a String.

315

* @param resource the resource to load the SQL script from

316

* @return the contents of the SQL script

317

* @throws IOException if there is an error reading from the resource

318

*/

319

public static String readScript(Resource resource) throws IOException;

320

321

/**

322

* Read the given SQL script using the specified character encoding and return its contents as a String.

323

* @param resource the resource to load the SQL script from

324

* @param encoding the encoding to use when reading the script

325

* @return the contents of the SQL script

326

* @throws IOException if there is an error reading from the resource

327

*/

328

public static String readScript(Resource resource, @Nullable String encoding) throws IOException;

329

330

/**

331

* Determine if the given SQL script contains the specified delimiter.

332

* @param script the SQL script to search

333

* @param delim the delimiter to search for

334

* @return true if the script contains the delimiter

335

*/

336

public static boolean containsSqlScriptDelimiters(String script, String delim);

337

338

/**

339

* Split the given SQL script into separate statements delimited by the provided delimiter character.

340

* @param script the SQL script to split

341

* @param delim the delimiter character

342

* @return an array of individual SQL statements

343

*/

344

public static String[] splitSqlScript(String script, char delim);

345

346

/**

347

* Split the given SQL script into separate statements delimited by the provided delimiter string.

348

* @param script the SQL script to split

349

* @param delim the delimiter string

350

* @return an array of individual SQL statements

351

*/

352

public static String[] splitSqlScript(String script, String delim);

353

}

354

```

355

356

### Database Test Configuration

357

358

Utility classes for configuring embedded databases and test data sources.

359

360

```java { .api }

361

/**

362

* Configuration class for embedded database testing support.

363

*/

364

public class EmbeddedDatabaseBuilder {

365

366

/**

367

* Specify the type of embedded database.

368

* @param databaseType the database type

369

* @return this EmbeddedDatabaseBuilder

370

*/

371

public EmbeddedDatabaseBuilder setType(EmbeddedDatabaseType databaseType);

372

373

/**

374

* Set the name of the embedded database.

375

* @param databaseName the database name

376

* @return this EmbeddedDatabaseBuilder

377

*/

378

public EmbeddedDatabaseBuilder setName(String databaseName);

379

380

/**

381

* Add a SQL script to execute to populate the database.

382

* @param sqlResource the SQL script resource

383

* @return this EmbeddedDatabaseBuilder

384

*/

385

public EmbeddedDatabaseBuilder addScript(String sqlResource);

386

387

/**

388

* Add multiple SQL scripts to execute to populate the database.

389

* @param sqlResources the SQL script resources

390

* @return this EmbeddedDatabaseBuilder

391

*/

392

public EmbeddedDatabaseBuilder addScripts(String... sqlResources);

393

394

/**

395

* Specify a custom script configuration.

396

* @param config the script configuration

397

* @return this EmbeddedDatabaseBuilder

398

*/

399

public EmbeddedDatabaseBuilder setScriptConfiguration(DatabasePopulator config);

400

401

/**

402

* Build the embedded database.

403

* @return the EmbeddedDatabase instance

404

*/

405

public EmbeddedDatabase build();

406

}

407

408

/**

409

* Factory for creating embedded database instances for testing.

410

*/

411

public class EmbeddedDatabaseFactory {

412

413

/**

414

* Set the type of embedded database.

415

* @param databaseType the database type

416

*/

417

public void setDatabaseType(EmbeddedDatabaseType databaseType);

418

419

/**

420

* Set the configuration for populating the database.

421

* @param databasePopulator the database populator

422

*/

423

public void setDatabasePopulator(DatabasePopulator databasePopulator);

424

425

/**

426

* Set the configuration for cleaning up the database.

427

* @param databaseCleaner the database cleaner

428

*/

429

public void setDatabaseCleaner(DatabasePopulator databaseCleaner);

430

431

/**

432

* Factory method to create the embedded database instance.

433

* @return the EmbeddedDatabase

434

*/

435

public EmbeddedDatabase getDatabase();

436

}

437

438

/**

439

* Interface representing an embedded database that can be shut down.

440

*/

441

public interface EmbeddedDatabase extends DataSource {

442

443

/**

444

* Shut down this embedded database.

445

*/

446

void shutdown();

447

}

448

449

/**

450

* Enumeration for the types of embedded databases supported.

451

*/

452

public enum EmbeddedDatabaseType {

453

454

/** The Hypersonic SQL Database Engine */

455

HSQL,

456

457

/** The H2 Database Engine */

458

H2,

459

460

/** The Apache Derby Database */

461

DERBY

462

}

463

```

464

465

**Usage Examples:**

466

467

```java

468

import org.springframework.test.context.jdbc.*;

469

import org.springframework.test.jdbc.JdbcTestUtils;

470

import org.springframework.jdbc.core.JdbcTemplate;

471

472

// Basic SQL script execution

473

@SpringJUnitConfig(DatabaseTestConfig.class)

474

@Transactional

475

class UserRepositoryTest {

476

477

@Autowired

478

private JdbcTemplate jdbcTemplate;

479

480

@Autowired

481

private UserRepository userRepository;

482

483

@Test

484

@Sql("/test-data/users.sql")

485

void shouldFindUserById() {

486

User user = userRepository.findById(1L);

487

assertThat(user.getName()).isEqualTo("John Doe");

488

}

489

490

@Test

491

@Sql(scripts = "/test-data/users.sql",

492

executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)

493

@Sql(scripts = "/test-data/cleanup.sql",

494

executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)

495

void shouldCleanupAfterTest() {

496

// Test with setup and cleanup scripts

497

int initialCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, "users");

498

assertThat(initialCount).isGreaterThan(0);

499

500

userRepository.deleteAll();

501

// Cleanup script will run after test

502

}

503

}

504

505

// Inline SQL statements

506

@SpringJUnitConfig(DatabaseTestConfig.class)

507

@Transactional

508

class InlineSqlTest {

509

510

@Test

511

@Sql(statements = {

512

"INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')",

513

"INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')"

514

})

515

void shouldExecuteInlineStatements() {

516

int userCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, "users");

517

assertThat(userCount).isEqualTo(2);

518

}

519

}

520

521

// Advanced SQL configuration

522

@SpringJUnitConfig(DatabaseTestConfig.class)

523

@Transactional

524

class AdvancedSqlConfigTest {

525

526

@Test

527

@Sql(

528

scripts = "/complex-schema.sql",

529

config = @SqlConfig(

530

dataSource = "testDataSource",

531

transactionManager = "testTransactionManager",

532

transactionMode = SqlConfig.TransactionMode.ISOLATED,

533

encoding = "UTF-8",

534

separator = "@@",

535

commentPrefix = "#",

536

errorMode = SqlConfig.ErrorMode.CONTINUE_ON_ERROR

537

)

538

)

539

void shouldUseCustomSqlConfiguration() {

540

// Test with custom SQL script configuration

541

}

542

}

543

544

// Multiple SQL annotations

545

@SpringJUnitConfig(DatabaseTestConfig.class)

546

@SqlGroup({

547

@Sql(scripts = "/schema.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS),

548

@Sql(scripts = "/lookup-data.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)

549

})

550

class MultipleScriptsTest {

551

552

@Test

553

@Sql("/test-specific-data.sql")

554

void shouldRunWithMultipleScripts() {

555

// Class-level scripts + method-level script

556

}

557

}

558

559

// SQL merge modes

560

@SpringJUnitConfig(DatabaseTestConfig.class)

561

@Sql("/base-data.sql")

562

@SqlMergeMode(SqlMergeMode.MergeMode.MERGE)

563

class MergedSqlTest {

564

565

@Test

566

@Sql("/additional-data.sql")

567

void shouldMergeWithClassLevelSql() {

568

// Both base-data.sql and additional-data.sql will be executed

569

}

570

}

571

572

@SpringJUnitConfig(DatabaseTestConfig.class)

573

@Sql("/base-data.sql")

574

@SqlMergeMode(SqlMergeMode.MergeMode.OVERRIDE)

575

class OverriddenSqlTest {

576

577

@Test

578

@Sql("/replacement-data.sql")

579

void shouldOverrideClassLevelSql() {

580

// Only replacement-data.sql will be executed

581

}

582

}

583

584

// JDBC test utilities usage

585

@SpringJUnitConfig(DatabaseTestConfig.class)

586

@Transactional

587

class JdbcUtilitiesTest {

588

589

@Autowired

590

private JdbcTemplate jdbcTemplate;

591

592

@Test

593

@Sql("/test-data/sample-data.sql")

594

void shouldUseJdbcTestUtils() {

595

// Count rows in tables

596

int totalUsers = JdbcTestUtils.countRowsInTable(jdbcTemplate, "users");

597

int activeUsers = JdbcTestUtils.countRowsInTableWhere(

598

jdbcTemplate, "users", "status = 'ACTIVE'");

599

600

assertThat(totalUsers).isEqualTo(10);

601

assertThat(activeUsers).isEqualTo(7);

602

603

// Delete test data

604

int deletedRows = JdbcTestUtils.deleteFromTableWhere(

605

jdbcTemplate, "users", "created_date < '2023-01-01'");

606

assertThat(deletedRows).isGreaterThan(0);

607

608

// Clean up multiple tables

609

JdbcTestUtils.deleteFromTables(jdbcTemplate, "user_roles", "users", "roles");

610

611

// Verify cleanup

612

assertThat(JdbcTestUtils.countRowsInTable(jdbcTemplate, "users")).isEqualTo(0);

613

}

614

615

@Test

616

void shouldExecuteScriptDirectly() throws Exception {

617

Resource script = new ClassPathResource("/test-data/setup.sql");

618

JdbcTestUtils.executeSqlScript(jdbcTemplate, script, false);

619

620

int rowCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, "products");

621

assertThat(rowCount).isGreaterThan(0);

622

}

623

}

624

625

// Embedded database testing

626

@TestConfiguration

627

class EmbeddedDatabaseTestConfig {

628

629

@Bean

630

@Primary

631

public DataSource dataSource() {

632

return new EmbeddedDatabaseBuilder()

633

.setType(EmbeddedDatabaseType.H2)

634

.setName("testdb")

635

.addScript("classpath:schema.sql")

636

.addScript("classpath:test-data.sql")

637

.build();

638

}

639

640

@Bean

641

public JdbcTemplate jdbcTemplate(DataSource dataSource) {

642

return new JdbcTemplate(dataSource);

643

}

644

}

645

646

@SpringJUnitConfig(EmbeddedDatabaseTestConfig.class)

647

class EmbeddedDatabaseTest {

648

649

@Autowired

650

private DataSource dataSource;

651

652

@Test

653

void shouldUseEmbeddedDatabase() {

654

assertThat(dataSource).isInstanceOf(EmbeddedDatabase.class);

655

656

JdbcTemplate template = new JdbcTemplate(dataSource);

657

int count = JdbcTestUtils.countRowsInTable(template, "users");

658

assertThat(count).isGreaterThan(0);

659

}

660

661

@AfterEach

662

void cleanup() {

663

if (dataSource instanceof EmbeddedDatabase embeddedDb) {

664

embeddedDb.shutdown();

665

}

666

}

667

}

668

```

669

670

## Types

671

672

```java { .api }

673

/**

674

* Strategy interface for populating, initializing, or cleaning up a database.

675

*/

676

public interface DatabasePopulator {

677

678

/**

679

* Populate, initialize, or clean up the database using the provided JDBC connection.

680

* @param connection the JDBC connection to use to access the database

681

* @throws SQLException if an unrecoverable data access exception occurs during database population

682

* @throws ScriptException in all other error cases

683

*/

684

void populate(Connection connection) throws SQLException, ScriptException;

685

}

686

687

/**

688

* Populates, initializes, or cleans up a database using SQL scripts.

689

*/

690

public class ResourceDatabasePopulator implements DatabasePopulator {

691

692

/**

693

* Construct a new ResourceDatabasePopulator with default settings.

694

*/

695

public ResourceDatabasePopulator();

696

697

/**

698

* Construct a new ResourceDatabasePopulator with the supplied scripts.

699

* @param scripts the scripts to execute to populate, initialize, or clean up the database

700

*/

701

public ResourceDatabasePopulator(Resource... scripts);

702

703

/**

704

* Add a script to execute to populate, initialize, or clean up the database.

705

* @param script the script to execute

706

*/

707

public void addScript(Resource script);

708

709

/**

710

* Add multiple scripts to execute to populate, initialize, or clean up the database.

711

* @param scripts the scripts to execute

712

*/

713

public void addScripts(Resource... scripts);

714

715

/**

716

* Specify the character encoding used in the SQL scripts, if different from the platform encoding.

717

* @param sqlScriptEncoding the encoding used in the scripts

718

*/

719

public void setSqlScriptEncoding(@Nullable String sqlScriptEncoding);

720

721

/**

722

* Specify the statement separator in the SQL scripts, typically ";" (semicolon) or "\n" (newline).

723

* @param separator the script statement separator

724

*/

725

public void setSeparator(String separator);

726

727

/**

728

* Set the prefix that identifies single-line comments in the SQL scripts.

729

* @param commentPrefix the prefix for single-line comments

730

*/

731

public void setCommentPrefix(String commentPrefix);

732

733

/**

734

* Set the start delimiter that identifies block comments in the SQL scripts.

735

* @param blockCommentStartDelimiter the start delimiter for block comments

736

*/

737

public void setBlockCommentStartDelimiter(String blockCommentStartDelimiter);

738

739

/**

740

* Set the end delimiter that identifies block comments in the SQL scripts.

741

* @param blockCommentEndDelimiter the end delimiter for block comments

742

*/

743

public void setBlockCommentEndDelimiter(String blockCommentEndDelimiter);

744

745

/**

746

* Flag to indicate that all failures in SQL should be logged but not cause a failure.

747

* @param continueOnError true if script execution should continue on error

748

*/

749

public void setContinueOnError(boolean continueOnError);

750

751

/**

752

* Flag to indicate that failed SQL DROP statements should be ignored.

753

* @param ignoreFailedDrops true if failed DROP statements should be ignored

754

*/

755

public void setIgnoreFailedDrops(boolean ignoreFailedDrops);

756

}

757

758

/**

759

* Thrown when we cannot determine anything more specific than "something went wrong

760

* while processing an SQL script": for example, an SQLException from JDBC that we cannot pinpoint more precisely.

761

*/

762

public class ScriptException extends RuntimeException {

763

764

/**

765

* Constructor for ScriptException.

766

* @param message the detail message

767

*/

768

public ScriptException(String message);

769

770

/**

771

* Constructor for ScriptException.

772

* @param message the detail message

773

* @param cause the root cause

774

*/

775

public ScriptException(String message, @Nullable Throwable cause);

776

}

777

778

/**

779

* Utility class for common operations on SQL scripts.

780

*/

781

public abstract class ScriptUtils {

782

783

/** Default statement separator within SQL scripts: ";" */

784

public static final String DEFAULT_STATEMENT_SEPARATOR = ";";

785

786

/** Default prefix for single-line comments: "--" */

787

public static final String DEFAULT_COMMENT_PREFIX = "--";

788

789

/** Default start delimiter for block comments: "/*" */

790

public static final String DEFAULT_BLOCK_COMMENT_START_DELIMITER = "/*";

791

792

/** Default end delimiter for block comments: "*/" */

793

public static final String DEFAULT_BLOCK_COMMENT_END_DELIMITER = "*/";

794

795

/**

796

* Execute the given SQL script using default settings.

797

* @param connection the JDBC connection to use to execute the script

798

* @param resource the resource (potentially associated with a specific encoding) to load the SQL script from

799

* @throws ScriptException if an error occurred while executing the SQL script

800

*/

801

public static void executeSqlScript(Connection connection, Resource resource) throws ScriptException;

802

803

/**

804

* Execute the given SQL script.

805

* @param connection the JDBC connection to use to execute the script

806

* @param resource the resource (potentially associated with a specific encoding) to load the SQL script from

807

* @param continueOnError whether or not to continue without throwing an exception in the event of an error

808

* @param ignoreFailedDrops whether or not to continue in the event of failed DROP statements

809

* @param commentPrefix the prefix that identifies comments in the SQL script (typically "--")

810

* @param separator the script statement separator; falls back to "\n" if not specified and not found in the script

811

* @param blockCommentStartDelimiter the start delimiter for block comments (typically "/*")

812

* @param blockCommentEndDelimiter the end delimiter for block comments (typically "*/")

813

* @throws ScriptException if an error occurred while executing the SQL script

814

*/

815

public static void executeSqlScript(Connection connection, Resource resource, boolean continueOnError,

816

boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter,

817

String blockCommentEndDelimiter) throws ScriptException;

818

}

819

```