schema_dumper.rb 8.8 KB
Newer Older
1
require 'stringio'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/big_decimal'
3

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

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

W
wangjohn 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32
    class << self
      def dump(connection=ActiveRecord::Base.connection, stream=STDOUT, config = ActiveRecord::Base)
        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
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 47
        @connection = connection
        @types = @connection.native_database_types
48
        @version = Migrator::current_version rescue nil
W
wangjohn 已提交
49
        @options = options
50 51 52
      end

      def header(stream)
53 54
        define_params = @version ? "version: #{@version}" : ""

55
        if stream.respond_to?(:external_encoding) && stream.external_encoding
56 57 58
          stream.puts "# encoding: #{stream.external_encoding.name}"
        end

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

72
ActiveRecord::Schema.define(#{define_params}) do
73

74
HEADER
75 76 77 78 79 80
      end

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

81 82 83
      def extensions(stream)
        return unless @connection.supports_extensions?
        extensions = @connection.extensions
84 85 86 87 88 89
        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
90 91 92
        end
      end

93
      def tables(stream)
94
        sorted_tables = @connection.tables.sort
95 96 97

        sorted_tables.each do |table_name|
          table(table_name, stream) unless ignored?(table_name)
98
        end
99 100 101 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|
            foreign_keys(tbl, stream)
          end
        end
106 107 108 109
      end

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

113
          # first dump primary key column
114
          if @connection.respond_to?(:pk_and_sequence_for)
A
Aaron Patterson 已提交
115
            pk, _ = @connection.pk_and_sequence_for(table)
116 117
          end
          if !pk && @connection.respond_to?(:primary_key)
118
            pk = @connection.primary_key(table)
119
          end
A
Aaron Patterson 已提交
120

121
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
122 123
          pkcol = columns.detect { |c| c.name == pk }
          if pkcol
124
            if pk != 'id'
125
              tbl.print %Q(, primary_key: "#{pk}")
126 127
            elsif pkcol.sql_type == 'uuid'
              tbl.print ", id: :uuid"
128
              tbl.print %Q(, default: "#{pkcol.default_function}") if pkcol.default_function
129 130
            end
          else
131
            tbl.print ", id: false"
132
          end
133
          tbl.print ", force: true"
134 135
          tbl.puts " do |t|"

136
          # then dump all non-primary key columns
137
          column_specs = columns.map do |column|
138
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
139
            next if column.name == pk
140
            @connection.column_spec(column, @types)
141
          end.compact
142 143

          # find all migration keys used in this table
144
          keys = @connection.migration_keys
145 146

          # figure out the lengths for each column based on above keys
A
Aaron Patterson 已提交
147 148 149 150 151
          lengths = keys.map { |key|
            column_specs.map { |spec|
              spec[key] ? spec[key].length + 2 : 0
            }.max
          }
152 153 154 155 156 157 158 159 160 161 162 163

          # the string we're going to sprintf our values against, with standardized column widths
          format_string = lengths.map{ |len| "%-#{len}s" }

          # find the max length for the 'type' column, which is special
          type_length = column_specs.map{ |column| column[:type].length }.max

          # add column type definition to our format string
          format_string.unshift "    t.%-#{type_length}s "

          format_string *= ''

164 165
          column_specs.each do |colspec|
            values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
166
            values.unshift colspec[:type]
167
            tbl.print((format_string % values).gsub(/,\s*$/, ''))
168 169 170 171 172
            tbl.puts
          end

          tbl.puts "  end"
          tbl.puts
A
Aaron Patterson 已提交
173

174 175 176 177 178 179 180
          indexes(table, tbl)

          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}"
181 182
          stream.puts
        end
A
Aaron Patterson 已提交
183

184
        stream
185 186 187
      end

      def indexes(table, stream)
188 189
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
A
Aaron Patterson 已提交
190
            statement_parts = [
191
              ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
A
Aaron Patterson 已提交
192
              index.columns.inspect,
193
              ('name: ' + index.name.inspect),
A
Aaron Patterson 已提交
194
            ]
195
            statement_parts << 'unique: true' if index.unique
196

A
Aaron Patterson 已提交
197
            index_lengths = (index.lengths || []).compact
198
            statement_parts << ('length: ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?
199

200
            index_orders = (index.orders || {})
201
            statement_parts << ('order: ' + index.orders.inspect) unless index_orders.empty?
202

203
            statement_parts << ('where: ' + index.where.inspect) if index.where
204

205 206
            statement_parts << ('using: ' + index.using.inspect) if index.using

207 208
            statement_parts << ('type: ' + index.type.inspect) if index.type

209
            '  ' + statement_parts.join(', ')
210 211 212
          end

          stream.puts add_index_statements.sort.join("\n")
213 214 215
          stream.puts
        end
      end
216

Y
Yves Senn 已提交
217 218 219 220 221 222 223
      def foreign_keys(table, stream)
        if (foreign_keys = @connection.foreign_keys(table)).any?
          add_foreign_key_statements = foreign_keys.map do |foreign_key|
            parts = [
                     'add_foreign_key ' + remove_prefix_and_suffix(foreign_key.from_table).inspect,
                     remove_prefix_and_suffix(foreign_key.to_table).inspect,
                    ]
Y
Yves Senn 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236

            if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table)
              parts << ('column: ' + foreign_key.column.inspect)
            end

            if foreign_key.custom_primary_key?
              parts << ('primary_key: ' + foreign_key.primary_key.inspect)
            end

            if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/
              parts << ('name: ' + foreign_key.name.inspect)
            end

Y
Yves Senn 已提交
237
            parts << ('on_update: ' + foreign_key.on_update.inspect) if foreign_key.on_update
238
            parts << ('on_delete: ' + foreign_key.on_delete.inspect) if foreign_key.on_delete
239

Y
Yves Senn 已提交
240 241 242 243 244 245 246
            '  ' + parts.join(', ')
          end

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

247
      def remove_prefix_and_suffix(table)
W
wangjohn 已提交
248
        table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/,  "\\2")
249
      end
250 251 252 253 254 255 256 257 258 259 260

      def ignored?(table_name)
        ['schema_migrations', ignore_tables].flatten.any? do |ignored|
          case ignored
          when String; remove_prefix_and_suffix(table_name) == ignored
          when Regexp; remove_prefix_and_suffix(table_name) =~ ignored
          else
            raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
          end
        end
      end
261
  end
J
Jeremy Kemper 已提交
262
end