Spec-Zone.ru › Ruby on Rails 5.2

класс ActiveRecord::ConnectionAdapters::SQLite3Adapter

Родитель:
ActiveRecord::ConnectionAdapters::AbstractAdapter

Адаптер SQLite3 работает с SQLite 3.6.16 или новее с драйверами sqlite3-ruby (доступен как gem на rubygems.org/gems/sqlite3).

Опции:

  • :database - Путь к файлу базы данных.

Константы

ADAPTER_NAME
COLLATE_REGEX
NATIVE_DATABASE_TYPES

Публичные методы класса

new(connection, logger, connection_options, config) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 101
def initialize(connection, logger, connection_options, config)
  super(connection, logger, config)

  @active     = true
  @statements = StatementPool.new(self.class.type_cast_config_to_integer(config[:statement_limit]))

  configure_connection
end
Вызывает метод суперкласса ActiveRecord::ConnectionAdapters::QueryCache.new
represent_boolean_as_integer() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 92
class_attribute :represent_boolean_as_integer, default: false

Указывает, хранятся ли значения булевых типов в базах данных sqlite3 как 1 и 0 или 't' и 'f'. Оставление ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer в значении false устарело. Базы данных SQLite используют 't' и 'f' для сериализации булевых значений и требуют преобразования старых данных в 1 и 0 (родная сериализация булевых типов) перед установкой этого флага в значение true. Преобразование можно выполнить, создав задачу rake, которая выполнит

ExampleModel.where("boolean_column = 't'").update_all(boolean_column: 1)
ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)

для всех моделей и всех столбцов булевого типа, после чего флаг должен быть установлен в true, добавив следующее в ваш файл application.rb:

Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true

Общедоступные методы экземпляра

active?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 146
def active?
  @active
end
allowed_index_name_length() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 170
def allowed_index_name_length
  index_name_length - 2
end

Возвращает 62. SQLite поддерживает имена индексов длиной до 64 символов. Остальное используется Rails для внутренних операций временного переименования.

clear_cache!() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 159
def clear_cache!
  @statements.clear
end

Очищает кэш подготовленных запросов.

disconnect!() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 152
def disconnect!
  super
  @active = false
  @connection.close rescue nil
end

Отключается от базы данных, если уже подключен. В противном случае этот метод ничего не делает.

Вызывает метод суперкласса ActiveRecord::ConnectionAdapters::AbstractAdapter#disconnect!
encoding() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 179
def encoding
  @connection.encoding.to_s
end

Возвращает текущий формат кодирования базы данных в виде строки, например: 'UTF-8'

exec_delete(sql, name = "SQL", binds = []) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 242
def exec_delete(sql, name = "SQL", binds = [])
  exec_query(sql, name, binds)
  @connection.changes
end
Также псевдоним: exec_update
exec_query(sql, name = nil, binds = [], prepare: false) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 209
def exec_query(sql, name = nil, binds = [], prepare: false)
  type_casted_binds = type_casted_binds(binds)

  log(sql, name, binds, type_casted_binds) do
    ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
      # Don't cache statements if they are not prepared
      unless prepare
        stmt = @connection.prepare(sql)
        begin
          cols = stmt.columns
          unless without_prepared_statement?(binds)
            stmt.bind_params(type_casted_binds)
          end
          records = stmt.to_a
        ensure
          stmt.close
        end
      else
        cache = @statements[sql] ||= {
          stmt: @connection.prepare(sql)
        }
        stmt = cache[:stmt]
        cols = cache[:cols] ||= stmt.columns
        stmt.reset!
        stmt.bind_params(type_casted_binds)
        records = stmt.to_a
      end

      ActiveRecord::Result.new(cols, records)
    end
  end
end
exec_update(sql, name = "SQL", binds = [])
Псевдоним для: exec_delete
explain(arel, binds = []) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 204
def explain(arel, binds = [])
  sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
  SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", []))
end
foreign_keys(table_name) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 356
def foreign_keys(table_name)
  fk_info = exec_query("PRAGMA foreign_key_list(#{quote(table_name)})", "SCHEMA")
  fk_info.map do |row|
    options = {
      column: row["from"],
      primary_key: row["to"],
      on_delete: extract_foreign_key_action(row["on_delete"]),
      on_update: extract_foreign_key_action(row["on_update"])
    }
    ForeignKeyDefinition.new(table_name, row["table"], options)
  end
end
insert_fixtures(rows, table_name) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 369
      def insert_fixtures(rows, table_name)
        ActiveSupport::Deprecation.warn(<<-MSG.squish)
          `insert_fixtures` is deprecated and will be removed in the next version of Rails.
          Consider using `insert_fixtures_set` for performance improvement.
        MSG
        insert_fixtures_set(table_name => rows)
      end
insert_fixtures_set(fixture_set, tables_to_delete = []) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 377
def insert_fixtures_set(fixture_set, tables_to_delete = [])
  disable_referential_integrity do
    transaction(requires_new: true) do
      tables_to_delete.each { |table| delete "DELETE FROM #{quote_table_name(table)}", "Fixture Delete" }

      fixture_set.each do |table_name, rows|
        rows.each { |row| insert_fixture(row, table_name) }
      end
    end
  end
end
last_inserted_id(result) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 248
def last_inserted_id(result)
  @connection.last_insert_row_id
end
rename_table(table_name, new_name) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 288
def rename_table(table_name, new_name)
  exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
  rename_table_indexes(table_name, new_name)
end

Переименовывает таблицу.

Пример:

rename_table('octopuses', 'octopi')
requires_reloading?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 122
def requires_reloading?
  true
end
supports_datetime_with_precision?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 134
def supports_datetime_with_precision?
  true
end
supports_ddl_transactions?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 110
def supports_ddl_transactions?
  true
end
supports_explain?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 183
def supports_explain?
  true
end
supports_foreign_keys_in_create?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 126
def supports_foreign_keys_in_create?
  sqlite_version >= "3.6.19"
end
supports_index_sort_order?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 163
def supports_index_sort_order?
  true
end
supports_json?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 138
def supports_json?
  true
end
supports_multi_insert?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 142
def supports_multi_insert?
  sqlite_version >= "3.7.11"
end
supports_partial_index?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 118
def supports_partial_index?
  sqlite_version >= "3.8.0"
end
supports_savepoints?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 114
def supports_savepoints?
  true
end
supports_views?() Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 130
def supports_views?
  true
end
valid_alter_table_type?(type, options = {}) Показать исходный код
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 293
def valid_alter_table_type?(type, options = {})
  !invalid_alter_table_type?(type, options)
end

© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API