AmberDB

 view release on metacpan or  search on metacpan

lib/AmberDB/Tools/Maintain.pm  view on Meta::CPAN

        my $schema_file = "$schema_dir/$tid.table";
        if ( -e $schema_file ) {
            open my $sfh, "<:raw", $schema_file or next;
            local $/ = undef;
            my $schema_content = <$sfh>;
            close $sfh;
            $tar->add_data( "schema/$tid.table", $schema_content );
            $table_manifest->{schema} = "schema/$tid.table";
        }

        # Tablo ID tipine göre anahtar kontrolü (use_simple, ascii, num)
        my $key_validator = $self->_get_key_validator($tid);

        # B. Export Data Files (.db, .del, .aut, .cnt) as Base64 text dump
        foreach my $sfx ( keys %sfx_map ) {
            my $fpath = "$tpath.$sfx";
            if ( -e $fpath ) {
                next unless $adb->table_read($fpath);

                my $dcontent   = "";
                my $valid_keys = 0;
                $adb->recs_scan(
                    $fpath,
                    sub {
                        my ( $k, $v ) = @_;
                        return unless $key_validator->( $k, $sfx );
                        my $b64 = MIME::Base64::encode_base64( $v, "" );
                        $dcontent .= "$k\t$b64\n";
                        $valid_keys++;
                    }
                );
                $adb->table_close($fpath);

                my $dump_sfx = $sfx_map{$sfx};
                my $norm_fpath = $fpath;
                $norm_fpath =~ s{\\}{/}g;
                my $arch_path;
                if ( $norm_fpath =~ m{^\Q$base_dir\E/(.+)\.\Q$sfx\E$} ) {
                    $arch_path = "$1.$dump_sfx";
                }
                else {
                    $arch_path = "table/$tid.$dump_sfx";
                }

                $tar->add_data( $arch_path, $dcontent );
                push @{ $table_manifest->{files} }, $arch_path;

                my $sha256 = Digest::SHA::sha256_hex($dcontent);
                $table_manifest->{sha256}->{$arch_path} = $sha256;

                if ( $sfx eq $db_ext ) {
                    $table_manifest->{records} = $valid_keys;
                }
            }
        }

        $manifest->{tables}->{$tid} = $table_manifest;
    }

    # Add manifest.json to archive
    my $json = JSON::PP->new->utf8->pretty->encode($manifest);
    $tar->add_data( "manifest.json", $json );

    # Write tar.gz archive
    unless ( $tar->write( $outfile, Archive::Tar::COMPRESS_GZIP() ) ) {
        cluck "[DB_BACKUP] Failed to write archive $outfile: " . $tar->error() . "\n";
        return;
    }

    $self->{say} .= "Archive successfully written to $outfile (" . ( -s $outfile ) . " bytes)\n";
    return wantarray ? ( $outfile, $manifest ) : $outfile;
}

# Restores a .amberdb archive into target database, validates checksums,
# writes data files via native DB_File, and deterministically rebuilds all indexes.
# my $res = $tools->restore( file => 'backup.amberdb', [force => 1], [reindex => 1] );
# ---------------------------------------------------------------------
sub restore {
    my ( $self, @args ) = @_;
    my $adb = $self->{_adb} or return;

    my %opts;
    if ( @args == 1 && ref( $args[0] ) eq 'HASH' ) {
        %opts = %{ $args[0] };
    }
    elsif ( @args % 2 == 1 && !ref( $args[0] ) ) {
        my $first = shift @args;
        %opts = @args;
        $opts{file} //= $first if defined $first && length $first;
    }
    else {
        %opts = @args;
    }

    my $file = $opts{file} or do {
        cluck "[DB_RESTORE] Missing required parameter 'file'.\n";
        return;
    };
    return unless -e $file;

    require Archive::Tar;
    require Digest::SHA;
    require JSON::PP;
    require MIME::Base64;
    require File::Path;

    my $tar = Archive::Tar->new();
    unless ( $tar->read($file) ) {
        cluck "[DB_RESTORE] Cannot read archive $file: " . $tar->error() . "\n";
        return;
    }

    # 1. Read and parse manifest.json
    my $manifest_content = $tar->get_content("manifest.json");
    unless ($manifest_content) {
        cluck "[DB_RESTORE] Archive $file is missing manifest.json.\n";
        return;
    }

    my $manifest = eval { JSON::PP->new->utf8->decode($manifest_content) };
    if ( $@ || ref($manifest) ne 'HASH' ) {
        cluck "[DB_RESTORE] Corrupted manifest.json in $file: $@\n";
        return;
    }

    # 2. Check if target DB is empty or force is set
    my $schema_dir = $adb->path('schema_dir')
      || ( $adb->path('dbase_dir') ? $adb->path('dbase_dir') . "/schema" : "schema" );
    my $table_dir = $adb->path('table_dir')
      || ( $adb->path('dbase_dir') ? $adb->path('dbase_dir') . "/table" : "table" );

    my $force = $opts{force} || $opts{overwrite};
    unless ($force) {
        my $has_existing = 0;
        my $db_ext = $adb->{db_ext} || "db";
        foreach my $tid ( keys %{ $manifest->{tables} || {} } ) {
            if ( -e "$table_dir/$tid.$db_ext" || -e "$schema_dir/$tid.table" ) {
                $has_existing = 1;
                last;
            }
        }
        if ($has_existing) {
            cluck "[DB_RESTORE] Target database is not empty. Use 'force => 1' to overwrite existing tables.\n";
            return;
        }
    }

    # Ensure target directories exist
    $adb->make_path($schema_dir);
    $adb->make_path($table_dir);

    # Flush all active handles before restoring
    $adb->close_all();

    my @restored_tables;
    my %table_filter = $opts{tables} ? map { $_ => 1 } @{ $opts{tables} } : ();

    # 3. Extract .dbase database group schemas
    if ( ref( $manifest->{dbases} ) eq 'HASH' ) {
        foreach my $dbs ( sort keys %{ $manifest->{dbases} } ) {
            my $arch_path = $manifest->{dbases}->{$dbs};
            my $scontent = $tar->get_content($arch_path);
            if ( defined $scontent ) {
                my $target_dbase = "$schema_dir/$dbs.dbase";
                open my $dfh, ">:raw", $target_dbase or do {
                    cluck "[DB_RESTORE] Cannot write dbase schema $target_dbase: $!\n";
                    return;
                };
                print $dfh $scontent;
                close $dfh;
            }
        }
    }

    # 4. Extract table schemas and data files
    my $base_dir = $adb->path('dbase_dir') || ".";
    $base_dir =~ s{\\}{/}g;
    $base_dir =~ s{/$}{};

    my %restore_sfx_map = (



( run in 0.571 second using v1.01-cache-2.11-cpan-234fa220139 )