DROP FUNCTION IF EXISTS vclib.t_entities_attributes_update CASCADE;
CREATE  FUNCTION vclib.t_entities_attributes_update()
RETURNS TRIGGER AS $$
BEGIN

    INSERT INTO ies.t_entity_attributes_change(
        entityattributeschangeid, entityid, "index", attributetype, "name", description, systemtype, maxlength, "precision", "scale", defaultformat, iscalculated, isflag, isrequired,
        mappingtype, mappingname, save, linkattributename, choiceattributedata, isstored, attrlexem, pathsattributes, iscashed, isadditional, mappingtable, mappingreftable, parametersdata, customsdata, requiredattributes,
        sortingattribute, enumtype, isidentity, iscustom, removeaction, isprimarykey, entitiesattributesid, editdate, "action"
    )
    SELECT
        gen_random_uuid(), NEW.entityid, NEW.index, NEW.attributetype, NEW.name, NEW.description, NEW.systemtype, NEW.maxlength, NEW.precision, NEW.scale, NEW.defaultformat, NEW.iscalculated, NEW.isflag, NEW.isrequired,
        NEW.mappingtype, NEW.mappingname, NEW.save, NEW.linkattributename, NEW.choiceattributedata, NEW.isstored, t2.attrlexem, t2.pathsattributes, NEW.iscashed, NEW.isadditional, NEW.mappingtable, NEW.mappingreftable, NEW.parametersdata, NEW.customsdata, NEW.requiredattributes,
        NEW.sortingattribute, NEW.enumtype, NEW.isidentity, NEW.iscustom, NEW.removeaction, NEW.isprimarykey, NEW.entitiesattributesid, NOW(), 1
    FROM vclib.t_entities_attributes t2
    LEFT JOIN LATERAL (select * from ies.t_entity_attributes_change t100 where t100.entitiesattributesid = NEW.entitiesattributesid AND t100.action IN (0, 1) 
			order by t100.EditDate desc LIMIT 1) aa on true
    WHERE NEW.entitiesattributesid = t2.entitiesattributesid
     AND (aa.entityattributeschangeid IS NULL OR
         aa.attributetype <> NEW.attributetype OR
         aa.name <> NEW.name OR
         COALESCE(aa.systemtype, '') <> COALESCE(NEW.systemtype, '') OR
         COALESCE(aa.attrlexem::text, '') <> COALESCE(t2.attrlexem::text, '') OR
         COALESCE(aa.pathsattributes::text, '') <> COALESCE(t2.pathsattributes::text, '') OR
         COALESCE(aa.mappingname, '') <> COALESCE(NEW.mappingname, '') OR
         COALESCE(aa.maxlength, -1) <> COALESCE(NEW.maxlength, -1) OR
         COALESCE(aa.precision, -1) <> COALESCE(NEW.precision, -1) OR
         COALESCE(aa.mappingtype, -1) <> COALESCE(NEW.mappingtype, -1));

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS t_entities_attributes_after_update ON vclib.t_entities_attributes;
CREATE TRIGGER t_entities_attributes_after_update
AFTER UPDATE ON vclib.t_entities_attributes
FOR EACH ROW EXECUTE FUNCTION vclib.t_entities_attributes_update();