Class: SQLite::Database
- Inherits:
-
Object
- Object
- SQLite::Database
- Includes:
- Pragmas
- Defined in:
- lib/sqlite/database.rb
Overview
The Database class encapsulates a single connection to a SQLite database. Its usage is very straightforward:
require 'sqlite'
db = SQLite::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 API module, include includes the Pragmas module for access to various pragma convenience methods.
The Database class provides type translation services as well, by which the SQLite 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.
Defined Under Namespace
Classes: FunctionProxy
Instance Attribute Summary collapse
-
#handle ⇒ Object
readonly
The low-level opaque database handle that this object wraps.
-
#results_as_hash ⇒ Object
A boolean that indicates whether rows in result sets should be returned as hashes or not.
Class Method Summary collapse
-
.complete?(string) ⇒ Boolean
Return
true
if the string is a valid (ie, parsable) SQL statement, andfalse
otherwise. -
.decode(string) ⇒ Object
Unserializes the object contained in the given string.
-
.encode(object) ⇒ Object
Returns a string that represents the serialization of the given object.
-
.open(file_name) ⇒ Object
Opens the database contained in the given file.
-
.quote(string) ⇒ Object
Quotes the given string, making it safe to use in an SQL statement.
Instance Method Summary collapse
-
#busy_handler(&block) ⇒ Object
Register a busy handler with this database instance.
-
#busy_timeout(ms) ⇒ Object
Indicates that if a request for a resource terminates because that resource is busy, SQLite should wait for the indicated number of milliseconds before trying again.
-
#changes ⇒ Object
Returns the number of changes made to this database instance by the last operation performed.
-
#close ⇒ Object
Closes this database.
-
#closed? ⇒ Boolean
Returns
true
if this database instance has been closed (see #close). -
#commit ⇒ Object
Commits the current transaction.
-
#create_aggregate(name, arity, step, finalize, type = nil) ⇒ Object
Creates a new aggregate function for use in SQL statements.
-
#create_aggregate_handler(handler) ⇒ Object
This is another approach to creating an aggregate function (see #create_aggregate).
-
#create_function(name, arity, type = nil, &block) ⇒ Object
Creates a new function for use in SQL statements.
-
#execute(sql, *bind_vars) ⇒ Object
Executes the given SQL statement.
-
#execute2(sql, *bind_vars) ⇒ Object
Executes the given SQL statement, exactly as with #execute.
-
#execute_batch(sql, *bind_vars) ⇒ Object
Executes all SQL statements in the given string.
-
#get_first_row(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first row of a result set, and discarding all others.
-
#get_first_value(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first value of the first row of a result set, and discarding all other values and rows.
-
#initialize(file_name, mode = 0) ⇒ Database
constructor
Create a new Database object that opens the given file.
-
#interrupt ⇒ Object
Interrupts the currently executing operation, causing it to abort.
-
#last_insert_row_id ⇒ Object
Obtains the unique row ID of the last row to be inserted by this Database instance.
-
#prepare(sql) ⇒ Object
Returns a Statement object representing the given SQL.
-
#query(sql, *bind_vars, &block) ⇒ Object
This does like #execute and #execute2 (binding variables and so forth), but instead of yielding each row from the result set, this will yield the ResultSet instance itself (q.v.).
-
#rollback ⇒ Object
Rolls the current transaction back.
-
#transaction ⇒ Object
Begins a new transaction.
-
#transaction_active? ⇒ Boolean
Returns
true
if there is a transaction active, andfalse
otherwise. -
#translator ⇒ Object
Return the type translator employed by this database instance.
-
#type_translation ⇒ Object
Returns
true
if type translation is enabled for this database, orfalse
otherwise. -
#type_translation=(mode) ⇒ Object
Enable or disable type translation for this database.
Constructor Details
#initialize(file_name, mode = 0) ⇒ Database
Create a new Database object that opens the given file. The mode parameter has no meaning yet, and may be omitted. If the file does not exist, it will be created if possible.
By default, the new database will return result rows as arrays (#results_as_hash) and has type translation disabled (#type_translation=).
116 117 118 119 120 121 122 |
# File 'lib/sqlite/database.rb', line 116 def initialize( file_name, mode=0 ) @handle = SQLite::API.open( file_name, mode ) @closed = false @results_as_hash = false @type_translation = false @translator = nil end |
Instance Attribute Details
#handle ⇒ Object (readonly)
The low-level opaque database handle that this object wraps.
104 105 106 |
# File 'lib/sqlite/database.rb', line 104 def handle @handle end |
#results_as_hash ⇒ Object
A boolean that indicates whether rows in result sets should be returned as hashes or not. By default, rows are returned as arrays.
108 109 110 |
# File 'lib/sqlite/database.rb', line 108 def results_as_hash @results_as_hash end |
Class Method Details
.complete?(string) ⇒ Boolean
Return true
if the string is a valid (ie, parsable) SQL statement, and false
otherwise.
99 100 101 |
# File 'lib/sqlite/database.rb', line 99 def self.complete?( string ) SQLite::API.complete( string ) end |
.decode(string) ⇒ Object
Unserializes the object contained in the given string. The string must be one that was returned by #encode.
93 94 95 |
# File 'lib/sqlite/database.rb', line 93 def self.decode( string ) Marshal.load( Base64.decode64( string ) ) end |
.encode(object) ⇒ Object
Returns a string that represents the serialization of the given object. The string may safely be used in an SQL statement.
87 88 89 |
# File 'lib/sqlite/database.rb', line 87 def self.encode( object ) Base64.encode64( Marshal.dump( object ) ).strip end |
.open(file_name) ⇒ Object
Opens the database contained in the given file. This just calls #new, passing 0 as the mode parameter. This returns the new Database instance.
74 75 76 |
# File 'lib/sqlite/database.rb', line 74 def self.open( file_name ) new( file_name, 0 ) end |
.quote(string) ⇒ Object
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.
81 82 83 |
# File 'lib/sqlite/database.rb', line 81 def self.quote( string ) string.gsub( /'/, "''" ) end |
Instance Method Details
#busy_handler(&block) ⇒ Object
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 #busy_timeout.
307 308 309 |
# File 'lib/sqlite/database.rb', line 307 def busy_handler( &block ) # :yields: resource, retries SQLite::API.busy_handler( @handle, block ) end |
#busy_timeout(ms) ⇒ Object
Indicates that if a request for a resource terminates because that resource is busy, SQLite should wait for the indicated number of milliseconds before trying again. By default, SQLite does not retry busy resources. To restore the default behavior, send 0 as the ms
parameter.
See also #busy_handler.
318 319 320 |
# File 'lib/sqlite/database.rb', line 318 def busy_timeout( ms ) SQLite::API.busy_timeout( @handle, ms ) end |
#changes ⇒ Object
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.
289 290 291 |
# File 'lib/sqlite/database.rb', line 289 def changes SQLite::API.changes( @handle ) end |
#close ⇒ Object
Closes this database. No checks are done to ensure that a database is not closed more than once, and closing a database more than once can be catastrophic.
148 149 150 151 |
# File 'lib/sqlite/database.rb', line 148 def close SQLite::API.close( @handle ) @closed = true end |
#closed? ⇒ Boolean
Returns true
if this database instance has been closed (see #close).
154 155 156 |
# File 'lib/sqlite/database.rb', line 154 def closed? @closed end |
#commit ⇒ Object
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
.
593 594 595 596 597 |
# File 'lib/sqlite/database.rb', line 593 def commit execute "commit transaction" @transaction_active = false true end |
#create_aggregate(name, arity, step, finalize, type = nil) ⇒ Object
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.) If type
is non-nil, it should be a value as described in #create_function.
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:
step = proc do |func, value|
func[ :total ] ||= 0
func[ :total ] += ( value ? value.length : 0 )
end
finalize = proc do |func|
func.set_result( func[ :total ] || 0 )
end
db.create_aggregate( "lengths", 1, step, finalize, :numeric )
puts db.get_first_value( "select lengths(name) from table" )
See also #create_aggregate_handler for a more object-oriented approach to aggregate functions.
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 |
# File 'lib/sqlite/database.rb', line 411 def create_aggregate( name, arity, step, finalize, type=nil ) case type when :numeric type = SQLite::API::NUMERIC when :text type = SQLite::API::TEXT when :args type = SQLite::API::ARGS end step_callback = proc do |func,*args| ctx = SQLite::API.aggregate_context( func ) unless ctx[:__error] begin step.call( FunctionProxy.new( func, ctx ), *args ) rescue Exception => e ctx[:__error] = e end end end finalize_callback = proc do |func| ctx = SQLite::API.aggregate_context( func ) unless ctx[:__error] begin finalize.call( FunctionProxy.new( func, ctx ) ) rescue Exception => e SQLite::API.set_result_error( func, "#{e.} (#{e.class})" ) end else e = ctx[:__error] SQLite::API.set_result_error( func, "#{e.} (#{e.class})" ) end end SQLite::API.create_aggregate( @handle, name, arity, step_callback, finalize_callback ) SQLite::API.function_type( @handle, name, type ) if type self end |
#create_aggregate_handler(handler) ⇒ Object
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:
function_type
-
corresponds to the
type
parameter of #create_aggregate. This is an optional message, and if the handler does not respond to it, the function type will not be set for this function. 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.function_type; :numeric; end
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" )
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
# File 'lib/sqlite/database.rb', line 505 def create_aggregate_handler( handler ) type = nil arity = -1 type = handler.function_type if handler.respond_to?(:function_type) arity = handler.arity if handler.respond_to?(:arity) name = handler.name case type when :numeric type = SQLite::API::NUMERIC when :text type = SQLite::API::TEXT when :args type = SQLite::API::ARGS end step = proc do |func,*args| ctx = SQLite::API.aggregate_context( func ) unless ctx[ :__error ] ctx[ :handler ] ||= handler.new begin ctx[ :handler ].step( FunctionProxy.new( func, ctx ), *args ) rescue Exception => e ctx[ :__error ] = e end end end finalize = proc do |func| ctx = SQLite::API.aggregate_context( func ) unless ctx[ :__error ] ctx[ :handler ] ||= handler.new begin ctx[ :handler ].finalize( FunctionProxy.new( func, ctx ) ) rescue Exception => e ctx[ :__error ] = e end end if ctx[ :__error ] e = ctx[ :__error ] SQLite::API.set_result_error( func, "#{e.} (#{e.class})" ) end end SQLite::API.create_aggregate( @handle, name, arity, step, finalize ) SQLite::API.function_type( @handle, name, type ) if type self end |
#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.} (#{e.class})" ) end end SQLite::API.create_function( @handle, name, arity, callback ) SQLite::API.function_type( @handle, name, type ) if type self end |
#execute(sql, *bind_vars) ⇒ Object
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.
Each placeholder must match one of the following formats:
-
?
-
?nnn
-
:word
-
:word:
where nnn is an integer value indicating the index of the bind variable to be bound at that position, and word is an alphanumeric identifier for that placeholder. For “?
”, an index is automatically assigned of one greater than the previous index used (or 1, if it is the first).
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, #execute_batch and #query for additional ways of executing statements.
191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
# File 'lib/sqlite/database.rb', line 191 def execute( sql, *bind_vars ) stmt = prepare( sql ) stmt.bind_params( *bind_vars ) result = stmt.execute begin if block_given? result.each { |row| yield row } else return result.inject( [] ) { |arr,row| arr << row; arr } end ensure result.close end end |
#execute2(sql, *bind_vars) ⇒ Object
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, #execute_batch and #query for additional ways of executing statements.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/sqlite/database.rb', line 216 def execute2( sql, *bind_vars ) stmt = prepare( sql ) stmt.bind_params( *bind_vars ) result = stmt.execute begin if block_given? yield result.columns result.each { |row| yield row } else return result.inject( [ result.columns ] ) { |arr,row| arr << row; arr } end ensure result.close end end |
#execute_batch(sql, *bind_vars) ⇒ Object
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.
240 241 242 243 244 245 246 247 248 249 |
# File 'lib/sqlite/database.rb', line 240 def execute_batch( sql, *bind_vars ) loop do stmt = prepare( sql ) stmt.bind_params *bind_vars stmt.execute sql = stmt.remainder break if sql.length < 1 end nil end |
#get_first_row(sql, *bind_vars) ⇒ Object
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.
265 266 267 268 |
# File 'lib/sqlite/database.rb', line 265 def get_first_row( sql, *bind_vars ) execute( sql, *bind_vars ) { |row| return row } nil end |
#get_first_value(sql, *bind_vars) ⇒ Object
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.
275 276 277 278 |
# File 'lib/sqlite/database.rb', line 275 def get_first_value( sql, *bind_vars ) execute( sql, *bind_vars ) { |row| return row[0] } nil end |
#interrupt ⇒ Object
Interrupts the currently executing operation, causing it to abort.
294 295 296 |
# File 'lib/sqlite/database.rb', line 294 def interrupt SQLite::API.interrupt( @handle ) end |
#last_insert_row_id ⇒ Object
Obtains the unique row ID of the last row to be inserted by this Database instance.
282 283 284 |
# File 'lib/sqlite/database.rb', line 282 def last_insert_row_id SQLite::API.last_insert_row_id( @handle ) end |
#prepare(sql) ⇒ Object
Returns a Statement object representing the given SQL. This does not execute the statement; it merely prepares the statement for execution.
160 161 162 |
# File 'lib/sqlite/database.rb', line 160 def prepare( sql ) Statement.new( self, sql ) end |
#query(sql, *bind_vars, &block) ⇒ Object
This does like #execute and #execute2 (binding variables and so forth), but instead of yielding each row from the result set, this will yield the ResultSet instance itself (q.v.). If no block is given, the ResultSet instance will be returned.
255 256 257 258 259 |
# File 'lib/sqlite/database.rb', line 255 def query( sql, *bind_vars, &block ) # :yields: result_set stmt = prepare( sql ) stmt.bind_params( *bind_vars ) stmt.execute( &block ) end |
#rollback ⇒ Object
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
.
603 604 605 606 607 |
# File 'lib/sqlite/database.rb', line 603 def rollback execute "rollback transaction" @transaction_active = false true end |
#transaction ⇒ Object
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.
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.
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
# File 'lib/sqlite/database.rb', line 570 def transaction execute "begin transaction" @transaction_active = true if block_given? abort = false begin yield self rescue Exception abort = true raise ensure abort and rollback or commit end end true end |
#transaction_active? ⇒ Boolean
Returns true
if there is a transaction active, and false
otherwise.
610 611 612 |
# File 'lib/sqlite/database.rb', line 610 def transaction_active? @transaction_active end |
#translator ⇒ Object
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.)
130 131 132 |
# File 'lib/sqlite/database.rb', line 130 def translator @translator ||= Translator.new end |
#type_translation ⇒ Object
Returns true
if type translation is enabled for this database, or false
otherwise.
136 137 138 |
# File 'lib/sqlite/database.rb', line 136 def type_translation @type_translation end |
#type_translation=(mode) ⇒ Object
Enable or disable type translation for this database.
141 142 143 |
# File 'lib/sqlite/database.rb', line 141 def type_translation=( mode ) @type_translation = mode end |