schema_dumper.rb 8.2 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

W
wangjohn 已提交
20
    class << self
21
      def dump(connection = ActiveRecord::Base.connection, stream = STDOUT, config = ActiveRecord::Base)
22
        connection.create_schema_dumper(generate_options(config)).dump(stream)
W
wangjohn 已提交
23 24 25 26 27 28 29 30 31 32
        stream
      end

      private
        def generate_options(config)
          {
            table_name_prefix: config.table_name_prefix,
            table_name_suffix: config.table_name_suffix
          }
        end
33 34 35 36
    end

    def dump(stream)
      header(stream)
37
      extensions(stream)
38 39 40 41 42 43 44
      tables(stream)
      trailer(stream)
      stream
    end

    private

W
wangjohn 已提交
45
      def initialize(connection, options = {})
46
        @connection = connection
47
        @version = Migrator::current_version rescue nil
W
wangjohn 已提交
48
        @options = options
49 50
      end

R
Ryuta Kamizono 已提交
51
      # turns 20170404131909 into "2017_04_04_131909"
52 53 54 55 56 57
      def formatted_version
        stringified = @version.to_s
        return stringified unless stringified.length == 14
        stringified.insert(4, "_").insert(7, "_").insert(10, "_")
      end

R
Ryuta Kamizono 已提交
58 59 60
      def define_params
        @version ? "version: #{formatted_version}" : ""
      end
61

R
Ryuta Kamizono 已提交
62
      def header(stream)
63
        stream.puts <<HEADER
64
# This file is auto-generated from the current state of the database. Instead
R
Rizwan Reza 已提交
65 66
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
67
#
68
# Note that this schema.rb definition is the authoritative source for your
R
Rizwan Reza 已提交
69 70 71
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
72 73
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
74
# It's strongly recommended that you check this file into your version control system.
75

76
ActiveRecord::Schema.define(#{define_params}) do
77

78
HEADER
79 80 81 82 83 84
      end

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

85
      # extensions are only supported by PostgreSQL
86 87 88
      def extensions(stream)
      end

89
      def tables(stream)
90
        sorted_tables = @connection.tables.sort
91 92 93

        sorted_tables.each do |table_name|
          table(table_name, stream) unless ignored?(table_name)
94
        end
95 96 97 98

        # dump foreign keys at the end to make sure all dependent tables exist.
        if @connection.supports_foreign_keys?
          sorted_tables.each do |tbl|
99
            foreign_keys(tbl, stream) unless ignored?(tbl)
100 101
          end
        end
102 103 104
      end

      def table(table, stream)
105
        columns = @connection.columns(table)
106 107
        begin
          tbl = StringIO.new
108

109
          # first dump primary key column
110
          pk = @connection.primary_key(table)
A
Aaron Patterson 已提交
111

112
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
113 114 115

          case pk
          when String
116
            tbl.print ", primary_key: #{pk.inspect}" unless pk == "id"
117
            pkcol = columns.detect { |c| c.name == pk }
118
            pkcolspec = column_spec_for_primary_key(pkcol)
119
            if pkcolspec.present?
120
              tbl.print ", #{format_colspec(pkcolspec)}"
121
            end
122 123
          when Array
            tbl.print ", primary_key: #{pk.inspect}"
124
          else
125
            tbl.print ", id: false"
126
          end
127 128

          table_options = @connection.table_options(table)
129
          if table_options.present?
R
Ryuta Kamizono 已提交
130
            tbl.print ", #{format_options(table_options)}"
131
          end
132

133
          tbl.puts ", force: :cascade do |t|"
134

R
Ryuta Kamizono 已提交
135 136 137 138
          # 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
139
            type, colspec = column_spec(column)
140 141 142
            tbl.print "    t.#{type} #{column.name.inspect}"
            tbl.print ", #{format_colspec(colspec)}" if colspec.present?
            tbl.puts
143 144
          end

145 146
          indexes_in_create(table, tbl)

147 148
          tbl.puts "  end"
          tbl.puts
A
Aaron Patterson 已提交
149

150 151 152 153 154
          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}"
155 156 157 158
          stream.puts
        end
      end

159
      # Keep it for indexing materialized views
160
      def indexes(table, stream)
161 162
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
163
            table_name = remove_prefix_and_suffix(index.table).inspect
164
            "  add_index #{([table_name] + index_parts(index)).join(', ')}"
165 166 167
          end

          stream.puts add_index_statements.sort.join("\n")
168
          stream.puts
169 170
        end
      end
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185
      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}",
        ]
186
        index_parts << "unique: true" if index.unique
187 188
        index_parts << "length: { #{format_options(index.lengths)} }" if index.lengths.present?
        index_parts << "order: { #{format_options(index.orders)} }" if index.orders.present?
189
        index_parts << "where: #{index.where.inspect}" if index.where
190
        index_parts << "using: #{index.using.inspect}" if !@connection.default_index_type?(index)
191
        index_parts << "type: #{index.type.inspect}" if index.type
192
        index_parts << "opclass: #{index.opclass.inspect}" if index.opclass.present?
193 194 195 196
        index_parts << "comment: #{index.comment.inspect}" if index.comment
        index_parts
      end

Y
Yves Senn 已提交
197 198 199 200
      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 已提交
201 202 203
              "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
              remove_prefix_and_suffix(foreign_key.to_table).inspect,
            ]
Y
Yves Senn 已提交
204 205

            if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table)
206
              parts << "column: #{foreign_key.column.inspect}"
Y
Yves Senn 已提交
207 208 209
            end

            if foreign_key.custom_primary_key?
210
              parts << "primary_key: #{foreign_key.primary_key.inspect}"
Y
Yves Senn 已提交
211 212 213
            end

            if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/
214
              parts << "name: #{foreign_key.name.inspect}"
Y
Yves Senn 已提交
215 216
            end

217 218
            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
219

220
            "  #{parts.join(', ')}"
Y
Yves Senn 已提交
221 222 223 224 225 226
          end

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

227 228 229 230
      def format_colspec(colspec)
        colspec.map { |key, value| "#{key}: #{value}" }.join(", ")
      end

R
Ryuta Kamizono 已提交
231
      def format_options(options)
R
Ryuta Kamizono 已提交
232
        options.map { |key, value| "#{key}: #{value.inspect}" }.join(", ")
R
Ryuta Kamizono 已提交
233 234
      end

235
      def remove_prefix_and_suffix(table)
236 237 238
        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")
239
      end
240 241

      def ignored?(table_name)
242
        [ActiveRecord::Base.schema_migrations_table_name, ActiveRecord::Base.internal_metadata_table_name, ignore_tables].flatten.any? do |ignored|
243
          ignored === remove_prefix_and_suffix(table_name)
244 245
        end
      end
246
  end
J
Jeremy Kemper 已提交
247
end