# Path: django_sharding_library/utils.py
# def create_postgres_global_sequence(sequence_name, db_alias, reset_sequence=False):
#     cursor = connections[db_alias].cursor()
#     sid = transaction.savepoint(db_alias)
#     create_sequence_if_not_exists_sql = """DO
# $$
# BEGIN
#         CREATE SEQUENCE %s;
# EXCEPTION WHEN duplicate_table THEN
#         -- do nothing, it's already there
# END
# $$ LANGUAGE plpgsql;"""
#     try:
#         cursor.execute(create_sequence_if_not_exists_sql % sequence_name)
#     except DatabaseError:
#         transaction.savepoint_rollback(sid, using=db_alias)
#     else:
#         transaction.savepoint_commit(sid, using=db_alias)
#     if reset_sequence:
#         cursor.execute("SELECT setval('%s', 1, false)" % (sequence_name,))
#     cursor.close()
# 
# def create_postgres_shard_id_function(sequence_name, db_alias, shard_id):
#     cursor = connections[db_alias].cursor()
#     cursor.execute(postgres_shard_id_function_sql % {'shard_epoch': settings.SHARD_EPOCH,
#                                                      'shard_id': shard_id,
#                                                      'sequence_name': sequence_name})
#     cursor.close()
# 
# def verify_postres_id_field_setup_correctly(sequence_name, db_alias, function_name):
#     cursor = connections[db_alias].cursor()
#     cursor.execute(
#         "SELECT count(*) FROM pg_class c WHERE c.relkind = '%s' and c.relname = '%s';" % ('S', sequence_name)
#     )
# 
#     if cursor.fetchone()[0] == 0:
#         cursor.close()
#         return False
# 
#     cursor.execute(
#         "SELECT count(*) from pg_proc p where p.proname = '%s';" % (function_name,)
#     )
# 
#     if cursor.fetchone()[0] == 0:
#         cursor.close()
#         return False
# 
#     cursor.close()
#     return True


from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django_sharding_library.utils import create_postgres_global_sequence, create_postgres_shard_id_function, verify_postres_id_field_setup_correctly
            action='store',
            dest='sequence_name',
            default='global_id_sequence',
            help='The name of the sequence to create and verify exists.',
        )
        parser.add_argument(
            '--reset-sequence', action='store_true', dest='reset_sequence', default=False,
            help="Reset the sequence if it exists.",
        )
        parser.add_argument(
            '--dry-run', action='store_true', dest='dry_run', default=False,
            help="Check they exist but make no changes to the database.",
        )

    def get_all_but_replica_dbs(self):
        return sorted(list(filter(
            lambda db: not settings.DATABASES[db].get('PRIMARY', None),
            settings.DATABASES.keys()
        )))

    def handle(self, *args, **options):
        if not options['database'] or options['database'] == 'all':
            databases = self.get_all_but_replica_dbs()
        elif options['database'] not in self.get_all_but_replica_dbs():
            raise CommandError('You must migrate an existing primary DB.')
        else:
            databases = [options['database']]

        has_errors = False


# Path: django_sharding_library/utils.py
# def create_postgres_global_sequence(sequence_name, db_alias, reset_sequence=False):
#     cursor = connections[db_alias].cursor()
#     sid = transaction.savepoint(db_alias)
#     create_sequence_if_not_exists_sql = """DO
# $$
# BEGIN
#         CREATE SEQUENCE %s;
# EXCEPTION WHEN duplicate_table THEN
#         -- do nothing, it's already there
# END
# $$ LANGUAGE plpgsql;"""
#     try:
#         cursor.execute(create_sequence_if_not_exists_sql % sequence_name)
#     except DatabaseError:
#         transaction.savepoint_rollback(sid, using=db_alias)
#     else:
#         transaction.savepoint_commit(sid, using=db_alias)
#     if reset_sequence:
#         cursor.execute("SELECT setval('%s', 1, false)" % (sequence_name,))
#     cursor.close()
# 
# def create_postgres_shard_id_function(sequence_name, db_alias, shard_id):
#     cursor = connections[db_alias].cursor()
#     cursor.execute(postgres_shard_id_function_sql % {'shard_epoch': settings.SHARD_EPOCH,
#                                                      'shard_id': shard_id,
#                                                      'sequence_name': sequence_name})
#     cursor.close()
# 
# def verify_postres_id_field_setup_correctly(sequence_name, db_alias, function_name):
#     cursor = connections[db_alias].cursor()
#     cursor.execute(
#         "SELECT count(*) FROM pg_class c WHERE c.relkind = '%s' and c.relname = '%s';" % ('S', sequence_name)
#     )
# 
#     if cursor.fetchone()[0] == 0:
#         cursor.close()
#         return False
# 
#     cursor.execute(
#         "SELECT count(*) from pg_proc p where p.proname = '%s';" % (function_name,)
#     )
# 
#     if cursor.fetchone()[0] == 0:
#         cursor.close()
#         return False
# 
#     cursor.close()
#     return True


# Path: django_sharding_library/management/commands/create_postgres_sequences.py
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django_sharding_library.utils import create_postgres_global_sequence, create_postgres_shard_id_function, verify_postres_id_field_setup_correctly

            action='store',
            dest='sequence_name',
            default='global_id_sequence',
            help='The name of the sequence to create and verify exists.',
        )
        parser.add_argument(
            '--reset-sequence', action='store_true', dest='reset_sequence', default=False,
            help="Reset the sequence if it exists.",
        )
        parser.add_argument(
            '--dry-run', action='store_true', dest='dry_run', default=False,
            help="Check they exist but make no changes to the database.",
        )

    def get_all_but_replica_dbs(self):
        return sorted(list(filter(
            lambda db: not settings.DATABASES[db].get('PRIMARY', None),
            settings.DATABASES.keys()
        )))

    def handle(self, *args, **options):
        if not options['database'] or options['database'] == 'all':
            databases = self.get_all_but_replica_dbs()
        elif options['database'] not in self.get_all_but_replica_dbs():
            raise CommandError('You must migrate an existing primary DB.')
        else:
            databases = [options['database']]

        has_errors = False


        for database in databases: