Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Neto committed Jul 28, 2024
1 parent 1d1e04f commit 13fe6c9
Showing 1 changed file with 18 additions and 174 deletions.
192 changes: 18 additions & 174 deletions install/mysqlRestore.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//streamer config
$global['createDatabase'] = 1;
$doNotIncludeConfig = 1;
require_once __DIR__ . '/../videos/configuration.php';
require_once __DIR__.'/../videos/configuration.php';

if (php_sapi_name() !== 'cli') {
return die('Command Line only');
Expand All @@ -15,7 +15,7 @@
echo "Searching [{$globPattern}]" . PHP_EOL;
$glob = glob($globPattern);
foreach ($glob as $key => $file) {
echo "($key) {$file} " . humanFileSize(filesize($file)) . PHP_EOL;
echo "($key) {$file} ".humanFileSize(filesize($file)) . PHP_EOL;
}

// Check for command line argument
Expand All @@ -39,7 +39,7 @@
//include './mysqlDump.php';
echo PHP_EOL . "Backup file created at {$file}" . PHP_EOL;
*/

$global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, '', @$mysqlPort);
try {
Expand All @@ -54,189 +54,33 @@
$global['mysqli']->select_db($mysqlDatabase);

echo "Execute filename {$filename}" . PHP_EOL;
//executeFile($filename);
executeFileUsingCommandLine($filename);
executeFile($filename);

function executeFile($filename)
{
function executeFile($filename) {
global $global;
$templine = '';
// Read in entire file
$lines = file($filename);
// Lista para armazenar comandos SQL
$commands = [];
// Lista para armazenar comandos de criação de tabelas
$createTableCommands = [];
// Lista para armazenar todas as tabelas identificadas
$tables = [];
// Separar comandos SQL e identificar tabelas
// Loop through each line
foreach ($lines as $line) {
// Pular se for um comentário ou linha vazia
if (substr($line, 0, 2) == '--' || trim($line) == '')
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;

// Adicionar esta linha ao segmento atual
// Add this line to the current segment
$templine .= $line;
// Se tiver um ponto e vírgula no final, é o final da consulta
if (substr(trim($line), -1) == ';') {
$commands[] = $templine;
if (stripos($templine, 'CREATE TABLE') !== false) {
$createTableCommands[] = $templine;
$tableName = preg_split('/[\s`]+/', $templine)[2]; // Extrair o nome da tabela
$tables[] = $tableName;
}
// Resetar a variável temporária para vazia
$templine = '';
}
}
// Modificar comandos CREATE TABLE para CREATE TABLE IF NOT EXISTS
foreach ($createTableCommands as &$command) {
if (stripos($command, 'CREATE TABLE') !== false && stripos($command, 'IF NOT EXISTS') === false) {
$command = str_ireplace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $command);
}
}
// Desativar a verificação de chaves estrangeiras
try {
$global['mysqli']->query('SET foreign_key_checks = 0;');
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'SET foreign_key_checks = 0\': ' . $e->getMessage() . PHP_EOL;
return;
}
// Executar DROP TABLE IF EXISTS separado de CREATE TABLE
foreach ($tables as $table) {
$dropTableCommand = 'DROP TABLE IF EXISTS `' . $table . '`;';
try {
if (!$global['mysqli']->query($dropTableCommand)) {
throw new Exception($global['mysqli']->error);
}
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $dropTableCommand . '\': ' . $e->getMessage() . PHP_EOL;
}
}
// Executar comandos de criação de tabela
foreach ($createTableCommands as $command) {
try {
if (!$global['mysqli']->query($command)) {
throw new Exception($global['mysqli']->error);
}
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $command . '\': ' . $e->getMessage() . PHP_EOL;
}
}
// Adicionar LOCK TABLES para todas as tabelas identificadas
if (!empty($tables)) {
$lockTables = 'LOCK TABLES ' . implode(' WRITE, ', $tables) . ' WRITE;';
try {
if (!$global['mysqli']->query($lockTables)) {
throw new Exception($global['mysqli']->error);
}
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $lockTables . '\': ' . $e->getMessage() . PHP_EOL;
return;
}
}
// Executar todos os outros comandos SQL
foreach ($commands as $command) {
if (!in_array($command, $createTableCommands)) {
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
try {
if (!$global['mysqli']->query($command)) {
throw new Exception($global['mysqli']->error);
if (!$global['mysqli']->query($templine)) {
echo ('sqlDAL::executeFile ' . $filename . ' Error performing query \'<strong>' . $templine . '\': ' . $global['mysqli']->error . '<br /><br />');
}
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'' . $command . '\': ' . $e->getMessage() . PHP_EOL;
} catch (\Exception $th) {
echo $th->getMessage().PHP_EOL;
}
// Reset temp variable to empty
$templine = '';
}
}
// Reativar a verificação de chaves estrangeiras
try {
$global['mysqli']->query('SET foreign_key_checks = 1;');
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'SET foreign_key_checks = 1\': ' . $e->getMessage() . PHP_EOL;
}
// Desbloquear as tabelas no final
try {
$global['mysqli']->query('UNLOCK TABLES;');
} catch (Exception $e) {
echo 'sqlDAL::executeFile ' . $filename . ' Error performing query \'UNLOCK TABLES\': ' . $e->getMessage() . PHP_EOL;
}
}
*/
executeFileUsingCommandLine($filename);

function executeFileUsingCommandLine($filename) {
global $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort;

$mysqli = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, '', @$mysqlPort);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

// Drop and create the database again
try {
$dropSQL = "DROP DATABASE IF EXISTS {$mysqlDatabase};";
$createSQL = "CREATE DATABASE IF NOT EXISTS {$mysqlDatabase};";

if (!$mysqli->query($dropSQL)) {
throw new Exception($mysqli->error);
}
if (!$mysqli->query($createSQL)) {
throw new Exception($mysqli->error);
}
$mysqli->select_db($mysqlDatabase);
} catch (Exception $e) {
echo 'Error performing query: ' . $e->getMessage() . PHP_EOL;
return;
}

// Disable foreign key checks
try {
$mysqli->query('SET foreign_key_checks = 0;');
} catch (Exception $e) {
echo 'Error disabling foreign key checks: ' . $e->getMessage() . PHP_EOL;
return;
}

// Prepare the command
$command = sprintf(
'mysql --host=%s --user=%s --password=%s --port=%s %s < %s',
escapeshellarg($mysqlHost),
escapeshellarg($mysqlUser),
escapeshellarg($mysqlPass),
escapeshellarg($mysqlPort),
escapeshellarg($mysqlDatabase),
escapeshellarg($filename)
);

echo "Executing command..." . PHP_EOL;

$output = [];
$return_var = null;
exec($command, $output, $return_var);

if ($return_var !== 0) {
echo "Error executing file using command line. Return code: $return_var" . PHP_EOL;
echo implode(PHP_EOL, $output) . PHP_EOL;
} else {
echo "File executed successfully using command line." . PHP_EOL;
}

// Enable foreign key checks
try {
$mysqli->query('SET foreign_key_checks = 1;');
} catch (Exception $e) {
echo 'Error enabling foreign key checks: ' . $e->getMessage() . PHP_EOL;
return;
}

$mysqli->close();
}

0 comments on commit 13fe6c9

Please sign in to comment.