Removed superfluous 'tracks' directory at the root of the repository.

Testing commits to github.
This commit is contained in:
bsag 2008-05-20 21:28:26 +01:00
parent 6a42901514
commit 4cbf5a34d3
2269 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,72 @@
# The filename begins with "aaa" to ensure this is the first test.
require 'abstract_unit'
class AAACreateTablesTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
def setup
@base_path = "#{File.dirname(__FILE__)}/fixtures/db_definitions"
end
def test_drop_and_create_main_tables
recreate ActiveRecord::Base unless use_migrations?
assert true
end
def test_load_schema
if ActiveRecord::Base.connection.supports_migrations?
eval(File.read("#{File.dirname(__FILE__)}/fixtures/db_definitions/schema.rb"))
else
recreate ActiveRecord::Base, '3'
end
assert true
end
def test_drop_and_create_courses_table
if Course.connection.supports_migrations?
eval(File.read("#{File.dirname(__FILE__)}/fixtures/db_definitions/schema2.rb"))
end
recreate Course, '2' unless use_migrations_for_courses?
assert true
end
private
def use_migrations?
unittest_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + ".sql"
not File.exist? "#{@base_path}/#{unittest_sql_filename}"
end
def use_migrations_for_courses?
unittest2_sql_filename = ActiveRecord::Base.connection.adapter_name.downcase + "2.sql"
not File.exist? "#{@base_path}/#{unittest2_sql_filename}"
end
def recreate(base, suffix = nil)
connection = base.connection
adapter_name = connection.adapter_name.downcase + suffix.to_s
execute_sql_file "#{@base_path}/#{adapter_name}.drop.sql", connection
execute_sql_file "#{@base_path}/#{adapter_name}.sql", connection
end
def execute_sql_file(path, connection)
# OpenBase has a different format for sql files
if current_adapter?(:OpenBaseAdapter) then
File.read(path).split("go").each_with_index do |sql, i|
begin
# OpenBase does not support comments embedded in sql
connection.execute(sql,"SQL statement ##{i}") unless sql.blank?
rescue ActiveRecord::StatementInvalid
#$stderr.puts "warning: #{$!}"
end
end
else
File.read(path).split(';').each_with_index do |sql, i|
begin
connection.execute("\n\n-- statement ##{i}\n#{sql}\n") unless sql.blank?
rescue ActiveRecord::StatementInvalid
#$stderr.puts "warning: #{$!}"
end
end
end
end
end

View file

@ -0,0 +1,84 @@
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
require 'test/unit'
require 'active_record'
require 'active_record/fixtures'
require 'active_support/test_case'
require 'connection'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type') unless Object.const_defined?(:QUOTED_TYPE)
class Test::Unit::TestCase #:nodoc:
self.fixture_path = File.dirname(__FILE__) + "/fixtures/"
self.use_instantiated_fixtures = false
self.use_transactional_fixtures = (ENV['AR_NO_TX_FIXTURES'] != "yes")
def create_fixtures(*table_names, &block)
Fixtures.create_fixtures(File.dirname(__FILE__) + "/fixtures/", table_names, {}, &block)
end
def assert_date_from_db(expected, actual, message = nil)
# SQL Server doesn't have a separate column type just for dates,
# so the time is in the string and incorrectly formatted
if current_adapter?(:SQLServerAdapter)
assert_equal expected.strftime("%Y/%m/%d 00:00:00"), actual.strftime("%Y/%m/%d 00:00:00")
elsif current_adapter?(:SybaseAdapter)
assert_equal expected.to_s, actual.to_date.to_s, message
else
assert_equal expected.to_s, actual.to_s, message
end
end
def assert_queries(num = 1)
$query_count = 0
yield
ensure
assert_equal num, $query_count, "#{$query_count} instead of #{num} queries were executed."
end
def assert_no_queries(&block)
assert_queries(0, &block)
end
end
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
end
end
def uses_mocha(test_name)
require 'rubygems'
require 'mocha'
yield
rescue LoadError
$stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end
ActiveRecord::Base.connection.class.class_eval do
unless defined? IGNORED_SQL
IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/]
def execute_with_counting(sql, name = nil, &block)
$query_count ||= 0
$query_count += 1 unless IGNORED_SQL.any? { |r| sql =~ r }
execute_without_counting(sql, name, &block)
end
alias_method_chain :execute, :counting
end
end
# Make with_scope public for tests
class << ActiveRecord::Base
public :with_scope, :with_exclusive_scope
end
#ActiveRecord::Base.logger = Logger.new(STDOUT)
#ActiveRecord::Base.colorize_logging = false

View file

@ -0,0 +1,43 @@
require 'abstract_unit'
class ActiveSchemaTest < Test::Unit::TestCase
def setup
ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
alias_method :real_execute, :execute
def execute(sql, name = nil) return sql end
end
end
def teardown
ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:alias_method, :execute, :real_execute)
end
def test_drop_table
assert_equal "DROP TABLE `people`", drop_table(:people)
end
if current_adapter?(:MysqlAdapter)
def test_create_mysql_database_with_encoding
assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
end
end
def test_add_column
assert_equal "ALTER TABLE `people` ADD `last_name` varchar(255)", add_column(:people, :last_name, :string)
end
def test_add_column_with_limit
assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
end
def test_drop_table_with_specific_database
assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
end
private
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
end
end

View file

@ -0,0 +1,105 @@
require 'abstract_unit'
class AdapterTest < Test::Unit::TestCase
def setup
@connection = ActiveRecord::Base.connection
end
def test_tables
if @connection.respond_to?(:tables)
tables = @connection.tables
assert tables.include?("accounts")
assert tables.include?("authors")
assert tables.include?("tasks")
assert tables.include?("topics")
else
warn "#{@connection.class} does not respond to #tables"
end
end
def test_indexes
idx_name = "accounts_idx"
if @connection.respond_to?(:indexes)
indexes = @connection.indexes("accounts")
assert indexes.empty?
@connection.add_index :accounts, :firm_id, :name => idx_name
indexes = @connection.indexes("accounts")
assert_equal "accounts", indexes.first.table
# OpenBase does not have the concept of a named index
# Indexes are merely properties of columns.
assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter)
assert !indexes.first.unique
assert_equal ["firm_id"], indexes.first.columns
else
warn "#{@connection.class} does not respond to #indexes"
end
ensure
@connection.remove_index(:accounts, :name => idx_name) rescue nil
end
def test_current_database
if @connection.respond_to?(:current_database)
assert_equal ENV['ARUNIT_DB_NAME'] || "activerecord_unittest", @connection.current_database
end
end
if current_adapter?(:MysqlAdapter)
def test_charset
assert_not_nil @connection.charset
assert_not_equal 'character_set_database', @connection.charset
assert_equal @connection.show_variable('character_set_database'), @connection.charset
end
def test_collation
assert_not_nil @connection.collation
assert_not_equal 'collation_database', @connection.collation
assert_equal @connection.show_variable('collation_database'), @connection.collation
end
def test_show_nonexistent_variable_returns_nil
assert_nil @connection.show_variable('foo_bar_baz')
end
end
def test_table_alias
def @connection.test_table_alias_length() 10; end
class << @connection
alias_method :old_table_alias_length, :table_alias_length
alias_method :table_alias_length, :test_table_alias_length
end
assert_equal 'posts', @connection.table_alias_for('posts')
assert_equal 'posts_comm', @connection.table_alias_for('posts_comments')
assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')
class << @connection
alias_method :table_alias_length, :old_table_alias_length
end
end
# test resetting sequences in odd tables in postgreSQL
if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
require 'fixtures/movie'
require 'fixtures/subscriber'
def test_reset_empty_table_with_custom_pk
Movie.delete_all
Movie.connection.reset_pk_sequence! 'movies'
assert_equal 1, Movie.create(:name => 'fight club').id
end
if ActiveRecord::Base.connection.adapter_name != "FrontBase"
def test_reset_table_with_non_integer_pk
Subscriber.delete_all
Subscriber.connection.reset_pk_sequence! 'subscribers'
sub = Subscriber.new(:name => 'robert drake')
sub.id = 'bob drake'
assert_nothing_raised { sub.save! }
end
end
end
end

View file

@ -0,0 +1,95 @@
require 'abstract_unit'
require 'fixtures/default'
require 'fixtures/post'
require 'fixtures/task'
class SqlServerAdapterTest < Test::Unit::TestCase
class TableWithRealColumn < ActiveRecord::Base; end
fixtures :posts, :tasks
def setup
@connection = ActiveRecord::Base.connection
end
def teardown
@connection.execute("SET LANGUAGE us_english") rescue nil
end
def test_real_column_has_float_type
assert_equal :float, TableWithRealColumn.columns_hash["real_number"].type
end
# SQL Server 2000 has a bug where some unambiguous date formats are not
# correctly identified if the session language is set to german
def test_date_insertion_when_language_is_german
@connection.execute("SET LANGUAGE deutsch")
assert_nothing_raised do
Task.create(:starting => Time.utc(2000, 1, 31, 5, 42, 0), :ending => Date.new(2006, 12, 31))
end
end
def test_indexes_with_descending_order
# Make sure we have an index with descending order
@connection.execute "CREATE INDEX idx_credit_limit ON accounts (credit_limit DESC)" rescue nil
assert_equal ["credit_limit"], @connection.indexes('accounts').first.columns
ensure
@connection.execute "DROP INDEX accounts.idx_credit_limit"
end
def test_execute_without_block_closes_statement
assert_all_statements_used_are_closed do
@connection.execute("SELECT 1")
end
end
def test_execute_with_block_closes_statement
assert_all_statements_used_are_closed do
@connection.execute("SELECT 1") do |sth|
assert !sth.finished?, "Statement should still be alive within block"
end
end
end
def test_insert_with_identity_closes_statement
assert_all_statements_used_are_closed do
@connection.insert("INSERT INTO accounts ([id], [firm_id],[credit_limit]) values (999, 1, 50)")
end
end
def test_insert_without_identity_closes_statement
assert_all_statements_used_are_closed do
@connection.insert("INSERT INTO accounts ([firm_id],[credit_limit]) values (1, 50)")
end
end
def test_active_closes_statement
assert_all_statements_used_are_closed do
@connection.active?
end
end
def assert_all_statements_used_are_closed(&block)
existing_handles = []
ObjectSpace.each_object(DBI::StatementHandle) {|handle| existing_handles << handle}
GC.disable
yield
used_handles = []
ObjectSpace.each_object(DBI::StatementHandle) {|handle| used_handles << handle unless existing_handles.include? handle}
assert_block "No statements were used within given block" do
used_handles.size > 0
end
ObjectSpace.each_object(DBI::StatementHandle) do |handle|
assert_block "Statement should have been closed within given block" do
handle.finished?
end
end
ensure
GC.enable
end
end

View file

@ -0,0 +1,128 @@
require 'abstract_unit'
require 'fixtures/customer'
class AggregationsTest < Test::Unit::TestCase
fixtures :customers
def test_find_single_value_object
assert_equal 50, customers(:david).balance.amount
assert_kind_of Money, customers(:david).balance
assert_equal 300, customers(:david).balance.exchange_to("DKK").amount
end
def test_find_multiple_value_object
assert_equal customers(:david).address_street, customers(:david).address.street
assert(
customers(:david).address.close_to?(Address.new("Different Street", customers(:david).address_city, customers(:david).address_country))
)
end
def test_change_single_value_object
customers(:david).balance = Money.new(100)
customers(:david).save
assert_equal 100, customers(:david).reload.balance.amount
end
def test_immutable_value_objects
customers(:david).balance = Money.new(100)
assert_raises(TypeError) { customers(:david).balance.instance_eval { @amount = 20 } }
end
def test_inferred_mapping
assert_equal "35.544623640962634", customers(:david).gps_location.latitude
assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
customers(:david).gps_location = GpsLocation.new("39x-110")
assert_equal "39", customers(:david).gps_location.latitude
assert_equal "-110", customers(:david).gps_location.longitude
customers(:david).save
customers(:david).reload
assert_equal "39", customers(:david).gps_location.latitude
assert_equal "-110", customers(:david).gps_location.longitude
end
def test_reloaded_instance_refreshes_aggregations
assert_equal "35.544623640962634", customers(:david).gps_location.latitude
assert_equal "-105.9309951055148", customers(:david).gps_location.longitude
Customer.update_all("gps_location = '24x113'")
customers(:david).reload
assert_equal '24x113', customers(:david)['gps_location']
assert_equal GpsLocation.new('24x113'), customers(:david).gps_location
end
def test_gps_equality
assert GpsLocation.new('39x110') == GpsLocation.new('39x110')
end
def test_gps_inequality
assert GpsLocation.new('39x110') != GpsLocation.new('39x111')
end
def test_allow_nil_gps_is_nil
assert_equal nil, customers(:zaphod).gps_location
end
def test_allow_nil_gps_set_to_nil
customers(:david).gps_location = nil
customers(:david).save
customers(:david).reload
assert_equal nil, customers(:david).gps_location
end
def test_allow_nil_set_address_attributes_to_nil
customers(:zaphod).address = nil
assert_equal nil, customers(:zaphod).attributes[:address_street]
assert_equal nil, customers(:zaphod).attributes[:address_city]
assert_equal nil, customers(:zaphod).attributes[:address_country]
end
def test_allow_nil_address_set_to_nil
customers(:zaphod).address = nil
customers(:zaphod).save
customers(:zaphod).reload
assert_equal nil, customers(:zaphod).address
end
def test_nil_raises_error_when_allow_nil_is_false
assert_raises(NoMethodError) { customers(:david).balance = nil }
end
def test_allow_nil_address_loaded_when_only_some_attributes_are_nil
customers(:zaphod).address_street = nil
customers(:zaphod).save
customers(:zaphod).reload
assert_kind_of Address, customers(:zaphod).address
assert customers(:zaphod).address.street.nil?
end
def test_nil_assignment_results_in_nil
customers(:david).gps_location = GpsLocation.new('39x111')
assert_not_equal nil, customers(:david).gps_location
customers(:david).gps_location = nil
assert_equal nil, customers(:david).gps_location
end
end
class OverridingAggregationsTest < Test::Unit::TestCase
class Name; end
class DifferentName; end
class Person < ActiveRecord::Base
composed_of :composed_of, :mapping => %w(person_first_name first_name)
end
class DifferentPerson < Person
composed_of :composed_of, :class_name => 'DifferentName', :mapping => %w(different_person_first_name first_name)
end
def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited
assert_not_equal Person.reflect_on_aggregation(:composed_of),
DifferentPerson.reflect_on_aggregation(:composed_of)
end
end

8
vendor/rails/activerecord/test/all.sh vendored Executable file
View file

@ -0,0 +1,8 @@
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $0 <database>" 1>&2
exit 1
fi
ruby -I connections/native_$1 -e 'Dir["**/*_test.rb"].each { |path| require path }'

View file

@ -0,0 +1,33 @@
require 'abstract_unit'
require "#{File.dirname(__FILE__)}/../lib/active_record/schema"
if ActiveRecord::Base.connection.supports_migrations?
class ActiveRecordSchemaTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
def setup
@connection = ActiveRecord::Base.connection
end
def teardown
@connection.drop_table :fruits rescue nil
end
def test_schema_define
ActiveRecord::Schema.define(:version => 7) do
create_table :fruits do |t|
t.column :color, :string
t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle
t.column :texture, :string
t.column :flavor, :string
end
end
assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" }
assert_nothing_raised { @connection.select_all "SELECT * FROM schema_info" }
assert_equal 7, @connection.select_one("SELECT version FROM schema_info")['version'].to_i
end
end
end

View file

@ -0,0 +1,14 @@
require 'abstract_unit'
require 'fixtures/company'
class AssociationInheritanceReloadTest < Test::Unit::TestCase
fixtures :companies
def test_set_attributes
assert_equal ["errors.add_on_empty('name', \"can't be empty\")"], Firm.read_inheritable_attribute("validate"), "Second run"
# ActiveRecord::Base.reset_column_information_and_inheritable_attributes_for_all_subclasses
remove_subclass_of(ActiveRecord::Base)
load 'fixtures/company.rb'
assert_equal ["errors.add_on_empty('name', \"can't be empty\")"], Firm.read_inheritable_attribute("validate"), "Second run"
end
end

View file

@ -0,0 +1,147 @@
require 'abstract_unit'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/project'
require 'fixtures/developer'
class AssociationCallbacksTest < Test::Unit::TestCase
fixtures :posts, :authors, :projects, :developers
def setup
@david = authors(:david)
@thinking = posts(:thinking)
@authorless = posts(:authorless)
assert @david.post_log.empty?
end
def test_adding_macro_callbacks
@david.posts_with_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}"], @david.post_log
@david.posts_with_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}", "before_adding#{@thinking.id}",
"after_adding#{@thinking.id}"], @david.post_log
end
def test_adding_with_proc_callbacks
@david.posts_with_proc_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}"], @david.post_log
@david.posts_with_proc_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "after_adding#{@thinking.id}", "before_adding#{@thinking.id}",
"after_adding#{@thinking.id}"], @david.post_log
end
def test_removing_with_macro_callbacks
first_post, second_post = @david.posts_with_callbacks[0, 2]
@david.posts_with_callbacks.delete(first_post)
assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}"], @david.post_log
@david.posts_with_callbacks.delete(second_post)
assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}", "before_removing#{second_post.id}",
"after_removing#{second_post.id}"], @david.post_log
end
def test_removing_with_proc_callbacks
first_post, second_post = @david.posts_with_callbacks[0, 2]
@david.posts_with_proc_callbacks.delete(first_post)
assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}"], @david.post_log
@david.posts_with_proc_callbacks.delete(second_post)
assert_equal ["before_removing#{first_post.id}", "after_removing#{first_post.id}", "before_removing#{second_post.id}",
"after_removing#{second_post.id}"], @david.post_log
end
def test_multiple_callbacks
@david.posts_with_multiple_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}", "after_adding#{@thinking.id}",
"after_adding_proc#{@thinking.id}"], @david.post_log
@david.posts_with_multiple_callbacks << @thinking
assert_equal ["before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}", "after_adding#{@thinking.id}",
"after_adding_proc#{@thinking.id}", "before_adding#{@thinking.id}", "before_adding_proc#{@thinking.id}",
"after_adding#{@thinking.id}", "after_adding_proc#{@thinking.id}"], @david.post_log
end
def test_has_many_callbacks_with_create
morten = Author.create :name => "Morten"
post = morten.posts_with_proc_callbacks.create! :title => "Hello", :body => "How are you doing?"
assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
end
def test_has_many_callbacks_with_create!
morten = Author.create! :name => "Morten"
post = morten.posts_with_proc_callbacks.create :title => "Hello", :body => "How are you doing?"
assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
end
def test_has_many_callbacks_for_save_on_parent
jack = Author.new :name => "Jack"
post = jack.posts_with_callbacks.build :title => "Call me back!", :body => "Before you wake up and after you sleep"
callback_log = ["before_adding<new>", "after_adding#{jack.posts_with_callbacks.first.id}"]
assert_equal callback_log, jack.post_log
assert jack.save
assert_equal 1, jack.posts_with_callbacks.count
assert_equal callback_log, jack.post_log
end
def test_has_and_belongs_to_many_add_callback
david = developers(:david)
ar = projects(:active_record)
assert ar.developers_log.empty?
ar.developers_with_callbacks << david
assert_equal ["before_adding#{david.id}", "after_adding#{david.id}"], ar.developers_log
ar.developers_with_callbacks << david
assert_equal ["before_adding#{david.id}", "after_adding#{david.id}", "before_adding#{david.id}",
"after_adding#{david.id}"], ar.developers_log
end
def test_has_and_belongs_to_many_remove_callback
david = developers(:david)
jamis = developers(:jamis)
activerecord = projects(:active_record)
assert activerecord.developers_log.empty?
activerecord.developers_with_callbacks.delete(david)
assert_equal ["before_removing#{david.id}", "after_removing#{david.id}"], activerecord.developers_log
activerecord.developers_with_callbacks.delete(jamis)
assert_equal ["before_removing#{david.id}", "after_removing#{david.id}", "before_removing#{jamis.id}",
"after_removing#{jamis.id}"], activerecord.developers_log
end
def test_has_and_belongs_to_many_remove_callback_on_clear
activerecord = projects(:active_record)
assert activerecord.developers_log.empty?
if activerecord.developers_with_callbacks.size == 0
activerecord.developers << developers(:david)
activerecord.developers << developers(:jamis)
activerecord.reload
assert activerecord.developers_with_callbacks.size == 2
end
log_array = activerecord.developers_with_callbacks.collect {|d| ["before_removing#{d.id}","after_removing#{d.id}"]}.flatten.sort
assert activerecord.developers_with_callbacks.clear
assert_equal log_array, activerecord.developers_log.sort
end
def test_has_many_and_belongs_to_many_callbacks_for_save_on_parent
project = Project.new :name => "Callbacks"
project.developers_with_callbacks.build :name => "Jack", :salary => 95000
callback_log = ["before_adding<new>", "after_adding<new>"]
assert_equal callback_log, project.developers_log
assert project.save
assert_equal 1, project.developers_with_callbacks.count
assert_equal callback_log, project.developers_log
end
def test_dont_add_if_before_callback_raises_exception
assert !@david.unchangable_posts.include?(@authorless)
begin
@david.unchangable_posts << @authorless
rescue Exception => e
end
assert @david.post_log.empty?
assert !@david.unchangable_posts.include?(@authorless)
@david.reload
assert !@david.unchangable_posts.include?(@authorless)
end
end

View file

@ -0,0 +1,110 @@
require 'abstract_unit'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/reply'
class CascadedEagerLoadingTest < Test::Unit::TestCase
fixtures :authors, :mixins, :companies, :posts, :topics
def test_eager_association_loading_with_cascaded_two_levels
authors = Author.find(:all, :include=>{:posts=>:comments}, :order=>"authors.id")
assert_equal 2, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 1, authors[1].posts.size
assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
end
def test_eager_association_loading_with_cascaded_two_levels_and_one_level
authors = Author.find(:all, :include=>[{:posts=>:comments}, :categorizations], :order=>"authors.id")
assert_equal 2, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 1, authors[1].posts.size
assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
assert_equal 1, authors[0].categorizations.size
assert_equal 2, authors[1].categorizations.size
end
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
authors = Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id")
assert_equal 2, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 1, authors[1].posts.size
assert_equal 9, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
end
def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
authors = Author.find(:all, :include=>{:posts=>[:comments, :author]}, :order=>"authors.id")
assert_equal 2, authors.size
assert_equal 5, authors[0].posts.size
assert_equal authors(:david).name, authors[0].name
assert_equal [authors(:david).name], authors[0].posts.collect{|post| post.author.name}.uniq
end
def test_eager_association_loading_with_cascaded_two_levels_with_condition
authors = Author.find(:all, :include=>{:posts=>:comments}, :conditions=>"authors.id=1", :order=>"authors.id")
assert_equal 1, authors.size
assert_equal 5, authors[0].posts.size
end
def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
firms = Firm.find(:all, :include=>{:account=>{:firm=>:account}}, :order=>"companies.id")
assert_equal 2, firms.size
assert_equal firms.first.account, firms.first.account.firm.account
assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account }
assert_equal companies(:first_firm).account.firm.account, assert_no_queries { firms.first.account.firm.account }
end
def test_eager_association_loading_with_has_many_sti
topics = Topic.find(:all, :include => :replies, :order => 'topics.id')
assert_equal topics(:first, :second), topics
assert_no_queries do
assert_equal 1, topics[0].replies.size
assert_equal 0, topics[1].replies.size
end
end
def test_eager_association_loading_with_belongs_to_sti
replies = Reply.find(:all, :include => :topic, :order => 'topics.id')
assert_equal [topics(:second)], replies
assert_equal topics(:first), assert_no_queries { replies.first.topic }
end
def test_eager_association_loading_with_multiple_stis_and_order
author = Author.find(:first, :include => { :posts => [ :special_comments , :very_special_comment ] }, :order => 'authors.name, comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4')
assert_equal authors(:david), author
assert_no_queries do
author.posts.first.special_comments
author.posts.first.very_special_comment
end
end
def test_eager_association_loading_of_stis_with_multiple_references
authors = Author.find(:all, :include => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4')
assert_equal [authors(:david)], authors
assert_no_queries do
authors.first.posts.first.special_comments.first.post.special_comments
authors.first.posts.first.special_comments.first.post.very_special_comment
end
end
end
require 'fixtures/vertex'
require 'fixtures/edge'
class CascadedEagerLoadingTest < Test::Unit::TestCase
fixtures :edges, :vertices
def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
source = Vertex.find(:first, :include=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id')
assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first }
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many
sink = Vertex.find(:first, :include=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC')
assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first }
end
end

View file

@ -0,0 +1,145 @@
require 'abstract_unit'
class Virus < ActiveRecord::Base
belongs_to :octopus
end
class Octopus < ActiveRecord::Base
has_one :virus
end
class Pass < ActiveRecord::Base
belongs_to :bus
end
class Bus < ActiveRecord::Base
has_many :passes
end
class Mess < ActiveRecord::Base
has_and_belongs_to_many :crises
end
class Crisis < ActiveRecord::Base
has_and_belongs_to_many :messes
has_many :analyses, :dependent => :destroy
has_many :successes, :through => :analyses
has_many :dresses, :dependent => :destroy
has_many :compresses, :through => :dresses
end
class Analysis < ActiveRecord::Base
belongs_to :crisis
belongs_to :success
end
class Success < ActiveRecord::Base
has_many :analyses, :dependent => :destroy
has_many :crises, :through => :analyses
end
class Dress < ActiveRecord::Base
belongs_to :crisis
has_many :compresses
end
class Compress < ActiveRecord::Base
belongs_to :dress
end
class EagerSingularizationTest < Test::Unit::TestCase
def setup
if ActiveRecord::Base.connection.supports_migrations?
ActiveRecord::Base.connection.create_table :viri do |t|
t.column :octopus_id, :integer
t.column :species, :string
end
ActiveRecord::Base.connection.create_table :octopi do |t|
t.column :species, :string
end
ActiveRecord::Base.connection.create_table :passes do |t|
t.column :bus_id, :integer
t.column :rides, :integer
end
ActiveRecord::Base.connection.create_table :buses do |t|
t.column :name, :string
end
ActiveRecord::Base.connection.create_table :crises_messes, :id => false do |t|
t.column :crisis_id, :integer
t.column :mess_id, :integer
end
ActiveRecord::Base.connection.create_table :messes do |t|
t.column :name, :string
end
ActiveRecord::Base.connection.create_table :crises do |t|
t.column :name, :string
end
ActiveRecord::Base.connection.create_table :successes do |t|
t.column :name, :string
end
ActiveRecord::Base.connection.create_table :analyses do |t|
t.column :crisis_id, :integer
t.column :success_id, :integer
end
ActiveRecord::Base.connection.create_table :dresses do |t|
t.column :crisis_id, :integer
end
ActiveRecord::Base.connection.create_table :compresses do |t|
t.column :dress_id, :integer
end
@have_tables = true
else
@have_tables = false
end
end
def teardown
ActiveRecord::Base.connection.drop_table :viri
ActiveRecord::Base.connection.drop_table :octopi
ActiveRecord::Base.connection.drop_table :passes
ActiveRecord::Base.connection.drop_table :buses
ActiveRecord::Base.connection.drop_table :crises_messes
ActiveRecord::Base.connection.drop_table :messes
ActiveRecord::Base.connection.drop_table :crises
ActiveRecord::Base.connection.drop_table :successes
ActiveRecord::Base.connection.drop_table :analyses
ActiveRecord::Base.connection.drop_table :dresses
ActiveRecord::Base.connection.drop_table :compresses
end
def test_eager_no_extra_singularization_belongs_to
return unless @have_tables
assert_nothing_raised do
Virus.find(:all, :include => :octopus)
end
end
def test_eager_no_extra_singularization_has_one
return unless @have_tables
assert_nothing_raised do
Octopus.find(:all, :include => :virus)
end
end
def test_eager_no_extra_singularization_has_many
return unless @have_tables
assert_nothing_raised do
Bus.find(:all, :include => :passes)
end
end
def test_eager_no_extra_singularization_has_and_belongs_to_many
return unless @have_tables
assert_nothing_raised do
Crisis.find(:all, :include => :messes)
Mess.find(:all, :include => :crises)
end
end
def test_eager_no_extra_singularization_has_many_through_belongs_to
return unless @have_tables
assert_nothing_raised do
Crisis.find(:all, :include => :successes)
end
end
def test_eager_no_extra_singularization_has_many_through_has_many
return unless @have_tables
assert_nothing_raised do
Crisis.find(:all, :include => :compresses)
end
end
end

View file

@ -0,0 +1,442 @@
require 'abstract_unit'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/company'
require 'fixtures/person'
require 'fixtures/reader'
class EagerAssociationTest < Test::Unit::TestCase
fixtures :posts, :comments, :authors, :categories, :categories_posts,
:companies, :accounts, :tags, :people, :readers
def test_loading_with_one_association
posts = Post.find(:all, :include => :comments)
post = posts.find { |p| p.id == 1 }
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
post = Post.find(:first, :include => :comments, :conditions => "posts.title = 'Welcome to the weblog'")
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
end
def test_loading_conditions_with_or
posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'")
assert_nil posts.detect { |p| p.author_id != authors(:david).id },
"expected to find only david's posts"
end
def test_with_ordering
list = Post.find(:all, :include => :comments, :order => "posts.id DESC")
[:eager_other, :sti_habtm, :sti_post_and_comments, :sti_comments,
:authorless, :thinking, :welcome
].each_with_index do |post, index|
assert_equal posts(post), list[index]
end
end
def test_with_two_tables_in_from_without_getting_double_quoted
posts = Post.find(:all,
:select => "posts.*",
:from => "authors, posts",
:include => :comments,
:conditions => "posts.author_id = authors.id",
:order => "posts.id"
)
assert_equal 2, posts.first.comments.size
end
def test_loading_with_multiple_associations
posts = Post.find(:all, :include => [ :comments, :author, :categories ], :order => "posts.id")
assert_equal 2, posts.first.comments.size
assert_equal 2, posts.first.categories.size
assert posts.first.comments.include?(comments(:greetings))
end
def test_loading_from_an_association
posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id")
assert_equal 2, posts.first.comments.size
end
def test_loading_with_no_associations
assert_nil Post.find(posts(:authorless).id, :include => :author).author
end
def test_eager_association_loading_with_belongs_to
comments = Comment.find(:all, :include => :post)
assert_equal 10, comments.length
titles = comments.map { |c| c.post.title }
assert titles.include?(posts(:welcome).title)
assert titles.include?(posts(:sti_post_and_comments).title)
end
def test_eager_association_loading_with_belongs_to_and_limit
comments = Comment.find(:all, :include => :post, :limit => 5, :order => 'comments.id')
assert_equal 5, comments.length
assert_equal [1,2,3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 4', :limit => 3, :order => 'comments.id')
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset
comments = Comment.find(:all, :include => :post, :limit => 3, :offset => 2, :order => 'comments.id')
assert_equal 3, comments.length
assert_equal [3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
comments = Comment.find(:all, :include => :post, :conditions => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id')
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
comments = Comment.find(:all, :include => :post, :conditions => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id')
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
posts = Post.find(:all, :include => [:author, :very_special_comment], :limit => 1, :order => 'posts.id')
assert_equal 1, posts.length
assert_equal [1], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
posts = Post.find(:all, :include => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id')
assert_equal 1, posts.length
assert_equal [2], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_explicit_join
posts = Post.find(:all, :include => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id')
assert_equal 1, posts.length
end
def test_eager_with_has_many_through
posts_with_comments = people(:michael).posts.find(:all, :include => :comments)
posts_with_author = people(:michael).posts.find(:all, :include => :author )
posts_with_comments_and_author = people(:michael).posts.find(:all, :include => [ :comments, :author ])
assert_equal 2, posts_with_comments.inject(0) { |sum, post| sum += post.comments.size }
assert_equal authors(:david), assert_no_queries { posts_with_author.first.author }
assert_equal authors(:david), assert_no_queries { posts_with_comments_and_author.first.author }
end
def test_eager_with_has_many_through_an_sti_join_model
author = Author.find(:first, :include => :special_post_comments, :order => 'authors.id')
assert_equal [comments(:does_it_hurt)], assert_no_queries { author.special_post_comments }
end
def test_eager_with_has_many_through_an_sti_join_model_with_conditions_on_both
author = Author.find(:first, :include => :special_nonexistant_post_comments, :order => 'authors.id')
assert_equal [], author.special_nonexistant_post_comments
end
def test_eager_with_has_many_through_join_model_with_conditions
assert_equal Author.find(:first, :include => :hello_post_comments,
:order => 'authors.id').hello_post_comments.sort_by(&:id),
Author.find(:first, :order => 'authors.id').hello_post_comments.sort_by(&:id)
end
def test_eager_with_has_many_and_limit
posts = Post.find(:all, :order => 'posts.id asc', :include => [ :author, :comments ], :limit => 2)
assert_equal 2, posts.size
assert_equal 3, posts.inject(0) { |sum, post| sum += post.comments.size }
end
def test_eager_with_has_many_and_limit_and_conditions
if current_adapter?(:OpenBaseAdapter)
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id")
else
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => "posts.body = 'hello'", :order => "posts.id")
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
end
def test_eager_with_has_many_and_limit_and_conditions_array
if current_adapter?(:OpenBaseAdapter)
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id")
else
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "posts.body = ?", 'hello' ], :order => "posts.id")
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
end
def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ])
assert_equal 2, posts.size
count = Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ])
assert_equal count, posts.size
end
def test_eager_with_has_many_and_limit_ond_high_offset
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ])
assert_equal 0, posts.size
end
def test_count_eager_with_has_many_and_limit_ond_high_offset
posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ])
assert_equal 0, posts
end
def test_eager_with_has_many_and_limit_with_no_results
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => "posts.title = 'magic forest'")
assert_equal 0, posts.size
end
def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional
author = authors(:david)
author_posts_without_comments = author.posts.select { |post| post.comments.blank? }
assert_equal author_posts_without_comments.size, author.posts.count(:all, :include => :comments, :conditions => 'comments.id is null')
end
def test_eager_with_has_and_belongs_to_many_and_limit
posts = Post.find(:all, :include => :categories, :order => "posts.id", :limit => 3)
assert_equal 3, posts.size
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
assert_equal 0, posts[2].categories.size
assert posts[0].categories.include?(categories(:technology))
assert posts[1].categories.include?(categories(:general))
end
def test_eager_with_has_many_and_limit_and_conditions_on_the_eagers
posts = authors(:david).posts.find(:all,
:include => :comments,
:conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'",
:limit => 2
)
assert_equal 2, posts.size
count = Post.count(
:include => [ :comments, :author ],
:conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')",
:limit => 2
)
assert_equal count, posts.size
end
def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers
posts = nil
Post.with_scope(:find => {
:include => :comments,
:conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'"
}) do
posts = authors(:david).posts.find(:all, :limit => 2)
assert_equal 2, posts.size
end
Post.with_scope(:find => {
:include => [ :comments, :author ],
:conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')"
}) do
count = Post.count(:limit => 2)
assert_equal count, posts.size
end
end
def test_eager_with_has_many_and_limit_and_scoped_and_explicit_conditions_on_the_eagers
Post.with_scope(:find => { :conditions => "1=1" }) do
posts = authors(:david).posts.find(:all,
:include => :comments,
:conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'",
:limit => 2
)
assert_equal 2, posts.size
count = Post.count(
:include => [ :comments, :author ],
:conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')",
:limit => 2
)
assert_equal count, posts.size
end
end
def test_eager_with_scoped_order_using_association_limiting_without_explicit_scope
posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :order => 'posts.id DESC', :limit => 2)
posts_with_scoped_order = Post.with_scope(:find => {:order => 'posts.id DESC'}) do
Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :limit => 2)
end
assert_equal posts_with_explicit_order, posts_with_scoped_order
end
def test_eager_association_loading_with_habtm
posts = Post.find(:all, :include => :categories, :order => "posts.id")
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
assert_equal 0, posts[2].categories.size
assert posts[0].categories.include?(categories(:technology))
assert posts[1].categories.include?(categories(:general))
end
def test_eager_with_inheritance
posts = SpecialPost.find(:all, :include => [ :comments ])
end
def test_eager_has_one_with_association_inheritance
post = Post.find(4, :include => [ :very_special_comment ])
assert_equal "VerySpecialComment", post.very_special_comment.class.to_s
end
def test_eager_has_many_with_association_inheritance
post = Post.find(4, :include => [ :special_comments ])
post.special_comments.each do |special_comment|
assert_equal "SpecialComment", special_comment.class.to_s
end
end
def test_eager_habtm_with_association_inheritance
post = Post.find(6, :include => [ :special_categories ])
assert_equal 1, post.special_categories.size
post.special_categories.each do |special_category|
assert_equal "SpecialCategory", special_category.class.to_s
end
end
def test_eager_with_has_one_dependent_does_not_destroy_dependent
assert_not_nil companies(:first_firm).account
f = Firm.find(:first, :include => :account,
:conditions => ["companies.name = ?", "37signals"])
assert_not_nil f.account
assert_equal companies(:first_firm, :reload).account, f.account
end
def test_eager_with_multi_table_conditional_properly_counts_the_records_when_using_size
author = authors(:david)
posts_with_no_comments = author.posts.select { |post| post.comments.blank? }
assert_equal posts_with_no_comments.size, author.posts_with_no_comments.size
assert_equal posts_with_no_comments, author.posts_with_no_comments
end
def test_eager_with_invalid_association_reference
assert_raises(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
post = Post.find(6, :include=> :monkeys )
}
assert_raises(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
post = Post.find(6, :include=>[ :monkeys ])
}
assert_raises(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
post = Post.find(6, :include=>[ 'monkeys' ])
}
assert_raises(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
post = Post.find(6, :include=>[ :monkeys, :elephants ])
}
end
def find_all_ordered(className, include=nil)
className.find(:all, :order=>"#{className.table_name}.#{className.primary_key}", :include=>include)
end
def test_limited_eager_with_order
assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title)', :limit => 2, :offset => 1)
assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1)
end
def test_limited_eager_with_multiple_order_columns
assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title), posts.id', :limit => 2, :offset => 1)
assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC, posts.id', :limit => 2, :offset => 1)
end
def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm
# Eager includes of has many and habtm associations aren't necessarily sorted in the same way
def assert_equal_after_sort(item1, item2, item3 = nil)
assert_equal(item1.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id})
assert_equal(item3.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id}) if item3
end
# Test regular association, association with conditions, association with
# STI, and association with conditions assured not to be true
post_types = [:posts, :other_posts, :special_posts]
# test both has_many and has_and_belongs_to_many
[Author, Category].each do |className|
d1 = find_all_ordered(className)
# test including all post types at once
d2 = find_all_ordered(className, post_types)
d1.each_index do |i|
assert_equal(d1[i], d2[i])
assert_equal_after_sort(d1[i].posts, d2[i].posts)
post_types[1..-1].each do |post_type|
# test including post_types together
d3 = find_all_ordered(className, [:posts, post_type])
assert_equal(d1[i], d3[i])
assert_equal_after_sort(d1[i].posts, d3[i].posts)
assert_equal_after_sort(d1[i].send(post_type), d2[i].send(post_type), d3[i].send(post_type))
end
end
end
end
def test_eager_with_multiple_associations_with_same_table_has_one
d1 = find_all_ordered(Firm)
d2 = find_all_ordered(Firm, :account)
d1.each_index do |i|
assert_equal(d1[i], d2[i])
assert_equal(d1[i].account, d2[i].account)
end
end
def test_eager_with_multiple_associations_with_same_table_belongs_to
firm_types = [:firm, :firm_with_basic_id, :firm_with_other_name, :firm_with_condition]
d1 = find_all_ordered(Client)
d2 = find_all_ordered(Client, firm_types)
d1.each_index do |i|
assert_equal(d1[i], d2[i])
firm_types.each { |type| assert_equal(d1[i].send(type), d2[i].send(type)) }
end
end
def test_eager_with_valid_association_as_string_not_symbol
assert_nothing_raised { Post.find(:all, :include => 'comments') }
end
def test_preconfigured_includes_with_belongs_to
author = posts(:welcome).author_with_posts
assert_equal 5, author.posts.size
end
def test_preconfigured_includes_with_has_one
comment = posts(:sti_comments).very_special_comment_with_post
assert_equal posts(:sti_comments), comment.post
end
def test_preconfigured_includes_with_has_many
posts = authors(:david).posts_with_comments
one = posts.detect { |p| p.id == 1 }
assert_equal 5, posts.size
assert_equal 2, one.comments.size
end
def test_preconfigured_includes_with_habtm
posts = authors(:david).posts_with_categories
one = posts.detect { |p| p.id == 1 }
assert_equal 5, posts.size
assert_equal 2, one.categories.size
end
def test_preconfigured_includes_with_has_many_and_habtm
posts = authors(:david).posts_with_comments_and_categories
one = posts.detect { |p| p.id == 1 }
assert_equal 5, posts.size
assert_equal 2, one.comments.size
assert_equal 2, one.categories.size
end
def test_count_with_include
if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15")
elsif current_adapter?(:OpenBaseAdapter)
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15")
else
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15")
end
end
end

View file

@ -0,0 +1,47 @@
require 'abstract_unit'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/project'
require 'fixtures/developer'
class AssociationsExtensionsTest < Test::Unit::TestCase
fixtures :projects, :developers, :developers_projects, :comments, :posts
def test_extension_on_has_many
assert_equal comments(:more_greetings), posts(:welcome).comments.find_most_recent
end
def test_extension_on_habtm
assert_equal projects(:action_controller), developers(:david).projects.find_most_recent
end
def test_named_extension_on_habtm
assert_equal projects(:action_controller), developers(:david).projects_extended_by_name.find_most_recent
end
def test_named_two_extensions_on_habtm
assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_twice.find_most_recent
assert_equal projects(:active_record), developers(:david).projects_extended_by_name_twice.find_least_recent
end
def test_named_extension_and_block_on_habtm
assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_and_block.find_most_recent
assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent
end
def test_marshalling_extensions
david = developers(:david)
assert_equal projects(:action_controller), david.projects.find_most_recent
david = Marshal.load(Marshal.dump(david))
assert_equal projects(:action_controller), david.projects.find_most_recent
end
def test_marshalling_named_extensions
david = developers(:david)
assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
david = Marshal.load(Marshal.dump(david))
assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
end
end

View file

@ -0,0 +1,88 @@
require 'abstract_unit'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
class InnerJoinAssociationTest < Test::Unit::TestCase
fixtures :authors, :posts, :comments, :categories, :categories_posts, :categorizations
def test_construct_finder_sql_creates_inner_joins
sql = Author.send(:construct_finder_sql, :joins => :posts)
assert_match /INNER JOIN `?posts`? ON `?posts`?.author_id = authors.id/, sql
end
def test_construct_finder_sql_cascades_inner_joins
sql = Author.send(:construct_finder_sql, :joins => {:posts => :comments})
assert_match /INNER JOIN `?posts`? ON `?posts`?.author_id = authors.id/, sql
assert_match /INNER JOIN `?comments`? ON `?comments`?.post_id = posts.id/, sql
end
def test_construct_finder_sql_inner_joins_through_associations
sql = Author.send(:construct_finder_sql, :joins => :categorized_posts)
assert_match /INNER JOIN `?categorizations`?.*INNER JOIN `?posts`?/, sql
end
def test_construct_finder_sql_applies_association_conditions
sql = Author.send(:construct_finder_sql, :joins => :categories_like_general, :conditions => "TERMINATING_MARKER")
assert_match /INNER JOIN `?categories`? ON.*AND.*`?General`?.*TERMINATING_MARKER/, sql
end
def test_construct_finder_sql_unpacks_nested_joins
sql = Author.send(:construct_finder_sql, :joins => {:posts => [[:comments]]})
assert_no_match /inner join.*inner join.*inner join/i, sql, "only two join clauses should be present"
assert_match /INNER JOIN `?posts`? ON `?posts`?.author_id = authors.id/, sql
assert_match /INNER JOIN `?comments`? ON `?comments`?.post_id = `?posts`?.id/, sql
end
def test_construct_finder_sql_ignores_empty_joins_hash
sql = Author.send(:construct_finder_sql, :joins => {})
assert_no_match /JOIN/i, sql
end
def test_construct_finder_sql_ignores_empty_joins_array
sql = Author.send(:construct_finder_sql, :joins => [])
assert_no_match /JOIN/i, sql
end
def test_find_with_implicit_inner_joins_honors_readonly_without_select
authors = Author.find(:all, :joins => :posts)
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| a.readonly? }, "expected all authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_with_select
authors = Author.find(:all, :select => 'authors.*', :joins => :posts)
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_false
authors = Author.find(:all, :joins => :posts, :readonly => false)
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_does_not_set_associations
authors = Author.find(:all, :select => 'authors.*', :joins => :posts)
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.send(:instance_variables).include?("@posts")}, "expected no authors to have the @posts association loaded"
end
def test_count_honors_implicit_inner_joins
real_count = Author.find(:all).sum{|a| a.posts.count }
assert_equal real_count, Author.count(:joins => :posts), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins
real_count = Author.find(:all).sum{|a| a.posts.count }
assert_equal real_count, Author.calculate(:count, 'authors.id', :joins => :posts), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
real_count = Author.find(:all).select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
authors_with_welcoming_post_titles = Author.calculate(:count, 'authors.id', :joins => :posts, :distinct => true, :conditions => "posts.title like 'Welcome%'")
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
end

View file

@ -0,0 +1,559 @@
require 'abstract_unit'
require 'fixtures/tag'
require 'fixtures/tagging'
require 'fixtures/post'
require 'fixtures/item'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
require 'fixtures/vertex'
require 'fixtures/edge'
require 'fixtures/book'
require 'fixtures/citation'
class AssociationsJoinModelTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books
def test_has_many
assert authors(:david).categories.include?(categories(:general))
end
def test_has_many_inherited
assert authors(:mary).categories.include?(categories(:sti_test))
end
def test_inherited_has_many
assert categories(:sti_test).authors.include?(authors(:mary))
end
def test_has_many_uniq_through_join_model
assert_equal 2, authors(:mary).categorized_posts.size
assert_equal 1, authors(:mary).unique_categorized_posts.size
end
def test_has_many_uniq_through_count
author = authors(:mary)
assert !authors(:mary).unique_categorized_posts.loaded?
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
assert !authors(:mary).unique_categorized_posts.loaded?
end
def test_polymorphic_has_many
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end
def test_polymorphic_has_one
assert_equal taggings(:welcome_general), posts(:welcome).tagging
end
def test_polymorphic_belongs_to
assert_equal posts(:welcome), posts(:welcome).taggings.first.taggable
end
def test_polymorphic_has_many_going_through_join_model
assert_equal tags(:general), tag = posts(:welcome).tags.first
assert_no_queries do
tag.tagging
end
end
def test_count_polymorphic_has_many
assert_equal 1, posts(:welcome).taggings.count
assert_equal 1, posts(:welcome).tags.count
end
def test_polymorphic_has_many_going_through_join_model_with_find
assert_equal tags(:general), tag = posts(:welcome).tags.find(:first)
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection
assert_equal tags(:general), tag = posts(:welcome).funky_tags.first
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection_with_find
assert_equal tags(:general), tag = posts(:welcome).funky_tags.find(:first)
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_disabled_include
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
assert_queries 1 do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
tag.author_id
end
def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
assert_equal tags(:misc), taggings(:welcome_general).super_tag
assert_equal tags(:misc), posts(:welcome).super_tags.first
end
def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class
post = SubStiPost.create :title => 'SubStiPost', :body => 'SubStiPost body'
assert_instance_of SubStiPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
assert_equal "SubStiPost", tagging.taggable_type
end
def test_polymorphic_has_many_going_through_join_model_with_inheritance
assert_equal tags(:general), posts(:thinking).tags.first
end
def test_polymorphic_has_many_going_through_join_model_with_inheritance_with_custom_class_name
assert_equal tags(:general), posts(:thinking).funky_tags.first
end
def test_polymorphic_has_many_create_model_with_inheritance
post = posts(:thinking)
assert_instance_of SpecialPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
assert_equal "Post", tagging.taggable_type
end
def test_polymorphic_has_one_create_model_with_inheritance
tagging = tags(:misc).create_tagging(:taggable => posts(:thinking))
assert_equal "Post", tagging.taggable_type
end
def test_set_polymorphic_has_many
tagging = tags(:misc).taggings.create
posts(:thinking).taggings << tagging
assert_equal "Post", tagging.taggable_type
end
def test_set_polymorphic_has_one
tagging = tags(:misc).taggings.create
posts(:thinking).tagging = tagging
assert_equal "Post", tagging.taggable_type
end
def test_create_polymorphic_has_many_with_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_bang_polymorphic_with_has_many_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create!(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_polymorphic_has_one_with_scope
old_count = Tagging.count
tagging = posts(:welcome).tagging.create(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, Tagging.count
end
def test_delete_polymorphic_has_many_with_delete_all
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDeleteAll'
post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_many_with_destroy
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDestroy'
post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_many_with_nullify
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyNullify'
post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
old_count = Tagging.count
post.destroy
assert_equal old_count, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_one_with_destroy
assert posts(:welcome).tagging
posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneDestroy'
post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_nil posts(:welcome).tagging(true)
end
def test_delete_polymorphic_has_one_with_nullify
assert posts(:welcome).tagging
posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneNullify'
post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
old_count = Tagging.count
post.destroy
assert_equal old_count, Tagging.count
assert_nil posts(:welcome).tagging(true)
end
def test_has_many_with_piggyback
assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
end
def test_include_has_many_through
posts = Post.find(:all, :order => 'posts.id')
posts_with_authors = Post.find(:all, :include => :authors, :order => 'posts.id')
assert_equal posts.length, posts_with_authors.length
posts.length.times do |i|
assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
end
end
def test_include_polymorphic_has_one
post = Post.find_by_id(posts(:welcome).id, :include => :tagging)
tagging = taggings(:welcome_general)
assert_no_queries do
assert_equal tagging, post.tagging
end
end
def test_include_polymorphic_has_one_defined_in_abstract_parent
item = Item.find_by_id(items(:dvd).id, :include => :tagging)
tagging = taggings(:godfather)
assert_no_queries do
assert_equal tagging, item.tagging
end
end
def test_include_polymorphic_has_many_through
posts = Post.find(:all, :order => 'posts.id')
posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id')
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
end
end
def test_include_polymorphic_has_many
posts = Post.find(:all, :order => 'posts.id')
posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id')
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
end
end
def test_has_many_find_all
assert_equal [categories(:general)], authors(:david).categories.find(:all)
end
def test_has_many_find_first
assert_equal categories(:general), authors(:david).categories.find(:first)
end
def test_has_many_with_hash_conditions
assert_equal categories(:general), authors(:david).categories_like_general.find(:first)
end
def test_has_many_find_conditions
assert_equal categories(:general), authors(:david).categories.find(:first, :conditions => "categories.name = 'General'")
assert_equal nil, authors(:david).categories.find(:first, :conditions => "categories.name = 'Technology'")
end
def test_has_many_class_methods_called_by_method_missing
assert_equal categories(:general), authors(:david).categories.find_all_by_name('General').first
assert_equal nil, authors(:david).categories.find_by_name('Technology')
end
def test_has_many_going_through_join_model_with_custom_foreign_key
assert_equal [], posts(:thinking).authors
assert_equal [authors(:mary)], posts(:authorless).authors
end
def test_belongs_to_polymorphic_with_counter_cache
assert_equal 0, posts(:welcome)[:taggings_count]
tagging = posts(:welcome).taggings.create(:tag => tags(:general))
assert_equal 1, posts(:welcome, :reload)[:taggings_count]
tagging.destroy
assert posts(:welcome, :reload)[:taggings_count].zero?
end
def test_unavailable_through_reflection
assert_raises (ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings }
end
def test_has_many_through_join_model_with_conditions
assert_equal [], posts(:welcome).invalid_taggings
assert_equal [], posts(:welcome).invalid_tags
end
def test_has_many_polymorphic
assert_raises ActiveRecord::HasManyThroughAssociationPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggables
end
assert_raises ActiveRecord::EagerLoadPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable)
end
end
def test_has_many_polymorphic_with_source_type
assert_equal posts(:welcome, :thinking), tags(:general).tagged_posts
end
def test_eager_has_many_polymorphic_with_source_type
tag_with_include = Tag.find(tags(:general).id, :include => :tagged_posts)
desired = posts(:welcome, :thinking)
assert_no_queries do
assert_equal desired, tag_with_include.tagged_posts
end
end
def test_has_many_through_has_many_find_all
assert_equal comments(:greetings), authors(:david).comments.find(:all, :order => 'comments.id').first
end
def test_has_many_through_has_many_find_all_with_custom_class
assert_equal comments(:greetings), authors(:david).funky_comments.find(:all, :order => 'comments.id').first
end
def test_has_many_through_has_many_find_first
assert_equal comments(:greetings), authors(:david).comments.find(:first, :order => 'comments.id')
end
def test_has_many_through_has_many_find_conditions
options = { :conditions => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
assert_equal comments(:does_it_hurt), authors(:david).comments.find(:first, options)
end
def test_has_many_through_has_many_find_by_id
assert_equal comments(:more_greetings), authors(:david).comments.find(2)
end
def test_has_many_through_polymorphic_has_one
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tagging }
end
def test_has_many_through_polymorphic_has_many
assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.uniq.sort_by { |t| t.id }
end
def test_include_has_many_through_polymorphic_has_many
author = Author.find_by_id(authors(:david).id, :include => :taggings)
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
end
end
def test_has_many_through_has_many_through
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tags }
end
def test_has_many_through_habtm
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).post_categories }
end
def test_eager_load_has_many_through_has_many
author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id'
SpecialComment.new; VerySpecialComment.new
assert_no_queries do
assert_equal [1,2,3,5,6,7,8,9,10], author.comments.collect(&:id)
end
end
def test_eager_load_has_many_through_has_many_with_conditions
post = Post.find(:first, :include => :invalid_tags)
assert_no_queries do
post.invalid_tags
end
end
def test_eager_belongs_to_and_has_one_not_singularized
assert_nothing_raised do
Author.find(:first, :include => :author_address)
AuthorAddress.find(:first, :include => :author)
end
end
def test_self_referential_has_many_through
assert_equal [authors(:mary)], authors(:david).favorite_authors
assert_equal [], authors(:mary).favorite_authors
end
def test_add_to_self_referential_has_many_through
new_author = Author.create(:name => "Bob")
authors(:david).author_favorites.create :favorite_author => new_author
assert_equal new_author, authors(:david).reload.favorite_authors.first
end
def test_has_many_through_uses_conditions_specified_on_the_has_many_association
author = Author.find(:first)
assert !author.comments.blank?
assert author.nonexistant_comments.blank?
end
def test_has_many_through_uses_correct_attributes
assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"]
end
def test_raise_error_when_adding_new_record_to_has_many_through
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags << tags(:general).clone }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).clone.tags << tags(:general) }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.build }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.new }
end
def test_create_associate_when_adding_to_has_many_through
count = posts(:thinking).tags.count
push = Tag.create!(:name => 'pushme')
post_thinking = posts(:thinking)
assert_nothing_raised { post_thinking.tags << push }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 1, post_thinking.tags.size)
assert_equal(count + 1, post_thinking.tags(true).size)
assert_kind_of Tag, post_thinking.tags.create!(:name => 'foo')
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 2, post_thinking.tags.size)
assert_equal(count + 2, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => 'abc'), Tag.create!(:name => 'def')) }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 4, post_thinking.tags.size)
assert_equal(count + 4, post_thinking.tags(true).size)
# Raises if the wrong reflection name is used to set the Edge belongs_to
assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
end
def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
author = authors(:david)
assert_equal 9, author.comments.size
assert !author.comments.loaded?
end
uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do
def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
author = authors(:david)
author.stubs(:read_attribute).with('comments_count').returns(100)
assert_equal 100, author.comments.size
assert !author.comments.loaded?
end
end
def test_adding_junk_to_has_many_through_should_raise_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
end
def test_adding_to_has_many_through_should_return_self
tags = posts(:thinking).tags
assert_equal tags, posts(:thinking).tags.push(tags(:general))
end
def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id
count = books(:awdr).references.count
references_before = books(:awdr).references
book = Book.create!(:name => 'Getting Real')
book_awdr = books(:awdr)
book_awdr.references << book
assert_equal(count + 1, book_awdr.references(true).size)
assert_nothing_raised { book_awdr.references.delete(book) }
assert_equal(count, book_awdr.references.size)
assert_equal(count, book_awdr.references(true).size)
assert_equal(references_before.sort, book_awdr.references.sort)
end
def test_delete_associate_when_deleting_from_has_many_through
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags
tag = Tag.create!(:name => 'doomed')
post_thinking = posts(:thinking)
post_thinking.tags << tag
assert_equal(count + 1, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.delete(tag) }
assert_equal(count, post_thinking.tags.size)
assert_equal(count, post_thinking.tags(true).size)
assert_equal(tags_before.sort, post_thinking.tags.sort)
end
def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags
doomed = Tag.create!(:name => 'doomed')
doomed2 = Tag.create!(:name => 'doomed2')
quaked = Tag.create!(:name => 'quaked')
post_thinking = posts(:thinking)
post_thinking.tags << doomed << doomed2
assert_equal(count + 2, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.delete(doomed, doomed2, quaked) }
assert_equal(count, post_thinking.tags.size)
assert_equal(count, post_thinking.tags(true).size)
assert_equal(tags_before.sort, post_thinking.tags.sort)
end
def test_deleting_junk_from_has_many_through_should_raise_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete("Uhh what now?") }
end
def test_has_many_through_sum_uses_calculations
assert_nothing_raised { authors(:david).comments.sum(:post_id) }
end
def test_has_many_through_has_many_with_sti
assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments
end
def test_uniq_has_many_through_should_retain_order
comment_ids = authors(:david).comments.map(&:id)
assert_equal comment_ids.sort, authors(:david).ordered_uniq_comments.map(&:id)
assert_equal comment_ids.sort.reverse, authors(:david).ordered_uniq_comments_desc.map(&:id)
end
private
# create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency)
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
Post.find(post_id).update_attribute :type, class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
klass.set_table_name 'posts'
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
klass.find(post_id)
end
end

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,146 @@
require 'abstract_unit'
require 'fixtures/topic'
class AttributeMethodsTest < Test::Unit::TestCase
fixtures :topics
def setup
@old_suffixes = ActiveRecord::Base.send(:attribute_method_suffixes).dup
@target = Class.new(ActiveRecord::Base)
@target.table_name = 'topics'
end
def teardown
ActiveRecord::Base.send(:attribute_method_suffixes).clear
ActiveRecord::Base.attribute_method_suffix *@old_suffixes
end
def test_match_attribute_method_query_returns_match_data
assert_not_nil md = @target.match_attribute_method?('title=')
assert_equal 'title', md.pre_match
assert_equal ['='], md.captures
%w(_hello_world ist! _maybe?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
assert_not_nil md = @target.match_attribute_method?("title#{suffix}")
assert_equal 'title', md.pre_match
assert_equal [suffix], md.captures
end
end
def test_declared_attribute_method_affects_respond_to_and_method_missing
topic = @target.new(:title => 'Budget')
assert topic.respond_to?('title')
assert_equal 'Budget', topic.title
assert !topic.respond_to?('title_hello_world')
assert_raise(NoMethodError) { topic.title_hello_world }
%w(_hello_world _it! _candidate= able?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
meth = "title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
def test_should_unserialize_attributes_for_frozen_records
myobj = {:value1 => :value2}
topic = Topic.create("content" => myobj)
topic.freeze
assert_equal myobj, topic.content
end
def test_kernel_methods_not_implemented_in_activerecord
%w(test name display y).each do |method|
assert_equal false, ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined"
end
end
def test_primary_key_implemented
assert_equal true, Class.new(ActiveRecord::Base).instance_method_already_implemented?('id')
end
def test_defined_kernel_methods_implemented_in_model
%w(test name display y).each do |method|
klass = Class.new ActiveRecord::Base
klass.class_eval "def #{method}() 'defined #{method}' end"
assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined"
end
end
def test_defined_kernel_methods_implemented_in_model_abstract_subclass
%w(test name display y).each do |method|
abstract = Class.new ActiveRecord::Base
abstract.class_eval "def #{method}() 'defined #{method}' end"
abstract.abstract_class = true
klass = Class.new abstract
assert_equal true, klass.instance_method_already_implemented?(method), "##{method} is not defined"
end
end
def test_raises_dangerous_attribute_error_when_defining_activerecord_method_in_model
%w(save create_or_update).each do |method|
klass = Class.new ActiveRecord::Base
klass.class_eval "def #{method}() 'defined #{method}' end"
assert_raises ActiveRecord::DangerousAttributeError do
klass.instance_method_already_implemented?(method)
end
end
end
def test_only_time_related_columns_are_meant_to_be_cached_by_default
expected = %w(datetime timestamp time date).sort
assert_equal expected, ActiveRecord::Base.attribute_types_cached_by_default.map(&:to_s).sort
end
def test_declaring_attributes_as_cached_adds_them_to_the_attributes_cached_by_default
default_attributes = Topic.cached_attributes
Topic.cache_attributes :replies_count
expected = default_attributes + ["replies_count"]
assert_equal expected.sort, Topic.cached_attributes.sort
Topic.instance_variable_set "@cached_attributes", nil
end
def test_time_related_columns_are_actually_cached
column_types = %w(datetime timestamp time date).map(&:to_sym)
column_names = Topic.columns.select{|c| column_types.include?(c.type) }.map(&:name)
assert_equal column_names.sort, Topic.cached_attributes.sort
assert_equal time_related_columns_on_topic.sort, Topic.cached_attributes.sort
end
def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_else
t = topics(:first)
cache = t.instance_variable_get "@attributes_cache"
assert_not_nil cache
assert cache.empty?
all_columns = Topic.columns.map(&:name)
cached_columns = time_related_columns_on_topic
uncached_columns = all_columns - cached_columns
all_columns.each do |attr_name|
attribute_gets_cached = Topic.cache_attribute?(attr_name)
val = t.send attr_name unless attr_name == "type"
if attribute_gets_cached
assert cached_columns.include?(attr_name)
assert_equal val, cache[attr_name]
else
assert uncached_columns.include?(attr_name)
assert !cache.include?(attr_name)
end
end
end
private
def time_related_columns_on_topic
Topic.columns.select{|c| [:time, :date, :datetime, :timestamp].include?(c.type)}.map(&:name)
end
end

1745
vendor/rails/activerecord/test/base_test.rb vendored Executable file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
require 'abstract_unit'
# Without using prepared statements, it makes no sense to test
# BLOB data with SQL Server, because the length of a statement is
# limited to 8KB.
#
# Without using prepared statements, it makes no sense to test
# BLOB data with DB2 or Firebird, because the length of a statement
# is limited to 32KB.
unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
require 'fixtures/binary'
class BinaryTest < Test::Unit::TestCase
FIXTURES = %w(flowers.jpg example.log)
def test_load_save
Binary.delete_all
FIXTURES.each do |filename|
data = File.read("#{File.dirname(__FILE__)}/fixtures/#{filename}").freeze
bin = Binary.new(:data => data)
assert_equal data, bin.data, 'Newly assigned data differs from original'
bin.save!
assert_equal data, bin.data, 'Data differs from original after save'
assert_equal data, bin.reload.data, 'Reloaded data differs from original'
end
end
end
end

View file

@ -0,0 +1,251 @@
require 'abstract_unit'
require 'fixtures/company'
require 'fixtures/topic'
Company.has_many :accounts
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
end
class CalculationsTest < Test::Unit::TestCase
fixtures :companies, :accounts, :topics
def test_should_sum_field
assert_equal 318, Account.sum(:credit_limit)
end
def test_should_average_field
value = Account.average(:credit_limit)
assert_kind_of Float, value
assert_in_delta 53.0, value, 0.001
end
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
end
def test_should_get_maximum_of_field_with_include
assert_equal 50, Account.maximum(:credit_limit, :include => :firm, :conditions => "companies.name != 'Summit'")
end
def test_should_get_maximum_of_field_with_scoped_include
Account.with_scope :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do
assert_equal 50, Account.maximum(:credit_limit)
end
end
def test_should_get_minimum_of_field
assert_equal 50, Account.minimum(:credit_limit)
end
def test_should_group_by_field
c = Account.sum(:credit_limit, :group => :firm_id)
[1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
end
def test_should_group_by_summed_field
c = Account.sum(:credit_limit, :group => :firm_id)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_order_by_grouped_field
c = Account.sum(:credit_limit, :group => :firm_id, :order => "firm_id")
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
c = Account.sum(:credit_limit, :group => :firm_id, :order => "sum_credit_limit desc, firm_id")
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2, :offset => 1)
assert_equal [2, 6], c.keys.compact
end
def test_should_group_by_summed_field_having_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => 'sum(credit_limit) > 50')
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_association
c = Account.sum(:credit_limit, :group => :firm)
assert_equal 50, c[companies(:first_firm)]
assert_equal 105, c[companies(:rails_core)]
assert_equal 60, c[companies(:first_client)]
end
def test_should_sum_field_with_conditions
assert_equal 105, Account.sum(:credit_limit, :conditions => 'firm_id = 6')
end
def test_should_group_by_summed_field_with_conditions
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
:group => :firm_id)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_with_conditions_and_having
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
:group => :firm_id,
:having => 'sum(credit_limit) > 60')
assert_nil c[1]
assert_equal 105, c[6]
assert_nil c[2]
end
def test_should_group_by_fields_with_table_alias
c = Account.sum(:credit_limit, :group => 'accounts.firm_id')
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_with_invalid_field
assert_equal 6, Account.calculate(:count, '*')
assert_equal 6, Account.calculate(:count, :all)
end
def test_should_calculate_grouped_with_invalid_field
c = Account.count(:all, :group => 'accounts.firm_id')
assert_equal 1, c[1]
assert_equal 2, c[6]
assert_equal 1, c[2]
end
def test_should_calculate_grouped_association_with_invalid_field
c = Account.count(:all, :group => :firm)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end
uses_mocha 'group_by_non_numeric_foreign_key_association' do
def test_should_group_by_association_with_non_numeric_foreign_key
ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])
firm = mock()
firm.expects(:id).returns("ABC")
firm.expects(:class).returns(Firm)
Company.expects(:find).with(["ABC"]).returns([firm])
column = mock()
column.expects(:name).at_least_once.returns(:firm_id)
column.expects(:type_cast).with("ABC").returns("ABC")
Account.expects(:columns).at_least_once.returns([column])
c = Account.count(:all, :group => :firm)
assert_equal Firm, c.first.first.class
assert_equal 1, c.first.last
end
end
def test_should_not_modify_options_when_using_includes
options = {:conditions => 'companies.id > 1', :include => :firm}
options_copy = options.dup
Account.count(:all, options)
assert_equal options_copy, options
end
def test_should_calculate_grouped_by_function
c = Company.count(:all, :group => "UPPER(#{QUOTED_TYPE})")
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 3, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_calculate_grouped_by_function_with_table_alias
c = Company.count(:all, :group => "UPPER(companies.#{QUOTED_TYPE})")
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 3, c['CLIENT']
assert_equal 2, c['FIRM']
end
def test_should_not_overshadow_enumerable_sum
assert_equal 6, [1, 2, 3].sum(&:abs)
end
def test_should_sum_scoped_field
assert_equal 15, companies(:rails_core).companies.sum(:id)
end
def test_should_sum_scoped_field_with_conditions
assert_equal 8, companies(:rails_core).companies.sum(:id, :conditions => 'id > 7')
end
def test_should_group_by_scoped_field
c = companies(:rails_core).companies.sum(:id, :group => :name)
assert_equal 7, c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_group_by_summed_field_with_conditions_and_having
c = companies(:rails_core).companies.sum(:id, :group => :name,
:having => 'sum(id) > 7')
assert_nil c['Leetsoft']
assert_equal 8, c['Jadedpixel']
end
def test_should_reject_invalid_options
assert_nothing_raised do
[:count, :sum].each do |func|
# empty options are valid
Company.send(:validate_calculation_options, func)
# these options are valid for all calculations
[:select, :conditions, :joins, :order, :group, :having, :distinct].each do |opt|
Company.send(:validate_calculation_options, func, opt => true)
end
end
# :include is only valid on :count
Company.send(:validate_calculation_options, :count, :include => true)
end
assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :sum, :foo => :bar) }
assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :count, :foo => :bar) }
end
def test_should_count_selected_field_with_include
assert_equal 6, Account.count(:distinct => true, :include => :firm)
assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
end
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
def test_count_with_column_and_options_parameter
assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50")
end
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated { Account.count }
end
def test_count_with_too_many_parameters_raises
assert_raise(ArgumentError) { Account.count(1, 2, 3) }
end
end

View file

@ -0,0 +1,400 @@
require 'abstract_unit'
class CallbackDeveloper < ActiveRecord::Base
set_table_name 'developers'
class << self
def callback_string(callback_method)
"history << [#{callback_method.to_sym.inspect}, :string]"
end
def callback_proc(callback_method)
Proc.new { |model| model.history << [callback_method, :proc] }
end
def define_callback_method(callback_method)
define_method("#{callback_method}_method") do |model|
model.history << [callback_method, :method]
end
end
def callback_object(callback_method)
klass = Class.new
klass.send(:define_method, callback_method) do |model|
model.history << [callback_method, :object]
end
klass.new
end
end
ActiveRecord::Callbacks::CALLBACKS.each do |callback_method|
callback_method_sym = callback_method.to_sym
define_callback_method(callback_method_sym)
send(callback_method, callback_method_sym)
send(callback_method, callback_string(callback_method_sym))
send(callback_method, callback_proc(callback_method_sym))
send(callback_method, callback_object(callback_method_sym))
send(callback_method) { |model| model.history << [callback_method_sym, :block] }
end
def history
@history ||= []
end
# after_initialize and after_find are invoked only if instance methods have been defined.
def after_initialize
end
def after_find
end
end
class ParentDeveloper < ActiveRecord::Base
set_table_name 'developers'
attr_accessor :after_save_called
before_validation {|record| record.after_save_called = true}
end
class ChildDeveloper < ParentDeveloper
end
class RecursiveCallbackDeveloper < ActiveRecord::Base
set_table_name 'developers'
before_save :on_before_save
after_save :on_after_save
attr_reader :on_before_save_called, :on_after_save_called
def on_before_save
@on_before_save_called ||= 0
@on_before_save_called += 1
save unless @on_before_save_called > 1
end
def on_after_save
@on_after_save_called ||= 0
@on_after_save_called += 1
save unless @on_after_save_called > 1
end
end
class ImmutableDeveloper < ActiveRecord::Base
set_table_name 'developers'
validates_inclusion_of :salary, :in => 50000..200000
before_save :cancel
before_destroy :cancel
def cancelled?
@cancelled == true
end
private
def cancel
@cancelled = true
false
end
end
class ImmutableMethodDeveloper < ActiveRecord::Base
set_table_name 'developers'
validates_inclusion_of :salary, :in => 50000..200000
def cancelled?
@cancelled == true
end
def before_save
@cancelled = true
false
end
def before_destroy
@cancelled = true
false
end
end
class CallbackCancellationDeveloper < ActiveRecord::Base
set_table_name 'developers'
def before_create
false
end
end
class CallbacksTest < Test::Unit::TestCase
fixtures :developers
def test_initialize
david = CallbackDeveloper.new
assert_equal [
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
], david.history
end
def test_find
david = CallbackDeveloper.find(1)
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
], david.history
end
def test_new_valid?
david = CallbackDeveloper.new
david.valid?
assert_equal [
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_validation, :string ],
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
[ :before_validation_on_create, :string ],
[ :before_validation_on_create, :proc ],
[ :before_validation_on_create, :object ],
[ :before_validation_on_create, :block ],
[ :after_validation, :string ],
[ :after_validation, :proc ],
[ :after_validation, :object ],
[ :after_validation, :block ],
[ :after_validation_on_create, :string ],
[ :after_validation_on_create, :proc ],
[ :after_validation_on_create, :object ],
[ :after_validation_on_create, :block ]
], david.history
end
def test_existing_valid?
david = CallbackDeveloper.find(1)
david.valid?
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_validation, :string ],
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
[ :before_validation_on_update, :string ],
[ :before_validation_on_update, :proc ],
[ :before_validation_on_update, :object ],
[ :before_validation_on_update, :block ],
[ :after_validation, :string ],
[ :after_validation, :proc ],
[ :after_validation, :object ],
[ :after_validation, :block ],
[ :after_validation_on_update, :string ],
[ :after_validation_on_update, :proc ],
[ :after_validation_on_update, :object ],
[ :after_validation_on_update, :block ]
], david.history
end
def test_create
david = CallbackDeveloper.create('name' => 'David', 'salary' => 1000000)
assert_equal [
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_validation, :string ],
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
[ :before_validation_on_create, :string ],
[ :before_validation_on_create, :proc ],
[ :before_validation_on_create, :object ],
[ :before_validation_on_create, :block ],
[ :after_validation, :string ],
[ :after_validation, :proc ],
[ :after_validation, :object ],
[ :after_validation, :block ],
[ :after_validation_on_create, :string ],
[ :after_validation_on_create, :proc ],
[ :after_validation_on_create, :object ],
[ :after_validation_on_create, :block ],
[ :before_save, :string ],
[ :before_save, :proc ],
[ :before_save, :object ],
[ :before_save, :block ],
[ :before_create, :string ],
[ :before_create, :proc ],
[ :before_create, :object ],
[ :before_create, :block ],
[ :after_create, :string ],
[ :after_create, :proc ],
[ :after_create, :object ],
[ :after_create, :block ],
[ :after_save, :string ],
[ :after_save, :proc ],
[ :after_save, :object ],
[ :after_save, :block ]
], david.history
end
def test_save
david = CallbackDeveloper.find(1)
david.save
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_validation, :string ],
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
[ :before_validation_on_update, :string ],
[ :before_validation_on_update, :proc ],
[ :before_validation_on_update, :object ],
[ :before_validation_on_update, :block ],
[ :after_validation, :string ],
[ :after_validation, :proc ],
[ :after_validation, :object ],
[ :after_validation, :block ],
[ :after_validation_on_update, :string ],
[ :after_validation_on_update, :proc ],
[ :after_validation_on_update, :object ],
[ :after_validation_on_update, :block ],
[ :before_save, :string ],
[ :before_save, :proc ],
[ :before_save, :object ],
[ :before_save, :block ],
[ :before_update, :string ],
[ :before_update, :proc ],
[ :before_update, :object ],
[ :before_update, :block ],
[ :after_update, :string ],
[ :after_update, :proc ],
[ :after_update, :object ],
[ :after_update, :block ],
[ :after_save, :string ],
[ :after_save, :proc ],
[ :after_save, :object ],
[ :after_save, :block ]
], david.history
end
def test_destroy
david = CallbackDeveloper.find(1)
david.destroy
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_destroy, :string ],
[ :before_destroy, :proc ],
[ :before_destroy, :object ],
[ :before_destroy, :block ],
[ :after_destroy, :string ],
[ :after_destroy, :proc ],
[ :after_destroy, :object ],
[ :after_destroy, :block ]
], david.history
end
def test_delete
david = CallbackDeveloper.find(1)
CallbackDeveloper.delete(david.id)
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
], david.history
end
def test_before_save_returning_false
david = ImmutableDeveloper.find(1)
assert david.valid?
assert !david.save
assert_raises(ActiveRecord::RecordNotSaved) { david.save! }
david = ImmutableDeveloper.find(1)
david.salary = 10_000_000
assert !david.valid?
assert !david.save
assert_raises(ActiveRecord::RecordInvalid) { david.save! }
end
def test_before_create_returning_false
someone = CallbackCancellationDeveloper.new
assert someone.valid?
assert !someone.save
end
def test_before_destroy_returning_false
david = ImmutableDeveloper.find(1)
assert !david.destroy
assert_not_nil ImmutableDeveloper.find_by_id(1)
end
def test_zzz_callback_returning_false # must be run last since we modify CallbackDeveloper
david = CallbackDeveloper.find(1)
CallbackDeveloper.before_validation proc { |model| model.history << [:before_validation, :returning_false]; return false }
CallbackDeveloper.before_validation proc { |model| model.history << [:before_validation, :should_never_get_here] }
david.save
assert_equal [
[ :after_find, :string ],
[ :after_find, :proc ],
[ :after_find, :object ],
[ :after_find, :block ],
[ :after_initialize, :string ],
[ :after_initialize, :proc ],
[ :after_initialize, :object ],
[ :after_initialize, :block ],
[ :before_validation, :string ],
[ :before_validation, :proc ],
[ :before_validation, :object ],
[ :before_validation, :block ],
[ :before_validation, :returning_false ]
], david.history
end
def test_inheritence_of_callbacks
parent = ParentDeveloper.new
assert !parent.after_save_called
parent.save
assert parent.after_save_called
child = ChildDeveloper.new
assert !child.after_save_called
child.save
assert child.after_save_called
end
end

View file

@ -0,0 +1,32 @@
require 'test/unit'
require 'abstract_unit'
require 'active_support/core_ext/class/inheritable_attributes'
class A
include ClassInheritableAttributes
end
class B < A
write_inheritable_array "first", [ :one, :two ]
end
class C < A
write_inheritable_array "first", [ :three ]
end
class D < B
write_inheritable_array "first", [ :four ]
end
class ClassInheritableAttributesTest < Test::Unit::TestCase
def test_first_level
assert_equal [ :one, :two ], B.read_inheritable_attribute("first")
assert_equal [ :three ], C.read_inheritable_attribute("first")
end
def test_second_level
assert_equal [ :one, :two, :four ], D.read_inheritable_attribute("first")
assert_equal [ :one, :two ], B.read_inheritable_attribute("first")
end
end

View file

@ -0,0 +1,17 @@
require 'abstract_unit'
require 'fixtures/topic'
class TestColumnAlias < Test::Unit::TestCase
fixtures :topics
QUERY = if 'Oracle' == ActiveRecord::Base.connection.adapter_name
'SELECT id AS pk FROM topics WHERE ROWNUM < 2'
else
'SELECT id AS pk FROM topics'
end
def test_column_alias
records = Topic.connection.select_all(QUERY)
assert_equal 'pk', records[0].keys[0]
end
end

View file

@ -0,0 +1,8 @@
require "#{File.dirname(__FILE__)}/abstract_unit"
class FirebirdConnectionTest < Test::Unit::TestCase
def test_charset_properly_set
fb_conn = ActiveRecord::Base.connection.instance_variable_get(:@connection)
assert_equal 'UTF8', fb_conn.database.character_set
end
end

View file

@ -0,0 +1,30 @@
require "#{File.dirname(__FILE__)}/abstract_unit"
class MysqlConnectionTest < Test::Unit::TestCase
def setup
@connection = ActiveRecord::Base.connection
end
def test_no_automatic_reconnection_after_timeout
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
assert !@connection.active?
end
def test_successful_reconnection_after_timeout_with_manual_reconnect
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
@connection.reconnect!
assert @connection.active?
end
def test_successful_reconnection_after_timeout_with_verify
assert @connection.active?
@connection.update('set @@wait_timeout=1')
sleep 2
@connection.verify!(0)
assert @connection.active?
end
end

View file

@ -0,0 +1,25 @@
print "Using native DB2\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'db2',
:host => 'localhost',
:username => 'arunit',
:password => 'arunit',
:database => 'arunit'
},
'arunit2' => {
:adapter => 'db2',
:host => 'localhost',
:username => 'arunit',
:password => 'arunit',
:database => 'arunit2'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,26 @@
print "Using native Firebird\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'firebird',
:host => 'localhost',
:username => 'rails',
:password => 'rails',
:database => 'activerecord_unittest',
:charset => 'UTF8'
},
'arunit2' => {
:adapter => 'firebird',
:host => 'localhost',
:username => 'rails',
:password => 'rails',
:database => 'activerecord_unittest2'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,27 @@
puts 'Using native Frontbase'
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'frontbase',
:host => 'localhost',
:username => 'rails',
:password => '',
:database => 'activerecord_unittest',
:session_name => "unittest-#{$$}"
},
'arunit2' => {
:adapter => 'frontbase',
:host => 'localhost',
:username => 'rails',
:password => '',
:database => 'activerecord_unittest2',
:session_name => "unittest-#{$$}"
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,27 @@
print "Using native MySQL\n"
require_dependency 'fixtures/course'
require 'logger'
RAILS_DEFAULT_LOGGER = Logger.new('debug.log')
RAILS_DEFAULT_LOGGER.level = Logger::DEBUG
ActiveRecord::Base.logger = RAILS_DEFAULT_LOGGER
# GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost';
# GRANT ALL PRIVILEGES ON activerecord_unittest2.* to 'rails'@'localhost';
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'mysql',
:username => 'rails',
:encoding => 'utf8',
:database => 'activerecord_unittest',
},
'arunit2' => {
:adapter => 'mysql',
:username => 'rails',
:database => 'activerecord_unittest2'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,21 @@
print "Using native OpenBase\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'openbase',
:username => 'admin',
:database => 'activerecord_unittest',
},
'arunit2' => {
:adapter => 'openbase',
:username => 'admin',
:database => 'activerecord_unittest2'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,27 @@
print "Using Oracle\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new STDOUT
ActiveRecord::Base.logger.level = Logger::WARN
# Set these to your database connection strings
db = ENV['ARUNIT_DB'] || 'activerecord_unittest'
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'oracle',
:username => 'arunit',
:password => 'arunit',
:database => db,
},
'arunit2' => {
:adapter => 'oracle',
:username => 'arunit2',
:password => 'arunit2',
:database => db
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,23 @@
print "Using native PostgreSQL\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'postgresql',
:username => 'postgres',
:database => 'activerecord_unittest',
:min_messages => 'warning'
},
'arunit2' => {
:adapter => 'postgresql',
:username => 'postgres',
:database => 'activerecord_unittest2',
:min_messages => 'warning'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,25 @@
print "Using native SQlite\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
class SqliteError < StandardError
end
BASE_DIR = File.expand_path(File.dirname(__FILE__) + '/../../fixtures')
sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite"
sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite"
def make_connection(clazz, db_file)
ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite', :database => db_file } }
unless File.exist?(db_file)
puts "SQLite database not found at #{db_file}. Rebuilding it."
sqlite_command = %Q{sqlite "#{db_file}" "create table a (a integer); drop table a;"}
puts "Executing '#{sqlite_command}'"
raise SqliteError.new("Seems that there is no sqlite executable available") unless system(sqlite_command)
end
clazz.establish_connection(clazz.name)
end
make_connection(ActiveRecord::Base, sqlite_test_db)
make_connection(Course, sqlite_test_db2)

View file

@ -0,0 +1,25 @@
print "Using native SQLite3\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
class SqliteError < StandardError
end
BASE_DIR = File.expand_path(File.dirname(__FILE__) + '/../../fixtures')
sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3"
sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3"
def make_connection(clazz, db_file)
ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } }
unless File.exist?(db_file)
puts "SQLite3 database not found at #{db_file}. Rebuilding it."
sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"}
puts "Executing '#{sqlite_command}'"
raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command)
end
clazz.establish_connection(clazz.name)
end
make_connection(ActiveRecord::Base, sqlite_test_db)
make_connection(Course, sqlite_test_db2)

View file

@ -0,0 +1,18 @@
print "Using native SQLite3\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
class SqliteError < StandardError
end
def make_connection(clazz, db_definitions_file)
clazz.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
File.read("#{File.dirname(__FILE__)}/../../fixtures/db_definitions/#{db_definitions_file}").split(';').each do |command|
clazz.connection.execute(command) unless command.strip.empty?
end
end
make_connection(ActiveRecord::Base, 'sqlite.sql')
make_connection(Course, 'sqlite2.sql')
load("#{File.dirname(__FILE__)}/../../fixtures/db_definitions/schema.rb")

View file

@ -0,0 +1,23 @@
print "Using native Sybase Open Client\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
ActiveRecord::Base.configurations = {
'arunit' => {
:adapter => 'sybase',
:host => 'database_ASE',
:username => 'sa',
:database => 'activerecord_unittest'
},
'arunit2' => {
:adapter => 'sybase',
:host => 'database_ASE',
:username => 'sa',
:database => 'activerecord_unittest2'
}
}
ActiveRecord::Base.establish_connection 'arunit'
Course.establish_connection 'arunit2'

View file

@ -0,0 +1,69 @@
require 'abstract_unit'
class CopyTableTest < Test::Unit::TestCase
fixtures :companies, :comments
def setup
@connection = ActiveRecord::Base.connection
class << @connection
public :copy_table, :table_structure, :indexes
end
end
def test_copy_table(from = 'companies', to = 'companies2', options = {})
assert_nothing_raised {copy_table(from, to, options)}
assert_equal row_count(from), row_count(to)
if block_given?
yield from, to, options
else
assert_equal column_names(from), column_names(to)
end
@connection.drop_table(to) rescue nil
end
def test_copy_table_renaming_column
test_copy_table('companies', 'companies2',
:rename => {'client_of' => 'fan_of'}) do |from, to, options|
expected = column_values(from, 'client_of')
assert expected.any?, 'only nils in resultset; real values are needed'
assert_equal expected, column_values(to, 'fan_of')
end
end
def test_copy_table_with_index
test_copy_table('comments', 'comments_with_index') do
@connection.add_index('comments_with_index', ['post_id', 'type'])
test_copy_table('comments_with_index', 'comments_with_index2') do
assert_equal table_indexes_without_name('comments_with_index'),
table_indexes_without_name('comments_with_index2')
end
end
end
def test_copy_table_without_primary_key
test_copy_table('developers_projects', 'programmers_projects')
end
protected
def copy_table(from, to, options = {})
@connection.copy_table(from, to, {:temporary => true}.merge(options))
end
def column_names(table)
@connection.table_structure(table).map {|column| column['name']}
end
def column_values(table, column)
@connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]}
end
def table_indexes_without_name(table)
@connection.indexes('comments_with_index').delete(:name)
end
def row_count(table)
@connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']
end
end

View file

@ -0,0 +1,203 @@
require 'abstract_unit'
class PostgresqlArray < ActiveRecord::Base
end
class PostgresqlMoney < ActiveRecord::Base
end
class PostgresqlNumber < ActiveRecord::Base
end
class PostgresqlTime < ActiveRecord::Base
end
class PostgresqlNetworkAddress < ActiveRecord::Base
end
class PostgresqlBitString < ActiveRecord::Base
end
class PostgresqlOid < ActiveRecord::Base
end
class PostgresqlDataTypeTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
def setup
@connection = ActiveRecord::Base.connection
@connection.execute("INSERT INTO postgresql_arrays (commission_by_quarter, nicknames) VALUES ( '{35000,21000,18000,17000}', '{foo,bar,baz}' )")
@first_array = PostgresqlArray.find(1)
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('$567.89')")
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('-$567.89')")
@first_money = PostgresqlMoney.find(1)
@second_money = PostgresqlMoney.find(2)
@connection.execute("INSERT INTO postgresql_numbers (single, double) VALUES (123.456, 123456.789)")
@first_number = PostgresqlNumber.find(1)
@connection.execute("INSERT INTO postgresql_times (time_interval) VALUES ('1 year 2 days ago')")
@first_time = PostgresqlTime.find(1)
@connection.execute("INSERT INTO postgresql_network_addresses (cidr_address, inet_address, mac_address) VALUES('192.168.0/24', '172.16.1.254/32', '01:23:45:67:89:0a')")
@first_network_address = PostgresqlNetworkAddress.find(1)
@connection.execute("INSERT INTO postgresql_bit_strings (bit_string, bit_string_varying) VALUES (B'00010101', X'15')")
@first_bit_string = PostgresqlBitString.find(1)
@connection.execute("INSERT INTO postgresql_oids (obj_id) VALUES (1234)")
@first_oid = PostgresqlOid.find(1)
end
def test_data_type_of_array_types
assert_equal :string, @first_array.column_for_attribute(:commission_by_quarter).type
assert_equal :string, @first_array.column_for_attribute(:nicknames).type
end
def test_data_type_of_money_types
assert_equal :decimal, @first_money.column_for_attribute(:wealth).type
end
def test_data_type_of_number_types
assert_equal :float, @first_number.column_for_attribute(:single).type
assert_equal :float, @first_number.column_for_attribute(:double).type
end
def test_data_type_of_time_types
assert_equal :string, @first_time.column_for_attribute(:time_interval).type
end
def test_data_type_of_network_address_types
assert_equal :string, @first_network_address.column_for_attribute(:cidr_address).type
assert_equal :string, @first_network_address.column_for_attribute(:inet_address).type
assert_equal :string, @first_network_address.column_for_attribute(:mac_address).type
end
def test_data_type_of_bit_string_types
assert_equal :string, @first_bit_string.column_for_attribute(:bit_string).type
assert_equal :string, @first_bit_string.column_for_attribute(:bit_string_varying).type
end
def test_data_type_of_oid_types
assert_equal :integer, @first_oid.column_for_attribute(:obj_id).type
end
def test_array_values
assert_equal '{35000,21000,18000,17000}', @first_array.commission_by_quarter
assert_equal '{foo,bar,baz}', @first_array.nicknames
end
def test_money_values
assert_equal 567.89, @first_money.wealth
assert_equal -567.89, @second_money.wealth
end
def test_number_values
assert_equal 123.456, @first_number.single
assert_equal 123456.789, @first_number.double
end
def test_time_values
assert_equal '-1 years -2 days', @first_time.time_interval
end
def test_network_address_values
assert_equal '192.168.0.0/24', @first_network_address.cidr_address
assert_equal '172.16.1.254', @first_network_address.inet_address
assert_equal '01:23:45:67:89:0a', @first_network_address.mac_address
end
def test_bit_string_values
assert_equal '00010101', @first_bit_string.bit_string
assert_equal '00010101', @first_bit_string.bit_string_varying
end
def test_oid_values
assert_equal 1234, @first_oid.obj_id
end
def test_update_integer_array
new_value = '{32800,95000,29350,17000}'
assert @first_array.commission_by_quarter = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.commission_by_quarter, new_value
assert @first_array.commission_by_quarter = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.commission_by_quarter, new_value
end
def test_update_text_array
new_value = '{robby,robert,rob,robbie}'
assert @first_array.nicknames = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.nicknames, new_value
assert @first_array.nicknames = new_value
assert @first_array.save
assert @first_array.reload
assert_equal @first_array.nicknames, new_value
end
def test_update_money
new_value = 123.45
assert @first_money.wealth = new_value
assert @first_money.save
assert @first_money.reload
assert_equal @first_money.wealth, new_value
end
def test_update_number
new_single = 789.012
new_double = 789012.345
assert @first_number.single = new_single
assert @first_number.double = new_double
assert @first_number.save
assert @first_number.reload
assert_equal @first_number.single, new_single
assert_equal @first_number.double, new_double
end
def test_update_time
assert @first_time.time_interval = '2 years 3 minutes'
assert @first_time.save
assert @first_time.reload
assert_equal @first_time.time_interval, '2 years 00:03:00'
end
def test_update_network_address
new_cidr_address = '10.1.2.3/32'
new_inet_address = '10.0.0.0/8'
new_mac_address = 'bc:de:f0:12:34:56'
assert @first_network_address.cidr_address = new_cidr_address
assert @first_network_address.inet_address = new_inet_address
assert @first_network_address.mac_address = new_mac_address
assert @first_network_address.save
assert @first_network_address.reload
assert_equal @first_network_address.cidr_address, new_cidr_address
assert_equal @first_network_address.inet_address, new_inet_address
assert_equal @first_network_address.mac_address, new_mac_address
end
def test_update_bit_string
new_bit_string = '11111111'
new_bit_string_varying = 'FF'
assert @first_bit_string.bit_string = new_bit_string
assert @first_bit_string.bit_string_varying = new_bit_string_varying
assert @first_bit_string.save
assert @first_bit_string.reload
assert_equal @first_bit_string.bit_string, new_bit_string
assert_equal @first_bit_string.bit_string, @first_bit_string.bit_string_varying
end
def test_update_oid
new_value = 567890
assert @first_oid.obj_id = new_value
assert @first_oid.save
assert @first_oid.reload
assert_equal @first_oid.obj_id, new_value
end
end

View file

@ -0,0 +1,37 @@
require 'abstract_unit'
require 'fixtures/topic'
require 'fixtures/task'
class DateTimeTest < Test::Unit::TestCase
def test_saves_both_date_and_time
time_values = [1807, 2, 10, 15, 30, 45]
now = DateTime.civil(*time_values)
task = Task.new
task.starting = now
task.save!
# check against Time.local_time, since some platforms will return a Time instead of a DateTime
assert_equal Time.local_time(*time_values), Task.find(task.id).starting
end
def test_assign_empty_date_time
task = Task.new
task.starting = ''
task.ending = nil
assert_nil task.starting
assert_nil task.ending
end
def test_assign_empty_date
topic = Topic.new
topic.last_read = ''
assert_nil topic.last_read
end
def test_assign_empty_time
topic = Topic.new
topic.bonus_time = ''
assert_nil topic.bonus_time
end
end

View file

@ -0,0 +1,16 @@
require 'abstract_unit'
require 'fixtures/default'
class DefaultTest < Test::Unit::TestCase
def test_default_timestamp
default = Default.new
assert_instance_of(Time, default.default_timestamp)
assert_equal(:datetime, default.column_for_attribute(:default_timestamp).type)
# Variance should be small; increase if required -- e.g., if test db is on
# remote host and clocks aren't synchronized.
t1 = Time.new
accepted_variance = 1.0
assert_in_delta(t1.to_f, default.default_timestamp.to_f, accepted_variance)
end
end

View file

@ -0,0 +1,67 @@
require 'abstract_unit'
require 'fixtures/default'
require 'fixtures/entrant'
class DefaultTest < Test::Unit::TestCase
def test_nil_defaults_for_not_null_columns
column_defaults =
if current_adapter?(:MysqlAdapter)
{ 'id' => nil, 'name' => '', 'course_id' => nil }
else
{ 'id' => nil, 'name' => nil, 'course_id' => nil }
end
column_defaults.each do |name, default|
column = Entrant.columns_hash[name]
assert !column.null, "#{name} column should be NOT NULL"
assert_equal default, column.default, "#{name} column should be DEFAULT #{default.inspect}"
end
end
if current_adapter?(:MysqlAdapter)
# MySQL uses an implicit default 0 rather than NULL unless in strict mode.
# We use an implicit NULL so schema.rb is compatible with other databases.
def test_mysql_integer_not_null_defaults
klass = Class.new(ActiveRecord::Base)
klass.table_name = 'test_integer_not_null_default_zero'
klass.connection.create_table klass.table_name do |t|
t.column :zero, :integer, :null => false, :default => 0
t.column :omit, :integer, :null => false
end
assert_equal 0, klass.columns_hash['zero'].default
assert !klass.columns_hash['zero'].null
# 0 in MySQL 4, nil in 5.
assert [0, nil].include?(klass.columns_hash['omit'].default)
assert !klass.columns_hash['omit'].null
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }
assert_nothing_raised do
instance = klass.create!(:omit => 1)
assert_equal 0, instance.zero
assert_equal 1, instance.omit
end
ensure
klass.connection.drop_table(klass.table_name) rescue nil
end
end
if current_adapter?(:PostgreSQLAdapter, :SQLServerAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
def test_default_integers
default = Default.new
assert_instance_of Fixnum, default.positive_integer
assert_equal 1, default.positive_integer
assert_instance_of Fixnum, default.negative_integer
assert_equal -1, default.negative_integer
assert_instance_of BigDecimal, default.decimal_number
assert_equal BigDecimal.new("2.78"), default.decimal_number
end
end
if current_adapter?(:PostgreSQLAdapter)
def test_multiline_default_text
assert_equal "--- []\n\n", Default.columns_hash['multiline_default'].default
end
end
end

View file

@ -0,0 +1,30 @@
require 'abstract_unit'
require 'fixtures/entrant'
class DeprecatedFinderTest < Test::Unit::TestCase
fixtures :entrants
def test_deprecated_find_all_was_removed
assert_raise(NoMethodError) { Entrant.find_all }
end
def test_deprecated_find_first_was_removed
assert_raise(NoMethodError) { Entrant.find_first }
end
def test_deprecated_find_on_conditions_was_removed
assert_raise(NoMethodError) { Entrant.find_on_conditions }
end
def test_count
assert_equal(0, Entrant.count(:conditions => "id > 3"))
assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
end
def test_count_by_sql
assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
end
end

View file

@ -0,0 +1,650 @@
require 'abstract_unit'
require 'fixtures/author'
require 'fixtures/comment'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/reply'
require 'fixtures/entrant'
require 'fixtures/developer'
require 'fixtures/post'
class FinderTest < Test::Unit::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors
def test_find
assert_equal(topics(:first).title, Topic.find(1).title)
end
# find should handle strings that come from URLs
# (example: Category.find(params[:id]))
def test_find_with_string
assert_equal(Topic.find(1).title,Topic.find("1").title)
end
def test_exists
assert Topic.exists?(1)
assert Topic.exists?("1")
assert Topic.exists?(:author_name => "David")
assert Topic.exists?(:author_name => "Mary", :approved => true)
assert Topic.exists?(["parent_id = ?", 1])
assert !Topic.exists?(45)
begin
assert !Topic.exists?("foo")
rescue ActiveRecord::StatementInvalid
# PostgreSQL complains about string comparison with integer field
rescue Exception
flunk
end
assert_raise(NoMethodError) { Topic.exists?([1,2]) }
end
def test_find_by_array_of_one_id
assert_kind_of(Array, Topic.find([ 1 ]))
assert_equal(1, Topic.find([ 1 ]).length)
end
def test_find_by_ids
assert_equal 2, Topic.find(1, 2).size
assert_equal topics(:second).title, Topic.find([2]).first.title
end
def test_find_by_ids_with_limit_and_offset
assert_equal 2, Entrant.find([1,3,2], :limit => 2).size
assert_equal 1, Entrant.find([1,3,2], :limit => 3, :offset => 2).size
# Also test an edge case: If you have 11 results, and you set a
# limit of 3 and offset of 9, then you should find that there
# will be only 2 results, regardless of the limit.
devs = Developer.find :all
last_devs = Developer.find devs.map(&:id), :limit => 3, :offset => 9
assert_equal 2, last_devs.size
end
def test_find_an_empty_array
assert_equal [], Topic.find([])
end
def test_find_by_ids_missing_one
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, 2, 45) }
end
def test_find_all_with_limit
entrants = Entrant.find(:all, :order => "id ASC", :limit => 2)
assert_equal(2, entrants.size)
assert_equal(entrants(:first).name, entrants.first.name)
end
def test_find_all_with_prepared_limit_and_offset
entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 1)
assert_equal(2, entrants.size)
assert_equal(entrants(:second).name, entrants.first.name)
entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 2)
assert_equal(1, entrants.size)
assert_equal(entrants(:third).name, entrants.first.name)
end
def test_find_all_with_limit_and_offset_and_multiple_orderings
developers = Developer.find(:all, :order => "salary ASC, id DESC", :limit => 3, :offset => 1)
assert_equal ["David", "fixture_10", "fixture_9"], developers.collect {|d| d.name}
end
def test_find_with_limit_and_condition
developers = Developer.find(:all, :order => "id DESC", :conditions => "salary = 100000", :limit => 3, :offset =>7)
assert_equal(1, developers.size)
assert_equal("fixture_3", developers.first.name)
end
def test_find_with_entire_select_statement
topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
end
def test_find_with_prepared_select_statement
topics = Topic.find_by_sql ["SELECT * FROM topics WHERE author_name = ?", "Mary"]
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
end
def test_find_by_sql_with_sti_on_joined_table
accounts = Account.find_by_sql("SELECT * FROM accounts INNER JOIN companies ON companies.id = accounts.firm_id")
assert_equal [Account], accounts.collect(&:class).uniq
end
def test_find_first
first = Topic.find(:first, :conditions => "title = 'The First Topic'")
assert_equal(topics(:first).title, first.title)
end
def test_find_first_failing
first = Topic.find(:first, :conditions => "title = 'The First Topic!'")
assert_nil(first)
end
def test_unexisting_record_exception_handling
assert_raises(ActiveRecord::RecordNotFound) {
Topic.find(1).parent
}
Topic.find(2).topic
end
def test_find_only_some_columns
topic = Topic.find(1, :select => "author_name")
assert_raises(ActiveRecord::MissingAttributeError) {topic.title}
assert_equal "David", topic.author_name
assert !topic.attribute_present?("title")
#assert !topic.respond_to?("title")
assert topic.attribute_present?("author_name")
assert topic.respond_to?("author_name")
end
def test_find_on_blank_conditions
[nil, " ", [], {}].each do |blank|
assert_nothing_raised { Topic.find(:first, :conditions => blank) }
end
end
def test_find_on_blank_bind_conditions
[ [""], ["",{}] ].each do |blank|
assert_nothing_raised { Topic.find(:first, :conditions => blank) }
end
end
def test_find_on_array_conditions
assert Topic.find(1, :conditions => ["approved = ?", false])
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => ["approved = ?", true]) }
end
def test_find_on_hash_conditions
assert Topic.find(1, :conditions => { :approved => false })
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :approved => true }) }
end
def test_find_on_hash_conditions_with_explicit_table_name
assert Topic.find(1, :conditions => { 'topics.approved' => false })
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { 'topics.approved' => true }) }
end
def test_find_on_association_proxy_conditions
assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort
end
def test_find_on_hash_conditions_with_range
assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1..2 }).map(&:id).sort
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :id => 2..3 }) }
end
def test_find_on_hash_conditions_with_multiple_ranges
assert_equal [1,2,3], Comment.find(:all, :conditions => { :id => 1..3, :post_id => 1..2 }).map(&:id).sort
assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
end
def test_find_on_multiple_hash_conditions
assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false })
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }) }
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
end
def test_condition_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
end
def test_condition_array_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
end
def test_condition_hash_interpolation
assert_kind_of Firm, Company.find(:first, :conditions => { :name => "37signals"})
assert_nil Company.find(:first, :conditions => { :name => "37signals!"})
assert_kind_of Time, Topic.find(:first, :conditions => {:id => 1}).written_on
end
def test_hash_condition_find_malformed
assert_raises(ActiveRecord::StatementInvalid) {
Company.find(:first, :conditions => { :id => 2, :dhh => true })
}
end
def test_hash_condition_find_with_escaped_characters
Company.create("name" => "Ain't noth'n like' \#stuff")
assert Company.find(:first, :conditions => { :name => "Ain't noth'n like' \#stuff" })
end
def test_hash_condition_find_with_array
p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2] }, :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2.id] }, :order => 'id asc')
end
def test_hash_condition_find_with_nil
topic = Topic.find(:first, :conditions => { :last_read => nil } )
assert_not_nil topic
assert_nil topic.last_read
end
def test_bind_variables
assert_kind_of Firm, Company.find(:first, :conditions => ["name = ?", "37signals"])
assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!"])
assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = ?", 1]).written_on
assert_raises(ActiveRecord::PreparedStatementInvalid) {
Company.find(:first, :conditions => ["id=? AND name = ?", 2])
}
assert_raises(ActiveRecord::PreparedStatementInvalid) {
Company.find(:first, :conditions => ["id=?", 2, 3, 4])
}
end
def test_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find(:first, :conditions => ["name = ?", "37signals' go'es agains"])
end
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find(:first, :conditions => ["name = :name", {:name => "37signals' go'es agains"}])
end
def test_bind_arity
assert_nothing_raised { bind '' }
assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '?' }
assert_nothing_raised { bind '?', 1 }
assert_raises(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
end
def test_named_bind_variables
assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
assert_kind_of Firm, Company.find(:first, :conditions => ["name = :name", { :name => "37signals" }])
assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!" }])
assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!' OR 1=1" }])
assert_kind_of Time, Topic.find(:first, :conditions => ["id = :id", { :id => 1 }]).written_on
end
def test_bind_enumerable
quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
assert_equal '1,2,3', bind('?', [1, 2, 3])
assert_equal quoted_abc, bind('?', %w(a b c))
assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
require 'set'
assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
assert_equal quoted_abc, bind('?', Set.new(%w(a b c)))
assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3]))
assert_equal quoted_abc, bind(':a', :a => Set.new(%w(a b c))) # '
end
def test_bind_empty_enumerable
quoted_nil = ActiveRecord::Base.connection.quote(nil)
assert_equal quoted_nil, bind('?', [])
assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
end
def test_bind_string
assert_equal ActiveRecord::Base.connection.quote(''), bind('?', '')
end
def test_bind_record
o = Struct.new(:quoted_id).new(1)
assert_equal '1', bind('?', o)
os = [o] * 3
assert_equal '1,1,1', bind('?', os)
end
def test_string_sanitation
assert_not_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
assert_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something; select table'", ActiveRecord::Base.sanitize("something; select table")
end
def test_count
assert_equal(0, Entrant.count(:conditions => "id > 3"))
assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
end
def test_count_by_sql
assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
end
def test_find_by_one_attribute
assert_equal topics(:first), Topic.find_by_title("The First Topic")
assert_nil Topic.find_by_title("The First Topic!")
end
def test_find_by_one_attribute_caches_dynamic_finder
# ensure this test can run independently of order
class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.respond_to?(:find_by_title)
assert !Topic.respond_to?(:find_by_title)
t = Topic.find_by_title("The First Topic")
assert Topic.respond_to?(:find_by_title)
end
def test_dynamic_finder_returns_same_results_after_caching
# ensure this test can run independently of order
class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.respond_to?(:find_by_title)
t = Topic.find_by_title("The First Topic")
assert_equal t, Topic.find_by_title("The First Topic") # find_by_title has been cached
end
def test_find_by_one_attribute_with_order_option
assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
end
def test_find_by_one_attribute_with_conditions
assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
end
def test_dynamic_finder_on_one_attribute_with_conditions_caches_method
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.respond_to?(:find_by_credit_limit)
assert !Account.respond_to?(:find_by_credit_limit)
a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
assert Account.respond_to?(:find_by_credit_limit)
end
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.respond_to?(:find_by_credit_limit)
a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
assert_equal a, Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) # find_by_credit_limit has been cached
end
def test_find_by_one_attribute_with_several_options
assert_equal accounts(:unknown), Account.find_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
end
def test_find_by_one_missing_attribute
assert_raises(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
end
def test_find_by_invalid_method_syntax
assert_raises(NoMethodError) { Topic.fail_to_find_by_title("The First Topic") }
assert_raises(NoMethodError) { Topic.find_by_title?("The First Topic") }
assert_raises(NoMethodError) { Topic.fail_to_find_or_create_by_title("Nonexistent Title") }
assert_raises(NoMethodError) { Topic.find_or_create_by_title?("Nonexistent Title") }
end
def test_find_by_two_attributes
assert_equal topics(:first), Topic.find_by_title_and_author_name("The First Topic", "David")
assert_nil Topic.find_by_title_and_author_name("The First Topic", "Mary")
end
def test_find_all_by_one_attribute
topics = Topic.find_all_by_content("Have a nice day")
assert_equal 2, topics.size
assert topics.include?(topics(:first))
assert_equal [], Topic.find_all_by_title("The First Topic!!")
end
def test_find_all_by_one_attribute_with_options
topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
assert topics(:first), topics.last
topics = Topic.find_all_by_content("Have a nice day", :order => "id")
assert topics(:first), topics.first
end
def test_find_all_by_array_attribute
assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic's of the day"]).size
end
def test_find_all_by_boolean_attribute
topics = Topic.find_all_by_approved(false)
assert_equal 1, topics.size
assert topics.include?(topics(:first))
topics = Topic.find_all_by_approved(true)
assert_equal 1, topics.size
assert topics.include?(topics(:second))
end
def test_find_by_nil_attribute
topic = Topic.find_by_last_read nil
assert_not_nil topic
assert_nil topic.last_read
end
def test_find_all_by_nil_attribute
topics = Topic.find_all_by_last_read nil
assert_equal 1, topics.size
assert_nil topics[0].last_read
end
def test_find_by_nil_and_not_nil_attributes
topic = Topic.find_by_last_read_and_author_name nil, "Mary"
assert_equal "Mary", topic.author_name
end
def test_find_all_by_nil_and_not_nil_attributes
topics = Topic.find_all_by_last_read_and_author_name nil, "Mary"
assert_equal 1, topics.size
assert_equal "Mary", topics[0].author_name
end
def test_find_or_create_from_one_attribute
number_of_companies = Company.count
sig38 = Company.find_or_create_by_name("38signals")
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name("38signals")
assert !sig38.new_record?
end
def test_find_or_create_from_two_attributes
number_of_topics = Topic.count
another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
assert_equal number_of_topics + 1, Topic.count
assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
assert !another.new_record?
end
def test_find_or_create_from_one_attribute_and_hash
number_of_companies = Company.count
sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert !sig38.new_record?
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
end
def test_find_or_initialize_from_one_attribute
sig38 = Company.find_or_initialize_by_name("38signals")
assert_equal "38signals", sig38.name
assert sig38.new_record?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected
c = Company.find_or_initialize_by_name_and_rating("Fortune 1000", 1000)
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
assert c.new_record?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected
c = Company.find_or_create_by_name_and_rating("Fortune 1000", 1000)
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
assert !c.new_record?
end
def test_dynamic_find_or_initialize_from_one_attribute_caches_method
class << Company; self; end.send(:remove_method, :find_or_initialize_by_name) if Company.respond_to?(:find_or_initialize_by_name)
assert !Company.respond_to?(:find_or_initialize_by_name)
sig38 = Company.find_or_initialize_by_name("38signals")
assert Company.respond_to?(:find_or_initialize_by_name)
end
def test_find_or_initialize_from_two_attributes
another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
assert_equal "Another topic", another.title
assert_equal "John", another.author_name
assert another.new_record?
end
def test_find_or_initialize_from_one_attribute_and_hash
sig38 = Company.find_or_initialize_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
assert sig38.new_record?
end
def test_find_with_bad_sql
assert_raises(ActiveRecord::StatementInvalid) { Topic.find_by_sql "select 1 from badtable" }
end
def test_find_with_invalid_params
assert_raises(ArgumentError) { Topic.find :first, :join => "It should be `joins'" }
assert_raises(ArgumentError) { Topic.find :first, :conditions => '1 = 1', :join => "It should be `joins'" }
end
def test_dynamic_finder_with_invalid_params
assert_raises(ArgumentError) { Topic.find_by_title 'No Title', :join => "It should be `joins'" }
end
def test_find_all_with_limit
first_five_developers = Developer.find :all, :order => 'id ASC', :limit => 5
assert_equal 5, first_five_developers.length
assert_equal 'David', first_five_developers.first.name
assert_equal 'fixture_5', first_five_developers.last.name
no_developers = Developer.find :all, :order => 'id ASC', :limit => 0
assert_equal 0, no_developers.length
end
def test_find_all_with_limit_and_offset
first_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 0
second_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 3
last_two_developers = Developer.find :all, :order => 'id ASC', :limit => 2, :offset => 8
assert_equal 3, first_three_developers.length
assert_equal 3, second_three_developers.length
assert_equal 2, last_two_developers.length
assert_equal 'David', first_three_developers.first.name
assert_equal 'fixture_4', second_three_developers.first.name
assert_equal 'fixture_9', last_two_developers.first.name
end
def test_find_all_with_limit_and_offset_and_multiple_order_clauses
first_three_posts = Post.find :all, :order => 'author_id, id', :limit => 3, :offset => 0
second_three_posts = Post.find :all, :order => ' author_id,id ', :limit => 3, :offset => 3
last_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 6
assert_equal [[0,3],[1,1],[1,2]], first_three_posts.map { |p| [p.author_id, p.id] }
assert_equal [[1,4],[1,5],[1,6]], second_three_posts.map { |p| [p.author_id, p.id] }
assert_equal [[2,7]], last_posts.map { |p| [p.author_id, p.id] }
end
def test_find_all_with_join
developers_on_project_one = Developer.find(
:all,
:joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
:conditions => 'project_id=1'
)
assert_equal 3, developers_on_project_one.length
developer_names = developers_on_project_one.map { |d| d.name }
assert developer_names.include?('David')
assert developer_names.include?('Jamis')
end
def test_joins_dont_clobber_id
first = Firm.find(
:first,
:joins => 'INNER JOIN companies AS clients ON clients.firm_id = companies.id',
:conditions => 'companies.id = 1'
)
assert_equal 1, first.id
end
def test_find_by_id_with_conditions_with_or
assert_nothing_raised do
Post.find([1,2,3],
:conditions => "posts.id <= 3 OR posts.#{QUOTED_TYPE} = 'Post'")
end
end
# http://dev.rubyonrails.org/ticket/6778
def test_find_ignores_previously_inserted_record
post = Post.create!(:title => 'test', :body => 'it out')
assert_equal [], Post.find_all_by_id(nil)
end
def test_find_by_empty_ids
assert_equal [], Post.find([])
end
def test_find_by_empty_in_condition
assert_equal [], Post.find(:all, :conditions => ['id in (?)', []])
end
def test_find_by_records
p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2]], :order => 'id asc')
assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2.id]], :order => 'id asc')
end
def test_select_value
assert_equal "37signals", Company.connection.select_value("SELECT name FROM companies WHERE id = 1")
assert_nil Company.connection.select_value("SELECT name FROM companies WHERE id = -1")
# make sure we didn't break count...
assert_equal 0, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = 'Halliburton'")
assert_equal 1, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = '37signals'")
end
def test_select_values
assert_equal ["1","2","3","4","5","6","7","8","9"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s }
assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
end
def test_select_rows
assert_equal(
[["1", nil, nil, "37signals"],
["2", "1", "2", "Summit"],
["3", "1", "1", "Microsoft"]],
Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
assert_equal [["1", "37signals"], ["2", "Summit"], ["3", "Microsoft"]],
Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}}
end
protected
def bind(statement, *vars)
if vars.first.is_a?(Hash)
ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
else
ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
end
end
end

View file

@ -0,0 +1,28 @@
signals37:
id: 1
firm_id: 1
credit_limit: 50
unknown:
id: 2
credit_limit: 50
rails_core_account:
id: 3
firm_id: 6
credit_limit: 50
last_account:
id: 4
firm_id: 2
credit_limit: 60
rails_core_account_2:
id: 5
firm_id: 6
credit_limit: 55
odegy_account:
id: 6
firm_id: 9
credit_limit: 53

View file

View file

View file

@ -0,0 +1,109 @@
class Author < ActiveRecord::Base
has_many :posts
has_many :posts_with_comments, :include => :comments, :class_name => "Post"
has_many :posts_with_categories, :include => :categories, :class_name => "Post"
has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post"
has_many :posts_with_extension, :class_name => "Post" do #, :extend => ProxyTestExtension
def testing_proxy_owner
proxy_owner
end
def testing_proxy_reflection
proxy_reflection
end
def testing_proxy_target
proxy_target
end
end
has_many :comments, :through => :posts
has_many :comments_desc, :through => :posts, :source => :comments, :order => 'comments.id DESC'
has_many :limited_comments, :through => :posts, :source => :comments, :limit => 1
has_many :funky_comments, :through => :posts, :source => :comments
has_many :ordered_uniq_comments, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id'
has_many :ordered_uniq_comments_desc, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id DESC'
has_many :special_posts
has_many :special_post_comments, :through => :special_posts, :source => :comments
has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'"
has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => "comments.post_id = 0"
has_many :nonexistant_comments, :through => :posts
has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'"
has_many :hello_post_comments, :through => :hello_posts, :source => :comments
has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :include => :comments
has_many :other_posts, :class_name => "Post"
has_many :posts_with_callbacks, :class_name => "Post", :before_add => :log_before_adding,
:after_add => :log_after_adding,
:before_remove => :log_before_removing,
:after_remove => :log_after_removing
has_many :posts_with_proc_callbacks, :class_name => "Post",
:before_add => Proc.new {|o, r| o.post_log << "before_adding#{r.id || '<new>'}"},
:after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id || '<new>'}"},
:before_remove => Proc.new {|o, r| o.post_log << "before_removing#{r.id}"},
:after_remove => Proc.new {|o, r| o.post_log << "after_removing#{r.id}"}
has_many :posts_with_multiple_callbacks, :class_name => "Post",
:before_add => [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}"}],
:after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}"}]
has_many :unchangable_posts, :class_name => "Post", :before_add => :raise_exception, :after_add => :log_after_adding
has_many :categorizations
has_many :categories, :through => :categorizations
has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' }
has_many :categorized_posts, :through => :categorizations, :source => :post
has_many :unique_categorized_posts, :through => :categorizations, :source => :post, :uniq => true
has_many :nothings, :through => :kateggorisatons, :class_name => 'Category'
has_many :author_favorites
has_many :favorite_authors, :through => :author_favorites, :order => 'name'
has_many :tagging, :through => :posts # through polymorphic has_one
has_many :taggings, :through => :posts, :source => :taggings # through polymorphic has_many
has_many :tags, :through => :posts # through has_many :through
has_many :post_categories, :through => :posts, :source => :categories
belongs_to :author_address
attr_accessor :post_log
def after_initialize
@post_log = []
end
def label
"#{id}-#{name}"
end
private
def log_before_adding(object)
@post_log << "before_adding#{object.id || '<new>'}"
end
def log_after_adding(object)
@post_log << "after_adding#{object.id}"
end
def log_before_removing(object)
@post_log << "before_removing#{object.id}"
end
def log_after_removing(object)
@post_log << "after_removing#{object.id}"
end
def raise_exception(object)
raise Exception.new("You can't add a post")
end
end
class AuthorAddress < ActiveRecord::Base
has_one :author
end
class AuthorFavorite < ActiveRecord::Base
belongs_to :author
belongs_to :favorite_author, :class_name => "Author", :foreign_key => 'favorite_author_id'
end

View file

@ -0,0 +1,4 @@
david_mary:
id: 1
author_id: 1
favorite_author_id: 2

View file

@ -0,0 +1,7 @@
david:
id: 1
name: David
mary:
id: 2
name: Mary

View file

@ -0,0 +1,4 @@
class AutoId < ActiveRecord::Base
def self.table_name () "auto_id_tests" end
def self.primary_key () "auto_id" end
end

View file

@ -0,0 +1 @@
1b => 1

View file

@ -0,0 +1 @@
a b => 1

View file

@ -0,0 +1,3 @@
a => 1
b => 2

View file

@ -0,0 +1,3 @@
a => 1
b => 2
a => 3

View file

@ -0,0 +1 @@
a =>

View file

@ -0,0 +1,132 @@
flowers:
id: 1
data: !binary | /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAA0JCQoKCg4LCw4UDQsNFBcRDg4R
FxsVFRUVFRsbFRcXFxcVGxoeICEgHhonJyoqJyc1NTU1NTY2NjY2NjY2Njb/
2wBDAQ4NDRERERcRERcXExQTFx0ZGhoZHSYdHR4dHSYsJCAgICAkLCgrJiYm
KygvLywsLy82NjY2NjY2NjY2NjY2Njb/wAARCACvAIMDAREAAhEBAxEB/8QA
GwAAAgMBAQEAAAAAAAAAAAAABAUAAwYCAQf/xABAEAACAQMCBAMFBwMBBQkA
AAABAgMABBESIQUTMUEiUWEUMnGBkQYjQlKxwdEzYqGSFSRD4fAlNUVyc4Ki
svH/xAAZAQADAQEBAAAAAAAAAAAAAAAAAQIDBAX/xAAqEQACAgEEAQQCAgID
AAAAAAAAAQIRAxIhMUFRBBMiYTJxgaFCUpGxwf/aAAwDAQACEQMRAD8A+nUA
SgCUASgDxmCjJ2A6k0ADe3QumqFhID7rA+E/OgBNLecbWcCVoRA2f6Wcj/Vv
USvyNHDtI5y7s3zqCgWR2S7gjiy0koZQM4Axg5+NC+hkHFr8WcjpIYriL3kf
xAMp8S+KnbQqHEHGXG06Z/uT+KpT8icRnBcwzjMTBvMdx8RVkltAEoAlAEoA
lAEoAlAEoArmmSBNbnb9aAEtxdG7bTKP927x9Q3ofOp1DoTwCSy4okMAK2TB
pY4z2/Og+ZyKm9yqD2bVO594NupO2M/h+VJgjmWPmIVyyZ7r1pDJw9Iku44V
Yu8Ebl+Zu+XK75/xVRJZXxzh8WmS7ErRM2kMgAIdiQo+dOaHB7nMCFECMzNj
8T7k/SoGEBuURIjaXXcMD+tCYmh7bXetE52EkbHwJ8hWpAVTAlAEoAlAEoAl
AFc0ywxl26D/ADQAjurlpW5khwOw8hWTZSQMLiAn3x/18aQwTi03s8UV0oyI
ZAzEdkPhfb4GgaDgV2ZTqB3B86BFVwCQGV9Dr7rfh+DVEl/DAGt7qJLiKULm
5cOknpnBwfhp2pwyL+Q8l97O72+ZUEpR1ZFG2fEBg7+tW3YkW/HY0iiMB086
SAsYM7623Pb0+FVZI2sL3mfdSf1B0P5v+dXGVioOqhEoAlAEoA8JxuelAGNu
ftDeX1/7Na2x5eWEJfbVp6t8+1RzwVQXDwtrkcziO7fhgU4VfiV61SQr8Hb8
E4eR4UMZ7FHYH9TRSCxfDYXEuoQzAJpAZJBqDasg7j+KiKstsEtzfWlxdZjV
wjBCAdtlDArnsQaTQfYf7RxEdbGT5Ff5o0sNvIvEgF8sxhdZnDKsW27dBsPS
s6qV9gXXd5ccnBtpIiWXS5G2QwP12q2OIQvEZ239jm33zpPf5U6Yie2Xsp0w
2uG6EOQCMeeaVAR4+KgBpGjjUnBAOo/oP1p6aJs7g4bNIqzG8kVveXQo28uu
acY9hfRqbSbmxDJy42f4+fzrQkvoAlAEoAV8cuWjhECdZfeOcYUdd/Wom9hx
EFhHjiMTYO2r8QONjUwLlwP61Mzk0AAWGxYeg/eoh2VLoC4iUteIrPM3+7Xa
cps7BZI/d+qk0pFR4/QzkuFiVGOcMQNgT1rTolLkSSpJJc61KIBLpjYn3ve2
+O/asq1PYsae1WsdseYA7QeNde+SncD0rSqKhjbkl5Flp9qPapFXkMZG1agp
8K4G2TjvSTO+fpNHYfDe25lRWOJZAdJII6dck4p/Zz5fTtptdFl2fCo9c/QU
pnEi2DaJB6CnHoT5CbaflSBvwnZvhTAcUASgCUAZ/i6e0SK222eozttUTKiL
7WEJexMWX3vygHofKpiUx3Wpmck0AL7Q4kb/AMv71EOypcIB+0EkLRpE5wUc
SasZC4OdwO2KT8eCsf0WT36sXXK+AqkZ8R+9xq+80dh5VZajQseaWVI5IHCR
MwZkIHhckAOPyrkdKlPnoNqdLdkml9mI0za0VtAjCr/VOWLMRjrTGpNU2BSH
lxy3HD5dAClZYG6nR4QQcYI3+NJb7o9DDnWaPyj8r5DC9w0cVsYyyrCGUrjU
8vhJ0b48PlT+hKUVJ773/Q4kLmGMPq5nLOvVjVnGN9O1KfR52SnOTXAWmyge
lX0YnuaAGfCrkzwMGxqiYrt+X8JpAHUwKrltMZ8ztQAg4mhJXwlgwK4H1qJF
RFqQyNd240MMON8Y6bmpiyn2aA1qZlRkUSCPPjIyB6ClfQAMBxK3wP61OPk1
q6Qn4pJcyXeI49UUiaZCPy1r7bt/cTphh0WvKPeCS+02oZtTSkYYquBkbAlt
qK+KtkyT0pbJFV/dSxW8kZBLNEq83w6HcnG4x1rOXZnJbbeQO9RrSKKMnW6t
45Nj4hjYbZ6GufMpbU+DBthXBrG61ZeZo4bZtXs4B0bjOGzse1XhHGTXAebZ
b/dzh4yrow/Cd+nyq49minpYXMfHj+0D6miXKIXYXWhBKAOOBTSxXZidTpbK
E42yNxWa5KfBpa0JBLxt1X50AKOKe5Gdup66vL+2omVHkVxY9rg2QeMdpM1E
eS3wNrq/htQzSnSFGf8A8rY0xencv5FnD76PiN61xETohBU5HXsNPp5+tZ6L
nqsnNg9trfkF4rfrbRvp8cm66B6nbP8AFbQhTbuzpw4qpsVT3XD3n5d1cttE
MFchAxzkeHoR5GtHOG5eTPDeIJFx8w2/Kt5Gj8eU22GWydq5jgk+PsvueJST
BeeBIi7YAwSD3x50tW+5pKq2e5JZ2uFS3c/dBmKsBuc+dZzfSMn8ugi3llsp
fBI0nNULIr+bdCPlWduMkl2QuRvDOLTVzPTVjfSPXFdscdJts6vYcld0WwTx
XcjGM5Axg/ChQU02gWH4Nh5IAyeg6mkcp6hJAJGn41NgBWsgSUuCMq+fecdD
UdmlbGuVtQBHQ7itTMAuDmVvTagBfxCUxquBnrUTKiK2upDLEFAXUwGc+tRH
ktAvFkubZpI5NUyTKyjIz4z00/Stj1MUoNKtmgHhd+bSRrd9UK8soW/EvcN8
DWCk1N2rPOnqlle1/IW8QnnwfEdW5yPI9cfKqlq1N3syvUxyY5PfkVQ8oSa5
TshB0fm9KaOWP2X35iuZOZbJ4QMyaBgAeZA6U0VL8VRdaSxkYmy6Lkjpnby1
VlKO4vDHFhcw+EIcsQS6YBchd8IfM5p49q8mi/tlF8US45aKwyOcS/hZQ2+N
O9LJ8XZD5aBH4s7HlP8A0s+IrsxX1qpSlJVexXvSez4HlrcQq5e3O0gAx0C4
863nmhFLQehKcdCSDBfXEsZCqAc+HUwHw8Jx0/WuaTnJPT/ZwSxveQRBE4TU
+qSRRnfGB323OanHjfMm2zI8trqXHbT8d60NDT8Pn5tnE7bMRv8ALatUzMGk
OXY+ppgA8UH+7Z6EHYk4/WoycDRnVvUjViyDndE1HYefn9a5sOR63GS/Rv6f
8qmWcFuGmnHtPVieSzncjyz3O1dn7Ov1cYxinF7+DvjEltcXSK7qlvb+BmA8
z4lb08qIuLel8h6OaipLnI/J3NwuEqDbeDBXWPe1Rjqu/wCYV0PGmazcskdL
Kr37OcOuHWSNeTkqSE93HcaexIp+xBmD9NB/TOG+zdnCJmtQUeVWRIycp4hp
3zk+tKWBdCl6ZU62A2+y0VtbLqLTyKCZCh07/wBoINYyxUYS9PVFdnAIIo8R
bFG9paUeMdT91q2Bx9ajSTpSsFDR3Gow6pvDp5jDEjd/EMnp0rly25KkZP5P
gEdIYyBpyw643GfM57071JdCrpIbcrRJaCI632MrdUC+WO9dkcKSS/5PRji2
j/Y2iWGS4eGNkDLh1wPCenu5zWkMSi3XBosaiuORlDcxgmJ2CuOgI05/mpyQ
o5M2Ct0B2yQ6D4Vzuerj9q5aMR9w9glpGoG2P39atGbPasQNf7wYzjJ8gf1q
ZcDjyZjjNr9ykyyeOLvjr8umP1qFR2YpxpxmrAU4YdpGkC3Kf6D5fCn7eqPN
DXptcdeoJ4ct887TcyCNR4csQdQ7rpP61p6aNdhg7Td/9jb2hh+TI2+7YEf6
etdp2RRwbiViREpbT72O1cmT1Si6FKUV3R6t+Op2PTftW+PIpqy1G9wKbjCS
utvCGdnb7x12wnfSehNKcujmyvpFL3DBy64a3CFnGC+wbJKE/pWL5OeSr9Ir
jis7hG9mHLlc6o2IwXGdye/eolBTT68EabVoL4TwlJpi08XQEddjj8461msT
tXVIUYb2MWtYLxHMOiO4hfSM+4WXorY3x8K3U6Ov5w47QktmntzpuAIry2zE
yY2zksuCeqsp6+Vaavjd7hHNcN+UH3V3rg1toFzEA2gHOdW3gz19Ky9x72Rj
z03e6KeHz3CSK12GUxnVGrZJPVTo8t6y35ZjPz5NDbXDNCpVCR500c4bViBe
IIWtyR1Xfy9KiXA0Zu+R1hbEYJ8iwz8t6xst/QFPy2iRYoWhf/ian15P6CsM
mR1pWyRPuyrTewTwuZVK2zJHpc+++c+gFb+jzfJQdb/5dm3pslOhoPYJWZYQ
khT3yuCF+JG1esqZ6MZ32VgTQKTHjSxzgiuXJ6GMnY5YoyOBaId5xqDdc9M+
tb48KxqiuFR5d20FtDI+eTgasjAJ076ct50pr7OfL58Gdu5IeIrG0UmZzsFi
BAC4911Pr5Vzs43Ut+w7hHtNvbkOhTUwKnGl8HqwDb9qUXzsPEjQcLmymVyx
zplkI0sxHmKLNdKdlHE/ub1buFFMGwkRAch+xYLQaY8lQcH+XkRcavFuLyK6
3PKTl4PQjuNt+hxuaiUjz55PlsW8znWjzxwgLFiMBcHAG++odKV2my7uOoL4
bMjW2F0q+nGnfVqPUnPb0HrQpXF+Rt6kWiK7xtJPj00gfLBqorYnY1FwwiLk
gkKeijJ+gpvbczEfFOLAjkhBo/FzMgj4qP3rly5b2/8ABGflu87xx/dxnOvG
AfXVuTUJP9DPfazO5d/eY5b4msZ3bsRxc40nPQg/pRDlMa2GHCOI8Lg4ZDFH
IMJpWRejyTP1AXvv3r24TVI78WSOlbjXUs4wv9IEgsdskdhmtdR0KQDHfxQX
Pss7aucmuINtqUErpGe9S59ClkV1wxZxy/itrf2csJTINLQtvjyOe1ZzmjHP
ljTXkF4HPwzh8trcysA4fSTk5GrwuSOmBnY+VYnJcUl5Hl6sE105X75cAmWN
vmACDRaOiLDLS7UHMhA7KuQNvTOKRbXAp+0ExS5SSJuXzFOtVbr2ye24rnzN
pqjlzPfkzzylpWxvj/raj8kmznHfApFS1uhJup/4R6Nt3+taRquTbF+Dst4d
JHaJonZR+UqPwnz071OuK7FexsrBoZ7WOWLdG6eEjvitVJEF12CJWx33FUBk
+MWXFOYzuRNbA6gVwgGe5Xz9azd8ktMUuPDg4YfHIqHJeBaGTaVyxOmYBUEW
n38bD5j/ADUThrX2NffJzejl2zPICOX4WHffp1rmjF60ijOgCNo3R8nZsjqp
8jnuPSvQuhJ1wHzz390BJLNoVGDKo93I74pvP/LNfdm+yrifEpL2USEjIAVf
T4UtTk7kRPI5MHt7d7iQIvXclv3p0wSbouktOSjcwb7fLPSs2pahSjRbacbn
srRrRUR0bOJCMMurr0OD6VoVGdD3iH2i4W9nCLLLXsWATIh93GD6Ghmksol5
rSku8hLMe46fSuWTMXueezg+IOMkjbfejVs1RNfYdHbyhdTKQvn28utRpl/A
1fAwtOGyP4mU47Yx9Sa0hj8l15PodlFybWGP8qAV1USU3y7q3ypgAXKh4XU9
MGpl2Bl723iMMoCqpKnGFK+tYmj4YDaW91I0fO2B3EmMkY33P7mhJmSvkb3t
vBPaj7tvZiMs2Nyo6Y1uSd+m9VJdlGOveGCE5WTVEc6fCc/x/mlHI/8AUWkY
8AurKAv7eNOpcQM4OnQOoHXeqpcmkWhdeexy3MrW33dv6/sKndGUudgeJnjc
GFipHQjbHwqtbBNnsvN0qskjOoJxk567nNGpvrcLb5OhbpJgINR2AGd/lUW1
yBwLaXSZhGdKEAt8a05Q6DH+5VNSNkjbbqeprmS1N7gN+C21tcoJllTnr1jf
dRnoD339K2hjXkSGl/NKIbi2dTq0rJ5hl1AZDdznber+ike8OTmvFGFbxsB7
n75qVyU+Dd4rYgquk1xHzG4+VACxsaTnpijoDN3kC8s+JjnqMmudmoQvD/b7
O1YYVdAWXG2dOV7Vt0QnyNXijePlsoKYxj4dKdEmV43ZJaYDkurKTk7+n6Vn
LYtdiyLhVxeWYuWAECjRGPxNjPTemkSlqYm0EOQDgjbI6fKhiregm3tlOkyS
feO+APLHeplfXRMgmaCK5i0qzFwckbduuKmGz3Bc7hElhZ5ieNgjkZAyR7oD
Z7jI771tJKnwzZxj0VtfzItxa4xLlgrZ93OOnbfvU6tG3NE66tFllwDiE9rG
I7kLG+S8erKgfhbbz8utSop7rkzD7fgt3Zyq8kSXMfuycv39PoD+1Dj53Aa8
RSKGxRYwQGdQNWScbtjxb9qp0o8FxGH2bi5s+v8ADCM/+47ClBFSNRWpBKAF
NzHy2dO2+PhR0Blblm5ZBbY1zmo24If+zYvTUP8A5GtlwjNhpqhCT7RQiSOI
noGIP6/tWeToqIN/4CiqMkb48vGaTfxFwzOPb4dv7jt/ArGMrlSJ7PBGyb9h
512JFHrtoGfd9cUUn0Kgq0iadrf8hfUMjv2NTJdLgfRxdWfst1ytWuVgGd/N
m3OK5skWuyDVwW/IxygNJ6r0+JFbxjVFBQqwAuNDMEX/AKoP0BqZ8DjyaPgN
mbWxXUPvZfG/z6D6URWwMZVQiUADXsOtNQ95f070AYi5wMr+Un9aw7NehpwT
/u+P4v8A/Y1rHhGbDqoQs41g22M76gcd6znwVHkWx3kX+zfZ9LM+46bDxZ61
Mn8K8g+RfPExboCcZz6+Qq4YUqFR5GpVgwzpO5U7q3xBrUVFrmX3kiAC9gMf
SqCjt2bSHxpc/wCKUr4oEcjl3d4zS+5lQfkB0rnmvluVWw9W5hHc1epE0WLc
w/mp6kFBENkvEpoRkGGF+ZL8gcL8zRyBpaYEoAlAEoAx/wBobBrWcyqMwTEk
H8rdSv8AFZTXZafQutOJSxwLBHhQhbfGTuSe9NS2Bota6lb3nJ+dTYUgaZiw
60mMF3UEb77mhAeI+kjX3z8q3TAJiuo4gRpGr1rTUQ4lct5IeunHlijULSBc
ySRyMjbqDsR/NS5F0Fwx/XzrnfIwxM0AXRxSSuI0XLscAetArNhw2xWxtxEN
3O8jebVqiAumBKAJQBKAKbm2iuoWhmGqNxgikBirngsvDZWV/HGxJjkx7w8j
61k40aJlWnekByy0wB3U0ADTLgnoNXVjVxYFPNDjDdvP9iN6sD1iMfi2/vH7
0WBLePXINI2+v+TUyYDaOLA6VmIvSMswUdT7oHegDUcJ4WLRebLvcMP9I8hW
iRDGdUBKAJQBKAJQBKAK54IriMxyrqQ9qQGZ4jwaW1JeMGWDz7r8R+9Q4lJi
rH9tSM5ZCR0/xQBXLbcwYxin+gF83D7nV4Vz/dmrUh2epw+7OxGB6n/nRqDY
YW9qkA3bxd6ixB9rayXL6IFLHv5D4mnQjS8O4TFZ+NvHP+fy9Fq0ibGFMCUA
SgCUASgCUASgCUASgAC74PbXOTvE5/En7jpSoLE8/wBn7uPJjKyj46T9D/NT
pKsXyQzxNpdNP0/akB5484WkMKh4RfXG4UafNmH7b0UxWMrb7Nxg6rl9Z/Im
w+vWq0iscQwxQroiUIvkKsRZQBKAJQBKAJQB/9k=

View file

@ -0,0 +1,2 @@
class Binary < ActiveRecord::Base
end

View file

@ -0,0 +1,4 @@
class Book < ActiveRecord::Base
has_many :citations, :foreign_key => 'book1_id'
has_many :references, :through => :citations, :source => :reference_of, :uniq => true
end

View file

@ -0,0 +1,7 @@
awdr:
id: 1
name: "Agile Web Development with Rails"
rfr:
id: 2
name: "Ruby for Rails"

View file

@ -0,0 +1,14 @@
general:
id: 1
name: General
type: Category
technology:
id: 2
name: Technology
type: Category
sti_test:
id: 3
name: Special category
type: SpecialCategory

View file

@ -0,0 +1,9 @@
sub_special_1:
id: 100
name: A special category in a subdir file
type: SpecialCategory
sub_special_2:
id: 101
name: Another special category
type: SpecialCategory

View file

@ -0,0 +1,4 @@
sub_special_3:
id: 102
name: A special category in an arbitrarily named subsubdir file
type: SpecialCategory

View file

@ -0,0 +1,7 @@
--- !!omap
<% 100.times do |i| %>
- fixture_no_<%= i %>:
id: <%= i %>
name: <%= "Category #{i}" %>
type: Category
<% end %>

View file

@ -0,0 +1,23 @@
general_welcome:
category_id: 1
post_id: 1
technology_welcome:
category_id: 2
post_id: 1
general_thinking:
category_id: 1
post_id: 2
general_sti_habtm:
category_id: 1
post_id: 6
sti_test_sti_habtm:
category_id: 3
post_id: 6
general_hello:
category_id: 1
post_id: 4

View file

@ -0,0 +1,5 @@
class Categorization < ActiveRecord::Base
belongs_to :post
belongs_to :category
belongs_to :author
end

View file

@ -0,0 +1,17 @@
david_welcome_general:
id: 1
author_id: 1
post_id: 1
category_id: 1
mary_thinking_sti:
id: 2
author_id: 2
post_id: 2
category_id: 3
mary_thinking_general:
id: 3
author_id: 2
post_id: 2
category_id: 1

View file

@ -0,0 +1,26 @@
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
has_and_belongs_to_many :special_posts, :class_name => "Post"
has_and_belongs_to_many :other_posts, :class_name => "Post"
has_and_belongs_to_many(:select_testing_posts,
:class_name => 'Post',
:foreign_key => 'category_id',
:association_foreign_key => 'post_id',
:select => 'posts.*, 1 as correctness_marker')
def self.what_are_you
'a category...'
end
has_many :categorizations
has_many :authors, :through => :categorizations, :select => 'authors.*, categorizations.post_id'
end
class SpecialCategory < Category
def self.what_are_you
'a special category...'
end
end

View file

@ -0,0 +1,6 @@
class Citation < ActiveRecord::Base
belongs_to :reference_of, :class_name => "Book", :foreign_key => :book2_id
belongs_to :book1, :class_name => "Book", :foreign_key => :book1_id
belongs_to :book2, :class_name => "Book", :foreign_key => :book2_id
end

View file

@ -0,0 +1,3 @@
class ColumnName < ActiveRecord::Base
def self.table_name () "colnametests" end
end

View file

@ -0,0 +1,23 @@
class Comment < ActiveRecord::Base
belongs_to :post
def self.what_are_you
'a comment...'
end
def self.search_by_type(q)
self.find(:all, :conditions => ["#{QUOTED_TYPE} = ?", q])
end
end
class SpecialComment < Comment
def self.what_are_you
'a special comment...'
end
end
class VerySpecialComment < Comment
def self.what_are_you
'a very special comment...'
end
end

View file

@ -0,0 +1,59 @@
greetings:
id: 1
post_id: 1
body: Thank you for the welcome
type: Comment
more_greetings:
id: 2
post_id: 1
body: Thank you again for the welcome
type: Comment
does_it_hurt:
id: 3
post_id: 2
body: Don't think too hard
type: SpecialComment
eager_sti_on_associations_vs_comment:
id: 5
post_id: 4
body: Very Special type
type: VerySpecialComment
eager_sti_on_associations_s_comment1:
id: 6
post_id: 4
body: Special type
type: SpecialComment
eager_sti_on_associations_s_comment2:
id: 7
post_id: 4
body: Special type 2
type: SpecialComment
eager_sti_on_associations_comment:
id: 8
post_id: 4
body: Normal type
type: Comment
check_eager_sti_on_associations:
id: 9
post_id: 5
body: Normal type
type: Comment
check_eager_sti_on_associations2:
id: 10
post_id: 5
body: Special Type
type: SpecialComment
eager_other_comment1:
id: 11
post_id: 7
body: go crazy
type: SpecialComment

View file

@ -0,0 +1,55 @@
first_client:
id: 2
type: Client
firm_id: 1
client_of: 2
name: Summit
ruby_type: Client
first_firm:
id: 1
type: Firm
name: 37signals
ruby_type: Firm
second_client:
id: 3
type: Client
firm_id: 1
client_of: 1
name: Microsoft
ruby_type: Client
another_firm:
id: 4
type: Firm
name: Flamboyant Software
ruby_type: Firm
another_client:
id: 5
type: Client
firm_id: 4
client_of: 4
name: Ex Nihilo
ruby_type: Client
rails_core:
id: 6
name: RailsCore
type: DependentFirm
leetsoft:
id: 7
name: Leetsoft
client_of: 6
jadedpixel:
id: 8
name: Jadedpixel
client_of: 6
odegy:
id: 9
name: Odegy
type: ExclusivelyDependentFirm

View file

@ -0,0 +1,114 @@
class AbstractCompany < ActiveRecord::Base
self.abstract_class = true
end
class Company < AbstractCompany
attr_protected :rating
set_sequence_name :companies_nonstd_seq
validates_presence_of :name
has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account"
def arbitrary_method
"I am Jack's profound disappointment"
end
end
class Firm < Company
has_many :clients, :order => "id", :dependent => :destroy, :counter_sql =>
"SELECT COUNT(*) FROM companies WHERE firm_id = 1 " +
"AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )"
has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
has_many :dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :destroy
has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all
has_many :limited_clients, :class_name => "Client", :order => "id", :limit => 1
has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id"
has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => 'rating > #{rating}'
has_many :clients_like_ms_with_hash_conditions, :conditions => { :name => 'Microsoft' }, :class_name => "Client", :order => "id"
has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
has_many :clients_using_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}',
:counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = #{id}'
has_many :clients_using_zero_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}',
:counter_sql => 'SELECT 0 FROM companies WHERE client_of = #{id}'
has_many :no_clients_using_counter_sql, :class_name => "Client",
:finder_sql => 'SELECT * FROM companies WHERE client_of = 1000',
:counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000'
has_many :clients_using_finder_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE 1=1'
has_many :plain_clients, :class_name => 'Client'
has_one :account, :foreign_key => "firm_id", :dependent => :destroy
end
class DependentFirm < Company
has_one :account, :foreign_key => "firm_id", :dependent => :nullify
has_many :companies, :foreign_key => 'client_of', :order => "id", :dependent => :nullify
end
class ExclusivelyDependentFirm < Company
has_one :account, :foreign_key => "firm_id", :dependent => :delete
has_many :dependent_sanitized_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => "name = 'BigShot Inc.'"
has_many :dependent_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => ["name = ?", 'BigShot Inc.']
end
class Client < Company
belongs_to :firm, :foreign_key => "client_of"
belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id"
belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
belongs_to :firm_with_condition, :class_name => "Firm", :foreign_key => "client_of", :conditions => ["1 = ?", 1]
# Record destruction so we can test whether firm.clients.clear has
# is calling client.destroy, deleting from the database, or setting
# foreign keys to NULL.
def self.destroyed_client_ids
@destroyed_client_ids ||= Hash.new { |h,k| h[k] = [] }
end
before_destroy do |client|
if client.firm
Client.destroyed_client_ids[client.firm.id] << client.id
end
true
end
# Used to test that read and question methods are not generated for these attributes
def ruby_type
read_attribute :ruby_type
end
def rating?
query_attribute :rating
end
end
class SpecialClient < Client
end
class VerySpecialClient < SpecialClient
end
class Account < ActiveRecord::Base
belongs_to :firm
def self.destroyed_account_ids
@destroyed_account_ids ||= Hash.new { |h,k| h[k] = [] }
end
before_destroy do |account|
if account.firm
Account.destroyed_account_ids[account.firm.id] << account.id
end
true
end
protected
def validate
errors.add_on_empty "credit_limit"
end
end

View file

@ -0,0 +1,59 @@
module MyApplication
module Business
class Company < ActiveRecord::Base
attr_protected :rating
end
class Firm < Company
has_many :clients, :order => "id", :dependent => :destroy
has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id"
has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}'
has_one :account, :dependent => :destroy
end
class Client < Company
belongs_to :firm, :foreign_key => "client_of"
belongs_to :firm_with_other_name, :class_name => "Firm", :foreign_key => "client_of"
end
class Developer < ActiveRecord::Base
has_and_belongs_to_many :projects
validates_length_of :name, :within => (3..20)
end
class Project < ActiveRecord::Base
has_and_belongs_to_many :developers
end
end
module Billing
class Firm < ActiveRecord::Base
self.table_name = 'companies'
end
module Nested
class Firm < ActiveRecord::Base
self.table_name = 'companies'
end
end
class Account < ActiveRecord::Base
with_options(:foreign_key => :firm_id) do |i|
i.belongs_to :firm, :class_name => 'MyApplication::Business::Firm'
i.belongs_to :qualified_billing_firm, :class_name => 'MyApplication::Billing::Firm'
i.belongs_to :unqualified_billing_firm, :class_name => 'Firm'
i.belongs_to :nested_qualified_billing_firm, :class_name => 'MyApplication::Billing::Nested::Firm'
i.belongs_to :nested_unqualified_billing_firm, :class_name => 'Nested::Firm'
end
protected
def validate
errors.add_on_empty "credit_limit"
end
end
end
end

View file

@ -0,0 +1,4 @@
class Computer < ActiveRecord::Base
belongs_to :developer, :foreign_key=>'developer'
end

View file

@ -0,0 +1,4 @@
workstation:
id: 1
developer: 1
extendedWarranty: 1

View file

@ -0,0 +1,16 @@
class Contact < ActiveRecord::Base
# mock out self.columns so no pesky db is needed for these tests
def self.column(name, sql_type = nil, options = {})
@columns ||= []
@columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options[:null])
end
column :name, :string
column :age, :integer
column :avatar, :binary
column :created_at, :datetime
column :awesome, :boolean
column :preferences, :string
serialize :preferences
end

View file

@ -0,0 +1,3 @@
class Course < ActiveRecord::Base
has_many :entrants
end

View file

@ -0,0 +1,7 @@
ruby:
id: 1
name: Ruby Development
java:
id: 2
name: Java Development

View file

@ -0,0 +1,55 @@
class Customer < ActiveRecord::Base
composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true
composed_of(:balance, :class_name => "Money", :mapping => %w(balance amount)) { |balance| balance.to_money }
composed_of :gps_location, :allow_nil => true
end
class Address
attr_reader :street, :city, :country
def initialize(street, city, country)
@street, @city, @country = street, city, country
end
def close_to?(other_address)
city == other_address.city && country == other_address.country
end
def ==(other)
other.is_a?(self.class) && other.street == street && other.city == city && other.country == country
end
end
class Money
attr_reader :amount, :currency
EXCHANGE_RATES = { "USD_TO_DKK" => 6, "DKK_TO_USD" => 0.6 }
def initialize(amount, currency = "USD")
@amount, @currency = amount, currency
end
def exchange_to(other_currency)
Money.new((amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor, other_currency)
end
end
class GpsLocation
attr_reader :gps_location
def initialize(gps_location)
@gps_location = gps_location
end
def latitude
gps_location.split("x").first
end
def longitude
gps_location.split("x").last
end
def ==(other)
self.latitude == other.latitude && self.longitude == other.longitude
end
end

View file

@ -0,0 +1,17 @@
david:
id: 1
name: David
balance: 50
address_street: Funny Street
address_city: Scary Town
address_country: Loony Land
gps_location: 35.544623640962634x-105.9309951055148
zaphod:
id: 2
name: Zaphod
balance: 62
address_street: Avenue Road
address_city: Hamlet Town
address_country: Nation Land
gps_location: NULL

View file

@ -0,0 +1,33 @@
DROP TABLE accounts;
DROP TABLE funny_jokes;
DROP TABLE companies;
DROP TABLE topics;
DROP TABLE developers;
DROP TABLE projects;
DROP TABLE developers_projects;
DROP TABLE orders;
DROP TABLE customers;
DROP TABLE movies;
DROP TABLE subscribers;
DROP TABLE booleantests;
DROP TABLE auto_id_tests;
DROP TABLE entrants;
DROP TABLE colnametests;
DROP TABLE mixins;
DROP TABLE people;
DROP TABLE readers;
DROP TABLE binaries;
DROP TABLE computers;
DROP TABLE posts;
DROP TABLE comments;
DROP TABLE authors;
DROP TABLE tasks;
DROP TABLE categories;
DROP TABLE categories_posts;
DROP TABLE fk_test_has_pk;
DROP TABLE fk_test_has_fk;
DROP TABLE keyboards;
DROP TABLE legacy_things;
DROP TABLE numeric_data;
DROP TABLE mixed_case_monkeys;
DROP TABLE minimalistics;

View file

@ -0,0 +1,235 @@
CREATE TABLE accounts (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
firm_id INT DEFAULT NULL,
credit_limit INT DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE funny_jokes (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE companies (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
type VARCHAR(50) DEFAULT NULL,
ruby_type VARCHAR(50) DEFAULT NULL,
firm_id INT DEFAULT NULL,
name VARCHAR(50) DEFAULT NULL,
client_of INT DEFAULT NULL,
rating INT DEFAULT 1,
PRIMARY KEY (id)
);
CREATE TABLE topics (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
title VARCHAR(255) DEFAULT NULL,
author_name VARCHAR(255) DEFAULT NULL,
author_email_address VARCHAR(255) DEFAULT NULL,
written_on TIMESTAMP DEFAULT NULL,
bonus_time TIME DEFAULT NULL,
last_read DATE DEFAULT NULL,
content VARCHAR(3000),
approved SMALLINT DEFAULT 1,
replies_count INT DEFAULT 0,
parent_id INT DEFAULT NULL,
type VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE developers (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(100) DEFAULT NULL,
salary INT DEFAULT 70000,
created_at TIMESTAMP DEFAULT NULL,
updated_at TIMESTAMP DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE projects (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(100) DEFAULT NULL,
type VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE developers_projects (
developer_id INT NOT NULL,
project_id INT NOT NULL,
joined_on DATE DEFAULT NULL,
access_level SMALLINT DEFAULT 1
);
CREATE TABLE orders (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(100) DEFAULT NULL,
billing_customer_id INT DEFAULT NULL,
shipping_customer_id INT DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE customers (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(100) DEFAULT NULL,
balance INT DEFAULT 0,
address_street VARCHAR(100) DEFAULT NULL,
address_city VARCHAR(100) DEFAULT NULL,
address_country VARCHAR(100) DEFAULT NULL,
gps_location VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE movies (
movieid INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (movieid)
);
CREATE TABLE subscribers (
nick VARCHAR(100) NOT NULL,
name VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (nick)
);
CREATE TABLE booleantests (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
value INT DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE auto_id_tests (
auto_id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
value INT DEFAULT NULL,
PRIMARY KEY (auto_id)
);
CREATE TABLE entrants (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
course_id INT NOT NULL
);
CREATE TABLE colnametests (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
references INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE mixins (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
parent_id INT DEFAULT NULL,
pos INT DEFAULT NULL,
created_at TIMESTAMP DEFAULT NULL,
updated_at TIMESTAMP DEFAULT NULL,
lft INT DEFAULT NULL,
rgt INT DEFAULT NULL,
root_id INT DEFAULT NULL,
type VARCHAR(40) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE people (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
first_name VARCHAR(40) NOT NULL,
lock_version INT DEFAULT 0,
PRIMARY KEY (id)
);
CREATE TABLE readers (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
post_id INT NOT NULL,
person_id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE binaries (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
data BLOB(50000),
PRIMARY KEY (id)
);
CREATE TABLE computers (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
developer INT NOT NULL,
extendedWarranty INT NOT NULL
);
CREATE TABLE posts (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
author_id INT DEFAULT NULL,
title VARCHAR(255) DEFAULT NULL,
type VARCHAR(255) DEFAULT NULL,
body VARCHAR(3000) DEFAULT NULL
);
CREATE TABLE comments (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
post_id INT DEFAULT NULL,
type VARCHAR(255) DEFAULT NULL,
body VARCHAR(3000) DEFAULT NULL
);
CREATE TABLE authors (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(255) DEFAULT NULL
);
CREATE TABLE tasks (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
starting TIMESTAMP DEFAULT NULL,
ending TIMESTAMP DEFAULT NULL
);
CREATE TABLE categories (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(255) NOT NULL,
type VARCHAR(40) DEFAULT NULL
);
CREATE TABLE categories_posts (
category_id INT NOT NULL,
post_id INT NOT NULL
);
CREATE TABLE keyboards (
key_number INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
name VARCHAR(255)
);
CREATE TABLE fk_test_has_pk (
id INT NOT NULL PRIMARY KEY
);
CREATE TABLE fk_test_has_fk (
id INT NOT NULL PRIMARY KEY,
fk_id INT NOT NULL,
FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id)
);
--This table has an altered lock_version column name
CREATE TABLE legacy_things (
id INT GENERATED BY DEFAULT AS IDENTITY (START WITH 10000),
tps_report_number INT DEFAULT NULL,
version INT DEFAULT 0,
PRIMARY KEY (id)
);
CREATE TABLE numeric_data (
id INT NOT NULL PRIMARY KEY,
bank_balance DECIMAL(10,2),
big_bank_balance DECIMAL(15,2),
world_population DECIMAL(10),
my_house_population DECIMAL(2),
decimal_number_with_default DECIMAL(3,2) DEFAULT 2.78
);
CREATE TABLE mixed_case_monkeys (
monkeyID INT NOT NULL PRIMARY KEY,
fleaCount INT
);
CREATE TABLE minimalistics (
id INT NOT NULL PRIMARY KEY
);

View file

@ -0,0 +1,2 @@
DROP TABLE courses;

View file

@ -0,0 +1,5 @@
CREATE TABLE courses (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
);

View file

@ -0,0 +1,65 @@
DROP TABLE accounts;
DROP TABLE funny_jokes;
DROP TABLE companies;
DROP TABLE topics;
DROP TABLE developers;
DROP TABLE projects;
DROP TABLE developers_projects;
DROP TABLE orders;
DROP TABLE customers;
DROP TABLE movies;
DROP TABLE subscribers;
DROP TABLE booleantests;
DROP TABLE auto_id_tests;
DROP TABLE entrants;
DROP TABLE colnametests;
DROP TABLE mixins;
DROP TABLE people;
DROP TABLE readers;
DROP TABLE binaries;
DROP TABLE computers;
DROP TABLE posts;
DROP TABLE comments;
DROP TABLE authors;
DROP TABLE tasks;
DROP TABLE categories;
DROP TABLE categories_posts;
DROP TABLE fk_test_has_fk;
DROP TABLE fk_test_has_pk;
DROP TABLE keyboards;
DROP TABLE defaults;
DROP TABLE legacy_things;
DROP TABLE numeric_data;
DROP TABLE mixed_case_monkeys;
DROP TABLE minimalistics;
DROP DOMAIN D_BOOLEAN;
DROP GENERATOR accounts_seq;
DROP GENERATOR funny_jokes_seq;
DROP GENERATOR companies_nonstd_seq;
DROP GENERATOR topics_seq;
DROP GENERATOR developers_seq;
DROP GENERATOR projects_seq;
DROP GENERATOR orders_seq;
DROP GENERATOR customers_seq;
DROP GENERATOR movies_seq;
DROP GENERATOR booleantests_seq;
DROP GENERATOR auto_id_tests_seq;
DROP GENERATOR entrants_seq;
DROP GENERATOR colnametests_seq;
DROP GENERATOR mixins_seq;
DROP GENERATOR people_seq;
DROP GENERATOR binaries_seq;
DROP GENERATOR computers_seq;
DROP GENERATOR posts_seq;
DROP GENERATOR comments_seq;
DROP GENERATOR authors_seq;
DROP GENERATOR tasks_seq;
DROP GENERATOR categories_seq;
DROP GENERATOR keyboards_seq;
DROP GENERATOR defaults_seq;
DROP GENERATOR legacy_things_seq;
DROP GENERATOR numeric_data_seq;
DROP GENERATOR mixed_case_monkeys_seq;
DROP GENERATOR minimalistics_seq;

View file

@ -0,0 +1,310 @@
CREATE DOMAIN D_BOOLEAN AS SMALLINT CHECK (VALUE IN (0, 1) OR VALUE IS NULL);
CREATE TABLE accounts (
id BIGINT NOT NULL,
firm_id BIGINT,
credit_limit INTEGER,
PRIMARY KEY (id)
);
CREATE GENERATOR accounts_seq;
SET GENERATOR accounts_seq TO 10000;
CREATE TABLE funny_jokes (
id BIGINT NOT NULL,
name VARCHAR(50),
PRIMARY KEY (id)
);
CREATE GENERATOR funny_jokes_seq;
SET GENERATOR funny_jokes_seq TO 10000;
CREATE TABLE companies (
id BIGINT NOT NULL,
"TYPE" VARCHAR(50),
ruby_type VARCHAR(50),
firm_id BIGINT,
name VARCHAR(50),
client_of INTEGER,
rating INTEGER DEFAULT 1,
PRIMARY KEY (id)
);
CREATE GENERATOR companies_nonstd_seq;
SET GENERATOR companies_nonstd_seq TO 10000;
CREATE TABLE topics (
id BIGINT NOT NULL,
title VARCHAR(255),
author_name VARCHAR(255),
author_email_address VARCHAR(255),
written_on TIMESTAMP,
bonus_time TIME,
last_read DATE,
content VARCHAR(4000),
approved D_BOOLEAN DEFAULT 1,
replies_count INTEGER DEFAULT 0,
parent_id BIGINT,
"TYPE" VARCHAR(50),
PRIMARY KEY (id)
);
CREATE GENERATOR topics_seq;
SET GENERATOR topics_seq TO 10000;
CREATE TABLE developers (
id BIGINT NOT NULL,
name VARCHAR(100),
salary INTEGER DEFAULT 70000,
created_at TIMESTAMP,
updated_at TIMESTAMP,
PRIMARY KEY (id)
);
CREATE GENERATOR developers_seq;
SET GENERATOR developers_seq TO 10000;
CREATE TABLE projects (
id BIGINT NOT NULL,
name VARCHAR(100),
"TYPE" VARCHAR(255),
PRIMARY KEY (id)
);
CREATE GENERATOR projects_seq;
SET GENERATOR projects_seq TO 10000;
CREATE TABLE developers_projects (
developer_id BIGINT NOT NULL,
project_id BIGINT NOT NULL,
joined_on DATE,
access_level SMALLINT DEFAULT 1
);
CREATE TABLE orders (
id BIGINT NOT NULL,
name VARCHAR(100),
billing_customer_id BIGINT,
shipping_customer_id BIGINT,
PRIMARY KEY (id)
);
CREATE GENERATOR orders_seq;
SET GENERATOR orders_seq TO 10000;
CREATE TABLE customers (
id BIGINT NOT NULL,
name VARCHAR(100),
balance INTEGER DEFAULT 0,
address_street VARCHAR(100),
address_city VARCHAR(100),
address_country VARCHAR(100),
gps_location VARCHAR(100),
PRIMARY KEY (id)
);
CREATE GENERATOR customers_seq;
SET GENERATOR customers_seq TO 10000;
CREATE TABLE movies (
movieid BIGINT NOT NULL,
name varchar(100),
PRIMARY KEY (movieid)
);
CREATE GENERATOR movies_seq;
SET GENERATOR movies_seq TO 10000;
CREATE TABLE subscribers (
nick VARCHAR(100) NOT NULL,
name VARCHAR(100),
PRIMARY KEY (nick)
);
CREATE TABLE booleantests (
id BIGINT NOT NULL,
"VALUE" D_BOOLEAN,
PRIMARY KEY (id)
);
CREATE GENERATOR booleantests_seq;
SET GENERATOR booleantests_seq TO 10000;
CREATE TABLE auto_id_tests (
auto_id BIGINT NOT NULL,
"VALUE" INTEGER,
PRIMARY KEY (auto_id)
);
CREATE GENERATOR auto_id_tests_seq;
SET GENERATOR auto_id_tests_seq TO 10000;
CREATE TABLE entrants (
id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
course_id INTEGER NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR entrants_seq;
SET GENERATOR entrants_seq TO 10000;
CREATE TABLE colnametests (
id BIGINT NOT NULL,
"REFERENCES" INTEGER NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR colnametests_seq;
SET GENERATOR colnametests_seq TO 10000;
CREATE TABLE mixins (
id BIGINT NOT NULL,
parent_id BIGINT,
pos INTEGER,
created_at TIMESTAMP,
updated_at TIMESTAMP,
lft INTEGER,
rgt INTEGER,
root_id BIGINT,
"TYPE" VARCHAR(40),
PRIMARY KEY (id)
);
CREATE GENERATOR mixins_seq;
SET GENERATOR mixins_seq TO 10000;
CREATE TABLE people (
id BIGINT NOT NULL,
first_name VARCHAR(40),
lock_version INTEGER DEFAULT 0 NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR people_seq;
SET GENERATOR people_seq TO 10000;
CREATE TABLE readers (
id BIGINT NOT NULL,
post_id BIGINT NOT NULL,
person_id BIGINT NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR readers_seq;
SET GENERATOR readers_seq TO 10000;
CREATE TABLE binaries (
id BIGINT NOT NULL,
data BLOB,
PRIMARY KEY (id)
);
CREATE GENERATOR binaries_seq;
SET GENERATOR binaries_seq TO 10000;
CREATE TABLE computers (
id BIGINT NOT NULL,
developer INTEGER NOT NULL,
"extendedWarranty" INTEGER NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR computers_seq;
SET GENERATOR computers_seq TO 10000;
CREATE TABLE posts (
id BIGINT NOT NULL,
author_id BIGINT,
title VARCHAR(255) NOT NULL,
"TYPE" VARCHAR(255) NOT NULL,
body VARCHAR(3000) NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR posts_seq;
SET GENERATOR posts_seq TO 10000;
CREATE TABLE comments (
id BIGINT NOT NULL,
post_id BIGINT NOT NULL,
"TYPE" VARCHAR(255) NOT NULL,
body VARCHAR(3000) NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR comments_seq;
SET GENERATOR comments_seq TO 10000;
CREATE TABLE authors (
id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR authors_seq;
SET GENERATOR authors_seq TO 10000;
CREATE TABLE tasks (
id BIGINT NOT NULL,
"STARTING" TIMESTAMP,
ending TIMESTAMP,
PRIMARY KEY (id)
);
CREATE GENERATOR tasks_seq;
SET GENERATOR tasks_seq TO 10000;
CREATE TABLE categories (
id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
"TYPE" VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR categories_seq;
SET GENERATOR categories_seq TO 10000;
CREATE TABLE categories_posts (
category_id BIGINT NOT NULL,
post_id BIGINT NOT NULL,
PRIMARY KEY (category_id, post_id)
);
CREATE TABLE fk_test_has_pk (
id BIGINT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE fk_test_has_fk (
id BIGINT NOT NULL,
fk_id BIGINT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id)
);
CREATE TABLE keyboards (
key_number BIGINT NOT NULL,
name VARCHAR(50),
PRIMARY KEY (key_number)
);
CREATE GENERATOR keyboards_seq;
SET GENERATOR keyboards_seq TO 10000;
CREATE TABLE defaults (
id BIGINT NOT NULL,
default_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE GENERATOR defaults_seq;
SET GENERATOR defaults_seq TO 10000;
CREATE TABLE legacy_things (
id BIGINT NOT NULL,
tps_report_number INTEGER,
version INTEGER DEFAULT 0 NOT NULL,
PRIMARY KEY (id)
);
CREATE GENERATOR legacy_things_seq;
SET GENERATOR legacy_things_seq TO 10000;
CREATE TABLE numeric_data (
id BIGINT NOT NULL,
bank_balance DECIMAL(10,2),
big_bank_balance DECIMAL(15,2),
world_population DECIMAL(10),
my_house_population DECIMAL(2),
decimal_number_with_default DECIMAL(3,2) DEFAULT 2.78,
PRIMARY KEY (id)
);
CREATE GENERATOR numeric_data_seq;
SET GENERATOR numeric_data_seq TO 10000;
CREATE TABLE mixed_case_monkeys (
"monkeyID" BIGINT NOT NULL,
"fleaCount" INTEGER
);
CREATE GENERATOR mixed_case_monkeys_seq;
SET GENERATOR mixed_case_monkeys_seq TO 10000;
CREATE TABLE minimalistics (
id BIGINT NOT NULL
);
CREATE GENERATOR minimalistics_seq;
SET GENERATOR minimalistics_seq TO 10000;

View file

@ -0,0 +1,2 @@
DROP TABLE courses;
DROP GENERATOR courses_seq;

View file

@ -0,0 +1,6 @@
CREATE TABLE courses (
id BIGINT NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE GENERATOR courses_seq;
SET GENERATOR courses_seq TO 10000;

View file

@ -0,0 +1,33 @@
DROP TABLE accounts CASCADE;
DROP TABLE funny_jokes CASCADE;
DROP TABLE companies CASCADE;
DROP TABLE topics CASCADE;
DROP TABLE developers CASCADE;
DROP TABLE projects CASCADE;
DROP TABLE developers_projects CASCADE;
DROP TABLE orders CASCADE;
DROP TABLE customers CASCADE;
DROP TABLE movies CASCADE;
DROP TABLE subscribers CASCADE;
DROP TABLE booleantests CASCADE;
DROP TABLE auto_id_tests CASCADE;
DROP TABLE entrants CASCADE;
DROP TABLE colnametests CASCADE;
DROP TABLE mixins CASCADE;
DROP TABLE people CASCADE;
DROP TABLE readers CASCADE;
DROP TABLE binaries CASCADE;
DROP TABLE computers CASCADE;
DROP TABLE posts CASCADE;
DROP TABLE comments CASCADE;
DROP TABLE authors CASCADE;
DROP TABLE tasks CASCADE;
DROP TABLE categories CASCADE;
DROP TABLE categories_posts CASCADE;
DROP TABLE fk_test_has_fk CASCADE;
DROP TABLE fk_test_has_pk CASCADE;
DROP TABLE keyboards CASCADE;
DROP TABLE legacy_things CASCADE;
DROP TABLE numeric_data CASCADE;
DROP TABLE mixed_case_monkeys CASCADE;
DROP TABLE minimalistics CASCADE;

View file

@ -0,0 +1,273 @@
CREATE TABLE accounts (
id integer DEFAULT unique,
firm_id integer,
credit_limit integer,
PRIMARY KEY (id)
);
SET UNIQUE FOR accounts(id);
CREATE TABLE funny_jokes (
id integer DEFAULT unique,
firm_id integer default NULL,
name character varying(50),
PRIMARY KEY (id)
);
SET UNIQUE FOR funny_jokes(id);
CREATE TABLE companies (
id integer DEFAULT unique,
"type" character varying(50),
"ruby_type" character varying(50),
firm_id integer,
name character varying(50),
client_of integer,
rating integer default 1,
PRIMARY KEY (id)
);
SET UNIQUE FOR companies(id);
CREATE TABLE topics (
id integer DEFAULT unique,
title character varying(255),
author_name character varying(255),
author_email_address character varying(255),
written_on timestamp,
bonus_time time,
last_read date,
content varchar(65536),
approved boolean default true,
replies_count integer default 0,
parent_id integer,
"type" character varying(50),
PRIMARY KEY (id)
);
SET UNIQUE FOR topics(id);
CREATE TABLE developers (
id integer DEFAULT unique,
name character varying(100),
salary integer DEFAULT 70000,
created_at timestamp,
updated_at timestamp,
PRIMARY KEY (id)
);
SET UNIQUE FOR developers(id);
CREATE TABLE projects (
id integer DEFAULT unique,
name character varying(100),
type varchar(255),
PRIMARY KEY (id)
);
SET UNIQUE FOR projects(id);
CREATE TABLE developers_projects (
developer_id integer NOT NULL,
project_id integer NOT NULL,
joined_on date,
access_level integer default 1
);
CREATE TABLE orders (
id integer DEFAULT unique,
name character varying(100),
billing_customer_id integer,
shipping_customer_id integer,
PRIMARY KEY (id)
);
SET UNIQUE FOR orders(id);
CREATE TABLE customers (
id integer DEFAULT unique,
name character varying(100),
balance integer default 0,
address_street character varying(100),
address_city character varying(100),
address_country character varying(100),
gps_location character varying(100),
PRIMARY KEY (id)
);
SET UNIQUE FOR customers(id);
CREATE TABLE movies (
movieid integer DEFAULT unique,
name varchar(65536),
PRIMARY KEY (movieid)
);
SET UNIQUE FOR movies(movieid);
CREATE TABLE subscribers (
nick varchar(65536) NOT NULL,
name varchar(65536),
PRIMARY KEY (nick)
);
CREATE TABLE booleantests (
id integer DEFAULT unique,
value boolean,
PRIMARY KEY (id)
);
SET UNIQUE FOR booleantests(id);
CREATE TABLE auto_id_tests (
auto_id integer DEFAULT unique,
value integer,
PRIMARY KEY (auto_id)
);
SET UNIQUE FOR auto_id_tests(auto_id);
CREATE TABLE entrants (
id integer DEFAULT unique,
name varchar(65536),
course_id integer,
PRIMARY KEY (id)
);
SET UNIQUE FOR entrants(id);
CREATE TABLE colnametests (
id integer DEFAULT unique,
"references" integer NOT NULL,
PRIMARY KEY (id)
);
SET UNIQUE FOR colnametests(id);
CREATE TABLE mixins (
id integer DEFAULT unique,
parent_id integer,
type character varying(100),
pos integer,
lft integer,
rgt integer,
root_id integer,
created_at timestamp,
updated_at timestamp,
PRIMARY KEY (id)
);
SET UNIQUE FOR mixins(id);
CREATE TABLE people (
id integer DEFAULT unique,
first_name varchar(65536),
lock_version integer default 0,
PRIMARY KEY (id)
);
SET UNIQUE FOR people(id);
CREATE TABLE readers (
id integer DEFAULT unique,
post_id INTEGER NOT NULL,
person_id INTEGER NOT NULL,
PRIMARY KEY (id)
);
SET UNIQUE FOR readers(id);
CREATE TABLE binaries (
id integer DEFAULT unique,
data BLOB,
PRIMARY KEY (id)
);
SET UNIQUE FOR binaries(id);
CREATE TABLE computers (
id integer DEFAULT unique,
developer integer NOT NULL,
"extendedWarranty" integer NOT NULL,
PRIMARY KEY (id)
);
SET UNIQUE FOR computers(id);
CREATE TABLE posts (
id integer DEFAULT unique,
author_id integer,
title varchar(255),
type varchar(255),
body varchar(65536),
PRIMARY KEY (id)
);
SET UNIQUE FOR posts(id);
CREATE TABLE comments (
id integer DEFAULT unique,
post_id integer,
type varchar(255),
body varchar(65536),
PRIMARY KEY (id)
);
SET UNIQUE FOR comments(id);
CREATE TABLE authors (
id integer DEFAULT unique,
name varchar(255) default NULL,
PRIMARY KEY (id)
);
SET UNIQUE FOR authors(id);
CREATE TABLE tasks (
id integer DEFAULT unique,
starting timestamp,
ending timestamp,
PRIMARY KEY (id)
);
SET UNIQUE FOR tasks(id);
CREATE TABLE categories (
id integer DEFAULT unique,
name varchar(255),
type varchar(255),
PRIMARY KEY (id)
);
SET UNIQUE FOR categories(id);
CREATE TABLE categories_posts (
category_id integer NOT NULL,
post_id integer NOT NULL
);
CREATE TABLE fk_test_has_pk (
id INTEGER NOT NULL PRIMARY KEY
);
SET UNIQUE FOR fk_test_has_pk(id);
CREATE TABLE fk_test_has_fk (
id INTEGER NOT NULL PRIMARY KEY,
fk_id INTEGER NOT NULL REFERENCES fk_test_has_fk(id)
);
SET UNIQUE FOR fk_test_has_fk(id);
CREATE TABLE keyboards (
key_number integer DEFAULT unique,
"name" character varying(50),
PRIMARY KEY (key_number)
);
SET UNIQUE FOR keyboards(key_number);
create table "legacy_things"
(
"id" int,
"tps_report_number" int default NULL,
"version" int default 0 not null,
primary key ("id")
);
SET UNIQUE FOR legacy_things(id);
CREATE TABLE "numeric_data" (
"id" integer NOT NULL
"bank_balance" DECIMAL(10,2),
"big_bank_balance" DECIMAL(15,2),
"world_population" DECIMAL(10),
"my_house_population" DECIMAL(2),
"decimal_number_with_default" DECIMAL(3,2) DEFAULT 2.78,
primary key ("id")
);
SET UNIQUE FOR numeric_data(id);
CREATE TABLE mixed_case_monkeys (
"monkeyID" integer DEFAULT unique,
"fleaCount" integer
);
SET UNIQUE FOR mixed_case_monkeys("monkeyID");
CREATE TABLE minimalistics (
"id" integer NOT NULL
);
SET UNIQUE FOR minimalistics("id");

View file

@ -0,0 +1 @@
DROP TABLE courses CASCADE;

View file

@ -0,0 +1,4 @@
CREATE TABLE courses (
id integer DEFAULT unique,
name varchar(100)
);

View file

@ -0,0 +1,2 @@
DROP ALL
go

View file

@ -0,0 +1,318 @@
CREATE TABLE accounts (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
firm_id integer,
credit_limit integer
)
go
CREATE PRIMARY KEY accounts (id)
go
CREATE TABLE funny_jokes (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name char(50) DEFAULT NULL
)
go
CREATE PRIMARY KEY funny_jokes (id)
go
CREATE TABLE companies (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
type char(50),
ruby_type char(50),
firm_id integer,
name char(50),
client_of integer,
rating integer default 1
)
go
CREATE PRIMARY KEY companies (id)
go
CREATE TABLE developers_projects (
developer_id integer NOT NULL,
project_id integer NOT NULL,
joined_on date,
access_level integer default 1
)
go
CREATE TABLE developers (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name char(100),
salary integer DEFAULT 70000,
created_at datetime,
updated_at datetime
)
go
CREATE PRIMARY KEY developers (id)
go
CREATE TABLE projects (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name char(100),
type char(255)
)
go
CREATE PRIMARY KEY projects (id)
go
CREATE TABLE topics (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
title char(255),
author_name char(255),
author_email_address char(255),
written_on datetime,
bonus_time time,
last_read date,
content char(4096),
approved boolean default true,
replies_count integer default 0,
parent_id integer,
type char(50)
)
go
CREATE PRIMARY KEY topics (id)
go
CREATE TABLE customers (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name char,
balance integer default 0,
address_street char,
address_city char,
address_country char,
gps_location char
)
go
CREATE PRIMARY KEY customers (id)
go
CREATE TABLE orders (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name char,
billing_customer_id integer,
shipping_customer_id integer
)
go
CREATE PRIMARY KEY orders (id)
go
CREATE TABLE movies (
movieid integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
name text
)
go
CREATE PRIMARY KEY movies (movieid)
go
CREATE TABLE subscribers (
nick CHAR(100) NOT NULL DEFAULT _rowid,
name CHAR(100)
)
go
CREATE PRIMARY KEY subscribers (nick)
go
CREATE TABLE booleantests (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
value boolean
)
go
CREATE PRIMARY KEY booleantests (id)
go
CREATE TABLE defaults (
id integer UNIQUE INDEX ,
modified_date date default CURDATE(),
modified_date_function date default NOW(),
fixed_date date default '2004-01-01',
modified_time timestamp default NOW(),
modified_time_function timestamp default NOW(),
fixed_time timestamp default '2004-01-01 00:00:00.000000-00',
char1 char(1) default 'Y',
char2 char(50) default 'a char field',
char3 text default 'a text field',
positive_integer integer default 1,
negative_integer integer default -1,
decimal_number money default 2.78
)
go
CREATE PRIMARY KEY defaults (id)
go
CREATE TABLE auto_id_tests (
auto_id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
value integer
)
go
CREATE PRIMARY KEY auto_id_tests (auto_id)
go
CREATE TABLE entrants (
id integer NOT NULL UNIQUE INDEX,
name text NOT NULL,
course_id integer NOT NULL
)
go
CREATE PRIMARY KEY entrants (id)
go
CREATE TABLE colnametests (
id integer UNIQUE INDEX ,
references integer NOT NULL
)
go
CREATE PRIMARY KEY colnametests (id)
go
CREATE TABLE mixins (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
parent_id integer,
type char,
pos integer,
lft integer,
rgt integer,
root_id integer,
created_at timestamp,
updated_at timestamp
)
go
CREATE PRIMARY KEY mixins (id)
go
CREATE TABLE people (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
first_name text,
lock_version integer default 0
)
go
CREATE PRIMARY KEY people (id)
go
CREATE TABLE readers (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
post_id integer NOT NULL,
person_id integer NOT NULL
)
go
CREATE PRIMARY KEY readers (id)
go
CREATE TABLE binaries (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
data object
)
go
CREATE PRIMARY KEY binaries (id)
go
CREATE TABLE computers (
id integer UNIQUE INDEX ,
developer integer NOT NULL,
extendedWarranty integer NOT NULL
)
go
CREATE TABLE posts (
id integer UNIQUE INDEX ,
author_id integer,
title char(255),
type char(255),
body text
)
go
CREATE TABLE comments (
id integer UNIQUE INDEX ,
post_id integer,
type char(255),
body text
)
go
CREATE TABLE authors (
id integer UNIQUE INDEX ,
name char(255) default NULL
)
go
CREATE TABLE tasks (
id integer NOT NULL UNIQUE INDEX DEFAULT _rowid,
starting datetime,
ending datetime
)
go
CREATE PRIMARY KEY tasks (id)
go
CREATE TABLE categories (
id integer UNIQUE INDEX ,
name char(255),
type char(255)
)
go
CREATE TABLE categories_posts (
category_id integer NOT NULL,
post_id integer NOT NULL
)
go
CREATE TABLE fk_test_has_pk (
id INTEGER NOT NULL DEFAULT _rowid
)
go
CREATE PRIMARY KEY fk_test_has_pk (id)
go
CREATE TABLE fk_test_has_fk (
id INTEGER NOT NULL DEFAULT _rowid,
fk_id INTEGER NOT NULL REFERENCES fk_test_has_pk.id
)
go
CREATE PRIMARY KEY fk_test_has_fk (id)
go
CREATE TABLE keyboards (
key_number integer UNIQUE INDEX DEFAULT _rowid,
name char(50)
)
go
CREATE PRIMARY KEY keyboards (key_number)
go
CREATE TABLE legacy_things (
id INTEGER NOT NULL DEFAULT _rowid,
tps_report_number INTEGER default NULL,
version integer NOT NULL default 0
)
go
CREATE PRIMARY KEY legacy_things (id)
go
CREATE TABLE numeric_data (
id INTEGER NOT NULL DEFAULT _rowid,
bank_balance MONEY,
big_bank_balance MONEY,
world_population longlong,
my_house_population longlong,
decimal_number_with_default MONEY DEFAULT 2.78
);
go
CREATE PRIMARY KEY numeric_data (id)
go
CREATE TABLE mixed_case_monkeys (
monkeyID INTEGER NOT NULL DEFAULT _rowid,
fleaCount INTEGER
);
go
CREATE PRIMARY KEY mixed_case_monkeys (monkeyID)
go
CREATE TABLE minimalistics (
id INTEGER NOT NULL DEFAULT _rowid
);
go
CREATE PRIMARY KEY minimalistics (id)
go

View file

@ -0,0 +1,2 @@
DROP TABLE courses
go

View file

@ -0,0 +1,7 @@
CREATE TABLE courses (
id integer UNIQUE INDEX DEFAULT _rowid,
name text
)
go
CREATE PRIMARY KEY courses (id)
go

View file

@ -0,0 +1,67 @@
drop table accounts;
drop table funny_jokes;
drop table companies;
drop table topics;
drop synonym subjects;
drop table developers_projects;
drop table computers;
drop table developers;
drop table projects;
drop table customers;
drop table orders;
drop table movies;
drop table subscribers;
drop table booleantests;
drop table auto_id_tests;
drop table entrants;
drop table colnametests;
drop table mixins;
drop table people;
drop table readers;
drop table binaries;
drop table comments;
drop table authors;
drop table tasks;
drop table categories_posts;
drop table categories;
drop table posts;
drop table fk_test_has_pk;
drop table fk_test_has_fk;
drop table keyboards;
drop table legacy_things;
drop table numeric_data;
drop table mixed_case_monkeys;
drop table minimalistics;
drop sequence accounts_seq;
drop sequence funny_jokes_seq;
drop sequence companies_nonstd_seq;
drop sequence topics_seq;
drop sequence developers_seq;
drop sequence projects_seq;
drop sequence developers_projects_seq;
drop sequence customers_seq;
drop sequence orders_seq;
drop sequence movies_seq;
drop sequence subscribers_seq;
drop sequence booleantests_seq;
drop sequence auto_id_tests_seq;
drop sequence entrants_seq;
drop sequence colnametests_seq;
drop sequence mixins_seq;
drop sequence people_seq;
drop sequence binaries_seq;
drop sequence posts_seq;
drop sequence comments_seq;
drop sequence authors_seq;
drop sequence tasks_seq;
drop sequence computers_seq;
drop sequence categories_seq;
drop sequence categories_posts_seq;
drop sequence fk_test_has_pk_seq;
drop sequence fk_test_has_fk_seq;
drop sequence keyboards_seq;
drop sequence legacy_things_seq;
drop sequence numeric_data_seq;
drop sequence mixed_case_monkeys_seq;
drop sequence minimalistics_seq;

Some files were not shown because too many files have changed in this diff Show more