or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

container-providers.mddatabase-containers.mdindex.mdjdbc-driver.mdurl-configuration.md

database-containers.mddocs/

0

# Database Containers

1

2

The `JdbcDatabaseContainer` class provides the foundation for database containers that expose JDBC connectivity with automatic lifecycle management and initialization support.

3

4

## Capabilities

5

6

### Abstract Base Class

7

8

Base class for all database containers that provide JDBC connections.

9

10

```java { .api }

11

/**

12

* Base class for containers that expose a JDBC connection

13

* @param <SELF> self-referencing type for fluent interface

14

*/

15

public abstract class JdbcDatabaseContainer<SELF extends JdbcDatabaseContainer<SELF>>

16

extends GenericContainer<SELF>

17

implements LinkableContainer {

18

}

19

```

20

21

### Required Implementation Methods

22

23

Abstract methods that database-specific implementations must provide.

24

25

```java { .api }

26

/**

27

* Get the name of the actual JDBC driver to use

28

* @return fully qualified driver class name (e.g., "com.mysql.cj.jdbc.Driver")

29

*/

30

public abstract String getDriverClassName();

31

32

/**

33

* Get JDBC URL for connecting to the containerized database

34

* @return JDBC URL with container's host and port

35

*/

36

public abstract String getJdbcUrl();

37

38

/**

39

* Get the standard database username for connections

40

* @return database username

41

*/

42

public abstract String getUsername();

43

44

/**

45

* Get the standard password for connections

46

* @return database password

47

*/

48

public abstract String getPassword();

49

50

/**

51

* Get test query string for health checks

52

* @return SQL query suitable for testing database connectivity

53

*/

54

protected abstract String getTestQueryString();

55

```

56

57

### Database Configuration

58

59

Methods for configuring database connection parameters.

60

61

```java { .api }

62

/**

63

* Get the database name (may not be supported by all databases)

64

* @return database name

65

* @throws UnsupportedOperationException if not supported

66

*/

67

public String getDatabaseName();

68

69

/**

70

* Set the database username

71

* @param username database username

72

* @return self for method chaining

73

* @throws UnsupportedOperationException if not supported by database type

74

*/

75

public SELF withUsername(String username);

76

77

/**

78

* Set the database password

79

* @param password database password

80

* @return self for method chaining

81

* @throws UnsupportedOperationException if not supported by database type

82

*/

83

public SELF withPassword(String password);

84

85

/**

86

* Set the database name

87

* @param dbName database name

88

* @return self for method chaining

89

* @throws UnsupportedOperationException if not supported by database type

90

*/

91

public SELF withDatabaseName(String dbName);

92

93

/**

94

* Add URL parameter to JDBC connection string

95

* @param paramName parameter name

96

* @param paramValue parameter value

97

* @return self for method chaining

98

*/

99

public SELF withUrlParam(String paramName, String paramValue);

100

```

101

102

**Usage Example:**

103

```java

104

// Configure MySQL container

105

MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.0")

106

.withUsername("testuser")

107

.withPassword("testpass")

108

.withDatabaseName("testdb")

109

.withUrlParam("useSSL", "false")

110

.withUrlParam("allowPublicKeyRetrieval", "true");

111

```

112

113

### Timeout Configuration

114

115

Methods for configuring startup and connection timeouts.

116

117

```java { .api }

118

/**

119

* Set startup timeout including image pull time

120

* @param startupTimeoutSeconds timeout in seconds (default: 120)

121

* @return self for method chaining

122

*/

123

public SELF withStartupTimeoutSeconds(int startupTimeoutSeconds);

124

125

/**

126

* Set connection establishment timeout

127

* @param connectTimeoutSeconds timeout in seconds (default: 120)

128

* @return self for method chaining

129

*/

130

public SELF withConnectTimeoutSeconds(int connectTimeoutSeconds);

131

```

132

133

### Database Initialization

134

135

Methods for setting up database initialization scripts and functions.

136

137

```java { .api }

138

/**

139

* Set single initialization script (replaces any previous scripts)

140

* @param initScriptPath path to script file (classpath resource)

141

* @return self for method chaining

142

*/

143

public SELF withInitScript(String initScriptPath);

144

145

/**

146

* Set multiple initialization scripts in execution order

147

* @param initScriptPaths array of script paths

148

* @return self for method chaining

149

*/

150

public SELF withInitScripts(String... initScriptPaths);

151

152

/**

153

* Set initialization scripts from collection

154

* @param initScriptPaths iterable of script paths

155

* @return self for method chaining

156

*/

157

public SELF withInitScripts(Iterable<String> initScriptPaths);

158

```

159

160

**Usage Example:**

161

```java

162

PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13")

163

.withInitScript("schema.sql") // Single script

164

.withInitScripts("001-schema.sql", "002-data.sql", "003-indexes.sql"); // Multiple scripts

165

```

166

167

### JDBC Driver Management

168

169

Methods for obtaining and managing the underlying JDBC driver.

170

171

```java { .api }

172

/**

173

* Get instance of the database-specific JDBC driver

174

* @return JDBC Driver instance

175

* @throws NoDriverFoundException if driver class cannot be loaded

176

*/

177

public Driver getJdbcDriverInstance() throws NoDriverFoundException;

178

```

179

180

### Connection Creation

181

182

Methods for creating database connections to the containerized database.

183

184

```java { .api }

185

/**

186

* Create connection to the database with query string parameters

187

* @param queryString query parameters to append (must include leading '?')

188

* @return database Connection

189

* @throws SQLException if connection cannot be established

190

* @throws NoDriverFoundException if JDBC driver not available

191

*/

192

public Connection createConnection(String queryString)

193

throws SQLException, NoDriverFoundException;

194

195

/**

196

* Create connection with query string and additional properties

197

* @param queryString query parameters to append (must include leading '?')

198

* @param info additional JDBC connection properties

199

* @return database Connection

200

* @throws SQLException if connection cannot be established

201

* @throws NoDriverFoundException if JDBC driver not available

202

*/

203

public Connection createConnection(String queryString, Properties info)

204

throws SQLException, NoDriverFoundException;

205

```

206

207

**Usage Example:**

208

```java

209

JdbcDatabaseContainer<?> container = new MySQLContainer<>("mysql:8.0");

210

container.start();

211

212

// Simple connection

213

Connection conn1 = container.createConnection("");

214

215

// Connection with parameters

216

Connection conn2 = container.createConnection("?useSSL=false&allowPublicKeyRetrieval=true");

217

218

// Connection with properties

219

Properties props = new Properties();

220

props.setProperty("user", "admin");

221

props.setProperty("password", "secret");

222

Connection conn3 = container.createConnection("", props);

223

```

224

225

### Container Parameters

226

227

Methods for setting container-specific parameters.

228

229

```java { .api }

230

/**

231

* Set all container parameters (replaces existing parameters)

232

* @param parameters map of parameter names to values

233

*/

234

public void setParameters(Map<String, String> parameters);

235

236

/**

237

* Add single container parameter

238

* @param paramName parameter name

239

* @param value parameter value

240

*/

241

public void addParameter(String paramName, String value);

242

```

243

244

### URL Construction

245

246

Protected method for building JDBC connection URLs.

247

248

```java { .api }

249

/**

250

* Construct JDBC URL for connections including query parameters

251

* @param queryString query parameters (must start with '?')

252

* @return complete JDBC URL

253

* @throws IllegalArgumentException if queryString doesn't start with '?'

254

*/

255

protected String constructUrlForConnection(String queryString);

256

257

/**

258

* Construct URL parameter string with delimiters

259

* @param startCharacter delimiter before parameters

260

* @param delimiter delimiter between parameters

261

* @return formatted parameter string

262

*/

263

protected String constructUrlParameters(String startCharacter, String delimiter);

264

265

/**

266

* Construct URL parameter string with start and end delimiters

267

* @param startCharacter delimiter before parameters

268

* @param delimiter delimiter between parameters

269

* @param endCharacter delimiter after parameters

270

* @return formatted parameter string

271

*/

272

protected String constructUrlParameters(String startCharacter, String delimiter, String endCharacter);

273

```

274

275

### Resource Mapping

276

277

Protected methods for mapping classpath resources as container volumes.

278

279

```java { .api }

280

/**

281

* Map classpath resource as container volume if parameter is set

282

* @param paramName parameter name to check

283

* @param pathNameInContainer target path inside container

284

* @param defaultResource default resource path if parameter not set

285

* @param fileMode optional file permissions mode

286

*/

287

protected void optionallyMapResourceParameterAsVolume(

288

String paramName,

289

String pathNameInContainer,

290

String defaultResource,

291

Integer fileMode

292

);

293

```

294

295

### Database Delegate

296

297

Method for obtaining a database delegate for script execution.

298

299

```java { .api }

300

/**

301

* Get database delegate for executing SQL scripts and statements

302

* @return DatabaseDelegate instance for this container

303

*/

304

protected DatabaseDelegate getDatabaseDelegate();

305

```

306

307

### Deprecated Methods

308

309

Legacy methods maintained for backward compatibility.

310

311

```java { .api }

312

/**

313

* Get startup timeout in seconds

314

* @return startup timeout in seconds

315

* @deprecated Use withStartupTimeoutSeconds() in constructor instead

316

*/

317

@Deprecated

318

protected int getStartupTimeoutSeconds();

319

320

/**

321

* Get connection timeout in seconds

322

* @return connection timeout in seconds

323

* @deprecated Use withConnectTimeoutSeconds() in constructor instead

324

*/

325

@Deprecated

326

protected int getConnectTimeoutSeconds();

327

328

/**

329

* Map classpath resource as container volume (legacy 3-parameter version)

330

* @param paramName parameter name to check

331

* @param pathNameInContainer target path inside container

332

* @param defaultResource default resource path if parameter not set

333

* @deprecated Use 4-parameter version with fileMode instead

334

*/

335

@Deprecated

336

protected void optionallyMapResourceParameterAsVolume(

337

String paramName,

338

String pathNameInContainer,

339

String defaultResource

340

);

341

```

342

343

## Constructors

344

345

Available constructors for creating container instances.

346

347

```java { .api }

348

/**

349

* Create container with Docker image name string

350

* @param dockerImageName Docker image name

351

* @deprecated Use DockerImageName version instead

352

*/

353

public JdbcDatabaseContainer(String dockerImageName);

354

355

/**

356

* Create container with future image name

357

* @param image Future that will resolve to image name

358

*/

359

public JdbcDatabaseContainer(Future<String> image);

360

361

/**

362

* Create container with DockerImageName

363

* @param dockerImageName Docker image name object

364

*/

365

public JdbcDatabaseContainer(DockerImageName dockerImageName);

366

```

367

368

## Exception Types

369

370

```java { .api }

371

/**

372

* Exception thrown when JDBC driver cannot be found or loaded

373

*/

374

public static class NoDriverFoundException extends RuntimeException {

375

public NoDriverFoundException(String message, Throwable cause);

376

}

377

```

378

379

## Container Lifecycle

380

381

The container follows standard Testcontainers lifecycle:

382

383

1. **Creation**: Container instance created but not started

384

2. **Configuration**: Methods like `withUsername()`, `withInitScript()` configure the container

385

3. **Startup**: Container started when `start()` called or first connection requested

386

4. **Health Check**: Container waits until database accepts connections using test query

387

5. **Initialization**: Init scripts executed after database is ready

388

6. **Ready**: Container ready to accept connections

389

7. **Shutdown**: Container stopped when `stop()` called or test completes

390

391

## Database Initialization Process

392

393

When initialization scripts are provided:

394

395

1. Container starts and database becomes ready

396

2. Scripts executed in the order specified

397

3. Each script parsed and executed statement by statement

398

4. Errors can be configured to continue or fail the initialization

399

5. Initialization happens only once per container instance

400

401

**Script Execution Options:**

402

- **Continue on Error**: Scripts continue executing even if statements fail

403

- **Ignore Failed Drops**: DROP statements that fail are ignored (useful for cleanup scripts)

404

- **Custom Delimiters**: Support for stored procedures and complex SQL with custom delimiters