module Fiona7 class SuperIdFinder def initialize(forbidden_obj_classes=[], fields=[], connection=::Fiona7::WriteObj.connection, instance_name=RailsConnector::CmsBaseModel.instance_name) @instance_name = instance_name @forbidden = forbidden_obj_classes @fields = fields @conn = connection end def find(type=:preview, obj_ids) case type when :preview preview(obj_ids) when :live live(obj_ids) else raise ArgumentError, "Uknown type #{type.inspect} expected :preview or :live" end end def preview(obj_ids) query = "SELECT #{objects_table}.object_id FROM #{links_table} INNER JOIN #{objects_table} ON #{links_table}.content_id = #{objects_table}.edited_content_id WHERE #{links_table}.sub_object_id IN #{obj_ids_array(obj_ids)} #{self.obj_class_condition} UNION SELECT #{objects_table}.object_id FROM #{links_table} INNER JOIN #{objects_table} ON #{links_table}.content_id = #{objects_table}.committed_cont_id WHERE #{links_table}.sub_object_id IN #{obj_ids_array(obj_ids)} #{self.obj_class_condition} UNION SELECT #{objects_table}.object_id FROM #{links_table} INNER JOIN #{objects_table} ON #{links_table}.content_id = #{objects_table}.released_cont_id WHERE #{links_table}.sub_object_id IN #{obj_ids_array(obj_ids)} AND #{objects_table}.committed_cont_id IS NULL AND #{objects_table}.edited_content_id IS NULL #{self.obj_class_condition} #{self.field_condition}" ids = self.sql_query(query).to_a.flatten end def live(obj_ids) query = "SELECT #{objects_table}.object_id FROM #{links_table} INNER JOIN #{objects_table} ON #{links_table}.content_id = #{objects_table}.released_cont_id WHERE #{links_table}.sub_object_id IN #{obj_ids_array(obj_ids)} #{self.obj_class_condition} #{self.field_condition}" ids = self.sql_query(query).to_a.flatten end protected def links_table "#{@instance_name}_links" end def obj_ids_array(obj_ids) obj_ids = obj_ids.presence || [0] values = obj_ids.map {|obj_id| @conn.quote(obj_id) }.join(", ") " (#{values}) " end def obj_class_condition if @forbidden.present? values = @forbidden.map { |f| @conn.quote(f) }.join(", ") " AND #{objects_table}.obj_class NOT IN (#{values}) " else "" end end def field_condition if @fields.present? values = @fields.map { |f| @conn.quote(f) }.join(", ") " AND #{links_table}.attribute_name IN (#{values}) " else "" end end def objects_table "#{@instance_name}_objects" end def sql_query(query, *args) @conn.execute(query, *args) end end end