hapifhir / hapi-fhir

🔥 HAPI FHIR - Java API for HL7 FHIR Clients and Servers
http://hapifhir.io
Apache License 2.0
2k stars 1.31k forks source link

ConstraintViolationException during $expunge #2068

Open rbhman opened 4 years ago

rbhman commented 4 years ago

The exception below was encountered during running $expunge on my Postgres hapi-fhir-jpaserver (5.1.0). The database is in early stages of being populated, but lots of patient and related resources have been successfully added during this development phase of the project.

I note though that some data may have been populated while using an earlier version of hapi (4.1.0?)

Note that empi.enabled=false.

Here are the hapi.properties:

fhir_version=R4

server_address=http://localhost:8080/hapi-fhir-jpaserver/fhir/

enable_index_missing_fields=false
auto_create_placeholder_reference_targets=false
enforce_referential_integrity_on_write=false
enforce_referential_integrity_on_delete=false
default_encoding=JSON
etag_support=ENABLED
reuse_cached_search_results_millis=60000
retain_cached_searches_mins=60
default_page_size=20
max_page_size=200
allow_override_default_search_params=true
allow_contains_searches=true
allow_multiple_delete=true
allow_external_references=true
allow_cascading_deletes=true
allow_placeholder_references=true
expunge_enabled=true
persistence_unit_name=HAPI_PU
logger.name=fhirtest.access
logger.format=Path[${servletPath}] Source[${requestHeader.x-forwarded-for}] Operation[${operationType} ${operationName} ${idOrResourceName}] UA[${requestHeader.user-agent}] Params[${requestParameters}] ResponseEncoding[${responseEncodingNoDefault}]
logger.error_format=ERROR - ${requestVerb} ${requestUrl}
logger.log_exceptions=true

datasource.driver=org.postgresql.Driver
datasource.url=jdbc:postgresql://localhost:5432/pmds_research
hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect
datasource.username=admin
datasource.password=admin
#datasource.driver=org.h2.Driver
#datasource.url=jdbc:h2:file:./target/database/h2
#datasource.username=
#datasource.password=
server.name=http://localhost:8080/hapi-fhir-jpaserver/fhir/
server.id=home
test.port=

max_binary_size=104857600

# Should all incoming requests be validated
validation.requests.enabled=false
# Should outgoing responses be validated
validation.responses.enabled=false

filter_search.enabled=true
graphql.enabled=true
# See FhirPathFilterInterceptor
fhirpath_interceptor.enabled=false

#hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.search.model_mapping=ca.uhn.fhir.jpa.search.LuceneSearchMappingFactory
hibernate.format_sql=false
hibernate.show_sql=false
hibernate.hbm2ddl.auto=update
hibernate.jdbc.batch_size=20
hibernate.cache.use_query_cache=false
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_structured_entries=false
hibernate.cache.use_minimal_puts=false
hibernate.search.default.directory_provider=filesystem
hibernate.search.default.indexBase=target/lucenefiles
hibernate.search.lucene_version=LUCENE_CURRENT
tester.config.refuse_to_fetch_third_party_urls=false

elasticsearch.enabled=false
elasticsearch.rest_url=http://localhost:9200
elasticsearch.username=SomeUsername
elasticsearch.password=SomePassword
elasticsearch.required_index_status=YELLOW
elasticsearch.schema_management_strategy=CREATE
# Immediately refresh indexes after every write. This is very bad for
# performance, but can be helpful for testing.
elasticsearch.debug.refresh_after_write=false
elasticsearch.debug.pretty_print_json_log=false

binary_storage.enabled=true

bulk.export.enabled=true

cors.enabled=true
cors.allowCredentials=true
# Supports multiple, comma separated allowed origin entries
# cors.allowed_origin=http://localhost:8080,https://localhost:8080,https://fhirtest.uhn.ca
cors.allowed_origin=*

subscription.resthook.enabled=false

# Enable Email Subscription Channel
subscription.email.enabled=false
email.enabled=false
email.from=some@test.com
email.host=
email.port=0
email.username=
email.password=

# Enable Websocket Subscription Channel
subscription.websocket.enabled=false

empi.enabled=false

partitioning.multitenancy.enabled=false
#daoconfig.client_id_strategy=ANY

The body of the expunge request:

{ "resourceType": "Parameters", "parameter": [ { "name": "expungeEverything", "valueBoolean": true } ] }

Here is the pom:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--
    Note: HAPI projects use the "hapi-fhir" POM as their base to provide easy management.
    You do not need to use this in your own projects, so the "parent" tag and it's
    contents below may be removed
    if you are using this file as a basis for your own project.
    -->
    <parent>
        <groupId>ca.uhn.hapi.fhir</groupId>
        <artifactId>hapi-fhir</artifactId>
        <version>5.1.0</version>
    </parent>

    <artifactId>hapi-fhir-jpaserver-starter</artifactId>

    <prerequisites>
        <maven>3.5.0</maven>
    </prerequisites>

    <packaging>war</packaging>

    <name>HAPI FHIR JPA Server - Starter Project</name>

    <repositories>
        <repository>
            <id>oss-snapshots</id>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-api</artifactId>
            <version>${jetty_version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-client</artifactId>
            <version>${jetty_version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.9</version>
        </dependency>

        <!-- Needed for Email subscriptions -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>javax.activation</groupId>
                    <artifactId>activation</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
        </dependency>
        -->

        <!-- This dependency includes the core HAPI-FHIR classes -->
        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-base</artifactId>
            <version>${project.version}</version>
        </dependency>

        <!-- This dependency includes the JPA server itself, which is packaged separately from the rest of HAPI FHIR -->
        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-jpaserver-base</artifactId>
            <version>${project.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-jcl</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- This dependency includes the JPA EMPI Server -->
        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-jpaserver-empi</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- This dependency is used for the "FHIR Tester" web app overlay -->
        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-testpage-overlay</artifactId>
            <version>${project.version}</version>
            <type>war</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-testpage-overlay</artifactId>
            <version>${project.version}</version>
            <classifier>classes</classifier>
            <scope>provided</scope>
        </dependency>

        <!-- HAPI-FHIR uses Logback for logging support. The logback library is included automatically by Maven as a part of the hapi-fhir-base dependency, but you also need to include a logging library. Logback
            is used here, but log4j would also be fine. -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <!-- Needed for JEE/Servlet support -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- If you are using HAPI narrative generation, you will need to include Thymeleaf as well. Otherwise the following can be omitted. -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
        </dependency>

        <!-- Used for CORS support -->
        <!-- Spring Web is used to deploy the server to a web container. -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <!-- You may not need this if you are deploying to an application server which provides database connection pools itself. -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- This example uses H2 embedded database. If you are using another database such as Mysql or Oracle, you may omit the following dependencies and replace them with an appropriate database client
            dependency for your database platform. -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <!-- webjars -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>Eonasdan-bootstrap-datetimepicker</artifactId>
            <version>4.17.43</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>font-awesome</artifactId>
            <version>5.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>awesome-bootstrap-checkbox</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jstimezonedetect</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>select2</artifactId>
            <version>4.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>moment</artifactId>
            <version>2.15.1</version>
        </dependency>

        <!-- The following dependencies are only needed for automated unit tests, you do not neccesarily need them to run the example. -->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-server</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <scope>test</scope>
        </dependency>
        <!--
        <dependency>
            <groupId>com.helger</groupId>
            <artifactId>ph-schematron</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>Saxon-HE</artifactId>
                    <groupId>net.sf.saxon</groupId>
                </exclusion>
            </exclusions>
        </dependency>
            -->

        <!--
        For some reason JavaDoc crashed during site generation unless we have this dependency
        -->
        <dependency>
            <groupId>javax.interceptor</groupId>
            <artifactId>javax.interceptor-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>ca.uhn.hapi.fhir</groupId>
            <artifactId>hapi-fhir-test-utilities</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <version>4.0.0-rc1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>

        <!-- Tells Maven to name the generated WAR file as hapi-fhir-jpaserver.war -->
        <finalName>hapi-fhir-jpaserver</finalName>

        <plugins>
            <!-- The following is not required for the application to build, but allows you to test it by issuing "mvn jetty:run" from the command line. -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                     <version>${jetty_version}</version>
                <configuration>
                    <webApp>
                        <contextPath>/hapi-fhir-jpaserver</contextPath>
                        <allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>
                    </webApp>
                </configuration>
            </plugin>

            <!-- Tell Maven which Java source version you want to use -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- The configuration here tells the WAR plugin to include the FHIR Tester overlay. You can omit it if you are not using that feature. -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Build-Time>${maven.build.timestamp}</Build-Time>
                        </manifestEntries>
                    </archive>
                    <overlays>
                        <overlay>
                            <groupId>ca.uhn.hapi.fhir</groupId>
                            <artifactId>hapi-fhir-testpage-overlay</artifactId>
                        </overlay>
                    </overlays>
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                </configuration>
            </plugin>

            <!-- This is to run the integration tests -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <configuration>
                    <redirectTestOutputToFile>true</redirectTestOutputToFile>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.basepom.maven</groupId>
                <artifactId>duplicate-finder-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <inherited>true</inherited>
                    </execution>
                </executions>
                <configuration>
                    <failBuildInCaseOfConflict>true</failBuildInCaseOfConflict>
                    <checkTestClasspath>false</checkTestClasspath>
                    <!--
                    <printEqualFiles>false</printEqualFiles>
                    <failBuildInCaseOfDifferentContentConflict>true</failBuildInCaseOfDifferentContentConflict>
                    <failBuildInCaseOfEqualContentConflict>true</failBuildInCaseOfEqualContentConflict>
                    <failBuildInCaseOfConflict>true</failBuildInCaseOfConflict>
                    <checkCompileClasspath>true</checkCompileClasspath>
                    <checkRuntimeClasspath>false</checkRuntimeClasspath>
                    <skip>false</skip>
                    <quiet>false</quiet>
                    <preferLocal>true</preferLocal>
                    <useResultFile>true</useResultFile>
                    <resultFileMinClasspathCount>2</resultFileMinClasspathCount>
                    <resultFile>${project.build.directory}/duplicate-finder-result.xml</resultFile>
                    -->
                    <!--
                    <ignoredDependencies>
                        <dependency>
                            <groupId>javax.el</groupId>
                            <artifactId>javax.el-api</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>javax.mail</groupId>
                            <artifactId>javax.mail-api</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>javax.activation</groupId>
                            <artifactId>javax.activation-api</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>com.helger</groupId>
                            <artifactId>ph-schematron</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>commons-logging</groupId>
                            <artifactId>commons-logging</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.jscience</groupId>
                            <artifactId>jscience</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-jcl</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-jcl</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>com.google.code.findbugs</groupId>
                            <artifactId>annotations</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.apache.derby</groupId>
                            <artifactId>derbyclient</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.apache.derby</groupId>
                            <artifactId>derbynet</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.apache.derby</groupId>
                            <artifactId>derbyclient</artifactId>
                        </dependency>
                        <dependency>
                            <groupId>org.checkerframework</groupId>
                            <artifactId>checker-compat-qual</artifactId>
                        </dependency>
                    </ignoredDependencies>
                    -->
                    <ignoredResourcePatterns>
                        <ignoredResourcePattern>.*\.txt$</ignoredResourcePattern>
                        <ignoredResourcePattern>.*\.html$</ignoredResourcePattern>
                        <ignoredResourcePattern>config/favicon.ico</ignoredResourcePattern>
                    </ignoredResourcePatterns>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

Here is the exception:

...
2020-09-07 13:38:01.788 [qtp2009502388-16] INFO  c.u.f.j.d.e.ExpungeEverythingService [ExpungeEverythingService.java:197] Have deleted 193000 entities of type ResourceTable in 2084ms
2020-09-07 13:38:04.125 [qtp2009502388-16] INFO  c.u.f.j.d.e.ExpungeEverythingService [ExpungeEverythingService.java:197] Have deleted 194000 entities of type ResourceTable in 2336ms
2020-09-07 13:38:05.742 [qtp2009502388-16] INFO  o.h.e.j.b.internal.AbstractBatchImpl [AbstractBatchImpl.java:208] HHH000010: On release of batch it still contained JDBC statements
2020-09-07 13:38:05.744 [qtp2009502388-16] ERROR o.h.e.j.batch.internal.BatchingBatch [BatchingBatch.java:128] HHH000315: Exception executing batch [java.sql.BatchUpdateException: Batch entry 17 delete from HFJ_RESOURCE where RES_ID=206 and RES_VER=1 was aborted: ERROR: update or delete on table "hfj_resource" violates foreign key constraint "fk_empi_link_target" on table "mpi_link"
  Detail: Key (res_id)=(206) is still referenced from table "mpi_link".  Call getNextException to see other errors in the batch.], SQL: delete from HFJ_RESOURCE where RES_ID=? and RES_VER=?
2020-09-07 13:38:05.746 [qtp2009502388-16] WARN  o.h.e.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:137] SQL Error: 0, SQLState: 23503
2020-09-07 13:38:05.747 [qtp2009502388-16] ERROR o.h.e.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:142] Batch entry 17 delete from HFJ_RESOURCE where RES_ID=206 and RES_VER=1 was aborted: ERROR: update or delete on table "hfj_resource" violates foreign key constraint "fk_empi_link_target" on table "mpi_link"
  Detail: Key (res_id)=(206) is still referenced from table "mpi_link".  Call getNextException to see other errors in the batch.
2020-09-07 13:38:05.748 [qtp2009502388-16] ERROR o.h.e.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:142] ERROR: update or delete on table "hfj_resource" violates foreign key constraint "fk_empi_link_target" on table "mpi_link"
  Detail: Key (res_id)=(206) is still referenced from table "mpi_link".
2020-09-07 13:38:05.774 [qtp2009502388-16] ERROR c.u.f.r.s.i.ExceptionHandlingInterceptor [ExceptionHandlingInterceptor.java:140] Failure during REST processing
ca.uhn.fhir.rest.server.exceptions.InternalErrorException: Failed to call access method: org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [delete from HFJ_RESOURCE where RES_ID=? and RES_VER=?]; constraint [fk_empi_link_target]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute batch
        at ca.uhn.fhir.rest.server.method.BaseMethodBinding.invokeServerMethod(BaseMethodBinding.java:250)
        at ca.uhn.fhir.rest.server.method.OperationMethodBinding.invokeServer(OperationMethodBinding.java:329)
        at ca.uhn.fhir.rest.server.method.BaseResourceReturningMethodBinding.doInvokeServer(BaseResourceReturningMethodBinding.java:247)
        at ca.uhn.fhir.rest.server.method.BaseResourceReturningMethodBinding.invokeServer(BaseResourceReturningMethodBinding.java:384)
        at ca.uhn.fhir.rest.server.method.OperationMethodBinding.invokeServer(OperationMethodBinding.java:304)
        at ca.uhn.fhir.rest.server.RestfulServer.handleRequest(RestfulServer.java:1025)
        at ca.uhn.fhir.rest.server.RestfulServer.doPost(RestfulServer.java:374)
        at ca.uhn.fhir.rest.server.RestfulServer.service(RestfulServer.java:1722)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder$NotAsyncServlet.service(ServletHolder.java:1402)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:763)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1631)
        at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:226)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1618)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:549)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:602)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:235)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1610)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1369)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:489)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1580)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1284)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:191)
        at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
        at org.eclipse.jetty.server.Server.handle(Server.java:501)
        at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:383)
        at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:556)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:375)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:272)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
        at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:806)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:938)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException: null
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at ca.uhn.fhir.rest.server.method.BaseMethodBinding.invokeServerMethod(BaseMethodBinding.java:245)
        ... 41 common frames omitted
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [delete from HFJ_RESOURCE where RES_ID=? and RES_VER=?]; constraint [fk_empi_link_target]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute batch
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:298)
        at ca.uhn.fhir.jpa.config.HapiFhirHibernateJpaDialect.convertHibernateAccessException(HapiFhirHibernateJpaDialect.java:120)
        at ca.uhn.fhir.jpa.config.HapiFhirHibernateJpaDialect.convertHibernateAccessException(HapiFhirHibernateJpaDialect.java:63)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:538)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:744)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:712)
        at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:152)
        at ca.uhn.fhir.jpa.dao.expunge.ExpungeEverythingService.expungeEverythingByType(ExpungeEverythingService.java:179)
        at ca.uhn.fhir.jpa.dao.expunge.ExpungeEverythingService.expungeEverything(ExpungeEverythingService.java:162)
        at ca.uhn.fhir.jpa.dao.expunge.ExpungeService.expunge(ExpungeService.java:54)
        at ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.expunge(BaseHapiFhirSystemDao.java:57)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
        at com.sun.proxy.$Proxy249.expunge(Unknown Source)
        at ca.uhn.fhir.jpa.provider.BaseJpaSystemProvider.doExpunge(BaseJpaSystemProvider.java:60)
        at ca.uhn.fhir.jpa.provider.r4.JpaSystemProviderR4.expunge(JpaSystemProviderR4.java:80)
        ... 46 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute batch
        at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:109)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
        at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:129)
        at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.addToBatch(BatchingBatch.java:89)
        at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3551)
        at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3810)
        at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:124)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
        at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
        at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
        at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
        at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443)
        at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202)
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534)
        ... 69 common frames omitted
Caused by: java.sql.BatchUpdateException: Batch entry 17 delete from HFJ_RESOURCE where RES_ID=206 and RES_VER=1 was aborted: ERROR: update or delete on table "hfj_resource" violates foreign key constraint "fk_empi_link_target" on table "mpi_link"
  Detail: Key (res_id)=(206) is still referenced from table "mpi_link".  Call getNextException to see other errors in the batch.
        at org.postgresql.jdbc.BatchResultHandler.handleError(BatchResultHandler.java:153)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2242)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:508)
        at org.postgresql.jdbc.PgStatement.internalExecuteBatch(PgStatement.java:850)
        at org.postgresql.jdbc.PgStatement.executeBatch(PgStatement.java:873)
        at org.postgresql.jdbc.PgPreparedStatement.executeBatch(PgPreparedStatement.java:1562)
        at org.apache.commons.dbcp2.DelegatingStatement.executeBatch(DelegatingStatement.java:242)
        at org.apache.commons.dbcp2.DelegatingStatement.executeBatch(DelegatingStatement.java:242)
        at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:119)
        ... 90 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: update or delete on table "hfj_resource" violates foreign key constraint "fk_empi_link_target" on table "mpi_link"
  Detail: Key (res_id)=(206) is still referenced from table "mpi_link".
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2505)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2241)
        ... 97 common frames omitted
2020-09-07 13:38:06.055 [qtp2009502388-16] INFO  fhirtest.access [LoggingInterceptor.java:160] ERROR - POST http://localhost:8080/hapi-fhir-jpaserver/fhir//$expunge
palfrey commented 3 years ago

I've just hit this with 5.0.0. Notably, this was on a test instance that had no data from earlier versions.