fix format
This commit is contained in:
parent
7163158baf
commit
2edd65d145
5 changed files with 407 additions and 388 deletions
|
|
@ -172,10 +172,10 @@ class Action
|
||||||
}
|
}
|
||||||
$view = $this->forward($action, $request);
|
$view = $this->forward($action, $request);
|
||||||
if ($view instanceof View) {
|
if ($view instanceof View) {
|
||||||
$view->active_module = get_class($this);
|
$view->active_module = get_class($this);
|
||||||
$view->module_action = $action;
|
$view->module_action = $action;
|
||||||
}
|
}
|
||||||
return $view;
|
return $view;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function execute(HttpRequest $request)
|
public function execute(HttpRequest $request)
|
||||||
|
|
@ -332,8 +332,8 @@ class Action
|
||||||
public function render()
|
public function render()
|
||||||
{
|
{
|
||||||
$view = $this->view;
|
$view = $this->view;
|
||||||
if ($view instanceof View) {
|
if ($view instanceof View) {
|
||||||
$this->view->assignValues($this->ctrlValues);
|
$this->view->assignValues($this->ctrlValues);
|
||||||
|
|
||||||
$node/*: Composite*/ = null;
|
$node/*: Composite*/ = null;
|
||||||
foreach ($this->childNodes as $name => $node) {
|
foreach ($this->childNodes as $name => $node) {
|
||||||
|
|
@ -344,7 +344,7 @@ class Action
|
||||||
foreach ($this->childViews as $name => $node) {
|
foreach ($this->childViews as $name => $node) {
|
||||||
$this->view->setView($name, $node);
|
$this->view->setView($name, $node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return $this->view;
|
return $this->view;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,139 +8,139 @@ class JsonInstall {
|
||||||
public $db_manager;
|
public $db_manager;
|
||||||
public $serialColumns;
|
public $serialColumns;
|
||||||
|
|
||||||
public function __construct(Manager $db_manager) {
|
public function __construct(Manager $db_manager) {
|
||||||
$this->db_manager = $db_manager;
|
$this->db_manager = $db_manager;
|
||||||
}
|
}
|
||||||
|
|
||||||
function install($dbinit_path, $dbfill_path = null) {
|
function install($dbinit_path, $dbfill_path = null) {
|
||||||
$dbinit_file = file_get_contents($dbinit_path);
|
$dbinit_file = file_get_contents($dbinit_path);
|
||||||
if (is_string($dbinit_file)) {
|
if (is_string($dbinit_file)) {
|
||||||
$initActions = json_decode($dbinit_file, true);
|
$initActions = json_decode($dbinit_file, true);
|
||||||
if (!$initActions) {
|
if (!$initActions) {
|
||||||
echo "Invalid ".$dbinit_path;
|
echo "Invalid ".$dbinit_path;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
echo "No ".$dbinit_path;
|
echo "No ".$dbinit_path;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->initDataBase($initActions, $dbinit_path);
|
$this->initDataBase($initActions, $dbinit_path);
|
||||||
if ($dbfill_path) {
|
if ($dbfill_path) {
|
||||||
$this->fillDataBase($dbfill_path);
|
$this->fillDataBase($dbfill_path);
|
||||||
}
|
}
|
||||||
$this->makeConstraints($initActions);
|
$this->makeConstraints($initActions);
|
||||||
}
|
}
|
||||||
|
|
||||||
function missingTables($tables) {
|
function missingTables($tables) {
|
||||||
$actual_tables = $this->db_manager->GetAllTableNames();
|
$actual_tables = $this->db_manager->GetAllTableNames();
|
||||||
$missingTables = [];
|
$missingTables = [];
|
||||||
foreach ($tables as $table) {
|
foreach ($tables as $table) {
|
||||||
if (!in_array($table, $actual_tables))
|
if (!in_array($table, $actual_tables))
|
||||||
$missingTables[] = $table;
|
$missingTables[] = $table;
|
||||||
}
|
}
|
||||||
return $missingTables;
|
return $missingTables;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Создать таблицы
|
//Создать таблицы
|
||||||
function initDataBase($initActions/*: array*/, $dbinit_path) {
|
function initDataBase($initActions/*: array*/, $dbinit_path) {
|
||||||
$pg = $this->db_manager->db->isPostgres();
|
$pg = $this->db_manager->db->isPostgres();
|
||||||
if (!$pg) {
|
if (!$pg) {
|
||||||
$refs = [];
|
$refs = [];
|
||||||
//В sqlite нет alter reference. Референсы надо создавать при создании таблицы.
|
//В sqlite нет alter reference. Референсы надо создавать при создании таблицы.
|
||||||
foreach ($initActions as $action) {
|
foreach ($initActions as $action) {
|
||||||
if ($action["type"] == "alterReference") {
|
if ($action["type"] == "alterReference") {
|
||||||
if (!isset($refs[$action["table"]]))
|
if (!isset($refs[$action["table"]]))
|
||||||
$refs[$action["table"]] = [];
|
$refs[$action["table"]] = [];
|
||||||
$refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы
|
$refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($initActions as $action) {
|
foreach ($initActions as $action) {
|
||||||
if (!$pg) {
|
if (!$pg) {
|
||||||
if ($action["type"] == "createTable") {
|
if ($action["type"] == "createTable") {
|
||||||
$table_name = $action["table_name"];
|
$table_name = $action["table_name"];
|
||||||
if (isset($refs[$table_name])) {
|
if (isset($refs[$table_name])) {
|
||||||
foreach ($refs[$table_name] as $value) {
|
foreach ($refs[$table_name] as $value) {
|
||||||
$action['fields'][$value['column']]['references'] =
|
$action['fields'][$value['column']]['references'] =
|
||||||
$value['refTable']."(".$value['refColumn'].")";
|
$value['refTable']."(".$value['refColumn'].")";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($action["type"] != "alterReference") {
|
if ($action["type"] != "alterReference") {
|
||||||
$this->db_manager->ExecuteAction($action, $dbinit_path);
|
$this->db_manager->ExecuteAction($action, $dbinit_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Запомнить все колонки serial
|
//Запомнить все колонки serial
|
||||||
$this->serialColumns = [];
|
$this->serialColumns = [];
|
||||||
if ($pg) {
|
if ($pg) {
|
||||||
foreach ($initActions as $action) {
|
foreach ($initActions as $action) {
|
||||||
if ($action["type"] == "createTable") {
|
if ($action["type"] == "createTable") {
|
||||||
foreach ($action["fields"] as $name => $field) {
|
foreach ($action["fields"] as $name => $field) {
|
||||||
if ($field["type"]=="serial") {
|
if ($field["type"]=="serial") {
|
||||||
$this->serialColumns[] = [
|
$this->serialColumns[] = [
|
||||||
"table"=>$action["table_name"],
|
"table"=>$action["table_name"],
|
||||||
"column"=>$name
|
"column"=>$name
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Заполнить данными
|
//Заполнить данными
|
||||||
function fillDataBase($dbfill_file_path) {
|
function fillDataBase($dbfill_file_path) {
|
||||||
$dbfill_file = file_get_contents($dbfill_file_path);
|
$dbfill_file = file_get_contents($dbfill_file_path);
|
||||||
if (is_string($dbfill_file)) {
|
if (is_string($dbfill_file)) {
|
||||||
$actions = json_decode($dbfill_file,true);
|
$actions = json_decode($dbfill_file,true);
|
||||||
if ($actions) {
|
if ($actions) {
|
||||||
|
|
||||||
//Проверка что упоминаемые в списке действий таблицы уже есть в базе
|
//Проверка что упоминаемые в списке действий таблицы уже есть в базе
|
||||||
$affected_tables = [];
|
$affected_tables = [];
|
||||||
foreach ($actions as $action) {
|
foreach ($actions as $action) {
|
||||||
if ($action["table_name"]) {
|
if ($action["table_name"]) {
|
||||||
$affected_tables[$action["table_name"]] = 1;
|
$affected_tables[$action["table_name"]] = 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$missing = $this->missingTables(array_keys($affected_tables));
|
$missing = $this->missingTables(array_keys($affected_tables));
|
||||||
if (!empty($missing)) {
|
if (!empty($missing)) {
|
||||||
echo "dbfill error. Missing tables: ".implode(" ", $missing);
|
echo "dbfill error. Missing tables: ".implode(" ", $missing);
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
//Выполнение действий
|
|
||||||
foreach ($actions as $action) {
|
|
||||||
$this->db_manager->ExecuteAction($action, $dbfill_file_path);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
echo "Invalid dbfill.json";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
echo "No dbfill.json";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Обновить ключи serial и создать ограничения
|
|
||||||
function makeConstraints($initActions) {
|
|
||||||
$pg = $this->db_manager->db->isPostgres();
|
|
||||||
if ($pg) {
|
|
||||||
foreach ($this->serialColumns as $serialColumn) {
|
|
||||||
$this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
foreach ($initActions as $action) {
|
|
||||||
if ($action["type"] == "alterReference") {
|
|
||||||
$this->db_manager->ExecuteAction($action);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
//Выполнение действий
|
||||||
}
|
foreach ($actions as $action) {
|
||||||
|
$this->db_manager->ExecuteAction($action, $dbfill_file_path);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "Invalid dbfill.json";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "No dbfill.json";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Обновить ключи serial и создать ограничения
|
||||||
|
function makeConstraints($initActions) {
|
||||||
|
$pg = $this->db_manager->db->isPostgres();
|
||||||
|
if ($pg) {
|
||||||
|
foreach ($this->serialColumns as $serialColumn) {
|
||||||
|
$this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
foreach ($initActions as $action) {
|
||||||
|
if ($action["type"] == "alterReference") {
|
||||||
|
$this->db_manager->ExecuteAction($action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -1,236 +1,255 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace ctiso\Database;
|
namespace ctiso\Database;
|
||||||
use ctiso\Database,
|
|
||||||
ctiso\Tools\SQLStatementExtractor,
|
use ctiso\Database;
|
||||||
ctiso\Path,
|
use ctiso\Tools\SQLStatementExtractor;
|
||||||
Exception;
|
use ctiso\Path;
|
||||||
|
use Exception;
|
||||||
|
|
||||||
class Manager
|
class Manager
|
||||||
{
|
{
|
||||||
public $db/*: Database*/;
|
public $db/*: Database*/;
|
||||||
|
|
||||||
function __construct(Database $db) {
|
public function __construct(Database $db)
|
||||||
$this->db = $db;
|
{
|
||||||
}
|
$this->db = $db;
|
||||||
|
|
||||||
public function ExecuteAction($action/*: array*/, $db_file = "") {
|
|
||||||
switch($action["type"]) {
|
|
||||||
case "dropTable":
|
|
||||||
$this->DropTableQuery($action["table_name"], true);
|
|
||||||
break;
|
|
||||||
case "createTable":
|
|
||||||
$constraints = isset($action["constraints"]) ? $action["constraints"] : NULL;
|
|
||||||
$this->CreateTableQuery($action["table_name"], $action["fields"], $constraints);
|
|
||||||
break;
|
|
||||||
case "addColumn":
|
|
||||||
$this->AddColumn($action["table_name"], $action["column_name"], $action["field"]);
|
|
||||||
break;
|
|
||||||
case "insert":
|
|
||||||
$this->db->insertQuery($action["table_name"], $action["values"]);
|
|
||||||
break;
|
|
||||||
case "alterReference":
|
|
||||||
$this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]);
|
|
||||||
break;
|
|
||||||
case "renameColumn":
|
|
||||||
$this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]);
|
|
||||||
break;
|
|
||||||
case "createView":
|
|
||||||
$this->recreateView($action["view"], $action["select"]);
|
|
||||||
break;
|
|
||||||
case "executeFile":
|
|
||||||
if ($this->db->isPostgres() && isset($action["pgsql"])) {
|
|
||||||
$file = $action["pgsql"];
|
|
||||||
} else {
|
|
||||||
$file = $action["source"];
|
|
||||||
}
|
|
||||||
|
|
||||||
$stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file));
|
|
||||||
foreach($stmtList as $stmt) {
|
|
||||||
$this->db->executeQuery($stmt);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new Exception("unknown action ". $action["type"] . PHP_EOL);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Дропает и создаёт SQL VIEW
|
|
||||||
public function recreateView($viewName, $selectStatement) {
|
|
||||||
$this->db->query("DROP VIEW ".$viewName);
|
|
||||||
$this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function DropTableQuery($table, $cascade=false) {
|
|
||||||
$statement = "DROP TABLE IF EXISTS ".$table;
|
|
||||||
if ($this->db->isPostgres()&&$cascade) {
|
|
||||||
$statement = $statement." CASCADE";
|
|
||||||
}
|
|
||||||
$this->db->query($statement);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function AlterReference($table,$column,$refTable,$refColumn) {
|
|
||||||
$this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")");
|
|
||||||
}
|
|
||||||
|
|
||||||
//Извлечение информации о полях таблицы
|
|
||||||
public function TableInfo($table) {
|
|
||||||
$pg = $this->db->isPostgres();
|
|
||||||
if ($pg) {
|
|
||||||
throw new Exception("Not implemented for postgres");
|
|
||||||
} else {
|
|
||||||
$results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");");
|
|
||||||
if (empty($results)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
$fields = [];
|
|
||||||
foreach ($results as $result) {
|
|
||||||
$fields[$result["name"]] = [
|
|
||||||
"type"=> $result["type"],
|
|
||||||
"not_null"=> boolval($result["notnull"]),
|
|
||||||
"constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null
|
|
||||||
];
|
|
||||||
}
|
|
||||||
return $fields;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function RenameColumn($table, $old_name, $new_name) {
|
|
||||||
$pg = $this->db->isPostgres();
|
|
||||||
if ($pg) {
|
|
||||||
$this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name);
|
|
||||||
} else {
|
|
||||||
$tmp_table = "tmp_" . $table;
|
|
||||||
$this->DropTableQuery($tmp_table);
|
|
||||||
$table_info = $this->TableInfo($table);
|
|
||||||
|
|
||||||
if (isset($table_info[$new_name])) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$data/*: array*/ = $this->DumpTable($table);
|
|
||||||
|
|
||||||
$this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";");
|
|
||||||
$table_info[$new_name] = $table_info[$old_name];
|
|
||||||
unset($table_info[$old_name]);
|
|
||||||
$this->CreateTableQuery($table,$table_info,null);
|
|
||||||
|
|
||||||
foreach ($data as $row) {
|
|
||||||
$values = $row['values'];
|
|
||||||
$values[$new_name] = $values[$old_name];
|
|
||||||
unset($values[$old_name]);
|
|
||||||
$this->db->insertQuery($table, $values);
|
|
||||||
}
|
|
||||||
$this->DropTableQuery($tmp_table);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Обновление ключа serial после ручной вставки
|
|
||||||
public function UpdateSerial($table,$column) {
|
|
||||||
$this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function Column_Definition($name,$data,$pg){
|
|
||||||
$constraint = isset($data['constraint'])?" ".$data['constraint']:"";
|
|
||||||
$references = "";
|
|
||||||
if (isset($data['references'])) {
|
|
||||||
$references = " REFERENCES ".$data['references'];
|
|
||||||
}
|
|
||||||
if (isset($data["not_null"]) && $data["not_null"])
|
|
||||||
$constraint .=" NOT NULL";
|
|
||||||
$type = $data['type'];
|
|
||||||
if (!$pg) {
|
|
||||||
if (strtolower($type)=="serial")
|
|
||||||
$type = "integer";
|
|
||||||
//if (strtolower($type)=="boolean")
|
|
||||||
// $type = "integer";
|
|
||||||
}
|
|
||||||
return $name." ".$type.$references.$constraint;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function AddColumn($table_name,$column_name,$field){
|
|
||||||
$pg = $this->db->isPostgres();
|
|
||||||
$q = "ALTER TABLE ".$table_name." ADD COLUMN ".
|
|
||||||
$this->Column_Definition($column_name, $field, $pg);
|
|
||||||
$this->db->query($q);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getConstraintDef($c/*: array*/) {
|
|
||||||
if ($c['type'] == 'unique') {
|
|
||||||
return "UNIQUE(" . implode(", ", $c['fields']) . ")";
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
//CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
|
|
||||||
public function CreateTableQuery($table, $fields, $constraints) {
|
|
||||||
$pg = $this->db->isPostgres();
|
|
||||||
if ($constraints) {
|
|
||||||
if (is_array($constraints)) {
|
|
||||||
$constraints = $this->getConstraintDef($constraints);
|
|
||||||
}
|
|
||||||
$constraints = ", " . $constraints;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$statement = "CREATE TABLE $table (" . implode(",",
|
public function ExecuteAction($action/*: array*/, $db_file = "")
|
||||||
array_map(function($name,$data) use ($pg) {
|
{
|
||||||
return $this->Column_Definition($name,$data,$pg);
|
switch($action["type"]) {
|
||||||
}, array_keys($fields), array_values($fields))
|
case "dropTable":
|
||||||
) . " " . $constraints . ")";
|
$this->DropTableQuery($action["table_name"], true);
|
||||||
$this->db->query($statement);
|
break;
|
||||||
}
|
case "createTable":
|
||||||
|
$constraints = isset($action["constraints"]) ? $action["constraints"] : null;
|
||||||
|
$this->CreateTableQuery($action["table_name"], $action["fields"], $constraints);
|
||||||
|
break;
|
||||||
|
case "addColumn":
|
||||||
|
$this->AddColumn($action["table_name"], $action["column_name"], $action["field"]);
|
||||||
|
break;
|
||||||
|
case "insert":
|
||||||
|
$this->db->insertQuery($action["table_name"], $action["values"]);
|
||||||
|
break;
|
||||||
|
case "alterReference":
|
||||||
|
$this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]);
|
||||||
|
break;
|
||||||
|
case "renameColumn":
|
||||||
|
$this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]);
|
||||||
|
break;
|
||||||
|
case "createView":
|
||||||
|
$this->recreateView($action["view"], $action["select"]);
|
||||||
|
break;
|
||||||
|
case "executeFile":
|
||||||
|
if ($this->db->isPostgres() && isset($action["pgsql"])) {
|
||||||
|
$file = $action["pgsql"];
|
||||||
|
} else {
|
||||||
|
$file = $action["source"];
|
||||||
|
}
|
||||||
|
|
||||||
public function DumpTable($table_name) {
|
$stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file));
|
||||||
$pg = $this->db->isPostgres();
|
foreach ($stmtList as $stmt) {
|
||||||
|
$this->db->executeQuery($stmt);
|
||||||
|
}
|
||||||
|
|
||||||
$result/*: array*/ = array();
|
break;
|
||||||
$data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";");
|
default:
|
||||||
|
throw new Exception("unknown action ". $action["type"] . PHP_EOL);
|
||||||
if (!$pg) {
|
|
||||||
$table_fields = $this->TableInfo($table_name);
|
|
||||||
foreach ($table_fields as $name => $value) {
|
|
||||||
$type = strtolower($value['type']);
|
|
||||||
if ($type == "boolean") {
|
|
||||||
foreach ($data as &$row) {
|
|
||||||
$row/*: array*/ = $row;
|
|
||||||
if (isset($row[$name])) {
|
|
||||||
$row[$name] = boolval($row[$name]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
foreach ($data as $r) {
|
|
||||||
$result[] = array(
|
|
||||||
"type" => "insert",
|
|
||||||
"table_name" => $table_name,
|
|
||||||
"values" => $r
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function GetAllTableNames() {
|
//Дропает и создаёт SQL VIEW
|
||||||
$result = [];
|
public function recreateView($viewName, $selectStatement)
|
||||||
if ($this->db->isPostgres()) {
|
{
|
||||||
$query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'";
|
$this->db->query("DROP VIEW ".$viewName);
|
||||||
} else {
|
$this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement);
|
||||||
$query = "SELECT * FROM sqlite_master WHERE type='table'";
|
|
||||||
}
|
}
|
||||||
$tables = $this->db->fetchAllArray($query);
|
|
||||||
foreach ($tables as $table) {
|
|
||||||
$result[] = $table['name'];
|
|
||||||
}
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function DumpInserts() {
|
public function DropTableQuery($table, $cascade=false)
|
||||||
$table_names = $this->GetAllTableNames();
|
{
|
||||||
$result = array();
|
$statement = "DROP TABLE IF EXISTS ".$table;
|
||||||
foreach ($table_names as $table_name) {
|
if ($this->db->isPostgres()&&$cascade) {
|
||||||
$result = array_merge($result, $this->DumpTable($table_name));
|
$statement = $statement." CASCADE";
|
||||||
|
}
|
||||||
|
$this->db->query($statement);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function AlterReference($table, $column, $refTable, $refColumn)
|
||||||
|
{
|
||||||
|
$this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")");
|
||||||
|
}
|
||||||
|
|
||||||
|
//Извлечение информации о полях таблицы
|
||||||
|
public function TableInfo($table)
|
||||||
|
{
|
||||||
|
$pg = $this->db->isPostgres();
|
||||||
|
if ($pg) {
|
||||||
|
throw new Exception("Not implemented for postgres");
|
||||||
|
} else {
|
||||||
|
$results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");");
|
||||||
|
if (empty($results)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$fields = [];
|
||||||
|
foreach ($results as $result) {
|
||||||
|
$fields[$result["name"]] = [
|
||||||
|
"type"=> $result["type"],
|
||||||
|
"not_null"=> boolval($result["notnull"]),
|
||||||
|
"constraint"=> ((bool) $result["pk"]) ? "PRIMARY KEY" : null
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return $fields;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function RenameColumn($table, $old_name, $new_name)
|
||||||
|
{
|
||||||
|
$pg = $this->db->isPostgres();
|
||||||
|
if ($pg) {
|
||||||
|
$this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name);
|
||||||
|
} else {
|
||||||
|
$tmp_table = "tmp_" . $table;
|
||||||
|
$this->DropTableQuery($tmp_table);
|
||||||
|
$table_info = $this->TableInfo($table);
|
||||||
|
|
||||||
|
if (isset($table_info[$new_name])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data/*: array*/ = $this->DumpTable($table);
|
||||||
|
|
||||||
|
$this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";");
|
||||||
|
$table_info[$new_name] = $table_info[$old_name];
|
||||||
|
unset($table_info[$old_name]);
|
||||||
|
$this->CreateTableQuery($table, $table_info, null);
|
||||||
|
|
||||||
|
foreach ($data as $row) {
|
||||||
|
$values = $row['values'];
|
||||||
|
$values[$new_name] = $values[$old_name];
|
||||||
|
unset($values[$old_name]);
|
||||||
|
$this->db->insertQuery($table, $values);
|
||||||
|
}
|
||||||
|
$this->DropTableQuery($tmp_table);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Обновление ключа serial после ручной вставки
|
||||||
|
public function UpdateSerial($table, $column)
|
||||||
|
{
|
||||||
|
$this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function Column_Definition($name, $data, $pg)
|
||||||
|
{
|
||||||
|
$constraint = isset($data['constraint']) ? " ".$data['constraint'] : "";
|
||||||
|
$references = "";
|
||||||
|
if (isset($data['references'])) {
|
||||||
|
$references = " REFERENCES ".$data['references'];
|
||||||
|
}
|
||||||
|
if (isset($data["not_null"]) && $data["not_null"]) {
|
||||||
|
$constraint .=" NOT NULL";
|
||||||
|
}
|
||||||
|
$type = $data['type'];
|
||||||
|
if (!$pg) {
|
||||||
|
if (strtolower($type)=="serial") {
|
||||||
|
$type = "integer";
|
||||||
|
}
|
||||||
|
//if (strtolower($type)=="boolean")
|
||||||
|
// $type = "integer";
|
||||||
|
}
|
||||||
|
return $name." ".$type.$references.$constraint;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function AddColumn($table_name, $column_name, $field)
|
||||||
|
{
|
||||||
|
$pg = $this->db->isPostgres();
|
||||||
|
$q = "ALTER TABLE ".$table_name." ADD COLUMN ".
|
||||||
|
$this->Column_Definition($column_name, $field, $pg);
|
||||||
|
$this->db->query($q);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getConstraintDef($c/*: array*/)
|
||||||
|
{
|
||||||
|
if ($c['type'] == 'unique') {
|
||||||
|
return "UNIQUE(" . implode(", ", $c['fields']) . ")";
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
//CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
|
||||||
|
public function CreateTableQuery($table, $fields, $constraints)
|
||||||
|
{
|
||||||
|
$pg = $this->db->isPostgres();
|
||||||
|
if ($constraints) {
|
||||||
|
if (is_array($constraints)) {
|
||||||
|
$constraints = $this->getConstraintDef($constraints);
|
||||||
|
}
|
||||||
|
$constraints = ", " . $constraints;
|
||||||
|
}
|
||||||
|
|
||||||
|
$statement = "CREATE TABLE $table (" . implode(
|
||||||
|
",",
|
||||||
|
array_map(function ($name, $data) use ($pg) {
|
||||||
|
return $this->Column_Definition($name, $data, $pg);
|
||||||
|
}, array_keys($fields), array_values($fields))
|
||||||
|
) . " " . $constraints . ")";
|
||||||
|
$this->db->query($statement);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function DumpTable($table_name)
|
||||||
|
{
|
||||||
|
$pg = $this->db->isPostgres();
|
||||||
|
|
||||||
|
$result/*: array*/ = array();
|
||||||
|
$data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";");
|
||||||
|
|
||||||
|
if (!$pg) {
|
||||||
|
$table_fields = $this->TableInfo($table_name);
|
||||||
|
foreach ($table_fields as $name => $value) {
|
||||||
|
$type = strtolower($value['type']);
|
||||||
|
if ($type == "boolean") {
|
||||||
|
foreach ($data as &$row) {
|
||||||
|
$row/*: array*/ = $row;
|
||||||
|
if (isset($row[$name])) {
|
||||||
|
$row[$name] = boolval($row[$name]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($data as $r) {
|
||||||
|
$result[] = array(
|
||||||
|
"type" => "insert",
|
||||||
|
"table_name" => $table_name,
|
||||||
|
"values" => $r
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function GetAllTableNames()
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
if ($this->db->isPostgres()) {
|
||||||
|
$query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'";
|
||||||
|
} else {
|
||||||
|
$query = "SELECT * FROM sqlite_master WHERE type='table'";
|
||||||
|
}
|
||||||
|
$tables = $this->db->fetchAllArray($query);
|
||||||
|
foreach ($tables as $table) {
|
||||||
|
$result[] = $table['name'];
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function DumpInserts()
|
||||||
|
{
|
||||||
|
$table_names = $this->GetAllTableNames();
|
||||||
|
$result = array();
|
||||||
|
foreach ($table_names as $table_name) {
|
||||||
|
$result = array_merge($result, $this->DumpTable($table_name));
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
}
|
}
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,19 +24,19 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
|
||||||
$this->cursorPos = 0;
|
$this->cursorPos = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function seek($rownum) {
|
public function seek($rownum) {
|
||||||
if ($rownum < 0) {
|
if ($rownum < 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostgreSQL rows start w/ 0, but this works, because we are
|
// PostgreSQL rows start w/ 0, but this works, because we are
|
||||||
// looking to move the position _before_ the next desired position
|
// looking to move the position _before_ the next desired position
|
||||||
$this->cursorPos = $rownum;
|
$this->cursorPos = $rownum;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function valid() {
|
function valid() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ class StatementIterator implements \Iterator
|
||||||
|
|
||||||
public function __construct($rs/*: PDOStatement*/) {
|
public function __construct($rs/*: PDOStatement*/) {
|
||||||
$this->result = $rs;
|
$this->result = $rs;
|
||||||
$this->row_count = $rs->getRecordCount();
|
$this->row_count = $rs->getRecordCount();
|
||||||
}
|
}
|
||||||
|
|
||||||
function rewind() {
|
function rewind() {
|
||||||
|
|
@ -21,7 +21,7 @@ class StatementIterator implements \Iterator
|
||||||
}
|
}
|
||||||
|
|
||||||
function valid() {
|
function valid() {
|
||||||
return ($this->pos < $this->row_count);
|
return ($this->pos < $this->row_count);
|
||||||
}
|
}
|
||||||
|
|
||||||
function key() {
|
function key() {
|
||||||
|
|
@ -40,10 +40,10 @@ class StatementIterator implements \Iterator
|
||||||
}
|
}
|
||||||
|
|
||||||
function seek($index) {
|
function seek($index) {
|
||||||
$this->pos = $index;
|
$this->pos = $index;
|
||||||
}
|
}
|
||||||
|
|
||||||
function count() {
|
function count() {
|
||||||
return $this->row_count;
|
return $this->row_count;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue