summaryrefslogtreecommitdiff
path: root/opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt
blob: 03fd902c8cbcf9c7c79ac1cf678d9fe40717761f (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
package org.opendc.common.utils

import com.fasterxml.jackson.dataformat.toml.TomlMapper
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.util.Properties
/**
 * Represents the Postgresql database.
 * On setup cleans the entire database.
 *
 * @author Mateusz Kwiatkowski
 *
 * @see <a href=https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/DriverManager.html>
 *     https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/DriverManager.html</a>
 */
@Suppress("DEPRECATION")
public class PostgresqlDB {
    private var properties = Properties()
    private var connection : Connection? = null

    init {
        try {
            properties  = TomlMapper().readerFor(Properties().javaClass)
                .readValue(PostgresqlDB::class.java.getResource("/database.toml"))
            connection = DriverManager.getConnection(
                properties.getProperty("address").asJdbc(properties.getProperty("database")),
                properties.getProperty("user"),
                properties.getProperty("password"))
            clear()
        } catch (e: SQLException) {
            print("${e.message}")
        }
    }
    public fun clear(){
        val DELETE_ALL_TABLES = """
            DROP SCHEMA public CASCADE;
            CREATE SCHEMA public;
        """.trimIndent()
        try {
            val st = connection?.createStatement()
            st?.executeQuery(DELETE_ALL_TABLES)
        } catch (e: SQLException){
            println("${e.message}")
        }
    }

    private fun String.asJdbc(database : String) : String {
        return "jdbc:postgresql://$this/$database"

    }

}