Class: SQLite3::Database
Relationships & Source Files | |
Namespace Children | |
Classes:
| |
Super Chains via Extension / Inclusion / Inheritance | |
Instance Chain:
self,
Pragmas
|
|
Inherits: | Object |
Defined in: | lib/sqlite3/database.rb, ext/sqlite3/database.c |
Overview
The Database class encapsulates a single connection to a ::SQLite3
database. Its usage is very straightforward:
require 'sqlite3'
SQLite3::Database.new( "data.db" ) do |db|
db.execute( "select * from table" ) do |row|
p row
end
end
It wraps the lower-level methods provided 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.
Thread safety:
When threadsafe? returns true, it is safe to share instances of the database class among threads without adding specific locking. Other object instances may require applications to provide their own locks if they are to be shared among threads. Please see the README.md
for more information.
Constant Summary
Pragmas
- Included
AUTO_VACUUM_MODES, ENCODINGS, JOURNAL_MODES, LOCKING_MODES, SYNCHRONOUS_MODES, TEMP_STORE_MODES, WAL_CHECKPOINTS
Class Method Summary
-
.new(file, options = {}) ⇒ Database
constructor
Create a new
Database
object that opens the given file. -
.open(*args)
Without block works exactly as new.
-
.quote(string)
Quotes the given string, making it safe to use in an SQL statement.
Instance Attribute Summary
-
#busy_handler_timeout=(milliseconds)
writeonly
Sets a #busy_handler that releases the GVL between retries, but only retries up to the indicated number of
milliseconds
. -
#closed? ⇒ Boolean
readonly
Returns
true
if this database instance has been closed (see #close). - #collations readonly
-
#extended_result_codes=(true)
writeonly
Enable extended result codes in SQLite.
-
#readonly? ⇒ Boolean
readonly
Returns
true
if the database has been open in readonly mode A helper to check before performing any operation. -
#results_as_hash
rw
A boolean that indicates whether rows in result sets should be returned as hashes or not.
-
#statement_timeout=(ms)
writeonly
Indicates that if a query lasts longer than the indicated number of milliseconds, SQLite should interrupt that query and return an error.
-
#transaction_active? ⇒ Boolean
readonly
Returns
true
if there is a transaction active, andfalse
otherwise.
Pragmas
- Included
Instance Method Summary
-
#authorizer(&block)
Installs (or removes) a block that will be invoked for every access to the database.
-
#set_authorizer=(auth)
Set the authorizer for this database.
-
#build_result_set(stmt)
Given a statement, return a result set.
-
#busy_handler {|count| ... }
Register a busy handler with this database instance.
-
#busy_timeout(milliseconds)
Alias for Pragmas#busy_timeout=.
-
#busy_timeout=(ms)
Indicates that if a request for a resource terminates because that resource is busy, SQLite should sleep and retry for up to the indicated number of milliseconds.
-
#changes
Returns the number of changes made to this database instance by the last operation performed.
-
#close
Close the database and release all associated resources.
-
#collation(name, comparator)
Add a collation with name
name
, and acomparator
object. -
#commit
Commits the current transaction.
-
#complete?(sql)
Return
true
if the string is a valid (ie, parsable) SQL statement, andfalse
otherwise. -
#create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block)
Creates a new aggregate function for use in SQL statements.
-
#create_aggregate_handler(handler)
This is another approach to creating an aggregate function (see #create_aggregate).
-
#create_function(name, arity, text_rep = Constants::TextRep::UTF8, &block)
Creates a new function for use in SQL statements.
-
#define_aggregator(name, aggregator)
Define an aggregate function named
name
using a object template objectaggregator
. -
#define_function(name) {|args, ...| ... }
Define a function named
name
withargs
. -
#define_function_with_flags(name, flags) {|args, ...| ... }
Define a function named
name
withargs
using TextRep bitflagsflags
. -
#enable_load_extension(onoff)
Enable or disable extension loading.
-
#encoding
Fetch the encoding set on this database.
-
#errcode
Return an integer representing the last error to have occurred with this database.
-
#errmsg
Return a string describing the last error to have occurred with this database.
-
#execute(sql, bind_vars = [], &block)
Executes the given SQL statement.
-
#execute2(sql, *bind_vars)
Executes the given SQL statement, exactly as with #execute.
-
#execute_batch(sql, bind_vars = [])
Executes all SQL statements in the given string.
-
#execute_batch2(sql, &block)
Executes all SQL statements in the given string.
-
#filename(db_name = "main")
Returns the filename for the database named
db_name
. -
#get_first_row(sql, *bind_vars)
A convenience method for obtaining the first row of a result set, and discarding all others.
-
#get_first_value(sql, *bind_vars)
A convenience method for obtaining the first value of the first row of a result set, and discarding all other values and rows.
-
#interrupt
Interrupts the currently executing operation, causing it to abort.
-
#last_insert_row_id
Obtains the unique row ID of the last row to be inserted by this
Database
instance. -
#load_extension(file)
Loads an SQLite extension library from the named file.
-
#prepare(sql)
Returns a
Statement
object representing the given SQL. -
#query(sql, bind_vars = [])
This is a convenience method for creating a statement, binding parameters to it, and calling execute:
-
#rollback
Rolls the current transaction back.
-
#total_changes ⇒ ?
Returns the total number of changes made to this database instance since it was opened.
-
#trace {|sql| ... }
Installs (or removes) a block that will be invoked for every SQL statement executed.
-
#transaction(mode = nil)
Begins a new transaction.
-
#db_filename(database_name)
private
Returns the file associated with
database_name
. - #define_aggregator2 private
- #disable_quirk_mode private
-
#discard
private
private method, primarily for testing.
-
#exec_batch(sql, results_as_hash)
private
Is invoked by calling db.execute_batch2(sql, &block).
- #open16(file) private
- #open_v2(file, mode, zvfs) private
Pragmas
- Included
#collation_list | :yields: row. |
#compile_options | :yields: row. |
#data_version, | |
#database_list | :yields: row. |
#foreign_key_check | :yields: row. |
#foreign_key_list | :yields: row. |
#freelist_count, | |
#get_boolean_pragma | Returns |
#get_enum_pragma | Return the value of the given pragma. |
#get_int_pragma | Returns the value of the given pragma as an integer. |
#get_query_pragma | Requests the given pragma (and parameters), and if the block is given, each row of the result set will be yielded to it. |
#incremental_vacuum | :yields: row. |
#index_info | :yields: row. |
#index_list | :yields: row. |
#index_xinfo | :yields: row. |
#integrity_check | :yields: row. |
#optimize | Attempt to optimize the database. |
#page_count, | |
#quick_check | :yields: row. |
#set_boolean_pragma | Sets the given pragma to the given boolean value. |
#set_enum_pragma | Set the value of the given pragma to |
#set_int_pragma | Set the value of the given pragma to the integer value of the |
#shrink_memory, | |
#stats | :yields: row. |
#table_info | Returns information about |
#tweak_default | Since SQLite 3.3.8, the table_info pragma has returned the default value of the row as a quoted SQL value. |
#version_compare | Compares two version strings. |
Constructor Details
.new(file, options = {}) ⇒ Database
Create a new Database
object that opens the given file.
Supported permissions options
:
-
the default mode is
READWRITE | CREATE
-
:readonly
: boolean (default false), true to set the mode toREADONLY
-
:readwrite
: boolean (default false), true to set the mode toREADWRITE
-
:flags
: set the mode to a combination ofConstants::Open
flags.
Supported encoding options
:
-
:utf16
: boolean (default false), is the filename’s encoding UTF-16 (only needed if the filename encoding is not UTF_16LE or BE)
Other supported options
:
-
:strict
: boolean (default false), disallow the use of double-quoted string literals (see www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted) -
:results_as_hash
: boolean (default false), return rows as hashes instead of arrays -
:default_transaction_mode
: one of:deferred
(default),:immediate
, or:exclusive
. If a mode is not specified in a call to #transaction, this will be the default transaction mode.
# File 'lib/sqlite3/database.rb', line 97
def initialize file, = {}, zvfs = nil mode = Constants::Open::READWRITE | Constants::Open::CREATE file = file.to_path if file.respond_to? :to_path if file.encoding == ::Encoding::UTF_16LE || file.encoding == ::Encoding::UTF_16BE || [:utf16] open16 file else # The three primary flag values for sqlite3_open_v2 are: # SQLITE_OPEN_READONLY # SQLITE_OPEN_READWRITE # SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE -- always used for sqlite3_open and sqlite3_open16 mode = Constants::Open::READONLY if [:readonly] if [:readwrite] raise "conflicting options: readonly and readwrite" if [:readonly] mode = Constants::Open::READWRITE end if [:flags] if [:readonly] || [:readwrite] raise "conflicting options: flags with readonly and/or readwrite" end mode = [:flags] end open_v2 file.encode("utf-8"), mode, zvfs if [:strict] disable_quirk_mode end end @tracefunc = nil @authorizer = nil @progress_handler = nil @collations = {} @functions = {} @results_as_hash = [:results_as_hash] @readonly = mode & Constants::Open::READONLY != 0 @default_transaction_mode = [:default_transaction_mode] || :deferred ForkSafety.track(self) if block_given? begin yield self ensure close end end end
Class Method Details
.open(*args)
Without block works exactly as new. With block, like new closes the database at the end, but unlike new returns the result of the block instead of the database instance.
.quote(string)
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 70
def quote(string) string.gsub("'", "''") end
Instance Attribute Details
#busy_handler_timeout=(milliseconds) (writeonly)
Sets a #busy_handler that releases the GVL between retries, but only retries up to the indicated number of milliseconds
. This is an alternative to #busy_timeout, which holds the GVL while SQLite sleeps and retries.
# File 'lib/sqlite3/database.rb', line 646
def busy_handler_timeout=(milliseconds) timeout_seconds = milliseconds.fdiv(1000) busy_handler do |count| now = Process.clock_gettime(Process::CLOCK_MONOTONIC) if count.zero? @timeout_deadline = now + timeout_seconds elsif now > @timeout_deadline next false else sleep(0.001) end end end
#closed? ⇒ Boolean
(readonly)
Returns true
if this database instance has been closed (see #close).
# File 'ext/sqlite3/database.c', line 224
static VALUE closed_p(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); if (!ctx->db) { return Qtrue; } return Qfalse; }
#collations (readonly)
[ GitHub ]# File 'lib/sqlite3/database.rb', line 45
attr_reader :collations
#extended_result_codes=(true) (writeonly)
Enable extended result codes in SQLite. These result codes allow for more detailed exception reporting, such a which type of constraint is violated.
# File 'ext/sqlite3/database.c', line 706
static VALUE set_extended_result_codes(VALUE self, VALUE enable) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_extended_result_codes(ctx->db, RTEST(enable) ? 1 : 0)); return self; }
#readonly? ⇒ Boolean
(readonly)
Returns true
if the database has been open in readonly mode A helper to check before performing any operation
# File 'lib/sqlite3/database.rb', line 638
def readonly? @readonly end
#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.
# File 'lib/sqlite3/database.rb', line 77
attr_accessor :results_as_hash
#statement_timeout=(ms) (writeonly)
Indicates that if a query lasts longer than the indicated number of milliseconds, SQLite should interrupt that query and return an error. By default, SQLite does not interrupt queries. To restore the default behavior, send 0 as the ms
parameter.
# File 'ext/sqlite3/database.c', line 363
static VALUE set_statement_timeout(VALUE self, VALUE milliseconds) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); ctx->stmt_timeout = NUM2INT(milliseconds); int n = NUM2INT(milliseconds) == 0 ? -1 : 1000; sqlite3_progress_handler(ctx->db, n, rb_sqlite3_statement_timeout, (void *)ctx); return self; }
#transaction_active? ⇒ Boolean
(readonly)
Returns true
if there is a transaction active, and false
otherwise.
# File 'ext/sqlite3/database.c', line 830
static VALUE transaction_active_p(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue; }
Instance Method Details
#authorizer(&block)
Installs (or removes) a block that will be invoked for every access to the database. If the block returns 0 (or nil
), the statement is allowed to proceed. Returning 1 causes an authorization error to occur, and returning 2 causes the access to be silently denied.
# File 'lib/sqlite3/database.rb', line 160
def (&block) self. = block end
#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.
# File 'ext/sqlite3/database.c', line 659
static VALUE set_authorizer(VALUE self, VALUE authorizer) { sqlite3RubyPtr ctx; int status; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); status = sqlite3_set_authorizer( ctx->db, NIL_P(authorizer) ? NULL : rb_sqlite3_auth, (void *)self ); CHECK(ctx->db, status); rb_iv_set(self, "@authorizer", authorizer); return self; }
#build_result_set(stmt)
Given a statement, return a result set. This is not intended for general consumption :nodoc:
# File 'lib/sqlite3/database.rb', line 697
def build_result_set stmt if results_as_hash HashResultSet.new(self, stmt) else ResultSet.new(self, stmt) end end
#busy_handler {|count| ... }
#busy_handler(Class.new { def call count; end }.new)
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 the mutually exclusive #busy_timeout.
# File 'ext/sqlite3/database.c', line 313
static VALUE busy_handler(int argc, VALUE *argv, VALUE self) { sqlite3RubyPtr ctx; VALUE block; int status; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); rb_scan_args(argc, argv, "01", &block); if (NIL_P(block) && rb_block_given_p()) { block = rb_block_proc(); } RB_OBJ_WRITE(self, &ctx->busy_handler, block); status = sqlite3_busy_handler( ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)ctx ); CHECK(ctx->db, status); return self; }
#busy_timeout(milliseconds)
Alias for Pragmas#busy_timeout=.
# File 'lib/sqlite3/database.rb', line 340
alias_method :busy_timeout, :busy_timeout=
#busy_timeout=(ms)
Indicates that if a request for a resource terminates because that resource is busy, SQLite should sleep and retry for up to the indicated number of milliseconds. By default, SQLite does not retry busy resources. To restore the default behavior, send 0 as the ms
parameter.
See also the mutually exclusive #busy_handler.
# File 'ext/sqlite3/database.c', line 689
static VALUE set_busy_timeout(VALUE self, VALUE timeout) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout))); return self; }
#changes
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.
# File 'ext/sqlite3/database.c', line 614
static VALUE changes(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM(sqlite3_changes(ctx->db)); }
#close
Close the database and release all associated resources.
⚠ Writable connections that are carried across a fork()
are not completely closed. Sqlite does not support forking, and fully closing a writable connection that has been carried across a fork may corrupt the database. Since it is an incomplete close, not all memory resources are freed, but this is safer than risking data loss.
See adr/2024-09-fork-safety.md for more information on fork safety.
# File 'ext/sqlite3/database.c', line 193
static VALUE sqlite3_rb_close(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); close_or_discard_db(ctx); rb_iv_set(self, "-aggregators", Qnil); return self; }
#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.
# File 'ext/sqlite3/database.c', line 753
static VALUE collation(VALUE self, VALUE name, VALUE comparator) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); CHECK(ctx->db, sqlite3_create_collation( ctx->db, StringValuePtr(name), SQLITE_UTF8, (void *)comparator, NIL_P(comparator) ? NULL : rb_comparator_func)); /* Make sure our comparator doesn't get garbage collected. */ rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator); return self; }
#commit
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 622
def commit execute "commit transaction" true end
#complete?(sql)
Return true
if the string is a valid (ie, parsable) SQL statement, and false
otherwise.
# File 'ext/sqlite3/database.c', line 598
static VALUE complete_p(VALUE UNUSED(self), VALUE sql) { if (sqlite3_complete(StringValuePtr(sql))) { return Qtrue; } return Qfalse; }
#create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block)
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 Database::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 Database::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 410
def create_aggregate(name, arity, step = nil, finalize = nil, text_rep = Constants::TextRep::ANY, &block) proxy = Class.new do def self.step(&block) define_method(:step_with_ctx, &block) end def self.finalize(&block) define_method(:finalize_with_ctx, &block) end end if block proxy.instance_eval(&block) else proxy.class_eval do define_method(:step_with_ctx, step) define_method(:finalize_with_ctx, finalize) end end proxy.class_eval do # class instance variables @name = name @arity = arity def self.name @name end def self.arity @arity end def initialize @ctx = FunctionProxy.new end def step(*args) step_with_ctx(@ctx, *args) end def finalize finalize_with_ctx(@ctx) @ctx.result end end define_aggregator2(proxy, name) end
#create_aggregate_handler(handler)
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 508
def create_aggregate_handler(handler) # This is a compatibility shim so the (basically pointless) FunctionProxy # "ctx" object is passed as first argument to both step() and finalize(). # Now its up to the library user whether he prefers to store his # temporaries as instance variables or fields in the FunctionProxy. # The library user still must set the result value with # FunctionProxy.result= as there is no backwards compatible way to # change this. proxy = Class.new(handler) do def initialize super @fp = FunctionProxy.new end def step(*args) super(@fp, *args) end def finalize super(@fp) @fp.result end end define_aggregator2(proxy, proxy.name) self end
#create_function(name, arity, text_rep = Constants::TextRep::UTF8, &block)
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 Database::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 365
def create_function name, arity, text_rep = Constants::TextRep::UTF8, &block define_function_with_flags(name, text_rep) do |*args| fp = FunctionProxy.new block.call(fp, *args) fp.result end self end
#db_filename(database_name) (private)
Returns the file associated with database_name
. Can return nil or an empty string if the database is temporary, or in-memory.
# File 'ext/sqlite3/database.c', line 918
static VALUE db_filename(VALUE self, VALUE db_name) { sqlite3RubyPtr ctx; const char *fname; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); fname = sqlite3_db_filename(ctx->db, StringValueCStr(db_name)); if (fname) { return SQLITE3_UTF8_STR_NEW2(fname); } return Qnil; }
#define_aggregator(name, aggregator)
Define an aggregate function named name
using a object template 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.
_API Change:_ aggregator
must also implement clone
. The provided aggregator
object will serve as template that is cloned to provide the individual instances of the aggregate function. Regular ruby objects already provide a suitable clone
. The functions arity is the arity of the step
method.
# File 'lib/sqlite3/database.rb', line 545
def define_aggregator(name, aggregator) # Previously, this has been implemented in C. Now this is just yet # another compatibility shim proxy = Class.new do @template = aggregator @name = name def self.template @template end def self.name @name end def self.arity # this is what sqlite3_obj_method_arity did before @template.method(:step).arity end def initialize @klass = self.class.template.clone end def step(*args) @klass.step(*args) end def finalize @klass.finalize end end define_aggregator2(proxy, name) self end
#define_aggregator2 (private)
[ GitHub ]#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.
# File 'ext/sqlite3/database.c', line 541
static VALUE define_function(VALUE self, VALUE name) { return define_function_with_flags(self, name, INT2FIX(SQLITE_UTF8)); }
#define_function_with_flags(name, flags) {|args, ...| ... }
Define a function named name
with args
using TextRep bitflags flags
. The arity of the block will be used as the arity for the function defined.
# File 'ext/sqlite3/database.c', line 506
static VALUE define_function_with_flags(VALUE self, VALUE name, VALUE flags) { sqlite3RubyPtr ctx; VALUE block; int status; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); block = rb_block_proc(); status = sqlite3_create_function( ctx->db, StringValuePtr(name), rb_proc_arity(block), NUM2INT(flags), (void *)block, rb_sqlite3_func, NULL, NULL ); CHECK(ctx->db, status); rb_hash_aset(rb_iv_get(self, "@functions"), name, block); return self; }
#disable_quirk_mode (private)
[ GitHub ]# File 'ext/sqlite3/database.c', line 164
static VALUE rb_sqlite3_disable_quirk_mode(VALUE self) { #if defined SQLITE_DBCONFIG_DQS_DDL sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); if (!ctx->db) { return Qfalse; } sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); return Qtrue; #else return Qfalse; #endif }
#discard (private)
private method, primarily for testing
# File 'ext/sqlite3/database.c', line 207
static VALUE sqlite3_rb_discard(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); discard_db(ctx); rb_iv_set(self, "-aggregators", Qnil); return self; }
#enable_load_extension(onoff)
Enable or disable extension loading.
# File 'ext/sqlite3/database.c', line 803
static VALUE enable_load_extension(VALUE self, VALUE onoff) { sqlite3RubyPtr ctx; int onoffparam; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); if (Qtrue == onoff) { onoffparam = 1; } else if (Qfalse == onoff) { onoffparam = 0; } else { onoffparam = (int)NUM2INT(onoff); } CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam)); return self; }
#encoding
Fetch the encoding set on this database
# File 'lib/sqlite3/database.rb', line 152
def encoding prepare("PRAGMA encoding") { |stmt| Encoding.find(stmt.first.first) } end
#errcode
Return an integer representing the last error to have occurred with this database.
# File 'ext/sqlite3/database.c', line 583
static VALUE errcode_(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM(sqlite3_errcode(ctx->db)); }
#errmsg
Return a string describing the last error to have occurred with this database.
# File 'ext/sqlite3/database.c', line 568
static VALUE errmsg(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return rb_str_new2(sqlite3_errmsg(ctx->db)); }
#exec_batch(sql, results_as_hash) (private)
Is invoked by calling db.execute_batch2(sql, &block)
Executes all statements in a given string separated by semicolons. If a query is made, all values returned are strings (except for ‘NULL’ values which return nil), so the user may parse values with a block. If no query is made, an empty array will be returned.
# File 'ext/sqlite3/database.c', line 887
static VALUE exec_batch(VALUE self, VALUE sql, VALUE results_as_hash) { sqlite3RubyPtr ctx; int status; VALUE callback_ary = rb_ary_new(); char *errMsg; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); if (results_as_hash == Qtrue) { status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)hash_callback_function, (void *)callback_ary, &errMsg); } else { status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)regular_callback_function, (void *)callback_ary, &errMsg); } CHECK_MSG(ctx->db, status, errMsg); return callback_ary; }
#execute(sql, bind_vars = [], &block)
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 201
def execute sql, bind_vars = [], &block prepare(sql) do |stmt| stmt.bind_params(bind_vars) stmt = build_result_set stmt if block stmt.each do |row| yield row end else stmt.to_a.freeze end end end
#execute2(sql, *bind_vars)
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.
#execute_batch(sql, bind_vars = [])
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 the result of the last statement.
See also #execute_batch2 for additional ways of executing statements.
# File 'lib/sqlite3/database.rb', line 250
def execute_batch(sql, bind_vars = []) sql = sql.strip result = nil until sql.empty? 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 result = stmt.step end sql = stmt.remainder.strip end end result end
#execute_batch2(sql, &block)
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. Bind parameters cannot be passed to #execute_batch2
.
If a query is made, all values will be returned as strings. If no query is made, an empty array will be returned.
Because all values except for ‘NULL’ are returned as strings, a block can be passed to parse the values accordingly.
See also #execute_batch for additional ways of executing statements.
# File 'lib/sqlite3/database.rb', line 283
def execute_batch2(sql, &block) if block result = exec_batch(sql, @results_as_hash) result.map do |val| yield val end else exec_batch(sql, @results_as_hash) end end
#filename(db_name = "main")
Returns the filename for the database named db_name
. db_name
defaults to “main”. Main return nil
or an empty string if the database is temporary or in-memory.
# File 'lib/sqlite3/database.rb', line 183
def filename db_name = "main" db_filename db_name end
#get_first_row(sql, *bind_vars)
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 322
def get_first_row(sql, *bind_vars) execute(sql, *bind_vars).first end
#get_first_value(sql, *bind_vars)
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 331
def get_first_value(sql, *bind_vars) query(sql, bind_vars) do |rs| if (row = rs.next) return @results_as_hash ? row[rs.columns[0]] : row[0] end end nil end
#interrupt
Interrupts the currently executing operation, causing it to abort.
# File 'ext/sqlite3/database.c', line 551
static VALUE interrupt(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); sqlite3_interrupt(ctx->db); return self; }
#last_insert_row_id
Obtains the unique row ID of the last row to be inserted by this Database
instance.
# File 'ext/sqlite3/database.c', line 382
static VALUE last_insert_row_id(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return LL2NUM(sqlite3_last_insert_rowid(ctx->db)); }
#load_extension(file)
Loads an SQLite extension library from the named file. Extension loading must be enabled using db.enable_load_extension(true) prior to calling this API.
# File 'ext/sqlite3/database.c', line 780
static VALUE load_extension(VALUE self, VALUE file) { sqlite3RubyPtr ctx; int status; char *errMsg; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); status = sqlite3_load_extension(ctx->db, StringValuePtr(file), 0, &errMsg); CHECK_MSG(ctx->db, status, errMsg); return self; }
#open16(file) (private)
[ GitHub ]# File 'ext/sqlite3/database.c', line 932
static VALUE rb_sqlite3_open16(VALUE self, VALUE file) { int status; sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); #if defined TAINTING_SUPPORT #if defined StringValueCStr StringValuePtr(file); rb_check_safe_obj(file); #else Check_SafeStr(file); #endif #endif // sqlite3_open16 implicitly uses flags (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) // see https://www.sqlite.org/capi3ref.html#sqlite3_open // so we do not ever set SQLITE3_RB_DATABASE_READONLY in ctx->flags status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); CHECK(ctx->db, status) return INT2NUM(status); }
#open_v2(file, mode, zvfs) (private)
[ GitHub ]# File 'ext/sqlite3/database.c', line 130
static VALUE rb_sqlite3_open_v2(VALUE self, VALUE file, VALUE mode, VALUE zvfs) { sqlite3RubyPtr ctx; int status; int flags; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); #if defined TAINTING_SUPPORT # if defined StringValueCStr StringValuePtr(file); rb_check_safe_obj(file); # else Check_SafeStr(file); # endif #endif flags = NUM2INT(mode); status = sqlite3_open_v2( StringValuePtr(file), &ctx->db, flags, NIL_P(zvfs) ? NULL : StringValuePtr(zvfs) ); CHECK(ctx->db, status); if (flags & SQLITE_OPEN_READONLY) { ctx->flags |= SQLITE3_RB_DATABASE_READONLY; } return self; }
#prepare(sql)
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.
#query(sql, bind_vars = [])
This is a convenience method for creating a statement, binding parameters 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.
#rollback
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 631
def rollback execute "rollback transaction" true end
#total_changes ⇒ ?
Returns the total number of changes made to this database instance since it was opened.
# File 'ext/sqlite3/database.c', line 240
static VALUE total_changes(VALUE self) { sqlite3RubyPtr ctx; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); return INT2NUM(sqlite3_total_changes(ctx->db)); }
#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.
# File 'ext/sqlite3/database.c', line 266
static VALUE trace(int argc, VALUE *argv, VALUE self) { sqlite3RubyPtr ctx; VALUE block; TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); REQUIRE_OPEN_DB(ctx); rb_scan_args(argc, argv, "01", &block); if (NIL_P(block) && rb_block_given_p()) { block = rb_block_proc(); } rb_iv_set(self, "@tracefunc", block); sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self); return self; }
#transaction(mode = nil)
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
, :immediate
, or :exclusive
. If nil
is specified, the default transaction mode, which was passed to #initialize
, is used.
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.