relation 0.5.2 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,402 @@
1
+ # BENCHMARK=1 ruby test/benchmarks/relation_benchmark.rb
2
+
3
+ require_relative "../test_helper"
4
+ require "benchmark/ips"
5
+ require "securerandom"
6
+
7
+ class RelationBenchmark
8
+ USER_COUNT = 1_000
9
+ ORDER_COUNT = 1_000
10
+
11
+ CARDINALITIES = [1, 10, 100, 1_000].freeze
12
+ BENCHMARK_TIME = 5
13
+ BENCHMARK_WARMUP = 2
14
+
15
+ def run_flag
16
+ ENV["BENCHMARK"] == "1"
17
+ end
18
+
19
+ def initialize
20
+ return unless run_flag
21
+
22
+ puts "Preparing benchmark data..."
23
+
24
+ Relation.delete_all
25
+
26
+ @users = create_users
27
+ @orders = create_orders
28
+
29
+ @user = @users.first
30
+ @order = @orders.first
31
+ @other_order = @orders.second
32
+
33
+ prepare_relationships
34
+
35
+ print_environment
36
+ end
37
+
38
+ def run
39
+ return unless run_flag
40
+
41
+ benchmark_add_new_raw
42
+ benchmark_add_existing
43
+ benchmark_add_remove
44
+
45
+ benchmark_queries
46
+ benchmark_cardinality
47
+
48
+ measure_queries
49
+ end
50
+
51
+ private
52
+
53
+ # --------------------------------------------------
54
+ # DATA PREPARATION
55
+ # --------------------------------------------------
56
+
57
+ def create_users
58
+ User.insert_all(
59
+ Array.new(USER_COUNT) do |i|
60
+ {
61
+ email: "benchmark#{i}@example.com",
62
+ created_at: Time.current,
63
+ updated_at: Time.current
64
+ }
65
+ end
66
+ )
67
+
68
+ User.order(:id).last(USER_COUNT)
69
+ end
70
+
71
+ def create_orders
72
+ Order.insert_all(
73
+ Array.new(ORDER_COUNT) do |i|
74
+ {
75
+ name: "benchmark#{i}",
76
+ created_at: Time.current,
77
+ updated_at: Time.current
78
+ }
79
+ end
80
+ )
81
+
82
+ Order.order(:id).last(ORDER_COUNT)
83
+ end
84
+
85
+ def prepare_relationships
86
+ rows = @users.zip(@orders).map do |user, order|
87
+ normalize(user, order)
88
+ end
89
+
90
+ Relation.insert_all(
91
+ rows,
92
+ unique_by: %i[from_name from_id to_name to_id]
93
+ )
94
+ end
95
+
96
+ def normalize(from, to)
97
+ {
98
+ from_name: from.class.polymorphic_name,
99
+ from_id: from.id,
100
+ to_name: to.class.polymorphic_name,
101
+ to_id: to.id
102
+ }
103
+ end
104
+
105
+ def print_environment
106
+ puts
107
+ puts "Ruby: #{RUBY_VERSION}"
108
+ puts "Rails: #{Rails.version}"
109
+ puts "Database: #{ActiveRecord::Base.connection.adapter_name}"
110
+ puts "Users: #{User.count}"
111
+ puts "Orders: #{Order.count}"
112
+ puts "Relations: #{Relation.count}"
113
+ puts
114
+ end
115
+
116
+ # --------------------------------------------------
117
+ # ADD: NEW RAW
118
+ # --------------------------------------------------
119
+
120
+ def benchmark_add_new_raw
121
+ puts "\n=== ADD NEW RAW ==="
122
+
123
+ index = 0
124
+
125
+ Benchmark.ips do |x|
126
+ x.config(time: BENCHMARK_TIME, warmup: BENCHMARK_WARMUP)
127
+
128
+ x.report("add_raw/new") do
129
+ index += 1
130
+
131
+ Relation.add_raw(
132
+ "BenchmarkUser",
133
+ index,
134
+ "BenchmarkOrder",
135
+ index
136
+ )
137
+ end
138
+
139
+ x.compare!
140
+ end
141
+ end
142
+
143
+ # --------------------------------------------------
144
+ # ADD: EXISTING
145
+ # --------------------------------------------------
146
+
147
+ def benchmark_add_existing
148
+ puts "\n=== ADD EXISTING ==="
149
+
150
+ Relation.add(@user, @order)
151
+
152
+ Benchmark.ips do |x|
153
+ x.config(time: BENCHMARK_TIME, warmup: BENCHMARK_WARMUP)
154
+
155
+ x.report("add/existing") do
156
+ Relation.add(@user, @order)
157
+ end
158
+
159
+ x.compare!
160
+ end
161
+ end
162
+
163
+ # --------------------------------------------------
164
+ # REMOVE
165
+ # --------------------------------------------------
166
+
167
+ def benchmark_add_remove
168
+ puts "\n=== REMOVE ==="
169
+
170
+ Relation.add(@user, @order)
171
+
172
+ Benchmark.ips do |x|
173
+ x.config(time: BENCHMARK_TIME, warmup: BENCHMARK_WARMUP)
174
+
175
+ x.report("remove + restore") do
176
+ Relation.remove(@user, @order)
177
+ Relation.add(@user, @order)
178
+ end
179
+
180
+ x.report("remove/missing") do
181
+ Relation.remove(@user, @other_order)
182
+ end
183
+
184
+ x.compare!
185
+ end
186
+ end
187
+
188
+ # --------------------------------------------------
189
+ # QUERIES
190
+ # --------------------------------------------------
191
+
192
+ def benchmark_queries
193
+ puts "\n=== QUERIES ==="
194
+
195
+ Benchmark.ips do |x|
196
+ x.config(time: BENCHMARK_TIME, warmup: BENCHMARK_WARMUP)
197
+
198
+ x.report("references/raw") do
199
+ Relation.references_raw(
200
+ User.polymorphic_name,
201
+ @user.id,
202
+ Order.polymorphic_name
203
+ )
204
+ end
205
+
206
+ x.report("references/objects") do
207
+ Relation.references(@user, Order).load
208
+ end
209
+
210
+ x.report("references/pluck") do
211
+ Relation.references(@user, Order).pluck(:id)
212
+ end
213
+
214
+ x.report("followers/raw") do
215
+ Relation.followers_raw(
216
+ User.polymorphic_name,
217
+ Order.polymorphic_name,
218
+ @order.id
219
+ )
220
+ end
221
+
222
+ x.report("followers/objects") do
223
+ Relation.followers(@order, User).load
224
+ end
225
+
226
+ x.report("followers/pluck") do
227
+ Relation.followers(@order, User).pluck(:id)
228
+ end
229
+
230
+ x.compare!
231
+ end
232
+ end
233
+
234
+ # --------------------------------------------------
235
+ # CARDINALITY
236
+ # --------------------------------------------------
237
+
238
+ def benchmark_cardinality
239
+ puts "\n=== CARDINALITY ==="
240
+
241
+ CARDINALITIES.each do |count|
242
+ benchmark_references_cardinality(count)
243
+ benchmark_followers_cardinality(count)
244
+ end
245
+ end
246
+
247
+ def benchmark_references_cardinality(count)
248
+ user = @users.first
249
+ orders = @orders.first(count)
250
+
251
+ Relation.where(
252
+ from_name: User.polymorphic_name,
253
+ from_id: user.id,
254
+ to_name: Order.polymorphic_name
255
+ ).delete_all
256
+
257
+ Relation.insert_all(
258
+ orders.map { |order| normalize(user, order) },
259
+ unique_by: %i[from_name from_id to_name to_id]
260
+ )
261
+
262
+ puts "\n=== REFERENCES: #{count} ==="
263
+
264
+ Benchmark.ips do |x|
265
+ x.config(time: 3, warmup: 1)
266
+
267
+ x.report("references/raw/#{count}") do
268
+ Relation.references_raw(
269
+ User.polymorphic_name,
270
+ user.id,
271
+ Order.polymorphic_name
272
+ )
273
+ end
274
+
275
+ x.report("references/objects/#{count}") do
276
+ Relation.references(user, Order).load
277
+ end
278
+
279
+ x.report("references/pluck/#{count}") do
280
+ Relation.references(user, Order).pluck(:id)
281
+ end
282
+
283
+ x.compare!
284
+ end
285
+ end
286
+
287
+ def benchmark_followers_cardinality(count)
288
+ order = @orders.first
289
+ users = @users.first(count)
290
+
291
+ Relation.where(
292
+ from_name: User.polymorphic_name,
293
+ to_name: Order.polymorphic_name,
294
+ to_id: order.id
295
+ ).delete_all
296
+
297
+ Relation.insert_all(
298
+ users.map { |user| normalize(user, order) },
299
+ unique_by: %i[from_name from_id to_name to_id]
300
+ )
301
+
302
+ puts "\n=== FOLLOWERS: #{count} ==="
303
+
304
+ Benchmark.ips do |x|
305
+ x.config(time: 3, warmup: 1)
306
+
307
+ x.report("followers/raw/#{count}") do
308
+ Relation.followers_raw(
309
+ User.polymorphic_name,
310
+ Order.polymorphic_name,
311
+ order.id
312
+ )
313
+ end
314
+
315
+ x.report("followers/objects/#{count}") do
316
+ Relation.followers(order, User).load
317
+ end
318
+
319
+ x.report("followers/pluck/#{count}") do
320
+ Relation.followers(order, User).pluck(:id)
321
+ end
322
+
323
+ x.compare!
324
+ end
325
+ end
326
+
327
+ # --------------------------------------------------
328
+ # SQL METRICS
329
+ # --------------------------------------------------
330
+
331
+ def measure_queries
332
+ puts "\n=== SQL METRICS ==="
333
+
334
+ tests = {
335
+ "references/raw" => lambda {
336
+ Relation.references_raw(
337
+ User.polymorphic_name,
338
+ @user.id,
339
+ Order.polymorphic_name
340
+ )
341
+ },
342
+
343
+ "references/objects" => lambda {
344
+ Relation.references(@user, Order).load
345
+ },
346
+
347
+ "references/pluck" => lambda {
348
+ Relation.references(@user, Order).pluck(:id)
349
+ },
350
+
351
+ "followers/raw" => lambda {
352
+ Relation.followers_raw(
353
+ User.polymorphic_name,
354
+ Order.polymorphic_name,
355
+ @order.id
356
+ )
357
+ },
358
+
359
+ "followers/objects" => lambda {
360
+ Relation.followers(@order, User).load
361
+ },
362
+
363
+ "followers/pluck" => lambda {
364
+ Relation.followers(@order, User).pluck(:id)
365
+ }
366
+ }
367
+
368
+ tests.each do |name, operation|
369
+ queries = []
370
+
371
+ callback = lambda do |_name, start, finish, _id, payload|
372
+ next if payload[:name] == "SCHEMA"
373
+ next if payload[:cached]
374
+
375
+ queries << {
376
+ sql: payload[:sql],
377
+ duration: (finish - start) * 1_000
378
+ }
379
+ end
380
+
381
+ ActiveSupport::Notifications.subscribed(
382
+ callback,
383
+ "sql.active_record"
384
+ ) do
385
+ operation.call
386
+ end
387
+
388
+ puts "\n#{name}"
389
+ puts "Queries: #{queries.size}"
390
+
391
+ total_time = queries.sum { |query| query[:duration] }
392
+
393
+ puts "SQL time: #{total_time.round(3)} ms"
394
+
395
+ queries.each do |query|
396
+ puts "#{query[:duration].round(3)} ms | #{query[:sql]}"
397
+ end
398
+ end
399
+ end
400
+ end
401
+
402
+ RelationBenchmark.new.run
@@ -0,0 +1,2 @@
1
+ class Product < ActiveRecord::Base
2
+ end
@@ -1,13 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  ActiveRecord::Schema.define(version: 202208) do
4
- create_table :relations, force: true, id: false do |t|
5
- t.string :name
6
- t.references :from, null: false
7
- t.references :to, null: false
8
- t.timestamps
4
+ create_table :relations, id: false do |t|
5
+ t.string :from_name, null: false
6
+ t.bigint :from_id, null: false
7
+ t.string :to_name, null: false
8
+ t.bigint :to_id, null: false
9
9
 
10
- t.index :name
10
+ t.index [:from_name, :from_id, :to_name, :to_id], unique: true
11
+ t.index [:to_name, :to_id, :from_name, :from_id]
11
12
  end
12
13
 
13
14
  create_table "orders", force: true do |t|
@@ -21,6 +22,22 @@ ActiveRecord::Schema.define(version: 202208) do
21
22
 
22
23
  create_table "users", force: true do |t|
23
24
  t.string :email
25
+ t.string "type"
26
+
27
+ t.datetime "created_at", null: false
28
+ t.datetime "updated_at", null: false
29
+ end
30
+
31
+ create_table "products", force: true do |t|
32
+ t.string :name
33
+
34
+ t.datetime "created_at", null: false
35
+ t.datetime "updated_at", null: false
36
+ end
37
+
38
+ create_table "items", force: true do |t|
39
+ t.string :name
40
+ t.string :type
24
41
 
25
42
  t.datetime "created_at", null: false
26
43
  t.datetime "updated_at", null: false
@@ -0,0 +1,103 @@
1
+ require "test_helper"
2
+
3
+ describe "Dangling" do
4
+ def setup
5
+ Relation.delete_all
6
+ Order.delete_all
7
+ User.delete_all
8
+ Product.delete_all
9
+ end
10
+
11
+ it "returns empty hash when no relationships exist" do
12
+ assert_empty Relation.dangling
13
+ end
14
+
15
+ it "returns empty hash when all records exist" do
16
+ order = Order.create!
17
+ user = User.create!
18
+
19
+ Relation.add order, user
20
+
21
+ assert_empty Relation.dangling
22
+ end
23
+
24
+ it "detects dangling from records" do
25
+ order = Order.create!
26
+ user = User.create!
27
+
28
+ Relation.add order, user
29
+
30
+ id = order.id
31
+ order.destroy!
32
+
33
+ assert_equal({"Order" => [id]}, Relation.dangling)
34
+ end
35
+
36
+ it "detects dangling to records" do
37
+ order = Order.create!
38
+ user = User.create!
39
+
40
+ Relation.add order, user
41
+
42
+ id = user.id
43
+ user.destroy!
44
+
45
+ assert_equal({"User" => [id]}, Relation.dangling)
46
+ end
47
+
48
+ it "detects dangling records on both sides" do
49
+ order = Order.create!
50
+ user = User.create!
51
+
52
+ Relation.add order, user
53
+
54
+ order_id = order.id
55
+ user_id = user.id
56
+
57
+ order.destroy!
58
+ user.destroy!
59
+
60
+ assert_equal(
61
+ {
62
+ "Order" => [order_id],
63
+ "User" => [user_id]
64
+ },
65
+ Relation.dangling
66
+ )
67
+ end
68
+
69
+ it "detects multiple dangling records of the same model" do
70
+ users = [User.create!, User.create!]
71
+ order = Order.create!
72
+
73
+ users.each { |user| Relation.add order, user }
74
+
75
+ ids = users.map(&:id)
76
+ users.each(&:destroy!)
77
+
78
+ assert_equal({"User" => ids}, Relation.dangling)
79
+ end
80
+
81
+ it "detects dangling records of different model types" do
82
+ order = Order.create!
83
+ user = User.create!
84
+ product = Product.create!
85
+
86
+ Relation.add order, user
87
+ Relation.add order, product
88
+
89
+ user_id = user.id
90
+ product_id = product.id
91
+
92
+ user.destroy!
93
+ product.destroy!
94
+
95
+ assert_equal(
96
+ {
97
+ "User" => [user_id],
98
+ "Product" => [product_id]
99
+ },
100
+ Relation.dangling
101
+ )
102
+ end
103
+ end
@@ -0,0 +1,65 @@
1
+ require "test_helper"
2
+
3
+ describe Relation do
4
+ let(:attrs) do
5
+ {
6
+ from_name: "User",
7
+ from_id: 100,
8
+ to_name: "Order",
9
+ to_id: 200
10
+ }
11
+ end
12
+
13
+ it "enforces unique relationships" do
14
+ Relation.insert_all!([attrs])
15
+
16
+ assert_raises(ActiveRecord::RecordNotUnique) do
17
+ Relation.insert_all!([attrs])
18
+ end
19
+ end
20
+
21
+ it "requires all relationship columns" do
22
+ assert_raises(ActiveRecord::NotNullViolation) do
23
+ Relation.insert_all!([attrs.merge(from_name: nil)])
24
+ end
25
+ end
26
+
27
+ it "has the required composite indexes" do
28
+ indexes = Relation.connection.indexes(:relations)
29
+
30
+ unique = indexes.find do |index|
31
+ index.columns == %w[from_name from_id to_name to_id]
32
+ end
33
+
34
+ reverse = indexes.find do |index|
35
+ index.columns == %w[to_name to_id from_name from_id]
36
+ end
37
+
38
+ assert unique, "missing unique relationship index"
39
+ assert unique.unique
40
+ assert reverse, "missing reverse relationship index"
41
+ refute reverse.unique
42
+ end
43
+
44
+ it "returns only the requested STI subclass" do
45
+ admin = Admin.create!(email: "admin@example.com")
46
+ customer = Customer.create!(email: "customer@example.com")
47
+
48
+ Relation.add(admin, order)
49
+ Relation.add(customer, order)
50
+
51
+ assert_equal [admin], Relation.followers(order, Admin)
52
+ assert_equal [customer], Relation.followers(order, Customer)
53
+ assert_equal [admin.id, customer.id].sort,
54
+ Relation.followers(order, User).pluck(:id).sort
55
+ end
56
+
57
+ it "rolls back relationships with the surrounding transaction" do
58
+ assert_no_difference("Relation.count") do
59
+ Relation.transaction do
60
+ Relation.add(user, order)
61
+ raise ActiveRecord::Rollback
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,44 @@
1
+ require "test_helper"
2
+
3
+ describe Relation do
4
+ it "returns followers as a lazy ActiveRecord relation" do
5
+ Relation.add(user, order)
6
+ Relation.add(user2, order)
7
+
8
+ result = Relation.followers(order, User)
9
+
10
+ assert_kind_of ActiveRecord::Relation, result
11
+ refute result.loaded?
12
+ assert_equal [user, user2].sort, result.to_a.sort
13
+ end
14
+
15
+ it "accepts model classes and names" do
16
+ Relation.add(user, order)
17
+
18
+ assert_equal [user], Relation.followers(order, User)
19
+ assert_equal [user], Relation.followers(order, "User")
20
+ end
21
+
22
+ it "returns an empty relation when no followers exist" do
23
+ assert_empty Relation.followers(order, User)
24
+ end
25
+
26
+ it "supports chained queries" do
27
+ Relation.add(user, order)
28
+ Relation.add(user2, order)
29
+
30
+ assert_equal [user2],
31
+ Relation.followers(order, User).where(id: user2.id)
32
+ end
33
+
34
+ it "returns only the requested STI subclass" do
35
+ admin = Admin.create!(email: "admin@example.com")
36
+ customer = Customer.create!(email: "customer@example.com")
37
+
38
+ Relation.add(admin, order)
39
+ Relation.add(customer, order)
40
+
41
+ assert_equal [admin], Relation.followers(order, Admin)
42
+ assert_equal [customer], Relation.followers(order, Customer)
43
+ end
44
+ end