Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Transitioning from standard SQL to JCR-SQL2 is not straight forward and presents some new challenges. One of the problems I faced when I started to use JCR-SQL2 was how do I select children nodes that have a particular type under a parent node whose ID I know.

To give some more background on this, I have namespaces defined like this:
 Namespaces
'wall' => 'http://travelblog.ws/ns/wall'
'pst' => 'http://travelblog.ws/ns/post'


Further I have a data type, tb:Post, defined like this as a CND file (this is a simplified version based on the actual definition):
 Data Type
<tb = 'http://travelblog.ws/ns'>
[tb:Post]
- tb:text (string)
- tb:postDate (date) mandatory


The tb:Post data type is used to create child nodes in the 'pst' namespace. These are attached to a parent node in the 'wall' namespace. The data looks something like this:
 Data
/ (root)
+-- wall:1
| +-- pst:1
| +-- pst:2
| ...
+-- wall:2
| +-- pst:3
| ...




So what I wanted to do was select all of the child nodes for say the wall:1 parent. I also wanted to do some sorting based on a property defined in tb:Post, tb:postDate in my case. Getting all the child nodes is simple if you have the parent node already, simply call getNodes() and you're done, but that doesn't sort your results, it also won't let you limit how much data is returned for paging purposes.

So we get to the JCR-SQL2 statement that will meet all of the above criteria...
 JCR=SQL2
SELECT * FROM [tb:Post] AS posts
WHERE posts.[jcr:path] LIKE '/wall:1/%'
ORDER BY tb:postDate DESC;


The above is a bit unintuitive at first because you're selecting from a data type?! Remember JCR doesn't define tables so in that context it makes sense. The where clause filters the data for the parent node using the ID of the parent and the jcr:path pseudo-property. The the sorting is done by tb:postDate.

It looks straight forward after getting it to work!

That simple example can be further built out to include support for pagination by adding the LIMIT clause.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.