-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathcoerced_tests.rb
2853 lines (2386 loc) · 109 KB
/
coerced_tests.rb
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
# frozen_string_literal: true
require "cases/helper_sqlserver"
require "models/author"
require "models/book"
require "models/car"
require "models/citation"
require "models/comment"
require "models/computer"
require "models/customer"
require "models/dashboard"
require "models/developer"
require "models/event"
require "models/non_primary_key"
require "models/post"
require "models/tag"
require "models/task"
require "models/topic"
class UniquenessValidationTest < ActiveRecord::TestCase
# So sp_executesql swallows this exception. Run without prepared to see it.
coerce_tests! :test_validate_uniqueness_with_limit
def test_validate_uniqueness_with_limit_coerced
connection.unprepared_statement do
assert_raise(ActiveRecord::ValueTooLong) do
Event.create(title: "abcdefgh")
end
end
end
# So sp_executesql swallows this exception. Run without prepared to see it.
coerce_tests! :test_validate_uniqueness_with_limit_and_utf8
def test_validate_uniqueness_with_limit_and_utf8_coerced
connection.unprepared_statement do
assert_raise(ActiveRecord::ValueTooLong) do
Event.create(title: "一二三四五六七八")
end
end
end
# Same as original coerced test except that it handles default SQL Server case-insensitive collation.
coerce_tests! :test_validate_uniqueness_by_default_database_collation
def test_validate_uniqueness_by_default_database_collation_coerced
Topic.validates_uniqueness_of(:author_email_address)
topic1 = Topic.new(author_email_address: "[email protected]")
topic2 = Topic.new(author_email_address: "[email protected]")
assert_equal 1, Topic.where(author_email_address: "[email protected]").count
assert_not topic1.valid?
assert_not topic1.save
# Case insensitive collation (SQL_Latin1_General_CP1_CI_AS) by default.
# Should not allow "David" if "david" exists.
assert_not topic2.valid?
assert_not topic2.save
assert_equal 1, Topic.where(author_email_address: "[email protected]").count
assert_equal 1, Topic.where(author_email_address: "[email protected]").count
end
end
class UniquenessValidationWithIndexTest < ActiveRecord::TestCase
# Need to explicitly set the WHERE clause to truthy.
coerce_tests! :test_partial_index
def test_partial_index_coerced
Topic.validates_uniqueness_of(:title)
@connection.add_index(:topics, :title, unique: true, where: "approved=1", name: :topics_index)
t = Topic.create!(title: "abc")
t.author_name = "John"
assert_queries_count(1) do
t.valid?
end
end
end
module ActiveRecord
class AdapterTest < ActiveRecord::TestCase
# Legacy binds are not supported.
coerce_tests! :test_select_all_insert_update_delete_with_casted_binds
# As far as I can tell, SQL Server does not support null bytes in strings.
coerce_tests! :test_update_prepared_statement
# So sp_executesql swallows this exception. Run without prepared to see it.
coerce_tests! :test_value_limit_violations_are_translated_to_specific_exception
def test_value_limit_violations_are_translated_to_specific_exception_coerced
connection.unprepared_statement do
error = assert_raises(ActiveRecord::ValueTooLong) do
Event.create(title: "abcdefgh")
end
assert_not_nil error.cause
end
end
end
end
module ActiveRecord
class AdapterPreventWritesTest < ActiveRecord::TestCase
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_errors_when_an_insert_query_is_called_while_preventing_writes
def test_errors_when_an_insert_query_is_called_while_preventing_writes_coerced
Subscriber.send(:load_schema!)
original_test_errors_when_an_insert_query_is_called_while_preventing_writes
end
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_containing_read_command_is_called_while_preventing_writes
def test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_containing_read_command_is_called_while_preventing_writes_coerced
Subscriber.send(:load_schema!)
original_test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_containing_read_command_is_called_while_preventing_writes
end
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_is_called_while_preventing_writes
def test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_is_called_while_preventing_writes_coerced
Subscriber.send(:load_schema!)
original_test_errors_when_an_insert_query_prefixed_by_a_double_dash_comment_is_called_while_preventing_writes
end
# Invalid character encoding causes `ActiveRecord::StatementInvalid` error similar to Postgres.
coerce_tests! :test_doesnt_error_when_a_select_query_has_encoding_errors
def test_doesnt_error_when_a_select_query_has_encoding_errors_coerced
ActiveRecord::Base.while_preventing_writes do
# TinyTDS fail on encoding errors.
# But at least we can assert it fails in the client and not before when trying to match the query.
assert_raises ActiveRecord::StatementInvalid do
@connection.select_all("SELECT '\xC8'")
end
end
end
end
end
module ActiveRecord
class AdapterTestWithoutTransaction < ActiveRecord::TestCase
# SQL Server does not allow truncation of tables that are referenced by foreign key
# constraints. So manually remove/add foreign keys in test.
coerce_tests! :test_truncate_tables
def test_truncate_tables_coerced
# Remove foreign key constraint to allow truncation.
@connection.remove_foreign_key :authors, :author_addresses
assert_operator Post.count, :>, 0
assert_operator Author.count, :>, 0
assert_operator AuthorAddress.count, :>, 0
@connection.truncate_tables("author_addresses", "authors", "posts")
assert_equal 0, Post.count
assert_equal 0, Author.count
assert_equal 0, AuthorAddress.count
ensure
reset_fixtures("posts", "authors", "author_addresses")
# Restore foreign key constraint.
@connection.add_foreign_key :authors, :author_addresses
end
# SQL Server does not allow truncation of tables that are referenced by foreign key
# constraints. So manually remove/add foreign keys in test.
coerce_tests! :test_truncate_tables_with_query_cache
def test_truncate_tables_with_query_cache
# Remove foreign key constraint to allow truncation.
@connection.remove_foreign_key :authors, :author_addresses
@connection.enable_query_cache!
assert_operator Post.count, :>, 0
assert_operator Author.count, :>, 0
assert_operator AuthorAddress.count, :>, 0
@connection.truncate_tables("author_addresses", "authors", "posts")
assert_equal 0, Post.count
assert_equal 0, Author.count
assert_equal 0, AuthorAddress.count
ensure
reset_fixtures("posts", "authors", "author_addresses")
@connection.disable_query_cache!
# Restore foreign key constraint.
@connection.add_foreign_key :authors, :author_addresses
end
end
end
class AttributeMethodsTest < ActiveRecord::TestCase
# Use IFF for boolean statement in SELECT
coerce_tests! %r{typecast attribute from select to false}
def test_typecast_attribute_from_select_to_false_coerced
Topic.create(title: "Budget")
topic = Topic.all.merge!(select: "topics.*, IIF (1 = 2, 1, 0) as is_test").first
assert_not_predicate topic, :is_test?
end
# Use IFF for boolean statement in SELECT
coerce_tests! %r{typecast attribute from select to true}
def test_typecast_attribute_from_select_to_true_coerced
Topic.create(title: "Budget")
topic = Topic.all.merge!(select: "topics.*, IIF (1 = 1, 1, 0) as is_test").first
assert_predicate topic, :is_test?
end
end
class BasicsTest < ActiveRecord::TestCase
# Use square brackets as SQL Server escaped character
coerce_tests! :test_column_names_are_escaped
def test_column_names_are_escaped_coerced
conn = ActiveRecord::Base.lease_connection
assert_equal "[t]]]", conn.quote_column_name("t]")
end
# Just like PostgreSQLAdapter does.
coerce_tests! :test_respect_internal_encoding
# Caused in Rails v4.2.5 by adding `firm_id` column in this http://git.io/vBfMs
# commit. Trust Rails has this covered.
coerce_tests! :test_find_keeps_multiple_group_values
def test_update_date_time_attributes
Time.use_zone("Eastern Time (US & Canada)") do
topic = Topic.find(1)
time = Time.zone.parse("2017-07-17 10:56")
topic.update!(written_on: time)
assert_equal(time, topic.written_on)
end
end
def test_update_date_time_attributes_with_default_timezone_local
with_env_tz "America/New_York" do
with_timezone_config default: :local do
Time.use_zone("Eastern Time (US & Canada)") do
topic = Topic.find(1)
time = Time.zone.parse("2017-07-17 10:56")
topic.update!(written_on: time)
assert_equal(time, topic.written_on)
end
end
end
end
end
class BelongsToAssociationsTest < ActiveRecord::TestCase
# Since @client.firm is a single first/top, and we use FETCH the order clause is used.
coerce_tests! :test_belongs_to_does_not_use_order_by
# Square brackets around column name
coerce_tests! :test_belongs_to_with_primary_key_joins_on_correct_column
def test_belongs_to_with_primary_key_joins_on_correct_column_coerced
sql = Client.joins(:firm_with_primary_key).to_sql
assert_no_match(/\[firm_with_primary_keys_companies\]\.\[id\]/, sql)
assert_match(/\[firm_with_primary_keys_companies\]\.\[name\]/, sql)
end
# Asserted SQL to get one row different from original test.
coerce_tests! :test_belongs_to
def test_belongs_to_coerced
client = Client.find(3)
first_firm = companies(:first_firm)
assert_queries_match(/FETCH NEXT @(\d) ROWS ONLY(.)*@\1 = 1/) do
assert_equal first_firm, client.firm
assert_equal first_firm.name, client.firm.name
end
end
end
module ActiveRecord
class BindParameterTest < ActiveRecord::TestCase
# Same as original coerced test except log is found using `EXEC sp_executesql` wrapper.
coerce_tests! :test_binds_are_logged
def test_binds_are_logged_coerced
sub = Arel::Nodes::BindParam.new(1)
binds = [Relation::QueryAttribute.new("id", 1, Type::Value.new)]
sql = "select * from topics where id = #{sub.to_sql}"
@connection.exec_query(sql, "SQL", binds)
logged_sql = "EXEC sp_executesql N'#{sql}', N'#{sub.to_sql} int', #{sub.to_sql} = 1"
message = @subscriber.calls.find { |args| args[4][:sql] == logged_sql }
assert_equal binds, message[4][:binds]
end
# SQL Server adapter does not use a statement cache as query plans are already reused using `EXEC sp_executesql`.
coerce_tests! :test_statement_cache
coerce_tests! :test_statement_cache_with_query_cache
coerce_tests! :test_statement_cache_with_find
coerce_tests! :test_statement_cache_with_find_by
coerce_tests! :test_statement_cache_with_in_clause
coerce_tests! :test_statement_cache_with_sql_string_literal
# Same as original coerced test except prepared statements include `EXEC sp_executesql` wrapper.
coerce_tests! :test_bind_params_to_sql_with_prepared_statements, :test_bind_params_to_sql_with_unprepared_statements
def test_bind_params_to_sql_with_prepared_statements_coerced
assert_bind_params_to_sql_coerced(prepared: true)
end
def test_bind_params_to_sql_with_unprepared_statements_coerced
@connection.unprepared_statement do
assert_bind_params_to_sql_coerced(prepared: false)
end
end
private
def assert_bind_params_to_sql_coerced(prepared:)
table = Author.quoted_table_name
pk = "#{table}.#{Author.quoted_primary_key}"
# prepared_statements: true
#
# EXEC sp_executesql N'SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (@0, @1, @2) OR [authors].[id] IS NULL)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3
#
# prepared_statements: false
#
# SELECT [authors].* FROM [authors] WHERE ([authors].[id] IN (1, 2, 3) OR [authors].[id] IS NULL)
#
sql_unprepared = "SELECT #{table}.* FROM #{table} WHERE (#{pk} IN (#{bind_params(1..3)}) OR #{pk} IS NULL)"
sql_prepared = "EXEC sp_executesql N'SELECT #{table}.* FROM #{table} WHERE (#{pk} IN (#{bind_params(1..3)}) OR #{pk} IS NULL)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3"
authors = Author.where(id: [1, 2, 3, nil])
assert_equal sql_unprepared, @connection.to_sql(authors.arel)
assert_queries_match(prepared ? sql_prepared : sql_unprepared) { assert_equal 3, authors.length }
# prepared_statements: true
#
# EXEC sp_executesql N'SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (@0, @1, @2)', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3
#
# prepared_statements: false
#
# SELECT [authors].* FROM [authors] WHERE [authors].[id] IN (1, 2, 3)
#
sql_unprepared = "SELECT #{table}.* FROM #{table} WHERE #{pk} IN (#{bind_params(1..3)})"
sql_prepared = "EXEC sp_executesql N'SELECT #{table}.* FROM #{table} WHERE #{pk} IN (#{bind_params(1..3)})', N'@0 bigint, @1 bigint, @2 bigint', @0 = 1, @1 = 2, @2 = 3"
authors = Author.where(id: [1, 2, 3, 9223372036854775808])
assert_equal sql_unprepared, @connection.to_sql(authors.arel)
assert_queries_match(prepared ? sql_prepared : sql_unprepared) { assert_equal 3, authors.length }
end
end
end
module ActiveRecord
class InstrumentationTest < ActiveRecord::TestCase
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_payload_name_on_load
def test_payload_name_on_load_coerced
Book.send(:load_schema!)
original_test_payload_name_on_load
end
# Need to remove index as SQL Server considers NULLs on a unique-index to be equal unlike PostgreSQL/MySQL/SQLite.
coerce_tests! :test_payload_row_count_on_select_all
def test_payload_row_count_on_select_all_coerced
connection.remove_index(:books, column: [:author_id, :name])
original_test_payload_row_count_on_select_all
ensure
Book.where(author_id: nil, name: "row count book 1").delete_all
Book.lease_connection.add_index(:books, [:author_id, :name], unique: true)
end
# Need to remove index as SQL Server considers NULLs on a unique-index to be equal unlike PostgreSQL/MySQL/SQLite.
coerce_tests! :test_payload_row_count_on_pluck
def test_payload_row_count_on_pluck_coerced
connection.remove_index(:books, column: [:author_id, :name])
original_test_payload_row_count_on_pluck
ensure
Book.where(author_id: nil, name: "row count book 2").delete_all
Book.lease_connection.add_index(:books, [:author_id, :name], unique: true)
end
# Need to remove index as SQL Server considers NULLs on a unique-index to be equal unlike PostgreSQL/MySQL/SQLite.
coerce_tests! :test_payload_row_count_on_raw_sql
def test_payload_row_count_on_raw_sql_coerced
connection.remove_index(:books, column: [:author_id, :name])
original_test_payload_row_count_on_raw_sql
ensure
Book.where(author_id: nil, name: "row count book 3").delete_all
Book.lease_connection.add_index(:books, [:author_id, :name], unique: true)
end
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_payload_affected_rows
def test_payload_affected_rows_coerced
Book.create!(name: "TEMP RECORD TO RUN SCHEMA QUERIES").destroy!
original_test_payload_affected_rows
end
end
end
class CalculationsTest < ActiveRecord::TestCase
# SELECT columns must be in the GROUP clause.
coerce_tests! :test_should_count_with_group_by_qualified_name_on_loaded
def test_should_count_with_group_by_qualified_name_on_loaded_coerced
accounts = Account.group("accounts.id").select("accounts.id")
expected = {1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1}
assert_not_predicate accounts, :loaded?
assert_equal expected, accounts.count
accounts.load
assert_predicate accounts, :loaded?
assert_equal expected, accounts.count(:id)
end
# Fix randomly failing test. The loading of the model's schema was affecting the test.
coerce_tests! :test_offset_is_kept
def test_offset_is_kept_coerced
Account.send(:load_schema!)
original_test_offset_is_kept
end
# The SQL Server `AVG()` function for a list of integers returns an integer (not a decimal).
coerce_tests! :test_should_return_decimal_average_of_integer_field
def test_should_return_decimal_average_of_integer_field_coerced
value = Account.average(:id)
assert_equal 3, value
end
# In SQL Server the `AVG()` function for a list of integers returns an integer so need to cast values as decimals before averaging.
# Match SQL Server limit implementation.
coerce_tests! :test_select_avg_with_group_by_as_virtual_attribute_with_sql
def test_select_avg_with_group_by_as_virtual_attribute_with_sql_coerced
rails_core = companies(:rails_core)
sql = <<~SQL
SELECT firm_id, AVG(CAST(credit_limit AS DECIMAL)) AS avg_credit_limit
FROM accounts
WHERE firm_id = ?
GROUP BY firm_id
ORDER BY firm_id
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
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
# In SQL Server the `AVG()` function for a list of integers returns an integer so need to cast values as decimals before averaging.
# Order column must be in the GROUP clause.
coerce_tests! :test_select_avg_with_group_by_as_virtual_attribute_with_ar
def test_select_avg_with_group_by_as_virtual_attribute_with_ar_coerced
rails_core = companies(:rails_core)
account = Account
.select(:firm_id, "AVG(CAST(credit_limit AS DECIMAL)) AS avg_credit_limit")
.where(firm: rails_core)
.group(:firm_id)
.order(: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
# In SQL Server the `AVG()` function for a list of integers returns an integer so need to cast values as decimals before averaging.
# SELECT columns must be in the GROUP clause.
# Match SQL Server limit implementation.
coerce_tests! :test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_sql
def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_sql_coerced
rails_core = companies(:rails_core)
sql = <<~SQL
SELECT companies.*, AVG(CAST(accounts.credit_limit AS DECIMAL)) AS avg_credit_limit
FROM companies
INNER JOIN accounts ON companies.id = accounts.firm_id
WHERE companies.id = ?
GROUP BY companies.id, companies.type, companies.firm_id, companies.firm_name, companies.name, companies.client_of, companies.rating, companies.account_id, companies.description, companies.status
ORDER BY companies.id
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
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
# In SQL Server the `AVG()` function for a list of integers returns an integer so need to cast values as decimals before averaging.
# SELECT columns must be in the GROUP clause.
coerce_tests! :test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_ar
def test_select_avg_with_joins_and_group_by_as_virtual_attribute_with_ar_coerced
rails_core = companies(:rails_core)
firm = DependentFirm
.select("companies.*", "AVG(CAST(accounts.credit_limit AS DECIMAL)) AS avg_credit_limit")
.where(id: rails_core)
.joins(:account)
.group(:id, :type, :firm_id, :firm_name, :name, :client_of, :rating, :account_id, :description, :status)
.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
# Match SQL Server limit implementation
coerce_tests! :test_limit_is_kept
def test_limit_is_kept_coerced
queries = capture_sql { Account.limit(1).count }
assert_equal 1, queries.length
assert_match(/ORDER BY \[accounts\]\.\[id\] ASC OFFSET 0 ROWS FETCH NEXT @0 ROWS ONLY.*@0 = 1/, queries.first)
end
# Match SQL Server limit implementation
coerce_tests! :test_limit_with_offset_is_kept
def test_limit_with_offset_is_kept_coerced
queries = capture_sql { Account.limit(1).offset(1).count }
assert_equal 1, queries.length
assert_match(/ORDER BY \[accounts\]\.\[id\] ASC OFFSET @0 ROWS FETCH NEXT @1 ROWS ONLY.*@0 = 1, @1 = 1/, queries.first)
end
# SQL Server needs an alias for the calculated column
coerce_tests! :test_distinct_count_all_with_custom_select_and_order
def test_distinct_count_all_with_custom_select_and_order_coerced
accounts = Account.distinct.select("credit_limit % 10 AS the_limit").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
# Leave it up to users to format selects/functions so HAVING works correctly.
coerce_tests! :test_having_with_strong_parameters
# SELECT columns must be in the GROUP clause. Since since `ids` only selects the primary key you cannot perform this query in SQL Server.
coerce_tests! :test_ids_with_includes_and_non_primary_key_order
# To limit the results in SQL Server we use `FETCH NEXT @0 ROWS ONLY` instead of `LIMIT @0`. To use `FETCH NEXT` an order must be provided.
coerce_tests! :test_no_order_by_when_counting_all
end
module ActiveRecord
class Migration
class ChangeSchemaTest < ActiveRecord::TestCase
# Integer.default is a number and not a string
coerce_tests! :test_create_table_with_defaults
def test_create_table_with_defaults_coerce
connection.create_table :testings do |t|
t.column :one, :string, default: "hello"
t.column :two, :boolean, default: true
t.column :three, :boolean, default: false
t.column :four, :integer, default: 1
t.column :five, :text, default: "hello"
end
columns = connection.columns(:testings)
one = columns.detect { |c| c.name == "one" }
two = columns.detect { |c| c.name == "two" }
three = columns.detect { |c| c.name == "three" }
four = columns.detect { |c| c.name == "four" }
five = columns.detect { |c| c.name == "five" }
assert_equal "hello", one.default
assert_equal true, two.fetch_cast_type(connection).deserialize(two.default)
assert_equal false, three.fetch_cast_type(connection).deserialize(three.default)
assert_equal 1, four.default
assert_equal "hello", five.default
end
# Use precision 6 by default for datetime/timestamp columns. SQL Server uses `datetime2` for date-times with precision.
coerce_tests! :test_add_column_with_postgresql_datetime_type
def test_add_column_with_postgresql_datetime_type_coerced
connection.create_table :testings do |t|
t.column :foo, :datetime
end
column = connection.columns(:testings).find { |c| c.name == "foo" }
assert_equal :datetime, column.type
assert_equal "datetime2(6)", column.sql_type
end
# Use precision 6 by default for datetime/timestamp columns. SQL Server uses `datetime2` for date-times with precision.
coerce_tests! :test_change_column_with_timestamp_type
def test_change_column_with_timestamp_type_coerced
connection.create_table :testings do |t|
t.column :foo, :datetime, null: false
end
connection.change_column :testings, :foo, :timestamp
column = connection.columns(:testings).find { |c| c.name == "foo" }
assert_equal :datetime, column.type
assert_equal "datetime2(6)", column.sql_type
end
# Use precision 6 by default for datetime/timestamp columns. SQL Server uses `datetime2` for date-times with precision.
coerce_tests! :test_add_column_with_timestamp_type
def test_add_column_with_timestamp_type_coerced
connection.create_table :testings do |t|
t.column :foo, :timestamp
end
column = connection.columns(:testings).find { |c| c.name == "foo" }
assert_equal :datetime, column.type
assert_equal "datetime2(6)", column.sql_type
end
end
end
end
module ActiveRecord
class Migration
class ColumnAttributesTest < ActiveRecord::TestCase
# We have a default 4000 varying character limit.
coerce_tests! :test_add_column_without_limit
def test_add_column_without_limit_coerced
add_column :test_models, :description, :string, limit: nil
TestModel.reset_column_information
_(TestModel.columns_hash["description"].limit).must_equal 4000
end
end
end
end
module ActiveRecord
class Migration
class ColumnsTest < ActiveRecord::TestCase
# Our defaults are real 70000 integers vs '70000' strings.
coerce_tests! :test_rename_column_preserves_default_value_not_null
def test_rename_column_preserves_default_value_not_null_coerced
add_column "test_models", "salary", :integer, default: 70000
default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default
assert_equal 70000, default_before
rename_column "test_models", "salary", "annual_salary"
TestModel.reset_column_information
assert TestModel.column_names.include?("annual_salary")
default_after = connection.columns("test_models").find { |c| c.name == "annual_salary" }.default
assert_equal 70000, default_after
end
# Dropping the column removes the single index.
coerce_tests! :test_remove_column_with_multi_column_index
def test_remove_column_with_multi_column_index_coerced
add_column "test_models", :hat_size, :integer
add_column "test_models", :hat_style, :string, limit: 100
add_index "test_models", ["hat_style", "hat_size"], unique: true
assert_equal 1, connection.indexes("test_models").size
remove_column("test_models", "hat_size")
assert_equal [], connection.indexes("test_models").map(&:name)
end
# Choose `StatementInvalid` vs `ActiveRecordError`.
coerce_tests! :test_rename_nonexistent_column
def test_rename_nonexistent_column_coerced
exception = ActiveRecord::StatementInvalid
assert_raise(exception) do
rename_column "test_models", "nonexistent", "should_fail"
end
end
end
end
end
class MigrationTest < ActiveRecord::TestCase
# For some reason our tests set Rails.@_env which breaks test env switching.
coerce_tests! :test_internal_metadata_stores_environment_when_other_data_exists
coerce_tests! :test_internal_metadata_stores_environment
# Same as original but using binary type instead of blob
coerce_tests! :test_add_column_with_casted_type_if_not_exists_set_to_true
def test_add_column_with_casted_type_if_not_exists_set_to_true_coerced
migration_a = Class.new(ActiveRecord::Migration::Current) {
def version
100
end
def migrate(x)
add_column "people", "last_name", :binary
end
}.new
migration_b = Class.new(ActiveRecord::Migration::Current) {
def version
101
end
def migrate(x)
add_column "people", "last_name", :binary, if_not_exists: true
end
}.new
ActiveRecord::Migrator.new(:up, [migration_a], @schema_migration, @internal_metadata, 100).migrate
assert_column Person, :last_name, "migration_a should have created the last_name column on people"
assert_nothing_raised do
ActiveRecord::Migrator.new(:up, [migration_b], @schema_migration, @internal_metadata, 101).migrate
end
ensure
Person.reset_column_information
if Person.column_names.include?("last_name")
Person.lease_connection.remove_column("people", "last_name")
end
end
end
module ActiveRecord
class Migration
class CompatibilityTest < ActiveRecord::TestCase
# Error message depends on the database adapter.
coerce_tests! :test_create_table_on_7_0
def test_create_table_on_7_0_coerced
long_table_name = "a" * (connection.table_name_length + 1)
migration = Class.new(ActiveRecord::Migration[7.0]) {
@@long_table_name = long_table_name
def version
100
end
def migrate(x)
create_table @@long_table_name
end
}.new
error = assert_raises(StandardError) do
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
end
assert_match(/The identifier that starts with '#{long_table_name[0...-1]}' is too long/i, error.message)
ensure
begin
connection.drop_table(long_table_name)
rescue
nil
end
end
# SQL Server truncates long table names when renaming (https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-ver16).
coerce_tests! :test_rename_table_on_7_0
def test_rename_table_on_7_0_coerced
long_table_name = "a" * (connection.table_name_length + 1)
connection.create_table(:more_testings)
migration = Class.new(ActiveRecord::Migration[7.0]) {
@@long_table_name = long_table_name
def version
100
end
def migrate(x)
rename_table :more_testings, @@long_table_name
end
}.new
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
assert connection.table_exists?(long_table_name[0...-1])
assert_not connection.table_exists?(:more_testings)
assert connection.table_exists?(long_table_name[0...-1])
ensure
begin
connection.drop_table(:more_testings)
rescue
nil
end
begin
connection.drop_table(long_table_name[0...-1])
rescue
nil
end
end
# SQL Server has a different maximum index name length.
coerce_tests! :test_add_index_errors_on_too_long_name_7_0
def test_add_index_errors_on_too_long_name_7_0_coerced
long_index_name = "a" * (connection.index_name_length + 1)
migration = Class.new(ActiveRecord::Migration[7.0]) {
@@long_index_name = long_index_name
def migrate(x)
add_column :testings, :very_long_column_name_to_test_with, :string
add_index :testings, [:foo, :bar, :very_long_column_name_to_test_with], name: @@long_index_name
end
}.new
error = assert_raises(StandardError) do
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
end
assert_match(/Index name '#{long_index_name}' on table 'testings' is too long/i, error.message)
end
# SQL Server has a different maximum index name length.
coerce_tests! :test_create_table_add_index_errors_on_too_long_name_7_0
def test_create_table_add_index_errors_on_too_long_name_7_0_coerced
long_index_name = "a" * (connection.index_name_length + 1)
migration = Class.new(ActiveRecord::Migration[7.0]) {
@@long_index_name = long_index_name
def migrate(x)
create_table :more_testings do |t|
t.integer :foo
t.integer :bar
t.integer :very_long_column_name_to_test_with
t.index [:foo, :bar, :very_long_column_name_to_test_with], name: @@long_index_name
end
end
}.new
error = assert_raises(StandardError) do
ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
end
assert_match(/Index name '#{long_index_name}' on table 'more_testings' is too long/i, error.message)
ensure
begin
connection.drop_table :more_testings
rescue
nil
end
end
end
end
end
class CoreTest < ActiveRecord::TestCase
# I think fixtures are using the wrong time zone and the `:first`
# `topics`.`bonus_time` attribute of 2005-01-30t15:28:00.00+01:00 is
# getting local EST time for me and set to "09:28:00.0000000".
coerce_tests! :test_pretty_print_persisted
end
module ActiveRecord
module ConnectionAdapters
# Just like PostgreSQLAdapter does.
TypeLookupTest.coerce_all_tests! if defined?(TypeLookupTest)
# All sorts of errors due to how we test. Even setting ENV['RAILS_ENV'] to
# a value of 'default_env' will still show tests failing. Just ignoring all
# of them since we have no monkey in this circus.
MergeAndResolveDefaultUrlConfigTest.coerce_all_tests! if defined?(MergeAndResolveDefaultUrlConfigTest)
ConnectionHandlerTest.coerce_all_tests! if defined?(ConnectionHandlerTest)
end
end
module ActiveRecord
# The original module is hardcoded for PostgreSQL/SQLite/MySQL tests.
module DatabaseTasksSetupper
undef_method :setup
def setup
@sqlserver_tasks =
Class.new do
def create
end
def drop
end
def purge
end
def charset
end
def collation
end
def structure_dump(*)
end
def structure_load(*)
end
end.new
$stdout, @original_stdout = StringIO.new, $stdout
$stderr, @original_stderr = StringIO.new, $stderr
end
undef_method :with_stubbed_new
def with_stubbed_new
ActiveRecord::Tasks::SQLServerDatabaseTasks.stub(:new, @sqlserver_tasks) do
yield
end
end
end
class DatabaseTasksCreateTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_create
with_stubbed_new do
assert_called(eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :create) do
ActiveRecord::Tasks::DatabaseTasks.create "adapter" => :sqlserver
end
end
end
end
class DatabaseTasksDropTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_drop
with_stubbed_new do
assert_called(eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :drop) do
ActiveRecord::Tasks::DatabaseTasks.drop "adapter" => :sqlserver
end
end
end
end
class DatabaseTasksPurgeTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_purge
with_stubbed_new do
assert_called(eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :purge) do
ActiveRecord::Tasks::DatabaseTasks.purge "adapter" => :sqlserver
end
end
end
end
class DatabaseTasksCharsetTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_charset
with_stubbed_new do
assert_called(eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :charset) do
ActiveRecord::Tasks::DatabaseTasks.charset "adapter" => :sqlserver
end
end
end
end
class DatabaseTasksCollationTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_collation
with_stubbed_new do
assert_called(eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :collation) do
ActiveRecord::Tasks::DatabaseTasks.collation "adapter" => :sqlserver
end
end
end
end
class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_structure_dump
with_stubbed_new do
assert_called_with(
eval("@sqlserver_tasks", binding, __FILE__, __LINE__), :structure_dump,
["awesome-file.sql", nil]
) do
ActiveRecord::Tasks::DatabaseTasks.structure_dump({"adapter" => :sqlserver}, "awesome-file.sql")
end
end
end
end
class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase
# Coerce PostgreSQL/SQLite/MySQL tests.
coerce_all_tests!
def test_sqlserver_structure_load
with_stubbed_new do
assert_called_with(
eval("@sqlserver_tasks", binding, __FILE__, __LINE__),
:structure_load,
["awesome-file.sql", nil]
) do
ActiveRecord::Tasks::DatabaseTasks.structure_load({"adapter" => :sqlserver}, "awesome-file.sql")
end
end