4 ms·
It's not obvious how to make SQL with nested queries with own WHERE in Norm. One of design goals of sqlbind was an ability to write complete high level structu
by bvrmn 3y ago
It's not obvious how to make SQL with nested queries with own WHERE in Norm. One of design goals of sqlbind was an ability to write complete high level structure of a big query. And to eliminate `if` statements as much as possible.
Norm:
def get_users(cursor, user_ids, only_girls=False, minimum_age=0):
s = (SELECT('first_name', 'age')
.FROM('people')
.WHERE('user_ids IN :user_ids') # doesn't work in sqlite
.bind(user_ids=user_ids))
if only_girls:
s = s.WHERE(gender='f')
if minimum_age:
s = (s.WHERE('age >= :minimum_age')
.bind(minimum_age=minimum_age))
return cursor.run_query(s)
VS sqlbind:
def get_users(cursor, user_ids, only_girls=False, minimum_age=0):
q = QParams()
filters = [
q.user_ids.IN(user_ids), # renders into FALSE if user_ids are empty and supports SQlite.
q.cond(only_girls, "gender = 'f'"),
q.age >= truthy/minimum_age,
]
sql = f'''\
SELECT first_name, age
FROM people
{WHERE(*filters)}
'''
return cursor.execute(sql, q)