-- taken and edited from __node_LinkDefaults
-- execute in command line client

drop temporary table if exists nodeLinkDefaultsTmp;
create temporary table nodeLinkDefaultsTmp(
    src_id int unsigned, 
    dst_id int unsigned, 
    primary key(src_id, dst_id)
) engine=MEMORY;

insert nodeLinkDefaultsTmp(src_id, dst_id)
select rootnode.id, n.id
from nodeT rootnode
join allowedNodeLinkT anl on rootnode.nodeTypeId = anl.srcNodeTypeId
join nodeT n on anl.dstNodeTypeId = n.nodeTypeId
left join templateT t on n.id = t.dstNodeId
where rootnode.isRoot = 'y'
    and t.dstNodeId is null
    and not exists (
        select 1 
        from nodeLinkT nl 
        where nl.nodeLinkTypeId = 1
            and nl.srcNodeId = rootnode.id
            and nl.dstNodeId = n.id
            and nl.metric = 1);

set @1 = nodeLink_UpdateStart();

select __nodeLink_Create('owns', src_id, dst_id)
from nodeLinkDefaultsTmp;

set @2 = nodeLink_UpdateEnd();

drop temporary table nodeLinkDefaultsTmp;
