sqlite-csv/sqlite-csv.fish

59 lines
1.6 KiB
Fish
Raw Normal View History

2023-09-29 16:45:37 +02:00
function sqlite-csv
argparse --exclusive csv,md,json json csv md 'sep=?' help -- $argv
if set -q _flag_help
echo "\
Usage: sqlite-csv [options] [<csv>] [<sql-command>]
If no <csv> file is specified, it will be read from stdin.
If no <sql-command> is specified, uses 'select * from data'.
If no output format is specified, uses ASCII box rendering.
Options:
--csv output as CSV using a , separator
--md ouput as markdown
--json output as JSON
--sep=SEP use SEP as the column separator when reading the CSV file (e.g. --sep=';')
--help show this message and exit
The imported CSV table is named `data`.
Example: sqlite-csv --md summary.csv 'select * from data order by name'"
return
end
if set -q _flag_csv
set outputMode "csv"
else if set -q _flag_md
set outputMode "markdown"
else if set -q _flag_json
set outputMode "json"
else
set outputMode "box"
end
if set -q _flag_sep
set insep $_flag_sep
else
set insep ","
end
# Check if first arg is a file that exists;
# if it isn't, read from stdin
if test "x$argv[1]" != "x"
and test -e $argv[1]
set db $argv[1]
set query $argv[2..]
else
set db "|cat -"
set query $argv[1..]
end
# If no query is specified, dump all columns
if test -z $query
set query 'select * from data'
end
sqlite3 :memory: -cmd '.mode csv' -cmd ".separator $insep" -cmd ".import '$db' data" -cmd ".mode $outputMode --wrap 120" "$query"
end