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
-
#column_attributes(type, attributes) ⇒ Object
-
#column_name(name) ⇒ Object
-
#column_type(type, attributes) ⇒ Object
-
#create_sequence(sequence_name, start = 1, increment = 1) ⇒ Object
-
#describe_table(table) ⇒ Object
-
#dump(stream, tables = nil) ⇒ Object
-
#dump_table_data(table, stream) ⇒ Object
-
#dump_value(val, field) ⇒ Object
-
#foreign_key_name(name) ⇒ Object
-
#get_table_create_sql(table) ⇒ Object
-
#list_tables ⇒ Object
-
#parse_url(url) ⇒ Object
-
#post_execute ⇒ Object
Methods to get information from the db #.
-
#schema_field_number_equal?(current, field) ⇒ Boolean
-
#schema_field_varchar2_equal?(current, field) ⇒ Boolean
-
#sequence_exists?(sequence_name) ⇒ Boolean
-
#sequence_name(name) ⇒ Object
-
#sequence_next(sequence_name) ⇒ Object
-
#sql_alter_field(table_name, name, type, attributes) ⇒ Object
-
#sql_condition_value(key, comp, value, bound_vars = true) ⇒ Object
-
#sql_delete(del, force = false) ⇒ Object
-
#sql_drop_foreign_key(table_name, key_name) ⇒ Object
-
#sql_drop_primary_key(table_name) ⇒ Object
-
#sql_insert(insert) ⇒ Object
-
#sql_insert_values(insert) ⇒ Object
-
#sql_limit(query) ⇒ Object
-
#sql_select(query) ⇒ Object
-
#sql_update(query) ⇒ Object
-
#sql_update_values(update) ⇒ Object
-
#table_name(name) ⇒ Object
-
#total_rows ⇒ Object
-
#update_sequence(name, val) ⇒ Object
-
#value_for_condition(type, value) ⇒ Object
-
#value_to_mapper(type, value) ⇒ Object
Methods inherited from DbStorage
#alter_table, #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_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, 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?, method_missing, open, reopen, send_to_loggers, unknown, #unknown, #warn, warn, warn?, #warn?
Class Attribute Details
.reserved_kewords ⇒ Object
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_conversions ⇒ Object
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_types ⇒ Object
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 416
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'
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
439
440
441
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 439
def column_name(name)
shorten_identifier(super, 30).upcase
end
|
#column_type(type, attributes) ⇒ Object
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 397
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
255
256
257
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 255
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 348
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
295
296
297
298
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 295
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 300
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
334
335
336
337
338
339
340
341
342
343
344
345
346
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 334
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
447
448
449
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 447
def foreign_key_name(name)
shorten_identifier(super, 30)
end
|
#get_table_create_sql(table) ⇒ Object
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 278
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
end
sql
end
|
#list_tables ⇒ Object
272
273
274
275
276
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 272
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)
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_execute ⇒ Object
Methods to get information from the db #
268
269
270
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 268
def post_execute
curr[:bind_cnt] = 0
end
|
#schema_field_number_equal?(current, field) ⇒ Boolean
456
457
458
459
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 456
def schema_field_number_equal?(current, field)
return true
end
|
#schema_field_varchar2_equal?(current, field) ⇒ Boolean
451
452
453
454
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 451
def schema_field_varchar2_equal?(current, field)
return true
end
|
#sequence_exists?(sequence_name) ⇒ Boolean
249
250
251
252
253
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 249
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
443
444
445
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 443
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
245
246
247
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 245
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 186
def sql_condition_value(key, comp, value, bound_vars=true)
curr[:bind_cnt] ||= 0
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
240
241
242
243
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 240
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
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
214
215
216
217
218
219
220
221
222
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 214
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
224
225
226
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 224
def sql_insert_values(insert)
insert[:values].values.map{":#{(curr[:bind_cnt] += 1)}"}.join(', ')
end
|
#sql_limit(query) ⇒ Object
182
183
184
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 182
def sql_limit(query)
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
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 109
def sql_select(query)
curr[:bind_cnt] = 0
bind_vars = query[:bind_vars] || []
query[:order_replacements] ||= {}
if query[:limit] replace_cnt = 0
query[:order] << [query[:keys][0], 'desc'] if query[:order].length < 1
query[:order].each do |o|
field, direction = o
transformed = "O#{replace_cnt += 1}"
query[:order_replacements][field.to_s] = transformed
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
query[:keys] << Db::FieldExpression.new(field.table, transformed, field.type, :expression => "#{field}")
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
sql += "WHERE #{where} " if where && !where.empty?
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(', ')
pk_sql = query[:primary_keys].reject{ |pk| pk.is_a?(Db::FieldExpression) }.join(', ')
distinct_sql = "SELECT DISTINCT #{pk_sql} FROM #{tables_sql}"
distinct_sql += " WHERE #{where}" if where && !where.empty?
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
228
229
230
231
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 228
def sql_update(query)
curr[:bind_cnt] = 0
super
end
|
#sql_update_values(update) ⇒ Object
233
234
235
236
237
238
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 233
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
434
435
436
437
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 434
def table_name(name)
table_name = name.to_s.gsub('::', '_')
return shorten_identifier(table_name, 30).upcase
end
|
#total_rows ⇒ Object
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] ? 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
259
260
261
262
|
# File 'lib/spiderfw/model/storage/db/adapters/oracle.rb', line 259
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 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
|