Skip to content

Instantly share code, notes, and snippets.

@aruprakshit
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruprakshit/eedb8c01671c81ce2f67 to your computer and use it in GitHub Desktop.
Save aruprakshit/eedb8c01671c81ce2f67 to your computer and use it in GitHub Desktop.
Rake task to import data from text file to Postgresl table.
desc "import task"
task :import, [:username, :password, :dbname, :path] do |t, args|
sh <<-SQL
PGPASSWORD=#{args[:password]} psql --username=#{args[:username]} --dbname=#{args[:dbname]} << EOF
\\copy films from #{args[:path]} (DELIMITER E'\t');
EOF
SQL
end
[arup@Ruby]$ cat /home/arup/Ruby/out1.txt
foo bar 1233
asd bvs 1236[arup@Ruby]$
[arup@Ruby]$ PGPASSWORD=postgres psql --username=postgres --dbname=postgres
psql (9.2.7)
Type "help" for help.
postgres=# select * from films;
code | title | did
-------+-------+------
foo | bar | 1233
asd | bvs | 1236
(2 rows)
postgres=# delete from films;
DELETE 2
postgres=# select * from films;
code | title | did
------+-------+-----
(0 rows)
postgres=# \q
[arup@Ruby]$ rake import[postgres,postgres,postgres,/home/arup/Ruby/out1.txt]
PGPASSWORD=postgres psql --username=postgres --dbname=postgres << EOF
\copy films from /home/arup/Ruby/out1.txt (DELIMITER E' ');
EOF
[arup@Ruby]$ PGPASSWORD=postgres psql --username=postgres --dbname=postgres
psql (9.2.7)
Type "help" for help.
postgres=# select * from films;
code | title | did
-------+-------+------
foo | bar | 1233
asd | bvs | 1236
(2 rows)
postgres=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment