Class: ActiveCypher::Relationship
- Inherits:
-
Object
- Object
- ActiveCypher::Relationship
- Includes:
- Logging, Model::Abstract, Model::Callbacks, Model::ConnectionOwner, Model::Countable, ActiveModel::API, ActiveModel::Attributes, ActiveModel::Dirty, ActiveModel::Naming, ActiveModel::Validations
- Defined in:
- lib/active_cypher/relationship.rb
Direct Known Subclasses
Constant Summary
Constants included from Model::Callbacks
Class Attribute Summary collapse
-
.last_internal_id ⇒ Object
readonly
Returns the value of attribute last_internal_id.
Instance Attribute Summary collapse
-
#from_node ⇒ Object
————————————————————– Life‑cycle ————————————————————–.
-
#new_record ⇒ Object
readonly
Returns the value of attribute new_record.
-
#to_node ⇒ Object
————————————————————– Life‑cycle ————————————————————–.
Class Method Summary collapse
-
.connection ⇒ Object
————————————————————– Connection fallback ————————————————————– Relationship classes usually share the same Bolt pool as the node they originate from; delegate there unless the relationship class was given its own pool explicitly.
-
.create(attrs = {}, from_node:, to_node:, **attribute_kwargs) ⇒ Object
– factories ———————————————– Mirrors ActiveRecord.create.
-
.create!(attrs = {}, from_node:, to_node:, **attribute_kwargs) ⇒ Object
Bang version of create - raises exception if save fails For when you want your relationship failures to be as dramatic as your breakups.
-
.find_by(attributes = {}) ⇒ Object
– Querying methods —————————————- Find the first relationship matching the given attributes Like finding a needle in a haystack, if the haystack was made of graph edges.
-
.find_by!(attributes = {}) ⇒ Object
Find the first relationship or raise an exception For when nil just isn’t dramatic enough for your data access needs.
-
.from_class(value = nil) ⇒ Object
(also: from_class_name)
– endpoints ————————————————.
-
.inherited(subclass) ⇒ Object
Prevent subclasses from overriding node_base_class.
-
.instantiate(attributes, from_node: nil, to_node: nil) ⇒ Object
Instantiate from DB row, marking the instance as persisted.
-
.node_base_class(klass = nil) ⇒ Object
DSL for setting or getting the node base class for connection delegation.
- .to_class(value = nil) ⇒ Object (also: to_class_name)
-
.type(value = nil) ⇒ Object
(also: relationship_type)
– type —————————————————–.
Instance Method Summary collapse
- #destroy ⇒ Object
- #destroyed? ⇒ Boolean
-
#initialize(attrs = {}, from_node: nil, to_node: nil, **attribute_kwargs) ⇒ Relationship
constructor
A new instance of Relationship.
- #new_record? ⇒ Boolean
- #persisted? ⇒ Boolean
-
#save(validate: true) ⇒ Object
————————————————————– Persistence API ————————————————————–.
-
#save! ⇒ Object
Bang version of save - raises exception if save fails For when you want your relationship persistence to be as dramatic as your code reviews.
Methods included from Logging
#log_bench, #log_debug, #log_error, #log_info, #log_warn, logger, #logger
Methods included from Model::ConnectionOwner
#adapter_class, #connection, db_key_for
Constructor Details
#initialize(attrs = {}, from_node: nil, to_node: nil, **attribute_kwargs) ⇒ Relationship
Returns a new instance of Relationship.
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'lib/active_cypher/relationship.rb', line 288 def initialize(attrs = {}, from_node: nil, to_node: nil, **attribute_kwargs) _run(:initialize) do super() # Merge explicit attrs hash with keyword arguments for attributes. # Note: `attribute_kwargs` takes precedence over `attrs` for keys that exist in both. combined_attrs = attrs.merge(attribute_kwargs) assign_attributes(combined_attrs) if combined_attrs.any? @from_node = from_node @to_node = to_node @new_record = true clear_changes_information end end |
Class Attribute Details
.last_internal_id ⇒ Object (readonly)
Returns the value of attribute last_internal_id.
97 98 99 |
# File 'lib/active_cypher/relationship.rb', line 97 def last_internal_id @last_internal_id end |
Instance Attribute Details
#from_node ⇒ Object
Life‑cycle
285 286 287 |
# File 'lib/active_cypher/relationship.rb', line 285 def from_node @from_node end |
#new_record ⇒ Object (readonly)
Returns the value of attribute new_record.
286 287 288 |
# File 'lib/active_cypher/relationship.rb', line 286 def new_record @new_record end |
#to_node ⇒ Object
Life‑cycle
285 286 287 |
# File 'lib/active_cypher/relationship.rb', line 285 def to_node @to_node end |
Class Method Details
.connection ⇒ Object
Connection fallback
Relationship classes usually share the same Bolt pool as the node they originate from; delegate there unless the relationship class was given its own pool explicitly.
WorksAtRelationship.connection # -> PersonNode.connection
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/active_cypher/relationship.rb', line 67 def self.connection # If this is a concrete relationship class with from_class defined, # prefer delegating to that node's connection (so role/shard routing is respected). if !abstract_class? && (fc = from_class_name) klass = fc.constantize role = ActiveCypher::RuntimeRegistry.current_role shard = ActiveCypher::RuntimeRegistry.current_shard return klass.connected_to(role: role, shard: shard) do klass.connection end end # Otherwise, fall back to node_base_class if present (even if abstract) if (klass = node_base_class) return klass.connection end from_class.constantize.connection end |
.create(attrs = {}, from_node:, to_node:, **attribute_kwargs) ⇒ Object
– factories ———————————————– Mirrors ActiveRecord.create
168 169 170 |
# File 'lib/active_cypher/relationship.rb', line 168 def create(attrs = {}, from_node:, to_node:, **attribute_kwargs) new(attrs, from_node: from_node, to_node: to_node, **attribute_kwargs).tap(&:save) end |
.create!(attrs = {}, from_node:, to_node:, **attribute_kwargs) ⇒ Object
Bang version of create - raises exception if save fails For when you want your relationship failures to be as dramatic as your breakups
174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/active_cypher/relationship.rb', line 174 def create!(attrs = {}, from_node:, to_node:, **attribute_kwargs) relationship = create(attrs, from_node: from_node, to_node: to_node, **attribute_kwargs) if relationship.persisted? relationship else error_msgs = relationship.errors..join(', ') error_msgs = 'Validation failed' if error_msgs.empty? raise ActiveCypher::RecordNotSaved, "#{name} could not be saved: #{error_msgs}. " \ "Perhaps the nodes aren't ready for this kind of commitment?" end end |
.find_by(attributes = {}) ⇒ Object
– Querying methods —————————————- Find the first relationship matching the given attributes Like finding a needle in a haystack, if the haystack was made of graph edges
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/active_cypher/relationship.rb', line 200 def find_by(attributes = {}) return nil if attributes.blank? rel_type = relationship_type id_func = connection.class::ID_FUNCTION # Build WHERE conditions for the attributes conditions = [] params = {} if attributes.key?(:internal_id) where_clause = "#{id_func}(r) = $p1" params['p1'] = attributes[:internal_id] else attributes.each_with_index do |(key, value), index| param_name = :"p#{index + 1}" conditions << "r.#{key} = $#{param_name}" params[param_name] = value end where_clause = conditions.join(' AND ') end cypher = <<~CYPHER MATCH ()-[r:#{rel_type}]-() WHERE #{where_clause} RETURN r, #{id_func}(r) as rid, startNode(r) as from_node, endNode(r) as to_node LIMIT 1 CYPHER result = connection.execute_cypher(cypher, params, 'Find Relationship By') row = result.first return nil unless row # Extract relationship data and instantiate rel_data = row[:r] || row['r'] rid = row[:rid] || row['rid'] from_node_id = (row[:from_node] || row['from_node'])&.dig(1, 0) to_node_id = (row[:to_node] || row['to_node'])&.dig(1, 0) # this is extra queries, but easier than navigating instantiation from the row data from_node = Object.const_get(from_class).find(from_node_id) to_node = Object.const_get(to_class).find(to_node_id) # Extract properties from the relationship data # Memgraph returns relationships wrapped as [type_code, [actual_data]] attrs = {} if rel_data.is_a?(Array) && rel_data.length == 2 # Extract the actual relationship data from the second element actual_data = rel_data[1] if actual_data.is_a?(Array) && actual_data.length >= 5 # Format: [rel_id, start_id, end_id, type, properties, ...] props = actual_data[4] attrs = props.is_a?(Hash) ? props : {} end elsif rel_data.is_a?(Hash) attrs = rel_data end # Convert string keys to symbols for attributes attrs = attrs.transform_keys(&:to_sym) attrs[:internal_id] = rid if rid instantiate(attrs, from_node: from_node, to_node: to_node) end |
.find_by!(attributes = {}) ⇒ Object
Find the first relationship or raise an exception For when nil just isn’t dramatic enough for your data access needs
271 272 273 274 275 276 277 278 279 |
# File 'lib/active_cypher/relationship.rb', line 271 def find_by!(attributes = {}) # Format attributes nicely for the error message formatted_attrs = attributes.map { |k, v| "#{k}: #{v.inspect}" }.join(', ') find_by(attributes) || raise(ActiveCypher::RecordNotFound, "Couldn't find #{name} with #{formatted_attrs}. " \ 'Maybe these nodes were never meant to be connected? ' \ 'Or perhaps their relationship status is... complicated?') end |
.from_class(value = nil) ⇒ Object Also known as: from_class_name
– endpoints ————————————————
144 145 146 147 148 |
# File 'lib/active_cypher/relationship.rb', line 144 def from_class(value = nil) return _from_class_name if value.nil? self._from_class_name = value.to_s end |
.inherited(subclass) ⇒ Object
Prevent subclasses from overriding node_base_class
129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/active_cypher/relationship.rb', line 129 def inherited(subclass) super # Reset abstract_class for subclasses (mirrors Model::Abstract behavior # which gets overridden by this method definition) subclass.abstract_class = false return unless _node_base_class subclass._node_base_class = _node_base_class def subclass.node_base_class(*) raise "Cannot override node_base_class in subclass #{name}; it is locked to #{_node_base_class}" end end |
.instantiate(attributes, from_node: nil, to_node: nil) ⇒ Object
Instantiate from DB row, marking the instance as persisted.
188 189 190 191 192 193 194 195 |
# File 'lib/active_cypher/relationship.rb', line 188 def instantiate(attributes, from_node: nil, to_node: nil) instance = allocate instance.send(:init_with_attributes, attributes, from_node: from_node, to_node: to_node) instance end |
.node_base_class(klass = nil) ⇒ Object
DSL for setting or getting the node base class for connection delegation
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/active_cypher/relationship.rb', line 100 def node_base_class(klass = nil) if klass.nil? # If not set, try convention: XxxRelationship -> XxxNode return _node_base_class if _node_base_class if name&.end_with?('Relationship') node_base_name = name.sub(/Relationship\z/, 'Node') begin node_base_klass = node_base_name.constantize if node_base_klass.respond_to?(:abstract_class?) && node_base_klass.abstract_class? self._node_base_class = node_base_klass return node_base_klass end rescue NameError # Do nothing, fallback to nil end end return _node_base_class end # Only allow setting on abstract relationship base classes raise "Cannot set node_base_class on non-abstract relationship class #{name}" unless abstract_class? unless klass.respond_to?(:abstract_class?) && klass.abstract_class? raise ArgumentError, "node_base_class must be an abstract node base class (got #{klass})" end self._node_base_class = klass end |
.to_class(value = nil) ⇒ Object Also known as: to_class_name
151 152 153 154 155 |
# File 'lib/active_cypher/relationship.rb', line 151 def to_class(value = nil) return _to_class_name if value.nil? self._to_class_name = value.to_s end |
.type(value = nil) ⇒ Object Also known as: relationship_type
– type —————————————————–
159 160 161 162 163 |
# File 'lib/active_cypher/relationship.rb', line 159 def type(value = nil) return _relationship_type if value.nil? self._relationship_type = value.to_s.upcase end |
Instance Method Details
#destroy ⇒ Object
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/active_cypher/relationship.rb', line 343 def destroy _run(:destroy) do raise 'Cannot destroy a new relationship' if new_record? raise 'Relationship already destroyed' if destroyed? adapter = self.class.connection.id_handler cypher = "MATCH ()-[r]-() WHERE #{adapter.with_direct_id(internal_id)} DELETE r" params = {} self.class.connection.execute_cypher(cypher, params, 'Destroy Relationship') @destroyed = true freeze true end rescue StandardError => e log_error "Failed to destroy #{self.class}: #{e.class} – #{e.}" false end |
#destroyed? ⇒ Boolean
306 |
# File 'lib/active_cypher/relationship.rb', line 306 def destroyed? = @destroyed == true |
#new_record? ⇒ Boolean
304 |
# File 'lib/active_cypher/relationship.rb', line 304 def new_record? = @new_record |
#persisted? ⇒ Boolean
305 |
# File 'lib/active_cypher/relationship.rb', line 305 def persisted? = !new_record? && internal_id.present? |
#save(validate: true) ⇒ Object
Persistence API
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/active_cypher/relationship.rb', line 311 def save(validate: true) return false if validate && !valid? _run(:save) do if new_record? _run(:create) { create_relationship } else _run(:update) { update_relationship } end end rescue ActiveCypher::RecordNotSaved, RuntimeError => e # Only catch specific validation errors, let other errors propagate raise unless e..include?('must be persisted') || e..include?('creation returned no id') log_error "Failed to save #{self.class}: #{e.}" false end |
#save! ⇒ Object
Bang version of save - raises exception if save fails For when you want your relationship persistence to be as dramatic as your code reviews
331 332 333 334 335 336 337 338 339 340 341 |
# File 'lib/active_cypher/relationship.rb', line 331 def save! if save self else error_msgs = errors..join(', ') error_msgs = 'Validation failed' if error_msgs.empty? raise ActiveCypher::RecordNotSaved, "#{self.class} could not be saved: #{error_msgs}. " \ 'Perhaps this relationship was never meant to be?' end end |