schema_dumper.rb 7.5 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 63 64 65 66 67 68 69 70
HEADER
      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 98 99 100 101 102
          if columns.detect { |c| c.name == pk }
            if pk != 'id'
              tbl.print %Q(, :primary_key => "#{pk}")
            end
          else
            tbl.print ", :id => false"
          end
103 104 105
          tbl.print ", :force => true"
          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
            spec = {}
111
            spec[:name]      = column.name.inspect
A
Aaron Patterson 已提交
112

113
            # AR has an optimization which handles zero-scale decimals as integers. This
114
            # code ensures that the dumper still dumps the column as a decimal.
115
            spec[:type]      = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
116 117 118 119 120
                                 'decimal'
                               else
                                 column.type.to_s
                               end
            spec[:limit]     = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal'
N
Neeraj Singh 已提交
121 122 123
            spec[:precision] = column.precision.inspect if column.precision
            spec[:scale]     = column.scale.inspect if column.scale
            spec[:null]      = 'false' unless column.null
124
            spec[:default]   = default_string(column.default) if column.has_default?
125 126 127
            (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.inspect} => ")}
            spec
          end.compact
128 129

          # find all migration keys used in this table
130
          keys = [:name, :limit, :precision, :scale, :default, :null]
131 132

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

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

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

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

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

170
        stream
171 172
      end

173 174 175 176 177
      def default_string(value)
        case value
        when BigDecimal
          value.to_s
        when Date, DateTime, Time
A
Akira Matsuda 已提交
178
          "'#{value.to_s(:db)}'"
179 180 181 182
        else
          value.inspect
        end
      end
A
Aaron Patterson 已提交
183

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

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

197 198 199
            index_orders = (index.orders || {})
            statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty?

200 201
            statement_parts << (':where => ' + index.where.inspect) if index.where

202
            '  ' + statement_parts.join(', ')
203 204 205
          end

          stream.puts add_index_statements.sort.join("\n")
206 207 208
          stream.puts
        end
      end
209 210 211 212

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