# Import all libraries that are needed import gradio as gr import re import os import psycopg2 import time import uuid from collections import defaultdict sql_host = os.getenv('SQL_HOST') db = os.getenv('DB') user = os.getenv('USER') password = os.getenv('PASSWORD') quiz1 = os.getenv('QUIZ1') quiz2 = os.getenv('QUIZ2') quiz3 = os.getenv('QUIZ3') quiz4 = os.getenv('QUIZ4') quiz5 = os.getenv('QUIZ5') quiz6 = os.getenv('QUIZ6') ro_user = os.getenv('RO_USER') ro_password = os.getenv('RO_PASSWORD') email_secret = os.getenv('EMAIL') # Session management sessions = defaultdict(lambda: {"timer": 60 * 45, "stop_quiz": True}) # Function to generate a unique user id for that session def generate_session_id(): return str(uuid.uuid4()) # Function to format time in MM:SS format def format_time(seconds): minutes, seconds = divmod(seconds, 60) return f"{minutes:02}:{seconds:02}" # Function to start the countdown def start_countdown(session_id): while sessions[session_id]["timer"] >= 0: if sessions[session_id]["stop_quiz"]: return None yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(), gr.update() time.sleep(1) sessions[session_id]["timer"] -= 1 yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(visible=False), gr.update(visible=True) # Function to stop the countdown def stop_countdown(session_id): sessions[session_id]["stop_quiz"] = True # Validation function def validate_inputs(session_id, first_name, last_name, email): # Check if first and last name are present if not first_name or not last_name: return gr.update(visible=True, value="First name and Last Name are required."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) # Check if email address is valid if not re.match(rf"^[^@]+@({email_secret})$", email, re.IGNORECASE): return gr.update(visible=True, value="Please enter a valid email address."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) # If inputs are valid, allow quiz to start and take user to next page sessions[session_id]["stop_quiz"] = False return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) # Function to reveal the final page, either when timer runs out or "End Quiz" is clicked def final_page_reveal(): return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) # Function to initialize the database def initialize_database(): # Details for connecting to Rockborne database conn = psycopg2.connect( host=sql_host, database=db, user=user, password=password ) cursor = conn.cursor() # Create the Quiz table cursor.execute(''' CREATE TABLE IF NOT EXISTS Quiz ( quiz_id SERIAL PRIMARY KEY, first_name TEXT, last_name TEXT, email TEXT ); ''') # Create the QuizAnswers table cursor.execute(''' CREATE TABLE IF NOT EXISTS QuizAnswers ( quiz_id INTEGER, question_number INTEGER, answer TEXT, FOREIGN KEY (quiz_id) REFERENCES Quiz (quiz_id), PRIMARY KEY (quiz_id, question_number) ); ''') # Create the employee table cursor.execute(''' CREATE TABLE IF NOT EXISTS employee ( id INT PRIMARY KEY, name VARCHAR(75), department VARCHAR(2), manager_id INT ); ''') # Insert data into the employee table cursor.executemany(''' INSERT INTO employee (id, name, department, manager_id) VALUES (%s, %s, %s, %s) ON CONFLICT (id) DO NOTHING; ''', [ (101, 'John', 'A', None), (102, 'Dan', 'A', 101), (103, 'James', 'A', 101), (104, 'Amy', 'A', 101), (105, 'Anne', 'A', 101), (106, 'Ron', 'B', 101) ]) # Create the courses table cursor.execute(''' CREATE TABLE IF NOT EXISTS courses ( student VARCHAR(1) PRIMARY KEY, class VARCHAR(50) ); ''') # Insert data into the courses table cursor.executemany(''' INSERT INTO courses (student, class) VALUES (%s, %s) ON CONFLICT (student) DO NOTHING; ''', [ ('A', 'Maths'), ('B', 'English'), ('C', 'Maths'), ('D', 'Biology'), ('E', 'Maths'), ('F', 'Computer'), ('G', 'Maths'), ('H', 'Maths'), ('I', 'Maths') ]) # Create the salesperson table cursor.execute(''' CREATE TABLE IF NOT EXISTS salesperson ( sales_id INT PRIMARY KEY, name VARCHAR(50), salary DECIMAL(10, 2), commission_rate DECIMAL(5, 2), hire_date DATE ); ''') # Insert data into the salesperson table cursor.executemany(''' INSERT INTO salesperson (sales_id, name, salary, commission_rate, hire_date) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (sales_id) DO NOTHING; ''', [ (1, 'John', 100000, 6, '2006-04-01'), (2, 'Amy', 120000, 5, '2010-05-01'), (3, 'Mark', 65000, 12, '2008-12-25'), (4, 'Pam', 25000, 25, '2005-01-01'), (5, 'Alex', 50000, 10, '2007-02-03') ]) # Create the company table cursor.execute(''' CREATE TABLE IF NOT EXISTS company ( com_id INT PRIMARY KEY, name VARCHAR(50), city VARCHAR(50) ); ''') # Insert data into the company table cursor.executemany(''' INSERT INTO company (com_id, name, city) VALUES (%s, %s, %s) ON CONFLICT (com_id) DO NOTHING; ''', [ (1, 'RED', 'Boston'), (2, 'ORANGE', 'New York'), (3, 'YELLOW', 'Boston'), (4, 'GREEN', 'Austin') ]) # Create the orders table cursor.execute(''' CREATE TABLE IF NOT EXISTS orders ( order_id INT PRIMARY KEY, order_date DATE, com_id INT, sales_id INT, amount DECIMAL(10, 2), FOREIGN KEY (sales_id) REFERENCES salesperson(sales_id), FOREIGN KEY (com_id) REFERENCES company(com_id) ); ''') # Insert data into the orders table cursor.executemany(''' INSERT INTO orders (order_id, order_date, com_id, sales_id, amount) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (order_id) DO NOTHING; ''', [ (1, '2014-01-01', 3, 4, 100000), (2, '2014-02-01', 4, 5, 5000), (3, '2014-03-01', 1, 1, 50000), (4, '2014-04-01', 1, 4, 25000) ]) # Create the tree table cursor.execute(''' CREATE TABLE IF NOT EXISTS tree ( id INT PRIMARY KEY, p_id INT ); ''') # Insert data into the tree table cursor.executemany(''' INSERT INTO tree (id, p_id) VALUES (%s, %s) ON CONFLICT (id) DO NOTHING; ''', [ (1, None), (2, 1), (3, 1), (4, 2), (5, 2) ]) # Create the movies table cursor.execute(''' CREATE TABLE IF NOT EXISTS movies ( id INT PRIMARY KEY, movie VARCHAR(50), description VARCHAR(50), rating DECIMAL(3, 1) ); ''') # Insert data into the movies table cursor.executemany(''' INSERT INTO movies (id, movie, description, rating) VALUES (%s, %s, %s, %s) ON CONFLICT (id) DO NOTHING; ''', [ (1, 'War', 'Great 3D', 8.9), (2, 'Science', 'Fiction', 8.5), (3, 'Irish', 'Boring', 6.2), (4, 'Ice song', 'Fantasy', 8.6), (5, 'House card', 'Interesting', 9.1) ]) # Create the product table cursor.execute(''' CREATE TABLE IF NOT EXISTS product ( product_key INT PRIMARY KEY ); ''') # Insert data into the product table cursor.executemany(''' INSERT INTO product (product_key) VALUES (%s) ON CONFLICT (product_key) DO NOTHING; ''', [ (5,), (6,) ]) # Create the customer table cursor.execute(''' CREATE TABLE IF NOT EXISTS customer ( customer_id INT , product_key INT, PRIMARY KEY (customer_id, product_key), FOREIGN KEY (product_key) REFERENCES product(product_key) ); ''') # Insert data into the customer table cursor.executemany(''' INSERT INTO customer (customer_id, product_key) VALUES (%s, %s) ON CONFLICT (customer_id, product_key) DO NOTHING; ''', [ (1, 5), (2, 6), (3, 5), (3, 6), (1, 6) ]) # Create the locations table cursor.execute(''' CREATE TABLE IF NOT EXISTS locations ( postal_code VARCHAR(50) PRIMARY KEY, city_name VARCHAR(50), location VARCHAR(50) ); ''') # Insert data into the locations table cursor.executemany(''' INSERT INTO locations (postal_code, city_name, location) VALUES (%s, %s, %s) ON CONFLICT (postal_code) DO NOTHING; ''', [ ('900', 'Los Angeles', 'California'), ('921', 'San Diego', 'CA'), ('691', 'Bakersfield', 'California') ]) # Create the departments table cursor.execute(''' CREATE TABLE IF NOT EXISTS departments ( department_id INT PRIMARY KEY, department_name VARCHAR(50), location VARCHAR(50) ); ''') # Insert data into the departments table cursor.executemany(''' INSERT INTO departments (department_id, department_name, location) VALUES (%s, %s, %s) ON CONFLICT (department_id) DO NOTHING; ''', [ (101, 'HR', 'California'), (102, 'IT', 'NY'), (103, 'Finance', 'CA') ]) # Create the employees table cursor.execute(''' CREATE TABLE IF NOT EXISTS employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(50), department_id INT, postal_code INT, FOREIGN KEY(department_id) REFERENCES departments(department_id) ); ''') # Insert data into the employees table cursor.executemany(''' INSERT INTO employees (employee_id, employee_name, department_id, postal_code) VALUES (%s, %s, %s, %s) ON CONFLICT (employee_id) DO NOTHING; ''', [ (1, 'Kent', '101', 900), (2, 'Taylor', '102', 691), (3, 'Rachel', '103', 690), (4, 'Sam', '101', 921) ]) conn.commit() cursor.close() conn.close() # Call the function to initialise the database initialize_database() # Function to create a new quiz entry and return the quiz_id def start_quiz(session_id, first_name, last_name, email): # Connect to the database conn = psycopg2.connect( host=sql_host, database=db, user=user, password=password ) cursor = conn.cursor() # If quiz is allowed to start (i.e. details are valid), submit the user details into the database with incrementally increased "quiz_id" if not sessions[session_id]["stop_quiz"]: cursor.execute(''' INSERT INTO Quiz (first_name, last_name, email) VALUES (%s, %s, %s) RETURNING quiz_id ''', (first_name, last_name, email)) quiz_id = cursor.fetchone()[0] # If quiz is not allowed to start (i.e. details not valid) don't update anything else: quiz_id = None conn.commit() cursor.close() conn.close() return quiz_id # Function to save a user's answerto a given question to the database def save_answer(quiz_id, question_number, answer): # Connect to the database conn = psycopg2.connect( host=sql_host, database=db, user=user, password=password ) cursor = conn.cursor() # Insert their answer into the database, updating if one already existed for that question cursor.execute(''' INSERT INTO QuizAnswers (quiz_id, question_number, answer) VALUES (%s, %s, %s) ON CONFLICT (quiz_id, question_number) DO UPDATE SET answer = EXCLUDED.answer ''', (quiz_id, question_number, answer)) conn.commit() cursor.close() conn.close() # Return success message return "Answer saved successfully!" # Function to return question details def get_questions(question): questions = { "Question 1": quiz1, "Question 2": quiz2, "Question 3": quiz3, "Question 4": quiz4, "Question 5": quiz5, "Question 6": quiz6 } return questions.get(question, "No details available") # Define the function to execute SQL queries def execute_sql(query): try: # Connect to the database conn = psycopg2.connect( host=sql_host, database=db, user=ro_user, password=ro_password ) cursor = conn.cursor() # Ensure the query only accesses the appropriate table if "quiz" in query.lower(): return f"### SQL Output\n\nYou are not allowed to access the table 'quiz'." if "quizanswers" in query.lower(): return f"### SQL Output\n\nYou are not allowed to access the table 'quizanswers'." if "insert" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'insert'." if "delete" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'delete'." if "update" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'update'." if "merge" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'merge'." if "truncate" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'truncate'." if "create" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'create'." if "alter" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'alter'." if "drop" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'drop'." if "rename" in query.lower(): return f"### SQL Output\n\nYou are not allowed use 'rename'." cursor.execute(query) conn.commit() # If the query involves a select statement, display their answer in a formatted table if "select" in query.strip().lower(): results = cursor.fetchall() column_names = [description[0] for description in cursor.description] # Create the header row with column names header = "| " + " | ".join(column_names) + " |" # Create the separator row with dashes separator = "| " + " | ".join(['---' for _ in column_names]) + " |" # Create the data rows rows = "\n".join(["| " + " | ".join(map(str, row)) + " |" for row in results]) # Combine header, separator, and rows into the final table string results_str = f"{header}\n{separator}\n{rows}" # Return the formatted table to be rendered in gr.Markdown return f"### SQL Output\n\n{results_str}" # If not a select statement, show that query was executed successfully else: return "Query executed successfully" # If there is an error, return error message except Exception as e: return str(e) # Close connection to the database finally: if conn: cursor.close() conn.close() #NEWW def show_confirmation(): return (gr.update(visible=True), # Make confirmation message visible gr.update(visible=True), # Make the "Yes, End Quiz" button visible gr.update(visible=True), # Make the "No, I want to continue" button visible gr.update(visible=False)) # Hide the original "End Quiz" button def hide_confirmation(): return (gr.update(visible=False), # Hide confirmation message gr.update(visible=False), # Hide the "Yes, End Quiz" button gr.update(visible=False), # Hide the "No, I want to continue" button gr.update(visible=True)) # Show the original "End Quiz" button again # Define the Gradio app layout with gr.Blocks() as app: # This defines the landing page, with instructions and inputs for user details with gr.Column(visible=True) as intro: # Generate a unique session_id for the user session_id = gr.State(generate_session_id) # HTML code for welcome page and instructions gr.Markdown("
This test is designed to evaluate your SQL proficiency by measuring your ability to write efficient and accurate SQL select queries. It will help you identify your strengths and areas for improvement.
This test consists of 6 SQL questions with varied levels of difficulty.
You will have 45 minutes to complete the assessment.
To start this test please input your first name, last name and your email address, then click on ‘Begin Test’.
After starting the test, click ‘Test query’ to test your SQL queries and view its output.
For each question, you must press 'Save Answer' for the answer to be submitted. These can be resubmitted, but only the most recent version will be marked.
When the timer reaches 0, the test will immediately end and no further answers can be submitted.
Clicking "End Quiz" before the time finishes will automatically end the quiz, it does not submit any unsaved answers.
Do NOT refresh the page, this will start a new user entry.
""") # Textboxes for users to input details first_name = gr.Textbox(label="First Name") last_name = gr.Textbox(label="Last Name") email = gr.Textbox(label="Email") error_message = gr.Markdown("", visible=False) submit_button = gr.Button("Start Test") # This defines the exit page, telling the user to quit the application with gr.Column(visible=False) as exit_page: gr.HTML( """Thank you for completing the quiz.
Please do not try to reattempt this assessment, only your first submission will be marked.
You may now close this page within your browser.