summaryrefslogtreecommitdiff
path: root/opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt
diff options
context:
space:
mode:
Diffstat (limited to 'opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt')
-rw-r--r--opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt71
1 files changed, 71 insertions, 0 deletions
diff --git a/opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt b/opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt
new file mode 100644
index 00000000..69314ef3
--- /dev/null
+++ b/opendc-common/src/main/kotlin/org/opendc/common/utils/PostgresqlDB.kt
@@ -0,0 +1,71 @@
+package org.opendc.common.utils
+
+import java.sql.Connection
+import java.sql.DriverManager
+import java.sql.SQLException
+
+/**
+ * Represents the Postgresql database.
+ * On setup cleans the entire database and creates empty tables.
+ *
+ * @author Mateusz
+ *
+ * @param address ipv4 address
+ * @param port postgres post
+ * @param dbName database name
+ * @param user
+ * @param password
+ */
+public class PostgresqlDB(
+ address : String,
+ port : Int,
+ dbName : String,
+ private var user : String,
+ private var password : String,
+) {
+ private var connection : Connection? = null
+ private var dbUrl : String = ""
+
+ init {
+ dbUrl = "jdbc:postgresql://$address:$port/$dbName"
+ println(dbUrl)
+ try {
+ connection = DriverManager.getConnection(dbUrl, user, password)
+ clear()
+ setup()
+ } catch (e: SQLException) {
+ print("${e.message}")
+ }
+ }
+ public fun setup(){
+ val CREATE_TABLE = """
+ CREATE TABLE metrics (
+ id SERIAL PRIMARY KEY,
+ timestamp bigint,
+ tasksActive integer,
+ clusterName varchar(10));
+ """.trimIndent()
+
+ try {
+ val conn = DriverManager.getConnection(dbUrl, user, password)
+ val st = conn.createStatement()
+ st.executeQuery(CREATE_TABLE)
+ } catch (e: SQLException){
+ println("${e.message}")
+ }
+ }
+
+ public fun clear(){
+ val DELETE_ALL_TABLES = """
+ DROP SCHEMA public CASCADE;
+ CREATE SCHEMA public;
+ """.trimIndent()
+ try {
+ val conn = DriverManager.getConnection(dbUrl, user, password)
+ val st = conn.createStatement()
+ st.executeQuery(DELETE_ALL_TABLES)
+ } catch (e: SQLException){
+ println("${e.message}")
+ }
+ }
+} \ No newline at end of file