psql2csv Run a query in psql and output the result开源项目

我要开发同款
匿名用户2021年11月17日
32阅读
开发技术JavaScript
所属分类应用工具、终端/远程登录
授权协议MIT License

作品详情

psql2csv

RunaqueryinpsqlandoutputtheresultasCSV.

InstallationMacOSX

psql2csvisavailableonHomebrew.

$brewinstallpsql2csvManual

Grabthefilepsql2csv,putinsomewhereinyour$PATH,andmakeitexecutable:

$curlhttps://raw.githubusercontent.com/fphilipe/psql2csv/master/psql2csv>/usr/local/bin/psql2csv&&chmod+x/usr/local/bin/psql2csvUsagepsql2csv[OPTIONS]<QUERYpsql2csv[OPTIONS]QUERYOptions

ThequeryisassumedtobethecontentsofSTDIN,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>sqlAdvancedUsage

Let'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')::timestamptz

Withthischangewecannowrunthequeryforanydesiredmonthasfollows:

$psql2csv-vMONTH=2019-02<monthly_report.sql>data.csvFurtherHelpPostgreSQLCOPYdocumentationpsqlvariablesAuthor

PhilipeFatio(@fphilipe)

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论