[英]psql - read SQL file and output to CSV
我有一個 SQL 文件my_query.sql
:
select * from my_table
使用psql
,我可以在這個 sql 文件中讀取:
\\i my_query.sql
或者將其作為參數傳遞:
psql -f my_query.sql
我可以將查詢字符串的結果輸出到 csv:
\\copy (select * from my_table) to 'output.csv' with csv header
有沒有辦法將這些組合起來,以便我可以將查詢結果從 SQL 文件輸出到 CSV?
不幸的是,這里沒有內置功能,因此您需要一點 bash-fu 才能使其正常工作。
CONN="psql -U my_user -d my_db"
QUERY="$(sed 's/;//g;/^--/ d;s/--.*//g;' my_query.sql | tr '\n' ' ')"
echo "\\copy ($QUERY) to 'out.csv' with CSV HEADER" | $CONN
sed
fun 刪除所有分號、注釋行和行尾注釋, tr
將換行符轉換為空格(如@abelisto 的評論中所述):
-- my_query.sql
select *
from my_table
where timestamp < current_date -- only want today's records
limit 10;
變成:
select * from my_table where timestamp < current_date limit 10
然后傳遞給有效的psql
命令:
\copy (select * from my_table where timestamp < current_date) to 'out.csv' with csv header
這是一個腳本:
sql_to_csv.sh
#!/bin/bash
# sql_to_csv.sh
CONN="psql -U my_user -d my_db"
QUERY="$(sed 's/;//g;/^--/ d;s/--.*//g;' $1 | tr '\n' ' ')"
echo "$QUERY"
echo "\\copy ($QUERY) to '$2' with csv header" | $CONN > /dev/null
./sql_to_csv.sh my_query.sql out.csv
您可以使用 bash 腳本來完成。
dump_query_to_csv.sh:
#!/bin/bash
# Takes an sql query file as an argument and dumps its results
# to a CSV file using psql \copy command.
#
# Usage:
#
# dump_query_to_csv.sh <sql_query_file> [<csv_output_filesname>]
SQL_FILE=$1
[ -z $SQL_FILE ] && echo "Must supply query file" && exit
shift
OUT_FILE=$1
[ -z $OUT_FILE ] && OUT_FILE="output.csv" # default to "output.csv" if no argument is passed
TMP_TABLE=ttt_temp_table_xx # some table name that will not collide with existing tables
## Build a psql script to do the work
PSQL_SCRIPT=temp.psql
# create a temporary database table using the SQL from the query file
echo "DROP TABLE IF EXISTS $TMP_TABLE;CREATE TABLE $TMP_TABLE AS" > $PSQL_SCRIPT
cat $SQL_FILE >> $PSQL_SCRIPT
echo ";" >> $PSQL_SCRIPT
# copy the temporary table to the output CSV file
echo "\copy (select * from $TMP_TABLE) to '$OUT_FILE' with csv header" >> $PSQL_SCRIPT
# drop the temporary table
echo "DROP TABLE IF EXISTS $TMP_TABLE;" >> temp.sql
## Run psql script using psql
psql my_database < $PSQL_SCRIPT # replace my_database and add user login credentials as necessary
## Remove the psql script
rm $PSQL_SCRIPT
您需要編輯腳本中的psql
行以連接到您的數據庫。 還可以增強腳本以將數據庫和帳戶憑據作為參數。
接受的解決方案是正確的,但我有 Windows 並且必須通過批處理(命令)文件運行它。 如果有人需要,請在此處發布
@echo off
echo 'Reading file %1'
set CONN="C:\Program Files\PostgreSQL\11\bin\psql.exe" -U dbusername -d mydbname
"C:\Program Files\Git\usr\bin\sed.exe" 's/;//g;/^--/ d;s/--.*//g;' %1 | "C:\Program Files\Git\usr\bin\tr.exe" '\n' ' ' > c:\temp\query.txt
set /p QUERY=<c:\temp\query.txt
echo %QUERY%
echo \copy (%QUERY%) to '%2' WITH (FORMAT CSV, HEADER) | %CONN%
我認為最簡單的方法是利用shell的變量擴展能力:
psql -U my_user -d my_db -c "COPY ($(cat my_query.sql)) TO STDOUT WITH CSV HEADER" > my_query_results.csv
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.