This commit is contained in:
Duidev Software House
2025-11-06 07:14:08 +07:00
parent 6dd49e447b
commit fda1ef3a5c
8 changed files with 174 additions and 110 deletions
@@ -35,30 +35,47 @@ class JsonTransferController extends Controller
public function generate()
{
//POSTGRESS
$tables = DB::select("SELECT tablename FROM pg_tables WHERE schemaname = 'public'");
$exportPath = base_path($this->exportPath);
if (!is_dir($exportPath)) {
mkdir($exportPath, 0777, true);
}
$tables = DB::select("SELECT tablename FROM pg_tables WHERE schemaname = 'public'");
$tableNames = array_map(fn($t) => $t->tablename, $tables);
//MYSQL
//$tables = DB::select('SHOW TABLES');
//$tableNames = array_map('current', $tables);
foreach ($tableNames as $table) {
try {
$data = DB::table($table)->get();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents(base_path($this->exportPath . $table . '.json'), $json);
$filePath = $exportPath . $table . '.json';
$handle = fopen($filePath, 'w');
fwrite($handle, "[\n");
$first = true;
foreach (DB::table($table)->cursor() as $row) {
$jsonRow = json_encode($row, JSON_UNESCAPED_UNICODE);
if (!$first) {
fwrite($handle, ",\n");
} else {
$first = false;
}
fwrite($handle, $jsonRow);
}
fwrite($handle, "\n]");
fclose($handle);
} catch (\Exception $e) {
// Bisa log error-nya atau skip tabel ini
\Log::warning("Gagal ekspor tabel $table: " . $e->getMessage());
continue;
}
}
return redirect()->back()->with('success', 'Semua tabel berhasil diekspor.');
return redirect()->back()->with('success', 'Semua tabel berhasil diekspor tanpa kehabisan memori.');
}
public function downloadTable($table)
{
$file = base_path($this->exportPath . $table . '.json');
@@ -89,30 +106,21 @@ class JsonTransferController extends Controller
public function importTable($table)
{
$path = base_path($this->exportPath . $table . '.json');
if (!file_exists($path)) {
return redirect()->back()->with('error', "File JSON untuk tabel $table tidak ditemukan.");
}
$json = file_get_contents($path);
$data = json_decode($json, true);
if (!is_array($data)) {
return redirect()->back()->with('error', "File JSON untuk tabel $table tidak valid.");
}
try {
DB::beginTransaction();
// Kosongkan tabel sebelum import (opsional, hati-hati!)
DB::table($table)->truncate();
$chunks = array_chunk($data, 200); // ubah 1000 sesuai kemampuan server
$chunks = array_chunk($data, 200);
foreach ($chunks as $chunk) {
DB::table($table)->insert($chunk);
}
DB::commit();
return redirect()->back()->with('success', "Data untuk tabel $table berhasil di-import.");
} catch (\Exception $e) {