Module: TreeNodes::ClassMethods

Defined in:
backend/app/model/mixins/tree_nodes.rb

Instance Method Summary collapse

Instance Method Details

#calculate_has_unpublished_ancestor(obj, check_root_record = true) ⇒ Object



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'backend/app/model/mixins/tree_nodes.rb', line 492

def calculate_has_unpublished_ancestor(obj, check_root_record = true)
  if check_root_record && obj.root_record_id
    root = root_model[obj.root_record_id]
    return true if root.publish == 0 || root.suppressed == 1
  end

  if obj.parent_id
    parent = node_model[obj.parent_id]
    if parent.publish == 0 || parent.suppressed == 1
      return true
    else
      return calculate_has_unpublished_ancestor(parent, false)
    end
  end

  false
end

#calculate_logical_ao_positions(objs) ⇒ Object



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
# File 'backend/app/model/mixins/tree_nodes.rb', line 444

def calculate_logical_ao_positions(objs)
  # For each AO in our set, we want to know how many have the same parent
  # but a smaller position.  Which is another way of saying "how many
  # records are before me in the list?"
  #
  # Previously we would do each as a query:
  #
  #   self.class.dataset.filter(:parent_name => self.parent_name).where { position < relative_position }.count
  #
  # but when you're dealing with trees containing hundreds of thousands of
  # records under a single node, this calculation gets slower (100+ ms) as
  # you get further down the list.
  #
  # We can speed things up for batches of records by ordering our records by
  # their DB position (say that gives us [A, B, C]), and then using the
  # following method:
  #
  #   * A's logical position is count(< A.position) -- as before
  #   * B's position is A.logical_position + count(< B.position && >= A.position)
  #   * C's position is B.logical_position + count(< C.position && >= B.position)
  #
  # Calculating the position for A incurs the same cost as before, but B
  # only needs to count the records between itself and A, and C only needs
  # to count the records between itself and B.  These ranges will be much
  # smaller in many cases.

  result = {}

  objs.group_by(&:parent_name).each do |parent_name, obj_group|
    next if parent_name.nil?

    sorted = obj_group.sort_by(&:position)

    last_physical_position = 0
    last_logical_position = 0

    sorted.each do |ao|
      c = self.dataset.filter(:parent_name => ao.parent_name).where { (position < ao.position) & (position >= last_physical_position) }.count

      last_logical_position = result[ao] = last_logical_position + c
      last_physical_position = ao.position
    end
  end

  result
end

#calculate_object_graph(object_graph, opts = {}) ⇒ Object



511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'backend/app/model/mixins/tree_nodes.rb', line 511

def calculate_object_graph(object_graph, opts = {})
  object_graph.each do |model, id_list|
    next if self != model

    ids = self.any_repo.filter(:parent_id => id_list).
               select(:id).map {|row|
      row[:id]
    }

    object_graph.add_objects(self, ids)
  end

  super
end

#create_from_json(json, extra_values = {}) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'backend/app/model/mixins/tree_nodes.rb', line 337

def create_from_json(json, extra_values = {})
  obj = nil

  retry_db_update do
    DB.open do
      position_values = determine_tree_position_for_new_node(json)
      obj = super(json, extra_values.merge(position_values))
    end
  end

  if obj.nil?
    Log.error("Failed to set the position for #{node_model}: #{last_error}")
    raise last_error
  end

  migration = extra_values[:migration] ? extra_values[:migration].value : false
  if json.position && !migration
    obj.set_position_in_list(json.position)
  end

  ensure_consistent_tree(obj)

  obj
end

#determine_tree_position_for_new_node(json) ⇒ Object



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
# File 'backend/app/model/mixins/tree_nodes.rb', line 363

def determine_tree_position_for_new_node(json)
  result = {}

  root_record_uri = json[root_record_type]['ref']
  result["root_record_id"] = JSONModel.parse_reference(root_record_uri).fetch(:id)

  # 'parent_name' is a bit funny.  We need this column because the combination
  # of (parent, position) needs to be unique, to ensure that two siblings
  # don't occupy the same position when ordering them.  However, parent_id can
  # be NULL, meaning that the current node is at the top level of the tree.
  # This prevents the uniqueness check for working against top-level elements.
  #
  # So, parent_name gets used as a stand in in this case: it always has a
  # value for any node belonging to a hierarchy, and this value gets used in
  # the uniqueness check.
  #
  if json.parent
    parent_id = JSONModel.parse_reference(json.parent['ref']).fetch(:id)

    result["parent_id"] = parent_id
    result["parent_name"] = "#{parent_id}@#{self.node_record_type}"
  else
    result["parent_id"] = nil
    result["parent_name"] = "root@#{root_record_uri}"
  end

  # We'll add this new node to the end of the list.  To do that, find the
  # maximum position assigned so far and go TreeNodes::POSITION_STEP places
  # after that.  If another create_from_json gets in first, we'll have to
  # retry, but that's fine.
  result["position"] = next_position_for_parent(result['root_record_id'], result['parent_id'])

  result
end

#ensure_consistent_tree(obj) ⇒ Object



326
327
328
329
330
331
332
333
334
335
# File 'backend/app/model/mixins/tree_nodes.rb', line 326

def ensure_consistent_tree(obj)
  if obj.parent_id
    parent_root_record_id = node_model.filter(:id => obj.parent_id).get(:root_record_id)
    unless obj.root_record_id == parent_root_record_id
      raise "Consistency check failed: " \
            "#{node_model} #{obj.id} is in #{root_model} #{obj.root_record_id}," \
            " but its parent is in #{root_model} #{parent_root_record_id}."
    end
  end
end

#handle_delete(ids_to_delete) ⇒ Object



527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'backend/app/model/mixins/tree_nodes.rb', line 527

def handle_delete(ids_to_delete)
  ids = self.filter(:id => ids_to_delete )

  # Update the root record's mtime so that any tree-related records are reindexed
  root_model.filter(:id => ids.select(:root_record_id)).update(:system_mtime => Time.now)

  # lets get a group of records that have unique parents or root_records
  parents = ids.select_group(:parent_id, :root_record_id).all
  # we then nil out the parent id so deletes can do its thing
  ids.update(:parent_id => nil)
  # trigger the deletes...
  super
end

#next_position_for_parent(root_record_id, parent_id) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
# File 'backend/app/model/mixins/tree_nodes.rb', line 398

def next_position_for_parent(root_record_id, parent_id)
  max_position = DB.open do |db|
    db[node_model.table_name]
      .filter(:root_record_id => root_record_id, :parent_id => parent_id)
      .select(:position)
      .max(:position)
  end
  max_position ||= 0

  max_position + TreeNodes::POSITION_STEP
end

#node_modelObject



322
323
324
# File 'backend/app/model/mixins/tree_nodes.rb', line 322

def node_model
  Kernel.const_get(node_record_type.camelize)
end

#node_record_typeObject



312
313
314
# File 'backend/app/model/mixins/tree_nodes.rb', line 312

def node_record_type
  @node_record_type
end

#ordered_record_properties(record_ids) ⇒ Object

Default: to be overriden by implementing models



542
543
544
# File 'backend/app/model/mixins/tree_nodes.rb', line 542

def ordered_record_properties(record_ids)
  {}
end

#retry_db_update(&block) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'backend/app/model/mixins/tree_nodes.rb', line 285

def retry_db_update(&block)
  finished = false
  last_error = nil

  TreeNodes::DB_RETRIES.times do
    break if finished

    DB.attempt {
      block.call
      return
    }.and_if_constraint_fails {|err|
      last_error = err
    }
  end

  raise last_error
end

#root_modelObject



317
318
319
# File 'backend/app/model/mixins/tree_nodes.rb', line 317

def root_model
  Kernel.const_get(root_record_type.camelize)
end

#root_record_typeObject



308
309
310
# File 'backend/app/model/mixins/tree_nodes.rb', line 308

def root_record_type
  @root_record_type
end

#sequel_to_jsonmodel(objs, opts = {}) ⇒ Object



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'backend/app/model/mixins/tree_nodes.rb', line 410

def sequel_to_jsonmodel(objs, opts = {})
  jsons = super

  positions = calculate_logical_ao_positions(objs)

  jsons.zip(objs).each do |json, obj|
    if obj.root_record_id
      json[root_record_type] = {'ref' => uri_for(root_record_type, obj.root_record_id)}

      if obj.parent_id
        json.parent = {'ref' => uri_for(node_record_type, obj.parent_id)}
      end

      if obj.parent_name
        # Calculate the logical (gapless) position of this node.  This
        # bridges the gap between the DB's view of position, which only
        # cares that the positions order correctly, with the API's view,
        # which speaks in logical numbering (i.e. the first position is 0,
        # the second position is 1, etc.)

        json.position = positions.fetch(obj)
      end

    end

    if node_model.publishable?
      json['has_unpublished_ancestor'] = calculate_has_unpublished_ancestor(obj)
    end
  end

  jsons
end

#tree_record_types(root, node) ⇒ Object



303
304
305
306
# File 'backend/app/model/mixins/tree_nodes.rb', line 303

def tree_record_types(root, node)
  @root_record_type = root.to_s
  @node_record_type = node.to_s
end