Module: SQLite::API

Defined in:
ext/sqlite-api.c

Constant Summary collapse

VERSION =
rb_str_new2( sqlite_libversion() )
ENCODING =
rb_str_new2( sqlite_libencoding() )
NUMERIC =
INT2FIX( SQLITE_NUMERIC )
TEXT =
INT2FIX( SQLITE_TEXT )
ARGS =
INT2FIX( SQLITE_ARGS )

Class Method Summary collapse

Class Method Details

.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.

Returns:

  • (Hash)


858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# File 'ext/sqlite-api.c', line 858

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.

Returns:

  • (Fixnum)


888
889
890
891
892
893
894
895
# File 'ext/sqlite-api.c', line 888

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.

Returns:

  • (nil)


584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'ext/sqlite-api.c', line 584

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.

Returns:

  • (nil)


615
616
617
618
619
620
621
622
623
624
625
626
# File 'ext/sqlite-api.c', line 615

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.)

Returns:

  • (Fixnum)


528
529
530
531
532
533
534
535
536
# File 'ext/sqlite-api.c', line 528

static VALUE
static_api_changes( VALUE module, VALUE db )
{
  sqlite *handle;

  GetDB( handle, db );

  return INT2FIX( sqlite_changes( handle ) );
}

.close(db) ⇒ Object

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



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'ext/sqlite-api.c', line 311

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) ⇒ Array

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.

Returns:

  • (Array)


336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'ext/sqlite-api.c', line 336

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) ⇒ Object

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



562
563
564
565
566
567
# File 'ext/sqlite-api.c', line 562

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.

Returns:

  • (nil)


704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'ext/sqlite-api.c', line 704

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.

Returns:

  • (nil)


645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'ext/sqlite-api.c', line 645

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.

Returns:

  • (nil)


479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'ext/sqlite-api.c', line 479

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.

Returns:

  • (nil)


755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'ext/sqlite-api.c', line 755

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.

Returns:

  • (nil)


544
545
546
547
548
549
550
551
552
553
# File 'ext/sqlite-api.c', line 544

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.

Returns:

  • (Fixnum)


509
510
511
512
513
514
515
516
517
# File 'ext/sqlite-api.c', line 509

static VALUE
static_api_last_insert_row_id( VALUE module, VALUE db )
{
  sqlite *handle;

  GetDB( handle, db );

  return INT2FIX( sqlite_last_insert_rowid( handle ) );
}

.openObject

.set_result(func, result) ⇒ Object

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.



791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
# File 'ext/sqlite-api.c', line 791

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.

Returns:

  • (String)


830
831
832
833
834
835
836
837
838
839
840
841
842
# File 'ext/sqlite-api.c', line 830

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) ⇒ Object

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.



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'ext/sqlite-api.c', line 381

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;
}