модуль ActiveRecord::ConnectionHandling
Константы
- DEFAULT_ENV
- RAILS_ENV
Атрибуты
Публичные методы экземпляров
# File activerecord/lib/active_record/connection_handling.rb, line 132 def connected? connection_handler.connected?(connection_specification_name) end
Возвращает true, если Active Record подключен.
# File activerecord/lib/active_record/connection_handling.rb, line 90 def connection retrieve_connection end
Возвращает соединение, в настоящее время связанное с классом. Его также можно использовать, чтобы «одолжить» соединение для выполнения работы с базой данных, не связанной с конкретными Active Records.
# File activerecord/lib/active_record/connection_handling.rb, line 119 def connection_config connection_pool.spec.config end
Возвращает конфигурацию связанного соединения в виде хэша:
ActiveRecord::Base.connection_config
# => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
Используйте только для чтения.
# File activerecord/lib/active_record/connection_handling.rb, line 105 def connection_id ActiveRecord::RuntimeRegistry.connection_id ||= Thread.current.object_id end
# File activerecord/lib/active_record/connection_handling.rb, line 109 def connection_id=(connection_id) ActiveRecord::RuntimeRegistry.connection_id = connection_id end
# File activerecord/lib/active_record/connection_handling.rb, line 123 def connection_pool connection_handler.retrieve_connection_pool(connection_specification_name) or raise ConnectionNotEstablished end
# File activerecord/lib/active_record/connection_handling.rb, line 98
def connection_specification_name
if !defined?(@connection_specification_name) || @connection_specification_name.nil?
return self == Base ? "primary" : superclass.connection_specification_name
end
@connection_specification_name
end Возвращает идентификатор спецификации из этого класса, в противном случае ищет его в родительском классе.
# File activerecord/lib/active_record/connection_handling.rb, line 47
def establish_connection(spec = nil)
raise RuntimeError, "Anonymous class is not allowed." unless name
spec ||= DEFAULT_ENV.call.to_sym
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new configurations
# TODO: uses name on establish_connection, for backwards compatibility
spec = resolver.spec(spec, self == Base ? "primary" : name)
unless respond_to?(spec.adapter_method)
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
end
remove_connection(spec.name)
self.connection_specification_name = spec.name
connection_handler.establish_connection spec
end Устанавливает соединение с базой данных. Принимает хэш в качестве входных данных, где ключ adapter должен быть указан с именем адаптера базы данных (в нижнем регистре), например для обычных баз данных (MySQL, PostgreSQL и т. д.):
ActiveRecord::Base.establish_connection( adapter: "mysql2", host: "localhost", username: "myuser", password: "mypass", database: "somedatabase" )
Пример для базы данных SQLite:
ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: "path/to/dbfile" )
Также принимает ключи в виде строк (например, для парсинга из YAML):
ActiveRecord::Base.establish_connection( "adapter" => "sqlite3", "database" => "path/to/dbfile" )
Или URL:
ActiveRecord::Base.establish_connection( "postgres://myuser:mypass@localhost/somedatabase" )
В случае, если ActiveRecord::Base.configurations задан (Rails автоматически загружает содержимое config/database.yml в него), в качестве аргумента также можно указать символ, представляющий ключ в хэше конфигурации:
ActiveRecord::Base.establish_connection(:production)
При ошибке могут быть возвращены исключения AdapterNotSpecified, AdapterNotFound и DatabaseConnectionError.
# File activerecord/lib/active_record/connection_handling.rb, line 136
def remove_connection(name = nil)
name ||= @connection_specification_name if defined?(@connection_specification_name)
# if removing a connection that have a pool, we reset the
# connection_specification_name so it will use the parent
# pool.
if connection_handler.retrieve_connection_pool(name)
self.connection_specification_name = nil
end
connection_handler.remove_connection(name)
end # File activerecord/lib/active_record/connection_handling.rb, line 127 def retrieve_connection connection_handler.retrieve_connection(connection_specification_name) end
© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.