Class: SQLite3::Database
- Inherits:
-
Object
- Object
- SQLite3::Database
- Includes:
- Fiddle, Pragmas
- Defined in:
- lib/sqlite3/database.rb
Defined Under Namespace
Classes: FunctionProxy
Constant Summary collapse
- OPEN_READONLY =
Ok for sqlite3_open_v2()
0x00000001
- OPEN_READWRITE =
Ok for sqlite3_open_v2()
0x00000002
- OPEN_CREATE =
Ok for sqlite3_open_v2()
0x00000004
- OPEN_DELETEONCLOSE =
VFS only
0x00000008
- OPEN_EXCLUSIVE =
VFS only
0x00000010
- OPEN_AUTOPROXY =
VFS only
0x00000020
- OPEN_URI =
Ok for sqlite3_open_v2()
0x00000040
- OPEN_MEMORY =
Ok for sqlite3_open_v2()
0x00000080
- OPEN_MAIN_DB =
VFS only
0x00000100
- OPEN_TEMP_DB =
VFS only
0x00000200
- OPEN_TRANSIENT_DB =
VFS only
0x00000400
- OPEN_MAIN_JOURNAL =
VFS only
0x00000800
- OPEN_TEMP_JOURNAL =
VFS only
0x00001000
- OPEN_SUBJOURNAL =
VFS only
0x00002000
- OPEN_MASTER_JOURNAL =
VFS only
0x00004000
- OPEN_NOMUTEX =
Ok for sqlite3_open_v2()
0x00008000
- OPEN_FULLMUTEX =
Ok for sqlite3_open_v2()
0x00010000
- OPEN_SHAREDCACHE =
Ok for sqlite3_open_v2()
0x00020000
- OPEN_PRIVATECACHE =
Ok for sqlite3_open_v2()
0x00040000
- OPEN_WAL =
VFS only
0x00080000
- SQLITE_UTF8 =
1
- FUNC_PARAMS =
[TYPE_VOIDP, TYPE_INT, TYPE_VOIDP].freeze
- TRACE_PARAMS =
[TYPE_VOIDP, TYPE_VOIDP].freeze
- AUTH_PARAMS =
[ TYPE_VOIDP, TYPE_INT, TYPE_VOIDP, TYPE_VOIDP, TYPE_VOIDP, TYPE_VOIDP ].freeze
- COLLATION_PARAMS =
[ TYPE_VOIDP, TYPE_INT, TYPE_VOIDP, TYPE_INT, TYPE_VOIDP ].freeze
- BUSY_PARAMS =
[TYPE_VOIDP, TYPE_INT].freeze
Constants included from Pragmas
Pragmas::SYNCHRONOUS_MODES, Pragmas::TEMP_STORE_MODES
Instance Attribute Summary collapse
-
#collations ⇒ Object
readonly
Returns the value of attribute collations.
-
#results_as_hash ⇒ Object
A boolean that indicates whether rows in result sets should be returned as hashes or not.
Class Method Summary collapse
-
.quote(string) ⇒ Object
Quotes the given string, making it safe to use in an SQL statement.
Instance Method Summary collapse
- #authorizer(&block) ⇒ Object
-
#authorizer=(handler) ⇒ Object
call-seq: set_authorizer = auth.
- #busy_handler(handler = nil, &block) ⇒ Object
- #busy_timeout(ms) ⇒ Object
- #changes ⇒ Object
- #check(error_code) ⇒ Object
- #close ⇒ Object
- #closed? ⇒ Boolean
-
#collation(name, comparator) ⇒ Object
call-seq: db.collation(name, comparator).
-
#commit ⇒ Object
Commits the current transaction.
- #complete?(sql) ⇒ Boolean
-
#create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block) ⇒ 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, text_rep = Constants::TextRep::ANY, &handler) ⇒ Object
Creates a new function for use in SQL statements.
-
#define_aggregator(name, aggregator) ⇒ Object
call-seq: define_aggregator(name, aggregator).
-
#define_function(name, &handler) ⇒ Object
call-seq: define_function(name) { |args,…| }.
- #encoding ⇒ Object
- #errcode ⇒ Object
- #errmsg ⇒ Object
-
#execute(sql, bind_vars = [], *args, &block) ⇒ Object
(also: #exec)
Executes the given SQL statement.
-
#execute2(sql, *bind_vars) ⇒ Object
Executes the given SQL statement, exactly as with #execute.
-
#execute_batch(sql, bind_vars = [], *args) ⇒ Object
(also: #batch)
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.
- #handle ⇒ Object
-
#initialize(uri, opts = {}) ⇒ Database
constructor
A new instance of Database.
- #interrupt ⇒ Object
- #last_insert_row_id ⇒ Object
-
#prepare(sql) ⇒ Object
Returns a Statement object representing the given SQL.
-
#query(sql, bind_vars = [], *args) ⇒ Object
This is a convenience method for creating a statement, binding paramters to it, and calling execute:.
- #readonly?(db = 'main') ⇒ Boolean
-
#rollback ⇒ Object
Rolls the current transaction back.
- #total_changes ⇒ Object
-
#trace(tracer = nil, &block) ⇒ Object
call-seq: trace { |sql| … } trace(Class.new { def call sql; end }.new).
-
#transaction(mode = :deferred) ⇒ Object
Begins a new transaction.
- #transaction_active? ⇒ Boolean
Methods included from Pragmas
#auto_vacuum, #auto_vacuum=, #cache_size, #cache_size=, #database_list, #default_cache_size, #default_cache_size=, #default_synchronous, #default_synchronous=, #default_temp_store, #default_temp_store=, #foreign_key_list, #full_column_names, #full_column_names=, #index_info, #index_list, #integrity_check, #parser_trace, #parser_trace=, #schema_cookie, #schema_cookie=, #synchronous, #synchronous=, #table_info, #temp_store, #temp_store=, #user_cookie, #user_cookie=, #vdbe_trace, #vdbe_trace=
Constructor Details
#initialize(uri, opts = {}) ⇒ Database
Returns a new instance of Database.
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/sqlite3/database.rb', line 94 def initialize(uri, opts = {}) fail TypeError, "invalid uri" unless uri.is_a? String @results_as_hash = opts[:results_as_hash] || false @functions = {} @collations = {} @authorizer = nil @tracefunc = nil @encoding = nil @busy_handler = nil @db = Pointer.malloc(SIZEOF_VOIDP) if uri.encoding == Encoding::UTF_16LE || uri.encoding == Encoding::UTF_16BE check Driver.sqlite3_open16(uri, @db.ref) else if opts[:readonly] mode = OPEN_READONLY else mode = OPEN_READWRITE | OPEN_CREATE; end uri = uri.encode(Encoding::UTF_8) check Driver.sqlite3_open_v2(uri, @db.ref, mode, nil) end if block_given? begin yield self ensure close end end end |
Instance Attribute Details
#collations ⇒ Object (readonly)
Returns the value of attribute collations.
128 129 130 |
# File 'lib/sqlite3/database.rb', line 128 def collations @collations 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.
132 133 134 |
# File 'lib/sqlite3/database.rb', line 132 def results_as_hash @results_as_hash end |
Class Method Details
.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.
88 89 90 |
# File 'lib/sqlite3/database.rb', line 88 def quote( string ) string.gsub( /'/, "''" ) end |
Instance Method Details
#authorizer(&block) ⇒ Object
224 225 226 227 |
# File 'lib/sqlite3/database.rb', line 224 def (&block) self. = block if block_given? @authorizer end |
#authorizer=(handler) ⇒ Object
call-seq: set_authorizer = auth
Set the authorizer for this database. auth
must respond to call
, and call
must take 5 arguments.
Installs (or removes) a block that will be invoked for every access to the database. If the block returns 0 (or true
), the statement is allowed to proceed. Returning 1 or false causes an authorization error to occur, and returning 2 or nil causes the access to be silently denied.
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/sqlite3/database.rb', line 197 def (handler) must_be_open! @authorizer = handler if handler auth = Closure::BlockCaller.new(TYPE_VOIDP, AUTH_PARAMS) do |*args| args.shift # remove nil ruby_args = [args.shift] args.each do |ptr| ruby_args << ptr.null? ? nil : ptr.to_s end ret = @authorizer.call(*ruby_args) if ret.is_a? Fixnum ret elsif ret == false || ret == true ret == true ? OK : DENY else IGNORE end end else auth = nil end check Driver.(@db, auth, nil) end |
#busy_handler(handler = nil, &block) ⇒ Object
153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/sqlite3/database.rb', line 153 def busy_handler(handler = nil, &block) must_be_open! if handler.nil? and block_given? @busy_handler = block else @busy_handler = nil end cb = Closure::BlockCaller.new(TYPE_INT, BUSY_PARAMS) do |_, count| @busy_handler.call(self, count) ? 1 : 0 end if @busy_handler check Driver.sqlite3_busy_handler(@db, cb, nil) end |
#busy_timeout(ms) ⇒ Object
229 230 231 232 |
# File 'lib/sqlite3/database.rb', line 229 def busy_timeout(ms) must_be_open! Driver.sqlite3_busy_timeout(@db, ms) end |
#changes ⇒ Object
586 587 588 589 |
# File 'lib/sqlite3/database.rb', line 586 def changes must_be_open! Driver.sqlite3_changes(@db) end |
#check(error_code) ⇒ Object
772 773 774 775 776 777 778 |
# File 'lib/sqlite3/database.rb', line 772 def check(error_code) if error_code != SQLITE_OK ptr = Driver.sqlite3_errmsg(@db) fail(ERR_EXEPTION_MAPPING[error_code] || RuntimeError, ptr.to_s) end error_code end |
#close ⇒ Object
134 135 136 137 138 |
# File 'lib/sqlite3/database.rb', line 134 def close must_be_open! check Driver.sqlite3_close(@db) @db = nil end |
#closed? ⇒ Boolean
140 141 142 |
# File 'lib/sqlite3/database.rb', line 140 def closed? @db.nil? end |
#collation(name, comparator) ⇒ Object
call-seq: db.collation(name, comparator)
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.
174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/sqlite3/database.rb', line 174 def collation(name, comparator) must_be_open! cb = Closure::BlockCaller.new(TYPE_INT, COLLATION_PARAMS) do |_, aenc, astr, benc, bstr| target = Encoding.default_internal || Encoding::UTF_8 comparator.compare(sqlite_encoding(astr.to_s, aenc).encode(target), sqlite_encoding(bstr.to_s, benc).encode(target)).to_i end if comparator @collations[name] = comparator check Driver.sqlite3_create_collation(@db, name, Constants::TextRep::UTF8, nil, cb); 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
.
758 759 760 761 |
# File 'lib/sqlite3/database.rb', line 758 def commit execute "commit transaction" true end |
#complete?(sql) ⇒ Boolean
582 583 584 |
# File 'lib/sqlite3/database.rb', line 582 def complete?(sql) Driver.sqlite3_complete(sql.to_s) == 1 end |
#create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block) ⇒ 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.)
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#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.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.
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/sqlite3/database.rb', line 308 def create_aggregate( name, arity, step=nil, finalize=nil, text_rep=Constants::TextRep::ANY, &block ) factory = Class.new do def self.step( &block ) define_method(:step, &block) end def self.finalize( &block ) define_method(:finalize, &block) end end if block_given? factory.instance_eval(&block) else factory.class_eval do define_method(:step, step) define_method(:finalize, finalize) end end proxy = factory.new proxy.extend(Module.new { attr_accessor :ctx def step( *args ) super(@ctx, *args) end def finalize super(@ctx) end }) proxy.ctx = FunctionProxy.new define_aggregator(name, proxy) 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:
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 self.name; 'lengths'; end
def initialize
@total = 0
end
def step( ctx, name )
@total += ( name ? name.length : 0 )
end
def finalize( ctx )
ctx.result = @total
end
end
db.create_aggregate_handler( LengthsAggregateHandler )
puts db.get_first_value( "select lengths(name) from A" )
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 |
# File 'lib/sqlite3/database.rb', line 393 def create_aggregate_handler( handler ) proxy = Class.new do def initialize klass @klass = klass @fp = FunctionProxy.new end def step( *args ) instance.step(@fp, *args) end def finalize instance.finalize @fp @instance = nil @fp.result end private def instance @instance ||= @klass.new end end define_aggregator(handler.name, proxy.new(handler)) self end |
#create_function(name, arity, text_rep = Constants::TextRep::ANY, &handler) ⇒ 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.)
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#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" )
443 444 445 446 447 448 |
# File 'lib/sqlite3/database.rb', line 443 def create_function(name, arity, text_rep=Constants::TextRep::ANY, &handler) must_be_open! @functions[name] = handler check Driver.sqlite3_create_function(@db, name, arity, text_rep, nil, compile_function(FunctionProxy.proxy(handler)), nil, nil) end |
#define_aggregator(name, aggregator) ⇒ Object
call-seq: define_aggregator(name, aggregator)
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.
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
# File 'lib/sqlite3/database.rb', line 253 def define_aggregator(name, aggregator) must_be_open! @functions[name] = aggregator step = Closure::BlockCaller.new(TYPE_VOIDP, FUNC_PARAMS) do |_, argc, argv| aggregator.step(*native_to_ruby_args(argc, argv)) 0 # return something end fin = Closure::BlockCaller.new(TYPE_VOIDP, FUNC_PARAMS) do |ctx, _, _| Driver.set_context_result(ctx, aggregator.finalize()) 0 # return something end check Driver.sqlite3_create_function(@db, name, aggregator.method(:step).arity, Constants::TextRep::UTF8, nil, nil, step, fin) end |
#define_function(name, &handler) ⇒ Object
call-seq: define_function(name) { |args,…| }
Define a function named name
with args
. The arity of the block will be used as the arity for the function defined.
239 240 241 242 243 244 |
# File 'lib/sqlite3/database.rb', line 239 def define_function(name, &handler) must_be_open! @functions[name] = handler check Driver.sqlite3_create_function(@db, name, handler.arity, Constants::TextRep::UTF8, nil, compile_function(handler), nil, nil) end |
#encoding ⇒ Object
720 721 722 |
# File 'lib/sqlite3/database.rb', line 720 def encoding @encoding = Encoding.find(get_first_value('PRAGMA encoding')) end |
#errcode ⇒ Object
591 592 593 594 |
# File 'lib/sqlite3/database.rb', line 591 def errcode must_be_open! Driver.sqlite3_errcode(@db) end |
#errmsg ⇒ Object
596 597 598 599 |
# File 'lib/sqlite3/database.rb', line 596 def errmsg must_be_open! Driver.sqlite3_errmsg(@db).to_s end |
#execute(sql, bind_vars = [], *args, &block) ⇒ Object Also known as: exec
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.
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/sqlite3/database.rb', line 486 def execute sql, bind_vars = [], *args, &block if bind_vars.nil? || !args.empty? if args.empty? bind_vars = [] else bind_vars = [bind_vars] + args end end prepare( sql ) do |stmt| stmt.bind_params(bind_vars) columns = stmt.columns if block_given? stmt.each do |row| if @results_as_hash yield ordered_map_for(columns, row) else yield row end end else if @results_as_hash stmt.map { |row| ordered_map_for(columns, row) } else stmt.to_a end end 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, #query, and #execute_batch for additional ways of executing statements.
527 528 529 530 531 532 533 534 535 536 537 538 |
# File 'lib/sqlite3/database.rb', line 527 def execute2( sql, *bind_vars ) prepare( sql ) do |stmt| result = stmt.execute( *bind_vars ) if block_given? yield stmt.columns result.each { |row| yield row } else return result.inject( [ stmt.columns ] ) { |arr,row| arr << row; arr } end end end |
#execute_batch(sql, bind_vars = [], *args) ⇒ Object Also known as: batch
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.
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
# File 'lib/sqlite3/database.rb', line 548 def execute_batch( sql, bind_vars = [], *args ) # FIXME: remove this stuff later unless [Array, Hash].include?(bind_vars.class) bind_vars = [bind_vars] end # FIXME: remove this stuff later if bind_vars.nil? || !args.empty? if args.empty? bind_vars = [] else bind_vars = [nil] + args end end sql = sql.strip until sql.empty? do prepare( sql ) do |stmt| unless stmt.closed? # FIXME: this should probably use sqlite3's api for batch execution # This implementation requires stepping over the results. if bind_vars.length == stmt.bind_parameter_count stmt.bind_params(bind_vars) end stmt.step end sql = stmt.remainder.strip end end # FIXME: we should not return `nil` as a success return value 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.
667 668 669 |
# File 'lib/sqlite3/database.rb', line 667 def get_first_row( sql, *bind_vars ) execute( sql, *bind_vars ).first 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.
676 677 678 679 |
# File 'lib/sqlite3/database.rb', line 676 def get_first_value( sql, *bind_vars ) execute( sql, *bind_vars ) { |row| return row[0] } nil end |
#handle ⇒ Object
144 145 146 |
# File 'lib/sqlite3/database.rb', line 144 def handle @db end |
#interrupt ⇒ Object
148 149 150 151 |
# File 'lib/sqlite3/database.rb', line 148 def interrupt must_be_open! Driver.sqlite3_interrupt(@db) end |
#last_insert_row_id ⇒ Object
606 607 608 609 |
# File 'lib/sqlite3/database.rb', line 606 def last_insert_row_id must_be_open! Driver.sqlite3_last_insert_rowid(@db) 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.
The Statement can then be executed using Statement#execute.
651 652 653 654 655 656 657 658 659 660 661 |
# File 'lib/sqlite3/database.rb', line 651 def prepare sql must_be_open! stmt = SQLite3::Statement.new(self, sql) return stmt unless block_given? begin yield stmt ensure stmt.close unless stmt.closed? end end |
#query(sql, bind_vars = [], *args) ⇒ Object
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.
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 |
# File 'lib/sqlite3/database.rb', line 622 def query( sql, bind_vars = [], *args ) if bind_vars.nil? || !args.empty? if args.empty? bind_vars = [] else bind_vars = [bind_vars] + args end end result = prepare( sql ).execute( bind_vars ) if block_given? begin yield result ensure result.close end else return result end end |
#readonly?(db = 'main') ⇒ Boolean
749 750 751 752 |
# File 'lib/sqlite3/database.rb', line 749 def readonly?(db = 'main') must_be_open! Driver.sqlite3_db_readonly(@db, db.to_s) == 1 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
.
767 768 769 770 |
# File 'lib/sqlite3/database.rb', line 767 def rollback execute "rollback transaction" true end |
#total_changes ⇒ Object
601 602 603 604 |
# File 'lib/sqlite3/database.rb', line 601 def total_changes must_be_open! Driver.sqlite3_total_changes(@db) end |
#trace(tracer = nil, &block) ⇒ Object
call-seq:
trace { |sql| ... }
trace(Class.new { def call sql; end }.new)
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.
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 |
# File 'lib/sqlite3/database.rb', line 732 def trace(tracer = nil, &block) must_be_open! tracer = block if block_given? @tracefunc = tracer if tracer cb = Closure::BlockCaller.new(TYPE_VOIDP, TRACE_PARAMS) do |_, sql| tracer.call(sql.to_s) 0 # return something end end Driver.sqlite3_trace(@db, cb, nil) @tracefunc end |
#transaction(mode = :deferred) ⇒ 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.
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.
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 |
# File 'lib/sqlite3/database.rb', line 697 def transaction( mode = :deferred ) execute "begin #{mode.to_s} transaction" if block_given? abort = false begin yield self rescue ::Object abort = true raise ensure abort and rollback or commit end end true end |
#transaction_active? ⇒ Boolean
715 716 717 718 |
# File 'lib/sqlite3/database.rb', line 715 def transaction_active? must_be_open! Driver.sqlite3_get_autocommit(@db) != 1 end |