|
<?php |
|
|
|
namespace PicoDb; |
|
|
|
use PDOException; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Schema |
|
{ |
|
|
|
|
|
|
|
|
|
|
|
|
|
protected $db = null; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
protected $namespace = '\Schema'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function __construct(Database $db) |
|
{ |
|
$this->db = $db; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function setNamespace($namespace) |
|
{ |
|
$this->namespace = $namespace; |
|
return $this; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function getNamespace() |
|
{ |
|
return $this->namespace; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function check($last_version = 1) |
|
{ |
|
$current_version = $this->db->getDriver()->getSchemaVersion(); |
|
|
|
if ($current_version < $last_version) { |
|
return $this->migrateTo($current_version, $last_version); |
|
} |
|
|
|
return true; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public function migrateTo($current_version, $next_version) |
|
{ |
|
try { |
|
for ($i = $current_version + 1; $i <= $next_version; $i++) { |
|
$this->db->getDriver()->disableForeignKeys(); |
|
$this->db->startTransaction(); |
|
|
|
$function_name = $this->getNamespace().'\version_'.$i; |
|
|
|
if (function_exists($function_name)) { |
|
$this->db->setLogMessage('Running migration '.$function_name); |
|
call_user_func($function_name, $this->db->getConnection()); |
|
} |
|
|
|
$this->db->getDriver()->setSchemaVersion($i); |
|
$this->db->closeTransaction(); |
|
$this->db->getDriver()->enableForeignKeys(); |
|
} |
|
} catch (PDOException $e) { |
|
$this->db->setLogMessage($e->getMessage()); |
|
$this->db->cancelTransaction(); |
|
$this->db->getDriver()->enableForeignKeys(); |
|
return false; |
|
} |
|
|
|
return true; |
|
} |
|
} |
|
|