Testing Postgres Domains
With Atlas, you can test and validate PostgreSQL domain types and constraints alongside every other schema element. his helps you catch validation issues and data logic bugs before they reach production and ensures that your custom types behave as expected across environments.
In this guide, you’ll learn how to use Atlas's schema test command to test Postgres Domain Types.
Database Domains
A domain is a user-defined data type that is based on an existing data type but with optional constraints and default values.
Domains are currently available only to Atlas Pro users. To use this feature, run:
atlas login
Project Setup
Schema File
For this example, let's assume we have the following schema, including a domain:
schema "public" {}
table "users" {
schema = schema.public
column "id" {
type = int
}
column "name" {
type = text
}
column "zip" {
type = domain.us_postal_code
}
primary_key {
columns = [column.id]
}
}
domain "us_postal_code" {
schema = schema.public
type = text
null = true
check "us_postal_code_check" {
expr = "((VALUE ~ '^\\d{5}$'::text) OR (VALUE ~ '^\\d{5}-\\d{4}$'::text))"
}
}
The schema has a simple users table, with id, name, and zip as columns.
The domain, us_postal_code, extends the type text, ensuring
that the data entered conforms to the standard formats used for U.S. postal codes,
such as "12345" or "12345-6789".
Config File
Before we begin testing, create a config file named
atlas.hcl.
In this file we will create an environment, specify the source of our schema, and a URL for our dev database.
We will also create a file named schema.test.hcl to write our tests, and
add it to the atlas.hcl file in the test block.
env "dev" {
src = "file://schema.hcl"
dev = "docker://postgres/15/dev?search_path=public"
# Test configuration for local development.
test {
schema {
src = ["schema.test.hcl"]
}
}
}