Class: Amalgalite::Aggregate

Inherits:
Object
  • Object
show all
Defined in:
lib/amalgalite/aggregate.rb

Overview

A Base class to inherit from for creating your own SQL aggregate functions in ruby.

These are SQL functions similar to _max(X)_, _count(X)_, _avg(X)_. The built in SQLite aggregate functions are:

If you choose to use Aggregate as a parent class of your SQL scalar function implementation you must:

  • implement initalize with 0 arguments

  • call super() in your initialize method

  • set the @arity data member

  • set the @name data member

  • implement step with arity of @arity

  • implement finalize with arity of 0

For instance to implement a unique_word_count(X) aggregate function you could implement it as:

class UniqueWordCount < ::Amalgalite::Aggregate
  attr_accessor :words

  def initialize
    super
    @name = 'unique_word_count'
    @arity = 1
    @words = Hash.new { |h,k| h[k] = 0 }
  end

  def step( str )
    str.split(/\W+/).each do |word|
      words[ word.downcase ] += 1
    end
    return nil
  end

  def finalize
    return words.size
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAggregate

Returns a new instance of Aggregate.



55
56
57
# File 'lib/amalgalite/aggregate.rb', line 55

def initialize
  @_exception = nil
end

Instance Attribute Details

#arityObject

The arity of the SQL function



53
54
55
# File 'lib/amalgalite/aggregate.rb', line 53

def arity
  @arity
end

#nameObject

The name of the SQL function



50
51
52
# File 'lib/amalgalite/aggregate.rb', line 50

def name
  @name
end

Instance Method Details

#finalizeObject

finalize should return the final value of the aggregate function

Raises:

  • (NotImplementedError)


60
61
62
# File 'lib/amalgalite/aggregate.rb', line 60

def finalize
  raise NotImplementedError, "Aggregate#finalize must be implemented"
end

#signatureObject

Do Not Override

The function signature for use by the Amaglaite datase in tracking function creation.



69
70
71
# File 'lib/amalgalite/aggregate.rb', line 69

def signature
  @signature ||= ::Amalgalite::SQLite3::Database::Function.signature( self.name, self.arity )
end