Forcefully delete a document with many attachments

Last modified by Manuel Leduc on 2026/06/02 17:54

cogUse internal APIs to permanently delete a document when the total size of its attachments prevents a normal delete from the UI
TypeSnippet
Category
Developed by

Sergiu Dumitriu

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

When a document gets too many attachments, it will become impossible to delete it without increasing the memory allocated to the JVM to absurd values. See . Here is a workaround for it.

Warning

This script requires Programming Rights

{{velocity}}
## Replace the target document name here:
#set ($targetDoc = $xwiki.getDocument('Space.TargetDocument').getDocument())

#set ($attachmentStore = $xwiki.getXWiki().getAttachmentStore())
#foreach ($attachment in $targetDoc.getAttachmentList())
  $attachmentStore.deleteXWikiAttachment($attachment, false, $xcontext.context, true)
#end
$xwiki.getXWiki().deleteDocument($targetDoc, false, $xcontext.context)
{{/velocity}}

Updated script that asks for confirmation:

{{velocity}}
## Replace the target document name here:
#set($hql = $xwiki.searchDocuments("where doc.name='TargetDocument' and doc.space='TargetSpace' order by doc.name"))
#if($hql.size() == 0)
 No document was found.
#else
#foreach($page in $hql)
 #set($mydoc = $xwiki.getDocument($page).getDocument())
 #if($request.confirm != "1")
 The page [[$page]] will be deleted.
 #end
 #if($request.confirm == "1")
   #set ($attachmentStore = $xwiki.getXWiki().getAttachmentStore())
   #foreach ($attachment in $targetDoc.getAttachmentList())
     $attachmentStore.deleteXWikiAttachment($attachment, false, $xcontext.context, true)
   #end
   $xwiki.getXWiki().deleteDocument($mydoc, false, $xcontext.context)
   The page $page was deleted.
 #end
#end

{{html wiki="true"}}
#if($request.confirm != "1")
<div class="buttons">
  <span class="buttonwrapper">[[Confirm>>$doc.fullName||queryString="confirm=1"]]</span>
</div>
#end
{{/html}}

#end
{{/velocity}}

Get Connected