Class: ActiveCypher::Relationship

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

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

Constructor Details

#initialize(attrs = {}, from_node: nil, to_node: nil, **attribute_kwargs) ⇒ Relationship

Returns a new instance of Relationship.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/active_cypher/relationship.rb', line 267

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.



88
89
90
# File 'lib/active_cypher/relationship.rb', line 88

def last_internal_id
  @last_internal_id
end

Instance Attribute Details

#from_nodeObject


Life‑cycle




264
265
266
# File 'lib/active_cypher/relationship.rb', line 264

def from_node
  @from_node
end

#new_recordObject (readonly)

Returns the value of attribute new_record.



265
266
267
# File 'lib/active_cypher/relationship.rb', line 265

def new_record
  @new_record
end

#to_nodeObject


Life‑cycle




264
265
266
# File 'lib/active_cypher/relationship.rb', line 264

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


68
69
70
71
72
73
74
75
76
77
# File 'lib/active_cypher/relationship.rb', line 68

def self.connection
  # If a node_base_class is set (directly or by convention), always delegate to its connection
  if (klass = node_base_class)
    return klass.connection
  end

  return @connection if defined?(@connection) && @connection

  from_class.constantize.connection
end

.create(attrs = {}, from_node:, to_node:, **attribute_kwargs) ⇒ Object

– factories ———————————————– Mirrors ActiveRecord.create



155
156
157
# File 'lib/active_cypher/relationship.rb', line 155

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



161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/active_cypher/relationship.rb', line 161

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



187
188
189
190
191
192
193
194
195
196
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
# File 'lib/active_cypher/relationship.rb', line 187

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



250
251
252
253
254
255
256
257
258
# File 'lib/active_cypher/relationship.rb', line 250

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



131
132
133
134
135
# File 'lib/active_cypher/relationship.rb', line 131

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



120
121
122
123
124
125
126
127
128
# File 'lib/active_cypher/relationship.rb', line 120

def inherited(subclass)
  super
  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.



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

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



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/active_cypher/relationship.rb', line 91

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



138
139
140
141
142
# File 'lib/active_cypher/relationship.rb', line 138

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



146
147
148
149
150
# File 'lib/active_cypher/relationship.rb', line 146

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

  self._relationship_type = value.to_s.upcase
end

Instance Method Details

#destroyObject



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/active_cypher/relationship.rb', line 324

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)


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

def destroyed?   = @destroyed == true

#new_record?Boolean

Returns:

  • (Boolean)


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

def new_record?  = @new_record

#persisted?Boolean

Returns:

  • (Boolean)


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

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

#save(validate: true) ⇒ Object


Persistence API




290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/active_cypher/relationship.rb', line 290

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
  if e.message.include?('must be persisted') || e.message.include?('creation returned no id')
    log_error "Failed to save #{self.class}: #{e.message}"
    false
  else
    raise
  end
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



312
313
314
315
316
317
318
319
320
321
322
# File 'lib/active_cypher/relationship.rb', line 312

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