feat(backup): implement proprietary encrypted .kmh format, dual backup selection (pilih vs semua), and clean minimalist UI

This commit is contained in:
Ray1111-aa
2026-10-28 09:20:18 +07:00
parent 238ec128d2
commit cb9891b1e3
5 changed files with 742 additions and 670 deletions
+330 -239
View File
@@ -11,6 +11,8 @@ use ZipArchive;
class DatabaseBackupService
{
public const KMH_MAGIC_HEADER = "KMH_ENCRYPTED_BACKUP_V1\n";
protected string $backupDir;
public function __construct()
@@ -29,6 +31,61 @@ class DatabaseBackupService
return $this->backupDir;
}
/**
* Dapatkan kunci enkripsi 256-bit berbasis APP_KEY sistem.
* Hanya sistem ini yang bisa mendekripsi dan membaca konten file .kmh.
*/
protected function getEncryptionKey(): string
{
$appKey = config('app.key');
if (str_starts_with((string)$appKey, 'base64:')) {
$appKey = base64_decode(substr((string)$appKey, 7));
}
return hash('sha256', (string)$appKey . '_RKM_KMH_ENCRYPTION_SECRET', true);
}
/**
* Enkripsi payload mentah ke dalam format kontainer aman .kmh dengan header magic bytes & HMAC.
*/
public function encryptToKmh(string $rawContent): string
{
$key = $this->getEncryptionKey();
$iv = random_bytes(16);
$ciphertext = openssl_encrypt($rawContent, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext, $key, true);
return self::KMH_MAGIC_HEADER . $iv . $hmac . $ciphertext;
}
/**
* Dekripsi file .kmh kembali ke konten arsip aslinya setelah verifikasi HMAC.
*/
public function decryptFromKmh(string $kmhContent): string
{
$headerLen = strlen(self::KMH_MAGIC_HEADER);
if (substr($kmhContent, 0, $headerLen) !== self::KMH_MAGIC_HEADER) {
throw new RuntimeException("File ini bukan format arsip .kmh yang sah atau file rusak.");
}
$iv = substr($kmhContent, $headerLen, 16);
$hmac = substr($kmhContent, $headerLen + 16, 32);
$ciphertext = substr($kmhContent, $headerLen + 48);
$key = $this->getEncryptionKey();
$calculatedHmac = hash_hmac('sha256', $ciphertext, $key, true);
if (!hash_equals($hmac, $calculatedHmac)) {
throw new RuntimeException("Gagal membuka file .kmh: Kunci enkripsi tidak cocok atau file telah dimodifikasi oleh sistem luar.");
}
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
throw new RuntimeException("Gagal mendekripsi payload arsip .kmh.");
}
return $decrypted;
}
/**
* Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru.
*
@@ -40,7 +97,8 @@ class DatabaseBackupService
* size_raw: int,
* size_human: string,
* created_at: Carbon,
* created_at_human: string
* created_at_human: string,
* is_kmh: bool
* }>
*/
public function listBackups(): array
@@ -50,17 +108,18 @@ class DatabaseBackupService
foreach ($files as $file) {
$extension = strtolower($file->getExtension());
if (!in_array($extension, ['sql', 'zip', 'gz'])) {
if (!in_array($extension, ['kmh', 'sql', 'zip', 'gz'])) {
continue;
}
$filename = $file->getFilename();
$size = $file->getSize();
$createdAt = Carbon::createFromTimestamp($file->getMTime());
$isKmh = ($extension === 'kmh');
$isFull = str_ends_with($filename, '.zip') || str_contains($filename, '_full_');
$type = $isFull ? 'full' : 'database';
$typeLabel = $isFull ? 'Full Backup (+ File Media)' : 'Database SQL';
$isFull = str_contains($filename, 'semua') || str_contains($filename, '_full_') || $extension === 'zip';
$type = $isFull ? 'semua' : 'pilihan';
$typeLabel = $isFull ? 'Backup Semua' : 'Pilih Backup';
$backups[] = [
'filename' => $filename,
@@ -71,6 +130,7 @@ class DatabaseBackupService
'size_human' => $this->formatBytes($size),
'created_at' => $createdAt,
'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB',
'is_kmh' => $isKmh,
];
}
@@ -80,167 +140,104 @@ class DatabaseBackupService
}
/**
* Buat backup database (MySQL / SQLite) ke dalam file .sql murni.
* Menggunakan PDO stream generator mandiri tanpa ketergantungan mysqldump eksternal.
* Buat backup terenkripsi .kmh (baik "Pilih Backup" tabel tertentu atau "Backup Semua" + media).
*
* @param array<int, string>|null $selectedTables Tabel yang dipilih (null = semua tabel)
* @param bool $includeMedia Sertakan file media upload di storage/app/public
* @param string|null $customFilename Nama file kustom opsional
*/
public function createDatabaseBackup(?string $customFilename = null): string
{
@set_time_limit(300);
@ini_set('memory_limit', '512M');
$driver = DB::connection()->getDriverName();
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database);
$timestamp = now()->format('Ymd_His');
$filename = $customFilename ?: "backup_db_{$cleanDbName}_{$timestamp}.sql";
// Amankan nama file dari traversal
$filename = basename($filename);
if (!str_ends_with($filename, '.sql')) {
$filename .= '.sql';
}
$fullPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename;
$handle = fopen($fullPath, 'w');
if (!$handle) {
throw new RuntimeException("Gagal membuka file backup untuk penulisan: {$fullPath}");
}
try {
$pdo = DB::connection()->getPdo();
$nowString = now()->format('Y-m-d H:i:s');
// Header SQL Standar
fwrite($handle, "-- ==============================================================\n");
fwrite($handle, "-- RKM-KMH DATABASE BACKUP (PT Kerinci Merangin Hidro)\n");
fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n");
fwrite($handle, "-- Driver : {$driver}\n");
fwrite($handle, "-- Database : {$database}\n");
fwrite($handle, "-- ==============================================================\n\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n");
} else {
fwrite($handle, "SET NAMES utf8mb4;\n");
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n");
fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n");
fwrite($handle, "SET time_zone = '+00:00';\n\n");
}
// Ambil daftar seluruh tabel aktif
$tables = $this->getAllTableNames();
foreach ($tables as $tableName) {
$this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver);
}
// Footer SQL
fwrite($handle, "\n-- ==============================================================\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = ON;\n");
} else {
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n");
}
fwrite($handle, "-- END OF RKM-KMH DATABASE BACKUP\n");
fwrite($handle, "-- ==============================================================\n");
fclose($handle);
return $filename;
} catch (\Throwable $e) {
if (is_resource($handle)) {
fclose($handle);
}
if (File::exists($fullPath)) {
File::delete($fullPath);
}
throw new RuntimeException("Gagal membuat backup database: " . $e->getMessage(), 0, $e);
}
}
/**
* Buat full backup (.zip) yang mencakup file database .sql dan seluruh file upload media (storage/app/public).
*/
public function createFullBackup(?string $customFilename = null): string
public function createKmhBackup(?array $selectedTables = null, bool $includeMedia = false, ?string $customFilename = null): string
{
@set_time_limit(600);
@ini_set('memory_limit', '512M');
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
throw new RuntimeException('Ekstensi PHP ZipArchive diperlukan untuk memaketkan arsip.');
}
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$allTables = $this->getAllTableNames();
$targetTables = (!empty($selectedTables)) ? array_values(array_intersect($allTables, $selectedTables)) : $allTables;
if (empty($targetTables)) {
throw new RuntimeException('Silakan pilih minimal satu tabel yang ingin dicadangkan.');
}
$database = config('database.connections.' . config('database.default') . '.database', 'rkm_kmh');
$cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database);
$timestamp = now()->format('Ymd_His');
$zipFilename = $customFilename ?: "backup_full_{$cleanDbName}_{$timestamp}.zip";
$zipFilename = basename($zipFilename);
if (!str_ends_with($zipFilename, '.zip')) {
$zipFilename .= '.zip';
$isFull = ($includeMedia || count($targetTables) === count($allTables));
$prefix = $includeMedia ? 'backup_semua' : 'backup_pilihan';
$filename = $customFilename ?: "{$prefix}_{$cleanDbName}_{$timestamp}.kmh";
$filename = basename($filename);
if (!str_ends_with($filename, '.kmh')) {
$filename .= '.kmh';
}
$zipFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $zipFilename;
// 1. Buat temporary SQL dump terlebih dahulu
$tempSqlName = "temp_db_{$timestamp}.sql";
$this->createDatabaseBackup($tempSqlName);
$tempSqlFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $tempSqlName;
// 1. Buat temporary SQL dump untuk tabel-tabel yang dipilih
$tempSqlFile = storage_path('app/temp_dump_' . uniqid() . '.sql');
$this->dumpTablesToSqlFile($targetTables, $tempSqlFile);
// 2. Buat temporary ZIP container
$tempZipFile = storage_path('app/temp_pkg_' . uniqid() . '.zip');
$zip = new ZipArchive();
if ($zip->open($zipFullPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
throw new RuntimeException("Gagal membuat file ZIP di: {$zipFullPath}");
if ($zip->open($tempZipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
@unlink($tempSqlFile);
throw new RuntimeException('Gagal membuat paket arsip sementara.');
}
try {
// Masukkan database SQL ke dalam root arsip ZIP
$zip->addFile($tempSqlFullPath, 'database.sql');
$zip->addFile($tempSqlFile, 'database.sql');
// Masukkan seluruh file media yang ada di storage/app/public (misal foto profil, foto kendaraan, simper)
$publicStorageDir = storage_path('app/public');
if (File::isDirectory($publicStorageDir)) {
$files = File::allFiles($publicStorageDir);
foreach ($files as $file) {
$relativePath = 'storage/' . $file->getRelativePathname();
$zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath));
// Tambahkan file media jika diminta (Backup Semua)
if ($includeMedia) {
$publicStorageDir = storage_path('app/public');
if (File::isDirectory($publicStorageDir)) {
$files = File::allFiles($publicStorageDir);
foreach ($files as $file) {
$relativePath = 'storage/' . $file->getRelativePathname();
$zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath));
}
}
}
// Tambahkan metadata ringkas manifest.json
// Manifest informasi arsip .kmh
$manifest = [
'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)',
'format' => 'KMH_ENCRYPTED_V1',
'created_at' => now()->toIso8601String(),
'type' => 'full',
'type' => $includeMedia ? 'semua' : 'pilihan',
'database' => $database,
'table_count' => count($targetTables),
'tables' => $targetTables,
'has_media' => $includeMedia,
'laravel_version' => app()->version(),
'php_version' => PHP_VERSION,
];
$zip->addFromString('manifest.json', json_encode($manifest, JSON_PRETTY_PRINT));
$zip->close();
// Hapus file temporary SQL
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
@unlink($tempSqlFile);
return $zipFilename;
// 3. Enkripsi seluruh paket ZIP menjadi file .kmh terenkripsi
$rawZipContent = file_get_contents($tempZipFile);
@unlink($tempZipFile);
$encryptedKmh = $this->encryptToKmh($rawZipContent);
$finalPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename;
file_put_contents($finalPath, $encryptedKmh);
return $filename;
} catch (\Throwable $e) {
$zip->close();
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
if (File::exists($zipFullPath)) {
File::delete($zipFullPath);
}
throw new RuntimeException("Gagal membuat full backup ZIP: " . $e->getMessage(), 0, $e);
if (is_file($tempSqlFile)) @unlink($tempSqlFile);
if (is_file($tempZipFile)) @unlink($tempZipFile);
throw new RuntimeException("Gagal membuat arsip terenkripsi .kmh: " . $e->getMessage(), 0, $e);
}
}
/**
* Pulihkan (Restore) database & aset dari file backup (.sql atau .zip).
* Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback).
*/
public function restore(string $backupFilenameOrPath): void
{
@@ -255,28 +252,107 @@ class DatabaseBackupService
throw new RuntimeException("File backup tidak ditemukan: {$filePath}");
}
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$content = file_get_contents($filePath);
$headerLen = strlen(self::KMH_MAGIC_HEADER);
// Jika file berformat .kmh terenkripsi
if (substr($content, 0, $headerLen) === self::KMH_MAGIC_HEADER) {
$this->restoreFromKmhContent($content);
return;
}
// Fallback untuk file .sql atau .zip warisan
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if ($extension === 'zip') {
$this->restoreFromZip($filePath);
} elseif ($extension === 'sql') {
$this->restoreFromSql($filePath);
} elseif ($extension === 'gz') {
$this->restoreFromGzip($filePath);
} else {
throw new RuntimeException("Format file tidak didukung untuk pemulihan: .{$extension}");
}
}
/**
* Pulihkan dari file SQL langsung.
* Pulihkan dari konten terenkripsi .kmh.
*/
protected function restoreFromKmhContent(string $kmhContent): void
{
$decryptedZipContent = $this->decryptFromKmh($kmhContent);
$tempZipFile = storage_path('app/temp_restore_' . uniqid() . '.zip');
file_put_contents($tempZipFile, $decryptedZipContent);
try {
$this->restoreFromZip($tempZipFile);
@unlink($tempZipFile);
} catch (\Throwable $e) {
if (is_file($tempZipFile)) @unlink($tempZipFile);
throw $e;
}
}
/**
* Pulihkan dari file arsip ZIP.
*/
public function restoreFromZip(string $zipFilePath): void
{
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
}
$zip = new ZipArchive();
if ($zip->open($zipFilePath) !== true) {
throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}");
}
$tempExtractDir = storage_path('app/temp_extract_' . uniqid());
File::makeDirectory($tempExtractDir, 0755, true);
try {
$zip->extractTo($tempExtractDir);
$zip->close();
// 1. Eksekusi file SQL database
$sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql';
if (!File::exists($sqlFile)) {
$foundSql = File::glob($tempExtractDir . '/*.sql');
if (!empty($foundSql)) {
$sqlFile = $foundSql[0];
} else {
throw new RuntimeException('File database.sql tidak ditemukan di dalam paket arsip.');
}
}
$this->restoreFromSql($sqlFile);
// 2. Pulihkan file aset media ke storage/app/public jika ada
$extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage';
$targetStorageDir = storage_path('app/public');
if (File::isDirectory($extractedStorageDir)) {
if (!File::isDirectory($targetStorageDir)) {
File::makeDirectory($targetStorageDir, 0755, true);
}
File::copyDirectory($extractedStorageDir, $targetStorageDir);
}
File::deleteDirectory($tempExtractDir);
} catch (\Throwable $e) {
if (File::isDirectory($tempExtractDir)) {
File::deleteDirectory($tempExtractDir);
}
throw $e;
}
}
/**
* Eksekusi pemulihan dari file skrip SQL.
*/
public function restoreFromSql(string $sqlFilePath): void
{
$pdo = DB::connection()->getPdo();
$driver = DB::connection()->getDriverName();
// Nonaktifkan pemeriksaan foreign key untuk mencegah deadlock/relasi urutan
if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = OFF;");
} else {
@@ -303,9 +379,7 @@ class DatabaseBackupService
while (($line = fgets($handle)) !== false) {
$trimmed = trim($line);
// Lewati komentar baris tunggal jika tidak sedang di dalam quote
if (!$inQuotes && (str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*') || str_starts_with($trimmed, '#'))) {
// Cek jika komentar multi baris
if (str_starts_with($trimmed, '/*') && !str_ends_with($trimmed, '*/')) {
while (($line = fgets($handle)) !== false) {
if (str_contains($line, '*/')) break;
@@ -341,7 +415,6 @@ class DatabaseBackupService
$quoteChar = $char;
$currentQuery .= $char;
} elseif ($char === ';') {
// Akhir dari sebuah statement SQL
$statement = trim($currentQuery);
if ($statement !== '') {
$pdo->exec($statement);
@@ -354,7 +427,6 @@ class DatabaseBackupService
}
}
// Jalankan statement terakhir jika ada yang tersisa tanpa titik koma
$finalStatement = trim($currentQuery);
if ($finalStatement !== '') {
$pdo->exec($finalStatement);
@@ -379,96 +451,6 @@ class DatabaseBackupService
}
}
/**
* Pulihkan dari file full backup .zip (restore database.sql dan sinkronkan file media).
*/
public function restoreFromZip(string $zipFilePath): void
{
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
}
$zip = new ZipArchive();
if ($zip->open($zipFilePath) !== true) {
throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}");
}
$tempExtractDir = storage_path('app/temp_restore_' . uniqid());
File::makeDirectory($tempExtractDir, 0755, true);
try {
$zip->extractTo($tempExtractDir);
$zip->close();
// 1. Eksekusi file SQL database
$sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql';
if (!File::exists($sqlFile)) {
$foundSql = File::glob($tempExtractDir . '/*.sql');
if (!empty($foundSql)) {
$sqlFile = $foundSql[0];
} else {
throw new RuntimeException('File database.sql tidak ditemukan di dalam paket ZIP.');
}
}
$this->restoreFromSql($sqlFile);
// 2. Pulihkan file aset media ke storage/app/public jika ada
$extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage';
$targetStorageDir = storage_path('app/public');
if (File::isDirectory($extractedStorageDir)) {
if (!File::isDirectory($targetStorageDir)) {
File::makeDirectory($targetStorageDir, 0755, true);
}
File::copyDirectory($extractedStorageDir, $targetStorageDir);
}
// Bersihkan temporary folder
File::deleteDirectory($tempExtractDir);
} catch (\Throwable $e) {
if (File::isDirectory($tempExtractDir)) {
File::deleteDirectory($tempExtractDir);
}
throw $e;
}
}
/**
* Pulihkan dari file SQL terkompresi Gzip (.sql.gz).
*/
protected function restoreFromGzip(string $gzFilePath): void
{
if (!function_exists('gzopen')) {
throw new RuntimeException('Ekstensi PHP zlib tidak tersedia untuk dekompresi gzip.');
}
$tempSqlFile = storage_path('app/temp_restore_' . uniqid() . '.sql');
$gz = gzopen($gzFilePath, 'rb');
$out = fopen($tempSqlFile, 'wb');
if (!$gz || !$out) {
throw new RuntimeException("Gagal mengekstrak file gzip: {$gzFilePath}");
}
while (!gzeof($gz)) {
fwrite($out, gzread($gz, 65536));
}
gzclose($gz);
fclose($out);
try {
$this->restoreFromSql($tempSqlFile);
File::delete($tempSqlFile);
} catch (\Throwable $e) {
if (File::exists($tempSqlFile)) {
File::delete($tempSqlFile);
}
throw $e;
}
}
/**
* Hapus file backup tertentu dari penyimpanan.
*/
@@ -486,16 +468,6 @@ class DatabaseBackupService
/**
* Dapatkan informasi statistik penyimpanan backup dan database sistem.
*
* @return array{
* total_backups: int,
* total_size_raw: int,
* total_size_human: string,
* database_name: string,
* table_count: int,
* estimated_db_size_human: string,
* last_backup: ?array
* }
*/
public function getSystemStats(): array
{
@@ -556,6 +528,126 @@ class DatabaseBackupService
return $names;
}
/**
* Kelompokkan tabel database ke dalam modul-modul fungsional untuk memudahkan pilihan backup.
*
* @return array<string, array{name: string, description: string, tables: array<int, string>}>
*/
public function getTableGroups(): array
{
$allTables = $this->getAllTableNames();
$groups = [
'hse' => [
'name' => 'K3 / HSE (Karyawan & SIMPER)',
'description' => 'Data personil karyawan, master jenis SIMPER, dan izin mengemudi.',
'tables' => array_values(array_intersect($allTables, [
'employees', 'simper_types', 'employee_simpers'
])),
],
'qma' => [
'name' => 'QMA (Kendaraan, Alat Berat & P2H)',
'description' => 'Master unit LV/HE, checklist P2H, transfer unit, dan log aktivitas.',
'tables' => array_values(array_intersect($allTables, [
'vehicles', 'vehicle_activities', 'vehicle_location_histories',
'unit_transfers', 'unit_support_timesheets', 'p2h_templates',
'p2h_template_items', 'p2h_records', 'p2h_record_items'
])),
],
'pg' => [
'name' => 'Private Guard (Satpam & Pos Gerbang)',
'description' => 'Data personil satpam lapangan dan pos pemeriksaan gerbang.',
'tables' => array_values(array_intersect($allTables, [
'gates', 'security_guards'
])),
],
'rbac' => [
'name' => 'Pengguna & Hak Akses (RBAC)',
'description' => 'Akun pengguna, jabatan role, direct permissions, dan log aktivitas admin.',
'tables' => array_values(array_intersect($allTables, [
'users', 'roles', 'permissions', 'model_has_roles',
'model_has_permissions', 'role_has_permissions', 'admin_activity_logs'
])),
],
'system' => [
'name' => 'Sistem & Internal Database',
'description' => 'Migrasi, sesi, cache, dan antrean background jobs.',
'tables' => array_values(array_intersect($allTables, [
'migrations', 'sessions', 'cache', 'cache_locks',
'jobs', 'job_batches', 'failed_jobs', 'password_reset_tokens'
])),
],
];
// Kelompokkan tabel lain jika ada tabel kustom tambahan di database
$categorized = [];
foreach ($groups as $g) {
$categorized = array_merge($categorized, $g['tables']);
}
$otherTables = array_values(array_diff($allTables, $categorized));
if (!empty($otherTables)) {
$groups['other'] = [
'name' => 'Tabel Lainnya',
'description' => 'Tabel data tambahan sistem.',
'tables' => $otherTables,
];
}
return $groups;
}
/**
* Dump struktur dan data dari daftar tabel tertentu ke file SQL.
*
* @param array<int, string> $tables
*/
protected function dumpTablesToSqlFile(array $tables, string $targetSqlPath): void
{
$handle = fopen($targetSqlPath, 'w');
if (!$handle) {
throw new RuntimeException("Gagal membuka file SQL sementara untuk penulisan: {$targetSqlPath}");
}
try {
$pdo = DB::connection()->getPdo();
$driver = DB::connection()->getDriverName();
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$nowString = now()->format('Y-m-d H:i:s');
fwrite($handle, "-- ==============================================================\n");
fwrite($handle, "-- RKM-KMH SECURE DATABASE DUMP (PT Kerinci Merangin Hidro)\n");
fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n");
fwrite($handle, "-- Database : {$database}\n");
fwrite($handle, "-- ==============================================================\n\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n");
} else {
fwrite($handle, "SET NAMES utf8mb4;\n");
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n");
fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n");
fwrite($handle, "SET time_zone = '+00:00';\n\n");
}
foreach ($tables as $tableName) {
$this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver);
}
fwrite($handle, "\n-- ==============================================================\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = ON;\n");
} else {
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n");
}
fwrite($handle, "-- END OF DUMP\n");
fclose($handle);
} catch (\Throwable $e) {
if (is_resource($handle)) fclose($handle);
throw $e;
}
}
/**
* Dump struktur dan data satu tabel database.
*/
@@ -579,7 +671,6 @@ class DatabaseBackupService
fwrite($handle, $createTableSql . ";\n\n");
}
// Dump Data Baris (chunk 200 baris untuk efisiensi RAM)
fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n");
$query = DB::table($tableName);