RunaqueryinpsqlandoutputtheresultasCSV.
InstallationMacOSXpsql2csvisavailableonHomebrew.
$brewinstallpsql2csvManualGrabthefilepsql2csv,putinsomewhereinyour$PATH,andmakeitexecutable:
$curlhttps://raw.githubusercontent.com/fphilipe/psql2csv/master/psql2csv>/usr/local/bin/psql2csv&&chmod+x/usr/local/bin/psql2csvUsagepsql2csv[OPTIONS]<QUERYpsql2csv[OPTIONS]QUERYOptionsThequeryisassumedtobethecontentsofSTDIN,ifpresent,orthelastargument.Allotherargumentsareforwardedtopsqlexceptforthese:
-?,--helpshowthishelp,thenexit--delimiter=DELIMITERsetthefielddelimiter(default:,)--quote=QUOTEsetthequotedelimiter(default:")--escape=ESCAPEsettheescapecharacter(default:QUOTE)--null=NULLsetthestringrepresentingNULL;printedwithoutquotes(default:emptystring)--force-quote=FORCE_QUOTEsetthecolumnstobeforcequoted;commaseparatedlistofcolumnsor*forall(default:none)--encoding=ENCODINGsettheoutputencoding;Excellikeslatin1(default:UTF8)--no-headerdonotoutputaheader--timezone=TIMEZONEsetthetimezoneconfigbeforerunningthequery--search-path=SEARCH_PATHsetthesearch_pathconfigbeforerunningthequery--dry-runprinttheCOPYstatementthatwouldberunwithoutactuallyrunningitExampleUsage$psql2csvdbname"select*fromtable">data.csv$psql2csvdbname<query.sql>data.csv$psql2csv--no-header--delimiter=$'\t'--encoding=latin1dbname<<sql>SELECT*>FROMsome_table>WHEREsome_condition>LIMIT10>sqlAdvancedUsageLet'sassumeyouhaveascriptmonthly_report.sqlthatyouruneverymonth.ThisscripthasaWHEREthatlimitsthereporttoacertainmonth:
WHEREdate_trunc('month',created_at)='2019-01-01'Everytimeyourunityouhavetoeditthescripttochangethemonthyouwanttorunitfor.Wouldn'titbenicetobeabletospecifyavariableinstead?
Turnsoutpsqldoeshavesupportforvariableswhichyoucanpasstopsql(andthustopsql2csv)via-v,--variable,or--set.Tointerpolatethevariableintothequeryyoucanuse:VARfortheliteralvalue,:'VAR'forthevalueasastring,or:"VAR"forthevalueasanidentifier.
Let'schangetheWHEREclauseinmonthly_report.sqlfiletouseavariableinstead:
WHEREdate_trunc('month',created_at)=(:'MONTH'||'-01')::timestamptzWiththischangewecannowrunthequeryforanydesiredmonthasfollows:
$psql2csv-vMONTH=2019-02<monthly_report.sql>data.csvFurtherHelpPostgreSQLCOPYdocumentationpsqlvariablesAuthorPhilipeFatio(@fphilipe)
评论