summaryrefslogtreecommitdiff
path: root/common/src/main/kotlin/db/DbPool.kt
blob: f003e1d2c7a0a9fff75e7cc60c1430798e0a94e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024 Taler Systems S.A.
 *
 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.
 *
 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

package tech.libeufin.common.db

import tech.libeufin.common.*
import org.postgresql.jdbc.PgConnection
import org.postgresql.util.PSQLState
import java.sql.SQLException
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

open class DbPool(cfg: DatabaseConfig, schema: String) : java.io.Closeable {
    val pgSource = pgDataSource(cfg.dbConnStr)
    private val pool: HikariDataSource

    init {
        val config = HikariConfig()
        config.dataSource = pgSource
        config.schema = schema.replace("-", "_")
        config.transactionIsolation = "TRANSACTION_SERIALIZABLE"
        pool = HikariDataSource(config)
        pool.connection.use { con ->
            val meta = con.metaData
            val majorVersion = meta.databaseMajorVersion
            val minorVersion = meta.databaseMinorVersion
            if (majorVersion < MIN_VERSION) {
                throw Exception("postgres version must be at least $MIN_VERSION.0 got $majorVersion.$minorVersion")
            }
            checkMigrations(con, cfg, schema)
        }
    }

    suspend fun <R> conn(lambda: suspend (PgConnection) -> R): R {
        // Use a coroutine dispatcher that we can block as JDBC API is blocking
        return withContext(Dispatchers.IO) {
            pool.connection.use { lambda(it.unwrap(PgConnection::class.java)) }
        }
    }

    suspend fun <R> serializable(lambda: suspend (PgConnection) -> R): R = conn { conn ->
        repeat(SERIALIZATION_RETRY) {
            try {
                return@conn lambda(conn)
            } catch (e: SQLException) {
                if (e.sqlState != PSQLState.SERIALIZATION_FAILURE.state)
                    throw e
            }
        }
        try {
            return@conn lambda(conn)
        } catch (e: SQLException) {
            logger.warn("Serialization failure after $SERIALIZATION_RETRY retry")
            throw e
        }
    }

    override fun close() {
        pool.close()
    }
}