Skip to content

Primary Keys

Validate the model has at least one column with a unique and not_null test

Source code in checkers/checks.py
def check_model_has_primary_key_test(model: Model, params: Dict):
    """
    Validate the model has at least one column with a unique and not_null test
    """

    column_test_maps = {c: [] for c in model.columns}
    for test in model.tests:
        if test.column_name in column_test_maps:
            column_test_maps[test.column_name].append(test.test_name)
    for column_name, column_tests in column_test_maps.items():
        if "unique" in column_tests and "not_null" in column_tests:
            break
    else:
        raise AssertionError(
            "Missing a column that defined both a unique and not_null test"
        )

Reason to flag#

A primary key test ensures that every table has a single column with unique, not null values. These primary keys are important for debugging issues, and helpful for features like snapshotting. We recommend every model define a primary key.

Fixing#

Add a unique and not_null test to one of the model's columns.

Example yaml entry:

models:
  - name: user
    description: A model representing all the product's users
    columns:
      - name: user_id
        tests:
          - unique
          - not_null

Parameters#

N/A