Active Record SQLite3 Adapter

The SQLite3 adapter works with the sqlite3-ruby drivers (available as gem from rubygems.org/gems/sqlite3).

Options:

  • :database - Path to the database file.

Methods

Included Modules

Constants

ADAPTER_NAME = "SQLite"
COLLATE_REGEX = /.*"(\w+)".*collate\s+"(\w+)".*/i
DEFAULT_PRAGMAS = { "foreign_keys" => true, "journal_mode" => :wal, "synchronous" => :normal, "mmap_size" => 134217728, # 128 megabytes "journal_size_limit" => 67108864, # 64 megabytes "cache_size" => 2000 }
DEFERRABLE_REGEX = /DEFERRABLE INITIALLY (\w+)/
EXTENDED_TYPE_MAPS = Concurrent::Map.new
FK_REGEX = /.*FOREIGN KEY\s+\("(\w+)"\)\s+REFERENCES\s+"(\w+)"\s+\("(\w+)"\)/
GENERATED_ALWAYS_AS_REGEX = /.*"(\w+)".+GENERATED ALWAYS AS \((.+)\) (?:STORED|VIRTUAL)/i
NATIVE_DATABASE_TYPES = { primary_key: "integer PRIMARY KEY AUTOINCREMENT NOT NULL", string: { name: "varchar" }, text: { name: "text" }, integer: { name: "integer" }, float: { name: "float" }, decimal: { name: "decimal" }, datetime: { name: "datetime" }, time: { name: "time" }, date: { name: "date" }, binary: { name: "blob" }, boolean: { name: "boolean" }, json: { name: "json" }, }
PRIMARY_KEY_AUTOINCREMENT_REGEX = /.*"(\w+)".+PRIMARY KEY AUTOINCREMENT/i
TYPE_MAP = Type::TypeMap.new.tap { |m| initialize_type_map(m) }

Class Public methods

dbconsole(config, options = {})

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 41
        def dbconsole(config, options = {})
          args = []

          args << "-#{options[:mode]}" if options[:mode]
          args << "-header" if options[:header]
          args << File.expand_path(config.database, Rails.respond_to?(:root) ? Rails.root : nil)

          find_cmd_and_exec("sqlite3", *args)
        end
🔎 See on GitHub

new(...)

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 99
      def initialize(...)
        super

        @memory_database = false
        case @config[:database].to_s
        when ""
          raise ArgumentError, "No database file specified. Missing argument: database"
        when ":memory:"
          @memory_database = true
        when /\Afile:/
        else
          # Otherwise we have a path relative to Rails.root
          @config[:database] = File.expand_path(@config[:database], Rails.root) if defined?(Rails.root)
          dirname = File.dirname(@config[:database])
          unless File.directory?(dirname)
            begin
              FileUtils.mkdir_p(dirname)
            rescue SystemCallError
              raise ActiveRecord::NoDatabaseError.new(connection_pool: @pool)
            end
          end
        end

        @config[:strict] = ConnectionAdapters::SQLite3Adapter.strict_strings_by_default unless @config.key?(:strict)
        @connection_parameters = @config.merge(database: @config[:database].to_s, results_as_hash: true)
        @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
      end
🔎 See on GitHub

new_client(config)

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 31
        def new_client(config)
          ::SQLite3::Database.new(config[:database].to_s, config)
        rescue Errno::ENOENT => error
          if error.message.include?("No such file or directory")
            raise ActiveRecord::NoDatabaseError
          else
            raise
          end
        end
🔎 See on GitHub

strict_strings_by_default

Configure the SQLite3Adapter to be used in a strict strings mode. This will disable double-quoted string literals, because otherwise typos can silently go unnoticed. For example, it is possible to create an index for a non existing column. If you wish to enable this mode you can add the following line to your application.rb file:

config.active_record.sqlite3_adapter_strict_strings_by_default = true
📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 64
      class_attribute :strict_strings_by_default, default: false
🔎 See on GitHub

Instance Public methods

active?()

Alias for: connected?

add_timestamps(table_name, **options)

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 352
      def add_timestamps(table_name, **options)
        options[:null] = false if options[:null].nil?

        if !options.key?(:precision)
          options[:precision] = 6
        end

        alter_table(table_name) do |definition|
          definition.column :created_at, :datetime, **options
          definition.column :updated_at, :datetime, **options
        end
      end
🔎 See on GitHub

connected?()

Also aliased as: active?
📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 198
      def connected?
        !(@raw_connection.nil? || @raw_connection.closed?)
      end
🔎 See on GitHub

database_exists?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 127
      def database_exists?
        @config[:database] == ":memory:" || File.exist?(@config[:database].to_s)
      end
🔎 See on GitHub

disconnect!()

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

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 208
      def disconnect!
        super

        @raw_connection&.close rescue nil
        @raw_connection = nil
      end
🔎 See on GitHub

encoding()

Returns the current database encoding format as a string, e.g. ‘UTF-8’

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 224
      def encoding
        any_raw_connection.encoding.to_s
      end
🔎 See on GitHub

foreign_keys(table_name)

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 372
      def foreign_keys(table_name)
        # SQLite returns 1 row for each column of composite foreign keys.
        fk_info = internal_exec_query("PRAGMA foreign_key_list(#{quote(table_name)})", "SCHEMA")
        # Deferred or immediate foreign keys can only be seen in the CREATE TABLE sql
        fk_defs = table_structure_sql(table_name)
                    .select do |column_string|
                      column_string.start_with?("CONSTRAINT") &&
                      column_string.include?("FOREIGN KEY")
                    end
                    .to_h do |fk_string|
                      _, from, table, to = fk_string.match(FK_REGEX).to_a
                      _, mode = fk_string.match(DEFERRABLE_REGEX).to_a
                      deferred = mode&.downcase&.to_sym || false
                      [[table, from, to], deferred]
                    end

        grouped_fk = fk_info.group_by { |row| row["id"] }.values.each { |group| group.sort_by! { |row| row["seq"] } }
        grouped_fk.map do |group|
          row = group.first
          options = {
            on_delete: extract_foreign_key_action(row["on_delete"]),
            on_update: extract_foreign_key_action(row["on_update"]),
            deferrable: fk_defs[[row["table"], row["from"], row["to"]]]
          }

          if group.one?
            options[:column] = row["from"]
            options[:primary_key] = row["to"]
          else
            options[:column] = group.map { |row| row["from"] }
            options[:primary_key] = group.map { |row| row["to"] }
          end
          ForeignKeyDefinition.new(table_name, row["table"], options)
        end
      end
🔎 See on GitHub

rename_table(table_name, new_name, **options)

Renames a table.

Example:

rename_table('octopuses', 'octopi')
📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 285
      def rename_table(table_name, new_name, **options)
        validate_table_length!(new_name) unless options[:_uses_legacy_table_name]
        schema_cache.clear_data_source_cache!(table_name.to_s)
        schema_cache.clear_data_source_cache!(new_name.to_s)
        exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
        rename_table_indexes(table_name, new_name, **options)
      end
🔎 See on GitHub

requires_reloading?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 151
      def requires_reloading?
        true
      end
🔎 See on GitHub

supports_check_constraints?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 159
      def supports_check_constraints?
        true
      end
🔎 See on GitHub

supports_common_table_expressions?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 175
      def supports_common_table_expressions?
        database_version >= "3.8.3"
      end
🔎 See on GitHub

supports_concurrent_connections?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 190
      def supports_concurrent_connections?
        !@memory_database
      end
🔎 See on GitHub

supports_datetime_with_precision?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 167
      def supports_datetime_with_precision?
        true
      end
🔎 See on GitHub

supports_ddl_transactions?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 131
      def supports_ddl_transactions?
        true
      end
🔎 See on GitHub

supports_deferrable_constraints?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 236
      def supports_deferrable_constraints?
        true
      end
🔎 See on GitHub

supports_explain?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 228
      def supports_explain?
        true
      end
🔎 See on GitHub

supports_expression_index?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 147
      def supports_expression_index?
        database_version >= "3.9.0"
      end
🔎 See on GitHub

supports_foreign_keys?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 155
      def supports_foreign_keys?
        true
      end
🔎 See on GitHub

supports_index_sort_order?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 215
      def supports_index_sort_order?
        true
      end
🔎 See on GitHub

supports_insert_conflict_target?()

supports_insert_on_conflict?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 183
      def supports_insert_on_conflict?
        database_version >= "3.24.0"
      end
🔎 See on GitHub

supports_insert_on_duplicate_skip?()

supports_insert_on_duplicate_update?()

supports_insert_returning?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 179
      def supports_insert_returning?
        database_version >= "3.35.0"
      end
🔎 See on GitHub

supports_json?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 171
      def supports_json?
        true
      end
🔎 See on GitHub

supports_lazy_transactions?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 232
      def supports_lazy_transactions?
        true
      end
🔎 See on GitHub

supports_partial_index?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 143
      def supports_partial_index?
        true
      end
🔎 See on GitHub

supports_savepoints?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 135
      def supports_savepoints?
        true
      end
🔎 See on GitHub

supports_transaction_isolation?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 139
      def supports_transaction_isolation?
        true
      end
🔎 See on GitHub

supports_views?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 163
      def supports_views?
        true
      end
🔎 See on GitHub

supports_virtual_columns?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 194
      def supports_virtual_columns?
        database_version >= "3.31.0"
      end
🔎 See on GitHub

use_insert_returning?()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 431
      def use_insert_returning?
        @use_insert_returning
      end
🔎 See on GitHub