fix format

This commit is contained in:
origami11@yandex.ru 2023-04-13 11:38:49 +03:00
parent 7163158baf
commit 2edd65d145
5 changed files with 407 additions and 388 deletions

View file

@ -23,7 +23,7 @@ class Action
const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов
const ACTION_PREFIX = "action"; // Префикс для функций действий const ACTION_PREFIX = "action"; // Префикс для функций действий
// Параметры устанавливаются при создании контроллера // Параметры устанавливаются при создании контроллера
public $name = ''; // Имя модуля public $name = ''; // Имя модуля
public $front; public $front;
@ -37,12 +37,12 @@ class Action
*/ */
public $db; public $db;
// Фильтры // Фильтры
public $access = null; // Обьект хранит параметры доступа public $access = null; // Обьект хранит параметры доступа
public $logger = null; // Обьект для ведения лога public $logger = null; // Обьект для ведения лога
private $factory = null; // Ссылка на обьект создания модели private $factory = null; // Ссылка на обьект создания модели
private $helpers = array(); // Помошники для действий private $helpers = array(); // Помошники для действий
public $part = null; // Параметры для ссылки public $part = null; // Параметры для ссылки
public $config/*: Registry*/; // Ссылка на настройки public $config/*: Registry*/; // Ссылка на настройки
@ -100,7 +100,7 @@ class Action
/** /**
* Создает представление * Создает представление
* @param string * @param string
* @param string $viewClass * @param string $viewClass
* @return Composite * @return Composite
*/ */
@ -130,7 +130,7 @@ class Action
$scriptPath = Path::join($webPath, 'assets'); $scriptPath = Path::join($webPath, 'assets');
$tpl->set('icons', $iconsPath); // Путь к файлам текущей темы $tpl->set('icons', $iconsPath); // Путь к файлам текущей темы
$tpl->set('assets', $stylePath); $tpl->set('assets', $stylePath);
$tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('script', $scriptPath); // Путь к файлам скриптов
$tpl->set('template', $path); // Путь к файлам текущего шаблона $tpl->set('template', $path); // Путь к файлам текущего шаблона
@ -162,7 +162,7 @@ class Action
* Т.к действия являются методами класса то * Т.к действия являются методами класса то
* 1. Можно переопределить действия * 1. Можно переопределить действия
* 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение
* @param HttpRequest $request запроса * @param HttpRequest $request запроса
*/ */
public function preProcess(HttpRequest $request) public function preProcess(HttpRequest $request)
{ {
@ -172,12 +172,12 @@ 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)
{ {
$result = $this->preProcess($request); $result = $this->preProcess($request);
@ -298,14 +298,14 @@ class Action
/** /**
* Установка заголовка для отображения * Установка заголовка для отображения
*/ */
public function setTitle($title) public function setTitle($title)
{ {
$this->view->setTitle($title); $this->view->setTitle($title);
} }
/** /**
* Добавление widget к отображению * Добавление widget к отображению
*/ */
public function addChild($section, $node) 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; $this->childViews[$section] = $node;
} }
@ -329,11 +329,11 @@ class Action
* Генерация содержания * Генерация содержания
* Путаница c execute и render * Путаница c execute и render
*/ */
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,17 +344,17 @@ 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;
} }
function getPageId(HttpRequest $request) { function getPageId(HttpRequest $request) {
$pageId = time(); $pageId = time();
$request->session()->set('page', $pageId); $request->session()->set('page', $pageId);
return $pageId; return $pageId;
} }
function checkPageId(HttpRequest $request, $page) function checkPageId(HttpRequest $request, $page)
{ {
if ($request->get('__forced__')) { if ($request->get('__forced__')) {
return true; return true;

View file

@ -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);
}
}
}
}
} }

View file

@ -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;
}
} }

View file

@ -10,33 +10,33 @@ use TheSeer\Tokenizer\Exception;
class PDOStatement extends \PDOStatement implements \IteratorAggregate class PDOStatement extends \PDOStatement implements \IteratorAggregate
{ {
protected $cursorPos = 0; protected $cursorPos = 0;
public $cache = array(); public $cache = array();
public $fields; public $fields;
function getIterator(): \Iterator { function getIterator(): \Iterator {
return new StatementIterator($this); return new StatementIterator($this);
} }
protected function __construct() { protected function __construct() {
} }
function rewind() { function rewind() {
$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;
} }
@ -49,7 +49,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
if ($this->getRecordCount() > $this->cursorPos) { if ($this->getRecordCount() > $this->cursorPos) {
if (!isset($this->cache[$this->cursorPos])) { if (!isset($this->cache[$this->cursorPos])) {
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC); $this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
} }
$this->fields = $this->cache[$this->cursorPos]; $this->fields = $this->cache[$this->cursorPos];
$this->cursorPos++; $this->cursorPos++;
@ -102,7 +102,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
function getRecordCount() { function getRecordCount() {
return count($this->cache); return count($this->cache);
} }
function execute($args = null) { function execute($args = null) {
$result = parent::execute($args); $result = parent::execute($args);
return $result; return $result;

View file

@ -10,40 +10,40 @@ class StatementIterator implements \Iterator
private $pos = 0; private $pos = 0;
private $fetchmode; private $fetchmode;
private $row_count; private $row_count;
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() {
$this->pos = 0; $this->pos = 0;
} }
function valid() { function valid() {
return ($this->pos < $this->row_count); return ($this->pos < $this->row_count);
} }
function key() { function key() {
return $this->pos; return $this->pos;
} }
function current() { function current() {
if (!isset($this->result->cache[$this->pos])) { if (!isset($this->result->cache[$this->pos])) {
$this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC); $this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC);
} }
return $this->result->cache[$this->pos]; return $this->result->cache[$this->pos];
} }
function next() { function next() {
$this->pos++; $this->pos++;
} }
function seek($index) { function seek($index) {
$this->pos = $index; $this->pos = $index;
} }
function count() { function count() {
return $this->row_count; return $this->row_count;
} }
} }