Created
August 8, 2014 19:02
-
-
Save neves/a135c2f781fd7fb1516e to your computer and use it in GitHub Desktop.
This file contains 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 | |
class DB2PHP { | |
public function __construct($dir, $conn, $records_per_page = 1000) { | |
@mkdir($dir); | |
$this->dir = $dir; | |
$this->conn = $conn; | |
$this->records_per_page = $records_per_page; | |
} | |
public function exportTables($tables) { | |
foreach ($tables as $table) { | |
$this->exportSchema($table); | |
$this->exportTable($table); | |
} | |
} | |
protected function exportSchema($table) { | |
$columns = $this->getTableColumns($table); | |
$columns = var_export($columns, true); | |
$schema = "<? \$columns = $columns;\n"; | |
file_put_contents("$this->dir/$table.php", $schema); | |
} | |
protected function getTableColumns($table) { | |
$row = $this->conn->query("SELECT * FROM $table LIMIT 1")->fetch(PDO::FETCH_ASSOC); | |
return $row ? array_keys($row) : array(); | |
} | |
protected function exportTable($table) { | |
$dir = $this->createTableDir($table); | |
$page = -1; | |
$start = time(); | |
echo PHP_EOL.$table.PHP_EOL; | |
while (true) { | |
$page++; | |
$file = sprintf('%s/%05d.php', $dir, $page); | |
$time = date("i:s", time() - $start); | |
echo " $time\t$page \r"; | |
if ( file_exists($file) ) continue; | |
$rows = $this->paginate($table, $page); | |
if (empty($rows)) break; | |
$this->writeRowsToPageFile($rows, $file); | |
} | |
echo PHP_EOL; | |
} | |
protected function createTableDir($table) { | |
$dir = "$this->dir/$table"; | |
@mkdir($dir); | |
return $dir; | |
} | |
protected function buildQuery($table, $page) { | |
$page = $page * $this->records_per_page; | |
return "SELECT * FROM $table LIMIT $page, $this->records_per_page"; | |
} | |
protected function paginate($table, $page) { | |
$sql = $this->buildQuery($table, $page); | |
return $this->conn->query($sql)->fetchAll(PDO::FETCH_NUM); | |
} | |
protected function writeRowsToPageFile($rows, $file) { | |
$array = var_export($rows, true); | |
$php = "<?php\n\$array = $array;\n"; | |
file_put_contents($file, $php); | |
} | |
} | |
$pdo = new PDO('mysql:host=localhost;dbname=isse', 'root', ''); | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$db2php = new DB2PHP('/tmp/isse', $pdo); | |
$tables = ['autos_protocolos', 'autos', 'usuarios_log', 'pagamentos', 'endereco', 'doc_dados']; | |
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN, 0); | |
$db2php->exportTables($tables); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment