protected static SqlParts sqlToSortIds ( Set < String > docIdSet , List < FieldSort > sortDocument , List < Index > indexes ) throws QueryException { String chosenIndex = chooseIndexForSort ( sortDocument , indexes ) ; if ( chosenIndex == null ) { String msg = String . format ( Locale . ENGLISH , "No single index can satisfy order %s" , sortDocument ) ; logger . log ( Level . SEVERE , msg ) ; throw new QueryException ( msg ) ; } String indexTable = QueryImpl . tableNameForIndex ( chosenIndex ) ; // for small result sets: // SELECT _id FROM idx WHERE _id IN (?, ?) ORDER BY fieldName ASC, fieldName2 DESC // for large result sets: // SELECT _id FROM idx ORDER BY fieldName ASC, fieldName2 DESC List < String > orderClauses = new ArrayList < String > ( ) ; for ( FieldSort clause : sortDocument ) { String fieldName = clause . field ; String direction = clause . sort == FieldSort . Direction . ASCENDING ? "asc" : "desc" ; String orderClause = String . format ( "\"%s\" %s" , fieldName , direction . toUpperCase ( Locale . ENGLISH ) ) ; orderClauses . add ( orderClause ) ; } // If we have few results, it's more efficient to reduce the search space // for SQLite. 500 placeholders should be a safe value. List < String > parameterList = new ArrayList < String > ( ) ; String whereClause = "" ; if ( docIdSet . size ( ) < SMALL_RESULT_SET_SIZE_THRESHOLD ) { List < String > placeholders = new ArrayList < String > ( ) ; for ( String docId : docIdSet ) { placeholders . add ( "?" ) ; parameterList . add ( docId ) ; } whereClause = String . format ( "WHERE _id IN (%s)" , Misc . join ( ", " , placeholders ) ) ; } String orderBy = Misc . join ( ", " , orderClauses ) ; String sql = String . format ( "SELECT DISTINCT _id FROM %s %s ORDER BY %s" , indexTable , whereClause , orderBy ) ; String [ ] parameters = new String [ parameterList . size ( ) ] ; return SqlParts . partsForSql ( sql , parameterList . toArray ( parameters ) ) ; }
Return SQL to get ordered list of docIds .