1 | <?php |
2 | |
3 | class Bd |
4 | { |
5 | private static ?PDO $pdo = null; |
6 | |
7 | static function pdo(): PDO |
8 | { |
9 | if (self::$pdo === null) { |
10 | |
11 | self::$pdo = new PDO( |
12 | |
13 | "sqlite:srvauno.db", |
14 | |
15 | null, |
16 | |
17 | null, |
18 | |
19 | [PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] |
20 | ); |
21 | |
22 | self::$pdo->exec( |
23 | 'CREATE TABLE IF NOT EXISTS PASATIEMPO ( |
24 | PAS_ID INTEGER, |
25 | PAS_NOMBRE TEXT NOT NULL, |
26 | CONSTRAINT PAS_PK |
27 | PRIMARY KEY(PAS_ID), |
28 | CONSTRAINT PAS_NOM_UNQ |
29 | UNIQUE(PAS_NOMBRE), |
30 | CONSTRAINT PAS_NOM_NV |
31 | CHECK(LENGTH(PAS_NOMBRE) > 0) |
32 | )' |
33 | ); |
34 | self::$pdo->exec( |
35 | 'CREATE TABLE IF NOT EXISTS AMIGO ( |
36 | AMI_ID INTEGER, |
37 | AMI_NOMBRE TEXT NOT NULL, |
38 | PAS_ID INTEGER, |
39 | CONSTRAINT AMI_PK |
40 | PRIMARY KEY(AMI_ID), |
41 | CONSTRAINT AMI_NOM_UNQ |
42 | UNIQUE(AMI_NOMBRE), |
43 | CONSTRAINT AMI_NOM_NV |
44 | CHECK(LENGTH(AMI_NOMBRE) > 0), |
45 | CONSTRAINT AMI_PAS_FK |
46 | FOREIGN KEY (PAS_ID) REFERENCES PASATIEMPO(PAS_ID) |
47 | )' |
48 | ); |
49 | |
50 | $cantidadDePasatiempos = |
51 | self::$pdo->query("SELECT COUNT(PAS_ID) FROM PASATIEMPO")->fetchColumn(); |
52 | |
53 | if ($cantidadDePasatiempos === 0) { |
54 | self::$pdo->exec( |
55 | "INSERT INTO PASATIEMPO (PAS_NOMBRE) VALUES ('Futbol'), ('Videojuegos')" |
56 | ); |
57 | } |
58 | } |
59 | |
60 | return self::$pdo; |
61 | } |
62 | } |
63 | |