Inferensys

Prompt

Cross-Schema Dependency Analysis Prompt

A practical prompt playbook for using Cross-Schema Dependency Analysis Prompt in production AI workflows to map foreign references, materialized view dependencies, ETL pipeline breakage risks, and cross-database query failures before migration execution.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for cross-schema dependency analysis.

This prompt is built for data platform engineers and backend teams who own migrations that span multiple schemas, databases, or services. The job-to-be-done is producing a structured cross-schema impact map before a migration reaches production—identifying every foreign reference, materialized view dependency, ETL pipeline breakage risk, and cross-database query that could fail when the schema changes. You should use this prompt when a migration script touches objects referenced outside its own schema boundary, when you lack a single automated dependency graph, or when you need a human-auditable impact assessment to attach to a change request.

The prompt requires specific input context to be useful: the full migration DDL, the current schema definitions for all affected and potentially dependent schemas, and a list of known ETL pipelines, materialized views, or cross-database queries that reference the target objects. Without this context, the model will hallucinate dependencies. The output is a structured impact map with dependency type, affected object, failure mode, and severity classification. This is not a prompt for simple single-schema migrations, for environments where a complete automated dependency graph already exists and is trusted, or for migrations where you cannot provide the cross-schema metadata the analysis requires.

Do not use this prompt as a replacement for actual migration dry-run execution or transaction safety review. It identifies dependency risks but does not simulate runtime behavior, lock contention, or data correctness. The output should feed into your migration review checklist alongside rollback safety analysis, data profiling results, and dry-run logs. For high-risk migrations affecting financial data, PII, or compliance-bound systems, always pair this analysis with human review and a rollback plan before execution.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Cross-Schema Dependency Analysis Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your migration review workflow before wiring it into a CI/CD pipeline.

01

Good Fit: Multi-Schema Migration Reviews

Use when: a migration touches tables, views, or functions that span multiple schemas or databases. The prompt excels at tracing foreign key references, materialized view dependencies, and ETL pipeline breakage risks that single-schema reviews miss. Guardrail: always provide the actual schema DDL and dependency metadata as input context—do not rely on the model's training data for your specific database topology.

02

Bad Fit: Single-Table, Isolated Changes

Avoid when: the migration modifies a single table with no foreign keys, no views, and no cross-schema references. The cross-schema analysis prompt adds unnecessary complexity and token cost for changes that a simpler migration review prompt handles more efficiently. Guardrail: route simple migrations to a lightweight schema review prompt and reserve this prompt for changes flagged by a dependency check harness.

03

Required Inputs: Schema Metadata and Migration DDL

What to watch: the prompt cannot introspect your database. Without actual DDL, foreign key definitions, view source code, and ETL job configurations, the analysis will be speculative and miss real breakage. Guardrail: build a harness that extracts schema metadata, dependency graphs, and migration SQL before calling the prompt. Validate that all referenced objects exist in the provided context.

04

Operational Risk: False Negatives on Implicit Dependencies

What to watch: the prompt may miss dependencies that are not explicitly declared in schema metadata—such as application-level joins, ORM relationship definitions, or dynamic SQL constructed at runtime. These implicit dependencies can still break in production. Guardrail: supplement schema metadata with application code references, ORM model files, and query logs. Flag any dependency the prompt cannot verify as requiring manual review.

05

Scale Risk: Large Schema Graphs

What to watch: databases with hundreds of schemas and thousands of cross-references can exceed context windows or cause the model to produce incomplete dependency maps. Truncated analysis creates a false sense of safety. Guardrail: implement a pre-filtering step that identifies only the schemas and objects directly or transitively connected to the migration target. Feed the prompt a focused subgraph rather than the entire catalog.

06

Pipeline Integration: Human Review Required for Destructive Changes

What to watch: the prompt may correctly identify a breaking dependency but the migration still proceeds automatically if the output is not gated. Automated pipelines that apply migrations without human approval can still cause outages. Guardrail: require human approval for any migration where the prompt flags a cross-schema dependency with a severity of HIGH or CRITICAL. Block automated deployment until the review is acknowledged.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating a cross-schema dependency impact map from migration scripts and schema metadata.

This prompt template is designed to be the core instruction set you send to a model. It accepts a proposed migration script, the current state of all related schemas, and a set of constraints to produce a structured, risk-ranked dependency impact map. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to parameterize in your application code. The goal is to surface hidden breakages—such as a renamed column that orphans a materialized view in another schema or a dropped table that silently breaks an ETL pipeline—before the migration reaches production.

text
You are a database reliability engineer reviewing a migration script for cross-schema impact. Your task is to produce a structured dependency impact map.

## INPUTS

### PROPOSED MIGRATION
[MIGRATION_SCRIPT]

### CURRENT SCHEMA CONTEXT
This includes DDL for all related schemas, materialized views, stored procedures, and known ETL pipeline definitions.
[SCHEMA_CONTEXT]

### KNOWN DEPENDENCIES
A list of known cross-schema references, foreign keys, views, and ETL jobs that touch the affected tables.
[KNOWN_DEPENDENCIES]

## CONSTRAINTS
[CONSTRAINTS]

## OUTPUT SCHEMA
You must respond with a single JSON object conforming to this structure:
{
  "migration_summary": "string (one-sentence summary of what the migration does)",
  "impact_map": [
    {
      "target_object": "string (fully qualified schema.object name)",
      "dependency_type": "string (e.g., FOREIGN_KEY, MATERIALIZED_VIEW, ETL_PIPELINE, STORED_PROCEDURE, CROSS_DATABASE_QUERY)",
      "impact_description": "string (explain exactly how the migration breaks or alters this dependency)",
      "risk_level": "string (HIGH | MEDIUM | LOW)",
      "fix_suggestion": "string (a concrete, actionable recommendation to resolve the issue)"
    }
  ],
  "rollback_risks": ["string (list of risks specific to rolling back this migration)"],
  "unresolved_questions": ["string (list of questions that must be answered before proceeding, e.g., unclear ownership of a dependent object)"]
}

## INSTRUCTIONS
1. Parse the [MIGRATION_SCRIPT] to identify all DDL and DML operations.
2. For each operation, cross-reference the [SCHEMA_CONTEXT] and [KNOWN_DEPENDENCIES] to find every dependent object.
3. Do not report dependencies that are unaffected by the change.
4. If a dependency is mentioned in [KNOWN_DEPENDENCIES] but cannot be verified in [SCHEMA_CONTEXT], flag it as an unresolved question.
5. Adhere strictly to the [CONSTRAINTS] provided.
6. Output only the JSON object. No markdown, no preamble.

To adapt this template, replace each bracketed placeholder with data from your own systems. [MIGRATION_SCRIPT] should be the raw SQL or ORM-generated diff. [SCHEMA_CONTEXT] is the most critical input—it must include the full DDL for every schema that could be affected, not just the one being modified. For large environments, you may need to use a retrieval-augmented generation (RAG) approach to pull in only the relevant schema objects. [KNOWN_DEPENDENCIES] can be sourced from your data catalog, ETL scheduler, or a manual list maintained by the team. Use [CONSTRAINTS] to enforce team-specific policies, such as "ignore dependencies on schemas owned by team X" or "treat any impact on a materialized view as HIGH risk." The output schema is rigid by design; parse the JSON response in your harness and validate it against this structure before presenting results to the user.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Cross-Schema Dependency Analysis Prompt. Each variable must be populated before the prompt is assembled. Missing or malformed inputs are the most common cause of incomplete dependency maps.

PlaceholderPurposeExampleValidation Notes

[MIGRATION_SCRIPT]

The full DDL/DML migration script to analyze for cross-schema dependencies

ALTER TABLE orders.payments ADD COLUMN tax_region_id INT REFERENCES accounting.tax_regions(id);

Must be non-empty and parseable SQL. Validate with sqlparse or equivalent before prompt assembly. Reject if script contains only comments or whitespace.

[SCHEMA_METADATA]

Current schema definitions for all referenced databases, including tables, views, materialized views, foreign keys, and stored procedures

{"orders": {"tables": ["payments", "invoices"], "views": ["revenue_summary"]}, "accounting": {"tables": ["tax_regions", "ledger"]}}

Must be valid JSON with database names as keys. Validate schema completeness: every schema referenced in [MIGRATION_SCRIPT] must appear here. Missing schemas produce false-negative dependency reports.

[ETL_PIPELINE_MANIFEST]

List of ETL jobs, data pipelines, and scheduled queries that read from or write to the affected schemas

["nightly_revenue_rollup", "tax_region_sync", "invoice_export"]

Can be empty array if no ETL pipelines exist. Each entry should match a known pipeline name. Validate against pipeline registry if available; warn if manifest is empty when production schemas are involved.

[CROSS_DB_QUERY_LOG]

Sample of recent cross-database queries from query logs, application code, or reporting tools that span the affected schemas

SELECT o.total, t.rate FROM orders.payments o JOIN accounting.tax_regions t ON o.tax_region_id = t.id WHERE o.created > '2025-01-01';

Can be empty if no cross-db queries are known. Prefer production query log samples over hand-written examples. Validate that each query parses successfully and references at least two distinct schemas.

[APPLICATION_CODE_REFERENCES]

Code snippets or file paths from application codebases that reference the affected tables, columns, or schemas

["src/payments/tax.py:42", "src/reports/revenue.sql:15"]

Can be empty array for pure-infrastructure migrations. Each entry should include file path and line reference. Validate that file paths exist in the repository at the analyzed commit; stale references produce false positives.

[MATERIALIZED_VIEW_DEFINITIONS]

Current definitions of all materialized views in the affected schemas, including refresh schedules and dependency chains

CREATE MATERIALIZED VIEW orders.revenue_summary AS SELECT p.total, t.rate FROM orders.payments p JOIN accounting.tax_regions t ON p.tax_region_id = t.id WITH DATA; REFRESH EVERY 6 HOURS;

Must be valid SQL view definitions. Validate that each view references only tables and schemas present in [SCHEMA_METADATA]. Missing materialized view definitions cause the prompt to miss refresh-failure risks.

[DEPLOYMENT_CONTEXT]

Deployment environment details: target environment, deployment order across services, and whether blue-green or rolling deployment is in use

{"environment": "production", "deployment_order": ["accounting", "orders"], "strategy": "blue-green"}

Must include at minimum the target environment name. Validate that deployment_order lists all schemas referenced in [MIGRATION_SCRIPT]. Missing deployment context causes the prompt to skip ordering and compatibility analysis.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Cross-Schema Dependency Analysis Prompt into a reliable, automated review pipeline.

This prompt is designed to be the reasoning engine inside a broader application harness, not a standalone chat interface. The core workflow involves: (1) collecting schema metadata from all relevant databases, (2) assembling the migration script and its context, (3) executing the prompt, (4) validating the structured output, and (5) routing the impact map to the appropriate reviewers or blocking the migration pipeline. The harness is responsible for data gathering and output enforcement; the prompt is responsible for analysis and reasoning.

Input Assembly: The harness must gather the full DDL for all schemas referenced in the migration, including views, materialized views, triggers, and stored procedures. This is non-negotiable; the prompt cannot analyze dependencies it cannot see. Use pg_dump --schema-only or equivalent introspection tools. The [SOURCE_SCHEMA_DDL] and [TARGET_SCHEMA_DDL] placeholders should be populated with the complete, unredacted schema definitions. The [MIGRATION_SCRIPT] placeholder receives the exact SQL to be reviewed. For ETL and cross-database dependencies, the harness should also include a [CROSS_DB_ACCESS_MAP] documenting foreign data wrappers, dblink usage, or application-level connection strings that reference other databases.

Model Selection and Tool Use: This task requires a model with strong SQL comprehension and the ability to reason about implicit dependencies (e.g., a view referencing a table in another schema via a qualified name). A frontier model like GPT-4o or Claude 3.5 Sonnet is recommended. The prompt does not require tool use for the analysis itself, but the harness should provide a schema introspection tool that the model can call if it identifies a missing dependency not included in the initial DDL. The tool should accept a schema and object name and return its DDL, allowing the model to request additional context on demand.

Output Validation and Retries: The prompt requests a strict JSON schema. The harness must validate the response against this schema immediately. If validation fails, implement a single retry by feeding the validation error back into the prompt as [PREVIOUS_OUTPUT_ERROR]. If the retry also fails, log the raw output, flag the review as incomplete, and escalate to a human. Do not loop indefinitely. For high-risk migrations (e.g., those involving financial data or PII), the harness should automatically set [RISK_LEVEL] to high, which instructs the prompt to be more conservative and flag borderline cases as requires_review.

Integration and Logging: Wire the harness into your CI/CD pipeline as a required check on migration PRs. Log the full prompt, the model response, the validated JSON, and the final pass/fail decision to your prompt observability platform. This audit trail is critical for post-incident review. The impact_map output should be parsed and used to automatically request reviews from the owners of affected downstream systems. A finding with severity: blocker should fail the CI check. The next step is to pair this prompt with a Migration Dry-Run Simulation Prompt that tests the script against a production-like schema, using this dependency map to ensure all affected objects are included in the simulation scope.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the cross-schema dependency analysis output. Use this contract to build a parser that validates the model response before it enters downstream workflows.

Field or ElementType or FormatRequiredValidation Rule

dependency_map

Array of objects

Must be a JSON array. Each element must contain source_schema, target_schema, and dependency_type fields.

dependency_map[].source_schema

String

Must match a schema name present in the input migration manifest. Non-empty string.

dependency_map[].target_schema

String

Must match a schema name present in the input migration manifest. Must differ from source_schema for the same entry.

dependency_map[].dependency_type

Enum string

Must be one of: FOREIGN_KEY, MATERIALIZED_VIEW, ETL_PIPELINE, CROSS_DB_QUERY, VIEW, TRIGGER, SYNONYM. Parse check against allowed values.

dependency_map[].impacted_objects

Array of strings

Each string must be a fully qualified object name (schema.object). Array must not be empty. Null entries not allowed.

dependency_map[].breakage_risk

Enum string

Must be one of: HIGH, MEDIUM, LOW. Parse check against allowed values.

dependency_map[].breakage_description

String

Non-empty string. Must reference at least one impacted_object by name. Max 500 characters.

cross_schema_query_failures

Array of strings

If present, each string must contain a SQL fragment or query pattern. Null allowed if no cross-database queries detected.

PRACTICAL GUARDRAILS

Common Failure Modes

Cross-schema dependency analysis is inherently complex. The prompt can fail silently by missing hidden dependencies, misinterpreting dialect-specific syntax, or hallucinating references that don't exist. These are the most common failure modes and how to guard against them before the analysis reaches a release decision.

01

Hallucinated Foreign Key References

What to watch: The model invents foreign key relationships between tables that have no actual constraint defined, often because column naming conventions suggest a relationship. Guardrail: Require the prompt to cite specific constraint names or DDL source lines. Cross-reference every claimed dependency against actual INFORMATION_SCHEMA or pg_catalog output in the harness before surfacing the finding.

02

Dialect-Specific Syntax Blindness

What to watch: The model treats all SQL dialects as interchangeable, missing PostgreSQL-specific features like GENERATED ALWAYS AS columns, INHERITS, or materialized view refresh semantics that break cross-schema assumptions. Guardrail: Inject the target database engine and version into the prompt as a [DIALECT] constraint. Add a pre-check that flags dialect-specific objects and forces the model to explain their impact explicitly.

03

ETL Pipeline Dependency Omission

What to watch: The prompt focuses exclusively on database-level dependencies (views, constraints, triggers) and misses ETL jobs, Airflow DAGs, or dbt models that read from or write to the affected schemas. Guardrail: Require [ETL_MANIFEST] or pipeline registry data as a required input. If no pipeline inventory is provided, the prompt output must include a disclaimer section listing external pipeline risk as an unassessed category.

04

Materialized View Refresh Cascade Miss

What to watch: The analysis identifies that a materialized view depends on a changed table but fails to flag that refreshing it will cascade to downstream views, dashboards, or application caches that read from it. Guardrail: Add a recursive dependency traversal step in the prompt instructions. Require the output to include a dependency depth column and flag any object with downstream dependents beyond one level.

05

Cross-Database Query String Mismatch

What to watch: The model correctly identifies cross-database references but assumes they are resolved via fully qualified names, missing cases where connection strings, foreign data wrappers, or linked server configurations are required and may break after a schema change. Guardrail: Require [CROSS_DB_CONFIG] as input context. If unavailable, the prompt must flag every cross-database reference with a CONFIG_VERIFICATION_REQUIRED tag and refuse to mark it as safe.

06

Implicit Default Value Breakage

What to watch: The analysis flags explicit column changes but misses that INSERT statements in other schemas rely on DEFAULT values or column ordering that the migration alters, causing silent data corruption. Guardrail: Add an instruction to scan for INSERT statements without explicit column lists across all dependent schemas. If the codebase scan is unavailable, the output must include a MISSING_INSERT_ANALYSIS warning with explicit risk language.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a Cross-Schema Dependency Analysis output before integrating it into a deployment pipeline or review workflow.

CriterionPass StandardFailure SignalTest Method

Schema boundary identification

Every distinct schema or database referenced in the migration script is listed with its connection name.

A schema referenced in a cross-database query or foreign key is missing from the dependency list.

Parse the migration SQL for fully-qualified table references and compare against the output's schema inventory.

Foreign key dependency mapping

All foreign keys that cross schema boundaries are listed with source table, target table, and constraint name.

A cross-schema foreign key exists in the database metadata but is absent from the analysis output.

Query information_schema for cross-schema FK constraints and diff against the prompt output.

Materialized view impact detection

Every materialized view that references a table in the migration scope is flagged with its refresh schedule and dependency chain.

A materialized view dependent on a modified table is not listed, risking stale data after migration.

Parse the database's view definitions for references to migration-target tables and verify full coverage in the output.

ETL pipeline breakage risk

Each ETL pipeline or scheduled job that reads from or writes to affected objects is identified with its orchestrator name and estimated failure mode.

A production ETL job that queries a table being altered is omitted, creating a silent failure risk.

Cross-reference the output's pipeline list against the orchestration system's job definitions and lineage metadata.

Cross-database query failure flagging

Every cross-database query in application code or stored procedures that references a modified object is flagged with the specific query location and expected breakage type.

A cross-database JOIN in a critical application query is not flagged, and the query would fail after the migration.

Grep application code and stored procedure definitions for cross-database references to migration targets and verify all are present in the output.

Downstream consumer enumeration

All services, reports, and external systems that consume data from affected objects are listed with their contact team and SLA tier.

A downstream reporting system that reads from a table being migrated is missing, causing an uncommunicated outage.

Compare the output's consumer list against the service registry and data lineage tool to confirm completeness.

Rollback dependency ordering

A correct reverse-order dependency list is provided showing the sequence required to safely roll back the migration across schemas.

The rollback order suggests dropping a schema before removing foreign key references from another schema, causing errors.

Validate the rollback sequence by simulating it against a staging environment with the same cross-schema dependencies.

Citation and evidence grounding

Every dependency claim includes a reference to the specific SQL object, code file, or configuration that proves the relationship.

A dependency is asserted without any source reference, making it unverifiable during review.

Sample 5 dependency claims from the output and confirm each has a traceable source reference that can be independently verified.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single pair of schemas. Use [SCHEMA_A_DDL] and [SCHEMA_B_DDL] as the only inputs. Skip the full dependency graph output format and ask for a plain-text impact list instead. Run against a small, known schema pair where you can manually verify every dependency claim.

Prompt snippet

code
Analyze the following two schemas for cross-schema dependencies.

Schema A:
[SCHEMA_A_DDL]

Schema B:
[SCHEMA_B_DDL]

List every dependency where Schema A references Schema B or vice versa. For each dependency, state the object type (foreign key, view, materialized view, trigger, procedure, ETL reference), the referencing object, and the referenced object.

Watch for

  • Missing indirect dependencies (e.g., a view in Schema A that selects from a view in Schema B that selects from a table)
  • False positives when object names match coincidentally across schemas
  • Overlooking cross-database references if connection strings or linked server names appear in DDL
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.