From d770f21042c1e3199cfb7cca3f1b2a1c395f1558 Mon Sep 17 00:00:00 2001 From: Jonathan Hoyt Date: Mon, 22 Dec 2008 15:35:20 -0500 Subject: [PATCH] Added dialup administration, not as a module [#19 state:resolved] --- app/controllers/radchecks_controller.rb | 38 ++++ app/models/client.rb | 10 ++ app/models/device.rb | 2 +- app/models/radcheck.rb | 16 ++ app/views/clients/_dialup.html.erb | 61 +++++++ app/views/shared/_new_device.html.erb | 3 +- config/routes.rb | 2 + vendor/plugins/use_db/MIT-LICENSE | 20 +++ vendor/plugins/use_db/README | 86 +++++++++ vendor/plugins/use_db/Rakefile | 22 +++ vendor/plugins/use_db/init.rb | 13 ++ vendor/plugins/use_db/install.rb | 1 + vendor/plugins/use_db/lib/migration.rb | 21 +++ .../plugins/use_db/lib/override_fixtures.rb | 32 ++++ .../plugins/use_db/lib/override_test_case.rb | 79 +++++++++ vendor/plugins/use_db/lib/test_model.rb | 11 ++ vendor/plugins/use_db/lib/use_db.rb | 67 +++++++ vendor/plugins/use_db/lib/use_db_test.rb | 152 ++++++++++++++++ vendor/plugins/use_db/tasks/use_db_tasks.rake | 167 ++++++++++++++++++ vendor/plugins/use_db/test/use_db_test.rb | 8 + vendor/plugins/use_db/uninstall.rb | 1 + 21 files changed, 810 insertions(+), 2 deletions(-) create mode 100644 app/controllers/radchecks_controller.rb create mode 100644 app/models/radcheck.rb create mode 100644 app/views/clients/_dialup.html.erb create mode 100644 vendor/plugins/use_db/MIT-LICENSE create mode 100644 vendor/plugins/use_db/README create mode 100644 vendor/plugins/use_db/Rakefile create mode 100644 vendor/plugins/use_db/init.rb create mode 100644 vendor/plugins/use_db/install.rb create mode 100644 vendor/plugins/use_db/lib/migration.rb create mode 100644 vendor/plugins/use_db/lib/override_fixtures.rb create mode 100644 vendor/plugins/use_db/lib/override_test_case.rb create mode 100644 vendor/plugins/use_db/lib/test_model.rb create mode 100644 vendor/plugins/use_db/lib/use_db.rb create mode 100644 vendor/plugins/use_db/lib/use_db_test.rb create mode 100644 vendor/plugins/use_db/tasks/use_db_tasks.rake create mode 100644 vendor/plugins/use_db/test/use_db_test.rb create mode 100644 vendor/plugins/use_db/uninstall.rb diff --git a/app/controllers/radchecks_controller.rb b/app/controllers/radchecks_controller.rb new file mode 100644 index 0000000..962a338 --- /dev/null +++ b/app/controllers/radchecks_controller.rb @@ -0,0 +1,38 @@ +class RadchecksController < ApplicationController + before_filter :login_required + layout nil + + def create + @radcheck = Radcheck.new(params[:radcheck]) + if @radcheck.save + flash[:notice] = "Dialup account created successfully!" + redirect_to :back + else + flash[:notice] = "Suite could not create this dialup account." + redirect_to :back + end + end + + def update + @radcheck = Radcheck.find(params[:id]) + if @radcheck.update_attributes(params[:radcheck]) + flash[:notice] = "Dialup account updated successfully!" + redirect_to :back + else + flash[:notice] = "Suite could not update this dialup account." + redirect_to :back + end + end + + def destroy + @radcheck = Radcheck.find(params[:id]) + if @radcheck.destroy + flash[:notice] = "Dialup account deleted successfully." + redirect_to :back + else + flash[:notice] = "Dialup account could not be deleted." + redirect_to :back + end + end + +end \ No newline at end of file diff --git a/app/models/client.rb b/app/models/client.rb index 083f72a..7c7c5bd 100644 --- a/app/models/client.rb +++ b/app/models/client.rb @@ -13,6 +13,8 @@ class Client < ActiveRecord::Base has_many :phones, :dependent => :destroy has_many :emails, :dependent => :destroy has_many :addresses, :dependent => :destroy + + has_one :radcheck, :dependent => :destroy validates_associated :phones, :emails, :addresses @@ -135,5 +137,13 @@ def primary_address def open_tickets Ticket.find(:all, :conditions => {:archived_on => nil, :client_id => self.id}) end + + def active_dialup_user? + if self.radcheck && self.radcheck.value[0..8] != "disabled_" + return true + else + return false + end + end end diff --git a/app/models/device.rb b/app/models/device.rb index ad889df..60743e7 100644 --- a/app/models/device.rb +++ b/app/models/device.rb @@ -12,7 +12,7 @@ class Device < ActiveRecord::Base after_create :create_checklists def create_service_tag - if self.service_tag == "" + if self.service_tag.blank? recent_device = Device.find(:first, :order => 'created_at DESC', :conditions => {:created_at.gt => DateTime.now.beginning_of_day, :created_at.lt => DateTime.now.end_of_day, :device_type_id => self.device_type_id}) device_type = DeviceType.find(self.device_type_id) if recent_device != nil diff --git a/app/models/radcheck.rb b/app/models/radcheck.rb new file mode 100644 index 0000000..5e852b8 --- /dev/null +++ b/app/models/radcheck.rb @@ -0,0 +1,16 @@ +class Radcheck < ActiveRecord::Base + use_db :prefix => "freeradius_" + set_table_name "radcheck" + + belongs_to :client + + validates_presence_of :username, :attribute, :value + validates_uniqueness_of :username + + # this won't work for some reason + before_create :set_attribute + def set_attribute + self.attribute = "User-Password" + end + +end \ No newline at end of file diff --git a/app/views/clients/_dialup.html.erb b/app/views/clients/_dialup.html.erb new file mode 100644 index 0000000..3f1ba9a --- /dev/null +++ b/app/views/clients/_dialup.html.erb @@ -0,0 +1,61 @@ +<% !@client.radcheck.blank? ? @radcheck = @client.radcheck : @radcheck = Radcheck.new %> +
+ <% if @client.radcheck.blank? %> + + <% else %> + + <% end %> +
+ <% form_for @radcheck do |f| %> + + + + + + + + + +
Username:<%= f.text_field :username %>
Password:<%= f.text_field :value %>
+ <%= f.hidden_field :attribute, :value => "User-Password" %> + <%= f.hidden_field :client_id, :value => @client.id %> + <%= f.submit "Save" %> + <% end %> +
+
+
+ + \ No newline at end of file diff --git a/app/views/shared/_new_device.html.erb b/app/views/shared/_new_device.html.erb index b56c1c3..f0970ee 100644 --- a/app/views/shared/_new_device.html.erb +++ b/app/views/shared/_new_device.html.erb @@ -1,6 +1,7 @@

New Device

<% form_for Device.new(), :url => "" do |f| -%> - <%= f.hidden_field :client_id, :value => @ticket.client.id %> + <% @client.blank? ? @client_id = @ticket.client.id : @client_id = @client.id %> + <%= f.hidden_field :client_id, :value => @client_id %> diff --git a/config/routes.rb b/config/routes.rb index 7e238b4..eba85f8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -43,6 +43,8 @@ map.resources :things + map.resources :radchecks + map.device_details '/tickets/:ticket_id/devices/:id/details', :controller => 'devices', :action => 'details' map.add_to_ticket '/tickets/:ticket_id/devices/:id/add_to_ticket', :controller => 'devices', :action => 'add_to_ticket' map.remove_device_from_ticket '/tickets/:ticket_id/devices/:id/remove_from_ticket', :controller => 'devices', :action => 'remove_from_ticket' diff --git a/vendor/plugins/use_db/MIT-LICENSE b/vendor/plugins/use_db/MIT-LICENSE new file mode 100644 index 0000000..6600438 --- /dev/null +++ b/vendor/plugins/use_db/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2007 [name of plugin creator] + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/plugins/use_db/README b/vendor/plugins/use_db/README new file mode 100644 index 0000000..bf182e1 --- /dev/null +++ b/vendor/plugins/use_db/README @@ -0,0 +1,86 @@ +UseDb +by David Stevenson +ds@elctech.com +===== +USAGE + +This plugin allows you to use multiple databases in your rails application. +You can switch the database for a model in the following manner: + +class MyModel < ActiveRecord::Base + use_db :prefix => "secdb_", :suffix => "_cool" +end + +"use_db" takes a prefix and a suffix (only 1 of which is required) which are prepended and appended onto the current RAILS_ENV. +In the above example, I would have to make the following database entries to my database.yml: + +secdb_development_cool: + adapter: mysql + database: secdb_dev_db + ... + +secdb_test_cool: + adapater: mysql + database: secdb_test_db + ... + +It's often useful to create a single abstract model which all models using a different database extend from: + +class SecdbBase < ActiveRecord::Base + use_db :prefix => "secdb_" + self.abstract_class = true +end + +class MyModel < SecdbBase + # this model will use a different database automatically now +end + +========== +MIGRATIONS + +To write a migration which executes on a different database, add the following method to your +migration: + +class MyMigration < ActiveRecord::Migration + def self.database_model + return "SecdbBase" + end + + def self.up + ... + end + + ... +end + +The "self.database_model" call must return a string which is the name of the model whose connection +you want to borrow when performing the migration. If this method is undefined, the default ActiveRecord::Base +connection is used. + +======= +TESTING + +In order to test multiple databases, you must invoke a task which clones the development database +structure and copies it into the test database, clearing out the existing test data. There is a single +helper method which executes this task and you invoke it as follows: + +UseDbTest.prepare_test_db(:prefix => "secdb_") + +Even though it might not be the best place for it, I often place a call to this in my test helper. +You don't want it to execute for every test, so put the following guards around it: + +unless defined?(CLONED_SEC_DB_FOR_TEST) + UseDbTest.prepare_test_db(:prefix => "secdb_") + CLONED_SEC_DB_FOR_TEST = true +end + +======== +FIXTURES + +Fixtures will automatically be loaded into the correct database as long as the fixture name corresponds +to the name of a model. For example, if I have a model called SecdbUser who uses a different database and +I create a fixture file called secdb_users.yml, the fixture loader will use whatever database connection +belongs to hte SecdbUser model. + +There is currently no other way to force a fixture to use a specific database (sorry, no join tables yet), +like there is for migrations. \ No newline at end of file diff --git a/vendor/plugins/use_db/Rakefile b/vendor/plugins/use_db/Rakefile new file mode 100644 index 0000000..130167d --- /dev/null +++ b/vendor/plugins/use_db/Rakefile @@ -0,0 +1,22 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the use_db plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the use_db plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'UseDb' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/vendor/plugins/use_db/init.rb b/vendor/plugins/use_db/init.rb new file mode 100644 index 0000000..fcf3723 --- /dev/null +++ b/vendor/plugins/use_db/init.rb @@ -0,0 +1,13 @@ +# Include hook code here + +require "use_db" +require "use_db_test" +require 'active_record/fixtures' +require "override_fixtures" +require 'active_record/migration' +require 'override_test_case' +require "migration" + +ActiveRecord::Base.extend(UseDbPlugin) +#Fixtures.send(:extend, OverrideFixtures::ClassMethods) +#Fixtures.send(:include, OverrideFixtures::InstanceMethods) \ No newline at end of file diff --git a/vendor/plugins/use_db/install.rb b/vendor/plugins/use_db/install.rb new file mode 100644 index 0000000..f7732d3 --- /dev/null +++ b/vendor/plugins/use_db/install.rb @@ -0,0 +1 @@ +# Install hook code here diff --git a/vendor/plugins/use_db/lib/migration.rb b/vendor/plugins/use_db/lib/migration.rb new file mode 100644 index 0000000..6b73493 --- /dev/null +++ b/vendor/plugins/use_db/lib/migration.rb @@ -0,0 +1,21 @@ +module ActiveRecord + class Migration + class << self + def method_missing(method, *arguments, &block) + say_with_time "#{method}(#{arguments.map { |a| a.inspect }.join(", ")})" do + arguments[0] = Migrator.proper_table_name(arguments.first) unless arguments.empty? || method == :execute + if (self.respond_to?(:database_model)) + write "Using custom database model's connection (#{self.database_model}) for this migration" + eval("#{self.database_model}.connection.send(method, *arguments, &block)") + else + ActiveRecord::Base.connection.send(method, *arguments, &block) + end + end + end + + def uses_db? + true + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/use_db/lib/override_fixtures.rb b/vendor/plugins/use_db/lib/override_fixtures.rb new file mode 100644 index 0000000..ecc7a11 --- /dev/null +++ b/vendor/plugins/use_db/lib/override_fixtures.rb @@ -0,0 +1,32 @@ +# Override the rails fixtures to borrow the proper model's connection when inserting or deleting +# data whenever possible. + +class Fixtures + alias_method :rails_delete_existing_fixtures, :delete_existing_fixtures + def delete_existing_fixtures + m = get_model + #puts "Model: #{m}, class_name: #{@class_name}" + return rails_delete_existing_fixtures unless m && m.respond_to?(:uses_db?) && m.uses_db? + connection = m.connection + connection.delete "DELETE FROM #{m.table_name}", 'Fixture Delete' + end + + alias_method :rails_insert_fixtures, :insert_fixtures + def insert_fixtures + m = get_model + return rails_insert_fixtures unless m && m.respond_to?(:uses_db?) && m.uses_db? + connection = m.connection + values.each do |fixture| + #puts "Inserting fixtures into custom DB for #{connection.current_database}.#{m.table_name}: INSERT INTO #{m.table_name} (#{fixture.key_list}) VALUES (#{fixture.value_list})" + connection.execute("INSERT INTO #{m.table_name} (#{fixture.key_list}) VALUES (#{fixture.value_list})", 'Fixture Insert') + end + end + +private + def get_model + klass = eval(@class_name) + return klass + rescue + return nil + end +end \ No newline at end of file diff --git a/vendor/plugins/use_db/lib/override_test_case.rb b/vendor/plugins/use_db/lib/override_test_case.rb new file mode 100644 index 0000000..fd77bec --- /dev/null +++ b/vendor/plugins/use_db/lib/override_test_case.rb @@ -0,0 +1,79 @@ +# puts "Overriding Test::Unit::TestCase" + +module Test #:nodoc: + module Unit #:nodoc: + class TestCase #:nodoc: + #alias_method :rails_setup_with_fixtures, :setup_with_fixtures + + def setup_with_fixtures + return unless defined?(ActiveRecord::Base) && !ActiveRecord::Base.configurations.blank? + + if pre_loaded_fixtures && !use_transactional_fixtures + raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures' + end + + @fixture_cache = Hash.new + + # Load fixtures once and begin transaction. + if use_transactional_fixtures? + # puts "Using transactional fixtures" + if @@already_loaded_fixtures[self.class] + @loaded_fixtures = @@already_loaded_fixtures[self.class] + else + load_fixtures + @@already_loaded_fixtures[self.class] = @loaded_fixtures + end + + UseDbPlugin.all_use_dbs.collect do |klass| + klass + end + + # puts "Establishing TRANSACTION for #{ActiveRecord::Base.active_connections.values.uniq.length} open connections" + + ActiveRecord::Base.active_connections.values.uniq.each do |conn| + # puts "BEGIN on #{klass_name}: #{Thread.current['open_transactions']}" + Thread.current['open_transactions'] ||= 0 + Thread.current['open_transactions'] += 1 + conn.begin_db_transaction + end + + # Load fixtures for every test. + else + # puts "NOT Using transactional fixtures: #{self.use_transactional_fixtures}" + @@already_loaded_fixtures[self.class] = nil + load_fixtures + end + + # Instantiate fixtures for every test if requested. + if use_instantiated_fixtures + # puts "Instantiating fixtures for #{self.class}" + instantiate_fixtures + else + # puts "Not instantiating fixtures" + end + end + + #alias_method :rails_teardown_with_fixtures, :teardown_with_fixtures + + def teardown_with_fixtures + # puts "Finshing TRANSACTION for #{ActiveRecord::Base.active_connections.values.uniq.length} open connections" + + return unless defined?(ActiveRecord::Base) && !ActiveRecord::Base.configurations.blank? + + # Rollback changes if a transaction is active + ActiveRecord::Base.active_connections.values.uniq.each do |conn| + if use_transactional_fixtures? + conn.rollback_db_transaction + Thread.current['open_transactions'] = 0 + end + + # klass.verify_active_connections! + end + end + + def self.uses_db? + return true + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/use_db/lib/test_model.rb b/vendor/plugins/use_db/lib/test_model.rb new file mode 100644 index 0000000..e264511 --- /dev/null +++ b/vendor/plugins/use_db/lib/test_model.rb @@ -0,0 +1,11 @@ +def create_test_model(model_name, prefix="", suffix="", rails_env=RAILS_ENV) + # puts "Creating test model '#{model_name}', :prefix => '#{prefix}', :suffix => '#{suffix}'" + str = <<-EOF + require "use_db" + + class #{model_name} < ActiveRecord::Base + use_db :prefix => "#{prefix}", :suffix => "#{suffix}", :rails_env => "#{rails_env}" + end +EOF + eval(str) +end \ No newline at end of file diff --git a/vendor/plugins/use_db/lib/use_db.rb b/vendor/plugins/use_db/lib/use_db.rb new file mode 100644 index 0000000..0590ef6 --- /dev/null +++ b/vendor/plugins/use_db/lib/use_db.rb @@ -0,0 +1,67 @@ +# UseDb + +module UseDbPlugin + # options can have one or the other of the following options: + # :prefix - Specify the prefix to append to the RAILS_ENV when finding the adapter secification in database.yml + # :suffix - Just like :prefix, only contactentated + # OR + # :adapter + # :host + # :username + # :password + # ... etc ... same as the options in establish_connection + # + # Set the following to true in your test environment + # to enable extended debugging printing during testing ... + # UseDbPlugin.debug_print = true + # + + @@use_dbs = [ActiveRecord::Base] + @@debug_print = false + + def use_db(options) + options_dup = options.dup + conn_spec = get_use_db_conn_spec(options) + puts "Establishing connecting on behalf of #{self.to_s} to #{conn_spec.inspect}" if UseDbPlugin.debug_print + establish_connection(conn_spec) + extend ClassMixin + @@use_dbs << self unless @@use_dbs.include?(self) || self.to_s.starts_with?("TestModel") + end + + def self.all_use_dbs + return @@use_dbs + end + + def self.debug_print + return @@debug_print + end + + def self.debug_print=(newval) + @@debug_print = newval + end + + module ClassMixin + def uses_db? + true + end + end + + def get_use_db_conn_spec(options) + options.symbolize_keys + suffix = options.delete(:suffix) + prefix = options.delete(:prefix) + rails_env = options.delete(:rails_env) || RAILS_ENV + if (options[:adapter]) + return options + else + str = "#{prefix}#{rails_env}#{suffix}" + connections = YAML.load(ERB.new(IO.read("#{RAILS_ROOT}/config/database.yml"), nil, nil, '_use_db_erbout').result) + raise "Cannot find database specification. Configuration '#{str}' expected in config/database.yml" if (connections[str].nil?) + return connections[str] + end + end +end + +class UseDbPluginClass + extend UseDbPlugin +end diff --git a/vendor/plugins/use_db/lib/use_db_test.rb b/vendor/plugins/use_db/lib/use_db_test.rb new file mode 100644 index 0000000..3e221f2 --- /dev/null +++ b/vendor/plugins/use_db/lib/use_db_test.rb @@ -0,0 +1,152 @@ +require "use_db.rb" +require "test_model.rb" + +class UseDbTest + + extend UseDbPlugin + + def self.other_databases + YAML.load(File.read("#{RAILS_ROOT}/config/use_db.yml")).values.collect(&:symbolize_keys!) + end + + def self.prepare_test_db(options) + dump_db_structure(options) + purge_db(options) + clone_db_structure(options) + end + + def self.dump_db_structure(options) + options_dup = options.dup + options_dup[:rails_env] = "development" + conn_spec = get_use_db_conn_spec(options_dup) + #establish_connection(conn_spec) + + test_class = setup_test_model(options[:prefix], options[:suffix], "ForDumpStructure") + + # puts "Dumping DB structure #{test_class.inspect}..." + + case conn_spec["adapter"] + when "mysql", "oci", "oracle" + test_class.establish_connection(conn_spec) + File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << test_class.connection.structure_dump } +=begin when "postgresql" + ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"] + ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"] + ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"] + search_path = abcs[RAILS_ENV]["schema_search_path"] + search_path = "--schema=#{search_path}" if search_path + `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}` + raise "Error dumping database" if $?.exitstatus == 1 + when "sqlite", "sqlite3" + dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"] + `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql` + when "sqlserver" + `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r` + `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r` + when "firebird" + set_firebird_env(abcs[RAILS_ENV]) + db_string = firebird_db_string(abcs[RAILS_ENV]) + sh "isql -a #{db_string} > db/#{RAILS_ENV}_structure.sql" +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + #if test_class.connection.supports_migrations? + # File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } + #end + + test_class.connection.disconnect! + end + + def self.clone_db_structure(options) + options_dup = options.dup + conn_spec = get_use_db_conn_spec(options_dup) + #establish_connection(conn_spec) + + test_class = setup_test_model(options[:prefix], options[:suffix], "ForClone") + + # puts "Cloning DB structure #{test_class.inspect}..." + + case conn_spec["adapter"] + when "mysql" + test_class.connection.execute('SET foreign_key_checks = 0') + IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table| + test_class.connection.execute(table) + end + when "oci", "oracle" + IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl| + test_class.connection.execute(ddl) + end +=begin when "postgresql" + ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"] + ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"] + ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"] + `psql -U "#{abcs["test"]["username"]}" -f db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}` + when "sqlite", "sqlite3" + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"] + `#{abcs["test"]["adapter"]} #{dbfile} < db/#{RAILS_ENV}_structure.sql` + when "sqlserver" + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql` + when "firebird" + set_firebird_env(abcs["test"]) + db_string = firebird_db_string(abcs["test"]) + sh "isql -i db/#{RAILS_ENV}_structure.sql #{db_string}" +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + test_class.connection.disconnect! + end + + def self.purge_db(options) + options_dup = options.dup + conn_spec = get_use_db_conn_spec(options_dup) + #establish_connection(conn_spec) + + test_class = setup_test_model(options[:prefix], options[:suffix], "ForPurge") + + case conn_spec["adapter"] + when "mysql" + test_class.connection.recreate_database(conn_spec["database"]) + when "oci", "oracle" + test_class.connection.structure_drop.split(";\n\n").each do |ddl| + test_class.connection.execute(ddl) + end + when "firebird" + test_class.connection.recreate_database! +=begin + when "postgresql" + ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"] + ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"] + ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"] + enc_option = "-E #{abcs["test"]["encoding"]}" if abcs["test"]["encoding"] + + ActiveRecord::Base.clear_active_connections! + `dropdb -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}` + `createdb #{enc_option} -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}` + when "sqlite","sqlite3" + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"] + File.delete(dbfile) if File.exist?(dbfile) + when "sqlserver" + dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-') + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}` + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql` +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + test_class.connection.disconnect! + end + + def self.setup_test_model(prefix="", suffix="", model_suffix="", rails_env=RAILS_ENV) + prefix ||= "" + suffix ||= "" + model_name = "TestModel#{prefix.camelize}#{suffix.camelize}#{model_suffix}".gsub("_","").gsub("-","") + return eval(model_name) if eval("defined?(#{model_name})") + create_test_model(model_name, prefix, suffix, rails_env) + return eval(model_name) + end +end \ No newline at end of file diff --git a/vendor/plugins/use_db/tasks/use_db_tasks.rake b/vendor/plugins/use_db/tasks/use_db_tasks.rake new file mode 100644 index 0000000..7e3f9da --- /dev/null +++ b/vendor/plugins/use_db/tasks/use_db_tasks.rake @@ -0,0 +1,167 @@ +# desc "Explaining what the task does" +# task :use_db do +# # Task goes here +# end + +namespace :db do + namespace :structure do + task :dump_use_db do + require "use_db.rb" + require "test_model.rb" + + UseDbTest.other_databases.each do |options| + puts "DUMPING TEST DB: #{options.inspect}" if UseDbPlugin.debug_print + + options_dup = options.dup + options_dup[:rails_env] = "development" + conn_spec = UseDbPluginClass.get_use_db_conn_spec(options_dup) + #establish_connection(conn_spec) + + test_class = UseDbTest.setup_test_model(options[:prefix], options[:suffix], "ForDumpStructure") + + # puts "Dumping DB structure #{test_class.inspect}..." + + case conn_spec["adapter"] + when "mysql", "oci", "oracle" + test_class.establish_connection(conn_spec) + File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_#{options[:prefix]}_#{options[:suffix]}_structure.sql", "w+") { |f| f << test_class.connection.structure_dump } +=begin when "postgresql" + ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"] + ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"] + ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"] + search_path = abcs[RAILS_ENV]["schema_search_path"] + search_path = "--schema=#{search_path}" if search_path + `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}` + raise "Error dumping database" if $?.exitstatus == 1 + when "sqlite", "sqlite3" + dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"] + `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql` + when "sqlserver" + `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r` + `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r` + when "firebird" + set_firebird_env(abcs[RAILS_ENV]) + db_string = firebird_db_string(abcs[RAILS_ENV]) + sh "isql -a #{db_string} > db/#{RAILS_ENV}_structure.sql" +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + #if test_class.connection.supports_migrations? + # File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } + #end + + test_class.connection.disconnect! + end + end + end + + namespace :test do + task :clone_structure => "db:test:clone_structure_use_db" + + task :clone_structure_use_db => ["db:structure:dump_use_db","db:test:purge_use_db"] do + require "use_db.rb" + require "test_model.rb" + + UseDbTest.other_databases.each do |options| + + puts "CLONING TEST DB: #{options.inspect}" if UseDbPlugin.debug_print + + options_dup = options.dup + conn_spec = UseDbPluginClass.get_use_db_conn_spec(options_dup) + #establish_connection(conn_spec) + + test_class = UseDbTest.setup_test_model(options[:prefix], options[:suffix], "ForClone", "test") + + # puts "Cloning DB structure #{test_class.inspect}..." + + case conn_spec["adapter"] + when "mysql" + test_class.connection.execute('SET foreign_key_checks = 0') + IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_#{options[:prefix]}_#{options[:suffix]}_structure.sql").join.split("\n\n").each do |table| + test_class.connection.execute(table) + end + when "oci", "oracle" + IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_#{options[:prefix]}_#{options[:suffix]}_structure.sql").join.split(";\n\n").each do |ddl| + test_class.connection.execute(ddl) + end +=begin when "postgresql" + ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"] + ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"] + ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"] + `psql -U "#{abcs["test"]["username"]}" -f db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}` + when "sqlite", "sqlite3" + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"] + `#{abcs["test"]["adapter"]} #{dbfile} < db/#{RAILS_ENV}_structure.sql` + when "sqlserver" + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql` + when "firebird" + set_firebird_env(abcs["test"]) + db_string = firebird_db_string(abcs["test"]) + sh "isql -i db/#{RAILS_ENV}_structure.sql #{db_string}" +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + test_class.connection.disconnect! + end + end + + task :purge_use_db => "db:test:purge" do + require "use_db.rb" + require "test_model.rb" + + UseDbTest.other_databases.each do |options| + puts "PURGING TEST DB: #{options.inspect}" if UseDbPlugin.debug_print + options_dup = options.dup + options_dup[:rails_env] = "test" + conn_spec = UseDbPluginClass.get_use_db_conn_spec(options_dup) + puts "GOT CONN_SPEC: #{conn_spec.inspect}" + test_class = UseDbTest.setup_test_model(options[:prefix], options[:suffix], "ForPurge", "test") + puts "GOT TEST_CLASS: #{test_class.inspect}" + #test_class.establish_connection + + case conn_spec["adapter"] + when "mysql" + test_class.connection.recreate_database(conn_spec["database"]) + when "oci", "oracle" + test_class.connection.structure_drop.split(";\n\n").each do |ddl| + test_class.connection.execute(ddl) + end + when "firebird" + test_class.connection.recreate_database! +=begin + when "postgresql" + ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"] + ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"] + ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"] + enc_option = "-E #{abcs["test"]["encoding"]}" if abcs["test"]["encoding"] + + ActiveRecord::Base.clear_active_connections! + `dropdb -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}` + `createdb #{enc_option} -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}` + when "sqlite","sqlite3" + dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"] + File.delete(dbfile) if File.exist?(dbfile) + when "sqlserver" + dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-') + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}` + `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql` +=end + else + raise "Task not supported by '#{conn_spec["adapter"]}'" + end + + test_class.connection.disconnect! + end + end + end +end + +namespace :test do + task :units => "db:test:clone_structure_use_db" + task :functionals => "db:test:clone_structure_use_db" + task :integrations => "db:test:clone_structure_use_db" +end \ No newline at end of file diff --git a/vendor/plugins/use_db/test/use_db_test.rb b/vendor/plugins/use_db/test/use_db_test.rb new file mode 100644 index 0000000..14fcdeb --- /dev/null +++ b/vendor/plugins/use_db/test/use_db_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class UseDbTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_it_will_get_the_right_connection + flunk + end +end diff --git a/vendor/plugins/use_db/uninstall.rb b/vendor/plugins/use_db/uninstall.rb new file mode 100644 index 0000000..9738333 --- /dev/null +++ b/vendor/plugins/use_db/uninstall.rb @@ -0,0 +1 @@ +# Uninstall hook code here
Service Tag:<%= f.text_field :service_tag %> Auto-Generated