CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-typesafe-play--play-jdbc-2-11

Play Framework JDBC support library providing database access, connection pooling, and database configuration management for Play applications.

Pending
Overview
Eval results
Files

connection-pooling.mddocs/

Connection Pooling

HikariCP-based connection pool implementation with comprehensive configuration options, performance monitoring, and lifecycle management.

Capabilities

ConnectionPool Interface

Abstract interface for connection pool implementations.

trait ConnectionPool {
  /** Create a data source with the given configuration */
  def create(name: String, dbConfig: DatabaseConfig, configuration: Config): DataSource
  /** Close the given data source */
  def close(dataSource: DataSource): Unit
}

ConnectionPool Factory Methods

Factory methods for creating connection pool instances.

object ConnectionPool {
  /** Load a connection pool from a configured connection pool with Injector support */
  def fromConfig(
    config: String,
    injector: Injector,
    environment: Environment, 
    default: ConnectionPool
  ): ConnectionPool
  
  /** Load a connection pool from configuration for compile-time DI */
  def fromConfig(
    config: String, 
    environment: Environment, 
    default: ConnectionPool
  ): ConnectionPool
  
  /** Extract and process database URL, supporting shortcut formats */
  def extractUrl(maybeUrl: Option[String], mode: Mode): (Option[String], Option[(String, String)])
  
  /** Wrap a data source for SQL logging if logSql is enabled */
  private[db] def wrapToLogSql(dataSource: DataSource, configuration: Config): DataSource
  
  /** Unwrap a data source if it has been wrapped for SQL logging */
  private[db] def unwrap(dataSource: DataSource): DataSource
}

Usage Examples:

import play.api.db._
import play.api.Environment

// Create connection pool for compile-time DI
val environment = Environment.simple()
val defaultPool = new HikariCPConnectionPool(environment)
val pool = ConnectionPool.fromConfig("hikaricp", environment, defaultPool)

// URL extraction with credential parsing
val (extractedUrl, credentials) = ConnectionPool.extractUrl(
  Some("postgres://user:pass@localhost:5432/mydb"), 
  play.api.Mode.Dev
)
// extractedUrl: Some("jdbc:postgresql://localhost:5432/mydb")
// credentials: Some(("user", "pass"))

HikariCP Implementation

HikariCP-based implementation of the ConnectionPool interface.

@Singleton
class HikariCPConnectionPool @Inject()(environment: Environment) extends ConnectionPool {
  /** Create a HikariCP data source with the given configuration */
  override def create(name: String, dbConfig: DatabaseConfig, configuration: Config): DataSource
  /** Close the HikariCP data source */
  override def close(dataSource: DataSource): Unit
}

Usage Examples:

import play.api.db._
import play.api.{Configuration, Environment}
import com.typesafe.config.ConfigFactory

val environment = Environment.simple()
val pool = new HikariCPConnectionPool(environment)

val dbConfig = DatabaseConfig(
  driver = Some("org.postgresql.Driver"),
  url = Some("jdbc:postgresql://localhost/myapp"),
  username = Some("dbuser"), 
  password = Some("dbpass"),
  jndiName = None
)

val config = ConfigFactory.parseString("""
  hikaricp {
    maximumPoolSize = 20
    minimumIdle = 5
    connectionTimeout = 30 seconds
    idleTimeout = 10 minutes
    maxLifetime = 30 minutes
  }
""")

val dataSource = pool.create("myapp", dbConfig, config)
try {
  val connection = dataSource.getConnection()
  // Use connection...
  connection.close()
} finally {
  pool.close(dataSource)
}

HikariCP Configuration

Comprehensive configuration options for HikariCP connection pools.

private[db] class HikariCPConfig(dbConfig: DatabaseConfig, configuration: Configuration) {
  def toHikariConfig: HikariConfig
}

Configuration Properties:

Essential configurations:

  • dataSourceClassName - Data source class name (alternative to driver/url)
  • jdbcUrl - JDBC URL (from dbConfig.url)
  • driverClassName - JDBC driver class (from dbConfig.driver)
  • username - Database username (from dbConfig.username)
  • password - Database password (from dbConfig.password)

Frequently used:

  • autoCommit - Auto-commit behavior (default: true)
  • connectionTimeout - Maximum wait time for connection (default: 30 seconds)
  • idleTimeout - Maximum idle time before connection is retired (default: 10 minutes)
  • maxLifetime - Maximum lifetime of a connection (default: 30 minutes)
  • connectionTestQuery - Query to validate connections
  • minimumIdle - Minimum number of idle connections
  • maximumPoolSize - Maximum number of connections in pool (default: 10)
  • poolName - User-defined name for the connection pool

Infrequently used:

  • initializationFailTimeout - Pool initialization failure timeout
  • isolateInternalQueries - Isolate internal pool queries
  • allowPoolSuspension - Allow pool suspension
  • readOnly - Default read-only mode for connections
  • registerMbeans - Register JMX management beans
  • connectionInitSql - SQL executed after connection creation
  • catalog - Default catalog name
  • transactionIsolation - Default transaction isolation level
  • validationTimeout - Maximum time for connection validation
  • leakDetectionThreshold - Connection leak detection threshold

Configuration Example:

db.default {
  driver = "org.postgresql.Driver"
  url = "jdbc:postgresql://localhost/myapp"
  username = "dbuser"
  password = "dbpass"
  
  # HikariCP specific settings
  hikaricp {
    # Pool sizing
    minimumIdle = 5
    maximumPoolSize = 20
    
    # Connection timeouts
    connectionTimeout = 30 seconds
    idleTimeout = 10 minutes
    maxLifetime = 30 minutes
    
    # Connection testing
    connectionTestQuery = "SELECT 1"
    
    # Pool behavior
    autoCommit = true
    readOnly = false
    
    # Monitoring
    registerMbeans = true
    leakDetectionThreshold = 60 seconds
    
    # Data source properties
    dataSource {
      cachePrepStmts = true
      prepStmtCacheSize = 250
      prepStmtCacheSqlLimit = 2048
      useServerPrepStmts = true
    }
  }
  
  # SQL logging
  logSql = false
}

Database URL Parsing

Support for shortcut URL formats with automatic credential extraction.

Supported URL Formats:

PostgreSQL shortcut:

postgres://username:password@host/database

Converts to:

jdbc:postgresql://host/database

MySQL shortcut:

mysql://username:password@host/database

Converts to:

jdbc:mysql://host/database?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci

H2 development mode:

jdbc:h2:mem:testdb

Automatically adds DB_CLOSE_DELAY=-1 in development mode.

Usage Examples:

import play.api.db.ConnectionPool
import play.api.Mode

// PostgreSQL shortcut URL
val (pgUrl, pgCreds) = ConnectionPool.extractUrl(
  Some("postgres://myuser:mypass@db.example.com/production"),
  Mode.Prod
)
// pgUrl: Some("jdbc:postgresql://db.example.com/production")
// pgCreds: Some(("myuser", "mypass"))

// MySQL shortcut URL  
val (mysqlUrl, mysqlCreds) = ConnectionPool.extractUrl(
  Some("mysql://app:secret@mysql.example.com/appdb"),
  Mode.Prod  
)
// mysqlUrl: Some("jdbc:mysql://mysql.example.com/appdb?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci")
// mysqlCreds: Some(("app", "secret"))

// H2 in development
val (h2Url, h2Creds) = ConnectionPool.extractUrl(
  Some("jdbc:h2:mem:testdb"),
  Mode.Dev
)
// h2Url: Some("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1")
// h2Creds: None

SQL Logging

Optional SQL logging capability using jdbcdslog proxy.

private[db] def wrapToLogSql(dataSource: DataSource, configuration: Config): DataSource
private[db] def unwrap(dataSource: DataSource): DataSource

Configuration:

db.default {
  # Enable SQL logging
  logSql = true
}

When enabled, all SQL statements and their parameters are logged to the console, useful for development and debugging.

JNDI Support

Support for binding data sources to JNDI names.

Configuration:

db.default {
  driver = "org.postgresql.Driver"
  url = "jdbc:postgresql://localhost/myapp"
  jndiName = "java:comp/env/jdbc/MyAppDS"
}

The data source will be automatically bound to the specified JNDI name during creation.

Performance Tuning

Connection Pool Sizing

  • minimumIdle: Should be same as maximumPoolSize for stable workloads
  • maximumPoolSize: Formula: ((core_count * 2) + disk_count) for typical OLTP workloads
  • connectionTimeout: Should be longer than typical connection acquisition time
  • idleTimeout: Should be shorter than database server connection timeout

Prepared Statement Caching

db.default {
  hikaricp {
    dataSource {
      cachePrepStmts = true
      prepStmtCacheSize = 250
      prepStmtCacheSqlLimit = 2048
      useServerPrepStmts = true
    }
  }
}

Connection Leak Detection

db.default {
  hikaricp {
    leakDetectionThreshold = 60 seconds
    registerMbeans = true
  }
}

Error Handling

  • SQLException: Thrown by underlying database operations
  • Connection timeouts: Thrown when connection acquisition exceeds connectionTimeout
  • Pool exhaustion: Thrown when no connections are available within timeout period
  • Configuration errors: Thrown for invalid HikariCP configuration parameters

Monitoring

  • JMX MBeans: Enable with registerMbeans = true for pool metrics
  • Connection leak detection: Configure leakDetectionThreshold to detect leaked connections
  • SQL logging: Enable logSql = true for development debugging

Install with Tessl CLI

npx tessl i tessl/maven-com-typesafe-play--play-jdbc-2-11

docs

connection-pooling.md

database-configuration.md

database-management.md

database-operations.md

dependency-injection.md

index.md

tile.json