The blog has moved to http://jessehouse.com/ ... Many google searches point here so I am leaving it operational, but there will be no new posts.

Sunday, April 29, 2012

postgres: random useful things

Run sql statements from the command line, use the -c flag
psql your_db -c "update users set is_active = 'f';"


create a random value
select md5(random()::text)


crazy updates using regexp_matches
-- changes joe.smith@gmail.com -> joe.smith@qa.com
update users set email = replace(replace(regexp_matches(email, '.*@')::varchar, '{', ''), '}', '') || 'qa.com';
-- there must be a better way to get rid of the {} chars returned by regexp_matches


postgres: terminate all database connections

Using psql from the command line you can terminate all connections to a database

# replace your_db with the name of your database
psql postgres -c "select pg_terminate_backend(procpid) from pg_stat_activity where datname='your_db';"
Comes in handy when you want to do things like restore your staging or development database

psql postgres -c "select pg_terminate_backend(procpid) from pg_stat_activity where datname='your_db';"
dropdb your_db
createdb --template=template0 --encoding=unicode your_db