The Database class encapsulates a single connection to a SQLite3 database. Its usage is very straightforward:
require 'sqlite3' db = SQLite3::Database.new( "data.db" ) db.execute( "select * from table" ) do |row| p row end db.close
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.
- authorizer
- busy_handler
- busy_timeout
- changes
- close
- closed?
- commit
- complete?
- create_aggregate
- create_aggregate_handler
- create_function
- errcode
- errmsg
- execute
- execute2
- execute_batch
- get_first_row
- get_first_value
- interrupt
- last_insert_row_id
- new
- prepare
- query
- quote
- rollback
- total_changes
- trace
- transaction
- transaction_active?
- translator
[R] | driver | A reference to the underlying SQLite3 driver used by this database. |
[R] | handle | The low-level opaque database handle that this object wraps. |
[RW] | results_as_hash | A boolean that indicates whether rows in result sets should be returned as hashes or not. By default, rows are returned as arrays. |
[RW] | type_translation | A boolean indicating whether or not type translation is enabled for this database. |
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 (results_as_hash) and has type translation disabled (type_translation=).
[ show source ]
# File lib/sqlite3/database.rb, line 72 72: def initialize( file_name, options={} ) 73: utf16 = options.fetch(:utf16, false) 74: load_driver( options[:driver] ) 75: 76: @statement_factory = options[:statement_factory] || Statement 77: 78: result, @handle = @driver.open( file_name, utf16 ) 79: Error.check( result, self, "could not open database" ) 80: 81: @closed = false 82: @results_as_hash = options.fetch(:results_as_hash,false) 83: @type_translation = options.fetch(:type_translation,false) 84: @translator = nil 85: @transaction_active = false 86: end
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.
[ show source ]
# File lib/sqlite3/database.rb, line 47 47: def quote( string ) 48: string.gsub( /'/, "''" ) 49: end
Installs (or removes) a block that will be invoked for every access to the database. If the block returns 0 (or nil), the statement is allowed to proceed. Returning 1 causes an authorization error to occur, and returning 2 causes the access to be silently denied.
[ show source ]
# File lib/sqlite3/database.rb, line 143 143: def authorizer( data=nil, &block ) 144: result = @driver.set_authorizer( @handle, data, &block ) 145: Error.check( result, self ) 146: 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 busy_timeout.
[ show source ]
# File lib/sqlite3/database.rb, line 309 309: def busy_handler( data=nil, &block ) # :yields: data, retries 310: result = @driver.busy_handler( @handle, data, &block ) 311: Error.check( result, self ) 312: end
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 busy_handler.
[ show source ]
# File lib/sqlite3/database.rb, line 321 321: def busy_timeout( ms ) 322: result = @driver.busy_timeout( @handle, ms ) 323: Error.check( result, self ) 324: end
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.
[ show source ]
# File lib/sqlite3/database.rb, line 285 285: def changes 286: @driver.changes( @handle ) 287: end
Closes this database.
[ show source ]
# File lib/sqlite3/database.rb, line 118 118: def close 119: unless @closed 120: result = @driver.close( @handle ) 121: Error.check( result, self ) 122: end 123: @closed = true 124: end
Returns true if this database instance has been closed (see close).
[ show source ]
# File lib/sqlite3/database.rb, line 127 127: def closed? 128: @closed 129: end
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.
[ show source ]
# File lib/sqlite3/database.rb, line 580 580: def commit 581: execute "commit transaction" 582: @transaction_active = false 583: true 584: end
Return true if the string is a valid (ie, parsable) SQL statement, and false otherwise. If +utf16+ is true, then the string is a UTF-16 character string.
[ show source ]
# File lib/sqlite3/database.rb, line 91 91: def complete?( string, utf16=false ) 92: @driver.complete?( string, utf16 ) 93: end
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 create_aggregate_handler for a more object-oriented approach to aggregate functions.
[ show source ]
# File lib/sqlite3/database.rb, line 405 405: def create_aggregate( name, arity, step=nil, finalize=nil, 406: text_rep=Constants::TextRep::ANY, &block ) 407: # begin 408: if block 409: proxy = AggregateDefinitionProxy.new 410: proxy.instance_eval(&block) 411: step ||= proxy.step_callback 412: finalize ||= proxy.finalize_callback 413: end 414: 415: step_callback = proc do |func,*args| 416: ctx = @driver.aggregate_context( func ) 417: unless ctx[:__error] 418: begin 419: step.call( FunctionProxy.new( @driver, func, ctx ), 420: *args.map{|v| Value.new(self,v)} ) 421: rescue Exception => e 422: ctx[:__error] = e 423: end 424: end 425: end 426: 427: finalize_callback = proc do |func| 428: ctx = @driver.aggregate_context( func ) 429: unless ctx[:__error] 430: begin 431: finalize.call( FunctionProxy.new( @driver, func, ctx ) ) 432: rescue Exception => e 433: @driver.result_error( func, 434: "#{e.message} (#{e.class})", -1 ) 435: end 436: else 437: e = ctx[:__error] 438: @driver.result_error( func, 439: "#{e.message} (#{e.class})", -1 ) 440: end 441: end 442: 443: result = @driver.create_function( @handle, name, arity, text_rep, nil, 444: nil, step_callback, finalize_callback ) 445: Error.check( result, self ) 446: 447: self 448: end
This is another approach to creating an aggregate function (see create_aggregate). 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 create_aggregate. 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 create_aggregate. |
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 create_aggregate. |
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" )
[ show source ]
# File lib/sqlite3/database.rb, line 496 496: def create_aggregate_handler( handler ) 497: arity = -1 498: text_rep = Constants::TextRep::ANY 499: 500: arity = handler.arity if handler.respond_to?(:arity) 501: text_rep = handler.text_rep if handler.respond_to?(:text_rep) 502: name = handler.name 503: 504: step = proc do |func,*args| 505: ctx = @driver.aggregate_context( func ) 506: unless ctx[ :__error ] 507: ctx[ :handler ] ||= handler.new 508: begin 509: ctx[ :handler ].step( FunctionProxy.new( @driver, func, ctx ), 510: *args.map{|v| Value.new(self,v)} ) 511: rescue Exception, StandardError => e 512: ctx[ :__error ] = e 513: end 514: end 515: end 516: 517: finalize = proc do |func| 518: ctx = @driver.aggregate_context( func ) 519: unless ctx[ :__error ] 520: ctx[ :handler ] ||= handler.new 521: begin 522: ctx[ :handler ].finalize( FunctionProxy.new( @driver, func, ctx ) ) 523: rescue Exception => e 524: ctx[ :__error ] = e 525: end 526: end 527: 528: if ctx[ :__error ] 529: e = ctx[ :__error ] 530: @driver.sqlite3_result_error( func, "#{e.message} (#{e.class})", -1 ) 531: end 532: end 533: 534: result = @driver.create_function( @handle, name, arity, text_rep, nil, 535: nil, step, finalize ) 536: Error.check( result, self ) 537: 538: self 539: 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" )
[ show source ]
# File lib/sqlite3/database.rb, line 349 349: def create_function( name, arity, text_rep=Constants::TextRep::ANY, 350: &block ) # :yields: func, *args 351: # begin 352: callback = proc do |func,*args| 353: begin 354: block.call( FunctionProxy.new( @driver, func ), 355: *args.map{|v| Value.new(self,v)} ) 356: rescue StandardError, Exception => e 357: @driver.result_error( func, 358: "#{e.message} (#{e.class})", -1 ) 359: end 360: end 361: 362: result = @driver.create_function( @handle, name, arity, text_rep, nil, 363: callback, nil, nil ) 364: Error.check( result, self ) 365: 366: self 367: end
Return an integer representing the last error to have occurred with this database.
[ show source ]
# File lib/sqlite3/database.rb, line 103 103: def errcode 104: @driver.errcode( @handle ) 105: end
Return a string describing the last error to have occurred with this database.
[ show source ]
# File lib/sqlite3/database.rb, line 97 97: def errmsg( utf16=false ) 98: @driver.errmsg( @handle, utf16 ) 99: end
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 execute2, query, and execute_batch for additional ways of executing statements.
[ show source ]
# File lib/sqlite3/database.rb, line 180 180: def execute( sql, *bind_vars ) 181: prepare( sql ) do |stmt| 182: result = stmt.execute( *bind_vars ) 183: if block_given? 184: result.each { |row| yield row } 185: else 186: return result.inject( [] ) { |arr,row| arr << row; arr } 187: end 188: end 189: end
Executes the given SQL statement, exactly as with execute. 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 execute, query, and execute_batch for additional ways of executing statements.
[ show source ]
# File lib/sqlite3/database.rb, line 201 201: def execute2( sql, *bind_vars ) 202: prepare( sql ) do |stmt| 203: result = stmt.execute( *bind_vars ) 204: if block_given? 205: yield result.columns 206: result.each { |row| yield row } 207: else 208: return result.inject( [ result.columns ] ) { |arr,row| 209: arr << row; arr } 210: end 211: end 212: 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.
[ show source ]
# File lib/sqlite3/database.rb, line 222 222: def execute_batch( sql, *bind_vars ) 223: sql = sql.strip 224: until sql.empty? do 225: prepare( sql ) do |stmt| 226: stmt.execute( *bind_vars ) 227: sql = stmt.remainder.strip 228: end 229: end 230: nil 231: end
A convenience method for obtaining the first row of a result set, and discarding all others. It is otherwise identical to execute.
See also get_first_value.
[ show source ]
# File lib/sqlite3/database.rb, line 261 261: def get_first_row( sql, *bind_vars ) 262: execute( sql, *bind_vars ) { |row| return row } 263: nil 264: 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 execute.
See also get_first_row.
[ show source ]
# File lib/sqlite3/database.rb, line 271 271: def get_first_value( sql, *bind_vars ) 272: execute( sql, *bind_vars ) { |row| return row[0] } 273: nil 274: end
Interrupts the currently executing operation, causing it to abort.
[ show source ]
# File lib/sqlite3/database.rb, line 296 296: def interrupt 297: @driver.interrupt( @handle ) 298: end
Obtains the unique row ID of the last row to be inserted by this Database instance.
[ show source ]
# File lib/sqlite3/database.rb, line 278 278: def last_insert_row_id 279: @driver.last_insert_rowid( @handle ) 280: end
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.
[ show source ]
# File lib/sqlite3/database.rb, line 153 153: def prepare( sql ) 154: stmt = @statement_factory.new( self, sql ) 155: if block_given? 156: begin 157: yield stmt 158: ensure 159: stmt.close 160: end 161: else 162: return stmt 163: end 164: 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.
[ show source ]
# File lib/sqlite3/database.rb, line 244 244: def query( sql, *bind_vars ) 245: result = prepare( sql ).execute( *bind_vars ) 246: if block_given? 247: begin 248: yield result 249: ensure 250: result.close 251: end 252: else 253: return result 254: end 255: 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.
[ show source ]
# File lib/sqlite3/database.rb, line 590 590: def rollback 591: execute "rollback transaction" 592: @transaction_active = false 593: true 594: end
Returns the total number of changes made to this database instance since it was opened.
[ show source ]
# File lib/sqlite3/database.rb, line 291 291: def total_changes 292: @driver.total_changes( @handle ) 293: end
Installs (or removes) a block that will be invoked for every SQL statement executed. The block receives a two parameters: the data argument, and the SQL statement executed. If the block is nil, any existing tracer will be uninstalled.
[ show source ]
# File lib/sqlite3/database.rb, line 135 135: def trace( data=nil, &block ) 136: @driver.trace( @handle, data, &block ) 137: end
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, commit and rollback 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 commit, or by calling rollback.
[ show source ]
# File lib/sqlite3/database.rb, line 557 557: def transaction( mode = :deferred ) 558: execute "begin #{mode.to_s} transaction" 559: @transaction_active = true 560: 561: if block_given? 562: abort = false 563: begin 564: yield self 565: rescue ::Object 566: abort = true 567: raise 568: ensure 569: abort and rollback or commit 570: end 571: end 572: 573: true 574: end
Returns true if there is a transaction active, and false otherwise.
[ show source ]
# File lib/sqlite3/database.rb, line 597 597: def transaction_active? 598: @transaction_active 599: 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.)
[ show source ]
# File lib/sqlite3/database.rb, line 113 113: def translator 114: @translator ||= Translator.new 115: end