Skip to content

Support mutating row in --convert without returning it #371

Closed

Description

@simonw

Currently you have to do this:

$ sqlite-utils insert dogs.db dogs dogs.json --convert '
row["is_good"] = 1
return row'

Would be neat if this worked too:

$ sqlite-utils insert dogs.db dogs dogs.json \
  --convert 'row["is_good"] = 1'

Activity

  1. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    Might be a case of modifying this line:

    docs = (fn(doc) for doc in docs)

    To:

    docs = (fn(doc) or doc for doc in docs)
  2. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    Also need to update relevant docs for that example.

  3. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    Tried this test:

        result = CliRunner().invoke(
            cli.cli,
            [
                "insert",
                db_path,
                "rows",
                "-",
                "--convert",
                'row["is_chicken"] = True',
            ],
            input='{"name": "Azi"}',
        )

    And got this error:

    E + where 1 = <Result SyntaxError('invalid syntax', ('<string>', 2, 30, ' return row["is_chicken"] = True\n'))>.exit_code

    The code snippet compilation isn't currently compatible with this.

  4. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    Here's the code in question:

    # 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
    # If single line and no 'return', add the return
    if "\n" not in code and not code.strip().startswith("return "):
    code = "return {}".format(code)

  5. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    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"]
  6. simonw commented on Jan 9, 2022

    @simonw
    OwnerAuthor

    The previous code for highlighting errors in syntax (which was already a bit confused thanks to the added return, see #355 (comment) - isn't compatible with this approach at all. I'm going to ditch it and just show a generic Error: Could not compile code message.

  7. added a commit that references this issue on Jan 9, 2022
  8. added this to the 3.21 milestone on Jan 10, 2022
  9. added 2 commits that reference this issue on Jan 11, 2022
  10. added a commit that references this issue on Mar 12, 2024
    22c8d10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions