# Path: django_sharding_library/sql.py

# 
# Path: django_sharding_library/exceptions.py
# class DjangoShardingException(Exception):
#     pass


from django.db import connections, DatabaseError, transaction
from django.conf import settings
from django_sharding_library.sql import postgres_shard_id_function_sql
from django.db.models import signals
from django_sharding_library.exceptions import DjangoShardingException

    if is_sharded:
        shard_group = getattr(model, 'django_sharding__shard_group', None)
        if shard_group:
            return settings.DATABASES[database]['SHARD_GROUP'] == shard_group
        raise DjangoShardingException("Unable to determine what database the model is on as the shard group of {} is unknown.".format(model.__class__.__name__))

    return database == "default"


def get_possible_databases_for_model(model):
    return [
        database for database in settings.DATABASES
        if is_model_class_on_database(model=model, database=database)
    ]


def get_database_for_model_instance(instance):
    if instance._state.db:
        return instance._state.db

    model = instance._meta.model
    possible_databases = get_possible_databases_for_model(model=model)
    if len(possible_databases) == 1:
        return possible_databases[0]
    elif len(possible_databases) == 0:
        pass
    else:
        return instance.get_shard()


# Path: django_sharding_library/sql.py

# 
# Path: django_sharding_library/exceptions.py
# class DjangoShardingException(Exception):
#     pass


# Path: django_sharding_library/utils.py
from django.db import connections, DatabaseError, transaction
from django.conf import settings
from django_sharding_library.sql import postgres_shard_id_function_sql
from django.db.models import signals
from django_sharding_library.exceptions import DjangoShardingException


    if is_sharded:
        shard_group = getattr(model, 'django_sharding__shard_group', None)
        if shard_group:
            return settings.DATABASES[database]['SHARD_GROUP'] == shard_group
        raise DjangoShardingException("Unable to determine what database the model is on as the shard group of {} is unknown.".format(model.__class__.__name__))

    return database == "default"


def get_possible_databases_for_model(model):
    return [
        database for database in settings.DATABASES
        if is_model_class_on_database(model=model, database=database)
    ]


def get_database_for_model_instance(instance):
    if instance._state.db:
        return instance._state.db

    model = instance._meta.model
    possible_databases = get_possible_databases_for_model(model=model)
    if len(possible_databases) == 1:
        return possible_databases[0]
    elif len(possible_databases) == 0:
        pass
    else:
        return instance.get_shard()


    raise DjangoShardingException("Unable to deduce datbase for model instance")