Module: QuickCount

Defined in:
lib/quick_count.rb,
lib/quick_count/railtie.rb,
lib/quick_count/version.rb,
lib/quick_count/active_record/base.rb

Defined Under Namespace

Modules: ActiveRecord Classes: Railtie

Constant Summary collapse

VERSION =
"0.0.5"

Class Method Summary collapse

Class Method Details

.installObject



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
# File 'lib/quick_count.rb', line 18

def self.install
  ::ActiveRecord::Base.connection.execute("    CREATE OR REPLACE FUNCTION quick_count(table_name text) RETURNS bigint AS\n    $func$\n    DECLARE\n        rec   record;\n        rows  integer;\n    BEGIN\n      RETURN (SELECT SUM(estimate) AS estimate FROM (\n      SELECT\n          SUM(child.reltuples::bigint) AS estimate\n      FROM pg_inherits\n          JOIN pg_class parent            ON pg_inherits.inhparent = parent.oid\n          JOIN pg_class child             ON pg_inherits.inhrelid   = child.oid\n          JOIN pg_namespace nmsp_parent   ON nmsp_parent.oid  = parent.relnamespace\n          JOIN pg_namespace nmsp_child    ON nmsp_child.oid   = child.relnamespace\n      WHERE parent.relname = table_name\n      GROUP BY parent.reltuples\n      UNION SELECT reltuples::bigint AS estimate FROM pg_class where relname=table_name) as tables);\n    END\n    $func$ LANGUAGE plpgsql;\n  eos\n  )\n  ::ActiveRecord::Base.connection.execute(<<-eos\n      CREATE OR REPLACE FUNCTION count_estimate(query text) RETURNS integer AS\n      $func$\n      DECLARE\n          rec   record;\n          rows  integer;\n      BEGIN\n          FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP\n              rows := substring(rec.\"QUERY PLAN\" FROM ' rows=([[:digit:]]+)');\n              EXIT WHEN rows IS NOT NULL;\n          END LOOP;\n\n          RETURN rows;\n      END\n      $func$ LANGUAGE plpgsql;\n  eos\n  )\nend\n"

.loadObject



13
14
15
16
# File 'lib/quick_count.rb', line 13

def self.load
  ::ActiveRecord::Base.send :include, QuickCount::ActiveRecord::Base
  ::ActiveRecord::Relation.send :include, CountEstimate::ActiveRecord::Relation
end

.rootObject



9
10
11
# File 'lib/quick_count.rb', line 9

def self.root
  @root ||= Pathname.new(File.dirname(File.expand_path(File.dirname(__FILE__), '/../')))
end

.uninstallObject



60
61
62
63
# File 'lib/quick_count.rb', line 60

def self.uninstall
  ::ActiveRecord::Base.connection.execute("DROP FUNCTION quick_count(text);")
  ::ActiveRecord::Base.connection.execute("DROP FUNCTION count_estimate(text);")
end