Class: SQLite3::Database
- Inherits:
-
Object
- Object
- SQLite3::Database
- Includes:
- Extensions, Pragmas
- Defined in:
- lib/sqlite3/database.rb
Overview
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.
Instance Attribute Summary collapse
-
#driver ⇒ Object
readonly
A reference to the underlying SQLite3 driver used by this database.
-
#encoding ⇒ Object
readonly
Encoding used to comunicate with database.
-
#handle ⇒ Object
readonly
The low-level opaque database handle that this object wraps.
-
#results_as_hash ⇒ Object
A boolean that indicates whether rows in result sets should be returned as hashes or not.
Class Method Summary collapse
-
.quote(string) ⇒ Object
Quotes the given string, making it safe to use in an SQL statement.
Instance Method Summary collapse
-
#busy_timeout(ms) ⇒ Object
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 ⇒ Object
Returns the number of changes made to this database instance by the last operation performed.
-
#close ⇒ Object
Closes this database.
-
#closed? ⇒ Boolean
Returns
true
if this database instance has been closed (see #close). -
#commit ⇒ Object
Commits the current transaction.
-
#complete?(string) ⇒ Boolean
Return
true
if the string is a valid (ie, parsable) SQL statement, andfalse
otherwise. -
#errcode ⇒ Object
Return an integer representing the last error to have occurred with this database.
-
#errmsg ⇒ Object
Return a string describing the last error to have occurred with this database.
-
#execute(sql, *bind_vars) ⇒ Object
Executes the given SQL statement.
-
#execute2(sql, *bind_vars) ⇒ Object
Executes the given SQL statement, exactly as with #execute.
-
#get_first_row(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first row of a result set, and discarding all others.
-
#get_first_value(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first value of the first row of a result set, and discarding all other values and rows.
-
#initialize(file_name, options = {}) ⇒ Database
constructor
Create a new Database object that opens the given file.
-
#last_insert_row_id ⇒ Object
Obtains the unique row ID of the last row to be inserted by this Database instance.
-
#prepare(sql) ⇒ Object
Returns a Statement object representing the given SQL.
-
#rollback ⇒ Object
Rolls the current transaction back.
-
#transaction(mode = :deferred) ⇒ Object
Begins a new transaction.
-
#transaction_active? ⇒ Boolean
Returns
true
if there is a transaction active, andfalse
otherwise.
Methods included from Extensions
#disable_load_extension, #enable_load_extension, #load_extension
Methods included from Pragmas
Constructor Details
#initialize(file_name, options = {}) ⇒ Database
Create a new Database object that opens the given file. If utf16 is true
, the filename is interpreted as a UTF-16 encoded string.
By default, the new database will return result rows as arrays (#results_as_hash) and has type translation disabled (#type_translation=).
65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/sqlite3/database.rb', line 65 def initialize(file_name, = {}) @encoding = Encoding.find(.fetch(:encoding, "utf-8")) @driver = Driver.new @statement_factory = [:statement_factory] || Statement result, @handle = @driver.open(file_name, Encoding.utf_16?(@encoding)) Error.check(result, self, "could not open database") @closed = false @results_as_hash = .fetch(:results_as_hash, false) end |
Instance Attribute Details
#driver ⇒ Object (readonly)
A reference to the underlying SQLite3 driver used by this database.
51 52 53 |
# File 'lib/sqlite3/database.rb', line 51 def driver @driver end |
#encoding ⇒ Object (readonly)
Encoding used to comunicate with database.
58 59 60 |
# File 'lib/sqlite3/database.rb', line 58 def encoding @encoding end |
#handle ⇒ Object (readonly)
The low-level opaque database handle that this object wraps.
48 49 50 |
# File 'lib/sqlite3/database.rb', line 48 def handle @handle end |
#results_as_hash ⇒ Object
A boolean that indicates whether rows in result sets should be returned as hashes or not. By default, rows are returned as arrays.
55 56 57 |
# File 'lib/sqlite3/database.rb', line 55 def results_as_hash @results_as_hash end |
Class Method Details
.quote(string) ⇒ Object
Quotes the given string, making it safe to use in an SQL statement. It replaces all instances of the single-quote character with two single-quote characters. The modified string is returned.
41 42 43 |
# File 'lib/sqlite3/database.rb', line 41 def quote(string) string.gsub(/'/, "''") end |
Instance Method Details
#busy_timeout(ms) ⇒ Object
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.
215 216 217 218 |
# File 'lib/sqlite3/database.rb', line 215 def busy_timeout(ms) result = @driver.busy_timeout(@handle, ms) Error.check(result, self) end |
#changes ⇒ Object
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.
204 205 206 |
# File 'lib/sqlite3/database.rb', line 204 def changes @driver.changes(@handle) end |
#close ⇒ Object
Closes this database.
98 99 100 101 102 103 104 |
# File 'lib/sqlite3/database.rb', line 98 def close unless @closed result = @driver.close(@handle) Error.check(result, self) end @closed = true end |
#closed? ⇒ Boolean
Returns true
if this database instance has been closed (see #close).
107 108 109 |
# File 'lib/sqlite3/database.rb', line 107 def closed? @closed end |
#commit ⇒ Object
Commits the current transaction. If there is no current transaction, this will cause an error to be raised. This returns true
, in order to allow it to be used in idioms like abort? and rollback or commit
.
259 260 261 262 263 |
# File 'lib/sqlite3/database.rb', line 259 def commit execute "commit transaction" @transaction_active = false true end |
#complete?(string) ⇒ Boolean
Return true
if the string is a valid (ie, parsable) SQL statement, and false
otherwise
81 82 83 |
# File 'lib/sqlite3/database.rb', line 81 def complete?(string) @driver.complete?(string) end |
#errcode ⇒ Object
Return an integer representing the last error to have occurred with this database.
93 94 95 |
# File 'lib/sqlite3/database.rb', line 93 def errcode @driver.errcode(@handle) end |
#errmsg ⇒ Object
Return a string describing the last error to have occurred with this database.
87 88 89 |
# File 'lib/sqlite3/database.rb', line 87 def errmsg @driver.errmsg(@handle) end |
#execute(sql, *bind_vars) ⇒ Object
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.
143 144 145 146 147 148 149 150 151 152 |
# File 'lib/sqlite3/database.rb', line 143 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 |
#execute2(sql, *bind_vars) ⇒ Object
Executes the given SQL statement, exactly as with #execute. However, the first row returned (either via the block, or in the returned array) is always the names of the columns. Subsequent rows correspond to the data from the result set.
Thus, even if the query itself returns no rows, this method will always return at least one row–the names of the columns.
See also #execute, #query, and #execute_batch for additional ways of executing statements.
164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/sqlite3/database.rb', line 164 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 |
#get_first_row(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first row of a result set, and discarding all others. It is otherwise identical to #execute.
See also #get_first_value.
180 181 182 183 |
# File 'lib/sqlite3/database.rb', line 180 def get_first_row(sql, *bind_vars) execute(sql, *bind_vars) { |row| return row } nil end |
#get_first_value(sql, *bind_vars) ⇒ Object
A convenience method for obtaining the first value of the first row of a result set, and discarding all other values and rows. It is otherwise identical to #execute.
See also #get_first_row.
190 191 192 193 |
# File 'lib/sqlite3/database.rb', line 190 def get_first_value(sql, *bind_vars) execute(sql, *bind_vars) { |row| return row[0] } nil end |
#last_insert_row_id ⇒ Object
Obtains the unique row ID of the last row to be inserted by this Database instance.
197 198 199 |
# File 'lib/sqlite3/database.rb', line 197 def last_insert_row_id @driver.last_insert_rowid(@handle) end |
#prepare(sql) ⇒ Object
Returns a Statement object representing the given SQL. This does not execute the statement; it merely prepares the statement for execution.
The Statement can then be executed using Statement#execute.
116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/sqlite3/database.rb', line 116 def prepare(sql) stmt = @statement_factory.new(self, sql, Encoding.utf_16?(@encoding)) if block_given? begin yield stmt ensure stmt.close end else return stmt end end |
#rollback ⇒ Object
Rolls the current transaction back. If there is no current transaction, this will cause an error to be raised. This returns true
, in order to allow it to be used in idioms like abort? and rollback or commit
.
269 270 271 272 273 |
# File 'lib/sqlite3/database.rb', line 269 def rollback execute "rollback transaction" @transaction_active = false true end |
#transaction(mode = :deferred) ⇒ Object
Begins a new transaction. Note that nested transactions are not allowed by SQLite, so attempting to nest a transaction will result in a runtime exception.
The mode
parameter may be either :deferred
(the default), :immediate
, or :exclusive
.
If a block is given, the database instance is yielded to it, and the transaction is committed when the block terminates. If the block raises an exception, a rollback will be performed instead. Note that if a block is given, #commit and #rollback should never be called explicitly or you’ll get an error when the block terminates.
If a block is not given, it is the caller’s responsibility to end the transaction explicitly, either by calling #commit, or by calling #rollback.
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/sqlite3/database.rb', line 236 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 |
#transaction_active? ⇒ Boolean
Returns true
if there is a transaction active, and false
otherwise.
276 277 278 |
# File 'lib/sqlite3/database.rb', line 276 def transaction_active? @transaction_active end |