Method: SQLite3::Database#create_function

Defined in:
lib/sqlite3/database.rb

#create_function(name, arity, text_rep = Constants::TextRep::ANY, &block) ⇒ Object

Creates a new function for use in SQL statements. It will be added as name, with the given arity. (For variable arity functions, use -1 for the arity.)

The block should accept at least one parameter–the FunctionProxy instance that wraps this function invocation–and any other arguments it needs (up to its arity).

The block does not return a value directly. Instead, it will invoke the FunctionProxy#set_result method on the func parameter and indicate the return value that way.

Example:

db.create_function( "maim", 1 ) do |func, value|
  if value.nil?
    func.result = nil
  else
    func.result = value.split(//).sort.join
  end
end

puts db.get_first_value( "select maim(name) from table" )


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/sqlite3/database.rb', line 349

def create_function( name, arity, text_rep=Constants::TextRep::ANY,
  &block ) # :yields: func, *args
# begin
  callback = proc do |func,*args|
    begin
      block.call( FunctionProxy.new( @driver, func ),
        *args.map{|v| Value.new(self,v)} )
    rescue StandardError, Exception => e
      @driver.result_error( func,
        "#{e.message} (#{e.class})", -1 )
    end
  end

  result = @driver.create_function( @handle, name, arity, text_rep, nil,
    callback, nil, nil )
  Error.check( result, self )

  self
end