schema_dumper.rb 8.4 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
        @connection = connection
47
        @version = Migrator::current_version rescue nil
W
wangjohn 已提交
48
        @options = options
49 50 51
      end

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

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

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

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

73
HEADER
74 75 76 77 78 79
      end

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

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

92
      def tables(stream)
93
        sorted_tables = @connection.tables.sort
94 95 96

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

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

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

112
          # first dump primary key column
113
          pk = @connection.primary_key(table)
A
Aaron Patterson 已提交
114

115
          tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
116 117
          pkcol = columns.detect { |c| c.name == pk }
          if pkcol
118
            if pk != 'id'
119
              tbl.print %Q(, primary_key: "#{pk}")
A
Aaron Patterson 已提交
120 121
            elsif pkcol.sql_type == 'bigint'
              tbl.print ", id: :bigserial"
122 123
            elsif pkcol.sql_type == 'uuid'
              tbl.print ", id: :uuid"
124
              tbl.print %Q(, default: #{pkcol.default_function.inspect})
125 126
            end
          else
127
            tbl.print ", id: false"
128
          end
129
          tbl.print ", force: :cascade"
130 131
          tbl.puts " do |t|"

132
          # then dump all non-primary key columns
133
          column_specs = columns.map do |column|
134
            raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type)
135
            next if column.name == pk
136
            @connection.column_spec(column)
137
          end.compact
138 139

          # find all migration keys used in this table
140
          keys = @connection.migration_keys
141 142

          # figure out the lengths for each column based on above keys
A
Aaron Patterson 已提交
143 144 145 146 147
          lengths = keys.map { |key|
            column_specs.map { |spec|
              spec[key] ? spec[key].length + 2 : 0
            }.max
          }
148 149 150 151 152 153 154 155 156 157 158 159

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

160 161
          column_specs.each do |colspec|
            values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
162
            values.unshift colspec[:type]
163
            tbl.print((format_string % values).gsub(/,\s*$/, ''))
164 165 166 167 168
            tbl.puts
          end

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

170 171 172 173 174 175 176
          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}"
177 178
          stream.puts
        end
A
Aaron Patterson 已提交
179

180
        stream
181 182 183
      end

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

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

T
Tee Parham 已提交
196 197
            index_orders = index.orders || {}
            statement_parts << "order: #{index.orders.inspect}" if index_orders.any?
198 199 200
            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
201

202
            "  #{statement_parts.join(', ')}"
203 204 205
          end

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

Y
Yves Senn 已提交
210 211 212 213
      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 已提交
214 215 216
              "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
              remove_prefix_and_suffix(foreign_key.to_table).inspect,
            ]
Y
Yves Senn 已提交
217 218

            if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table)
219
              parts << "column: #{foreign_key.column.inspect}"
Y
Yves Senn 已提交
220 221 222
            end

            if foreign_key.custom_primary_key?
223
              parts << "primary_key: #{foreign_key.primary_key.inspect}"
Y
Yves Senn 已提交
224 225 226
            end

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

230 231
            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
232

233
            "  #{parts.join(', ')}"
Y
Yves Senn 已提交
234 235 236 237 238 239
          end

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

240
      def remove_prefix_and_suffix(table)
W
wangjohn 已提交
241
        table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/,  "\\2")
242
      end
243 244 245

      def ignored?(table_name)
        ['schema_migrations', ignore_tables].flatten.any? do |ignored|
246
          ignored === remove_prefix_and_suffix(table_name)
247 248
        end
      end
249
  end
J
Jeremy Kemper 已提交
250
end