Module: ActiveRecord::ConnectionAdapters::OracleEnhancedStructureDump

Defined in:
lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb

Overview

:nodoc:

Constant Summary collapse

STATEMENT_TOKEN =

Statements separator used in structure dump to allow loading of structure dump also with SQL*Plus

"\n\n/\n\n"

Instance Method Summary collapse

Instance Method Details

#add_column_options!(sql, options) ⇒ Object

:nodoc:



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 266

def add_column_options!(sql, options) #:nodoc:
  type = options[:type] || ((column = options[:column]) && column.type)
  type = type && type.to_sym
  # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly
  if options_include_default?(options)
    if type == :text
      sql << " DEFAULT #{quote(options[:default])}"
    else
      # from abstract adapter
      sql << " DEFAULT #{quote(options[:default], options[:column])}"
    end
  end
  # must explicitly add NULL or NOT NULL to allow change_column to work on migrations
  if options[:null] == false
    sql << " NOT NULL"
  elsif options[:null] == true
    sql << " NULL" unless type == :primary_key
  end
  # add AS expression for virtual columns
  if options[:as].present?
    sql << " AS (#{options[:as]})"
  end
end

#execute_structure_dump(string) ⇒ Object



290
291
292
293
294
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 290

def execute_structure_dump(string)
  string.split(STATEMENT_TOKEN).each do |ddl|
    execute(ddl) unless ddl.blank?
  end
end

#foreign_key_definition(to_table, options = {}) ⇒ Object

:nodoc:



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 164

def foreign_key_definition(to_table, options = {}) #:nodoc:
  columns = Array(options[:column] || options[:columns])

  if columns.size > 1
    # composite foreign key
    columns_sql = columns.map {|c| quote_column_name(c)}.join(',')
    references = options[:references] || columns
    references_sql = references.map {|c| quote_column_name(c)}.join(',')
  else
    columns_sql = quote_column_name(columns.first || "#{to_table.to_s.singularize}_id")
    references = options[:references] ? options[:references].first : nil
    references_sql = quote_column_name(options[:primary_key] || references || "id")
  end

  table_name = to_table

  sql = "FOREIGN KEY (#{columns_sql}) REFERENCES #{quote_table_name(table_name)}(#{references_sql})"

  case options[:dependent]
  when :nullify
    sql << " ON DELETE SET NULL"
  when :delete
    sql << " ON DELETE CASCADE"
  end
  sql
end

#full_drop(preserve_tables = false) ⇒ Object

:nodoc:



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 253

def full_drop(preserve_tables=false) #:nodoc:
  s = preserve_tables ? [] : [structure_drop]
  s << temp_table_drop if preserve_tables
  s << drop_sql_for_feature("view")
  s << drop_sql_for_feature("materialized view")
  s << drop_sql_for_feature("synonym")
  s << drop_sql_for_feature("type")
  s << drop_sql_for_object("package")
  s << drop_sql_for_object("function")
  s << drop_sql_for_object("procedure")
  s.join
end

#structure_dropObject

:nodoc:



231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 231

def structure_drop #:nodoc:
  statements = select_values("SELECT sequence_name FROM user_sequences ORDER BY 1").map do |seq|
    "DROP SEQUENCE \"#{seq}\""
  end
  select_values("SELECT table_name from all_tables t
              WHERE owner = SYS_CONTEXT('userenv', 'current_schema') AND secondary = 'N'
                AND NOT EXISTS (SELECT mv.mview_name FROM all_mviews mv WHERE mv.owner = t.owner AND mv.mview_name = t.table_name)
                AND NOT EXISTS (SELECT mvl.log_table FROM all_mview_logs mvl WHERE mvl.log_owner = t.owner AND mvl.log_table = t.table_name)
              ORDER BY 1").each do |table|
    statements << "DROP TABLE \"#{table}\" CASCADE CONSTRAINTS"
  end
  join_with_statement_token(statements)
end

#structure_dumpObject

:nodoc:



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 8

def structure_dump #:nodoc:
  structure = select_values("SELECT sequence_name FROM user_sequences ORDER BY 1").map do |seq|
    "CREATE SEQUENCE \"#{seq}\""
  end
  select_values("SELECT table_name FROM all_tables t
              WHERE owner = SYS_CONTEXT('userenv', 'current_schema') AND secondary = 'N'
                AND NOT EXISTS (SELECT mv.mview_name FROM all_mviews mv WHERE mv.owner = t.owner AND mv.mview_name = t.table_name)
                AND NOT EXISTS (SELECT mvl.log_table FROM all_mview_logs mvl WHERE mvl.log_owner = t.owner AND mvl.log_table = t.table_name)
              ORDER BY 1").each do |table_name|
    virtual_columns = virtual_columns_for(table_name)
    ddl = "CREATE#{ ' GLOBAL TEMPORARY' if temporary_table?(table_name)} TABLE \"#{table_name}\" (\n"
    cols = select_all(%Q{
      SELECT column_name, data_type, data_length, char_used, char_length, data_precision, data_scale, data_default, nullable
      FROM user_tab_columns
      WHERE table_name = '#{table_name}'
      ORDER BY column_id
    }).map do |row|
      if(v = virtual_columns.find {|col| col['column_name'] == row['column_name']})
        structure_dump_virtual_column(row, v['data_default'])
      else
        structure_dump_column(row)
      end
    end
    ddl << cols.join(",\n ")
    ddl << structure_dump_primary_key(table_name)
    ddl << "\n)"
    structure << ddl
    structure << structure_dump_indexes(table_name)
    structure << structure_dump_unique_keys(table_name)
    structure << structure_dump_table_comments(table_name)
    structure << structure_dump_column_comments(table_name)
  end

  join_with_statement_token(structure) << structure_dump_fk_constraints
end

#structure_dump_column(column) ⇒ Object

:nodoc:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 44

def structure_dump_column(column) #:nodoc:
  col = "\"#{column['column_name']}\" #{column['data_type']}"
  if column['data_type'] =='NUMBER' and !column['data_precision'].nil?
    col << "(#{column['data_precision'].to_i}"
    col << ",#{column['data_scale'].to_i}" if !column['data_scale'].nil?
    col << ')'
  elsif column['data_type'].include?('CHAR') || column['data_type'] == 'RAW'
    length = column['char_used'] == 'C' ? column['char_length'].to_i : column['data_length'].to_i
    col <<  "(#{length})"
  end
  col << " DEFAULT #{column['data_default']}" if !column['data_default'].nil?
  col << ' NOT NULL' if column['nullable'] == 'N'
  col
end

#structure_dump_column_comments(table_name) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 150

def structure_dump_column_comments(table_name)
  comments = []
  columns = select_values("SELECT column_name FROM user_tab_columns WHERE table_name = '#{table_name}' ORDER BY column_id")

  columns.each do |column|
    comment = column_comment(table_name, column)
    unless comment.nil?
      comments << "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column)} IS '#{quote_string(comment)}'"
    end
  end

  join_with_statement_token(comments)
end

#structure_dump_db_stored_codeObject

Extract all stored procedures, packages, synonyms and views.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 193

def structure_dump_db_stored_code #:nodoc:
  structure = []
  select_all("SELECT DISTINCT name, type
               FROM all_source
              WHERE type IN ('PROCEDURE', 'PACKAGE', 'PACKAGE BODY', 'FUNCTION', 'TRIGGER', 'TYPE')
                AND name NOT LIKE 'BIN$%'
                AND owner = SYS_CONTEXT('userenv', 'current_schema') ORDER BY type").each do |source|
    ddl = "CREATE OR REPLACE   \n"
    select_all(%Q{
            SELECT text
              FROM all_source
             WHERE name = '#{source['name']}'
               AND type = '#{source['type']}'
               AND owner = SYS_CONTEXT('userenv', 'current_schema')
             ORDER BY line
          }).each do |row|
      ddl << row['text']
    end
    ddl << ";" unless ddl.strip[-1,1] == ';'
    structure << ddl
  end

  # export views 
  select_all("SELECT view_name, text FROM user_views ORDER BY view_name ASC").each do |view|
    structure << "CREATE OR REPLACE FORCE VIEW #{view['view_name']} AS\n #{view['text']}"
  end

  # export synonyms
  select_all("SELECT owner, synonym_name, table_name, table_owner
                FROM all_synonyms
               WHERE owner = SYS_CONTEXT('userenv', 'current_schema') ").each do |synonym|
    structure << "CREATE OR REPLACE #{synonym['owner'] == 'PUBLIC' ? 'PUBLIC' : '' } SYNONYM #{synonym['synonym_name']}
			FOR #{synonym['table_owner']}.#{synonym['table_name']}"
  end

  join_with_statement_token(structure)
end

#structure_dump_fk_constraintsObject

:nodoc:



127
128
129
130
131
132
133
134
135
136
137
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 127

def structure_dump_fk_constraints #:nodoc:
  fks = select_all("SELECT table_name FROM all_tables WHERE owner = SYS_CONTEXT('userenv', 'current_schema') ORDER BY 1").map do |table|
    if respond_to?(:foreign_keys) && (foreign_keys = foreign_keys(table["table_name"])).any?
      foreign_keys.map do |fk|
        sql = "ALTER TABLE #{quote_table_name(fk.from_table)} ADD CONSTRAINT #{quote_column_name(fk.options[:name])} "
        sql << "#{foreign_key_definition(fk.to_table, fk.options)}"
      end
    end
  end.flatten.compact
  join_with_statement_token(fks)
end

#structure_dump_indexes(table_name) ⇒ Object

:nodoc:



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 111

def structure_dump_indexes(table_name) #:nodoc:
  indexes(table_name).map do |options|
    column_names = options[:columns]
    options = {:name => options[:name], :unique => options[:unique]}
    index_name   = index_name(table_name, :column => column_names)
    if Hash === options # legacy support, since this param was a string
      index_type = options[:unique] ? "UNIQUE" : ""
      index_name = options[:name] || index_name
    else
      index_type = options
    end
    quoted_column_names = column_names.map { |e| quote_column_name_or_expression(e) }.join(", ")
    "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{quoted_column_names})"
  end
end

#structure_dump_primary_key(table) ⇒ Object

:nodoc:



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 73

def structure_dump_primary_key(table) #:nodoc:
  opts = {:name => '', :cols => []}
  pks = select_all(<<-SQL, "Primary Keys") 
    SELECT a.constraint_name, a.column_name, a.position
      FROM user_cons_columns a
      JOIN user_constraints c
        ON a.constraint_name = c.constraint_name
     WHERE c.table_name = '#{table.upcase}'
       AND c.constraint_type = 'P'
       AND c.owner = SYS_CONTEXT('userenv', 'current_schema')
  SQL
  pks.each do |row|
    opts[:name] = row['constraint_name']
    opts[:cols][row['position']-1] = row['column_name']
  end
  opts[:cols].length > 0 ? ",\n CONSTRAINT #{opts[:name]} PRIMARY KEY (#{opts[:cols].join(',')})" : ''
end

#structure_dump_table_comments(table_name) ⇒ Object



139
140
141
142
143
144
145
146
147
148
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 139

def structure_dump_table_comments(table_name)
  comments = []
  comment = table_comment(table_name)

  unless comment.nil?
    comments << "COMMENT ON TABLE #{quote_table_name(table_name)} IS '#{quote_string(comment)}'"
  end

  join_with_statement_token(comments)
end

#structure_dump_unique_keys(table) ⇒ Object

:nodoc:



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 91

def structure_dump_unique_keys(table) #:nodoc:
  keys = {}
  uks = select_all(<<-SQL, "Primary Keys") 
    SELECT a.constraint_name, a.column_name, a.position
      FROM user_cons_columns a
      JOIN user_constraints c
        ON a.constraint_name = c.constraint_name
     WHERE c.table_name = '#{table.upcase}'
       AND c.constraint_type = 'U'
       AND c.owner = SYS_CONTEXT('userenv', 'current_schema')
  SQL
  uks.each do |uk|
    keys[uk['constraint_name']] ||= []
    keys[uk['constraint_name']][uk['position']-1] = uk['column_name']
  end
  keys.map do |k,v|
    "ALTER TABLE #{table.upcase} ADD CONSTRAINT #{k} UNIQUE (#{v.join(',')})"
  end
end

#structure_dump_virtual_column(column, data_default) ⇒ Object

:nodoc:



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 59

def structure_dump_virtual_column(column, data_default) #:nodoc:
  data_default = data_default.gsub(/"/, '')
  col = "\"#{column['column_name']}\" #{column['data_type']}"
  if column['data_type'] =='NUMBER' and !column['data_precision'].nil?
    col << "(#{column['data_precision'].to_i}"
    col << ",#{column['data_scale'].to_i}" if !column['data_scale'].nil?
    col << ')'
  elsif column['data_type'].include?('CHAR') || column['data_type'] == 'RAW'
    length = column['char_used'] == 'C' ? column['char_length'].to_i : column['data_length'].to_i
    col <<  "(#{length})"
  end
  col << " GENERATED ALWAYS AS (#{data_default}) VIRTUAL"
end

#temp_table_dropObject

:nodoc:



245
246
247
248
249
250
251
# File 'lib/active_record/connection_adapters/oracle_enhanced/structure_dump.rb', line 245

def temp_table_drop #:nodoc:
  join_with_statement_token(select_values(
            "SELECT table_name FROM all_tables
              WHERE owner = SYS_CONTEXT('userenv', 'current_schema') AND secondary = 'N' AND temporary = 'Y' ORDER BY 1").map do |table|
    "DROP TABLE \"#{table}\" CASCADE CONSTRAINTS"
  end)
end