or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdbasic-connectivity.mdcopy-operations.mddatasource.mdindex.mdlarge-objects.mdpostgresql-types.mdreplication.mdresultset.mdssl-security.mdstatement-execution.mdtransactions.md

basic-connectivity.mddocs/

0

# Basic Connectivity

1

2

This document covers the fundamental aspects of establishing connections to PostgreSQL databases using the JDBC driver, including driver registration, connection URL formats, and connection management.

3

4

## Capabilities

5

6

### Driver Class

7

8

The main JDBC driver class that handles connection requests and driver registration.

9

10

```java { .api }

11

package org.postgresql;

12

13

import java.sql.Connection;

14

import java.sql.Driver;

15

import java.sql.DriverPropertyInfo;

16

import java.sql.SQLException;

17

import java.sql.SQLFeatureNotSupportedException;

18

import java.util.Properties;

19

import java.util.logging.Logger;

20

import org.postgresql.util.SharedTimer;

21

22

/**

23

* PostgreSQL JDBC Driver implementation

24

* Automatically registered with DriverManager when class is loaded

25

*/

26

public class Driver implements java.sql.Driver {

27

/**

28

* Attempts to make a database connection to the given URL.

29

* The driver returns null if it realizes it is the wrong kind of driver

30

* to connect to the given URL.

31

*

32

* @param url JDBC URL of the form:

33

* jdbc:postgresql://host:port/database

34

* jdbc:postgresql://host1:port1,host2:port2/database

35

* jdbc:postgresql:database

36

* jdbc:postgresql:/

37

* @param info Connection properties including:

38

* - user: database username

39

* - password: database password

40

* - ssl: enable SSL (true/false)

41

* - and many other optional properties

42

* @return A Connection object that represents a connection to the URL,

43

* or null if the URL is not suitable for this driver

44

* @throws SQLException if a database access error occurs

45

*/

46

public Connection connect(String url, Properties info) throws SQLException;

47

48

/**

49

* Returns true if the driver thinks it can open a connection to the given URL.

50

* Typically drivers will return true if they understand the subprotocol

51

* specified in the URL and false if they don't.

52

*

53

* @param url JDBC URL to test

54

* @return true if this driver can connect to the given URL

55

* @throws SQLException if a database access error occurs

56

*/

57

public boolean acceptsURL(String url) throws SQLException;

58

59

/**

60

* Gets information about the possible properties for this driver.

61

*

62

* @param url JDBC URL for which properties are requested

63

* @param info Proposed set of properties

64

* @return Array of DriverPropertyInfo objects describing possible properties

65

* @throws SQLException if a database access error occurs

66

*/

67

public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)

68

throws SQLException;

69

70

/**

71

* Gets the driver's major version number.

72

*

73

* @return Driver's major version number

74

*/

75

public int getMajorVersion();

76

77

/**

78

* Gets the driver's minor version number.

79

*

80

* @return Driver's minor version number

81

*/

82

public int getMinorVersion();

83

84

/**

85

* Returns the driver version as a string (e.g., "42.7.5").

86

*

87

* @return Driver version string

88

*/

89

public static String getVersion();

90

91

/**

92

* Reports whether this driver is a genuine JDBC Compliant driver.

93

* Returns false because PostgreSQL is not yet SQL92 Entry Level compliant.

94

*

95

* @return false, PostgreSQL is not yet SQL92 Entry Level compliant

96

*/

97

public boolean jdbcCompliant();

98

99

/**

100

* Returns the parent Logger of all loggers used by this driver.

101

*

102

* @return The parent Logger for this driver

103

* @throws SQLFeatureNotSupportedException if the driver does not use java.util.logging

104

*/

105

public Logger getParentLogger() throws SQLFeatureNotSupportedException;

106

107

/**

108

* Registers the driver with DriverManager.

109

* This is called automatically when the class is loaded, but can be

110

* called manually if needed.

111

*

112

* @throws SQLException if driver cannot be registered

113

*/

114

public static void register() throws SQLException;

115

116

/**

117

* Deregisters the driver from DriverManager.

118

* Useful for cleaning up in application servers or when hot-redeploying.

119

*

120

* @throws SQLException if driver cannot be deregistered

121

*/

122

public static void deregister() throws SQLException;

123

124

/**

125

* Checks if the driver is currently registered with DriverManager.

126

*

127

* @return true if driver is registered

128

*/

129

public static boolean isRegistered();

130

131

/**

132

* Returns the shared timer instance used for connection timeouts.

133

*

134

* @return SharedTimer instance

135

*/

136

public static SharedTimer getSharedTimer();

137

138

/**

139

* Helper method that creates a SQLFeatureNotSupportedException for

140

* features not implemented by the driver.

141

*

142

* @param callClass Class where the unimplemented method was called

143

* @param functionName Name of the unimplemented function

144

* @return SQLFeatureNotSupportedException with appropriate message

145

*/

146

public static SQLFeatureNotSupportedException notImplemented(

147

Class<?> callClass, String functionName);

148

149

/**

150

* Parses a JDBC URL into a Properties object.

151

*

152

* @param url JDBC URL to parse

153

* @param defaults Default properties to merge with URL properties (can be null)

154

* @return Properties object containing all connection parameters, or null if URL is not recognized

155

*/

156

public static Properties parseURL(String url, Properties defaults);

157

}

158

```

159

160

**Usage Examples:**

161

162

```java

163

import org.postgresql.Driver;

164

import java.sql.Connection;

165

import java.sql.DriverManager;

166

import java.sql.SQLException;

167

import java.util.Properties;

168

169

// Example 1: Automatic driver registration (most common)

170

// The driver registers itself automatically when the class is loaded

171

public class AutomaticRegistration {

172

public static void main(String[] args) throws SQLException {

173

// No explicit registration needed

174

String url = "jdbc:postgresql://localhost:5432/mydb";

175

Connection conn = DriverManager.getConnection(url, "user", "password");

176

// use connection...

177

conn.close();

178

}

179

}

180

181

// Example 2: Manual driver registration

182

public class ManualRegistration {

183

public static void main(String[] args) throws SQLException {

184

// Explicitly load and register the driver

185

Driver.register();

186

187

String url = "jdbc:postgresql://localhost:5432/mydb";

188

Connection conn = DriverManager.getConnection(url, "user", "password");

189

conn.close();

190

}

191

}

192

193

// Example 3: Check driver version

194

public class DriverInfo {

195

public static void main(String[] args) throws SQLException {

196

Driver driver = new Driver();

197

System.out.println("Driver version: " +

198

driver.getMajorVersion() + "." + driver.getMinorVersion());

199

System.out.println("JDBC compliant: " + driver.jdbcCompliant());

200

}

201

}

202

203

// Example 4: Parse URL to see properties

204

public class URLParsing {

205

public static void main(String[] args) {

206

String url = "jdbc:postgresql://localhost:5432/mydb?ssl=true&user=postgres";

207

Properties props = Driver.parseURL(url, new Properties());

208

209

// See what properties were extracted

210

if (props != null) {

211

for (String key : props.stringPropertyNames()) {

212

System.out.println(key + " = " + props.getProperty(key));

213

}

214

}

215

}

216

}

217

```

218

219

### Connection URLs

220

221

PostgreSQL JDBC URLs follow specific formats and support extensive configuration.

222

223

**URL Format:**

224

225

```

226

jdbc:postgresql://[host][:port][/database][?property=value[&property=value...]]

227

```

228

229

**URL Components:**

230

231

- **Protocol**: `jdbc:postgresql:` (required)

232

- **Host**: Hostname or IP address (default: localhost)

233

- **Port**: Port number (default: 5432)

234

- **Database**: Database name (optional, defaults to username)

235

- **Properties**: Query string with key=value pairs

236

237

**Common URL Patterns:**

238

239

```java

240

// Basic connection to localhost

241

String url1 = "jdbc:postgresql://localhost/mydb";

242

243

// Specify port

244

String url2 = "jdbc:postgresql://localhost:5432/mydb";

245

246

// Specify user and password in URL (not recommended for security)

247

String url3 = "jdbc:postgresql://localhost/mydb?user=postgres&password=secret";

248

249

// SSL connection

250

String url4 = "jdbc:postgresql://localhost/mydb?ssl=true&sslmode=require";

251

252

// Multiple hosts for high availability

253

String url5 = "jdbc:postgresql://host1:5432,host2:5432,host3:5432/mydb"

254

+ "?targetServerType=primary";

255

256

// Unix socket connection (requires pgsql.so library)

257

String url6 = "jdbc:postgresql://localhost/mydb"

258

+ "?socketFactory=org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg"

259

+ "&socketFactoryArg=/var/run/postgresql/.s.PGSQL.5432";

260

261

// Database on different port

262

String url7 = "jdbc:postgresql://db.example.com:5433/production";

263

264

// Connect using pg_service.conf

265

String url8 = "jdbc:postgresql://?service=myservice";

266

267

// Minimal URL (uses defaults)

268

String url9 = "jdbc:postgresql:mydb";

269

270

// IPv6 address

271

String url10 = "jdbc:postgresql://[::1]:5432/mydb";

272

```

273

274

### Connection Establishment

275

276

Methods for creating database connections.

277

278

```java { .api }

279

import java.sql.Connection;

280

import java.sql.DriverManager;

281

import java.sql.SQLException;

282

import java.util.Properties;

283

284

/**

285

* Standard JDBC method for getting a connection using DriverManager

286

*/

287

public class java.sql.DriverManager {

288

/**

289

* Establishes a connection to the database

290

* @param url JDBC URL

291

* @param user Database username

292

* @param password Database password

293

* @return Connection object

294

* @throws SQLException if connection fails

295

*/

296

public static Connection getConnection(String url, String user, String password)

297

throws SQLException;

298

299

/**

300

* Establishes a connection using Properties

301

* @param url JDBC URL

302

* @param info Connection properties

303

* @return Connection object

304

* @throws SQLException if connection fails

305

*/

306

public static Connection getConnection(String url, Properties info)

307

throws SQLException;

308

309

/**

310

* Establishes a connection with embedded credentials in URL

311

* @param url JDBC URL with user/password parameters

312

* @return Connection object

313

* @throws SQLException if connection fails

314

*/

315

public static Connection getConnection(String url) throws SQLException;

316

}

317

```

318

319

**Usage Examples:**

320

321

```java

322

import java.sql.Connection;

323

import java.sql.DriverManager;

324

import java.sql.SQLException;

325

import java.util.Properties;

326

327

// Example 1: Simple connection with user/password

328

public class SimpleConnection {

329

public static Connection getConnection() throws SQLException {

330

String url = "jdbc:postgresql://localhost:5432/mydb";

331

String user = "postgres";

332

String password = "secret";

333

return DriverManager.getConnection(url, user, password);

334

}

335

}

336

337

// Example 2: Connection with Properties

338

public class PropertiesConnection {

339

public static Connection getConnection() throws SQLException {

340

String url = "jdbc:postgresql://localhost:5432/mydb";

341

342

Properties props = new Properties();

343

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

344

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

345

props.setProperty("ssl", "true");

346

props.setProperty("sslmode", "require");

347

props.setProperty("ApplicationName", "MyApp");

348

props.setProperty("connectTimeout", "10"); // 10 seconds

349

350

return DriverManager.getConnection(url, props);

351

}

352

}

353

354

// Example 3: All-in-URL connection

355

public class URLConnection {

356

public static Connection getConnection() throws SQLException {

357

String url = "jdbc:postgresql://localhost:5432/mydb"

358

+ "?user=postgres"

359

+ "&password=secret"

360

+ "&ssl=true"

361

+ "&ApplicationName=MyApp";

362

return DriverManager.getConnection(url);

363

}

364

}

365

366

// Example 4: Connection with timeout and retry logic

367

public class RobustConnection {

368

public static Connection getConnectionWithRetry(int maxRetries)

369

throws SQLException {

370

String url = "jdbc:postgresql://localhost:5432/mydb";

371

Properties props = new Properties();

372

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

373

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

374

props.setProperty("connectTimeout", "5");

375

props.setProperty("socketTimeout", "30");

376

props.setProperty("loginTimeout", "10");

377

378

SQLException lastException = null;

379

for (int i = 0; i < maxRetries; i++) {

380

try {

381

return DriverManager.getConnection(url, props);

382

} catch (SQLException e) {

383

lastException = e;

384

System.err.println("Connection attempt " + (i + 1) +

385

" failed: " + e.getMessage());

386

if (i < maxRetries - 1) {

387

try {

388

Thread.sleep(1000); // Wait 1 second before retry

389

} catch (InterruptedException ie) {

390

Thread.currentThread().interrupt();

391

throw new SQLException("Interrupted during retry", ie);

392

}

393

}

394

}

395

}

396

throw lastException;

397

}

398

}

399

```

400

401

### PGConnection Interface

402

403

PostgreSQL-specific extensions to the standard Connection interface.

404

405

```java { .api }

406

package org.postgresql;

407

408

import org.postgresql.copy.CopyManager;

409

import org.postgresql.fastpath.Fastpath;

410

import org.postgresql.jdbc.AutoSave;

411

import org.postgresql.jdbc.PreferQueryMode;

412

import org.postgresql.largeobject.LargeObjectManager;

413

import org.postgresql.replication.PGReplicationConnection;

414

import org.postgresql.util.PGobject;

415

416

import java.sql.Array;

417

import java.sql.Connection;

418

import java.sql.SQLException;

419

import java.util.Map;

420

421

/**

422

* PostgreSQL extensions to java.sql.Connection.

423

* All connections returned by the PostgreSQL driver implement this interface.

424

* Cast a standard Connection to PGConnection to access PostgreSQL-specific features.

425

*/

426

public interface PGConnection extends Connection {

427

/**

428

* Creates a PostgreSQL array with support for primitive arrays.

429

* This is an enhanced version of Connection.createArrayOf() that also

430

* supports primitive array types.

431

*

432

* @param typeName SQL name of the array element type (e.g., "integer", "text")

433

* @param elements Array of elements (may be primitive array, Object[], or null)

434

* @return Array object wrapping the elements

435

* @throws SQLException if array cannot be created

436

*/

437

Array createArrayOf(String typeName, @Nullable Object elements) throws SQLException;

438

439

/**

440

* Returns notifications received via LISTEN/NOTIFY since last call.

441

* Returns null if no notifications are available.

442

*

443

* @return Array of notifications or null

444

* @throws SQLException if retrieval fails

445

*/

446

PGNotification[] getNotifications() throws SQLException;

447

448

/**

449

* Returns notifications with timeout support.

450

* Blocks until at least one notification is received or timeout expires.

451

*

452

* @param timeoutMillis Timeout in milliseconds (0 = block forever,

453

* >0 = wait up to specified time)

454

* @return Array of notifications or null if timeout expires

455

* @throws SQLException if retrieval fails

456

*/

457

PGNotification[] getNotifications(int timeoutMillis) throws SQLException;

458

459

/**

460

* Returns the COPY API for bulk data operations.

461

*

462

* @return CopyManager for this connection

463

* @throws SQLException if CopyManager cannot be obtained

464

*/

465

CopyManager getCopyAPI() throws SQLException;

466

467

/**

468

* Returns the Large Object API for BLOB operations.

469

*

470

* @return LargeObjectManager for this connection

471

* @throws SQLException if LargeObjectManager cannot be obtained

472

*/

473

LargeObjectManager getLargeObjectAPI() throws SQLException;

474

475

/**

476

* Returns the Fastpath API (deprecated).

477

*

478

* @return Fastpath interface

479

* @throws SQLException if Fastpath cannot be obtained

480

* @deprecated Use PreparedStatement with binary parameters instead

481

*/

482

@Deprecated

483

Fastpath getFastpathAPI() throws SQLException;

484

485

/**

486

* Registers a custom data type handler.

487

* The class must extend org.postgresql.util.PGobject.

488

*

489

* @param type PostgreSQL type name

490

* @param klass Class that handles the type

491

* @throws SQLException if registration fails or class is invalid

492

*/

493

void addDataType(String type, Class<? extends PGobject> klass)

494

throws SQLException;

495

496

/**

497

* Deprecated: Registers a custom data type handler using class name.

498

* The class must extend org.postgresql.util.PGobject.

499

*

500

* @param type PostgreSQL type name

501

* @param className Fully qualified class name that handles the type

502

* @throws RuntimeException if class cannot be loaded or is invalid

503

* @deprecated Use {@link #addDataType(String, Class)} instead

504

*/

505

@Deprecated

506

void addDataType(String type, String className);

507

508

/**

509

* Sets the default threshold for server-side prepared statements.

510

* Statements will be prepared on the server after this many executions.

511

*

512

* @param threshold Number of executions before server prepare:

513

* - Positive value N: Use server prepare on Nth and subsequent executions

514

* - 0: Never use server prepare

515

* - Negative: Reserved for internal use (forceBinary mode)

516

* - Default: 5 (configurable via prepareThreshold connection property)

517

* @see org.postgresql.PGStatement#setPrepareThreshold(int)

518

*/

519

void setPrepareThreshold(int threshold);

520

521

/**

522

* Gets the default prepare threshold for this connection.

523

*

524

* @return Current prepare threshold

525

*/

526

int getPrepareThreshold();

527

528

/**

529

* Sets the default fetch size for statements created from this connection.

530

*

531

* @param fetchSize Default fetch size (0 = fetch all rows at once)

532

* @throws SQLException if fetchSize is negative

533

*/

534

void setDefaultFetchSize(int fetchSize) throws SQLException;

535

536

/**

537

* Gets the default fetch size for this connection.

538

*

539

* @return Current default fetch size

540

*/

541

int getDefaultFetchSize();

542

543

/**

544

* Returns the PostgreSQL backend process ID for this connection.

545

* Useful for monitoring and debugging.

546

*

547

* @return Backend process ID

548

*/

549

int getBackendPID();

550

551

/**

552

* Cancels the currently executing query on this connection.

553

* This sends a cancel request to the backend.

554

*

555

* @throws SQLException if cancellation fails

556

*/

557

void cancelQuery() throws SQLException;

558

559

/**

560

* Escapes an identifier for safe use in SQL.

561

* Adds quotes if necessary and escapes embedded quotes.

562

*

563

* @param identifier Identifier to escape

564

* @return Properly escaped identifier

565

* @throws SQLException if escaping fails

566

*/

567

String escapeIdentifier(String identifier) throws SQLException;

568

569

/**

570

* Escapes a string literal for safe use in SQL.

571

* Properly escapes quotes and backslashes.

572

*

573

* @param literal String literal to escape

574

* @return Properly escaped literal

575

* @throws SQLException if escaping fails

576

*/

577

String escapeLiteral(String literal) throws SQLException;

578

579

/**

580

* Returns the query execution mode for this connection.

581

*

582

* @return Current PreferQueryMode

583

*/

584

PreferQueryMode getPreferQueryMode();

585

586

/**

587

* Returns the autosave configuration for this connection.

588

*

589

* @return Current AutoSave setting

590

*/

591

AutoSave getAutosave();

592

593

/**

594

* Sets the autosave behavior for automatic savepoint management.

595

*

596

* @param autoSave AutoSave mode to use

597

*/

598

void setAutosave(AutoSave autoSave);

599

600

/**

601

* Enables or disables adaptive fetch for this connection.

602

* Existing statements and result sets won't be affected by this change.

603

*

604

* Adaptive fetch automatically adjusts the fetch size based on the

605

* rate at which rows are consumed by the application.

606

*

607

* @param adaptiveFetch true to enable, false to disable

608

*/

609

void setAdaptiveFetch(boolean adaptiveFetch);

610

611

/**

612

* Returns the current adaptive fetch setting for this connection.

613

*

614

* @return true if adaptive fetch is enabled, false otherwise

615

*/

616

boolean getAdaptiveFetch();

617

618

/**

619

* Returns the replication API for this connection.

620

* Only available if connection was opened with replication=database or

621

* replication=true parameter.

622

*

623

* @return PGReplicationConnection interface

624

*/

625

PGReplicationConnection getReplicationAPI();

626

627

/**

628

* Changes a PostgreSQL user's password.

629

* The password is encrypted locally before transmission.

630

*

631

* @param user Username to modify

632

* @param newPassword New password (will be zeroed after use)

633

* @param encryptionType Encryption type: null (use server default),

634

* "md5", or "scram-sha-256"

635

* @throws SQLException if password change fails

636

*/

637

void alterUserPassword(String user, char[] newPassword, String encryptionType)

638

throws SQLException;

639

640

/**

641

* Returns all server parameters reported by PostgreSQL.

642

* PostgreSQL reports values for GUC_REPORT parameters like

643

* server_version, TimeZone, DateStyle, etc.

644

*

645

* @return Unmodifiable map of parameter names to values

646

*/

647

Map<String, String> getParameterStatuses();

648

649

/**

650

* Returns a specific server parameter value.

651

*

652

* @param parameterName Parameter name (case-insensitive)

653

* @return Parameter value or null if not reported

654

*/

655

String getParameterStatus(String parameterName);

656

657

/**

658

* Enables or disables adaptive fetch size adjustment.

659

* When enabled, the driver automatically adjusts fetch size based on

660

* result set characteristics.

661

*

662

* @param adaptiveFetch true to enable adaptive fetch

663

*/

664

void setAdaptiveFetch(boolean adaptiveFetch);

665

666

/**

667

* Returns whether adaptive fetch is enabled.

668

*

669

* @return true if adaptive fetch is enabled

670

*/

671

boolean getAdaptiveFetch();

672

}

673

```

674

675

**Usage Examples:**

676

677

```java

678

import org.postgresql.PGConnection;

679

import java.sql.Connection;

680

import java.sql.DriverManager;

681

import java.sql.SQLException;

682

683

// Example 1: Cast to PGConnection and use extensions

684

public class PGConnectionExample {

685

public static void useExtensions() throws SQLException {

686

String url = "jdbc:postgresql://localhost/mydb";

687

Connection conn = DriverManager.getConnection(url, "user", "password");

688

689

// Cast to PGConnection to access PostgreSQL-specific features

690

PGConnection pgConn = conn.unwrap(PGConnection.class);

691

692

// Get backend process ID

693

int pid = pgConn.getBackendPID();

694

System.out.println("Connected to backend PID: " + pid);

695

696

// Configure prepare threshold

697

pgConn.setPrepareThreshold(5); // Prepare after 5 executions

698

699

// Set default fetch size

700

pgConn.setDefaultFetchSize(100); // Fetch 100 rows at a time

701

702

// Get server parameters

703

String serverVersion = pgConn.getParameterStatus("server_version");

704

String timeZone = pgConn.getParameterStatus("TimeZone");

705

System.out.println("Server version: " + serverVersion);

706

System.out.println("Server timezone: " + timeZone);

707

708

conn.close();

709

}

710

}

711

712

// Example 2: Escape identifiers and literals

713

public class SQLEscaping {

714

public static void demonstrateEscaping() throws SQLException {

715

Connection conn = DriverManager.getConnection(

716

"jdbc:postgresql://localhost/mydb", "user", "password");

717

PGConnection pgConn = conn.unwrap(PGConnection.class);

718

719

// Escape table name for dynamic SQL

720

String tableName = "user's data"; // Contains quote

721

String escapedTable = pgConn.escapeIdentifier(tableName);

722

System.out.println("Escaped table: " + escapedTable);

723

// Output: "user's data"

724

725

// Escape string literal

726

String userInput = "O'Brien"; // Contains quote

727

String escapedLiteral = pgConn.escapeLiteral(userInput);

728

System.out.println("Escaped literal: " + escapedLiteral);

729

// Output: 'O''Brien'

730

731

conn.close();

732

}

733

}

734

735

// Example 3: Check connection parameters

736

public class ConnectionInfo {

737

public static void showConnectionInfo() throws SQLException {

738

Connection conn = DriverManager.getConnection(

739

"jdbc:postgresql://localhost/mydb", "user", "password");

740

PGConnection pgConn = conn.unwrap(PGConnection.class);

741

742

// Get all server parameters

743

Map<String, String> params = pgConn.getParameterStatuses();

744

System.out.println("Server Parameters:");

745

for (Map.Entry<String, String> entry : params.entrySet()) {

746

System.out.println(" " + entry.getKey() + " = " + entry.getValue());

747

}

748

749

// Get query mode

750

System.out.println("Query mode: " + pgConn.getPreferQueryMode());

751

752

// Get autosave setting

753

System.out.println("Autosave: " + pgConn.getAutosave());

754

755

conn.close();

756

}

757

}

758

```

759

760

### Connection Properties

761

762

Comprehensive list of connection properties supported by the driver.

763

764

```java { .api }

765

package org.postgresql;

766

767

import java.sql.DriverPropertyInfo;

768

import java.util.Properties;

769

770

/**

771

* Enumeration of all connection properties supported by PostgreSQL JDBC driver.

772

* Properties can be set in JDBC URL, Properties object, or DataSource setters.

773

* Note: This enum contains 80+ properties; the most commonly used properties are shown below.

774

*/

775

public enum PGProperty {

776

// Authentication properties

777

USER("user", null, "Database user name", true),

778

PASSWORD("password", null, "Database user password", false),

779

780

// Connection properties

781

PG_HOST("PGHOST", "localhost", "PostgreSQL server hostname", false),

782

PG_PORT("PGPORT", "5432", "PostgreSQL server port", false),

783

PG_DBNAME("PGDBNAME", null, "Database name", false),

784

785

// SSL properties

786

SSL("ssl", "false", "Enable SSL connection", false),

787

SSL_MODE("sslmode", "prefer", "SSL mode: disable, allow, prefer, require, verify-ca, verify-full", false),

788

SSL_FACTORY("sslfactory", null, "Custom SSL socket factory class", false),

789

SSL_FACTORY_ARG("sslfactoryarg", null, "Argument for SSL factory", false),

790

SSL_CERT("sslcert", null, "Client certificate file", false),

791

SSL_KEY("sslkey", null, "Client key file", false),

792

SSL_ROOT_CERT("sslrootcert", null, "Root certificate file", false),

793

SSL_PASSWORD("sslpassword", null, "Password for encrypted client key", false),

794

SSL_PASSWORD_CALLBACK("sslpasswordcallback", null, "SSL password callback class", false),

795

SSL_HOSTNAME_VERIFIER("sslhostnameverifier", null, "Custom hostname verifier", false),

796

797

// Timeout properties

798

CONNECT_TIMEOUT("connectTimeout", "10", "Connection timeout in seconds", false),

799

SOCKET_TIMEOUT("socketTimeout", "0", "Socket timeout in seconds (0 = no timeout)", false),

800

LOGIN_TIMEOUT("loginTimeout", "0", "Login timeout in seconds", false),

801

CANCEL_SIGNAL_TIMEOUT("cancelSignalTimeout", "10", "Query cancel signal timeout in seconds", false),

802

803

// Performance properties

804

PREPARE_THRESHOLD("prepareThreshold", "5", "Statement executions before server prepare", false),

805

PREPARED_STATEMENT_CACHE_QUERIES("preparedStatementCacheQueries", "256",

806

"Prepared statement cache size", false),

807

PREPARED_STATEMENT_CACHE_SIZE_MIB("preparedStatementCacheSizeMiB", "5",

808

"Prepared statement cache size in MiB", false),

809

DEFAULT_ROW_FETCH_SIZE("defaultRowFetchSize", "0",

810

"Default fetch size for ResultSets (0 = all rows)", false),

811

BINARY_TRANSFER("binaryTransfer", "true", "Use binary format for applicable types", false),

812

BINARY_TRANSFER_ENABLE("binaryTransferEnable", "",

813

"Comma-separated list of OIDs to enable binary transfer", false),

814

BINARY_TRANSFER_DISABLE("binaryTransferDisable", "",

815

"Comma-separated list of OIDs to disable binary transfer", false),

816

817

// Application properties

818

APPLICATION_NAME("ApplicationName", "PostgreSQL JDBC Driver",

819

"Application name for connection tracking", false),

820

ASSUME_MIN_SERVER_VERSION("assumeMinServerVersion", null,

821

"Assume minimum server version to skip version checks", false),

822

823

// Behavior properties

824

AUTOSAVE("autosave", "never", "Automatic savepoint mode: never, always, conservative", false),

825

PREFER_QUERY_MODE("preferQueryMode", "extended",

826

"Query mode: simple, extended, extendedForPrepared, extendedCacheEverything", false),

827

REPLICATION("replication", null, "Enable replication protocol: true, database", false),

828

STRING_TYPE("stringtype", "varchar", "String type mapping: varchar or unspecified", false),

829

830

// Multi-host properties

831

TARGET_SERVER_TYPE("targetServerType", "any",

832

"Target server type: any, primary, secondary, preferSecondary", false),

833

LOAD_BALANCE_HOSTS("loadBalanceHosts", "false",

834

"Enable random host selection for load balancing", false),

835

HOST_RECHECK_SECONDS("hostRecheckSeconds", "10",

836

"Seconds between host status rechecks", false),

837

838

// Authentication properties

839

GSS_LIB("gsslib", "auto", "GSS library: auto, sspi, gssapi", false),

840

SSPI_SERVICE_CLASS("sspiServiceClass", "POSTGRES",

841

"SSPI service class for authentication", false),

842

ALLOW_ENCODING_CHANGES("allowEncodingChanges", "false",

843

"Allow client_encoding changes", false),

844

LOG_UNCLOSED_CONNECTIONS("logUnclosedConnections", "false",

845

"Log stack trace of unclosed connections", false),

846

847

// Additional properties

848

TCP_KEEP_ALIVE("tcpKeepAlive", "false", "Enable TCP keepalive", false),

849

ADAPTIVE_FETCH("adaptiveFetch", "false", "Enable adaptive fetch size", false),

850

LOGGER_LEVEL("loggerLevel", null, "Logger level: OFF, DEBUG, TRACE", false),

851

LOGGER_FILE("loggerFile", null, "Log file location", false);

852

853

private final String name;

854

private final String defaultValue;

855

private final String description;

856

private final boolean required;

857

858

/**

859

* Gets the property name

860

*/

861

public String getName();

862

863

/**

864

* Gets the default value for this property

865

*/

866

public String getDefaultValue();

867

868

/**

869

* Gets the description of this property

870

*/

871

public String getDescription();

872

873

/**

874

* Returns whether this property is required

875

*/

876

public boolean isRequired();

877

878

/**

879

* Gets allowed choices for this property (if restricted)

880

*/

881

public String[] getChoices();

882

883

/**

884

* Gets the property value or default from Properties

885

*/

886

public String getOrDefault(Properties properties);

887

888

/**

889

* Sets the property value in Properties

890

*/

891

public void set(Properties properties, String value);

892

893

/**

894

* Gets property value as boolean

895

*/

896

public boolean getBoolean(Properties properties);

897

898

/**

899

* Gets property value as int

900

*/

901

public int getInt(Properties properties);

902

903

/**

904

* Checks if property is present in Properties

905

*/

906

public boolean isPresent(Properties properties);

907

908

/**

909

* Converts to JDBC DriverPropertyInfo

910

*/

911

public DriverPropertyInfo toDriverPropertyInfo(Properties properties);

912

913

/**

914

* Looks up a property by name

915

*/

916

public static PGProperty forName(String name);

917

}

918

```

919

920

**Usage Examples:**

921

922

```java

923

import org.postgresql.PGProperty;

924

import java.sql.Connection;

925

import java.sql.DriverManager;

926

import java.sql.SQLException;

927

import java.util.Properties;

928

929

// Example: Configure connection with various properties

930

public class ConnectionConfiguration {

931

public static Connection getConfiguredConnection() throws SQLException {

932

String url = "jdbc:postgresql://localhost:5432/mydb";

933

Properties props = new Properties();

934

935

// Authentication

936

PGProperty.USER.set(props, "postgres");

937

PGProperty.PASSWORD.set(props, "secret");

938

939

// SSL

940

PGProperty.SSL.set(props, "true");

941

PGProperty.SSL_MODE.set(props, "require");

942

943

// Timeouts

944

PGProperty.CONNECT_TIMEOUT.set(props, "10");

945

PGProperty.SOCKET_TIMEOUT.set(props, "30");

946

947

// Performance

948

PGProperty.PREPARE_THRESHOLD.set(props, "5");

949

PGProperty.DEFAULT_ROW_FETCH_SIZE.set(props, "100");

950

PGProperty.BINARY_TRANSFER.set(props, "true");

951

952

// Application tracking

953

PGProperty.APPLICATION_NAME.set(props, "MyApplication");

954

955

// Autosave

956

PGProperty.AUTOSAVE.set(props, "conservative");

957

958

return DriverManager.getConnection(url, props);

959

}

960

961

// Get property value

962

public static void checkProperty() {

963

Properties props = new Properties();

964

PGProperty.PREPARE_THRESHOLD.set(props, "10");

965

966

int threshold = PGProperty.PREPARE_THRESHOLD.getInt(props);

967

System.out.println("Prepare threshold: " + threshold);

968

969

String defaultValue = PGProperty.PREPARE_THRESHOLD.getDefaultValue();

970

System.out.println("Default threshold: " + defaultValue);

971

}

972

}

973

```

974

975

### Multi-Host Connections

976

977

Support for high availability configurations with multiple database hosts.

978

979

**Multi-Host URL Format:**

980

981

```

982

jdbc:postgresql://host1:port1,host2:port2,host3:port3/database?properties

983

```

984

985

**Usage Examples:**

986

987

```java

988

import java.sql.Connection;

989

import java.sql.DriverManager;

990

import java.sql.SQLException;

991

import java.util.Properties;

992

993

// Example 1: Basic failover configuration

994

public class FailoverConnection {

995

public static Connection getConnection() throws SQLException {

996

// Driver will try hosts in order until successful connection

997

String url = "jdbc:postgresql://primary:5432,standby1:5432,standby2:5432/mydb"

998

+ "?user=postgres&password=secret";

999

return DriverManager.getConnection(url);

1000

}

1001

}

1002

1003

// Example 2: Connect to primary server only

1004

public class PrimaryConnection {

1005

public static Connection getConnection() throws SQLException {

1006

String url = "jdbc:postgresql://host1:5432,host2:5432,host3:5432/mydb";

1007

Properties props = new Properties();

1008

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

1009

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

1010

props.setProperty("targetServerType", "primary");

1011

return DriverManager.getConnection(url, props);

1012

}

1013

}

1014

1015

// Example 3: Load balancing across read replicas

1016

public class LoadBalancedConnection {

1017

public static Connection getConnection() throws SQLException {

1018

String url = "jdbc:postgresql://replica1:5432,replica2:5432,replica3:5432/mydb";

1019

Properties props = new Properties();

1020

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

1021

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

1022

props.setProperty("targetServerType", "secondary");

1023

props.setProperty("loadBalanceHosts", "true"); // Random selection

1024

return DriverManager.getConnection(url, props);

1025

}

1026

}

1027

1028

// Example 4: Prefer secondary, fallback to primary

1029

public class PreferSecondaryConnection {

1030

public static Connection getConnection() throws SQLException {

1031

String url = "jdbc:postgresql://primary:5432,secondary:5432/mydb";

1032

Properties props = new Properties();

1033

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

1034

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

1035

props.setProperty("targetServerType", "preferSecondary");

1036

return DriverManager.getConnection(url, props);

1037

}

1038

}

1039

```

1040

1041

### Connection Validation

1042

1043

Methods for testing and validating connections.

1044

1045

**Usage Examples:**

1046

1047

```java

1048

import java.sql.Connection;

1049

import java.sql.SQLException;

1050

import java.sql.Statement;

1051

import java.sql.ResultSet;

1052

1053

// Example 1: Basic connection validation

1054

public class ConnectionValidation {

1055

public static boolean isConnectionValid(Connection conn) {

1056

if (conn == null) {

1057

return false;

1058

}

1059

1060

try {

1061

// JDBC 4.0+ method with timeout

1062

return conn.isValid(5); // 5 second timeout

1063

} catch (SQLException e) {

1064

return false;

1065

}

1066

}

1067

1068

// Alternative validation with simple query

1069

public static boolean isConnectionValidWithQuery(Connection conn) {

1070

if (conn == null || conn.isClosed()) {

1071

return false;

1072

}

1073

1074

try (Statement stmt = conn.createStatement();

1075

ResultSet rs = stmt.executeQuery("SELECT 1")) {

1076

return rs.next();

1077

} catch (SQLException e) {

1078

return false;

1079

}

1080

}

1081

}

1082

1083

// Example 2: Connection pool validation query

1084

public class PoolValidation {

1085

public static final String VALIDATION_QUERY = "SELECT 1";

1086

1087

public static boolean validateConnection(Connection conn) {

1088

try (Statement stmt = conn.createStatement()) {

1089

stmt.setQueryTimeout(5); // 5 second timeout

1090

try (ResultSet rs = stmt.executeQuery(VALIDATION_QUERY)) {

1091

return rs.next();

1092

}

1093

} catch (SQLException e) {

1094

return false;

1095

}

1096

}

1097

}

1098

```

1099