Checkout of Instiki Trunk 1/21/2007.

This commit is contained in:
Jacques Distler 2007-01-22 07:43:50 -06:00
commit 69b62b6f33
1138 changed files with 139586 additions and 0 deletions

View file

@ -0,0 +1,55 @@
# 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
assert true
end
def test_load_schema
eval(File.read("#{File.dirname(__FILE__)}/fixtures/db_definitions/schema.rb"))
assert true
end
def test_drop_and_create_courses_table
recreate Course, '2'
assert true
end
private
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,67 @@
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
require 'test/unit'
require 'active_record'
require 'active_record/fixtures'
require 'active_support/binding_of_caller'
require 'active_support/breakpoint'
require 'connection'
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)
ActiveRecord::Base.connection.class.class_eval do
self.query_count = 0
alias_method :execute, :execute_with_query_counting
end
yield
ensure
ActiveRecord::Base.connection.class.class_eval do
alias_method :execute, :execute_without_query_counting
end
assert_equal num, ActiveRecord::Base.connection.query_count, "#{ActiveRecord::Base.connection.query_count} instead of #{num} queries were executed."
end
def assert_no_queries(&block)
assert_queries(0, &block)
end
end
def current_adapter?(type)
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
ActiveRecord::Base.connection.instance_of?(ActiveRecord::ConnectionAdapters.const_get(type))
end
ActiveRecord::Base.connection.class.class_eval do
cattr_accessor :query_count
alias_method :execute_without_query_counting, :execute
def execute_with_query_counting(sql, name = nil)
self.query_count += 1
execute_without_query_counting(sql, name)
end
end
#ActiveRecord::Base.logger = Logger.new(STDOUT)
#ActiveRecord::Base.colorize_logging = false

View file

@ -0,0 +1,31 @@
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
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
private
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
end
end

View file

@ -0,0 +1,85 @@
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
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
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

View file

@ -0,0 +1,66 @@
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, Customer.find(1).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
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 connections/<db_library>" 1>&2
exit 1
fi
ruby -I $1 -e 'Dir.foreach(".") { |file| require file if file =~ /_test.rb$/ }'

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,124 @@
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_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_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
def test_push_with_attributes
david = developers(:david)
activerecord = projects(:active_record)
assert activerecord.developers_log.empty?
activerecord.developers_with_callbacks.push_with_attributes(david, {})
assert_equal ["before_adding#{david.id}", "after_adding#{david.id}"], activerecord.developers_log
activerecord.developers_with_callbacks.push_with_attributes(david, {})
assert_equal ["before_adding#{david.id}", "after_adding#{david.id}", "before_adding#{david.id}",
"after_adding#{david.id}"], activerecord.developers_log
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,106 @@
require 'abstract_unit'
require 'active_record/acts/list'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
require 'fixtures/mixin'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/reply'
class CascadedEagerLoadingTest < Test::Unit::TestCase
fixtures :authors, :mixins, :companies, :posts, :categorizations, :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 1, 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_acts_as_tree
roots = TreeMixin.find(:all, :include=>"children", :conditions=>"mixins.parent_id IS NULL", :order=>"mixins.id")
assert_equal [mixins(:tree_1), mixins(:tree2_1), mixins(:tree3_1)], roots
assert_no_queries do
assert_equal 2, roots[0].children.size
assert_equal 0, roots[1].children.size
assert_equal 0, roots[2].children.size
end
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), topics(: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

View file

@ -0,0 +1,37 @@
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_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,359 @@
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_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_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_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
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => "posts.body = 'hello'", :order => "posts.id")
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
posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "posts.body = ?", 'hello' ], :order => "posts.id")
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_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_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_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_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, :hello_posts, :special_posts, :nonexistent_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
end

View file

@ -0,0 +1,370 @@
require 'abstract_unit'
require 'fixtures/tag'
require 'fixtures/tagging'
require 'fixtures/post'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
class AssociationsJoinModelTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites
def test_has_many
assert_equal categories(:general), authors(:david).categories.first
end
def test_has_many_inherited
assert_equal categories(:sti_test), authors(:mary).categories.first
end
def test_inherited_has_many
assert_equal authors(:mary), categories(:sti_test).authors.first
end
def test_polymorphic_has_many
assert_equal taggings(:welcome_general), posts(:welcome).taggings.first
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_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_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_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), posts(:thinking)], tags(:general).taggables
end
assert_raises ActiveRecord::EagerLoadPolymorphicError do
assert_equal [posts(:welcome), posts(:thinking)], tags(:general).taggings.find(:all, :include => :taggable)
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
assert_equal comments(:does_it_hurt), authors(:david).comments.find(:first, :conditions => "comments.type='SpecialComment'", :order => 'comments.id')
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), taggings(: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), taggings(: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_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_correct_attributes
assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_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

1314
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,37 @@
require 'abstract_unit'
require 'fixtures/binary'
class BinaryTest < Test::Unit::TestCase
BINARY_FIXTURE_PATH = File.dirname(__FILE__) + '/fixtures/flowers.jpg'
def setup
Binary.connection.execute 'DELETE FROM binaries'
@data = File.read(BINARY_FIXTURE_PATH).freeze
end
def test_truth
assert true
end
# 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 %w(SQLServer Sybase DB2 Oracle Firebird).include? ActiveRecord::Base.connection.adapter_name
def test_load_save
bin = Binary.new
bin.data = @data
assert @data == bin.data, 'Newly assigned data differs from original'
bin.save
assert @data == bin.data, 'Data differs from original after save'
db_bin = Binary.find(bin.id)
assert @data == db_bin.data, 'Reloaded data differs from original'
end
end
end

View file

@ -0,0 +1,181 @@
require 'abstract_unit'
require 'fixtures/company'
require 'fixtures/topic'
Company.has_many :accounts
class CalculationsTest < Test::Unit::TestCase
fixtures :companies, :accounts, :topics
def test_should_sum_field
assert_equal 265, Account.sum(:credit_limit)
end
def test_should_average_field
value = Account.average(:credit_limit)
assert_equal 53, value
assert_kind_of Float, value
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
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], 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, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 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 5, Account.calculate(:count, '*')
assert_equal 5, 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
def test_should_calculate_grouped_by_function
c = Company.count(:all, :group => 'UPPER(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.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_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, :include => :posts) }
assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :sum, :foo => :bar) }
assert_raises(ArgumentError) { Company.send(:validate_calculation_options, :count, :foo => :bar) }
end
end

View file

@ -0,0 +1,364 @@
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 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 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_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
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,24 @@
print "Using native DB2\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
db1 = 'arunit'
db2 = 'arunit2'
ActiveRecord::Base.establish_connection(
:adapter => "db2",
:host => "localhost",
:username => "arunit",
:password => "arunit",
:database => db1
)
Course.establish_connection(
:adapter => "db2",
:host => "localhost",
:username => "arunit2",
:password => "arunit2",
:database => db2
)

View file

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

View file

@ -0,0 +1,21 @@
print "Using native MySQL\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
db1 = 'activerecord_unittest'
db2 = 'activerecord_unittest2'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:username => "rails",
:encoding => "utf8",
:database => db1
)
Course.establish_connection(
:adapter => "mysql",
:username => "rails",
:database => db2
)

View file

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

View file

@ -0,0 +1,23 @@
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.establish_connection(
:adapter => 'oracle',
:username => 'arunit',
:password => 'arunit',
:database => db
)
Course.establish_connection(
:adapter => 'oracle',
:username => 'arunit2',
:password => 'arunit2',
:database => db
)

View file

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

View file

@ -0,0 +1,37 @@
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, db_definitions_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)
clazz.establish_connection(
:adapter => "sqlite",
:database => db_file)
script = File.read("#{BASE_DIR}/db_definitions/#{db_definitions_file}")
# SQLite-Ruby has problems with semi-colon separated commands, so split and execute one at a time
script.split(';').each do
|command|
clazz.connection.execute(command) unless command.strip.empty?
end
else
clazz.establish_connection(
:adapter => "sqlite",
:database => db_file)
end
end
make_connection(ActiveRecord::Base, sqlite_test_db, 'sqlite.sql')
make_connection(Course, sqlite_test_db2, 'sqlite2.sql')
load(File.join(BASE_DIR, 'db_definitions', 'schema.rb'))

View file

@ -0,0 +1,37 @@
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, db_definitions_file)
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)
clazz.establish_connection(
:adapter => "sqlite3",
:database => db_file)
script = File.read("#{BASE_DIR}/db_definitions/#{db_definitions_file}")
# SQLite-Ruby has problems with semi-colon separated commands, so split and execute one at a time
script.split(';').each do
|command|
clazz.connection.execute(command) unless command.strip.empty?
end
else
clazz.establish_connection(
:adapter => "sqlite3",
:database => db_file)
end
end
make_connection(ActiveRecord::Base, sqlite_test_db, 'sqlite.sql')
make_connection(Course, sqlite_test_db2, 'sqlite2.sql')
load(File.join(BASE_DIR, 'db_definitions', 'schema.rb'))

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,24 @@
print "Using native SQLServer\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
db1 = 'activerecord_unittest'
db2 = 'activerecord_unittest2'
ActiveRecord::Base.establish_connection(
:adapter => "sqlserver",
:host => "localhost",
:username => "sa",
:password => "",
:database => db1
)
Course.establish_connection(
:adapter => "sqlserver",
:host => "localhost",
:username => "sa",
:password => "",
:database => db2
)

View file

@ -0,0 +1,26 @@
print "Using native SQLServer via ODBC\n"
require_dependency 'fixtures/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
dsn1 = 'activerecord_unittest'
dsn2 = 'activerecord_unittest2'
ActiveRecord::Base.establish_connection(
:adapter => "sqlserver",
:mode => "ODBC",
:host => "localhost",
:username => "sa",
:password => "",
:dsn => dsn1
)
Course.establish_connection(
:adapter => "sqlserver",
:mode => "ODBC",
:host => "localhost",
:username => "sa",
:password => "",
:dsn => dsn2
)

View file

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

View file

@ -0,0 +1,64 @@
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|
assert_equal column_values(from, 'client_of').compact.sort,
column_values(to, 'fan_of').compact.sort
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
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}").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,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,18 @@
require 'abstract_unit'
require 'fixtures/default'
class DefaultsTest < Test::Unit::TestCase
if %w(PostgreSQL).include? ActiveRecord::Base.connection.adapter_name
def test_default_integers
default = Default.new
assert_instance_of(Fixnum, default.positive_integer)
assert_equal(default.positive_integer, 1)
assert_instance_of(Fixnum, default.negative_integer)
assert_equal(default.negative_integer, -1)
end
else
def test_dummy
assert true
end
end
end

View file

@ -0,0 +1,352 @@
require 'abstract_unit'
require 'fixtures/developer'
require 'fixtures/project'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/reply'
# Can't declare new classes in test case methods, so tests before that
bad_collection_keys = false
begin
class Car < ActiveRecord::Base; has_many :wheels, :name => "wheels"; end
rescue ArgumentError
bad_collection_keys = true
end
raise "ActiveRecord should have barked on bad collection keys" unless bad_collection_keys
class DeprecatedAssociationsTest < Test::Unit::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
:developers_projects
def test_has_many_find
assert_equal 2, Firm.find_first.clients.length
end
def test_has_many_orders
assert_equal "Summit", Firm.find_first.clients.first.name
end
def test_has_many_class_name
assert_equal "Microsoft", Firm.find_first.clients_sorted_desc.first.name
end
def test_has_many_foreign_key
assert_equal "Microsoft", Firm.find_first.clients_of_firm.first.name
end
def test_has_many_conditions
assert_equal "Microsoft", Firm.find_first.clients_like_ms.first.name
end
def test_has_many_sql
firm = Firm.find_first
assert_equal "Microsoft", firm.clients_using_sql.first.name
assert_equal 1, firm.clients_using_sql_count
assert_equal 1, Firm.find_first.clients_using_sql_count
end
def test_has_many_counter_sql
assert_equal 1, Firm.find_first.clients_using_counter_sql_count
end
def test_has_many_queries
assert Firm.find_first.has_clients?
firm = Firm.find_first
assert_equal 2, firm.clients_count # tests using class count
firm.clients
assert firm.has_clients?
assert_equal 2, firm.clients_count # tests using collection length
end
def test_has_many_dependence
assert_equal 3, Client.find_all.length
Firm.find_first.destroy
assert_equal 1, Client.find_all.length
end
uses_transaction :test_has_many_dependence_with_transaction_support_on_failure
def test_has_many_dependence_with_transaction_support_on_failure
assert_equal 3, Client.find_all.length
firm = Firm.find_first
clients = firm.clients
clients.last.instance_eval { def before_destroy() raise "Trigger rollback" end }
firm.destroy rescue "do nothing"
assert_equal 3, Client.find_all.length
end
def test_has_one_dependence
num_accounts = Account.count
firm = Firm.find(1)
assert firm.has_account?
firm.destroy
assert_equal num_accounts - 1, Account.count
end
def test_has_one_dependence_with_missing_association
Account.destroy_all
firm = Firm.find(1)
assert !firm.has_account?
firm.destroy
end
def test_belongs_to
assert_equal companies(:first_firm).name, Client.find(3).firm.name
assert Client.find(3).has_firm?, "Microsoft should have a firm"
# assert !Company.find(1).has_firm?, "37signals shouldn't have a firm"
end
def test_belongs_to_with_different_class_name
assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
assert Company.find(3).has_firm_with_other_name?, "Microsoft should have a firm"
end
def test_belongs_to_with_condition
assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
assert Company.find(3).has_firm_with_condition?, "Microsoft should have a firm"
end
def test_belongs_to_equality
assert Company.find(3).firm?(Company.find(1)), "Microsoft should have 37signals as firm"
assert_raises(RuntimeError) { !Company.find(3).firm?(Company.find(3)) } # "Summit shouldn't have itself as firm"
end
def test_has_one
assert companies(:first_firm).account?(Account.find(1))
assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit
assert companies(:first_firm).has_account?, "37signals should have an account"
assert Account.find(1).firm?(companies(:first_firm)), "37signals account should be able to backtrack"
assert Account.find(1).has_firm?, "37signals account should be able to backtrack"
assert !Account.find(2).has_firm?, "Unknown isn't linked"
assert !Account.find(2).firm?(companies(:first_firm)), "Unknown isn't linked"
end
def test_has_many_dependence_on_account
num_accounts = Account.count
companies(:first_firm).destroy
assert_equal num_accounts - 1, Account.count
end
def test_find_in
assert_equal Client.find(2).name, companies(:first_firm).find_in_clients(2).name
assert_raises(ActiveRecord::RecordNotFound) { companies(:first_firm).find_in_clients(6) }
end
def test_force_reload
firm = Firm.new("name" => "A New Firm, Inc")
firm.save
firm.clients.each {|c|} # forcing to load all clients
assert firm.clients.empty?, "New firm shouldn't have client objects"
assert !firm.has_clients?, "New firm shouldn't have clients"
assert_equal 0, firm.clients_count, "New firm should have 0 clients"
client = Client.new("name" => "TheClient.com", "firm_id" => firm.id)
client.save
assert firm.clients.empty?, "New firm should have cached no client objects"
assert !firm.has_clients?, "New firm should have cached a no-clients response"
assert_equal 0, firm.clients_count, "New firm should have cached 0 clients count"
assert !firm.clients(true).empty?, "New firm should have reloaded client objects"
assert firm.has_clients?(true), "New firm should have reloaded with a have-clients response"
assert_equal 1, firm.clients_count(true), "New firm should have reloaded clients count"
end
def test_included_in_collection
assert companies(:first_firm).clients.include?(Client.find(2))
end
def test_build_to_collection
assert_equal 1, companies(:first_firm).clients_of_firm_count
new_client = companies(:first_firm).build_to_clients_of_firm("name" => "Another Client")
assert_equal "Another Client", new_client.name
assert new_client.save
assert new_client.firm?(companies(:first_firm))
assert_equal 2, companies(:first_firm).clients_of_firm_count(true)
end
def test_create_in_collection
assert_equal companies(:first_firm).create_in_clients_of_firm("name" => "Another Client"), companies(:first_firm).clients_of_firm(true).last
end
def test_has_and_belongs_to_many
david = Developer.find(1)
assert david.has_projects?
assert_equal 2, david.projects_count
active_record = Project.find(1)
assert active_record.has_developers?
assert_equal 3, active_record.developers_count
assert active_record.developers.include?(david)
end
def test_has_and_belongs_to_many_removing
david = Developer.find(1)
active_record = Project.find(1)
david.remove_projects(active_record)
assert_equal 1, david.projects_count
assert_equal 2, active_record.developers_count
end
def test_has_and_belongs_to_many_zero
david = Developer.find(1)
david.remove_projects(Project.find_all)
assert_equal 0, david.projects_count
assert !david.has_projects?
end
def test_has_and_belongs_to_many_adding
jamis = Developer.find(2)
action_controller = Project.find(2)
jamis.add_projects(action_controller)
assert_equal 2, jamis.projects_count
assert_equal 2, action_controller.developers_count
end
def test_has_and_belongs_to_many_adding_from_the_project
jamis = Developer.find(2)
action_controller = Project.find(2)
action_controller.add_developers(jamis)
assert_equal 2, jamis.projects_count
assert_equal 2, action_controller.developers_count
end
def test_has_and_belongs_to_many_adding_a_collection
aredridel = Developer.new("name" => "Aredridel")
aredridel.save
aredridel.add_projects([ Project.find(1), Project.find(2) ])
assert_equal 2, aredridel.projects_count
end
def test_belongs_to_counter
topic = Topic.create("title" => "Apple", "content" => "hello world")
assert_equal 0, topic.send(:read_attribute, "replies_count"), "No replies yet"
reply = topic.create_in_replies("title" => "I'm saying no!", "content" => "over here")
assert_equal 1, Topic.find(topic.id).send(:read_attribute, "replies_count"), "First reply created"
reply.destroy
assert_equal 0, Topic.find(topic.id).send(:read_attribute, "replies_count"), "First reply deleted"
end
def test_natural_assignment_of_has_one
apple = Firm.create("name" => "Apple")
citibank = Account.create("credit_limit" => 10)
apple.account = citibank
assert_equal apple.id, citibank.firm_id
end
def test_natural_assignment_of_belongs_to
apple = Firm.create("name" => "Apple")
citibank = Account.create("credit_limit" => 10)
citibank.firm = apple
assert_equal apple.id, citibank.firm_id
end
def test_natural_assignment_of_has_many
apple = Firm.create("name" => "Apple")
natural = Client.create("name" => "Natural Company")
apple.clients << natural
assert_equal apple.id, natural.firm_id
assert_equal Client.find(natural.id), Firm.find(apple.id).clients.find(natural.id)
apple.clients.delete natural
assert_raises(ActiveRecord::RecordNotFound) {
Firm.find(apple.id).clients.find(natural.id)
}
end
def test_natural_adding_of_has_and_belongs_to_many
rails = Project.create("name" => "Rails")
ap = Project.create("name" => "Action Pack")
john = Developer.create("name" => "John")
mike = Developer.create("name" => "Mike")
rails.developers << john
rails.developers << mike
assert_equal Developer.find(john.id), Project.find(rails.id).developers.find(john.id)
assert_equal Developer.find(mike.id), Project.find(rails.id).developers.find(mike.id)
assert_equal Project.find(rails.id), Developer.find(mike.id).projects.find(rails.id)
assert_equal Project.find(rails.id), Developer.find(john.id).projects.find(rails.id)
ap.developers << john
assert_equal Developer.find(john.id), Project.find(ap.id).developers.find(john.id)
assert_equal Project.find(ap.id), Developer.find(john.id).projects.find(ap.id)
ap.developers.delete john
assert_raises(ActiveRecord::RecordNotFound) {
Project.find(ap.id).developers.find(john.id)
}
assert_raises(ActiveRecord::RecordNotFound) {
Developer.find(john.id).projects.find(ap.id)
}
end
def test_storing_in_pstore
require "pstore"
require "tmpdir"
apple = Firm.create("name" => "Apple")
natural = Client.new("name" => "Natural Company")
apple.clients << natural
db = PStore.new(File.join(Dir.tmpdir, "ar-pstore-association-test"))
db.transaction do
db["apple"] = apple
end
db = PStore.new(File.join(Dir.tmpdir, "ar-pstore-association-test"))
db.transaction do
assert_equal "Natural Company", db["apple"].clients.first.name
end
end
def test_has_many_find_all
assert_equal 2, Firm.find_first.find_all_in_clients("#{QUOTED_TYPE} = 'Client'").length
assert_equal 1, Firm.find_first.find_all_in_clients("name = 'Summit'").length
end
def test_has_one
assert companies(:first_firm).account?(Account.find(1))
assert companies(:first_firm).has_account?, "37signals should have an account"
assert Account.find(1).firm?(companies(:first_firm)), "37signals account should be able to backtrack"
assert Account.find(1).has_firm?, "37signals account should be able to backtrack"
assert !Account.find(2).has_firm?, "Unknown isn't linked"
assert !Account.find(2).firm?(companies(:first_firm)), "Unknown isn't linked"
end
def test_has_one_build
firm = Firm.new("name" => "GlobalMegaCorp")
assert firm.save
account = firm.build_account("credit_limit" => 1000)
assert account.save
assert_equal account, firm.account
end
def test_has_one_failing_build_association
firm = Firm.new("name" => "GlobalMegaCorp")
firm.save
account = firm.build_account
assert !account.save
assert_equal "can't be empty", account.errors.on("credit_limit")
end
def test_has_one_create
firm = Firm.new("name" => "GlobalMegaCorp")
firm.save
assert_equal firm.create_account("credit_limit" => 1000), firm.account
end
end

View file

@ -0,0 +1,134 @@
require 'abstract_unit'
require 'fixtures/company'
require 'fixtures/topic'
require 'fixtures/entrant'
require 'fixtures/developer'
class DeprecatedFinderTest < Test::Unit::TestCase
fixtures :companies, :topics, :entrants, :developers
def test_find_all_with_limit
entrants = Entrant.find_all nil, "id ASC", 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 nil, "id ASC", [2, 1]
assert_equal(2, entrants.size)
assert_equal(entrants(:second).name, entrants.first.name)
end
def test_find_first
first = Topic.find_first "title = 'The First Topic'"
assert_equal(topics(:first).title, first.title)
end
def test_find_first_failing
first = Topic.find_first "title = 'The First Topic!'"
assert_nil(first)
end
def test_deprecated_find_on_conditions
assert Topic.find_on_conditions(1, ["approved = ?", false])
assert_raises(ActiveRecord::RecordNotFound) { Topic.find_on_conditions(1, ["approved = ?", true]) }
end
def test_condition_interpolation
assert_kind_of Firm, Company.find_first(["name = '%s'", "37signals"])
assert_nil Company.find_first(["name = '%s'", "37signals!"])
assert_nil Company.find_first(["name = '%s'", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find_first(["id = %d", 1]).written_on
end
def test_bind_variables
assert_kind_of Firm, Company.find_first(["name = ?", "37signals"])
assert_nil Company.find_first(["name = ?", "37signals!"])
assert_nil Company.find_first(["name = ?", "37signals!' OR 1=1"])
assert_kind_of Time, Topic.find_first(["id = ?", 1]).written_on
assert_raises(ActiveRecord::PreparedStatementInvalid) {
Company.find_first(["id=? AND name = ?", 2])
}
assert_raises(ActiveRecord::PreparedStatementInvalid) {
Company.find_first(["id=?", 2, 3, 4])
}
end
def test_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find_first(["name = ?", "37signals' go'es agains"])
end
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
assert Company.find_first(["name = :name", {:name => "37signals' go'es agains"}])
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(["name = :name", { :name => "37signals" }])
assert_nil Company.find_first(["name = :name", { :name => "37signals!" }])
assert_nil Company.find_first(["name = :name", { :name => "37signals!' OR 1=1" }])
assert_kind_of Time, Topic.find_first(["id = :id", { :id => 1 }]).written_on
end
def test_count
assert_equal(0, Entrant.count("id > 3"))
assert_equal(1, Entrant.count(["id > ?", 2]))
assert_equal(2, Entrant.count(["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_all_with_limit
first_five_developers = Developer.find_all nil, 'id ASC', 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 nil, 'id ASC', 0
assert_equal 0, no_developers.length
assert_equal first_five_developers, Developer.find_all(nil, 'id ASC', [5])
assert_equal no_developers, Developer.find_all(nil, 'id ASC', [0])
end
def test_find_all_with_limit_and_offset
first_three_developers = Developer.find_all nil, 'id ASC', [3, 0]
second_three_developers = Developer.find_all nil, 'id ASC', [3, 3]
last_two_developers = Developer.find_all nil, 'id ASC', [2, 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_by_one_attribute_with_options
topics = Topic.find_all_by_content("Have a nice day", "id DESC")
assert topics(:first), topics.last
topics = Topic.find_all_by_content("Have a nice day", "id DESC")
assert topics(:first), topics.first
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,381 @@
require 'abstract_unit'
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, :accounts
def test_find
assert_equal(topics(:first).title, Topic.find(1).title)
end
def test_exists
assert (Topic.exists?(1))
assert !(Topic.exists?(45))
assert !(Topic.exists?("foo"))
assert !(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).length)
assert_equal(topics(:second).title, Topic.find([ 2 ]).first.title)
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_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(NoMethodError) { 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_conditions
assert Topic.find(1, :conditions => ["approved = ?", false])
assert_raises(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => ["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_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
assert_equal '1,2,3', bind('?', [1, 2, 3])
assert_equal %('a','b','c'), bind('?', %w(a b c))
assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
assert_equal %('a','b','c'), bind(':a', :a => %w(a b c)) # '
require 'set'
assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
assert_equal %('a','b','c'), bind('?', Set.new(%w(a b c)))
assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3]))
assert_equal %('a','b','c'), bind(':a', :a => Set.new(%w(a b c))) # '
end
def test_bind_string
assert_equal "''", bind('?', '')
end
def test_string_sanitation
assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
end
def test_count
assert_equal(0, Entrant.count("id > 3"))
assert_equal(1, Entrant.count(["id > ?", 2]))
assert_equal(2, Entrant.count(["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_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_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_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")
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")
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_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_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
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"], 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"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
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,23 @@
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

View file

@ -0,0 +1,76 @@
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 :comments, :through => :posts
has_many :funky_comments, :through => :posts, :source => :comments
has_many :special_posts, :class_name => "Post"
has_many :hello_posts, :class_name => "Post", :conditions=>"\#{aliased_table_name}.body = 'hello'"
has_many :nonexistent_posts, :class_name => "Post", :conditions=>"\#{aliased_table_name}.body = 'nonexistent'"
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}"},
:after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id}"},
: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}"}],
:after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id}"}]
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 :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
private
def log_before_adding(object)
@post_log << "before_adding#{object.id}"
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,2 @@
class Binary < ActiveRecord::Base
end

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,11 @@
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

View file

@ -0,0 +1,21 @@
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 :hello_posts, :class_name => "Post", :conditions => "\#{aliased_table_name}.body = 'hello'"
has_and_belongs_to_many :nonexistent_posts, :class_name => "Post", :conditions=>"\#{aliased_table_name}.body = 'nonexistent'"
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,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,65 @@
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_comment:
id: 4
post_id: 4
body: Normal type
type: Comment
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,50 @@
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

View file

@ -0,0 +1,85 @@
class Company < ActiveRecord::Base
attr_protected :rating
set_sequence_name :companies_nonstd_seq
validates_presence_of :name
has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account"
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_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_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 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
protected
def validate
errors.add_on_empty "credit_limit"
end
end

View file

@ -0,0 +1,61 @@
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
protected
def validate
errors.add_on_boundary_breaking("name", 3..20)
end
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
belongs_to :firm, :class_name => 'MyApplication::Business::Firm'
belongs_to :qualified_billing_firm, :class_name => 'MyApplication::Billing::Firm'
belongs_to :unqualified_billing_firm, :class_name => 'Firm'
belongs_to :nested_qualified_billing_firm, :class_name => 'MyApplication::Billing::Nested::Firm'
belongs_to :nested_unqualified_billing_firm, :class_name => 'Nested::Firm'
protected
def validate
errors.add_on_empty "credit_limit"
end
end
end
end

View file

@ -0,0 +1,3 @@
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,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) ]
composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
composed_of :gps_location
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,8 @@
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

View file

@ -0,0 +1,30 @@
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;

View file

@ -0,0 +1,217 @@
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)
);

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,58 @@
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 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;

View file

@ -0,0 +1,285 @@
CREATE DOMAIN D_BOOLEAN AS SMALLINT CHECK (VALUE IN (0, 1));
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;

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,30 @@
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 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 computers;
DROP TABLE tasks;
DROP TABLE posts;
DROP TABLE comments;
DROP TABLE authors;
DROP TABLE categories;
DROP TABLE categories_posts;
DROP TABLE fk_test_has_fk;
DROP TABLE fk_test_has_pk;
DROP TABLE keyboards;
DROP TABLE legacy_things;

View file

@ -0,0 +1,219 @@
CREATE TABLE `accounts` (
`id` int(11) NOT NULL auto_increment,
`firm_id` int(11) default NULL,
`credit_limit` int(5) default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `funny_jokes` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `companies` (
`id` int(11) NOT NULL auto_increment,
`type` varchar(50) default NULL,
`ruby_type` varchar(50) default NULL,
`firm_id` int(11) default NULL,
`name` varchar(50) default NULL,
`client_of` int(11) default NULL,
`rating` int(11) default NULL default 1,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `topics` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`author_name` varchar(255) default NULL,
`author_email_address` varchar(255) default NULL,
`written_on` datetime default NULL,
`bonus_time` time default NULL,
`last_read` date default NULL,
`content` text,
`approved` tinyint(1) default 1,
`replies_count` int(11) default 0,
`parent_id` int(11) default NULL,
`type` varchar(50) default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `developers` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`salary` int(11) default 70000,
`created_at` datetime default NULL,
`updated_at` datetime default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `projects` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`type` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `developers_projects` (
`developer_id` int(11) NOT NULL,
`project_id` int(11) NOT NULL,
`joined_on` date default NULL,
`access_level` smallint default 1
) TYPE=InnoDB;
CREATE TABLE `orders` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`billing_customer_id` int(11) default NULL,
`shipping_customer_id` int(11) default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `customers` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`balance` int(6) 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`)
) TYPE=InnoDB;
CREATE TABLE `movies` (
`movieid` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
PRIMARY KEY (`movieid`)
) TYPE=InnoDB;
CREATE TABLE `subscribers` (
`nick` varchar(100) NOT NULL,
`name` varchar(100) default NULL,
PRIMARY KEY (`nick`)
) TYPE=InnoDB;
CREATE TABLE `booleantests` (
`id` int(11) NOT NULL auto_increment,
`value` integer default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `auto_id_tests` (
`auto_id` int(11) NOT NULL auto_increment,
`value` integer default NULL,
PRIMARY KEY (`auto_id`)
) TYPE=InnoDB;
CREATE TABLE `entrants` (
`id` INTEGER NOT NULL PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`course_id` INTEGER NOT NULL
);
CREATE TABLE `colnametests` (
`id` int(11) NOT NULL auto_increment,
`references` int(11) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `mixins` (
`id` int(11) NOT NULL auto_increment,
`parent_id` int(11) default NULL,
`pos` int(11) default NULL,
`created_at` datetime default NULL,
`updated_at` datetime default NULL,
`lft` int(11) default NULL,
`rgt` int(11) default NULL,
`root_id` int(11) default NULL,
`type` varchar(40) default NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `people` (
`id` INTEGER NOT NULL PRIMARY KEY,
`first_name` VARCHAR(40) NOT NULL,
`lock_version` INTEGER NOT NULL DEFAULT 0
) TYPE=InnoDB;
CREATE TABLE `readers` (
`id` int(11) NOT NULL PRIMARY KEY,
`post_id` INTEGER NOT NULL,
`person_id` INTEGER NOT NULL
) TYPE=InnoDB;
CREATE TABLE `binaries` (
`id` int(11) NOT NULL auto_increment,
`data` mediumblob,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `computers` (
`id` INTEGER NOT NULL PRIMARY KEY,
`developer` INTEGER NOT NULL,
`extendedWarranty` INTEGER NOT NULL
) TYPE=InnoDB;
CREATE TABLE `posts` (
`id` INTEGER NOT NULL PRIMARY KEY,
`author_id` INTEGER,
`title` VARCHAR(255) NOT NULL,
`body` TEXT NOT NULL,
`type` VARCHAR(255) NOT NULL
) TYPE=InnoDB;
CREATE TABLE `comments` (
`id` INTEGER NOT NULL PRIMARY KEY,
`post_id` INTEGER NOT NULL,
`body` TEXT NOT NULL,
`type` VARCHAR(255) NOT NULL
) TYPE=InnoDB;
CREATE TABLE `authors` (
`id` INTEGER NOT NULL PRIMARY KEY,
`name` VARCHAR(255) NOT NULL
) TYPE=InnoDB;
CREATE TABLE `tasks` (
`id` int(11) NOT NULL auto_increment,
`starting` datetime NOT NULL default '0000-00-00 00:00:00',
`ending` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `categories` (
`id` int(11) NOT NULL auto_increment,
`name` VARCHAR(255) NOT NULL,
`type` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) TYPE=InnoDB;
CREATE TABLE `categories_posts` (
`category_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL
) TYPE=InnoDB;
CREATE TABLE `fk_test_has_pk` (
`id` INTEGER NOT NULL PRIMARY KEY
) TYPE=InnoDB;
CREATE TABLE `fk_test_has_fk` (
`id` INTEGER NOT NULL PRIMARY KEY,
`fk_id` INTEGER NOT NULL,
FOREIGN KEY (`fk_id`) REFERENCES `fk_test_has_pk`(`id`)
) TYPE=InnoDB;
CREATE TABLE `keyboards` (
`key_number` int(11) NOT NULL auto_increment primary key,
`name` varchar(50) default NULL
);
-- Altered lock_version column name.
CREATE TABLE `legacy_things` (
`id` int(11) NOT NULL auto_increment,
`tps_report_number` int(11) default NULL,
`version` int(11) NOT NULL default 0,
PRIMARY KEY (`id`)
) TYPE=InnoDB;

View file

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

View file

@ -0,0 +1,5 @@
CREATE TABLE `courses` (
`id` INTEGER NOT NULL PRIMARY KEY,
`name` VARCHAR(255) NOT NULL
) TYPE=InnoDB;

View file

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

View file

@ -0,0 +1,282 @@
CREATE TABLE accounts (
id integer UNIQUE INDEX DEFAULT _rowid,
firm_id integer,
credit_limit integer
)
go
CREATE PRIMARY KEY accounts (id)
go
CREATE TABLE funny_jokes (
id integer UNIQUE INDEX DEFAULT _rowid,
name char(50) DEFAULT NULL
)
go
CREATE PRIMARY KEY funny_jokes (id)
go
CREATE TABLE companies (
id integer 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 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 UNIQUE INDEX DEFAULT _rowid,
name char(100),
type char(255)
)
go
CREATE PRIMARY KEY projects (id)
go
CREATE TABLE topics (
id integer 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 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 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 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 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'
)
go
CREATE TABLE auto_id_tests (
auto_id integer UNIQUE INDEX DEFAULT _rowid,
value integer
)
go
CREATE PRIMARY KEY auto_id_tests (auto_id)
go
CREATE TABLE entrants (
id integer UNIQUE INDEX ,
name text,
course_id integer
)
go
CREATE TABLE colnametests (
id integer UNIQUE INDEX ,
references integer NOT NULL
)
go
CREATE TABLE mixins (
id integer 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 UNIQUE INDEX DEFAULT _rowid,
first_name text,
lock_version integer default 0
)
go
CREATE PRIMARY KEY people (id)
go
CREATE TABLE readers (
id integer 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 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 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

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,61 @@
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 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;

View file

@ -0,0 +1,292 @@
create table companies (
id integer not null,
type varchar(50) default null,
ruby_type varchar(50) default null,
firm_id integer default null references companies initially deferred disable,
name varchar(50) default null,
client_of integer default null references companies initially deferred disable,
companies_count integer default 0,
rating integer default 1,
primary key (id)
);
-- non-standard sequence name used to test set_sequence_name
--
create sequence companies_nonstd_seq minvalue 10000;
create table funny_jokes (
id integer not null,
name varchar(50) default null,
primary key (id)
);
create sequence funny_jokes_seq minvalue 10000;
create table accounts (
id integer not null,
firm_id integer default null references companies initially deferred disable,
credit_limit integer default null
);
create sequence accounts_seq minvalue 10000;
create table topics (
id integer not null,
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 timestamp default null,
last_read timestamp default null,
content varchar(4000),
approved integer default 1,
replies_count integer default 0,
parent_id integer references topics initially deferred disable,
type varchar(50) default null,
primary key (id)
);
-- try again for 8i
create table topics (
id integer not null,
title varchar(255) default null,
author_name varchar(255) default null,
author_email_address varchar(255) default null,
written_on date default null,
bonus_time date default null,
last_read date default null,
content varchar(4000),
approved integer default 1,
replies_count integer default 0,
parent_id integer references topics initially deferred disable,
type varchar(50) default null,
primary key (id)
);
create sequence topics_seq minvalue 10000;
create synonym subjects for topics;
create table developers (
id integer not null,
name varchar(100) default null,
salary integer default 70000,
created_at timestamp default null,
updated_at timestamp default null,
primary key (id)
);
create sequence developers_seq minvalue 10000;
create table projects (
id integer not null,
name varchar(100) default null,
type varchar(255) default null,
primary key (id)
);
create sequence projects_seq minvalue 10000;
create table developers_projects (
developer_id integer not null references developers initially deferred disable,
project_id integer not null references projects initially deferred disable,
joined_on timestamp default null,
access_level integer default 1
);
-- Try again for 8i
create table developers_projects (
developer_id integer not null references developers initially deferred disable,
project_id integer not null references projects initially deferred disable,
joined_on date default null
);
create sequence developers_projects_seq minvalue 10000;
create table orders (
id integer not null,
name varchar(100) default null,
billing_customer_id integer default null,
shipping_customer_id integer default null,
primary key (id)
);
create sequence orders_seq minvalue 10000;
create table customers (
id integer not null,
name varchar(100) default null,
balance integer 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 sequence customers_seq minvalue 10000;
create table movies (
movieid integer not null,
name varchar(100) default null,
primary key (movieid)
);
create sequence movies_seq minvalue 10000;
create table subscribers (
nick varchar(100) not null,
name varchar(100) default null,
primary key (nick)
);
create sequence subscribers_seq minvalue 10000;
create table booleantests (
id integer not null,
value integer default null,
primary key (id)
);
create sequence booleantests_seq minvalue 10000;
create table auto_id_tests (
auto_id integer not null,
value integer default null,
primary key (auto_id)
);
create sequence auto_id_tests_seq minvalue 10000;
create table entrants (
id integer not null primary key,
name varchar(255) not null,
course_id integer not null
);
create sequence entrants_seq minvalue 10000;
create table colnametests (
id integer not null,
references integer not null,
primary key (id)
);
create sequence colnametests_seq minvalue 10000;
create table mixins (
id integer not null,
parent_id integer default null references mixins initially deferred disable,
type varchar(40) default null,
pos integer default null,
lft integer default null,
rgt integer default null,
root_id integer default null,
created_at timestamp default null,
updated_at timestamp default null,
primary key (id)
);
-- try again for 8i
create table mixins (
id integer not null,
parent_id integer default null references mixins initially deferred disable,
type varchar(40) default null,
pos integer default null,
lft integer default null,
rgt integer default null,
root_id integer default null,
created_at date default null,
updated_at date default null,
primary key (id)
);
create sequence mixins_seq minvalue 10000;
create table people (
id integer not null,
first_name varchar(40) null,
lock_version integer default 0,
primary key (id)
);
create sequence people_seq minvalue 10000;
create table readers (
id integer not null,
post_id integer not null,
person_id integer not null,
primary key (id)
);
create sequence readers_seq minvalue 10000;
create table binaries (
id integer not null,
data blob null,
primary key (id)
);
create sequence binaries_seq minvalue 10000;
create table computers (
id integer not null primary key,
developer integer not null references developers initially deferred disable,
"extendedWarranty" integer not null
);
create sequence computers_seq minvalue 10000;
create table posts (
id integer not null primary key,
author_id integer default null,
title varchar(255) default null,
type varchar(255) default null,
body varchar(3000) default null
);
create sequence posts_seq minvalue 10000;
create table comments (
id integer not null primary key,
post_id integer default null,
type varchar(255) default null,
body varchar(3000) default null
);
create sequence comments_seq minvalue 10000;
create table authors (
id integer not null primary key,
name varchar(255) default null
);
create sequence authors_seq minvalue 10000;
create table tasks (
id integer not null primary key,
starting date default null,
ending date default null
);
create sequence tasks_seq minvalue 10000;
create table categories (
id integer not null primary key,
name varchar(255) default null,
type varchar(255) default null
);
create sequence categories_seq minvalue 10000;
create table categories_posts (
category_id integer not null references categories initially deferred disable,
post_id integer not null references posts initially deferred disable
);
create sequence categories_posts_seq minvalue 10000;
create table fk_test_has_pk (
id integer not null primary key
);
create sequence fk_test_has_pk_seq minvalue 10000;
create table fk_test_has_fk (
id integer not null primary key,
fk_id integer not null references fk_test_has_fk initially deferred disable
);
create sequence fk_test_has_fk_seq minvalue 10000;
create table keyboards (
key_number integer not null,
name varchar(50) default null
);
create sequence keyboards_seq minvalue 10000;
create table test_oracle_defaults (
id integer not null primary key,
test_char char(1) default 'X' not null,
test_string varchar2(20) default 'hello' not null,
test_int integer default 3 not null
);
create sequence test_oracle_defaults_seq minvalue 10000;
--This table has an altered lock_version column name.
create table legacy_things (
id integer not null primary key,
tps_report_number integer default null,
version integer default 0
);
create sequence legacy_things_seq minvalue 10000;

View file

@ -0,0 +1,2 @@
drop table courses;
drop sequence courses_seq;

View file

@ -0,0 +1,6 @@
create table courses (
id int not null primary key,
name varchar(255) not null
);
create sequence courses_seq minvalue 10000;

View file

@ -0,0 +1,34 @@
DROP SEQUENCE accounts_id_seq;
DROP TABLE accounts;
DROP TABLE funny_jokes;
DROP TABLE companies;
DROP SEQUENCE companies_nonstd_seq;
DROP TABLE topics;
DROP TABLE developers;
DROP TABLE projects;
DROP TABLE developers_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 computers;
DROP TABLE posts;
DROP TABLE comments;
DROP TABLE authors;
DROP TABLE tasks;
DROP TABLE categories;
DROP TABLE categories_posts;
DROP TABLE defaults;
DROP TABLE fk_test_has_fk;
DROP TABLE fk_test_has_pk;
DROP TABLE geometrics;
DROP TABLE keyboards;
DROP TABLE legacy_things;

View file

@ -0,0 +1,248 @@
CREATE SEQUENCE public.accounts_id_seq START 100;
CREATE TABLE accounts (
id integer DEFAULT nextval('public.accounts_id_seq'),
firm_id integer,
credit_limit integer,
PRIMARY KEY (id)
);
CREATE TABLE funny_jokes (
id serial,
name character varying(50)
);
CREATE SEQUENCE companies_nonstd_seq START 101;
CREATE TABLE companies (
id integer DEFAULT nextval('companies_nonstd_seq'),
"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)
);
CREATE TABLE developers_projects (
developer_id integer NOT NULL,
project_id integer NOT NULL,
joined_on date,
access_level integer default 1
);
CREATE TABLE developers (
id serial,
name character varying(100),
salary integer DEFAULT 70000,
created_at timestamp,
updated_at timestamp,
PRIMARY KEY (id)
);
SELECT setval('developers_id_seq', 100);
CREATE TABLE projects (
id serial,
name character varying(100),
type varchar(255),
PRIMARY KEY (id)
);
SELECT setval('projects_id_seq', 100);
CREATE TABLE topics (
id serial,
title character varying(255),
author_name character varying(255),
author_email_address character varying(255),
written_on timestamp without time zone,
bonus_time time,
last_read date,
content text,
approved boolean default true,
replies_count integer default 0,
parent_id integer,
"type" character varying(50),
PRIMARY KEY (id)
);
SELECT setval('topics_id_seq', 100);
CREATE TABLE customers (
id serial,
name character varying,
balance integer default 0,
address_street character varying,
address_city character varying,
address_country character varying,
gps_location character varying,
PRIMARY KEY (id)
);
SELECT setval('customers_id_seq', 100);
CREATE TABLE orders (
id serial,
name character varying,
billing_customer_id integer,
shipping_customer_id integer,
PRIMARY KEY (id)
);
SELECT setval('orders_id_seq', 100);
CREATE TABLE movies (
movieid serial,
name text,
PRIMARY KEY (movieid)
);
CREATE TABLE subscribers (
nick text NOT NULL,
name text,
PRIMARY KEY (nick)
);
CREATE TABLE booleantests (
id serial,
value boolean,
PRIMARY KEY (id)
);
CREATE TABLE defaults (
id serial,
modified_date date default CURRENT_DATE,
modified_date_function date default now(),
fixed_date date default '2004-01-01',
modified_time timestamp default CURRENT_TIMESTAMP,
modified_time_function timestamp default now(),
fixed_time timestamp default '2004-01-01 00:00:00.000000-00',
char1 char(1) default 'Y',
char2 character varying(50) default 'a varchar field',
char3 text default 'a text field',
positive_integer integer default 1,
negative_integer integer default -1
);
CREATE TABLE auto_id_tests (
auto_id serial,
value integer,
PRIMARY KEY (auto_id)
);
CREATE TABLE entrants (
id serial,
name text,
course_id integer
);
CREATE TABLE colnametests (
id serial,
"references" integer NOT NULL
);
CREATE TABLE mixins (
id serial,
parent_id integer,
type character varying,
pos integer,
lft integer,
rgt integer,
root_id integer,
created_at timestamp,
updated_at timestamp,
PRIMARY KEY (id)
);
CREATE TABLE people (
id serial,
first_name text,
lock_version integer default 0,
PRIMARY KEY (id)
);
CREATE TABLE readers (
id serial,
post_id integer NOT NULL,
person_id integer NOT NULL,
primary key (id)
);
CREATE TABLE binaries (
id serial ,
data bytea,
PRIMARY KEY (id)
);
CREATE TABLE computers (
id serial,
developer integer NOT NULL,
"extendedWarranty" integer NOT NULL
);
CREATE TABLE posts (
id serial,
author_id integer,
title varchar(255),
type varchar(255),
body text
);
CREATE TABLE comments (
id serial,
post_id integer,
type varchar(255),
body text
);
CREATE TABLE authors (
id serial,
name varchar(255) default NULL
);
CREATE TABLE tasks (
id serial,
starting timestamp,
ending timestamp,
PRIMARY KEY (id)
);
CREATE TABLE categories (
id serial,
name varchar(255),
type varchar(255)
);
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
);
CREATE TABLE fk_test_has_fk (
id INTEGER NOT NULL PRIMARY KEY,
fk_id INTEGER NOT NULL REFERENCES fk_test_has_fk(id)
);
CREATE TABLE geometrics (
id serial primary key,
a_point point,
-- a_line line, (the line type is currently not implemented in postgresql)
a_line_segment lseg,
a_box box,
a_path path,
a_polygon polygon,
a_circle circle
);
CREATE TABLE keyboards (
key_number serial primary key,
"name" character varying(50)
);
--Altered lock_version column name.
CREATE TABLE legacy_things (
id serial primary key,
tps_report_number integer,
version integer default 0
);

View file

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

View file

@ -0,0 +1,5 @@
CREATE TABLE courses (
id serial,
name text
);

View file

@ -0,0 +1,32 @@
ActiveRecord::Schema.define do
create_table :taggings, :force => true do |t|
t.column :tag_id, :integer
t.column :super_tag_id, :integer
t.column :taggable_type, :string
t.column :taggable_id, :integer
end
create_table :tags, :force => true do |t|
t.column :name, :string
t.column :taggings_count, :integer, :default => 0
end
create_table :categorizations, :force => true do |t|
t.column :category_id, :integer
t.column :post_id, :integer
t.column :author_id, :integer
end
add_column :posts, :taggings_count, :integer, :default => 0
add_column :authors, :author_address_id, :integer
create_table :author_addresses, :force => true do |t|
t.column :author_address_id, :integer
end
create_table :author_favorites, :force => true do |t|
t.column :author_id, :integer
t.column :favorite_author_id, :integer
end
end

View file

@ -0,0 +1,30 @@
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 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 computers;
DROP TABLE tasks;
DROP TABLE posts;
DROP TABLE comments;
DROP TABLE authors;
DROP TABLE categories;
DROP TABLE categories_posts;
DROP TABLE fk_test_has_fk;
DROP TABLE fk_test_has_pk;
DROP TABLE keyboards;
DROP TABLE legacy_things;

View file

@ -0,0 +1,201 @@
CREATE TABLE 'accounts' (
'id' INTEGER PRIMARY KEY NOT NULL,
'firm_id' INTEGER DEFAULT NULL,
'credit_limit' INTEGER DEFAULT NULL
);
CREATE TABLE 'funny_jokes' (
'id' INTEGER PRIMARY KEY NOT NULL,
'name' TEXT DEFAULT NULL
);
CREATE TABLE 'companies' (
'id' INTEGER PRIMARY KEY NOT NULL,
'type' VARCHAR(255) DEFAULT NULL,
'ruby_type' VARCHAR(255) DEFAULT NULL,
'firm_id' INTEGER DEFAULT NULL,
'name' TEXT DEFAULT NULL,
'client_of' INTEGER DEFAULT NULL,
'rating' INTEGER DEFAULT 1
);
CREATE TABLE 'topics' (
'id' INTEGER PRIMARY KEY NOT NULL,
'title' VARCHAR(255) DEFAULT NULL,
'author_name' VARCHAR(255) DEFAULT NULL,
'author_email_address' VARCHAR(255) DEFAULT NULL,
'written_on' DATETIME DEFAULT NULL,
'bonus_time' TIME DEFAULT NULL,
'last_read' DATE DEFAULT NULL,
'content' TEXT,
'approved' boolean DEFAULT 't',
'replies_count' INTEGER DEFAULT 0,
'parent_id' INTEGER DEFAULT NULL,
'type' VARCHAR(255) DEFAULT NULL
);
CREATE TABLE 'developers' (
'id' INTEGER PRIMARY KEY NOT NULL,
'name' TEXT DEFAULT NULL,
'salary' INTEGER DEFAULT 70000,
'created_at' DATETIME DEFAULT NULL,
'updated_at' DATETIME DEFAULT NULL
);
CREATE TABLE 'projects' (
'id' INTEGER PRIMARY KEY NOT NULL,
'name' TEXT DEFAULT NULL,
'type' VARCHAR(255) DEFAULT NULL
);
CREATE TABLE 'developers_projects' (
'developer_id' INTEGER NOT NULL,
'project_id' INTEGER NOT NULL,
'joined_on' DATE DEFAULT NULL,
'access_level' INTEGER DEFAULT 1
);
CREATE TABLE 'orders' (
'id' INTEGER PRIMARY KEY NOT NULL,
'name' VARCHAR(255) DEFAULT NULL,
'billing_customer_id' INTEGER DEFAULT NULL,
'shipping_customer_id' INTEGER DEFAULT NULL
);
CREATE TABLE 'customers' (
'id' INTEGER PRIMARY KEY NOT NULL,
'name' VARCHAR(255) DEFAULT NULL,
'balance' INTEGER DEFAULT 0,
'address_street' TEXT DEFAULT NULL,
'address_city' TEXT DEFAULT NULL,
'address_country' TEXT DEFAULT NULL,
'gps_location' TEXT DEFAULT NULL
);
CREATE TABLE 'movies' (
'movieid' INTEGER PRIMARY KEY NOT NULL,
'name' VARCHAR(255) DEFAULT NULL
);
CREATE TABLE subscribers (
'nick' VARCHAR(255) PRIMARY KEY NOT NULL,
'name' VARCHAR(255) DEFAULT NULL
);
CREATE TABLE 'booleantests' (
'id' INTEGER PRIMARY KEY NOT NULL,
'value' INTEGER DEFAULT NULL
);
CREATE TABLE 'auto_id_tests' (
'auto_id' INTEGER PRIMARY KEY NOT NULL,
'value' INTEGER DEFAULT NULL
);
CREATE TABLE 'entrants' (
'id' INTEGER NOT NULL PRIMARY KEY,
'name' VARCHAR(255) NOT NULL,
'course_id' INTEGER NOT NULL
);
CREATE TABLE 'colnametests' (
'id' INTEGER NOT NULL PRIMARY KEY,
'references' INTEGER NOT NULL
);
CREATE TABLE 'mixins' (
'id' INTEGER NOT NULL PRIMARY KEY,
'parent_id' INTEGER DEFAULT NULL,
'type' VARCHAR(40) DEFAULT NULL,
'pos' INTEGER DEFAULT NULL,
'lft' INTEGER DEFAULT NULL,
'rgt' INTEGER DEFAULT NULL,
'root_id' INTEGER DEFAULT NULL,
'created_at' DATETIME DEFAULT NULL,
'updated_at' DATETIME DEFAULT NULL
);
CREATE TABLE 'people' (
'id' INTEGER NOT NULL PRIMARY KEY,
'first_name' VARCHAR(40) DEFAULT NULL,
'lock_version' INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE 'readers' (
'id' INTEGER NOT NULL PRIMARY KEY,
'post_id' INTEGER NOT NULL,
'person_id' INTEGER NOT NULL
);
CREATE TABLE 'binaries' (
'id' INTEGER NOT NULL PRIMARY KEY,
'data' BLOB DEFAULT NULL
);
CREATE TABLE 'computers' (
'id' INTEGER NOT NULL PRIMARY KEY,
'developer' INTEGER NOT NULL,
'extendedWarranty' INTEGER NOT NULL
);
CREATE TABLE 'posts' (
'id' INTEGER NOT NULL PRIMARY KEY,
'author_id' INTEGER,
'title' VARCHAR(255) NOT NULL,
'type' VARCHAR(255) NOT NULL,
'body' TEXT NOT NULL
);
CREATE TABLE 'comments' (
'id' INTEGER NOT NULL PRIMARY KEY,
'post_id' INTEGER NOT NULL,
'type' VARCHAR(255) NOT NULL,
'body' TEXT NOT NULL
);
CREATE TABLE 'authors' (
'id' INTEGER NOT NULL PRIMARY KEY,
'name' VARCHAR(255) NOT NULL
);
CREATE TABLE 'tasks' (
'id' INTEGER NOT NULL PRIMARY KEY,
'starting' DATETIME DEFAULT NULL,
'ending' DATETIME DEFAULT NULL
);
CREATE TABLE 'categories' (
'id' INTEGER NOT NULL PRIMARY KEY,
'name' VARCHAR(255) NOT NULL,
'type' VARCHAR(255) DEFAULT NULL
);
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
);
CREATE TABLE 'fk_test_has_fk' (
'id' INTEGER NOT NULL PRIMARY KEY,
'fk_id' INTEGER NOT NULL,
FOREIGN KEY ('fk_id') REFERENCES 'fk_test_has_pk'('id')
);
CREATE TABLE 'keyboards' (
'key_number' INTEGER PRIMARY KEY NOT NULL,
'name' VARCHAR(255) DEFAULT NULL
);
--Altered lock_version column name.
CREATE TABLE 'legacy_things' (
'id' INTEGER NOT NULL PRIMARY KEY,
'tps_report_number' INTEGER DEFAULT NULL,
'version' INTEGER NOT NULL DEFAULT 0
)

View file

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

View file

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

View file

@ -0,0 +1,30 @@
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 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 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 legacy_things;

View file

@ -0,0 +1,203 @@
CREATE TABLE accounts (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
firm_id int default NULL,
credit_limit int default NULL
);
CREATE TABLE funny_jokes (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(50) default NULL
);
CREATE TABLE companies (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
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
);
CREATE TABLE topics (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
title varchar(255) default NULL,
author_name varchar(255) default NULL,
author_email_address varchar(255) default NULL,
written_on datetime default NULL,
bonus_time datetime default NULL,
last_read datetime default NULL,
content varchar(255) default NULL,
approved bit default 1,
replies_count int default 0,
parent_id int default NULL,
type varchar(50) default NULL
);
CREATE TABLE developers (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(100) default NULL,
salary int default 70000,
created_at datetime default NULL,
updated_at datetime default NULL
);
CREATE TABLE projects (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(100) default NULL,
type varchar(255) default NULL
);
CREATE TABLE developers_projects (
developer_id int NOT NULL,
project_id int NOT NULL,
joined_on datetime default NULL,
access_level int default 1
);
CREATE TABLE orders (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(100) default NULL,
billing_customer_id int default NULL,
shipping_customer_id int default NULL
);
CREATE TABLE customers (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
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
);
CREATE TABLE movies (
movieid int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(100) default NULL
);
CREATE TABLE subscribers (
nick varchar(100) NOT NULL PRIMARY KEY,
name varchar(100) default NULL
);
CREATE TABLE booleantests (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
value bit default NULL
);
CREATE TABLE auto_id_tests (
auto_id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
value int default NULL
);
CREATE TABLE entrants (
id int NOT NULL PRIMARY KEY,
name varchar(255) NOT NULL,
course_id int NOT NULL
);
CREATE TABLE colnametests (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[references] int NOT NULL
);
CREATE TABLE mixins (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
parent_id int default NULL,
pos int default NULL,
created_at datetime default NULL,
updated_at datetime default NULL,
lft int default NULL,
rgt int default NULL,
root_id int default NULL,
type varchar(40) default NULL
);
CREATE TABLE people (
id int NOT NULL IDENTITY(1, 1),
first_name varchar(40) NULL,
lock_version int default 0,
PRIMARY KEY (id)
);
CREATE TABLE readers (
id int NOT NULL IDENTITY(1, 1),
post_id int NOT NULL,
person_id int NOT NULL,
primary key (id)
);
CREATE TABLE binaries (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
data image NULL
);
CREATE TABLE computers (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
developer int NOT NULL,
extendedWarranty int NOT NULL
);
CREATE TABLE posts (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
author_id int default NULL,
title varchar(255) default NULL,
type varchar(255) default NULL,
body varchar(4096) default NULL
);
CREATE TABLE comments (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
post_id int default NULL,
type varchar(255) default NULL,
body varchar(4096) default NULL
);
CREATE TABLE authors (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(255) default NULL
);
CREATE TABLE tasks (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
starting datetime default NULL,
ending datetime default NULL
);
CREATE TABLE categories (
id int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(255),
type varchar(255) default NULL
);
CREATE TABLE categories_posts (
category_id int NOT NULL,
post_id int NOT NULL
);
CREATE TABLE fk_test_has_pk (
id INTEGER NOT NULL PRIMARY KEY
);
CREATE TABLE fk_test_has_fk (
id INTEGER NOT NULL PRIMARY KEY,
fk_id INTEGER NOT NULL,
FOREIGN KEY (fk_id) REFERENCES fk_test_has_pk(id)
);
CREATE TABLE keyboards (
key_number int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
name varchar(50) default NULL
);
--This table has an altered lock_version column name.
CREATE TABLE legacy_things (
id int NOT NULL IDENTITY(1, 1),
tps_report_number int default NULL,
version int default 0,
PRIMARY KEY (id)
);

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