001/*
002 * #%L
003 * HAPI FHIR JPA Server
004 * %%
005 * Copyright (C) 2014 - 2025 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.jpa.search.builder;
021
022import ca.uhn.fhir.context.ComboSearchParamType;
023import ca.uhn.fhir.context.FhirContext;
024import ca.uhn.fhir.context.FhirVersionEnum;
025import ca.uhn.fhir.context.RuntimeResourceDefinition;
026import ca.uhn.fhir.context.RuntimeSearchParam;
027import ca.uhn.fhir.i18n.Msg;
028import ca.uhn.fhir.interceptor.api.HookParams;
029import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
030import ca.uhn.fhir.interceptor.api.Pointcut;
031import ca.uhn.fhir.interceptor.model.RequestPartitionId;
032import ca.uhn.fhir.jpa.api.config.JpaStorageSettings;
033import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
034import ca.uhn.fhir.jpa.api.svc.IIdHelperService;
035import ca.uhn.fhir.jpa.api.svc.ResolveIdentityMode;
036import ca.uhn.fhir.jpa.config.HapiFhirLocalContainerEntityManagerFactoryBean;
037import ca.uhn.fhir.jpa.config.HibernatePropertiesProvider;
038import ca.uhn.fhir.jpa.dao.BaseStorageDao;
039import ca.uhn.fhir.jpa.dao.IFulltextSearchSvc;
040import ca.uhn.fhir.jpa.dao.IJpaStorageResourceParser;
041import ca.uhn.fhir.jpa.dao.IResultIterator;
042import ca.uhn.fhir.jpa.dao.ISearchBuilder;
043import ca.uhn.fhir.jpa.dao.data.IResourceHistoryTableDao;
044import ca.uhn.fhir.jpa.dao.data.IResourceHistoryTagDao;
045import ca.uhn.fhir.jpa.dao.data.IResourceTagDao;
046import ca.uhn.fhir.jpa.dao.search.ResourceNotFoundInIndexException;
047import ca.uhn.fhir.jpa.interceptor.JpaPreResourceAccessDetails;
048import ca.uhn.fhir.jpa.model.config.PartitionSettings;
049import ca.uhn.fhir.jpa.model.cross.IResourceLookup;
050import ca.uhn.fhir.jpa.model.dao.JpaPid;
051import ca.uhn.fhir.jpa.model.dao.JpaPidFk;
052import ca.uhn.fhir.jpa.model.entity.BaseResourceIndexedSearchParam;
053import ca.uhn.fhir.jpa.model.entity.BaseTag;
054import ca.uhn.fhir.jpa.model.entity.ResourceHistoryTable;
055import ca.uhn.fhir.jpa.model.entity.ResourceHistoryTablePk;
056import ca.uhn.fhir.jpa.model.entity.ResourceHistoryTag;
057import ca.uhn.fhir.jpa.model.entity.ResourceLink;
058import ca.uhn.fhir.jpa.model.entity.ResourceTag;
059import ca.uhn.fhir.jpa.model.search.SearchBuilderLoadIncludesParameters;
060import ca.uhn.fhir.jpa.model.search.SearchRuntimeDetails;
061import ca.uhn.fhir.jpa.model.search.StorageProcessingMessage;
062import ca.uhn.fhir.jpa.partition.IRequestPartitionHelperSvc;
063import ca.uhn.fhir.jpa.search.SearchConstants;
064import ca.uhn.fhir.jpa.search.builder.models.ResolvedSearchQueryExecutor;
065import ca.uhn.fhir.jpa.search.builder.models.SearchQueryProperties;
066import ca.uhn.fhir.jpa.search.builder.sql.GeneratedSql;
067import ca.uhn.fhir.jpa.search.builder.sql.SearchQueryBuilder;
068import ca.uhn.fhir.jpa.search.builder.sql.SearchQueryExecutor;
069import ca.uhn.fhir.jpa.search.builder.sql.SqlObjectFactory;
070import ca.uhn.fhir.jpa.search.lastn.IElasticsearchSvc;
071import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
072import ca.uhn.fhir.jpa.searchparam.util.Dstu3DistanceHelper;
073import ca.uhn.fhir.jpa.searchparam.util.JpaParamUtil;
074import ca.uhn.fhir.jpa.searchparam.util.LastNParameterHelper;
075import ca.uhn.fhir.jpa.util.BaseIterator;
076import ca.uhn.fhir.jpa.util.CartesianProductUtil;
077import ca.uhn.fhir.jpa.util.CurrentThreadCaptureQueriesListener;
078import ca.uhn.fhir.jpa.util.QueryChunker;
079import ca.uhn.fhir.jpa.util.ScrollableResultsIterator;
080import ca.uhn.fhir.jpa.util.SqlQueryList;
081import ca.uhn.fhir.model.api.IQueryParameterType;
082import ca.uhn.fhir.model.api.Include;
083import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
084import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
085import ca.uhn.fhir.model.valueset.BundleEntrySearchModeEnum;
086import ca.uhn.fhir.rest.api.Constants;
087import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum;
088import ca.uhn.fhir.rest.api.SearchContainedModeEnum;
089import ca.uhn.fhir.rest.api.SortOrderEnum;
090import ca.uhn.fhir.rest.api.SortSpec;
091import ca.uhn.fhir.rest.api.server.IPreResourceAccessDetails;
092import ca.uhn.fhir.rest.api.server.RequestDetails;
093import ca.uhn.fhir.rest.param.BaseParamWithPrefix;
094import ca.uhn.fhir.rest.param.DateParam;
095import ca.uhn.fhir.rest.param.DateRangeParam;
096import ca.uhn.fhir.rest.param.ParamPrefixEnum;
097import ca.uhn.fhir.rest.param.ParameterUtil;
098import ca.uhn.fhir.rest.param.ReferenceParam;
099import ca.uhn.fhir.rest.param.StringParam;
100import ca.uhn.fhir.rest.param.TokenParam;
101import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
102import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
103import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
104import ca.uhn.fhir.rest.server.util.CompositeInterceptorBroadcaster;
105import ca.uhn.fhir.rest.server.util.ISearchParamRegistry;
106import ca.uhn.fhir.system.HapiSystemProperties;
107import ca.uhn.fhir.util.SearchParameterUtil;
108import ca.uhn.fhir.util.StopWatch;
109import ca.uhn.fhir.util.StringUtil;
110import ca.uhn.fhir.util.UrlUtil;
111import com.google.common.annotations.VisibleForTesting;
112import com.google.common.collect.ListMultimap;
113import com.google.common.collect.Lists;
114import com.google.common.collect.MultimapBuilder;
115import com.healthmarketscience.sqlbuilder.Condition;
116import jakarta.annotation.Nonnull;
117import jakarta.annotation.Nullable;
118import jakarta.persistence.EntityManager;
119import jakarta.persistence.PersistenceContext;
120import jakarta.persistence.PersistenceContextType;
121import jakarta.persistence.Query;
122import jakarta.persistence.Tuple;
123import jakarta.persistence.TypedQuery;
124import jakarta.persistence.criteria.CriteriaBuilder;
125import jakarta.persistence.criteria.CriteriaQuery;
126import jakarta.persistence.criteria.Predicate;
127import jakarta.persistence.criteria.Root;
128import jakarta.persistence.criteria.Selection;
129import org.apache.commons.collections4.ListUtils;
130import org.apache.commons.lang3.StringUtils;
131import org.apache.commons.lang3.Validate;
132import org.apache.commons.lang3.math.NumberUtils;
133import org.apache.commons.lang3.tuple.Pair;
134import org.hibernate.ScrollMode;
135import org.hibernate.ScrollableResults;
136import org.hl7.fhir.instance.model.api.IAnyResource;
137import org.hl7.fhir.instance.model.api.IBaseResource;
138import org.hl7.fhir.instance.model.api.IIdType;
139import org.slf4j.Logger;
140import org.slf4j.LoggerFactory;
141import org.springframework.beans.factory.annotation.Autowired;
142import org.springframework.jdbc.core.JdbcTemplate;
143import org.springframework.transaction.support.TransactionSynchronizationManager;
144
145import java.util.ArrayList;
146import java.util.Arrays;
147import java.util.Collection;
148import java.util.Collections;
149import java.util.Comparator;
150import java.util.HashMap;
151import java.util.HashSet;
152import java.util.Iterator;
153import java.util.LinkedList;
154import java.util.List;
155import java.util.Map;
156import java.util.Objects;
157import java.util.Set;
158import java.util.stream.Collectors;
159
160import static ca.uhn.fhir.jpa.model.util.JpaConstants.UNDESIRED_RESOURCE_LINKAGES_FOR_EVERYTHING_ON_PATIENT_INSTANCE;
161import static ca.uhn.fhir.jpa.search.builder.QueryStack.LOCATION_POSITION;
162import static ca.uhn.fhir.jpa.search.builder.QueryStack.SearchForIdsParams.with;
163import static ca.uhn.fhir.jpa.util.InClauseNormalizer.normalizeIdListForInClause;
164import static ca.uhn.fhir.rest.param.ParamPrefixEnum.EQUAL;
165import static java.util.Objects.requireNonNull;
166import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
167import static org.apache.commons.lang3.StringUtils.isBlank;
168import static org.apache.commons.lang3.StringUtils.isNotBlank;
169import static org.apache.commons.lang3.StringUtils.stripStart;
170
171/**
172 * The SearchBuilder is responsible for actually forming the SQL query that handles
173 * searches for resources
174 */
175public class SearchBuilder implements ISearchBuilder<JpaPid> {
176
177        /**
178         * See loadResourcesByPid
179         * for an explanation of why we use the constant 800
180         */
181        // NB: keep public
182        @Deprecated
183        public static final int MAXIMUM_PAGE_SIZE = SearchConstants.MAX_PAGE_SIZE;
184
185        public static final String RESOURCE_ID_ALIAS = "resource_id";
186        public static final String PARTITION_ID_ALIAS = "partition_id";
187        public static final String RESOURCE_VERSION_ALIAS = "resource_version";
188        private static final Logger ourLog = LoggerFactory.getLogger(SearchBuilder.class);
189        private static final JpaPid NO_MORE = JpaPid.fromId(-1L);
190        private static final String MY_SOURCE_RESOURCE_PID = "mySourceResourcePid";
191        private static final String MY_SOURCE_RESOURCE_PARTITION_ID = "myPartitionIdValue";
192        private static final String MY_SOURCE_RESOURCE_TYPE = "mySourceResourceType";
193        private static final String MY_TARGET_RESOURCE_PID = "myTargetResourcePid";
194        private static final String MY_TARGET_RESOURCE_PARTITION_ID = "myTargetResourcePartitionId";
195        private static final String MY_TARGET_RESOURCE_TYPE = "myTargetResourceType";
196        private static final String MY_TARGET_RESOURCE_VERSION = "myTargetResourceVersion";
197        public static final JpaPid[] EMPTY_JPA_PID_ARRAY = new JpaPid[0];
198        public static boolean myUseMaxPageSize50ForTest = false;
199        public static Integer myMaxPageSizeForTests = null;
200        protected final IInterceptorBroadcaster myInterceptorBroadcaster;
201        protected final IResourceTagDao myResourceTagDao;
202        private String myResourceName;
203        private final Class<? extends IBaseResource> myResourceType;
204        private final HapiFhirLocalContainerEntityManagerFactoryBean myEntityManagerFactory;
205        private final SqlObjectFactory mySqlBuilderFactory;
206        private final HibernatePropertiesProvider myDialectProvider;
207        private final ISearchParamRegistry mySearchParamRegistry;
208        private final PartitionSettings myPartitionSettings;
209        private final DaoRegistry myDaoRegistry;
210        private final FhirContext myContext;
211        private final IIdHelperService<JpaPid> myIdHelperService;
212        private final JpaStorageSettings myStorageSettings;
213        private final SearchQueryProperties mySearchProperties;
214        private final IResourceHistoryTableDao myResourceHistoryTableDao;
215        private final IJpaStorageResourceParser myJpaStorageResourceParser;
216
217        @PersistenceContext(type = PersistenceContextType.TRANSACTION)
218        protected EntityManager myEntityManager;
219
220        private CriteriaBuilder myCriteriaBuilder;
221        private SearchParameterMap myParams;
222        private String mySearchUuid;
223        private int myFetchSize;
224
225        private boolean myRequiresTotal;
226
227        /**
228         * @see SearchBuilder#setDeduplicateInDatabase(boolean)
229         */
230        private Set<JpaPid> myPidSet;
231
232        private boolean myHasNextIteratorQuery = false;
233        private RequestPartitionId myRequestPartitionId;
234
235        private IFulltextSearchSvc myFulltextSearchSvc;
236
237        @Autowired(required = false)
238        public void setFullTextSearch(IFulltextSearchSvc theFulltextSearchSvc) {
239                myFulltextSearchSvc = theFulltextSearchSvc;
240        }
241
242        @Autowired(required = false)
243        private IElasticsearchSvc myIElasticsearchSvc;
244
245        @Autowired
246        private IResourceHistoryTagDao myResourceHistoryTagDao;
247
248        @Autowired
249        private IRequestPartitionHelperSvc myPartitionHelperSvc;
250
251        /**
252         * Constructor
253         */
254        @SuppressWarnings({"rawtypes", "unchecked"})
255        public SearchBuilder(
256                        String theResourceName,
257                        JpaStorageSettings theStorageSettings,
258                        HapiFhirLocalContainerEntityManagerFactoryBean theEntityManagerFactory,
259                        SqlObjectFactory theSqlBuilderFactory,
260                        HibernatePropertiesProvider theDialectProvider,
261                        ISearchParamRegistry theSearchParamRegistry,
262                        PartitionSettings thePartitionSettings,
263                        IInterceptorBroadcaster theInterceptorBroadcaster,
264                        IResourceTagDao theResourceTagDao,
265                        DaoRegistry theDaoRegistry,
266                        FhirContext theContext,
267                        IIdHelperService theIdHelperService,
268                        IResourceHistoryTableDao theResourceHistoryTagDao,
269                        IJpaStorageResourceParser theIJpaStorageResourceParser,
270                        Class<? extends IBaseResource> theResourceType) {
271                myResourceName = theResourceName;
272                myResourceType = theResourceType;
273                myStorageSettings = theStorageSettings;
274
275                myEntityManagerFactory = theEntityManagerFactory;
276                mySqlBuilderFactory = theSqlBuilderFactory;
277                myDialectProvider = theDialectProvider;
278                mySearchParamRegistry = theSearchParamRegistry;
279                myPartitionSettings = thePartitionSettings;
280                myInterceptorBroadcaster = theInterceptorBroadcaster;
281                myResourceTagDao = theResourceTagDao;
282                myDaoRegistry = theDaoRegistry;
283                myContext = theContext;
284                myIdHelperService = theIdHelperService;
285                myResourceHistoryTableDao = theResourceHistoryTagDao;
286                myJpaStorageResourceParser = theIJpaStorageResourceParser;
287
288                mySearchProperties = new SearchQueryProperties();
289        }
290
291        @VisibleForTesting
292        void setResourceName(String theName) {
293                myResourceName = theName;
294        }
295
296        @Override
297        public void setMaxResultsToFetch(Integer theMaxResultsToFetch) {
298                mySearchProperties.setMaxResultsRequested(theMaxResultsToFetch);
299        }
300
301        @Override
302        public void setDeduplicateInDatabase(boolean theShouldDeduplicateInDB) {
303                mySearchProperties.setDeduplicateInDatabase(theShouldDeduplicateInDB);
304        }
305
306        @Override
307        public void setRequireTotal(boolean theRequireTotal) {
308                myRequiresTotal = theRequireTotal;
309        }
310
311        @Override
312        public boolean requiresTotal() {
313                return myRequiresTotal;
314        }
315
316        private void searchForIdsWithAndOr(
317                        SearchQueryBuilder theSearchSqlBuilder,
318                        QueryStack theQueryStack,
319                        @Nonnull SearchParameterMap theParams,
320                        RequestDetails theRequest) {
321                myParams = theParams;
322                mySearchProperties.setSortSpec(myParams.getSort());
323
324                // Remove any empty parameters
325                theParams.clean();
326
327                // For DSTU3, pull out near-distance first so when it comes time to evaluate near, we already know the distance
328                if (myContext.getVersion().getVersion() == FhirVersionEnum.DSTU3) {
329                        Dstu3DistanceHelper.setNearDistance(myResourceType, theParams);
330                }
331
332                // Attempt to lookup via composite unique key.
333                if (isCompositeUniqueSpCandidate()) {
334                        attemptComboUniqueSpProcessing(theQueryStack, theParams, theRequest);
335                }
336
337                // Handle _id and _tag last, since they can typically be tacked onto a different parameter
338                List<String> paramNames = myParams.keySet().stream()
339                                .filter(t -> !t.equals(IAnyResource.SP_RES_ID))
340                                .filter(t -> !t.equals(Constants.PARAM_TAG))
341                                .collect(Collectors.toList());
342                if (myParams.containsKey(IAnyResource.SP_RES_ID)) {
343                        paramNames.add(IAnyResource.SP_RES_ID);
344                }
345                if (myParams.containsKey(Constants.PARAM_TAG)) {
346                        paramNames.add(Constants.PARAM_TAG);
347                }
348
349                // Handle each parameter
350                for (String nextParamName : paramNames) {
351                        if (myParams.isLastN() && LastNParameterHelper.isLastNParameter(nextParamName, myContext)) {
352                                // Skip parameters for Subject, Patient, Code and Category for LastN as these will be filtered by
353                                // Elasticsearch
354                                continue;
355                        }
356                        List<List<IQueryParameterType>> andOrParams = myParams.get(nextParamName);
357                        Condition predicate = theQueryStack.searchForIdsWithAndOr(with().setResourceName(myResourceName)
358                                        .setParamName(nextParamName)
359                                        .setAndOrParams(andOrParams)
360                                        .setRequest(theRequest)
361                                        .setRequestPartitionId(myRequestPartitionId)
362                                        .setIncludeDeleted(myParams.getSearchIncludeDeletedMode()));
363                        if (predicate != null) {
364                                theSearchSqlBuilder.addPredicate(predicate);
365                        }
366                }
367        }
368
369        /**
370         * A search is a candidate for Composite Unique SP if unique indexes are enabled, there is no EverythingMode, and the
371         * parameters all have no modifiers.
372         */
373        private boolean isCompositeUniqueSpCandidate() {
374                return myStorageSettings.isUniqueIndexesEnabled() && myParams.getEverythingMode() == null;
375        }
376
377        @SuppressWarnings("ConstantConditions")
378        @Override
379        public Long createCountQuery(
380                        SearchParameterMap theParams,
381                        String theSearchUuid,
382                        RequestDetails theRequest,
383                        @Nonnull RequestPartitionId theRequestPartitionId) {
384
385                assert theRequestPartitionId != null;
386                assert TransactionSynchronizationManager.isActualTransactionActive();
387
388                init(theParams, theSearchUuid, theRequestPartitionId);
389
390                if (checkUseHibernateSearch()) {
391                        return myFulltextSearchSvc.count(myResourceName, theParams.clone());
392                }
393
394                SearchQueryProperties properties = mySearchProperties.clone();
395                properties.setDoCountOnlyFlag(true);
396                properties.setSortSpec(null); // counts don't require sorts
397                properties.setMaxResultsRequested(null);
398                properties.setOffset(null);
399                List<ISearchQueryExecutor> queries = createQuery(theParams.clone(), properties, theRequest, null);
400                if (queries.isEmpty()) {
401                        return 0L;
402                } else {
403                        JpaPid jpaPid = queries.get(0).next();
404                        return jpaPid.getId();
405                }
406        }
407
408        /**
409         * @param thePidSet May be null
410         */
411        @Override
412        public void setPreviouslyAddedResourcePids(@Nonnull List<JpaPid> thePidSet) {
413                myPidSet = new HashSet<>(thePidSet);
414        }
415
416        @SuppressWarnings("ConstantConditions")
417        @Override
418        public IResultIterator<JpaPid> createQuery(
419                        SearchParameterMap theParams,
420                        SearchRuntimeDetails theSearchRuntimeDetails,
421                        RequestDetails theRequest,
422                        @Nonnull RequestPartitionId theRequestPartitionId) {
423                assert theRequestPartitionId != null;
424                assert TransactionSynchronizationManager.isActualTransactionActive();
425
426                init(theParams, theSearchRuntimeDetails.getSearchUuid(), theRequestPartitionId);
427
428                if (myPidSet == null) {
429                        myPidSet = new HashSet<>();
430                }
431
432                return new QueryIterator(theSearchRuntimeDetails, theRequest);
433        }
434
435        private void init(SearchParameterMap theParams, String theSearchUuid, RequestPartitionId theRequestPartitionId) {
436                myCriteriaBuilder = myEntityManager.getCriteriaBuilder();
437                // we mutate the params.  Make a private copy.
438                myParams = theParams.clone();
439                mySearchProperties.setSortSpec(myParams.getSort());
440                mySearchUuid = theSearchUuid;
441                myRequestPartitionId = theRequestPartitionId;
442        }
443
444        /**
445         * The query created can be either a count query or the
446         * actual query.
447         * This is why it takes a SearchQueryProperties object
448         * (and doesn't use the local version of it).
449         * The properties may differ slightly for whichever
450         * query this is.
451         */
452        private List<ISearchQueryExecutor> createQuery(
453                        SearchParameterMap theParams,
454                        SearchQueryProperties theSearchProperties,
455                        RequestDetails theRequest,
456                        SearchRuntimeDetails theSearchRuntimeDetails) {
457                ArrayList<ISearchQueryExecutor> queries = new ArrayList<>();
458
459                if (checkUseHibernateSearch()) {
460                        // we're going to run at least part of the search against the Fulltext service.
461
462                        // Ugh - we have two different return types for now
463                        ISearchQueryExecutor fulltextExecutor = null;
464                        List<JpaPid> fulltextMatchIds = null;
465                        int resultCount = 0;
466                        if (myParams.isLastN()) {
467                                fulltextMatchIds = executeLastNAgainstIndex(theRequest, theSearchProperties.getMaxResultsRequested());
468                                resultCount = fulltextMatchIds.size();
469                        } else if (myParams.getEverythingMode() != null) {
470                                fulltextMatchIds = queryHibernateSearchForEverythingPids(theRequest);
471                                resultCount = fulltextMatchIds.size();
472                        } else {
473                                // todo performance MB - some queries must intersect with JPA (e.g. they have a chain, or we haven't
474                                // enabled SP indexing).
475                                // and some queries don't need JPA.  We only need the scroll when we need to intersect with JPA.
476                                // It would be faster to have a non-scrolled search in this case, since creating the scroll requires
477                                // extra work in Elastic.
478                                // if (eligibleToSkipJPAQuery) fulltextExecutor = myFulltextSearchSvc.searchNotScrolled( ...
479
480                                // we might need to intersect with JPA.  So we might need to traverse ALL results from lucene, not just
481                                // a page.
482                                fulltextExecutor = myFulltextSearchSvc.searchScrolled(myResourceName, myParams, theRequest);
483                        }
484
485                        if (fulltextExecutor == null) {
486                                fulltextExecutor =
487                                                SearchQueryExecutors.from(fulltextMatchIds != null ? fulltextMatchIds : new ArrayList<>());
488                        }
489
490                        if (theSearchRuntimeDetails != null) {
491                                theSearchRuntimeDetails.setFoundIndexMatchesCount(resultCount);
492                                IInterceptorBroadcaster compositeBroadcaster =
493                                                CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, theRequest);
494                                if (compositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_INDEXSEARCH_QUERY_COMPLETE)) {
495                                        HookParams params = new HookParams()
496                                                        .add(RequestDetails.class, theRequest)
497                                                        .addIfMatchesType(ServletRequestDetails.class, theRequest)
498                                                        .add(SearchRuntimeDetails.class, theSearchRuntimeDetails);
499                                        compositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_INDEXSEARCH_QUERY_COMPLETE, params);
500                                }
501                        }
502
503                        // can we skip the database entirely and return the pid list from here?
504                        boolean canSkipDatabase =
505                                        // if we processed an AND clause, and it returned nothing, then nothing can match.
506                                        !fulltextExecutor.hasNext()
507                                                        ||
508                                                        // Our hibernate search query doesn't respect partitions yet
509                                                        (!myPartitionSettings.isPartitioningEnabled()
510                                                                        &&
511                                                                        // were there AND terms left?  Then we still need the db.
512                                                                        theParams.isEmpty()
513                                                                        &&
514                                                                        // not every param is a param. :-(
515                                                                        theParams.getNearDistanceParam() == null
516                                                                        &&
517                                                                        // todo MB don't we support _lastUpdated and _offset now?
518                                                                        theParams.getLastUpdated() == null
519                                                                        && theParams.getEverythingMode() == null
520                                                                        && theParams.getOffset() == null);
521
522                        if (canSkipDatabase) {
523                                ourLog.trace("Query finished after HSearch.  Skip db query phase");
524                                if (theSearchProperties.hasMaxResultsRequested()) {
525                                        fulltextExecutor = SearchQueryExecutors.limited(
526                                                        fulltextExecutor, theSearchProperties.getMaxResultsRequested());
527                                }
528                                queries.add(fulltextExecutor);
529                        } else {
530                                ourLog.trace("Query needs db after HSearch.  Chunking.");
531                                // Finish the query in the database for the rest of the search parameters, sorting, partitioning, etc.
532                                // We break the pids into chunks that fit in the 1k limit for jdbc bind params.
533                                QueryChunker.chunk(
534                                                fulltextExecutor,
535                                                SearchBuilder.getMaximumPageSize(),
536                                                // for each list of (SearchBuilder.getMaximumPageSize())
537                                                // we create a chunked query and add it to 'queries'
538                                                t -> doCreateChunkedQueries(theParams, t, theSearchProperties, theRequest, queries));
539                        }
540                } else {
541                        // do everything in the database.
542                        createChunkedQuery(theParams, theSearchProperties, theRequest, null, queries);
543                }
544
545                return queries;
546        }
547
548        /**
549         * Check to see if query should use Hibernate Search, and error if the query can't continue.
550         *
551         * @return true if the query should first be processed by Hibernate Search
552         * @throws InvalidRequestException if fulltext search is not enabled but the query requires it - _content or _text
553         */
554        private boolean checkUseHibernateSearch() {
555                boolean fulltextEnabled = (myFulltextSearchSvc != null) && !myFulltextSearchSvc.isDisabled();
556
557                if (!fulltextEnabled) {
558                        failIfUsed(Constants.PARAM_TEXT);
559                        failIfUsed(Constants.PARAM_CONTENT);
560                } else {
561                        for (SortSpec sortSpec : myParams.getAllChainsInOrder()) {
562                                final String paramName = sortSpec.getParamName();
563                                if (paramName.contains(".")) {
564                                        failIfUsedWithChainedSort(Constants.PARAM_TEXT);
565                                        failIfUsedWithChainedSort(Constants.PARAM_CONTENT);
566                                }
567                        }
568                }
569
570                // someday we'll want a query planner to figure out if we _should_ or _must_ use the ft index, not just if we
571                // can.
572                return fulltextEnabled
573                                && myParams != null
574                                && myParams.getSearchContainedMode() == SearchContainedModeEnum.FALSE
575                                && myFulltextSearchSvc.canUseHibernateSearch(myResourceName, myParams)
576                                && myFulltextSearchSvc.supportsAllSortTerms(myResourceName, myParams);
577        }
578
579        private void failIfUsed(String theParamName) {
580                if (myParams.containsKey(theParamName)) {
581                        throw new InvalidRequestException(Msg.code(1192)
582                                        + "Fulltext search is not enabled on this service, can not process parameter: " + theParamName);
583                }
584        }
585
586        private void failIfUsedWithChainedSort(String theParamName) {
587                if (myParams.containsKey(theParamName)) {
588                        throw new InvalidRequestException(Msg.code(2524)
589                                        + "Fulltext search combined with chained sorts are not supported, can not process parameter: "
590                                        + theParamName);
591                }
592        }
593
594        private List<JpaPid> executeLastNAgainstIndex(RequestDetails theRequestDetails, Integer theMaximumResults) {
595                // Can we use our hibernate search generated index on resource to support lastN?:
596                if (myStorageSettings.isHibernateSearchIndexSearchParams()) {
597                        if (myFulltextSearchSvc == null) {
598                                throw new InvalidRequestException(Msg.code(2027)
599                                                + "LastN operation is not enabled on this service, can not process this request");
600                        }
601                        return myFulltextSearchSvc.lastN(myParams, theMaximumResults).stream()
602                                        .map(t -> (JpaPid) t)
603                                        .collect(Collectors.toList());
604                } else {
605                        throw new InvalidRequestException(
606                                        Msg.code(2033) + "LastN operation is not enabled on this service, can not process this request");
607                }
608        }
609
610        private List<JpaPid> queryHibernateSearchForEverythingPids(RequestDetails theRequestDetails) {
611                JpaPid pid = null;
612                if (myParams.get(IAnyResource.SP_RES_ID) != null) {
613                        String idParamValue;
614                        IQueryParameterType idParam =
615                                        myParams.get(IAnyResource.SP_RES_ID).get(0).get(0);
616                        if (idParam instanceof TokenParam idParm) {
617                                idParamValue = idParm.getValue();
618                        } else {
619                                StringParam idParm = (StringParam) idParam;
620                                idParamValue = idParm.getValue();
621                        }
622
623                        pid = myIdHelperService
624                                        .resolveResourceIdentity(
625                                                        myRequestPartitionId,
626                                                        myResourceName,
627                                                        idParamValue,
628                                                        ResolveIdentityMode.includeDeleted().cacheOk())
629                                        .getPersistentId();
630                }
631                return myFulltextSearchSvc.everything(myResourceName, myParams, pid, theRequestDetails);
632        }
633
634        private void doCreateChunkedQueries(
635                        SearchParameterMap theParams,
636                        List<JpaPid> thePids,
637                        SearchQueryProperties theSearchQueryProperties,
638                        RequestDetails theRequest,
639                        ArrayList<ISearchQueryExecutor> theQueries) {
640
641                if (thePids.size() < getMaximumPageSize()) {
642                        thePids = normalizeIdListForInClause(thePids);
643                }
644                theSearchQueryProperties.setMaxResultsRequested(thePids.size());
645                createChunkedQuery(theParams, theSearchQueryProperties, theRequest, thePids, theQueries);
646        }
647
648        /**
649         * Combs through the params for any _id parameters and extracts the PIDs for them
650         */
651        private void extractTargetPidsFromIdParams(Set<JpaPid> theTargetPids) {
652                // get all the IQueryParameterType objects
653                // for _id -> these should all be StringParam values
654                HashSet<IIdType> ids = new HashSet<>();
655                List<List<IQueryParameterType>> params = myParams.get(IAnyResource.SP_RES_ID);
656                for (List<IQueryParameterType> paramList : params) {
657                        for (IQueryParameterType param : paramList) {
658                                String id;
659                                if (param instanceof StringParam) {
660                                        // we expect all _id values to be StringParams
661                                        id = ((StringParam) param).getValue();
662                                } else if (param instanceof TokenParam) {
663                                        id = ((TokenParam) param).getValue();
664                                } else {
665                                        // we do not expect the _id parameter to be a non-string value
666                                        throw new IllegalArgumentException(
667                                                        Msg.code(1193) + "_id parameter must be a StringParam or TokenParam");
668                                }
669
670                                IIdType idType = myContext.getVersion().newIdType();
671                                if (id.contains("/")) {
672                                        idType.setValue(id);
673                                } else {
674                                        idType.setValue(myResourceName + "/" + id);
675                                }
676                                ids.add(idType);
677                        }
678                }
679
680                // fetch our target Pids
681                // this will throw if an id is not found
682                Map<IIdType, IResourceLookup<JpaPid>> idToIdentity = myIdHelperService.resolveResourceIdentities(
683                                myRequestPartitionId,
684                                new ArrayList<>(ids),
685                                ResolveIdentityMode.failOnDeleted().noCacheUnlessDeletesDisabled());
686
687                // add the pids to targetPids
688                for (IResourceLookup<JpaPid> pid : idToIdentity.values()) {
689                        theTargetPids.add(pid.getPersistentId());
690                }
691        }
692
693        private void createChunkedQuery(
694                        SearchParameterMap theParams,
695                        SearchQueryProperties theSearchProperties,
696                        RequestDetails theRequest,
697                        List<JpaPid> thePidList,
698                        List<ISearchQueryExecutor> theSearchQueryExecutors) {
699                if (myParams.getEverythingMode() != null) {
700                        createChunkedQueryForEverythingSearch(
701                                        theRequest, theParams, theSearchProperties, thePidList, theSearchQueryExecutors);
702                } else {
703                        createChunkedQueryNormalSearch(
704                                        theParams, theSearchProperties, theRequest, thePidList, theSearchQueryExecutors);
705                }
706        }
707
708        private void createChunkedQueryNormalSearch(
709                        SearchParameterMap theParams,
710                        SearchQueryProperties theSearchProperties,
711                        RequestDetails theRequest,
712                        List<JpaPid> thePidList,
713                        List<ISearchQueryExecutor> theSearchQueryExecutors) {
714                SearchQueryBuilder sqlBuilder = new SearchQueryBuilder(
715                                myContext,
716                                myStorageSettings,
717                                myPartitionSettings,
718                                myRequestPartitionId,
719                                myResourceName,
720                                mySqlBuilderFactory,
721                                myDialectProvider,
722                                theSearchProperties.isDoCountOnlyFlag(),
723                                myResourceName == null || myResourceName.isBlank());
724                QueryStack queryStack3 = new QueryStack(
725                                theRequest,
726                                theParams,
727                                myStorageSettings,
728                                myContext,
729                                sqlBuilder,
730                                mySearchParamRegistry,
731                                myPartitionSettings);
732
733                if (theParams.keySet().size() > 1
734                                || theParams.getSort() != null
735                                || theParams.keySet().contains(Constants.PARAM_HAS)
736                                || isPotentiallyContainedReferenceParameterExistsAtRoot(theParams)) {
737                        List<RuntimeSearchParam> activeComboParams = mySearchParamRegistry.getActiveComboSearchParams(
738                                        myResourceName, theParams.keySet(), ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
739                        if (activeComboParams.isEmpty()) {
740                                sqlBuilder.setNeedResourceTableRoot(true);
741                        }
742                }
743
744                /*
745                 * If we're doing a filter, always use the resource table as the root - This avoids the possibility of
746                 * specific filters with ORs as their root from working around the natural resource type / deletion
747                 * status / partition IDs built into queries.
748                 */
749                if (theParams.containsKey(Constants.PARAM_FILTER)) {
750                        Condition partitionIdPredicate = sqlBuilder
751                                        .getOrCreateResourceTablePredicateBuilder()
752                                        .createPartitionIdPredicate(myRequestPartitionId);
753                        if (partitionIdPredicate != null) {
754                                sqlBuilder.addPredicate(partitionIdPredicate);
755                        }
756                }
757
758                // Normal search
759                // we will create a resourceTablePredicate if and only if we have an _id SP.
760                searchForIdsWithAndOr(sqlBuilder, queryStack3, myParams, theRequest);
761
762                // If we haven't added any predicates yet, we're doing a search for all resources. Make sure we add the
763                // partition ID predicate in that case.
764                if (!sqlBuilder.haveAtLeastOnePredicate()) {
765                        Condition partitionIdPredicate;
766
767                        if (theParams.getSearchIncludeDeletedMode() != null) {
768                                partitionIdPredicate = sqlBuilder
769                                                .getOrCreateResourceTablePredicateBuilder(true, theParams.getSearchIncludeDeletedMode())
770                                                .createPartitionIdPredicate(myRequestPartitionId);
771                        } else {
772                                partitionIdPredicate = sqlBuilder
773                                                .getOrCreateResourceTablePredicateBuilder()
774                                                .createPartitionIdPredicate(myRequestPartitionId);
775                        }
776
777                        if (partitionIdPredicate != null) {
778                                sqlBuilder.addPredicate(partitionIdPredicate);
779                        }
780                }
781
782                // Add PID list predicate for full text search and/or lastn operation
783                addPidListPredicate(thePidList, sqlBuilder);
784
785                // Last updated
786                addLastUpdatePredicate(sqlBuilder);
787
788                /*
789                 * Exclude the pids already in the previous iterator. This is an optimization, as opposed
790                 * to something needed to guarantee correct results.
791                 *
792                 * Why do we need it? Suppose for example, a query like:
793                 *    Observation?category=foo,bar,baz
794                 * And suppose you have many resources that have all 3 of these category codes. In this case
795                 * the SQL query will probably return the same PIDs multiple times, and if this happens enough
796                 * we may exhaust the query results without getting enough distinct results back. When that
797                 * happens we re-run the query with a larger limit. Excluding results we already know about
798                 * tries to ensure that we get new unique results.
799                 *
800                 * The challenge with that though is that lots of DBs have an issue with too many
801                 * parameters in one query. So we only do this optimization if there aren't too
802                 * many results.
803                 */
804                if (myHasNextIteratorQuery) {
805                        if (myPidSet.size() + sqlBuilder.countBindVariables() < 900) {
806                                sqlBuilder.excludeResourceIdsPredicate(myPidSet);
807                        }
808                }
809
810                /*
811                 * If offset is present, we want to deduplicate the results by using GROUP BY;
812                 * OR
813                 * if the MaxResultsToFetch is null, we are requesting "everything",
814                 * so we'll let the db do the deduplication (instead of in-memory)
815                 */
816                if (theSearchProperties.isDeduplicateInDatabase()) {
817                        queryStack3.addGrouping();
818                        queryStack3.setUseAggregate(true);
819                }
820
821                /*
822                 * Sort
823                 *
824                 * If we have a sort, we wrap the criteria search (the search that actually
825                 * finds the appropriate resources) in an outer search which is then sorted
826                 */
827                if (theSearchProperties.hasSort()) {
828                        assert !theSearchProperties.isDoCountOnlyFlag();
829
830                        createSort(queryStack3, theSearchProperties.getSortSpec(), theParams);
831                }
832
833                /*
834                 * Now perform the search
835                 */
836                executeSearch(theSearchProperties, theSearchQueryExecutors, sqlBuilder);
837        }
838
839        private void executeSearch(
840                        SearchQueryProperties theProperties,
841                        List<ISearchQueryExecutor> theSearchQueryExecutors,
842                        SearchQueryBuilder sqlBuilder) {
843                GeneratedSql generatedSql =
844                                sqlBuilder.generate(theProperties.getOffset(), theProperties.getMaxResultsRequested());
845                if (!generatedSql.isMatchNothing()) {
846                        SearchQueryExecutor executor =
847                                        mySqlBuilderFactory.newSearchQueryExecutor(generatedSql, theProperties.getMaxResultsRequested());
848                        theSearchQueryExecutors.add(executor);
849                }
850        }
851
852        private void createChunkedQueryForEverythingSearch(
853                        RequestDetails theRequest,
854                        SearchParameterMap theParams,
855                        SearchQueryProperties theSearchQueryProperties,
856                        List<JpaPid> thePidList,
857                        List<ISearchQueryExecutor> theSearchQueryExecutors) {
858
859                SearchQueryBuilder sqlBuilder = new SearchQueryBuilder(
860                                myContext,
861                                myStorageSettings,
862                                myPartitionSettings,
863                                myRequestPartitionId,
864                                null,
865                                mySqlBuilderFactory,
866                                myDialectProvider,
867                                theSearchQueryProperties.isDoCountOnlyFlag(),
868                                false);
869
870                QueryStack queryStack3 = new QueryStack(
871                                theRequest,
872                                theParams,
873                                myStorageSettings,
874                                myContext,
875                                sqlBuilder,
876                                mySearchParamRegistry,
877                                myPartitionSettings);
878
879                JdbcTemplate jdbcTemplate = initializeJdbcTemplate(theSearchQueryProperties.getMaxResultsRequested());
880
881                Set<JpaPid> targetPids = new HashSet<>();
882                if (myParams.get(IAnyResource.SP_RES_ID) != null) {
883
884                        extractTargetPidsFromIdParams(targetPids);
885
886                        // add the target pids to our executors as the first
887                        // results iterator to go through
888                        theSearchQueryExecutors.add(new ResolvedSearchQueryExecutor(new ArrayList<>(targetPids)));
889                } else {
890                        // For Everything queries, we make the query root by the ResourceLink table, since this query
891                        // is basically a reverse-include search. For type/Everything (as opposed to instance/Everything)
892                        // the one problem with this approach is that it doesn't catch Patients that have absolutely
893                        // nothing linked to them. So we do one additional query to make sure we catch those too.
894                        SearchQueryBuilder fetchPidsSqlBuilder = new SearchQueryBuilder(
895                                        myContext,
896                                        myStorageSettings,
897                                        myPartitionSettings,
898                                        myRequestPartitionId,
899                                        myResourceName,
900                                        mySqlBuilderFactory,
901                                        myDialectProvider,
902                                        theSearchQueryProperties.isDoCountOnlyFlag(),
903                                        false);
904                        GeneratedSql allTargetsSql = fetchPidsSqlBuilder.generate(
905                                        theSearchQueryProperties.getOffset(), mySearchProperties.getMaxResultsRequested());
906                        String sql = allTargetsSql.getSql();
907                        Object[] args = allTargetsSql.getBindVariables().toArray(new Object[0]);
908
909                        List<JpaPid> output =
910                                        jdbcTemplate.query(sql, args, new JpaPidRowMapper(myPartitionSettings.isPartitioningEnabled()));
911
912                        // we add a search executor to fetch unlinked patients first
913                        theSearchQueryExecutors.add(new ResolvedSearchQueryExecutor(output));
914                }
915
916                List<String> typeSourceResources = new ArrayList<>();
917                if (myParams.get(Constants.PARAM_TYPE) != null) {
918                        typeSourceResources.addAll(extractTypeSourceResourcesFromParams());
919                }
920
921                queryStack3.addPredicateEverythingOperation(
922                                myResourceName, typeSourceResources, targetPids.toArray(EMPTY_JPA_PID_ARRAY));
923
924                // Add PID list predicate for full text search and/or lastn operation
925                addPidListPredicate(thePidList, sqlBuilder);
926
927                /*
928                 * If offset is present, we want deduplicate the results by using GROUP BY
929                 * ORDER BY is required to make sure we return unique results for each page
930                 */
931                if (theSearchQueryProperties.hasOffset()) {
932                        queryStack3.addGrouping();
933                        queryStack3.addOrdering();
934                        queryStack3.setUseAggregate(true);
935                }
936
937                if (myParams.getEverythingMode().isPatient()) {
938                        /*
939                         * NB: patient-compartment limitation
940                         *
941                         * We are manually excluding Group and List resources
942                         * from the patient-compartment for $everything operations on Patient type/instance.
943                         *
944                         * See issue: https://github.com/hapifhir/hapi-fhir/issues/7118
945                         */
946                        sqlBuilder.excludeResourceTypesPredicate(
947                                        SearchParameterUtil.RESOURCE_TYPES_TO_SP_TO_OMIT_FROM_PATIENT_COMPARTMENT.keySet());
948                }
949
950                /*
951                 * Now perform the search
952                 */
953                executeSearch(theSearchQueryProperties, theSearchQueryExecutors, sqlBuilder);
954        }
955
956        private void addPidListPredicate(List<JpaPid> thePidList, SearchQueryBuilder theSqlBuilder) {
957                if (thePidList != null && !thePidList.isEmpty()) {
958                        theSqlBuilder.addResourceIdsPredicate(thePidList);
959                }
960        }
961
962        private void addLastUpdatePredicate(SearchQueryBuilder theSqlBuilder) {
963                DateRangeParam lu = myParams.getLastUpdated();
964                if (lu != null && !lu.isEmpty()) {
965                        Condition lastUpdatedPredicates = theSqlBuilder.addPredicateLastUpdated(lu);
966                        theSqlBuilder.addPredicate(lastUpdatedPredicates);
967                }
968        }
969
970        private JdbcTemplate initializeJdbcTemplate(Integer theMaximumResults) {
971                JdbcTemplate jdbcTemplate = new JdbcTemplate(myEntityManagerFactory.getDataSource());
972                jdbcTemplate.setFetchSize(myFetchSize);
973                if (theMaximumResults != null) {
974                        jdbcTemplate.setMaxRows(theMaximumResults);
975                }
976                return jdbcTemplate;
977        }
978
979        private Collection<String> extractTypeSourceResourcesFromParams() {
980
981                List<List<IQueryParameterType>> listOfList = myParams.get(Constants.PARAM_TYPE);
982
983                // first off, let's flatten the list of list
984                List<IQueryParameterType> iQueryParameterTypesList =
985                                listOfList.stream().flatMap(List::stream).collect(Collectors.toList());
986
987                // then, extract all elements of each CSV into one big list
988                List<String> resourceTypes = iQueryParameterTypesList.stream()
989                                .map(param -> ((StringParam) param).getValue())
990                                .map(csvString -> List.of(csvString.split(",")))
991                                .flatMap(List::stream)
992                                .collect(Collectors.toList());
993
994                Set<String> knownResourceTypes = myContext.getResourceTypes();
995
996                // remove leading/trailing whitespaces if any and remove duplicates
997                Set<String> retVal = new HashSet<>();
998
999                for (String type : resourceTypes) {
1000                        String trimmed = type.trim();
1001                        if (!knownResourceTypes.contains(trimmed)) {
1002                                throw new ResourceNotFoundException(
1003                                                Msg.code(2197) + "Unknown resource type '" + trimmed + "' in _type parameter.");
1004                        }
1005                        retVal.add(trimmed);
1006                }
1007
1008                return retVal;
1009        }
1010
1011        private boolean isPotentiallyContainedReferenceParameterExistsAtRoot(SearchParameterMap theParams) {
1012                return myStorageSettings.isIndexOnContainedResources()
1013                                && theParams.values().stream()
1014                                                .flatMap(Collection::stream)
1015                                                .flatMap(Collection::stream)
1016                                                .anyMatch(ReferenceParam.class::isInstance);
1017        }
1018
1019        private void createSort(QueryStack theQueryStack, SortSpec theSort, SearchParameterMap theParams) {
1020                if (theSort == null || isBlank(theSort.getParamName())) {
1021                        return;
1022                }
1023
1024                boolean ascending = (theSort.getOrder() == null) || (theSort.getOrder() == SortOrderEnum.ASC);
1025
1026                if (IAnyResource.SP_RES_ID.equals(theSort.getParamName())) {
1027
1028                        theQueryStack.addSortOnResourceId(ascending);
1029
1030                } else if (Constants.PARAM_PID.equals(theSort.getParamName())) {
1031
1032                        theQueryStack.addSortOnResourcePID(ascending);
1033
1034                } else if (Constants.PARAM_LASTUPDATED.equals(theSort.getParamName())) {
1035
1036                        theQueryStack.addSortOnLastUpdated(ascending);
1037
1038                } else {
1039                        RuntimeSearchParam param = mySearchParamRegistry.getActiveSearchParam(
1040                                        myResourceName, theSort.getParamName(), ISearchParamRegistry.SearchParamLookupContextEnum.SORT);
1041
1042                        /*
1043                         * If we have a sort like _sort=subject.name and we  have an
1044                         * uplifted refchain for that combination we can do it more efficiently
1045                         * by using the index associated with the uplifted refchain. In this case,
1046                         * we need to find the actual target search parameter (corresponding
1047                         * to "name" in this example) so that we know what datatype it is.
1048                         */
1049                        String paramName = theSort.getParamName();
1050                        if (param == null && myStorageSettings.isIndexOnUpliftedRefchains()) {
1051                                String[] chains = StringUtils.split(paramName, '.');
1052                                if (chains.length == 2) {
1053
1054                                        // Given: Encounter?_sort=Patient:subject.name
1055                                        String referenceParam = chains[0]; // subject
1056                                        String referenceParamTargetType = null; // Patient
1057                                        String targetParam = chains[1]; // name
1058
1059                                        int colonIdx = referenceParam.indexOf(':');
1060                                        if (colonIdx > -1) {
1061                                                referenceParamTargetType = referenceParam.substring(0, colonIdx);
1062                                                referenceParam = referenceParam.substring(colonIdx + 1);
1063                                        }
1064                                        RuntimeSearchParam outerParam = mySearchParamRegistry.getActiveSearchParam(
1065                                                        myResourceName, referenceParam, ISearchParamRegistry.SearchParamLookupContextEnum.SORT);
1066                                        if (outerParam == null) {
1067                                                throwInvalidRequestExceptionForUnknownSortParameter(myResourceName, referenceParam);
1068                                        } else if (outerParam.hasUpliftRefchain(targetParam)) {
1069                                                for (String nextTargetType : outerParam.getTargets()) {
1070                                                        if (referenceParamTargetType != null && !referenceParamTargetType.equals(nextTargetType)) {
1071                                                                continue;
1072                                                        }
1073                                                        RuntimeSearchParam innerParam = mySearchParamRegistry.getActiveSearchParam(
1074                                                                        nextTargetType,
1075                                                                        targetParam,
1076                                                                        ISearchParamRegistry.SearchParamLookupContextEnum.SORT);
1077                                                        if (innerParam != null) {
1078                                                                param = innerParam;
1079                                                                break;
1080                                                        }
1081                                                }
1082                                        }
1083                                }
1084                        }
1085
1086                        int colonIdx = paramName.indexOf(':');
1087                        String referenceTargetType = null;
1088                        if (colonIdx > -1) {
1089                                referenceTargetType = paramName.substring(0, colonIdx);
1090                                paramName = paramName.substring(colonIdx + 1);
1091                        }
1092
1093                        int dotIdx = paramName.indexOf('.');
1094                        String chainName = null;
1095                        if (param == null && dotIdx > -1) {
1096                                chainName = paramName.substring(dotIdx + 1);
1097                                paramName = paramName.substring(0, dotIdx);
1098                                if (chainName.contains(".")) {
1099                                        String msg = myContext
1100                                                        .getLocalizer()
1101                                                        .getMessageSanitized(
1102                                                                        BaseStorageDao.class,
1103                                                                        "invalidSortParameterTooManyChains",
1104                                                                        paramName + "." + chainName);
1105                                        throw new InvalidRequestException(Msg.code(2286) + msg);
1106                                }
1107                        }
1108
1109                        if (param == null) {
1110                                param = mySearchParamRegistry.getActiveSearchParam(
1111                                                myResourceName, paramName, ISearchParamRegistry.SearchParamLookupContextEnum.SORT);
1112                        }
1113
1114                        if (param == null) {
1115                                throwInvalidRequestExceptionForUnknownSortParameter(getResourceName(), paramName);
1116                        }
1117
1118                        // param will never be null here (the above line throws if it does)
1119                        // this is just to prevent the warning
1120                        assert param != null;
1121                        if (isNotBlank(chainName) && param.getParamType() != RestSearchParameterTypeEnum.REFERENCE) {
1122                                throw new InvalidRequestException(
1123                                                Msg.code(2285) + "Invalid chain, " + paramName + " is not a reference SearchParameter");
1124                        }
1125
1126                        switch (param.getParamType()) {
1127                                case STRING:
1128                                        theQueryStack.addSortOnString(myResourceName, paramName, ascending);
1129                                        break;
1130                                case DATE:
1131                                        theQueryStack.addSortOnDate(myResourceName, paramName, ascending);
1132                                        break;
1133                                case REFERENCE:
1134                                        theQueryStack.addSortOnResourceLink(
1135                                                        myResourceName, referenceTargetType, paramName, chainName, ascending, theParams);
1136                                        break;
1137                                case TOKEN:
1138                                        theQueryStack.addSortOnToken(myResourceName, paramName, ascending);
1139                                        break;
1140                                case NUMBER:
1141                                        theQueryStack.addSortOnNumber(myResourceName, paramName, ascending);
1142                                        break;
1143                                case URI:
1144                                        theQueryStack.addSortOnUri(myResourceName, paramName, ascending);
1145                                        break;
1146                                case QUANTITY:
1147                                        theQueryStack.addSortOnQuantity(myResourceName, paramName, ascending);
1148                                        break;
1149                                case COMPOSITE:
1150                                        List<RuntimeSearchParam> compositeList =
1151                                                        JpaParamUtil.resolveComponentParameters(mySearchParamRegistry, param);
1152                                        if (compositeList == null) {
1153                                                throw new InvalidRequestException(Msg.code(1195) + "The composite _sort parameter " + paramName
1154                                                                + " is not defined by the resource " + myResourceName);
1155                                        }
1156                                        if (compositeList.size() != 2) {
1157                                                throw new InvalidRequestException(Msg.code(1196) + "The composite _sort parameter " + paramName
1158                                                                + " must have 2 composite types declared in parameter annotation, found "
1159                                                                + compositeList.size());
1160                                        }
1161                                        RuntimeSearchParam left = compositeList.get(0);
1162                                        RuntimeSearchParam right = compositeList.get(1);
1163
1164                                        createCompositeSort(theQueryStack, left.getParamType(), left.getName(), ascending);
1165                                        createCompositeSort(theQueryStack, right.getParamType(), right.getName(), ascending);
1166
1167                                        break;
1168                                case SPECIAL:
1169                                        if (LOCATION_POSITION.equals(param.getPath())) {
1170                                                theQueryStack.addSortOnCoordsNear(paramName, ascending, theParams);
1171                                                break;
1172                                        }
1173                                        throw new InvalidRequestException(
1174                                                        Msg.code(2306) + "This server does not support _sort specifications of type "
1175                                                                        + param.getParamType() + " - Can't serve _sort=" + paramName);
1176
1177                                case HAS:
1178                                default:
1179                                        throw new InvalidRequestException(
1180                                                        Msg.code(1197) + "This server does not support _sort specifications of type "
1181                                                                        + param.getParamType() + " - Can't serve _sort=" + paramName);
1182                        }
1183                }
1184
1185                // Recurse
1186                createSort(theQueryStack, theSort.getChain(), theParams);
1187        }
1188
1189        private void throwInvalidRequestExceptionForUnknownSortParameter(String theResourceName, String theParamName) {
1190                Collection<String> validSearchParameterNames = mySearchParamRegistry.getValidSearchParameterNamesIncludingMeta(
1191                                theResourceName, ISearchParamRegistry.SearchParamLookupContextEnum.SORT);
1192                String msg = myContext
1193                                .getLocalizer()
1194                                .getMessageSanitized(
1195                                                BaseStorageDao.class,
1196                                                "invalidSortParameter",
1197                                                theParamName,
1198                                                theResourceName,
1199                                                validSearchParameterNames);
1200                throw new InvalidRequestException(Msg.code(1194) + msg);
1201        }
1202
1203        private void createCompositeSort(
1204                        QueryStack theQueryStack,
1205                        RestSearchParameterTypeEnum theParamType,
1206                        String theParamName,
1207                        boolean theAscending) {
1208
1209                switch (theParamType) {
1210                        case STRING:
1211                                theQueryStack.addSortOnString(myResourceName, theParamName, theAscending);
1212                                break;
1213                        case DATE:
1214                                theQueryStack.addSortOnDate(myResourceName, theParamName, theAscending);
1215                                break;
1216                        case TOKEN:
1217                                theQueryStack.addSortOnToken(myResourceName, theParamName, theAscending);
1218                                break;
1219                        case QUANTITY:
1220                                theQueryStack.addSortOnQuantity(myResourceName, theParamName, theAscending);
1221                                break;
1222                        case NUMBER:
1223                        case REFERENCE:
1224                        case COMPOSITE:
1225                        case URI:
1226                        case HAS:
1227                        case SPECIAL:
1228                        default:
1229                                throw new InvalidRequestException(
1230                                                Msg.code(1198) + "Don't know how to handle composite parameter with type of " + theParamType
1231                                                                + " on _sort=" + theParamName);
1232                }
1233        }
1234
1235        private void doLoadPids(
1236                        Collection<JpaPid> thePids,
1237                        Collection<JpaPid> theIncludedPids,
1238                        List<IBaseResource> theResourceListToPopulate,
1239                        boolean theForHistoryOperation,
1240                        Map<Long, Integer> thePosition) {
1241
1242                Map<JpaPid, Long> resourcePidToVersion = null;
1243                for (JpaPid next : thePids) {
1244                        if (next.getVersion() != null && myStorageSettings.isRespectVersionsForSearchIncludes()) {
1245                                if (resourcePidToVersion == null) {
1246                                        resourcePidToVersion = new HashMap<>();
1247                                }
1248                                resourcePidToVersion.put(next, next.getVersion());
1249                        }
1250                }
1251
1252                List<JpaPid> versionlessPids = new ArrayList<>(thePids);
1253                if (versionlessPids.size() < getMaximumPageSize()) {
1254                        versionlessPids = normalizeIdListForInClause(versionlessPids);
1255                }
1256
1257                // Load the resource bodies
1258                List<ResourceHistoryTable> resourceSearchViewList =
1259                                myResourceHistoryTableDao.findCurrentVersionsByResourcePidsAndFetchResourceTable(
1260                                                JpaPidFk.fromPids(versionlessPids));
1261
1262                /*
1263                 * If we have specific versions to load, replace the history entries with the
1264                 * correct ones
1265                 *
1266                 * TODO: this could definitely be made more efficient, probably by not loading the wrong
1267                 * version entity first, and by batching the fetches. But this is a fairly infrequently
1268                 * used feature, and loading history entities by PK is a very efficient query so it's
1269                 * not the end of the world
1270                 */
1271                if (resourcePidToVersion != null) {
1272                        for (int i = 0; i < resourceSearchViewList.size(); i++) {
1273                                ResourceHistoryTable next = resourceSearchViewList.get(i);
1274                                JpaPid resourceId = next.getPersistentId();
1275                                Long version = resourcePidToVersion.get(resourceId);
1276                                resourceId.setVersion(version);
1277                                if (version != null && !version.equals(next.getVersion())) {
1278                                        ResourceHistoryTable replacement = myResourceHistoryTableDao.findForIdAndVersion(
1279                                                        next.getResourceId().toFk(), version);
1280                                        resourceSearchViewList.set(i, replacement);
1281                                }
1282                        }
1283                }
1284
1285                // -- preload all tags with tag definition if any
1286                Map<JpaPid, Collection<BaseTag>> tagMap = getResourceTagMap(resourceSearchViewList);
1287
1288                for (ResourceHistoryTable next : resourceSearchViewList) {
1289                        if (next.getDeleted() != null) {
1290                                continue;
1291                        }
1292
1293                        Class<? extends IBaseResource> resourceType =
1294                                        myContext.getResourceDefinition(next.getResourceType()).getImplementingClass();
1295
1296                        JpaPid resourceId = next.getPersistentId();
1297
1298                        if (resourcePidToVersion != null) {
1299                                Long version = resourcePidToVersion.get(resourceId);
1300                                resourceId.setVersion(version);
1301                        }
1302
1303                        IBaseResource resource;
1304                        resource = myJpaStorageResourceParser.toResource(
1305                                        resourceType, next, tagMap.get(next.getResourceId()), theForHistoryOperation);
1306                        if (resource == null) {
1307                                ourLog.warn(
1308                                                "Unable to find resource {}/{}/_history/{} in database",
1309                                                next.getResourceType(),
1310                                                next.getIdDt().getIdPart(),
1311                                                next.getVersion());
1312                                continue;
1313                        }
1314
1315                        Integer index = thePosition.get(resourceId.getId());
1316                        if (index == null) {
1317                                ourLog.warn("Got back unexpected resource PID {}", resourceId);
1318                                continue;
1319                        }
1320
1321                        if (theIncludedPids.contains(resourceId)) {
1322                                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put(resource, BundleEntrySearchModeEnum.INCLUDE);
1323                        } else {
1324                                ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.put(resource, BundleEntrySearchModeEnum.MATCH);
1325                        }
1326
1327                        // ensure there's enough space; "<=" because of 0-indexing
1328                        while (theResourceListToPopulate.size() <= index) {
1329                                theResourceListToPopulate.add(null);
1330                        }
1331                        theResourceListToPopulate.set(index, resource);
1332                }
1333        }
1334
1335        private Map<JpaPid, Collection<BaseTag>> getResourceTagMap(Collection<ResourceHistoryTable> theHistoryTables) {
1336                return switch (myStorageSettings.getTagStorageMode()) {
1337                        case VERSIONED -> getPidToTagMapVersioned(theHistoryTables);
1338                        case NON_VERSIONED -> getPidToTagMapUnversioned(theHistoryTables);
1339                        case INLINE -> Map.of();
1340                };
1341        }
1342
1343        @Nonnull
1344        private Map<JpaPid, Collection<BaseTag>> getPidToTagMapVersioned(
1345                        Collection<ResourceHistoryTable> theHistoryTables) {
1346                List<ResourceHistoryTablePk> idList = new ArrayList<>(theHistoryTables.size());
1347
1348                // -- find all resource has tags
1349                for (ResourceHistoryTable resource : theHistoryTables) {
1350                        if (resource.isHasTags()) {
1351                                idList.add(resource.getId());
1352                        }
1353                }
1354
1355                Map<JpaPid, Collection<BaseTag>> tagMap = new HashMap<>();
1356
1357                // -- no tags
1358                if (idList.isEmpty()) {
1359                        return tagMap;
1360                }
1361
1362                // -- get all tags for the idList
1363                Collection<ResourceHistoryTag> tagList = myResourceHistoryTagDao.findByVersionIds(idList);
1364
1365                // -- build the map, key = resourceId, value = list of ResourceTag
1366                JpaPid resourceId;
1367                Collection<BaseTag> tagCol;
1368                for (ResourceHistoryTag tag : tagList) {
1369
1370                        resourceId = tag.getResourcePid();
1371                        tagCol = tagMap.get(resourceId);
1372                        if (tagCol == null) {
1373                                tagCol = new ArrayList<>();
1374                                tagCol.add(tag);
1375                                tagMap.put(resourceId, tagCol);
1376                        } else {
1377                                tagCol.add(tag);
1378                        }
1379                }
1380
1381                return tagMap;
1382        }
1383
1384        @Nonnull
1385        private Map<JpaPid, Collection<BaseTag>> getPidToTagMapUnversioned(
1386                        Collection<ResourceHistoryTable> theHistoryTables) {
1387                List<JpaPid> idList = new ArrayList<>(theHistoryTables.size());
1388
1389                // -- find all resource has tags
1390                for (ResourceHistoryTable resource : theHistoryTables) {
1391                        if (resource.isHasTags()) {
1392                                idList.add(resource.getResourceId());
1393                        }
1394                }
1395
1396                Map<JpaPid, Collection<BaseTag>> tagMap = new HashMap<>();
1397
1398                // -- no tags
1399                if (idList.isEmpty()) {
1400                        return tagMap;
1401                }
1402
1403                // -- get all tags for the idList
1404                Collection<ResourceTag> tagList = myResourceTagDao.findByResourceIds(idList);
1405
1406                // -- build the map, key = resourceId, value = list of ResourceTag
1407                JpaPid resourceId;
1408                Collection<BaseTag> tagCol;
1409                for (ResourceTag tag : tagList) {
1410
1411                        resourceId = tag.getResourceId();
1412                        tagCol = tagMap.get(resourceId);
1413                        if (tagCol == null) {
1414                                tagCol = new ArrayList<>();
1415                                tagCol.add(tag);
1416                                tagMap.put(resourceId, tagCol);
1417                        } else {
1418                                tagCol.add(tag);
1419                        }
1420                }
1421
1422                return tagMap;
1423        }
1424
1425        @Override
1426        public void loadResourcesByPid(
1427                        Collection<JpaPid> thePids,
1428                        Collection<JpaPid> theIncludedPids,
1429                        List<IBaseResource> theResourceListToPopulate,
1430                        boolean theForHistoryOperation,
1431                        RequestDetails theDetails) {
1432                if (thePids.isEmpty()) {
1433                        ourLog.debug("The include pids are empty");
1434                }
1435
1436                // Dupes will cause a crash later anyhow, but this is expensive so only do it
1437                // when running asserts
1438                assert new HashSet<>(thePids).size() == thePids.size() : "PID list contains duplicates: " + thePids;
1439
1440                Map<Long, Integer> position = new HashMap<>();
1441                int index = 0;
1442                for (JpaPid next : thePids) {
1443                        position.put(next.getId(), index++);
1444                }
1445
1446                // Can we fast track this loading by checking elastic search?
1447                boolean isUsingElasticSearch = isLoadingFromElasticSearchSupported(thePids);
1448                if (isUsingElasticSearch) {
1449                        try {
1450                                theResourceListToPopulate.addAll(loadResourcesFromElasticSearch(thePids));
1451                                return;
1452
1453                        } catch (ResourceNotFoundInIndexException theE) {
1454                                // some resources were not found in index, so we will inform this and resort to JPA search
1455                                ourLog.warn(
1456                                                "Some resources were not found in index. Make sure all resources were indexed. Resorting to database search.");
1457                        }
1458                }
1459
1460                // We only chunk because some jdbc drivers can't handle long param lists.
1461                QueryChunker.chunk(
1462                                thePids,
1463                                t -> doLoadPids(t, theIncludedPids, theResourceListToPopulate, theForHistoryOperation, position));
1464        }
1465
1466        /**
1467         * Check if we can load the resources from Hibernate Search instead of the database.
1468         * We assume this is faster.
1469         * <p>
1470         * Hibernate Search only stores the current version, and only if enabled.
1471         *
1472         * @param thePids the pids to check for versioned references
1473         * @return can we fetch from Hibernate Search?
1474         */
1475        private boolean isLoadingFromElasticSearchSupported(Collection<JpaPid> thePids) {
1476                // is storage enabled?
1477                return myStorageSettings.isStoreResourceInHSearchIndex()
1478                                && myStorageSettings.isHibernateSearchIndexSearchParams()
1479                                &&
1480                                // we don't support history
1481                                thePids.stream().noneMatch(p -> p.getVersion() != null)
1482                                &&
1483                                // skip the complexity for metadata in dstu2
1484                                myContext.getVersion().getVersion().isEqualOrNewerThan(FhirVersionEnum.DSTU3);
1485        }
1486
1487        private List<IBaseResource> loadResourcesFromElasticSearch(Collection<JpaPid> thePids) {
1488                // Do we use the fulltextsvc via hibernate-search to load resources or be backwards compatible with older ES
1489                // only impl
1490                // to handle lastN?
1491                if (myStorageSettings.isHibernateSearchIndexSearchParams()
1492                                && myStorageSettings.isStoreResourceInHSearchIndex()) {
1493                        List<Long> pidList = thePids.stream().map(JpaPid::getId).collect(Collectors.toList());
1494
1495                        return myFulltextSearchSvc.getResources(pidList);
1496                } else if (!Objects.isNull(myParams) && myParams.isLastN()) {
1497                        // legacy LastN implementation
1498                        return myIElasticsearchSvc.getObservationResources(thePids);
1499                } else {
1500                        return Collections.emptyList();
1501                }
1502        }
1503
1504        /**
1505         * THIS SHOULD RETURN HASHSET and not just Set because we add to it later
1506         * so it can't be Collections.emptySet() or some such thing.
1507         * The JpaPid returned will have resource type populated.
1508         */
1509        @Override
1510        public Set<JpaPid> loadIncludes(
1511                        FhirContext theContext,
1512                        EntityManager theEntityManager,
1513                        Collection<JpaPid> theMatches,
1514                        Collection<Include> theIncludes,
1515                        boolean theReverseMode,
1516                        DateRangeParam theLastUpdated,
1517                        String theSearchIdOrDescription,
1518                        RequestDetails theRequest,
1519                        Integer theMaxCount) {
1520                SearchBuilderLoadIncludesParameters<JpaPid> parameters = new SearchBuilderLoadIncludesParameters<>();
1521                parameters.setFhirContext(theContext);
1522                parameters.setEntityManager(theEntityManager);
1523                parameters.setMatches(theMatches);
1524                parameters.setIncludeFilters(theIncludes);
1525                parameters.setReverseMode(theReverseMode);
1526                parameters.setLastUpdated(theLastUpdated);
1527                parameters.setSearchIdOrDescription(theSearchIdOrDescription);
1528                parameters.setRequestDetails(theRequest);
1529                parameters.setMaxCount(theMaxCount);
1530                return loadIncludes(parameters);
1531        }
1532
1533        @Override
1534        public Set<JpaPid> loadIncludes(SearchBuilderLoadIncludesParameters<JpaPid> theParameters) {
1535                Collection<JpaPid> matches = theParameters.getMatches();
1536                Collection<Include> currentIncludes = theParameters.getIncludeFilters();
1537                boolean reverseMode = theParameters.isReverseMode();
1538                EntityManager entityManager = theParameters.getEntityManager();
1539                Integer maxCount = theParameters.getMaxCount();
1540                FhirContext fhirContext = theParameters.getFhirContext();
1541                RequestDetails request = theParameters.getRequestDetails();
1542                String searchIdOrDescription = theParameters.getSearchIdOrDescription();
1543                List<String> desiredResourceTypes = theParameters.getDesiredResourceTypes();
1544                boolean hasDesiredResourceTypes = desiredResourceTypes != null && !desiredResourceTypes.isEmpty();
1545                IInterceptorBroadcaster compositeBroadcaster =
1546                                CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, request);
1547
1548                if (compositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_RAW_SQL)) {
1549                        CurrentThreadCaptureQueriesListener.startCapturing();
1550                }
1551                if (matches.isEmpty()) {
1552                        return new HashSet<>();
1553                }
1554                if (currentIncludes == null || currentIncludes.isEmpty()) {
1555                        return new HashSet<>();
1556                }
1557                String searchPidFieldName = reverseMode ? MY_TARGET_RESOURCE_PID : MY_SOURCE_RESOURCE_PID;
1558                String searchPartitionIdFieldName =
1559                                reverseMode ? MY_TARGET_RESOURCE_PARTITION_ID : MY_SOURCE_RESOURCE_PARTITION_ID;
1560                String findPidFieldName = reverseMode ? MY_SOURCE_RESOURCE_PID : MY_TARGET_RESOURCE_PID;
1561                String findPartitionIdFieldName =
1562                                reverseMode ? MY_SOURCE_RESOURCE_PARTITION_ID : MY_TARGET_RESOURCE_PARTITION_ID;
1563                String findResourceTypeFieldName = reverseMode ? MY_SOURCE_RESOURCE_TYPE : MY_TARGET_RESOURCE_TYPE;
1564                String findVersionFieldName = null;
1565                if (!reverseMode && myStorageSettings.isRespectVersionsForSearchIncludes()) {
1566                        findVersionFieldName = MY_TARGET_RESOURCE_VERSION;
1567                }
1568
1569                List<JpaPid> nextRoundMatches = new ArrayList<>(matches);
1570                HashSet<JpaPid> allAdded = new HashSet<>();
1571                HashSet<JpaPid> original = new HashSet<>(matches);
1572                ArrayList<Include> includes = new ArrayList<>(currentIncludes);
1573
1574                int roundCounts = 0;
1575                StopWatch w = new StopWatch();
1576
1577                boolean addedSomeThisRound;
1578                do {
1579                        roundCounts++;
1580
1581                        HashSet<JpaPid> pidsToInclude = new HashSet<>();
1582
1583                        for (Iterator<Include> iter = includes.iterator(); iter.hasNext(); ) {
1584                                Include nextInclude = iter.next();
1585                                if (!nextInclude.isRecurse()) {
1586                                        iter.remove();
1587                                }
1588
1589                                // Account for _include=*
1590                                boolean matchAll = "*".equals(nextInclude.getValue());
1591
1592                                // Account for _include=[resourceType]:*
1593                                String wantResourceType = null;
1594                                if (!matchAll) {
1595                                        if ("*".equals(nextInclude.getParamName())) {
1596                                                wantResourceType = nextInclude.getParamType();
1597                                                matchAll = true;
1598                                        }
1599                                }
1600
1601                                if (matchAll) {
1602                                        loadIncludesMatchAll(
1603                                                        findPidFieldName,
1604                                                        findPartitionIdFieldName,
1605                                                        findResourceTypeFieldName,
1606                                                        findVersionFieldName,
1607                                                        searchPidFieldName,
1608                                                        searchPartitionIdFieldName,
1609                                                        wantResourceType,
1610                                                        reverseMode,
1611                                                        hasDesiredResourceTypes,
1612                                                        nextRoundMatches,
1613                                                        entityManager,
1614                                                        maxCount,
1615                                                        desiredResourceTypes,
1616                                                        pidsToInclude,
1617                                                        request);
1618                                } else {
1619                                        loadIncludesMatchSpecific(
1620                                                        nextInclude,
1621                                                        fhirContext,
1622                                                        findPidFieldName,
1623                                                        findPartitionIdFieldName,
1624                                                        findVersionFieldName,
1625                                                        searchPidFieldName,
1626                                                        reverseMode,
1627                                                        nextRoundMatches,
1628                                                        entityManager,
1629                                                        maxCount,
1630                                                        pidsToInclude,
1631                                                        request);
1632                                }
1633                        }
1634
1635                        nextRoundMatches.clear();
1636                        for (JpaPid next : pidsToInclude) {
1637                                if (!original.contains(next) && !allAdded.contains(next)) {
1638                                        nextRoundMatches.add(next);
1639                                } else {
1640                                        ourLog.trace("Skipping include since it has already been seen. [jpaPid={}]", next);
1641                                }
1642                        }
1643
1644                        addedSomeThisRound = allAdded.addAll(pidsToInclude);
1645
1646                        if (maxCount != null && allAdded.size() >= maxCount) {
1647                                break;
1648                        }
1649
1650                } while (!includes.isEmpty() && !nextRoundMatches.isEmpty() && addedSomeThisRound);
1651
1652                allAdded.removeAll(original);
1653
1654                ourLog.info(
1655                                "Loaded {} {} in {} rounds and {} ms for search {}",
1656                                allAdded.size(),
1657                                reverseMode ? "_revincludes" : "_includes",
1658                                roundCounts,
1659                                w.getMillisAndRestart(),
1660                                searchIdOrDescription);
1661
1662                if (compositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_RAW_SQL)) {
1663                        callRawSqlHookWithCurrentThreadQueries(request, compositeBroadcaster);
1664                }
1665
1666                // Interceptor call: STORAGE_PREACCESS_RESOURCES
1667                // This can be used to remove results from the search result details before
1668                // the user has a chance to know that they were in the results
1669                if (!allAdded.isEmpty()) {
1670
1671                        if (compositeBroadcaster.hasHooks(Pointcut.STORAGE_PREACCESS_RESOURCES)) {
1672                                List<JpaPid> includedPidList = new ArrayList<>(allAdded);
1673                                JpaPreResourceAccessDetails accessDetails =
1674                                                new JpaPreResourceAccessDetails(includedPidList, () -> this);
1675                                HookParams params = new HookParams()
1676                                                .add(IPreResourceAccessDetails.class, accessDetails)
1677                                                .add(RequestDetails.class, request)
1678                                                .addIfMatchesType(ServletRequestDetails.class, request);
1679                                compositeBroadcaster.callHooks(Pointcut.STORAGE_PREACCESS_RESOURCES, params);
1680
1681                                for (int i = includedPidList.size() - 1; i >= 0; i--) {
1682                                        if (accessDetails.isDontReturnResourceAtIndex(i)) {
1683                                                JpaPid value = includedPidList.remove(i);
1684                                                if (value != null) {
1685                                                        allAdded.remove(value);
1686                                                }
1687                                        }
1688                                }
1689                        }
1690                }
1691
1692                return allAdded;
1693        }
1694
1695        private void loadIncludesMatchSpecific(
1696                        Include nextInclude,
1697                        FhirContext fhirContext,
1698                        String findPidFieldName,
1699                        String findPartitionFieldName,
1700                        String findVersionFieldName,
1701                        String searchPidFieldName,
1702                        boolean reverseMode,
1703                        List<JpaPid> nextRoundMatches,
1704                        EntityManager entityManager,
1705                        Integer maxCount,
1706                        HashSet<JpaPid> pidsToInclude,
1707                        RequestDetails theRequest) {
1708                List<String> paths;
1709
1710                // Start replace
1711                RuntimeSearchParam param;
1712                String resType = nextInclude.getParamType();
1713                if (isBlank(resType)) {
1714                        return;
1715                }
1716                RuntimeResourceDefinition def = fhirContext.getResourceDefinition(resType);
1717                if (def == null) {
1718                        ourLog.warn("Unknown resource type in include/revinclude=" + nextInclude.getValue());
1719                        return;
1720                }
1721
1722                String paramName = nextInclude.getParamName();
1723                if (isNotBlank(paramName)) {
1724                        param = mySearchParamRegistry.getActiveSearchParam(
1725                                        resType, paramName, ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
1726                } else {
1727                        param = null;
1728                }
1729                if (param == null) {
1730                        ourLog.warn("Unknown param name in include/revinclude=" + nextInclude.getValue());
1731                        return;
1732                }
1733
1734                paths = param.getPathsSplitForResourceType(resType);
1735                // end replace
1736
1737                Set<String> targetResourceTypes = computeTargetResourceTypes(nextInclude, param);
1738
1739                for (String nextPath : paths) {
1740                        String findPidFieldSqlColumn =
1741                                        findPidFieldName.equals(MY_SOURCE_RESOURCE_PID) ? "src_resource_id" : "target_resource_id";
1742                        String fieldsToLoad = "r." + findPidFieldSqlColumn + " AS " + RESOURCE_ID_ALIAS;
1743                        if (findVersionFieldName != null) {
1744                                fieldsToLoad += ", r.target_resource_version AS " + RESOURCE_VERSION_ALIAS;
1745                        }
1746                        if (myPartitionSettings.isDatabasePartitionMode()) {
1747                                fieldsToLoad += ", r.";
1748                                fieldsToLoad += findPartitionFieldName.equals(MY_SOURCE_RESOURCE_PARTITION_ID)
1749                                                ? "partition_id"
1750                                                : "target_res_partition_id";
1751                                fieldsToLoad += " as " + PARTITION_ID_ALIAS;
1752                        }
1753
1754                        // Query for includes lookup has 2 cases
1755                        // Case 1: Where target_resource_id is available in hfj_res_link table for local references
1756                        // Case 2: Where target_resource_id is null in hfj_res_link table and referred by a canonical
1757                        // url in target_resource_url
1758
1759                        // Case 1:
1760                        Map<String, Object> localReferenceQueryParams = new HashMap<>();
1761
1762                        String searchPidFieldSqlColumn =
1763                                        searchPidFieldName.equals(MY_TARGET_RESOURCE_PID) ? "target_resource_id" : "src_resource_id";
1764                        StringBuilder localReferenceQuery = new StringBuilder();
1765                        localReferenceQuery.append("SELECT ").append(fieldsToLoad);
1766                        localReferenceQuery.append(" FROM hfj_res_link r ");
1767                        localReferenceQuery.append("WHERE r.src_path = :src_path");
1768                        if (!"target_resource_id".equals(searchPidFieldSqlColumn)) {
1769                                localReferenceQuery.append(" AND r.target_resource_id IS NOT NULL");
1770                        }
1771                        localReferenceQuery
1772                                        .append(" AND r.")
1773                                        .append(searchPidFieldSqlColumn)
1774                                        .append(" IN (:target_pids) ");
1775                        if (myPartitionSettings.isDatabasePartitionMode()) {
1776                                String partitionFieldToSearch = findPartitionFieldName.equals(MY_SOURCE_RESOURCE_PARTITION_ID)
1777                                                ? "target_res_partition_id"
1778                                                : "partition_id";
1779                                localReferenceQuery
1780                                                .append("AND r.")
1781                                                .append(partitionFieldToSearch)
1782                                                .append(" = :search_partition_id ");
1783                        }
1784                        localReferenceQueryParams.put("src_path", nextPath);
1785                        // we loop over target_pids later.
1786                        if (targetResourceTypes != null) {
1787                                if (targetResourceTypes.size() == 1) {
1788                                        localReferenceQuery.append("AND r.target_resource_type = :target_resource_type ");
1789                                        localReferenceQueryParams.put(
1790                                                        "target_resource_type",
1791                                                        targetResourceTypes.iterator().next());
1792                                } else {
1793                                        localReferenceQuery.append("AND r.target_resource_type in (:target_resource_types) ");
1794                                        localReferenceQueryParams.put("target_resource_types", targetResourceTypes);
1795                                }
1796                        }
1797
1798                        // Case 2:
1799                        Pair<String, Map<String, Object>> canonicalQuery =
1800                                        buildCanonicalUrlQuery(findVersionFieldName, targetResourceTypes, reverseMode, theRequest, param);
1801
1802                        String sql = localReferenceQuery.toString();
1803                        if (canonicalQuery != null) {
1804                                sql = localReferenceQuery + "UNION " + canonicalQuery.getLeft();
1805                        }
1806
1807                        Map<String, Object> limitParams = new HashMap<>();
1808                        if (maxCount != null) {
1809                                LinkedList<Object> bindVariables = new LinkedList<>();
1810                                sql = SearchQueryBuilder.applyLimitToSql(
1811                                                myDialectProvider.getDialect(), null, maxCount, sql, null, bindVariables);
1812
1813                                // The dialect SQL limiter uses positional params, but we're using
1814                                // named params here, so we need to replace the positional params
1815                                // with equivalent named ones
1816                                StringBuilder sb = new StringBuilder();
1817                                for (int i = 0; i < sql.length(); i++) {
1818                                        char nextChar = sql.charAt(i);
1819                                        if (nextChar == '?') {
1820                                                String nextName = "limit" + i;
1821                                                sb.append(':').append(nextName);
1822                                                limitParams.put(nextName, bindVariables.removeFirst());
1823                                        } else {
1824                                                sb.append(nextChar);
1825                                        }
1826                                }
1827                                sql = sb.toString();
1828                        }
1829
1830                        List<Collection<JpaPid>> partitions = partitionBySizeAndPartitionId(nextRoundMatches, getMaximumPageSize());
1831                        for (Collection<JpaPid> nextPartition : partitions) {
1832                                Query q = entityManager.createNativeQuery(sql, Tuple.class);
1833                                q.setParameter("target_pids", JpaPid.toLongList(nextPartition));
1834                                if (myPartitionSettings.isDatabasePartitionMode()) {
1835                                        q.setParameter(
1836                                                        "search_partition_id",
1837                                                        nextPartition.iterator().next().getPartitionId());
1838                                }
1839                                localReferenceQueryParams.forEach(q::setParameter);
1840                                if (canonicalQuery != null) {
1841                                        canonicalQuery.getRight().forEach(q::setParameter);
1842                                }
1843                                limitParams.forEach(q::setParameter);
1844
1845                                try (ScrollableResultsIterator<Tuple> iter = new ScrollableResultsIterator<>(toScrollableResults(q))) {
1846                                        Tuple result;
1847                                        while (iter.hasNext()) {
1848                                                result = iter.next();
1849                                                Long resourceId = NumberUtils.createLong(String.valueOf(result.get(RESOURCE_ID_ALIAS)));
1850                                                Long resourceVersion = null;
1851                                                if (findVersionFieldName != null && result.get(RESOURCE_VERSION_ALIAS) != null) {
1852                                                        resourceVersion =
1853                                                                        NumberUtils.createLong(String.valueOf(result.get(RESOURCE_VERSION_ALIAS)));
1854                                                }
1855                                                Integer partitionId = null;
1856                                                if (myPartitionSettings.isDatabasePartitionMode()) {
1857                                                        partitionId = result.get(PARTITION_ID_ALIAS, Integer.class);
1858                                                }
1859
1860                                                JpaPid pid = JpaPid.fromIdAndVersion(resourceId, resourceVersion);
1861                                                pid.setPartitionId(partitionId);
1862                                                pidsToInclude.add(pid);
1863                                        }
1864                                }
1865                                //                              myEntityManager.clear();
1866                        }
1867                }
1868        }
1869
1870        private void loadIncludesMatchAll(
1871                        String findPidFieldName,
1872                        String findPartitionFieldName,
1873                        String findResourceTypeFieldName,
1874                        String findVersionFieldName,
1875                        String searchPidFieldName,
1876                        String searchPartitionFieldName,
1877                        String wantResourceType,
1878                        boolean reverseMode,
1879                        boolean hasDesiredResourceTypes,
1880                        List<JpaPid> nextRoundMatches,
1881                        EntityManager entityManager,
1882                        Integer maxCount,
1883                        List<String> desiredResourceTypes,
1884                        HashSet<JpaPid> pidsToInclude,
1885                        RequestDetails request) {
1886
1887                record IncludesRecord(
1888                                Long resourceId, String resourceType, String resourceCanonicalUrl, Long version, Integer partitionId) {}
1889
1890                CriteriaBuilder cb = entityManager.getCriteriaBuilder();
1891                CriteriaQuery<IncludesRecord> query = cb.createQuery(IncludesRecord.class);
1892                Root<ResourceLink> root = query.from(ResourceLink.class);
1893
1894                List<Selection<?>> selectionList = new ArrayList<>();
1895                selectionList.add(root.get(findPidFieldName));
1896                selectionList.add(root.get(findResourceTypeFieldName));
1897                selectionList.add(root.get("myTargetResourceUrl"));
1898                if (findVersionFieldName != null) {
1899                        selectionList.add(root.get(findVersionFieldName));
1900                } else {
1901                        selectionList.add(cb.nullLiteral(Long.class));
1902                }
1903                if (myPartitionSettings.isDatabasePartitionMode()) {
1904                        selectionList.add(root.get(findPartitionFieldName));
1905                } else {
1906                        selectionList.add(cb.nullLiteral(Integer.class));
1907                }
1908                query.multiselect(selectionList);
1909
1910                List<Predicate> predicates = new ArrayList<>();
1911
1912                if (myPartitionSettings.isDatabasePartitionMode()) {
1913                        predicates.add(
1914                                        cb.equal(root.get(searchPartitionFieldName), cb.parameter(Integer.class, "target_partition_id")));
1915                }
1916
1917                predicates.add(root.get(searchPidFieldName).in(cb.parameter(List.class, "target_pids")));
1918
1919                /*
1920                 * We need to set the resource type in 2 cases only:
1921                 * 1) we are in $everything mode
1922                 *              (where we only want to fetch specific resource types, regardless of what is
1923                 *              available to fetch)
1924                 * 2) we are doing revincludes
1925                 *
1926                 *      Technically if the request is a qualified star (e.g. _include=Observation:*) we
1927                 * should always be checking the source resource type on the resource link. We don't
1928                 * actually index that column though by default, so in order to try and be efficient
1929                 * we don't actually include it for includes (but we do for revincludes). This is
1930                 * because for an include, it doesn't really make sense to include a different
1931                 * resource type than the one you are searching on.
1932                 */
1933                if (wantResourceType != null && (reverseMode || (myParams != null && myParams.getEverythingMode() != null))) {
1934                        // because mySourceResourceType is not part of the HFJ_RES_LINK
1935                        // index, this might not be the most optimal performance.
1936                        // but it is for an $everything operation (and maybe we should update the index)
1937                        predicates.add(
1938                                        cb.equal(root.get("mySourceResourceType"), cb.parameter(String.class, "want_resource_type")));
1939                } else {
1940                        wantResourceType = null;
1941                }
1942
1943                // When calling $everything on a Patient instance, we don't want to recurse into new Patient
1944                // resources
1945                // (e.g. via Provenance, List, or Group) when in an $everything operation
1946                if (myParams != null
1947                                && myParams.getEverythingMode() == SearchParameterMap.EverythingModeEnum.PATIENT_INSTANCE) {
1948                        predicates.add(cb.notEqual(root.get("myTargetResourceType"), "Patient"));
1949                        predicates.add(cb.not(root.get("mySourceResourceType")
1950                                        .in(UNDESIRED_RESOURCE_LINKAGES_FOR_EVERYTHING_ON_PATIENT_INSTANCE)));
1951                }
1952
1953                if (hasDesiredResourceTypes) {
1954                        predicates.add(
1955                                        root.get("myTargetResourceType").in(cb.parameter(List.class, "desired_target_resource_types")));
1956                }
1957
1958                query.where(cb.and(predicates.toArray(new Predicate[0])));
1959
1960                List<Collection<JpaPid>> partitions = partitionBySizeAndPartitionId(nextRoundMatches, getMaximumPageSize());
1961                for (Collection<JpaPid> nextPartition : partitions) {
1962
1963                        TypedQuery<IncludesRecord> q = myEntityManager.createQuery(query);
1964                        q.setParameter("target_pids", JpaPid.toLongList(nextPartition));
1965                        if (myPartitionSettings.isDatabasePartitionMode()) {
1966                                q.setParameter(
1967                                                "target_partition_id", nextPartition.iterator().next().getPartitionId());
1968                        }
1969                        if (wantResourceType != null) {
1970                                q.setParameter("want_resource_type", wantResourceType);
1971                        }
1972                        if (maxCount != null) {
1973                                q.setMaxResults(maxCount);
1974                        }
1975                        if (hasDesiredResourceTypes) {
1976                                q.setParameter("desired_target_resource_types", desiredResourceTypes);
1977                        }
1978
1979                        Set<String> canonicalUrls = null;
1980
1981                        try (ScrollableResultsIterator<IncludesRecord> iter =
1982                                        new ScrollableResultsIterator<>(toScrollableResults(q))) {
1983                                IncludesRecord nextRow;
1984                                while (iter.hasNext()) {
1985                                        nextRow = iter.next();
1986                                        if (nextRow == null) {
1987                                                // This can happen if there are outgoing references which are canonical or point to
1988                                                // other servers
1989                                                continue;
1990                                        }
1991
1992                                        Long version = nextRow.version;
1993                                        Long resourceId = nextRow.resourceId;
1994                                        String resourceType = nextRow.resourceType;
1995                                        String resourceCanonicalUrl = nextRow.resourceCanonicalUrl;
1996                                        Integer partitionId = nextRow.partitionId;
1997
1998                                        if (resourceId != null) {
1999                                                JpaPid pid = JpaPid.fromIdAndVersionAndResourceType(resourceId, version, resourceType);
2000                                                pid.setPartitionId(partitionId);
2001                                                pidsToInclude.add(pid);
2002                                        } else if (resourceCanonicalUrl != null) {
2003                                                if (canonicalUrls == null) {
2004                                                        canonicalUrls = new HashSet<>();
2005                                                }
2006                                                canonicalUrls.add(resourceCanonicalUrl);
2007                                        }
2008                                }
2009                        }
2010
2011                        if (canonicalUrls != null) {
2012                                loadCanonicalUrls(request, canonicalUrls, entityManager, pidsToInclude, reverseMode);
2013                        }
2014                }
2015        }
2016
2017        private void loadCanonicalUrls(
2018                        RequestDetails theRequestDetails,
2019                        Set<String> theCanonicalUrls,
2020                        EntityManager theEntityManager,
2021                        HashSet<JpaPid> thePidsToInclude,
2022                        boolean theReverse) {
2023                StringBuilder sqlBuilder;
2024                CanonicalUrlTargets canonicalUrlTargets =
2025                                calculateIndexUriIdentityHashesForResourceTypes(theRequestDetails, null, theReverse);
2026                if (canonicalUrlTargets.isEmpty()) {
2027                        return;
2028                }
2029
2030                String message =
2031                                "Search with _include=* can be inefficient when references using canonical URLs are detected. Use more specific _include values instead.";
2032                firePerformanceWarning(theRequestDetails, message);
2033
2034                List<List<String>> canonicalUrlPartitions = ListUtils.partition(
2035                                List.copyOf(theCanonicalUrls), getMaximumPageSize() - canonicalUrlTargets.hashIdentityValues.size());
2036
2037                sqlBuilder = new StringBuilder();
2038                sqlBuilder.append("SELECT ");
2039                if (myPartitionSettings.isPartitioningEnabled()) {
2040                        sqlBuilder.append("i.myPartitionIdValue, ");
2041                }
2042                sqlBuilder.append("i.myResourcePid ");
2043
2044                sqlBuilder.append("FROM ResourceIndexedSearchParamUri i ");
2045                sqlBuilder.append("WHERE i.myHashIdentity IN (:hash_identity) ");
2046                sqlBuilder.append("AND i.myUri IN (:uris)");
2047
2048                String canonicalResSql = sqlBuilder.toString();
2049
2050                for (Collection<String> nextCanonicalUrlList : canonicalUrlPartitions) {
2051                        TypedQuery<Object[]> canonicalResIdQuery = theEntityManager.createQuery(canonicalResSql, Object[].class);
2052                        canonicalResIdQuery.setParameter("hash_identity", canonicalUrlTargets.hashIdentityValues);
2053                        canonicalResIdQuery.setParameter("uris", nextCanonicalUrlList);
2054                        List<Object[]> results = canonicalResIdQuery.getResultList();
2055                        for (var next : results) {
2056                                if (next != null) {
2057                                        Integer partitionId = null;
2058                                        Long pid;
2059                                        if (next.length == 1) {
2060                                                pid = (Long) next[0];
2061                                        } else {
2062                                                partitionId = (Integer) ((Object[]) next)[0];
2063                                                pid = (Long) ((Object[]) next)[1];
2064                                        }
2065                                        if (pid != null) {
2066                                                thePidsToInclude.add(JpaPid.fromId(pid, partitionId));
2067                                        }
2068                                }
2069                        }
2070                }
2071        }
2072
2073        /**
2074         * Calls Performance Trace Hook
2075         *
2076         * @param request                 the request deatils
2077         *                                Sends a raw SQL query to the Pointcut for raw SQL queries.
2078         */
2079        private void callRawSqlHookWithCurrentThreadQueries(
2080                        RequestDetails request, IInterceptorBroadcaster theCompositeBroadcaster) {
2081                SqlQueryList capturedQueries = CurrentThreadCaptureQueriesListener.getCurrentQueueAndStopCapturing();
2082                HookParams params = new HookParams()
2083                                .add(RequestDetails.class, request)
2084                                .addIfMatchesType(ServletRequestDetails.class, request)
2085                                .add(SqlQueryList.class, capturedQueries);
2086                theCompositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_RAW_SQL, params);
2087        }
2088
2089        @Nullable
2090        private static Set<String> computeTargetResourceTypes(Include nextInclude, RuntimeSearchParam param) {
2091                String targetResourceType = nextInclude.getParamTargetType();
2092                boolean haveTargetTypesDefinedByParam = param.hasTargets();
2093                Set<String> targetResourceTypes;
2094                if (targetResourceType != null) {
2095                        targetResourceTypes = Set.of(targetResourceType);
2096                } else if (haveTargetTypesDefinedByParam) {
2097                        targetResourceTypes = param.getTargets();
2098                } else {
2099                        // all types!
2100                        targetResourceTypes = null;
2101                }
2102                return targetResourceTypes;
2103        }
2104
2105        @Nullable
2106        private Pair<String, Map<String, Object>> buildCanonicalUrlQuery(
2107                        String theVersionFieldName,
2108                        Set<String> theTargetResourceTypes,
2109                        boolean theReverse,
2110                        RequestDetails theRequest,
2111                        RuntimeSearchParam theParam) {
2112
2113                String[] searchParameterPaths = SearchParameterUtil.splitSearchParameterExpressions(theParam.getPath());
2114
2115                // If we know for sure that none of the paths involved in this SearchParameter could
2116                // be indexing a canonical
2117                if (Arrays.stream(searchParameterPaths)
2118                                .noneMatch(t -> SearchParameterUtil.referencePathCouldPotentiallyReferenceCanonicalElement(
2119                                                myContext, myResourceName, t, theReverse))) {
2120                        return null;
2121                }
2122
2123                String fieldsToLoadFromSpidxUriTable = theReverse ? "r.src_resource_id" : "rUri.res_id";
2124                if (theVersionFieldName != null) {
2125                        // canonical-uri references aren't versioned, but we need to match the column count for the UNION
2126                        fieldsToLoadFromSpidxUriTable += ", NULL";
2127                }
2128
2129                if (myPartitionSettings.isDatabasePartitionMode()) {
2130                        if (theReverse) {
2131                                fieldsToLoadFromSpidxUriTable += ", r.partition_id as " + PARTITION_ID_ALIAS;
2132                        } else {
2133                                fieldsToLoadFromSpidxUriTable += ", rUri.partition_id as " + PARTITION_ID_ALIAS;
2134                        }
2135                }
2136
2137                // The logical join will be by hfj_spidx_uri on sp_name='uri' and sp_uri=target_resource_url.
2138                // But sp_name isn't indexed, so we use hash_identity instead.
2139                CanonicalUrlTargets canonicalUrlTargets =
2140                                calculateIndexUriIdentityHashesForResourceTypes(theRequest, theTargetResourceTypes, theReverse);
2141                if (canonicalUrlTargets.isEmpty()) {
2142                        return null;
2143                }
2144
2145                Map<String, Object> canonicalUriQueryParams = new HashMap<>();
2146                StringBuilder canonicalUrlQuery = new StringBuilder();
2147                canonicalUrlQuery
2148                                .append("SELECT ")
2149                                .append(fieldsToLoadFromSpidxUriTable)
2150                                .append(' ');
2151                canonicalUrlQuery.append("FROM hfj_res_link r ");
2152
2153                // join on hash_identity and sp_uri - indexed in IDX_SP_URI_HASH_IDENTITY_V2
2154                canonicalUrlQuery.append("JOIN hfj_spidx_uri rUri ON (");
2155                if (myPartitionSettings.isDatabasePartitionMode()) {
2156                        canonicalUrlQuery.append("rUri.partition_id IN (:uri_partition_id) AND ");
2157                        canonicalUriQueryParams.put("uri_partition_id", canonicalUrlTargets.partitionIds);
2158                }
2159                if (canonicalUrlTargets.hashIdentityValues.size() == 1) {
2160                        canonicalUrlQuery.append("rUri.hash_identity = :uri_identity_hash");
2161                        canonicalUriQueryParams.put(
2162                                        "uri_identity_hash",
2163                                        canonicalUrlTargets.hashIdentityValues.iterator().next());
2164                } else {
2165                        canonicalUrlQuery.append("rUri.hash_identity in (:uri_identity_hashes)");
2166                        canonicalUriQueryParams.put("uri_identity_hashes", canonicalUrlTargets.hashIdentityValues);
2167                }
2168                canonicalUrlQuery.append(" AND r.target_resource_url = rUri.sp_uri");
2169                canonicalUrlQuery.append(")");
2170
2171                canonicalUrlQuery.append(" WHERE r.src_path = :src_path AND");
2172                canonicalUrlQuery.append(" r.target_resource_id IS NULL");
2173                canonicalUrlQuery.append(" AND");
2174                if (myPartitionSettings.isDatabasePartitionMode()) {
2175                        if (theReverse) {
2176                                canonicalUrlQuery.append(" rUri.partition_id");
2177                        } else {
2178                                canonicalUrlQuery.append(" r.partition_id");
2179                        }
2180                        canonicalUrlQuery.append(" = :search_partition_id");
2181                        canonicalUrlQuery.append(" AND");
2182                }
2183                if (theReverse) {
2184                        canonicalUrlQuery.append(" rUri.res_id");
2185                } else {
2186                        canonicalUrlQuery.append(" r.src_resource_id");
2187                }
2188                canonicalUrlQuery.append(" IN (:target_pids)");
2189
2190                return Pair.of(canonicalUrlQuery.toString(), canonicalUriQueryParams);
2191        }
2192
2193        @Nonnull
2194        CanonicalUrlTargets calculateIndexUriIdentityHashesForResourceTypes(
2195                        RequestDetails theRequestDetails, Set<String> theTargetResourceTypes, boolean theReverse) {
2196                Set<String> targetResourceTypes = theTargetResourceTypes;
2197                if (targetResourceTypes == null) {
2198                        /*
2199                         * If we don't have a list of valid target types, we need to figure out a list of all
2200                         * possible target types in order to perform the search of the URI index table. This is
2201                         * because the hash_identity column encodes the resource type, so we'll need a hash
2202                         * value for each possible target type.
2203                         */
2204                        targetResourceTypes = new HashSet<>();
2205                        Set<String> possibleTypes = myDaoRegistry.getRegisteredDaoTypes();
2206                        if (theReverse) {
2207                                // For reverse includes, it is really hard to figure out what types
2208                                // are actually potentially pointing to the type we're searching for
2209                                // in this context, so let's just assume it could be anything.
2210                                targetResourceTypes = possibleTypes;
2211                        } else {
2212                                List<RuntimeSearchParam> params = mySearchParamRegistry
2213                                                .getActiveSearchParams(myResourceName, ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH)
2214                                                .values()
2215                                                .stream()
2216                                                .filter(t -> t.getParamType().equals(RestSearchParameterTypeEnum.REFERENCE))
2217                                                .toList();
2218                                for (var next : params) {
2219
2220                                        String paths = next.getPath();
2221                                        for (String path : SearchParameterUtil.splitSearchParameterExpressions(paths)) {
2222
2223                                                if (!SearchParameterUtil.referencePathCouldPotentiallyReferenceCanonicalElement(
2224                                                                myContext, myResourceName, path, theReverse)) {
2225                                                        continue;
2226                                                }
2227
2228                                                if (!next.getTargets().isEmpty()) {
2229                                                        // For each reference parameter on the resource type we're searching for,
2230                                                        // add all the potential target types to the list of possible target
2231                                                        // resource types we can look up.
2232                                                        for (var nextTarget : next.getTargets()) {
2233                                                                if (possibleTypes.contains(nextTarget)) {
2234                                                                        targetResourceTypes.add(nextTarget);
2235                                                                }
2236                                                        }
2237                                                } else {
2238                                                        // If we have any references that don't define any target types, then
2239                                                        // we need to assume that all enabled resource types are possible target
2240                                                        // types
2241                                                        targetResourceTypes.addAll(possibleTypes);
2242                                                        break;
2243                                                }
2244                                        }
2245                                }
2246                        }
2247                }
2248
2249                if (targetResourceTypes.isEmpty()) {
2250                        return new CanonicalUrlTargets(Set.of(), Set.of());
2251                }
2252
2253                Set<Long> hashIdentityValues = new HashSet<>();
2254                Set<Integer> partitionIds = new HashSet<>();
2255                for (String type : targetResourceTypes) {
2256
2257                        RequestPartitionId readPartition;
2258                        if (myPartitionSettings.isPartitioningEnabled()) {
2259                                readPartition =
2260                                                myPartitionHelperSvc.determineReadPartitionForRequestForSearchType(theRequestDetails, type);
2261                        } else {
2262                                readPartition = RequestPartitionId.defaultPartition();
2263                        }
2264                        if (readPartition.hasPartitionIds()) {
2265                                partitionIds.addAll(readPartition.getPartitionIds());
2266                        }
2267
2268                        Long hashIdentity = BaseResourceIndexedSearchParam.calculateHashIdentity(
2269                                        myPartitionSettings, readPartition, type, "url");
2270                        hashIdentityValues.add(hashIdentity);
2271                }
2272
2273                return new CanonicalUrlTargets(hashIdentityValues, partitionIds);
2274        }
2275
2276        record CanonicalUrlTargets(@Nonnull Set<Long> hashIdentityValues, @Nonnull Set<Integer> partitionIds) {
2277                public boolean isEmpty() {
2278                        return hashIdentityValues.isEmpty();
2279                }
2280        }
2281
2282        /**
2283         * This method takes in a list of {@link JpaPid}'s and returns a series of sublists containing
2284         * those pids where:
2285         * <ul>
2286         *     <li>No single list is more than {@literal theMaxLoad} entries</li>
2287         *     <li>Each list only contains JpaPids with the same partition ID</li>
2288         * </ul>
2289         */
2290        static List<Collection<JpaPid>> partitionBySizeAndPartitionId(List<JpaPid> theNextRoundMatches, int theMaxLoad) {
2291
2292                if (theNextRoundMatches.size() <= theMaxLoad) {
2293                        boolean allSamePartition = true;
2294                        for (int i = 1; i < theNextRoundMatches.size(); i++) {
2295                                if (!Objects.equals(
2296                                                theNextRoundMatches.get(i - 1).getPartitionId(),
2297                                                theNextRoundMatches.get(i).getPartitionId())) {
2298                                        allSamePartition = false;
2299                                        break;
2300                                }
2301                        }
2302                        if (allSamePartition) {
2303                                return Collections.singletonList(theNextRoundMatches);
2304                        }
2305                }
2306
2307                // Break into partitioned sublists
2308                ListMultimap<String, JpaPid> lists =
2309                                MultimapBuilder.hashKeys().arrayListValues().build();
2310                for (JpaPid nextRoundMatch : theNextRoundMatches) {
2311                        String partitionId = nextRoundMatch.getPartitionId() != null
2312                                        ? nextRoundMatch.getPartitionId().toString()
2313                                        : "";
2314                        lists.put(partitionId, nextRoundMatch);
2315                }
2316
2317                List<Collection<JpaPid>> retVal = new ArrayList<>();
2318                for (String key : lists.keySet()) {
2319                        List<List<JpaPid>> nextPartition = Lists.partition(lists.get(key), theMaxLoad);
2320                        retVal.addAll(nextPartition);
2321                }
2322
2323                // In unit test mode, we sort the results just for unit test predictability
2324                if (HapiSystemProperties.isUnitTestModeEnabled()) {
2325                        retVal = retVal.stream()
2326                                        .map(t -> t.stream().sorted().collect(Collectors.toList()))
2327                                        .collect(Collectors.toList());
2328                }
2329
2330                return retVal;
2331        }
2332
2333        private void attemptComboUniqueSpProcessing(
2334                        QueryStack theQueryStack, @Nonnull SearchParameterMap theParams, RequestDetails theRequest) {
2335                RuntimeSearchParam comboParam = null;
2336                List<String> comboParamNames = null;
2337                List<RuntimeSearchParam> exactMatchParams = mySearchParamRegistry.getActiveComboSearchParams(
2338                                myResourceName, theParams.keySet(), ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
2339                if (!exactMatchParams.isEmpty()) {
2340                        comboParam = exactMatchParams.get(0);
2341                        comboParamNames = new ArrayList<>(theParams.keySet());
2342                }
2343
2344                if (comboParam == null) {
2345                        List<RuntimeSearchParam> candidateComboParams = mySearchParamRegistry.getActiveComboSearchParams(
2346                                        myResourceName, ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
2347                        for (RuntimeSearchParam nextCandidate : candidateComboParams) {
2348                                List<String> nextCandidateParamNames =
2349                                                JpaParamUtil.resolveComponentParameters(mySearchParamRegistry, nextCandidate).stream()
2350                                                                .map(RuntimeSearchParam::getName)
2351                                                                .collect(Collectors.toList());
2352                                if (theParams.keySet().containsAll(nextCandidateParamNames)) {
2353                                        comboParam = nextCandidate;
2354                                        comboParamNames = nextCandidateParamNames;
2355                                        break;
2356                                }
2357                        }
2358                }
2359
2360                if (comboParam != null) {
2361                        Collections.sort(comboParamNames);
2362
2363                        // Since we're going to remove elements below
2364                        theParams.values().forEach(this::ensureSubListsAreWritable);
2365
2366                        /*
2367                         * Apply search against the combo param index in a loop:
2368                         *
2369                         * 1. First we check whether the actual parameter values in the
2370                         * parameter map are actually usable for searching against the combo
2371                         * param index. E.g. no search modifiers, date comparators, etc.,
2372                         * since these mean you can't use the combo index.
2373                         *
2374                         * 2. Apply and create the join SQl. We remove parameter values from
2375                         * the map as we apply them, so any parameter values remaining in the
2376                         * map after each loop haven't yet been factored into the SQL.
2377                         *
2378                         * The loop allows us to create multiple combo index joins if there
2379                         * are multiple AND expressions for the related parameters.
2380                         */
2381                        while (validateParamValuesAreValidForComboParam(theRequest, theParams, comboParamNames, comboParam)) {
2382                                applyComboSearchParam(theQueryStack, theParams, theRequest, comboParamNames, comboParam);
2383                        }
2384                }
2385        }
2386
2387        private void applyComboSearchParam(
2388                        QueryStack theQueryStack,
2389                        @Nonnull SearchParameterMap theParams,
2390                        RequestDetails theRequest,
2391                        List<String> theComboParamNames,
2392                        RuntimeSearchParam theComboParam) {
2393
2394                List<List<IQueryParameterType>> inputs = new ArrayList<>();
2395                for (String nextParamName : theComboParamNames) {
2396                        List<IQueryParameterType> nextValues = theParams.get(nextParamName).remove(0);
2397                        inputs.add(nextValues);
2398                }
2399
2400                List<List<IQueryParameterType>> inputPermutations = Lists.cartesianProduct(inputs);
2401                List<String> indexStrings = new ArrayList<>(CartesianProductUtil.calculateCartesianProductSize(inputs));
2402                for (List<IQueryParameterType> nextPermutation : inputPermutations) {
2403
2404                        StringBuilder searchStringBuilder = new StringBuilder();
2405                        searchStringBuilder.append(myResourceName);
2406                        searchStringBuilder.append("?");
2407
2408                        boolean first = true;
2409                        for (int paramIndex = 0; paramIndex < theComboParamNames.size(); paramIndex++) {
2410
2411                                String nextParamName = theComboParamNames.get(paramIndex);
2412                                IQueryParameterType nextOr = nextPermutation.get(paramIndex);
2413                                // The only prefix accepted when combo searching is 'eq' (see validateParamValuesAreValidForComboParam).
2414                                // As a result, we strip the prefix if present.
2415                                String nextOrValue = stripStart(nextOr.getValueAsQueryToken(myContext), EQUAL.getValue());
2416
2417                                RuntimeSearchParam nextParamDef = mySearchParamRegistry.getActiveSearchParam(
2418                                                myResourceName, nextParamName, ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
2419                                if (theComboParam.getComboSearchParamType() == ComboSearchParamType.NON_UNIQUE) {
2420                                        if (nextParamDef.getParamType() == RestSearchParameterTypeEnum.STRING) {
2421                                                nextOrValue = StringUtil.normalizeStringForSearchIndexing(nextOrValue);
2422                                        }
2423                                }
2424
2425                                if (first) {
2426                                        first = false;
2427                                } else {
2428                                        searchStringBuilder.append('&');
2429                                }
2430
2431                                nextParamName = UrlUtil.escapeUrlParam(nextParamName);
2432                                nextOrValue = UrlUtil.escapeUrlParam(nextOrValue);
2433
2434                                searchStringBuilder.append(nextParamName).append('=').append(nextOrValue);
2435                        }
2436
2437                        String indexString = searchStringBuilder.toString();
2438                        ourLog.debug(
2439                                        "Checking for {} combo index for query: {}", theComboParam.getComboSearchParamType(), indexString);
2440
2441                        indexStrings.add(indexString);
2442                }
2443
2444                // Just to make sure we're stable for tests
2445                indexStrings.sort(Comparator.naturalOrder());
2446
2447                // Interceptor broadcast: JPA_PERFTRACE_INFO
2448                IInterceptorBroadcaster compositeBroadcaster =
2449                                CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, theRequest);
2450                if (compositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_INFO)) {
2451                        String indexStringForLog = indexStrings.size() > 1 ? indexStrings.toString() : indexStrings.get(0);
2452                        StorageProcessingMessage msg = new StorageProcessingMessage()
2453                                        .setMessage("Using " + theComboParam.getComboSearchParamType() + " index(es) for query for search: "
2454                                                        + indexStringForLog);
2455                        HookParams params = new HookParams()
2456                                        .add(RequestDetails.class, theRequest)
2457                                        .addIfMatchesType(ServletRequestDetails.class, theRequest)
2458                                        .add(StorageProcessingMessage.class, msg);
2459                        compositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_INFO, params);
2460                }
2461
2462                switch (requireNonNull(theComboParam.getComboSearchParamType())) {
2463                        case UNIQUE:
2464                                theQueryStack.addPredicateCompositeUnique(indexStrings, myRequestPartitionId);
2465                                break;
2466                        case NON_UNIQUE:
2467                                theQueryStack.addPredicateCompositeNonUnique(indexStrings, myRequestPartitionId);
2468                                break;
2469                }
2470
2471                // Remove any empty parameters remaining after this
2472                theParams.clean();
2473        }
2474
2475        /**
2476         * Returns {@literal true} if the actual parameter instances in a given query are actually usable for
2477         * searching against a combo param with the given parameter names. This might be {@literal false} if
2478         * parameters have modifiers (e.g. <code>?name:exact=SIMPSON</code>), prefixes
2479         * (e.g. <code>?date=gt2024-02-01</code>), etc.
2480         */
2481        private boolean validateParamValuesAreValidForComboParam(
2482                        RequestDetails theRequest,
2483                        @Nonnull SearchParameterMap theParams,
2484                        List<String> theComboParamNames,
2485                        RuntimeSearchParam theComboParam) {
2486                boolean paramValuesAreValidForCombo = true;
2487                List<List<IQueryParameterType>> paramOrValues = new ArrayList<>(theComboParamNames.size());
2488
2489                for (String nextParamName : theComboParamNames) {
2490                        List<List<IQueryParameterType>> nextValues = theParams.get(nextParamName);
2491
2492                        if (nextValues == null || nextValues.isEmpty()) {
2493                                paramValuesAreValidForCombo = false;
2494                                break;
2495                        }
2496
2497                        List<IQueryParameterType> nextAndValue = nextValues.get(0);
2498                        paramOrValues.add(nextAndValue);
2499
2500                        for (IQueryParameterType nextOrValue : nextAndValue) {
2501                                if (nextOrValue instanceof DateParam dateParam) {
2502                                        if (dateParam.getPrecision() != TemporalPrecisionEnum.DAY) {
2503                                                String message = "Search with params " + theComboParamNames
2504                                                                + " is not a candidate for combo searching - Date search with non-DAY precision for parameter '"
2505                                                                + nextParamName + "'";
2506                                                firePerformanceInfo(theRequest, message);
2507                                                paramValuesAreValidForCombo = false;
2508                                                break;
2509                                        }
2510                                }
2511                                if (nextOrValue instanceof BaseParamWithPrefix<?> paramWithPrefix) {
2512                                        ParamPrefixEnum prefix = paramWithPrefix.getPrefix();
2513                                        // A parameter with the 'eq' prefix is the only accepted prefix when combo searching since
2514                                        // birthdate=2025-01-01 and birthdate=eq2025-01-01 are equivalent searches.
2515                                        if (prefix != null && prefix != EQUAL) {
2516                                                String message = "Search with params " + theComboParamNames
2517                                                                + " is not a candidate for combo searching - Parameter '" + nextParamName
2518                                                                + "' has prefix: '"
2519                                                                + paramWithPrefix.getPrefix().getValue() + "'";
2520                                                firePerformanceInfo(theRequest, message);
2521                                                paramValuesAreValidForCombo = false;
2522                                                break;
2523                                        }
2524                                }
2525                                if (isNotBlank(nextOrValue.getQueryParameterQualifier())) {
2526                                        String message = "Search with params " + theComboParamNames
2527                                                        + " is not a candidate for combo searching - Parameter '" + nextParamName
2528                                                        + "' has modifier: '" + nextOrValue.getQueryParameterQualifier() + "'";
2529                                        firePerformanceInfo(theRequest, message);
2530                                        paramValuesAreValidForCombo = false;
2531                                        break;
2532                                }
2533                        }
2534
2535                        // Reference params are only eligible for using a composite index if they
2536                        // are qualified
2537                        RuntimeSearchParam nextParamDef = mySearchParamRegistry.getActiveSearchParam(
2538                                        myResourceName, nextParamName, ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
2539                        if (nextParamDef.getParamType() == RestSearchParameterTypeEnum.REFERENCE) {
2540                                ReferenceParam param = (ReferenceParam) nextValues.get(0).get(0);
2541                                if (isBlank(param.getResourceType())) {
2542                                        ourLog.debug(
2543                                                        "Search is not a candidate for unique combo searching - Reference with no type specified");
2544                                        paramValuesAreValidForCombo = false;
2545                                        break;
2546                                }
2547                        }
2548
2549                        // Date params are not eligible for using composite unique index
2550                        // as index could contain date with different precision (e.g. DAY, SECOND)
2551                        if (nextParamDef.getParamType() == RestSearchParameterTypeEnum.DATE
2552                                        && theComboParam.getComboSearchParamType() == ComboSearchParamType.UNIQUE) {
2553                                ourLog.debug(
2554                                                "Search with params {} is not a candidate for combo searching - "
2555                                                                + "Unique combo search parameter '{}' has DATE type",
2556                                                theComboParamNames,
2557                                                nextParamName);
2558                                paramValuesAreValidForCombo = false;
2559                                break;
2560                        }
2561                }
2562
2563                if (CartesianProductUtil.calculateCartesianProductSize(paramOrValues) > 500) {
2564                        ourLog.debug(
2565                                        "Search is not a candidate for unique combo searching - Too many OR values would result in too many permutations");
2566                        paramValuesAreValidForCombo = false;
2567                }
2568
2569                return paramValuesAreValidForCombo;
2570        }
2571
2572        private <T> void ensureSubListsAreWritable(List<List<T>> theListOfLists) {
2573                for (int i = 0; i < theListOfLists.size(); i++) {
2574                        List<T> oldSubList = theListOfLists.get(i);
2575                        if (!(oldSubList instanceof ArrayList)) {
2576                                List<T> newSubList = new ArrayList<>(oldSubList);
2577                                theListOfLists.set(i, newSubList);
2578                        }
2579                }
2580        }
2581
2582        @Override
2583        public void setFetchSize(int theFetchSize) {
2584                myFetchSize = theFetchSize;
2585        }
2586
2587        public SearchParameterMap getParams() {
2588                return myParams;
2589        }
2590
2591        public CriteriaBuilder getBuilder() {
2592                return myCriteriaBuilder;
2593        }
2594
2595        public Class<? extends IBaseResource> getResourceType() {
2596                return myResourceType;
2597        }
2598
2599        public String getResourceName() {
2600                return myResourceName;
2601        }
2602
2603        /**
2604         * IncludesIterator, used to recursively fetch resources from the provided list of PIDs
2605         */
2606        private class IncludesIterator extends BaseIterator<JpaPid> implements Iterator<JpaPid> {
2607
2608                private final RequestDetails myRequest;
2609                private final Set<JpaPid> myCurrentPids;
2610                private Iterator<JpaPid> myCurrentIterator;
2611                private JpaPid myNext;
2612
2613                IncludesIterator(Set<JpaPid> thePidSet, RequestDetails theRequest) {
2614                        myCurrentPids = new HashSet<>(thePidSet);
2615                        myCurrentIterator = null;
2616                        myRequest = theRequest;
2617                }
2618
2619                private void fetchNext() {
2620                        while (myNext == null) {
2621
2622                                if (myCurrentIterator == null) {
2623                                        Set<Include> includes = new HashSet<>();
2624                                        if (myParams.containsKey(Constants.PARAM_TYPE)) {
2625                                                for (List<IQueryParameterType> typeList : myParams.get(Constants.PARAM_TYPE)) {
2626                                                        for (IQueryParameterType type : typeList) {
2627                                                                String queryString = ParameterUtil.unescape(type.getValueAsQueryToken(myContext));
2628                                                                for (String resourceType : queryString.split(",")) {
2629                                                                        String rt = resourceType.trim();
2630                                                                        if (isNotBlank(rt)) {
2631                                                                                includes.add(new Include(rt + ":*", true));
2632                                                                        }
2633                                                                }
2634                                                        }
2635                                                }
2636                                        }
2637                                        if (includes.isEmpty()) {
2638                                                includes.add(new Include("*", true));
2639                                        }
2640                                        Set<JpaPid> newPids = loadIncludes(
2641                                                        myContext,
2642                                                        myEntityManager,
2643                                                        myCurrentPids,
2644                                                        includes,
2645                                                        false,
2646                                                        getParams().getLastUpdated(),
2647                                                        mySearchUuid,
2648                                                        myRequest,
2649                                                        null);
2650                                        myCurrentIterator = newPids.iterator();
2651                                }
2652
2653                                if (myCurrentIterator.hasNext()) {
2654                                        myNext = myCurrentIterator.next();
2655                                } else {
2656                                        myNext = NO_MORE;
2657                                }
2658                        }
2659                }
2660
2661                @Override
2662                public boolean hasNext() {
2663                        fetchNext();
2664                        return !NO_MORE.equals(myNext);
2665                }
2666
2667                @Override
2668                public JpaPid next() {
2669                        fetchNext();
2670                        JpaPid retVal = myNext;
2671                        myNext = null;
2672                        return retVal;
2673                }
2674        }
2675        /**
2676         * Basic Query iterator, used to fetch the results of a query.
2677         */
2678        private final class QueryIterator extends BaseIterator<JpaPid> implements IResultIterator<JpaPid> {
2679
2680                private final SearchRuntimeDetails mySearchRuntimeDetails;
2681
2682                private final RequestDetails myRequest;
2683                private final boolean myHaveRawSqlHooks;
2684                private final boolean myHavePerfTraceFoundIdHook;
2685                private final SortSpec mySort;
2686                private final Integer myOffset;
2687                private final IInterceptorBroadcaster myCompositeBroadcaster;
2688                private boolean myFirst = true;
2689                private IncludesIterator myIncludesIterator;
2690                /**
2691                 * The next JpaPid value of the next result in this query.
2692                 * Will not be null if fetched using getNext()
2693                 */
2694                private JpaPid myNext;
2695                /**
2696                 * The current query result iterator running sql and supplying PIDs
2697                 * @see #myQueryList
2698                 */
2699                private ISearchQueryExecutor myResultsIterator;
2700
2701                private boolean myFetchIncludesForEverythingOperation;
2702
2703                /**
2704                 * The count of resources skipped because they were seen in earlier results
2705                 */
2706                private int mySkipCount = 0;
2707                /**
2708                 * The count of resources that are new in this search
2709                 * (ie, not cached in previous searches)
2710                 */
2711                private int myNonSkipCount = 0;
2712                /**
2713                 * The list of queries to use to find all results.
2714                 * Normal JPA queries will normally have a single entry.
2715                 * Queries that involve Hibernate Search/Elasticsearch may have
2716                 * multiple queries because of chunking.
2717                 * The $everything operation also jams some extra results in.
2718                 */
2719                private List<ISearchQueryExecutor> myQueryList = new ArrayList<>();
2720
2721                private QueryIterator(SearchRuntimeDetails theSearchRuntimeDetails, RequestDetails theRequest) {
2722                        mySearchRuntimeDetails = theSearchRuntimeDetails;
2723                        mySort = myParams.getSort();
2724                        myOffset = myParams.getOffset();
2725                        myRequest = theRequest;
2726                        myCompositeBroadcaster =
2727                                        CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, theRequest);
2728
2729                        // everything requires fetching recursively all related resources
2730                        if (myParams.getEverythingMode() != null) {
2731                                myFetchIncludesForEverythingOperation = true;
2732                        }
2733
2734                        myHavePerfTraceFoundIdHook = myCompositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_SEARCH_FOUND_ID);
2735                        myHaveRawSqlHooks = myCompositeBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_RAW_SQL);
2736                }
2737
2738                private void fetchNext() {
2739                        try {
2740                                if (myHaveRawSqlHooks) {
2741                                        CurrentThreadCaptureQueriesListener.startCapturing();
2742                                }
2743
2744                                // If we don't have a query yet, create one
2745                                if (myResultsIterator == null) {
2746                                        if (!mySearchProperties.hasMaxResultsRequested()) {
2747                                                mySearchProperties.setMaxResultsRequested(calculateMaxResultsToFetch());
2748                                        }
2749
2750                                        /*
2751                                         * assigns the results iterator
2752                                         * and populates the myQueryList.
2753                                         */
2754                                        initializeIteratorQuery(myOffset, mySearchProperties.getMaxResultsRequested());
2755                                }
2756
2757                                if (myNext == null) {
2758                                        // no next means we need a new query (if one is available)
2759                                        while (myResultsIterator.hasNext() || !myQueryList.isEmpty()) {
2760                                                /*
2761                                                 * Because we combine our DB searches with Lucene
2762                                                 * sometimes we can have multiple results iterators
2763                                                 * (with only some having data in them to extract).
2764                                                 *
2765                                                 * We'll iterate our results iterators until we
2766                                                 * either run out of results iterators, or we
2767                                                 * have one that actually has data in it.
2768                                                 */
2769                                                while (!myResultsIterator.hasNext() && !myQueryList.isEmpty()) {
2770                                                        retrieveNextIteratorQuery();
2771                                                }
2772
2773                                                if (!myResultsIterator.hasNext()) {
2774                                                        // we couldn't find a results iterator;
2775                                                        // we're done here
2776                                                        break;
2777                                                }
2778
2779                                                JpaPid nextPid = myResultsIterator.next();
2780                                                if (myHavePerfTraceFoundIdHook) {
2781                                                        callPerformanceTracingHook(nextPid);
2782                                                }
2783
2784                                                if (nextPid != null) {
2785                                                        if (!myPidSet.contains(nextPid)) {
2786                                                                if (!mySearchProperties.isDeduplicateInDatabase()) {
2787                                                                        /*
2788                                                                         * We only add to the map if we aren't fetching "everything";
2789                                                                         * otherwise, we let the de-duplication happen in the database
2790                                                                         * (see createChunkedQueryNormalSearch above), because it
2791                                                                         * saves memory that way.
2792                                                                         */
2793                                                                        myPidSet.add(nextPid);
2794                                                                }
2795                                                                if (doNotSkipNextPidForEverything()) {
2796                                                                        myNext = nextPid;
2797                                                                        myNonSkipCount++;
2798                                                                        break;
2799                                                                }
2800                                                        } else {
2801                                                                mySkipCount++;
2802                                                        }
2803                                                }
2804
2805                                                if (!myResultsIterator.hasNext()) {
2806                                                        if (mySearchProperties.hasMaxResultsRequested()
2807                                                                        && (mySkipCount + myNonSkipCount == mySearchProperties.getMaxResultsRequested())) {
2808                                                                if (mySkipCount > 0 && myNonSkipCount == 0) {
2809                                                                        sendProcessingMsgAndFirePerformanceHook();
2810                                                                        // need the next iterator; increase the maxsize
2811                                                                        // (we should always do this)
2812                                                                        int maxResults = mySearchProperties.getMaxResultsRequested() + 1000;
2813                                                                        mySearchProperties.setMaxResultsRequested(maxResults);
2814
2815                                                                        if (!mySearchProperties.isDeduplicateInDatabase()) {
2816                                                                                // if we're not using the database to deduplicate
2817                                                                                // we should recheck our memory usage
2818                                                                                // the prefetch size check is future proofing
2819                                                                                int prefetchSize = myStorageSettings
2820                                                                                                .getSearchPreFetchThresholds()
2821                                                                                                .size();
2822                                                                                if (prefetchSize > 0) {
2823                                                                                        if (myStorageSettings
2824                                                                                                                        .getSearchPreFetchThresholds()
2825                                                                                                                        .get(prefetchSize - 1)
2826                                                                                                        < mySearchProperties.getMaxResultsRequested()) {
2827                                                                                                mySearchProperties.setDeduplicateInDatabase(true);
2828                                                                                        }
2829                                                                                }
2830                                                                        }
2831
2832                                                                        initializeIteratorQuery(myOffset, mySearchProperties.getMaxResultsRequested());
2833                                                                }
2834                                                        }
2835                                                }
2836                                        }
2837                                }
2838
2839                                if (myNext == null) {
2840                                        // if we got here, it means the current JpaPid has already been processed,
2841                                        // and we will decide (here) if we need to fetch related resources recursively
2842                                        if (myFetchIncludesForEverythingOperation) {
2843                                                myIncludesIterator = new IncludesIterator(myPidSet, myRequest);
2844                                                myFetchIncludesForEverythingOperation = false;
2845                                        }
2846                                        if (myIncludesIterator != null) {
2847                                                while (myIncludesIterator.hasNext()) {
2848                                                        JpaPid next = myIncludesIterator.next();
2849                                                        if (next != null && myPidSet.add(next) && doNotSkipNextPidForEverything()) {
2850                                                                myNext = next;
2851                                                                break;
2852                                                        }
2853                                                }
2854                                                if (myNext == null) {
2855                                                        myNext = NO_MORE;
2856                                                }
2857                                        } else {
2858                                                myNext = NO_MORE;
2859                                        }
2860                                }
2861
2862                                if (!mySearchProperties.hasMaxResultsRequested()) {
2863                                        mySearchRuntimeDetails.setFoundIndexMatchesCount(myNonSkipCount);
2864                                } else {
2865                                        mySearchRuntimeDetails.setFoundMatchesCount(myPidSet.size());
2866                                }
2867
2868                        } finally {
2869                                // search finished - fire hooks
2870                                if (myHaveRawSqlHooks) {
2871                                        callRawSqlHookWithCurrentThreadQueries(myRequest, myCompositeBroadcaster);
2872                                }
2873                        }
2874
2875                        if (myFirst) {
2876                                HookParams params = new HookParams()
2877                                                .add(RequestDetails.class, myRequest)
2878                                                .addIfMatchesType(ServletRequestDetails.class, myRequest)
2879                                                .add(SearchRuntimeDetails.class, mySearchRuntimeDetails);
2880                                myCompositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_SEARCH_FIRST_RESULT_LOADED, params);
2881                                myFirst = false;
2882                        }
2883
2884                        if (NO_MORE.equals(myNext)) {
2885                                HookParams params = new HookParams()
2886                                                .add(RequestDetails.class, myRequest)
2887                                                .addIfMatchesType(ServletRequestDetails.class, myRequest)
2888                                                .add(SearchRuntimeDetails.class, mySearchRuntimeDetails);
2889                                myCompositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_SEARCH_SELECT_COMPLETE, params);
2890                        }
2891                }
2892
2893                private Integer calculateMaxResultsToFetch() {
2894                        if (myParams.getLoadSynchronousUpTo() != null) {
2895                                return myParams.getLoadSynchronousUpTo();
2896                        } else if (myParams.getOffset() != null && myParams.getCount() != null) {
2897                                return myParams.getEverythingMode() != null
2898                                                ? myParams.getOffset() + myParams.getCount()
2899                                                : myParams.getCount();
2900                        } else {
2901                                return myStorageSettings.getFetchSizeDefaultMaximum();
2902                        }
2903                }
2904
2905                private boolean doNotSkipNextPidForEverything() {
2906                        return !(myParams.getEverythingMode() != null && (myOffset != null && myOffset >= myPidSet.size()));
2907                }
2908
2909                private void callPerformanceTracingHook(JpaPid theNextPid) {
2910                        HookParams params = new HookParams()
2911                                        .add(Integer.class, System.identityHashCode(this))
2912                                        .add(Object.class, theNextPid);
2913                        myCompositeBroadcaster.callHooks(Pointcut.JPA_PERFTRACE_SEARCH_FOUND_ID, params);
2914                }
2915
2916                private void sendProcessingMsgAndFirePerformanceHook() {
2917                        String msg = "Pass completed with no matching results seeking rows "
2918                                        + myPidSet.size() + "-" + mySkipCount
2919                                        + ". This indicates an inefficient query! Retrying with new max count of "
2920                                        + mySearchProperties.getMaxResultsRequested();
2921                        firePerformanceWarning(myRequest, msg);
2922                }
2923
2924                private void initializeIteratorQuery(Integer theOffset, Integer theMaxResultsToFetch) {
2925                        Integer offset = theOffset;
2926                        if (myQueryList.isEmpty()) {
2927                                // Capture times for Lucene/Elasticsearch queries as well
2928                                mySearchRuntimeDetails.setQueryStopwatch(new StopWatch());
2929
2930                                // setting offset to 0 to fetch all resource ids to guarantee
2931                                // correct output result for everything operation during paging
2932                                if (myParams.getEverythingMode() != null) {
2933                                        offset = 0;
2934                                }
2935
2936                                SearchQueryProperties properties = mySearchProperties.clone();
2937                                properties
2938                                                .setOffset(offset)
2939                                                .setMaxResultsRequested(theMaxResultsToFetch)
2940                                                .setDoCountOnlyFlag(false)
2941                                                .setDeduplicateInDatabase(properties.isDeduplicateInDatabase() || offset != null);
2942                                myQueryList = createQuery(myParams, properties, myRequest, mySearchRuntimeDetails);
2943                        }
2944
2945                        mySearchRuntimeDetails.setQueryStopwatch(new StopWatch());
2946
2947                        retrieveNextIteratorQuery();
2948
2949                        mySkipCount = 0;
2950                        myNonSkipCount = 0;
2951                }
2952
2953                private void retrieveNextIteratorQuery() {
2954                        close();
2955                        if (isNotEmpty(myQueryList)) {
2956                                myResultsIterator = myQueryList.remove(0);
2957                                myHasNextIteratorQuery = true;
2958                        } else {
2959                                myResultsIterator = SearchQueryExecutor.emptyExecutor();
2960                                myHasNextIteratorQuery = false;
2961                        }
2962                }
2963
2964                @Override
2965                public boolean hasNext() {
2966                        if (myNext == null) {
2967                                fetchNext();
2968                        }
2969                        return !NO_MORE.equals(myNext);
2970                }
2971
2972                @Override
2973                public JpaPid next() {
2974                        fetchNext();
2975                        JpaPid retVal = myNext;
2976                        myNext = null;
2977                        Validate.isTrue(!NO_MORE.equals(retVal), "No more elements");
2978                        return retVal;
2979                }
2980
2981                @Override
2982                public int getSkippedCount() {
2983                        return mySkipCount;
2984                }
2985
2986                @Override
2987                public int getNonSkippedCount() {
2988                        return myNonSkipCount;
2989                }
2990
2991                @Override
2992                public Collection<JpaPid> getNextResultBatch(long theBatchSize) {
2993                        Collection<JpaPid> batch = new ArrayList<>();
2994                        while (this.hasNext() && batch.size() < theBatchSize) {
2995                                batch.add(this.next());
2996                        }
2997                        return batch;
2998                }
2999
3000                @Override
3001                public void close() {
3002                        if (myResultsIterator != null) {
3003                                myResultsIterator.close();
3004                        }
3005                        myResultsIterator = null;
3006                }
3007        }
3008
3009        private void firePerformanceInfo(RequestDetails theRequest, String theMessage) {
3010                // Only log at debug level since these messages aren't considered important enough
3011                // that we should be cluttering the system log, but they are important to the
3012                // specific query being executed to we'll INFO level them there
3013                ourLog.debug(theMessage);
3014                firePerformanceMessage(theRequest, theMessage, Pointcut.JPA_PERFTRACE_INFO);
3015        }
3016
3017        private void firePerformanceWarning(RequestDetails theRequest, String theMessage) {
3018                ourLog.warn(theMessage);
3019                firePerformanceMessage(theRequest, theMessage, Pointcut.JPA_PERFTRACE_WARNING);
3020        }
3021
3022        private void firePerformanceMessage(RequestDetails theRequest, String theMessage, Pointcut thePointcut) {
3023                IInterceptorBroadcaster compositeBroadcaster =
3024                                CompositeInterceptorBroadcaster.newCompositeBroadcaster(myInterceptorBroadcaster, theRequest);
3025                if (compositeBroadcaster.hasHooks(thePointcut)) {
3026                        StorageProcessingMessage message = new StorageProcessingMessage();
3027                        message.setMessage(theMessage);
3028                        HookParams params = new HookParams()
3029                                        .add(RequestDetails.class, theRequest)
3030                                        .addIfMatchesType(ServletRequestDetails.class, theRequest)
3031                                        .add(StorageProcessingMessage.class, message);
3032                        compositeBroadcaster.callHooks(thePointcut, params);
3033                }
3034        }
3035
3036        public static int getMaximumPageSize() {
3037                if (myMaxPageSizeForTests != null) {
3038                        return myMaxPageSizeForTests;
3039                }
3040                return MAXIMUM_PAGE_SIZE;
3041        }
3042
3043        public static void setMaxPageSizeForTest(Integer theTestSize) {
3044                myMaxPageSizeForTests = theTestSize;
3045        }
3046
3047        private static ScrollableResults<?> toScrollableResults(Query theQuery) {
3048                org.hibernate.query.Query<?> hibernateQuery = (org.hibernate.query.Query<?>) theQuery;
3049                return hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
3050        }
3051}