database/src/Request/Create.php

56 lines
1.7 KiB
PHP
Raw Normal View History

2018-05-01 12:48:27 +00:00
<?php
namespace Krutush\Database\Request;
use Krutush\Database\Database;
use Krutush\Database\DatabaseException;
class Create extends Request{
protected $table;
protected $columns = [];
protected $primary = [];
2018-05-01 16:57:32 +00:00
protected $unique = [];
2018-05-01 12:48:27 +00:00
public function table(string $table): Create{
$this->table = $table;
return $this;
}
2018-05-01 16:57:32 +00:00
public function column(string $name, string $type, int $lenght = null, bool $not_null = false, bool $primary = false, bool $unique = false, string $more = null): Create{
2018-05-01 12:48:27 +00:00
$this->columns[] = '`'.$name.'` '.$type.($lenght ? '('.$lenght.')' : '').($not_null ? ' NOT NULL' : '').(isset($more) ? ' '.$more : '');
if($primary)
$this->primary[] = '`'.$name.'`';
2018-05-01 16:57:32 +00:00
if($unique)
$this->unique[$name] = [$name];
2018-05-01 12:48:27 +00:00
return $this;
}
public function sql(){
if(!isset($this->table))
throw new DatabaseException('Any table set');
if(empty($this->columns))
throw new DatabaseException('Any columns set');
2018-05-01 16:57:32 +00:00
$uniques = [];
foreach ($this->unique as $name => $columns) {
$uniques[] = 'CONSTRAINT UC_'.ucfirst(strtolower($name)).' UNIQUE ('.implode(', ', $columns).')';
}
return 'CREATE TABLE `'.$this->table.'`('."\n".
2018-05-01 12:48:27 +00:00
$sql = implode(",\n",
2018-05-01 16:57:32 +00:00
array_merge(
$this->columns,
(empty($this->primary) ? [] : [
'CONSTRAINT PK_'.ucfirst(strtolower(strtok($this->table, ' '))).' PRIMARY KEY ('.implode(', ', $this->primary).')'
]),
$uniques
)
2018-05-01 12:48:27 +00:00
)."\n)";
}
public function run(array $values = null){
return parent::execute($this->sql(), $values);
}
}