summaryrefslogtreecommitdiff
path: root/classes/Db.php
blob: dcaa482e5abb4e3bc33a8a1e4056870dca3a226b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php

class Db {
	private static ?Db $instance = null;

	private PDO $pdo;

	private function __construct() {
		$db_type = Config::get(Config::DB_TYPE);

		try {
			$this->pdo = new PDO(self::get_dsn(),
				Config::get(Config::DB_USER),
				Config::get(Config::DB_PASS));

			if ($db_type == 'sqlite') {
				$this->pdo->query('PRAGMA journal_mode = wal');
			}
		} catch (Exception $e) {
			user_error($e, E_USER_WARNING);
			die("Unable to initialize database driver: " . Config::get(Config::DB_TYPE));
		}

		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		try {
			ORM::configure(self::get_dsn());
			ORM::configure('return_result_sets', true);

			if ($db_type == 'pgsql') {
				ORM::configure('username', Config::get(Config::DB_USER));
				ORM::configure('password', Config::get(Config::DB_PASS));
				ORM::configure('return_result_sets', true);
			} else {
				ORM::raw_execute('PRAGMA journal_mode = wal');
			}

		} catch (Exception $e) {
			user_error($e, E_USER_WARNING);
			die("Unable to initialize ORM layer.");
		}
	}

	public static function get_dsn() : string {
		$db_type = Config::get(Config::DB_TYPE);

		if ($db_type == 'pgsql') {
			$db_port = Config::get(Config::DB_PORT) ? ';port=' . Config::get(Config::DB_PORT) : '';
			$db_host = Config::get(Config::DB_HOST) ? ';host=' . Config::get(Config::DB_HOST) : '';

			return $db_type . ':dbname=' . Config::get(Config::DB_NAME) . $db_host . $db_port;

		} else {
			return $db_type . ':' . Config::get(Config::SCRATCH_DB);
		}
	}

	public static function pdo() : PDO {
		if (self::$instance == null)
			self::$instance = new self();

		return self::$instance->pdo;
	}

};