Module: SQLite::API

Module SQLite::API |
In: | ext/sqlite-api.c

This is a one-to-one bridge between Ruby code and the C interface for SQLite. It defines (more-or-less) one method per function (with set_result being one exception). It is generally not advisable to use these methods directly; instead, you should use the SQLite::Database class and related interfaces, which provide a more object-oriented view of this interface.

Methods

- aggregate_context
- aggregate_count
- busy_handler
- busy_timeout
- changes
- close
- compile
- complete
- create_aggregate
- create_function
- finalize
- function_type
- interrupt
- last_insert_row_id
- open
- set_result
- set_result_error
- step

Public Instance methods
aggregate_context( func ) → hash

Returns the aggregate context for the given function. This context is a Hash object that is allocated on demand and is available only to the current invocation of the function. It may be used by aggregate functions to accumulate data over multiple rows, prior to being finalized.

The `func` parameter must be an opaque function handle as given to the callbacks for create_aggregate.

See create_aggregate and aggregate_count.

[ show source ]

    /**
     * call-seq:
     *     aggregate_context( func ) -> hash
     *
     * Returns the aggregate context for the given function. This context is a
     * Hash object that is allocated on demand and is available only to the
     * current invocation of the function. It may be used by aggregate functions
     * to accumulate data over multiple rows, prior to being finalized.
     *
     * The +func+ parameter must be an opaque function handle as given to the
     * callbacks for #create_aggregate.
     *
     * See #create_aggregate and #aggregate_count.
     */
    static VALUE
    static_api_aggregate_context( VALUE module, VALUE func )
    {
      sqlite_func *func_ptr;
      VALUE *ptr;

      GetFunc( func_ptr, func );

      /* FIXME: pointers to VALUEs...how nice is the GC about this kind of
       * thing? Especially when someone else frees the memory? */

      ptr = (VALUE*)sqlite_aggregate_context( func_ptr, sizeof(VALUE) );

      if( *ptr == 0 )
        *ptr = rb_hash_new();

      return *ptr;
    }

aggregate_count( func ) → fixnum

Returns the number of rows that have been processed so far by the current aggregate function. This always includes the current row, so that number that is returned will always be at least 1.

The `func` parameter must be an opaque function handle as given to the callbacks for create_aggregate.

[ show source ]

    /**
     * call-seq:
     *     aggregate_count( func ) -> fixnum
     *
     * Returns the number of rows that have been processed so far by the current
     * aggregate function. This always includes the current row, so that number
     * that is returned will always be at least 1.
     *
     * The +func+ parameter must be an opaque function handle as given to the
     * callbacks for #create_aggregate.
     */
    static VALUE
    static_api_aggregate_count( VALUE module, VALUE func )
    {
      sqlite_func *func_ptr;

      GetFunc( func_ptr, func );
      return INT2FIX( sqlite_aggregate_count( func_ptr ) );
    }

busy_handler( db, handler ) → nil

Installs a callback to be invoked whenever a request cannot be honored because a database is busy. The handler should take two parameters: a string naming the resource that was being accessed, and an integer indicating how many times the current request has failed due to the resource being busy.

If the handler returns `false`, the operation will be aborted, with a SQLite::BusyException being raised. Otherwise, SQLite will attempt to access the resource again.

See busy_timeout for an easier way to manage the common case.

[ show source ]

    /**
     * call-seq:
     *     busy_handler( db, handler ) -> nil
     *
     * Installs a callback to be invoked whenever a request cannot be honored
     * because a database is busy. The handler should take two parameters: a
     * string naming the resource that was being accessed, and an integer indicating
     * how many times the current request has failed due to the resource being busy.
     *
     * If the handler returns +false+, the operation will be aborted, with a
     * SQLite::BusyException being raised. Otherwise, SQLite will attempt to
     * access the resource again.
     *
     * See #busy_timeout for an easier way to manage the common case.
     */
    static VALUE
    static_api_busy_handler( VALUE module, VALUE db, VALUE handler )
    {
      sqlite *handle;

      GetDB( handle, db );
      if( handler == Qnil )
      {
        sqlite_busy_handler( handle, NULL, NULL );
      }
      else
      {
        if( !rb_obj_is_kind_of( handler, rb_cProc ) )
        {
          rb_raise( rb_eArgError, "handler must be a proc" );
        }

        sqlite_busy_handler( handle, static_busy_handler, (void*)handler );
      }

      return Qnil;
    }

busy_timeout( db, ms ) → nil

Specifies the number of milliseconds that SQLite should wait before retrying to access a busy resource. Specifying zero milliseconds restores the default behavior.

[ show source ]

    /**
     * call-seq:
     *     busy_timeout( db, ms ) -> nil
     *
     * Specifies the number of milliseconds that SQLite should wait before retrying
     * to access a busy resource. Specifying zero milliseconds restores the default
     * behavior.
     */
    static VALUE
    static_api_busy_timeout( VALUE module, VALUE db, VALUE ms )
    {
      sqlite *handle;

      GetDB( handle, db );
      Check_Type( ms, T_FIXNUM );

      sqlite_busy_timeout( handle, FIX2INT( ms ) );

      return Qnil;
    }

changes( db ) → fixnum

Returns the number of changed rows affected by the last operation. (Note: doing a "delete from table" without a where clause does not affect the result of this method—see the documentation for SQLite itself for the reason behind this.)

[ show source ]

    /**
     * call-seq:
     *     changes( db ) -> fixnum
     *
     * Returns the number of changed rows affected by the last operation.
     * (Note: doing a "delete from table" without a where clause does not affect
     * the result of this method--see the documentation for SQLite itself for
     * the reason behind this.)
     */
    static VALUE
    static_api_changes( VALUE module, VALUE db )
    {
      sqlite *handle;

      GetDB( handle, db );

      return INT2FIX( sqlite_changes( handle ) );
    }

close( db )

Closes the given opaque database handle. The handle must be one that was returned by a call to open.

[ show source ]

    /**
     * call-seq:
     *     close( db )
     *
     * Closes the given opaque database handle. The handle _must_ be one that was
     * returned by a call to #open.
     */
    static VALUE
    static_api_close( VALUE module, VALUE db )
    {
      sqlite *handle;

      /* FIXME: should this be executed atomically? */
      GetDB( handle, db );
      sqlite_close( handle );

      /* don't need to free the handle anymore */
      RDATA(db)->dfree = NULL;
      RDATA(db)->data = NULL;

      return Qnil;
    }

compile( db, sql ) → [ vm, remainder ]

Compiles the given SQL statement and returns a new virtual machine handle for executing it. Returns a tuple: [ vm, remainder ], where `remainder` is any text that follows the first complete SQL statement in the `sql` parameter.

[ show source ]

    /**
     * call-seq:
     *     compile( db, sql ) -> [ vm, remainder ]
     *
     * Compiles the given SQL statement and returns a new virtual machine handle
     * for executing it. Returns a tuple: [ vm, remainder ], where +remainder+ is
     * any text that follows the first complete SQL statement in the +sql+
     * parameter.
     */
    static VALUE
    static_api_compile( VALUE module, VALUE db, VALUE sql )
    {
      sqlite     *handle;
      sqlite_vm  *vm;
      char       *errmsg;
      const char *sql_tail;
      int         result;
      VALUE       tuple;

      GetDB( handle, db );
      Check_Type( sql, T_STRING );

      result = sqlite_compile( handle,
                               STR2CSTR( sql ),
                               &sql_tail,
                               &vm,
                               &errmsg );

      if( result != SQLITE_OK )
      {
        static_raise_db_error2( result, &errmsg );
        /* "raise" does not return */
      }

      tuple = rb_ary_new();
      rb_ary_push( tuple, Data_Wrap_Struct( rb_cData, NULL, static_free_vm, vm ) );
      rb_ary_push( tuple, rb_str_new2( sql_tail ) );

      return tuple;
    }

complete( sql ) → true | false

Returns `true` if the given SQL text is complete (parsable), and `false` otherwise.

[ show source ]

    /**
     * call-seq:
     *     complete( sql ) -> true | false
     *
     * Returns +true+ if the given SQL text is complete (parsable), and
     * +false+ otherwise.
     */
    static VALUE
    static_api_complete( VALUE module, VALUE sql )
    {
      Check_Type( sql, T_STRING );
      return ( sqlite_complete( STR2CSTR( sql ) ) ? Qtrue : Qfalse );
    }

create_aggregate( db, name, args, step, finalize ) → nil

Defines a new aggregate function that may be invoked from within an SQL statement. The `args` parameter specifies how many arguments the function expects—use -1 to specify variable arity.

The `step` parameter specifies a proc object that will be invoked for each row that the function processes. It should accept an opaque handle to the function object, followed by its expected arguments:

      step = proc do |func, *args|
        ...
      end

The `finalize` parameter specifies a proc object that will be invoked after all rows have been processed. This gives the function an opportunity to aggregate and finalize the results. It should accept a single parameter: the opaque function handle:

      finalize = proc do |func|
        ...
      end

The function object is used when calling the set_result, set_result_error, aggregate_context, and aggregate_count methods.

[ show source ]

    /**
     * call-seq:
     *     create_aggregate( db, name, args, step, finalize ) -> nil
     *
     * Defines a new aggregate function that may be invoked from within an SQL
     * statement. The +args+ parameter specifies how many arguments the function
     * expects--use -1 to specify variable arity.
     *
     * The +step+ parameter specifies a proc object that will be invoked for each
     * row that the function processes. It should accept an opaque handle to the
     * function object, followed by its expected arguments:
     *
     *   step = proc do |func, *args|
     *     ...
     *   end
     *
     * The +finalize+ parameter specifies a proc object that will be invoked after
     * all rows have been processed. This gives the function an opportunity to
     * aggregate and finalize the results. It should accept a single parameter:
     * the opaque function handle:
     *
     *   finalize = proc do |func|
     *     ...
     *   end
     *
     * The function object is used when calling the #set_result,
     * #set_result_error, #aggregate_context, and #aggregate_count methods.
     */
    static VALUE
    static_api_create_aggregate( VALUE module, VALUE db, VALUE name, VALUE n,
      VALUE step, VALUE finalize )
    {
      sqlite *handle;
      int     result;
      VALUE   data;

      GetDB( handle, db );
      Check_Type( name, T_STRING );
      Check_Type( n, T_FIXNUM );
      if( !rb_obj_is_kind_of( step, rb_cProc ) )
      {
        rb_raise( rb_eArgError, "step must be a proc" );
      }
      if( !rb_obj_is_kind_of( finalize, rb_cProc ) )
      {
        rb_raise( rb_eArgError, "finalize must be a proc" );
      }

      /* FIXME: will the GC kill this before it is used? */
      data = rb_ary_new3( 2, step, finalize );

      result = sqlite_create_aggregate( handle,
                  StringValueCStr(name),
                  FIX2INT(n),
                  static_function_callback,
                  static_aggregate_finalize_callback,
                  (void*)data );

      if( result != SQLITE_OK )
      {
        static_raise_db_error( result, "create aggregate %s(%d)",
          StringValueCStr(name), FIX2INT(n) );
        /* "raise" does not return */
      }

      return Qnil;
    }

create_function( db, name, args, proc ) → nil

Defines a new function that may be invoked from within an SQL statement. The `args` parameter specifies how many arguments the function expects—use -1 to specify variable arity. The `proc` parameter must be a proc that expects `args` + 1 parameters, with the first parameter being an opaque handle to the function object itself:

      proc do |func, *args|
        ...
      end

The function object is used when calling the set_result and set_result_error methods.

[ show source ]

    /**
     * call-seq:
     *     create_function( db, name, args, proc ) -> nil
     *
     * Defines a new function that may be invoked from within an SQL
     * statement. The +args+ parameter specifies how many arguments the function
     * expects--use -1 to specify variable arity. The +proc+ parameter must be
     * a proc that expects +args+ + 1 parameters, with the first parameter
     * being an opaque handle to the function object itself:
     *
     *   proc do |func, *args|
     *     ...
     *   end
     *
     * The function object is used when calling the #set_result and
     * #set_result_error methods.
     */
    static VALUE
    static_api_create_function( VALUE module, VALUE db, VALUE name, VALUE n,
      VALUE proc )
    {
      sqlite *handle;
      int     result;

      GetDB( handle, db );
      Check_Type( name, T_STRING );
      Check_Type( n, T_FIXNUM );
      if( !rb_obj_is_kind_of( proc, rb_cProc ) )
      {
        rb_raise( rb_eArgError, "handler must be a proc" );
      }

      result = sqlite_create_function( handle,
                  StringValueCStr(name),
                  FIX2INT(n),
                  static_function_callback,
                  (void*)proc );

      if( result != SQLITE_OK )
      {
        static_raise_db_error( result, "create function %s(%d)",
          StringValueCStr(name), FIX2INT(n) );
        /* "raise" does not return */
      }

      return Qnil;
    }

finalize( vm ) → nil

Destroys the given virtual machine and releases any associated memory. Once finalized, the VM should not be used.

[ show source ]

    /**
     * call-seq:
     *     finalize( vm ) -> nil
     *
     * Destroys the given virtual machine and releases any associated memory. Once
     * finalized, the VM should not be used.
     */
    static VALUE
    static_api_finalize( VALUE module, VALUE vm )
    {
      sqlite_vm *vm_ptr;
      int        result;
      char      *errmsg;

      /* FIXME: should this be executed atomically? */
      GetVM( vm_ptr, vm );

      result = sqlite_finalize( vm_ptr, &errmsg );
      if( result != SQLITE_OK )
      {
        static_raise_db_error2( result, &errmsg );
        /* "raise" does not return */
      }

      /* don't need to free the handle anymore */
      RDATA(vm)->dfree = NULL;
      RDATA(vm)->data = NULL;

      return Qnil;
    }

function_type( db, name, type ) → nil

Allows you to specify the type of the data that the named function returns. If type is SQLite::API::NUMERIC, then the function is expected to return a numeric value. If it is SQLite::API::TEXT, then the function is expected to return a textual value. If it is SQLite::API::ARGS, then the function returns whatever its arguments are. And if it is a positive (or zero) integer, then the function returns whatever type the argument at that position is.

[ show source ]

    /**
     * call-seq:
     *     function_type( db, name, type ) -> nil
     *
     * Allows you to specify the type of the data that the named function returns. If
     * type is SQLite::API::NUMERIC, then the function is expected to return a numeric
     * value. If it is SQLite::API::TEXT, then the function is expected to return a
     * textual value. If it is SQLite::API::ARGS, then the function returns whatever its
     * arguments are. And if it is a positive (or zero) integer, then the function
     * returns whatever type the argument at that position is.
     */
    static VALUE
    static_api_function_type( VALUE module, VALUE db, VALUE name, VALUE type )
    {
      sqlite *handle;
      int     result;

      GetDB( handle, db );
      Check_Type( name, T_STRING );
      Check_Type( type, T_FIXNUM );

      result = sqlite_function_type( handle,
                 StringValuePtr( name ),
                 FIX2INT( type ) );

      if( result != SQLITE_OK )
      {
        static_raise_db_error( result, "function type %s(%d)",
          StringValuePtr(name), FIX2INT(type) );
        /* "raise" does not return */
      }

      return Qnil;
    }

interrupt( db ) → nil

Interrupts the currently executing operation.

[ show source ]

    /**
     * call-seq:
     *     interrupt( db ) -> nil
     *
     * Interrupts the currently executing operation.
     */
    static VALUE
    static_api_interrupt( VALUE module, VALUE db )
    {
      sqlite *handle;

      GetDB( handle, db );
      sqlite_interrupt( handle );

      return Qnil;
    }

last_insert_row_id( db ) → fixnum

Returns the unique row ID of the last insert operation.

[ show source ]

    /**
     * call-seq:
     *     last_insert_row_id( db ) -> fixnum
     *
     * Returns the unique row ID of the last insert operation.
     */
    static VALUE
    static_api_last_insert_row_id( VALUE module, VALUE db )
    {
      sqlite *handle;

      GetDB( handle, db );

      return INT2FIX( sqlite_last_insert_rowid( handle ) );
    }

open( file_name, mode ) → db

Open the named database file. Returns the opaque handle.

[ show source ]

    /**
     * call-seq:
     *     open( file_name, mode ) -> db
     *
     * Open the named database file. Returns the opaque handle.
     */
    static VALUE
    static_api_open( VALUE module, VALUE file_name, VALUE mode )
    {
      char   *s_file_name;
      char   *errmsg;
      int     i_mode;
      sqlite *db;

      Check_Type( file_name, T_STRING );
      Check_Type( mode,      T_FIXNUM );

      s_file_name = STR2CSTR( file_name );
      i_mode      = FIX2INT( mode );

      db = sqlite_open( s_file_name, i_mode, &errmsg );
      if( db == NULL )
      {
        static_raise_db_error2( -1, &errmsg );
        /* "raise" does not return */
      }

      return Data_Wrap_Struct( rb_cData, NULL, sqlite_close, db );
    }

set_result( func, result ) → result

Sets the result of the given function to the given value. This is typically called in the callback function for create_function or the finalize callback in create_aggregate. The result must be either a string, an integer, or a double.

The `func` parameter must be the opaque function handle as given to the callback functions mentioned above.

[ show source ]

    /**
     * call-seq:
     *     set_result( func, result ) -> result
     *
     * Sets the result of the given function to the given value. This is typically
     * called in the callback function for #create_function or the finalize
     * callback in #create_aggregate. The result must be either a string, an integer,
     * or a double.
     *
     * The +func+ parameter must be the opaque function handle as given to the
     * callback functions mentioned above.
     */
    static VALUE
    static_api_set_result( VALUE module, VALUE func, VALUE result )
    {
      sqlite_func *func_ptr;

      GetFunc( func_ptr, func );
      switch( TYPE(result) )
      {
        case T_STRING:
          sqlite_set_result_string( func_ptr,
            RSTRING(result)->ptr,
            RSTRING(result)->len );
          break;

        case T_FIXNUM:
          sqlite_set_result_int( func_ptr, FIX2INT(result) );
          break;

        case T_FLOAT:
          sqlite_set_result_double( func_ptr, NUM2DBL(result) );
          break;

        default:
          static_raise_db_error( -1, "bad type in set result (%d)",
            TYPE(result) );
      }

      return result;
    }

set_result_error( func, string ) → string

Sets the result of the given function to be the error message given in the `string` parameter. The `func` parameter must be an opaque function handle as given to the callback function for create_function or create_aggregate.

[ show source ]

    /**
     * call-seq:
     *     set_result_error( func, string ) -> string
     *
     * Sets the result of the given function to be the error message given in the
     * +string+ parameter. The +func+ parameter must be an opaque function handle
     * as given to the callback function for #create_function or
     * #create_aggregate.
     */
    static VALUE
    static_api_set_result_error( VALUE module, VALUE func, VALUE string )
    {
      sqlite_func *func_ptr;

      GetFunc( func_ptr, func );
      Check_Type( string, T_STRING );

      sqlite_set_result_error( func_ptr, RSTRING(string)->ptr,
        RSTRING(string)->len );

      return string;
    }

step( vm ) → hash | nil

Steps through a single result for the given virtual machine. Returns a Hash object. If there was a valid row returned, the hash will contain a `:row` key, which maps to an array of values for that row. In addition, the hash will (nearly) always contain a `:columns` key (naming the columns in the result) and a `:types` key (giving the data types for each column).

This will return `nil` if there was an error previously.

[ show source ]

    /**
     * call-seq:
     *     step( vm ) -> hash | nil
     *
     * Steps through a single result for the given virtual machine. Returns a
     * Hash object. If there was a valid row returned, the hash will contain
     * a <tt>:row</tt> key, which maps to an array of values for that row.
     * In addition, the hash will (nearly) always contain a <tt>:columns</tt>
     * key (naming the columns in the result) and a <tt>:types</tt> key
     * (giving the data types for each column).
     *
     * This will return +nil+ if there was an error previously.
     */
    static VALUE
    static_api_step( VALUE module, VALUE vm )
    {
      sqlite_vm   *vm_ptr;
      const char **values;
      const char **metadata;
      int          columns;
      int          result;
      int          index;
      VALUE        hash;
      VALUE        value;

      GetVM( vm_ptr, vm );
      hash = rb_hash_new();

      result = sqlite_step( vm_ptr,
                            &columns,
                            &values,
                            &metadata );

      switch( result )
      {
        case SQLITE_BUSY:
          static_raise_db_error( result, "busy in step" );

        case SQLITE_ROW:
          value = rb_ary_new2( columns );
          for( index = 0; index < columns; index++ )
          {
            VALUE entry = Qnil;

            if( values[index] != NULL )
              entry = rb_str_new2( values[index] );

            rb_ary_store( value, index, entry  );
          }
          rb_hash_aset( hash, ID2SYM(idRow), value );

        case SQLITE_DONE:
          value = rb_ivar_get( vm, idColumns );

          if( value == Qnil )
          {
            value = rb_ary_new2( columns );
            for( index = 0; index < columns; index++ )
            {
              rb_ary_store( value, index, rb_str_new2( metadata[ index ] ) );
            }
            rb_ivar_set( vm, idColumns, value );
          }

          rb_hash_aset( hash, ID2SYM(idColumns), value );

          value = rb_ivar_get( vm, idTypes );

          if( value == Qnil )
          {
            value = rb_ary_new2( columns );
            for( index = 0; index < columns; index++ )
            {
              VALUE item = Qnil;
              if( metadata[ index+columns ] )
                item = rb_str_new2( metadata[ index+columns ] );
              rb_ary_store( value, index, item );
            }
            rb_ivar_set( vm, idTypes, value );
          }

          rb_hash_aset( hash, ID2SYM(idTypes), value );
          break;

        case SQLITE_ERROR:
        case SQLITE_MISUSE:
          {
            char *msg = NULL;
            sqlite_finalize( vm_ptr, &msg );
            RDATA(vm)->dfree = NULL;
            RDATA(vm)->data = NULL;
            static_raise_db_error2( result, &msg );
          }
          /* "raise" doesn't return */

        default:
          static_raise_db_error( -1, "[BUG] unknown result %d from sqlite_step",
            result );
          /* "raise" doesn't return */
      }

      return hash;
    }

[Validate]