class PgClip::Paginator

Attributes

connection[RW]
query[RW]

Public Class Methods

new(query, connection) click to toggle source
# File lib/pg_clip/paginator.rb, line 5
def initialize(query, connection)
  @query      = query
  @connection = connection
end

Public Instance Methods

execute_paginated_query(query, page: 1, per_page: 1000) click to toggle source
# File lib/pg_clip/paginator.rb, line 34
    def execute_paginated_query(query, page: 1, per_page: 1000)
      offset = (page - 1) * per_page

      connection.execute <<-SQL
        SET intervalstyle = 'iso_8601';
        WITH insight AS (#{query}), stats AS (
          SELECT
           #{page}                                 AS page,
           COUNT(*)                                AS total_count,
           CEIL(COUNT(*) / #{per_page}::numeric)   AS total_pages
          FROM insight
        )
        SELECT
          stats.*,
          row_to_json(insight) AS record
        FROM insight, stats
        OFFSET #{offset} LIMIT #{per_page};
      SQL
    end
execute_query(query) click to toggle source
# File lib/pg_clip/paginator.rb, line 16
    def execute_query(query)
      connection.execute <<-SQL
        SET intervalstyle = 'iso_8601';
        WITH insight AS (#{query}), stats AS (
          SELECT
           1        AS page,
           COUNT(*) AS total_count,
           1        AS total_pages
          FROM insight
        )

        SELECT
          stats.*,
          row_to_json(insight) AS record
        FROM insight, stats
      SQL
    end
records() click to toggle source
# File lib/pg_clip/paginator.rb, line 10
def records
  execute_query(query).map do |r|
    JSON.parse(r['record'], max_nesting: 1) # it's flat structure
  end
end