PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/activerecord/test/cases/calculations_test.rb

https://bitbucket.org/glassscribe/rails
Ruby | 549 lines | 437 code | 103 blank | 9 comment | 12 complexity | 91abb4988c0148f28e5da3d22df61710 MD5 | raw file
  1. require "cases/helper"
  2. require 'models/company'
  3. require "models/contract"
  4. require 'models/topic'
  5. require 'models/edge'
  6. require 'models/club'
  7. require 'models/organization'
  8. Company.has_many :accounts
  9. class NumericData < ActiveRecord::Base
  10. self.table_name = 'numeric_data'
  11. end
  12. class CalculationsTest < ActiveRecord::TestCase
  13. fixtures :companies, :accounts, :topics
  14. def test_should_sum_field
  15. assert_equal 318, Account.sum(:credit_limit)
  16. end
  17. def test_should_average_field
  18. value = Account.average(:credit_limit)
  19. assert_equal 53.0, value
  20. end
  21. def test_should_return_decimal_average_of_integer_field
  22. value = Account.average(:id)
  23. assert_equal 3.5, value
  24. end
  25. def test_should_return_integer_average_if_db_returns_such
  26. Account.connection.stubs :select_value => 3
  27. value = Account.average(:id)
  28. assert_equal 3, value
  29. end
  30. def test_should_return_nil_as_average
  31. assert_nil NumericData.average(:bank_balance)
  32. end
  33. def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
  34. assert_equal 0, NumericData.scoped.send(:type_cast_calculated_value, 0, nil, 'avg')
  35. assert_equal 53.0, NumericData.scoped.send(:type_cast_calculated_value, 53, nil, 'avg')
  36. end
  37. def test_should_get_maximum_of_field
  38. assert_equal 60, Account.maximum(:credit_limit)
  39. end
  40. def test_should_get_maximum_of_field_with_include
  41. assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit)
  42. end
  43. def test_should_get_minimum_of_field
  44. assert_equal 50, Account.minimum(:credit_limit)
  45. end
  46. def test_should_group_by_field
  47. c = Account.group(:firm_id).sum(:credit_limit)
  48. [1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
  49. end
  50. def test_should_group_by_multiple_fields
  51. c = Account.group('firm_id', :credit_limit).count(:all)
  52. [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
  53. end
  54. def test_should_group_by_multiple_fields_having_functions
  55. c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
  56. assert_equal 1, c[["Carl", "The Third Topic of the day"]]
  57. assert_equal 1, c[["Mary", "Reply"]]
  58. assert_equal 1, c[["David", "The First Topic"]]
  59. assert_equal 1, c[["Carl", "Reply"]]
  60. end
  61. def test_should_group_by_summed_field
  62. c = Account.group(:firm_id).sum(:credit_limit)
  63. assert_equal 50, c[1]
  64. assert_equal 105, c[6]
  65. assert_equal 60, c[2]
  66. end
  67. def test_should_order_by_grouped_field
  68. c = Account.scoped(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
  69. assert_equal [1, 2, 6, 9], c.keys.compact
  70. end
  71. def test_should_order_by_calculation
  72. c = Account.scoped(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
  73. assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
  74. assert_equal [6, 2, 9, 1], c.keys.compact
  75. end
  76. def test_should_limit_calculation
  77. c = Account.scoped(:where => "firm_id IS NOT NULL",
  78. :group => :firm_id, :order => "firm_id", :limit => 2).sum(:credit_limit)
  79. assert_equal [1, 2], c.keys.compact
  80. end
  81. def test_should_limit_calculation_with_offset
  82. c = Account.scoped(:where => "firm_id IS NOT NULL", :group => :firm_id,
  83. :order => "firm_id", :limit => 2, :offset => 1).sum(:credit_limit)
  84. assert_equal [2, 6], c.keys.compact
  85. end
  86. def test_limit_should_apply_before_count
  87. accounts = Account.limit(3).where('firm_id IS NOT NULL')
  88. assert_equal 3, accounts.count(:firm_id)
  89. assert_equal 3, accounts.select(:firm_id).count
  90. end
  91. def test_count_should_shortcut_with_limit_zero
  92. accounts = Account.limit(0)
  93. assert_no_queries { assert_equal 0, accounts.count }
  94. end
  95. def test_limit_is_kept
  96. return if current_adapter?(:OracleAdapter)
  97. queries = assert_sql { Account.limit(1).count }
  98. assert_equal 1, queries.length
  99. assert_match(/LIMIT/, queries.first)
  100. end
  101. def test_offset_is_kept
  102. return if current_adapter?(:OracleAdapter)
  103. queries = assert_sql { Account.offset(1).count }
  104. assert_equal 1, queries.length
  105. assert_match(/OFFSET/, queries.first)
  106. end
  107. def test_limit_with_offset_is_kept
  108. return if current_adapter?(:OracleAdapter)
  109. queries = assert_sql { Account.limit(1).offset(1).count }
  110. assert_equal 1, queries.length
  111. assert_match(/LIMIT/, queries.first)
  112. assert_match(/OFFSET/, queries.first)
  113. end
  114. def test_no_limit_no_offset
  115. queries = assert_sql { Account.count }
  116. assert_equal 1, queries.length
  117. assert_no_match(/LIMIT/, queries.first)
  118. assert_no_match(/OFFSET/, queries.first)
  119. end
  120. def test_should_group_by_summed_field_having_condition
  121. c = Account.scoped(:group => :firm_id,
  122. :having => 'sum(credit_limit) > 50').sum(:credit_limit)
  123. assert_nil c[1]
  124. assert_equal 105, c[6]
  125. assert_equal 60, c[2]
  126. end
  127. def test_should_group_by_summed_field_having_condition_from_select
  128. c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("MIN(credit_limit) > 50").sum(:credit_limit)
  129. assert_nil c[1]
  130. assert_equal 60, c[2]
  131. assert_equal 53, c[9]
  132. end
  133. def test_should_group_by_summed_association
  134. c = Account.group(:firm).sum(:credit_limit)
  135. assert_equal 50, c[companies(:first_firm)]
  136. assert_equal 105, c[companies(:rails_core)]
  137. assert_equal 60, c[companies(:first_client)]
  138. end
  139. def test_should_sum_field_with_conditions
  140. assert_equal 105, Account.where('firm_id = 6').sum(:credit_limit)
  141. end
  142. def test_should_return_zero_if_sum_conditions_return_nothing
  143. assert_equal 0, Account.where('1 = 2').sum(:credit_limit)
  144. assert_equal 0, companies(:rails_core).companies.where('1 = 2').sum(:id)
  145. end
  146. def test_sum_should_return_valid_values_for_decimals
  147. NumericData.create(:bank_balance => 19.83)
  148. assert_equal 19.83, NumericData.sum(:bank_balance)
  149. end
  150. def test_should_group_by_summed_field_with_conditions
  151. c = Account.scoped(:where => 'firm_id > 1',
  152. :group => :firm_id).sum(:credit_limit)
  153. assert_nil c[1]
  154. assert_equal 105, c[6]
  155. assert_equal 60, c[2]
  156. end
  157. def test_should_group_by_summed_field_with_conditions_and_having
  158. c = Account.scoped(:where => 'firm_id > 1',
  159. :group => :firm_id,
  160. :having => 'sum(credit_limit) > 60').sum(:credit_limit)
  161. assert_nil c[1]
  162. assert_equal 105, c[6]
  163. assert_nil c[2]
  164. end
  165. def test_should_group_by_fields_with_table_alias
  166. c = Account.group('accounts.firm_id').sum(:credit_limit)
  167. assert_equal 50, c[1]
  168. assert_equal 105, c[6]
  169. assert_equal 60, c[2]
  170. end
  171. def test_should_calculate_with_invalid_field
  172. assert_equal 6, Account.calculate(:count, '*')
  173. assert_equal 6, Account.calculate(:count, :all)
  174. end
  175. def test_should_calculate_grouped_with_invalid_field
  176. c = Account.group('accounts.firm_id').count(:all)
  177. assert_equal 1, c[1]
  178. assert_equal 2, c[6]
  179. assert_equal 1, c[2]
  180. end
  181. def test_should_calculate_grouped_association_with_invalid_field
  182. c = Account.group(:firm).count(:all)
  183. assert_equal 1, c[companies(:first_firm)]
  184. assert_equal 2, c[companies(:rails_core)]
  185. assert_equal 1, c[companies(:first_client)]
  186. end
  187. def test_should_group_by_association_with_non_numeric_foreign_key
  188. ActiveRecord::Base.connection.expects(:select_all).returns([{"count_all" => 1, "firm_id" => "ABC"}])
  189. firm = mock()
  190. firm.expects(:id).returns("ABC")
  191. firm.expects(:class).returns(Firm)
  192. Company.expects(:find).with(["ABC"]).returns([firm])
  193. column = mock()
  194. column.expects(:name).at_least_once.returns(:firm_id)
  195. column.expects(:type_cast).with("ABC").returns("ABC")
  196. Account.expects(:columns).at_least_once.returns([column])
  197. c = Account.group(:firm).count(:all)
  198. first_key = c.keys.first
  199. assert_equal Firm, first_key.class
  200. assert_equal 1, c[first_key]
  201. end
  202. def test_should_calculate_grouped_association_with_foreign_key_option
  203. Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
  204. c = Account.group(:another_firm).count(:all)
  205. assert_equal 1, c[companies(:first_firm)]
  206. assert_equal 2, c[companies(:rails_core)]
  207. assert_equal 1, c[companies(:first_client)]
  208. end
  209. def test_should_calculate_grouped_by_function
  210. c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
  211. assert_equal 2, c[nil]
  212. assert_equal 1, c['DEPENDENTFIRM']
  213. assert_equal 4, c['CLIENT']
  214. assert_equal 2, c['FIRM']
  215. end
  216. def test_should_calculate_grouped_by_function_with_table_alias
  217. c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
  218. assert_equal 2, c[nil]
  219. assert_equal 1, c['DEPENDENTFIRM']
  220. assert_equal 4, c['CLIENT']
  221. assert_equal 2, c['FIRM']
  222. end
  223. def test_should_not_overshadow_enumerable_sum
  224. assert_equal 6, [1, 2, 3].sum(&:abs)
  225. end
  226. def test_should_sum_scoped_field
  227. assert_equal 15, companies(:rails_core).companies.sum(:id)
  228. end
  229. def test_should_sum_scoped_field_with_from
  230. assert_equal Club.count, Organization.clubs.count
  231. end
  232. def test_should_sum_scoped_field_with_conditions
  233. assert_equal 8, companies(:rails_core).companies.where('id > 7').sum(:id)
  234. end
  235. def test_should_group_by_scoped_field
  236. c = companies(:rails_core).companies.group(:name).sum(:id)
  237. assert_equal 7, c['Leetsoft']
  238. assert_equal 8, c['Jadedpixel']
  239. end
  240. def test_should_group_by_summed_field_through_association_and_having
  241. c = companies(:rails_core).companies.group(:name).having('sum(id) > 7').sum(:id)
  242. assert_nil c['Leetsoft']
  243. assert_equal 8, c['Jadedpixel']
  244. end
  245. def test_should_count_selected_field_with_include
  246. assert_equal 6, Account.includes(:firm).count(:distinct => true)
  247. assert_equal 4, Account.includes(:firm).select(:credit_limit).count(:distinct => true)
  248. end
  249. def test_should_not_perform_joined_include_by_default
  250. assert_equal Account.count, Account.includes(:firm).count
  251. queries = assert_sql { Account.includes(:firm).count }
  252. assert_no_match(/join/i, queries.last)
  253. end
  254. def test_should_perform_joined_include_when_referencing_included_tables
  255. joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count
  256. assert_equal 1, joined_count
  257. end
  258. def test_should_count_scoped_select
  259. Account.update_all("credit_limit = NULL")
  260. assert_equal 0, Account.scoped(:select => "credit_limit").count
  261. end
  262. def test_should_count_scoped_select_with_options
  263. Account.update_all("credit_limit = NULL")
  264. Account.last.update_column('credit_limit', 49)
  265. Account.first.update_column('credit_limit', 51)
  266. assert_equal 1, Account.scoped(:select => "credit_limit").where('credit_limit >= 50').count
  267. end
  268. def test_should_count_manual_select_with_include
  269. assert_equal 6, Account.scoped(:select => "DISTINCT accounts.id", :includes => :firm).count
  270. end
  271. def test_count_with_column_parameter
  272. assert_equal 5, Account.count(:firm_id)
  273. end
  274. def test_count_with_column_and_options_parameter
  275. assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
  276. end
  277. def test_should_count_field_in_joined_table
  278. assert_equal 5, Account.joins(:firm).count('companies.id')
  279. assert_equal 4, Account.joins(:firm).count('companies.id', :distinct => true)
  280. end
  281. def test_should_count_field_in_joined_table_with_group_by
  282. c = Account.scoped(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
  283. [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
  284. end
  285. def test_count_with_no_parameters_isnt_deprecated
  286. assert_not_deprecated { Account.count }
  287. end
  288. def test_count_with_too_many_parameters_raises
  289. assert_raise(ArgumentError) { Account.count(1, 2, 3) }
  290. end
  291. def test_should_sum_expression
  292. # Oracle adapter returns floating point value 636.0 after SUM
  293. if current_adapter?(:OracleAdapter)
  294. assert_equal 636, Account.sum("2 * credit_limit")
  295. else
  296. assert_equal 636, Account.sum("2 * credit_limit").to_i
  297. end
  298. end
  299. def test_count_with_from_option
  300. assert_equal Company.count(:all), Company.from('companies').count(:all)
  301. assert_equal Account.where("credit_limit = 50").count(:all),
  302. Account.from('accounts').where("credit_limit = 50").count(:all)
  303. assert_equal Company.where(:type => "Firm").count(:type),
  304. Company.where(:type => "Firm").from('companies').count(:type)
  305. end
  306. def test_count_with_block_acts_as_array
  307. accounts = Account.where('id > 0')
  308. assert_equal Account.count, accounts.count { true }
  309. assert_equal 0, accounts.count { false }
  310. assert_equal Account.where('credit_limit > 50').size, accounts.count { |account| account.credit_limit > 50 }
  311. assert_equal Account.count, Account.count { true }
  312. assert_equal 0, Account.count { false }
  313. end
  314. def test_sum_with_block_acts_as_array
  315. accounts = Account.where('id > 0')
  316. assert_equal Account.sum(:credit_limit), accounts.sum { |account| account.credit_limit }
  317. assert_equal Account.sum(:credit_limit) + Account.count, accounts.sum{ |account| account.credit_limit + 1 }
  318. assert_equal 0, accounts.sum { |account| 0 }
  319. end
  320. def test_sum_with_from_option
  321. assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit)
  322. assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
  323. Account.where("credit_limit > 50").from('accounts').sum(:credit_limit)
  324. end
  325. def test_sum_array_compatibility
  326. assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit)
  327. end
  328. def test_average_with_from_option
  329. assert_equal Account.average(:credit_limit), Account.from('accounts').average(:credit_limit)
  330. assert_equal Account.where("credit_limit > 50").average(:credit_limit),
  331. Account.where("credit_limit > 50").from('accounts').average(:credit_limit)
  332. end
  333. def test_minimum_with_from_option
  334. assert_equal Account.minimum(:credit_limit), Account.from('accounts').minimum(:credit_limit)
  335. assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
  336. Account.where("credit_limit > 50").from('accounts').minimum(:credit_limit)
  337. end
  338. def test_maximum_with_from_option
  339. assert_equal Account.maximum(:credit_limit), Account.from('accounts').maximum(:credit_limit)
  340. assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
  341. Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
  342. end
  343. def test_maximum_with_not_auto_table_name_prefix_if_column_included
  344. Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  345. # TODO: Investigate why PG isn't being typecast
  346. if current_adapter?(:PostgreSQLAdapter)
  347. assert_equal "7", Company.includes(:contracts).maximum(:developer_id)
  348. else
  349. assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
  350. end
  351. end
  352. def test_minimum_with_not_auto_table_name_prefix_if_column_included
  353. Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  354. # TODO: Investigate why PG isn't being typecast
  355. if current_adapter?(:PostgreSQLAdapter)
  356. assert_equal "7", Company.includes(:contracts).minimum(:developer_id)
  357. else
  358. assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
  359. end
  360. end
  361. def test_sum_with_not_auto_table_name_prefix_if_column_included
  362. Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  363. # TODO: Investigate why PG isn't being typecast
  364. if current_adapter?(:MysqlAdapter) || current_adapter?(:PostgreSQLAdapter)
  365. assert_equal "7", Company.includes(:contracts).sum(:developer_id)
  366. else
  367. assert_equal 7, Company.includes(:contracts).sum(:developer_id)
  368. end
  369. end
  370. def test_from_option_with_specified_index
  371. if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
  372. assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
  373. assert_equal Edge.where('sink_id < 5').count(:all),
  374. Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
  375. end
  376. end
  377. def test_from_option_with_table_different_than_class
  378. assert_equal Account.count(:all), Company.from('accounts').count(:all)
  379. end
  380. def test_distinct_is_honored_when_used_with_count_operation_after_group
  381. # Count the number of authors for approved topics
  382. approved_topics_count = Topic.group(:approved).count(:author_name)[true]
  383. assert_equal approved_topics_count, 3
  384. # Count the number of distinct authors for approved Topics
  385. distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true]
  386. assert_equal distinct_authors_for_approved_count, 2
  387. end
  388. def test_pluck
  389. assert_equal [1,2,3,4], Topic.order(:id).pluck(:id)
  390. end
  391. def test_pluck_type_cast
  392. topic = topics(:first)
  393. relation = Topic.where(:id => topic.id)
  394. assert_equal [ topic.approved ], relation.pluck(:approved)
  395. assert_equal [ topic.last_read ], relation.pluck(:last_read)
  396. assert_equal [ topic.written_on ], relation.pluck(:written_on)
  397. end
  398. def test_pluck_and_uniq
  399. assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit)
  400. end
  401. def test_pluck_in_relation
  402. company = Company.first
  403. contract = company.contracts.create!
  404. assert_equal [contract.id], company.contracts.pluck(:id)
  405. end
  406. def test_pluck_with_serialization
  407. t = Topic.create!(:content => { :foo => :bar })
  408. assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
  409. end
  410. def test_pluck_with_qualified_column_name
  411. assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id")
  412. end
  413. def test_pluck_auto_table_name_prefix
  414. c = Company.create!(:name => "test", :contracts => [Contract.new])
  415. assert_equal [c.id], Company.joins(:contracts).pluck(:id)
  416. end
  417. def test_pluck_if_table_included
  418. c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  419. assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
  420. end
  421. def test_pluck_not_auto_table_name_prefix_if_column_joined
  422. Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  423. assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
  424. end
  425. def test_pluck_with_selection_clause
  426. assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort
  427. assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT accounts.credit_limit').sort
  428. assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT(credit_limit)').sort
  429. # MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless
  430. # an alias is provided. Without the alias, the column cannot be found
  431. # and properly typecast.
  432. assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
  433. end
  434. def test_pluck_expects_a_single_selection
  435. assert_raise(ArgumentError) { Account.pluck 'id, credit_limit' }
  436. end
  437. def test_plucks_with_ids
  438. assert_equal Company.all.map(&:id).sort, Company.ids.sort
  439. end
  440. def test_pluck_not_auto_table_name_prefix_if_column_included
  441. Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
  442. ids = Company.includes(:contracts).pluck(:developer_id)
  443. assert_equal Company.count, ids.length
  444. assert_equal [7], ids.compact
  445. end
  446. end