Generate Unique Random Table Name for PostgreSQL

  • Share this:

Code introduction


This function generates a random table name that does not exist in the PostgreSQL database. It first connects to the database, then queries all table names in the 'public' schema and stores them in a list. After that, it generates a random string as the table name. If the table name already exists in the list, it continues generating until a unique table name is found.


Technology Stack : psycopg2

Code Type : Database operation

Code Difficulty : Intermediate


                
                    
def generate_random_table_name(postgres_connection):
    import random
    import string

    def random_string(length=10):
        letters = string.ascii_lowercase
        return ''.join(random.choice(letters) for i in range(length))

    with postgres_connection.cursor() as cursor:
        cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
        existing_tables = [table[0] for table in cursor.fetchall()]
        new_table_name = random_string()
        while new_table_name in existing_tables:
            new_table_name = random_string()
        return new_table_name                
              
Tags: