diff options
author | Jonas Kohl | 2024-09-09 17:57:00 +0200 |
---|---|---|
committer | Jonas Kohl | 2024-09-09 17:57:00 +0200 |
commit | 34b1b391d4b03659a96f868857c230002b351514 (patch) | |
tree | 4173dd2831963d2bf85676de7e821b913640e43a /src/application/mystic/forum/Database.php | |
parent | 415a0a96a76afbe7f1ad2f51862641793caf1b6c (diff) |
More updates
Diffstat (limited to 'src/application/mystic/forum/Database.php')
-rw-r--r-- | src/application/mystic/forum/Database.php | 26 |
1 files changed, 25 insertions, 1 deletions
diff --git a/src/application/mystic/forum/Database.php b/src/application/mystic/forum/Database.php index f574386..9b9cf55 100644 --- a/src/application/mystic/forum/Database.php +++ b/src/application/mystic/forum/Database.php @@ -10,6 +10,7 @@ use mystic\forum\attributes\NotNull; use mystic\forum\attributes\PrimaryKey; use mystic\forum\attributes\References; use mystic\forum\attributes\Table; +use mystic\forum\exceptions\DatabaseConnectionException; use mystic\forum\orm\Entity; use mystic\forum\utils\ArrayUtils; use mystic\forum\utils\StringUtils; @@ -26,7 +27,13 @@ class Database { private const REFERENCES = 0b0000_0100; public function __construct(string $connectionString) { - $this->connection = \pg_connect($connectionString); + try { + $conn = \pg_connect($connectionString); + if ($conn !== false) + $this->connection = $conn; + } catch (\ErrorException $ex) { + throw new DatabaseConnectionException($ex->getMessage(), $ex->getCode(), $ex); + } } public static function getConnectionString(string $host, string $user, string $password, string $dbname, int $port = 5432): string { @@ -281,6 +288,23 @@ class Database { return true; } + public function delete(Entity &$entity): bool { + $entityClassName = get_class($entity); + $tableName = self::getTableName($entityClassName); + $reflClass = new ReflectionClass($entityClassName); + $cols = self::getColumns($reflClass); + $primaryCol = self::getPrimaryKeyColumn($cols); + if ($primaryCol === null) + throw new \RuntimeException("Deleting an entity requires a primary key column to be specified"); + $query = "DELETE FROM $tableName WHERE $primaryCol = \$1;"; + $result = \pg_query_params($this->connection, $query, [ $entity->{$cols[$primaryCol]["propertyName"]} ]); + if ($result === false) + throw new \RuntimeException("Deletion failed: " . \pg_last_error($this->connection)); + $num_affected_rows = \pg_affected_rows($result); + \pg_free_result($result); + return $num_affected_rows >= 1; + } + public function update(Entity &$entity): bool { $tableName = self::getTableName(get_class($entity)); $reflClass = new ReflectionClass($entity); |