| 1 |
<?php |
| 2 |
namespace Hurrytimer; |
| 3 |
|
| 4 |
class SQL_Builder |
| 5 |
{ |
| 6 |
public $table; |
| 7 |
public $charset_collate; |
| 8 |
public $sql_fields = []; |
| 9 |
const DELETE_CASCADE = 1; |
| 10 |
public function __construct($_table, $_charset_collate) |
| 11 |
{ |
| 12 |
$this->table = $_table; |
| 13 |
$this->charset_collate = $_charset_collate; |
| 14 |
} |
| 15 |
|
| 16 |
public function create() |
| 17 |
{ |
| 18 |
$sql = "CREATE TABLE {$this->table} ("; |
| 19 |
$this->sql_fields[] = $sql; |
| 20 |
return $this; |
| 21 |
} |
| 22 |
private function _field($name, $type, $length, $unsigned = false, $is_nullable = false) |
| 23 |
{ |
| 24 |
$sql = $name . ' ' . strtoupper($type) . '(' . $length . ') '; |
| 25 |
$sql .= ($unsigned ? 'UNSIGNED ' : ''); |
| 26 |
$sql .= ($is_nullable ? 'NULL' : 'NOT NULL'); |
| 27 |
return $sql; |
| 28 |
} |
| 29 |
public function string($name, $length = 50, $is_nullable = false) |
| 30 |
{ |
| 31 |
$sql = $this->_field($name, "VARCHAR", $length, false, $is_nullable); |
| 32 |
$this->sql_fields[] = $sql; |
| 33 |
return $this; |
| 34 |
} |
| 35 |
public function primary_key($name) |
| 36 |
{ |
| 37 |
$sql = "PRIMARY KEY($name)"; |
| 38 |
$this->sql_fields[] = $sql; |
| 39 |
return $this; |
| 40 |
} |
| 41 |
public function foreign_key($name, $reference, $delete) |
| 42 |
{ |
| 43 |
$sql = "FOREIGN KEY($name) REFERENCES $reference ON DELETE "; |
| 44 |
switch ($delete) { |
| 45 |
case self::DELETE_CASCADE: |
| 46 |
$sql .= "CASCADE"; |
| 47 |
break; |
| 48 |
} |
| 49 |
$this->sql_fields[] = $sql; |
| 50 |
return $this; |
| 51 |
} |
| 52 |
|
| 53 |
public function build() |
| 54 |
{ |
| 55 |
$sql = array_shift($this->sql_fields); |
| 56 |
$sql .= implode(',', $this->sql_fields); |
| 57 |
$sql .= ')'; |
| 58 |
if ($this->charset_collate) { |
| 59 |
$sql .= ' ' . $this->charset_collate . ';'; |
| 60 |
} |
| 61 |
return $sql; |
| 62 |
} |
| 63 |
|
| 64 |
public function bigint($name, $length = 20, $unsigned = false, $is_nullable = false, $auto_increment = false) |
| 65 |
{ |
| 66 |
$sql = $this->_field($name, 'BIGINT', $length, $unsigned, $is_nullable); |
| 67 |
$sql .= ($auto_increment ? ' AUTO_INCREMENT' : ''); |
| 68 |
$this->sql_fields[] = $sql; |
| 69 |
return $this; |
| 70 |
} |
| 71 |
public function timestamp($name, $is_nullable = false) |
| 72 |
{ |
| 73 |
$sql = $name . ' ' . 'TIMESTAMP '; |
| 74 |
$sql .= ($is_nullable ? 'NULL' : 'NOT NULL'); |
| 75 |
$this->sql_fields[] = $sql; |
| 76 |
return $this; |
| 77 |
} |
| 78 |
|
| 79 |
} |
| 80 |
|