Skip to content

Instantly share code, notes, and snippets.

@gabecoyne
Last active December 14, 2015 15:58
Show Gist options
  • Save gabecoyne/5111202 to your computer and use it in GitHub Desktop.
Save gabecoyne/5111202 to your computer and use it in GitHub Desktop.
class Warehouse < ActiveRecord::Base
# Data Warehousing AR
# - create env_warehouse definitions in database.yml
# - RAILS_ENV=env_warehouse rake db:schema:load
# - Warehouse.archive_all on some interval (daily, hourly, etc)
# - Truncate un-needed data from prod database!
if ENV["DATABASE_WAREHOUSE_URL"].present? # for heroku since it overwrites the database.yml
establish_connection ENV["DATABASE_WAREHOUSE_URL"]
else
establish_connection "#{Rails.env}_warehouse"
end
def self.sql(*query)
sql = sanitize_sql_array(query)
puts "Warehouse: #{sql}" unless Rails.env.test?
self.connection.execute(sql)
end
def self.count(table)
sql("select count(*) from #{table}").first["count"].to_i
end
def self.archive(table)
ar_class = eval table.singularize.camelcase rescue nil
return false if ar_class.nil?
latest_in_warehouse = sql("select created_at from #{table} order by created_at desc limit 1").first['created_at'].to_time rescue Time.now - 100.years
ar_class.where('created_at > ?', latest_in_warehouse).find_each do |r|
# sql("insert into #{table} values (?)", r.attributes.values)
sql("insert into #{table} (#{r.attributes.keys.join(", ")}) values (?)", r.attributes.values)
end
end
def self.archive_all
ActiveRecord::Base.connection.tables.sort.each do |table|
archive table
end
end
# Un-Tested recover
# def self.recover(table, scope = "")
# ar_class = eval table.singularize.camelcase rescue nil
# return false if ar_class.nil?
# sql("select * from #{table} #{scope}").each do |r|
# ar_class.create(r) rescue nil # if there is a duplicate id in the scope selected
# end
# end
# def self.recover_all
# ActiveRecord::Base.connection.tables.sort.each do |table|
# recover table
# end
# end
def self.truncate_all # ONLY FOR TEST SUITE
return false unless Rails.env.test?
ActiveRecord::Base.connection.tables.sort.each do |table|
sql "truncate #{table}"
end
end
# everything below here is just to make this model work without a table
def self.columns
@columns ||= [];
end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
# Override the save method to prevent exceptions.
def save(validate = true)
validate ? valid? : true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment