mercredi 24 février 2016

Building the appropriate SQL queries for a web from, when order doesn't matter

I will read the input into the following web form:

enter image description here

via Flask thus:

def query():
    if request.method == "POST":
        job_title_input = request.form['title']
        description_operator = request.form['DescriptionOperator']
        description_input = request.form['description']
        salary_operator = request.form['SalaryOperator']
        salary_input = request.form['salary']
        location_input = request.form['location']

The values received will be used to query this table in SQLite:

CREATE TABLE scrapedjobs
             (id integer primary key autoincrement not null,
             huburl text,
             business_name text,
             location text,
             jobtitle text,
             description text,
             joburl text,
             salary int,
             date_first_scraped date)

It's my first time attempting to handle of the permutations in a web form's submission, and after cascading down through just the first two fields, I can see already that it's is getting convoluted:

    base_query = """SELECT * FROM scrapedjobs"""
    if job_title_input != '':
        base_query = base_query + """ WHERE jobtitle IN ('""" + job_title_input + """')"""
        job_title_input_flag = """ AND"""
    else:
        job_title_input_flag = """"""

    if description_input != '':
        if job_title_input_flag != '':
            base_query = base_query + """ AND description """ + description_operator + " " + "('" + description_input + "')"
            description_input_flag = """ AND"""
        else:
            base_query = base_query + """ WHERE description """ + description_operator + " " + "('" + description_input + "')"
            description_input_flag = """ AND"""
    else:
        description_input_flag = """"""

The further down I go, the more nesting of if/else's will be needed, and it's not sustainable if new fields are added to the form. A major flaw also is that I'm setting things up whereby each field depends on whether the previous fields had a value, and so on. The reality of course is that in a straight query like this without grouping or joins or the like, order is irrelevant, once I can take care of when I need AND (in case a field did have a value) and when I need instead WHERE. Worse still, I will have to parameterize all of this when I pass it to cursor.execute() in sqlite3.

I'm not the first person to every read in values from a multiple form and build appropriate SELECTs - what patterns or more efficient techniques can I take advantage of?

Aucun commentaire:

Enregistrer un commentaire