PageRenderTime 166ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/activerecord/test/cases/calculations_test.rb

http://github.com/rails/rails
Ruby | 1199 lines | 954 code | 230 blank | 15 comment | 8 complexity | cc12e7a923e1d1a36a1eacfb30c35f08 MD5 | raw file
  1. # frozen_string_literal: true
  2. require "cases/helper"
  3. require "models/book"
  4. require "models/club"
  5. require "models/company"
  6. require "models/contract"
  7. require "models/edge"
  8. require "models/organization"
  9. require "models/possession"
  10. require "models/topic"
  11. require "models/reply"
  12. require "models/numeric_data"
  13. require "models/minivan"
  14. require "models/speedometer"
  15. require "models/ship_part"
  16. require "models/treasure"
  17. require "models/developer"
  18. require "models/post"
  19. require "models/comment"
  20. require "models/rating"
  21. require "support/stubs/strong_parameters"
  22. class CalculationsTest < ActiveRecord::TestCase
  23. fixtures :companies, :accounts, :topics, :speedometers, :minivans, :books, :posts, :comments
  24. def test_should_sum_field
  25. assert_equal 318, Account.sum(:credit_limit)
  26. end
  27. def test_should_sum_arel_attribute
  28. assert_equal 318, Account.sum(Account.arel_table[:credit_limit])
  29. end
  30. def test_should_average_field
  31. value = Account.average(:credit_limit)
  32. assert_equal 53.0, value
  33. end
  34. def test_should_average_arel_attribute
  35. value = Account.average(Account.arel_table[:credit_limit])
  36. assert_equal 53.0, value
  37. end
  38. def test_should_resolve_aliased_attributes
  39. assert_equal 318, Account.sum(:available_credit)
  40. end
  41. def test_should_return_decimal_average_of_integer_field
  42. value = Account.average(:id)
  43. assert_equal 3.5, value
  44. end
  45. def test_should_return_integer_average_if_db_returns_such
  46. ShipPart.delete_all
  47. ShipPart.create!(id: 3, name: "foo")
  48. value = ShipPart.average(:id)
  49. assert_equal 3, value
  50. end
  51. def test_should_return_nil_as_average
  52. assert_nil NumericData.average(:bank_balance)
  53. end
  54. def test_should_get_maximum_of_field
  55. assert_equal 60, Account.maximum(:credit_limit)
  56. end
  57. def test_should_get_maximum_of_arel_attribute
  58. assert_equal 60, Account.maximum(Account.arel_table[:credit_limit])
  59. end
  60. def test_should_get_maximum_of_field_with_include
  61. assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit)
  62. end
  63. def test_should_get_maximum_of_arel_attribute_with_include
  64. assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(Account.arel_table[:credit_limit])
  65. end
  66. def test_should_get_minimum_of_field
  67. assert_equal 50, Account.minimum(:credit_limit)
  68. end
  69. def test_should_get_minimum_of_arel_attribute
  70. assert_equal 50, Account.minimum(Account.arel_table[:credit_limit])
  71. end
  72. def test_should_group_by_field
  73. c = Account.group(:firm_id).sum(:credit_limit)
  74. [1, 6, 2].each do |firm_id|
  75. assert_includes c.keys, firm_id, "Group #{c.inspect} does not contain firm_id #{firm_id}"
  76. end
  77. end
  78. def test_should_group_by_arel_attribute
  79. c = Account.group(Account.arel_table[:firm_id]).sum(:credit_limit)
  80. [1, 6, 2].each do |firm_id|
  81. assert_includes c.keys, firm_id, "Group #{c.inspect} does not contain firm_id #{firm_id}"
  82. end
  83. end
  84. def test_should_group_by_multiple_fields
  85. c = Account.group("firm_id", :credit_limit).count(:all)
  86. [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert_includes c.keys, firm_and_limit }
  87. end
  88. def test_should_group_by_multiple_fields_having_functions
  89. c = Topic.group(:author_name, "COALESCE(type, title)").count(:all)
  90. assert_equal 1, c[["Carl", "The Third Topic of the day"]]
  91. assert_equal 1, c[["Mary", "Reply"]]
  92. assert_equal 1, c[["David", "The First Topic"]]
  93. assert_equal 1, c[["Carl", "Reply"]]
  94. end
  95. def test_should_group_by_summed_field
  96. expected = { nil => 50, 1 => 50, 2 => 60, 6 => 105, 9 => 53 }
  97. assert_equal expected, Account.group(:firm_id).sum(:credit_limit)
  98. end
  99. def test_group_by_multiple_same_field
  100. accounts = Account.group(:firm_id)
  101. expected = {
  102. nil => 50,
  103. 1 => 50,
  104. 2 => 60,
  105. 6 => 105,
  106. 9 => 53
  107. }
  108. assert_equal expected, accounts.sum(:credit_limit)
  109. expected = {
  110. [nil, nil] => 50,
  111. [1, 1] => 50,
  112. [2, 2] => 60,
  113. [6, 6] => 55,
  114. [9, 9] => 53
  115. }
  116. assert_equal expected, accounts.merge!(accounts).maximum(:credit_limit)
  117. expected = {
  118. [nil, nil, nil, nil] => 50,
  119. [1, 1, 1, 1] => 50,
  120. [2, 2, 2, 2] => 60,
  121. [6, 6, 6, 6] => 50,
  122. [9, 9, 9, 9] => 53
  123. }
  124. assert_equal expected, accounts.merge!(accounts).minimum(:credit_limit)
  125. end
  126. def test_should_generate_valid_sql_with_joins_and_group
  127. assert_nothing_raised do
  128. AuditLog.joins(:developer).group(:id).count
  129. end
  130. end
  131. def test_should_calculate_against_given_relation
  132. developer = Developer.create!(name: "developer")
  133. developer.audit_logs.create!(message: "first log")
  134. developer.audit_logs.create!(message: "second log")
  135. c = developer.audit_logs.joins(:developer).group(:id).count
  136. assert_equal developer.audit_logs.count, c.size
  137. developer.audit_logs.each do |log|
  138. assert_equal 1, c[log.id]
  139. end
  140. end
  141. def test_should_not_use_alias_for_grouped_field
  142. assert_sql(/GROUP BY #{Regexp.escape(Account.connection.quote_table_name("accounts.firm_id"))}/i) do
  143. c = Account.group(:firm_id).order("accounts_firm_id").sum(:credit_limit)
  144. assert_equal [1, 2, 6, 9], c.keys.compact
  145. end
  146. end
  147. def test_should_order_by_grouped_field
  148. c = Account.group(:firm_id).order("firm_id").sum(:credit_limit)
  149. assert_equal [1, 2, 6, 9], c.keys.compact
  150. end
  151. def test_should_order_by_calculation
  152. c = Account.group(:firm_id).order("sum_credit_limit desc, firm_id").sum(:credit_limit)
  153. assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
  154. assert_equal [6, 2, 9, 1], c.keys.compact
  155. end
  156. def test_should_limit_calculation
  157. c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").limit(2).sum(:credit_limit)
  158. assert_equal [1, 2], c.keys.compact
  159. end
  160. def test_should_limit_calculation_with_offset
  161. c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").
  162. limit(2).offset(1).sum(:credit_limit)
  163. assert_equal [2, 6], c.keys.compact
  164. end
  165. def test_limit_should_apply_before_count
  166. accounts = Account.order(:id).limit(4)
  167. assert_equal 3, accounts.count(:firm_id)
  168. assert_equal 3, accounts.select(:firm_id).count
  169. end
  170. def test_limit_should_apply_before_count_arel_attribute
  171. accounts = Account.order(:id).limit(4)
  172. firm_id_attribute = Account.arel_table[:firm_id]
  173. assert_equal 3, accounts.count(firm_id_attribute)
  174. assert_equal 3, accounts.select(firm_id_attribute).count
  175. end
  176. def test_count_should_shortcut_with_limit_zero
  177. accounts = Account.limit(0)
  178. assert_no_queries { assert_equal 0, accounts.count }
  179. end
  180. def test_limit_is_kept
  181. return if current_adapter?(:OracleAdapter)
  182. queries = capture_sql { Account.limit(1).count }
  183. assert_equal 1, queries.length
  184. assert_match(/LIMIT/, queries.first)
  185. end
  186. def test_offset_is_kept
  187. return if current_adapter?(:OracleAdapter)
  188. queries = capture_sql { Account.offset(1).count }
  189. assert_equal 1, queries.length
  190. assert_match(/OFFSET/, queries.first)
  191. end
  192. def test_limit_with_offset_is_kept
  193. return if current_adapter?(:OracleAdapter)
  194. queries = capture_sql { Account.limit(1).offset(1).count }
  195. assert_equal 1, queries.length
  196. assert_match(/LIMIT/, queries.first)
  197. assert_match(/OFFSET/, queries.first)
  198. end
  199. def test_no_limit_no_offset
  200. queries = capture_sql { Account.count }
  201. assert_equal 1, queries.length
  202. assert_no_match(/LIMIT/, queries.first)
  203. assert_no_match(/OFFSET/, queries.first)
  204. end
  205. def test_count_on_invalid_columns_raises
  206. e = assert_raises(ActiveRecord::StatementInvalid) {
  207. Account.select("credit_limit, firm_name").count
  208. }
  209. assert_match %r{accounts}i, e.sql
  210. assert_match "credit_limit, firm_name", e.sql
  211. end
  212. def test_apply_distinct_in_count
  213. queries = capture_sql do
  214. Account.distinct.count
  215. Account.group(:firm_id).distinct.count
  216. end
  217. queries.each do |query|
  218. assert_match %r{\ASELECT(?! DISTINCT) COUNT\(DISTINCT\b}, query
  219. end
  220. end
  221. def test_count_with_eager_loading_and_custom_order
  222. posts = Post.includes(:comments).order("comments.id")
  223. assert_queries(1) { assert_equal 11, posts.count }
  224. assert_queries(1) { assert_equal 11, posts.count(:all) }
  225. end
  226. def test_count_with_eager_loading_and_custom_select_and_order
  227. posts = Post.includes(:comments).order("comments.id").select(:type)
  228. assert_queries(1) { assert_equal 11, posts.count }
  229. assert_queries(1) { assert_equal 11, posts.count(:all) }
  230. end
  231. def test_count_with_eager_loading_and_custom_order_and_distinct
  232. posts = Post.includes(:comments).order("comments.id").distinct
  233. assert_queries(1) { assert_equal 11, posts.count }
  234. assert_queries(1) { assert_equal 11, posts.count(:all) }
  235. end
  236. def test_distinct_count_all_with_custom_select_and_order
  237. accounts = Account.distinct.select("credit_limit % 10").order(Arel.sql("credit_limit % 10"))
  238. assert_queries(1) { assert_equal 3, accounts.count(:all) }
  239. assert_queries(1) { assert_equal 3, accounts.load.size }
  240. end
  241. def test_distinct_count_with_order_and_limit
  242. assert_equal 4, Account.distinct.order(:firm_id).limit(4).count
  243. end
  244. def test_distinct_count_with_order_and_offset
  245. assert_equal 4, Account.distinct.order(:firm_id).offset(2).count
  246. end
  247. def test_distinct_count_with_order_and_limit_and_offset
  248. assert_equal 4, Account.distinct.order(:firm_id).limit(4).offset(2).count
  249. end
  250. def test_distinct_joins_count_with_order_and_limit
  251. assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).limit(3).count
  252. end
  253. def test_distinct_joins_count_with_order_and_offset
  254. assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).offset(2).count
  255. end
  256. def test_distinct_joins_count_with_order_and_limit_and_offset
  257. assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).limit(3).offset(2).count
  258. end
  259. def test_distinct_joins_count_with_group_by
  260. expected = { nil => 4, 1 => 1, 2 => 1, 4 => 1, 5 => 1, 7 => 1 }
  261. assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.count(:author_id)
  262. assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.select(:author_id).count
  263. assert_equal expected, Post.left_joins(:comments).group(:post_id).count("DISTINCT posts.author_id")
  264. assert_equal expected, Post.left_joins(:comments).group(:post_id).select("DISTINCT posts.author_id").count
  265. expected = { nil => 6, 1 => 1, 2 => 1, 4 => 1, 5 => 1, 7 => 1 }
  266. assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.count(:all)
  267. assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.select(:author_id).count(:all)
  268. end
  269. def test_distinct_count_with_group_by_and_order_and_limit
  270. assert_equal({ 6 => 2 }, Account.group(:firm_id).distinct.order("1 DESC").limit(1).count)
  271. end
  272. def test_should_group_by_summed_field_having_condition
  273. c = Account.group(:firm_id).having("sum(credit_limit) > 50").sum(:credit_limit)
  274. assert_nil c[1]
  275. assert_equal 105, c[6]
  276. assert_equal 60, c[2]
  277. end
  278. def test_should_group_by_summed_field_having_condition_from_select
  279. skip unless current_adapter?(:Mysql2Adapter, :SQLite3Adapter)
  280. c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("min_credit_limit > 50").sum(:credit_limit)
  281. assert_nil c[1]
  282. assert_equal 60, c[2]
  283. assert_equal 53, c[9]
  284. end
  285. def test_should_group_by_summed_association
  286. c = Account.group(:firm).sum(:credit_limit)
  287. assert_equal 50, c[companies(:first_firm)]
  288. assert_equal 105, c[companies(:rails_core)]
  289. assert_equal 60, c[companies(:first_client)]
  290. end
  291. def test_should_sum_field_with_conditions
  292. assert_equal 105, Account.where("firm_id = 6").sum(:credit_limit)
  293. end
  294. def test_should_return_zero_if_sum_conditions_return_nothing
  295. assert_equal 0, Account.where("1 = 2").sum(:credit_limit)
  296. assert_equal 0, companies(:rails_core).companies.where("1 = 2").sum(:id)
  297. end
  298. def test_sum_should_return_valid_values_for_decimals
  299. NumericData.create(bank_balance: 19.83)
  300. assert_equal 19.83, NumericData.sum(:bank_balance)
  301. end
  302. def test_should_return_type_casted_values_with_group_and_expression
  303. assert_equal 0.5, Account.group(:firm_name).sum("0.01 * credit_limit")["37signals"]
  304. end
  305. def test_should_group_by_summed_field_with_conditions
  306. c = Account.where("firm_id > 1").group(:firm_id).sum(:credit_limit)
  307. assert_nil c[1]
  308. assert_equal 105, c[6]
  309. assert_equal 60, c[2]
  310. end
  311. def test_should_group_by_summed_field_with_conditions_and_having
  312. c = Account.where("firm_id > 1").group(:firm_id).
  313. having("sum(credit_limit) > 60").sum(:credit_limit)
  314. assert_nil c[1]
  315. assert_equal 105, c[6]
  316. assert_nil c[2]
  317. end
  318. def test_should_group_by_fields_with_table_alias
  319. c = Account.group("accounts.firm_id").sum(:credit_limit)
  320. assert_equal 50, c[1]
  321. assert_equal 105, c[6]
  322. assert_equal 60, c[2]
  323. end
  324. def test_should_calculate_grouped_with_longer_field
  325. field = "a" * Account.connection.max_identifier_length
  326. Account.update_all("#{field} = credit_limit")
  327. c = Account.group(:firm_id).sum(field)
  328. assert_equal 50, c[1]
  329. assert_equal 105, c[6]
  330. assert_equal 60, c[2]
  331. end
  332. def test_should_calculate_with_invalid_field
  333. assert_equal 6, Account.calculate(:count, "*")
  334. assert_equal 6, Account.calculate(:count, :all)
  335. end
  336. def test_should_calculate_grouped_with_invalid_field
  337. c = Account.group("accounts.firm_id").count(:all)
  338. assert_equal 1, c[1]
  339. assert_equal 2, c[6]
  340. assert_equal 1, c[2]
  341. end
  342. def test_should_calculate_grouped_association_with_invalid_field
  343. c = Account.group(:firm).count(:all)
  344. assert_equal 1, c[companies(:first_firm)]
  345. assert_equal 2, c[companies(:rails_core)]
  346. assert_equal 1, c[companies(:first_client)]
  347. end
  348. def test_should_group_by_association_with_non_numeric_foreign_key
  349. Speedometer.create! id: "ABC"
  350. Minivan.create! id: "OMG", speedometer_id: "ABC"
  351. c = Minivan.group(:speedometer).count(:all)
  352. first_key = c.keys.first
  353. assert_equal Speedometer, first_key.class
  354. assert_equal 1, c[first_key]
  355. end
  356. def test_should_calculate_grouped_association_with_foreign_key_option
  357. Account.belongs_to :another_firm, class_name: "Firm", foreign_key: "firm_id"
  358. c = Account.group(:another_firm).count(:all)
  359. assert_equal 1, c[companies(:first_firm)]
  360. assert_equal 2, c[companies(:rails_core)]
  361. assert_equal 1, c[companies(:first_client)]
  362. end
  363. def test_should_calculate_grouped_by_function
  364. c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
  365. assert_equal 2, c[nil]
  366. assert_equal 1, c["DEPENDENTFIRM"]
  367. assert_equal 5, c["CLIENT"]
  368. assert_equal 2, c["FIRM"]
  369. end
  370. def test_should_calculate_grouped_by_function_with_table_alias
  371. c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
  372. assert_equal 2, c[nil]
  373. assert_equal 1, c["DEPENDENTFIRM"]
  374. assert_equal 5, c["CLIENT"]
  375. assert_equal 2, c["FIRM"]
  376. end
  377. def test_should_not_overshadow_enumerable_sum
  378. assert_equal 6, [1, 2, 3].sum(&:abs)
  379. end
  380. def test_should_sum_scoped_field
  381. assert_equal 15, companies(:rails_core).companies.sum(:id)
  382. end
  383. def test_should_sum_scoped_field_with_from
  384. assert_equal Club.count, Organization.clubs.count
  385. end
  386. def test_should_sum_scoped_field_with_conditions
  387. assert_equal 8, companies(:rails_core).companies.where("id > 7").sum(:id)
  388. end
  389. def test_should_group_by_scoped_field
  390. c = companies(:rails_core).companies.group(:name).sum(:id)
  391. assert_equal 7, c["Leetsoft"]
  392. assert_equal 8, c["Jadedpixel"]
  393. end
  394. def test_should_group_by_summed_field_through_association_and_having
  395. c = companies(:rails_core).companies.group(:name).having("sum(id) > 7").sum(:id)
  396. assert_nil c["Leetsoft"]
  397. assert_equal 8, c["Jadedpixel"]
  398. end
  399. def test_should_count_selected_field_with_include
  400. assert_equal 6, Account.includes(:firm).distinct.count
  401. assert_equal 4, Account.includes(:firm).distinct.select(:credit_limit).count
  402. assert_equal 4, Account.includes(:firm).distinct.count("DISTINCT credit_limit")
  403. assert_equal 4, Account.includes(:firm).distinct.count("DISTINCT(credit_limit)")
  404. end
  405. def test_should_not_perform_joined_include_by_default
  406. assert_equal Account.count, Account.includes(:firm).count
  407. queries = capture_sql { Account.includes(:firm).count }
  408. assert_no_match(/join/i, queries.last)
  409. end
  410. def test_should_perform_joined_include_when_referencing_included_tables
  411. joined_count = Account.includes(:firm).where(companies: { name: "37signals" }).count
  412. assert_equal 1, joined_count
  413. end
  414. def test_should_count_scoped_select
  415. Account.update_all("credit_limit = NULL")
  416. assert_equal 0, Account.select("credit_limit").count
  417. end
  418. def test_should_count_scoped_select_with_options
  419. Account.update_all("credit_limit = NULL")
  420. Account.last.update_columns("credit_limit" => 49)
  421. Account.first.update_columns("credit_limit" => 51)
  422. assert_equal 1, Account.select("credit_limit").where("credit_limit >= 50").count
  423. end
  424. def test_should_count_manual_select_with_include
  425. assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count
  426. end
  427. def test_should_count_manual_select_with_count_all
  428. assert_equal 5, Account.select("DISTINCT accounts.firm_id").count(:all)
  429. end
  430. def test_should_count_with_manual_distinct_select_and_distinct
  431. assert_equal 4, Account.select("DISTINCT accounts.firm_id").distinct(true).count
  432. end
  433. def test_should_count_manual_select_with_group_with_count_all
  434. expected = { nil => 1, 1 => 1, 2 => 1, 6 => 2, 9 => 1 }
  435. actual = Account.select("DISTINCT accounts.firm_id").group("accounts.firm_id").count(:all)
  436. assert_equal expected, actual
  437. end
  438. def test_should_count_manual_with_count_all
  439. assert_equal 6, Account.count(:all)
  440. end
  441. def test_count_selected_arel_attribute
  442. assert_equal 5, Account.select(Account.arel_table[:firm_id]).count
  443. assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count
  444. end
  445. def test_count_with_column_parameter
  446. assert_equal 5, Account.count(:firm_id)
  447. end
  448. def test_count_with_arel_attribute
  449. assert_equal 5, Account.count(Account.arel_table[:firm_id])
  450. end
  451. def test_count_with_arel_star
  452. assert_equal 6, Account.count(Arel.star)
  453. end
  454. def test_count_with_distinct
  455. assert_equal 4, Account.select(:credit_limit).distinct.count
  456. end
  457. def test_count_with_aliased_attribute
  458. assert_equal 6, Account.count(:available_credit)
  459. end
  460. def test_count_with_column_and_options_parameter
  461. assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
  462. end
  463. def test_should_count_field_in_joined_table
  464. assert_equal 5, Account.joins(:firm).count("companies.id")
  465. assert_equal 4, Account.joins(:firm).distinct.count("companies.id")
  466. end
  467. def test_count_arel_attribute_in_joined_table_with
  468. assert_equal 5, Account.joins(:firm).count(Company.arel_table[:id])
  469. assert_equal 4, Account.joins(:firm).distinct.count(Company.arel_table[:id])
  470. end
  471. def test_count_selected_arel_attribute_in_joined_table
  472. assert_equal 5, Account.joins(:firm).select(Company.arel_table[:id]).count
  473. assert_equal 4, Account.joins(:firm).distinct.select(Company.arel_table[:id]).count
  474. end
  475. def test_should_count_field_in_joined_table_with_group_by
  476. c = Account.group("accounts.firm_id").joins(:firm).count("companies.id")
  477. [1, 6, 2, 9].each { |firm_id| assert_includes c.keys, firm_id }
  478. end
  479. def test_should_count_field_of_root_table_with_conflicting_group_by_column
  480. expected = { 1 => 2, 2 => 1, 4 => 5, 5 => 2, 7 => 1 }
  481. assert_equal expected, Post.joins(:comments).group(:post_id).count
  482. assert_equal expected, Post.joins(:comments).group("comments.post_id").count
  483. assert_equal expected, Post.joins(:comments).group(:post_id).select("DISTINCT posts.author_id").count(:all)
  484. end
  485. def test_count_with_no_parameters_isnt_deprecated
  486. assert_not_deprecated { Account.count }
  487. end
  488. def test_count_with_too_many_parameters_raises
  489. assert_raise(ArgumentError) { Account.count(1, 2, 3) }
  490. end
  491. def test_count_with_order
  492. assert_equal 6, Account.order(:credit_limit).count
  493. end
  494. def test_count_with_reverse_order
  495. assert_equal 6, Account.order(:credit_limit).reverse_order.count
  496. end
  497. def test_count_with_where_and_order
  498. assert_equal 1, Account.where(firm_name: "37signals").count
  499. assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).count
  500. assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).reverse_order.count
  501. end
  502. def test_count_with_block
  503. assert_equal 4, Account.count { |account| account.credit_limit.modulo(10).zero? }
  504. end
  505. def test_should_sum_expression
  506. assert_equal 636, Account.sum("2 * credit_limit")
  507. end
  508. def test_sum_expression_returns_zero_when_no_records_to_sum
  509. assert_equal 0, Account.where("1 = 2").sum("2 * credit_limit")
  510. end
  511. def test_count_with_from_option
  512. assert_equal Company.count(:all), Company.from("companies").count(:all)
  513. assert_equal Account.where("credit_limit = 50").count(:all),
  514. Account.from("accounts").where("credit_limit = 50").count(:all)
  515. assert_equal Company.where(type: "Firm").count(:type),
  516. Company.where(type: "Firm").from("companies").count(:type)
  517. end
  518. def test_sum_with_from_option
  519. assert_equal Account.sum(:credit_limit), Account.from("accounts").sum(:credit_limit)
  520. assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
  521. Account.where("credit_limit > 50").from("accounts").sum(:credit_limit)
  522. end
  523. def test_average_with_from_option
  524. assert_equal Account.average(:credit_limit), Account.from("accounts").average(:credit_limit)
  525. assert_equal Account.where("credit_limit > 50").average(:credit_limit),
  526. Account.where("credit_limit > 50").from("accounts").average(:credit_limit)
  527. end
  528. def test_minimum_with_from_option
  529. assert_equal Account.minimum(:credit_limit), Account.from("accounts").minimum(:credit_limit)
  530. assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
  531. Account.where("credit_limit > 50").from("accounts").minimum(:credit_limit)
  532. end
  533. def test_maximum_with_from_option
  534. assert_equal Account.maximum(:credit_limit), Account.from("accounts").maximum(:credit_limit)
  535. assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
  536. Account.where("credit_limit > 50").from("accounts").maximum(:credit_limit)
  537. end
  538. def test_maximum_with_not_auto_table_name_prefix_if_column_included
  539. Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  540. assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
  541. end
  542. def test_minimum_with_not_auto_table_name_prefix_if_column_included
  543. Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  544. assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
  545. end
  546. def test_sum_with_not_auto_table_name_prefix_if_column_included
  547. Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  548. assert_equal 7, Company.includes(:contracts).sum(:developer_id)
  549. end
  550. if current_adapter?(:Mysql2Adapter)
  551. def test_from_option_with_specified_index
  552. assert_equal Edge.count(:all), Edge.from("edges USE INDEX(unique_edge_index)").count(:all)
  553. assert_equal Edge.where("sink_id < 5").count(:all),
  554. Edge.from("edges USE INDEX(unique_edge_index)").where("sink_id < 5").count(:all)
  555. end
  556. end
  557. def test_from_option_with_table_different_than_class
  558. assert_equal Account.count(:all), Company.from("accounts").count(:all)
  559. end
  560. def test_distinct_is_honored_when_used_with_count_operation_after_group
  561. # Count the number of authors for approved topics
  562. approved_topics_count = Topic.group(:approved).count(:author_name)[true]
  563. assert_equal approved_topics_count, 4
  564. # Count the number of distinct authors for approved Topics
  565. distinct_authors_for_approved_count = Topic.group(:approved).distinct.count(:author_name)[true]
  566. assert_equal distinct_authors_for_approved_count, 3
  567. end
  568. def test_pluck
  569. assert_equal [1, 2, 3, 4, 5], Topic.order(:id).pluck(:id)
  570. end
  571. def test_pluck_with_empty_in
  572. Topic.send(:load_schema)
  573. assert_no_queries do
  574. assert_equal [], Topic.where(id: []).pluck(:id)
  575. end
  576. end
  577. def test_pluck_without_column_names
  578. if current_adapter?(:OracleAdapter)
  579. assert_equal [[1, "Firm", 1, nil, "37signals", nil, 1, nil, nil]], Company.order(:id).limit(1).pluck
  580. else
  581. assert_equal [[1, "Firm", 1, nil, "37signals", nil, 1, nil, ""]], Company.order(:id).limit(1).pluck
  582. end
  583. end
  584. def test_pluck_type_cast
  585. topic = topics(:first)
  586. relation = Topic.where(id: topic.id)
  587. assert_equal [ topic.approved ], relation.pluck(:approved)
  588. assert_equal [ topic.last_read ], relation.pluck(:last_read)
  589. assert_equal [ topic.written_on ], relation.pluck(:written_on)
  590. end
  591. def test_pluck_with_type_cast_does_not_corrupt_the_query_cache
  592. topic = topics(:first)
  593. relation = Topic.where(id: topic.id)
  594. assert_queries 1 do
  595. Topic.cache do
  596. kind = relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on).class
  597. relation.pluck(:written_on)
  598. assert_kind_of kind, relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on)
  599. end
  600. end
  601. end
  602. def test_pluck_and_distinct
  603. assert_equal [50, 53, 55, 60], Account.order(:credit_limit).distinct.pluck(:credit_limit)
  604. end
  605. def test_pluck_in_relation
  606. company = Company.first
  607. contract = company.contracts.create!
  608. assert_equal [contract.id], company.contracts.pluck(:id)
  609. end
  610. def test_pluck_on_aliased_attribute
  611. assert_equal "The First Topic", Topic.order(:id).pluck(:heading).first
  612. end
  613. def test_pluck_with_serialization
  614. t = Topic.create!(content: { foo: :bar })
  615. assert_equal [{ foo: :bar }], Topic.where(id: t.id).pluck(:content)
  616. end
  617. def test_pluck_with_qualified_column_name
  618. assert_equal [1, 2, 3, 4, 5], Topic.order(:id).pluck("topics.id")
  619. end
  620. def test_pluck_auto_table_name_prefix
  621. c = Company.create!(name: "test", contracts: [Contract.new])
  622. assert_equal [c.id], Company.joins(:contracts).pluck(:id)
  623. end
  624. def test_pluck_if_table_included
  625. c = Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  626. assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
  627. end
  628. def test_pluck_not_auto_table_name_prefix_if_column_joined
  629. company = Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  630. metadata = company.contracts.first.metadata
  631. assert_equal [metadata], Company.joins(:contracts).pluck(:metadata)
  632. end
  633. def test_pluck_with_selection_clause
  634. assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT credit_limit")).sort
  635. assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT accounts.credit_limit")).sort
  636. assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT(credit_limit)")).sort
  637. assert_equal [50 + 53 + 55 + 60], Account.pluck(Arel.sql("SUM(DISTINCT(credit_limit))"))
  638. end
  639. def test_plucks_with_ids
  640. assert_equal Company.all.map(&:id).sort, Company.ids.sort
  641. end
  642. def test_pluck_with_includes_limit_and_empty_result
  643. assert_equal [], Topic.includes(:replies).limit(0).pluck(:id)
  644. assert_equal [], Topic.includes(:replies).limit(1).where("0 = 1").pluck(:id)
  645. end
  646. def test_pluck_with_includes_offset
  647. assert_equal [5], Topic.includes(:replies).order(:id).offset(4).pluck(:id)
  648. assert_equal [], Topic.includes(:replies).order(:id).offset(5).pluck(:id)
  649. end
  650. def test_pluck_with_join
  651. assert_equal [[2, 2], [4, 4]], Reply.includes(:topic).order(:id).pluck(:id, :"topics.id")
  652. end
  653. def test_group_by_with_order_by_virtual_count_attribute
  654. expected = { "SpecialPost" => 1, "StiPost" => 2 }
  655. actual = Post.group(:type).order(:count).limit(2).maximum(:comments_count)
  656. assert_equal expected, actual
  657. end if current_adapter?(:PostgreSQLAdapter)
  658. def test_group_by_with_limit
  659. expected = { "Post" => 8, "SpecialPost" => 1 }
  660. actual = Post.includes(:comments).group(:type).order(:type).limit(2).count("comments.id")
  661. assert_equal expected, actual
  662. end
  663. def test_group_by_with_offset
  664. expected = { "SpecialPost" => 1, "StiPost" => 2 }
  665. actual = Post.includes(:comments).group(:type).order(:type).offset(1).count("comments.id")
  666. assert_equal expected, actual
  667. end
  668. def test_group_by_with_limit_and_offset
  669. expected = { "SpecialPost" => 1 }
  670. actual = Post.includes(:comments).group(:type).order(:type).offset(1).limit(1).count("comments.id")
  671. assert_equal expected, actual
  672. end
  673. def test_group_by_with_quoted_count_and_order_by_alias
  674. quoted_posts_id = Post.connection.quote_table_name("posts.id")
  675. expected = { "SpecialPost" => 1, "StiPost" => 1, "Post" => 9 }
  676. actual = Post.group(:type).order("count_posts_id").count(quoted_posts_id)
  677. assert_equal expected, actual
  678. end
  679. def test_pluck_not_auto_table_name_prefix_if_column_included
  680. Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  681. ids = Company.includes(:contracts).pluck(:developer_id)
  682. assert_equal Company.count, ids.length
  683. assert_equal [7], ids.compact
  684. end
  685. def test_pluck_multiple_columns
  686. assert_equal [
  687. [1, "The First Topic"], [2, "The Second Topic of the day"],
  688. [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
  689. [5, "The Fifth Topic of the day"]
  690. ], Topic.order(:id).pluck(:id, :title)
  691. assert_equal [
  692. [1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
  693. [3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"],
  694. [5, "The Fifth Topic of the day", "Jason"]
  695. ], Topic.order(:id).pluck(:id, :title, :author_name)
  696. end
  697. def test_pluck_with_multiple_columns_and_selection_clause
  698. assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
  699. Account.order(:id).pluck("id, credit_limit")
  700. end
  701. def test_pluck_with_multiple_columns_and_includes
  702. Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
  703. companies_and_developers = Company.order("companies.id").includes(:contracts).pluck(:name, :developer_id)
  704. assert_equal Company.count, companies_and_developers.length
  705. assert_equal ["37signals", nil], companies_and_developers.first
  706. assert_equal ["test", 7], companies_and_developers.last
  707. end
  708. def test_pluck_with_reserved_words
  709. Possession.create!(where: "Over There")
  710. assert_equal ["Over There"], Possession.pluck(:where)
  711. end
  712. def test_pluck_replaces_select_clause
  713. taks_relation = Topic.select(:approved, :id).order(:id)
  714. assert_equal [1, 2, 3, 4, 5], taks_relation.pluck(:id)
  715. assert_equal [false, true, true, true, true], taks_relation.pluck(:approved)
  716. end
  717. def test_pluck_columns_with_same_name
  718. expected = [["The First Topic", "The Second Topic of the day"], ["The Third Topic of the day", "The Fourth Topic of the day"]]
  719. actual = Topic.joins(:replies).order(:id)
  720. .pluck("topics.title", "replies_topics.title")
  721. assert_equal expected, actual
  722. end
  723. def test_pluck_functions_with_alias
  724. assert_equal [
  725. [1, "The First Topic"], [2, "The Second Topic of the day"],
  726. [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
  727. [5, "The Fifth Topic of the day"]
  728. ], Topic.order(:id).pluck(
  729. Arel.sql("COALESCE(id, 0) id"),
  730. Arel.sql("COALESCE(title, 'untitled') title")
  731. )
  732. end
  733. def test_pluck_functions_without_alias
  734. assert_equal [
  735. [1, "The First Topic"], [2, "The Second Topic of the day"],
  736. [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
  737. [5, "The Fifth Topic of the day"]
  738. ], Topic.order(:id).pluck(
  739. Arel.sql("COALESCE(id, 0)"),
  740. Arel.sql("COALESCE(title, 'untitled')")
  741. )
  742. end
  743. def test_calculation_with_polymorphic_relation
  744. part = ShipPart.create!(name: "has trinket")
  745. part.trinkets.create!
  746. assert_equal part.id, ShipPart.joins(:trinkets).sum(:id)
  747. end
  748. def test_pluck_joined_with_polymorphic_relation
  749. part = ShipPart.create!(name: "has trinket")
  750. part.trinkets.create!
  751. assert_equal [part.id], ShipPart.joins(:trinkets).pluck(:id)
  752. end
  753. def test_pluck_loaded_relation
  754. companies = Company.order(:id).limit(3).load
  755. assert_queries(0) do
  756. assert_equal ["37signals", "Summit", "Microsoft"], companies.pluck(:name)
  757. end
  758. end
  759. def test_pluck_loaded_relation_multiple_columns
  760. companies = Company.order(:id).limit(3).load
  761. assert_queries(0) do
  762. assert_equal [[1, "37signals"], [2, "Summit"], [3, "Microsoft"]], companies.pluck(:id, :name)
  763. end
  764. end
  765. def test_pluck_loaded_relation_sql_fragment
  766. companies = Company.order(:name).limit(3).load
  767. assert_queries(1) do
  768. assert_equal ["37signals", "Apex", "Ex Nihilo"], companies.pluck(Arel.sql("DISTINCT name"))
  769. end
  770. end
  771. def test_pick_one
  772. assert_equal "The First Topic", Topic.order(:id).pick(:heading)
  773. assert_no_queries do
  774. assert_nil Topic.none.pick(:heading)
  775. assert_nil Topic.where(id: 9999999999999999999).pick(:heading)
  776. end
  777. end
  778. def test_pick_two
  779. assert_equal ["David", "david@loudthinking.com"], Topic.order(:id).pick(:author_name, :author_email_address)
  780. assert_no_queries do
  781. assert_nil Topic.none.pick(:author_name, :author_email_address)
  782. assert_nil Topic.where(id: 9999999999999999999).pick(:author_name, :author_email_address)
  783. end
  784. end
  785. def test_pick_delegate_to_all
  786. cool_first = minivans(:cool_first)
  787. assert_equal cool_first.color, Minivan.pick(:color)
  788. end
  789. def test_pick_loaded_relation
  790. companies = Company.order(:id).limit(3).load
  791. assert_no_queries do
  792. assert_equal "37signals", companies.pick(:name)
  793. end
  794. end
  795. def test_pick_loaded_relation_multiple_columns
  796. companies = Company.order(:id).limit(3).load
  797. assert_no_queries do
  798. assert_equal [1, "37signals"], companies.pick(:id, :name)
  799. end
  800. end
  801. def test_pick_loaded_relation_sql_fragment
  802. companies = Company.order(:name).limit(3).load
  803. assert_queries 1 do
  804. assert_equal "37signals", companies.pick(Arel.sql("DISTINCT name"))
  805. end
  806. end
  807. def test_grouped_calculation_with_polymorphic_relation
  808. part = ShipPart.create!(name: "has trinket")
  809. part.trinkets.create!
  810. assert_equal({ "has trinket" => part.id }, ShipPart.joins(:trinkets).group("ship_parts.name").sum(:id))
  811. end
  812. def test_calculation_grouped_by_association_doesnt_error_when_no_records_have_association
  813. Client.update_all(client_of: nil)
  814. assert_equal({ nil => Client.count }, Client.group(:firm).count)
  815. end
  816. def test_should_reference_correct_aliases_while_joining_tables_of_has_many_through_association
  817. assert_nothing_raised do
  818. developer = Developer.create!(name: "developer")
  819. developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count
  820. end
  821. end
  822. def test_sum_uses_enumerable_version_when_block_is_given
  823. block_called = false
  824. relation = Client.all.load
  825. assert_no_queries do
  826. assert_equal 0, relation.sum { block_called = true; 0 }
  827. end
  828. assert block_called
  829. end
  830. def test_having_with_strong_parameters
  831. params = ProtectedParams.new(credit_limit: "50")
  832. assert_raises(ActiveModel::ForbiddenAttributesError) do
  833. Account.group(:id).having(params)
  834. end
  835. result = Account.group(:id).having(params.permit!)
  836. assert_equal 50, result[0].credit_limit
  837. assert_equal 50, result[1].credit_limit
  838. assert_equal 50, result[2].credit_limit
  839. end
  840. def test_group_by_attribute_with_custom_type
  841. assert_equal({ "proposed" => 2, "published" => 2 }, Book.group(:status).count)
  842. end
  843. def test_aggregate_attribute_on_custom_type
  844. assert_equal 4, Book.sum(:status)
  845. assert_equal 1, Book.sum(:difficulty)
  846. assert_equal 0, Book.minimum(:status)
  847. assert_equal 1, Book.maximum(:difficulty)
  848. assert_equal({ "proposed" => 0, "published" => 4 }, Book.group(:status).sum(:status))
  849. assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).sum(:difficulty))
  850. assert_equal({ "proposed" => 0, "published" => 2 }, Book.group(:status).minimum(:status))
  851. assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).maximum(:difficulty))
  852. end
  853. def test_minimum_and_maximum_on_non_numeric_type
  854. assert_equal Date.new(2004, 4, 15), Topic.minimum(:last_read)
  855. assert_equal Date.new(2004, 4, 15), Topic.maximum(:last_read)
  856. assert_equal({ false => Date.new(2004, 4, 15), true => nil }, Topic.group(:approved).minimum(:last_read))
  857. assert_equal({ false => Date.new(2004, 4, 15), true => nil }, Topic.group(:approved).maximum(:last_read))
  858. end
  859. def test_select_avg_with_group_by_as_virtual_attribute_with_sql
  860. rails_core = companies(:rails_core)
  861. sql = <<~SQL
  862. SELECT firm_id, AVG(credit_limit) AS avg_credit_limit
  863. FROM accounts
  864. WHERE firm_id = ?
  865. GROUP BY firm_id
  866. LIMIT 1
  867. SQL
  868. account = Account.find_by_sql([sql, rails_core]).first
  869. # id was not selected, so it should be nil
  870. # (cannot select id because it wasn't used in the GROUP BY clause)
  871. assert_nil account.id
  872. # firm_id was explicitly selected, so it should be present
  873. assert_equal(rails_core, account.firm)
  874. # avg_credit_limit should be present as a virtual attribute
  875. assert_equal(52.5, account.avg_credit_limit)
  876. end
  877. def test_select_avg_with_group_by_as_virtual_attribute_with_ar
  878. rails_core = companies(:rails_core)
  879. account = Account
  880. .select(:firm_id, "AVG(credit_limit) AS avg_credit_limit")
  881. .where(firm: rails_core)
  882. .group(:firm_id)
  883. .take!
  884. # id was not selected, so it should be nil
  885. # (cannot select id because it wasn't used in the GROUP BY clause)
  886. assert_nil account.id
  887. # firm_id was explicitly selected, so it should be present
  888. assert_equal(rails_core, account.firm)
  889. # avg_credit_limit should be present as a virtual attribute
  890. assert_equal(52.5, account.avg_credit_limit)
  891. end
  892. def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_sql
  893. rails_core = companies(:rails_core)
  894. sql = <<~SQL
  895. SELECT companies.*, AVG(accounts.credit_limit) AS avg_credit_limit
  896. FROM companies
  897. INNER JOIN accounts ON companies.id = accounts.firm_id
  898. WHERE companies.id = ?
  899. GROUP BY companies.id
  900. LIMIT 1
  901. SQL
  902. firm = DependentFirm.find_by_sql([sql, rails_core]).first
  903. # all the DependentFirm attributes should be present
  904. assert_equal rails_core, firm
  905. assert_equal rails_core.name, firm.name
  906. # avg_credit_limit should be present as a virtual attribute
  907. assert_equal(52.5, firm.avg_credit_limit)
  908. end
  909. def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_ar
  910. rails_core = companies(:rails_core)
  911. firm = DependentFirm
  912. .select("companies.*", "AVG(accounts.credit_limit) AS avg_credit_limit")
  913. .where(id: rails_core)
  914. .joins(:account)
  915. .group(:id)
  916. .take!
  917. # all the DependentFirm attributes should be present
  918. assert_equal rails_core, firm
  919. assert_equal rails_core.name, firm.name
  920. # avg_credit_limit should be present as a virtual attribute
  921. assert_equal(52.5, firm.avg_credit_limit)
  922. end
  923. def test_count_with_block_and_column_name_raises_an_error
  924. assert_raises(ArgumentError) do
  925. Account.count(:firm_id) { true }
  926. end
  927. end
  928. def test_sum_with_block_and_column_name_raises_an_error
  929. assert_raises(ArgumentError) do
  930. Account.sum(:firm_id) { 1 }
  931. end
  932. end
  933. test "#skip_query_cache! for #pluck" do
  934. Account.cache do
  935. assert_queries(1) do
  936. Account.pluck(:credit_limit)
  937. Account.pluck(:credit_limit)
  938. end
  939. assert_queries(2) do
  940. Account.all.skip_query_cache!.pluck(:credit_limit)
  941. Account.all.skip_query_cache!.pluck(:credit_limit)
  942. end
  943. end
  944. end
  945. test "#skip_query_cache! for a simple calculation" do
  946. Account.cache do
  947. assert_queries(1) do
  948. Account.calculate(:sum, :credit_limit)
  949. Account.calculate(:sum, :credit_limit)
  950. end
  951. assert_queries(2) do
  952. Account.all.skip_query_cache!.calculate(:sum, :credit_limit)
  953. Account.all.skip_query_cache!.calculate(:sum, :credit_limit)
  954. end
  955. end
  956. end
  957. test "#skip_query_cache! for a grouped calculation" do
  958. Account.cache do
  959. assert_queries(1) do
  960. Account.group(:firm_id).calculate(:sum, :credit_limit)
  961. Account.group(:firm_id).calculate(:sum, :credit_limit)
  962. end
  963. assert_queries(2) do
  964. Account.all.skip_query_cache!.group(:firm_id).calculate(:sum, :credit_limit)
  965. Account.all.skip_query_cache!.group(:firm_id).calculate(:sum, :credit_limit)
  966. end
  967. end
  968. end
  969. end