0
# JDBC Driver
1
2
The `ContainerDatabaseDriver` is the core component that implements the JDBC Driver interface to intercept database connections and manage Docker containers automatically.
3
4
## Capabilities
5
6
### Driver Registration
7
8
The driver automatically registers itself with the JDBC DriverManager when the class is loaded.
9
10
```java { .api }
11
/**
12
* JDBC Driver implementation that handles jdbc:tc: URLs
13
*/
14
public class ContainerDatabaseDriver implements java.sql.Driver {
15
// Driver automatically registers itself via static block
16
}
17
```
18
19
### URL Acceptance
20
21
Determines whether the driver can handle a given JDBC URL.
22
23
```java { .api }
24
/**
25
* Tests whether this driver can connect to the given URL
26
* @param url JDBC URL to test
27
* @return true if URL starts with "jdbc:tc:", false otherwise
28
* @throws SQLException if database access error occurs
29
*/
30
public boolean acceptsURL(String url) throws SQLException;
31
```
32
33
**Usage Example:**
34
```java
35
ContainerDatabaseDriver driver = new ContainerDatabaseDriver();
36
boolean canHandle = driver.acceptsURL("jdbc:tc:mysql:8.0://localhost/test"); // true
37
boolean cannotHandle = driver.acceptsURL("jdbc:mysql://localhost/test"); // false
38
```
39
40
### Connection Establishment
41
42
Creates database connections by provisioning containers and delegating to the appropriate database driver.
43
44
```java { .api }
45
/**
46
* Attempts to make a database connection to the given URL
47
* @param url JDBC URL in format jdbc:tc:type:tag://host:port/database?params
48
* @param info connection properties (user, password, etc.)
49
* @return Connection to the containerized database, or null if URL not supported
50
* @throws SQLException if database access error occurs
51
*/
52
public synchronized Connection connect(String url, Properties info) throws SQLException;
53
```
54
55
**Connection Process:**
56
1. Parse the JDBC URL to extract database type and parameters
57
2. Check cache for existing container with matching URL
58
3. If not found, use ServiceLoader to find appropriate `JdbcDatabaseContainerProvider`
59
4. Create and start new database container
60
5. Execute initialization scripts/functions if specified
61
6. Return wrapped connection with cleanup callbacks
62
63
**Usage Example:**
64
```java
65
Properties props = new Properties();
66
props.setProperty("user", "test");
67
props.setProperty("password", "test");
68
69
String url = "jdbc:tc:postgresql:13.7://localhost/testdb?TC_INITSCRIPT=schema.sql";
70
Connection conn = DriverManager.getConnection(url, props);
71
```
72
73
### Driver Properties
74
75
Provides information about supported connection properties.
76
77
```java { .api }
78
/**
79
* Gets information about possible properties for connections
80
* @param url JDBC URL
81
* @param info proposed connection properties
82
* @return array of DriverPropertyInfo objects
83
* @throws SQLException if database access error occurs
84
*/
85
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException;
86
```
87
88
### Version Information
89
90
Provides driver version information.
91
92
```java { .api }
93
/**
94
* Gets the driver's major version number
95
* @return major version number (delegates to underlying driver or returns 1)
96
*/
97
public int getMajorVersion();
98
99
/**
100
* Gets the driver's minor version number
101
* @return minor version number (delegates to underlying driver or returns 0)
102
*/
103
public int getMinorVersion();
104
```
105
106
### JDBC Compliance
107
108
Indicates whether the driver is JDBC compliant.
109
110
```java { .api }
111
/**
112
* Reports whether this driver is a genuine JDBC Compliant driver
113
* @return true if underlying driver is JDBC compliant, false otherwise
114
*/
115
public boolean jdbcCompliant();
116
```
117
118
### Logging Support
119
120
Provides access to the driver's logger.
121
122
```java { .api }
123
/**
124
* Return the parent Logger of all the Loggers used by this driver
125
* @return parent Logger for this driver
126
* @throws SQLFeatureNotSupportedException if not supported by underlying driver
127
*/
128
public Logger getParentLogger() throws SQLFeatureNotSupportedException;
129
```
130
131
### Container Management Utilities
132
133
Static utility methods for managing database containers directly.
134
135
```java { .api }
136
/**
137
* Utility method to kill ALL database containers
138
* Provided for cleanup in testing scenarios with resource constraints
139
*/
140
public static void killContainers();
141
142
/**
143
* Utility method to kill a specific database container
144
* @param jdbcUrl the JDBC URL of the container to kill
145
*/
146
public static void killContainer(String jdbcUrl);
147
148
/**
149
* Utility method to get container instance by JDBC URL
150
* @param jdbcUrl the JDBC URL of the container to retrieve
151
* @return container instance or null if not found
152
*/
153
static JdbcDatabaseContainer getContainer(String jdbcUrl);
154
```
155
156
**Usage Example:**
157
```java
158
// Clean up all containers after test suite
159
@AfterAll
160
public static void cleanup() {
161
ContainerDatabaseDriver.killContainers();
162
}
163
164
// Clean up specific container
165
ContainerDatabaseDriver.killContainer("jdbc:tc:mysql:8.0://localhost/test");
166
167
// Get container for inspection
168
JdbcDatabaseContainer container = ContainerDatabaseDriver.getContainer(
169
"jdbc:tc:postgresql:13://localhost/app"
170
);
171
if (container != null) {
172
System.out.println("Container is running: " + container.isRunning());
173
}
174
```
175
176
## Supported URL Format
177
178
The driver accepts URLs in the following format:
179
180
```
181
jdbc:tc:<database_type>[:<image_tag>]://[<host>:<port>]/<database_name>[?<parameters>]
182
```
183
184
**Components:**
185
- `database_type` - Database type (mysql, postgresql, oracle, etc.)
186
- `image_tag` - Optional Docker image tag (uses provider default if omitted)
187
- `host:port` - Optional host and port (ignored, container provides these)
188
- `database_name` - Database name to connect to
189
- `parameters` - Query parameters for both JDBC driver and Testcontainers
190
191
**Examples:**
192
```java
193
// MySQL with default tag
194
"jdbc:tc:mysql://localhost/testdb"
195
196
// PostgreSQL with specific version
197
"jdbc:tc:postgresql:13.7://localhost/myapp?user=app&password=secret"
198
199
// With initialization script
200
"jdbc:tc:mysql:8.0://localhost/test?TC_INITSCRIPT=schema.sql"
201
202
// With initialization function
203
"jdbc:tc:postgresql://localhost/test?TC_INITFUNCTION=com.example.DbInit::setupSchema"
204
```
205
206
## Container Lifecycle
207
208
The driver manages container lifecycle based on connection usage:
209
210
1. **Container Creation**: First connection with a new URL creates and starts container
211
2. **Connection Sharing**: Subsequent connections to same URL reuse existing container
212
3. **Automatic Cleanup**: Container stops when all connections are closed (unless in daemon mode)
213
4. **Daemon Mode**: Containers marked with `TC_DAEMON=true` persist across connection cycles
214
5. **Reusable Containers**: Containers marked with `TC_REUSABLE=true` may be reused across test runs
215
216
## Thread Safety
217
218
The driver implementation is thread-safe with synchronized access to container caches and connection management.