Created
April 3, 2012 17:25
-
-
Save gnarl/2293884 to your computer and use it in GitHub Desktop.
PG Setup and Backup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'logger' | |
require 'active_record' | |
require 'awesome_print' | |
# edit postgresql.conf, using /tmp/pg for testing | |
# http://www.postgresql.org/docs/9.1/interactive/continuous-archiving.html | |
# wal_level = archive | |
# archive_mode = on | |
# archive_command = 'test ! -f /tmp/pg/%f && cp %p /tmp/pg/%f' | |
PG_SPEC = { | |
:adapter => "postgresql", | |
:username => "charlesfouts", | |
:database => "firstdb", | |
:encoding => 'utf8' | |
} | |
ActiveRecord::Base.logger = Logger.new(STDERR) | |
# drops and create need to be performed with a connection to the 'postgres' (system) database | |
ActiveRecord::Base.establish_connection(PG_SPEC.merge('database' => 'postgres', 'schema_search_path' => 'public')) | |
# drop the old database (if it exists) | |
ActiveRecord::Base.connection.drop_database PG_SPEC[:database] rescue nil | |
# create new | |
ActiveRecord::Base.connection.create_database(PG_SPEC[:database]) | |
ActiveRecord::Base.establish_connection(PG_SPEC) | |
ActiveRecord::Schema.define do | |
create_table :foxes do |t| | |
t.column :name, :string | |
end | |
create_table :trucks do |t| | |
t.column :fox_id, :integer | |
t.column :color, :string | |
t.column :bed, :string | |
end | |
end | |
class Fox < ActiveRecord::Base | |
has_many :trucks | |
end | |
class Truck < ActiveRecord::Base | |
belongs_to :fox | |
end | |
def print_trucks | |
Fox.find(1).trucks.each {|x| ap x } | |
end | |
fox = Fox.create :name => "Grey" | |
fox.trucks.create(:color => "Blue", :bed => "Short") | |
fox.trucks.create(:color => "Orange", :bed => "Long") | |
puts Fox.find(1).trucks.length | |
print_trucks | |
#User needs to have updated the config file | |
puts "Do you want to backup the DB (y/N)?" | |
answer = gets.chomp | |
if answer.eql?('y') | |
sql = "SELECT pg_start_backup('/tmp/pg/backup/')" | |
res = ActiveRecord::Base.connection.execute(sql) | |
res.each {|x| ap x} | |
sleep(5) | |
#"pg_start_backup" => "0/2000020" | |
puts "Copy the backup files and hit enter to continue." | |
nop = gets.chomp | |
sql_stop = "SELECT pg_stop_backup()" | |
res = ActiveRecord::Base.connection.execute(sql_stop) | |
res.each {|x| ap x} | |
puts "okay finished" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment