Query/src/Query/Drivers/Pgsql/Util.php

97 lines
2.0 KiB
PHP
Raw Normal View History

2016-10-12 22:12:25 -04:00
<?php declare(strict_types=1);
/**
* Query
*
2016-09-07 13:17:17 -04:00
* SQL Query Builder / Database Abstraction Layer
*
2018-01-19 13:43:19 -05:00
* PHP version 7.1
2016-09-07 13:17:17 -04:00
*
* @package Query
* @author Timothy J. Warren <tim@timshomepage.net>
2018-01-19 13:43:19 -05:00
* @copyright 2012 - 2018 Timothy J. Warren
2016-09-07 13:17:17 -04:00
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link https://git.timshomepage.net/aviat4ion/Query
*/
namespace Query\Drivers\Pgsql;
2014-04-02 17:08:50 -04:00
2016-09-07 17:39:19 -04:00
use Query\Drivers\AbstractUtil;
/**
* Posgres-specific backup, import and creation methods
*/
2016-09-07 17:39:19 -04:00
class Util extends AbstractUtil {
/**
* Create an SQL backup file for the current database's structure
*
* @return string
*/
2016-10-13 21:55:23 -04:00
public function backupStructure()
{
2016-09-07 17:39:19 -04:00
// @TODO Implement Backup function
return '';
}
/**
* Create an SQL backup file for the current database's data
*
* @param array $exclude
* @return string
*/
2016-10-13 21:55:23 -04:00
public function backupData($exclude=[])
{
2016-10-13 21:55:23 -04:00
$tables = $this->getDriver()->getTables();
// Filter out the tables you don't want
if( ! empty($exclude))
{
$tables = array_diff($tables, $exclude);
}
2016-10-13 21:55:23 -04:00
$outputSql = '';
// Get the data for each object
foreach($tables as $t)
{
$sql = 'SELECT * FROM "'.trim($t).'"';
2016-10-13 21:55:23 -04:00
$res = $this->getDriver()->query($sql);
$objRes = $res->fetchAll(\PDO::FETCH_ASSOC);
// Don't add to the file if the table is empty
2016-10-13 21:55:23 -04:00
if (count($objRes) < 1)
2015-11-11 09:25:21 -05:00
{
continue;
}
$res = NULL;
// Nab the column names by getting the keys of the first row
2016-10-13 21:55:23 -04:00
$columns = @array_keys($objRes[0]);
2016-10-13 21:55:23 -04:00
$insertRows = [];
// Create the insert statements
2016-10-13 21:55:23 -04:00
foreach($objRes as $row)
{
$row = array_values($row);
// Quote values as needed by type
2016-10-13 21:55:23 -04:00
$row = array_map([$this->getDriver(), 'quote'], $row);
$row = array_map('trim', $row);
2016-10-13 21:55:23 -04:00
$rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
$row = NULL;
2016-10-13 21:55:23 -04:00
$insertRows[] = $rowString;
}
2016-10-13 21:55:23 -04:00
$objRes = NULL;
2016-10-13 21:55:23 -04:00
$outputSql .= "\n\n".implode("\n", $insertRows)."\n";
}
2016-10-13 21:55:23 -04:00
return $outputSql;
}
2016-10-13 21:55:23 -04:00
}