Skip to content

Instantly share code, notes, and snippets.

@rah00l
Created February 26, 2016 18:36
Show Gist options
  • Save rah00l/3610ef1aa18b587bcd34 to your computer and use it in GitHub Desktop.
Save rah00l/3610ef1aa18b587bcd34 to your computer and use it in GitHub Desktop.
Populate 1 Million Records
#-----------IT TAKES AROUND 20 MIN -------------------
## Associations are as follw ::
## Book ---> (has_many) FileSubmissions
## FileSubmission --> (has_one) FileDetail
## Flush all dependent records:
FileDetail.delete_all
FileSubmission.delete_all
Book.delete_all
## Alter tables to generate data always with id 1 and increment it from there
Book.connection.execute "ALTER TABLE `books` AUTO_INCREMENT = 1;"
FileSubmission.connection.execute "ALTER TABLE `books` AUTO_INCREMENT = 1;"
FileDetail.connection.execute "ALTER TABLE `books` AUTO_INCREMENT = 1;"
Book.transaction do
start = Time.now.to_i
1.upto(1000000) do |i|
date = rand(30.day).seconds.ago.to_s :db
Book.connection.execute "INSERT INTO `books` (`id`,`isbn`, `created_at`, `updated_at`) VALUES (#{i}, #{i}, '#{date}', '#{date}')" ;
FileSubmission.connection.execute "INSERT INTO `file_submissions` (`id`,`book_id`,`original_name`,`created_at`, `updated_at`)
VALUES (#{i}, #{i}, '#{Array.new(12){[*'a'..'z', *'A'..'Z'].sample}.join}', '#{date}', '#{date}')" ;
FileDetail.connection.execute "INSERT INTO `file_details` (`id`,`file_submission_id`, `created_at`, `updated_at`)
VALUES (#{i}, #{i}, '#{date}', '#{date}')" ;
end time = Time.now.to_i - start
p "Time taken in seconds #{time}"
end
#---------------- SCRIPT END ---------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment