1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
|
# frozen_string_literal: true
require "cases/helper"
require "models/book"
require "models/club"
require "models/company"
require "models/contract"
require "models/edge"
require "models/organization"
require "models/possession"
require "models/author"
require "models/topic"
require "models/reply"
require "models/numeric_data"
require "models/need_quoting"
require "models/minivan"
require "models/speedometer"
require "models/ship_part"
require "models/treasure"
require "models/developer"
require "models/post"
require "models/comment"
require "models/rating"
require "models/too_long_table_name"
require "support/stubs/strong_parameters"
require "support/async_helper"
require "models/cpk"
class CalculationsTest < ActiveRecord::TestCase
include AsyncHelper
fixtures :companies, :accounts, :authors, :author_addresses, :topics, :speedometers, :minivans, :books, :posts, :comments, :cpk_books
def test_should_sum_field
assert_equal 318, Account.sum(:credit_limit)
assert_async_equal 318, Account.async_sum(:credit_limit)
end
def test_should_sum_arel_attribute
assert_equal 318, Account.sum(Account.arel_table[:credit_limit])
assert_async_equal 318, Account.async_sum(Account.arel_table[:credit_limit])
end
def test_should_average_field
assert_equal 53.0, Account.average(:credit_limit)
assert_async_equal 53.0, Account.async_average(:credit_limit)
end
def test_should_average_arel_attribute
assert_equal 53.0, Account.average(Account.arel_table[:credit_limit])
assert_async_equal 53.0, Account.async_average(Account.arel_table[:credit_limit])
end
def test_should_resolve_aliased_attributes
assert_equal 318, Account.sum(:available_credit)
end
def test_should_return_decimal_average_of_integer_field
value = Account.average(:id)
assert_equal 3.5, value
assert_instance_of BigDecimal, value
end
def test_should_return_integer_average_if_db_returns_such
value = Book.average(:status)
assert_equal 1.0, value
assert_instance_of BigDecimal, value
end
def test_should_return_float_average_if_db_returns_such
NumericData.create!(temperature: 37.5)
value = NumericData.average(:temperature)
assert_equal 37.5, value
assert_instance_of Float, value
if current_adapter?(:PostgreSQLAdapter, :SQLite3Adapter)
NumericData.create!(temperature: "Infinity")
value = NumericData.average(:temperature)
assert_equal Float::INFINITY, value
assert_instance_of Float, value
end
end
def test_should_return_decimal_average_if_db_returns_such
NumericData.create!([{ bank_balance: 37.50 }, { bank_balance: 37.45 }])
value = NumericData.average(:bank_balance)
assert_equal 37.475, value
assert_instance_of BigDecimal, value
end
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
assert_async_equal 60, Account.async_maximum(:credit_limit)
end
def test_should_get_maximum_of_arel_attribute
assert_equal 60, Account.maximum(Account.arel_table[:credit_limit])
assert_async_equal 60, Account.async_maximum(Account.arel_table[:credit_limit])
end
def test_should_get_maximum_of_field_with_include
relation = Account.where("companies.name != 'Summit'").references(:companies).includes(:firm)
assert_equal 55, relation.maximum(:credit_limit)
assert_async_equal 55, relation.async_maximum(:credit_limit)
end
def test_should_get_maximum_of_arel_attribute_with_include
assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(Account.arel_table[:credit_limit])
end
def test_should_get_minimum_of_field
assert_equal 50, Account.minimum(:credit_limit)
assert_async_equal 50, Account.async_minimum(:credit_limit)
end
def test_should_get_minimum_of_arel_attribute
assert_equal 50, Account.minimum(Account.arel_table[:credit_limit])
assert_async_equal 50, Account.async_minimum(Account.arel_table[:credit_limit])
end
def test_should_group_by_field
c = Account.group(:firm_id).sum(:credit_limit)
[1, 6, 2].each do |firm_id|
assert_includes c.keys, firm_id, "Group #{c.inspect} does not contain firm_id #{firm_id}"
end
assert_async_equal c, Account.group(:firm_id).async_sum(:credit_limit)
end
def test_should_group_by_arel_attribute
c = Account.group(Account.arel_table[:firm_id]).sum(:credit_limit)
[1, 6, 2].each do |firm_id|
assert_includes c.keys, firm_id, "Group #{c.inspect} does not contain firm_id #{firm_id}"
end
end
def test_should_group_by_multiple_fields
c = Account.group("firm_id", :credit_limit).count(:all)
[ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert_includes c.keys, firm_and_limit }
end
def test_should_group_by_multiple_fields_when_table_name_is_too_long
2.times do
TooLongTableName.create!(
toooooooo_long_a_id: 1,
toooooooo_long_b_id: 2
)
end
res = TooLongTableName.group(:toooooooo_long_a_id, :toooooooo_long_b_id).count
assert_equal({ [1, 2] => 2 }, res)
end
def test_should_group_by_multiple_fields_having_functions
c = Topic.group(:author_name, "COALESCE(type, title)").count(:all)
assert_equal 1, c[["Carl", "The Third Topic of the day"]]
assert_equal 1, c[["Mary", "Reply"]]
assert_equal 1, c[["David", "The First Topic"]]
assert_equal 1, c[["Carl", "Reply"]]
end
def test_should_group_by_summed_field
expected = { nil => 50, 1 => 50, 2 => 60, 6 => 105, 9 => 53 }
assert_equal expected, Account.group(:firm_id).sum(:credit_limit)
end
def test_group_by_multiple_same_field
accounts = Account.group(:firm_id)
expected = {
nil => 50,
1 => 50,
2 => 60,
6 => 105,
9 => 53
}
assert_equal expected, accounts.sum(:credit_limit)
assert_equal expected, accounts.merge!(accounts).uniq!(:group).sum(:credit_limit)
expected = {
nil => 50,
1 => 50,
2 => 60,
6 => 55,
9 => 53
}
assert_equal expected, accounts.merge!(accounts).maximum(:credit_limit)
expected = {
nil => 50,
1 => 50,
2 => 60,
6 => 50,
9 => 53
}
assert_equal expected, accounts.merge!(accounts).minimum(:credit_limit)
end
def test_should_generate_valid_sql_with_joins_and_group
assert_nothing_raised do
AuditLog.joins(:developer).group(:id).count
end
end
def test_should_calculate_against_given_relation
developer = Developer.create!(name: "developer")
developer.audit_logs.create!(message: "first log")
developer.audit_logs.create!(message: "second log")
c = developer.audit_logs.joins(:developer).group(:id).count
assert_equal developer.audit_logs.count, c.size
developer.audit_logs.each do |log|
assert_equal 1, c[log.id]
end
end
def test_should_not_use_alias_for_grouped_field
assert_queries_match(/GROUP BY #{Regexp.escape(Account.lease_connection.quote_table_name("accounts.firm_id"))}/i) do
c = Account.group(:firm_id).order("accounts_firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
end
end
def test_should_order_by_grouped_field
c = Account.group(:firm_id).order("firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
c = Account.group(:firm_id).order("sum_credit_limit desc, firm_id").sum(:credit_limit)
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").limit(2).sum(:credit_limit)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
c = Account.where("firm_id IS NOT NULL").group(:firm_id).order("firm_id").
limit(2).offset(1).sum(:credit_limit)
assert_equal [2, 6], c.keys.compact
end
def test_limit_should_apply_before_count
accounts = Account.order(:id).limit(4)
assert_equal 3, accounts.count(:firm_id)
assert_equal 3, accounts.select(:firm_id).count
end
def test_limit_should_apply_before_count_arel_attribute
accounts = Account.order(:id).limit(4)
firm_id_attribute = Account.arel_table[:firm_id]
assert_equal 3, accounts.count(firm_id_attribute)
assert_equal 3, accounts.select(firm_id_attribute).count
end
def test_count_should_shortcut_with_limit_zero
accounts = Account.limit(0)
assert_no_queries { assert_equal 0, accounts.count }
end
def test_limit_is_kept
queries = capture_sql { Account.limit(1).count }
assert_equal 1, queries.length
assert_match(/LIMIT/, queries.first)
end
def test_offset_is_kept
queries = capture_sql { Account.offset(1).count }
assert_equal 1, queries.length
assert_match(/OFFSET/, queries.first)
end
def test_limit_with_offset_is_kept
queries = capture_sql { Account.limit(1).offset(1).count }
assert_equal 1, queries.length
assert_match(/LIMIT/, queries.first)
assert_match(/OFFSET/, queries.first)
end
def test_no_limit_no_offset
queries = capture_sql { Account.count }
assert_equal 1, queries.length
assert_no_match(/LIMIT/, queries.first)
assert_no_match(/OFFSET/, queries.first)
end
def test_count_on_invalid_columns_raises
e = assert_raises(ActiveRecord::StatementInvalid) {
Account.select("credit_limit, firm_name").count
}
assert_match %r{accounts}i, e.sql
assert_match "credit_limit, firm_name", e.sql
end
def test_apply_distinct_in_count
queries = capture_sql do
Account.distinct.count
Account.group(:firm_id).distinct.count
end
queries.each do |query|
assert_match %r{\ASELECT(?! DISTINCT) COUNT\(DISTINCT\b}, query
end
end
def test_count_with_eager_loading_and_custom_order
posts = Post.includes(:comments).order("comments.id")
assert_queries_count(1) { assert_equal 11, posts.count }
assert_queries_count(1) { assert_equal 11, posts.count(:all) }
end
def test_count_with_eager_loading_and_custom_select_and_order
posts = Post.includes(:comments).order("comments.id").select(:type)
assert_queries_count(1) { assert_equal 11, posts.count }
assert_queries_count(1) { assert_equal 11, posts.count(:all) }
end
def test_count_with_eager_loading_and_custom_order_and_distinct
posts = Post.includes(:comments).order("comments.id").distinct
assert_queries_count(1) { assert_equal 11, posts.count }
assert_queries_count(1) { assert_equal 11, posts.count(:all) }
end
def test_distinct_count_all_with_custom_select_and_order
accounts = Account.distinct.select("credit_limit % 10").order(Arel.sql("credit_limit % 10"))
assert_queries_count(1) { assert_equal 3, accounts.count(:all) }
assert_queries_count(1) { assert_equal 3, accounts.load.size }
end
def test_distinct_count_with_order_and_limit
assert_equal 4, Account.distinct.order(:firm_id).limit(4).count
end
def test_distinct_count_with_order_and_offset
assert_equal 4, Account.distinct.order(:firm_id).offset(2).count
end
def test_distinct_count_with_order_and_limit_and_offset
assert_equal 4, Account.distinct.order(:firm_id).limit(4).offset(2).count
end
def test_distinct_joins_count_with_order_and_limit
assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).limit(3).count
end
def test_distinct_joins_count_with_order_and_offset
assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).offset(2).count
end
def test_distinct_joins_count_with_order_and_limit_and_offset
assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).limit(3).offset(2).count
end
def test_distinct_joins_count_with_group_by
expected = { nil => 4, 1 => 1, 2 => 1, 4 => 1, 5 => 1, 7 => 1 }
assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.count(:author_id)
assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.select(:author_id).count
assert_equal expected, Post.left_joins(:comments).group(:post_id).count("DISTINCT posts.author_id")
assert_equal expected, Post.left_joins(:comments).group(:post_id).select("DISTINCT posts.author_id").count
expected = { nil => 6, 1 => 1, 2 => 1, 4 => 1, 5 => 1, 7 => 1 }
assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.count(:all)
assert_equal expected, Post.left_joins(:comments).group(:post_id).distinct.select(:author_id).count(:all)
end
def test_distinct_count_with_group_by_and_order_and_limit
assert_equal({ 6 => 2 }, Account.group(:firm_id).distinct.order("1 DESC").limit(1).count)
end
def test_count_for_a_composite_primary_key_model
book = cpk_books(:cpk_great_author_first_book)
assert_equal(1, Cpk::Book.where(author_id: book.author_id, id: book.id).count)
end
def test_group_by_count_for_a_composite_primary_key_model
book = cpk_books(:cpk_great_author_first_book)
expected = { book.author_id => Cpk::Book.where(author_id: book.author_id).count }
assert_equal(expected, Cpk::Book.where(author_id: book.author_id).group(:author_id).count)
end
def test_count_for_a_composite_primary_key_model_with_includes_and_references
assert_equal Cpk::Book.count, Cpk::Book.includes(:chapters).references(:chapters).count
end
def test_should_group_by_summed_field_having_condition
c = Account.group(:firm_id).having("sum(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_having_condition_from_select
skip unless current_adapter?(:Mysql2Adapter, :TrilogyAdapter, :SQLite3Adapter)
c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("min_credit_limit > 50").sum(:credit_limit)
assert_nil c[1]
assert_equal 60, c[2]
assert_equal 53, c[9]
end
def test_should_group_by_summed_association
c = Account.group(:firm).sum(:credit_limit)
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.where("firm_id = 6").sum(:credit_limit)
end
def test_should_return_zero_if_sum_conditions_return_nothing
assert_equal 0, Account.where("1 = 2").sum(:credit_limit)
assert_equal 0, companies(:rails_core).companies.where("1 = 2").sum(:id)
end
def test_sum_should_return_valid_values_for_decimals
NumericData.create(bank_balance: 19.83)
assert_equal 19.83, NumericData.sum(:bank_balance)
end
def test_should_return_type_casted_values_with_group_and_expression
assert_equal 0.5, Account.group(:firm_name).sum("0.01 * credit_limit")["37signals"]
end
def test_should_group_by_summed_field_with_conditions
c = Account.where("firm_id > 1").group(:firm_id).sum(:credit_limit)
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
relation = Account.where("firm_id > 1").group(:firm_id).having("sum(credit_limit) > 60")
c = relation.sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_nil c[2]
assert_async_equal c, relation.async_sum(:credit_limit)
end
def test_should_group_by_fields_with_table_alias
c = Account.group("accounts.firm_id").sum(:credit_limit)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_grouped_with_longer_field
field = "a" * Account.lease_connection.max_identifier_length
Account.update_all("#{field} = credit_limit")
c = Account.group(:firm_id).sum(field)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_with_invalid_field
assert_equal 6, Account.calculate(:count, "*")
assert_equal 6, Account.calculate(:count, :all)
end
def test_should_calculate_grouped_with_invalid_field
c = Account.group("accounts.firm_id").count(:all)
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.group(:firm).count(:all)
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_group_by_association_with_non_numeric_foreign_key
Speedometer.create! id: "ABC"
Minivan.create! id: "OMG", speedometer_id: "ABC"
c = Minivan.group(:speedometer).count(:all)
first_key = c.keys.first
assert_equal Speedometer, first_key.class
assert_equal 1, c[first_key]
end
def test_should_calculate_grouped_association_with_foreign_key_option
Account.belongs_to :another_firm, class_name: "Firm", foreign_key: "firm_id"
c = Account.group(:another_firm).count(:all)
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.group("UPPER(#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c["DEPENDENTFIRM"]
assert_equal 5, c["CLIENT"]
assert_equal 3, c["FIRM"]
end
def test_should_calculate_grouped_by_function_with_table_alias
c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c["DEPENDENTFIRM"]
assert_equal 5, c["CLIENT"]
assert_equal 3, c["FIRM"]
end
def test_should_not_overshadow_enumerable_sum
some_companies = companies(:rails_core).companies.order(:id)
assert_equal 6, [1, 2, 3].sum(&:abs)
assert_equal 15, some_companies.sum(&:id)
assert_equal 25, some_companies.sum(10, &:id)
assert_raises(TypeError) do
some_companies.sum(&:name)
end
assert_equal "companies: LeetsoftJadedpixel", some_companies.sum("companies: ", &:name)
end
def test_should_sum_scoped_field
assert_equal 15, companies(:rails_core).companies.sum(:id)
end
def test_should_sum_scoped_field_with_from
assert_equal Club.count, Organization.clubs.count
end
def test_should_sum_scoped_field_with_conditions
assert_equal 8, companies(:rails_core).companies.where("id > 7").sum(:id)
end
def test_should_group_by_scoped_field
c = companies(:rails_core).companies.group(:name).sum(:id)
assert_equal 7, c["Leetsoft"]
assert_equal 8, c["Jadedpixel"]
end
def test_should_group_by_summed_field_through_association_and_having
c = companies(:rails_core).companies.group(:name).having("sum(id) > 7").sum(:id)
assert_nil c["Leetsoft"]
assert_equal 8, c["Jadedpixel"]
end
def test_should_count_selected_field_with_include
assert_equal 6, Account.includes(:firm).distinct.count
assert_equal 4, Account.includes(:firm).distinct.select(:credit_limit).count
assert_equal 4, Account.includes(:firm).distinct.count("DISTINCT credit_limit")
assert_equal 4, Account.includes(:firm).distinct.count("DISTINCT(credit_limit)")
end
def test_should_not_perform_joined_include_by_default
assert_equal Account.count, Account.includes(:firm).count
queries = capture_sql { Account.includes(:firm).count }
assert_no_match(/join/i, queries.last)
end
def test_should_perform_joined_include_when_referencing_included_tables
joined_count = Account.includes(:firm).where(companies: { name: "37signals" }).count
assert_equal 1, joined_count
end
def test_should_count_scoped_select
Account.update_all("credit_limit = NULL")
assert_equal 0, Account.select("credit_limit").count
end
def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = NULL")
Account.last.update_columns("credit_limit" => 49)
Account.first.update_columns("credit_limit" => 51)
assert_equal 1, Account.select("credit_limit").where("credit_limit >= 50").count
end
def test_should_count_manual_select_with_include
assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count
end
def test_should_count_manual_select_with_count_all
assert_equal 5, Account.select("DISTINCT accounts.firm_id").count(:all)
end
def test_should_count_with_manual_distinct_select_and_distinct
assert_equal 4, Account.select("DISTINCT accounts.firm_id").distinct(true).count
end
def test_should_count_manual_select_with_group_with_count_all
expected = { nil => 1, 1 => 1, 2 => 1, 6 => 2, 9 => 1 }
actual = Account.select("DISTINCT accounts.firm_id").group("accounts.firm_id").count(:all)
assert_equal expected, actual
end
def test_should_count_manual_with_count_all
assert_equal 6, Account.count(:all)
end
def test_count_selected_arel_attribute
assert_equal 5, Account.select(Account.arel_table[:firm_id]).count
assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count
end
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
def test_count_with_arel_attribute
assert_equal 5, Account.count(Account.arel_table[:firm_id])
end
def test_count_with_arel_star
assert_equal 6, Account.count(Arel.star)
end
def test_count_with_distinct
assert_equal 4, Account.select(:credit_limit).distinct.count
end
def test_count_with_aliased_attribute
assert_equal 6, Account.count(:available_credit)
end
def test_count_with_column_and_options_parameter
assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
end
def test_should_count_field_in_joined_table
assert_equal 5, Account.joins(:firm).count("companies.id")
assert_equal 4, Account.joins(:firm).distinct.count("companies.id")
end
def test_count_arel_attribute_in_joined_table_with
assert_equal 5, Account.joins(:firm).count(Company.arel_table[:id])
assert_equal 4, Account.joins(:firm).distinct.count(Company.arel_table[:id])
end
def test_count_selected_arel_attribute_in_joined_table
assert_equal 5, Account.joins(:firm).select(Company.arel_table[:id]).count
assert_equal 4, Account.joins(:firm).distinct.select(Company.arel_table[:id]).count
end
def test_should_count_field_in_joined_table_with_group_by
c = Account.group("accounts.firm_id").joins(:firm).count("companies.id")
[1, 6, 2, 9].each { |firm_id| assert_includes c.keys, firm_id }
end
def test_should_count_field_in_joined_table_with_group_by_when_tables_share_column_names
assert Company.columns_hash.key?("status")
assert Account.columns_hash.key?("status")
counts = Company.joins(:account).group("accounts.status").count
assert_equal({ "active" => 2, "trial" => 2, "suspended" => 1 }, counts)
end
def test_should_count_field_of_root_table_with_conflicting_group_by_column
expected = { 1 => 2, 2 => 1, 4 => 5, 5 => 3, 7 => 1 }
assert_equal expected, Post.joins(:comments).group(:post_id).count
assert_equal expected, Post.joins(:comments).group("comments.post_id").count
assert_equal expected, Post.joins(:comments).group(:post_id).select("DISTINCT posts.author_id").count(:all)
end
def test_count_with_no_parameters_isnt_deprecated
assert_not_deprecated(ActiveRecord.deprecator) { Account.count }
end
def test_count_with_too_many_parameters_raises
assert_raise(ArgumentError) { Account.count(1, 2, 3) }
end
def test_count_with_order
assert_equal 6, Account.order(:credit_limit).count
end
def test_count_with_reverse_order
assert_equal 6, Account.order(:credit_limit).reverse_order.count
end
def test_count_with_where_and_order
assert_equal 1, Account.where(firm_name: "37signals").count
assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).count
assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).reverse_order.count
end
def test_count_with_block
assert_equal 4, Account.count { |account| account.credit_limit.modulo(10).zero? }
end
def test_should_sum_expression
assert_equal 636, Account.sum("2 * credit_limit")
end
def test_sum_expression_returns_zero_when_no_records_to_sum
assert_equal 0, Account.where("1 = 2").sum("2 * credit_limit")
end
def test_count_with_from_option
assert_equal Company.count(:all), Company.from("companies").count(:all)
assert_equal Account.where("credit_limit = 50").count(:all),
Account.from("accounts").where("credit_limit = 50").count(:all)
assert_equal Company.where(type: "Firm").count(:type),
Company.where(type: "Firm").from("companies").count(:type)
end
def test_sum_with_from_option
assert_equal Account.sum(:credit_limit), Account.from("accounts").sum(:credit_limit)
assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
Account.where("credit_limit > 50").from("accounts").sum(:credit_limit)
end
def test_average_with_from_option
assert_equal Account.average(:credit_limit), Account.from("accounts").average(:credit_limit)
assert_equal Account.where("credit_limit > 50").average(:credit_limit),
Account.where("credit_limit > 50").from("accounts").average(:credit_limit)
end
def test_minimum_with_from_option
assert_equal Account.minimum(:credit_limit), Account.from("accounts").minimum(:credit_limit)
assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
Account.where("credit_limit > 50").from("accounts").minimum(:credit_limit)
end
def test_maximum_with_from_option
assert_equal Account.maximum(:credit_limit), Account.from("accounts").maximum(:credit_limit)
assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
Account.where("credit_limit > 50").from("accounts").maximum(:credit_limit)
end
def test_no_queries_for_empty_relation_on_count
assert_queries_count(0) do
assert_equal 0, Post.where(id: []).count
end
end
def test_no_queries_for_empty_relation_on_sum
assert_queries_count(0) do
assert_equal 0, Post.where(id: []).sum(:tags_count)
end
end
def test_no_queries_for_empty_relation_on_average
assert_queries_count(0) do
assert_nil Post.where(id: []).average(:tags_count)
end
end
def test_no_queries_for_empty_relation_on_minimum
assert_queries_count(0) do
assert_nil Account.where(id: []).minimum(:id)
end
end
def test_no_queries_for_empty_relation_on_maximum
assert_queries_count(0) do
assert_nil Account.where(id: []).maximum(:id)
end
end
def test_maximum_with_not_auto_table_name_prefix_if_column_included
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
end
def test_minimum_with_not_auto_table_name_prefix_if_column_included
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
end
def test_sum_with_not_auto_table_name_prefix_if_column_included
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).sum(:developer_id)
end
def test_from_option_with_specified_index
edges = Edge.from("edges /*! USE INDEX(unique_edge_index) */")
assert_equal Edge.count(:all), edges.count(:all)
assert_equal Edge.where("sink_id < 5").count(:all), edges.where("sink_id < 5").count(:all)
end
def test_from_option_with_table_different_than_class
assert_equal Account.count(:all), Company.from("accounts").count(:all)
end
def test_distinct_is_honored_when_used_with_count_operation_after_group
# Count the number of authors for approved topics
approved_topics_count = Topic.group(:approved).count(:author_name)[true]
assert_equal 4, approved_topics_count
# Count the number of distinct authors for approved Topics
distinct_authors_for_approved_count = Topic.group(:approved).distinct.count(:author_name)[true]
assert_equal 3, distinct_authors_for_approved_count
end
def test_pluck
assert_equal [1, 2, 3, 4, 5], Topic.order(:id).pluck(:id)
assert_async_equal [1, 2, 3, 4, 5], Topic.order(:id).async_pluck(:id)
end
def test_async_pluck_on_loaded_relation
relation = Topic.order(:id).load
assert_async_equal relation.pluck(:id), relation.async_pluck(:id)
end
def test_async_pluck_none_relation
assert_async_equal [], Topic.none.async_pluck(:id)
end
def test_pluck_with_empty_in
assert_queries_count(0) do
assert_equal [], Topic.where(id: []).pluck(:id)
end
assert_async_equal [], Topic.where(id: []).async_pluck(:id)
end
def test_pluck_without_column_names
assert_equal [[1, "Firm", 1, nil, "37signals", nil, 1, nil, "", "active"]], Company.order(:id).limit(1).pluck
end
def test_pluck_type_cast
topic = topics(:first)
relation = Topic.where(id: topic.id)
assert_equal [ topic.approved ], relation.pluck(:approved)
assert_equal [ topic.last_read ], relation.pluck(:last_read)
assert_equal [ topic.written_on ], relation.pluck(:written_on)
assert_equal(
[[topic.written_on, topic.replies_count]],
relation.pluck("min(written_on)", "min(replies_count)")
)
end
def test_pluck_type_cast_with_conflict_column_names
expected = [
[Date.new(2004, 4, 15), "unread"],
[Date.new(2004, 4, 15), "reading"],
[Date.new(2004, 4, 15), "read"],
]
actual = AuthorAddress.joins(author: [:topics, :books]).order(:"books.last_read")
.where("books.last_read": [:unread, :reading, :read])
.pluck(:"topics.last_read", :"books.last_read")
assert_equal expected, actual
end
def test_pluck_type_cast_with_joins_without_table_name_qualified_column
assert_pluck_type_cast_without_table_name_qualified_column(AuthorAddress.joins(author: :books))
end
def test_pluck_type_cast_with_left_joins_without_table_name_qualified_column
assert_pluck_type_cast_without_table_name_qualified_column(AuthorAddress.left_joins(author: :books))
end
def test_pluck_type_cast_with_eager_load_without_table_name_qualified_column
assert_pluck_type_cast_without_table_name_qualified_column(AuthorAddress.eager_load(author: :books))
end
def assert_pluck_type_cast_without_table_name_qualified_column(author_addresses)
expected = [
[nil, "unread"],
["ebook", "reading"],
["paperback", "read"],
]
actual = author_addresses.order(:last_read)
.where("books.last_read": [:unread, :reading, :read])
.pluck(:format, :last_read)
assert_equal expected, actual
end
private :assert_pluck_type_cast_without_table_name_qualified_column
def test_pluck_with_type_cast_does_not_corrupt_the_query_cache
topic = topics(:first)
relation = Topic.where(id: topic.id)
assert_queries_count 1 do
Topic.cache do
kind = relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on).class
relation.pluck(:written_on)
assert_kind_of kind, relation.select(:written_on).load.first.read_attribute_before_type_cast(:written_on)
end
end
end
def test_pluck_and_distinct
assert_equal [50, 53, 55, 60], Account.order(:credit_limit).distinct.pluck(:credit_limit)
end
def test_pluck_in_relation
company = Company.first
contract = company.contracts.create!
assert_equal [contract.id], company.contracts.pluck(:id)
end
def test_pluck_on_aliased_attribute
assert_equal "The First Topic", Topic.order(:id).pluck(:heading).first
end
def test_pluck_with_serialization
t = Topic.create!(content: { "foo" => "bar" })
assert_equal [{ "foo" => "bar" }], Topic.where(id: t.id).pluck(:content)
end
def test_pluck_with_qualified_column_name
assert_equal [1, 2, 3, 4, 5], Topic.order(:id).pluck("topics.id")
end
def test_pluck_auto_table_name_prefix
c = Company.create!(name: "test", contracts: [Contract.new])
assert_equal [c.id], Company.joins(:contracts).pluck(:id)
end
def test_pluck_if_table_included
c = Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
end
def test_pluck_not_auto_table_name_prefix_if_column_joined
company = Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
metadata = company.contracts.first.metadata
assert_equal [metadata], Company.joins(:contracts).pluck(:metadata)
end
def test_pluck_with_selection_clause
assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT credit_limit")).sort
assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT accounts.credit_limit")).sort
assert_equal [50, 53, 55, 60], Account.pluck(Arel.sql("DISTINCT(credit_limit)")).sort
assert_equal [50 + 53 + 55 + 60], Account.pluck(Arel.sql("SUM(DISTINCT(credit_limit))"))
end
def test_pluck_with_hash_argument
expected = [
[1, "The First Topic"],
[2, "The Second Topic of the day"],
[3, "The Third Topic of the day"]
]
assert_equal expected, Topic.order(:id).limit(3).pluck(:id, topics: [:title])
end
def test_pluck_with_hash_argument_with_multiple_tables
expected = [
[1, 1, "Thank you for the welcome"],
[1, 2, "Thank you again for the welcome"],
[2, 3, "Don't think too hard"]
]
assert_equal expected, Post.joins(:comments).order(posts: { id: :asc }, comments: { id: :asc }).limit(3).pluck(posts: [:id], comments: [:id, :body])
end
def test_pluck_with_hash_argument_containing_non_existent_field
assert_raises(ActiveRecord::StatementInvalid) do
Topic.pluck(topics: [:non_existent])
end
end
def test_ids
assert_equal Company.all.map(&:id).sort, Company.all.ids.sort
end
def test_ids_for_a_composite_primary_key
assert_equal Cpk::Book.all.map(&:id).sort, Cpk::Book.all.ids.sort
end
def test_pluck_for_a_composite_primary_key
assert_equal Cpk::Book.all.pluck([:author_id, :id]).sort, Cpk::Book.all.ids.sort
end
def test_ids_for_a_composite_primary_key_with_scope
book = cpk_books(:cpk_great_author_first_book)
assert_equal [book.id], Cpk::Book.all.where(title: book.title).ids
end
def test_ids_for_a_composite_primary_key_on_loaded_relation
book = cpk_books(:cpk_great_author_first_book)
relation = Cpk::Book.where(title: book.title)
relation.to_a
assert_predicate relation, :loaded?
assert_equal [book.id], relation.ids
end
def test_ids_with_scope
scoped_ids = [1, 2]
assert_equal Company.where(id: scoped_ids).map(&:id).sort, Company.where(id: scoped_ids).ids.sort
end
def test_ids_on_relation
company = Company.first
contract = company.contracts.create!
assert_equal [contract.id], company.contracts.ids
end
def test_ids_on_loaded_relation
loaded_companies = Company.all.load
company_ids = Company.all.map(&:id)
assert_queries_count(0) do
assert_equal company_ids.sort, loaded_companies.ids.sort
end
end
def test_ids_on_loaded_relation_with_scope
scoped_ids = [1, 2]
loaded_companies = Company.where(id: scoped_ids).load
company_ids = Company.where(id: scoped_ids).map(&:id)
assert_queries_count(0) do
assert_equal company_ids.sort, loaded_companies.ids.sort
end
end
def test_ids_async_on_loaded_relation
loaded_companies = Company.all.order(:id).load
assert_async_equal loaded_companies.ids, loaded_companies.async_ids
end
def test_ids_with_contradicting_scope
empty_scope_ids = []
company_ids = Company.where(id: empty_scope_ids).map(&:id)
assert_predicate company_ids, :empty?
assert_queries_count(0) do
assert_equal company_ids, Company.where(id: empty_scope_ids).ids
end
end
def test_ids_with_join
company = Company.first
company.contracts.create!
assert_equal [company.id], Company.joins(:contracts).where("contracts.id" => company.contracts.first).ids
end
def test_ids_with_polymorphic_relation_join
part = ShipPart.create!(name: "has trinket")
part.trinkets.create!
assert_equal [part.id], ShipPart.joins(:trinkets).ids
assert_async_equal [part.id], ShipPart.joins(:trinkets).async_ids
end
def test_ids_with_eager_load
company = Company.first
5.times { company.contracts.create! }
assert_equal Company.all.map(&:id).sort, Company.all.eager_load(:contracts).ids.sort
end
def test_ids_with_preload
company = Company.first
5.times { company.contracts.create! }
assert_equal Company.all.map(&:id).sort, Company.all.preload(:contracts).ids.sort
end
def test_ids_with_includes
company = Company.first
5.times { company.contracts.create! }
assert_equal Company.all.map(&:id).sort, Company.all.includes(:contracts).ids.sort
end
def test_ids_with_includes_and_non_primary_key_order
rating = 1
Company.all.each { |company| company.update!(rating: rating += 1) }
assert_equal Company.all.sort_by(&:rating).map(&:id), Company.includes(:comments).order(:rating).ids
end
def test_ids_with_includes_and_scope
scoped_ids = [1, 2]
company = Company.where(id: scoped_ids).first
5.times { company.contracts.create! }
assert_equal Company.where(id: scoped_ids).map(&:id).sort, Company.includes(:contracts).where(id: scoped_ids).ids.sort
end
def test_ids_with_includes_and_table_scope
company = Company.first
company.contracts.create!
assert_equal [company.id], Company.includes(:contracts).where("contracts.id" => company.contracts.first).ids
end
def test_ids_on_loaded_relation_with_includes_and_table_scope
company = Company.first
company.contracts.create!
loaded_companies = Company.includes(:contracts).where("contracts.id" => company.contracts.first).load
assert_queries_count(0) do
assert_equal [company.id], loaded_companies.ids
end
end
def test_ids_with_includes_limit_and_empty_result
assert_equal [], Topic.includes(:replies).limit(0).ids
assert_equal [], Topic.includes(:replies).limit(1).where("0 = 1").ids
end
def test_ids_with_includes_offset
assert_equal [5], Topic.includes(:replies).order(:id).offset(4).ids
assert_equal [], Topic.includes(:replies).order(:id).offset(5).ids
end
def test_pluck_with_includes_limit_and_empty_result
assert_equal [], Topic.includes(:replies).limit(0).pluck(:id)
assert_equal [], Topic.includes(:replies).limit(1).where("0 = 1").pluck(:id)
end
def test_pluck_with_includes_offset
assert_equal [5], Topic.includes(:replies).order(:id).offset(4).pluck(:id)
assert_equal [], Topic.includes(:replies).order(:id).offset(5).pluck(:id)
end
def test_pluck_with_join
assert_equal [[2, 2], [4, 4]], Reply.includes(:topic).order(:id).pluck(:id, :"topics.id")
end
def test_pluck_with_join_alias
assert_equal [[2, 1], [4, 3]], Reply.includes(:topic).order(:id).pluck(:id, :"topic.id")
end
def test_group_by_with_order_by_virtual_count_attribute
expected = { "SpecialPost" => 1, "StiPost" => 2 }
actual = Post.group(:type).order(:count).limit(2).maximum(:comments_count)
assert_equal expected, actual
end if current_adapter?(:PostgreSQLAdapter)
def test_group_by_with_limit
expected = { "StiPost" => 3, "SpecialPost" => 1 }
actual = Post.includes(:comments).group(:type).order(type: :desc).limit(2).count("comments.id")
assert_equal expected, actual
end
def test_group_by_with_offset
expected = { "SpecialPost" => 1, "Post" => 8 }
actual = Post.includes(:comments).group(:type).order(type: :desc).offset(1).count("comments.id")
assert_equal expected, actual
end
def test_group_by_with_limit_and_offset
expected = { "SpecialPost" => 1 }
actual = Post.includes(:comments).group(:type).order(type: :desc).offset(1).limit(1).count("comments.id")
assert_equal expected, actual
end
def test_group_by_with_quoted_count_and_order_by_alias
quoted_posts_id = Post.lease_connection.quote_table_name("posts.id")
expected = { "SpecialPost" => 1, "StiPost" => 1, "Post" => 9 }
actual = Post.group(:type).order("count_posts_id").count(quoted_posts_id)
assert_equal expected, actual
end
def test_pluck_not_auto_table_name_prefix_if_column_included
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
ids = Company.includes(:contracts).pluck(:developer_id)
assert_equal Company.count, ids.length
assert_equal [7], ids.compact
end
def test_pluck_multiple_columns
assert_equal [
[1, "The First Topic"], [2, "The Second Topic of the day"],
[3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
], Topic.order(:id).pluck(:id, :title)
assert_equal [
[1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
[3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"],
[5, "The Fifth Topic of the day", "Jason"]
], Topic.order(:id).pluck(:id, :title, :author_name)
end
def test_pluck_with_multiple_columns_and_selection_clause
assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
Account.order(:id).pluck("id, credit_limit")
end
def test_pluck_with_line_endings
assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
Account.order(:id).pluck("id, credit_limit\n")
end
def test_pluck_with_multiple_columns_and_includes
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
companies_and_developers = Company.order("companies.id").includes(:contracts).pluck(:name, :developer_id)
assert_equal Company.count, companies_and_developers.length
assert_equal ["37signals", nil], companies_and_developers.first
assert_equal ["test", 7], companies_and_developers.last
end
def test_pluck_with_reserved_words
Possession.create!(where: "Over There")
assert_equal ["Over There"], Possession.pluck(:where)
end
def test_pluck_replaces_select_clause
takes_relation = Topic.select(:approved, :id).order(:id)
assert_equal [1, 2, 3, 4, 5], takes_relation.pluck(:id)
assert_equal [false, true, true, true, true], takes_relation.pluck(:approved)
end
def test_pluck_with_qualified_name_on_loaded
topics = Topic.joins(:replies).order(:id)
assert_not_predicate topics, :loaded?
assert_equal [[1, 2], [3, 4]], topics.pluck("topics.id", "replies.id")
topics.load
assert_predicate topics, :loaded?
assert_equal [[1, 2], [3, 4]], topics.pluck("topics.id", "replies.id")
end
def test_pluck_columns_with_same_name
expected = [["The First Topic", "The Second Topic of the day"], ["The Third Topic of the day", "The Fourth Topic of the day"]]
actual = Topic.joins(:replies).order(:id)
.pluck("topics.title", "replies_topics.title")
assert_equal expected, actual
end
def test_pluck_functions_with_alias
assert_equal [
[1, "The First Topic"], [2, "The Second Topic of the day"],
[3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
], Topic.order(:id).pluck(
Arel.sql("COALESCE(id, 0) id"),
Arel.sql("COALESCE(title, 'untitled') title")
)
end
def test_pluck_functions_without_alias
expected = [
[1, "The First Topic"],
[2, "The Second Topic of the day"],
[3, "The Third Topic of the day"],
[4, "The Fourth Topic of the day"],
[5, "The Fifth Topic of the day"]
]
assert_equal expected, Topic.order(:id).pluck(
Arel.sql("COALESCE(id, 0)"),
Arel.sql("COALESCE(title, 'untitled')")
)
end
def test_calculation_with_polymorphic_relation
part = ShipPart.create!(name: "has trinket")
part.trinkets.create!
assert_equal part.id, ShipPart.joins(:trinkets).sum(:id)
assert_async_equal part.id, ShipPart.joins(:trinkets).async_sum(:id)
end
def test_calculation_with_query_cache
ShipPart.cache do
count = ShipPart.count
assert_async_equal count, ShipPart.async_count
end
ShipPart.cache do
count = ShipPart.async_count
assert_async_equal count.value, ShipPart.async_count
end
end
def test_pluck_joined_with_polymorphic_relation
part = ShipPart.create!(name: "has trinket")
part.trinkets.create!
assert_equal [part.id], ShipPart.joins(:trinkets).pluck(:id)
assert_async_equal [part.id], ShipPart.joins(:trinkets).async_pluck(:id)
end
def test_pluck_loaded_relation
companies = Company.order(:id).limit(3).load
assert_queries_count(0) do
assert_equal ["37signals", "Summit", "Microsoft"], companies.pluck(:name)
end
end
def test_pluck_loaded_relation_multiple_columns
companies = Company.order(:id).limit(3).load
assert_queries_count(0) do
assert_equal [[1, "37signals"], [2, "Summit"], [3, "Microsoft"]], companies.pluck(:id, :name)
end
end
def test_pluck_loaded_relation_sql_fragment
companies = Company.order(:name).limit(3).load
assert_queries_count(1) do
assert_equal ["37signals", "Apex", "Ex Nihilo"], companies.pluck(Arel.sql("DISTINCT name"))
end
end
def test_pluck_loaded_relation_aliased_attribute
companies = Company.order(:id).limit(3).load
assert_queries_count(0) do
assert_equal ["37signals", "Summit", "Microsoft"], companies.pluck(:new_name)
end
end
def test_pick_one
assert_equal "The First Topic", Topic.order(:id).pick(:heading)
assert_no_queries do
assert_nil Topic.none.pick(:heading)
assert_nil Topic.where(id: 9999999999999999999).pick(:heading)
end
assert_async_equal "The First Topic", Topic.order(:id).async_pick(:heading)
end
def test_pick_two
assert_equal ["David", "david@loudthinking.com"], Topic.order(:id).pick(:author_name, :author_email_address)
assert_no_queries do
assert_nil Topic.none.pick(:author_name, :author_email_address)
assert_nil Topic.where(id: 9999999999999999999).pick(:author_name, :author_email_address)
end
assert_async_equal ["David", "david@loudthinking.com"], Topic.order(:id).async_pick(:author_name, :author_email_address)
end
def test_pick_delegate_to_all
cool_first = minivans(:cool_first)
assert_equal cool_first.color, Minivan.pick(:color)
end
def test_pick_loaded_relation
companies = Company.order(:id).limit(3).load
assert_no_queries do
assert_equal "37signals", companies.pick(:name)
end
end
def test_pick_loaded_relation_multiple_columns
companies = Company.order(:id).limit(3).load
assert_no_queries do
assert_equal [1, "37signals"], companies.pick(:id, :name)
end
end
def test_pick_loaded_relation_sql_fragment
companies = Company.order(:name).limit(3).load
assert_queries_count 1 do
assert_equal "37signals", companies.pick(Arel.sql("DISTINCT name"))
end
end
def test_pick_loaded_relation_aliased_attribute
companies = Company.order(:id).limit(3).load
assert_no_queries do
assert_equal "37signals", companies.pick(:new_name)
end
end
def test_grouped_calculation_with_polymorphic_relation
part = ShipPart.create!(name: "has trinket")
part.trinkets.create!
assert_equal({ "has trinket" => part.id }, ShipPart.joins(:trinkets).group("ship_parts.name").sum(:id))
end
def test_calculation_grouped_by_association_doesnt_error_when_no_records_have_association
Client.update_all(client_of: nil)
assert_equal({ nil => Client.count }, Client.group(:firm).count)
end
def test_should_reference_correct_aliases_while_joining_tables_of_has_many_through_association
assert_nothing_raised do
developer = Developer.create!(name: "developer")
developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count
end
end
def test_sum_uses_enumerable_version_when_block_is_given
block_called = false
relation = Client.all.load
assert_no_queries do
assert_equal 0, relation.sum { block_called = true; 0 }
end
assert block_called
end
def test_having_with_strong_parameters
params = ProtectedParams.new(credit_limit: "50")
assert_raises(ActiveModel::ForbiddenAttributesError) do
Account.group(:id).having(params)
end
result = Account.group(:id).having(params.permit!)
assert_equal 50, result[0].credit_limit
assert_equal 50, result[1].credit_limit
assert_equal 50, result[2].credit_limit
end
def test_count_takes_attribute_type_precedence_over_database_type
assert_called(
Account.lease_connection, :select_all,
returns: ActiveRecord::Result.new(["count"], [["10"]])
) do
result = Account.count
assert_equal 10, result
assert_instance_of Integer, result
end
end
def test_sum_takes_attribute_type_precedence_over_database_type
assert_called(
Account.lease_connection, :select_all,
returns: ActiveRecord::Result.new(["sum"], [[10.to_d]])
) do
result = Account.sum(:credit_limit)
assert_equal 10, result
assert_instance_of Integer, result
end
end
def test_group_by_attribute_with_custom_type
assert_equal({ "proposed" => 2, "published" => 2 }, Book.group(:status).count)
end
def test_aggregate_attribute_on_enum_type
assert_equal 4, Book.sum(:status)
assert_equal 1, Book.sum(:difficulty)
assert_equal 0, Book.minimum(:difficulty)
assert_equal 1, Book.maximum(:difficulty)
assert_equal({ "proposed" => 0, "published" => 4 }, Book.group(:status).sum(:status))
assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).sum(:difficulty))
assert_equal({ "proposed" => 0, "published" => 0 }, Book.group(:status).minimum(:difficulty))
assert_equal({ "proposed" => 0, "published" => 1 }, Book.group(:status).maximum(:difficulty))
end
def test_minimum_and_maximum_on_non_numeric_type
assert_equal Date.new(2004, 4, 15), Topic.minimum(:last_read)
assert_equal Date.new(2004, 4, 15), Topic.maximum(:last_read)
assert_equal({ false => Date.new(2004, 4, 15), true => nil }, Topic.group(:approved).minimum(:last_read))
assert_equal({ false => Date.new(2004, 4, 15), true => nil }, Topic.group(:approved).maximum(:last_read))
end
def test_minimum_and_maximum_on_time_attributes
assert_minimum_and_maximum_on_time_attributes(Time)
end
def test_minimum_and_maximum_on_tz_aware_attributes
with_timezone_config aware_attributes: true, zone: "Pacific Time (US & Canada)" do
Topic.reset_column_information
assert_minimum_and_maximum_on_time_attributes(ActiveSupport::TimeWithZone)
end
ensure
Topic.reset_column_information
end
def assert_minimum_and_maximum_on_time_attributes(time_class)
skip unless supports_datetime_with_precision? # Remove once MySQL 5.5 support is dropped.
actual = Topic.minimum(:written_on)
assert_equal Time.utc(2003, 7, 16, 14, 28, 11, 223300), actual
assert_instance_of time_class, actual
actual = Topic.maximum(:written_on)
assert_equal Time.utc(2013, 7, 13, 11, 11, 0, 9900), actual
assert_instance_of time_class, actual
expected = {
false => Time.utc(2003, 7, 16, 14, 28, 11, 223300),
true => Time.utc(2004, 7, 15, 14, 28, 0, 9900),
}
actual = Topic.group(:approved).minimum(:written_on)
assert_equal expected, actual
assert_instance_of time_class, actual[true]
assert_instance_of time_class, actual[true]
expected = {
false => Time.utc(2003, 7, 16, 14, 28, 11, 223300),
true => Time.utc(2013, 7, 13, 11, 11, 0, 9900),
}
actual = Topic.group(:approved).maximum(:written_on)
assert_equal expected, actual
assert_instance_of time_class, actual[true]
assert_instance_of time_class, actual[true]
assert_minimum_and_maximum_on_time_attributes_joins_with_column(time_class, :"topics.written_on")
assert_minimum_and_maximum_on_time_attributes_joins_with_column(time_class, :written_on)
end
private :assert_minimum_and_maximum_on_time_attributes
def assert_minimum_and_maximum_on_time_attributes_joins_with_column(time_class, column)
actual = Author.joins(:topics).maximum(column)
assert_equal Time.utc(2004, 7, 15, 14, 28, 0, 9900), actual
assert_instance_of time_class, actual
actual = Author.joins(:topics).minimum(column)
assert_equal Time.utc(2003, 7, 16, 14, 28, 11, 223300), actual
assert_instance_of time_class, actual
expected = {
1 => Time.utc(2003, 7, 16, 14, 28, 11, 223300),
2 => Time.utc(2004, 7, 15, 14, 28, 0, 9900),
}
actual = Author.joins(:topics).group(:id).maximum(column)
assert_equal expected, actual
assert_instance_of time_class, actual[1]
assert_instance_of time_class, actual[2]
actual = Author.joins(:topics).group(:id).minimum(column)
assert_equal expected, actual
assert_instance_of time_class, actual[1]
assert_instance_of time_class, actual[2]
end
private :assert_minimum_and_maximum_on_time_attributes_joins_with_column
def test_select_avg_with_group_by_as_virtual_attribute_with_sql
rails_core = companies(:rails_core)
sql = <<~SQL
SELECT firm_id, AVG(credit_limit) AS avg_credit_limit
FROM accounts
WHERE firm_id = ?
GROUP BY firm_id
LIMIT 1
SQL
account = Account.find_by_sql([sql, rails_core]).first
# id was not selected, so it should be nil
# (cannot select id because it wasn't used in the GROUP BY clause)
assert_nil account.id
# firm_id was explicitly selected, so it should be present
assert_equal(rails_core, account.firm)
# avg_credit_limit should be present as a virtual attribute
assert_equal(52.5, account.avg_credit_limit)
end
def test_select_avg_with_group_by_as_virtual_attribute_with_ar
rails_core = companies(:rails_core)
account = Account
.select(:firm_id, "AVG(credit_limit) AS avg_credit_limit")
.where(firm: rails_core)
.group(:firm_id)
.take!
# id was not selected, so it should be nil
# (cannot select id because it wasn't used in the GROUP BY clause)
assert_nil account.id
# firm_id was explicitly selected, so it should be present
assert_equal(rails_core, account.firm)
# avg_credit_limit should be present as a virtual attribute
assert_equal(52.5, account.avg_credit_limit)
end
def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_sql
rails_core = companies(:rails_core)
sql = <<~SQL
SELECT companies.*, AVG(accounts.credit_limit) AS avg_credit_limit
FROM companies
INNER JOIN accounts ON companies.id = accounts.firm_id
WHERE companies.id = ?
GROUP BY companies.id
LIMIT 1
SQL
firm = DependentFirm.find_by_sql([sql, rails_core]).first
# all the DependentFirm attributes should be present
assert_equal rails_core, firm
assert_equal rails_core.name, firm.name
# avg_credit_limit should be present as a virtual attribute
assert_equal(52.5, firm.avg_credit_limit)
end
def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_ar
rails_core = companies(:rails_core)
firm = DependentFirm
.select("companies.*", "AVG(accounts.credit_limit) AS avg_credit_limit")
.where(id: rails_core)
.joins(:account)
.group(:id)
.take!
# all the DependentFirm attributes should be present
assert_equal rails_core, firm
assert_equal rails_core.name, firm.name
# avg_credit_limit should be present as a virtual attribute
assert_equal(52.5, firm.avg_credit_limit)
end
def test_count_with_block_and_column_name_raises_an_error
assert_raises(ArgumentError) do
Account.count(:firm_id) { true }
end
end
test "#skip_query_cache! for #pluck" do
Account.cache do
assert_queries_count(1) do
Account.pluck(:credit_limit)
Account.pluck(:credit_limit)
end
assert_queries_count(2) do
Account.all.skip_query_cache!.pluck(:credit_limit)
Account.all.skip_query_cache!.pluck(:credit_limit)
end
end
end
test "#skip_query_cache! for #ids" do
Account.cache do
assert_queries_count(1) do
Account.ids
Account.ids
end
assert_queries_count(2) do
Account.all.skip_query_cache!.ids
Account.all.skip_query_cache!.ids
end
end
end
test "#skip_query_cache! for a simple calculation" do
Account.cache do
assert_queries_count(1) do
Account.calculate(:sum, :credit_limit)
Account.calculate(:sum, :credit_limit)
end
assert_queries_count(2) do
Account.all.skip_query_cache!.calculate(:sum, :credit_limit)
Account.all.skip_query_cache!.calculate(:sum, :credit_limit)
end
end
end
test "#skip_query_cache! for a grouped calculation" do
Account.cache do
assert_queries_count(1) do
Account.group(:firm_id).calculate(:sum, :credit_limit)
Account.group(:firm_id).calculate(:sum, :credit_limit)
end
assert_queries_count(2) do
Account.all.skip_query_cache!.group(:firm_id).calculate(:sum, :credit_limit)
Account.all.skip_query_cache!.group(:firm_id).calculate(:sum, :credit_limit)
end
end
end
test "group alias is properly quoted" do
assert_nothing_raised do
NeedQuoting.group(:name).count
end
end
end
|