schema_dumper.rb 6.2 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 27 28 29 30 31 32 33 34 35 36

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

    def dump(stream)
      header(stream)
      tables(stream)
      trailer(stream)
      stream
    end

    private

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

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

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

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

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

62
HEADER
63 64 65 66 67 68 69 70
      end

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

      def tables(stream)
        @connection.tables.sort.each do |tbl|
71
          next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
72
            case ignored
73 74
            when String; remove_prefix_and_suffix(tbl) == ignored
            when Regexp; remove_prefix_and_suffix(tbl) =~ ignored
75
            else
76
              raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
77
            end
A
Aaron Patterson 已提交
78
          end
79 80 81 82 83 84
          table(tbl, stream)
        end
      end

      def table(table, stream)
        columns = @connection.columns(table)
85 86
        begin
          tbl = StringIO.new
87

88
          # first dump primary key column
89
          if @connection.respond_to?(:pk_and_sequence_for)
A
Aaron Patterson 已提交
90
            pk, _ = @connection.pk_and_sequence_for(table)
91 92
          elsif @connection.respond_to?(:primary_key)
            pk = @connection.primary_key(table)
93
          end
A
Aaron Patterson 已提交
94

95
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
96 97
          if columns.detect { |c| c.name == pk }
            if pk != 'id'
98
              tbl.print %Q(, primary_key: "#{pk}")
99 100
            end
          else
101
            tbl.print ", id: false"
102
          end
103
          tbl.print ", force: true"
104 105
          tbl.puts " do |t|"

106
          # then dump all non-primary key columns
107
          column_specs = columns.map do |column|
108
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil?
109
            next if column.name == pk
110
            @connection.column_spec(column, @types)
111
          end.compact
112 113

          # find all migration keys used in this table
114
          keys = @connection.migration_keys
115 116

          # figure out the lengths for each column based on above keys
A
Aaron Patterson 已提交
117 118 119 120 121
          lengths = keys.map { |key|
            column_specs.map { |spec|
              spec[key] ? spec[key].length + 2 : 0
            }.max
          }
122 123 124 125 126 127 128 129 130 131 132 133

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

134 135
          column_specs.each do |colspec|
            values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
136
            values.unshift colspec[:type]
137
            tbl.print((format_string % values).gsub(/,\s*$/, ''))
138 139 140 141 142
            tbl.puts
          end

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

144 145 146 147 148 149 150
          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}"
151 152
          stream.puts
        end
A
Aaron Patterson 已提交
153

154
        stream
155 156 157
      end

      def indexes(table, stream)
158 159
        if (indexes = @connection.indexes(table)).any?
          add_index_statements = indexes.map do |index|
A
Aaron Patterson 已提交
160
            statement_parts = [
161
              ('add_index ' + remove_prefix_and_suffix(index.table).inspect),
A
Aaron Patterson 已提交
162
              index.columns.inspect,
163
              ('name: ' + index.name.inspect),
A
Aaron Patterson 已提交
164
            ]
165
            statement_parts << 'unique: true' if index.unique
166

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

170
            index_orders = (index.orders || {})
171
            statement_parts << ('order: ' + index.orders.inspect) unless index_orders.empty?
172

173
            statement_parts << ('where: ' + index.where.inspect) if index.where
174

175
            '  ' + statement_parts.join(', ')
176 177 178
          end

          stream.puts add_index_statements.sort.join("\n")
179 180 181
          stream.puts
        end
      end
182 183 184 185

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