Search code examples
xpathietf-netmod-yang

YANG, leaf must be unique in a list


I cant figure out how to create a "must" for a leaf that makes it unique in a list.

This is list with a leaf in it, this leaf may not have the same value as any other leaf in this list.

Example of code:

list myList {
  key name;

  leaf name {
    type uint32;
  }

  container myContainer {

    leaf myLeaf {
      type uint32;
    }
    must "count(/myList/myContainer/myLeaf = .) > 1" { //Dont know how to create this must function.
      error-message "myLeaf needs to be unique in the myList list";
    }

  }

}

So i want myLeaf to trigger the error-message if there already exist an element in myList with the current value.


Solution

  • You have the list's unique keyword for that purpose, no need to bash you head against must expressions. It takes one or more space separated schema node identifiers in its argument.

        list myList {
          key name;
          unique "myContainer/myLeaf";
    
          leaf name {
            type uint32;
          }
    
          container myContainer {
    
            leaf myLeaf {
              type uint32;
            }
    
          }
    
        }
    

    If you really want a must to handle this (which you shouldn't) you could do something like:

        leaf myLeaf {
          must "count(/myList/myContainer/myLeaf[current()=.])=1";
          type uint32;
        }
    

    The current() XPath function returns the leaf being checked (the initial context node), while . stands for self::node() and applies to whatever you selected (current XPath context node set).

    Also note: a must constraint represents an assertion - it MUST evaluate to true(), otherwise an instance is considered invalid. Your > 1 condition would therefore achieve the opposite of what you require.