-
Notifications
You must be signed in to change notification settings - Fork 199
/
Neo4jEntityQueries.java
313 lines (288 loc) · 11.7 KB
/
Neo4jEntityQueries.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.datastore.neo4j.dialect.impl;
import static org.hibernate.ogm.datastore.neo4j.dialect.impl.NodeLabel.EMBEDDED;
import static org.hibernate.ogm.datastore.neo4j.dialect.impl.NodeLabel.ENTITY;
import static org.hibernate.ogm.datastore.neo4j.query.parsing.cypherdsl.impl.CypherDSL.escapeIdentifier;
import static org.hibernate.ogm.util.impl.EmbeddedHelper.split;
import java.util.Map;
import org.hibernate.internal.util.collections.BoundedConcurrentHashMap;
import org.hibernate.ogm.model.key.spi.EntityKeyMetadata;
import org.hibernate.ogm.util.impl.ArrayHelper;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
/**
* Container for the queries related to one entity type in Neo4j. Unfortunately, we cannot use the same queries for all
* entities, as Neo4j does not allow to parameterize on node labels which would be required, as the entity name is
* stored as a label.
*
* @author Davide D'Alto
*/
public class Neo4jEntityQueries extends QueriesBase {
private static final int CACHE_CAPACITY = 1000;
private static final int CACHE_CONCURRENCY_LEVEL = 20;
private final BoundedConcurrentHashMap<String, String> updateEmbeddedPropertyQueryCache;
private final String createEmbeddedNodeQuery;
private final String findEntityQuery;
private final String findEntitiesQuery;
private final String createEntityQuery;
private final String removeEntityQuery;
private final String updateEmbeddedNodeQuery;
private final String removeEmbdeddedElementQuery;
public Neo4jEntityQueries(EntityKeyMetadata entityKeyMetadata) {
this.updateEmbeddedPropertyQueryCache = new BoundedConcurrentHashMap<String, String>( CACHE_CAPACITY, CACHE_CONCURRENCY_LEVEL, BoundedConcurrentHashMap.Eviction.LIRS );
this.createEmbeddedNodeQuery = initCreateEmbeddedNodeQuery( entityKeyMetadata );
this.findEntityQuery = initFindEntityQuery( entityKeyMetadata );
this.findEntitiesQuery = initFindEntitiesQuery( entityKeyMetadata );
this.createEntityQuery = initCreateEntityQuery( entityKeyMetadata );
this.removeEntityQuery = initRemoveEntityQuery( entityKeyMetadata );
this.updateEmbeddedNodeQuery = initUpdateEmbeddedNodeQuery( entityKeyMetadata );
this.removeEmbdeddedElementQuery = initRemoveEmbdeddedElementQuery( entityKeyMetadata );
}
/*
* Example:
*
* CREATE (n:EMBEDDED:table {id: {0}})
* RETURN n
*/
private static String initCreateEmbeddedNodeQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "CREATE " );
queryBuilder.append( "(n:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ":" );
appendLabel( entityKeyMetadata, queryBuilder );
appendProperties( entityKeyMetadata, queryBuilder );
queryBuilder.append( ") RETURN n" );
return queryBuilder.toString();
}
/* This is only the first part of the query, the one related to the owner of the embedded.
* We need to know the embedded columns to create the whole query.
*
* Example:
* MERGE (owner:ENTITY:Example {id: {0}}) MERGE (owner)
*/
private static String initUpdateEmbeddedNodeQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "MERGE " );
appendEntityNode( "owner", entityKeyMetadata, queryBuilder );
queryBuilder.append( " MERGE (owner)" );
return queryBuilder.toString();
}
private static void appendRelationshipType(StringBuilder queryBuilder, String relationshipType) {
escapeIdentifier( queryBuilder, relationshipType );
}
/*
* Example:
*
* MATCH (n:ENTITY:table {id: {0}})
* RETURN n
*/
private static String initFindEntityQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
appendEntityNode( "n", entityKeyMetadata, queryBuilder );
queryBuilder.append( " RETURN n" );
return queryBuilder.toString();
}
private static void appendEntityNode(String alias, EntityKeyMetadata entityKeyMetadata, StringBuilder queryBuilder) {
queryBuilder.append( "(");
queryBuilder.append( alias );
queryBuilder.append( ":" );
queryBuilder.append( ENTITY );
queryBuilder.append( ":" );
appendLabel( entityKeyMetadata, queryBuilder );
appendProperties( entityKeyMetadata, queryBuilder );
queryBuilder.append( ")" );
}
/*
* Example:
*
* MATCH (n:ENTITY:table )
* RETURN n
*/
private static String initFindEntitiesQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
queryBuilder.append( "(n:" );
queryBuilder.append( ENTITY );
queryBuilder.append( ":" );
appendLabel( entityKeyMetadata, queryBuilder );
queryBuilder.append( ") RETURN n" );
return queryBuilder.toString();
}
/*
* Example:
*
* CREATE (n:ENTITY:table {id: {0}})
* RETURN n
*/
private static String initCreateEntityQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "CREATE " );
appendEntityNode( "n", entityKeyMetadata, queryBuilder );
queryBuilder.append( " RETURN n" );
return queryBuilder.toString();
}
/*
* Example:
*
* MATCH (n:ENTITY:table {id: {0}}) --> (e:EMBEDDED)
* WITH e
* MATCH path=(e) -[*0..]-> (:EMBEDDED)
* FOREACH (r IN relationships(path) | DELETE r)
* FOREACH (e IN relationships(path) | DELETE e)
*/
private static String initRemoveEmbdeddedElementQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
appendEntityNode( "n", entityKeyMetadata, queryBuilder );
queryBuilder.append( " --> (e:EMBEDDED)" );
queryBuilder.append( " WITH e " );
queryBuilder.append( " MATCH path=(e) -[*0..]-> (:EMBEDDED) ");
queryBuilder.append( " FOREACH ( r IN relationships(path) | DELETE r )" );
queryBuilder.append( " FOREACH ( e IN nodes(path) | DELETE e )" );
return queryBuilder.toString();
}
/*
* Example:
*
* MATCH (n:ENTITY:table {id: {0}})
* OPTIONAL MATCH (n) - [r] - ()
* DELETE n, r
*/
private static String initRemoveEntityQuery(EntityKeyMetadata entityKeyMetadata) {
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
appendEntityNode( "n", entityKeyMetadata, queryBuilder );
queryBuilder.append( " OPTIONAL MATCH (n) - [r] - ()" );
queryBuilder.append( " DELETE n, r" );
return queryBuilder.toString();
}
/**
* Create a single node representing an embedded element.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @param columnValues the values in {@link org.hibernate.ogm.model.key.spi.EntityKey#getColumnValues()}
* @return the corresponding node;
*/
public Node createEmbedded(ExecutionEngine executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
ExecutionResult result = executionEngine.execute( createEmbeddedNodeQuery, params );
return singleResult( result );
}
/**
* Find the node corresponding to an entity.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @param columnValues the values in {@link org.hibernate.ogm.model.key.spi.EntityKey#getColumnValues()}
* @return the corresponding node
*/
public Node findEntity(ExecutionEngine executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
ExecutionResult result = executionEngine.execute( findEntityQuery, params );
return singleResult( result );
}
/**
* Creates the node corresponding to an entity.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @param columnValues the values in {@link org.hibernate.ogm.model.key.spi.EntityKey#getColumnValues()}
* @return the corresponding node
*/
public Node insertEntity(ExecutionEngine executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
ExecutionResult result = executionEngine.execute( createEntityQuery, params );
return singleResult( result );
}
/**
* Find all the node representing the entity.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @return an iterator over the nodes representing an entity
*/
public ResourceIterator<Node> findEntities(ExecutionEngine executionEngine) {
ExecutionResult result = executionEngine.execute( findEntitiesQuery );
return result.columnAs( "n" );
}
/**
* Remove the nodes representing the entity and the embedded elements attached to it.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @param columnValues the values of the key identifying the entity to remove
*/
public void removeEntity(ExecutionEngine executionEngine, Object[] columnValues) {
Map<String, Object> params = params( columnValues );
// Remove the embedded elements first
executionEngine.execute( removeEmbdeddedElementQuery, params );
// Remove the entity
executionEngine.execute( removeEntityQuery, params );
}
/**
* Update the value of an embedded node property.
*
* @param executionEngine the {@link ExecutionEngine} used to run the query
* @param keyValues the columns representing the identifier in the entity owning the embedded
* @param embeddedColumn the column on the embedded node (dot-separated properties)
* @param value the new value for the property
*/
public void updateEmbeddedColumn(ExecutionEngine executionEngine, Object[] keyValues, String embeddedColumn, Object value) {
String query = updateEmbeddedPropertyQueryCache.get( embeddedColumn );
if ( query == null ) {
query = initUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );
String cached = updateEmbeddedPropertyQueryCache.putIfAbsent( embeddedColumn, query );
if ( cached != null ) {
query = cached;
}
}
Map<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );
executionEngine.execute( query, params );
}
/*
* Example:
*
* MERGE (owner:ENTITY:Account {login: {0}})
* MERGE (owner) - [:homeAddress] -> (e:EMBEDDED)
* ON CREATE SET e.country = {1}
* ON MATCH SET e.country = {2}
*/
private String initUpdateEmbeddedColumnQuery(Object[] keyValues, String embeddedColumn) {
StringBuilder queryBuilder = new StringBuilder( updateEmbeddedNodeQuery );
String[] columns = appendEmbeddedNodes( embeddedColumn, queryBuilder );
queryBuilder.append( " ON CREATE SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length );
queryBuilder.append( "}" );
queryBuilder.append( " ON MATCH SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length + 1 );
queryBuilder.append( "}" );
return queryBuilder.toString();
}
/*
* Given an embedded properties path returns the cypher representation that can be appended to a MERGE or CREATE
* query.
*/
private static String[] appendEmbeddedNodes(String path, StringBuilder queryBuilder) {
String[] columns = split( path );
for ( int i = 0; i < columns.length - 1; i++ ) {
queryBuilder.append( " - [:" );
appendRelationshipType( queryBuilder, columns[i] );
queryBuilder.append( "] ->" );
if ( i < columns.length - 2 ) {
queryBuilder.append( " (e" );
queryBuilder.append( i );
queryBuilder.append( ":" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ") MERGE (e" );
queryBuilder.append( i );
queryBuilder.append( ")" );
}
}
queryBuilder.append( " (e:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ")" );
return columns;
}
}