/
JcrQueryManagerTest.java
3099 lines (2798 loc) · 152 KB
/
JcrQueryManagerTest.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ModeShape (http://www.modeshape.org)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* ModeShape is free software. Unless otherwise indicated, all code in ModeShape
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* ModeShape is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.modeshape.jcr;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO;
import static javax.jcr.query.qom.QueryObjectModelConstants.JCR_OPERATOR_LIKE;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.nodetype.InvalidNodeTypeDefinitionException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import javax.jcr.query.qom.ChildNode;
import javax.jcr.query.qom.Column;
import javax.jcr.query.qom.Constraint;
import javax.jcr.query.qom.Join;
import javax.jcr.query.qom.Literal;
import javax.jcr.query.qom.Ordering;
import javax.jcr.query.qom.PropertyValue;
import javax.jcr.query.qom.QueryObjectModelConstants;
import javax.jcr.query.qom.Selector;
import org.infinispan.schematic.document.Document;
import org.infinispan.schematic.document.Json;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.modeshape.common.FixFor;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.api.query.QueryManager;
import org.modeshape.jcr.api.query.qom.Limit;
import org.modeshape.jcr.api.query.qom.QueryObjectModelFactory;
import org.modeshape.jcr.api.query.qom.SelectQuery;
import org.modeshape.jcr.cache.CachedNode;
import org.modeshape.jcr.cache.ChildReferences;
import org.modeshape.jcr.cache.NodeCache;
import org.modeshape.jcr.cache.NodeKey;
import org.modeshape.jcr.query.JcrQueryResult;
import org.modeshape.jcr.value.Name;
import org.modeshape.jcr.value.Path.Segment;
/**
* This is a test suite that operates against a complete JcrRepository instance created and managed using the JcrEngine.
* Essentially this is an integration test, but it does test lower-level functionality of the implementation of the JCR interfaces
* related to querying. (It is simply more difficult to unit test these implementations because of the difficulty in mocking the
* many other components to replicate the same functionality.)
* <p>
* Also, because queries are read-only, the engine is set up once and used for the entire set of test methods.
* </p>
*/
public class JcrQueryManagerTest extends MultiUseAbstractTest {
private static final String[] INDEXED_SYSTEM_NODES_PATHS = new String[] {"/jcr:system/jcr:nodeTypes",
"/jcr:system/mode:namespaces", "/jcr:system/mode:repository"};
private static final String[] NON_INDEXED_SYSTEM_NODES_PATHS = new String[] {"/", "/jcr:system/mode:locks",
"/jcr:system/jcr:versionStorage"};
private static final boolean WRITE_INDEXES_TO_FILE = false;
/** The total number of nodes excluding '/jcr:system' */
protected static final int TOTAL_NON_SYSTEM_NODE_COUNT = 25;
/** The total number of nodes at or below '/jcr:system' */
protected static int totalSystemNodeCount;
/** The total number of nodes */
protected static int totalNodeCount;
protected static URI resourceUri( String name ) throws URISyntaxException {
return resourceUrl(name).toURI();
}
protected static URL resourceUrl( String name ) {
return JcrQueryManagerTest.class.getClassLoader().getResource(name);
}
protected static InputStream resourceStream( String name ) {
return JcrQueryManagerTest.class.getClassLoader().getResourceAsStream(name);
}
private static String[] prefixEach( String[] original,
String prefix ) {
String[] result = new String[original.length];
for (int i = 0; i != original.length; ++i) {
result[i] = prefix + original[i];
}
return result;
}
private static String[] allOf( String[]... arrays ) {
List<String> result = new ArrayList<String>();
for (String[] array : arrays) {
for (String value : array) {
result.add(value);
}
}
return result.toArray(new String[result.size()]);
}
protected static String[] carColumnNames() {
return new String[] {"car:mpgCity", "car:lengthInInches", "car:maker", "car:userRating", "car:mpgHighway", "car:engine",
"car:valueRating", "jcr:primaryType", "jcr:mixinTypes", "car:wheelbaseInInches", "car:model", "car:year", "car:msrp",
"jcr:created", "jcr:createdBy", "jcr:name", "jcr:path", "jcr:score", "mode:depth", "mode:localName",
"car:alternateModels"};
}
protected static String[] carColumnNames( String selectorName ) {
return prefixEach(carColumnNames(), selectorName + ".");
}
protected static String[] allColumnNames() {
return new String[] {"jcr:primaryType", "jcr:mixinTypes", "jcr:name", "jcr:path", "jcr:score", "mode:depth",
"mode:localName"};
}
protected static String[] allColumnNames( String selectorName ) {
return prefixEach(allColumnNames(), selectorName + ".");
}
protected static String[] typedColumnNames() {
return new String[] {"notion:booleanProperty", "notion:booleanProperty2", "notion:stringProperty",
"notion:booleanCreatedPropertyWithDefault", "notion:stringPropertyWithDefault",
"notion:booleanAutoCreatedPropertyWithDefault", "notion:stringAutoCreatedPropertyWithDefault", "notion:longProperty",
"notion:singleReference", "notion:multipleReferences", "jcr:primaryType", "jcr:mixinTypes", "jcr:name", "jcr:path",
"jcr:score", "mode:depth", "mode:localName"};
}
protected static String[] typedColumnNames( String selectorName ) {
return prefixEach(typedColumnNames(), selectorName + ".");
}
protected static String[] searchColumnNames() {
return new String[] {"jcr:score"};
}
private boolean print;
@SuppressWarnings( "deprecation" )
@BeforeClass
public static void beforeAll() throws Exception {
if (WRITE_INDEXES_TO_FILE) {
File dir = new File("target/querytest/indexes");
if (dir.exists()) FileUtil.delete(dir);
}
String simpleName = JcrQueryManagerTest.class.getSimpleName();
String configFileName = WRITE_INDEXES_TO_FILE ? simpleName + "Disk.json" : simpleName + ".json";
String configFilePath = "config/" + configFileName;
InputStream configStream = JcrQueryManagerTest.class.getClassLoader().getResourceAsStream(configFilePath);
assertThat("Unable to find configuration file '" + configFilePath, configStream, is(notNullValue()));
Document configDoc = Json.read(configStream);
RepositoryConfiguration config = new RepositoryConfiguration(configDoc, configFileName);
startRepository(config);
try {
// Use a session to load the contents ...
JcrSession session = repository.login();
try {
registerNodeTypes(session, "cnd/fincayra.cnd");
registerNodeTypes(session, "cnd/magnolia.cnd");
registerNodeTypes(session, "cnd/notionalTypes.cnd");
registerNodeTypes(session, "cnd/cars.cnd");
registerNodeTypes(session, "cnd/validType.cnd");
InputStream stream = resourceStream("io/cars-system-view.xml");
try {
session.getWorkspace().importXML("/", stream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
} catch (Throwable t) {
t.printStackTrace();
} finally {
stream.close();
}
// Create a branch that contains some same-name-siblings ...
Node other = session.getRootNode().addNode("Other", "nt:unstructured");
Node a = other.addNode("NodeA", "nt:unstructured");
a.addMixin("mix:referenceable");
a.setProperty("something", "value3 quick brown fox");
a.setProperty("somethingElse", "value2");
a.setProperty("propA", "value1");
Node other2 = other.addNode("NodeA", "nt:unstructured");
other2.addMixin("mix:referenceable");
other2.setProperty("something", "value2 quick brown cat wearing hat");
other2.setProperty("propB", "value1");
other2.setProperty("propC", "value2");
Node other3 = other.addNode("NodeA", "nt:unstructured");
other3.addMixin("mix:referenceable");
other3.setProperty("something", new String[] {"black dog", "white dog"});
other3.setProperty("propB", "value1");
other3.setProperty("propC", "value3");
Value[] refValues = new Value[2];
refValues[0] = session.getValueFactory().createValue(other2);
refValues[1] = session.getValueFactory().createValue(other3);
other3.setProperty("otherNode", a);
other3.setProperty("otherNodes", refValues);
Node c = other.addNode("NodeC", "notion:typed");
c.setProperty("notion:booleanProperty", true);
c.setProperty("notion:booleanProperty2", false);
c.setProperty("propD", "value4");
c.setProperty("propC", "value1");
c.setProperty("notion:singleReference", a);
c.setProperty("notion:multipleReferences", refValues);
session.getRootNode().addNode("NodeB", "nt:unstructured").setProperty("myUrl", "http://www.acme.com/foo/bar");
session.save();
// Initialize the nodes count
initNodesCount();
// Prime creating a first XPath query and SQL query ...
session.getWorkspace().getQueryManager().createQuery("//element(*,nt:unstructured)", Query.XPATH);
session.getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:base]", Query.JCR_SQL2);
} finally {
session.logout();
}
// Prime creating the schemata ...
repository.nodeTypeManager().getRepositorySchemata();
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
private static void initNodesCount() throws RepositoryException {
JcrSession session = repository.login();
try {
NodeCache systemSession = repository.createSystemSession(session.context(), true);
totalSystemNodeCount = countAllNodesBelow(systemSession.getRootKey(), systemSession)
- NON_INDEXED_SYSTEM_NODES_PATHS.length;
totalNodeCount = totalSystemNodeCount + TOTAL_NON_SYSTEM_NODE_COUNT;
} finally {
session.logout();
}
}
private static int countAllNodesBelow( NodeKey nodeKey,
NodeCache cache ) throws RepositoryException {
int result = 1;
CachedNode node = cache.getNode(nodeKey);
ChildReferences childReferences = node.getChildReferences(cache);
for (Iterator<NodeKey> nodeKeyIterator = childReferences.getAllKeys(); nodeKeyIterator.hasNext();) {
NodeKey childKey = nodeKeyIterator.next();
result += countAllNodesBelow(childKey, cache);
}
return result;
}
@AfterClass
public static void afterAll() throws Exception {
MultiUseAbstractTest.afterAll();
}
@Before
@Override
public void beforeEach() throws Exception {
super.beforeEach();
print = false;
}
protected static void registerNodeTypes( JcrSession session,
String pathToClasspathResource ) throws RepositoryException, IOException {
URL url = resourceUrl(pathToClasspathResource);
session.getWorkspace().getNodeTypeManager().registerNodeTypes(url, true);
}
protected Name name( String name ) {
return session.nameFactory().create(name);
}
protected Segment segment( String segment ) {
return session.pathFactory().createSegment(segment);
}
protected List<Segment> segments( String... segments ) {
List<Segment> result = new ArrayList<Segment>();
for (String segment : segments) {
result.add(segment(segment));
}
return result;
}
protected void assertResults( Query query,
QueryResult result,
long numberOfResults ) throws RepositoryException {
assertThat(query, is(notNullValue()));
assertThat(result, is(notNullValue()));
if (print /*|| result.getNodes().getSize() != numberOfResults || result.getRows().getSize() != numberOfResults*/) {
System.out.println();
System.out.println(query);
System.out.println(" plan -> " + ((org.modeshape.jcr.api.query.QueryResult)result).getPlan());
System.out.println(result);
}
if (result.getSelectorNames().length == 1) {
NodeIterator iter = result.getNodes();
if (iter.getSize() != numberOfResults && !print) {
// print anyway since this is an error
System.out.println();
System.out.println(query);
System.out.println(" plan -> " + ((JcrQueryResult)result).getPlan());
System.out.println(result);
}
assertThat(iter.getSize(), is(numberOfResults));
} else {
try {
result.getNodes();
if (!print) {
// print anyway since this is an error
System.out.println();
System.out.println(query);
System.out.println(" plan -> " + ((JcrQueryResult)result).getPlan());
System.out.println(result);
}
fail("should not be able to call this method when the query has multiple selectors");
} catch (RepositoryException e) {
// expected; can't call this when the query uses multiple selectors ...
}
}
assertThat(result.getRows().getSize(), is(numberOfResults));
}
protected void assertResultsHaveColumns( QueryResult result,
String... columnNames ) throws RepositoryException {
List<String> expectedNames = new ArrayList<String>();
for (String name : columnNames) {
expectedNames.add(name);
}
List<String> actualNames = new ArrayList<String>();
for (String name : result.getColumnNames()) {
actualNames.add(name);
}
Collections.sort(expectedNames);
Collections.sort(actualNames);
assertThat(actualNames, is(expectedNames));
}
protected void assertResultsHaveRows( QueryResult result,
String columnName,
String... rowValuesAsStrings ) throws RepositoryException {
RowIterator iter = result.getRows();
int i = 0;
while (iter.hasNext()) {
Row row = iter.nextRow();
assertThat(row.getValue(columnName).getString(), is(rowValuesAsStrings[i++]));
}
}
public interface RowResult {
public RowResult has( String columnName,
String value ) throws RepositoryException;
public RowResult has( String columnName,
long value ) throws RepositoryException;
public RowResult and( String columnName,
String value ) throws RepositoryException;
public RowResult and( String columnName,
long value ) throws RepositoryException;
}
public class SpecificRowResult implements RowResult {
private final Row row;
public SpecificRowResult( Row row ) {
this.row = row;
}
@Override
public RowResult has( String columnName,
String value ) throws RepositoryException {
assertThat(row.getValue(columnName).getString(), is(value));
return this;
}
@Override
public RowResult has( String columnName,
long value ) throws RepositoryException {
assertThat(row.getValue(columnName).getLong(), is(value));
return this;
}
@Override
public RowResult and( String columnName,
String value ) throws RepositoryException {
return has(columnName, value);
}
@Override
public RowResult and( String columnName,
long value ) throws RepositoryException {
return has(columnName, value);
}
}
public class SomeRowResult implements RowResult {
private final QueryResult result;
private final List<Row> matchingRows = new LinkedList<Row>();
public SomeRowResult( QueryResult result ) throws RepositoryException {
this.result = result;
for (RowIterator iterator = result.getRows(); iterator.hasNext();) {
Row row = iterator.nextRow();
matchingRows.add(row);
}
}
@Override
public RowResult has( String columnName,
long value ) throws RepositoryException {
// Remove all the rows that don't have a matching value ...
ListIterator<Row> iter = matchingRows.listIterator();
while (iter.hasNext()) {
Row row = iter.next();
if (row.getValue(columnName).getLong() != value) iter.remove();
}
if (matchingRows.isEmpty()) {
fail("Failed to find row");
}
return this;
}
@Override
public RowResult has( String columnName,
String value ) throws RepositoryException {
// Remove all the rows that don't have a matching value ...
ListIterator<Row> iter = matchingRows.listIterator();
while (iter.hasNext()) {
Row row = iter.next();
Value actualValue = row.getValue(columnName);
if (actualValue == null && value == null) continue;
if (actualValue != null && actualValue.getString().equals(value)) continue;
iter.remove();
}
if (matchingRows.isEmpty()) {
fail("Failed to find row");
}
return this;
}
@Override
public RowResult and( String columnName,
long value ) throws RepositoryException {
return has(columnName, value);
}
@Override
public RowResult and( String columnName,
String value ) throws RepositoryException {
return has(columnName, value);
}
@Override
public String toString() {
return result.toString();
}
}
protected RowResult assertRow( QueryResult result ) throws RepositoryException {
return new SomeRowResult(result);
}
protected RowResult assertRow( QueryResult result,
int rowNumber ) throws RepositoryException {
RowIterator rowIter = result.getRows();
Row row = null;
for (int i = 0; i != rowNumber; ++i) {
row = rowIter.nextRow();
}
assertThat(row, is(notNullValue()));
return new SpecificRowResult(row);
}
@Test
public void shouldStartUp() {
assertThat(session, is(notNullValue()));
}
@Test
public void shouldHaveLoadedContent() throws RepositoryException {
Node node = session.getRootNode().getNode("Cars");
assertThat(node, is(notNullValue()));
assertThat(node.hasNode("Sports"), is(true));
assertThat(node.hasNode("Utility"), is(true));
assertThat(node.hasNode("Hybrid"), is(true));
// System.out.println(node.getNode("Hybrid").getNodes().nextNode().getPath());
assertThat(node.hasNode("Hybrid/Toyota Prius"), is(true));
assertThat(node.getPrimaryNodeType().getName(), is("nt:unstructured"));
}
@Test
public void shouldReturnQueryManagerFromWorkspace() throws RepositoryException {
assertThat(session.getWorkspace().getQueryManager(), is(notNullValue()));
}
// ----------------------------------------------------------------------------------------------------------------
// JCR-SQL2 Queries
// ----------------------------------------------------------------------------------------------------------------
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllNodes() throws RepositoryException {
Query query = session.getWorkspace().getQueryManager().createQuery("SELECT * FROM [nt:base]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, totalNodeCount);
assertResultsHaveColumns(result, allColumnNames("nt:base"));
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllNodesWithOrderByPath() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [nt:base] ORDER BY [jcr:path]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, totalNodeCount);
assertResultsHaveColumns(result, allColumnNames("nt:base"));
}
@FixFor( "MODE-1095" )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryWithOrderByUsingPseudoColumnWithSelectStar() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [car:Car] WHERE [car:year] < 2009 ORDER BY [jcr:path]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, carColumnNames("car:Car"));
}
@FixFor( "MODE-1095" )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryWithOrderByUsingColumnWithSelectStar() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [car:Car] WHERE [car:year] < 2009 ORDER BY [car:year]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, carColumnNames("car:Car"));
}
@FixFor( "MODE-1095" )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryWithOrderByUsingColumnNotInSelect() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT [car:model], [car:maker] FROM [car:Car] WHERE [car:year] <= 2012 ORDER BY [car:year] DESC",
Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, "car:model", "car:maker", "car:year");
}
@FixFor( "MODE-1095" )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryWithJoinCriteriaOnColumnsInSelect() throws RepositoryException {
String sql = "SELECT x.*, y.* FROM [nt:unstructured] AS x INNER JOIN [nt:unstructured] AS y ON x.somethingElse = y.propC ORDER BY x.propC";
Query query = session.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 1);
assertResultsHaveColumns(result, allOf(allColumnNames("x"), allColumnNames("y"), new String[] {"x.propC"}));
RowIterator rows = result.getRows();
Row row1 = rows.nextRow();
assertThat(row1.getNode("x").getPath(), is("/Other/NodeA"));
assertThat(row1.getNode("y").getPath(), is("/Other/NodeA[2]"));
}
@FixFor( {"MODE-1095", "MODE-1680"} )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryWithJoinCriteriaOnColumnsNotInSelect() throws RepositoryException {
String sql = "SELECT y.* FROM [nt:unstructured] AS x INNER JOIN [nt:unstructured] AS y ON x.somethingElse = y.propC ORDER BY x.propC";
Query query = session.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 1);
assertResultsHaveColumns(result, allOf(allColumnNames("y")));
RowIterator rows = result.getRows();
Row row1 = rows.nextRow();
assertThat(row1.getNode().getPath(), is("/Other/NodeA[2]"));
}
@FixFor( "MODE-1055" )
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllNodesWithCriteria() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [nt:base] WHERE [car:year] < 2009", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, allColumnNames("nt:base"));
}
@FixFor( "MODE-1055" )
@Test
public void shouldReturnNullValuesForNonExistantPropertiesInSelectClauseOfJcrSql2Query() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT bogus, laughable, [car:year] FROM [nt:base] WHERE [car:year] < 2009",
Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, "bogus", "laughable", "car:year");
RowIterator rows = result.getRows();
while (rows.hasNext()) {
Row row = rows.nextRow();
assertThat(row.getValue("bogus"), is(nullValue()));
assertThat(row.getValue("laughable"), is(nullValue()));
assertThat(row.getValue("car:year"), is(not(nullValue())));
}
}
@FixFor( "MODE-1055" )
@Test
public void shouldNotMatchNodesWhenQueryUsesNonExistantPropertyInCriteriaInSelectClauseOfJcrSql2Query()
throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT bogus, laughable, [car:year] FROM [nt:base] WHERE argle < 2009", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 0);
assertResultsHaveColumns(result, "bogus", "laughable", "car:year");
}
@FixFor( "MODE-1055" )
@Test
public void shouldNotOrderByNonExistantPropertyInCriteriaInSelectClauseOfJcrSql2Query() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT bogus, laughable, [car:year] FROM [nt:base] ORDER BY argle", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, totalNodeCount);
assertResultsHaveColumns(result, "bogus", "laughable", "argle", "car:year");
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllCarNodes() throws RepositoryException {
Query query = session.getWorkspace().getQueryManager().createQuery("SELECT * FROM [car:Car]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, carColumnNames("car:Car"));
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllCarNodesOrderedByYear() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [car:Car] ORDER BY [car:year]", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, carColumnNames("car:Car"));
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllCarNodesOrderedByMsrp() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT * FROM [car:Car] ORDER BY [car:msrp] DESC", Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 13);
assertResultsHaveColumns(result, carColumnNames("car:Car"));
// Results are sorted by lexicographic MSRP (as a string, not as a number)!!!
assertRow(result, 1).has("car:model", "LR3").and("car:msrp", "$48,525").and("car:mpgCity", 12);
assertRow(result, 2).has("car:model", "IS350").and("car:msrp", "$36,305").and("car:mpgCity", 18);
assertRow(result, 10).has("car:model", "DB9").and("car:msrp", "$171,600").and("car:mpgCity", 12);
}
@FixFor( "MODE-1234" )
@Test
public void shouldAllowEqualityCriteriaOnPropertyDefinedWithBooleanPropertyDefinition() throws RepositoryException {
assertQueryWithBooleanValue(1, "");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty] = true");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty] = false");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty] > false");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty] >= false");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty] > true");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty] >= true");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty] < false");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty] <= false");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty] < true");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty] <= true");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty2] = true");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty2] = false");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty2] > false");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty2] >= false");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty2] > true");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty2] >= true");
assertQueryWithBooleanValue(0, "WHERE [notion:booleanProperty2] < false");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty2] <= false");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty2] < true");
assertQueryWithBooleanValue(1, "WHERE [notion:booleanProperty2] <= true");
}
protected void assertQueryWithBooleanValue( int numResults,
String criteria ) throws RepositoryException {
String[] columnNames = {"notion:booleanProperty", "notion:booleanProperty2"};
String queryStr = "SELECT [notion:booleanProperty], [notion:booleanProperty2] FROM [notion:typed] AS node " + criteria;
Query query = session.getWorkspace().getQueryManager().createQuery(queryStr, Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, numResults);
assertResultsHaveColumns(result, columnNames);
}
@FixFor( "MODE-1611" )
@Test
public void shouldAllowQomEqualityCriteriaOnPropertyDefinedWithBooleanPropertyDefinition() throws RepositoryException {
assertQomQueryWithBooleanValue(1, null, null, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty", JCR_OPERATOR_EQUAL_TO, true);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty", JCR_OPERATOR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty", JCR_OPERATOR_GREATER_THAN, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty", JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty", JCR_OPERATOR_GREATER_THAN, true);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty", JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, true);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty", JCR_OPERATOR_LESS_THAN, false);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty", JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty", JCR_OPERATOR_LESS_THAN, true);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty", JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, true);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty2", JCR_OPERATOR_EQUAL_TO, true);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty2", JCR_OPERATOR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty2", JCR_OPERATOR_GREATER_THAN, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty2", JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty2", JCR_OPERATOR_GREATER_THAN, true);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty2", JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO, true);
assertQomQueryWithBooleanValue(0, "notion:booleanProperty2", JCR_OPERATOR_LESS_THAN, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty2", JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, false);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty2", JCR_OPERATOR_LESS_THAN, true);
assertQomQueryWithBooleanValue(1, "notion:booleanProperty2", JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO, true);
}
protected void assertQomQueryWithBooleanValue( int numResults,
String propertyName,
String operator,
boolean propertyValue ) throws RepositoryException {
QueryObjectModelFactory qomFactory = session.getWorkspace().getQueryManager().getQOMFactory();
ValueFactory valueFactory = session.getValueFactory();
Value propertyValueObj = valueFactory.createValue(propertyValue);
Selector selector = qomFactory.selector("notion:typed", "node");
Constraint constraint = null;
if (propertyName != null && operator != null) {
PropertyValue propValue = qomFactory.propertyValue("node", propertyName);
Literal literal = qomFactory.literal(propertyValueObj);
constraint = qomFactory.comparison(propValue, operator, literal);
}
Column[] columns = new Column[2];
columns[0] = qomFactory.column("node", "notion:booleanProperty", "notion:booleanProperty");
columns[1] = qomFactory.column("node", "notion:booleanProperty2", "notion:booleanProperty2");
Ordering[] orderings = null;
// Build and execute the query ...
Query query = qomFactory.createQuery(selector, constraint, orderings, columns);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, numResults);
String[] columnNames = {"notion:booleanProperty", "notion:booleanProperty2"};
assertResultsHaveColumns(result, columnNames);
}
@FixFor( "MODE-1611" )
@Test
public void shouldAllowQomUseOfIsChildNodeInWhereClause() throws RepositoryException {
QueryObjectModelFactory qomFactory = session.getWorkspace().getQueryManager().getQOMFactory();
Selector selector = qomFactory.selector("nt:base", "category");
ChildNode childNodeConstraint = qomFactory.childNode("category", "/Cars");
Constraint constraint = childNodeConstraint;
Column[] columns = new Column[0];
Ordering[] orderings = null;
// Build and execute the query ...
Query query = qomFactory.createQuery(selector, constraint, orderings, columns);
assertThat(query.getStatement(), is("SELECT * FROM [nt:base] AS category WHERE ISCHILDNODE(category,'/Cars')"));
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 4L); // just 4 children below "/Cars"
String[] expectedColumns = {"category.jcr:primaryType", "category.jcr:mixinTypes", "category.jcr:name",
"category.jcr:path", "category.jcr:score", "category.mode:depth", "category.mode:localName"};
assertResultsHaveColumns(result, expectedColumns);
}
@FixFor( "MODE-1057" )
@Test
public void shouldAllowEqualityNumericCriteriaOnPropertyDefinedWithNumericPropertyDefinition() throws RepositoryException {
assertQueryWithLongValue(13, "");
assertQueryWithLongValue(2, "WHERE [car:userRating] = 3");
assertQueryWithLongValue(1, "WHERE [car:userRating] < 3");
assertQueryWithLongValue(8, "WHERE [car:userRating] > 3");
assertQueryWithLongValue(3, "WHERE [car:userRating] <= 3");
assertQueryWithLongValue(10, "WHERE [car:userRating] >= 3");
assertQueryWithLongValue(9, "WHERE [car:userRating] <> 3");
assertQueryWithLongValue(9, "WHERE [car:userRating] != 3");
}
@FixFor( "MODE-1057" )
@Test
public void shouldAllowEqualityStringCriteriaOnPropertyDefinedWithNumericPropertyDefinition() throws RepositoryException {
assertQueryWithLongValue(13, "");
assertQueryWithLongValue(2, "WHERE [car:userRating] = '3'");
assertQueryWithLongValue(1, "WHERE [car:userRating] < '3'");
assertQueryWithLongValue(8, "WHERE [car:userRating] > '3'");
assertQueryWithLongValue(3, "WHERE [car:userRating] <= '3'");
assertQueryWithLongValue(10, "WHERE [car:userRating] >= '3'");
assertQueryWithLongValue(9, "WHERE [car:userRating] <> '3'");
assertQueryWithLongValue(9, "WHERE [car:userRating] != '3'");
}
protected void assertQueryWithLongValue( int numResults,
String criteria ) throws RepositoryException {
String[] columnNames = {"car:maker", "car:model", "car:year", "car:userRating"};
String queryStr = "SELECT [car:maker], [car:model], [car:year], [car:userRating] FROM [car:Car] AS car " + criteria;
Query query = session.getWorkspace().getQueryManager().createQuery(queryStr, Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, numResults);
assertResultsHaveColumns(result, columnNames);
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllCarsUnderHybrid() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT car.[car:maker], car.[car:model], car.[car:year], car.[car:msrp] FROM [car:Car] AS car WHERE PATH(car) LIKE '%/Hybrid/%'",
Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 3L);
assertResultsHaveColumns(result, "car:maker", "car:model", "car:year", "car:msrp");
assertRow(result).has("car:model", "Altima").and("car:msrp", "$18,260").and("car:year", 2008);
assertRow(result).has("car:model", "Highlander").and("car:msrp", "$34,200").and("car:year", 2008);
assertRow(result).has("car:model", "Prius").and("car:msrp", "$21,500").and("car:year", 2008);
}
@FixFor( "MODE-1824" )
@Test
public void shouldBeAbleToExecuteQueryWithTwoColumns() throws RepositoryException {
QueryManager queryManager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = queryManager.getQOMFactory();
Selector car1Selector = factory.selector("car:Car", "car1");
Selector car2Selector = factory.selector("car:Car", "car2");
Join join = factory.join(car1Selector,
car2Selector,
QueryObjectModelConstants.JCR_JOIN_TYPE_INNER,
factory.equiJoinCondition("car1", "car:maker", "car2", "car:maker"));
Column[] columns = new Column[] {factory.column("car1", "car:maker", "maker"),
factory.column("car2", "car:model", "model")};
Query query = factory.createQuery(join, null, null, columns);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 21L);
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryToFindAllCarsUnderHybridWithOrderBy() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT car.[car:maker], car.[car:model], car.[car:year], car.[car:msrp] FROM [car:Car] AS car WHERE PATH(car) LIKE '%/Hybrid/%' ORDER BY [jcr:name]",
Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 3L);
assertResultsHaveColumns(result, "car:maker", "jcr:name", "car:model", "car:year", "car:msrp");
assertRow(result, 1).has("car:model", "Altima").and("car:msrp", "$18,260").and("car:year", 2008);
assertRow(result, 2).has("car:model", "Highlander").and("car:msrp", "$34,200").and("car:year", 2008);
assertRow(result, 3).has("car:model", "Prius").and("car:msrp", "$21,500").and("car:year", 2008);
}
@Test
public void shouldBeAbleToCreateAndExecuteJcrSql2QueryUsingJoinToFindAllCarsUnderHybrid() throws RepositoryException {
Query query = session.getWorkspace()
.getQueryManager()
.createQuery("SELECT car.[car:maker], car.[car:model], car.[car:year], car.[car:msrp] FROM [car:Car] AS car JOIN [nt:unstructured] AS hybrid ON ISCHILDNODE(car,hybrid) WHERE NAME(hybrid) = 'Hybrid'",
Query.JCR_SQL2);
assertThat(query, is(notNullValue()));
QueryResult result = query.execute();
assertThat(result, is(notNullValue()));
assertResults(query, result, 3L);
assertResultsHaveColumns(result, "car.car:maker", "car.car:model", "car.car:year", "car.car:msrp");
assertRow(result).has("car:model", "Altima").and("car.car:msrp", "$18,260").and("car.car:year", 2008);
assertRow(result).has("car:model", "Highlander").and("car.car:msrp", "$34,200").and("car.car:year", 2008);
assertRow(result).has("car:model", "Prius").and("car.car:msrp", "$21,500").and("car.car:year", 2008);
}
@FixFor( "MODE-1825" )
@Test
public void shouldBeAbleToExecuteQueryForAllColumns() throws RepositoryException {
QueryManager queryManager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = queryManager.getQOMFactory();
Selector car1Selector = factory.selector("car:Car", "car1");
Selector car2Selector = factory.selector("car:Car", "car2");
Join join = factory.join(car1Selector,
car2Selector,
QueryObjectModelConstants.JCR_JOIN_TYPE_INNER,
factory.equiJoinCondition("car1", "car:maker", "car2", "car:maker"));
Column[] columns = new Column[] {factory.column("car1", null, null)};
Constraint constraint = factory.comparison(factory.propertyValue("car1", "car:maker"),
QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO,