1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bonfim\ActiveRecord; |
4
|
|
|
|
5
|
|
|
abstract class Schema extends ActiveRecord |
6
|
|
|
{ |
7
|
|
|
private $sql = ''; |
8
|
|
|
private $table; |
9
|
|
|
|
10
|
|
|
abstract public function up(); |
11
|
|
|
abstract public function down(); |
12
|
|
|
|
13
|
|
|
public function __construct() |
14
|
|
|
{ |
15
|
|
|
$this->table = new Table(); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function create(string $name, $callback) |
19
|
|
|
{ |
20
|
|
|
call_user_func_array($callback, [$this->table]); |
21
|
|
|
|
22
|
|
|
$q = "CREATE TABLE IF NOT EXISTS $name ({$this->getColumns()}"; |
23
|
|
|
$q .= $this->pk().$this->fk().$this->onUpdate().$this->onDelete(); |
24
|
|
|
$q .= "\n) ENGINE=INNODB;"; |
25
|
|
|
|
26
|
|
|
$this->sql = $q; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function drop(string $name) |
30
|
|
|
{ |
31
|
|
|
$this->sql = "DROP TABLE $name"; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private function pk() |
35
|
|
|
{ |
36
|
|
|
return (!empty($pk = $this->table->getPk())) |
|
|
|
|
37
|
|
|
? $this->sql .= ",\n\tPRIMARY KEY ($pk)" |
38
|
|
|
: ""; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function fk() |
42
|
|
|
{ |
43
|
|
|
return (!empty($fk = $this->table->getFk())) |
|
|
|
|
44
|
|
|
? ",\n\t$fk {$this->table->getReferences()}" |
|
|
|
|
45
|
|
|
: ""; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function onUpdate() |
49
|
|
|
{ |
50
|
|
|
return (!empty($on = $this->table->getOnupdate())) |
|
|
|
|
51
|
|
|
? " $on" |
52
|
|
|
: ""; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function onDelete() |
56
|
|
|
{ |
57
|
|
|
return (!empty($on = $this->table->getOndelete())) |
|
|
|
|
58
|
|
|
? " $on" |
59
|
|
|
: ""; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function getColumns() |
63
|
|
|
{ |
64
|
|
|
$q = "\n\t"; |
65
|
|
|
|
66
|
|
|
$columns = $this->table->getColumns(); |
67
|
|
|
$count = count($columns); |
68
|
|
|
|
69
|
|
|
reset($columns); |
70
|
|
|
|
71
|
|
|
for ($i = 0; $i < $count; $i++) { |
72
|
|
|
$key = key($columns); |
73
|
|
|
$q .= key($columns) . ' ' . $columns[$key]; |
74
|
|
|
if ($i < $count - 1) { |
75
|
|
|
$q .= ",\n\t"; |
76
|
|
|
} |
77
|
|
|
next($columns); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $q; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function run() |
84
|
|
|
{ |
85
|
|
|
self::exec($this->sql); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|