New way of deriving named parameters using explain, refs #1421

This commit is contained in:
Simon Willison 2021-08-08 20:21:13 -07:00
commit fc4846850f
4 changed files with 31 additions and 2 deletions

View file

@ -1076,3 +1076,15 @@ class PrefixedUrlString(str):
class StartupError(Exception):
pass
_re_named_parameter = re.compile(":([a-zA-Z0-9_]+)")
async def derive_named_parameters(db, sql):
explain = 'explain {}'.format(sql.strip().rstrip(";"))
possible_params = _re_named_parameter.findall(sql)
try:
results = await db.execute(explain, {p: None for p in possible_params})
return [row["p4"].lstrip(":") for row in results if row["opcode"] == "Variable"]
except sqlite3.DatabaseError:
return []