method

foreign_keys

Importance_0
v7.2.3 - Show latest stable - 0 notes - Class: ActiveRecord::ConnectionAdapters::SQLite3Adapter
foreign_keys(table_name) public

No documentation

This method has no description. You can help the Ruby on Rails community by adding new notes.

Hide source
# File activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb, line 377
      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
Register or log in to add new notes.