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 95
        sorted_tables = @connection.tables.sort
        sorted_tables.each do |tbl|
96
          next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
97
            case ignored
98 99
            when String; remove_prefix_and_suffix(tbl) == ignored
            when Regexp; remove_prefix_and_suffix(tbl) =~ ignored
100
            else
101
              raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
102
            end
A
Aaron Patterson 已提交
103
          end
104 105
          table(tbl, stream)
        end
106 107 108 109 110 111 112

        # 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
113 114 115 116
      end

      def table(table, stream)
        columns = @connection.columns(table)
117 118
        begin
          tbl = StringIO.new
119

120
          # first dump primary key column
121
          if @connection.respond_to?(:pk_and_sequence_for)
A
Aaron Patterson 已提交
122
            pk, _ = @connection.pk_and_sequence_for(table)
123 124
          elsif @connection.respond_to?(:primary_key)
            pk = @connection.primary_key(table)
125
          end
A
Aaron Patterson 已提交
126

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

142
          # then dump all non-primary key columns
143
          column_specs = columns.map do |column|
144
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
145
            next if column.name == pk
146
            @connection.column_spec(column, @types)
147
          end.compact
148 149

          # find all migration keys used in this table
150
          keys = @connection.migration_keys
151 152

          # figure out the lengths for each column based on above keys
A
Aaron Patterson 已提交
153 154 155 156 157
          lengths = keys.map { |key|
            column_specs.map { |spec|
              spec[key] ? spec[key].length + 2 : 0
            }.max
          }
158 159 160 161 162 163 164 165 166 167 168 169

          # 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 *= ''

170 171
          column_specs.each do |colspec|
            values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
172
            values.unshift colspec[:type]
173
            tbl.print((format_string % values).gsub(/,\s*$/, ''))
174 175 176 177 178
            tbl.puts
          end

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

180 181 182 183 184 185 186
          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}"
187 188
          stream.puts
        end
A
Aaron Patterson 已提交
189

190
        stream
191 192 193
      end

      def indexes(table, stream)
194 195
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
A
Aaron Patterson 已提交
196
            statement_parts = [
197
              ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
A
Aaron Patterson 已提交
198
              index.columns.inspect,
199
              ('name: ' + index.name.inspect),
A
Aaron Patterson 已提交
200
            ]
201
            statement_parts << 'unique: true' if index.unique
202

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

206
            index_orders = (index.orders || {})
207
            statement_parts << ('order: ' + index.orders.inspect) unless index_orders.empty?
208

209
            statement_parts << ('where: ' + index.where.inspect) if index.where
210

211 212
            statement_parts << ('using: ' + index.using.inspect) if index.using

213 214
            statement_parts << ('type: ' + index.type.inspect) if index.type

215
            '  ' + statement_parts.join(', ')
216 217 218
          end

          stream.puts add_index_statements.sort.join("\n")
219 220 221
          stream.puts
        end
      end
222

Y
Yves Senn 已提交
223 224 225 226 227 228 229
      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 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242

            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 已提交
243
            parts << ('on_update: ' + foreign_key.on_update.inspect) if foreign_key.on_update
244
            parts << ('on_delete: ' + foreign_key.on_delete.inspect) if foreign_key.on_delete
245

Y
Yves Senn 已提交
246 247 248 249 250 251 252
            '  ' + parts.join(', ')
          end

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

253
      def remove_prefix_and_suffix(table)
W
wangjohn 已提交
254
        table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/,  "\\2")
255
      end
256
  end
J
Jeremy Kemper 已提交
257
end