/*
 * ** header v3.0
 * This file is a part of the CaosDB Project.
 *
 * Copyright (C) 2018 Research Group Biomedical Physics,
 * Max-Planck-Institute for Dynamics and Self-Organization Göttingen
 * Copyright (C) 2020 IndiScale GmbH <info@indiscale.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 *
 * ** end header
 */

/* Delete a (sparse) Entity from the database.

Note that all properties, including is-a relationships of this Entity should
have been deleted before.  This can be done for example with the
`deleteEntityProperties` procedure.

Parameters
==========

EntityID : UNSIGNED
The ID of the Entity.
*/

DROP PROCEDURE IF EXISTS db_2_0.deleteEntity;
delimiter //

CREATE PROCEDURE db_2_0.deleteEntity(in EntityID INT UNSIGNED)
BEGIN

    -- detele file properties
    DELETE FROM files where file_id=EntityID;

    -- delete datatype stuff
    DELETE FROM data_type WHERE domain_id=0 and (entity_id=0 and property_id=EntityID) or entity_id=EntityID; 
    DELETE FROM collection_type WHERE domain_id=0 and (entity_id=0 and property_id=EntityID) or entity_id=EntityID; 

    -- delete primary name (in case this is called without a prior call to deleteEntityProperties)
    DELETE FROM name_data WHERE domain_id = 0 AND entity_id = EntityID AND property_id = 20;

    DELETE FROM entities where id=EntityID;
    DELETE FROM entity_acl WHERE NOT EXISTS (SELECT 1 FROM entities WHERE entities.acl = entity_acl.id LIMIT 1);

END;
//
delimiter ;