require 'sqlite3/constants' require 'sqlite3/errors' require 'sqlite3/pragmas' require 'sqlite3/statement' require 'sqlite3/translator' require 'sqlite3/value' module SQLite3 # 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. class Database include Pragmas class < 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 # 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. 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 # 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" ) 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 # 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. 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 # 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. def commit execute "commit transaction" @transaction_active = false true 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. def rollback execute "rollback transaction" @transaction_active = false true end # Returns +true+ if there is a transaction active, and +false+ otherwise. def transaction_active? @transaction_active end # Loads the corresponding driver, or if it is nil, attempts to locate a # suitable driver. 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 [ "Native", "DL" ].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 private :load_driver # A helper class for dealing with custom functions (see #create_function, # #create_aggregate, and #create_aggregate_handler). It encapsulates the # opaque function object that represents the current invocation. It also # provides more convenient access to the API functions that operate on # the function object. # # This class will almost _always_ be instantiated indirectly, by working # with the create methods mentioned above. class FunctionProxy # Create a new FunctionProxy that encapsulates the given +func+ object. # If context is non-nil, the functions context will be set to that. If # it is non-nil, it must quack like a Hash. If it is nil, then none of # the context functions will be available. def initialize( driver, func, context=nil ) @driver = driver @func = func @context = context end # Calls #set_result to set the result of this function. def result=( result ) set_result( result ) end # Set the result of the function to the given value. The function will # then return this value. def set_result( result, utf16=false ) @driver.result_text( @func, result, utf16 ) end # Set the result of the function to the given error message. # The function will then return that error. def set_error( error ) @driver.result_error( @func, error.to_s, -1 ) end # (Only available to aggregate functions.) Returns the number of rows # that the aggregate has processed so far. This will include the current # row, and so will always return at least 1. def count ensure_aggregate! @driver.aggregate_count( @func ) end # Returns the value with the given key from the context. This is only # available to aggregate functions. def []( key ) ensure_aggregate! @context[ key ] end # Sets the value with the given key in the context. This is only # available to aggregate functions. def []=( key, value ) ensure_aggregate! @context[ key ] = value end # A function for performing a sanity check, to ensure that the function # being invoked is an aggregate function. This is implied by the # existence of the context variable. def ensure_aggregate! unless @context raise MisuseException, "function is not an aggregate" end end private :ensure_aggregate! end # A proxy used for defining the callbacks to an aggregate function. class AggregateDefinitionProxy # :nodoc: attr_reader :step_callback, :finalize_callback def step( &block ) @step_callback = block end def finalize( &block ) @finalize_callback = block end end end end