From deacd0dfc195bca41af631114804d29937337cd8 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Wed, 17 Jan 2024 02:11:31 +0900 Subject: . --- services/app/src/Database/Connection.php | 93 ++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 services/app/src/Database/Connection.php (limited to 'services/app/src/Database') diff --git a/services/app/src/Database/Connection.php b/services/app/src/Database/Connection.php new file mode 100644 index 0000000..01f46b2 --- /dev/null +++ b/services/app/src/Database/Connection.php @@ -0,0 +1,93 @@ +conn = self::tryConnect( + "$driver:host=$host;port=$port;dbname=$name;user=$user;password=$password", + $max_tries, + $sleep_sec, + ); + } + + public static function tryConnect( + string $dsn, + int $max_tries, + int $sleep_sec, + ): PDO { + $tries = 0; + while (true) { + try { + return self::connect($dsn); + } catch (PDOException $e) { + if ($max_tries <= $tries) { + throw $e; + } + sleep($sleep_sec); + } + $tries++; + } + } + + public function query(): QueryBuilder + { + return new QueryBuilder($this->conn); + } + + /** + * @template T + * @param callable(): T $fn + * @return T + */ + public function transaction(callable $fn): mixed + { + $this->conn->beginTransaction(); + try { + $result = $fn(); + $this->conn->commit(); + return $result; + } catch (Exception $e) { + $this->conn->rollBack(); + throw $e; + } + } + + /** + * @throws PDOException + */ + private static function connect(string $dsn): PDO + { + return new PDO( + dsn: $dsn, + options: [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_PERSISTENT => true, + ], + ); + } +} -- cgit v1.2.3-70-g09d2