add kvpairs2td
[hband-tools.git] / user-tools / LevelDB
blobbb6aa55a8693708a39e1aad3e41fcd78f3b1264a
1 #!/usr/bin/env perl
3 use Tie::LevelDB;
4 use Data::Dumper;
5 use feature 'switch';
8 if(scalar @ARGV == 0 or $ARGV[0] =~ /^-?-[h?]/i)
10 print "LevelDB - Commandline Interface for Google's leveldb key-value storage,
11 based on Tie::LeveDB(3pm)
12 Usage: LevelDB <leveldb-directory> <command> [<key> [<value>]]
13 Commands:
14 check exit zero if <leveldb-directory> is a valid leveldb
15 open try to open the database, exit non-zero if failed
17 keys enumerate all keys line-by-line
18 show display all keys and values in KEY<TAB>VALUE<LF> format
19 get KEY print the value of KEY
21 set KEY VAL set the value of KEY to VAL unless already equals to VAL
22 default KEY VAL set the value of KEY unless KEY is already set
23 replace KEY VAL set the value of KEY unless KEY does not exist
24 alter KEY VAL same as 'set' but force writes
25 del KEY remove KEY
27 merge [FILE] import all key-value pairs from FILE or STDIN in KEY<TAB>VALUE<LF> format
28 merge-default [FILE] same as 'merge' but sets only unset keys
29 merge-replace [FILE] same as 'merge' but sets only already existing keys
31 exit 1;
35 if($ARGV[1] eq 'check')
37 if(-f $ARGV[0]."/LOG" and -f $ARGV[0]."/CURRENT")
39 eval { new Tie::LevelDB::DB($ARGV[0]); 1; };
40 if($@)
42 if($@ =~ /^IO error: lock/)
44 exit 0;
46 die $@;
48 exit 0;
50 exit 1;
53 sub keyexists
55 return !! grep {$_ eq $_[0]} keys %DB;
58 if($ARGV[1] =~ /^(keys|show|merge|merge-default|merge-replace|get|set|alter|replace|default|del|open)$/)
60 tie %DB, 'Tie::LevelDB', $ARGV[0];
62 given($ARGV[1])
64 when('keys')
66 print "$_\n" for sort {lc $a cmp lc $b} keys %DB;
68 when('show')
70 print "$_\t$DB{$_}\n" for sort {lc $a cmp lc $b} keys %DB;
72 when(/^merge/)
74 if($ARGV[2] ne '')
76 open $fh, '<', $ARGV[2] or die $!;
78 else
80 $fh = \*STDIN;
83 while(<$fh>)
85 if(my ($key, $value) = /^(.+?)\t(.*)$/)
87 given($ARGV[1])
89 when('merge')
91 if(not keyexists($key) or $DB{$key} ne $value)
93 $DB{$key} = $value;
96 when('merge-default')
98 if(not keyexists($key))
100 $DB{$key} = $value;
103 when('merge-replace')
105 if(keyexists($key) and $DB{$key} ne $value)
107 $DB{$key} = $value;
112 else
114 warn "Invalid input: $_";
118 when('get')
120 print $DB{$ARGV[2]};
122 when('alter')
124 $DB{$ARGV[2]} = $ARGV[3];
126 when('set')
128 if(not keyexists($ARGV[2]) or $DB{$ARGV[2]} ne $ARGV[3])
130 $DB{$ARGV[2]} = $ARGV[3];
133 when('replace')
135 if(keyexists($ARGV[2]))
137 $DB{$ARGV[2]} = $ARGV[3];
140 when('default')
142 if(not keyexists($ARGV[2]))
144 $DB{$ARGV[2]} = $ARGV[3];
147 when('del')
149 delete $DB{$ARGV[2]};
151 when('open')
157 else
159 warn "Invalid command: $ARGV[1]\n";
160 exit 1;
163 __END__
165 =pod
167 =head1 NAME
169 LevelDB - Commandline interface for Google's leveldb key-value storage
171 =cut