Can't execute CREATE CONSTRAINT query from Python

Hi there,

Please kindly advise what I do wrong. I'd like to add constraints from python fuction but it doesn't work as seems Cypher gets literally "$variable" instead of variable meaning.

I get an error text:

> **CypherSyntaxError**: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '$': expected "FOR", "IF", "ON" or an identifier (line 1, column 19 (offset: 18))
"CREATE CONSTRAINT $cons_name IF NOT EXISTS"
                   ^}

And here is my code:

def events_constraint(tx, cons_name, label, prop):
    result = tx.run("""CREATE CONSTRAINT $cons_name IF NOT EXISTS
                        FOR (x:$label)
                        REQUIRE x.$prop IS UNIQUE
                       """ , cons_name = cons_name, label = label, prop = prop
                )          

with driver.session(database="mytest") as session:
    session.execute_write(events_constraint, "TestName", "Label", "property")

So what means Invalid input '$'?? How else I can put my variable to query? Another queries are ok with this but not CREARE CONSTRAINT.

Hi.

The short answer is: you can't. Cypher does not accept a variable in all places. Constraint names is one of them.

The long answer is: you can work around this by using string interpolation/concatenation. But you have to be really careful not to make your application vulnerable to query injection.

Here is some documentation that should help you get started https://neo4j.com/docs/python-manual/current/query-advanced/#_dynamic_values_in_property_keys_relationship_types_and_labels

1 Like

Got it, thank you very much!