--- /dev/null
+package de.unixwork.rssreader
+
+import java.sql.Connection
+import java.sql.DriverManager
+
+object Database {
+ val connection: Connection
+
+ init {
+ connection = DriverManager.getConnection("jdbc:h2:~/.rssreader/feeds")
+ ensureSchema(connection)
+ }
+
+ private fun ensureSchema(conn: Connection) {
+ val stmt = conn.createStatement()
+ val rs = stmt.executeQuery(
+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'FEEDCOLLECTIONS'"
+ )
+
+ var tableExists = false
+ if (rs.next()) {
+ tableExists = rs.getInt(1) > 0
+ }
+ rs.close()
+ stmt.close()
+
+ if (!tableExists) {
+ println("Database empty — creating tables...")
+ conn.createStatement().use { createStmt ->
+ createStmt.addBatch("""
+ CREATE TABLE feedcollections (
+ feedcollection_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ name VARCHAR,
+ update_interval INT
+ )
+ """.trimIndent())
+
+ createStmt.addBatch("""
+ CREATE TABLE feeds(
+ feed_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ feedcollection_id INT NOT NULL REFERENCES feedcollections(feedcollection_id) ON DELETE CASCADE,
+ url VARCHAR NOT NULL,
+ last_update TIMESTAMP
+ )
+ """.trimIndent())
+
+ createStmt.addBatch("""
+ CREATE TABLE items (
+ item_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ feed_id INT NOT NULL REFERENCES feeds(feed_id),
+ title VARCHAR NOT NULL,
+ link VARCHAR NOT NULL,
+ description CLOB,
+ author VARCHAR,
+ pub_date TIMESTAMP,
+ guid VARCHAR UNIQUE,
+ content CLOB
+ )
+ """.trimIndent())
+
+ createStmt.executeBatch()
+ }
+ } else {
+ println("Database schema already exists.")
+ }
+ }
+}