Object
The Database class encapsulates a single connection to a SQLite3 database. Its usage is very straightforward:
require 'sqlite3' SQLite3::Database.new( "data.db" ) do |db| db.execute( "select * from table" ) do |row| p row end end
It wraps the lower-level methods provides by the selected driver, and includes the Pragmas module for access to various pragma convenience methods.
The Database class provides type translation services as well, by which the SQLite3 data types (which are all represented as strings) may be converted into their corresponding types (as defined in the schemas for their tables). This translation only occurs when querying data from the database—insertions and updates are all still typeless.
Furthermore, the Database class has been designed to work well with the ArrayFields module from Ara Howard. If you require the ArrayFields module before performing a query, and if you have not enabled results as hashes, then the results will all be indexible by field name.
# File lib/sqlite3/database.rb, line 368 368: def self.finalize( &block ) 369: define_method(:finalize, &block) 370: end
# File lib/sqlite3/database.rb, line 446 446: def initialize handler 447: @handler = handler 448: @fp = FunctionProxy.new 449: end
Create a new Database object that opens the given file. If utf16 is true, the filename is interpreted as a UTF-16 encoded string.
By default, the new database will return result rows as arrays (#) and has type translation disabled (#).
static VALUE initialize(int argc, VALUE *argv, VALUE self) { sqlite3RubyPtr ctx; VALUE file; VALUE opts; VALUE zvfs; int status; Data_Get_Struct(self, sqlite3Ruby, ctx); rb_scan_args(argc, argv, "12", &file, &opts, &zvfs); if(NIL_P(opts)) opts = rb_hash_new(); #ifdef HAVE_RUBY_ENCODING_H if(UTF16_LE_P(file)) { status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); } else { #endif if(Qtrue == rb_hash_aref(opts, sym_utf16)) { status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); } else { #ifdef HAVE_RUBY_ENCODING_H if(!UTF8_P(file)) { file = rb_str_export_to_enc(file, rb_utf8_encoding()); } #endif status = sqlite3_open_v2( StringValuePtr(file), &ctx->db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NIL_P(zvfs) ? NULL : StringValuePtr(zvfs) ); } #ifdef HAVE_RUBY_ENCODING_H } #endif CHECK(ctx->db, status) rb_iv_set(self, "@tracefunc", Qnil); rb_iv_set(self, "@authorizer", Qnil); rb_iv_set(self, "@encoding", Qnil); rb_iv_set(self, "@busy_handler", Qnil); rb_iv_set(self, "@collations", rb_hash_new()); rb_iv_set(self, "@results_as_hash", rb_hash_aref(opts, sym_results_as_hash)); rb_iv_set(self, "@type_translation", rb_hash_aref(opts, sym_type_translation)); if(rb_block_given_p()) { rb_yield(self); rb_funcall(self, rb_intern("close"), 0); } return self; }
Quotes the given string, making it safe to use in an SQL statement. It replaces all instances of the single-quote character with two single-quote characters. The modified string is returned.
# File lib/sqlite3/database.rb, line 47 47: def quote( string ) 48: string.gsub( /'/, "''" ) 49: end
Register a busy handler with this database instance. When a requested resource is busy, this handler will be invoked. If the handler returns false, the operation will be aborted; otherwise, the resource will be requested again.
The handler will be invoked with the name of the resource that was busy, and the number of times it has been retried.
See also the mutually exclusive #.
static VALUE busy_handler(int argc, VALUE *argv, VALUE self) { sqlite3RubyPtr ctx; VALUE block; int status; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); rb_scan_args(argc, argv, "01", &block); if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); rb_iv_set(self, "@busy_handler", block); status = sqlite3_busy_handler( ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)self); CHECK(ctx->db, status); return self; }
Indicates that if a request for a resource terminates because that resource is busy, SQLite should sleep and retry for up to the indicated number of milliseconds. By default, SQLite does not retry busy resources. To restore the default behavior, send 0 as the ms parameter.
See also the mutually exclusive #.
static VALUE set_busy_timeout(VALUE self, VALUE timeout) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout))); return self; }
Returns the number of changes made to this database instance by the last operation performed. Note that a “delete from table” without a where clause will not affect this value.
static VALUE changes(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM(sqlite3_changes(ctx->db)); }
Closes this database.
static VALUE sqlite3_rb_close(VALUE self) { sqlite3RubyPtr ctx; sqlite3 * db; Data_Get_Struct(self, sqlite3Ruby, ctx); db = ctx->db; CHECK(db, sqlite3_close(ctx->db)); ctx->db = NULL; return self; }
Returns true if this database instance has been closed (see #).
static VALUE closed_p(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); if(!ctx->db) return Qtrue; return Qfalse; }
Add a collation with name name, and a comparator object. The comparator object should implement a method called “compare” that takes two parameters and returns an integer less than, equal to, or greater than 0.
static VALUE collation(VALUE self, VALUE name, VALUE comparator) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_create_collation_v2( ctx->db, StringValuePtr(name), SQLITE_UTF8, (void *)comparator, NIL_P(comparator) ? NULL : rb_comparator_func, NULL)); /* Make sure our comparator doesn't get garbage collected. */ rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator); return self; }
Commits the current transaction. If there is no current transaction, this will cause an error to be raised. This returns true, in order to allow it to be used in idioms like abort? and rollback or commit.
# File lib/sqlite3/database.rb, line 503 503: def commit 504: execute "commit transaction" 505: @transaction_active = false 506: true 507: end
Return true if the string is a valid (ie, parsable) SQL statement, and false otherwise.
static VALUE complete_p(VALUE UNUSED(self), VALUE sql) { if(sqlite3_complete(StringValuePtr(sql))) return Qtrue; return Qfalse; }
Creates a new aggregate function for use in SQL statements. Aggregate functions are functions that apply over every row in the result set, instead of over just a single row. (A very common aggregate function is the “count” function, for determining the number of rows that match a query.)
The new function will be added as name, with the given arity. (For variable arity functions, use -1 for the arity.)
The step parameter must be a proc object that accepts as its first parameter a FunctionProxy instance (representing the function invocation), with any subsequent parameters (up to the function’s arity). The step callback will be invoked once for each row of the result set.
The finalize parameter must be a proc object that accepts only a single parameter, the FunctionProxy instance representing the current function invocation. It should invoke FunctionProxy#set_result to store the result of the function.
Example:
db.create_aggregate( "lengths", 1 ) do step do |func, value| func[ :total ] ||= 0 func[ :total ] += ( value ? value.length : 0 ) end finalize do |func| func.set_result( func[ :total ] || 0 ) end end puts db.get_first_value( "select lengths(name) from table" )
See also # for a more object-oriented approach to aggregate functions.
# File lib/sqlite3/database.rb, line 360 360: def create_aggregate( name, arity, step=nil, finalize=nil, 361: text_rep=Constants::TextRep::ANY, &block ) 362: 363: factory = Class.new do 364: def self.step( &block ) 365: define_method(:step, &block) 366: end 367: 368: def self.finalize( &block ) 369: define_method(:finalize, &block) 370: end 371: end 372: 373: if block_given? 374: factory.instance_eval(&block) 375: else 376: factory.class_eval do 377: define_method(:step, step) 378: define_method(:finalize, finalize) 379: end 380: end 381: 382: proxy = factory.new 383: proxy.extend(Module.new { 384: attr_accessor :ctx 385: 386: def step( *args ) 387: super(@ctx, *args) 388: end 389: 390: def finalize 391: super(@ctx) 392: end 393: }) 394: proxy.ctx = FunctionProxy.new 395: define_aggregator(name, proxy) 396: end
This is another approach to creating an aggregate function (see #). Instead of explicitly specifying the name, callbacks, arity, and type, you specify a factory object (the “handler”) that knows how to obtain all of that information. The handler should respond to the following messages:
arity | corresponds to the arity parameter of #. This message is optional, and if the handler does not respond to it, the function will have an arity of -1. |
name | this is the name of the function. The handler must implement this message. |
new | this must be implemented by the handler. It should return a new instance of the object that will handle a specific invocation of the function. |
The handler instance (the object returned by the new message, described above), must respond to the following messages:
step | this is the method that will be called for each step of the aggregate function’s evaluation. It should implement the same signature as the step callback for #. |
finalize | this is the method that will be called to finalize the aggregate function’s evaluation. It should implement the same signature as the finalize callback for #. |
Example:
class LengthsAggregateHandler def self.arity; 1; end def initialize @total = 0 end def step( ctx, name ) @total += ( name ? name.length : 0 ) end def finalize( ctx ) ctx.set_result( @total ) end end db.create_aggregate_handler( LengthsAggregateHandler ) puts db.get_first_value( "select lengths(name) from A" )
# File lib/sqlite3/database.rb, line 444 444: def create_aggregate_handler( handler ) 445: proxy = Class.new do 446: def initialize handler 447: @handler = handler 448: @fp = FunctionProxy.new 449: end 450: 451: def step( *args ) 452: @handler.step(@fp, *args) 453: end 454: 455: def finalize 456: @handler.finalize @fp 457: @fp.result 458: end 459: end 460: define_aggregator(handler.name, proxy.new(handler.new)) 461: self 462: end
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" )
# File lib/sqlite3/database.rb, line 315 315: def create_function name, arity, text_rep=Constants::TextRep::ANY, &block 316: define_function(name) do |*args| 317: fp = FunctionProxy.new 318: block.call(fp, *args) 319: fp.result 320: end 321: self 322: end
Define an aggregate function named name using the object aggregator. aggregator must respond to step and finalize. step will be called with row information and finalize must return the return value for the aggregator function.
static VALUE define_aggregator(VALUE self, VALUE name, VALUE aggregator) { sqlite3RubyPtr ctx; int arity, status; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); arity = sqlite3_obj_method_arity(aggregator, rb_intern("step")); status = sqlite3_create_function( ctx->db, StringValuePtr(name), arity, SQLITE_UTF8, (void *)aggregator, NULL, rb_sqlite3_step, rb_sqlite3_final ); rb_iv_set(self, "@agregator", aggregator); CHECK(ctx->db, status); return self; }
Define a function named name with args. The arity of the block will be used as the arity for the function defined.
static VALUE define_function(VALUE self, VALUE name) { sqlite3RubyPtr ctx; VALUE block; int status; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); block = rb_block_proc(); status = sqlite3_create_function( ctx->db, StringValuePtr(name), rb_proc_arity(block), SQLITE_UTF8, (void *)block, rb_sqlite3_func, NULL, NULL ); CHECK(ctx->db, status); return self; }
Enable or disable extension loading.
static VALUE enable_load_extension(VALUE self, VALUE onoff) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, (int)NUM2INT(onoff))); return self; }
Fetch the encoding set on this database
static VALUE db_encoding(VALUE self) { sqlite3RubyPtr ctx; VALUE enc; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); enc = rb_iv_get(self, "@encoding"); if(NIL_P(enc)) { sqlite3_exec(ctx->db, "PRAGMA encoding", enc_cb, (void *)self, NULL); } return rb_iv_get(self, "@encoding"); }
Return an integer representing the last error to have occurred with this database.
static VALUE errcode_(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM((long)sqlite3_errcode(ctx->db)); }
Return a string describing the last error to have occurred with this database.
static VALUE errmsg(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); return rb_str_new2(sqlite3_errmsg(ctx->db)); }
Executes the given SQL statement. If additional parameters are given, they are treated as bind variables, and are bound to the placeholders in the query.
Note that if any of the values passed to this are hashes, then the key/value pairs are each bound separately, with the key being used as the name of the placeholder to bind the value to.
The block is optional. If given, it will be invoked for each row returned by the query. Otherwise, any results are accumulated into an array and returned wholesale.
See also #, #, and # for additional ways of executing statements.
# File lib/sqlite3/database.rb, line 109 109: def execute sql, bind_vars = [], *args, &block 110: # FIXME: This is a terrible hack and should be removed but is required 111: # for older versions of rails 112: hack = Object.const_defined?(:ActiveRecord) && sql =~ /^PRAGMA index_list/ 113: 114: if bind_vars.nil? || !args.empty? 115: if args.empty? 116: bind_vars = [] 117: else 118: bind_vars = [nil] + args 119: end 120: 121: warn(#{caller[0]} is calling SQLite3::Database#execute with nil or multiple bind paramswithout using an array. Please switch to passing bind parameters as an array.) if $VERBOSE 122: end 123: 124: prepare( sql ) do |stmt| 125: stmt.bind_params(bind_vars) 126: if type_translation 127: stmt = ResultSet.new(self, stmt).to_a 128: end 129: 130: if block_given? 131: stmt.each do |row| 132: if @results_as_hash 133: h = Hash[*stmt.columns.zip(row).flatten] 134: row.each_with_index { |r, i| h[i] = r } 135: 136: yield h 137: else 138: yield row 139: end 140: end 141: else 142: if @results_as_hash 143: stmt.map { |row| 144: h = Hash[*stmt.columns.zip(row).flatten] 145: row.each_with_index { |r, i| h[i] = r } 146: 147: # FIXME UGH TERRIBLE HACK! 148: h['unique'] = h['unique'].to_s if hack 149: 150: h 151: } 152: else 153: stmt.to_a 154: end 155: end 156: end 157: end
Executes the given SQL statement, exactly as with #. However, the first row returned (either via the block, or in the returned array) is always the names of the columns. Subsequent rows correspond to the data from the result set.
Thus, even if the query itself returns no rows, this method will always return at least one row—the names of the columns.
See also #, #, and # for additional ways of executing statements.
# File lib/sqlite3/database.rb, line 172 172: def execute2( sql, *bind_vars ) 173: prepare( sql ) do |stmt| 174: result = stmt.execute( *bind_vars ) 175: if block_given? 176: yield stmt.columns 177: result.each { |row| yield row } 178: else 179: return result.inject( [ stmt.columns ] ) { |arr,row| 180: arr << row; arr } 181: end 182: end 183: end
Executes all SQL statements in the given string. By contrast, the other means of executing queries will only execute the first statement in the string, ignoring all subsequent statements. This will execute each one in turn. The same bind parameters, if given, will be applied to each statement.
This always returns nil, making it unsuitable for queries that return rows.
# File lib/sqlite3/database.rb, line 193 193: def execute_batch( sql, bind_vars = [], *args ) 194: # FIXME: remove this stuff later 195: unless [Array, Hash].include?(bind_vars.class) 196: bind_vars = [bind_vars] 197: warn(#{caller[0]} is calling SQLite3::Database#execute_batch with bind parametersthat are not a list of a hash. Please switch to passing bind parameters as anarray or hash.) if $VERBOSE 198: end 199: 200: # FIXME: remove this stuff later 201: if bind_vars.nil? || !args.empty? 202: if args.empty? 203: bind_vars = [] 204: else 205: bind_vars = [nil] + args 206: end 207: 208: warn(#{caller[0]} is calling SQLite3::Database#execute_batch with nil or multiple bind paramswithout using an array. Please switch to passing bind parameters as an array.) if $VERBOSE 209: end 210: 211: sql = sql.strip 212: until sql.empty? do 213: prepare( sql ) do |stmt| 214: # FIXME: this should probably use sqlite3's api for batch execution 215: # This implementation requires stepping over the results. 216: if bind_vars.length == stmt.bind_parameter_count 217: stmt.bind_params(bind_vars) 218: end 219: stmt.step 220: sql = stmt.remainder.strip 221: end 222: end 223: nil 224: end
# File lib/sqlite3/database.rb, line 455 455: def finalize 456: @handler.finalize @fp 457: @fp.result 458: end
# File lib/sqlite3/database.rb, line 390 390: def finalize 391: super(@ctx) 392: end
A convenience method for obtaining the first value of the first row of a result set, and discarding all other values and rows. It is otherwise identical to #.
See also #.
# File lib/sqlite3/database.rb, line 285 285: def get_first_value( sql, *bind_vars ) 286: execute( sql, *bind_vars ) { |row| return row[0] } 287: nil 288: end
Interrupts the currently executing operation, causing it to abort.
static VALUE interrupt(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); sqlite3_interrupt(ctx->db); return self; }
Obtains the unique row ID of the last row to be inserted by this Database instance.
static VALUE last_insert_row_id(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); return LL2NUM(sqlite3_last_insert_rowid(ctx->db)); }
Loads an SQLite extension library from the named file. Extension loading must be enabled using db.enable_load_extension(1) prior to calling this API.
static VALUE load_extension(VALUE self, VALUE file) { sqlite3RubyPtr ctx; int status; char *errMsg; VALUE errexp; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); status = sqlite3_load_extension(ctx->db, RSTRING_PTR(file), 0, &errMsg); if (status != SQLITE_OK) { errexp = rb_exc_new2(rb_eRuntimeError, errMsg); sqlite3_free(errMsg); rb_exc_raise(errexp); } return self; }
Returns a Statement object representing the given SQL. This does not execute the statement; it merely prepares the statement for execution.
The Statement can then be executed using Statement#execute.
# File lib/sqlite3/database.rb, line 84 84: def prepare sql 85: stmt = SQLite3::Statement.new( self, sql ) 86: return stmt unless block_given? 87: 88: begin 89: yield stmt 90: ensure 91: stmt.close 92: end 93: end
This is a convenience method for creating a statement, binding paramters to it, and calling execute:
result = db.query( "select * from foo where a=?", 5 ) # is the same as result = db.prepare( "select * from foo where a=?" ).execute( 5 )
You must be sure to call close on the ResultSet instance that is returned, or you could have problems with locks on the table. If called with a block, close will be invoked implicitly when the block terminates.
# File lib/sqlite3/database.rb, line 244 244: def query( sql, bind_vars = [], *args ) 245: 246: if bind_vars.nil? || !args.empty? 247: if args.empty? 248: bind_vars = [] 249: else 250: bind_vars = [nil] + args 251: end 252: 253: warn(#{caller[0]} is calling SQLite3::Database#query with nil or multiple bind paramswithout using an array. Please switch to passing bind parameters as an array.) if $VERBOSE 254: end 255: 256: result = prepare( sql ).execute( bind_vars ) 257: if block_given? 258: begin 259: yield result 260: ensure 261: result.close 262: end 263: else 264: return result 265: end 266: end
Rolls the current transaction back. If there is no current transaction, this will cause an error to be raised. This returns true, in order to allow it to be used in idioms like abort? and rollback or commit.
# File lib/sqlite3/database.rb, line 513 513: def rollback 514: execute "rollback transaction" 515: @transaction_active = false 516: true 517: end
# File lib/sqlite3/database.rb, line 386 386: def step( *args ) 387: super(@ctx, *args) 388: end
# File lib/sqlite3/database.rb, line 451 451: def step( *args ) 452: @handler.step(@fp, *args) 453: end
Returns the total number of changes made to this database instance since it was opened.
static VALUE total_changes(VALUE self) { sqlite3RubyPtr ctx; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM((long)sqlite3_total_changes(ctx->db)); }
Installs (or removes) a block that will be invoked for every SQL statement executed. The block receives one parameter: the SQL statement executed. If the block is nil, any existing tracer will be uninstalled.
static VALUE trace(int argc, VALUE *argv, VALUE self) { sqlite3RubyPtr ctx; VALUE block; Data_Get_Struct(self, sqlite3Ruby, ctx); REQUIRE_OPEN_DB(ctx); rb_scan_args(argc, argv, "01", &block); if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); rb_iv_set(self, "@tracefunc", block); sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self); return self; }
Begins a new transaction. Note that nested transactions are not allowed by SQLite, so attempting to nest a transaction will result in a runtime exception.
The mode parameter may be either :deferred (the default), :immediate, or :exclusive.
If a block is given, the database instance is yielded to it, and the transaction is committed when the block terminates. If the block raises an exception, a rollback will be performed instead. Note that if a block is given, # and # should never be called explicitly or you’ll get an error when the block terminates.
If a block is not given, it is the caller’s responsibility to end the transaction explicitly, either by calling #, or by calling #.
# File lib/sqlite3/database.rb, line 480 480: def transaction( mode = :deferred ) 481: execute "begin #{mode.to_s} transaction" 482: @transaction_active = true 483: 484: if block_given? 485: abort = false 486: begin 487: yield self 488: rescue ::Object 489: abort = true 490: raise 491: ensure 492: abort and rollback or commit 493: end 494: end 495: 496: true 497: end
Returns true if there is a transaction active, and false otherwise.
# File lib/sqlite3/database.rb, line 520 520: def transaction_active? 521: @transaction_active 522: end
Return the type translator employed by this database instance. Each database instance has its own type translator; this allows for different type handlers to be installed in each instance without affecting other instances. Furthermore, the translators are instantiated lazily, so that if a database does not use type translation, it will not be burdened by the overhead of a useless type translator. (See the Translator class.)
# File lib/sqlite3/database.rb, line 67 67: def translator 68: @translator ||= Translator.new 69: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.