I went into an error that you might already have once, so here is a quick guide on how to fix it.

When deleting a document from D2 I had a popup with an error like: Cannot delete file because it is still referenced in a virtual document or an assembly. Well indeed the document that I wanted to delete was previously in a VD, but for some reasons I couldn’t find the VD by the search engine as it was deleted, but not its old versions.

To summarize, my document was still referenced by the old versions of a deleted VD. So here’s the way I fixed it:

First, I needed to know which VD referenced it, for this simply use the table dmr_containment:

select * from dmr_containment where component_id='<DOCUMENT_ID>';

You should see a list of ids like:

r_object_id: ID of the current row (we will need it)
parent_id: ID of the VD that references our document
component_id: ID of our document
order_no: Index order of all documents in this VD

The problem with old versions VD is that it is set as immutable so you can’t remove the document from the VD through DQL and API. You first have to set it mutable.

So here is the condensed version of API to remove a component in an immutable VD:

fetch,c,<PARRENT_ID>
set,c,l,r_immutable_flag
F
save,c,l
removepart,c,l,<R_OBJECT_ID>
save,c,l
fetch,c,l
set,c,l,r_immutable_flag
T
save,c,l

If you have a lot of entries to remove, you may want a scripted version in DQMan:

First select all entries:

select * from dmr_containment where component_id='<DOCUMENT_ID>';

Select all rows, right click and generate the script:

fetch,c,{parent_id}
set,c,l,r_immutable_flag
F
save,c,l
removepart,c,l,{r_object_id}
save,c,l
set,c,l,r_immutable_flag
T
save,c,l

Verify that each entries have been deleted and now you should be able to remove your document without errors.