-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbashdb
More file actions
1994 lines (1776 loc) · 46.3 KB
/
bashdb
File metadata and controls
1994 lines (1776 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, June 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/gpl-2.0.html>
# Copyright 2017 - Øyvind Hvidsten <bolt@dhampir.no>
# Description:
#
# Library to interact with a simple two dimensional table stored as pipe separated
# base64 encoded strings in a flat file. A simplistic database relying on very few
# external tools.
#
# Functions are provided for adding and removing data to a dynamic table structure.
# The library supports column names, searching, and pretty printing of table data.
#
# URL: https://blog.dhampir.no/content/bashdb-a-single-dynamic-database-table-for-bash-scripts
#
# v1.00, 2017.10.09 - Initial v1.0 release
# * All intended functionality implemented
#
# v1.01, 2017.10.11 - More features!
# * Added -i <index> switch to db_set for list index insert
# Without -i new items are added to the end as before
# * Added db_rename and db_rename_column to rename keys and columns
# * db_haskey renamed to db_has_key
# * Added db_has_column
# * Better error handling
# * Various minor bugfixes
#
# v1.02, 2017.10.12 - Temp file issues
# * More verbose handling of failing to create temporary files
#
# v1.03, 2017.10.13 - Better errors
# * When superfluous parameters are entered, they are now printed for
# easier debugging.
#
# v1.04, 2017.10.14 - Long key dumps
# * Fixed output of dumps with long keys
# * Much faster has_key function
# * Added ability to look for a key by regex using db_keys -r
# * Much faster search function
#
# v1.05, 2017.10.24 - List value searching
# * Fixed a crash that would happen if attempting to search on a
# column containing list values. As a slight bonus, the regex is
# now evaluated for each item in a list
#
# v1.06, 2017.11.17 - Verify
# * Expose internal db verification function through db_verify
#
# v1.07, 2017.11.25 - Allow empty default
# * When specifying -d, empty strings are allowed
#
# include guard (..ish)
if [[ -z "${_db_loaded:-}" ]]; then
_db_loaded=true
else
return 0
fi
# needed for runfunc to find the functions
_bashdb_header="db_"
# show the help!
function db_help
{
# intro
_db_println "BashDB help" >&2
# basics
db_verify -?
db_set -?
db_get -?
db_dump -?
# list
db_keys -?
db_columns -?
# copy
db_copy_row -?
# rename
db_rename -?
db_rename_column -?
# searching
db_has_key -?
db_has_column -?
db_search -?
# cleanup
db_delete -?
db_delete_column -?
db_trim -?
# testing
db_testdb -?
db_selftest -?
}
# print help
function _db_help
{
{
_db_println
_db_println " ---------- ${FUNCNAME[1]} ----------"
sed 's/\t/\ \ /g'
_db_println
} >&2
}
# printing stuff
function _db_print { printf '%s' "$*" 2>/dev/null; }
function _db_println { printf '%s\n' "$*" 2>/dev/null; }
function _db_print0 { printf '%s\0' "$*" 2>/dev/null; }
function _db_usage { _db_println "Usage: ${FUNCNAME[1]} $*" >&2; }
function _db_error { _db_println "Error: $*" >&2; }
function _db_func_error { _db_println "Error: ${FUNCNAME[1]}: $*" >&2; }
function _db_badarg { _db_error '%s\n' "${FUNCNAME[1]}: Option -${OPTARG} requires an argument"; }
function _db_badopt { _db_error "${FUNCNAME[1]}: Unknown option -${OPTARG}"; }
function _db_debug { ! ${DB_DEBUG:-false} || printf 'DEBUG: %s %s\n' "${FUNCNAME[1]}" "$*" >&2 2>/dev/null; }
function _db_noparam { _db_error "${FUNCNAME[1]}: Missing parameter: $*"; }
function _db_extra_opt { _db_error "${FUNCNAME[1]}: Unknown parameter: $*"; ${FUNCNAME[1]} -?; }
function _db_print_end { if ${1:-false}; then _db_println; else _db_print0; fi; }
function _db_print_pad { _db_print "$2"; local pad; pad=$(($1 - ${#2})); if ((pad > 0)); then printf "%$(($1 - ${#2}))s" 2>/dev/null; fi; }
function _db_tsprint { _db_print "$(date +'%Y-%m-%d %H:%M:%S (%z)') - $*"; }
# read opts
function _db_read_opt
{
if [[ -z "$OPTARG" ]] && ${3:-true}; then
_db_error "${FUNCNAME[1]}: Option (-${opt}) can not be empty"
return 1
elif [[ -z "${!1:-}" ]]; then
if ${2:-false}; then
printf -v "$1" '%s' "${OPTARG,,}"
else
printf -v "$1" '%s' "$OPTARG"
fi
else
_db_error "${FUNCNAME[1]}: Option (-${opt}) can not be specified more than once"
return 1
fi
}
# check that a database exists, or create it
function _db_check
{
_db_debug "$@"
# options
local write=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":w" opt; do
case "$opt" in
w) write=true ;;
[?]) _db_badopt; return 1 ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# read column spec
local file=$1 colspec
if ! [[ -e "$file" ]] && ! touch "$file" 2>/dev/null; then
_db_error "Failed to create database: $file"
return 1
fi
# check permissions
[[ -f "$file" ]] || { _db_error "$file is not a regular file!"; return 1; }
[[ -r "$file" ]] || { _db_error "File $file is not readable!"; return 1; }
! $write || [[ -w "$file" ]] || { _db_error "File $file is not writable!"; return 1; }
}
# verify that a database is relatively ok...
function db_verify
{
_db_debug "$@"
# options
local file
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?f:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Verify that a database file is good to use
REQUIRED:
-f <file>
The path to a database file
EOF
return 0
;;
f) _db_read_opt file ;;
[?]) _db_badopt; return 1 ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check "$file" || return 1
# nothing to do here...
}
# reading files
function _db_get_data { grep -v "^bashdb|" "$1"; }
function _db_get_head { grep -m 1 "^bashdb|" "$1"; }
function _db_get_row { grep -m 1 "^${2}|" "$1"; }
# get the columns
function _db_get_cols
{
_db_debug "$@"
# options
local file
local OPTIND=1 OPTARG OPTERR opt
while getopts ":f:" opt; do
case "$opt" in
f) _db_read_opt file ;;
[?]) _db_badopt; return 1 ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check "$file" || return 1
# read the first line (the colspec)A
local line
line=$(head -n 1 "$file")
# verify that this is a database or an empty file
if [[ "$line" != "bashdb|"* ]] && (( $(stat "$file" --format='%s') )); then
_db_error "Invalid database file: $file"
return 1
fi
# return
_db_print "${line#bashdb}"
}
# check if colspec has column
function _db_colspec_contains
{
_db_debug "$@"
local cols=$1 col=$2
[[ "${cols}|" = *"|${col}|"* ]]
}
# get index of column in return value from _db_get_cols
function _db_get_col_index
{
_db_debug "$@"
local column=$1 colspec=$2 index=0 n
while read -d '|' -r n; do
[[ "$n" != "$column" ]] || break
(( ++index ))
done <<<"${colspec#|}|"
_db_print "$index"
}
# encode/decode
function _db_encode
{
if (( $# )); then
_db_print "$*" | base64 -w 0
else
base64 -w 0
fi
}
function _db_decode { base64 -d 2>/dev/null; }
# get a value
function db_get
{
_db_debug "$@"
# options
local file key colname="" default="" use_default=false index human=false zero=false colspec column value
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?c:d:f:hi:k:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Set or unset (set to empty) a value in the table
REQUIRED:
-f <file>
The path to a database file
-k <key>
Which key to get
OPTIONS:
-c <column>
Which column to get
If this is not specified, the default unnamed column is used
-d <value>
A default value to display if the requested one is unset
-0
Append a null byte (\0) to the output, even if the value is not a list
-h
Append a newline to the output
-i <index>
When dealing with list values, get a single item from the list
Indexes start from 0 for the first item
EOF
return 0
;;
0) zero=true ;;
c) colname=$(_db_encode "${OPTARG,,}") ;;
d) default=$OPTARG; use_default=true ;;
f) _db_read_opt file ;;
h) human=true ;;
i) index=$OPTARG ;;
k) _db_read_opt key true ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
[[ -n "${key:-}" ]] || { _db_noparam "-k <key>"; return 1; }
[[ "${index:-0}" =~ [0-9]+ ]] || { _db_func_error "Invalid index: $index"; return 1; }
! $human || ! $zero || { _db_func_error "-0 and -h are mutually exclusive"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check "$file" || return 1
# find column
colspec=$(_db_get_cols -f "$file")
if _db_colspec_contains "$colspec" "$colname"; then
column=$(_db_get_col_index "$colname" "$colspec")
# encode key
key=$(_db_encode "$key")
# find value
value=$(_db_get_row "$file" "$key" | cut -d '|' -f $((column+2)))
else
value=""
fi
# print value
if [[ -n "$value" ]]; then
if [[ "$value" != *','* ]] && [[ -z "${index:-}" ]]; then
_db_print "$value" | _db_decode
if $human || $zero; then
_db_print_end "$human"
fi
return 0
else
local i=0
# print the correct index, or all of them if index is unset
while read -r -d ',' value; do
[[ -z "${index:-}" ]] || (( i++ == index )) || continue
_db_print "$value" | _db_decode
_db_print_end "$human"
[[ -z "${index:-}" ]] || return 0
done <<<"${value},"
# if we get here with an index, it's bad. otherwise, everything is fine
[[ -z "${index:-}" ]] && return 0 || return 1
fi
fi
# ..or the default
if $use_default; then
_db_print "$default"
if $human || $zero; then
_db_print_end "$human"
fi
else
return 1
fi
}
# get a temp file in a variable
function _db_mktemp
{
_db_debug "$@"
while (( $# )); do
if [[ -n "${TMP:-}" ]]; then
while true; do
printf -v "$1" '%s' "${TMP}/bashdb.$$.${RANDOM}.tmp"
if ! [[ -e "${!1}" ]]; then
>"${!1}"
break
fi
done
elif type mktemp >/dev/null 2>&1; then
printf -v "$1" '%s' "$(mktemp)" || exit $?
else
_db_error 'Could not create temp file. Either set $TMP or install mktemp'
exit 1
fi
chmod 600 "${!1}"
shift
done
}
# remove a key
function db_delete
{
_db_debug "$@"
# options
local file key
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?f:k:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Delete a row from the table
REQUIRED:
-f <file>
The path to a database file
-k <key>
The key to delete
EOF
return 0
;;
f) _db_read_opt file ;;
k) _db_read_opt key true ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
[[ -n "${key:-}" ]] || { _db_noparam "-k <key>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check -w "$file" || return 1
# check for existence
if ! db_has_key -f "$file" -k "$key"; then
_db_func_error "No such key: $key"
return 1
fi
# encode key
key=$(_db_encode "$key")
# remove
(
_db_mktemp tmp
trap "rm \"$tmp\"" EXIT
grep -v "^${key}|" "$file" >"$tmp"
cat "$tmp" >"$file"
)
}
# copy a database to a new table, possibly excluding a single column
# used internally to trim empty columns and to remove columns on command
function _db_copy
{
_db_debug "$@"
# sanity
(( $# == 2 )) || (( $# == 3 )) || { _db_usage "<source> <target> [exclude column]"; return 1; }
local src=$1 tgt=$2
_db_check "$src" || return 1
_db_check -w "$tgt" || return 1
[[ "$src" != "$tgt" ]] || { _db_func_error "Source file can not equal target"; return 1; }
if (( $(stat "$tgt" --format='%s') )); then
_db_func_error "Target file \"$tgt\" is not empty"
return 1
fi
# read columns and base lengths
local columns=( )
while read -r -d $'\0' col; do
columns+=( "$col" )
done < <(db_columns -f "$src")
# find empty columns
local i
for ((i="$(( ${#columns[@]} - 1 ))"; i >= 0; i--)); do
if
{ (( $# != 3 )) || [[ "${columns[i]}" != "$3" ]]; } &&
_db_get_data "$src" | cut -d '|' -f "$((i+2))" | grep -q -m 1 -v "^$"
then
columns[i]="$((i+2))"
else
unset columns[i]
fi
done
# copy
cut -d '|' -f "1,$( IFS=','; _db_print "${columns[*]:-}"; )" "$src" | grep -E -v "^[^|]+[|]+$" >"$tgt"
}
# use _db_copy to remove a column
function db_delete_column
{
_db_debug "$@"
# options
local file colname
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?c:f:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Delete a column from all rows in a table
REQUIRED:
-f <file>
The path to a database file
OPTIONS:
-c <column>
The column to delete
If none is specified, we will look for the default column
EOF
return 0
;;
c) _db_read_opt colname true false ;;
f) _db_read_opt file ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check -w "$file" || return 1
# check that the column exists
local col found=false
while read -r -d $'\0' col; do
if [[ "$col" = "${colname:-}" ]]; then
found=true
break
fi
done < <(db_columns -f "$file" 2>/dev/null)
if ! $found; then
if [[ -n "$colname" ]]; then
_db_func_error "Table has no such column: $colname"
else
_db_func_error "Table has no default column to remove"
fi
return 1
fi
# write to database
(
_db_mktemp tmp
trap "rm \"$tmp\"" EXIT
_db_copy "$file" "$tmp" "${colname:-}"
cat "$tmp" >"$file"
)
}
# trim a table, removing unused columns
function db_trim
{
_db_debug "$@"
# options
local file
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?f:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Trim a table, removing all columns that are unset in all rows
There's normally no reason to do this, as empty columns aren't a substantial performance issue,
and you might want to use them again later.
REQUIRED:
-f <file>
The path to a database file
EOF
return 0
;;
f) _db_read_opt file ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check -w "$file" || return 1
# copy
(
_db_mktemp tmp
trap "rm \"$tmp\"" EXIT
_db_copy "$file" "$tmp"
cat "$tmp" >"$file"
)
}
# search for a key given a full or partial value
function db_search
{
_db_debug "$@"
# options
local file regex colname="" dump=false human=false partial=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?c:dhf:r:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Searches for keys where a given column matches a regular expression
REQUIRED:
-f <file>
The path to a database file
-r <regex>
The regular expression used to match values
OPTIONS:
-d
Dump the results using db_dump instead of listing keys
-h
Human readable output. Replaces the default null byte (\0) key separator with a newline
-c <column>
The column to search in
The default column is used if this is not provided
EOF
return 0
;;
c) _db_read_opt colname true false ;;
d) dump=true ;;
f) _db_read_opt file ;;
h) human=true ;;
r) _db_read_opt regex ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
[[ -n "${regex:-}" ]] || { _db_noparam "-r <regex>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check "$file" || return 1
# encode column
colname=$(_db_encode "$colname")
# find the column
local colspec column
colspec=$(_db_get_cols -f "$file")
if ! _db_colspec_contains "$colspec" "$colname"; then
return 0 # nothing to see here
fi
column=$(_db_get_col_index "$colname" "$colspec")
# find the value
local key value s
while IFS='|' read -r key value; do
while read -r -d ',' s; do
s=$(_db_decode <<<"$s" | _db_print_filter)
if [[ "$s" =~ $regex ]]; then
if $dump; then
dumpopts+=( "-k" "$(_db_decode <<<"$key")" )
else
_db_print "$key" | _db_decode
_db_print_end "$human"
fi
continue 2
fi
done <<<"${value},"
done < <(_db_get_data "$file" | cut -d '|' -f 1,$((column+2)))
# dump?
if [[ -n "${dumpopts[*]:-}" ]]; then
db_dump -f "$file" "${dumpopts[@]}"
fi
}
# set a value
function db_set
{
_db_debug "$@"
# options
local file key values=() colname="" stdin=false colspec column mode index
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?c:f:k:i:Im:v:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Get a value (or a provided default) from a table
REQUIRED:
-f <file>
The path to a database file
-k <key>
Which key to modify
OPTIONS:
-c <column>
Which column to modify
If this is not specified, the default unnamed column is used
-i <index>
When dealing with list values, specify an index to insert the values add
Only makes sense in conjunction with "-m add"
Without -i, added values will be appended to the end of the list
This can also be used to reorder one or more items in the list
Indexes start from 0 for the first item
-I
Read value (text or binary) from standard input (pipe)
Can not be combined with -v
-v <value>
The value to set. Can be specified multiple times
-m <add|remove>
Specifies that the provided values should be added or removed from any existing ones
EOF
return 0
;;
c) colname=$(_db_encode "${OPTARG,,}") ;;
f) _db_read_opt file ;;
k) _db_read_opt key true ;;
m) _db_read_opt mode ;;
i) index=$OPTARG ;;
I) stdin=true ;;
v) [[ -z "$OPTARG" ]] || values+=( "$(_db_encode "$OPTARG")" ) ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
[[ -n "${key:-}" ]] || { _db_noparam "-k <key>"; return 1; }
[[ "${index:-0}" =~ [0-9]+ ]] || { _db_func_error "Invalid index: $index"; return 1; }
case "${mode:-}" in
'') ;;
add|remove) ! $stdin || { _db_func_error "-m and -I are mutually exclusive"; return 1; } ;;
*) _db_func_error "Unknown mode (add|remove): $mode"; return 1 ;;
esac
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check -w "$file" || return 1
# read value from stdin, encode
if $stdin; then
if [[ -n "${values[*]:-}" ]]; then
_db_error "-I was specified while a value parameter was provided"
exit 1
fi
values+=( "$(_db_encode)" )
fi
# find column
colspec=$(_db_get_cols -f "$file")
if ! _db_colspec_contains "$colspec" "$colname"; then
if [[ -n "${values[*]:-}" ]]; then
colspec+="|${colname}"
else
return 0 # no value and no column? nothing to unset
fi
fi
column=$(_db_get_col_index "$colname" "$colspec")
# encode key
key=$(_db_encode "$key")
# write to database
(
_db_mktemp tmp script
trap "rm \"$tmp\" \"$script\"" EXIT
# write everything except our key
_db_println "bashdb${colspec}" >"$tmp"
_db_get_data "$file" | grep -v "^${key}|" >>"$tmp" || :
# get the row
IFS='|' read -r -a row <<<"$(_db_get_row "$file" "$key" || _db_print "$key")"
# create empty columns until the position we want to set
pos=$((column+1))
for (( i=${#row[@]}; i < pos; i++ )); do row[i]=""; done
# add/remove (list) support
case "${mode:-}" in
add)
mapfile -t values < <(
i=0
while read -r -d ',' s; do
[[ -n "$s" ]] || continue
if [[ -n "${index:-}" ]] && (( i == index )); then
( IFS=$'\n'; _db_println "${values[*]}" )
(( ++i ))
fi
for v in "${values[@]}"; do
[[ "${v,,}" != "${s,,}" ]] || continue 2
done
_db_println "$s"
(( ++i ))
done <<<"${row[pos]:-},"
if [[ -z "${index:-}" ]] || (( i <= index )); then
( IFS=$'\n'; _db_println "${values[*]}" )
fi
)
;;
remove)
mapfile -t values < <(
while read -r -d ',' s; do
[[ -n "$s" ]] || continue
for v in "${values[@]}"; do
[[ "${v,,}" != "${s,,}" ]] || continue 2
done
_db_println "$s"
done <<<"${row[pos]:-},"
)
;;
esac
# concatenate new value
row[pos]="$( IFS=','; echo "${values[*]:-}"; )"
# unset empty values at the back of the row
for (( i=${#row[@]}-1; i > 0; i-- )); do
[[ -z "${row[i]}" ]] && unset row[i] || break
done
# if we still have more than just a key, write the row
if (( i )); then
( IFS='|'; _db_println "${row[*]}"; ) >>"$tmp"
fi
# save
cat "$tmp" >"$file"
)
}
# list keys
function db_keys
{
_db_debug "$@"
# options
local file human=false regex=""
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?f:hr:" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Show a list of the keys currently stored in the table
REQUIRED:
-f <file>
The path to a database file
OPTIONS:
-h
Human readable output. Replaces the default null byte (\0) separator with a newline
-r <regex>
Only keys matching this regex will be returned
EOF
return 0
;;
f) _db_read_opt file ;;
h) human=true ;;
r) _db_read_opt regex ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
# sanity
[[ -n "${file:-}" ]] || { _db_noparam "-f <file>"; return 1; }
(( $# == 0 )) || { _db_extra_opt "$@"; return 1; }
_db_check "$file" || return 1
# list
_db_get_data "$file" | cut -d '|' -f 1 | while read -r key; do
if [[ -n "$regex" ]]; then
key=$(_db_decode <<<"$key")
[[ "$key" =~ $regex ]] || continue
_db_print "$key"
else
_db_print "$key" | _db_decode
fi
_db_print_end "$human"
done
}
# list columns
function db_columns
{
_db_debug "$@"
# options
local file human=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":?f:h" opt; do
case "$opt" in
[?])
if [[ "${OPTARG:-}" != '?' ]]; then
_db_badopt
${FUNCNAME[0]} -?
return 1
fi
_db_help <<"EOF"
Show a list of the columns currently stored in the table
REQUIRED:
-f <file>
The path to a database file
OPTIONS:
-h
Human readable output. Replaces the default null byte (\0) separator with a newline
EOF
return 0
;;
f) _db_read_opt file ;;
h) human=true ;;
:) _db_badarg; return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi