Class: Solis::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/solis/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Model

Returns a new instance of Model.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/solis/model.rb', line 12

def initialize(attributes = {})
  @model_name = self.class.name
  @model_plural_name = @model_name.pluralize
  @language = Graphiti.context[:object]&.language || Solis::Options.instance.get[:language] || 'en'

  raise "Please look at /#{@model_name.tableize}/model for structure to supply" if attributes.nil?

  attributes.each do |attribute, value|
    if self.class.[:attributes].keys.include?(attribute.to_s)
      if !self.class.[:attributes][attribute.to_s][:node_kind].nil? && !(value.is_a?(Hash) || value.is_a?(Array) || value.class.ancestors.include?(Solis::Model))
        raise Solis::Error::InvalidAttributeError, "'#{@model_name}.#{attribute}' must be an object"
      end

      if self.class.[:attributes][attribute.to_s][:node_kind].is_a?(RDF::URI) && value.is_a?(Hash)
        inner_class = self.class.[:attributes][attribute.to_s][:datatype].to_s
        inner_model = self.class.graph.shape_as_model(inner_class)

        # Resolve a polymorphic reference to its concrete subclass, preferring an
        # explicit `type` key, then a full URI whose path segment names the class.
        # Keys may be strings (JSON) or symbols (internal callers).
        explicit_type = (value['type'] || value[:type] || value['@type'] || value[:'@type']).to_s
        value = value.reject { |k, _| %w[type @type].include?(k.to_s) }
        id_value = (value['id'] || value[:id]).to_s
        if !explicit_type.empty? && descendant_shape_names(inner_model.name).include?(explicit_type)
          inner_model = self.class.graph.shape_as_model(explicit_type)
        elsif !id_value.empty? && id_value.match?(self.class.graph_name)
          concrete = id_value.gsub(self.class.graph_name, '').split('/').first.classify.to_s
          if descendant_shape_names(inner_model.name).include?(concrete)
            inner_model = self.class.graph.shape_as_model(concrete)
          end
        end

        value = inner_model.new(value)
      elsif self.class.[:attributes][attribute.to_s][:node_kind].is_a?(RDF::URI) && value.is_a?(Array)
        new_value = []
        value.each do |v|
          if v.is_a?(Hash)
            inner_model = self.class.graph.shape_as_model(self.class.[:attributes][attribute.to_s][:datatype].to_s)
            new_value << inner_model.new(v)
          else
            new_value << v
          end
        end
        value = new_value
      end

      # switched off. currently language query parameters returns the value
      # value = {
      #   "@language" => @language,
      #   "@value" => value
      # } if self.class.metadata[:attributes][attribute.to_s][:datatype_rdf].eql?('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString')

      value = value.first if value.is_a?(Array) && (attribute.eql?('id') || attribute.eql?(:id))

      instance_variable_set("@#{attribute}", value)
    else
      raise Solis::Error::InvalidAttributeError, "'#{attribute}' is not part of the definition of #{@model_name}"
    end
  end

  self.class.make_id_for(self)
rescue StandardError => e
  Solis::LOGGER.error(e.message)
  raise Solis::Error::GeneralError, "Unable to create entity #{@model_name}"
end

Class Method Details

.batch_exists?(sparql, entities) ⇒ Boolean

Check existence of multiple entities in a single SPARQL query Returns a Set of graph_ids that exist

Returns:

  • (Boolean)


494
495
496
497
498
499
500
501
502
503
# File 'lib/solis/model.rb', line 494

def self.batch_exists?(sparql, entities)
  return Set.new if entities.empty?
  return Set.new([entities.first.graph_id]) if entities.size == 1 && entities.first.exists?(sparql)
  return Set.new if entities.size == 1

  values = entities.map { |e| "<#{e.graph_id}>" }.join(' ')
  query = "SELECT DISTINCT ?s WHERE { VALUES ?s { #{values} } . ?s ?p ?o }"
  results = sparql.query(query)
  Set.new(results.map { |r| r[:s].to_s })
end

.batch_save(entities, validate_dependencies: true, batch_size: 100) ⇒ Array<Solis::Model>

Save multiple entities in a single SPARQL INSERT operation. Entities that already exist are updated individually.

Parameters:

  • entities (Array<Solis::Model>)

    entities to save

  • validate_dependencies (Boolean) (defaults to: true)

    whether to validate dependencies

  • batch_size (Integer) (defaults to: 100)

    max entities per INSERT (default 100)

Returns:



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/solis/model.rb', line 442

def self.batch_save(entities, validate_dependencies: true, batch_size: 100)
  raise "I need a SPARQL endpoint" if sparql_endpoint.nil?
  return [] if entities.empty?

  sparql = SPARQL::Client.new(sparql_endpoint)

  # Batch check existence of all entities
  existing_ids = batch_exists?(sparql, entities)

  to_create = []
  to_update = []

  entities.each do |entity|
    if existing_ids.include?(entity.graph_id)
      to_update << entity
    else
      to_create << entity
    end
  end

  # Batch insert: combine new entity graphs into single INSERT DATA operations
  unless to_create.empty?
    to_create.each_slice(batch_size) do |batch|
      combined_graph = RDF::Graph.new
      combined_graph.name = RDF::URI(graph_name)
      visited = Set.new

      batch.each do |entity|
        entity.before_create_proc&.call(entity)
        entity.send(:serialize_entity, combined_graph, entity, true, visited, [])
      end

      sparql.insert_data(combined_graph, graph: combined_graph.name)

      batch.each { |entity| entity.after_create_proc&.call(entity) }
    end

    # Invalidate cache once for the entity type
    Solis::Query.invalidate_cache_for(name)
  end

  # Updates still processed individually (DELETE/INSERT requires per-entity WHERE)
  to_update.each do |entity|
    data = entity.send(:properties_to_hash, entity)
    entity.update(data, validate_dependencies, true, sparql)
  end

  entities
end

.construct(level = 0) ⇒ Object



616
617
618
# File 'lib/solis/model.rb', line 616

def self.construct(level = 0)
  raise 'to be implemented'
end

.graphObject



562
563
564
# File 'lib/solis/model.rb', line 562

def self.graph
  @graph
end

.graph=(graph) ⇒ Object



566
567
568
# File 'lib/solis/model.rb', line 566

def self.graph=(graph)
  @graph = graph
end

.graph_nameObject



538
539
540
# File 'lib/solis/model.rb', line 538

def self.graph_name
  @graph_name
end

.graph_name=(graph_name) ⇒ Object



542
543
544
# File 'lib/solis/model.rb', line 542

def self.graph_name=(graph_name)
  @graph_name = graph_name
end

.graph_prefixObject



550
551
552
# File 'lib/solis/model.rb', line 550

def self.graph_prefix
  @graph_prefix
end

.graph_prefix=(graph_prefix) ⇒ Object



546
547
548
# File 'lib/solis/model.rb', line 546

def self.graph_prefix=(graph_prefix)
  @graph_prefix = graph_prefix
end

.languageObject



570
571
572
# File 'lib/solis/model.rb', line 570

def self.language
  Graphiti.context[:object]&.language || Solis::Options.instance.get[:language] || @language || 'en'
end

.language=(language) ⇒ Object



574
575
576
# File 'lib/solis/model.rb', line 574

def self.language=(language)
  @language = language
end

.make_id_for(model) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/solis/model.rb', line 505

def self.make_id_for(model)
  id = model.instance_variable_get("@id")
  if id.nil? || (id.is_a?(String) && id&.empty?)
    id = SecureRandom.uuid
    LOGGER.info("ID(#{id}) generated for #{self.name}") if ConfigFile[:debug]
    model.instance_variable_set("@id", id)
  elsif id.to_s =~ /^https?:\/\//
    id = id.to_s.split('/').last
    LOGGER.info("ID(#{id}) normalised for #{self.name}") if ConfigFile[:debug]
    model.instance_variable_set("@id", id)
  end
  model
rescue StandardError => e
  Solis::LOGGER.error(e.message)
  raise Solis::Error::GeneralError, "Error generating id for #{self.name}"
end

.metadataObject



522
523
524
# File 'lib/solis/model.rb', line 522

def self.
  @metadata
end

.metadata=(m) ⇒ Object



526
527
528
# File 'lib/solis/model.rb', line 526

def self.metadata=(m)
  @metadata = m
end

.model(level = 0) ⇒ Object



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/solis/model.rb', line 578

def self.model(level = 0)
  m = { type: self.name.tableize, attributes: [] }
  self.[:attributes].each do |attribute, |
    if .key?(:class) && ![:class].nil? && [:class].value =~ /#{self.graph_name}/ && level == 0
      cm = self.graph.shape_as_model(self.[:attributes][attribute][:datatype].to_s).model(level + 1)
    end

    attribute_data = { name: attribute,
                       data_type: [:datatype],
                       mandatory: ([:mincount].to_i > 0),
                       repeatable: ([:maxcount].to_i > 1 || [:maxcount].nil?),
                       description: [:comment]&.value
    }
    attribute_data[:order] = [:order]&.value.to_i if .key?(:order) && ![:order].nil?
    attribute_data[:group] = [:group]&.value.gsub(graph_name,'').gsub(/Group$/,'') if .key?(:group) && ![:group].nil?
    attribute_data[:attributes] = cm[:attributes] if cm && cm[:attributes]

    m[:attributes] << attribute_data
  end

  m
end

.model_after_create(&blk) ⇒ Object



632
633
634
# File 'lib/solis/model.rb', line 632

def self.model_after_create(&blk)
  self.after_create_proc = blk
end

.model_after_delete(&blk) ⇒ Object



648
649
650
# File 'lib/solis/model.rb', line 648

def self.model_after_delete(&blk)
  self.after_delete_proc = blk
end

.model_after_read(&blk) ⇒ Object



624
625
626
# File 'lib/solis/model.rb', line 624

def self.model_after_read(&blk)
  self.after_read_proc = blk
end

.model_after_update(&blk) ⇒ Object



640
641
642
# File 'lib/solis/model.rb', line 640

def self.model_after_update(&blk)
  self.after_update_proc = blk
end

.model_before_create(&blk) ⇒ Object



628
629
630
# File 'lib/solis/model.rb', line 628

def self.model_before_create(&blk)
  self.before_create_proc = blk
end

.model_before_delete(&blk) ⇒ Object



644
645
646
# File 'lib/solis/model.rb', line 644

def self.model_before_delete(&blk)
  self.before_delete_proc = blk
end

.model_before_read(&blk) ⇒ Object



620
621
622
# File 'lib/solis/model.rb', line 620

def self.model_before_read(&blk)
  self.before_read_proc = blk
end

.model_before_update(&blk) ⇒ Object



636
637
638
# File 'lib/solis/model.rb', line 636

def self.model_before_update(&blk)
  self.before_update_proc = blk
end

.model_template(level = 0) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/solis/model.rb', line 601

def self.model_template(level = 0)
  m = { type: self.name.tableize, attributes: {} }
  self.[:attributes].each do |attribute, |

    if .key?(:class) && ![:class].nil? && [:class].value =~ /#{self.graph_name}/ && level == 0
      cm = self.graph.shape_as_model(self.[:attributes][attribute][:datatype].to_s).model_template(level + 1)
      m[:attributes][attribute.to_sym] = cm[:attributes]
    else
      m[:attributes][attribute.to_sym] = ''
    end
  end

  m
end

.shapesObject



534
535
536
# File 'lib/solis/model.rb', line 534

def self.shapes
  @shapes
end

.shapes=(s) ⇒ Object



530
531
532
# File 'lib/solis/model.rb', line 530

def self.shapes=(s)
  @shapes = s
end

.sparql_endpointObject



554
555
556
# File 'lib/solis/model.rb', line 554

def self.sparql_endpoint
  @sparql_endpoint
end

.sparql_endpoint=(sparql_endpoint) ⇒ Object



558
559
560
# File 'lib/solis/model.rb', line 558

def self.sparql_endpoint=(sparql_endpoint)
  @sparql_endpoint = sparql_endpoint
end

Instance Method Details

#destroyObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/solis/model.rb', line 126

def destroy
  raise "I need a SPARQL endpoint" if self.class.sparql_endpoint.nil?
  sparql = Solis::Store::Sparql::Client.new(self.class.sparql_endpoint)

  raise Solis::Error::QueryError, "#{self.id} is still referenced, refusing to delete" if is_referenced?(sparql)

  before_delete_proc&.call(self)

  query = %(
with <#{self.class.graph_name}>
delete {?s ?p ?o}
where {
values ?s {<#{self.graph_id}>}
?s ?p ?o }
  )
  result = sparql.query(query)

  if result.count > 0
    if result.first.bound?(result.variable_names.first) && result.first[result.variable_names.first].value =~ /done$/
      after_delete_proc&.call(self)
    else
      after_delete_proc&.call(result)
    end
  end

  # Invalidate cached queries for this entity type
  Solis::Query.invalidate_cache_for(self.class.name)

  result
end

#dump(format = :ttl, resolve_all = true) ⇒ Object



102
103
104
105
# File 'lib/solis/model.rb', line 102

def dump(format = :ttl, resolve_all = true)
  graph = as_graph(self, deep: resolve_all)
  graph.dump(format)
end

#exists?(sparql) ⇒ Boolean

Returns:

  • (Boolean)


432
433
434
# File 'lib/solis/model.rb', line 432

def exists?(sparql)
  sparql.query("ASK WHERE { <#{self.graph_id}> ?p ?o }")
end

#graph_idObject



424
425
426
# File 'lib/solis/model.rb', line 424

def graph_id
  "#{self.class.graph_name}#{tableized_class_name(self)}/#{self.id}"
end

#is_referenced?(sparql) ⇒ Boolean

Returns:

  • (Boolean)


428
429
430
# File 'lib/solis/model.rb', line 428

def is_referenced?(sparql)
  sparql.query("ASK WHERE { ?s ?p <#{self.graph_id}>. filter (!contains(str(?s), 'audit') && !contains(str(?p), 'audit'))}")
end

#model_class_name(plural = false) ⇒ Object

Removed the ‘name’ instance method to avoid conflicts with ‘name’ attributes Use model_class_name instead, or access @model_name directly



80
81
82
83
84
85
86
# File 'lib/solis/model.rb', line 80

def model_class_name(plural = false)
  if plural
    @model_plural_name
  else
    @model_name
  end
end

#queryObject



88
89
90
91
92
93
94
95
# File 'lib/solis/model.rb', line 88

def query
  raise "I need a SPARQL endpoint" if self.class.sparql_endpoint.nil?

  # before_read_proc&.call(self)
  result = Solis::Query.new(self)
  # after_read_proc&.call(result)
  result
end

#save(validate_dependencies = true, top_level = true) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
# File 'lib/solis/model.rb', line 157

def save(validate_dependencies = true, top_level = true)
  raise "I need a SPARQL endpoint" if self.class.sparql_endpoint.nil?
  sparql = SPARQL::Client.new(self.class.sparql_endpoint)

  before_create_proc&.call(self)

  if self.exists?(sparql)
    data = properties_to_hash(self)
    result = update(data, validate_dependencies, top_level, sparql)
  else
    readonly_list = (Solis::Options.instance.get[:embedded_readonly] || []).map(&:to_s)

    # Re-type polymorphic base-class id-only references (e.g. an `agent` stub
    # that is really an `Organisatie`) to their concrete subclass, so URIs and
    # existence checks target the subclass's storage path.
    resolve_polymorphic_references!(self, sparql)

    # Enumerate the whole in-memory tree: self plus every embedded descendant.
    all_entities = collect_known_entities(self).values
    existing_ids = self.class.batch_exists?(sparql, all_entities)

    # Classify each entity: new (insert), existing embedded (update), readonly,
    # or a pure reference. readonly only protects EMBEDDED entities; the entity
    # being saved (self) is always created even when its class is a code table.
    new_entities = []
    existing_embedded = []
    all_entities.each do |entity|
      entity_exists = existing_ids.include?(entity.graph_id)
      if !entity.equal?(self) && readonly_entity?(entity, readonly_list)
        Solis::LOGGER.warn("#{entity.class.name} (id: #{entity.id}) is readonly but does not exist in database. Skipping.") unless entity_exists
      elsif !entity.equal?(self) && shallow_stub?(entity) && top_level_entity?(entity)
        # An id-only reference to an independently-addressable entity: link only.
        # It is emitted as a URI by serialize_entity; never create or rewrite it.
        raise Solis::Error::NotFoundError, "#{entity.class.name} (id: #{entity.id}) is referenced but does not exist" unless entity_exists
      elsif entity_exists
        existing_embedded << entity
      else
        new_entities << entity
      end
    end

    # Existing embedded entities are updated individually (each needs DELETE/INSERT).
    unless existing_embedded.empty?
      embedded_originals = batch_load_originals(existing_embedded)
      existing_embedded.each do |embedded|
        embedded.update(properties_to_hash(embedded), validate_dependencies, false, nil,
                        prefetched_original: embedded_originals[embedded.id])
      end
    end

    # Serialize self and every new embedded entity into one INSERT DATA operation.
    graph = RDF::Graph.new
    graph.name = RDF::URI(self.class.graph_name)
    visited = Set.new
    new_entities.each { |entity| serialize_entity(graph, entity, false, visited, []) }

    validate_graph(graph) if validate_dependencies

    Solis::LOGGER.info SPARQL::Client::Update::InsertData.new(graph, graph: graph.name).to_s if ConfigFile[:debug]

    result = sparql.insert_data(graph, graph: graph.name)
  end

  # Invalidate cached queries for this entity type
  Solis::Query.invalidate_cache_for(self.class.name)

  after_create_proc&.call(self)
  self
rescue StandardError => e
  Solis::LOGGER.error e.message
  raise e
end

#to_graph(resolve_all = true) ⇒ Object



107
108
109
# File 'lib/solis/model.rb', line 107

def to_graph(resolve_all = true)
  as_graph(self, deep: resolve_all)
end

#to_ttl(resolve_all = true) ⇒ Object



97
98
99
100
# File 'lib/solis/model.rb', line 97

def to_ttl(resolve_all = true)
  graph = as_graph(self, deep: resolve_all)
  graph.dump(:ttl)
end

#update(data, validate_dependencies = true, top_level = true, sparql_client = nil, patch: false, prefetched_original: nil) ⇒ Object

Update an entity.

Parameters:

  • data (Hash)

    the attributes to update. Must include ‘id’.

  • validate_dependencies (Boolean) (defaults to: true)

    whether to validate dependencies (default: true)

  • top_level (Boolean) (defaults to: true)

    whether this is a top-level call (default: true)

  • sparql_client (SPARQL::Client, nil) (defaults to: nil)

    optional reusable SPARQL client

  • patch (Boolean) (defaults to: false)

    when true, uses PATCH semantics:

    • Only provided attributes are changed; omitted attributes are untouched

    • Embedded entity arrays are merged (new IDs added, existing IDs updated, missing IDs are kept as-is — not orphaned)

    • No orphan detection or deletion

    When false (default), uses PUT semantics:

    • Embedded entity arrays are fully replaced

    • Entities removed from the array are orphaned and deleted if unreferenced

  • prefetched_original (Solis::Model, nil) (defaults to: nil)

    optional pre-fetched original entity to avoid re-querying



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/solis/model.rb', line 245

def update(data, validate_dependencies = true, top_level = true, sparql_client = nil, patch: false, prefetched_original: nil)
  raise Solis::Error::GeneralError, "I need a SPARQL endpoint" if self.class.sparql_endpoint.nil?

  attributes = data.include?('attributes') ? data['attributes'] : data
  raise "id is mandatory when updating" unless attributes.keys.include?('id')

  id = attributes.delete('id')
  sparql = sparql_client || SPARQL::Client.new(self.class.sparql_endpoint)

  # prefetched_original is used only when it is a complete entity; an id-only stub
  # cannot seed updated_klass (omitted mandatory attributes would be lost).
  original_klass = prefetched_original unless prefetched_original && shallow_stub?(prefetched_original)
  original_klass ||= load_original(id)
  raise Solis::Error::NotFoundError if original_klass.nil?
  updated_klass = original_klass.deep_dup

  # Cache readonly entities list once
  readonly_list = (Solis::Options.instance.get[:embedded_readonly] || []).map(&:to_s)

  # Track entities to potentially delete (only used in PUT mode)
  entities_to_check_for_deletion = {}

  # First pass: collect all embedded entities for batched existence check
  embedded_by_key = {}
  poly_cache = {}
  attributes.each_pair do |key, value|
    unless original_klass.class.[:attributes][key][:node].nil?
      value = [value] unless value.is_a?(Array)
      embedded_by_key[key] = value.map do |sub_value|
        model = self.class.graph.shape_as_model(original_klass.class.[:attributes][key][:datatype].to_s).new(sub_value)
        # Re-type a polymorphic base-class id-only reference to its concrete
        # subclass so existence checks and emitted URIs target the right path.
        concrete = resolve_polymorphic_class(model, sparql, poly_cache)
        model = concrete.new({ id: model.id }) if concrete && concrete != model.class
        model
      end
    end
  end

  all_embedded = embedded_by_key.values.flatten
  existing_ids = self.class.batch_exists?(sparql, all_embedded)

  # Batch-load full stored originals for embedded entities that already exist, so
  # each recursive embedded update receives a complete original (one query per class).
  existing_embedded = all_embedded.select do |e|
    existing_ids.include?(e.graph_id) && !readonly_entity?(e, readonly_list)
  end
  embedded_originals = batch_load_originals(existing_embedded)

  # Second pass: process embedded entities using batched results
  embedded_by_key.each do |key, embedded_list|
    value = attributes[key]
    value = [value] unless value.is_a?(Array)

    # Get original embedded entities for this attribute
    original_embedded = original_klass.instance_variable_get("@#{key}")
    original_embedded = [original_embedded] unless original_embedded.nil? || original_embedded.is_a?(Array)
    original_embedded ||= []

    # Track original IDs
    original_ids = original_embedded.map { |e| solis_model?(e) ? e.id : nil }.compact

    # Build new array of embedded entities
    new_embedded_values = []
    new_ids = []

    embedded_list.each do |embedded|
      new_ids << embedded.id if embedded.id
      entity_exists = existing_ids.include?(embedded.graph_id)

      if readonly_entity?(embedded, readonly_list)
        if entity_exists
          new_embedded_values << embedded
        else
          Solis::LOGGER.warn("#{embedded.class.name} (id: #{embedded.id}) is readonly but does not exist in database. Skipping.")
        end
      else
        if entity_exists
          embedded_data = properties_to_hash(embedded)
          embedded.update(embedded_data, validate_dependencies, false, nil, prefetched_original: embedded_originals[embedded.id])
          new_embedded_values << embedded
        else
          embedded_value = embedded.save(validate_dependencies, false)
          new_embedded_values << embedded_value
        end
      end
    end

    if patch
      # PATCH mode: merge new embedded entities into the original array.
      # Keep original entities that were not mentioned in the update data.
      unmentioned = original_embedded.select do |e|
        solis_model?(e) && !new_ids.include?(e.id)
      end
      merged_values = unmentioned + new_embedded_values
    else
      # PUT mode: replace the entire array; detect orphans for deletion
      merged_values = new_embedded_values

      orphaned_ids = original_ids - new_ids
      unless orphaned_ids.empty?
        orphaned_entities = original_embedded.select { |e| solis_model?(e) && orphaned_ids.include?(e.id) }
        entities_to_check_for_deletion[key] = orphaned_entities
      end
    end

    maxcount = original_klass.class.[:attributes][key][:maxcount]
    embedded_value = maxcount && maxcount == 1 ? merged_values.first : merged_values
    updated_klass.instance_variable_set("@#{key}", embedded_value)
  end

  # Process non-embedded attributes
  attributes.each_pair do |key, value|
    next unless original_klass.class.[:attributes][key][:node].nil?

    updated_klass.instance_variable_set("@#{key}", value)
  end

  before_update_proc&.call(original_klass, updated_klass)

  properties_original_klass = properties_to_hash(original_klass)
  properties_updated_klass = properties_to_hash(updated_klass)

  if Hashdiff.best_diff(properties_original_klass, properties_updated_klass).empty?
    Solis::LOGGER.info("#{original_klass.class.name} unchanged, skipping")
    data = original_klass
  else
    # The delete graph carries the stored original's triples; the insert graph the
    # updated entity's. Embedded children are emitted as URI references in both —
    # they are persisted by their own recursive update/save above.
    delete_graph = as_graph(original_klass, deep: false)
    insert_graph = as_graph(updated_klass, deep: false)
    where_graph = RDF::Graph.new(graph_name: RDF::URI("#{self.class.graph_name}#{tableized_class_name(self)}/#{id}"), data: RDF::Repository.new)

    if id.is_a?(Array)
      id.each do |i|
        where_graph << [RDF::URI("#{self.class.graph_name}#{tableized_class_name(self)}/#{i}"), :p, :o]
      end
    else
      where_graph << [RDF::URI("#{self.class.graph_name}#{tableized_class_name(self)}/#{id}"), :p, :o]
    end

    validate_graph(insert_graph) if validate_dependencies

    delete_insert_query = SPARQL::Client::Update::DeleteInsert.new(delete_graph, insert_graph, where_graph, graph: insert_graph.name).to_s
    delete_insert_query.gsub!('_:p', '?p')

    sparql.query(delete_insert_query)

    # Invalidate cache before verification to avoid stale reads
    Solis::Query.invalidate_cache_for(self.class.name)

    # Verify the update succeeded by re-fetching; fallback to insert if needed
    data = self.query.filter({ filters: { id: [id] } }).find_all.map { |m| m }&.first
    if data.nil?
      sparql.insert_data(insert_graph, graph: insert_graph.name)
      data = updated_klass
    end

    # Delete orphaned entities after successful update (PUT mode only)
    delete_orphaned_entities(entities_to_check_for_deletion, sparql) unless patch
  end

  # Invalidate cached queries for this entity type
  Solis::Query.invalidate_cache_for(self.class.name)

  after_update_proc&.call(updated_klass, data)

  data
rescue StandardError => e
  original_graph = as_graph(original_klass, deep: false) if defined?(original_klass) && original_klass
  Solis::LOGGER.error(e.message)
  Solis::LOGGER.error original_graph.dump(:ttl) if defined?(original_graph) && original_graph
  Solis::LOGGER.error delete_insert_query if defined?(delete_insert_query)
  sparql.insert_data(original_graph, graph: original_graph.name) if defined?(original_graph) && original_graph && defined?(sparql) && sparql

  raise e
end

#valid?Boolean

Returns:

  • (Boolean)


111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/solis/model.rb', line 111

def valid?
  begin
    graph = as_graph(self)
  rescue Solis::Error::InvalidAttributeError => e
    Solis::LOGGER.error(e.message)
  end

  shacl = SHACL.get_shapes(self.class.graph.instance_variable_get(:"@graph"))
  report = shacl.execute(graph)

  report.conform?
rescue StandardError => e
  false
end