fix format
This commit is contained in:
parent
7163158baf
commit
2edd65d145
5 changed files with 407 additions and 388 deletions
|
|
@ -23,7 +23,7 @@ class Action
|
|||
const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов
|
||||
const ACTION_PREFIX = "action"; // Префикс для функций действий
|
||||
|
||||
// Параметры устанавливаются при создании контроллера
|
||||
// Параметры устанавливаются при создании контроллера
|
||||
public $name = ''; // Имя модуля
|
||||
public $front;
|
||||
|
||||
|
|
@ -37,12 +37,12 @@ class Action
|
|||
*/
|
||||
public $db;
|
||||
|
||||
// Фильтры
|
||||
// Фильтры
|
||||
public $access = null; // Обьект хранит параметры доступа
|
||||
public $logger = null; // Обьект для ведения лога
|
||||
|
||||
private $factory = null; // Ссылка на обьект создания модели
|
||||
private $helpers = array(); // Помошники для действий
|
||||
private $factory = null; // Ссылка на обьект создания модели
|
||||
private $helpers = array(); // Помошники для действий
|
||||
public $part = null; // Параметры для ссылки
|
||||
|
||||
public $config/*: Registry*/; // Ссылка на настройки
|
||||
|
|
@ -100,7 +100,7 @@ class Action
|
|||
|
||||
/**
|
||||
* Создает представление
|
||||
* @param string
|
||||
* @param string
|
||||
* @param string $viewClass
|
||||
* @return Composite
|
||||
*/
|
||||
|
|
@ -130,7 +130,7 @@ class Action
|
|||
$scriptPath = Path::join($webPath, 'assets');
|
||||
|
||||
$tpl->set('icons', $iconsPath); // Путь к файлам текущей темы
|
||||
$tpl->set('assets', $stylePath);
|
||||
$tpl->set('assets', $stylePath);
|
||||
$tpl->set('script', $scriptPath); // Путь к файлам скриптов
|
||||
$tpl->set('template', $path); // Путь к файлам текущего шаблона
|
||||
|
||||
|
|
@ -162,7 +162,7 @@ class Action
|
|||
* Т.к действия являются методами класса то
|
||||
* 1. Можно переопределить действия
|
||||
* 2. Использовать наследование чтобы добавить к старому обработчику новое поведение
|
||||
* @param HttpRequest $request запроса
|
||||
* @param HttpRequest $request запроса
|
||||
*/
|
||||
public function preProcess(HttpRequest $request)
|
||||
{
|
||||
|
|
@ -172,12 +172,12 @@ class Action
|
|||
}
|
||||
$view = $this->forward($action, $request);
|
||||
if ($view instanceof View) {
|
||||
$view->active_module = get_class($this);
|
||||
$view->module_action = $action;
|
||||
}
|
||||
return $view;
|
||||
$view->active_module = get_class($this);
|
||||
$view->module_action = $action;
|
||||
}
|
||||
return $view;
|
||||
}
|
||||
|
||||
|
||||
public function execute(HttpRequest $request)
|
||||
{
|
||||
$result = $this->preProcess($request);
|
||||
|
|
@ -298,14 +298,14 @@ class Action
|
|||
|
||||
/**
|
||||
* Установка заголовка для отображения
|
||||
*/
|
||||
*/
|
||||
public function setTitle($title)
|
||||
{
|
||||
$this->view->setTitle($title);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавление widget к отображению
|
||||
* Добавление widget к отображению
|
||||
*/
|
||||
public function addChild($section, $node)
|
||||
{
|
||||
|
|
@ -318,9 +318,9 @@ class Action
|
|||
}
|
||||
|
||||
/**
|
||||
* Добавление дочернего отображения к текущему отображению
|
||||
* Добавление дочернего отображения к текущему отображению
|
||||
*/
|
||||
public function addView($section, $node)
|
||||
public function addView($section, $node)
|
||||
{
|
||||
$this->childViews[$section] = $node;
|
||||
}
|
||||
|
|
@ -329,11 +329,11 @@ class Action
|
|||
* Генерация содержания
|
||||
* Путаница c execute и render
|
||||
*/
|
||||
public function render()
|
||||
public function render()
|
||||
{
|
||||
$view = $this->view;
|
||||
if ($view instanceof View) {
|
||||
$this->view->assignValues($this->ctrlValues);
|
||||
if ($view instanceof View) {
|
||||
$this->view->assignValues($this->ctrlValues);
|
||||
|
||||
$node/*: Composite*/ = null;
|
||||
foreach ($this->childNodes as $name => $node) {
|
||||
|
|
@ -344,17 +344,17 @@ class Action
|
|||
foreach ($this->childViews as $name => $node) {
|
||||
$this->view->setView($name, $node);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->view;
|
||||
}
|
||||
|
||||
function getPageId(HttpRequest $request) {
|
||||
$pageId = time();
|
||||
$pageId = time();
|
||||
$request->session()->set('page', $pageId);
|
||||
return $pageId;
|
||||
}
|
||||
|
||||
function checkPageId(HttpRequest $request, $page)
|
||||
function checkPageId(HttpRequest $request, $page)
|
||||
{
|
||||
if ($request->get('__forced__')) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -8,139 +8,139 @@ class JsonInstall {
|
|||
public $db_manager;
|
||||
public $serialColumns;
|
||||
|
||||
public function __construct(Manager $db_manager) {
|
||||
$this->db_manager = $db_manager;
|
||||
}
|
||||
public function __construct(Manager $db_manager) {
|
||||
$this->db_manager = $db_manager;
|
||||
}
|
||||
|
||||
function install($dbinit_path, $dbfill_path = null) {
|
||||
$dbinit_file = file_get_contents($dbinit_path);
|
||||
if (is_string($dbinit_file)) {
|
||||
$initActions = json_decode($dbinit_file, true);
|
||||
if (!$initActions) {
|
||||
echo "Invalid ".$dbinit_path;
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
echo "No ".$dbinit_path;
|
||||
return 0;
|
||||
}
|
||||
function install($dbinit_path, $dbfill_path = null) {
|
||||
$dbinit_file = file_get_contents($dbinit_path);
|
||||
if (is_string($dbinit_file)) {
|
||||
$initActions = json_decode($dbinit_file, true);
|
||||
if (!$initActions) {
|
||||
echo "Invalid ".$dbinit_path;
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
echo "No ".$dbinit_path;
|
||||
return 0;
|
||||
}
|
||||
|
||||
$this->initDataBase($initActions, $dbinit_path);
|
||||
if ($dbfill_path) {
|
||||
$this->fillDataBase($dbfill_path);
|
||||
}
|
||||
$this->makeConstraints($initActions);
|
||||
}
|
||||
$this->initDataBase($initActions, $dbinit_path);
|
||||
if ($dbfill_path) {
|
||||
$this->fillDataBase($dbfill_path);
|
||||
}
|
||||
$this->makeConstraints($initActions);
|
||||
}
|
||||
|
||||
function missingTables($tables) {
|
||||
$actual_tables = $this->db_manager->GetAllTableNames();
|
||||
$missingTables = [];
|
||||
foreach ($tables as $table) {
|
||||
if (!in_array($table, $actual_tables))
|
||||
$missingTables[] = $table;
|
||||
}
|
||||
return $missingTables;
|
||||
}
|
||||
function missingTables($tables) {
|
||||
$actual_tables = $this->db_manager->GetAllTableNames();
|
||||
$missingTables = [];
|
||||
foreach ($tables as $table) {
|
||||
if (!in_array($table, $actual_tables))
|
||||
$missingTables[] = $table;
|
||||
}
|
||||
return $missingTables;
|
||||
}
|
||||
|
||||
//Создать таблицы
|
||||
function initDataBase($initActions/*: array*/, $dbinit_path) {
|
||||
$pg = $this->db_manager->db->isPostgres();
|
||||
if (!$pg) {
|
||||
$refs = [];
|
||||
//В sqlite нет alter reference. Референсы надо создавать при создании таблицы.
|
||||
foreach ($initActions as $action) {
|
||||
if ($action["type"] == "alterReference") {
|
||||
if (!isset($refs[$action["table"]]))
|
||||
$refs[$action["table"]] = [];
|
||||
$refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы
|
||||
}
|
||||
}
|
||||
}
|
||||
//Создать таблицы
|
||||
function initDataBase($initActions/*: array*/, $dbinit_path) {
|
||||
$pg = $this->db_manager->db->isPostgres();
|
||||
if (!$pg) {
|
||||
$refs = [];
|
||||
//В sqlite нет alter reference. Референсы надо создавать при создании таблицы.
|
||||
foreach ($initActions as $action) {
|
||||
if ($action["type"] == "alterReference") {
|
||||
if (!isset($refs[$action["table"]]))
|
||||
$refs[$action["table"]] = [];
|
||||
$refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($initActions as $action) {
|
||||
if (!$pg) {
|
||||
if ($action["type"] == "createTable") {
|
||||
$table_name = $action["table_name"];
|
||||
if (isset($refs[$table_name])) {
|
||||
foreach ($refs[$table_name] as $value) {
|
||||
$action['fields'][$value['column']]['references'] =
|
||||
$value['refTable']."(".$value['refColumn'].")";
|
||||
}
|
||||
}
|
||||
foreach ($initActions as $action) {
|
||||
if (!$pg) {
|
||||
if ($action["type"] == "createTable") {
|
||||
$table_name = $action["table_name"];
|
||||
if (isset($refs[$table_name])) {
|
||||
foreach ($refs[$table_name] as $value) {
|
||||
$action['fields'][$value['column']]['references'] =
|
||||
$value['refTable']."(".$value['refColumn'].")";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
if ($action["type"] != "alterReference") {
|
||||
$this->db_manager->ExecuteAction($action, $dbinit_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($action["type"] != "alterReference") {
|
||||
$this->db_manager->ExecuteAction($action, $dbinit_path);
|
||||
}
|
||||
}
|
||||
|
||||
//Запомнить все колонки serial
|
||||
$this->serialColumns = [];
|
||||
if ($pg) {
|
||||
foreach ($initActions as $action) {
|
||||
if ($action["type"] == "createTable") {
|
||||
foreach ($action["fields"] as $name => $field) {
|
||||
if ($field["type"]=="serial") {
|
||||
$this->serialColumns[] = [
|
||||
//Запомнить все колонки serial
|
||||
$this->serialColumns = [];
|
||||
if ($pg) {
|
||||
foreach ($initActions as $action) {
|
||||
if ($action["type"] == "createTable") {
|
||||
foreach ($action["fields"] as $name => $field) {
|
||||
if ($field["type"]=="serial") {
|
||||
$this->serialColumns[] = [
|
||||
"table"=>$action["table_name"],
|
||||
"column"=>$name
|
||||
"column"=>$name
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Заполнить данными
|
||||
function fillDataBase($dbfill_file_path) {
|
||||
$dbfill_file = file_get_contents($dbfill_file_path);
|
||||
if (is_string($dbfill_file)) {
|
||||
$actions = json_decode($dbfill_file,true);
|
||||
if ($actions) {
|
||||
|
||||
//Проверка что упоминаемые в списке действий таблицы уже есть в базе
|
||||
$affected_tables = [];
|
||||
foreach ($actions as $action) {
|
||||
if ($action["table_name"]) {
|
||||
$affected_tables[$action["table_name"]] = 1;
|
||||
//Заполнить данными
|
||||
function fillDataBase($dbfill_file_path) {
|
||||
$dbfill_file = file_get_contents($dbfill_file_path);
|
||||
if (is_string($dbfill_file)) {
|
||||
$actions = json_decode($dbfill_file,true);
|
||||
if ($actions) {
|
||||
|
||||
//Проверка что упоминаемые в списке действий таблицы уже есть в базе
|
||||
$affected_tables = [];
|
||||
foreach ($actions as $action) {
|
||||
if ($action["table_name"]) {
|
||||
$affected_tables[$action["table_name"]] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
$missing = $this->missingTables(array_keys($affected_tables));
|
||||
if (!empty($missing)) {
|
||||
echo "dbfill error. Missing tables: ".implode(" ", $missing);
|
||||
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);
|
||||
$missing = $this->missingTables(array_keys($affected_tables));
|
||||
if (!empty($missing)) {
|
||||
echo "dbfill error. Missing tables: ".implode(" ", $missing);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,236 +1,255 @@
|
|||
<?php
|
||||
|
||||
namespace ctiso\Database;
|
||||
use ctiso\Database,
|
||||
ctiso\Tools\SQLStatementExtractor,
|
||||
ctiso\Path,
|
||||
Exception;
|
||||
|
||||
use ctiso\Database;
|
||||
use ctiso\Tools\SQLStatementExtractor;
|
||||
use ctiso\Path;
|
||||
use Exception;
|
||||
|
||||
class Manager
|
||||
{
|
||||
public $db/*: Database*/;
|
||||
public $db/*: Database*/;
|
||||
|
||||
function __construct(Database $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;
|
||||
public function __construct(Database $db)
|
||||
{
|
||||
$this->db = $db;
|
||||
}
|
||||
|
||||
$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 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"];
|
||||
}
|
||||
|
||||
public function DumpTable($table_name) {
|
||||
$pg = $this->db->isPostgres();
|
||||
$stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file));
|
||||
foreach ($stmtList as $stmt) {
|
||||
$this->db->executeQuery($stmt);
|
||||
}
|
||||
|
||||
$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]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Exception("unknown action ". $action["type"] . PHP_EOL);
|
||||
}
|
||||
}
|
||||
}
|
||||
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'";
|
||||
//Дропает и создаёт SQL VIEW
|
||||
public function recreateView($viewName, $selectStatement)
|
||||
{
|
||||
$this->db->query("DROP VIEW ".$viewName);
|
||||
$this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement);
|
||||
}
|
||||
$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));
|
||||
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"=> ((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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,33 +10,33 @@ use TheSeer\Tokenizer\Exception;
|
|||
class PDOStatement extends \PDOStatement implements \IteratorAggregate
|
||||
{
|
||||
protected $cursorPos = 0;
|
||||
public $cache = array();
|
||||
public $cache = array();
|
||||
public $fields;
|
||||
|
||||
function getIterator(): \Iterator {
|
||||
return new StatementIterator($this);
|
||||
}
|
||||
|
||||
protected function __construct() {
|
||||
protected function __construct() {
|
||||
}
|
||||
|
||||
function rewind() {
|
||||
function rewind() {
|
||||
$this->cursorPos = 0;
|
||||
}
|
||||
|
||||
public function seek($rownum) {
|
||||
if ($rownum < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// PostgreSQL rows start w/ 0, but this works, because we are
|
||||
// looking to move the position _before_ the next desired position
|
||||
$this->cursorPos = $rownum;
|
||||
return true;
|
||||
}
|
||||
public function seek($rownum) {
|
||||
if ($rownum < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// PostgreSQL rows start w/ 0, but this works, because we are
|
||||
// looking to move the position _before_ the next desired position
|
||||
$this->cursorPos = $rownum;
|
||||
return true;
|
||||
}
|
||||
|
||||
function valid() {
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -49,7 +49,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
|
|||
if ($this->getRecordCount() > $this->cursorPos) {
|
||||
if (!isset($this->cache[$this->cursorPos])) {
|
||||
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
|
||||
}
|
||||
}
|
||||
$this->fields = $this->cache[$this->cursorPos];
|
||||
|
||||
$this->cursorPos++;
|
||||
|
|
@ -102,7 +102,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
|
|||
function getRecordCount() {
|
||||
return count($this->cache);
|
||||
}
|
||||
|
||||
|
||||
function execute($args = null) {
|
||||
$result = parent::execute($args);
|
||||
return $result;
|
||||
|
|
|
|||
|
|
@ -10,40 +10,40 @@ class StatementIterator implements \Iterator
|
|||
private $pos = 0;
|
||||
private $fetchmode;
|
||||
private $row_count;
|
||||
|
||||
|
||||
public function __construct($rs/*: PDOStatement*/) {
|
||||
$this->result = $rs;
|
||||
$this->row_count = $rs->getRecordCount();
|
||||
$this->row_count = $rs->getRecordCount();
|
||||
}
|
||||
|
||||
function rewind() {
|
||||
|
||||
function rewind() {
|
||||
$this->pos = 0;
|
||||
}
|
||||
|
||||
|
||||
function valid() {
|
||||
return ($this->pos < $this->row_count);
|
||||
return ($this->pos < $this->row_count);
|
||||
}
|
||||
|
||||
|
||||
function key() {
|
||||
return $this->pos;
|
||||
}
|
||||
|
||||
|
||||
function current() {
|
||||
if (!isset($this->result->cache[$this->pos])) {
|
||||
$this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC);
|
||||
}
|
||||
}
|
||||
return $this->result->cache[$this->pos];
|
||||
}
|
||||
|
||||
|
||||
function next() {
|
||||
$this->pos++;
|
||||
}
|
||||
|
||||
function seek($index) {
|
||||
$this->pos = $index;
|
||||
$this->pos = $index;
|
||||
}
|
||||
|
||||
function count() {
|
||||
return $this->row_count;
|
||||
return $this->row_count;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue