Inspect a specific schema resource using the --include flag
How can I inspect a specific resource, such as a function, view, or table, using the schema --include
flag?
Answer
The atlas schema inspect
command provides an --include
flag that allows you to retrieve the schema definition of one or more objects
while ignoring the rest of the schema. There is the option of including the objects' children, as well.
This feature is useful when working with large schemas, allowing you to view or troubleshoot a smaller scope without being overwhelmed by unrelated objects.
Unlike the --exclude
flag, --include
is an Atlas Pro feature and is currently available only for the schema inspect
command.
Given the following schema:
-- Table
CREATE TABLE users (
id serial PRIMARY KEY,
name text NOT NULL
);
-- Function
CREATE FUNCTION get_user_count() RETURNS integer AS $$
BEGIN
RETURN (SELECT COUNT(*) FROM users);
END;
$$ LANGUAGE plpgsql;
-- View
CREATE VIEW active_users AS
SELECT id, name FROM users WHERE name IS NOT NULL;
Below are a few examples of how to inspect specific resources in this schema:
Since our DDL statements are not schema-qualified, we assume the work is done within a specific schema (e.g., public
in PostgreSQL).
Therefore, the top-level objects in our definitions are tables, views, functions, and so on. Read more about Schema vs. Database Scope.
Query a specific function by its name
By default, the --include
flag keeps only resources that match the given glob, allowing you to target specific objects by their names.
atlas schema inspect --env local --include get_user_count
The default output of schema inspect
is formatted in HCL. To retrieve the SQL definition of the resource instead, use the --format
flag:
atlas schema inspect --env local --include get_user_count --format '{{ sql . }}'
Query multiple resources by their names
The command below includes the definitions of both the get_user_count
function and the active_users
view.
atlas schema inspect --env local \
--include get_user_count \
--include active_users
Another option to achieve this is to use a glob pattern:
atlas schema inspect --env local \
--include "*_user*"
Query resources by their resource type
Glob patterns also accept a type
selector, which can be used to match only specific types of resources. For example:
atlas schema inspect --env local \
--include "*[type=function]"
Qualified Resources
When the database URL is set at the database level (i.e., it does not specify a single schema but operates across multiple schemas), the scope of work is database-wide.
In this case, the resources you reference with the --include
flag must be schema-qualified. This means your glob patterns
should include a schema prefix to match objects such as functions and views. You can qualify the resource name in two ways:
Use an explicit schema prefix:
--include "public.resource_name"
Or use a wildcard for the schema part, for example:
--include "*.resource_name"