schema_dumper.rb 6.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 20 21 22 23 24 25 26

    def self.dump(connection=ActiveRecord::Base.connection, stream=STDOUT)
      new(connection).dump(stream)
      stream
    end

    def dump(stream)
      header(stream)
27
      extensions(stream)
28 29 30 31 32 33 34 35 36 37
      tables(stream)
      trailer(stream)
      stream
    end

    private

      def initialize(connection)
        @connection = connection
        @types = @connection.native_database_types
38
        @version = Migrator::current_version rescue nil
39 40 41
      end

      def header(stream)
42 43
        define_params = @version ? "version: #{@version}" : ""

44
        if stream.respond_to?(:external_encoding) && stream.external_encoding
45 46 47
          stream.puts "# encoding: #{stream.external_encoding.name}"
        end

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

61
ActiveRecord::Schema.define(#{define_params}) do
62

63
HEADER
64 65 66 67 68 69
      end

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

70 71 72
      def extensions(stream)
        return unless @connection.supports_extensions?
        extensions = @connection.extensions
73 74 75 76 77 78
        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
79 80 81
        end
      end

82 83
      def tables(stream)
        @connection.tables.sort.each do |tbl|
84
          next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
85
            case ignored
86 87
            when String; remove_prefix_and_suffix(tbl) == ignored
            when Regexp; remove_prefix_and_suffix(tbl) =~ ignored
88
            else
89
              raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
90
            end
A
Aaron Patterson 已提交
91
          end
92 93 94 95 96 97
          table(tbl, stream)
        end
      end

      def table(table, stream)
        columns = @connection.columns(table)
98 99
        begin
          tbl = StringIO.new
100

101
          # first dump primary key column
102
          if @connection.respond_to?(:pk_and_sequence_for)
A
Aaron Patterson 已提交
103
            pk, _ = @connection.pk_and_sequence_for(table)
104 105
          elsif @connection.respond_to?(:primary_key)
            pk = @connection.primary_key(table)
106
          end
A
Aaron Patterson 已提交
107

108
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
109 110
          if columns.detect { |c| c.name == pk }
            if pk != 'id'
111
              tbl.print %Q(, primary_key: "#{pk}")
112 113
            end
          else
114
            tbl.print ", id: false"
115
          end
116
          tbl.print ", force: true"
117 118
          tbl.puts " do |t|"

119
          # then dump all non-primary key columns
120
          column_specs = columns.map do |column|
121
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
122
            next if column.name == pk
123
            @connection.column_spec(column, @types)
124
          end.compact
125 126

          # find all migration keys used in this table
127
          keys = @connection.migration_keys
128 129

          # figure out the lengths for each column based on above keys
A
Aaron Patterson 已提交
130 131 132 133 134
          lengths = keys.map { |key|
            column_specs.map { |spec|
              spec[key] ? spec[key].length + 2 : 0
            }.max
          }
135 136 137 138 139 140 141 142 143 144 145 146

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

147 148
          column_specs.each do |colspec|
            values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
149
            values.unshift colspec[:type]
150
            tbl.print((format_string % values).gsub(/,\s*$/, ''))
151 152 153 154 155
            tbl.puts
          end

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

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

167
        stream
168 169 170
      end

      def indexes(table, stream)
171 172
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
A
Aaron Patterson 已提交
173
            statement_parts = [
174
              ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
A
Aaron Patterson 已提交
175
              index.columns.inspect,
176
              ('name: ' + index.name.inspect),
A
Aaron Patterson 已提交
177
            ]
178
            statement_parts << 'unique: true' if index.unique
179

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

183
            index_orders = (index.orders || {})
184
            statement_parts << ('order: ' + index.orders.inspect) unless index_orders.empty?
185

186
            statement_parts << ('where: ' + index.where.inspect) if index.where
187

188 189
            statement_parts << ('using: ' + index.using.inspect) if index.using

190
            '  ' + statement_parts.join(', ')
191 192 193
          end

          stream.puts add_index_statements.sort.join("\n")
194 195 196
          stream.puts
        end
      end
197 198 199 200

      def remove_prefix_and_suffix(table)
        table.gsub(/^(#{ActiveRecord::Base.table_name_prefix})(.+)(#{ActiveRecord::Base.table_name_suffix})$/,  "\\2")
      end
201
  end
J
Jeremy Kemper 已提交
202
end