schema_dumper.rb 8.4 KB
Newer Older
1
require "stringio"
2

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

P
Pratik Naik 已提交
11 12
    ##
    # :singleton-method:
A
Aaron Patterson 已提交
13
    # A list of tables which should not be dumped to the schema.
14 15
    # Acceptable values are strings as well as regexp.
    # This setting is only used if ActiveRecord::Base.schema_format == :ruby
A
Aaron Patterson 已提交
16
    cattr_accessor :ignore_tables
17
    @@ignore_tables = []
18

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

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

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

    private

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

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

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

R
Ryuta Kamizono 已提交
61
      def header(stream)
62
        stream.puts <<HEADER
63
# This file is auto-generated from the current state of the database. Instead
R
Rizwan Reza 已提交
64 65
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
66
#
67
# Note that this schema.rb definition is the authoritative source for your
R
Rizwan Reza 已提交
68 69 70
# 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
71 72
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
73
# It's strongly recommended that you check this file into your version control system.
74

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

77
HEADER
78 79 80 81 82 83
      end

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

84 85 86
      def extensions(stream)
        return unless @connection.supports_extensions?
        extensions = @connection.extensions
87 88 89 90 91 92
        if extensions.any?
          stream.puts "  # These are extensions that must be enabled in order to support this database"
          extensions.each do |extension|
            stream.puts "  enable_extension #{extension.inspect}"
          end
          stream.puts
93 94 95
        end
      end

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

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

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

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

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

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

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

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

141 142
          tbl.puts " do |t|"

R
Ryuta Kamizono 已提交
143 144 145 146
          # 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
147 148 149 150
            type, colspec = @connection.column_spec(column)
            tbl.print "    t.#{type} #{column.name.inspect}"
            tbl.print ", #{format_colspec(colspec)}" if colspec.present?
            tbl.puts
151 152
          end

153 154
          indexes_in_create(table, tbl)

155 156
          tbl.puts "  end"
          tbl.puts
A
Aaron Patterson 已提交
157

158 159 160 161 162
          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}"
163 164
          stream.puts
        end
A
Aaron Patterson 已提交
165

166
        stream
167 168
      end

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

          stream.puts add_index_statements.sort.join("\n")
178
          stream.puts
179 180
        end
      end
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195
      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}",
        ]
196
        index_parts << "unique: true" if index.unique
197 198
        index_parts << "length: { #{format_options(index.lengths)} }" if index.lengths.present?
        index_parts << "order: { #{format_options(index.orders)} }" if index.orders.present?
199
        index_parts << "where: #{index.where.inspect}" if index.where
200
        index_parts << "using: #{index.using.inspect}" if !@connection.default_index_type?(index)
201 202 203 204 205
        index_parts << "type: #{index.type.inspect}" if index.type
        index_parts << "comment: #{index.comment.inspect}" if index.comment
        index_parts
      end

Y
Yves Senn 已提交
206 207 208 209
      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 已提交
210 211 212
              "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
              remove_prefix_and_suffix(foreign_key.to_table).inspect,
            ]
Y
Yves Senn 已提交
213 214

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

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

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

226 227
            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
228

229
            "  #{parts.join(', ')}"
Y
Yves Senn 已提交
230 231 232 233 234 235
          end

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

236 237 238 239
      def format_colspec(colspec)
        colspec.map { |key, value| "#{key}: #{value}" }.join(", ")
      end

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

244
      def remove_prefix_and_suffix(table)
W
wangjohn 已提交
245
        table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/,  "\\2")
246
      end
247 248

      def ignored?(table_name)
249
        [ActiveRecord::Base.schema_migrations_table_name, ActiveRecord::Base.internal_metadata_table_name, ignore_tables].flatten.any? do |ignored|
250
          ignored === remove_prefix_and_suffix(table_name)
251 252
        end
      end
253
  end
J
Jeremy Kemper 已提交
254
end