schema_dumper.rb 8.6 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "stringio"
4

5
module ActiveRecord
R
Rizwan Reza 已提交
6 7
  # = Active Record Schema Dumper
  #
8 9
  # This class is used to dump the database schema for some connection to some
  # output format (i.e., ActiveRecord::Schema).
10
  class SchemaDumper #:nodoc:
11
    private_class_method :new
A
Aaron Patterson 已提交
12

P
Pratik Naik 已提交
13 14
    ##
    # :singleton-method:
A
Aaron Patterson 已提交
15
    # A list of tables which should not be dumped to the schema.
16 17
    # Acceptable values are strings as well as regexp if ActiveRecord::Base.schema_format == :ruby.
    # Only strings are accepted if ActiveRecord::Base.schema_format == :sql.
18
    cattr_accessor :ignore_tables, default: []
19

20 21 22 23
    ##
    # :singleton-method:
    # Specify a custom regular expression matching foreign keys which name
    # should not be dumped to db/schema.rb.
24
    cattr_accessor :fk_ignore_pattern, default: /^fk_rails_[0-9a-f]{10}$/
25

W
wangjohn 已提交
26
    class << self
27
      def dump(connection = ActiveRecord::Base.connection, stream = STDOUT, config = ActiveRecord::Base)
28
        connection.create_schema_dumper(generate_options(config)).dump(stream)
W
wangjohn 已提交
29 30 31 32 33 34 35 36 37 38
        stream
      end

      private
        def generate_options(config)
          {
            table_name_prefix: config.table_name_prefix,
            table_name_suffix: config.table_name_suffix
          }
        end
39 40 41 42
    end

    def dump(stream)
      header(stream)
43
      extensions(stream)
44 45 46 47 48 49 50
      tables(stream)
      trailer(stream)
      stream
    end

    private

W
wangjohn 已提交
51
      def initialize(connection, options = {})
52
        @connection = connection
53
        @version = connection.migration_context.current_version rescue nil
W
wangjohn 已提交
54
        @options = options
55 56
      end

R
Ryuta Kamizono 已提交
57
      # turns 20170404131909 into "2017_04_04_131909"
58 59 60 61 62 63
      def formatted_version
        stringified = @version.to_s
        return stringified unless stringified.length == 14
        stringified.insert(4, "_").insert(7, "_").insert(10, "_")
      end

R
Ryuta Kamizono 已提交
64 65 66
      def define_params
        @version ? "version: #{formatted_version}" : ""
      end
67

R
Ryuta Kamizono 已提交
68
      def header(stream)
69
        stream.puts <<HEADER
70
# This file is auto-generated from the current state of the database. Instead
R
Rizwan Reza 已提交
71 72
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
73
#
74 75 76 77 78
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
79
#
80
# It's strongly recommended that you check this file into your version control system.
81

82
ActiveRecord::Schema.define(#{define_params}) do
83

84
HEADER
85 86 87 88 89 90
      end

      def trailer(stream)
        stream.puts "end"
      end

91
      # extensions are only supported by PostgreSQL
92 93 94
      def extensions(stream)
      end

95
      def tables(stream)
96
        sorted_tables = @connection.tables.sort
97 98 99

        sorted_tables.each do |table_name|
          table(table_name, stream) unless ignored?(table_name)
100
        end
101 102 103 104

        # dump foreign keys at the end to make sure all dependent tables exist.
        if @connection.supports_foreign_keys?
          sorted_tables.each do |tbl|
105
            foreign_keys(tbl, stream) unless ignored?(tbl)
106 107
          end
        end
108 109 110
      end

      def table(table, stream)
111
        columns = @connection.columns(table)
112 113
        begin
          tbl = StringIO.new
114

115
          # first dump primary key column
116
          pk = @connection.primary_key(table)
A
Aaron Patterson 已提交
117

118
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
119 120 121

          case pk
          when String
122
            tbl.print ", primary_key: #{pk.inspect}" unless pk == "id"
123
            pkcol = columns.detect { |c| c.name == pk }
124
            pkcolspec = column_spec_for_primary_key(pkcol)
125
            if pkcolspec.present?
126
              tbl.print ", #{format_colspec(pkcolspec)}"
127
            end
128 129
          when Array
            tbl.print ", primary_key: #{pk.inspect}"
130
          else
131
            tbl.print ", id: false"
132
          end
133 134

          table_options = @connection.table_options(table)
135
          if table_options.present?
R
Ryuta Kamizono 已提交
136
            tbl.print ", #{format_options(table_options)}"
137
          end
138

139
          tbl.puts ", force: :cascade do |t|"
140

R
Ryuta Kamizono 已提交
141 142 143 144
          # then dump all non-primary key columns
          columns.each do |column|
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
            next if column.name == pk
145
            type, colspec = column_spec(column)
146 147 148
            tbl.print "    t.#{type} #{column.name.inspect}"
            tbl.print ", #{format_colspec(colspec)}" if colspec.present?
            tbl.puts
149 150
          end

151 152
          indexes_in_create(table, tbl)

153 154
          tbl.puts "  end"
          tbl.puts
A
Aaron Patterson 已提交
155

156 157 158 159 160
          tbl.rewind
          stream.print tbl.read
        rescue => e
          stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}"
          stream.puts "#   #{e.message}"
161 162 163 164
          stream.puts
        end
      end

165
      # Keep it for indexing materialized views
166
      def indexes(table, stream)
167 168
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
169
            table_name = remove_prefix_and_suffix(index.table).inspect
170
            "  add_index #{([table_name] + index_parts(index)).join(', ')}"
171 172 173
          end

          stream.puts add_index_statements.sort.join("\n")
174
          stream.puts
175 176
        end
      end
177

178 179 180 181 182 183 184 185 186 187 188 189 190 191
      def indexes_in_create(table, stream)
        if (indexes = @connection.indexes(table)).any?
          index_statements = indexes.map do |index|
            "    t.index #{index_parts(index).join(', ')}"
          end
          stream.puts index_statements.sort.join("\n")
        end
      end

      def index_parts(index)
        index_parts = [
          index.columns.inspect,
          "name: #{index.name.inspect}",
        ]
192
        index_parts << "unique: true" if index.unique
193 194 195
        index_parts << "length: #{format_index_parts(index.lengths)}" if index.lengths.present?
        index_parts << "order: #{format_index_parts(index.orders)}" if index.orders.present?
        index_parts << "opclass: #{format_index_parts(index.opclasses)}" if index.opclasses.present?
196
        index_parts << "where: #{index.where.inspect}" if index.where
197
        index_parts << "using: #{index.using.inspect}" if !@connection.default_index_type?(index)
198 199 200 201 202
        index_parts << "type: #{index.type.inspect}" if index.type
        index_parts << "comment: #{index.comment.inspect}" if index.comment
        index_parts
      end

Y
Yves Senn 已提交
203 204 205 206
      def foreign_keys(table, stream)
        if (foreign_keys = @connection.foreign_keys(table)).any?
          add_foreign_key_statements = foreign_keys.map do |foreign_key|
            parts = [
T
Tee Parham 已提交
207 208 209
              "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
              remove_prefix_and_suffix(foreign_key.to_table).inspect,
            ]
Y
Yves Senn 已提交
210 211

            if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table)
212
              parts << "column: #{foreign_key.column.inspect}"
Y
Yves Senn 已提交
213 214 215
            end

            if foreign_key.custom_primary_key?
216
              parts << "primary_key: #{foreign_key.primary_key.inspect}"
Y
Yves Senn 已提交
217 218
            end

219
            if foreign_key.export_name_on_schema_dump?
220
              parts << "name: #{foreign_key.name.inspect}"
Y
Yves Senn 已提交
221 222
            end

223 224
            parts << "on_update: #{foreign_key.on_update.inspect}" if foreign_key.on_update
            parts << "on_delete: #{foreign_key.on_delete.inspect}" if foreign_key.on_delete
225

226
            "  #{parts.join(', ')}"
Y
Yves Senn 已提交
227 228 229 230 231 232
          end

          stream.puts add_foreign_key_statements.sort.join("\n")
        end
      end

233 234 235 236
      def format_colspec(colspec)
        colspec.map { |key, value| "#{key}: #{value}" }.join(", ")
      end

R
Ryuta Kamizono 已提交
237
      def format_options(options)
R
Ryuta Kamizono 已提交
238
        options.map { |key, value| "#{key}: #{value.inspect}" }.join(", ")
R
Ryuta Kamizono 已提交
239 240
      end

241 242 243 244 245 246 247 248
      def format_index_parts(options)
        if options.is_a?(Hash)
          "{ #{format_options(options)} }"
        else
          options.inspect
        end
      end

249
      def remove_prefix_and_suffix(table)
250 251 252
        prefix = Regexp.escape(@options[:table_name_prefix].to_s)
        suffix = Regexp.escape(@options[:table_name_suffix].to_s)
        table.sub(/\A#{prefix}(.+)#{suffix}\z/, "\\1")
253
      end
254 255

      def ignored?(table_name)
256
        [ActiveRecord::Base.schema_migrations_table_name, ActiveRecord::Base.internal_metadata_table_name, ignore_tables].flatten.any? do |ignored|
257
          ignored === remove_prefix_and_suffix(table_name)
258 259
        end
      end
260
  end
J
Jeremy Kemper 已提交
261
end