Class: Spider::Model::Mappers::DbMapper
- Inherits:
-
Spider::Model::Mapper
- Object
- Spider::Model::Mapper
- Spider::Model::Mappers::DbMapper
- Includes:
- Storage::Db
- Defined in:
- lib/spiderfw/model/mappers/db_mapper.rb
Overview
This is the Mapper subclass for interacting with databases.
Instance Attribute Summary
Attributes inherited from Spider::Model::Mapper
Class Method Summary collapse
-
.write? ⇒ true
Is this mapper writable?.
Instance Method Summary collapse
-
#alter_table(name, schema, attributes, force = nil) ⇒ Object
Returns an alter table structure description.
-
#assign_primary_keys(obj) ⇒ Object
Empty hook to set primary keys in the model before insert.
- #base_type(type) ⇒ Object
-
#before_save(obj, mode) ⇒ Object
Save (insert and update) #.
-
#bulk_update(values, condition) ⇒ Object
Updates according to a condition, storing the values, which must passed as a Hash.
-
#can_join?(element) ⇒ Boolean
Returns true if an element can be loaded joined-in.
-
#collect_real_keys(element, path = []) ⇒ Object
Returns an array of all keys, “dereferencing” model keys.
- #compute_foreign_key_constraints ⇒ Object
-
#count(condition_or_query) ⇒ Object
Implements the Mapper#count method doing a count SQL query.
-
#create_table(table_name, schema, attributes) ⇒ Object
Returns a create table structure description.
-
#define_schema(&proc) ⇒ Object
Define schema.
-
#do_delete(condition, force = false) ⇒ Object
:nodoc:.
-
#do_insert(obj) ⇒ Object
:nodoc:.
-
#do_update(obj) ⇒ Object
:nodoc:.
- #execute_action(action, object, params = {}) ⇒ Object
-
#fetch(query) ⇒ Object
Implements the Mapper#fetch method.
-
#find_by_sql(sql, *bind_vars) ⇒ Object
Finds objects by SQL, mapping back the storage result.
-
#generate_schema(schema = nil) ⇒ Object
Autogenerates schema.
-
#get_deep_join(dotted_element, join_type = nil) ⇒ Array
Returns the joins needed for an element down the tree, expressed in dotted notation.
-
#get_dependencies(task) ⇒ Object
UnitOfWork dependencies.
-
#get_join(element, join_type = :inner) ⇒ Object
Figures out a join for element.
-
#get_join_info(model, condition) ⇒ Object
Returns an hash with true for elements that need an inner join Note: subsequent joins of a left join have to be left joins, otherwise the first join will behave as an inner.
-
#get_schema ⇒ Object
Returns the schema, as defined or autogenerated.
- #has_aggregates?(condition, in_or = false) ⇒ Boolean
-
#have_references?(element) ⇒ Boolean
Checks if the schema has some key to reach element.
-
#initialize(model, storage) ⇒ DbMapper
constructor
A new instance of DbMapper.
-
#lock(obj = nil, mode = :exclusive) ⇒ Object
Lock db – FIXME.
-
#map(request, result, obj_or_model) ⇒ Object
Implements the Mapper#map method.
- #map_back_value(type, value) ⇒ Object
-
#map_type(type) ⇒ Object
Returns a type accepted by the storage for type.
-
#map_value(type, value, mode = nil) ⇒ Object
Converts a value in one accepted by the storage.
-
#max(element, condition = nil) ⇒ Object
Aggregates #.
- #pk ⇒ Object
-
#prepare_condition(condition, options = {}) ⇒ Object
Generates a storage description for the condition Returns a list of three elements, composed of * conditions: an hash { :conj => ‘and’|‘or’, :values => an array of [field, comparison, value] triplets } * joins: an array of structures as returned by #get_join * remaining_condition: part of the condition which can’t be passed to the storage – TODO: better name for :values.
-
#prepare_expression(expr) ⇒ Object
Takes a Spider::QueryFuncs::Expression, and associates the fields to the corresponding elements Returns an array of needed joins.
- #prepare_group_by(query) ⇒ Object
-
#prepare_insert(obj) ⇒ Object
Insert preprocessing.
-
#prepare_joins(joins) ⇒ Object
– FIXME: document.
-
#prepare_order(query) ⇒ Object
Returns a pair composed of * fields, an array of [field, direction] couples; and * joins, joins needed for the order, if any.
-
#prepare_query_request(request, obj = nil) ⇒ Object
:nodoc:.
- #prepare_queryfunc(func) ⇒ Object
-
#prepare_save(obj, save_mode) ⇒ Object
Save preprocessing.
- #prepare_save_value(element, element_val, save_mode, values = {}) ⇒ Object
-
#prepare_select(query) ⇒ Object
Generates a select hash description based on the query.
-
#prepare_update(obj) ⇒ Object
Update preprocessing.
-
#reset_schema ⇒ Object
Resets the schema, so that it is regenerated on the next call.
-
#schema ⇒ Object
Returns @schema, or creates one.
- #schema_table_name ⇒ Object
-
#sequence_next(name) ⇒ Object
Next value for the named sequence.
- #someone_have_references?(element) ⇒ Boolean
-
#sql_execute(sql, *values) ⇒ Object
Execute SQL directly, returning raw db results.
- #storage_column_attributes(type, attributes) ⇒ Object
- #storage_column_type(type, attributes) ⇒ Object
-
#sync_schema(force = false, options = {}) ⇒ Object
Modifies the storage according to the schema.
- #truncate! ⇒ Object
-
#with_schema(&proc) ⇒ Object
Extend schema.
Methods inherited from Spider::Model::Mapper
#after_delete, #after_save, #association_elements, #basic_preprocess, #before_delete, #before_insert, #before_update, #children_for_unit_of_work, #delete, #delete_all!, #delete_element_associations, #determine_save_mode, #find, #insert, #load, #load_element, #load_element!, #map_condition_value, #map_save_value, #mapped?, #no_map, #normalize, #prepare_delete_condition, #queryset_siblings, #save, #save_all, #save_associations, #save_done, #save_element_associations, #save_extended_models, #save_integrated, #set_pks_condition, #sortable?, #storage_value_to_mapper, #update
Constructor Details
#initialize(model, storage) ⇒ DbMapper
Returns a new instance of DbMapper.
13 14 15 16 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 13 def initialize(model, storage) super @type = :db end |
Class Method Details
.write? ⇒ true
Is this mapper writable?
20 21 22 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 20 def self.write? true end |
Instance Method Details
#alter_table(name, schema, attributes, force = nil) ⇒ Object
Returns an alter table structure description
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1340 def alter_table(name, schema, attributes, force=nil) # :nodoc: current = @storage.describe_table(name) current_fields = current[:columns] add_fields = [] alter_fields = [] all_fields = [] unsafe = [] fields = schema[:columns] schema[:fields_order].each do |f| field = f.name field_hash = { :name => field, :type => fields[field][:type], :attributes => fields[field][:attributes] } all_fields << field_hash if (!current_fields[field]) add_fields << field_hash else type = fields[field][:type] field_attributes = fields[field][:attributes] field_attributes ||= {} if (!@storage.schema_field_equal?(current_fields[field], fields[field])) # Spider.logger.debug("DIFFERENT: #{field}") # Spider.logger.debug(current_fields[field]) # Spider.logger.debug(fields[field]) unless @storage.safe_schema_conversion?(current_fields[field], fields[field]) || force unsafe << field next end alter_fields << field_hash end end end alter_attributes = {} if (current[:primary_keys] != attributes[:primary_keys]) alter_attributes[:primary_keys] = attributes[:primary_keys] end if (attributes[:foreign_key_constraints]) end alter_attributes[:foreign_key_constraints] = attributes[:foreign_key_constraints] @storage.alter_table({ :table => name, :add_fields => add_fields, :alter_fields => alter_fields, :all_fields => all_fields, :attributes => alter_attributes, :current => current }) raise SchemaSyncUnsafeConversion.new(unsafe) unless unsafe.empty? end |
#assign_primary_keys(obj) ⇒ Object
Empty hook to set primary keys in the model before insert. Override if needed.
977 978 979 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 977 def assign_primary_keys(obj) # may be implemented in model through the 'with_mapper' method end |
#base_type(type) ⇒ Object
1123 1124 1125 1126 1127 1128 1129 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1123 def base_type(type) if type <= Spider::DataTypes::PK Fixnum else super end end |
#before_save(obj, mode) ⇒ Object
Save (insert and update) #
46 47 48 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 46 def before_save(obj, mode) #:nodoc: super end |
#bulk_update(values, condition) ⇒ Object
Updates according to a condition, storing the values, which must passed as a Hash. Condition may be nil.
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 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 164 def bulk_update(values, condition) db_values = {} joins = [] integrated = {} condition = preprocess_condition(condition) if condition values.each do |key, val| element = @model.elements[key] if element.integrated? integrated[element.integrated_from] ||= {} integrated[element.integrated_from][key] = val next end next if !mapped?(element) next if element.multiple? next if element.model? && !schema.has_foreign_fields?(element.name) if val.is_a?(Spider::QueryFuncs::Expression) joins += prepare_expression(val) store_key = schema.field(element.name) next unless store_key db_values[store_key] = val else prepare_save_value(element, val, :update, db_values) end end integrated.each do |i_el, i_values| next unless condition[i_el.name] i_el.mapper.bulk_update(i_values, condition[i_el.name]) # FIXME? end return if db_values.empty? save = {:table => schema.table, :values => db_values} if condition condition, c_joins = prepare_condition(condition) joins += c_joins save[:condition] = condition end save[:joins] = prepare_joins(joins) sql, bind_vars = @storage.sql_update(save, true) return @storage.execute(sql, *bind_vars) end |
#can_join?(element) ⇒ Boolean
Returns true if an element can be loaded joined-in.
329 330 331 332 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 329 def can_join?(element) return false if element.storage != @storage return true end |
#collect_real_keys(element, path = []) ⇒ Object
Returns an array of all keys, “dereferencing” model keys.
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1245 def collect_real_keys(element, path=[]) # :nodoc: real_keys = [] element.type.primary_keys.each do |key| if (key.model?) real_keys += schema_collect_real_keys(key, path<<element.name) else real_keys << [key, path<<element.name] end end return real_keys end |
#compute_foreign_key_constraints ⇒ Object
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1220 def compute_foreign_key_constraints @model.each_element do |element| foreign_key_constraints = {} next if element.integrated? next unless mapped?(element) next if element.attributes[:added_reverse] && element.has_single_reverse? next unless element.model? next if element.multiple? next unless element.type.mapper.storage == @storage element.type.primary_keys.each do |key| column = self.schema.foreign_key_field(element.name, key.name) column_name = column.name next if !key.integrated? && !element.type.mapper.schema.column(key.name) # FIXME foreign_key_constraints[column_name] = key.integrated? ? \ element.type.mapper.schema.foreign_key_field(key.integrated_from.name, key.integrated_from_element).name : \ element.type.mapper.schema.column(key.name).name end unless foreign_key_constraints.empty? name = element.attributes[:db_foreign_key_name] || "FK_#{schema.table.name}_#{element.name}" self.schema.set_foreign_key_constraint(name, element.type.mapper.schema.table.name, foreign_key_constraints) end end end |
#count(condition_or_query) ⇒ Object
Implements the Mapper#count method doing a count SQL query.
221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 221 def count(condition_or_query) if (condition_or_query.is_a?(Query)) q = condition_or_query.clone else q = Query.new(condition_or_query, @model.primary_keys) end prepare_query(q) storage_query = prepare_select(q) storage_query[:query_type] = :count storage_query.delete(:order) storage_query.delete(:limit) return @storage.query(storage_query) end |
#create_table(table_name, schema, attributes) ⇒ Object
Returns a create table structure description.
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1323 def create_table(table_name, schema, attributes) # :nodoc: fields = schema[:fields_order].uniq.map do |f| details = schema[:columns][f.name] { :name => f.name, :type => details[:type], :attributes => details[:attributes] } end @storage.create_table({ :table => table_name, :fields => fields, :attributes => attributes }) end |
#define_schema(&proc) ⇒ Object
Define schema. Given block will be instance_eval’d before schema auto generation. See also #with_schema.
1081 1082 1083 1084 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1081 def define_schema(&proc) @schema_define_procs ||= [] @schema_define_procs << proc end |
#do_delete(condition, force = false) ⇒ Object
:nodoc:
68 69 70 71 72 73 74 75 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 68 def do_delete(condition, force=false) #:nodoc: #delete = prepare_delete(obj) del = {} del[:condition], del[:joins] = prepare_condition(condition) del[:table] = schema.table sql, values = storage.sql_delete(del, force) storage.execute(sql, *values) end |
#do_insert(obj) ⇒ Object
:nodoc:
51 52 53 54 55 56 57 58 59 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 51 def do_insert(obj) #:nodoc: if (obj.model.managed? || !obj.primary_keys_set?) assign_primary_keys(obj) end sql, values = prepare_insert(obj) if (sql) @storage.execute(sql, *values) end end |
#do_update(obj) ⇒ Object
:nodoc:
61 62 63 64 65 66 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 61 def do_update(obj) #:nodoc: sql, values = prepare_update(obj) if (sql) storage.execute(sql, *values) end end |
#execute_action(action, object, params = {}) ⇒ Object
1061 1062 1063 1064 1065 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1061 def execute_action(action, object, params={}) return super unless action == :delete_associations el = object.class.elements[params[:element]] delete_element_associations(object, el) end |
#fetch(query) ⇒ Object
Implements the Mapper#fetch method.
236 237 238 239 240 241 242 243 244 245 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 236 def fetch(query) # Spider.logger.debug("Fetching model #{@model} query:") # Spider.logger.debug(query) storage_query = prepare_select(query) if (storage_query) result = @storage.query(storage_query) result.total_rows = @storage.total_rows if (query.request.total_rows) end return result end |
#find_by_sql(sql, *bind_vars) ⇒ Object
Finds objects by SQL, mapping back the storage result.
248 249 250 251 252 253 254 255 256 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 248 def find_by_sql(sql, *bind_vars) result = storage.execute(sql, *bind_vars) set = QuerySet.new(@model) result.each do |row| set << map(nil, row, @model) end set.modified = false return set end |
#generate_schema(schema = nil) ⇒ Object
Autogenerates schema. Returns a DbSchema.
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1141 def generate_schema(schema=nil) had_schema = schema ? true : false schema ||= DbSchema.new schema.table ||= @model.attributes[:db_table] || schema_table_name integrated_pks = [] @model.each_element do |element| if element.integrated? integrated_pks << [element.integrated_from.name, element.integrated_from_element] if (element.primary_key?) end end @model.each_element do |element| next if element.integrated? next unless mapped?(element) next if had_schema && schema.pass[element.name] next if element.attributes[:added_reverse] && element.has_single_reverse? if (!element.model?) column = schema.columns[element.name] storage_type = base_type(element.type) db_attributes = column.attributes if column if (!db_attributes || db_attributes.empty?) db_attributes = storage_column_attributes(storage_type, element.attributes) db_attributes.merge(element.attributes[:db]) if (element.attributes[:db]) if (element.attributes[:autoincrement] && !db_attributes[:autoincrement]) schema.set_sequence(element.name, @storage.sequence_name("#{schema.table}_#{element.name}")) end end column_type = element.attributes[:db_column_type] || storage_column_type(storage_type, element.attributes) unless column column_name = element.attributes[:db_column_name] || @storage.column_name(element.name) column = Field.new(schema.table, column_name, column_type) end column.type ||= column_type column.attributes = db_attributes column.primary_key = true if element.primary_key? schema.set_column(element.name, column) elsif (true) # FIXME: must have condition element.storage == @storage in some of the subcases if (!element.multiple? && !element.attributes[:junction] && !element.attributes[:reverse_of]) # 1/n <-> 1 current_schema = schema.foreign_keys[element.name] || {} foreign_key_constraints = {} el_mapper = element.type.mapper element.type.primary_keys.each do |key| if key.model? # fixme: only works with single primary key model (after the first) curr_key = key curr_key = curr_key.model.primary_keys[0] while curr_key.model? && curr_key.model.primary_keys.length == 1 next if curr_key.model key_type = curr_key.type key_attributes = curr_key.attributes else key_type = key.type key_attributes = key.attributes end #key_column = element.mapper.schema.column(key.name) key_attributes = { :length => key_attributes[:length], :precision => key_attributes[:precision] } column = current_schema[key.name] key_storage_type = el_mapper.base_type(key_type) column_type = element.attributes[:db_column_type] || storage_column_type(key_storage_type, key_attributes) unless column column_name = element.attributes[:db_column_name] || @storage.column_name("#{element.name}_#{key.name}") column_attributes = @storage.column_attributes(base_type(key_type), key_attributes) column = Field.new(schema.table, column_name, column_type, column_attributes) end column.type ||= column_type column.primary_key = true if (element.primary_key? || integrated_pks.include?([element.name, key.name])) schema.set_foreign_key(element.name, key.name, column) end end end end @model.sequences.each do |name| schema.set_sequence(name, @storage.sequence_name("#{schema.table}_#{name}")) end return schema end |
#get_deep_join(dotted_element, join_type = nil) ⇒ Array
Returns the joins needed for an element down the tree, expressed in dotted notation. Returns a triplet composed of
-
joins
-
final model called
-
final element called
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 808 def get_deep_join(dotted_element, join_type=nil) #return [[], @model, @model.elements[dotted_element]] unless dotted_element.is_a?(String) parts = dotted_element.to_s.split('.').map{ |el| el.to_sym } current_model = @model joins = [] el = nil # Spider::Logger.debug("GETTING DEEP JOIN TO #{dotted_element} (#{@model})") cnt = 0 parts.each do |part| cnt += 1 el = current_model.elements[part] raise "Can't find element #{part} in model #{current_model}" unless el next if have_references?(el) && cnt == parts.length if el.integrated? joins << current_model.mapper.get_join(el.integrated_from, join_type) current_model = el.integrated_from.type el = current_model.elements[el.integrated_from_element] end if el.model? && can_join?(el) joins << current_model.mapper.get_join(el, join_type) current_model = el.model end end while el.integrated? && !have_references?(el) joins << current_model.mapper.get_join(el.integrated_from, join_type) # joins << current_model.integrated_from.mapper.get_join(el.integrated_from_element) current_model = el.integrated_from.type el = current_model.elements[el.integrated_from_element] end return [joins, current_model, el] end |
#get_dependencies(task) ⇒ Object
UnitOfWork dependencies.
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 987 def get_dependencies(task) deps = [] obj = task.object action = task.action deps = [] case action when :keys deps << [task, MapperTask.new(obj, :save)] unless obj.primary_keys_set? || (!obj.mapper || !obj.mapper.class.write?) when :save @model.primary_keys.each do |key| if key.integrated? && !obj.element_has_value?(key) obj.get(key.integrated_from) # ensure super object is instantiated, so it gets processed later end end elements = @model.elements.select{ |n, el| !el.integrated? && el.model? && obj.element_has_value?(el) && obj.element_modified?(el)} elements.each do |name, element| if have_references?(element) el_obj = obj.send(element.name) sub_task = MapperTask.new(el_obj, :keys) deps << [task, sub_task] else if element.type.mapper && element.type.mapper.class.write? el_val = obj.send(element.name) if element.multiple? set = el_val if element.junction? && !element.attributes[:keep_junction] set = obj.send("#{element.name}_junction") end delete_ass = nil #if set.modified # queryset modified if set.modified && obj.primary_keys_set? # queryset modified delete_ass = MapperTask.new(obj, :delete_associations, :element => element.name) deps << [task, delete_ass] end prev_task = nil set.each do |set_obj| sub_task = MapperTask.new(set_obj, :save) if set_obj.class.attributes[:sub_model] && delete_ass set_obj.class.primary_keys.each{ |pk| set_obj.set(pk, nil) } end if prev_task deps << [sub_task, prev_task] else deps << [sub_task, task] end if delete_ass del_dep = set_obj if element.reverse set_obj.set_modified(element.reverse) el = set_obj.class.elements[element.reverse] # ensure the real owner is added as a dependency while el.integrated? del_dep = set_obj.get(el.integrated_from) el = del_dep.class.elements[el.integrated_from_element] end end deps << [MapperTask.new(del_dep, :save), delete_ass] end prev_task = sub_task end else el_val.set_modified(element.reverse) #deps << [task, MapperTask.new(el_val, :save)] deps << [MapperTask.new(el_val, :save), task] end end end end end return deps end |
#get_join(element, join_type = :inner) ⇒ Object
Figures out a join for element. Returns join hash description, i.e. :
join = {
:type => :inner|:outer|...,
:from => 'table1',
:to => 'table2',
:keys => hash of key pairs,
:condition => join condition
}
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 734 def get_join(element, join_type = :inner) return unless element.model? #Spider::Logger.debug("Getting join for model #{@model} to element #{element}") #Spider::Logger.debug(@model.primary_keys.map{|k| k.name}) element_table = element.mapper.schema.table if (schema.has_foreign_fields?(element.name)) #Spider::Logger.debug("JOIN A from #{@model} to #{element.name}") keys = {} element.model.primary_keys.each do |key| if (key.integrated?) # FIXME raise "Unimplemented join dereference for multiple primary keys" if key.integrated_from.model.primary_keys.length > 1 el_field = element.mapper.schema.foreign_key_field(key.integrated_from.name, key.integrated_from.model.primary_keys[0].name) else el_field = element.mapper.schema.field(key.name) end fk = schema.foreign_key_field(element.name, key.name) keys[fk] = el_field # FIXME: works with models as primary keys through a hack in the field method of db_schema, # assuming the model has only one key. the correct way would be to get another join end if (element.condition) condition, condition_joins, condition_remaining = element.mapper.prepare_condition(element.condition) end as = nil if (element.model == @model) as = "#{schema.table}_#{element.name}" end join = { :type => join_type, :from => schema.table, :to => element.mapper.schema.table, :keys => keys, :condition => condition, :as => as } elsif (element.has_single_reverse? && element.mapper.schema.has_foreign_fields?(element.reverse)) # n/1 <-> n #Spider::Logger.debug("JOIN B from #{@model} to #{element.name}") keys = {} @model.primary_keys.each do |key| our_field = nil if (key.integrated?) our_field = schema.foreign_key_field(key.integrated_from.name, key.integrated_from_element) else our_field = schema.field(key.name) end keys[our_field] = element.mapper.schema.foreign_key_field(element.reverse, key.name) end if (element.condition) condition, condition_joins, condition_remaining = element.mapper.prepare_condition(element.condition) end join = { :type => join_type, :from => schema.table, :to => element.mapper.schema.table, :keys => keys, :condition => condition } else # n <-> n # no need to handle n <-> n end # FIXME: add element conditions! return join end |
#get_join_info(model, condition) ⇒ Object
Returns an hash with true for elements that need an inner join Note: subsequent joins of a left join have to be left joins, otherwise the first join will behave as an inner. Maybe they should be marked and later made behave like an inner with an appropriate (A.key is null or B.key is not null) condition. Not sure if this is needed, since first level conditions should filter out any unwanted results.
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 525 def get_join_info(model, condition) join_info = {} condition.each_with_comparison do |k, v, comp| next unless k.respond_to?(:to_sym) element = model.elements[k.to_sym] next unless element next unless model.mapper.mapped?(element) next unless element.model? join_info[k.to_s] = if v.nil? comp == '<>' ? true : false else comp == '<>' ? false : true end if v.is_a?(Spider::Model::Condition) el_join_info = get_join_info(element.model, v) has_true = false has_false = false el_join_info.each do |jk, jv| join_info["#{k}.#{jk}"] = jv has_true = true if jv has_false = true unless jv end if (v.conjunction == :and && has_true) || (has_true && !has_false) join_info[k.to_s] = true elsif (v.conjunction == :or && has_false) || (has_false && !has_true) join_info[k.to_s] = false end end end res = {} keys = join_info.keys sub_join_infos = [join_info] condition.subconditions.each do |sub_cond| next if sub_cond.empty? sub_join_info = get_join_info(model, sub_cond) keys += sub_join_info.keys sub_join_infos << sub_join_info end keys.uniq! sub_join_infos.each do |sub_join_info| keys.each do |k| if condition.conjunction == :or res[k] = true if sub_join_info[k] && res[k] != false res[k] = false unless sub_join_info[k] else res[k] = true if sub_join_info[k] end end end res end |
#get_schema ⇒ Object
Returns the schema, as defined or autogenerated.
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1093 def get_schema schema = @model.superclass.mapper.get_schema() if (@model.attributes[:inherit_storage]) if @schema_define_procs schema = DbSchema.new @schema_define_procs.each do |schema_proc| schema.instance_eval(&schema_proc) end end schema = generate_schema(schema) if @schema_procs @schema_procs.each do |schema_proc| schema.instance_eval(&schema_proc) end end return schema end |
#has_aggregates?(condition, in_or = false) ⇒ Boolean
582 583 584 585 586 587 588 589 590 591 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 582 def has_aggregates?(condition, in_or=false) condition.each_with_comparison do |k, v, comp| return true if k.is_a?(QueryFuncs::Function) && k.has_aggregates? end in_or = true if condition.conjunction == :or condition.subconditions.each do |sub_cond| return true if in_or && has_aggregates?(sub_cond, in_or) end return false end |
#have_references?(element) ⇒ Boolean
Checks if the schema has some key to reach element.
29 30 31 32 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 29 def have_references?(element) #:nodoc: element = @model.elements[element] unless element.is_a?(Element) schema.has_foreign_fields?(element.name) || schema.field(element.name) end |
#lock(obj = nil, mode = :exclusive) ⇒ Object
Lock db – FIXME
207 208 209 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 207 def lock(obj=nil, mode=:exclusive) #:nodoc: return storage.lock(@schema.table) unless obj end |
#map(request, result, obj_or_model) ⇒ Object
Implements the Mapper#map method. Converts a DB result row to an object.
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 260 def map(request, result, obj_or_model) if (!request || request == true) request = Request.new @model.elements_array.each{ |el| request.request(el.name) } end model = obj_or_model.is_a?(Class) ? obj_or_model : obj_or_model.model data = {} extra_data = {} request.keys.each do |element_name| if element_name.is_a?(QueryFuncs::SelectFunction) extra_data[element_name.as] = result[element_name.as.to_s] end element = @model.elements[element_name] result_value = nil next if !element || element.integrated? || !have_references?(element) if (element.model? && schema.has_foreign_fields?(element.name)) pks = {} keys_set = true element.model.primary_keys.each do |key| key_val = result[schema.foreign_key_field(element_name, key.name).name] keys_set = false unless key_val pks[key.name] = map_back_value(key.type, key_val) end # begin data[element_name] = keys_set ? Spider::Model.get(element.model, pks, true) : nil # rescue IdentityMapperException # null keys, nothing to set # end elsif !element.model? data[element_name] = map_back_value(element.type, result[schema.field(element_name).name]) end end begin obj = Spider::Model.get(model, data, true) rescue IdentityMapperException => exc # This should not happen Spider::Logger.warn("Row in DB without primary keys for model #{model}; won't be mapped:") Spider::Logger.warn(data) return nil end data.keys.each{ |el| obj.element_loaded(el) } extra_data.each do |k, v| obj[k] = v end if (request.polymorphs) request.polymorphs.each do |model, polym_request| polym_result = {} polym_request.keys.each do |element_name| field = model.mapper.schema.field(element_name).name res_field = "#{model.mapper.schema.table}_#{field}" polym_result[field] = result[res_field] if result[res_field] end if (!polym_result.empty?) polym_obj = model.new polym_obj = polym_obj.mapper.map(polym_request, polym_result, polym_obj) polym_obj.set_loaded_value(model.extended_models[@model], obj) obj = polym_obj break end end end return obj end |
#map_back_value(type, value) ⇒ Object
962 963 964 965 966 967 968 969 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 962 def map_back_value(type, value) case type.name when 'Spider::DataTypes::Bool' return value if value.nil? return value == 1 ? true : false end return super end |
#map_type(type) ⇒ Object
Returns a type accepted by the storage for type.
938 939 940 941 942 943 944 945 946 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 938 def map_type(type) st = type return Fixnum if st <= Spider::DataTypes::PK while (st && !storage.class.base_types.include?(st)) st = Model.simplify_type(st) end return type unless st return st end |
#map_value(type, value, mode = nil) ⇒ Object
Converts a value in one accepted by the storage.
949 950 951 952 953 954 955 956 957 958 959 960 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 949 def map_value(type, value, mode=nil) return value if value.nil? case type.name when 'Spider::DataTypes::Bool' value = value ? 1 : 0 else value = super end return value end |
#max(element, condition = nil) ⇒ Object
Aggregates #
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1398 def max(element, condition=nil) element = @model.elements[element] if element.is_a?(Symbol) schema = element.integrated? ? @model.elements[element.integrated_from.name].model.mapper.schema : self.schema max = {} max[:condition], joins = prepare_condition(condition) if condition max[:tables] = [schema.table] max[:field] = schema.field(element.name) joins ||= [] max[:joins] = prepare_joins(joins) sql, values = storage.sql_max(max) res = storage.execute(sql, *values) return res[0] && res[0]['M'] ? res[0]['M'] : 0 end |
#pk ⇒ Object
24 25 26 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 24 def pk [Fixnum, {:autoincrement => true}] end |
#prepare_condition(condition, options = {}) ⇒ Object
Generates a storage description for the condition Returns a list of three elements, composed of
-
conditions: an hash
{ :conj => 'and'|'or', :values => an array of [field, comparison, value] triplets }
-
joins: an array of structures as returned by #get_join
-
remaining_condition: part of the condition which can’t be passed to the storage
– TODO: better name for :values
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 506 def prepare_condition(condition, ={}) model = condition.polymorph ? condition.polymorph : @model model_schema = model.mapper.schema cond = {} bind_values = [] joins = [:joins] || [] remaining_condition = Condition.new # TODO: implement cond[:conj] = condition.conjunction.to_s cond[:values] = [] # Returns an hash with true for elements that need an inner join # Note: subsequent joins of a left join have to be left joins, # otherwise the first join will behave as an inner. # Maybe they should be marked and later made behave like an inner with an # appropriate (A.key is null or B.key is not null) condition. # Not sure if this is needed, since first level conditions should filter out # any unwanted results. def get_join_info(model, condition) join_info = {} condition.each_with_comparison do |k, v, comp| next unless k.respond_to?(:to_sym) element = model.elements[k.to_sym] next unless element next unless model.mapper.mapped?(element) next unless element.model? join_info[k.to_s] = if v.nil? comp == '<>' ? true : false else comp == '<>' ? false : true end if v.is_a?(Spider::Model::Condition) el_join_info = get_join_info(element.model, v) has_true = false has_false = false el_join_info.each do |jk, jv| join_info["#{k}.#{jk}"] = jv has_true = true if jv has_false = true unless jv end if (v.conjunction == :and && has_true) || (has_true && !has_false) join_info[k.to_s] = true elsif (v.conjunction == :or && has_false) || (has_false && !has_true) join_info[k.to_s] = false end end end res = {} keys = join_info.keys sub_join_infos = [join_info] condition.subconditions.each do |sub_cond| next if sub_cond.empty? sub_join_info = get_join_info(model, sub_cond) keys += sub_join_info.keys sub_join_infos << sub_join_info end keys.uniq! sub_join_infos.each do |sub_join_info| keys.each do |k| if condition.conjunction == :or res[k] = true if sub_join_info[k] && res[k] != false res[k] = false unless sub_join_info[k] else res[k] = true if sub_join_info[k] end end end res end join_info = [:join_info] join_info ||= get_join_info(@model, condition) def has_aggregates?(condition, in_or=false) condition.each_with_comparison do |k, v, comp| return true if k.is_a?(QueryFuncs::Function) && k.has_aggregates? end in_or = true if condition.conjunction == :or condition.subconditions.each do |sub_cond| return true if in_or && has_aggregates?(sub_cond, in_or) end return false end is_having = [:is_having] is_having = has_aggregates?(condition) if is_having.nil? cond[:group_by_fields] ||= [] if is_having condition.each_with_comparison do |k, v, comp| if k.is_a?(QueryFuncs::Function) field = prepare_queryfunc(k) cond[:values] << [field, comp, v] joins += field.joins if is_having k.inner_elements.each do |el_name, owner_func| next if owner_func.is_a?(QueryFuncs::AggregateFunction) cond[:group_by_fields] <<= owner_func.mapper_fields[el_name.to_s] end end next end element = model.elements[k.to_sym] next unless model.mapper.mapped?(element) if (element.model?) el_join_info = {} join_info.each do |jk, jv| if jk.index(k.to_s+'.') == 0 el_join_info[jk[k.to_s.length+1..-1]] = jv end end if v && model.mapper.have_references?(element.name) && v.primary_keys_only?(element.model) # 1/n <-> 1 with only primary keys element_cond = {:conj => 'AND', :values => [], :is_having => is_having} v.each_with_comparison do |el_k, el_v, el_comp| field = model_schema.foreign_key_field(element.name, el_k) next if field.is_a?(FixedExpression) el_comp ||= '=' op = el_comp field_cond = [field, op, map_condition_value(element.model.elements[el_k.to_sym].type, el_v)] element_cond[:values] << field_cond cond[:group_by_fields] << field if is_having end cond[:values] << element_cond else if element.storage == model.mapper.storage needs_join = true if v.nil? && comp == '=' el_model_schema = model_schema element_cond = {:conj => 'AND', :values => [], :is_having => is_having} if model.mapper.have_references?(element.name) el_name = element.name el_model = element.model needs_join = false elsif element.junction? el_model = element.type el_model_schema = element.model.mapper.schema el_name = element.attributes[:junction_their_element] else el_model = @model el_model_schema = element.type.mapper.schema el_name = element.reverse end el_model.primary_keys.each do |k| field = el_model_schema.foreign_key_field(el_name, k.name) next if field.is_a?(FixedExpression) field_cond = [field, comp, map_condition_value(el_model.elements[k.name].type, nil)] element_cond[:values] << field_cond element_cond[:is_having] = is_having cond[:group_by_fields] << field if is_having end cond[:values] << element_cond end if needs_join join_type = join_info[element.name.to_s] ? :inner : :left sub_join = model.mapper.get_join(element, join_type) # FIXME! cleanup, and apply the check to joins acquired in other places, too (maybe pass the current joins to get_join) existent = joins.select{ |j| j[:to] == sub_join[:to] } j_cnt = nil had_join = false existent.each do |j| if sub_join[:to] == j[:to] && sub_join[:keys] == j[:keys] && sub_join[:conditions] == j[:conditions] # if any condition allows a left join, then a left join should be used here as well j[:type] = :left if sub_join[:type] == :left sub_join = j had_join = true break else j_cnt ||= 0; j_cnt += 1 end end sub_join[:as] = "#{sub_join[:to]}#{j_cnt}" if j_cnt joins << sub_join unless had_join end if v sub_condition, sub_joins = element.mapper.prepare_condition(v, :table => sub_join[:as], :joins => joins, :join_info => el_join_info, :is_having => is_having || nil) sub_condition[:table] = sub_join[:as] if sub_join[:as] joins = sub_joins cond[:values] << sub_condition end else remaining_condition ||= Condition.new remaining_condition.set(k, comp, v) end end elsif(model_schema.field(element.name)) field = model_schema.field(element.name) field = FieldInAliasedTable.new(field, [:table]) if [:table] op = comp ? comp : '=' if (v.is_a?(Spider::QueryFuncs::Expression)) v_joins = prepare_expression(v) joins += v_joins cond[:values] << [field, op, v] else cond[:values] << [field, op, map_condition_value(model.elements[k.to_sym].type, v)] end cond[:group_by_fields] << field if is_having end end cond[:is_having] = is_having sub_sqls = [] sub_bind_values = [] condition.subconditions.each do |sub| sub_res = self.prepare_condition(sub, :joins => joins, :join_info => join_info, :is_having => is_having || nil) cond[:values] << sub_res[0] joins = sub_res[1] remaining_condition += sub_res[2] end return [cond, joins, remaining_condition] end |
#prepare_expression(expr) ⇒ Object
Takes a Spider::QueryFuncs::Expression, and associates the fields to the corresponding elements Returns an array of needed joins
857 858 859 860 861 862 863 864 865 866 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 857 def prepare_expression(expr) joins = [] expr.each_element do |v_el| v_joins, j_model, j_el = get_deep_join(v_el) db_field = j_model.mapper.schema.qualified_field(j_el.name) joins += v_joins expr[v_el] = db_field end return joins end |
#prepare_group_by(query) ⇒ Object
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 909 def prepare_group_by(query) return nil if !query.group_by_elements joins = [] fields = [] query.group_by_elements.each do |gb| el_model = @model el_joins, el_model, el = get_deep_join(gb) # FIXME: this is almost identical to prepare_order if el.model? if el_model.mapper.have_references?(el) || el.model.storage != storage el.model.primary_keys.each do |pk| fields << el_model.mapper.schema.foreign_key_field(el.name, pk.name) end else el.model.primary_keys.each do |pk| fields << el.model.mapper.schema.field(pk.name) end end else raise "Order on unmapped element #{el_model.name}.#{el.name}" unless el_model.mapper.mapped?(el) field = el_model.mapper.schema.field(el.name) fields << field end joins += el_joins end return [fields, joins] end |
#prepare_insert(obj) ⇒ Object
Insert preprocessing
140 141 142 143 144 145 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 140 def prepare_insert(obj) #:nodoc: save = prepare_save(obj, :insert) return nil unless save[:values].length > 0 save[:table] = @schema.table return @storage.sql_insert(save) end |
#prepare_joins(joins) ⇒ Object
– FIXME: document
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 458 def prepare_joins(joins) # :nodoc: h = {} left_joins = [] joins.each do |join| h[join[:from]] ||= {} cur = (h[join[:from]][join[:to]] ||= []) has_join = false cur.each do |cur_join| if (cur_join[:keys] == join[:keys] && cur_join[:conditions] == join[:conditions]) cur_join[:type] = :left if join[:type] == :left && !join[:order] has_join = true break end end left_joins << join if join[:type] == :left h[join[:from]][join[:to]] << join unless has_join end while left_joins.length > 0 new_left_joins = [] left_joins.each do |lj| if h[lj[:to]] h[lj[:to]].each_key do |to| h[lj[:to]][to].each do |j| unless j[:type] == :left new_left_joins << j j[:type] = :left end end end end end left_joins = new_left_joins end return h end |
#prepare_order(query) ⇒ Object
Returns a pair composed of
-
fields, an array of [field, direction] couples; and
-
joins, joins needed for the order, if any
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 871 def prepare_order(query) joins = [] fields = [] query.order.each do |order| order_element, direction = order el_model = @model if (order_element.is_a?(QueryFuncs::Function)) field = prepare_queryfunc(order_element) joins += field.joins fields << [field, direction] else el_joins, el_model, el = get_deep_join(order_element, :left) el_joins.each do |el_j| el_j[:order] = true end if el.model? if el_model.mapper.have_references?(el) || el.model.storage != storage el.model.primary_keys.each do |pk| field = el_model.mapper.schema.foreign_key_field(el.name, pk.name) next if field.is_a?(FixedExpression) fields << [field, direction] end else el.model.primary_keys.each do |pk| fields << [el.model.mapper.schema.field(pk.name), direction] end end else raise "Order on unmapped element #{el_model.name}.#{el.name}" unless el_model.mapper.mapped?(el) field = el_model.mapper.schema.field(el.name) fields << [field, direction] end joins += el_joins end end return [fields, joins] end |
#prepare_query_request(request, obj = nil) ⇒ Object
:nodoc:
324 325 326 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 324 def prepare_query_request(request, obj=nil) #:nodoc: super(request, obj) end |
#prepare_queryfunc(func) ⇒ Object
840 841 842 843 844 845 846 847 848 849 850 851 852 853 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 840 def prepare_queryfunc(func) joins = [] func_elements = func.inner_elements func_elements.each do |el_name, owner_func| el_joins, el_model, el = get_deep_join(el_name) joins += el_joins owner_func.mapper_fields ||= {} owner_func.mapper_fields[el_name.to_s] = el_model.mapper.schema.field(el.name) end f = FieldFunction.new(storage.function(func), schema.table, joins) f.as = func.as if func.is_a?(QueryFuncs::SelectFunction) f.aggregate = true if func.has_aggregates? return f end |
#prepare_save(obj, save_mode) ⇒ Object
Save preprocessing
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 92 def prepare_save(obj, save_mode) #:nodoc: values = {} obj.no_autoload do @model.each_element do |element| next if !mapped?(element) || element.integrated? next if save_mode == :update && !obj.element_modified?(element) if save_mode == :insert if element.attributes[:autoincrement] && !schema.attributes(element.name)[:autoincrement] obj.set(element.name, @storage.sequence_next(schema.sequence(element.name))) end end next if element.multiple? next if save_mode == :update && element.primary_key? next if element.model? && !schema.has_foreign_fields?(element.name) element_val = obj.get(element) prepare_save_value(element, element_val, save_mode, values) end end return { :values => values } end |
#prepare_save_value(element, element_val, save_mode, values = {}) ⇒ Object
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 116 def prepare_save_value(element, element_val, save_mode, values={}) element_val = nil if element.model? && element_val.is_a?(BaseModel) && !element_val.primary_keys_set? if element.model? element.model.primary_keys.each do |key| # FIXME! only works with one primary key if (key.model?) key_type = key.model.primary_keys[0].type key_value = element_val ? element_val.get(key.name).get(key.model.primary_keys[0]) : nil else key_type = key.model? ? key.model.primary_keys[0].type : key.type key_value = element_val ? element_val.get(key.name) : nil end store_key = schema.foreign_key_field(element.name, key.name) next if store_key.is_a?(FieldExpression) values[store_key] = map_save_value(key_type, key_value, save_mode) end else store_key = schema.field(element.name) values[store_key] = map_save_value(element.type, element_val, save_mode) end values end |
#prepare_select(query) ⇒ Object
Generates a select hash description based on the query.
335 336 337 338 339 340 341 342 343 344 345 346 347 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 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 335 def prepare_select(query) #:nodoc: condition, joins = prepare_condition(query.condition) elements = query.request.keys.select{ |k| !k.is_a?(QueryFuncs::SelectFunction) && mapped?(k) } select_functions = query.request.keys.select{ |k| k.is_a?(QueryFuncs::SelectFunction) } keys = [] primary_keys = [] types = {} if (query.limit && query.order.empty? && !query.only_one?) @model.primary_keys.each do |key| elements << key.name unless elements.include?(key.name) query.order_by(key.name, :asc) end end order, order_joins = prepare_order(query) cnt = 0 order_joins.each do |oj| oj[:as] ||= "ORD#{cnt+=1}" if joins.select{ |j| j[:to] == oj[:to] }.length > 0 end joins += order_joins if order_joins group_by, group_by_joins = prepare_group_by(query) joins += group_by_joins if group_by_joins seen_fields = {} model_pks = [] @model.primary_keys.each do |pk| if (pk.integrated?) model_pks << pk.integrated_from.name else model_pks << pk.name end end elements.each do |el| element = @model.elements[el.to_sym] next if !element || !element.type || element.integrated? if !element.model? field = schema.field(el) raise "Element #{el} in #{@model} does not have a schema field" unless field primary_keys << field if model_pks.include?(el) unless seen_fields[field.name] keys << field seen_fields[field.name] = true end elsif !element.attributes[:junction] if schema.has_foreign_fields?(el) element.model.primary_keys.each do |key| field = schema.foreign_key_field(el, key.name) raise "Can't find a foreign key field for key #{key.name} of element #{el} of model #{@model}" unless field primary_keys << field if model_pks.include?(el) unless seen_fields[field.name] keys << field seen_fields[field.name] = true end end end sub_request = query.request[element.name] end end select_functions.each do |f| keys << prepare_queryfunc(f) end if (query.request.polymorphs? || !query.condition.polymorphs.empty?) only_conditions = {:conj => 'or', :values => []} if (query.request.only_polymorphs?) polymorphs = (query.request.polymorphs.keys + query.condition.polymorphs).uniq polymorphs.each do |model| polym_request = query.request.polymorphs[model] || Request.new extension_element = model.extended_models[@model] model.mapper.prepare_query_request(polym_request) polym_request.reject!{|k, v| model.elements[k].integrated? && model.elements[k].integrated_from.name == extension_element } polym_only = {:conj => 'and', :values => []} if (query.request.only_polymorphs?) model.elements_array.select{ |el| el.attributes[:local_pk] }.each do |el| polym_request[el.name] = true if (query.request.only_polymorphs?) polym_only[:values] << [model.mapper.schema.qualified_field(el.name), '<>', nil] end end only_conditions[:values] << polym_only if query.request.only_polymorphs? polym_select = model.mapper.prepare_select(Query.new(nil, polym_request)) # FIXME! polym_select[:keys].map!{ |key| "#{key} AS #{key.to_s.gsub('.', '_')}"} keys += polym_select[:keys] join_fields = {} @model.primary_keys.each do |key| from_field = @schema.field(key.name) to_field = model.mapper.schema.foreign_key_field(extension_element, key.name) join_fields[from_field] = to_field end # FIXME: move to get_join join = { :type => :left, :from => @schema.table, :to => model.mapper.schema.table, :keys => join_fields } joins << join end end if (only_conditions) if (condition[:conj].downcase != 'and') condition = {:conj => 'and', :values => [condition]} end condition[:values] << only_conditions end tables = [schema.table] joins = prepare_joins(joins) return nil if (keys.empty?) return { :query_type => :select, :keys => keys, :primary_keys => primary_keys.uniq, :tables => tables, :condition => condition, :joins => joins, :order => order, :group_by => group_by, :offset => query.offset, :limit => query.limit } end |
#prepare_update(obj) ⇒ Object
Update preprocessing
148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 148 def prepare_update(obj) #:nodoc: save = prepare_save(obj, :update) return nil unless save[:values].length > 0 condition = Condition.and @model.primary_keys.each do |key| condition[key.name] = obj.get(key) end preprocess_condition(condition) save[:condition], save[:joins] = prepare_condition(condition) save[:joins] = prepare_joins(save[:joins]) save[:table] = @schema.table return @storage.sql_update(save) end |
#reset_schema ⇒ Object
Resets the schema, so that it is regenerated on the next call
1111 1112 1113 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1111 def reset_schema @schema = nil end |
#schema ⇒ Object
Returns @schema, or creates one.
1087 1088 1089 1090 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1087 def schema @schema ||= get_schema() return @schema end |
#schema_table_name ⇒ Object
1131 1132 1133 1134 1135 1136 1137 1138 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1131 def schema_table_name n = @model.name.sub('::Models', '') app = @model.app app_name = app.name if app short_prefix = app.short_prefix if app n.sub!(app_name, short_prefix) if short_prefix @storage.table_name(n) end |
#sequence_next(name) ⇒ Object
Next value for the named sequence
212 213 214 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 212 def sequence_next(name) return storage.sequence_next(schema.sequence(name)) end |
#someone_have_references?(element) ⇒ Boolean
34 35 36 37 38 39 40 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 34 def someone_have_references?(element) element = @model.elements[element] unless element.is_a?(Element) if (element.integrated?) return element.model.someone_have_references?(element.attributes[:integrated_from_element]) end return have_references?(element) end |
#sql_execute(sql, *values) ⇒ Object
Execute SQL directly, returning raw db results.
87 88 89 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 87 def sql_execute(sql, *values) storage.execute(sql, *values) end |
#storage_column_attributes(type, attributes) ⇒ Object
1119 1120 1121 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1119 def storage_column_attributes(type, attributes) @storage.column_attributes(type, attributes) end |
#storage_column_type(type, attributes) ⇒ Object
1115 1116 1117 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1115 def storage_column_type(type, attributes) @storage.column_type(type, attributes) end |
#sync_schema(force = false, options = {}) ⇒ Object
Modifies the storage according to the schema.
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1258 def sync_schema(force=false, ={}) compute_foreign_key_constraints unless [:no_foreign_key_constraints] || !storage.supports?(:foreign_keys) schema_description = schema.get_schemas sequences = {} sequences[schema.table] = schema.sequences @model.elements_array.select{ |el| el.attributes[:anonymous_model] }.each do |el| next if el.model.mapper.class != self.class el.model.mapper.compute_foreign_key_constraints schema_description.merge!(el.model.mapper.schema.get_schemas) sequences[el.model.mapper.schema.table] ||= {} sequences[el.model.mapper.schema.table].merge!(el.model.mapper.schema.sequences) # Spider::Logger.debug("MERGING SEQUENCES:") # Spider::Logger.debug(el.model.mapper.schema.sequences) # sequences.merge!(el.model.mapper.schema.sequences) end schema_description.each do |table_name, table_schema| table_attributes = { :primary_keys => table_schema[:attributes][:primary_keys] } unless [:no_foreign_key_constraints] || !storage.supports?(:foreign_keys) table_attributes[:foreign_key_constraints] = table_schema[:attributes][:foreign_key_constraints] || [] end if @storage.table_exists?(table_name) alter_table(table_name, table_schema, table_attributes, force) else create_table(table_name, table_schema, table_attributes) end if ([:drop_fields]) current = @storage.describe_table(table_name)[:columns] current.each_key do |cur| @storage.drop_field(table_name, cur) if (!table_schema[:columns][cur]) end end end @model.elements_array.select{ |el| el.attributes[:index] }.each do |el| found = false schema.table.fields.map do |field| found = (field.name == el.name.to_s) break if found end sql = @storage.create_index(schema.table,el.name.to_s,el.attributes[:index]) if found end if @model.extended_models.empty? seen = {} sequences.each do |sequence_table, table_sequences| table_sequences.each do |element_name, db_name| next if seen[db_name] if storage.sequence_exists?(db_name) if ([:update_sequences]) sql = "SELECT MAX(#{schema.field(element_name).name}) AS M FROM #{sequence_table}" res = @storage.execute(sql) max = res[0]['M'].to_i storage.update_sequence(db_name, max+1) end else storage.create_sequence(db_name) end seen[db_name] = true end end end |
#truncate! ⇒ Object
77 78 79 80 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 77 def truncate! sql = storage.sql_truncate(schema.table) storage.execute(sql) end |
#with_schema(&proc) ⇒ Object
Extend schema. Given block will be instance_eval’d after schema auto generation. See also #define_schema.
1074 1075 1076 1077 |
# File 'lib/spiderfw/model/mappers/db_mapper.rb', line 1074 def with_schema(&proc) @schema_procs ||= [] @schema_procs << proc end |