| 1 | #!/usr/local/bin/perl | ||
| 2 | |||
| 3 | # bin/amberdb_cli.pl - AmberDB Command Line Interface & Management Console | ||
| 4 | # Direct file-based embedded execution, token-based session lifecycle, dynamic method reflection, and dash-tolerant argument parser. | ||
| 5 | |||
| 6 | use 5.016; | ||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use File::Basename qw(dirname basename); | ||
| 10 | use Cwd qw(abs_path getcwd); | ||
| 11 | use File::Spec; | ||
| 12 | use File::Path qw(make_path remove_tree); | ||
| 13 | use JSON::PP qw(encode_json decode_json); | ||
| 14 | use Data::Dumper; | ||
| 15 | use Time::HiRes qw(gettimeofday tv_interval); | ||
| 16 | |||
| 17 | our $t0 = [gettimeofday]; | ||
| 18 | |||
| 19 | BEGIN { | ||
| 20 | my $script_path = __FILE__; | ||
| 21 | $script_path =~ s{[\\/]+}{/}g; | ||
| 22 | my $bin_dir = $script_path =~ m{^(.*)/[^/]+$} ? $1 : '.'; | ||
| 23 | my $lib_dir = "$bin_dir/../lib"; | ||
| 24 | my $abs_lib = eval { abs_path($lib_dir) } // $lib_dir; | ||
| 25 | unshift @INC, $abs_lib if -d $abs_lib; | ||
| 26 | unshift @INC, $lib_dir if -d $lib_dir && $lib_dir ne $abs_lib; | ||
| 27 | |||
| 28 | # Auto-detect local project lib directory if running from project root (e.g. ./lib) | ||
| 29 | for my $cand ( './lib', '../lib' ) { | ||
| 30 | my $abs_cand = eval { abs_path($cand) }; | ||
| 31 | unshift @INC, $abs_cand if defined $abs_cand && -d $abs_cand; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | use AmberDB; | ||
| 36 | use AmberDB::Tools; | ||
| 37 | |||
| 38 | $| = 1; | ||
| 39 | |||
| 40 | our $adb = AmberDB->new( path => { dbase_dir => 'dbstore' }, connect => { username => 'cli' }, config => { no_mkdir => 1 } ); | ||
| 41 | our $tools = AmberDB::Tools->new($adb); | ||
| 42 | |||
| 43 | # ============================================================================ | ||
| 44 | # ============================================================================ | ||
| 45 | # SESSION REGISTRY (~/.amberdb/session/) | ||
| 46 | # Stores session files per active session under ~/.amberdb/session/sess_$token | ||
| 47 | # ============================================================================ | ||
| 48 | |||
| 49 | my $user_home = $ENV{USERPROFILE} // $ENV{HOME} // '.'; | ||
| 50 | $user_home =~ s{\\}{/}g; | ||
| 51 | our $AMBERDB_HOME = "$user_home/.amberdb"; | ||
| 52 | our $CLI_SESS_DIR = "$AMBERDB_HOME/session"; | ||
| 53 | |||
| 54 | sub setup_global_workspace { | ||
| 55 | eval { | ||
| 56 | make_path($AMBERDB_HOME) unless -d $AMBERDB_HOME; | ||
| 57 | make_path($CLI_SESS_DIR) unless -d $CLI_SESS_DIR; | ||
| 58 | my $cfg_dir = "$AMBERDB_HOME/config"; | ||
| 59 | make_path($cfg_dir) unless -d $cfg_dir; | ||
| 60 | }; | ||
| 61 | } | ||
| 62 | |||
| 63 | # Auto-provision global workspace in background on first run if missing | ||
| 64 | if ( !-d $AMBERDB_HOME ) { | ||
| 65 | setup_global_workspace(); | ||
| 66 | } | ||
| 67 | |||
| 68 | sub resolve_abs_path { | ||
| 69 | my ($path) = @_; | ||
| 70 | return '' unless defined $path && length $path; | ||
| 71 | $path =~ s{\\}{/}g; | ||
| 72 | my $abs = eval { abs_path($path) }; | ||
| 73 | if ( defined $abs && length $abs ) { | ||
| 74 | $abs =~ s{\\}{/}g; | ||
| 75 | return $abs; | ||
| 76 | } | ||
| 77 | my $cwd = eval { getcwd() } // '.'; | ||
| 78 | $cwd =~ s{\\}{/}g; | ||
| 79 | my $rel = File::Spec->rel2abs( $path, $cwd ); | ||
| 80 | $rel =~ s{\\}{/}g; | ||
| 81 | return $rel; | ||
| 82 | } | ||
| 83 | |||
| 84 | sub cli_session_file { | ||
| 85 | my ($token) = @_; | ||
| 86 | return '' unless $token; | ||
| 87 | return "$CLI_SESS_DIR/sess_$token"; | ||
| 88 | } | ||
| 89 | |||
| 90 | sub get_session_path { | ||
| 91 | my ($token) = @_; | ||
| 92 | $token //= ''; | ||
| 93 | |||
| 94 | # 1. If token is provided, check ~/.amberdb/session/sess_$token | ||
| 95 | if ( $token ) { | ||
| 96 | my $file = cli_session_file($token); | ||
| 97 | if ( -f $file && open my $fh, '<', $file ) { | ||
| 98 | local $/; | ||
| 99 | my $content = <$fh>; | ||
| 100 | close $fh; | ||
| 101 | return '' unless $content; | ||
| 102 | my $data = eval { decode_json($content) }; | ||
| 103 | if ( $data && ref $data eq 'HASH' && $data->{path} && $data->{path}->{dbase_dir} ) { | ||
| 104 | return $data->{path}->{dbase_dir}; | ||
| 105 | } | ||
| 106 | # Fallback if stored as plain path string | ||
| 107 | $content =~ s/^\s+|\s+$//g if defined $content; | ||
| 108 | return $content if length $content && -d $content; | ||
| 109 | } | ||
| 110 | } | ||
| 111 | |||
| 112 | return undef; | ||
| 113 | } | ||
| 114 | |||
| 115 | sub set_session_path { | ||
| 116 | my ( $token, $db_path, $sess_data ) = @_; | ||
| 117 | return unless defined $token && length $token; | ||
| 118 | make_path($CLI_SESS_DIR) unless -d $CLI_SESS_DIR; | ||
| 119 | |||
| 120 | my $abs_path = resolve_abs_path($db_path); | ||
| 121 | |||
| 122 | my $file = cli_session_file($token); | ||
| 123 | if ( open my $fh, '>', $file ) { | ||
| 124 | if ($sess_data) { | ||
| 125 | $sess_data->{path}->{dbase_dir} = $abs_path if $sess_data->{path}; | ||
| 126 | print $fh encode_json($sess_data); | ||
| 127 | } | ||
| 128 | else { | ||
| 129 | print $fh encode_json( { | ||
| 130 | token => $token, | ||
| 131 | path => { dbase_dir => $abs_path }, | ||
| 132 | } ); | ||
| 133 | } | ||
| 134 | close $fh; | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 138 | sub del_session_path { | ||
| 139 | my ($token) = @_; | ||
| 140 | return unless defined $token && length $token; | ||
| 141 | |||
| 142 | # Delete ~/.amberdb/session/sess_$token | ||
| 143 | my $file = cli_session_file($token); | ||
| 144 | unlink $file if defined $file && -f $file; | ||
| 145 | } | ||
| 146 | |||
| 147 | # ============================================================================ | ||
| 148 | # RESOLVE DBASE_DIR FROM CLI ARGUMENTS | ||
| 149 | # 1- Argümanlı: --db=dbstore veya --dbase_dir=/path/to (ayrıca -d, db=, path-dbase_dir=) | ||
| 150 | # 2- Oturum token'ı varsa: .amberdb/session/ içinden dbase_dir tespit et | ||
| 151 | # Argümandan gelmiyorsa: bulunduğu dizinde dbstore oluşturur. | ||
| 152 | # (Not: connect'ten sonraki argüman veritabanı adıdır, dbase_dir değildir) | ||
| 153 | # ============================================================================ | ||
| 154 | |||
| 155 | my $target_db; | ||
| 156 | my $from_cli_args = 0; | ||
| 157 | |||
| 158 | # 1. Argümanlı: --db=dbstore veya --dbase_dir=/path/to (ayrıca -d, db=, path-dbase_dir=) | ||
| 159 | for (my $i = 0; $i < @ARGV; $i++) { | ||
| 160 | my $arg = $ARGV[$i]; | ||
| 161 | if ( $arg =~ /^--(?:db|dbase_dir)=(.*)$/i || $arg =~ /^(?:path-dbase_dir|db)=(.*)$/i ) { | ||
| 162 | $target_db = resolve_abs_path($1) if defined $1 && length $1; | ||
| 163 | $from_cli_args = 1; | ||
| 164 | last; | ||
| 165 | } | ||
| 166 | elsif ( ( $arg =~ /^--(?:db|dbase_dir)$/i || $arg =~ /^-d$/i ) && $i + 1 < @ARGV && $ARGV[$i + 1] !~ /^-/ ) { | ||
| 167 | $target_db = resolve_abs_path($ARGV[$i + 1]); | ||
| 168 | $from_cli_args = 1; | ||
| 169 | last; | ||
| 170 | } | ||
| 171 | } | ||
| 172 | |||
| 173 | # 3. Oturum token'ı varsa: .amberdb/session/ içinden dbase_dir tespit et | ||
| 174 | if ( !defined $target_db ) { | ||
| 175 | my $token; | ||
| 176 | for (my $i = 0; $i < @ARGV; $i++) { | ||
| 177 | my $arg = $ARGV[$i]; | ||
| 178 | if ( $arg =~ /^(?:--?)?token=(.*)$/i ) { | ||
| 179 | $token = $1; | ||
| 180 | last; | ||
| 181 | } | ||
| 182 | elsif ( ( $arg =~ /^--(?:token)$/i || $arg =~ /^-k$/i ) && $i + 1 < @ARGV && $ARGV[$i + 1] !~ /^-/ ) { | ||
| 183 | $token = $ARGV[$i + 1]; | ||
| 184 | last; | ||
| 185 | } | ||
| 186 | } | ||
| 187 | if ( !defined $token && @ARGV && $ARGV[0] =~ /^[0-9]{4}$/ ) { | ||
| 188 | $token = $ARGV[0]; | ||
| 189 | } | ||
| 190 | $token //= $ENV{AMBERDB_TOKEN}; | ||
| 191 | |||
| 192 | my $reg_db = get_session_path($token); | ||
| 193 | if ( defined $reg_db && length $reg_db ) { | ||
| 194 | $target_db = $reg_db; | ||
| 195 | } | ||
| 196 | } | ||
| 197 | |||
| 198 | # 4. Argümandan veya oturumdan gelmiyorsa: doğrudan yerel ./dbstore kullanılır | ||
| 199 | $target_db //= "dbstore"; | ||
| 200 | $target_db = resolve_abs_path($target_db); | ||
| 201 | |||
| 202 | # Datadir ataması (DİKKAT: Henüz diskte dizin oluşturulmaz! Sadece insert veya setup anında oluşturulur) | ||
| 203 | $adb->set_datadir($target_db); | ||
| 204 | |||
| 205 | # Auto-detect database name for CLI context (connect.pl -> core.conf -> path pattern) | ||
| 206 | my $detected_dbname; | ||
| 207 | if ( -f "$target_db/config/connect.pl" ) { | ||
| 208 | my $c_data = do "$target_db/config/connect.pl"; | ||
| 209 | $detected_dbname = $c_data->{database} if ref($c_data) eq 'HASH' && $c_data->{database}; | ||
| 210 | } | ||
| 211 | if ( !$detected_dbname && -f "$target_db/config/core.conf" ) { | ||
| 212 | if ( open my $cfh, '<', "$target_db/config/core.conf" ) { | ||
| 213 | while ( my $line = <$cfh> ) { | ||
| 214 | if ( $line =~ /^site_id\s+([^\s\t]+)/ ) { | ||
| 215 | $detected_dbname = $1; | ||
| 216 | last; | ||
| 217 | } | ||
| 218 | } | ||
| 219 | close $cfh; | ||
| 220 | } | ||
| 221 | } | ||
| 222 | if ( !$detected_dbname && $target_db =~ m{([^\/\\]+)[\/\\]dbstore$}i ) { | ||
| 223 | my $candidate = $1; | ||
| 224 | $detected_dbname = $candidate if $candidate && $candidate ne 'dbstore'; | ||
| 225 | } | ||
| 226 | if ( $detected_dbname && $detected_dbname ne 'dbstore' ) { | ||
| 227 | $adb->{_connect}->{database} = $detected_dbname; | ||
| 228 | $adb->clear_cache('ramdisk'); | ||
| 229 | $adb->ramdisk_setup(); | ||
| 230 | } | ||
| 231 | |||
| 232 | my $explicit_db = $from_cli_args; | ||
| 233 | my $has_cfg_updates = 0; | ||
| 234 | my $has_path_updates = 0; | ||
| 235 | |||
| 236 | # ============================================================================ | ||
| 237 | # SESSION MANAGEMENT (TOKEN & STATE PERSISTENCE UNDER $adb->path('session_dir')) | ||
| 238 | # ============================================================================ | ||
| 239 | |||
| 240 | sub generate_token { | ||
| 241 | # 4-digit session token (e.g. 1000..9999) with collision avoidance | ||
| 242 | for ( 1 .. 1000 ) { | ||
| 243 | my $token = sprintf( "%04d", int( rand(9000) ) + 1000 ); | ||
| 244 | my $sf = session_file($token); | ||
| 245 | next if defined $sf && -f $sf; | ||
| 246 | my $cf = cli_session_file($token); | ||
| 247 | next if defined $cf && -f $cf; | ||
| 248 | return $token; | ||
| 249 | } | ||
| 250 | return sprintf( "%04d", int( rand(9000) ) + 1000 ); | ||
| 251 | } | ||
| 252 | |||
| 253 | sub session_file { | ||
| 254 | my ($token) = @_; | ||
| 255 | return unless defined $token && length $token; | ||
| 256 | |||
| 257 | # 1. Local session file in working directory: .amberdb/session/sess_$token | ||
| 258 | my $local_sess = cli_session_file($token); | ||
| 259 | return $local_sess if defined $local_sess && -f $local_sess; | ||
| 260 | |||
| 261 | # 2. Database session file: RAM-disk veya standart disk | ||
| 262 | my $db_sess = $adb->path('session_dir') . "/cli_$token"; | ||
| 263 | return $db_sess if -f $db_sess; | ||
| 264 | |||
| 265 | return $local_sess; | ||
| 266 | } | ||
| 267 | |||
| 268 | sub save_session { | ||
| 269 | my ( $token, $data ) = @_; | ||
| 270 | return unless defined $token && length $token; | ||
| 271 | |||
| 272 | # 1. Save in working directory: .amberdb/session/sess_$token | ||
| 273 | set_session_path( $token, $adb->path('dbase_dir'), $data ); | ||
| 274 | |||
| 275 | # 2. Also save in database's own session_dir ($adb->path('session_dir')/cli_$token) | ||
| 276 | my $sess_dir = $adb->path('session_dir'); | ||
| 277 | my $db_file = "$sess_dir/cli_$token"; | ||
| 278 | if ( open my $dfh, '>', $db_file ) { | ||
| 279 | print $dfh encode_json($data); | ||
| 280 | close $dfh; | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 284 | sub load_session { | ||
| 285 | my ($token) = @_; | ||
| 286 | return unless defined $token && length $token; | ||
| 287 | |||
| 288 | # 1. Try local session in .amberdb/session/sess_$token | ||
| 289 | my $local_file = cli_session_file($token); | ||
| 290 | if ( defined $local_file && -f $local_file ) { | ||
| 291 | if ( open my $fh, '<', $local_file ) { | ||
| 292 | local $/; | ||
| 293 | my $json = <$fh>; | ||
| 294 | close $fh; | ||
| 295 | my $data = eval { decode_json($json) }; | ||
| 296 | # Touch mtime to mark as recently used | ||
| 297 | utime undef, undef, $local_file if $data; | ||
| 298 | return $data if $data; | ||
| 299 | } | ||
| 300 | } | ||
| 301 | |||
| 302 | # 2. Try candidate session file from database session_dir | ||
| 303 | my $file = session_file($token); | ||
| 304 | if ( defined $file && -f $file && $file ne ( $local_file // '' ) ) { | ||
| 305 | if ( open my $fh, '<', $file ) { | ||
| 306 | local $/; | ||
| 307 | my $json = <$fh>; | ||
| 308 | close $fh; | ||
| 309 | return eval { decode_json($json) }; | ||
| 310 | } | ||
| 311 | } | ||
| 312 | |||
| 313 | return undef; | ||
| 314 | } | ||
| 315 | |||
| 316 | sub delete_session { | ||
| 317 | my ($token) = @_; | ||
| 318 | return unless defined $token && length $token; | ||
| 319 | |||
| 320 | # 1. Delete from working directory: .amberdb/session/sess_$token | ||
| 321 | del_session_path($token); | ||
| 322 | |||
| 323 | # 2. Delete from database session_dir | ||
| 324 | my $db_sess = $adb->path('session_dir') . "/cli_$token"; | ||
| 325 | unlink $db_sess if -f $db_sess; | ||
| 326 | } | ||
| 327 | |||
| 328 | sub resolve_active_token { | ||
| 329 | my ( $cli_token, $allow_last_token ) = @_; | ||
| 330 | return $cli_token if defined $cli_token && length $cli_token; | ||
| 331 | return $ENV{AMBERDB_TOKEN} if defined $ENV{AMBERDB_TOKEN} && length $ENV{AMBERDB_TOKEN}; | ||
| 332 | return undef; | ||
| 333 | } | ||
| 334 | |||
| 335 | # ============================================================================ | ||
| 336 | # VALUE PARSING & NESTED KEY BUILDER | ||
| 337 | # ============================================================================ | ||
| 338 | |||
| 339 | sub parse_value { | ||
| 340 | my ($v) = @_; | ||
| 341 | return 1 unless defined $v; | ||
| 342 | $v =~ s/^\s+|\s+$//g; | ||
| 343 | # Strip wrapping quotes if preserved literally by shell (e.g. cmd.exe single quotes) | ||
| 344 | if ( ( $v =~ /^'(.*)'$/s ) || ( $v =~ /^"(.*)"$/s ) ) { | ||
| 345 | $v = $1; | ||
| 346 | $v =~ s/^\s+|\s+$//g; | ||
| 347 | } | ||
| 348 | if ( ( $v =~ /^\[.*\]$/s ) || ( $v =~ /^\{.*\}$/s ) ) { | ||
| 349 | my $decoded = eval { decode_json($v) }; | ||
| 350 | return $decoded if defined $decoded; | ||
| 351 | |||
| 352 | # Fallback if inner quotes were removed by shell: [Book,15] or ['Book',15] | ||
| 353 | if ( $v =~ /^\[(.*)\]$/s ) { | ||
| 354 | my $inner = $1; | ||
| 355 | my @items; | ||
| 356 | while ( $inner =~ /([^,]+)/g ) { | ||
| 357 | my $item = $1; | ||
| 358 | $item =~ s/^\s+|\s+$//g; | ||
| 359 | $item =~ s/^['"]//; | ||
| 360 | $item =~ s/['"]$//; | ||
| 361 | $item = 0 + $item if $item =~ /^-?\d+$/; | ||
| 362 | push @items, $item; | ||
| 363 | } | ||
| 364 | return \@items if @items; | ||
| 365 | } | ||
| 366 | |||
| 367 | # Fallback if inner quotes were removed by shell: {name:Ahmet,role:admin} | ||
| 368 | if ( $v =~ /^\{(.*)\}$/s ) { | ||
| 369 | my $inner = $1; | ||
| 370 | my %hash; | ||
| 371 | while ( $inner =~ /([^,:]+)\s*:\s*([^,]+)/g ) { | ||
| 372 | my ( $k, $item ) = ( $1, $2 ); | ||
| 373 | $k =~ s/^\s+|\s+$//g; | ||
| 374 | $k =~ s/^['"]//; | ||
| 375 | $k =~ s/['"]$//; | ||
| 376 | $item =~ s/^\s+|\s+$//g; | ||
| 377 | $item =~ s/^['"]//; | ||
| 378 | $item =~ s/['"]$//; | ||
| 379 | $item = 0 + $item if $item =~ /^-?\d+$/; | ||
| 380 | $hash{$k} = $item; | ||
| 381 | } | ||
| 382 | return \%hash if keys %hash; | ||
| 383 | } | ||
| 384 | } | ||
| 385 | return 1 if $v =~ /^(?:true|yes)$/i; | ||
| 386 | return 0 if $v =~ /^(?:false|no)$/i; | ||
| 387 | return 0 + $v if $v =~ /^-?\d+$/; | ||
| 388 | return $v; | ||
| 389 | } | ||
| 390 | |||
| 391 | sub set_nested_key { | ||
| 392 | my ( $target, $path, $val ) = @_; | ||
| 393 | my $curr = $target; | ||
| 394 | for my $i ( 0 .. $#$path - 1 ) { | ||
| 395 | my $p = $path->[$i]; | ||
| 396 | $curr->{$p} = {} unless ref $curr->{$p} eq 'HASH'; | ||
| 397 | $curr = $curr->{$p}; | ||
| 398 | } | ||
| 399 | $curr->{ $path->[-1] } = $val; | ||
| 400 | } | ||
| 401 | |||
| 402 | sub format_bytes { | ||
| 403 | my ($bytes) = @_; | ||
| 404 | return "0 B" unless defined $bytes && $bytes > 0; | ||
| 405 | if ( $bytes < 1024 ) { | ||
| 406 | return "$bytes B"; | ||
| 407 | } | ||
| 408 | elsif ( $bytes < 1024 * 1024 ) { | ||
| 409 | return sprintf( "%.1f KB", $bytes / 1024 ); | ||
| 410 | } | ||
| 411 | elsif ( $bytes < 1024 * 1024 * 1024 ) { | ||
| 412 | return sprintf( "%.1f MB", $bytes / ( 1024 * 1024 ) ); | ||
| 413 | } | ||
| 414 | else { | ||
| 415 | return sprintf( "%.2f GB", $bytes / ( 1024 * 1024 * 1024 ) ); | ||
| 416 | } | ||
| 417 | } | ||
| 418 | |||
| 419 | # ============================================================================ | ||
| 420 | # OUTPUT FORMATTING | ||
| 421 | # ============================================================================ | ||
| 422 | |||
| 423 | sub format_cell { | ||
| 424 | my ($val) = @_; | ||
| 425 | return '' unless defined $val; | ||
| 426 | if ( ref $val ) { | ||
| 427 | my $json = eval { JSON::PP->new->utf8(0)->canonical(1)->encode($val) }; | ||
| 428 | if ( defined $json ) { | ||
| 429 | $json =~ s/\r?\n/ /g; | ||
| 430 | return $json; | ||
| 431 | } | ||
| 432 | } | ||
| 433 | elsif ( $val =~ /^\{([^{}]*)\}$/s && $val !~ /"/ ) { | ||
| 434 | # Unquoted hash string from shell: {name:Ahmet,role:admin} | ||
| 435 | my $inner = $1; | ||
| 436 | my %hash; | ||
| 437 | while ( $inner =~ /([^,:]+)\s*:\s*([^,]+)/g ) { | ||
| 438 | my ( $k, $item ) = ( $1, $2 ); | ||
| 439 | $k =~ s/^\s+|\s+$//g; | ||
| 440 | $k =~ s/^['"]//; | ||
| 441 | $k =~ s/['"]$//; | ||
| 442 | $item =~ s/^\s+|\s+$//g; | ||
| 443 | $item =~ s/^['"]//; | ||
| 444 | $item =~ s/['"]$//; | ||
| 445 | $hash{$k} = ( $item =~ /^-?\d+$/ ? 0 + $item : $item ); | ||
| 446 | } | ||
| 447 | if ( keys %hash ) { | ||
| 448 | my $json = eval { JSON::PP->new->utf8(0)->canonical(1)->encode(\%hash) }; | ||
| 449 | if ( defined $json ) { | ||
| 450 | $json =~ s/\r?\n/ /g; | ||
| 451 | return $json; | ||
| 452 | } | ||
| 453 | } | ||
| 454 | } | ||
| 455 | return "$val"; | ||
| 456 | } | ||
| 457 | |||
| 458 | sub format_tsv_cell { | ||
| 459 | my ($val) = @_; | ||
| 460 | my $cell = format_cell($val); | ||
| 461 | $cell =~ s/\t/ /g; | ||
| 462 | $cell =~ s/\r?\n/ /g; | ||
| 463 | return $cell; | ||
| 464 | } | ||
| 465 | |||
| 466 | sub render_table_box { | ||
| 467 | my ( $headers, $rows ) = @_; | ||
| 468 | return unless @$headers; | ||
| 469 | |||
| 470 | # 1. Calculate max widths | ||
| 471 | my @widths = map { length($_) } @$headers; | ||
| 472 | for my $row (@$rows) { | ||
| 473 | for my $i ( 0 .. $#$headers ) { | ||
| 474 | my $cell = format_cell( $row->[$i] ); | ||
| 475 | $widths[$i] = length($cell) if length($cell) > $widths[$i]; | ||
| 476 | } | ||
| 477 | } | ||
| 478 | |||
| 479 | # 2. Border lines | ||
| 480 | my $sep_line = "+" . join( "+", map { "-" x ( $_ + 2 ) } @widths ) . "+"; | ||
| 481 | |||
| 482 | # 3. Print header | ||
| 483 | print $sep_line, "\n"; | ||
| 484 | print "|"; | ||
| 485 | for my $i ( 0 .. $#$headers ) { | ||
| 486 | printf( " %-${widths[$i]}s |", $headers->[$i] ); | ||
| 487 | } | ||
| 488 | print "\n"; | ||
| 489 | print $sep_line, "\n"; | ||
| 490 | |||
| 491 | # 4. Print rows | ||
| 492 | for my $row (@$rows) { | ||
| 493 | print "|"; | ||
| 494 | for my $i ( 0 .. $#$headers ) { | ||
| 495 | my $cell = format_cell( $row->[$i] ); | ||
| 496 | printf( " %-${widths[$i]}s |", $cell ); | ||
| 497 | } | ||
| 498 | print "\n"; | ||
| 499 | } | ||
| 500 | print $sep_line, "\n"; | ||
| 501 | } | ||
| 502 | |||
| 503 | our $current_table; | ||
| 504 | |||
| 505 | sub render_records_table { | ||
| 506 | my ( $recs, $table ) = @_; | ||
| 507 | return unless $recs && ref $recs eq 'ARRAY' && @$recs; | ||
| 508 | |||
| 509 | # Case 1: Pure hashes (e.g. inflated records from inflate=1: [ { id => 1, ... } ]) | ||
| 510 | if ( ref $recs->[0] eq 'HASH' ) { | ||
| 511 | my %seen_keys; | ||
| 512 | for my $r (@$recs) { | ||
| 513 | next unless ref $r eq 'HASH'; | ||
| 514 | for my $k ( keys %$r ) { | ||
| 515 | $seen_keys{$k} = 1 unless $k eq 'id'; | ||
| 516 | } | ||
| 517 | } | ||
| 518 | my @headers = ( ( grep { ref $_ eq 'HASH' && exists $_->{id} } @$recs ) ? ('id') : (), sort keys %seen_keys ); | ||
| 519 | my @rows; | ||
| 520 | for my $r (@$recs) { | ||
| 521 | push @rows, [ map { ref $r eq 'HASH' ? $r->{$_} : undef } @headers ]; | ||
| 522 | } | ||
| 523 | render_table_box( \@headers, \@rows ); | ||
| 524 | return; | ||
| 525 | } | ||
| 526 | |||
| 527 | # Case 2: Block-aligned records: [ [ id, block_1, block_2, ... ], ... ] | ||
| 528 | my @schema_blocks; | ||
| 529 | if ( defined $table && length $table && defined $adb ) { | ||
| 530 | my $info = eval { $adb->table_info($table) }; | ||
| 531 | if ( $info && ref $info eq 'HASH' && $info->{blocks} ) { | ||
| 532 | if ( ref $info->{blocks} eq 'ARRAY' ) { | ||
| 533 | for my $i ( 0 .. $#{ $info->{blocks} } ) { | ||
| 534 | my $b = $info->{blocks}->[$i]; | ||
| 535 | my $bname = ref $b eq 'HASH' ? ( $b->{name} // $b->{id} ) : $b; | ||
| 536 | push @schema_blocks, $bname if defined $bname && length $bname; | ||
| 537 | } | ||
| 538 | } | ||
| 539 | elsif ( ref $info->{blocks} eq 'HASH' ) { | ||
| 540 | for my $k ( sort { $a <=> $b } keys %{ $info->{blocks} } ) { | ||
| 541 | my $b = $info->{blocks}->{$k}; | ||
| 542 | my $bname = ref $b eq 'HASH' ? ( $b->{name} // $b->{id} ) : $b; | ||
| 543 | push @schema_blocks, $bname if defined $bname && length $bname; | ||
| 544 | } | ||
| 545 | } | ||
| 546 | } | ||
| 547 | } | ||
| 548 | |||
| 549 | my $max_cols = 0; | ||
| 550 | for my $r (@$recs) { | ||
| 551 | my $cnt = ref $r eq 'ARRAY' ? scalar(@$r) : 1; | ||
| 552 | $max_cols = $cnt if $cnt > $max_cols; | ||
| 553 | } | ||
| 554 | |||
| 555 | my @headers; | ||
| 556 | my $has_schema = @schema_blocks ? 1 : 0; | ||
| 557 | my $schema_has_id_at_0 = 0; | ||
| 558 | if ( $has_schema && defined $schema_blocks[0] && $schema_blocks[0] =~ /^(?:id|ID)$/i ) { | ||
| 559 | $schema_has_id_at_0 = 1; | ||
| 560 | } | ||
| 561 | |||
| 562 | for my $c ( 0 .. ( $max_cols - 1 ) ) { | ||
| 563 | if ( $c == 0 ) { | ||
| 564 | if ($has_schema) { | ||
| 565 | push @headers, $schema_has_id_at_0 ? $schema_blocks[0] : 'id'; | ||
| 566 | } | ||
| 567 | else { | ||
| 568 | push @headers, '0'; | ||
| 569 | } | ||
| 570 | } | ||
| 571 | else { | ||
| 572 | if ($has_schema) { | ||
| 573 | my $s_idx = $schema_has_id_at_0 ? $c : ( $c - 1 ); | ||
| 574 | my $name = $schema_blocks[$s_idx] // "$c"; | ||
| 575 | push @headers, $name; | ||
| 576 | } | ||
| 577 | else { | ||
| 578 | push @headers, "$c"; | ||
| 579 | } | ||
| 580 | } | ||
| 581 | } | ||
| 582 | |||
| 583 | my @rows; | ||
| 584 | for my $r (@$recs) { | ||
| 585 | my @row; | ||
| 586 | if ( ref $r eq 'ARRAY' ) { | ||
| 587 | @row = @$r; | ||
| 588 | while ( @row < $max_cols ) { | ||
| 589 | push @row, undef; | ||
| 590 | } | ||
| 591 | } | ||
| 592 | else { | ||
| 593 | @row = ($r); | ||
| 594 | } | ||
| 595 | push @rows, \@row; | ||
| 596 | } | ||
| 597 | render_table_box( \@headers, \@rows ); | ||
| 598 | } | ||
| 599 | |||
| 600 | sub output_result { | ||
| 601 | my ( $data, $format, $table ) = @_; | ||
| 602 | $format = lc( $format // '' ); | ||
| 603 | $table //= $current_table; | ||
| 604 | |||
| 605 | if ( $format eq 'json' ) { | ||
| 606 | print encode_json($data), "\n"; | ||
| 607 | return; | ||
| 608 | } | ||
| 609 | elsif ( $format eq 'pretty' ) { | ||
| 610 | print JSON::PP->new->ascii->pretty->canonical->encode($data); | ||
| 611 | return; | ||
| 612 | } | ||
| 613 | elsif ( $format eq 'raw' || $format eq 'dumper' || $format eq 'perl' ) { | ||
| 614 | print Dumper($data); | ||
| 615 | return; | ||
| 616 | } | ||
| 617 | elsif ( $format eq 'tsv' ) { | ||
| 618 | if ( ref $data eq 'HASH' ) { | ||
| 619 | if ( exists $data->{count} && exists $data->{records} && ref $data->{records} eq 'ARRAY' ) { | ||
| 620 | my $recs = $data->{records}; | ||
| 621 | if ( @$recs && ref $recs->[0] eq 'HASH' ) { | ||
| 622 | my @cols = sort keys %{ $recs->[0] }; | ||
| 623 | print join( "\t", @cols ), "\n"; | ||
| 624 | for my $row (@$recs) { | ||
| 625 | print join( "\t", map { format_tsv_cell( $row->{$_} ) } @cols ), "\n"; | ||
| 626 | } | ||
| 627 | } | ||
| 628 | else { | ||
| 629 | for my $row (@$recs) { | ||
| 630 | my @fields = ref $row eq 'ARRAY' ? @$row : ($row); | ||
| 631 | print join( "\t", map { format_tsv_cell($_) } @fields ), "\n"; | ||
| 632 | } | ||
| 633 | } | ||
| 634 | return; | ||
| 635 | } | ||
| 636 | |||
| 637 | for my $k ( sort keys %$data ) { | ||
| 638 | my $v = $data->{$k}; | ||
| 639 | print "$k\t" . format_tsv_cell($v) . "\n"; | ||
| 640 | } | ||
| 641 | return; | ||
| 642 | } | ||
| 643 | |||
| 644 | if ( ref $data eq 'ARRAY' ) { | ||
| 645 | if ( !@$data ) { | ||
| 646 | return; | ||
| 647 | } | ||
| 648 | if ( ref $data->[0] eq 'HASH' ) { | ||
| 649 | my @cols = sort keys %{ $data->[0] }; | ||
| 650 | print join( "\t", @cols ), "\n"; | ||
| 651 | for my $row (@$data) { | ||
| 652 | print join( "\t", map { format_tsv_cell( $row->{$_} ) } @cols ), "\n"; | ||
| 653 | } | ||
| 654 | } | ||
| 655 | elsif ( ref $data->[0] eq 'ARRAY' ) { | ||
| 656 | # List of array records | ||
| 657 | for my $row (@$data) { | ||
| 658 | print join( "\t", map { format_tsv_cell($_) } @$row ), "\n"; | ||
| 659 | } | ||
| 660 | } | ||
| 661 | else { | ||
| 662 | # Single record: [ $id, $field_1, $field_2, ... ] | ||
| 663 | print join( "\t", map { format_tsv_cell($_) } @$data ), "\n"; | ||
| 664 | } | ||
| 665 | return; | ||
| 666 | } | ||
| 667 | |||
| 668 | print( ( defined $data ? format_tsv_cell($data) : "" ), "\n" ); | ||
| 669 | return; | ||
| 670 | } | ||
| 671 | |||
| 672 | # Default / Table view | ||
| 673 | if ( !ref $data ) { | ||
| 674 | print( ( $data // "" ), "\n" ); | ||
| 675 | return; | ||
| 676 | } | ||
| 677 | |||
| 678 | if ( ref $data eq 'HASH' ) { | ||
| 679 | if ( exists $data->{count} && exists $data->{records} && ref $data->{records} eq 'ARRAY' ) { | ||
| 680 | print "[Found " . $data->{count} . " record(s)]\n"; | ||
| 681 | my $recs = $data->{records}; | ||
| 682 | if ( @$recs ) { | ||
| 683 | render_records_table( $recs, $table ); | ||
| 684 | } | ||
| 685 | return; | ||
| 686 | } | ||
| 687 | |||
| 688 | # Single record hash (e.g. from read_id with inflate=1) | ||
| 689 | if ( exists $data->{id} && !exists $data->{status} && !exists $data->{action} ) { | ||
| 690 | render_records_table( [ $data ], $table ); | ||
| 691 | return; | ||
| 692 | } | ||
| 693 | |||
| 694 | # Simple Key-Value Hash Display | ||
| 695 | my $max_k = 10; | ||
| 696 | for my $k ( keys %$data ) { | ||
| 697 | $max_k = length($k) if length($k) > $max_k; | ||
| 698 | } | ||
| 699 | print "-" x ( $max_k + 40 ), "\n"; | ||
| 700 | for my $k ( sort keys %$data ) { | ||
| 701 | my $v = $data->{$k}; | ||
| 702 | my $v_str = ref $v ? encode_json($v) : ( $v // "" ); | ||
| 703 | printf( "%-${max_k}s : %s\n", $k, $v_str ); | ||
| 704 | } | ||
| 705 | print "-" x ( $max_k + 40 ), "\n"; | ||
| 706 | return; | ||
| 707 | } | ||
| 708 | |||
| 709 | if ( ref $data eq 'ARRAY' ) { | ||
| 710 | if ( !@$data ) { | ||
| 711 | print "[0 records]\n"; | ||
| 712 | return; | ||
| 713 | } | ||
| 714 | if ( ref $data->[0] ) { | ||
| 715 | # List of records: [ [ ... ], [ ... ] ] or [ { ... }, { ... } ] | ||
| 716 | render_records_table( $data, $table ); | ||
| 717 | } | ||
| 718 | else { | ||
| 719 | # Single record: [ $id, ... ] or [ $id, \%hash ] | ||
| 720 | render_records_table( [ $data ], $table ); | ||
| 721 | } | ||
| 722 | return; | ||
| 723 | } | ||
| 724 | |||
| 725 | print Dumper($data); | ||
| 726 | } | ||
| 727 | |||
| 728 | # ============================================================================ | ||
| 729 | # CLI ARGUMENT PARSER (DASH-TOLERANT: --key=val, -key=val, key=val) | ||
| 730 | # ============================================================================ | ||
| 731 | |||
| 732 | my $opt_action; | ||
| 733 | my $opt_token; | ||
| 734 | my $opt_format; | ||
| 735 | our $opt_time = 0; | ||
| 736 | my $opt_dry_run = 0; | ||
| 737 | my $opt_force = 0; | ||
| 738 | our $opt_help = 0; | ||
| 739 | our $opt_help_lang; | ||
| 740 | my $opt_database; | ||
| 741 | my $opt_user; | ||
| 742 | my $opt_pass; | ||
| 743 | |||
| 744 | my %method_args; | ||
| 745 | my @pos_args; | ||
| 746 | |||
| 747 | # Step 1: Pre-pass for space-separated flags (--db <val>, -d <val>, --token <val>, etc.) | ||
| 748 | my @raw_tokens; | ||
| 749 | my $arg_idx = 0; | ||
| 750 | while ( $arg_idx < @ARGV ) { | ||
| 751 | my $curr = $ARGV[$arg_idx]; | ||
| 752 | if ( $curr =~ /^--(?:db|dbase|dbase_dir)=(.*)$/i ) { | ||
| 753 | my $val = eval { abs_path($1) } // $1; | ||
| 754 | $adb->set_datadir($val); | ||
| 755 | $explicit_db = 1; | ||
| 756 | $has_path_updates = 1; | ||
| 757 | } | ||
| 758 | elsif ( $curr =~ /^(?:path-dbase_dir|db)=(.*)$/i ) { | ||
| 759 | my $val = eval { abs_path($1) } // $1; | ||
| 760 | $adb->set_datadir($val); | ||
| 761 | $explicit_db = 1; | ||
| 762 | $has_path_updates = 1; | ||
| 763 | } | ||
| 764 | elsif ( ( $curr =~ /^--(?:db|dbase|dbase_dir)$/i || $curr =~ /^-d$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 765 | my $val = $ARGV[++$arg_idx]; | ||
| 766 | $val = eval { abs_path($val) } // $val; | ||
| 767 | $adb->set_datadir($val); | ||
| 768 | $explicit_db = 1; | ||
| 769 | $has_path_updates = 1; | ||
| 770 | } | ||
| 771 | elsif ( $curr =~ /^(?:--?)?token=(.*)$/i ) { | ||
| 772 | $opt_token = $1; | ||
| 773 | } | ||
| 774 | elsif ( ( $curr =~ /^--(?:token)$/i || $curr =~ /^-k$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 775 | $opt_token = $ARGV[++$arg_idx]; | ||
| 776 | } | ||
| 777 | elsif ( ( $curr =~ /^--(?:user|username)$/i || $curr =~ /^-u$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 778 | $opt_user = $ARGV[++$arg_idx]; | ||
| 779 | } | ||
| 780 | elsif ( ( $curr =~ /^--(?:pass|password|passwd)$/i || $curr =~ /^-p$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 781 | $opt_pass = $ARGV[++$arg_idx]; | ||
| 782 | } | ||
| 783 | elsif ( ( $curr =~ /^--(?:format)$/i || $curr =~ /^-f$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 784 | $opt_format = lc($ARGV[++$arg_idx]); | ||
| 785 | } | ||
| 786 | elsif ( ( $curr =~ /^--(?:limit)$/i || $curr =~ /^-l$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 787 | $method_args{limit} = parse_value($ARGV[++$arg_idx]); | ||
| 788 | } | ||
| 789 | elsif ( ( $curr =~ /^--(?:offset)$/i || $curr =~ /^-o$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 790 | $method_args{offset} = parse_value($ARGV[++$arg_idx]); | ||
| 791 | } | ||
| 792 | elsif ( ( $curr =~ /^--(?:dir)$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 793 | $method_args{dir} = lc($ARGV[++$arg_idx]); | ||
| 794 | } | ||
| 795 | elsif ( ( $curr =~ /^--(?:data)$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) { | ||
| 796 | $method_args{data} = parse_value($ARGV[++$arg_idx]); | ||
| 797 | } | ||
| 798 | elsif ( $curr =~ /^--(?:time)$/i ) { | ||
| 799 | $opt_time = 1; | ||
| 800 | } | ||
| 801 | elsif ( $curr =~ /^--(?:version)$/i || $curr =~ /^-v$/i ) { | ||
| 802 | $opt_action = 'version'; | ||
| 803 | } | ||
| 804 | else { | ||
| 805 | push @raw_tokens, $curr; | ||
| 806 | } | ||
| 807 | $arg_idx++; | ||
| 808 | } | ||
| 809 | |||
| 810 | # Step 2: Known action definitions | ||
| 811 | my %known_actions = map { $_ => 1 } qw( | ||
| 812 | setup install ramdisk | ||
| 813 | connect disconnect path config cfg attr table_attr user users | ||
| 814 | status tables list info table_info read read_id read_all read_list | ||
| 815 | search search_table fetch field_fetch count table_count | ||
| 816 | insert insert_id update update_id delete delete_id | ||
| 817 | reindex check vacuum migrate update_table update_storage update_version | ||
| 818 | export tie2csv import csv2tie dump restore rename drop help usage | ||
| 819 | help.tr usage.tr help.en usage.en version | ||
| 820 | ); | ||
| 821 | |||
| 822 | # Step 3: Check if first token is a session token (e.g. 1245 or existing session file) | ||
| 823 | if ( !defined $opt_token && @raw_tokens ) { | ||
| 824 | my $first = $raw_tokens[0]; | ||
| 825 | my $clean_first = $first; | ||
| 826 | $clean_first =~ s/^--?//; | ||
| 827 | if ( $clean_first !~ /=/ && !$known_actions{ lc($clean_first) } ) { | ||
| 828 | if ( $clean_first =~ /^[a-zA-Z0-9]{4,8}$/ && @raw_tokens > 1 ) { | ||
| 829 | $opt_token = shift @raw_tokens; | ||
| 830 | $opt_token =~ s/^--?//; | ||
| 831 | } | ||
| 832 | } | ||
| 833 | } | ||
| 834 | |||
| 835 | # Step 4: Extract trailing format and time keywords if provided as standalone keywords | ||
| 836 | for ( 1 .. 2 ) { | ||
| 837 | last unless @raw_tokens > 1; | ||
| 838 | my $last = $raw_tokens[-1]; | ||
| 839 | if ( !defined $opt_format && $last =~ /^(?:json|pretty|tsv|dumper|perl|raw|table)$/i && $last !~ /=/ ) { | ||
| 840 | $opt_format = lc( pop @raw_tokens ); | ||
| 841 | } | ||
| 842 | elsif ( !$opt_time && $last =~ /^time$/i ) { | ||
| 843 | my $act_candidate = lc( $raw_tokens[0] // '' ); | ||
| 844 | if ( @raw_tokens == 3 && ( $act_candidate eq 'search' || $act_candidate eq 'search_table' ) ) { | ||
| 845 | last; | ||
| 846 | } | ||
| 847 | $opt_time = 1; | ||
| 848 | pop @raw_tokens; | ||
| 849 | } | ||
| 850 | else { | ||
| 851 | last; | ||
| 852 | } | ||
| 853 | } | ||
| 854 | |||
| 855 | # Step 4b: Active session resolution & baseline state restoration | ||
| 856 | my $is_connect_cmd = 0; | ||
| 857 | for my $t (@raw_tokens) { | ||
| 858 | if ( $t =~ /^--?(?:action=)?connect$/i ) { | ||
| 859 | $is_connect_cmd = 1; | ||
| 860 | last; | ||
| 861 | } | ||
| 862 | } | ||
| 863 | my $is_session_cmd = 0; | ||
| 864 | for my $t (@raw_tokens) { | ||
| 865 | if ( $t =~ /^--?(?:action=)?(connect|disconnect|config|path|attr|cfg|table_attr|user|users)$/i ) { | ||
| 866 | $is_session_cmd = 1; | ||
| 867 | last; | ||
| 868 | } | ||
| 869 | } | ||
| 870 | |||
| 871 | if ( !defined $opt_token ) { | ||
| 872 | for my $t (@raw_tokens) { | ||
| 873 | if ( $t =~ /^(?:--?)?token=(.*)$/i ) { | ||
| 874 | $opt_token = $1; | ||
| 875 | last; | ||
| 876 | } | ||
| 877 | } | ||
| 878 | } | ||
| 879 | |||
| 880 | my $active_token; | ||
| 881 | my $session; | ||
| 882 | unless ($is_connect_cmd) { | ||
| 883 | $active_token = resolve_active_token( $opt_token, $is_session_cmd || !@raw_tokens ); | ||
| 884 | $session = $active_token ? load_session($active_token) : undef; | ||
| 885 | |||
| 886 | if ( defined $opt_token && !$session ) { | ||
| 887 | die "[AMBERDB_ERROR] Invalid or expired session token '$opt_token'.\n"; | ||
| 888 | } | ||
| 889 | |||
| 890 | if ($session) { | ||
| 891 | eval { $adb->connect( token => $active_token ) }; | ||
| 892 | if ( $session->{path}->{dbase_dir} && !$explicit_db ) { | ||
| 893 | $adb->set_datadir( $session->{path}->{dbase_dir} ); | ||
| 894 | } | ||
| 895 | $adb->path( $session->{path} ) if $session->{path}; | ||
| 896 | $adb->config( $session->{cfg} ) if $session->{cfg}; | ||
| 897 | if ( $session->{table_attrs} ) { | ||
| 898 | for my $tbl ( keys %{ $session->{table_attrs} } ) { | ||
| 899 | $adb->table_attr( $tbl, $session->{table_attrs}->{$tbl} ); | ||
| 900 | } | ||
| 901 | } | ||
| 902 | } | ||
| 903 | } | ||
| 904 | |||
| 905 | # Step 5: Process remaining tokens | ||
| 906 | for my $raw (@raw_tokens) { | ||
| 907 | my $arg = $raw; | ||
| 908 | $arg =~ s/^--?//; | ||
| 909 | |||
| 910 | if ( $arg =~ /^([^=]+)=(.*)$/s ) { | ||
| 911 | my ( $k, $v ) = ( $1, $2 ); | ||
| 912 | my $val = parse_value($v); | ||
| 913 | |||
| 914 | if ( $k eq 'action' ) { | ||
| 915 | $opt_action = $v; | ||
| 916 | } | ||
| 917 | elsif ( $k eq 'token' ) { | ||
| 918 | $opt_token = $v; | ||
| 919 | } | ||
| 920 | elsif ( $k eq 'format' ) { | ||
| 921 | $opt_format = lc($v); | ||
| 922 | } | ||
| 923 | elsif ( $k eq 'time' ) { | ||
| 924 | $opt_time = $val ? 1 : 0; | ||
| 925 | } | ||
| 926 | elsif ( $k =~ /^(?:dry-run|dry_run)$/ ) { | ||
| 927 | $opt_dry_run = $val ? 1 : 0; | ||
| 928 | } | ||
| 929 | elsif ( $k =~ /^(?:force|f)$/ ) { | ||
| 930 | $opt_force = $val ? 1 : 0; | ||
| 931 | } | ||
| 932 | elsif ( $k =~ /^(?:check|c)$/i ) { | ||
| 933 | $method_args{check} = $val ? 1 : 0; | ||
| 934 | } | ||
| 935 | elsif ( $k =~ /^(?:all|a)$/i ) { | ||
| 936 | $method_args{all} = $val ? 1 : 0; | ||
| 937 | } | ||
| 938 | elsif ( $k =~ /^(?:no-backup|no_backup)$/i ) { | ||
| 939 | $method_args{no_backup} = $val ? 1 : 0; | ||
| 940 | } | ||
| 941 | elsif ( $k eq 'cpanm' ) { | ||
| 942 | $method_args{cpanm} = $v; | ||
| 943 | } | ||
| 944 | elsif ( $k eq 'manifest' ) { | ||
| 945 | $method_args{manifest} = $v; | ||
| 946 | } | ||
| 947 | elsif ( $k =~ /^(?:help|h|usage)$/i ) { | ||
| 948 | $opt_help = 1; | ||
| 949 | if ( defined $v && $v =~ /^(?:tr|en)$/i ) { | ||
| 950 | $opt_help_lang = lc($v); | ||
| 951 | } | ||
| 952 | } | ||
| 953 | elsif ( $k =~ /^(?:help|usage)\.(tr|en)$/i ) { | ||
| 954 | $opt_help = 1; | ||
| 955 | $opt_help_lang = lc($1); | ||
| 956 | } | ||
| 957 | elsif ( $k =~ /^cfg-(.+)$/ ) { | ||
| 958 | $adb->config( $1 => $val ); | ||
| 959 | $has_cfg_updates = 1; | ||
| 960 | } | ||
| 961 | elsif ( $k =~ /^path-(.+)$/ ) { | ||
| 962 | my $pkey = $1; | ||
| 963 | if ( $pkey eq 'dbase_dir' || $pkey eq 'db' || $pkey eq 'dbase' ) { | ||
| 964 | my $abs = eval { abs_path($val) } // $val; | ||
| 965 | $adb->set_datadir($abs); | ||
| 966 | $explicit_db = 1; | ||
| 967 | } | ||
| 968 | else { | ||
| 969 | $adb->path( $pkey => $val ); | ||
| 970 | } | ||
| 971 | $has_path_updates = 1; | ||
| 972 | } | ||
| 973 | elsif ( $k eq 'no_write' ) { | ||
| 974 | $adb->config( no_write => $val ); | ||
| 975 | $has_cfg_updates = 1; | ||
| 976 | } | ||
| 977 | elsif ( $k eq 'db' || $k eq 'dbase_dir' || $k eq 'dbase' ) { | ||
| 978 | my $abs = eval { abs_path($val) } // $val; | ||
| 979 | $adb->set_datadir($abs); | ||
| 980 | $explicit_db = 1; | ||
| 981 | $has_path_updates = 1; | ||
| 982 | } | ||
| 983 | elsif ( $k eq 'data' ) { | ||
| 984 | $method_args{data} = $val; | ||
| 985 | } | ||
| 986 | elsif ( $k eq 'user' || $k eq 'username' ) { | ||
| 987 | $opt_user = $val; | ||
| 988 | } | ||
| 989 | elsif ( $k eq 'pass' || $k eq 'password' || $k eq 'passwd' ) { | ||
| 990 | $opt_pass = $val; | ||
| 991 | } | ||
| 992 | elsif ( $k eq 'database' || $k eq 'dbname' ) { | ||
| 993 | $opt_database = $val; | ||
| 994 | $adb->{_connect}->{database} = $val; | ||
| 995 | $adb->clear_cache('ramdisk'); | ||
| 996 | $adb->ramdisk_setup(); | ||
| 997 | } | ||
| 998 | else { | ||
| 999 | if ( $k =~ /[-.]/ ) { | ||
| 1000 | my @parts = split /[-.]/, $k; | ||
| 1001 | set_nested_key( \%method_args, \@parts, $val ); | ||
| 1002 | } | ||
| 1003 | else { | ||
| 1004 | $method_args{$k} = $val; | ||
| 1005 | } | ||
| 1006 | } | ||
| 1007 | } | ||
| 1008 | else { | ||
| 1009 | if ( $arg =~ /^(?:help|h|usage)$/i ) { | ||
| 1010 | $opt_help = 1; | ||
| 1011 | $opt_action //= 'help'; | ||
| 1012 | } | ||
| 1013 | elsif ( $arg =~ /^(?:help|usage)\.(tr|en)$/i ) { | ||
| 1014 | $opt_help = 1; | ||
| 1015 | $opt_help_lang = lc($1); | ||
| 1016 | $opt_action //= 'help'; | ||
| 1017 | } | ||
| 1018 | elsif ( $arg =~ /^(?:dry-run|dry_run)$/i ) { | ||
| 1019 | $opt_dry_run = 1; | ||
| 1020 | } | ||
| 1021 | elsif ( $arg =~ /^(?:force|f)$/i ) { | ||
| 1022 | $opt_force = 1; | ||
| 1023 | } | ||
| 1024 | elsif ( $raw =~ /^--?(?:check|c)$/i ) { | ||
| 1025 | $method_args{check} = 1; | ||
| 1026 | } | ||
| 1027 | elsif ( $raw =~ /^--?(?:all|a)$/i ) { | ||
| 1028 | $method_args{all} = 1; | ||
| 1029 | } | ||
| 1030 | elsif ( $raw =~ /^--?(?:no-backup|no_backup)$/i ) { | ||
| 1031 | $method_args{no_backup} = 1; | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | elsif ( $raw =~ /^--?time$/i ) { | ||
| 1035 | $opt_time = 1; | ||
| 1036 | } | ||
| 1037 | elsif ( !defined $opt_action ) { | ||
| 1038 | $opt_action = $arg; | ||
| 1039 | } | ||
| 1040 | else { | ||
| 1041 | push @pos_args, $arg; | ||
| 1042 | } | ||
| 1043 | } | ||
| 1044 | } | ||
| 1045 | |||
| 1046 | # Step 6: Action alias normalization | ||
| 1047 | if ( defined $opt_action ) { | ||
| 1048 | my $act = lc($opt_action); | ||
| 1049 | if ( $act =~ /^(?:help|usage)(?:\.(tr|en))?$/i ) { | ||
| 1050 | $opt_help = 1; | ||
| 1051 | $opt_help_lang = lc($1) if defined $1; | ||
| 1052 | $opt_action = 'help'; | ||
| 1053 | } | ||
| 1054 | $opt_action = 'setup' if $act eq 'setup' || $act eq 'install'; | ||
| 1055 | $opt_action = 'status' if $act eq 'tables' || $act eq 'list'; | ||
| 1056 | $opt_action = 'user' if $act eq 'users'; | ||
| 1057 | $opt_action = 'config' if $act eq 'cfg'; | ||
| 1058 | $opt_action = 'attr' if $act eq 'table_attr'; | ||
| 1059 | $opt_action = 'info' if $act eq 'table_info'; | ||
| 1060 | $opt_action = 'search' if $act eq 'search_table'; | ||
| 1061 | $opt_action = 'fetch' if $act eq 'field_fetch'; | ||
| 1062 | $opt_action = 'count' if $act eq 'table_count'; | ||
| 1063 | $opt_action = 'insert' if $act eq 'insert_id'; | ||
| 1064 | $opt_action = 'update' if $act eq 'update_id'; | ||
| 1065 | $opt_action = 'delete' if $act eq 'delete_id'; | ||
| 1066 | $opt_action = 'migrate' if $act eq 'update_table'; | ||
| 1067 | $opt_action = 'update_storage' if $act eq 'update-storage' || $act eq 'updatedb' || $act eq 'update_storage'; | ||
| 1068 | $opt_action = 'update_version' if $act eq 'update-amberdb' || $act eq 'update-version' || $act eq 'update_version'; | ||
| 1069 | $opt_action = 'export' if $act eq 'tie2csv'; | ||
| 1070 | $opt_action = 'import' if $act eq 'csv2tie'; | ||
| 1071 | $opt_action = 'reindex' if $act eq 'set_index'; | ||
| 1072 | $opt_action = 'vacuum' if $act eq 'vacuum'; | ||
| 1073 | } | ||
| 1074 | |||
| 1075 | # Step 6b: Subcommand resolution for 'update' (e.g. amberdb update storage / amberdb update version) | ||
| 1076 | if ( defined $opt_action && $opt_action eq 'update' && @pos_args ) { | ||
| 1077 | if ( lc($pos_args[0]) eq 'storage' ) { | ||
| 1078 | $opt_action = 'update_storage'; | ||
| 1079 | shift @pos_args; | ||
| 1080 | } | ||
| 1081 | elsif ( lc($pos_args[0]) eq 'version' || lc($pos_args[0]) eq 'engine' || lc($pos_args[0]) eq 'amberdb' ) { | ||
| 1082 | $opt_action = 'update_version'; | ||
| 1083 | shift @pos_args; | ||
| 1084 | } | ||
| 1085 | } | ||
| 1086 | |||
| 1087 | # Step 7: Natural 'read' command resolution | ||
| 1088 | if ( defined $opt_action && $opt_action eq 'read' ) { | ||
| 1089 | my $tbl = delete $method_args{table} // shift @pos_args; | ||
| 1090 | $method_args{table} = $tbl; | ||
| 1091 | |||
| 1092 | my $mode = shift @pos_args; | ||
| 1093 | if ( !defined $mode || $mode eq 'all' ) { | ||
| 1094 | $opt_action = 'read_all'; | ||
| 1095 | my $offset = shift @pos_args; | ||
| 1096 | my $limit = shift @pos_args; | ||
| 1097 | $method_args{offset} = parse_value($offset) if defined $offset; | ||
| 1098 | $method_args{limit} = parse_value($limit) if defined $limit; | ||
| 1099 | } | ||
| 1100 | elsif ( $mode =~ /,/ ) { | ||
| 1101 | $opt_action = 'read_list'; | ||
| 1102 | $method_args{ids} = [ split /,/, $mode ]; | ||
| 1103 | } | ||
| 1104 | elsif ( $mode =~ /^-?\d+$/ ) { | ||
| 1105 | if ( @pos_args && $pos_args[0] =~ /^-?\d+$/ ) { | ||
| 1106 | $opt_action = 'read_list'; | ||
| 1107 | $method_args{ids} = [ parse_value($mode), map { parse_value($_) } @pos_args ]; | ||
| 1108 | @pos_args = (); | ||
| 1109 | } | ||
| 1110 | else { | ||
| 1111 | $opt_action = 'read_id'; | ||
| 1112 | $method_args{id} = parse_value($mode); | ||
| 1113 | } | ||
| 1114 | } | ||
| 1115 | else { | ||
| 1116 | $opt_action = 'read_id'; | ||
| 1117 | $method_args{id} = $mode; | ||
| 1118 | } | ||
| 1119 | } | ||
| 1120 | |||
| 1121 | # ============================================================================ | ||
| 1122 | # USAGE / HELP SCREEN | ||
| 1123 | # ============================================================================ | ||
| 1124 | |||
| 1125 | sub show_usage { | ||
| 1126 | my ($lang) = @_; | ||
| 1127 | $lang = lc( $lang // 'en' ); | ||
| 1128 | |||
| 1129 | if ( $lang eq 'tr' ) { | ||
| 1130 | print <<"USAGE_TR"; | ||
| 1131 | AmberDB CLI v$AmberDB::VERSION - Gömülü Veritabanı Konsolu ve Yönetim Aracı | ||
| 1132 | |||
| 1133 | Kullanım: | ||
| 1134 | amberdb [eylem|token] [tablo] [parametreler...] | ||
| 1135 | |||
| 1136 | Kullanım Biçimleri: | ||
| 1137 | |||
| 1138 | 1. Doğrudan Yerel Kullanım (Varsayılan - Yerel ./dbstore): | ||
| 1139 | amberdb tables # Bulunulan dizindeki ./dbstore tablolarını listeler | ||
| 1140 | amberdb read products 10 # ID ile tekil kayıt okuma | ||
| 1141 | amberdb read products 10 inflate=1 json # Şema genişletmeli JSON okuma | ||
| 1142 | amberdb search products "kulaklık" limit=10 # Tam metin ve fonetik arama | ||
| 1143 | amberdb insert users 0 data='{"name":"Ali"}'# Kayıt ekler (yoksa ./dbstore oluşturur) | ||
| 1144 | amberdb update users 10 data='{"role":"admin"}' | ||
| 1145 | amberdb delete users 10 | ||
| 1146 | |||
| 1147 | 2. İsimlendirilmiş Oturum (Session Management): | ||
| 1148 | amberdb connect <database> # ~/.amberdb/<database> havuzuna bağlanır | ||
| 1149 | amberdb connect <database>\@<path> # Özel bir klasöre bağlanır (örn: mydb\@./dbstore) | ||
| 1150 | amberdb 1245 tables # 1245 nolu oturumun tablolarını listeler | ||
| 1151 | amberdb 1245 read products 10 # 1245 nolu oturumda okuma yapar | ||
| 1152 | amberdb 1245 disconnect # Oturumu sonlandırır | ||
| 1153 | |||
| 1154 | 3. Altyapı ve Kurulum: | ||
| 1155 | amberdb setup # ~/.amberdb global çalışma alanını kurar | ||
| 1156 | amberdb setup [dir] # Özel bir dizinde veritabanı iskeleti kurar | ||
| 1157 | amberdb setup ramdisk [start|stop|status] # RAM-disk sürücü yönetimi | ||
| 1158 | |||
| 1159 | Bakım ve Yönetim Eylemleri: | ||
| 1160 | amberdb update storage [--check] [--force] # Dizin & ABR v5 veri biçimi migrasyonu | ||
| 1161 | amberdb update version [--check] # MetaCPAN çekirdek sürüm kontrolü / güncelleme | ||
| 1162 | amberdb reindex products # İndeksleri sıfırdan oluştur | ||
| 1163 | amberdb check products # Fiziksel dosya bütünlük kontrolü | ||
| 1164 | amberdb vacuum products # BDB disk boşluklarını temizle | ||
| 1165 | amberdb migrate products # Şema güncellemesi | ||
| 1166 | amberdb export products file=yedek.csv # CSV dışa aktarımı | ||
| 1167 | amberdb import products file=yeni.csv # CSV içe aktarımı | ||
| 1168 | amberdb dump products file=yedek.tar.gz # Veritabanı yedeği al | ||
| 1169 | amberdb restore file=yedek.tar.gz # Yedekten geri yükle | ||
| 1170 | amberdb rename from=eski to=yeni # Tablo adı değiştir | ||
| 1171 | amberdb drop temp_tbl force=1 # Tabloyu kalıcı olarak sil | ||
| 1172 | |||
| 1173 | Genel Seçenekler: | ||
| 1174 | --format=table|json|pretty|tsv|dumper Çıktı biçimi (Varsayılan: table. Veya sonda: json, tsv, dumper) | ||
| 1175 | --db=/path/to/dbstore Oturumsuz doğrudan veritabanı yolu | ||
| 1176 | --token=TOKEN Aktif oturum anahtarı | ||
| 1177 | --time, time, time=1 İşlem süresini en altta satır olarak yazar | ||
| 1178 | --dry-run İşlemi uygulamadan simüle eder | ||
| 1179 | --force Silme eylemleri için zorunlu onay | ||
| 1180 | --version, -v, version Sürüm bilgisini yazar | ||
| 1181 | |||
| 1182 | İngilizce yardım için: amberdb usage | ||
| 1183 | USAGE_TR | ||
| 1184 | exit 0; | ||
| 1185 | } | ||
| 1186 | |||
| 1187 | # Default: English | ||
| 1188 | print <<"USAGE_EN"; | ||
| 1189 | AmberDB CLI v$AmberDB::VERSION - Embedded Database Console & Management Tool | ||
| 1190 | |||
| 1191 | Usage: | ||
| 1192 | amberdb [action|token] [table] [parameters...] | ||
| 1193 | |||
| 1194 | Usage Modes: | ||
| 1195 | |||
| 1196 | 1. Direct Local Execution (Default - Local ./dbstore): | ||
| 1197 | amberdb tables # List tables in current directory ./dbstore | ||
| 1198 | amberdb read products 10 # Read single record by ID | ||
| 1199 | amberdb read products 10 inflate=1 json # Read record with schema inflation as JSON | ||
| 1200 | amberdb search products "headphone" limit=10# Full-text and phonetic search | ||
| 1201 | amberdb insert users 0 data='{"name":"Ali"}'# Insert record (creates ./dbstore if missing) | ||
| 1202 | amberdb update users 10 data='{"role":"admin"}' | ||
| 1203 | amberdb delete users 10 | ||
| 1204 | |||
| 1205 | 2. Named Session (Session Management): | ||
| 1206 | amberdb connect <database> # Connect to ~/.amberdb/<database> pool | ||
| 1207 | amberdb connect <database>\@<path> # Connect to custom folder (e.g. mydb\@./dbstore) | ||
| 1208 | amberdb 1245 tables # List tables for session 1245 | ||
| 1209 | amberdb 1245 read products 10 # Read record in session 1245 | ||
| 1210 | amberdb 1245 disconnect # Terminate active session | ||
| 1211 | |||
| 1212 | 3. Infrastructure & Setup: | ||
| 1213 | amberdb setup # Provision ~/.amberdb global workspace | ||
| 1214 | amberdb setup [dir] # Initialize database skeleton in custom directory | ||
| 1215 | amberdb setup ramdisk [start|stop|status] # RAM-disk drive management | ||
| 1216 | |||
| 1217 | Maintenance & Administrative Actions: | ||
| 1218 | amberdb update storage [--check] [--force] # Directory & ABR v5 format migration | ||
| 1219 | amberdb update version [--check] # MetaCPAN core version check / update | ||
| 1220 | amberdb reindex products # Rebuild all derived indexes | ||
| 1221 | amberdb check products # Physical file integrity check | ||
| 1222 | amberdb vacuum products # Compact and reclaim BDB storage space | ||
| 1223 | amberdb migrate products # Schema migration | ||
| 1224 | amberdb export products file=backup.csv # Export table to CSV | ||
| 1225 | amberdb import products file=new.csv # Import table from CSV | ||
| 1226 | amberdb dump products file=backup.tar.gz # Create database backup archive | ||
| 1227 | amberdb restore file=backup.tar.gz # Restore database from backup | ||
| 1228 | amberdb rename from=old to=new # Rename table | ||
| 1229 | amberdb drop temp_tbl force=1 # Permanently drop table and indexes | ||
| 1230 | |||
| 1231 | General Options: | ||
| 1232 | --format=table|json|pretty|tsv|dumper Output format (Default: table. Or trailing: json, tsv, dumper) | ||
| 1233 | --db=/path/to/dbstore Direct database directory without session | ||
| 1234 | --token=TOKEN Active session token | ||
| 1235 | --time, time, time=1 Prints execution time at the bottom | ||
| 1236 | --dry-run Simulates execution without writes | ||
| 1237 | --force Required confirmation for destructive actions | ||
| 1238 | --version, -v, version Display version information | ||
| 1239 | |||
| 1240 | For Turkish help: amberdb usage.tr | ||
| 1241 | USAGE_EN | ||
| 1242 | exit 0; | ||
| 1243 | } | ||
| 1244 | |||
| 1245 | if ( $opt_help || ( defined $opt_action && $opt_action eq 'help' ) ) { | ||
| 1246 | my $lang = $opt_help_lang; | ||
| 1247 | if ( @pos_args && $pos_args[0] =~ /^(?:tr|en)$/i ) { | ||
| 1248 | $lang //= lc(shift @pos_args); | ||
| 1249 | } | ||
| 1250 | $lang //= 'en'; | ||
| 1251 | $opt_help = 1; | ||
| 1252 | show_usage($lang); | ||
| 1253 | } | ||
| 1254 | |||
| 1255 | if ( defined $opt_action && $opt_action =~ /^(?:version|--version|-v)$/i ) { | ||
| 1256 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1257 | output_result( { version => $AmberDB::VERSION, engine => 'AmberDB', platform => $^O }, $opt_format ); | ||
| 1258 | } | ||
| 1259 | else { | ||
| 1260 | print "AmberDB v$AmberDB::VERSION (CLI)\n"; | ||
| 1261 | } | ||
| 1262 | exit 0; | ||
| 1263 | } | ||
| 1264 | |||
| 1265 | # ============================================================================ | ||
| 1266 | # LIFECYCLE: CONNECT & DISCONNECT | ||
| 1267 | # ============================================================================ | ||
| 1268 | |||
| 1269 | if ( defined $opt_action && $opt_action eq 'connect' ) { | ||
| 1270 | my $conn_arg = $opt_database // shift @pos_args; | ||
| 1271 | my ( $conn_db, $custom_path ); | ||
| 1272 | |||
| 1273 | if ( defined $conn_arg ) { | ||
| 1274 | # Custom directory format: <dbname>@<path> (e.g. mydb@./dbstore or mydb@C:/data) | ||
| 1275 | if ( $conn_arg =~ /^([a-zA-Z0-9_\-]+)@(.+)$/ ) { | ||
| 1276 | $conn_db = $1; | ||
| 1277 | $custom_path = $2; | ||
| 1278 | } | ||
| 1279 | else { | ||
| 1280 | $conn_db = $conn_arg; | ||
| 1281 | } | ||
| 1282 | } | ||
| 1283 | |||
| 1284 | if ( defined $conn_db && ( $conn_db eq 'dbstore' || $conn_db =~ m{[/\\\\]} || $conn_db =~ /^[a-zA-Z]:/ ) ) { | ||
| 1285 | 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"; | ||
| 1286 | } | ||
| 1287 | |||
| 1288 | $conn_db //= $detected_dbname; | ||
| 1289 | unless ( defined $conn_db && length $conn_db ) { | ||
| 1290 | die "[AMBERDB_ERROR] Database name required. Usage: amberdb connect <database_name> (or <database_name>\@<path>)\n"; | ||
| 1291 | } | ||
| 1292 | |||
| 1293 | my $target_data_dir; | ||
| 1294 | if ( defined $custom_path && length $custom_path ) { | ||
| 1295 | $target_data_dir = resolve_abs_path($custom_path); | ||
| 1296 | } | ||
| 1297 | elsif ( $explicit_db ) { | ||
| 1298 | $target_data_dir = $adb->path('dbase_dir'); | ||
| 1299 | } | ||
| 1300 | else { | ||
| 1301 | # Central store under ~/.amberdb/<dbname> | ||
| 1302 | $target_data_dir = "$AMBERDB_HOME/$conn_db"; | ||
| 1303 | } | ||
| 1304 | $target_data_dir = resolve_abs_path($target_data_dir); | ||
| 1305 | |||
| 1306 | # Ensure target data directory and skeleton exist | ||
| 1307 | make_path( | ||
| 1308 | "$target_data_dir/table", "$target_data_dir/schema", "$target_data_dir/journal", | ||
| 1309 | "$target_data_dir/lock", "$target_data_dir/session", "$target_data_dir/config", | ||
| 1310 | "$target_data_dir/backup", "$target_data_dir/ramdisk" | ||
| 1311 | ); | ||
| 1312 | my $conf_file = "$target_data_dir/config/core.conf"; | ||
| 1313 | if ( !-f $conf_file && open my $cfh, '>', $conf_file ) { | ||
| 1314 | print $cfh "site_id $conn_db\nlanguage tr\n"; | ||
| 1315 | close $cfh; | ||
| 1316 | } | ||
| 1317 | |||
| 1318 | $adb->set_datadir($target_data_dir); | ||
| 1319 | $adb->{_connect}->{database} = $conn_db; | ||
| 1320 | $adb->clear_cache('ramdisk'); | ||
| 1321 | $adb->ramdisk_setup(); | ||
| 1322 | |||
| 1323 | # Authenticate and generate token | ||
| 1324 | my $conn_user = 'cli'; | ||
| 1325 | my $entered_user = shift @pos_args if @pos_args; | ||
| 1326 | my $conn_pass = $opt_pass // shift @pos_args // ''; | ||
| 1327 | |||
| 1328 | my $token = eval { | ||
| 1329 | $adb->connect( | ||
| 1330 | database => $conn_db, | ||
| 1331 | username => $conn_user, | ||
| 1332 | ( defined $conn_pass && length $conn_pass ? ( password => $conn_pass ) : () ), | ||
| 1333 | ); | ||
| 1334 | }; | ||
| 1335 | if ( $@ || !$token ) { | ||
| 1336 | my $err = $@ || $adb->last_error() || "Authentication failed"; | ||
| 1337 | $err =~ s/ at .* line \d+.*//s; | ||
| 1338 | die "[AMBERDB_ERROR] $err\n"; | ||
| 1339 | } | ||
| 1340 | |||
| 1341 | # Save session with canonical absolute path in ~/.amberdb/session/sess_$token | ||
| 1342 | my $sess_data = { | ||
| 1343 | token => $token, | ||
| 1344 | database => $conn_db, | ||
| 1345 | username => $conn_user, | ||
| 1346 | path => { dbase_dir => $target_data_dir }, | ||
| 1347 | cfg => $adb->config(), | ||
| 1348 | }; | ||
| 1349 | set_session_path( $token, $target_data_dir, $sess_data ); | ||
| 1350 | |||
| 1351 | my $actual_file = cli_session_file($token); | ||
| 1352 | |||
| 1353 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1354 | print encode_json( { | ||
| 1355 | status => 'connected', | ||
| 1356 | token => $token, | ||
| 1357 | session_file => $actual_file, | ||
| 1358 | database => $conn_db, | ||
| 1359 | username => $conn_user, | ||
| 1360 | path => { dbase_dir => $target_data_dir }, | ||
| 1361 | cfg => $adb->config(), | ||
| 1362 | } ), "\n"; | ||
| 1363 | } | ||
| 1364 | else { | ||
| 1365 | print "[AMBERDB] Connected successfully.\n"; | ||
| 1366 | print "Session Token : $token\n"; | ||
| 1367 | print "Database : $conn_db\n"; | ||
| 1368 | print "Data Dir : $target_data_dir\n"; | ||
| 1369 | print "Session File : $actual_file\n"; | ||
| 1370 | print "\nUsage with Token:\n"; | ||
| 1371 | print " amberdb $token tables\n"; | ||
| 1372 | print " amberdb $token read <table_name> <id>\n"; | ||
| 1373 | print "Or set environment variable in current shell:\n"; | ||
| 1374 | print " export AMBERDB_TOKEN=$token (Windows CMD: set AMBERDB_TOKEN=$token)\n"; | ||
| 1375 | } | ||
| 1376 | exit 0; | ||
| 1377 | } | ||
| 1378 | |||
| 1379 | if ( defined $opt_action && $opt_action eq 'disconnect' ) { | ||
| 1380 | my $token = $active_token || resolve_active_token( $opt_token, 1 ); | ||
| 1381 | unless ($token) { | ||
| 1382 | die "[AMBERDB_ERROR] No active session token found to disconnect.\n"; | ||
| 1383 | } | ||
| 1384 | $adb->disconnect($token); | ||
| 1385 | delete_session($token); | ||
| 1386 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1387 | print encode_json( { status => 'disconnected', token => $token } ), "\n"; | ||
| 1388 | } | ||
| 1389 | else { | ||
| 1390 | print "[AMBERDB] Disconnected session '$token' successfully.\n"; | ||
| 1391 | } | ||
| 1392 | exit 0; | ||
| 1393 | } | ||
| 1394 | |||
| 1395 | # If in session and global configs/paths changed without action, update session and exit | ||
| 1396 | if ( $session && ( $has_cfg_updates || $has_path_updates ) && !defined $opt_action ) { | ||
| 1397 | $session->{path} = $adb->path(); | ||
| 1398 | $session->{cfg} = $adb->config(); | ||
| 1399 | $session->{updated_at} = time(); | ||
| 1400 | save_session( $active_token, $session ); | ||
| 1401 | |||
| 1402 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1403 | print encode_json( { status => 'updated', token => $active_token, path => $adb->path(), cfg => $adb->config() } ), "\n"; | ||
| 1404 | } | ||
| 1405 | else { | ||
| 1406 | print "[AMBERDB] Session '$active_token' configuration updated successfully.\n"; | ||
| 1407 | print "Path : " . encode_json( $adb->path() ) . "\n"; | ||
| 1408 | print "Config : " . encode_json( $adb->config() ) . "\n"; | ||
| 1409 | } | ||
| 1410 | exit 0; | ||
| 1411 | } | ||
| 1412 | |||
| 1413 | # ============================================================================ | ||
| 1414 | # SESSION COMMANDS: CONFIG & PATH | ||
| 1415 | # ============================================================================ | ||
| 1416 | |||
| 1417 | if ( defined $opt_action && $opt_action eq 'config' ) { | ||
| 1418 | unless ($session) { | ||
| 1419 | die "[AMBERDB_ERROR] 'config' requires an active session. Run 'connect' first (e.g. amberdb connect path-dbase_dir=...) or specify a token.\n"; | ||
| 1420 | } | ||
| 1421 | if ( %method_args || $has_cfg_updates ) { | ||
| 1422 | for my $k ( keys %method_args ) { | ||
| 1423 | $adb->config( $k => $method_args{$k} ); | ||
| 1424 | } | ||
| 1425 | $session->{cfg} = $adb->config(); | ||
| 1426 | $session->{updated_at} = time(); | ||
| 1427 | save_session( $active_token, $session ); | ||
| 1428 | output_result( { status => 'ok', action => 'config', token => $active_token, cfg => $adb->config() }, $opt_format ); | ||
| 1429 | } | ||
| 1430 | else { | ||
| 1431 | output_result( $adb->config() // {}, $opt_format ); | ||
| 1432 | } | ||
| 1433 | exit 0; | ||
| 1434 | } | ||
| 1435 | |||
| 1436 | if ( defined $opt_action && $opt_action eq 'path' ) { | ||
| 1437 | unless ($session) { | ||
| 1438 | die "[AMBERDB_ERROR] 'path' requires an active session. Run 'connect' first (e.g. amberdb connect path-dbase_dir=...) or specify a token.\n"; | ||
| 1439 | } | ||
| 1440 | if ( %method_args || $has_path_updates ) { | ||
| 1441 | my $old_file = session_file($active_token); | ||
| 1442 | for my $k ( keys %method_args ) { | ||
| 1443 | my $val = $method_args{$k}; | ||
| 1444 | if ( $k eq 'dbase_dir' || $k eq 'db' || $k eq 'dbase' ) { | ||
| 1445 | my $new_db_dir = eval { abs_path($val) } // $val; | ||
| 1446 | $adb->set_datadir($new_db_dir); | ||
| 1447 | } | ||
| 1448 | else { | ||
| 1449 | $adb->path( $k => $val ); | ||
| 1450 | } | ||
| 1451 | } | ||
| 1452 | $session->{path} = $adb->path(); | ||
| 1453 | $session->{updated_at} = time(); | ||
| 1454 | |||
| 1455 | my $new_file = session_file($active_token); | ||
| 1456 | save_session( $active_token, $session ); | ||
| 1457 | if ( defined $old_file && -f $old_file && $old_file ne $new_file ) { | ||
| 1458 | unlink $old_file; | ||
| 1459 | } | ||
| 1460 | output_result( { status => 'ok', action => 'path', token => $active_token, path => $adb->path() }, $opt_format ); | ||
| 1461 | } | ||
| 1462 | else { | ||
| 1463 | output_result( $adb->path() // {}, $opt_format ); | ||
| 1464 | } | ||
| 1465 | exit 0; | ||
| 1466 | } | ||
| 1467 | |||
| 1468 | if ( defined $opt_action && $opt_action eq 'user' ) { | ||
| 1469 | my $subcmd = shift @pos_args // 'list'; | ||
| 1470 | if ( $subcmd eq 'list' ) { | ||
| 1471 | my @users = $adb->user_list(); | ||
| 1472 | if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' ) ) { | ||
| 1473 | output_result( { status => 'ok', action => 'user_list', users => \@users }, $opt_format ); | ||
| 1474 | } | ||
| 1475 | else { | ||
| 1476 | print "Database: " . ($adb->connect('database') || 'unknown') . "\n"; | ||
| 1477 | print "=" x 60, "\n"; | ||
| 1478 | printf( "%-20s %-15s %-15s\n", "Username", "Role", "Password Set" ); | ||
| 1479 | print "-" x 60, "\n"; | ||
| 1480 | for my $u (@users) { | ||
| 1481 | printf( "%-20s %-15s %-15s\n", | ||
| 1482 | $u->{username}, | ||
| 1483 | $u->{role}, | ||
| 1484 | $u->{has_password} ? "Yes (Shadow)" : "No (Passwordless)" | ||
| 1485 | ); | ||
| 1486 | } | ||
| 1487 | print "-" x 60, "\n"; | ||
| 1488 | } | ||
| 1489 | exit 0; | ||
| 1490 | } | ||
| 1491 | elsif ( $subcmd eq 'add' ) { | ||
| 1492 | my $u = shift @pos_args // $opt_user; | ||
| 1493 | my $p = shift @pos_args // $opt_pass // ''; | ||
| 1494 | my $role = shift @pos_args // 'user'; | ||
| 1495 | die "[AMBERDB_ERROR] Usage: amberdb user add <username> [password] [role]\n" unless defined $u && length $u; | ||
| 1496 | $adb->user_add( $u, $p, role => $role ); | ||
| 1497 | output_result( { status => 'ok', action => 'user_add', username => $u, role => $role }, $opt_format ); | ||
| 1498 | exit 0; | ||
| 1499 | } | ||
| 1500 | elsif ( $subcmd eq 'passwd' ) { | ||
| 1501 | my $u = shift @pos_args // $opt_user; | ||
| 1502 | my $p = shift @pos_args // $opt_pass // ''; | ||
| 1503 | die "[AMBERDB_ERROR] Usage: amberdb user passwd <username> <new_password>\n" unless defined $u && length $u; | ||
| 1504 | $adb->user_passwd( $u, $p ); | ||
| 1505 | output_result( { status => 'ok', action => 'user_passwd', username => $u }, $opt_format ); | ||
| 1506 | exit 0; | ||
| 1507 | } | ||
| 1508 | elsif ( $subcmd eq 'del' || $subcmd eq 'delete' ) { | ||
| 1509 | my $u = shift @pos_args // $opt_user; | ||
| 1510 | die "[AMBERDB_ERROR] Usage: amberdb user del <username>\n" unless defined $u && length $u; | ||
| 1511 | $adb->user_del($u); | ||
| 1512 | output_result( { status => 'ok', action => 'user_del', username => $u }, $opt_format ); | ||
| 1513 | exit 0; | ||
| 1514 | } | ||
| 1515 | else { | ||
| 1516 | die "[AMBERDB_ERROR] Unknown user subcommand '$subcmd'. Available: list, add, passwd, del\n"; | ||
| 1517 | } | ||
| 1518 | } | ||
| 1519 | |||
| 1520 | # ============================================================================ | ||
| 1521 | # INFRASTRUCTURE SETUP & PROVISIONING (amberdb setup [dir]) | ||
| 1522 | # ============================================================================ | ||
| 1523 | |||
| 1524 | if ( defined $opt_action && ( $opt_action eq 'setup' || $opt_action eq 'ramdisk' ) ) { | ||
| 1525 | my $first_arg = shift @pos_args; | ||
| 1526 | |||
| 1527 | # Check if ramdisk subcommand: amberdb setup ramdisk ... or amberdb ramdisk ... | ||
| 1528 | if ( ( $opt_action eq 'ramdisk' ) || ( defined $first_arg && lc($first_arg) eq 'ramdisk' ) ) { | ||
| 1529 | my $subcmd = ( $opt_action eq 'ramdisk' ) ? ( $first_arg // 'status' ) : ( shift @pos_args // 'status' ); | ||
| 1530 | $subcmd = lc($subcmd); | ||
| 1531 | $subcmd = 'start' if $subcmd eq 'mount' || $subcmd eq '--start'; | ||
| 1532 | $subcmd = 'stop' if $subcmd eq 'unmount' || $subcmd eq '--stop'; | ||
| 1533 | $subcmd = 'status' if $subcmd eq '--status'; | ||
| 1534 | |||
| 1535 | my $size = delete $method_args{size} // shift @pos_args // '512M'; | ||
| 1536 | my $drive = delete $method_args{drive} // shift @pos_args // 'R:'; | ||
| 1537 | |||
| 1538 | my $is_win = ( $^O eq 'MSWin32' || $^O eq 'msys' || $^O eq 'cygwin' ); | ||
| 1539 | |||
| 1540 | if ($is_win) { | ||
| 1541 | my $script_bin = eval { abs_path(dirname(__FILE__)) } // dirname(__FILE__) // '.'; | ||
| 1542 | my $bat_path = File::Spec->catfile( $script_bin, "setup_windows.bat" ); | ||
| 1543 | if ( -f $bat_path ) { | ||
| 1544 | system( "cmd.exe", "/c", $bat_path, $subcmd, $size, $drive ); | ||
| 1545 | exit $? >> 8; | ||
| 1546 | } | ||
| 1547 | else { | ||
| 1548 | if ( $subcmd eq 'start' ) { | ||
| 1549 | system( "imdisk", "-a", "-s", $size, "-m", $drive, "-p", "/fs:ntfs /q /y /v:AmberDB" ); | ||
| 1550 | } | ||
| 1551 | elsif ( $subcmd eq 'stop' ) { | ||
| 1552 | system( "imdisk", "-D", "-m", $drive ); | ||
| 1553 | } | ||
| 1554 | else { | ||
| 1555 | system( "imdisk", "-l", "-m", $drive ); | ||
| 1556 | } | ||
| 1557 | exit $? >> 8; | ||
| 1558 | } | ||
| 1559 | } | ||
| 1560 | else { | ||
| 1561 | if ( $subcmd eq 'status' ) { | ||
| 1562 | my $shm = -d "/dev/shm" ? "/dev/shm (Linux tmpfs available)" : "Not mounted"; | ||
| 1563 | print "RAM-Disk Status: $shm\n"; | ||
| 1564 | exit 0; | ||
| 1565 | } | ||
| 1566 | elsif ( $subcmd eq 'start' ) { | ||
| 1567 | eval { $adb->ramdisk_setup() }; | ||
| 1568 | print "[RAM-DISK] Linux /dev/shm initialized.\n"; | ||
| 1569 | exit 0; | ||
| 1570 | } | ||
| 1571 | elsif ( $subcmd eq 'stop' ) { | ||
| 1572 | print "[RAM-DISK] Stopped.\n"; | ||
| 1573 | exit 0; | ||
| 1574 | } | ||
| 1575 | } | ||
| 1576 | } | ||
| 1577 | |||
| 1578 | # If no argument is passed: setup global environment (~/.amberdb) | ||
| 1579 | if ( !defined $first_arg || !length $first_arg ) { | ||
| 1580 | setup_global_workspace(); | ||
| 1581 | |||
| 1582 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1583 | output_result( { | ||
| 1584 | status => 'ok', | ||
| 1585 | action => 'setup', | ||
| 1586 | mode => 'global', | ||
| 1587 | amberdb_home => $AMBERDB_HOME, | ||
| 1588 | session_dir => $CLI_SESS_DIR, | ||
| 1589 | }, $opt_format ); | ||
| 1590 | exit 0; | ||
| 1591 | } | ||
| 1592 | |||
| 1593 | print "=================================================================\n"; | ||
| 1594 | print " AmberDB Global Environment Setup & Initialization \n"; | ||
| 1595 | print "=================================================================\n"; | ||
| 1596 | print "AmberDB Home : $AMBERDB_HOME (~/.amberdb)\n"; | ||
| 1597 | print "Session Registry : $CLI_SESS_DIR/\n"; | ||
| 1598 | print "Platform : $^O\n"; | ||
| 1599 | print "-----------------------------------------------------------------\n"; | ||
| 1600 | print "[SUCCESS] AmberDB global workspace initialized successfully!\n\n"; | ||
| 1601 | print "Kullanım Biçimleri:\n"; | ||
| 1602 | print " 1. Yerel Proje : Proje klasörünüzde doğrudan çalıştırın (./dbstore kullanılır)\n"; | ||
| 1603 | print " amberdb insert users 0 data='{\"name\":\"Ahmet\"}'\n"; | ||
| 1604 | print " amberdb tables\n\n"; | ||
| 1605 | print " 2. Merkezi Havuz : Belirtilen ada oturum açarak ~/.amberdb/<ad> kullanılır\n"; | ||
| 1606 | print " amberdb connect eticaretim\n"; | ||
| 1607 | print " amberdb 1245 tables\n\n"; | ||
| 1608 | print " 3. Özel Klasör : 'ad\@yol' formatı ile oturum açılır\n"; | ||
| 1609 | print " amberdb connect eticaretim\@./dbstore\n"; | ||
| 1610 | print "=================================================================\n"; | ||
| 1611 | exit 0; | ||
| 1612 | } | ||
| 1613 | |||
| 1614 | # If custom directory passed (e.g. amberdb setup /var/data or amberdb setup my_dir) | ||
| 1615 | my $target_dir = resolve_abs_path($first_arg); | ||
| 1616 | my @subdirs = qw(table schema journal lock session config backup ramdisk); | ||
| 1617 | my @created; | ||
| 1618 | my @existing; | ||
| 1619 | make_path($target_dir) unless -d $target_dir; | ||
| 1620 | for my $sub (@subdirs) { | ||
| 1621 | my $dir_path = "$target_dir/$sub"; | ||
| 1622 | if ( -d $dir_path ) { | ||
| 1623 | push @existing, $sub; | ||
| 1624 | } | ||
| 1625 | else { | ||
| 1626 | make_path($dir_path); | ||
| 1627 | push @created, $sub; | ||
| 1628 | } | ||
| 1629 | } | ||
| 1630 | my $core_conf = "$target_dir/config/core.conf"; | ||
| 1631 | my $conf_created = 0; | ||
| 1632 | if ( !-f $core_conf && open my $fh, '>', $core_conf ) { | ||
| 1633 | print $fh "# AmberDB Core Configuration\n"; | ||
| 1634 | print $fh "site_id amberdb\n"; | ||
| 1635 | print $fh "language tr\n"; | ||
| 1636 | close $fh; | ||
| 1637 | $conf_created = 1; | ||
| 1638 | } | ||
| 1639 | if ( defined $opt_format && $opt_format eq 'json' ) { | ||
| 1640 | output_result( { | ||
| 1641 | status => 'ok', | ||
| 1642 | action => 'setup', | ||
| 1643 | dbase_dir => $target_dir, | ||
| 1644 | dirs_created => \@created, | ||
| 1645 | dirs_existing => \@existing, | ||
| 1646 | config_init => $conf_created ? 1 : 0, | ||
| 1647 | }, $opt_format ); | ||
| 1648 | exit 0; | ||
| 1649 | } | ||
| 1650 | |||
| 1651 | print "=================================================================\n"; | ||
| 1652 | print " AmberDB Infrastructure Setup: $target_dir \n"; | ||
| 1653 | print "=================================================================\n"; | ||
| 1654 | for my $c (@created) { print " [+] Created $c/\n"; } | ||
| 1655 | for my $e (@existing) { print " [.] Exists $e/\n"; } | ||
| 1656 | print "-----------------------------------------------------------------\n"; | ||
| 1657 | print "[SUCCESS] Initialized successfully in $target_dir\n"; | ||
| 1658 | print "=================================================================\n"; | ||
| 1659 | exit 0; | ||
| 1660 | } | ||
| 1661 | |||
| 1662 | # ============================================================================ | ||
| 1663 | # DEFAULT ACTION: DASHBOARD OVERVIEW (ALL TABLES) | ||
| 1664 | # ============================================================================ | ||
| 1665 | |||
| 1666 | if ( !defined $opt_action || $opt_action eq '' || $opt_action eq 'list' || $opt_action eq 'status' || $opt_action eq 'tables' ) { | ||
| 1667 | my $db_dir = $adb->path('dbase_dir') || "."; | ||
| 1668 | |||
| 1669 | if ( !-d $db_dir || ( !-d "$db_dir/table" && !-d "$db_dir/schema" ) ) { | ||
| 1670 | if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' ) ) { | ||
| 1671 | output_result( { | ||
| 1672 | database => $adb->connect('database') || $detected_dbname || '-', | ||
| 1673 | user => $adb->connect('username') || 'cli', | ||
| 1674 | data_dir => $db_dir, | ||
| 1675 | total_tables => 0, | ||
| 1676 | total_records => 0, | ||
| 1677 | total_bytes => 0, | ||
| 1678 | tables => [], | ||
| 1679 | }, $opt_format ); | ||
| 1680 | exit 0; | ||
| 1681 | } | ||
| 1682 | print "AmberDB | Data Dir: $db_dir\n"; | ||
| 1683 | print "=" x 80, "\n"; | ||
| 1684 | print "[AMBERDB] '$db_dir' dizini bulunamadı veya henüz bir tablo oluşturulmamış.\n"; | ||
| 1685 | print "İlk tabloyu oluşturmak için kayıt ekleyebilirsiniz:\n"; | ||
| 1686 | print " amberdb insert <tablo_adı> 0 data='{\"name\":\"sample\"}'\n"; | ||
| 1687 | print "=" x 80, "\n"; | ||
| 1688 | exit 0; | ||
| 1689 | } | ||
| 1690 | |||
| 1691 | my @tables = $tools->all_tables(); | ||
| 1692 | my @rows; | ||
| 1693 | my $total_records = 0; | ||
| 1694 | my $total_bytes = 0; | ||
| 1695 | |||
| 1696 | for my $tbl ( sort @tables ) { | ||
| 1697 | next unless defined $tbl && length $tbl; | ||
| 1698 | my $cnt = $adb->table_count($tbl) // 0; | ||
| 1699 | my $tpath = $adb->table_path($tbl); | ||
| 1700 | my $db_file = -f "$tpath.db" ? "$tpath.db" : ( -f "$db_dir/table/$tbl.db" ? "$db_dir/table/$tbl.db" : "$db_dir/$tbl.db" ); | ||
| 1701 | my $size = -f $db_file ? -s $db_file : 0; | ||
| 1702 | |||
| 1703 | $total_records += $cnt; | ||
| 1704 | $total_bytes += $size; | ||
| 1705 | |||
| 1706 | my $has_schema = ( -f "$tpath.table" || -f "$db_dir/schema/$tbl.table" ) ? "OK" : ( $adb->config('use_simple') ? "Simple" : "None" ); | ||
| 1707 | |||
| 1708 | my @indexes; | ||
| 1709 | push @indexes, "inx" if -f "$tpath.inx"; | ||
| 1710 | push @indexes, "src" if -f "$tpath.src"; | ||
| 1711 | push @indexes, "fld" if -f "$tpath.fld"; | ||
| 1712 | push @indexes, "slg" if -f "$tpath.slg"; | ||
| 1713 | push @indexes, "del" if -f "$tpath.del"; | ||
| 1714 | push @indexes, "lnk" if -f "$tpath.lnk"; | ||
| 1715 | |||
| 1716 | push @rows, { | ||
| 1717 | table => $tbl, | ||
| 1718 | records => $cnt, | ||
| 1719 | size => format_bytes($size), | ||
| 1720 | schema => $has_schema, | ||
| 1721 | indexes => @indexes ? join( ", ", @indexes ) : "-", | ||
| 1722 | }; | ||
| 1723 | } | ||
| 1724 | |||
| 1725 | if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' ) ) { | ||
| 1726 | output_result( { | ||
| 1727 | database => $adb->connect('database'), | ||
| 1728 | user => $adb->connect('username'), | ||
| 1729 | data_dir => $adb->path('dbase_dir'), | ||
| 1730 | total_tables => scalar(@rows), | ||
| 1731 | total_records => $total_records, | ||
| 1732 | total_bytes => $total_bytes, | ||
| 1733 | tables => \@rows, | ||
| 1734 | }, $opt_format ); | ||
| 1735 | } | ||
| 1736 | else { | ||
| 1737 | print "AmberDB v$AmberDB::VERSION | Database: " . ($adb->connect('database') || '-') . " | User: " . ($adb->connect('username') || '-') . " | Data Dir: " . $adb->path('dbase_dir') . "\n"; | ||
| 1738 | print "=" x 80, "\n"; | ||
| 1739 | printf( "%-28s %-10s %-12s %-10s %-15s\n", "Table Name", "Records", "Size", "Schema", "Indexes" ); | ||
| 1740 | print "-" x 80, "\n"; | ||
| 1741 | for my $r (@rows) { | ||
| 1742 | printf( "%-28s %-10s %-12s %-10s %-15s\n", | ||
| 1743 | substr( $r->{table}, 0, 27 ), | ||
| 1744 | $r->{records}, | ||
| 1745 | $r->{size}, | ||
| 1746 | $r->{schema}, | ||
| 1747 | $r->{indexes} | ||
| 1748 | ); | ||
| 1749 | } | ||
| 1750 | print "-" x 80, "\n"; | ||
| 1751 | printf( "Total Tables: %d | Total Records: %d | Total Size: %s\n", | ||
| 1752 | scalar(@rows), $total_records, format_bytes($total_bytes) ); | ||
| 1753 | } | ||
| 1754 | exit 0; | ||
| 1755 | } | ||
| 1756 | |||
| 1757 | # ============================================================================ | ||
| 1758 | # DYNAMIC METHOD DISPATCHER | ||
| 1759 | # ============================================================================ | ||
| 1760 | |||
| 1761 | my $action = $opt_action; | ||
| 1762 | |||
| 1763 | sub is_db_ready { | ||
| 1764 | my $dir = $adb->path('dbase_dir'); | ||
| 1765 | return 0 unless defined $dir && length $dir && -d $dir; | ||
| 1766 | return 1 if -d "$dir/table" || -d "$dir/schema"; | ||
| 1767 | return 0; | ||
| 1768 | } | ||
| 1769 | |||
| 1770 | sub table_file_exists { | ||
| 1771 | my ($tbl) = @_; | ||
| 1772 | return 0 unless defined $tbl && length $tbl; | ||
| 1773 | my $dir = $adb->path('dbase_dir'); | ||
| 1774 | return 0 unless defined $dir && length $dir && -d $dir; | ||
| 1775 | my $tbl_dir = $adb->path('table_dir') || "$dir/table"; | ||
| 1776 | return 1 if -f "$tbl_dir/$tbl.db"; | ||
| 1777 | return 1 if -f "$dir/$tbl.db"; | ||
| 1778 | my $tpath = eval { $adb->table_path($tbl) }; | ||
| 1779 | return 1 if defined $tpath && length $tpath && ( -f "$tpath.db" || -f $tpath ); | ||
| 1780 | return 0; | ||
| 1781 | } | ||
| 1782 | |||
| 1783 | sub normalize_list_result { | ||
| 1784 | my ( $limit, $is_inflate, @results ) = @_; | ||
| 1785 | if ($limit) { | ||
| 1786 | my $cnt = shift @results // 0; | ||
| 1787 | my $recs; | ||
| 1788 | if ($is_inflate) { | ||
| 1789 | my $raw = shift @results // []; | ||
| 1790 | $recs = ref $raw eq 'ARRAY' ? $raw : [ $raw ]; | ||
| 1791 | } | ||
| 1792 | else { | ||
| 1793 | $recs = \@results; | ||
| 1794 | } | ||
| 1795 | return { count => $cnt, records => $recs }; | ||
| 1796 | } | ||
| 1797 | else { | ||
| 1798 | my $recs; | ||
| 1799 | if ($is_inflate) { | ||
| 1800 | my $raw = $results[0] // []; | ||
| 1801 | $recs = ref $raw eq 'ARRAY' ? $raw : [ $raw ]; | ||
| 1802 | } | ||
| 1803 | else { | ||
| 1804 | $recs = \@results; | ||
| 1805 | } | ||
| 1806 | return { count => scalar(@$recs), records => $recs }; | ||
| 1807 | } | ||
| 1808 | } | ||
| 1809 | |||
| 1810 | # 1. TABLE_ATTR / ATTR | ||
| 1811 | if ( $action eq 'table_attr' || $action eq 'attr' ) { | ||
| 1812 | unless ($session) { | ||
| 1813 | die "[AMBERDB_ERROR] 'attr' requires an active session. Run 'connect' first (e.g. amberdb connect path-dbase_dir=...) or specify a token.\n"; | ||
| 1814 | } | ||
| 1815 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1816 | die "[AMBERDB_ERROR] 'table' parameter required for table_attr\n" unless defined $table && length $table; | ||
| 1817 | |||
| 1818 | if ( !keys %method_args ) { | ||
| 1819 | # Getter: return current attributes | ||
| 1820 | my $attrs = $session->{table_attrs}->{$table} || $adb->table_attr($table); | ||
| 1821 | output_result( $attrs, $opt_format ); | ||
| 1822 | exit 0; | ||
| 1823 | } | ||
| 1824 | |||
| 1825 | if ($opt_dry_run) { | ||
| 1826 | output_result( { dry_run => 1, action => 'table_attr', table => $table, attrs => \%method_args }, $opt_format ); | ||
| 1827 | exit 0; | ||
| 1828 | } | ||
| 1829 | |||
| 1830 | $adb->table_attr( $table, \%method_args ); | ||
| 1831 | my $updated_attrs = $adb->table_attr($table); | ||
| 1832 | |||
| 1833 | # Persist in session if session active | ||
| 1834 | if ($session) { | ||
| 1835 | $session->{table_attrs}->{$table} = $updated_attrs; | ||
| 1836 | $session->{updated_at} = time(); | ||
| 1837 | save_session( $active_token, $session ); | ||
| 1838 | } | ||
| 1839 | |||
| 1840 | output_result( { status => 'ok', action => 'table_attr', table => $table, attributes => $updated_attrs }, $opt_format ); | ||
| 1841 | exit 0; | ||
| 1842 | } | ||
| 1843 | |||
| 1844 | # 2. READ_ID | ||
| 1845 | if ( $action eq 'read_id' ) { | ||
| 1846 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1847 | my $id = delete $method_args{id} // shift @pos_args; | ||
| 1848 | die "[AMBERDB_ERROR] 'table' parameter required for read_id\n" unless defined $table && length $table; | ||
| 1849 | die "[AMBERDB_ERROR] 'id' parameter required for read_id\n" unless defined $id && length $id; | ||
| 1850 | |||
| 1851 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1852 | output_result( undef, $opt_format ); | ||
| 1853 | exit 0; | ||
| 1854 | } | ||
| 1855 | |||
| 1856 | my @fields = $adb->read_id( $table, $id, \%method_args ); | ||
| 1857 | my $res; | ||
| 1858 | if ( @fields == 1 && ref $fields[0] eq 'HASH' ) { | ||
| 1859 | $res = $fields[0]; | ||
| 1860 | } | ||
| 1861 | elsif (@fields) { | ||
| 1862 | $res = \@fields; | ||
| 1863 | } | ||
| 1864 | else { | ||
| 1865 | $res = undef; | ||
| 1866 | } | ||
| 1867 | output_result( $res, $opt_format, $table ); | ||
| 1868 | exit 0; | ||
| 1869 | } | ||
| 1870 | |||
| 1871 | # 3. READ_ALL | ||
| 1872 | if ( $action eq 'read_all' ) { | ||
| 1873 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1874 | my $offset = delete $method_args{offset} // 0; | ||
| 1875 | my $limit = delete $method_args{limit} // 0; | ||
| 1876 | my $is_inflate = $method_args{inflate} ? 1 : 0; | ||
| 1877 | die "[AMBERDB_ERROR] 'table' parameter required for read_all\n" unless defined $table && length $table; | ||
| 1878 | |||
| 1879 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1880 | my $res = normalize_list_result( $limit, $is_inflate ); | ||
| 1881 | output_result( $res, $opt_format, $table ); | ||
| 1882 | exit 0; | ||
| 1883 | } | ||
| 1884 | |||
| 1885 | my @results = $adb->read_all( $table, $offset, $limit, %method_args ); | ||
| 1886 | my $res = normalize_list_result( $limit, $is_inflate, @results ); | ||
| 1887 | output_result( $res, $opt_format, $table ); | ||
| 1888 | exit 0; | ||
| 1889 | } | ||
| 1890 | |||
| 1891 | # 4. READ_LIST | ||
| 1892 | if ( $action eq 'read_list' ) { | ||
| 1893 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1894 | my $ids = delete $method_args{ids} // delete $method_args{id}; | ||
| 1895 | $ids = [ split /,/, $ids ] if defined $ids && !ref $ids; | ||
| 1896 | $ids ||= \@pos_args; | ||
| 1897 | |||
| 1898 | die "[AMBERDB_ERROR] 'table' parameter required for read_list\n" unless defined $table && length $table; | ||
| 1899 | die "[AMBERDB_ERROR] 'ids' parameter required for read_list\n" unless ref $ids eq 'ARRAY' && @$ids; | ||
| 1900 | |||
| 1901 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1902 | output_result( [], $opt_format, $table ); | ||
| 1903 | exit 0; | ||
| 1904 | } | ||
| 1905 | |||
| 1906 | my @recs = $adb->read_list( $table, $ids, \%method_args ); | ||
| 1907 | output_result( \@recs, $opt_format, $table ); | ||
| 1908 | exit 0; | ||
| 1909 | } | ||
| 1910 | |||
| 1911 | # 5. FIELD_FETCH / FETCH | ||
| 1912 | if ( $action eq 'field_fetch' || $action eq 'fetch' ) { | ||
| 1913 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1914 | my $block = delete $method_args{block} // shift @pos_args; | ||
| 1915 | my $fetch = delete $method_args{fetch} // delete $method_args{value} // shift @pos_args; | ||
| 1916 | |||
| 1917 | if ( @pos_args >= 2 && $pos_args[0] =~ /^\d+$/ && $pos_args[1] =~ /^\d+$/ ) { | ||
| 1918 | $method_args{offset} //= parse_value(shift @pos_args); | ||
| 1919 | $method_args{limit} //= parse_value(shift @pos_args); | ||
| 1920 | } | ||
| 1921 | elsif ( @pos_args == 1 && $pos_args[0] =~ /^\d+$/ ) { | ||
| 1922 | $method_args{limit} //= parse_value(shift @pos_args); | ||
| 1923 | } | ||
| 1924 | |||
| 1925 | my $offset = delete $method_args{offset} // 0; | ||
| 1926 | my $limit = delete $method_args{limit} // 0; | ||
| 1927 | my $is_inflate = $method_args{inflate} ? 1 : 0; | ||
| 1928 | |||
| 1929 | die "[AMBERDB_ERROR] 'table', 'block', and 'fetch' parameters required for field_fetch\n" | ||
| 1930 | unless defined $table && defined $block && defined $fetch; | ||
| 1931 | |||
| 1932 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1933 | my $res = normalize_list_result( $limit, $is_inflate ); | ||
| 1934 | output_result( $res, $opt_format, $table ); | ||
| 1935 | exit 0; | ||
| 1936 | } | ||
| 1937 | |||
| 1938 | my @results = $adb->field_fetch( $table, $block, $fetch, $offset, $limit, %method_args ); | ||
| 1939 | my $res = normalize_list_result( $limit, $is_inflate, @results ); | ||
| 1940 | output_result( $res, $opt_format, $table ); | ||
| 1941 | exit 0; | ||
| 1942 | } | ||
| 1943 | |||
| 1944 | # 6. SEARCH_TABLE / SEARCH | ||
| 1945 | if ( $action eq 'search_table' || $action eq 'search' ) { | ||
| 1946 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1947 | my $query = delete $method_args{query} // delete $method_args{string} // delete $method_args{q} // shift @pos_args; | ||
| 1948 | |||
| 1949 | if ( @pos_args && defined $pos_args[0] && $pos_args[0] =~ /^(?:and|or)$/i ) { | ||
| 1950 | $method_args{and_or} //= shift @pos_args; | ||
| 1951 | } | ||
| 1952 | |||
| 1953 | if ( @pos_args >= 2 && $pos_args[0] =~ /^\d+$/ && $pos_args[1] =~ /^\d+$/ ) { | ||
| 1954 | $method_args{offset} //= parse_value(shift @pos_args); | ||
| 1955 | $method_args{limit} //= parse_value(shift @pos_args); | ||
| 1956 | } | ||
| 1957 | elsif ( @pos_args == 1 && $pos_args[0] =~ /^\d+$/ ) { | ||
| 1958 | $method_args{limit} //= parse_value(shift @pos_args); | ||
| 1959 | } | ||
| 1960 | |||
| 1961 | my $limit = $method_args{limit} // 0; | ||
| 1962 | my $is_inflate = $method_args{inflate} ? 1 : 0; | ||
| 1963 | |||
| 1964 | die "[AMBERDB_ERROR] 'table' and 'query' parameters required for search_table\n" | ||
| 1965 | unless defined $table && defined $query; | ||
| 1966 | |||
| 1967 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1968 | my $res = normalize_list_result( $limit, $is_inflate ); | ||
| 1969 | output_result( $res, $opt_format, $table ); | ||
| 1970 | exit 0; | ||
| 1971 | } | ||
| 1972 | |||
| 1973 | my @results = $adb->search_table( $table, $query, %method_args ); | ||
| 1974 | my $res = normalize_list_result( $limit, $is_inflate, @results ); | ||
| 1975 | output_result( $res, $opt_format, $table ); | ||
| 1976 | exit 0; | ||
| 1977 | } | ||
| 1978 | |||
| 1979 | # 7. TABLE_COUNT / COUNT | ||
| 1980 | if ( $action eq 'table_count' || $action eq 'count' ) { | ||
| 1981 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1982 | die "[AMBERDB_ERROR] 'table' parameter required for table_count\n" unless defined $table && length $table; | ||
| 1983 | |||
| 1984 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 1985 | output_result( { table => $table, count => 0 }, $opt_format ); | ||
| 1986 | exit 0; | ||
| 1987 | } | ||
| 1988 | |||
| 1989 | my $cnt = $adb->table_count($table); | ||
| 1990 | output_result( { table => $table, count => $cnt }, $opt_format ); | ||
| 1991 | exit 0; | ||
| 1992 | } | ||
| 1993 | |||
| 1994 | # 8. TABLE_INFO / INFO | ||
| 1995 | if ( $action eq 'table_info' || $action eq 'info' ) { | ||
| 1996 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 1997 | die "[AMBERDB_ERROR] 'table' parameter required for table_info\n" unless defined $table && length $table; | ||
| 1998 | |||
| 1999 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 2000 | if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' ) ) { | ||
| 2001 | output_result( {}, $opt_format ); | ||
| 2002 | } | ||
| 2003 | else { | ||
| 2004 | print "[AMBERDB] Table '$table' does not exist.\n"; | ||
| 2005 | } | ||
| 2006 | exit 0; | ||
| 2007 | } | ||
| 2008 | |||
| 2009 | my $info = $adb->table_info($table); | ||
| 2010 | if ( defined $opt_format && ( $opt_format eq 'json' || $opt_format eq 'pretty' || $opt_format eq 'raw' || $opt_format eq 'dumper' || $opt_format eq 'perl' ) ) { | ||
| 2011 | output_result( $info, $opt_format ); | ||
| 2012 | } | ||
| 2013 | else { | ||
| 2014 | print "AmberDB Table Schema: $table\n"; | ||
| 2015 | print "=" x 80, "\n"; | ||
| 2016 | printf( "%-6s %-20s %-12s %-12s %-8s %-15s\n", "Block", "Field Name", "Type", "Index", "Search", "RDBM" ); | ||
| 2017 | print "-" x 80, "\n"; | ||
| 2018 | my $blocks = ( ref $info eq 'HASH' && ref $info->{blocks} eq 'ARRAY' ) ? $info->{blocks} : []; | ||
| 2019 | my $search_blocks = ( ref $info eq 'HASH' ) ? ( $info->{search_block} || [] ) : []; | ||
| 2020 | my %is_search = map { $_ => 1 } ( ref $search_blocks eq 'ARRAY' ? @$search_blocks : keys %$search_blocks ); | ||
| 2021 | for my $i ( 0 .. $#$blocks ) { | ||
| 2022 | my $b = $blocks->[$i]; | ||
| 2023 | my $bname = ref $b eq 'HASH' ? ( $b->{name} // "block_$i" ) : "block_$i"; | ||
| 2024 | my $btype = ref $b eq 'HASH' ? ( $b->{type} // "string" ) : "string"; | ||
| 2025 | my $bidx = ref $b eq 'HASH' ? ( $b->{index} // "-" ) : "-"; | ||
| 2026 | my $srch = $is_search{$i} ? "yes" : "-"; | ||
| 2027 | my $rdbm = "-"; | ||
| 2028 | if ( ref $b eq 'HASH' && $b->{rdbm} ) { | ||
| 2029 | if ( ref $b->{rdbm} eq 'HASH' ) { | ||
| 2030 | my $rt = $b->{rdbm}->{table} // ''; | ||
| 2031 | my $rb = $b->{rdbm}->{block} // ''; | ||
| 2032 | $rdbm = ( $rb ne '' ) ? "$rt,$rb" : $rt; | ||
| 2033 | } | ||
| 2034 | else { | ||
| 2035 | $rdbm = $b->{rdbm}; | ||
| 2036 | } | ||
| 2037 | } | ||
| 2038 | printf( "%-6s %-20s %-12s %-12s %-8s %-15s\n", | ||
| 2039 | $i, | ||
| 2040 | substr( $bname, 0, 19 ), | ||
| 2041 | substr( $btype, 0, 11 ), | ||
| 2042 | substr( $bidx, 0, 11 ), | ||
| 2043 | $srch, | ||
| 2044 | substr( $rdbm, 0, 14 ) | ||
| 2045 | ); | ||
| 2046 | } | ||
| 2047 | print "=" x 80, "\n"; | ||
| 2048 | if ( ref $info eq 'HASH' ) { | ||
| 2049 | my @meta_attrs; | ||
| 2050 | for my $k ( sort keys %$info ) { | ||
| 2051 | next if $k eq 'blocks' || $k eq 'search_block'; | ||
| 2052 | my $v = $info->{$k}; | ||
| 2053 | push @meta_attrs, "$k=" . ( ref $v ? encode_json($v) : $v ); | ||
| 2054 | } | ||
| 2055 | print "Attributes: " . join( ", ", @meta_attrs ) . "\n" if @meta_attrs; | ||
| 2056 | } | ||
| 2057 | } | ||
| 2058 | exit 0; | ||
| 2059 | } | ||
| 2060 | |||
| 2061 | # 9. INSERT_ID / INSERT | ||
| 2062 | if ( $action eq 'insert_id' || $action eq 'insert' ) { | ||
| 2063 | if ( $adb->config('no_write') ) { | ||
| 2064 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma yetkisi kısıtlanmıştır!\n"; | ||
| 2065 | } | ||
| 2066 | |||
| 2067 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2068 | my $id = delete $method_args{id}; | ||
| 2069 | if ( !defined $id && @pos_args && $pos_args[0] =~ /^\d+$/ ) { | ||
| 2070 | $id = shift @pos_args; | ||
| 2071 | } | ||
| 2072 | $id //= 0; | ||
| 2073 | my $data = delete $method_args{data}; | ||
| 2074 | |||
| 2075 | # Ensure database directory and skeleton exist on write | ||
| 2076 | my $db_dir = $adb->path('dbase_dir') || "dbstore"; | ||
| 2077 | if ( !-d $db_dir || !-d "$db_dir/table" ) { | ||
| 2078 | make_path( | ||
| 2079 | "$db_dir/table", "$db_dir/schema", "$db_dir/journal", | ||
| 2080 | "$db_dir/lock", "$db_dir/session", "$db_dir/config", | ||
| 2081 | "$db_dir/backup", "$db_dir/ramdisk" | ||
| 2082 | ); | ||
| 2083 | my $conf_file = "$db_dir/config/core.conf"; | ||
| 2084 | if ( !-f $conf_file && open my $cfh, '>', $conf_file ) { | ||
| 2085 | print $cfh "site_id amberdb\nlanguage tr\n"; | ||
| 2086 | close $cfh; | ||
| 2087 | } | ||
| 2088 | } | ||
| 2089 | |||
| 2090 | if ( !defined $data ) { | ||
| 2091 | $data = scalar keys %method_args ? \%method_args : [ map { parse_value($_) } @pos_args ]; | ||
| 2092 | } | ||
| 2093 | elsif ( !ref $data ) { | ||
| 2094 | my $parsed = parse_value($data); | ||
| 2095 | $data = $parsed if ref $parsed; | ||
| 2096 | } | ||
| 2097 | |||
| 2098 | die "[AMBERDB_ERROR] 'table' parameter required for insert\n" unless defined $table && length $table; | ||
| 2099 | |||
| 2100 | if ($opt_dry_run) { | ||
| 2101 | output_result( { dry_run => 1, action => 'insert_id', table => $table, id => $id, data => $data }, $opt_format ); | ||
| 2102 | exit 0; | ||
| 2103 | } | ||
| 2104 | |||
| 2105 | my $res; | ||
| 2106 | if ( ref $data eq 'ARRAY' ) { | ||
| 2107 | $res = $adb->insert_id( $table, $id, @$data ); | ||
| 2108 | } | ||
| 2109 | else { | ||
| 2110 | $res = $adb->insert_id( $table, $id, $data ); | ||
| 2111 | } | ||
| 2112 | output_result( { status => 'ok', action => 'insert_id', table => $table, id => $res }, $opt_format ); | ||
| 2113 | exit 0; | ||
| 2114 | } | ||
| 2115 | |||
| 2116 | # 9b. UPDATE_STORAGE | ||
| 2117 | if ( $action eq 'update_storage' ) { | ||
| 2118 | my %opts; | ||
| 2119 | $opts{target_dir} = $adb->path('dbase_dir'); | ||
| 2120 | $opts{force} = $opt_force if $opt_force; | ||
| 2121 | $opts{check} = $method_args{check} if exists $method_args{check}; | ||
| 2122 | $opts{no_backup} = $method_args{no_backup} if exists $method_args{no_backup}; | ||
| 2123 | $opts{tables} = $method_args{tables} // $method_args{table} // ( @pos_args ? join(',', @pos_args) : undef ); | ||
| 2124 | $opts{manifest} = $method_args{manifest} if exists $method_args{manifest}; | ||
| 2125 | |||
| 2126 | my $res = $tools->update_storage(%opts); | ||
| 2127 | output_result( $res, $opt_format ) if defined $opt_format; | ||
| 2128 | exit 0; | ||
| 2129 | } | ||
| 2130 | |||
| 2131 | # 9c. UPDATE_VERSION | ||
| 2132 | if ( $action eq 'update_version' ) { | ||
| 2133 | my %opts; | ||
| 2134 | $opts{check} = $method_args{check} if exists $method_args{check}; | ||
| 2135 | $opts{cpanm} = $method_args{cpanm} if exists $method_args{cpanm}; | ||
| 2136 | |||
| 2137 | my $res = $tools->update_version(%opts); | ||
| 2138 | output_result( $res, $opt_format ) if defined $opt_format; | ||
| 2139 | exit 0; | ||
| 2140 | } | ||
| 2141 | |||
| 2142 | # 10. UPDATE_ID / UPDATE | ||
| 2143 | if ( $action eq 'update_id' || $action eq 'update' ) { | ||
| 2144 | if ( $adb->config('no_write') ) { | ||
| 2145 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma yetkisi kısıtlanmıştır!\n"; | ||
| 2146 | } | ||
| 2147 | |||
| 2148 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2149 | my $id = delete $method_args{id} // shift @pos_args; | ||
| 2150 | my $data = delete $method_args{data}; | ||
| 2151 | |||
| 2152 | if ( !defined $data ) { | ||
| 2153 | $data = scalar keys %method_args ? \%method_args : [ map { parse_value($_) } @pos_args ]; | ||
| 2154 | } | ||
| 2155 | elsif ( !ref $data ) { | ||
| 2156 | my $parsed = parse_value($data); | ||
| 2157 | $data = $parsed if ref $parsed; | ||
| 2158 | } | ||
| 2159 | |||
| 2160 | die "[AMBERDB_ERROR] 'table' and 'id' parameters required for update\n" | ||
| 2161 | unless defined $table && defined $id && length $id; | ||
| 2162 | |||
| 2163 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 2164 | die "[AMBERDB_ERROR] Table '$table' does not exist.\n"; | ||
| 2165 | } | ||
| 2166 | |||
| 2167 | if ($opt_dry_run) { | ||
| 2168 | output_result( { dry_run => 1, action => 'update_id', table => $table, id => $id, data => $data }, $opt_format ); | ||
| 2169 | exit 0; | ||
| 2170 | } | ||
| 2171 | |||
| 2172 | my $res; | ||
| 2173 | if ( ref $data eq 'ARRAY' ) { | ||
| 2174 | $res = $adb->update_id( $table, $id, @$data ); | ||
| 2175 | } | ||
| 2176 | else { | ||
| 2177 | $res = $adb->update_id( $table, $id, $data ); | ||
| 2178 | } | ||
| 2179 | output_result( { status => ( $res ? 'ok' : 'error' ), action => 'update_id', table => $table, id => $id, result => ( $res ? 1 : 0 ) }, $opt_format ); | ||
| 2180 | exit 0; | ||
| 2181 | } | ||
| 2182 | |||
| 2183 | # 11. DELETE_ID / DELETE | ||
| 2184 | if ( $action eq 'delete_id' || $action eq 'delete' ) { | ||
| 2185 | if ( $adb->config('no_write') ) { | ||
| 2186 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma yetkisi kısıtlanmıştır!\n"; | ||
| 2187 | } | ||
| 2188 | |||
| 2189 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2190 | my $id = delete $method_args{id} // shift @pos_args; | ||
| 2191 | |||
| 2192 | die "[AMBERDB_ERROR] 'table' and 'id' parameters required for delete_id\n" | ||
| 2193 | unless defined $table && defined $id && length $id; | ||
| 2194 | |||
| 2195 | if ( !is_db_ready() || !table_file_exists($table) ) { | ||
| 2196 | output_result( { status => 'not_found', table => $table, id => $id, result => 0 }, $opt_format ); | ||
| 2197 | exit 0; | ||
| 2198 | } | ||
| 2199 | |||
| 2200 | if ($opt_dry_run) { | ||
| 2201 | output_result( { dry_run => 1, action => 'delete_id', table => $table, id => $id }, $opt_format ); | ||
| 2202 | exit 0; | ||
| 2203 | } | ||
| 2204 | |||
| 2205 | my $res = $adb->delete_id( $table, $id ); | ||
| 2206 | output_result( { status => ( $res ? 'ok' : 'not_found' ), action => 'delete_id', table => $table, id => $id, result => ( $res ? 1 : 0 ) }, $opt_format ); | ||
| 2207 | exit 0; | ||
| 2208 | } | ||
| 2209 | |||
| 2210 | # 12. TOOLS: REINDEX | ||
| 2211 | if ( $action eq 'reindex' ) { | ||
| 2212 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2213 | my $all = delete $method_args{all} // 0; | ||
| 2214 | |||
| 2215 | if ( $all || !$table ) { | ||
| 2216 | my $ok = $tools->index_alltables(); | ||
| 2217 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'reindex_all', log => $tools->{say} }, $opt_format ); | ||
| 2218 | } | ||
| 2219 | else { | ||
| 2220 | my $ok = $tools->set_index($table); | ||
| 2221 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'reindex', table => $table, log => $tools->{say} }, $opt_format ); | ||
| 2222 | } | ||
| 2223 | exit 0; | ||
| 2224 | } | ||
| 2225 | |||
| 2226 | # 13. TOOLS: CHECK | ||
| 2227 | if ( $action eq 'check' ) { | ||
| 2228 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2229 | die "[AMBERDB_ERROR] 'table' parameter required for check\n" unless defined $table && length $table; | ||
| 2230 | |||
| 2231 | my $r_ok = $tools->check_readall($table); | ||
| 2232 | my $s_ok = $tools->check_search($table); | ||
| 2233 | output_result( { status => 'ok', table => $table, check_readall => $r_ok, check_search => $s_ok }, $opt_format ); | ||
| 2234 | exit 0; | ||
| 2235 | } | ||
| 2236 | |||
| 2237 | # 14. TOOLS: VACUUM | ||
| 2238 | if ( $action eq 'vacuum' ) { | ||
| 2239 | if ( $adb->config('no_write') ) { | ||
| 2240 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/vacuum yetkisi kısıtlanmıştır!\n"; | ||
| 2241 | } | ||
| 2242 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2243 | die "[AMBERDB_ERROR] 'table' parameter required for vacuum\n" unless defined $table && length $table; | ||
| 2244 | |||
| 2245 | my $ok = $tools->vacuum($table); | ||
| 2246 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'vacuum', table => $table }, $opt_format ); | ||
| 2247 | exit 0; | ||
| 2248 | } | ||
| 2249 | |||
| 2250 | # 15. TOOLS: MIGRATE / UPDATE_TABLE | ||
| 2251 | if ( $action eq 'migrate' || $action eq 'update_table' ) { | ||
| 2252 | if ( $adb->config('no_write') ) { | ||
| 2253 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/migrate yetkisi kısıtlanmıştır!\n"; | ||
| 2254 | } | ||
| 2255 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2256 | die "[AMBERDB_ERROR] 'table' parameter required for migrate\n" unless defined $table && length $table; | ||
| 2257 | |||
| 2258 | my $ok = $tools->update_table( $table, %method_args ); | ||
| 2259 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'migrate', table => $table, log => $tools->{say} }, $opt_format ); | ||
| 2260 | exit 0; | ||
| 2261 | } | ||
| 2262 | |||
| 2263 | # 16. TOOLS: EXPORT / TIE2CSV | ||
| 2264 | if ( $action eq 'export' || $action eq 'tie2csv' ) { | ||
| 2265 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2266 | my $file = delete $method_args{file} // shift @pos_args; | ||
| 2267 | die "[AMBERDB_ERROR] 'table' and 'file' parameters required for export\n" | ||
| 2268 | unless defined $table && defined $file; | ||
| 2269 | |||
| 2270 | my $ok = $tools->tie2csv( $table, $file ); | ||
| 2271 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'export', table => $table, file => $file }, $opt_format ); | ||
| 2272 | exit 0; | ||
| 2273 | } | ||
| 2274 | |||
| 2275 | # 17. TOOLS: IMPORT / CSV2TIE | ||
| 2276 | if ( $action eq 'import' || $action eq 'csv2tie' ) { | ||
| 2277 | if ( $adb->config('no_write') ) { | ||
| 2278 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/import yetkisi kısıtlanmıştır!\n"; | ||
| 2279 | } | ||
| 2280 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2281 | my $file = delete $method_args{file} // shift @pos_args; | ||
| 2282 | die "[AMBERDB_ERROR] 'table' and 'file' parameters required for import\n" | ||
| 2283 | unless defined $table && defined $file; | ||
| 2284 | |||
| 2285 | my $ok = $tools->csv2tie( $table, $file ); | ||
| 2286 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'import', table => $table, file => $file }, $opt_format ); | ||
| 2287 | exit 0; | ||
| 2288 | } | ||
| 2289 | |||
| 2290 | # 18. TOOLS: DUMP | ||
| 2291 | if ( $action eq 'dump' ) { | ||
| 2292 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2293 | my $file = delete $method_args{file}; | ||
| 2294 | my $ok = $tools->dump( | ||
| 2295 | ( defined $table && length $table ? ( table => $table ) : () ), | ||
| 2296 | ( defined $file && length $file ? ( file => $file ) : () ), | ||
| 2297 | %method_args | ||
| 2298 | ); | ||
| 2299 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'dump', ( defined $table ? ( table => $table ) : () ), ( defined $file ? ( file => $file ) : () ), log => $tools->{say} }, $opt_format ); | ||
| 2300 | exit 0; | ||
| 2301 | } | ||
| 2302 | |||
| 2303 | # 19. TOOLS: RESTORE | ||
| 2304 | if ( $action eq 'restore' ) { | ||
| 2305 | if ( $adb->config('no_write') ) { | ||
| 2306 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/restore yetkisi kısıtlanmıştır!\n"; | ||
| 2307 | } | ||
| 2308 | my $file = delete $method_args{file} // shift @pos_args; | ||
| 2309 | die "[AMBERDB_ERROR] 'file' parameter required for restore\n" unless defined $file; | ||
| 2310 | |||
| 2311 | my $ok = $tools->restore( | ||
| 2312 | file => $file, | ||
| 2313 | ( $opt_force ? ( force => 1 ) : () ), | ||
| 2314 | %method_args | ||
| 2315 | ); | ||
| 2316 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'restore', file => $file, log => $tools->{say} }, $opt_format ); | ||
| 2317 | exit 0; | ||
| 2318 | } | ||
| 2319 | |||
| 2320 | # 20. TOOLS: RENAME | ||
| 2321 | if ( $action eq 'rename' ) { | ||
| 2322 | if ( $adb->config('no_write') ) { | ||
| 2323 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/rename yetkisi kısıtlanmıştır!\n"; | ||
| 2324 | } | ||
| 2325 | my $from = delete $method_args{from} // shift @pos_args; | ||
| 2326 | my $to = delete $method_args{to} // shift @pos_args; | ||
| 2327 | die "[AMBERDB_ERROR] 'from' and 'to' parameters required for rename\n" unless defined $from && defined $to; | ||
| 2328 | |||
| 2329 | my $ok = $tools->replace_tablename( $from, $to ); | ||
| 2330 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'rename', from => $from, to => $to, log => $tools->{say} }, $opt_format ); | ||
| 2331 | exit 0; | ||
| 2332 | } | ||
| 2333 | |||
| 2334 | # 21. TOOLS: DROP | ||
| 2335 | if ( $action eq 'drop' ) { | ||
| 2336 | if ( $adb->config('no_write') ) { | ||
| 2337 | die "[AMBERDB_ERROR] no_write aktif: Bu oturumda yazma/drop yetkisi kısıtlanmıştır!\n"; | ||
| 2338 | } | ||
| 2339 | my $table = delete $method_args{table} // shift @pos_args; | ||
| 2340 | die "[AMBERDB_ERROR] 'table' parameter required for drop\n" unless defined $table && length $table; | ||
| 2341 | |||
| 2342 | unless ($opt_force) { | ||
| 2343 | if ( -t STDIN ) { | ||
| 2344 | print "\n[UYARI] '$table' tablosu ve ilişkili tüm indeksler kalıcı olarak silinecek!\n"; | ||
| 2345 | print "Onaylamak için tablo adını ('$table') yazın: "; | ||
| 2346 | my $confirm = <STDIN>; | ||
| 2347 | chomp($confirm) if defined $confirm; | ||
| 2348 | if ( !defined $confirm || $confirm ne $table ) { | ||
| 2349 | print "[AMBERDB] Tablo silme işlemi iptal edildi.\n"; | ||
| 2350 | exit 0; | ||
| 2351 | } | ||
| 2352 | } | ||
| 2353 | else { | ||
| 2354 | die "[AMBERDB_ERROR] Table drop requires 'force=1' or '--force' flag for safety.\n"; | ||
| 2355 | } | ||
| 2356 | } | ||
| 2357 | |||
| 2358 | my $ok = $tools->del_table($table); | ||
| 2359 | output_result( { status => ( $ok ? 'ok' : 'error' ), action => 'drop', table => $table }, $opt_format ); | ||
| 2360 | exit 0; | ||
| 2361 | } | ||
| 2362 | |||
| 2363 | # ============================================================================ | ||
| 2364 | # GENERIC DYNAMIC DISPATCH FALLBACK ($adb->$action or $tools->$action) | ||
| 2365 | # ============================================================================ | ||
| 2366 | |||
| 2367 | if ( $adb->can($action) ) { | ||
| 2368 | my $res = eval { $adb->$action( @pos_args, %method_args ) }; | ||
| 2369 | if ($@) { | ||
| 2370 | die "[AMBERDB_ERROR] Execution of \$adb->$action failed: $@\n"; | ||
| 2371 | } | ||
| 2372 | output_result( $res, $opt_format ); | ||
| 2373 | exit 0; | ||
| 2374 | } | ||
| 2375 | |||
| 2376 | if ( $tools->can($action) ) { | ||
| 2377 | my $res = eval { $tools->$action( @pos_args, %method_args ) }; | ||
| 2378 | if ($@) { | ||
| 2379 | die "[AMBERDB_ERROR] Execution of \$tools->$action failed: $@\n"; | ||
| 2380 | } | ||
| 2381 | output_result( $res, $opt_format ); | ||
| 2382 | exit 0; | ||
| 2383 | } | ||
| 2384 | |||
| 2385 | die "[AMBERDB_ERROR] Unknown action or method '$action'. Use 'help' to view available commands.\n"; | ||
| 2386 | |||
| 2387 | END { | ||
| 2388 | return unless $opt_time; | ||
| 2389 | return if $opt_help; | ||
| 2390 | return if defined $? && $? != 0; | ||
| 2391 | my $elapsed = eval { tv_interval($t0) } // 0; | ||
| 2392 | my $time_str = sprintf( "%.4fs (%.2f ms)", $elapsed, $elapsed * 1000 ); | ||
| 2393 | print "[Time: $time_str]\n"; | ||
| 2394 | } | ||
| 2395 | |||
| 2396 | __END__ |