Skip to content
This repository was archived by the owner on Mar 10, 2025. It is now read-only.

Commit 64131d2

Browse files
committed
Use $param instead of the old parameter syntax {param}
Use $param instead of the old parameter syntax {param} which is no longer supported #449
1 parent 67b36a6 commit 64131d2

File tree

13 files changed

+45
-48
lines changed

13 files changed

+45
-48
lines changed

grails-datastore-gorm-neo4j/src/main/groovy/grails/neo4j/Neo4jEntity.groovy

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ trait Neo4jEntity<D> implements GormEntity<D>, DynamicAttributes {
148148
GormEnhancer.findDatastore(getClass()).withSession { Neo4jSession session ->
149149
Map<String, Object> arguments
150150
if (session.getDatastore().multiTenancyMode == MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR) {
151-
if (!queryString.contains("{tenantId}")) {
151+
if (!queryString.contains("\$tenantId")) {
152152
throw new TenantNotFoundException("Query does not specify a tenant id, but multi tenant mode is DISCRIMINATOR!")
153153
} else {
154154
arguments = new LinkedHashMap<String, Object>()
@@ -265,7 +265,7 @@ trait Neo4jEntity<D> implements GormEntity<D>, DynamicAttributes {
265265

266266
private void includeTenantIdIfNecessary(Neo4jSession session, String queryString, Map<String, Object> paramsMap) {
267267
if ((this instanceof MultiTenant) && session.getDatastore().multiTenancyMode == MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR) {
268-
if (!queryString.contains("{tenantId}")) {
268+
if (!queryString.contains("\$tenantId")) {
269269
throw new TenantNotFoundException("Query does not specify a tenant id, but multi tenant mode is DISCRIMINATOR!")
270270
} else {
271271
paramsMap.put(GormProperties.TENANT_IDENTITY, Tenants.currentId(Neo4jDatastore))

grails-datastore-gorm-neo4j/src/main/groovy/org/grails/datastore/gorm/neo4j/GraphPersistentEntity.groovy

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class GraphPersistentEntity extends AbstractPersistentEntity<NodeConfig> {
3636

3737
public static final String LABEL_SEPARATOR = ':'
3838
protected static final String MATCH = "MATCH %s"
39-
protected static final String MATCH_ID = "$MATCH WHERE %s = {id}"
39+
protected static final String MATCH_ID = "$MATCH WHERE %s = \$id"
4040
protected final NodeConfig mappedForm
4141
protected final Collection<String> staticLabels = []
4242
protected Collection<Object> labelObjects
@@ -183,7 +183,7 @@ class GraphPersistentEntity extends AbstractPersistentEntity<NodeConfig> {
183183
*/
184184
String getBatchCreateStatement() {
185185
if(this.batchCreateStatement == null) {
186-
this.batchCreateStatement = formatBatchCreate("{${batchId}}")
186+
this.batchCreateStatement = formatBatchCreate("\$${batchId}")
187187
}
188188
return batchCreateStatement
189189
}
@@ -215,10 +215,10 @@ class GraphPersistentEntity extends AbstractPersistentEntity<NodeConfig> {
215215
/**
216216
* Formats a dynamic association query
217217
* @param variable The variable to use
218-
* @return The query which accepts an {id} argument
218+
* @return The query which accepts an $id argument
219219
*/
220220
String formatDynamicAssociationQuery(String variable = CypherBuilder.NODE_VAR) {
221-
"""${formatMatch(variable)}-[r]-(o) WHERE ${formatId(variable)} = {${GormProperties.IDENTITY}} RETURN type(r) as relType, startNode(r) = $variable as out, r.sourceType as sourceType, r.targetType as targetType, {ids: collect(${formatId("o")}), labels: collect(labels(o))} as values"""
221+
"""${formatMatch(variable)}-[r]-(o) WHERE ${formatId(variable)} = \$${GormProperties.IDENTITY} RETURN type(r) as relType, startNode(r) = $variable as out, r.sourceType as sourceType, r.targetType as targetType, {ids: collect(${formatId("o")}), labels: collect(labels(o))} as values"""
222222
}
223223

224224
/**
@@ -300,9 +300,9 @@ class GraphPersistentEntity extends AbstractPersistentEntity<NodeConfig> {
300300
StringBuilder builder = new StringBuilder( formatMatchId(variable) )
301301
Class clazz = Long
302302
if(isVersioned() && hasProperty(GormProperties.VERSION, clazz)) {
303-
builder.append(" AND ${variable}.version={version}")
303+
builder.append(" AND ${variable}.version=\$version")
304304
}
305-
builder.append(" SET ").append(variable).append(" +={props}")
305+
builder.append(" SET ").append(variable).append(" +=\$props")
306306
Set keysToRemove = []
307307
for(key in props.keySet()) {
308308
Object v = props.get(key)

grails-datastore-gorm-neo4j/src/main/groovy/org/grails/datastore/gorm/neo4j/Neo4jSession.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,7 @@ public void buildEntityCreateOperation(StringBuilder createCypher, String index,
665665
Map<String, List<Object>> dynamicRelProps = amendMapWithUndeclaredProperties(graphEntity, simpleProps, obj, getMappingContext());
666666
final String labels = graphEntity.getLabelsWithInheritance(obj);
667667

668-
String cypher = String.format("(n" + index + "%s {props" + index + "})", labels);
668+
String cypher = String.format("(n" + index + "%s $props" + index + ")", labels);
669669
createCypher.append(cypher);
670670
params.put("props" + index, simpleProps);
671671

@@ -820,12 +820,9 @@ public static boolean isCollectionWithPersistentEntities(Object o, MappingContex
820820
if (!(o instanceof Collection)) {
821821
return false;
822822
} else {
823-
Collection c = (Collection) o;
824-
for (Object obj : c) {
825-
if (mappingContext.isPersistentEntity(obj)) return true;
826-
}
823+
@SuppressWarnings("unchecked") Collection<Object> c = (Collection<Object>) o;
824+
return c.stream().anyMatch(mappingContext::isPersistentEntity);
827825
}
828-
return false;
829826
}
830827

831828

grails-datastore-gorm-neo4j/src/main/groovy/org/grails/datastore/gorm/neo4j/api/Neo4jGormStaticApi.groovy

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ class Neo4jGormStaticApi<D> extends GormStaticApi<D> {
258258
Relationship<F, T> relationship = null
259259
if(from != null && to != null) {
260260
String query = """MATCH (from)-[r]-(to)
261-
WHERE ${fromEntity.formatId(RelationshipPersistentEntity.FROM)} = {start} AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = {end}
261+
WHERE ${fromEntity.formatId(RelationshipPersistentEntity.FROM)} = \$start AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = \$end
262262
RETURN r
263263
LIMIT 1"""
264264
List<org.neo4j.driver.types.Relationship> results = executeQuery(query, [start:from.ident(), end:to.ident()])
@@ -291,7 +291,7 @@ LIMIT 1"""
291291
String skip = params.offset ? " SKIP ${Integer.valueOf(params.offset.toString())}" : ''
292292
String limit = params.max ? " LIMIT ${Integer.valueOf(params.max.toString())}" : ''
293293
String query = """MATCH (from)-[r]-(to)
294-
WHERE ${fromEntity.formatId(RelationshipPersistentEntity.FROM)} = {start} AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = {end}
294+
WHERE ${fromEntity.formatId(RelationshipPersistentEntity.FROM)} = \$start AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = \$end
295295
RETURN DISTINCT(r)$skip$limit"""
296296
List<org.neo4j.driver.types.Relationship> results = (List<org.neo4j.driver.types.Relationship>) executeQuery(query, [start:from.ident(), end:to.ident()])
297297

@@ -370,7 +370,7 @@ RETURN DISTINCT(r), from, to$skip$limit"""
370370
toEntity.formatNode(RelationshipPersistentEntity.TO)
371371
}, p = shortestPath((from)-[*..$maxDistance]-(to)) WHERE ${
372372
fromEntity.formatId(RelationshipPersistentEntity.FROM)
373-
} = {start} AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = {end} RETURN p"""
373+
} = \$start AND ${toEntity.formatId(RelationshipPersistentEntity.TO)} = \$end RETURN p"""
374374
Result result = cypherStatic(query, [start: fromId, end: toId])
375375
if(result.hasNext()) {
376376
Record record = result.next()
@@ -452,7 +452,7 @@ RETURN DISTINCT(r), from, to$skip$limit"""
452452
queryString = query.toString()
453453
}
454454
if (persistentEntity.isMultiTenant() && session.getDatastore().multiTenancyMode == MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR) {
455-
if (!queryString.contains("{tenantId}")) {
455+
if (!queryString.contains("\$tenantId")) {
456456
throw new TenantNotFoundException("Query does not specify a tenant id, but multi tenant mode is DISCRIMINATOR!")
457457
} else {
458458
Map<String,Object> paramsMap = new LinkedHashMap<>()
@@ -511,7 +511,7 @@ RETURN DISTINCT(r), from, to$skip$limit"""
511511

512512
private void includeTenantIdIfNecessary(Neo4jSession session, String queryString, Map<String, Object> paramsMap) {
513513
if (persistentEntity.isMultiTenant() && session.getDatastore().multiTenancyMode == MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR) {
514-
if (!queryString.contains("{tenantId}")) {
514+
if (!queryString.contains("\$tenantId")) {
515515
throw new TenantNotFoundException("Query does not specify a tenant id, but multi tenant mode is DISCRIMINATOR!")
516516
} else {
517517
paramsMap.put(GormProperties.TENANT_IDENTITY, Tenants.currentId(Neo4jDatastore))

grails-datastore-gorm-neo4j/src/main/groovy/org/grails/datastore/gorm/neo4j/engine/Neo4jAssociationQueryExecutor.groovy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ class Neo4jAssociationQueryExecutor implements AssociationQueryExecutor<Serializ
111111
StringBuilder cypher = new StringBuilder(CypherBuilder.buildRelationshipMatch(parent.labelsAsString, relType, related.labelsAsString))
112112
cypher.append('( ')
113113
.append(parent.formatId(RelationshipPersistentEntity.FROM))
114-
.append(" = {id} )")
114+
.append(" = \$id )")
115115

116116
boolean isLazyToMany = lazy && !isRelationship && association instanceof ToMany
117117
if(isLazyToMany) {

grails-datastore-gorm-neo4j/src/main/groovy/org/grails/datastore/gorm/neo4j/engine/Neo4jQuery.groovy

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ class Neo4jQuery extends Query {
243243
}
244244
}
245245

246-
return new CypherExpression(lhs, "{$paramNumber}", CriterionHandler.OPERATOR_EQUALS)
246+
return new CypherExpression(lhs, "\$$paramNumber", CriterionHandler.OPERATOR_EQUALS)
247247
}
248248

249249
},
@@ -252,7 +252,7 @@ class Neo4jQuery extends Query {
252252
@CompileStatic
253253
CypherExpression handle(GraphPersistentEntity entity, Query.IdEquals criterion, CypherBuilder builder, String prefix) {
254254
int paramNumber = addBuildParameterForCriterion(builder, entity, criterion)
255-
return new CypherExpression(entity.formatId(prefix), "{$paramNumber}", CriterionHandler.OPERATOR_EQUALS)
255+
return new CypherExpression(entity.formatId(prefix), "\$$paramNumber", CriterionHandler.OPERATOR_EQUALS)
256256
}
257257
},
258258
(Query.Like): new CriterionHandler<Query.Like>() {
@@ -261,7 +261,7 @@ class Neo4jQuery extends Query {
261261
CypherExpression handle(GraphPersistentEntity entity, Query.Like criterion, CypherBuilder builder, String prefix) {
262262
int paramNumber = addBuildParameterForCriterion(builder, entity, criterion)
263263
String operator = handleLike(criterion, builder, paramNumber, false)
264-
return new CypherExpression(entity.formatProperty(prefix, criterion.property), "{$paramNumber}", operator)
264+
return new CypherExpression(entity.formatProperty(prefix, criterion.property), "\$$paramNumber", operator)
265265
}
266266
},
267267
(Query.ILike): new CriterionHandler<Query.ILike>() {
@@ -271,7 +271,7 @@ class Neo4jQuery extends Query {
271271
int paramNumber = addBuildParameterForCriterion(builder, entity, criterion)
272272
String operator = handleLike(criterion, builder, paramNumber, true)
273273
String propertyRef = entity.formatProperty(prefix, criterion.property)
274-
String parameterRef = "{$paramNumber}"
274+
String parameterRef = "\$$paramNumber"
275275
if(operator != CriterionHandler.OPERATOR_LIKE) {
276276
propertyRef = "lower($propertyRef)"
277277
parameterRef = "lower($parameterRef)"
@@ -284,7 +284,7 @@ class Neo4jQuery extends Query {
284284
@CompileStatic
285285
CypherExpression handle(GraphPersistentEntity entity, Query.RLike criterion, CypherBuilder builder, String prefix) {
286286
int paramNumber = addBuildParameterForCriterion(builder, entity, criterion)
287-
return new CypherExpression(entity.formatProperty(prefix, criterion.property), "{$paramNumber}", CriterionHandler.OPERATOR_LIKE)
287+
return new CypherExpression(entity.formatProperty(prefix, criterion.property), "\$$paramNumber", CriterionHandler.OPERATOR_LIKE)
288288
}
289289
},
290290
(Query.In): new CriterionHandler<Query.In>() {
@@ -313,7 +313,7 @@ class Neo4jQuery extends Query {
313313
lhs = graphPersistentEntity.formatProperty(prefix, criterion.property)
314314
}
315315
builder.replaceParamAt(paramNumber, convertEnumsInList(values))
316-
return new CypherExpression(lhs, "{$paramNumber}", CriterionHandler.OPERATOR_IN)
316+
return new CypherExpression(lhs, "\$$paramNumber", CriterionHandler.OPERATOR_IN)
317317
}
318318
},
319319
(Query.IsNull): new CriterionHandler<Query.IsNull>() {
@@ -366,7 +366,7 @@ class Neo4jQuery extends Query {
366366
Neo4jMappingContext mappingContext = (Neo4jMappingContext)entity.mappingContext
367367
int paramNumberFrom = builder.addParam( mappingContext.convertToNative(criterion.from) )
368368
int parmaNumberTo = builder.addParam( mappingContext.convertToNative(criterion.to) )
369-
new CypherExpression( "{$paramNumberFrom}<=${prefix}.$criterion.property and ${prefix}.$criterion.property<={$parmaNumberTo}")
369+
new CypherExpression( "\$$paramNumberFrom<=${prefix}.$criterion.property and ${prefix}.$criterion.property<=\$$parmaNumberTo")
370370
}
371371
},
372372
(Query.SizeLessThanEquals): SizeCriterionHandler.LESS_THAN_EQUALS,
@@ -772,7 +772,7 @@ class Neo4jQuery extends Query {
772772
}
773773

774774
}
775-
return new CypherExpression(lhs, "{$paramNumber}", operator)
775+
return new CypherExpression(lhs, "\$$paramNumber", operator)
776776
}
777777
}
778778

@@ -832,7 +832,7 @@ class Neo4jQuery extends Query {
832832
int paramNumber = addBuildParameterForCriterion(builder, entity, criterion)
833833
Association association = entity.getPropertyByName(criterion.property) as Association
834834
builder.addMatch("(${prefix})${RelationshipUtils.matchForAssociation(association)}() WITH ${prefix},count(*) as count")
835-
return new CypherExpression(CriterionHandler.COUNT, "{$paramNumber}", operator)
835+
return new CypherExpression(CriterionHandler.COUNT, "\$$paramNumber", operator)
836836
}
837837
}
838838

grails-datastore-gorm-neo4j/src/test/groovy/grails/gorm/tests/CypherQueryStringSpec.groovy

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
2828
setupDomain()
2929

3030
when:
31-
int result = Club.executeUpdate("MATCH (n) where n.name = {name} SET n.ground = {ground}", [name:'FC Bayern Muenchen', ground:"Alliance Arena"])
32-
def club = Club.find("MATCH (n) where n.name = {1} RETURN n", 'FC Bayern Muenchen')
31+
int result = Club.executeUpdate("MATCH (n) where n.name = \$name SET n.ground = \$ground", [name:'FC Bayern Muenchen', ground:"Alliance Arena"])
32+
def club = Club.find("MATCH (n) where n.name = \$1 RETURN n", 'FC Bayern Muenchen')
3333

3434
then:
3535
result == 1
@@ -50,7 +50,7 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
5050
club.teams.size() == 2
5151

5252
when:"A find method is executed with map arguments"
53-
club = Club.find("MATCH (n) where n.name = {name} RETURN n", [name:'FC Bayern Muenchen'])
53+
club = Club.find("MATCH (n) where n.name = \$name RETURN n", [name:'FC Bayern Muenchen'])
5454

5555
then:"The result is correct"
5656
club instanceof Club
@@ -60,7 +60,7 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
6060

6161
when:"A find method is executed on the inverse side"
6262
session.clear()
63-
def team = Team.find("MATCH (n) where n.name = {name} RETURN n", [name:'FCB Team 1'])
63+
def team = Team.find("MATCH (n) where n.name = \$name RETURN n", [name:'FCB Team 1'])
6464

6565
then:"The result is correct"
6666
team instanceof Team
@@ -95,7 +95,7 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
9595

9696
when:"A find method is executed with map arguments"
9797
session.clear()
98-
clubs = Club.findAll("MATCH (n) where n.name = {name} RETURN n", [name:'FC Bayern Muenchen'])
98+
clubs = Club.findAll("MATCH (n) where n.name = \$name RETURN n", [name:'FC Bayern Muenchen'])
9999

100100
then:"The result is correct"
101101
clubs.size() == 1
@@ -128,7 +128,7 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
128128
setupDomain()
129129

130130
when:"A cypher query is executed"
131-
def result = Club.executeCypher("MATCH (n) where n.name = {name} RETURN n", [name:'FC Bayern Muenchen'])
131+
def result = Club.executeCypher("MATCH (n) where n.name = \$name RETURN n", [name:'FC Bayern Muenchen'])
132132
Club club = result as Club
133133

134134
then:"the conversion is correct"
@@ -138,7 +138,7 @@ class CypherQueryStringSpec extends GormDatastoreSpec {
138138
club.teams.size() == 2
139139

140140
when:"A cypher query is executed"
141-
result = Club.executeCypher("MATCH (n) where n.name = {name} RETURN n", [name:'FC Bayern Muenchen'])
141+
result = Club.executeCypher("MATCH (n) where n.name = \$name RETURN n", [name:'FC Bayern Muenchen'])
142142
List<Club> clubs = result.toList(Club)
143143

144144
then:"the conversion is correct"

grails-datastore-gorm-neo4j/src/test/groovy/grails/gorm/tests/ManyToManySpec.groovy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ class ManyToManySpec extends GormDatastoreSpec {
227227
fetchedFelix.friends.size() == 100
228228

229229
when: "we have 100 relationships"
230-
def result = session.transaction.nativeTransaction.run("MATCH (:BidirectionalFriends {name:{1}})<-[:FRIENDS]-(o) return count(o) as c", ["1":"felix"])
230+
def result = session.transaction.nativeTransaction.run("MATCH (:BidirectionalFriends {name:\$1})<-[:FRIENDS]-(o) return count(o) as c", ["1":"felix"])
231231

232232
then:
233233
IteratorUtil.single(result)["c"].asNumber() == 100

grails-datastore-gorm-neo4j/src/test/groovy/grails/gorm/tests/MiscSpec.groovy

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ class MiscSpec extends GormDatastoreSpec {
174174
def session = boltDriver.session()
175175
def tx = session.beginTransaction()
176176

177-
tx.run("CREATE (n1:Team {props})", [props:[name:"Team $count".toString()]])
177+
tx.run("CREATE (n1:Team \$props)", [props:[name:"Team $count".toString()]])
178178
tx.commit()
179179
session.close()
180180
}
@@ -342,18 +342,18 @@ class MiscSpec extends GormDatastoreSpec {
342342
when:
343343
def pet = new Pet(birthDate: new Date(), name: 'Cosima').save(flush: true)
344344
then:
345-
IteratorUtil.single(session.transaction.nativeTransaction.run("MATCH (p:Pet {name:{1}}) RETURN p.birthDate as birthDate", ["1":'Cosima'])).birthDate.asNumber() instanceof Long
345+
IteratorUtil.single(session.transaction.nativeTransaction.run("MATCH (p:Pet {name:\$1}) RETURN p.birthDate as birthDate", ["1":'Cosima'])).birthDate.asNumber() instanceof Long
346346
}
347347

348348
@Issue("https://github.com/SpringSource/grails-data-mapping/issues/52")
349-
@IgnoreIf({System.getenv('TRAVIS')}) // fails randomly on Travis
349+
@IgnoreIf({System.getenv('CI')}) // fails randomly on Travis
350350
def "verify backward compatibility, check that date properties stored as string can be read"() {
351351
setup: "create a instance with a date property and manually assign a string to it"
352352
def date = new Date()
353353
def pet = new Pet(birthDate: date, name:'Cosima').save(flush: true)
354354

355355
when: "write birthDate as a String"
356-
session.transaction.nativeTransaction.run("MATCH (p:Pet {name:{1}}) SET p.birthDate={2}",
356+
session.transaction.nativeTransaction.run("MATCH (p:Pet {name:\$1}) SET p.birthDate=\$2",
357357
['1':'Cosima', '2':date.time.toString()])
358358
pet = Pet.get(pet.id)
359359
then: "the string stored date gets parsed correctly"
@@ -365,7 +365,7 @@ class MiscSpec extends GormDatastoreSpec {
365365
when:
366366
def team = new Team(name: 'name', binaryData: 'abc'.bytes)
367367
team.save(flush: true)
368-
def value = IteratorUtil.single(session.transaction.nativeTransaction.run("MATCH (p:Team {name:{1}}) RETURN p.binaryData as binaryData",
368+
def value = IteratorUtil.single(session.transaction.nativeTransaction.run("MATCH (p:Team {name:\$1}) RETURN p.binaryData as binaryData",
369369
["1":'name'])).binaryData
370370

371371
then:

0 commit comments

Comments
 (0)