Class: ActiveRecord::ConnectionAdapters::SQLiteAdapter
- Inherits:
-
AbstractAdapter
- Object
- AbstractAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- Defined in:
- lib/active_record/connection_adapters/sqlite_adapter.rb
Overview
The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby drivers (available both as gems and from rubyforge.org/projects/sqlite-ruby/).
Options:
-
:database
- Path to the database file.
Direct Known Subclasses
Defined Under Namespace
Classes: BindSubstitution, ExplainPrettyPrinter, StatementPool, Version
Instance Attribute Summary
Attributes inherited from AbstractAdapter
#in_use, #last_use, #logger, #open_transactions, #pool, #schema_cache, #visitor
Attributes included from QueryCache
#query_cache, #query_cache_enabled
Instance Method Summary collapse
-
#adapter_name ⇒ Object
:nodoc:.
-
#add_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:.
-
#begin_db_transaction ⇒ Object
:nodoc:.
-
#change_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:.
-
#change_column_default(table_name, column_name, default) ⇒ Object
:nodoc:.
- #change_column_null(table_name, column_name, null, default = nil) ⇒ Object
-
#clear_cache! ⇒ Object
Clears the prepared statements cache.
-
#columns(table_name, name = nil) ⇒ Object
Returns an array of
SQLiteColumn
objects for the table specified bytable_name
. -
#commit_db_transaction ⇒ Object
:nodoc:.
- #create_savepoint ⇒ Object
-
#delete_sql(sql, name = nil) ⇒ Object
:nodoc:.
-
#disconnect! ⇒ Object
Disconnects from the database if already connected.
- #empty_insert_statement_value ⇒ Object
- #exec_delete(sql, name = 'SQL', binds = []) ⇒ Object (also: #exec_update)
- #exec_query(sql, name = nil, binds = []) ⇒ Object
-
#execute(sql, name = nil) ⇒ Object
:nodoc:.
-
#explain(arel, binds = []) ⇒ Object
DATABASE STATEMENTS ======================================.
-
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
-
#initialize(connection, logger, config) ⇒ SQLiteAdapter
constructor
A new instance of SQLiteAdapter.
-
#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object
(also: #create)
:nodoc:.
- #last_inserted_id(result) ⇒ Object
-
#native_database_types ⇒ Object
:nodoc:.
-
#primary_key(table_name) ⇒ Object
:nodoc:.
-
#quote_column_name(name) ⇒ Object
:nodoc:.
-
#quote_string(s) ⇒ Object
QUOTING ==================================================.
-
#quoted_date(value) ⇒ Object
Quote date/time values for use in SQL input.
- #release_savepoint ⇒ Object
-
#remove_column(table_name, *column_names) ⇒ Object
(also: #remove_columns)
:nodoc:.
-
#remove_index!(table_name, index_name) ⇒ Object
:nodoc:.
-
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:.
-
#rename_table(name, new_name) ⇒ Object
Renames a table.
- #requires_reloading? ⇒ Boolean
-
#rollback_db_transaction ⇒ Object
:nodoc:.
- #rollback_to_savepoint ⇒ Object
- #select_rows(sql, name = nil) ⇒ Object
-
#supports_add_column? ⇒ Boolean
Returns true if SQLite version is ‘3.1.6’ or greater, false otherwise.
-
#supports_autoincrement? ⇒ Boolean
Returns true if SQLite version is ‘3.1.0’ or greater, false otherwise.
-
#supports_count_distinct? ⇒ Boolean
Returns true if SQLite version is ‘3.2.6’ or greater, false otherwise.
-
#supports_ddl_transactions? ⇒ Boolean
Returns true if SQLite version is ‘2.0.0’ or greater, false otherwise.
-
#supports_explain? ⇒ Boolean
Returns true.
- #supports_index_sort_order? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
Returns true, since this connection adapter supports migrations.
-
#supports_primary_key? ⇒ Boolean
Returns true.
-
#supports_savepoints? ⇒ Boolean
Returns true if SQLite version is ‘3.6.8’ or greater, false otherwise.
-
#supports_statement_cache? ⇒ Boolean
Returns true, since this connection adapter supports prepared statement caching.
- #table_exists?(name) ⇒ Boolean
-
#tables(name = 'SCHEMA', table_name = nil) ⇒ Object
SCHEMA STATEMENTS ========================================.
-
#type_cast(value, column) ⇒ Object
:nodoc:.
-
#update_sql(sql, name = nil) ⇒ Object
:nodoc:.
-
#valid_alter_table_options(type, options) ⇒ Object
See: www.sqlite.org/lang_altertable.html SQLite has an additional restriction on the ALTER TABLE statement.
Methods inherited from AbstractAdapter
#active?, #case_insensitive_comparison, #case_sensitive_modifier, #close, #current_savepoint_name, #decrement_open_transactions, #disable_referential_integrity, #expire, #increment_open_transactions, #lease, #prefetch_primary_key?, #quote_table_name, #raw_connection, #reconnect!, #reset!, #substitute_at, #supports_bulk_alter?, #transaction_joinable=, #verify!
Methods included from QueryCache
#cache, #clear_query_cache, dirties_query_cache, #disable_query_cache!, #enable_query_cache!, included, #select_all, #uncached
Methods included from DatabaseLimits
#column_name_length, #columns_per_multicolumn_index, #columns_per_table, #in_clause_length, #index_name_length, #indexes_per_table, #joins_per_query, #sql_query_length, #table_alias_length, #table_name_length
Methods included from Quoting
#quote, #quote_table_name, #quoted_false, #quoted_true
Methods included from DatabaseStatements
#add_transaction_record, #case_sensitive_equality_operator, #default_sequence_name, #delete, #exec_insert, #insert, #insert_fixture, #join_to_update, #limited_update_conditions, #outside_transaction?, #reset_sequence!, #sanitize_limit, #select_all, #select_one, #select_value, #select_values, #to_sql, #transaction, #update
Methods included from SchemaStatements
#add_column_options!, #add_index, #add_timestamps, #assume_migrated_upto_version, #change_table, #column_exists?, #create_table, #distinct, #drop_table, #dump_schema_information, #index_exists?, #index_name, #index_name_exists?, #initialize_schema_migrations_table, #remove_index, #remove_timestamps, #rename_index, #structure_dump, #table_alias_for, #type_to_sql
Constructor Details
#initialize(connection, logger, config) ⇒ SQLiteAdapter
Returns a new instance of SQLiteAdapter.
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 77 def initialize(connection, logger, config) super(connection, logger) @statements = StatementPool.new(@connection, config.fetch(:statement_limit) { 1000 }) @config = config if config.fetch(:prepared_statements) { true } @visitor = Arel::Visitors::SQLite.new self else @visitor = BindSubstitution.new self end end |
Instance Method Details
#adapter_name ⇒ Object
:nodoc:
90 91 92 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 90 def adapter_name #:nodoc: 'SQLite' end |
#add_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:
398 399 400 401 402 403 404 405 406 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 398 def add_column(table_name, column_name, type, = {}) #:nodoc: if supports_add_column? && ( type, ) super(table_name, column_name, type, ) else alter_table(table_name) do |definition| definition.column(column_name, type, ) end end end |
#begin_db_transaction ⇒ Object
:nodoc:
313 314 315 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 313 def begin_db_transaction #:nodoc: log('begin transaction',nil) { @connection.transaction } end |
#change_column(table_name, column_name, type, options = {}) ⇒ Object
:nodoc:
440 441 442 443 444 445 446 447 448 449 450 451 452 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 440 def change_column(table_name, column_name, type, = {}) #:nodoc: alter_table(table_name) do |definition| include_default = () definition[column_name].instance_eval do self.type = type self.limit = [:limit] if .include?(:limit) self.default = [:default] if include_default self.null = [:null] if .include?(:null) self.precision = [:precision] if .include?(:precision) self.scale = [:scale] if .include?(:scale) end end end |
#change_column_default(table_name, column_name, default) ⇒ Object
:nodoc:
425 426 427 428 429 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 425 def change_column_default(table_name, column_name, default) #:nodoc: alter_table(table_name) do |definition| definition[column_name].default = default end end |
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
431 432 433 434 435 436 437 438 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 431 def change_column_null(table_name, column_name, null, default = nil) unless null || default.nil? exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end alter_table(table_name) do |definition| definition[column_name].null = null end end |
#clear_cache! ⇒ Object
Clears the prepared statements cache.
143 144 145 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 143 def clear_cache! @statements.clear end |
#columns(table_name, name = nil) ⇒ Object
Returns an array of SQLiteColumn
objects for the table specified by table_name
.
345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 345 def columns(table_name, name = nil) #:nodoc: table_structure(table_name).map do |field| case field["dflt_value"] when /^null$/i field["dflt_value"] = nil when /^'(.*)'$/ field["dflt_value"] = $1.gsub(/''/, "'") when /^"(.*)"$/ field["dflt_value"] = $1.gsub(/""/, '"') end SQLiteColumn.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0) end end |
#commit_db_transaction ⇒ Object
:nodoc:
317 318 319 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 317 def commit_db_transaction #:nodoc: log('commit transaction',nil) { @connection.commit } end |
#create_savepoint ⇒ Object
301 302 303 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 301 def create_savepoint execute("SAVEPOINT #{current_savepoint_name}") end |
#delete_sql(sql, name = nil) ⇒ Object
:nodoc:
286 287 288 289 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 286 def delete_sql(sql, name = nil) #:nodoc: sql += " WHERE 1=1" unless sql =~ /WHERE/i super sql, name end |
#disconnect! ⇒ Object
Disconnects from the database if already connected. Otherwise, this method does nothing.
136 137 138 139 140 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 136 def disconnect! super clear_cache! @connection.close rescue nil end |
#empty_insert_statement_value ⇒ Object
461 462 463 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 461 def empty_insert_statement_value "VALUES(NULL)" end |
#exec_delete(sql, name = 'SQL', binds = []) ⇒ Object Also known as: exec_update
267 268 269 270 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 267 def exec_delete(sql, name = 'SQL', binds = []) exec_query(sql, name, binds) @connection.changes end |
#exec_query(sql, name = nil, binds = []) ⇒ Object
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 241 def exec_query(sql, name = nil, binds = []) log(sql, name, binds) do # Don't cache statements without bind values if binds.empty? stmt = @connection.prepare(sql) cols = stmt.columns records = stmt.to_a stmt.close stmt = records else cache = @statements[sql] ||= { :stmt => @connection.prepare(sql) } stmt = cache[:stmt] cols = cache[:cols] ||= stmt.columns stmt.reset! stmt.bind_params binds.map { |col, val| type_cast(val, col) } end ActiveRecord::Result.new(cols, stmt.to_a) end end |
#execute(sql, name = nil) ⇒ Object
:nodoc:
277 278 279 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 277 def execute(sql, name = nil) #:nodoc: log(sql, name) { @connection.execute(sql) } end |
#explain(arel, binds = []) ⇒ Object
DATABASE STATEMENTS ======================================
222 223 224 225 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 222 def explain(arel, binds = []) sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}" ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) end |
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
361 362 363 364 365 366 367 368 369 370 371 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 361 def indexes(table_name, name = nil) #:nodoc: exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", name).map do |row| IndexDefinition.new( table_name, row['name'], row['unique'] != 0, exec_query("PRAGMA index_info('#{row['name']}')").map { |col| col['name'] }) end end |
#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) ⇒ Object Also known as: create
:nodoc:
291 292 293 294 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 291 def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc: super id_value || @connection.last_insert_row_id end |
#last_inserted_id(result) ⇒ Object
273 274 275 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 273 def last_inserted_id(result) @connection.last_insert_row_id end |
#native_database_types ⇒ Object
:nodoc:
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 161 def native_database_types #:nodoc: { :primary_key => default_primary_key_type, :string => { :name => "varchar", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "integer" }, :float => { :name => "float" }, :decimal => { :name => "decimal" }, :datetime => { :name => "datetime" }, :timestamp => { :name => "datetime" }, :time => { :name => "time" }, :date => { :name => "date" }, :binary => { :name => "blob" }, :boolean => { :name => "boolean" } } end |
#primary_key(table_name) ⇒ Object
:nodoc:
373 374 375 376 377 378 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 373 def primary_key(table_name) #:nodoc: column = table_structure(table_name).find { |field| field['pk'] == 1 } column && column['name'] end |
#quote_column_name(name) ⇒ Object
:nodoc:
185 186 187 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 185 def quote_column_name(name) #:nodoc: %Q("#{name.to_s.gsub('"', '""')}") end |
#quote_string(s) ⇒ Object
QUOTING ==================================================
181 182 183 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 181 def quote_string(s) #:nodoc: @connection.class.quote(s) end |
#quoted_date(value) ⇒ Object
Quote date/time values for use in SQL input. Includes microseconds if the value is a Time responding to usec.
191 192 193 194 195 196 197 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 191 def quoted_date(value) #:nodoc: if value.respond_to?(:usec) "#{super}.#{sprintf("%06d", value.usec)}" else super end end |
#release_savepoint ⇒ Object
309 310 311 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 309 def release_savepoint execute("RELEASE SAVEPOINT #{current_savepoint_name}") end |
#remove_column(table_name, *column_names) ⇒ Object Also known as: remove_columns
:nodoc:
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 408 def remove_column(table_name, *column_names) #:nodoc: raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.empty? if column_names.flatten! = 'Passing array to remove_columns is deprecated, please use ' + 'multiple arguments, like: `remove_columns(:posts, :foo, :bar)`' ActiveSupport::Deprecation.warn , caller end column_names.each do |column_name| alter_table(table_name) do |definition| definition.columns.delete(definition[column_name]) end end end |
#remove_index!(table_name, index_name) ⇒ Object
:nodoc:
380 381 382 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 380 def remove_index!(table_name, index_name) #:nodoc: exec_query "DROP INDEX #{quote_column_name(index_name)}" end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:
454 455 456 457 458 459 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 454 def rename_column(table_name, column_name, new_column_name) #:nodoc: unless columns(table_name).detect{|c| c.name == column_name.to_s } raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}" end alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s}) end |
#rename_table(name, new_name) ⇒ Object
Renames a table.
Example:
rename_table('octopuses', 'octopi')
388 389 390 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 388 def rename_table(name, new_name) exec_query "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}" end |
#requires_reloading? ⇒ Boolean
125 126 127 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 125 def requires_reloading? true end |
#rollback_db_transaction ⇒ Object
:nodoc:
321 322 323 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 321 def rollback_db_transaction #:nodoc: log('rollback transaction',nil) { @connection.rollback } end |
#rollback_to_savepoint ⇒ Object
305 306 307 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 305 def rollback_to_savepoint execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") end |
#select_rows(sql, name = nil) ⇒ Object
297 298 299 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 297 def select_rows(sql, name = nil) exec_query(sql, name).rows end |
#supports_add_column? ⇒ Boolean
Returns true if SQLite version is ‘3.1.6’ or greater, false otherwise.
130 131 132 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 130 def supports_add_column? sqlite_version >= '3.1.6' end |
#supports_autoincrement? ⇒ Boolean
Returns true if SQLite version is ‘3.1.0’ or greater, false otherwise.
153 154 155 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 153 def supports_autoincrement? #:nodoc: sqlite_version >= '3.1.0' end |
#supports_count_distinct? ⇒ Boolean
Returns true if SQLite version is ‘3.2.6’ or greater, false otherwise.
148 149 150 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 148 def supports_count_distinct? #:nodoc: sqlite_version >= '3.2.6' end |
#supports_ddl_transactions? ⇒ Boolean
Returns true if SQLite version is ‘2.0.0’ or greater, false otherwise.
95 96 97 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 95 def supports_ddl_transactions? sqlite_version >= '2.0.0' end |
#supports_explain? ⇒ Boolean
Returns true.
121 122 123 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 121 def supports_explain? true end |
#supports_index_sort_order? ⇒ Boolean
157 158 159 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 157 def supports_index_sort_order? sqlite_version >= '3.3.0' end |
#supports_migrations? ⇒ Boolean
Returns true, since this connection adapter supports migrations.
111 112 113 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 111 def supports_migrations? #:nodoc: true end |
#supports_primary_key? ⇒ Boolean
Returns true.
116 117 118 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 116 def supports_primary_key? #:nodoc: true end |
#supports_savepoints? ⇒ Boolean
Returns true if SQLite version is ‘3.6.8’ or greater, false otherwise.
100 101 102 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 100 def supports_savepoints? sqlite_version >= '3.6.8' end |
#supports_statement_cache? ⇒ Boolean
Returns true, since this connection adapter supports prepared statement caching.
106 107 108 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 106 def supports_statement_cache? true end |
#table_exists?(name) ⇒ Boolean
340 341 342 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 340 def table_exists?(name) name && tables('SCHEMA', name).any? end |
#tables(name = 'SCHEMA', table_name = nil) ⇒ Object
SCHEMA STATEMENTS ========================================
327 328 329 330 331 332 333 334 335 336 337 338 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 327 def tables(name = 'SCHEMA', table_name = nil) #:nodoc: sql = <<-SQL SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence' SQL sql << " AND name = #{quote_table_name(table_name)}" if table_name exec_query(sql, name).map do |row| row['name'] end end |
#type_cast(value, column) ⇒ Object
:nodoc:
200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 200 def type_cast(value, column) # :nodoc: return value.to_f if BigDecimal === value return super unless String === value return super unless column && value value = super if column.type == :string && value.encoding == Encoding::ASCII_8BIT logger.error "Binary data inserted for `string` type on column `#{column.name}`" if logger value.encode! 'utf-8' end value end |
#update_sql(sql, name = nil) ⇒ Object
:nodoc:
281 282 283 284 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 281 def update_sql(sql, name = nil) #:nodoc: super @connection.changes end |
#valid_alter_table_options(type, options) ⇒ Object
See: www.sqlite.org/lang_altertable.html SQLite has an additional restriction on the ALTER TABLE statement
394 395 396 |
# File 'lib/active_record/connection_adapters/sqlite_adapter.rb', line 394 def ( type, ) type.to_sym != :primary_key end |