/* call-seq: define_aggregator(name, aggregator)
 *
 * Define an aggregate function named +name+ using the object +aggregator+.
 * +aggregator+ must respond to +step+ and +finalize+.  +step+ will be called
 * with row information and +finalize+ must return the return value for the
 * aggregator function.
 */
static VALUE define_aggregator(VALUE self, VALUE name, VALUE aggregator)
{
  sqlite3RubyPtr ctx;
  int arity, status;

  Data_Get_Struct(self, sqlite3Ruby, ctx);
  REQUIRE_OPEN_DB(ctx);

  arity = sqlite3_obj_method_arity(aggregator, rb_intern("step"));

  status = sqlite3_create_function(
    ctx->db,
    StringValuePtr(name),
    arity,
    SQLITE_UTF8,
    (void *)aggregator,
    NULL,
    rb_sqlite3_step,
    rb_sqlite3_final
  );

  rb_iv_set(self, "@agregator", aggregator);

  CHECK(ctx->db, status);

  return self;
}