1 | <?php |
2 | |
3 | require_once __DIR__ . "/../lib/php/selectFirst.php"; |
4 | require_once __DIR__ . "/../lib/php/insert.php"; |
5 | require_once __DIR__ . "/TABLA_ROL.php"; |
6 | |
7 | class Bd |
8 | { |
9 | |
10 | private static ?PDO $pdo = null; |
11 | |
12 | static function pdo(): PDO |
13 | { |
14 | if (self::$pdo === null) { |
15 | |
16 | self::$pdo = new PDO( |
17 | |
18 | "sqlite:srvamuchos.db", |
19 | |
20 | null, |
21 | |
22 | null, |
23 | |
24 | [PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] |
25 | ); |
26 | |
27 | self::$pdo->exec( |
28 | 'CREATE TABLE IF NOT EXISTS USUARIO ( |
29 | USU_ID INTEGER, |
30 | USU_CUE TEXT NOT NULL, |
31 | CONSTRAINT USU_PK |
32 | PRIMARY KEY(USU_ID), |
33 | CONSTRAINT USU_CUE_UNQ |
34 | UNIQUE(USU_CUE), |
35 | CONSTRAINT USU_CUE_NV |
36 | CHECK(LENGTH(USU_CUE) > 0) |
37 | )' |
38 | ); |
39 | self::$pdo->exec( |
40 | 'CREATE TABLE IF NOT EXISTS ROL ( |
41 | ROL_ID TEXT NOT NULL, |
42 | ROL_DESCRIPCION TEXT NOT NULL, |
43 | CONSTRAINT ROL_PK |
44 | PRIMARY KEY(ROL_ID), |
45 | CONSTRAINT ROL_ID_NV |
46 | CHECK(LENGTH(ROL_ID) > 0), |
47 | CONSTRAINT ROL_DESCR_UNQ |
48 | UNIQUE(ROL_DESCRIPCION), |
49 | CONSTRAINT ROL_DESCR_NV |
50 | CHECK(LENGTH(ROL_DESCRIPCION) > 0) |
51 | )' |
52 | ); |
53 | self::$pdo->exec( |
54 | 'CREATE TABLE IF NOT EXISTS USU_ROL ( |
55 | USU_ID INTEGER NOT NULL, |
56 | ROL_ID TEXT NOT NULL, |
57 | CONSTRAINT USU_ROL_PK |
58 | PRIMARY KEY(USU_ID, ROL_ID), |
59 | CONSTRAINT USU_ROL_USU_FK |
60 | FOREIGN KEY (USU_ID) REFERENCES USUARIO(USU_ID), |
61 | CONSTRAINT USU_ROL_ROL_FK |
62 | FOREIGN KEY (ROL_ID) REFERENCES ROL(ROL_ID) |
63 | )' |
64 | ); |
65 | |
66 | if (selectFirst(self::$pdo, ROL, [ROL_ID => "Administrador"]) === false) { |
67 | insert( |
68 | pdo: self::$pdo, |
69 | into: ROL, |
70 | values: [ |
71 | ROL_ID => "Administrador", |
72 | ROL_DESCRIPCION => "Administra el sistema." |
73 | ] |
74 | ); |
75 | } |
76 | |
77 | if (selectFirst(self::$pdo, ROL, [ROL_ID => "Cliente"]) === false) { |
78 | insert( |
79 | pdo: self::$pdo, |
80 | into: ROL, |
81 | values: [ |
82 | ROL_ID => "Cliente", |
83 | ROL_DESCRIPCION => "Realiza compras." |
84 | ] |
85 | ); |
86 | } |
87 | } |
88 | |
89 | return self::$pdo; |
90 | } |
91 | } |
92 | |