Class: ActiveCypher::Relationship

Inherits:
Object
  • Object
show all
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

ApplicationGraphRelationship

Constant Summary

Constants included from Model::Callbacks

Model::Callbacks::EVENTS

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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.



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/active_cypher/relationship.rb', line 285

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_idObject (readonly)

Returns the value of attribute last_internal_id.



94
95
96
# File 'lib/active_cypher/relationship.rb', line 94

def last_internal_id
  @last_internal_id
end

Instance Attribute Details

#from_nodeObject


Life‑cycle




282
283
284
# File 'lib/active_cypher/relationship.rb', line 282

def from_node
  @from_node
end

#new_recordObject (readonly)

Returns the value of attribute new_record.



283
284
285
# File 'lib/active_cypher/relationship.rb', line 283

def new_record
  @new_record
end

#to_nodeObject


Life‑cycle




282
283
284
# File 'lib/active_cypher/relationship.rb', line 282

def to_node
  @to_node
end

Class Method Details

.connectionObject


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


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/active_cypher/relationship.rb', line 64

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



165
166
167
# File 'lib/active_cypher/relationship.rb', line 165

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



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/active_cypher/relationship.rb', line 171

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.full_messages.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



197
198
199
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
# File 'lib/active_cypher/relationship.rb', line 197

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(self.from_class).find(from_node_id)
  to_node = Object.const_get(self.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



268
269
270
271
272
273
274
275
276
# File 'lib/active_cypher/relationship.rb', line 268

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 ————————————————



141
142
143
144
145
# File 'lib/active_cypher/relationship.rb', line 141

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



126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/active_cypher/relationship.rb', line 126

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.



185
186
187
188
189
190
191
192
# File 'lib/active_cypher/relationship.rb', line 185

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



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/active_cypher/relationship.rb', line 97

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



148
149
150
151
152
# File 'lib/active_cypher/relationship.rb', line 148

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 —————————————————–



156
157
158
159
160
# File 'lib/active_cypher/relationship.rb', line 156

def type(value = nil)
  return _relationship_type if value.nil?

  self._relationship_type = value.to_s.upcase
end

Instance Method Details

#destroyObject



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/active_cypher/relationship.rb', line 340

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

Returns:

  • (Boolean)


303
# File 'lib/active_cypher/relationship.rb', line 303

def destroyed?   = @destroyed == true

#new_record?Boolean

Returns:

  • (Boolean)


301
# File 'lib/active_cypher/relationship.rb', line 301

def new_record?  = @new_record

#persisted?Boolean

Returns:

  • (Boolean)


302
# File 'lib/active_cypher/relationship.rb', line 302

def persisted?   = !new_record? && internal_id.present?

#save(validate: true) ⇒ Object


Persistence API




308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/active_cypher/relationship.rb', line 308

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.message.include?('must be persisted') || e.message.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



328
329
330
331
332
333
334
335
336
337
338
# File 'lib/active_cypher/relationship.rb', line 328

def save!
  if save
    self
  else
    error_msgs = errors.full_messages.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