# First cut at a global Django ORM database router for the RPKI CA code.
#
# https://docs.djangoproject.com/en/1.6/topics/db/multi-db/

class RPKIDBRouter(object):
  """
  Django ORM database router for RPKI code.  rpkid and pubd each get
  their own database, named"rpkidb" and "pubdb", respectively.
  Everything else goes to the "default" database.
  """

  dedicated = ("rpkidb", "pubdb")

  def db_for_read(self, model, **hints):
    if model._meta.app_label in self.dedicated:
      return model._meta.app_label 
    else:
      return "default"

  def db_for_write(self, model, **hints):
    if model._meta.app_label in self.dedicated:
      return model._meta.app_label 
    else:
      return "default"

  def allow_relation(self, obj1, obj2, **hints):
    if obj1._meta.app_label in self.dedicated and obj1._meta.app_label == obj2._meta.app_label:
      return True
    elif obj1._meta.app_label not in self.dedicated and obj2._meta.app_label not in self.dedicated:
      return True
    else:
      return None

  def allow_syncdb(self, db, model):
    if model._meta.app_label in self.dedicated:
      return db == model._meta.app_label
    else:
      return db not in self.dedicated
