From f1dafb3f4df9d64c30eda0b27f9777869cfef98d Mon Sep 17 00:00:00 2001 From: bernd Date: Wed, 3 Mar 2021 17:26:38 +0100 Subject: [PATCH] funktion zum erstellen der tabelle requests wieder eingebunden --- lib/db.php | 45 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/lib/db.php b/lib/db.php index 86badeb..92e2baa 100644 --- a/lib/db.php +++ b/lib/db.php @@ -100,33 +100,64 @@ class Database { public function __construct($pdo, $log) { + /** + * Übernimmt beim Erstellen der Klasse die Connection zur Datenbank + * und die Instanz des Loggers. Läßt kontrollieren ob die Tabelle zum + * Eintragen der Requests vorhanden ist und stößt die Erstellung der + * Tabelle an, wenn sie fehlt. + * TODO: Geht das eleganter? So wird das bei jeder Anfrage + * ausgeführt. + */ + $this->pdo = $pdo; $this->log = $log; $this->log->d("Databaseobject successfull created"); - // hier vielleicht TableCreate hin + if ($this->TableExists() === false) { + $this->log->n("No table requests found. Try to create table"); + $this->createTable(); + } } - public function TableExists(): int + private function TableExists(): bool { + /** + * Kontrolliert, ob eine Tabelle zum Eintragen der Requests + * vorhanden ist. + * TODO: Die Query ist Postgres spezifisch. Treiber durchreichen und + * eine Weiche anlegen? + */ + $stmt = "SELECT * FROM information_schema.tables WHERE table_type = 'BASE TABLE' and table_name = 'requests'"; $response = $this->pdo->query($stmt); - $count = $response->rowCount(); - return $count; + if ($response->rowCount() === 0) { + return false; + } + return true; } - public function createTable() + public function createTable(): bool { + /** + * Erstellt die Tabelle Requests. + */ + $stmt = "CREATE TABLE IF NOT EXISTS requests ( id serial PRIMARY KEY, nick varchar(80) NOT NULL UNIQUE, email varchar(80) NOT NULL, token char(32) NOT NULL UNIQUE, time integer NOT NULL);"; - $this->pdo->exec($stmt); - return $this; + try { + $this->pdo->exec($stmt); + } catch (PDOException $e) { + $this->log-e("Failed to create table requests"); + return false; + } + $this->log-n("Table requests successfull created"); + return true; }