unique constraints for Yang leaf-list across all nodes in a list

1.3k views Asked by At

I have below yang models

container PORT {

    description "PORT part of config_db.json";

    list PORT_LIST {

        key "name";

        leaf name {
            type string {
                length 1..128;
            }
        }

        leaf-list lanes {
            type string {
                length 1..128;
            }
        }
    }
}

And below config

PORT": {
    "PORT_LIST": [
        {
            "name": "Ethernet8",
            "lanes": ["65", "66"]
        },
        {
            "name": "Ethernet9",
            "lanes": ["65", "67"]
        }
    ]
}

How to add a constraint, 'must' or 'unique' such that elements of leaf-list 'lanes' are unique across all nodes in PORT_LIST. In above example value '65' in 'lanes' field should be allowed only in one node.

1

There are 1 answers

0
predi On

The unique statement may only refer to one or more leaf statements, so that is not an option.

You should be able to achieve a similar result with a must statement and a condition like this:

module c {
    yang-version 1.1;
    namespace "c:uri";
    prefix "c";

    container PORT {
        
        description "PORT part of config_db.json";
        
        list PORT_LIST {
            
            key "name";
            must "count(lanes[current()/preceding-sibling::PORT_LIST/lanes = .]) = 0" {
                error-message "Lanes entries must be unique accross all entries of PORT_LIST";
            }
            
            leaf name {
                type string {
                    length 1..128;
                }
            }
            
            leaf-list lanes {
                type string {
                    length 1..128;
                }
            }
        }
    }
}

The condition says something along the lines of: if there are any lanes for this PORT_LIST entry, none of them should have the same value as the lanes in any of the PORT_LIST entries that come before this one.

<?xml version="1.0" encoding="utf-8"?>
<config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
  <PORT xmlns="c:uri">
    <PORT_LIST>
      <name>Ethernet8</name>
      <lanes>65</lanes>
      <lanes>66</lanes>
    </PORT_LIST>
    <PORT_LIST>
      <name>Ethernet9</name>
      <lanes>65</lanes>
      <lanes>67</lanes>
    </PORT_LIST>
  </PORT>
</config>
Error at (9:5): failed assert at "/nc:config/c:PORT/c:PORT_LIST": Lanes entries must be unique accross all entries of PORT_LIST

This is just a quick example, there may be more efficient ways to define the condition.