# File lib/sqlite/database.rb, line 411
    def create_aggregate( name, arity, step, finalize, type=nil )
      case type
        when :numeric
          type = SQLite::API::NUMERIC
        when :text
          type = SQLite::API::TEXT
        when :args
          type = SQLite::API::ARGS
      end

      step_callback = proc do |func,*args|
        ctx = SQLite::API.aggregate_context( func )
        unless ctx[:__error]
          begin
            step.call( FunctionProxy.new( func, ctx ), *args )
          rescue Exception => e
            ctx[:__error] = e
          end
        end
      end

      finalize_callback = proc do |func|
        ctx = SQLite::API.aggregate_context( func )
        unless ctx[:__error]
          begin
            finalize.call( FunctionProxy.new( func, ctx ) )
          rescue Exception => e
            SQLite::API.set_result_error( func, "#{e.message} (#{e.class})" )
          end
        else
          e = ctx[:__error]
          SQLite::API.set_result_error( func, "#{e.message} (#{e.class})" )
        end
      end

      SQLite::API.create_aggregate( @handle, name, arity,
        step_callback, finalize_callback )

      SQLite::API.function_type( @handle, name, type ) if type

      self
    end