Active Record SQLite3 适配器¶ ↑
SQLite3 适配器可与 sqlite3 驱动程序配合使用。
选项¶ ↑
-
:database(String): 数据库文件的文件系统路径。 -
:statement_limit(Integer): 每个数据库连接缓存的预编译语句的最大数量。(默认值:1000) -
:timeout(Integer): 等待锁的超时时间(以毫秒为单位)。(默认值:不等待) -
:strict(Boolean): 启用或禁用严格模式。启用后,此设置将不允许 SQL 语句中使用双引号字符串字面量。(默认值:参见strict_strings_by_default) -
:extensions(Array): (**需要 sqlite3 v2.4.0**)每个条目指定一个要加载到此数据库的 sqlite 扩展。条目可以是文件系统路径,也可以是响应.to_path方法以提供扩展的文件系统路径的类名。有关更多信息,请参阅 sqlite3-ruby 文档。
可能还有其他特定于 SQLite3 驱动程序的选项。请阅读 SQLite3::Database.new 的文档。
- A
- C
- D
- E
- F
- N
- R
- S
-
- strict_strings_by_default,
- supports_check_constraints?,
- supports_common_table_expressions?,
- supports_concurrent_connections?,
- supports_datetime_with_precision?,
- supports_ddl_transactions?,
- supports_deferrable_constraints?,
- supports_explain?,
- supports_expression_index?,
- supports_foreign_keys?,
- supports_index_sort_order?,
- supports_insert_conflict_target?,
- supports_insert_on_conflict?,
- supports_insert_on_duplicate_skip?,
- supports_insert_on_duplicate_update?,
- supports_insert_returning?,
- supports_json?,
- supports_lazy_transactions?,
- supports_partial_index?,
- supports_savepoints?,
- supports_transaction_isolation?,
- supports_views?,
- supports_virtual_columns?
- V
常量
| 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 |
| FINAL_CLOSE_PARENS_REGEX | = | /\);*\z/ |
| FK_REGEX | = | /.*FOREIGN KEY\s+\("([^"]+)"\)\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) } |
| UNQUOTED_OPEN_PARENS_REGEX | = | /\((?![^'"]*['"][^'"]*$)/ |
| VIRTUAL_TABLE_REGEX | = | /USING\s+(\w+)\s*\((.+)\)/i |
类公共方法
dbconsole(config, options = {}) Link
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 60 def dbconsole(config, options = {}) args = [] args << "-#{options[:mode]}" if options[:mode] args << "-header" if options[:header] args << File.expand_path(config.database, defined?(Rails.root) ? Rails.root : nil) find_cmd_and_exec(ActiveRecord.database_cli[:sqlite], *args) end
new(...) Link
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 129 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 @previous_read_uncommitted = nil @config[:strict] = ConnectionAdapters::SQLite3Adapter.strict_strings_by_default unless @config.key?(:strict) extensions = @config.fetch(:extensions, []).map do |extension| extension.safe_constantize || extension end @connection_parameters = @config.merge( database: @config[:database].to_s, results_as_hash: true, default_transaction_mode: :immediate, extensions: extensions ) end
new_client(config) Link
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 50 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
strict_strings_by_default Link
配置 SQLite3Adapter 以“严格字符串”模式使用。启用后,此设置将不允许 SQL 语句中使用双引号字符串字面量,这可能会防止某些拼写错误,例如为不存在的列创建索引。默认值为 false。
如果您希望启用此模式,可以将以下行添加到您的 application.rb 文件中
config.active_record.sqlite3_adapter_strict_strings_by_default = true
也可以通过设置 strict: 选项在单个数据库上进行配置。
实例公共方法
active?() Link
add_timestamps(table_name, **options) Link
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 425 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
connected?() Link
create_virtual_table(table_name, module_name, values) Link
创建虚拟表
示例
create_virtual_table :emails, :fts5, ['sender', 'title', 'body']
database_exists?() Link
disconnect!() Link
如果已连接,则断开与数据库的连接。否则,此方法不执行任何操作。
drop_virtual_table(table_name, module_name, values, **options) Link
删除虚拟表
虽然此命令会忽略 module_name 和 values,但最好在迁移的 change 方法中提供它们,以便可以撤销。在这种情况下,module_name、values 和 options 将被 create_virtual_table 使用。
encoding() Link
以字符串形式返回当前数据库编码格式,例如‘UTF-8’
foreign_keys(table_name) Link
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 445 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
rename_table(table_name, new_name, **options) Link
重命名表。
示例
rename_table('octopuses', 'octopi')
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 358 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
requires_reloading?() Link
supports_check_constraints?() Link
supports_common_table_expressions?() Link
supports_concurrent_connections?() Link
supports_datetime_with_precision?() Link
supports_ddl_transactions?() Link
supports_deferrable_constraints?() Link
supports_explain?() Link
supports_expression_index?() Link
supports_foreign_keys?() Link
supports_index_sort_order?() Link
supports_insert_on_conflict?() Link
supports_insert_returning?() Link
supports_json?() Link
supports_lazy_transactions?() Link
supports_partial_index?() Link
supports_savepoints?() Link
supports_transaction_isolation?() Link
supports_views?() Link
supports_virtual_columns?() Link
virtual_tables() Link
返回已定义的虚拟表列表
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 325 def virtual_tables query = <<~SQL SELECT name, sql FROM sqlite_master WHERE sql LIKE 'CREATE VIRTUAL %'; SQL exec_query(query, "SCHEMA").cast_values.each_with_object({}) do |row, memo| table_name, sql = row[0], row[1] _, module_name, arguments = sql.match(VIRTUAL_TABLE_REGEX).to_a memo[table_name] = [module_name, arguments] end.to_a end