Skip to content

Instantly share code, notes, and snippets.

@jpignata
Created November 23, 2009 17:55
Show Gist options
  • Save jpignata/241231 to your computer and use it in GitHub Desktop.
Save jpignata/241231 to your computer and use it in GitHub Desktop.
begin
mysql = DBI.connect("DBI:Mysql:source:localhost", "username", "password")
pg = DBI.connect("DBI:Pg:destination:localhost", "username", "password")
mysql.execute("SET NAMES 'UTF8'")
mysql.select_all("SHOW TABLES") do |table|
next if ['schema_migrations', 'sessions'].include?(table.to_s)
select = mysql.execute("SELECT * FROM #{table}")
columns = select.column_names.map { |key| "\"#{key}\"" }.join(', ')
insert = pg.prepare("INSERT INTO #{table} (#{columns}) VALUES(#{(['?'] * select.column_names.size).join(',')})")
select.each do |row|
insert.execute(*row)
puts "Inserted ID #{row['id']} into #{table}"
end
insert.finish
pg.execute("SELECT setval('#{table}_id_seq', max(id), true) FROM #{table}") if select.column_names.include?('id')
end
rescue DBI::DatabaseError => e
puts "Error #{e.err}: #{e.errstr}"
ensure
mysql.disconnect if mysql
pg.disconnect if pg
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment