Method: SQLite::Database#create_function

Defined in:
lib/sqlite/database.rb

#create_function(name, arity, type = nil, &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.) If type is non-nil, it should either be an integer (indicating that the type of the function is always the type of the argument at that index), or one of the symbols :numeric, :text, :args (in which case the function is, respectively, numeric, textual, or the same type as its arguments).

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, :text ) do |func, value|
  if value.nil?
    func.set_value nil
  else
    func.set_value value.split(//).sort.join
  end
end

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


350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/sqlite/database.rb', line 350

def create_function( name, arity, type=nil, &block ) # :yields: func, *args
  case type
    when :numeric
      type = SQLite::API::NUMERIC
    when :text
      type = SQLite::API::TEXT
    when :args
      type = SQLite::API::ARGS
  end

  callback = proc do |func,*args|
    begin
      block.call( FunctionProxy.new( func ), *args )
    rescue Exception => e
      SQLite::API.set_result_error( func, "#{e.message} (#{e.class})" )
    end
  end

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

  self
end