Class: ActiveRecord::ConnectionAdapters::SQLiteAdapter

### Home Classes Methods

### In Files

- lib/active_record/connection_adapters/sqlite_adapter.rb

### Parent

ActiveRecord::ConnectionAdapters::AbstractAdapter

### Namespace

- CLASS ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- CLASS ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- CLASS ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version

### Methods

- ::new
- #change_column_null
- #clear_cache!
- #create_savepoint
- #default_primary_key_type
- #disconnect!
- #empty_insert_statement_value
- #exec_delete
- #exec_query
- #exec_update
- #explain
- #last_inserted_id
- #release_savepoint
- #rename_table
- #requires_reloading?
- #rollback_to_savepoint
- #select_rows
- #sqlite_version
- #supports_add_column?
- #supports_ddl_transactions?
- #supports_explain?
- #supports_index_sort_order?
- #supports_savepoints?
- #supports_statement_cache?
- #table_exists?
- #table_structure
- #translate_exception
- #valid_alter_table_options

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::AttributeAssignment
- ActiveRecord::AttributeAssignment::ClassMethods
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::Serialization
- ActiveRecord::AttributeMethods::Serialization::Attribute
- ActiveRecord::AttributeMethods::Serialization::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Batches
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Coders
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::Mysql2Adapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaCache
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::StatementPool
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::Delegation
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicMatchers
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::Explain
- ActiveRecord::FinderMethods
- ActiveRecord::Fixtures
- ActiveRecord::Fixtures::File
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::IdentityMap
- ActiveRecord::IdentityMap::Middleware
- ActiveRecord::Inheritance
- ActiveRecord::Inheritance::ClassMethods
- ActiveRecord::Integration
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::Migration::CommandRecorder
- ActiveRecord::MigrationProxy
- ActiveRecord::ModelSchema
- ActiveRecord::ModelSchema::ClassMethods
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::Persistence::ClassMethods
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Querying
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::ReadonlyAttributes
- ActiveRecord::ReadonlyAttributes::ClassMethods
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Result
- ActiveRecord::Rollback
- ActiveRecord::Sanitization
- ActiveRecord::Sanitization::ClassMethods
- ActiveRecord::Schema
- ActiveRecord::Scoping
- ActiveRecord::Scoping::ClassMethods
- ActiveRecord::Scoping::Default
- ActiveRecord::Scoping::Default::ClassMethods
- ActiveRecord::Scoping::Named
- ActiveRecord::Scoping::Named::ClassMethods
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::Store
- ActiveRecord::Store::ClassMethods
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::Translation
- ActiveRecord::UnknownAttributeError
- ActiveRecord::UnknownPrimaryKey
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- Mysql
- Mysql::Result
- Mysql::Stmt
- Mysql::Time
- ArJdbcMySQL
- ArJdbcMySQL::Error

No matching classes.

# ActiveRecord::ConnectionAdapters::SQLiteAdapter

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.

### Public Class Methods

new(connection, logger, config) click to toggle source

    # 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

### Public Instance Methods

change_column_null(table_name, column_name, null, default = nil) click to toggle source

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

Clears the prepared statements cache.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 143
    def clear_cache!
      @statements.clear
    end

create_savepoint() click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 301
    def create_savepoint
      execute("SAVEPOINT #{current_savepoint_name}")
    end

disconnect!() click to toggle source

Disconnects from the database if already connected. Otherwise, this method does nothing.

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

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

    # 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

Also aliased as: exec_update
exec_query(sql, name = nil, binds = []) click to toggle source

    # 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

exec_update(sql, name = 'SQL', binds = []) click to toggle source
Alias for: exec_delete
explain(arel, binds = []) click to toggle source

DATABASE STATEMENTS ======================================

    # 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

last_inserted_id(result) click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 273
    def last_inserted_id(result)
      @connection.last_insert_row_id
    end

release_savepoint() click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 309
    def release_savepoint
      execute("RELEASE SAVEPOINT #{current_savepoint_name}")
    end

rename_table(name, new_name) click to toggle source

Renames a table.

Example:

    rename_table('octopuses', 'octopi')

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

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 125
    def requires_reloading?
      true
    end

rollback_to_savepoint() click to toggle source

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

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

Returns true if SQLite version is '3.1.6' or greater, false otherwise.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 130
    def supports_add_column?
      sqlite_version >= '3.1.6'
    end

supports_ddl_transactions?() click to toggle source

Returns true if SQLite version is '2.0.0' or greater, false otherwise.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 95
    def supports_ddl_transactions?
      sqlite_version >= '2.0.0'
    end

supports_explain?() click to toggle source

Returns true.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 121
    def supports_explain?
      true
    end

supports_index_sort_order?() click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 157
    def supports_index_sort_order?
      sqlite_version >= '3.3.0'
    end

supports_savepoints?() click to toggle source

Returns true if SQLite version is '3.6.8' or greater, false otherwise.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 100
    def supports_savepoints?
      sqlite_version >= '3.6.8'
    end

supports_statement_cache?() click to toggle source

Returns true, since this connection adapter supports prepared statement caching.

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 106
    def supports_statement_cache?
      true
    end

table_exists?(name) click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 340
    def table_exists?(name)
      name && tables('SCHEMA', name).any?
    end

valid_alter_table_options( type, options) click to toggle source

See: www.sqlite.org/lang_altertable.html SQLite has an additional restriction on the ALTER TABLE statement

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 394
    def valid_alter_table_options( type, options)
      type.to_sym != :primary_key
    end

### Protected Instance Methods

default_primary_key_type() click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 564
    def default_primary_key_type
      if supports_autoincrement?
        'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
      else
        'INTEGER PRIMARY KEY NOT NULL'
      end
    end

sqlite_version() click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 560
    def sqlite_version
      @sqlite_version ||= SQLiteAdapter::Version.new(select_value('select sqlite_version(*)'))
    end

table_structure(table_name) click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 470
    def table_structure(table_name)
      structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash
      raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
      structure
    end

translate_exception(exception, message) click to toggle source

    # File lib/active_record/connection_adapters/sqlite_adapter.rb, line 572
    def translate_exception(exception, message)
      case exception.message
      when /column(s)? .* (is|are) not unique/
        RecordNotUnique.new(message, exception)
      else
        super
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.