• Stars
    star
    178
  • Rank 207,724 (Top 5 %)
  • Language
    Shell
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Run a query in psql and output the result as CSV.

psql2csv

Run a query in psql and output the result as CSV.

Installation

Mac OS X

psql2csv is available on Homebrew.

$ brew install psql2csv

Manual

Grab the file psql2csv, put in somewhere in your $PATH, and make it executable:

$ curl https://raw.githubusercontent.com/fphilipe/psql2csv/master/psql2csv > /usr/local/bin/psql2csv && chmod +x /usr/local/bin/psql2csv

Usage

psql2csv [OPTIONS] < QUERY
psql2csv [OPTIONS] QUERY

Options

The query is assumed to be the contents of STDIN, if present, or the last argument. All other arguments are forwarded to psql except for these:

-?, --help                 show this help, then exit
--delimiter=DELIMITER      set the field delimiter (default: ,)
--quote=QUOTE              set the quote delimiter (default: ")
--escape=ESCAPE            set the escape character (default: QUOTE)
--null=NULL                set the string representing NULL; printed without quotes (default: empty string)
--force-quote=FORCE_QUOTE  set the columns to be force quoted; comma separated list of columns or * for all (default: none)
--encoding=ENCODING        set the output encoding; Excel likes latin1 (default: UTF8)
--no-header                do not output a header
--timezone=TIMEZONE        set the timezone config before running the query
--search-path=SEARCH_PATH  set the search_path config before running the query
--dry-run                  print the COPY statement that would be run without actually running it

Example Usage

$ psql2csv dbname "select * from table" > data.csv

$ psql2csv dbname < query.sql > data.csv

$ psql2csv --no-header --delimiter=$'\t' --encoding=latin1 dbname <<sql
> SELECT *
> FROM some_table
> WHERE some_condition
> LIMIT 10
> sql

Advanced Usage

Let's assume you have a script monthly_report.sql that you run every month. This script has a WHERE that limits the report to a certain month:

WHERE date_trunc('month', created_at) = '2019-01-01'

Every time you run it you have to edit the script to change the month you want to run it for. Wouldn't it be nice to be able to specify a variable instead?

Turns out psql does have support for variables which you can pass to psql (and thus to psql2csv) via -v, --variable, or --set. To interpolate the variable into the query you can use :VAR for the literal value, :'VAR' for the value as a string, or :"VAR" for the value as an identifier.

Let's change the WHERE clause in monthly_report.sql file to use a variable instead:

WHERE date_trunc('month', created_at) = (:'MONTH' || '-01')::timestamptz

With this change we can now run the query for any desired month as follows:

$ psql2csv -v MONTH=2019-02 < monthly_report.sql > data.csv

Further Help

Author

Philipe Fatio (@fphilipe)

More Repositories

1

premailer-rails

CSS styled emails without the hassle.
Ruby
1,663
star
2

PHFComposeBarView

Compose bar from iOS 7 Messages.app
Objective-C
1,182
star
3

i18n-debug

Ever wondered which translations are being looked up by Rails, a gem, or simply your app? Wonder no more!
Ruby
180
star
4

PageExtender.app

Safari extension that injects custom CSS and JS files based on page host.
Swift
141
star
5

warden-github-rails

Use GitHub as authorization and more. Use organizations and teams as means of authorization by simply wrapping your rails routes in a block. Also useful to get a user's details through OAuth.
Ruby
99
star
6

PHFDelegateChain

Easily create delegation chains
Objective-C
52
star
7

PHFRefreshControl

YAPTRâ„¢: Yet another pull-to-refresh
Objective-C
48
star
8

resque-async_deliver

Deliver mails asynchronously using Resque without explicitly creating a performable job.
Ruby
31
star
9

dotfiles

My precious dotfiles
Vim Script
22
star
10

PHFArrayComparator

Animated table updates made easy.
Objective-C
20
star
11

xipio

Make xip.io play nicely with subdomains in rails development mode.
Ruby
18
star
12

push_builder

Easily construct JSON payloads for Apple's push notification service.
Ruby
11
star
13

bundler-private_install

https://phili.pe/posts/loading-additional-ruby-gems-in-development/
Ruby
6
star
14

ETH-MAVT-Zusammenfassungen

Zusammenfassungen für Maschinenbau Studiengang an der ETH Zürich – von Philipe Fatio
6
star
15

premailer-rails3

This project moved to https://github.com/fphilipe/premailer-rails
2
star
16

todo.wdgt

To Do is a lightweight and fast widget to manage tasks.
JavaScript
1
star