-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path017_query_count.rb
More file actions
105 lines (87 loc) · 1.96 KB
/
017_query_count.rb
File metadata and controls
105 lines (87 loc) · 1.96 KB
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
require 'rubygems'
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'activesupport'
gem 'activerecord'
gem 'pg'
end
require 'active_record'
puts "Loaded gems"
class Migration < ActiveRecord::Migration[5.0]
def up
create_table :things do |t|
t.string :col0
t.string :col1
t.string :col2
t.string :col3
t.string :col4
end
create_table :minions do |t|
t.integer :thing_id
t.string :name
end
sql = <<-END
INSERT INTO
things(col0, col1, col2, col3, col4)
(SELECT
rpad('x', 100, 'x'),
rpad('x', 100, 'x'),
rpad('x', 100, 'x'),
rpad('x', 100, 'x'),
rpad('x', 100, 'x')
FROM generate_series(1, 100)
);
END
ActiveRecord::Base.connection.execute sql
end
def down
drop_table :things
drop_table :minions
end
end
class Thing < ActiveRecord::Base
has_many :minions
end
class Minion < ActiveRecord::Base
belongs_to :thing
end
def migrate(dir = :up)
Migration.new.migrate(dir)
end
def track_queries
results = []
ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
query_name = event.payload[:name]
next if %w(SCHEMA).include? query_name # skip schema lookups
results << query_name
end
yield
ActiveSupport::Notifications.unsubscribe('sql.active_record')
results
end
# ------ main ------
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
database: '017_things',
host: 'localhost',
username: 'postgres'
)
cmd = ARGV[0]
case cmd
when '--migrate'
migrate(:up)
when '--rollback'
migrate(:down)
when '--each'
puts "Queries:\n"
puts (track_queries { Thing.limit(10).each { |thing| thing.minions.load } })
when '--include'
puts "Queries:\n"
puts (track_queries { Thing.limit(10).includes(:minions).load })
else
puts "No command provided!"
exit!(1)
end
exit!(0)