|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Erykai\Migration; |
|
4
|
|
|
|
|
5
|
|
|
class Migration extends Resource |
|
6
|
|
|
{ |
|
7
|
|
|
public function table(string $name): void |
|
8
|
|
|
{ |
|
9
|
|
|
$this->setTable($name); |
|
10
|
|
|
} |
|
11
|
|
|
|
|
12
|
|
|
public function column(string $name): static |
|
13
|
|
|
{ |
|
14
|
|
|
$this->setNull(" NOT NULL"); |
|
15
|
|
|
$this->setColumns($name); |
|
16
|
|
|
return $this; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function type(string $name): static |
|
20
|
|
|
{ |
|
21
|
|
|
$this->setTypes($name); |
|
22
|
|
|
return $this; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function null(): static |
|
26
|
|
|
{ |
|
27
|
|
|
$key = count($this->null) - 1; |
|
28
|
|
|
$this->null[$key] = ""; |
|
29
|
|
|
return $this; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function default(bool|string $default = false): static |
|
33
|
|
|
{ |
|
34
|
|
|
$this->setDefault($default); |
|
35
|
|
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function primary(string $nameColumn) |
|
39
|
|
|
{ |
|
40
|
|
|
$query = "ALTER TABLE `{$this->getTable()}` ADD PRIMARY KEY (`$nameColumn`)"; |
|
41
|
|
|
$this->conn->query($query); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function autoIncrement(string $nameColumn) |
|
45
|
|
|
{ |
|
46
|
|
|
$query = "ALTER TABLE `{$this->getTable()}` MODIFY `$nameColumn` int(11) NOT NULL AUTO_INCREMENT;"; |
|
47
|
|
|
$this->conn->query($query); |
|
48
|
|
|
$this->conn->query("COMMIT;"); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function addKey(string $nameKey, string $nameColumn, string $tableReference, string $idTableReference) |
|
52
|
|
|
{ |
|
53
|
|
|
$this->setKey($nameKey); |
|
54
|
|
|
$this->conn->query("ALTER TABLE `{$this->getTable()}` ADD KEY `{$this->getKey()}` (`$nameColumn`);"); |
|
55
|
|
|
$this->conn->query("ALTER TABLE `{$this->getTable()}` ADD CONSTRAINT `{$this->getKey()}` FOREIGN KEY (`$nameColumn`) REFERENCES `$tableReference` (`$idTableReference`) ON DELETE CASCADE ON UPDATE CASCADE;"); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
public function save(): void |
|
60
|
|
|
{ |
|
61
|
|
|
$query = "("; |
|
62
|
|
|
$default = null; |
|
63
|
|
|
foreach ($this->getColumns() as $key => $column) { |
|
64
|
|
|
if ($this->getDefault()[$key]) { |
|
65
|
|
|
$default = ' DEFAULT ' . $this->getDefault()[$key]; |
|
66
|
|
|
} |
|
67
|
|
|
$query .= "`$column` {$this->getTypes()[$key]}$default{$this->getNull()[$key]},"; |
|
68
|
|
|
} |
|
69
|
|
|
$query = rtrim($query, ","); |
|
70
|
|
|
$query .= ") "; |
|
71
|
|
|
$query .= "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; |
|
72
|
|
|
$data = "CREATE TABLE {$this->getTable()} $query"; |
|
73
|
|
|
$this->conn->query($data); |
|
74
|
|
|
} |
|
75
|
|
|
} |