class SQLite3::Database

Constants

AUTH_PARAMS
BUSY_PARAMS
COLLATION_PARAMS
FUNC_PARAMS
OPEN_AUTOPROXY
OPEN_CREATE
OPEN_DELETEONCLOSE
OPEN_EXCLUSIVE
OPEN_FULLMUTEX
OPEN_MAIN_DB
OPEN_MAIN_JOURNAL
OPEN_MASTER_JOURNAL
OPEN_MEMORY
OPEN_NOMUTEX
OPEN_PRIVATECACHE
OPEN_READONLY
OPEN_READWRITE
OPEN_SHAREDCACHE
OPEN_SUBJOURNAL
OPEN_TEMP_DB
OPEN_TEMP_JOURNAL
OPEN_TRANSIENT_DB
OPEN_URI
OPEN_WAL
SQLITE_UTF8
TRACE_PARAMS

Attributes

collations[R]
results_as_hash[RW]

A boolean that indicates whether rows in result sets should be returned as hashes or not. By default, rows are returned as arrays.

Public Class Methods

finalize( &block ) click to toggle source
# File lib/sqlite3/database.rb, line 316
def self.finalize( &block )
  define_method(:finalize, &block)
end
new(uri, opts = {}) { |self| ... } click to toggle source
# 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
quote( string ) click to toggle source

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.

# File lib/sqlite3/database.rb, line 88
def quote( string )
  string.gsub( /'/, "''" )
end
step( &block ) click to toggle source
# File lib/sqlite3/database.rb, line 312
def self.step( &block )
  define_method(:step, &block)
end

Public Instance Methods

authorizer(&block) click to toggle source
# File lib/sqlite3/database.rb, line 224
def authorizer(&block)
  self.authorizer = block if block_given?
  @authorizer
end
set_authorizer = auth click to toggle source

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.

# File lib/sqlite3/database.rb, line 197
def authorizer=(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.sqlite3_set_authorizer(@db, auth, nil)
end
batch( sql, bind_vars = [], *args )
Alias for: execute_batch
busy_handler(handler = nil, &block) click to toggle source
# 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) click to toggle source
# File lib/sqlite3/database.rb, line 229
def busy_timeout(ms)
  must_be_open!
  Driver.sqlite3_busy_timeout(@db, ms)
end
changes() click to toggle source
# File lib/sqlite3/database.rb, line 586
def changes
  must_be_open!
  Driver.sqlite3_changes(@db)
end
check(error_code) click to toggle source
# 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() click to toggle source
# File lib/sqlite3/database.rb, line 134
def close
  must_be_open!
  check Driver.sqlite3_close(@db)
  @db = nil
end
closed?() click to toggle source
# File lib/sqlite3/database.rb, line 140
def closed?
  @db.nil?
end
collation(name, comparator) click to toggle source

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.

# 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() click to toggle source

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.

# File lib/sqlite3/database.rb, line 758
def commit
  execute "commit transaction"
  true
end
complete?(sql) click to toggle source
# 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 ) click to toggle source

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.

# 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 ) click to toggle source

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" )
# 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) click to toggle source

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" )
# 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) click to toggle source

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.

# 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) { |args,...| } click to toggle source

Define a function named name with args. The arity of the block will be used as the arity for the function defined.

# 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() click to toggle source
# File lib/sqlite3/database.rb, line 720
def encoding
  @encoding = Encoding.find(get_first_value('PRAGMA encoding'))
end
errcode() click to toggle source
# File lib/sqlite3/database.rb, line 591
def errcode
  must_be_open!
  Driver.sqlite3_errcode(@db)
end
errmsg() click to toggle source
# File lib/sqlite3/database.rb, line 596
def errmsg
  must_be_open!
  Driver.sqlite3_errmsg(@db).to_s
end
exec(sql, bind_vars = [], *args, &block)
Alias for: execute
execute(sql, bind_vars = [], *args) { |ordered_map_for(columns, row)| ... } click to toggle source

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.

# 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
Also aliased as: exec
execute2( sql, *bind_vars ) { |columns| ... } click to toggle source

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.

# 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 ) click to toggle source

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.

# 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
Also aliased as: batch
finalize() click to toggle source
# File lib/sqlite3/database.rb, line 404
def finalize
  instance.finalize @fp
  @instance = nil
  @fp.result
end
get_first_row( sql, *bind_vars ) click to toggle source

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.

# 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 ) click to toggle source

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.

# 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() click to toggle source
# File lib/sqlite3/database.rb, line 144
def handle
  @db
end
instance() click to toggle source
# File lib/sqlite3/database.rb, line 412
def instance
  @instance ||= @klass.new
end
interrupt() click to toggle source
# File lib/sqlite3/database.rb, line 148
def interrupt
  must_be_open!
  Driver.sqlite3_interrupt(@db)
end
last_insert_row_id() click to toggle source
# File lib/sqlite3/database.rb, line 606
def last_insert_row_id
  must_be_open!
  Driver.sqlite3_last_insert_rowid(@db)
end
prepare(sql) { |stmt| ... } click to toggle source

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.

# 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 ) { |result| ... } click to toggle source

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.

# 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') click to toggle source
# 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() click to toggle source

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.

# File lib/sqlite3/database.rb, line 767
def rollback
  execute "rollback transaction"
  true
end
step( *args ) click to toggle source
# File lib/sqlite3/database.rb, line 400
def step( *args )
  instance.step(@fp, *args)
end
total_changes() click to toggle source
# File lib/sqlite3/database.rb, line 601
def total_changes
  must_be_open!
  Driver.sqlite3_total_changes(@db)
end
trace { |sql| ... } click to toggle source
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.

# 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 ) { |self| ... } click to toggle source

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.

# 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?() click to toggle source
# File lib/sqlite3/database.rb, line 715
def transaction_active?
  must_be_open!
  Driver.sqlite3_get_autocommit(@db) != 1
end

Private Instance Methods

compile_function(handler) click to toggle source
# File lib/sqlite3/database.rb, line 805
def compile_function(handler)
  Closure::BlockCaller.new(TYPE_VOIDP, FUNC_PARAMS) do |ctx, argc, argv|
    args = native_to_ruby_args(argc, argv)
    Driver.set_context_result(ctx, handler.call(*args))
    0 # return something
  end
end
must_be_open!() click to toggle source
# File lib/sqlite3/database.rb, line 813
def must_be_open!
  raise Exception, "#{self.class} closed!" if closed?
end
native_to_ruby_args(argc, argv) click to toggle source
# File lib/sqlite3/database.rb, line 797
def native_to_ruby_args(argc, argv)
  args = []
  argc.times do |i|
    args << Value.new(self, (argv + (i * SIZEOF_VOIDP)).ptr).native
  end
  args
end
ordered_map_for(columns, row) click to toggle source
# File lib/sqlite3/database.rb, line 817
def ordered_map_for columns, row
  h = Hash[*columns.zip(row).flatten]
  row.each_with_index { |r, i| h[i] = r }
  h
end
sqlite_encoding(str, sqlite_encoding) click to toggle source
# File lib/sqlite3/database.rb, line 782
def sqlite_encoding(str, sqlite_encoding)
  case sqlite_encoding
  when SQLite3::Constants::TextRep::UTF8
    str.force_encoding(Encoding::UTF_8)
  when SQLite3::Constants::TextRep::UTF16LE
    str.force_encoding(Encoding::UTF_16LE)
  when SQLite3::Constants::TextRep::UTF16BE
    str.force_encoding(Encoding::UTF_16BE)
  when SQLite3::Constants::TextRep::UTF16
    str.force_encoding(Encoding::UTF_16)
  when SQLite3::Constants::TextRep::ANY
    str
  end
end