Class: ActiveCypher::Relationship
- Inherits:
-
Object
- Object
- ActiveCypher::Relationship
- Includes:
- Logging, Model::Abstract, Model::Callbacks, Model::ConnectionHandling, 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.
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/active_cypher/relationship.rb', line 281 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.
98 99 100 |
# File 'lib/active_cypher/relationship.rb', line 98 def last_internal_id @last_internal_id end |
Instance Attribute Details
#from_node ⇒ Object
Life‑cycle
278 279 280 |
# File 'lib/active_cypher/relationship.rb', line 278 def from_node @from_node end |
#new_record ⇒ Object (readonly)
Returns the value of attribute new_record.
279 280 281 |
# File 'lib/active_cypher/relationship.rb', line 279 def new_record @new_record end |
#to_node ⇒ Object
Life‑cycle
278 279 280 |
# File 'lib/active_cypher/relationship.rb', line 278 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
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/active_cypher/relationship.rb', line 68 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
169 170 171 |
# File 'lib/active_cypher/relationship.rb', line 169 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
175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/active_cypher/relationship.rb', line 175 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
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 |
# File 'lib/active_cypher/relationship.rb', line 201 def find_by(attributes = {}) return nil if attributes.blank? rel_type = relationship_type # Build WHERE conditions for the attributes conditions = [] params = {} 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 ') # Determine ID function based on adapter type adapter_class = connection.class id_func = adapter_class.const_defined?(:ID_FUNCTION) ? adapter_class::ID_FUNCTION : 'id' cypher = " MATCH ()-[r:\#{rel_type}]-()\n WHERE \#{where_clause}\n RETURN r, \#{id_func}(r) as rid, startNode(r) as from_node, endNode(r) as to_node\n LIMIT 1\n CYPHER\n\n result = connection.execute_cypher(cypher, params, 'Find Relationship By')\n row = result.first\n\n return nil unless row\n\n # Extract relationship data and instantiate\n rel_data = row[:r] || row['r']\n rid = row[:rid] || row['rid']\n\n # Extract properties from the relationship data\n # Memgraph returns relationships wrapped as [type_code, [actual_data]]\n attrs = {}\n\n if rel_data.is_a?(Array) && rel_data.length == 2\n # Extract the actual relationship data from the second element\n actual_data = rel_data[1]\n\n if actual_data.is_a?(Array) && actual_data.length >= 5\n # Format: [rel_id, start_id, end_id, type, properties, ...]\n props = actual_data[4]\n attrs = props.is_a?(Hash) ? props : {}\n end\n elsif rel_data.is_a?(Hash)\n attrs = rel_data\n end\n\n # Convert string keys to symbols for attributes\n attrs = attrs.transform_keys(&:to_sym)\n attrs[:internal_id] = rid if rid\n\n instantiate(attrs)\nend\n" |
.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
264 265 266 267 268 269 270 271 272 |
# File 'lib/active_cypher/relationship.rb', line 264 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 ————————————————
145 146 147 148 149 |
# File 'lib/active_cypher/relationship.rb', line 145 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
130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/active_cypher/relationship.rb', line 130 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.
189 190 191 192 193 194 195 196 |
# File 'lib/active_cypher/relationship.rb', line 189 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
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 127 |
# File 'lib/active_cypher/relationship.rb', line 101 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
152 153 154 155 156 |
# File 'lib/active_cypher/relationship.rb', line 152 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 —————————————————–
160 161 162 163 164 |
# File 'lib/active_cypher/relationship.rb', line 160 def type(value = nil) return _relationship_type if value.nil? self._relationship_type = value.to_s.upcase end |
Instance Method Details
#destroy ⇒ Object
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
# File 'lib/active_cypher/relationship.rb', line 336 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.message}" false end |
#destroyed? ⇒ Boolean
299 |
# File 'lib/active_cypher/relationship.rb', line 299 def destroyed? = @destroyed == true |
#new_record? ⇒ Boolean
297 |
# File 'lib/active_cypher/relationship.rb', line 297 def new_record? = @new_record |
#persisted? ⇒ Boolean
298 |
# File 'lib/active_cypher/relationship.rb', line 298 def persisted? = !new_record? && internal_id.present? |
#save(validate: true) ⇒ Object
Persistence API
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/active_cypher/relationship.rb', line 304 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.message}" 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
324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/active_cypher/relationship.rb', line 324 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 |