BlueGit

blue-star tribegen

Files

tribegen / web / src / Database / Database.php

Database.php

Database.php 1.5 KiB Download Raw
1<?php
2
3class Database
4{
5 private static $instance = null;
6 private $pdo;
7
8 private function __construct()
9 {
10 $dataDir = __DIR__ . '\\..\\..\\data\\';
11 $dbPath = $dataDir . 'tribegen.db';
12
13 if (!is_dir($dataDir)) {
14 if (!mkdir($dataDir, 0775, true) && !is_dir($dataDir)) {
15 throw new RuntimeException("Failed to create data directory: $dataDir");
16 }
17 }
18
19 if (!is_writable($dataDir)) {
20 throw new RuntimeException("Data directory is not writable: $dataDir");
21 }
22
23 $this->pdo = new \PDO('sqlite:' . $dbPath);
24 $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
25 $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
26 }
27
28 public static function getInstance()
29 {
30 if (self::$instance === null) {
31 self::$instance = new self();
32 }
33 return self::$instance;
34 }
35
36 public function getPDO()
37 {
38 return $this->pdo;
39 }
40
41 public function initializeTables()
42 {
43 // Only the users table is stored in the database
44 // All game data is stored as JSON files in /data/saves/
45 $this->pdo->exec("
46 CREATE TABLE IF NOT EXISTS users (
47 id INTEGER PRIMARY KEY AUTOINCREMENT,
48 email TEXT UNIQUE NOT NULL,
49 password_hash TEXT NOT NULL,
50 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
51 );
52 ");
53 }
54}