private static < S extends Storable > String [ ] selectNaturalOrder ( Repository repo , Class < S > type , Filter < S > filter ) throws RepositoryException { if ( ! filter . isOpen ( ) && repo instanceof RepositoryAccess ) { UnionQueryAnalyzer . Result result = new UnionQueryAnalyzer ( type , ( RepositoryAccess ) repo ) . analyze ( filter , null , QueryHints . emptyHints ( ) . with ( QueryHint . CONSUME_SLICE ) ) ; OrderingList < S > ordering = result . getTotalOrdering ( ) ; if ( ordering == null ) { List < IndexedQueryAnalyzer . Result > list = result . getSubResults ( ) ; if ( ! list . isEmpty ( ) ) { StorableIndex < S > index = list . get ( 0 ) . getLocalIndex ( ) ; if ( index != null ) { ordering = OrderingList . get ( index . getOrderedProperties ( ) ) ; } } } if ( ordering != null ) { String [ ] props = new String [ ordering . size ( ) ] ; for ( int i = 0 ; i < props . length ; i ++ ) { props [ i ] = ordering . get ( i ) . toString ( ) ; } return props ; } } IndexInfoCapability capability = repo . getCapability ( IndexInfoCapability . class ) ; if ( capability == null ) { return null ; } IndexInfo info = null ; for ( IndexInfo candidate : capability . getIndexInfo ( type ) ) { if ( candidate . isClustered ( ) ) { info = candidate ; break ; } } if ( info == null ) { return null ; } // Verify index is part of primary key. Set < String > pkSet = StorableIntrospector . examine ( type ) . getPrimaryKeyProperties ( ) . keySet ( ) ; String [ ] propNames = info . getPropertyNames ( ) ; for ( String prop : propNames ) { if ( ! pkSet . contains ( prop ) ) { return null ; } } String [ ] orderBy = new String [ pkSet . size ( ) ] ; Direction [ ] directions = info . getPropertyDirections ( ) ; // Clone to remove elements. pkSet = new LinkedHashSet < String > ( pkSet ) ; int i ; for ( i = 0 ; i < propNames . length ; i ++ ) { orderBy [ i ] = ( ( directions [ i ] == Direction . DESCENDING ) ? "-" : "+" ) + propNames [ i ] ; pkSet . remove ( propNames [ i ] ) ; } // Append any remaining pk properties, to ensure complete ordering. if ( pkSet . size ( ) > 0 ) { for ( String prop : pkSet ) { orderBy [ i ++ ] = prop ; } } return orderBy ; }
Utility method to select the natural ordering of a storage by looking for a clustered index on the primary key . Returns null if no clustered index was found . If a filter is provided the ordering which utilizes the best index is used .