class SQLite3::Database
hashes, then the results will all be indexible by field name.
module before performing a query, and if you have not enabled results as
ArrayFields module from Ara Howard. If you require the ArrayFields
Furthermore, the Database class has been designed to work well with the
the database–insertions and updates are all still typeless.
for their tables). This translation only occurs when querying data from
converted into their corresponding types (as defined in the schemas
the SQLite3 data types (which are all represented as strings) may be
The Database class provides type translation services as well, by which
methods.
includes the Pragmas module for access to various pragma convenience
It wraps the lower-level methods provides by the selected driver, and
db.close
end
p row
db.execute(“select * from table”) do |row|
db = SQLite3::Database.new(“data.db”)
require “sqlite3”
Its usage is very straightforward:
The Database class encapsulates a single connection to a SQLite3 database.
def authorizer(data = nil, &block)
is allowed to proceed. Returning 1 causes an authorization error to
to the database. If the block returns 0 (or +nil+), the statement
Installs (or removes) a block that will be invoked for every access
def authorizer(data = nil, &block) result = @driver.set_authorizer(@handle, data, &block) Error.check(result, self) end
def busy_handler(data = nil, &block) # :yields: data, retries
See also the mutually exclusive #busy_timeout.
busy, and the number of times it has been retried.
The handler will be invoked with the name of the resource that was
be requested again.
+false+, the operation will be aborted; otherwise, the resource will
resource is busy, this handler will be invoked. If the handler returns
Register a busy handler with this database instance. When a requested
def busy_handler(data = nil, &block) # :yields: data, retries result = @driver.busy_handler(@handle, data, &block) Error.check(result, self) end
def busy_timeout(ms)
+ms+ parameter.
busy resources. To restore the default behavior, send 0 as the
number of milliseconds. By default, SQLite does not retry
resource is busy, SQLite should sleep and retry for up to the indicated
Indicates that if a request for a resource terminates because that
def busy_timeout(ms) result = @driver.busy_timeout(@handle, ms) Error.check(result, self) end
def changes
operation performed. Note that a "delete from table" without a where
Returns the number of changes made to this database instance by the last
def changes @driver.changes(@handle) end
def close
def close unless @closed result = @driver.close(@handle) Error.check(result, self) end @closed = true end
def closed?
def closed? @closed end
def commit
to allow it to be used in idioms like
this will cause an error to be raised. This returns +true+, in order
Commits the current transaction. If there is no current transaction,
def commit execute "commit transaction" @transaction_active = false true end
def complete?(string, utf16 = false)
+false+ otherwise. If +utf16+ is +true+, then the string is a UTF-16
Return +true+ if the string is a valid (ie, parsable) SQL statement, and
def complete?(string, utf16 = false) @driver.complete?(string, utf16) end
def create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block)
See also #create_aggregate_handler for a more object-oriented approach to
puts db.get_first_value("select lengths(name) from table")
end
end
func.set_result(func[:total] || 0)
finalize do |func|
end
func[:total] += (value ? value.length : 0)
func[:total] ||= 0
step do |func, value|
db.create_aggregate("lengths", 1) do
Example:
store the result of the function.
function invocation. It should invoke FunctionProxy#set_result to
single parameter, the FunctionProxy instance representing the current
The +finalize+ parameter must be a +proc+ object that accepts only a
The +step+ callback will be invoked once for each row of the result set.
invocation), with any subsequent parameters (up to the function's arity).
parameter a FunctionProxy instance (representing the function
The +step+ parameter must be a proc object that accepts as its first
variable arity functions, use -1 for the arity.)
The new function will be added as +name+, with the given +arity+. (For
a query.)
is the "count" function, for determining the number of rows that match
instead of over just a single row. (A very common aggregate function
functions are functions that apply over every row in the result set,
Creates a new aggregate function for use in SQL statements. Aggregate
def create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block) # begin if block proxy = AggregateDefinitionProxy.new proxy.instance_eval(&block) step ||= proxy.step_callback finalize ||= proxy.finalize_callback end step_callback = proc do |func, *args| ctx = @driver.aggregate_context(func) unless ctx[:__error] begin step.call(FunctionProxy.new(@driver, func, ctx), *args.map { |v| Value.new(self, v) }) rescue Exception => e ctx[:__error] = e end end end finalize_callback = proc do |func| ctx = @driver.aggregate_context(func) unless ctx[:__error] begin finalize.call(FunctionProxy.new(@driver, func, ctx)) rescue Exception => e @driver.result_error(func, "#{e.message} (#{e.class})", -1) end else e = ctx[:__error] @driver.result_error(func, "#{e.message} (#{e.class})", -1) end end result = @driver.create_function(@handle, name, arity, text_rep, nil, nil, step_callback, finalize_callback) Error.check(result, self) self end
def create_aggregate_handler(handler)
db.create_aggregate_handler(LengthsAggregateHandler)
end
end
ctx.set_result(@total)
def finalize(ctx)
end
@total += (name ? name.length : 0)
def step(ctx, name)
end
@total = 0
def initialize
def self.arity; 1; end
class LengthsAggregateHandler
Example:
#create_aggregate.
same signature as the +finalize+ callback for
aggregate function's evaluation. It should implement the
+finalize+:: this is the method that will be called to finalize the
signature as the +step+ callback for #create_aggregate.
aggregate function's evaluation. It should implement the same
+step+:: this is the method that will be called for each step of the
above), must respond to the following messages:
The handler instance (the object returned by the +new+ message, described
the function.
instance of the object that will handle a specific invocation of
+new+:: this must be implemented by the handler. It should return a new
this message.
+name+:: this is the name of the function. The handler _must_ implement
the function will have an arity of -1.
message is optional, and if the handler does not respond to it,
+arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
handler should respond to the following messages:
(the "handler") that knows how to obtain all of that information. The
callbacks, arity, and type, you specify a factory object
#create_aggregate). Instead of explicitly specifying the name,
This is another approach to creating an aggregate function (see
def create_aggregate_handler(handler) arity = -1 text_rep = Constants::TextRep::ANY arity = handler.arity if handler.respond_to?(:arity) text_rep = handler.text_rep if handler.respond_to?(:text_rep) name = handler.name step = proc do |func,*args| ctx = @driver.aggregate_context(func) unless ctx[:__error] ctx[:handler] ||= handler.new begin ctx[:handler].step(FunctionProxy.new(@driver, func, ctx), *args.map{|v| Value.new(self,v)}) rescue Exception, StandardError => e ctx[:__error] = e end end end finalize = proc do |func| ctx = @driver.aggregate_context(func) unless ctx[:__error] ctx[:handler] ||= handler.new begin ctx[:handler].finalize(FunctionProxy.new(@driver, func, ctx)) rescue Exception => e ctx[:__error] = e end end if ctx[:__error] e = ctx[:__error] @driver.sqlite3_result_error(func, "#{e.message} (#{e.class})", -1) end end result = @driver.create_function(@handle, name, arity, text_rep, nil, nil, step, finalize) Error.check(result, self) self end
def create_function(name, arity, text_rep = Constants::TextRep::ANY, &block) # :yields: func, *args
puts db.get_first_value("select maim(name) from table")
end
end
func.result = value.split(//).sort.join
else
func.result = nil
if value.nil?
db.create_function("maim", 1) do |func, value|
Example:
indicate the return value that way.
the FunctionProxy#set_result method on the +func+ parameter and
The block does not return a value directly. Instead, it will invoke
arguments it needs (up to its arity).
instance that wraps this function invocation--and any other
The block should accept at least one parameter--the FunctionProxy
-1 for the arity.)
+name+, with the given +arity+. (For variable arity functions, use
Creates a new function for use in SQL statements. It will be added as
def create_function(name, arity, text_rep = Constants::TextRep::ANY, &block) # :yields: func, *args # begin callback = proc do |func, *args| begin block.call(FunctionProxy.new(@driver, func), *args.map { |v| Value.new(self, v) }) rescue StandardError, Exception => e @driver.result_error(func, "#{e.message} (#{e.class})", -1) end end result = @driver.create_function(@handle, name, arity, text_rep, nil, callback, nil, nil) Error.check(result, self) self end
def errcode
Return an integer representing the last error to have occurred with this
def errcode @driver.errcode(@handle) end
def errmsg(utf16 = false)
Return a string describing the last error to have occurred with this
def errmsg(utf16 = false) @driver.errmsg(@handle, utf16) end
def execute(sql, *bind_vars)
See also #execute2, #query, and #execute_batch for additional ways of
returned wholesale.
by the query. Otherwise, any results are accumulated into an array and
The block is optional. If given, it will be invoked for each row returned
the name of the placeholder to bind the value to.
key/value pairs are each bound separately, with the key being used as
Note that if any of the values passed to this are hashes, then the
the query.
they are treated as bind variables, and are bound to the placeholders in
Executes the given SQL statement. If additional parameters are given,
def execute(sql, *bind_vars) prepare(sql) do |stmt| result = stmt.execute(*bind_vars) if block_given? result.each { |row| yield row } else return result.inject([]) { |arr, row| arr << row; arr } end end end
def execute2(sql, *bind_vars)
See also #execute, #query, and #execute_batch for additional ways of
return at least one row--the names of the columns.
Thus, even if the query itself returns no rows, this method will always
from the result set.
always the names of the columns. Subsequent rows correspond to the data
first row returned (either via the block, or in the returned array) is
Executes the given SQL statement, exactly as with #execute. However, the
def execute2(sql, *bind_vars) prepare(sql) do |stmt| result = stmt.execute(*bind_vars) if block_given? yield result.columns result.each { |row| yield row } else return result.inject([result.columns]) { |arr,row| arr << row; arr } end end end
def execute_batch(sql, *bind_vars)
This always returns +nil+, making it unsuitable for queries that return
statement.
in turn. The same bind parameters, if given, will be applied to each
string, ignoring all subsequent statements. This will execute each one
means of executing queries will only execute the first statement in the
Executes all SQL statements in the given string. By contrast, the other
def execute_batch(sql, *bind_vars) sql = sql.strip until sql.empty? do prepare(sql) do |stmt| stmt.execute(*bind_vars) sql = stmt.remainder.strip end end nil end
def get_first_row(sql, *bind_vars)
discarding all others. It is otherwise identical to #execute.
A convenience method for obtaining the first row of a result set, and
def get_first_row(sql, *bind_vars) execute(sql, *bind_vars) { |row| return row } nil end
def get_first_value(sql, *bind_vars)
identical to #execute.
result set, and discarding all other values and rows. It is otherwise
A convenience method for obtaining the first value of the first row of a
def get_first_value(sql, *bind_vars) execute(sql, *bind_vars) { |row| return row[0] } nil end
def initialize(file_name, options = {})
By default, the new database will return result rows as arrays
is +true+, the filename is interpreted as a UTF-16 encoded string.
Create a new Database object that opens the given file. If utf16
def initialize(file_name, options = {}) utf16 = options.fetch(:utf16, false) load_driver(options[:driver]) @statement_factory = options[:statement_factory] || Statement result, @handle = @driver.open(file_name, utf16) Error.check(result, self, "could not open database") @closed = false @results_as_hash = options.fetch(:results_as_hash,false) @type_translation = options.fetch(:type_translation,false) @translator = nil @transaction_active = false end
def interrupt
def interrupt @driver.interrupt(@handle) end
def last_insert_row_id
Obtains the unique row ID of the last row to be inserted by this Database
def last_insert_row_id @driver.last_insert_rowid(@handle) end
def load_driver(driver)
Loads the corresponding driver, or if it is nil, attempts to locate a
def load_driver(driver) case driver when Class # do nothing--use what was given when Symbol, String require "sqlite3/driver/#{driver.to_s.downcase}/driver" driver = SQLite3::Driver.const_get(driver)::Driver else ["FFI"].each do |d| begin require "sqlite3/driver/#{d.downcase}/driver" driver = SQLite3::Driver.const_get(d)::Driver break rescue SyntaxError raise rescue ScriptError, Exception, NameError end end raise "no driver for sqlite3 found" unless driver end @driver = driver.new end
def prepare(sql)
The Statement can then be executed using Statement#execute.
execute the statement; it merely prepares the statement for execution.
Returns a Statement object representing the given SQL. This does not
def prepare(sql) stmt = @statement_factory.new(self, sql) if block_given? begin yield stmt ensure stmt.close end else return stmt end end
def query(sql, *bind_vars)
with a block, +close+ will be invoked implicitly when the block
returned, or you could have problems with locks on the table. If called
You must be sure to call +close+ on the ResultSet instance that is
result = db.prepare("select * from foo where a=?").execute(5)
# is the same as
result = db.query("select * from foo where a=?", 5)
paramters to it, and calling execute:
This is a convenience method for creating a statement, binding
def query(sql, *bind_vars) result = prepare(sql).execute(*bind_vars) if block_given? begin yield result ensure result.close end else return result end end
def quote(string)
It replaces all instances of the single-quote character with two
Quotes the given string, making it safe to use in an SQL statement.
def quote(string) string.gsub(/'/, "''") end
def rollback
to allow it to be used in idioms like
this will cause an error to be raised. This returns +true+, in order
Rolls the current transaction back. If there is no current transaction,
def rollback execute "rollback transaction" @transaction_active = false true end
def total_changes
Returns the total number of changes made to this database instance
def total_changes @driver.total_changes(@handle) end
def trace(data = nil, &block)
argument, and the SQL statement executed. If the block is +nil+,
statement executed. The block receives a two parameters: the +data+
Installs (or removes) a block that will be invoked for every SQL
def trace(data = nil, &block) @driver.trace(@handle, data, &block) end
def transaction(mode = :deferred)
transaction explicitly, either by calling #commit, or by calling
If a block is not given, it is the caller's responsibility to end the
explicitly or you'll get an error when the block terminates.
a block is given, #commit and #rollback should never be called
raises an exception, a rollback will be performed instead. Note that if
transaction is committed when the block terminates. If the block
If a block is given, the database instance is yielded to it, and the
:immediate, or :exclusive.
The +mode+ parameter may be either :deferred (the default),
exception.
by SQLite, so attempting to nest a transaction will result in a runtime
Begins a new transaction. Note that nested transactions are not allowed
def transaction(mode = :deferred) execute "begin #{mode.to_s} transaction" @transaction_active = true if block_given? abort = false begin yield self rescue ::Object abort = true raise ensure abort and rollback or commit end end true end
def transaction_active?
def transaction_active? @transaction_active end
def translator
if a database does not use type translation, it will not be burdened by
instances. Furthermore, the translators are instantiated lazily, so that
type handlers to be installed in each instance without affecting other
database instance has its own type translator; this allows for different
Return the type translator employed by this database instance. Each
def translator @translator ||= Translator.new end