Home

Awesome

hikari-cp GitHub Workflow Status Clojars Project

A Clojure wrapper to HikariCP - "zero-overhead" production ready JDBC connection pool.

Installation

Add the following dependency to your project.clj file:

[hikari-cp "3.0.1"]

hikari-cp version 3.x targets Clojure 1.11. Version 2.14.3 was the last release for Clojure 1.9. Version 1.8.3 was the last release for Clojure 1.8.

Note that hikari-cp requires Java 11 or newer. Version 2.14.3 was the last release for Java 8.

You'll also need to add the JDBC driver needed for your database.

Configuration options

OptionRequiredDefault valueDescription
:auto-commitNotrueThis property controls the default auto-commit behavior of connections returned from the pool. It is a boolean value.
:read-onlyNofalseThis property controls whether Connections obtained from the pool are in read-only mode by default.
:connection-timeoutNo30000This property controls the maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown. 1000ms is the minimum value.
:validation-timeoutNo5000This property controls the maximum amount of time that a connection will be tested for aliveness. This value must be less than the :connection-timeout. The lowest accepted validation timeout is 1000ms (1 second).
:idle-timeoutNo600000This property controls the maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool.
:max-lifetimeNo1800000This property controls the maximum lifetime of a connection in the pool. A value of 0 indicates no maximum lifetime (infinite lifetime).
:minimum-idleNo10This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool.
:maximum-pool-sizeNo10This property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend.
:pool-nameNoAuto-generatedThis property represents a user-defined name for the connection pool and appears mainly in logging and JMX management consoles to identify pools and pool configurations.
:jdbc-urlYes¹NoneThis property sets the JDBC connection URL. Please note the h2 adapter expects :url instead of :jdbc-url.
:driver-class-nameNoNoneThis property sets the JDBC driver class.
:adapterYes¹NoneThis property sets the database adapter. Please check Adapters and corresponding datasource class names for the full list of supported adapters and their datasource class names. The value should be provided as a string.
:usernameNoNoneThis property sets the default authentication username used when obtaining Connections from the underlying driver.
:passwordNoNoneThis property sets the default authentication password used when obtaining Connections from the underlying driver.
:database-nameNoNoneThis property sets the database name.
:server-nameNoDepends on the adapterThis property sets the hostname client connects to.
:port-numberNoDepends on the adapterThis property sets the port clients connects on.
:connection-test-queryNoNoneIf your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" databases that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive.
:leak-detection-thresholdNo0This property controls the amount of time that a connection can be out of the pool before a message is logged indicating a possible connection leak. A value of 0 means leak detection is disabled, minimum accepted value is 2000 (ms). ( ps: it's rarely needed option, use only for debugging )
:register-mbeansNofalseThis property register mbeans which can be used in jmx to monitor hikari-cp.
:connection-init-sqlNoNoneThis property sets a SQL statement that will be executed after every new connection creation before adding it to the pool.
:datasourceNoNoneThis property allows you to directly set the instance of the DataSource to be wrapped by the pool.
:datasource-class-nameNoNoneThis is the name of the DataSource class provided by the JDBC driver.
:metric-registryNoNoneThis is an instance of a Dropwizard metrics MetricsRegistry.
:health-check-registryNoNoneThis is an instance of a Dropwizard metrics HealthCheckRegistry.
:metrics-tracker-factoryNoNoneThis is an implementation of a MetricsTrackerFactory (CodahaleMetricsTrackerFactory, MicrometerMetricsTrackerFactory, PrometheusMetricsTrackerFactory).
:transaction-isolationNoNoneConstant name from the Connection interface such as TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, etc.

¹ :adapter and :jdbc-url are mutually exclusive.

You can also add other datasource-specific configuration options. By default, keywords will be converted to the camelCase format add added as a datasource property, unless a special translation is defined:

;; {:tcp-keep-alive true} will be:
(.addDataSourceProperty config "tcpKeepAlive" true)

;; {:use-ssl false} has a custom translation, so it will be:
(.addDataSourceProperty config "useSSL" false)

;; {:tinyInt1isBit false} also has a custom translation to support
;; the incorrect property casing in the original java class.

Custom translations of properties can be added by extending the translate-property multimethod.

Please note: All time values are specified in milliseconds.

Adapters and corresponding datasource class names

AdapterDatasource class nameTested with hikari-cp
derbyorg.apache.derby.jdbc.ClientDataSourceNo
firebirdorg.firebirdsql.pool.FBSimpleDataSourceNo
db2com.ibm.db2.jcc.DB2SimpleDataSourceNo
h2org.h2.jdbcx.JdbcDataSourceYes
hsqldborg.hsqldb.jdbc.JDBCDataSourceNo
mariadborg.mariadb.jdbc.MySQLDataSourceNo
mysqlcom.mysql.jdbc.jdbc2.optional.MysqlDataSourceYes
mysql8com.mysql.cj.jdbc.MysqlDataSourceNo
neo4jorg.neo4j.jdbc.DataSourceNo
sqlserver-jtdsnet.sourceforge.jtds.jdbcx.JtdsDataSourceYes
sqlservercom.microsoft.sqlserver.jdbc.SQLServerDataSourceYes
oracleoracle.jdbc.pool.OracleDataSourceYes
pgjdbc-ngcom.impossibl.postgres.jdbc.PGDataSourceNo
postgresqlorg.postgresql.ds.PGSimpleDataSourceYes
fdbsqlcom.foundationdb.sql.jdbc.ds.FDBSimpleDataSourceNo
sybasecom.sybase.jdbc4.jdbc.SybDataSourceYes
sqliteorg.sqlite.SQLiteDataSourceNo

Usage

PostgreSQL example

(ns hikari-cp.example
  (:require [hikari-cp.core :refer :all]
            [clojure.java.jdbc :as jdbc]))

(def datasource-options {:auto-commit        true
                         :read-only          false
                         :connection-timeout 30000
                         :validation-timeout 5000
                         :idle-timeout       600000
                         :max-lifetime       1800000
                         :minimum-idle       10
                         :maximum-pool-size  10
                         :pool-name          "db-pool"
                         :adapter            "postgresql"
                         :username           "username"
                         :password           "password"
                         :database-name      "database"
                         :server-name        "localhost"
                         :port-number        5432
                         :register-mbeans    false})

(defonce datasource
  (delay (make-datasource datasource-options)))

(defn -main [& args]
  (jdbc/with-db-connection [conn {:datasource @datasource}]
    (let [rows (jdbc/query conn "SELECT 0")]
      (println rows)))
  (close-datasource @datasource))

Neo4j

(ns hikari-cp.example
  (:require [hikari-cp.core :refer :all]
            [clojure.java.jdbc :as jdbc]))

(def datasource-options {:jdbc-url "jdbc:neo4j:bolt://host:port/?username=neo4j&password=xxxx&debug=true"})

(defonce datasource
  (delay (make-datasource datasource-options)))

(defn -main [& args]
  (jdbc/with-db-connection [conn {:datasource @datasource}]
    (let [rows (jdbc/query conn ["MATCH (n:Foo) WHERE n.name = ? RETURN n" "john"])]
      (println rows)))
  (close-datasource @datasource))

H2 minimal config example

(def datasource-options {:adapter "h2"
                         :url     "jdbc:h2:~/test"})

Oracle example

(ns hikari-cp.example
  (:require [hikari-cp.core :refer :all]
            [clojure.java.jdbc :as jdbc]))

(def datasource-options {:username      "username"
                         :password      "password"
                         :database-name "database"
                         :server-name   "localhost"
                         :port-number   1521
                         :driverType    "thin"       ; Other options are oci8, oci or kprb. See jdbc.pool.OracleDataSource.makeURL()
                         :adapter       "oracle"})

(defonce datasource
  (delay (make-datasource datasource-options)))

(defn -main [& args]
  (jdbc/with-db-connection [conn {:datasource @datasource}]
    (let [rows (jdbc/query conn "SELECT 0 FROM dual")]
      (println rows)))
  (close-datasource @datasource))

Sybase example

(ns hikari-cp.example
  (:require [hikari-cp.core :refer :all]
            [clojure.java.jdbc :as jdbc]))

(def datasource-options {:username      "username"
                         :password      "password"
                         :database-name "database"
                         :server-name   "localhost"
                         :port-number   5900
                         :adapter       "sybase"}) ; assumes jconn4.jar (com.sybase.jdbc4.jdbc.SybDataSource)

; if you're using jconn2.jar or jconn3.jar replace :adapter "sybase" with the following
; :datasource-class-name "com.sybase.jdbc3.jdbc.SybDataSource"
; or
; :datasource-class-name "com.sybase.jdbc2.jdbc.SybDataSource"

(defonce datasource
  (delay (make-datasource datasource-options)))

(defn -main [& args]
  (jdbc/with-db-connection [conn {:datasource @datasource}]
    (let [rows (jdbc/query conn "SELECT 0")]
      (println rows)))
  (close-datasource @datasource))

SQLite example

(def datasource-options {:jdbc-url "jdbc:sqlite:db/database.db"})

ClickHouse example

hikari-cp can be used with official ClickHouse driver in following two ways:

  1. Using :datasource property:
(ns hikari-cp.example
  (:require
    [hikari-cp.core :refer :all]
    [next.jdbc :as jdbc])
  (:import
    [java.util Properties]
    [com.clickhouse.jdbc ClickHouseDataSource]))

(defonce clickhouse-datasource
  (let [jdbc-url "jdbc:ch://localhost:8123/test_db"
        properties (doto
                     (Properties.)
                     (.setProperty "user" "username")
                     (.setProperty "password" "password")
                     (.setProperty "client_name" "test_client")
                     (.setProperty "custom_http_params" "max_query_size=1000000"))]
    (ClickHouseDataSource. jdbc-url properties)))

(def datasource-options
  {:datasource clickhouse-datasource
   :connection-timeout 5000
   :maximum-pool-size 20
   :max-lifetime 300000
   :pool-name "clickhouse-conn-pool"})

(defonce datasource 
  (delay (make-datasource datasource-options)))

(defn -main
  [& args]
  (with-open [conn (jdbc/get-connection {:datasource @datasource})]
    (let [rows (jdbc/execute! conn ["SELECT 0"])]
      (println rows)))
  (close-datasource @datasource))
  1. Using :jdbc-url and :driver-class-name properties:
(ns hikari-cp.example
  (:require
    [hikari-cp.core :refer :all]
    [next.jdbc :as jdbc]))

(def datasource-options-2
  {:jdbc-url "jdbc:ch://localhost:8123/test_db"
   :username "username"
   :password "password"
   :driver-class-name "com.clickhouse.jdbc.ClickHouseDriver"
   :connection-timeout 5000
   :maximum-pool-size 20
   :max-lifetime 300000
   :pool-name "clickhouse-conn-pool"})

(defonce datasource
  (delay (make-datasource datasource-options)))

(defn -main
  [& args]
  (with-open [conn (jdbc/get-connection {:datasource @datasource})]
    (let [rows (jdbc/execute! conn ["SELECT 0"])]
      (println rows)))
  (close-datasource @datasource))

Notice

make-datasource will throw IllegalArgumentException when invalid arguments are provided:

(make-datasource (dissoc config :username :database-name))
;; IllegalArgumentException: Invalid configuration options: (:username :database-name)

License

Copyright © 2014 - 2024 Tomek Wałkuski and Jan Stępień

Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version.