Combining the ideas from:
Levon or Jesse, Faheel and ddrscott
with my formatting suggestion, you could write your query as:
query = ('SELECT'
' action.descr as "action"'
',role.id as role_id'
',role.descr as role'
' FROM'
' public.role_action_def'
',public.role'
',public.record_def'
',public.action'
' WHERE'
' role.id = role_action_def.role_id'
' AND'
' record_def.id = role_action_def.def_id'
' AND'
' action.id = role_action_def.action_id'
' AND'
' role_action_def.account_id = ?' # account_id
' AND'
' record_def.account_id = ?' # account_id
' AND'
' def_id = ?' # def_id
)
vars = (account_id, account_id, def_id) # A tuple of the query variables
cursor.execute(query, vars) # Using Python's sqlite3 module
Or like:
vars = []
query = ('SELECT'
' action.descr as "action"'
',role.id as role_id'
',role.descr as role'
' FROM'
' public.role_action_def'
',public.role'
',public.record_def'
',public.action'
' WHERE'
' role.id = role_action_def.role_id'
' AND'
' record_def.id = role_action_def.def_id'
' AND'
' action.id = role_action_def.action_id'
' AND'
' role_action_def.account_id = '
vars.append(account_id) or '?'
' AND'
' record_def.account_id = '
vars.append(account_id) or '?'
' AND'
' def_id = '
vars.append(def_id) or '?'
)
cursor.execute(query, tuple(vars)) # Using Python's sqlite3 module
Which could be interesting together with 'IN' and 'vars.extend(options) or n_options(len(options))', where:
def n_options(count):
return '(' + ','.join(count*'?') + ')'
Or with the hint from darkfeline, that you might still make mistakes with those leading spaces and separators and also with named placeholders:
SPACE_SEP = ' '
COMMA_SEP = ', '
AND_SEP = ' AND '
query = SPACE_SEP.join((
'SELECT',
COMMA_SEP.join((
'action.descr as "action"',
'role.id as role_id',
'role.descr as role',
)),
'FROM',
COMMA_SEP.join((
'public.role_action_def',
'public.role',
'public.record_def',
'public.action',
)),
'WHERE',
AND_SEP.join((
'role.id = role_action_def.role_id',
'record_def.id = role_action_def.def_id',
'action.id = role_action_def.action_id',
'role_action_def.account_id = :account_id',
'record_def.account_id = :account_id',
'def_id = :def_id',
)),
))
vars = {'account_id':account_id,'def_id':def_id} # A dictionary of the query variables
cursor.execute(query, vars) # Using Python's sqlite3 module
See documentation of Cursor.execute-function.
"This is the [most Pythonic] way!" - ...