Last active
September 3, 2021 15:05
-
-
Save frugan-dev/9b42050a54bf57ba5bcbe892c17bc809 to your computer and use it in GitHub Desktop.
Plugin for the RedBeanPHP ORM, which will create Backup files for a MySql DB Server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use RedBeanPHP\Facade as R; | |
//https://github.com/zewa666/RedBean_MysqlBackup | |
R::ext('mysqldump', function (string $file, int $step = 100) { | |
if (!(R::getWriter() instanceof \RedBeanPHP\QueryWriter\MySQL)) { | |
throw new Exception('This plugin only supports MySql.'); | |
} | |
$buffer = ''; | |
foreach (R::inspect() as $table) { | |
$buffer .= 'DROP TABLE '.$table.';'.PHP_EOL; | |
$row = R::getRow('SHOW CREATE TABLE '.$table); | |
$buffer .= $row['Create Table'].';'.PHP_EOL; | |
$fields = R::inspect($table); | |
$pdo = R::getPDO(); | |
$query = $pdo->prepare('SELECT * FROM '.$table); | |
$query->execute(); | |
$n = 0; | |
while ($row = $query->fetch()) { | |
$parts = []; | |
if (is_int($n / $step)) { | |
if ($n > 0) { | |
$buffer .= ';'.PHP_EOL; | |
} | |
$buffer .= 'INSERT INTO '.$table.' VALUES'; | |
} else { | |
$buffer .= ','; | |
} | |
$buffer .= ' ('; | |
foreach ($fields as $key => $field) { | |
if (is_null($row[$key])) { | |
$parts[] = 'NULL'; | |
} else { | |
$parts[] = $pdo->quote((string) $row[$key]); | |
} | |
} | |
$buffer .= implode(',', $parts).')'; | |
++$n; | |
} | |
if ($n > 0) { | |
$buffer .= ';'; | |
} | |
$buffer .= PHP_EOL; | |
} | |
return file_put_contents($file, $buffer); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment