schema_dumper.rb 9.0 KB
Newer Older
1 2
require 'stringio'

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 20 21 22 23 24 25 26 27 28 29 30 31
    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
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 50
      end

      def header(stream)
51 52
        define_params = @version ? "version: #{@version}" : ""

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

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

70
ActiveRecord::Schema.define(#{define_params}) do
71

72
HEADER
73 74 75 76 77 78
      end

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

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

91
      def tables(stream)
92
        sorted_tables = @connection.data_sources.sort - @connection.views
93 94 95

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

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

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

111
          # first dump primary key column
112 113 114 115 116 117
          if @connection.respond_to?(:primary_keys)
            pk = @connection.primary_keys(table)
            pk = pk.first unless pk.size > 1
          else
            pk = @connection.primary_key(table)
          end
A
Aaron Patterson 已提交
118

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

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

          table_options = @connection.table_options(table)
          tbl.print ", options: #{table_options.inspect}" unless table_options.blank?

141 142 143
          comment = @connection.table_comment(table)
          tbl.print ", comment: #{comment.inspect}" if comment

144 145
          tbl.puts " do |t|"

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

          # find all migration keys used in this table
154
          keys = @connection.migration_keys
155 156

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

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

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

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

184 185
          indexes(table, tbl)

186 187 188 189 190
          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}"
191 192
          stream.puts
        end
A
Aaron Patterson 已提交
193

194
        stream
195 196 197
      end

      def indexes(table, stream)
198 199
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
A
Aaron Patterson 已提交
200
            statement_parts = [
201 202
              "add_index #{remove_prefix_and_suffix(index.table).inspect}",
              index.columns.inspect,
203
              "name: #{index.name.inspect}",
A
Aaron Patterson 已提交
204
            ]
205
            statement_parts << 'unique: true' if index.unique
206

A
Aaron Patterson 已提交
207
            index_lengths = (index.lengths || []).compact
T
Tee Parham 已提交
208
            statement_parts << "length: #{Hash[index.columns.zip(index.lengths)].inspect}" if index_lengths.any?
209

T
Tee Parham 已提交
210 211
            index_orders = index.orders || {}
            statement_parts << "order: #{index.orders.inspect}" if index_orders.any?
212 213 214
            statement_parts << "where: #{index.where.inspect}" if index.where
            statement_parts << "using: #{index.using.inspect}" if index.using
            statement_parts << "type: #{index.type.inspect}" if index.type
215
            statement_parts << "comment: #{index.comment.inspect}" if index.comment
216

217
            "  #{statement_parts.join(', ')}"
218 219 220
          end

          stream.puts add_index_statements.sort.join("\n")
221
          stream.puts
222 223
        end
      end
224

Y
Yves Senn 已提交
225 226 227 228
      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 已提交
229 230 231
              "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
              remove_prefix_and_suffix(foreign_key.to_table).inspect,
            ]
Y
Yves Senn 已提交
232 233

            if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table)
234
              parts << "column: #{foreign_key.column.inspect}"
Y
Yves Senn 已提交
235 236 237
            end

            if foreign_key.custom_primary_key?
238
              parts << "primary_key: #{foreign_key.primary_key.inspect}"
Y
Yves Senn 已提交
239 240 241
            end

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

245 246
            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
247

248
            "  #{parts.join(', ')}"
Y
Yves Senn 已提交
249 250 251 252 253 254
          end

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

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

      def ignored?(table_name)
260
        [ActiveRecord::Base.schema_migrations_table_name, ActiveRecord::Base.internal_metadata_table_name, ignore_tables].flatten.any? do |ignored|
261
          ignored === remove_prefix_and_suffix(table_name)
262 263
        end
      end
264
  end
J
Jeremy Kemper 已提交
265
end