-
-
Notifications
You must be signed in to change notification settings - Fork 115
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support mutating row in --convert
without returning it
#371
Comments
Might be a case of modifying this line: sqlite-utils/sqlite_utils/cli.py Line 828 in e0c476b
To: docs = (fn(doc) or doc for doc in docs) |
Also need to update relevant docs for that example. |
Tried this test: result = CliRunner().invoke(
cli.cli,
[
"insert",
db_path,
"rows",
"-",
"--convert",
'row["is_chicken"] = True',
],
input='{"name": "Azi"}',
) And got this error:
The code snippet compilation isn't currently compatible with this. |
Here's the code in question: sqlite-utils/sqlite_utils/utils.py Lines 288 to 299 in b8c1340
|
This seems to work: def _compile_code(code, imports, variable="value"):
locals = {}
globals = {"r": recipes, "recipes": recipes}
# If user defined a convert() function, return that
try:
exec(code, globals, locals)
return locals["convert"]
except (AttributeError, SyntaxError, NameError, KeyError, TypeError):
pass
# Try compiling their code as a function instead
body_variants = [code]
# If single line and no 'return', try adding the return
if "\n" not in code and not code.strip().startswith("return "):
body_variants.insert(0, "return {}".format(code))
for variant in body_variants:
new_code = ["def fn({}):".format(variable)]
for line in variant.split("\n"):
new_code.append(" {}".format(line))
try:
code_o = compile("\n".join(new_code), "<string>", "exec")
break
except SyntaxError:
# Try another variant, e.g. for 'return row["column"] = 1'
continue
for import_ in imports:
globals[import_.split(".")[0]] = __import__(import_)
exec(code_o, globals, locals)
return locals["fn"] |
The previous code for highlighting errors in syntax (which was already a bit confused thanks to the added |
Currently you have to do this:
Would be neat if this worked too:
The text was updated successfully, but these errors were encountered: