'I can't understand why i'm getting no such table

I'm trying to run an AI generated SQL statement to run on my table from an unploaded CSV file and everything reads the table fine except the last section when trying to implement the SQL. can anyone please suggest where i'm going wrong?

PandaSQLException: (sqlite3.OperationalError) no such table: df [SQL: select * from df] (Background on this error at: https://sqlalche.me/e/14/e3q8)

import streamlit as st
from pandasql import sqldf
from QG_Backend import AI_backend


def pysqldf(q):
    '''
    This function allows you to run SQL queries against a pandas dataframe
    :param q: the query string
    :return: A dataframe.
    '''
    return sqldf(q, globals())

def app():

    backend = AI_backend
    df = None
    tables = None  

    st.title('Data')

    # This is creating a variable for the user to upload a CSV, XLS or XLS file.
    uploaded_file = st.sidebar.file_uploader("Upload CSV:",type=['CSV','xlsx','xls'])


    # This is checking to see if the user has uploaded a file. If they have, then the code will try to
    # read the file as a CSV. If it is not a CSV, then it will try to read it as an Excel spreadsheet. If
    # it is not a CSV or an Excel spreadsheet, then it will display an error message.
    if uploaded_file is not None:
        try:
            df = pd.read_csv(uploaded_file)
            df.columns = df.columns.str.replace(' ', '_')
            df = df.applymap(lambda s: s.casefold() if type(s) == str else s) 
        except:
            df = pd.read_excel(uploaded_file)
            df.columns = df.columns.str.replace(' ', '_')
            df = df.applymap(lambda s: s.casefold() if type(s) == str else s) 
    else:
        st.sidebar.info("Upload a file to query")

    st.subheader("File Query")
        
    # Create the columns/layout
    col1, col2 = st.columns(2)

    # This is creating a form for the user to enter their query.
    with col1:
        with st.form(key='query_form'):
            plain_text = st.text_area("Enter your query:")
            submit_text = st.form_submit_button("Execute")

            # This is checking to see if there are any spelling mistakes in the query. If there
            # are, it will correct them.
            fixed = backend.spellCheck(plain_text)

            # Sends the files column headers into a variable
            if df is not None:
                tables = (df.dtypes).to_string()

            # This is creating the prompt for the AI to generate the SQL code.
                prompt="### Example SQL querys:\nSELECT * FROM df WHERE star LIKE '%Tom Hanks%'\n\n----------\n\nCSV table name: df\n" + tables + "\n### A query to " + fixed + ".\nSELECT"
                st.write(fixed)

                # This is generating the SQL code for the user.
                output = backend.generateSQL(prompt) 
                  
                # This is adding the SELECT statement to the output of the AI generated SQL code.
                table_query = "SELECT" + output
                st.write(table_query)
                  

    # This displays the AI generated SQL code as a visual representation to the user
    if df is not None:
        with col2:
            if submit_text:
                st.info("Query Submitted")
                st.subheader("SQL Generated Code:")            
                st.write("SELECT" + output)

        # This is creating a collapsible box for the column headers and their types.
        with st.expander("File Columns:"):      
            dashed_tables = tables.replace(' ','-')
            st.write(dashed_tables)

        # This is creating a collapsible box for the table.
        with st.expander("Table:"):  
            if submit_text:
                output_table = pysqldf(table_query.casefold())
                #output_table = sqldf(table_query.casefold(), globals())
                output_table


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source