AmberDB

 view release on metacpan or  search on metacpan

bin/amberdb_cli.pl  view on Meta::CPAN

            render_records_table( [ $data ], $table );
        }
        return;
    }

    print Dumper($data);
}

# ============================================================================
# CLI ARGUMENT PARSER (DASH-TOLERANT: --key=val, -key=val, key=val)
# ============================================================================

my $opt_action;
my $opt_token;
my $opt_format;
our $opt_time   = 0;
my $opt_dry_run = 0;
my $opt_force   = 0;
our $opt_help      = 0;
our $opt_help_lang;
my $opt_database;
my $opt_user;
my $opt_pass;

my %method_args;
my @pos_args;

# Step 1: Pre-pass for space-separated flags (--db <val>, -d <val>, --token <val>, etc.)
my @raw_tokens;
my $arg_idx = 0;
while ( $arg_idx < @ARGV ) {
    my $curr = $ARGV[$arg_idx];
    if ( $curr =~ /^--(?:db|dbase|dbase_dir)=(.*)$/i ) {
        my $val = eval { abs_path($1) } // $1;
        $adb->set_datadir($val);
        $explicit_db = 1;
        $has_path_updates = 1;
    }
    elsif ( $curr =~ /^(?:path-dbase_dir|db)=(.*)$/i ) {
        my $val = eval { abs_path($1) } // $1;
        $adb->set_datadir($val);
        $explicit_db = 1;
        $has_path_updates = 1;
    }
    elsif ( ( $curr =~ /^--(?:db|dbase|dbase_dir)$/i || $curr =~ /^-d$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        my $val = $ARGV[++$arg_idx];
        $val = eval { abs_path($val) } // $val;
        $adb->set_datadir($val);
        $explicit_db = 1;
        $has_path_updates = 1;
    }
    elsif ( $curr =~ /^(?:--?)?token=(.*)$/i ) {
        $opt_token = $1;
    }
    elsif ( ( $curr =~ /^--(?:token)$/i || $curr =~ /^-k$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $opt_token = $ARGV[++$arg_idx];
    }
    elsif ( ( $curr =~ /^--(?:user|username)$/i || $curr =~ /^-u$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $opt_user = $ARGV[++$arg_idx];
    }
    elsif ( ( $curr =~ /^--(?:pass|password|passwd)$/i || $curr =~ /^-p$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $opt_pass = $ARGV[++$arg_idx];
    }
    elsif ( ( $curr =~ /^--(?:format)$/i || $curr =~ /^-f$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $opt_format = lc($ARGV[++$arg_idx]);
    }
    elsif ( ( $curr =~ /^--(?:limit)$/i || $curr =~ /^-l$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $method_args{limit} = parse_value($ARGV[++$arg_idx]);
    }
    elsif ( ( $curr =~ /^--(?:offset)$/i || $curr =~ /^-o$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $method_args{offset} = parse_value($ARGV[++$arg_idx]);
    }
    elsif ( ( $curr =~ /^--(?:dir)$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $method_args{dir} = lc($ARGV[++$arg_idx]);
    }
    elsif ( ( $curr =~ /^--(?:data)$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
        $method_args{data} = parse_value($ARGV[++$arg_idx]);
    }
    elsif ( $curr =~ /^--(?:time)$/i ) {
        $opt_time = 1;
    }
    elsif ( $curr =~ /^--(?:version)$/i || $curr =~ /^-v$/i ) {
        $opt_action = 'version';
    }
    else {
        push @raw_tokens, $curr;
    }
    $arg_idx++;
}

# Step 2: Known action definitions
my %known_actions = map { $_ => 1 } qw(
    setup install ramdisk
    connect disconnect path config cfg attr table_attr user users
    status tables list info table_info read read_id read_all read_list
    search search_table fetch field_fetch count table_count
    insert insert_id update update_id delete delete_id
    reindex check vacuum migrate update_table update_storage update_version
    export tie2csv import csv2tie dump restore rename drop help usage
    help.tr usage.tr help.en usage.en version
);

# Step 3: Check if first token is a session token (e.g. 1245 or existing session file)
if ( !defined $opt_token && @raw_tokens ) {
    my $first = $raw_tokens[0];
    my $clean_first = $first;
    $clean_first =~ s/^--?//;
    if ( $clean_first !~ /=/ && !$known_actions{ lc($clean_first) } ) {
        if ( $clean_first =~ /^[a-zA-Z0-9]{4,8}$/ && @raw_tokens > 1 ) {
            $opt_token = shift @raw_tokens;
            $opt_token =~ s/^--?//;
        }
    }
}

# Step 4: Extract trailing format and time keywords if provided as standalone keywords
for ( 1 .. 2 ) {
    last unless @raw_tokens > 1;
    my $last = $raw_tokens[-1];
    if ( !defined $opt_format && $last =~ /^(?:json|pretty|tsv|dumper|perl|raw|table)$/i && $last !~ /=/ ) {
        $opt_format = lc( pop @raw_tokens );

bin/amberdb_cli.pl  view on Meta::CPAN

        elsif ( $k =~ /^(?:force|f)$/ ) {
            $opt_force = $val ? 1 : 0;
        }
        elsif ( $k =~ /^(?:check|c)$/i ) {
            $method_args{check} = $val ? 1 : 0;
        }
        elsif ( $k =~ /^(?:all|a)$/i ) {
            $method_args{all} = $val ? 1 : 0;
        }
        elsif ( $k =~ /^(?:no-backup|no_backup)$/i ) {
            $method_args{no_backup} = $val ? 1 : 0;
        }
        elsif ( $k eq 'cpanm' ) {
            $method_args{cpanm} = $v;
        }
        elsif ( $k eq 'manifest' ) {
            $method_args{manifest} = $v;
        }
        elsif ( $k =~ /^(?:help|h|usage)$/i ) {
            $opt_help = 1;
            if ( defined $v && $v =~ /^(?:tr|en)$/i ) {
                $opt_help_lang = lc($v);
            }
        }
        elsif ( $k =~ /^(?:help|usage)\.(tr|en)$/i ) {
            $opt_help = 1;
            $opt_help_lang = lc($1);
        }
        elsif ( $k =~ /^cfg-(.+)$/ ) {
            $adb->config( $1 => $val );
            $has_cfg_updates = 1;
        }
        elsif ( $k =~ /^path-(.+)$/ ) {
            my $pkey = $1;
            if ( $pkey eq 'dbase_dir' || $pkey eq 'db' || $pkey eq 'dbase' ) {
                my $abs = eval { abs_path($val) } // $val;
                $adb->set_datadir($abs);
                $explicit_db = 1;
            }
            else {
                $adb->path( $pkey => $val );
            }
            $has_path_updates = 1;
        }
        elsif ( $k eq 'no_write' ) {
            $adb->config( no_write => $val );
            $has_cfg_updates = 1;
        }
        elsif ( $k eq 'db' || $k eq 'dbase_dir' || $k eq 'dbase' ) {
            my $abs = eval { abs_path($val) } // $val;
            $adb->set_datadir($abs);
            $explicit_db = 1;
            $has_path_updates = 1;
        }
        elsif ( $k eq 'data' ) {
            $method_args{data} = $val;
        }
        elsif ( $k eq 'user' || $k eq 'username' ) {
            $opt_user = $val;
        }
        elsif ( $k eq 'pass' || $k eq 'password' || $k eq 'passwd' ) {
            $opt_pass = $val;
        }
        elsif ( $k eq 'database' || $k eq 'dbname' ) {
            $opt_database = $val;
            $adb->{_connect}->{database} = $val;
            $adb->clear_cache('ramdisk');
            $adb->ramdisk_setup();
        }
        else {
            if ( $k =~ /[-.]/ ) {
                my @parts = split /[-.]/, $k;
                set_nested_key( \%method_args, \@parts, $val );
            }
            else {
                $method_args{$k} = $val;
            }
        }
    }
    else {
        if ( $arg =~ /^(?:help|h|usage)$/i ) {
            $opt_help = 1;
            $opt_action //= 'help';
        }
        elsif ( $arg =~ /^(?:help|usage)\.(tr|en)$/i ) {
            $opt_help = 1;
            $opt_help_lang = lc($1);
            $opt_action //= 'help';
        }
        elsif ( $arg =~ /^(?:dry-run|dry_run)$/i ) {
            $opt_dry_run = 1;
        }
        elsif ( $arg =~ /^(?:force|f)$/i ) {
            $opt_force = 1;
        }
        elsif ( $raw =~ /^--?(?:check|c)$/i ) {
            $method_args{check} = 1;
        }
        elsif ( $raw =~ /^--?(?:all|a)$/i ) {
            $method_args{all} = 1;
        }
        elsif ( $raw =~ /^--?(?:no-backup|no_backup)$/i ) {
            $method_args{no_backup} = 1;
        }

        elsif ( $raw =~ /^--?time$/i ) {
            $opt_time = 1;
        }
        elsif ( !defined $opt_action ) {
            $opt_action = $arg;
        }
        else {
            push @pos_args, $arg;
        }
    }
}

# Step 6: Action alias normalization
if ( defined $opt_action ) {
    my $act = lc($opt_action);
    if ( $act =~ /^(?:help|usage)(?:\.(tr|en))?$/i ) {

bin/amberdb_cli.pl  view on Meta::CPAN


    if ( defined $conn_arg ) {
        # Custom directory format: <dbname>@<path> (e.g. mydb@./dbstore or mydb@C:/data)
        if ( $conn_arg =~ /^([a-zA-Z0-9_\-]+)@(.+)$/ ) {
            $conn_db     = $1;
            $custom_path = $2;
        }
        else {
            $conn_db = $conn_arg;
        }
    }

    if ( defined $conn_db && ( $conn_db eq 'dbstore' || $conn_db =~ m{[/\\\\]} || $conn_db =~ /^[a-zA-Z]:/ ) ) {
        die "[AMBERDB_ERROR] '$conn_db' is a directory path/name, not a valid database name. Database name is expected after 'connect'. For custom directory use format: <dbname>\@<path> (e.g. amberdb connect mydb\@./dbstore) or specify --db=<dir>.\n"...
    }

    $conn_db //= $detected_dbname;
    unless ( defined $conn_db && length $conn_db ) {
        die "[AMBERDB_ERROR] Database name required. Usage: amberdb connect <database_name> (or <database_name>\@<path>)\n";
    }

    my $target_data_dir;
    if ( defined $custom_path && length $custom_path ) {
        $target_data_dir = resolve_abs_path($custom_path);
    }
    elsif ( $explicit_db ) {
        $target_data_dir = $adb->path('dbase_dir');
    }
    else {
        # Central store under ~/.amberdb/<dbname>
        $target_data_dir = "$AMBERDB_HOME/$conn_db";
    }
    $target_data_dir = resolve_abs_path($target_data_dir);

    # Ensure target data directory and skeleton exist
    make_path(
        "$target_data_dir/table", "$target_data_dir/schema", "$target_data_dir/journal",
        "$target_data_dir/lock",  "$target_data_dir/session", "$target_data_dir/config",
        "$target_data_dir/backup", "$target_data_dir/ramdisk"
    );
    my $conf_file = "$target_data_dir/config/core.conf";
    if ( !-f $conf_file && open my $cfh, '>', $conf_file ) {
        print $cfh "site_id        $conn_db\nlanguage       tr\n";
        close $cfh;
    }

    $adb->set_datadir($target_data_dir);
    $adb->{_connect}->{database} = $conn_db;
    $adb->clear_cache('ramdisk');
    $adb->ramdisk_setup();

    # Authenticate and generate token
    my $conn_user = 'cli';
    my $entered_user = shift @pos_args if @pos_args;
    my $conn_pass = $opt_pass // shift @pos_args // '';

    my $token = eval {
        $adb->connect(
            database => $conn_db,
            username => $conn_user,
            ( defined $conn_pass && length $conn_pass ? ( password => $conn_pass ) : () ),
        );
    };
    if ( $@ || !$token ) {
        my $err = $@ || $adb->last_error() || "Authentication failed";
        $err =~ s/ at .* line \d+.*//s;
        die "[AMBERDB_ERROR] $err\n";
    }

    # Save session with canonical absolute path in ~/.amberdb/session/sess_$token
    my $sess_data = {
        token    => $token,
        database => $conn_db,
        username => $conn_user,
        path     => { dbase_dir => $target_data_dir },
        cfg      => $adb->config(),
    };
    set_session_path( $token, $target_data_dir, $sess_data );

    my $actual_file = cli_session_file($token);

    if ( defined $opt_format && $opt_format eq 'json' ) {
        print encode_json( {
            status       => 'connected',
            token        => $token,
            session_file => $actual_file,
            database     => $conn_db,
            username     => $conn_user,
            path         => { dbase_dir => $target_data_dir },
            cfg          => $adb->config(),
        } ), "\n";
    }
    else {
        print "[AMBERDB] Connected successfully.\n";
        print "Session Token : $token\n";
        print "Database      : $conn_db\n";
        print "Data Dir      : $target_data_dir\n";
        print "Session File  : $actual_file\n";
        print "\nUsage with Token:\n";
        print "  amberdb $token tables\n";
        print "  amberdb $token read <table_name> <id>\n";
        print "Or set environment variable in current shell:\n";
        print "  export AMBERDB_TOKEN=$token  (Windows CMD: set AMBERDB_TOKEN=$token)\n";
    }
    exit 0;
}

if ( defined $opt_action && $opt_action eq 'disconnect' ) {
    my $token = $active_token || resolve_active_token( $opt_token, 1 );
    unless ($token) {
        die "[AMBERDB_ERROR] No active session token found to disconnect.\n";
    }
    $adb->disconnect($token);
    delete_session($token);
    if ( defined $opt_format && $opt_format eq 'json' ) {
        print encode_json( { status => 'disconnected', token => $token } ), "\n";
    }
    else {
        print "[AMBERDB] Disconnected session '$token' successfully.\n";
    }
    exit 0;

bin/amberdb_cli.pl  view on Meta::CPAN

        }
        $session->{cfg} = $adb->config();
        $session->{updated_at} = time();
        save_session( $active_token, $session );
        output_result( { status => 'ok', action => 'config', token => $active_token, cfg => $adb->config() }, $opt_format );
    }
    else {
        output_result( $adb->config() // {}, $opt_format );
    }
    exit 0;
}

if ( defined $opt_action && $opt_action eq 'path' ) {
    unless ($session) {
        die "[AMBERDB_ERROR] 'path' requires an active session. Run 'connect' first (e.g. amberdb connect path-dbase_dir=...) or specify a token.\n";
    }
    if ( %method_args || $has_path_updates ) {
        my $old_file = session_file($active_token);
        for my $k ( keys %method_args ) {
            my $val = $method_args{$k};
            if ( $k eq 'dbase_dir' || $k eq 'db' || $k eq 'dbase' ) {
                my $new_db_dir = eval { abs_path($val) } // $val;
                $adb->set_datadir($new_db_dir);
            }
            else {
                $adb->path( $k => $val );
            }
        }
        $session->{path} = $adb->path();
        $session->{updated_at} = time();

        my $new_file = session_file($active_token);
        save_session( $active_token, $session );
        if ( defined $old_file && -f $old_file && $old_file ne $new_file ) {
            unlink $old_file;
        }
        output_result( { status => 'ok', action => 'path', token => $active_token, path => $adb->path() }, $opt_format );
    }
    else {
        output_result( $adb->path() // {}, $opt_format );
    }
    exit 0;
}

if ( defined $opt_action && $opt_action eq 'user' ) {
    my $subcmd = shift @pos_args // 'list';
    if ( $subcmd eq 'list' ) {
        my @users = $adb->user_list();
        if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' ) ) {
            output_result( { status => 'ok', action => 'user_list', users => \@users }, $opt_format );
        }
        else {
            print "Database: " . ($adb->connect('database') || 'unknown') . "\n";
            print "=" x 60, "\n";
            printf( "%-20s %-15s %-15s\n", "Username", "Role", "Password Set" );
            print "-" x 60, "\n";
            for my $u (@users) {
                printf( "%-20s %-15s %-15s\n",
                    $u->{username},
                    $u->{role},
                    $u->{has_password} ? "Yes (Shadow)" : "No (Passwordless)"
                );
            }
            print "-" x 60, "\n";
        }
        exit 0;
    }
    elsif ( $subcmd eq 'add' ) {
        my $u = shift @pos_args // $opt_user;
        my $p = shift @pos_args // $opt_pass // '';
        my $role = shift @pos_args // 'user';
        die "[AMBERDB_ERROR] Usage: amberdb user add <username> [password] [role]\n" unless defined $u && length $u;
        $adb->user_add( $u, $p, role => $role );
        output_result( { status => 'ok', action => 'user_add', username => $u, role => $role }, $opt_format );
        exit 0;
    }
    elsif ( $subcmd eq 'passwd' ) {
        my $u = shift @pos_args // $opt_user;
        my $p = shift @pos_args // $opt_pass // '';
        die "[AMBERDB_ERROR] Usage: amberdb user passwd <username> <new_password>\n" unless defined $u && length $u;
        $adb->user_passwd( $u, $p );
        output_result( { status => 'ok', action => 'user_passwd', username => $u }, $opt_format );
        exit 0;
    }
    elsif ( $subcmd eq 'del' || $subcmd eq 'delete' ) {
        my $u = shift @pos_args // $opt_user;
        die "[AMBERDB_ERROR] Usage: amberdb user del <username>\n" unless defined $u && length $u;
        $adb->user_del($u);
        output_result( { status => 'ok', action => 'user_del', username => $u }, $opt_format );
        exit 0;
    }
    else {
        die "[AMBERDB_ERROR] Unknown user subcommand '$subcmd'. Available: list, add, passwd, del\n";
    }
}

# ============================================================================
# INFRASTRUCTURE SETUP & PROVISIONING (amberdb setup [dir])
# ============================================================================

if ( defined $opt_action && ( $opt_action eq 'setup' || $opt_action eq 'ramdisk' ) ) {
    my $first_arg = shift @pos_args;

    # Check if ramdisk subcommand: amberdb setup ramdisk ... or amberdb ramdisk ...
    if ( ( $opt_action eq 'ramdisk' ) || ( defined $first_arg && lc($first_arg) eq 'ramdisk' ) ) {
        my $subcmd = ( $opt_action eq 'ramdisk' ) ? ( $first_arg // 'status' ) : ( shift @pos_args // 'status' );
        $subcmd = lc($subcmd);
        $subcmd = 'start'  if $subcmd eq 'mount' || $subcmd eq '--start';
        $subcmd = 'stop'   if $subcmd eq 'unmount' || $subcmd eq '--stop';
        $subcmd = 'status' if $subcmd eq '--status';

        my $size  = delete $method_args{size}  // shift @pos_args // '512M';
        my $drive = delete $method_args{drive} // shift @pos_args // 'R:';

        my $is_win = ( $^O eq 'MSWin32' || $^O eq 'msys' || $^O eq 'cygwin' );

        if ($is_win) {
            my $script_bin = eval { abs_path(dirname(__FILE__)) } // dirname(__FILE__) // '.';
            my $bat_path = File::Spec->catfile( $script_bin, "setup_windows.bat" );
            if ( -f $bat_path ) {
                system( "cmd.exe", "/c", $bat_path, $subcmd, $size, $drive );
                exit $? >> 8;
            }
            else {
                if ( $subcmd eq 'start' ) {
                    system( "imdisk", "-a", "-s", $size, "-m", $drive, "-p", "/fs:ntfs /q /y /v:AmberDB" );
                }
                elsif ( $subcmd eq 'stop' ) {
                    system( "imdisk", "-D", "-m", $drive );
                }
                else {
                    system( "imdisk", "-l", "-m", $drive );
                }
                exit $? >> 8;
            }
        }
        else {
            if ( $subcmd eq 'status' ) {
                my $shm = -d "/dev/shm" ? "/dev/shm (Linux tmpfs available)" : "Not mounted";
                print "RAM-Disk Status: $shm\n";



( run in 0.945 second using v1.01-cache-2.11-cpan-f5f21f1076c )