Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Created June 29, 2012 16:41
Show Gist options
  • Save bil-bas/3019083 to your computer and use it in GitHub Desktop.
Save bil-bas/3019083 to your computer and use it in GitHub Desktop.
class Table < ActiveRecord::Base
self.table_name = "magi.tables"
has_many :headers
#--------------------------------------------------------------------------------------------------#
def self.generate
@tables = Table.select([:id, :source_database, :current_name, :magi_name])
@headers = Header.select([:id, :table_id, :current_name, :magi_name]) #refactor to call this in the loop
File.new("magi_generation.sql", "w")
@tables.each do |table|
File.open("magi_generation.sql", "a+") do |file|
file.puts "#Drops current view #{table[:magi_name]} and then recreates it using updated columns"
file.puts "DROP VIEW IF EXISTS `#{table[:magi_name]}`;"
file.puts "CREATE ALGORITHM=UNDEFINED DEFINER=`fed_write`@`127.0.0.1` SQL SECURITY DEFINER VIEW `#{table[:magi_name]}`"
file.puts "AS select"
@headers.each do |header|
file.puts "`#{table[:source_database]}`.`#{table[:current_name]}`.`#{header[:current_name]}` AS `#{header[:magi_name]}`#{"," unless @headers.last == header}" if header[:table_id] == table[:id]
end
file.puts "FROM `#{table[:source_database]}`.`#{table[:current_name]}`;"
file.puts ""
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment