Class: Spider::Model::Storage::Db::Oracle

Inherits:
DbStorage show all
Defined in:
lib/spiderfw/model/storage/db/adapters/oracle.rb

Defined Under Namespace

Classes: OracleNilValue

Class Attribute Summary collapse

Attributes inherited from BaseStorage

#instance_name, #url

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from DbStorage

#alter_table, #change_field, #collect_having_fields, #create_table, #drop_field, #drop_table, #function, #get_mapper, inherited, #initialize, #lock, #parse_db_column, #prepare_value, #query, #query_finished, #query_start, #reflect_column, #safe_schema_conversion?, #schema_field_equal?, #shorten_identifier, #sql_add_field, #sql_alter_table, #sql_change_field, #sql_condition, #sql_create_primary_key, #sql_create_table, #sql_drop_field, #sql_drop_table, #sql_joins, #sql_keys, #sql_max, #sql_order, #sql_table_field, #sql_tables, #sql_tables_join, #sql_truncate, storage_type

Methods inherited from BaseStorage

#==, #commit, #commit!, #commit_or_continue, #configure, #connect, #connected?, #connection, connection_alive?, #connection_attributes, connection_attributes, #connection_pool, connection_pools, #curr, disconnect, #do_commit, #do_rollback, #do_start_transaction, #generate_uuid, get_connection, #get_mapper, #in_transaction, #in_transaction?, inherited, #initialize, max_connections, new_connection, #prepare_value, #release, release_connection, remove_connection, #rollback, #rollback!, #rollback_savepoint, #savepoint, #sequence_file_path, sequence_sync, #start_transaction, storage_type, #supports?, supports?, #supports_transactions?, #transactions_enabled?, #value_for_save

Methods included from Logger

add, check_request_level, close, close_all, datetime_format, datetime_format=, #debug, debug, debug?, #debug?, enquire_loggers, #error, error, #error?, error?, fatal, #fatal, fatal?, #fatal?, info, #info, info?, #info?, #log, log, method_missing, open, reopen, request_level, send_to_loggers, set_request_level, unknown, #unknown, warn, #warn, warn?, #warn?

Constructor Details

This class inherits a constructor from Spider::Model::Storage::Db::DbStorage

Class Attribute Details

.reserved_kewordsObject (readonly)

Returns the value of attribute reserved_kewords.



18
19
20
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 18

def reserved_kewords
  @reserved_kewords
end

.safe_conversionsObject (readonly)

Returns the value of attribute safe_conversions.



18
19
20
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 18

def safe_conversions
  @safe_conversions
end

Class Method Details

.base_typesObject



20
21
22
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 20

def self.base_types
    super << Spider::DataTypes::Binary
end

Instance Method Details

#column_attributes(type, attributes) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 441

def column_attributes(type, attributes)
    db_attributes = super(type, attributes)
    case type.name
    when 'String'
        db_attributes[:length] = attributes[:length] || 255
    when 'Fixnum'
        db_attributes[:precision] = attributes[:precision] || 38
        db_attributes[:length] = nil
    when 'Float'
        # FIXME
        db_attributes[:precision] = attributes[:precision] if (attributes[:precision])
    when 'Spider::DataTypes::Bool'
        db_attributes[:precision] = 1
        db_attributes[:length] = nil
    end
    return db_attributes
end

#column_name(name) ⇒ Object



464
465
466
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 464

def column_name(name)
    shorten_identifier(super, 30).upcase
end

#column_type(type, attributes) ⇒ Object

Schema methods



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 422

def column_type(type, attributes)
    case type.name
    when 'String'
        'VARCHAR2'
    when 'Spider::DataTypes::Text'
        'CLOB'
    when 'Fixnum'
        'NUMBER'
    when 'Float'
        'FLOAT'
    when 'Date', 'DateTime'
        'DATE'
    when 'Spider::DataTypes::Binary'
        'BLOB'
    when 'Spider::DataTypes::Bool'
        'NUMBER'
    end
end

#create_sequence(sequence_name, start = 1, increment = 1) ⇒ Object



280
281
282
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 280

def create_sequence(sequence_name, start=1, increment=1)
    execute("create sequence #{sequence_name} start with #{start} increment by #{increment}")
end

#describe_table(table) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 373

def describe_table(table)
    primary_keys = []
    o_foreign_keys = {}
    columns = {}
    order = []
    connection do |conn|
        cols = do_describe_table(conn, table)
        cols.each do |col|
            columns[col[:name]] = col
            order << col[:name]
        end
        res = execute("SELECT cols.table_name, cols.COLUMN_NAME, cols.position, cons.status, cons.owner
        FROM user_constraints cons, user_cons_columns cols
        WHERE cons.constraint_type = 'P'
        AND cons.constraint_name = cols.constraint_name
        AND cols.table_name = '#{table}'".split("\n").join(' '))
        res.each do |h|
            primary_keys << h['COLUMN_NAME']
        end
        res = execute("SELECT cons.constraint_name as CONSTRAINT_NAME, cols.column_name as REFERENCED_COLUMN,
        cols.table_name as REFERENCED_TABLE, cons.column_name as COLUMN_NAME
        FROM user_tab_columns col
            join user_cons_columns cons
              on col.table_name = cons.table_name 
             and col.column_name = cons.column_name
            join user_constraints cc 
              on cons.constraint_name = cc.constraint_name
            join user_cons_columns cols 
              on cc.r_constraint_name = cols.constraint_name 
             and cons.position = cols.position
        WHERE cc.constraint_type = 'R'
        AND cons.table_name = '#{table}'".split("\n").join(' '))
        res.each do |h|
            fk_name = h['CONSTRAINT_NAME']
            o_foreign_keys[fk_name] ||= {:table => h['REFERENCED_TABLE'], :columns => {}}
            o_foreign_keys[fk_name][:columns][h['COLUMN_NAME']] = h['REFERENCED_COLUMN']
        end
    end
    foreign_keys = []
    o_foreign_keys.each do |fk_name, fk_hash|
        foreign_keys << ForeignKeyConstraint.new(fk_name, fk_hash[:table], fk_hash[:columns])
    end
    return {:columns => columns, :order => order, :primary_keys => primary_keys, :foreign_key_constraints => foreign_keys}

end

#dump(stream, tables = nil) ⇒ Object



320
321
322
323
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 320

def dump(stream, tables=nil)
    stream << "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';\n\n"
    super(stream, tables)
end

#dump_table_data(table, stream) ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 325

def dump_table_data(table, stream)
    connection do |c|
        cursor = c.parse("SELECT COUNT(*) AS N FROM #{table}")
        cursor.exec
        num = cursor.fetch[0]
        cursor.close
        cursor = c.parse("select * from #{table}")
        cursor.exec
        if num > 0
            info = describe_table(table)
            fields = info[:columns]
            stream << "INSERT INTO #{table} (#{info[:order].map{ |f| "#{f}"}.join(', ')})\n"
            stream << "VALUES\n"
            cnt = 0
            while row = cursor.fetch
                cnt += 1
                stream << "("
                info[:order].each_with_index do |f, i|
                    stream << dump_value(row[i], fields[f])
                    stream << ", " if i < fields.length - 1
                end
                stream << ")"
                if cnt < num
                    stream << ",\n"
                else
                    stream << ";\n"
                end
            end
            stream << "\n\n"
        end
        cursor.close
    end
end

#dump_value(val, field) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 359

def dump_value(val, field)
    return 'NULL' if val.nil?
    type =  field[:type]
    if ['CHAR', 'VARCHAR', 'VARCHAR2', 'BLOB', 'CLOB'].include?(type)
        val = val.gsub("'", "''").gsub("\n", '\n').gsub("\r", '\r')
        return "'#{val}'"
    elsif ['DATE', 'TIME', 'DATETIME'].include?(type)
        val = val.strftime("%Y-%m-%d %H:%M:%S")
        return "'#{val}'"
    else
        return val.to_s
    end
end

#foreign_key_name(name) ⇒ Object



472
473
474
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 472

def foreign_key_name(name)
    shorten_identifier(super, 30)
end

#get_table_create_sql(table) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 303

def get_table_create_sql(table)
    sql = nil
    connection do |c|
        out = nil
        cursor = c.parse('BEGIN :out1 := DBMS_METADATA.GET_DDL(object_type=>:in1, name=>:in2); END;')
        cursor.bind_param(1, out, OCI8::CLOB)
        cursor.bind_param(2, 'TABLE', String)
        cursor.bind_param(3, table, String)
        res = cursor.exec
        sql = cursor[1].read
        cursor.close
        # cursor = c.parse('BEGIN DBMS_METADATA_UTIL.LOAD_STYLESHEETS(); END;')
        # cursor.exec
    end
    sql
end

#list_tablesObject



297
298
299
300
301
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 297

def list_tables
    tables = execute("SELECT TABLE_NAME FROM user_tables ORDER BY table_name").map{ |r| r['TABLE_NAME'] }
    mv = execute("SELECT OBJECT_NAME FROM user_objects WHERE OBJECT_TYPE = 'MATERIALIZED VIEW'").map{ |r| r['OBJECT_NAME'] }
    tables - mv
end

#parse_url(url) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 26

def parse_url(url)
    # db:oracle://<username:password>:connect_role@<database>
    # where database is
    # the net8 connect descriptor (TNS) or
    # for Oracle client 10g or later, hostname_or_ip:port_no/oracle_sid
    if (url =~ /.+:\/\/(?:(.+):(.+)(?::(.+))?@)?(.+)/)
        @user = $1
        @pass = $2
        @role = $3
        @dbname = $4
    else
        raise ArgumentError, "Oracle url '#{url}' is invalid"
    end
    @connection_params = [@user, @pass, @dbname, @role]
end

#post_executeObject

Methods to get information from the db #



293
294
295
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 293

def post_execute
    curr[:bind_cnt] = 0
end

#schema_field_number_equal?(current, field) ⇒ Boolean

Returns:

  • (Boolean)


481
482
483
484
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 481

def schema_field_number_equal?(current, field)
    # FIXME: where is the precision?
    return true
end

#schema_field_varchar2_equal?(current, field) ⇒ Boolean

Returns:

  • (Boolean)


476
477
478
479
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 476

def schema_field_varchar2_equal?(current, field)
    # FIXME: can't find the length
    return true
end

#sequence_exists?(sequence_name) ⇒ Boolean

Returns:

  • (Boolean)


274
275
276
277
278
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 274

def sequence_exists?(sequence_name)
    check = "select SEQUENCE_NAME from user_sequences where sequence_name = :1"
    res = execute(check, sequence_name)
    return res[0] ? true : false
end

#sequence_name(name) ⇒ Object



468
469
470
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 468

def sequence_name(name)
    shorten_identifier(name, 30).upcase
end

#sequence_next(sequence_name) ⇒ Object



80
81
82
83
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 80

def sequence_next(sequence_name)
    res = execute("SELECT #{sequence_name}.NEXTVAL AS NEXT FROM DUAL")
    return res[0]['NEXT'].to_i
end

#sql_alter_field(table_name, name, type, attributes) ⇒ Object



270
271
272
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 270

def sql_alter_field(table_name, name, type, attributes)
    ["ALTER TABLE #{table_name} MODIFY #{sql_table_field(name, type, attributes)}"]
end

#sql_condition_value(key, comp, value, bound_vars = true) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 210

def sql_condition_value(key, comp, value, bound_vars=true)
    curr[:bind_cnt] ||= 0
    key = key.expression if key.is_a?(FieldExpression)
    if (comp.to_s.downcase == 'ilike')
        comp = 'like'
        key = "UPPER(#{key})"
    end
    if (value.nil?)
        comp = comp == '=' ? "IS" : "IS NOT"
        sql = "#{key} #{comp} NULL"
    else
        if comp.to_s.downcase == 'between'
            if bound_vars
                val0 = ":#{(curr[:bind_cnt] += 1)}"; val1 = ":#{(curr[:bind_cnt] += 1)}"
            else
                val0, val1 = value
            end
            sql = "#{key} #{comp} #{val0} AND #{val1}"
        else
            val = bound_vars ? ":#{(curr[:bind_cnt] += 1)}" : value
            sql = "#{key} #{comp} #{val}"
            if comp == '<>'
                sql = "(#{sql} or #{key} IS NULL)"
            end
        end
    end
    return sql
end

#sql_delete(del, force = false) ⇒ Object



265
266
267
268
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 265

def sql_delete(del, force=false)
    curr[:bind_cnt] = 0
    super
end

#sql_drop_foreign_key(table_name, key_name) ⇒ Object



104
105
106
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 104

def sql_drop_foreign_key(table_name, key_name)
    "ALTER TABLE #{table_name} DROP CONSTRAINT #{key_name}"
end

#sql_drop_primary_key(table_name) ⇒ Object

SQL methods #



90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 90

def sql_drop_primary_key(table_name)
    constraint_name = nil
    connection do |conn|
        res = conn.exec("SELECT cons.CONSTRAINT_NAME FROM USER_CONSTRAINTS cons, user_cons_columns cols 
                           WHERE cons.constraint_type = 'P'
                           AND cons.constraint_name = cols.constraint_name
                           AND cols.table_name = '#{table_name}'")
        if h = res.fetch_hash
            constraint_name = h['CONSTRAINT_NAME']
        end
    end
    "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint_name}"
end

#sql_insert(insert) ⇒ Object



239
240
241
242
243
244
245
246
247
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 239

def sql_insert(insert)
    curr[:bind_cnt] = 0
    keys = insert[:values].keys.join(', ')
    vals = insert[:values].values.map{":#{(curr[:bind_cnt] += 1)}"}
    vals = vals.join(', ')
    sql = "INSERT INTO #{insert[:table]} (#{keys}) " +
          "VALUES (#{vals})"
    return [sql, insert[:values].values]
end

#sql_insert_values(insert) ⇒ Object



249
250
251
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 249

def sql_insert_values(insert)
    insert[:values].values.map{":#{(curr[:bind_cnt] += 1)}"}.join(', ')
end

#sql_limit(query) ⇒ Object



206
207
208
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 206

def sql_limit(query)
    # already done in sql_condition
end

#sql_select(query) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 109

def sql_select(query)
    curr[:bind_cnt] = 0
    # Spider::Logger.debug("SQL SELECT:")
    # Spider::Logger.debug(query)
    bind_vars = query[:bind_vars] || []
    query[:order_replacements] ||= {}
    if query[:limit] # Oracle is so braindead
        replace_cnt = 0
        # add first field to order if none is found; order is needed for limit
        query[:order] << [query[:keys][0], 'desc'] if query[:order].length < 1
        query[:order].each do |o|
            field, direction = o
            
            if field.is_a?(Spider::Model::Storage::Db::Field) && !query[:tables].include?(field.table)
                query[:order_on_different_table] = true 
            end
            if field.is_a?(FieldFunction)
                query[:order_on_different_table] = true if field.joins.length > 0
            end
            if field.is_a?(Spider::Model::Storage::Db::Field) && field.type == 'CLOB'
                field = "CAST(#{field} as varchar2(100))"
            end
            field_expr = field.is_a?(FieldExpression) ? field.expression : field.to_s
            
            unless query[:keys].include?(field) || field.is_a?(FieldExpression)
               transformed = "O#{replace_cnt += 1}"
               query[:order_replacements][field.to_s] = transformed

               query[:keys] << Db::FieldExpression.new(field.table, transformed, field.type, :expression => field_expr)
           end
        end
    end
    keys = sql_keys(query)
    tables_sql, tables_values = sql_tables(query)

    sql = "SELECT #{keys} FROM #{tables_sql} "
    bind_vars += tables_values

    where, vals = sql_condition(query)
    bind_vars += vals if vals
    sql += "WHERE #{where} " if where && !where.empty?

    having, having_vals = sql_condition(query, true)
    unless having.blank?
       unless (query[:limit] || query[:query_type] == :count) && !query[:joins].empty?

           group_fields = (
               query[:keys].select{ |k| !k.is_a?(FieldExpression)
           } + collect_having_fields(query[:condition])).flatten.uniq
           group_keys = sql_keys(group_fields)
           sql += "GROUP BY #{group_keys} "
           sql += "HAVING #{having} "
       end
       bind_vars += having_vals
    end

    order = sql_order(query, query[:order_replacements])
    if (query[:limit] || query[:query_type] == :count)
        limit = nil
        if (query[:offset])
            limit = "oci8_row_num between :#{curr[:bind_cnt]+=1} and :#{curr[:bind_cnt]+=1}"
            bind_vars << query[:offset] + 1
            bind_vars << query[:offset] + query[:limit]
        elsif query[:limit]
            limit = "oci8_row_num < :#{curr[:bind_cnt]+=1}"
            bind_vars << query[:limit] + 1
        end
        if (!query[:joins].empty?)
            data_tables_sql = query[:order_on_different_table] ? tables_sql : query[:tables].join(', ')
            pks = query[:primary_keys].reject{ |pk| pk.is_a?(Db::FieldExpression) }
            pk_sql = pks.join(', ')
            distinct_sql = "SELECT DISTINCT #{pk_sql} FROM #{tables_sql}"
            distinct_sql += " WHERE #{where}" unless where.blank?
            unless having.blank?

               group_keys = sql_keys((pks + collect_having_fields(query[:condition])).flatten.uniq)
               distinct_sql += " GROUP BY #{group_keys} "
               distinct_sql += " HAVING #{having}"
            end
            data_sql = "SELECT #{keys} FROM #{data_tables_sql} WHERE (#{pk_sql}) IN (#{distinct_sql})"
            data_sql += " order by #{order}" unless order.blank?
        else
            data_sql = sql
            data_sql += " order by #{order}" unless order.blank?
        end
        count_sql = "SELECT /*+ FIRST_ROWS(n) */ a.*, ROWNUM oci8_row_num FROM (#{data_sql}) a"
        if limit
            sql = "SELECT * FROM (#{count_sql}) WHERE #{limit}"
        else
            sql = count_sql
        end
    else
        sql += "ORDER BY #{order} " if order && !order.empty?
    end
    return sql, bind_vars
end

#sql_update(query) ⇒ Object



253
254
255
256
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 253

def sql_update(query)
    curr[:bind_cnt] = 0
    super
end

#sql_update_values(update) ⇒ Object



258
259
260
261
262
263
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 258

def sql_update_values(update)
    update[:values].map{ |k, v| 
        val = v.is_a?(Spider::QueryFuncs::Expression) ? v : ":#{(curr[:bind_cnt] += 1)}"
        "#{k} = #{val}"
    }.join(', ')
end

#table_name(name) ⇒ Object



459
460
461
462
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 459

def table_name(name)
    table_name = name.to_s.gsub('::', '_')
    return shorten_identifier(table_name, 30).upcase
end

#total_rowsObject



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 66

def total_rows
    return nil unless curr[:last_executed]
    q = curr[:last_query].clone
    unless (q[:offset] || q[:limit])
        return curr[:last_result_length] ? curr[:last_result_length] : nil
    end
    q.delete(:offset); q.delete(:limit)
    q[:query_type] = :count
    sql, vars = sql_select(q)
    res = execute("SELECT COUNT(*) AS N FROM (#{sql})", *vars)
    return nil unless res && res[0]
    return res[0]['N'].to_i
end

#update_sequence(name, val) ⇒ Object



284
285
286
287
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 284

def update_sequence(name, val)
    execute("drop sequence #{name}")
    create_sequence(name, val)
end

#value_for_condition(type, value) ⇒ Object



44
45
46
47
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 44

def value_for_condition(type, value)
    return value if value.nil?
    super
end

#value_to_mapper(type, value) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 49

def value_to_mapper(type, value)
    case type.name
    when 'Date', 'DateTime'
        return nil unless value
        return value if value.class == type
        return value.to_datetime if type == DateTime
        return value.to_date # FIXME: check what is returned, here we espect an OCI8::Date
    when 'Spider::DataTypes::Text'
        value = value.read if value.respond_to?(:read)
    when 'Spider::DataTypes::Decimal', 'BigDecimal'
        value = value.to_s
    end
    return super(type, value)
end