Query icon
OutputValues icon
Log icon
If icon
SlackIncomingWebhook icon
Loop icon
Fail icon
Schedule icon

SQL Server Untrusted Foreign Key Revalidation Guard

Detect enabled but untrusted SQL Server foreign keys, alert Slack, then revalidate each with WITH CHECK CHECK CONSTRAINT and re-read the catalog to confirm.

Categories
DataInfrastructure

A SQL Server foreign key can be enabled yet untrusted. It happens after a bulk load that bypassed the constraint, after a key was added WITH NOCHECK or after a disabled key was re-enabled without a recheck. The constraint still blocks bad new writes, but SQL Server flags it is_not_trusted = 1. Once a key is untrusted the optimizer stops trusting it. It skips join elimination and other trusted-constraint shortcuts, so queries read more than they need. Any orphan rows that slipped in before the key was trusted stay hidden.

This blueprint reads sys.foreign_keys for the connected database, flags every foreign key that is enabled (is_disabled = 0) but untrusted (is_not_trusted = 1) and alerts Slack. When you allow it, it revalidates each one with ALTER TABLE ... WITH CHECK CHECK CONSTRAINT, one statement at a time, then reads the catalog again and fails the run if any enabled foreign key is still untrusted.

This blueprint was created by zkasuran.

Safety

  • Read-only by default. dry_run is true and auto_remediate is false, so a normal run only reads the catalog and alerts.
  • A write happens only when auto_remediate is true and dry_run is false.
  • WITH CHECK CHECK CONSTRAINT is WITH CHECK plus CHECK CONSTRAINT. It rechecks every existing row against the key before marking it trusted. If a row violates the key the statement errors, which is the correct result: the data has an integrity gap that revalidation must not paper over. That error routes to the errors block.
  • Each revalidation runs as its own autocommitting io.kestra.plugin.jdbc.sqlserver.Query, never a Queries task with transaction: true.
  • The remediation loop has concurrencyLimit: 1, so the statements never run in parallel.

How it works

  1. audit (io.kestra.plugin.jdbc.sqlserver.Query, read-only) reads sys.foreign_keys joined to sys.tables and sys.schemas for both the parent and the referenced table. It keeps every key where is_not_trusted = 1 and is_disabled = 0, then builds the ALTER TABLE ... WITH CHECK CHECK CONSTRAINT statement for each one with QUOTENAME.
  2. fixes (io.kestra.plugin.core.output.OutputValues) collects the per-key revalidation statements. summary (io.kestra.plugin.core.log.Log) logs the findings with the referenced table for each key.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs that every enabled foreign key is trusted.
    • findings: alert posts the flagged keys to Slack.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • remediate (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) runs each revalidation in turn.
      • reaudit re-reads the catalog. verify_result fails the run if any enabled foreign key is still untrusted.
  4. errors posts a Slack alert when a revalidation hits a violating row or the audit cannot run.

What you get

  • Every enabled foreign key the optimizer has stopped trusting, with the parent and referenced table for each.
  • A revalidation that rechecks the existing rows and marks the key trusted again, so join elimination and the other trusted-constraint plans come back.
  • A re-read of the catalog after the change that fails the run if a key is still untrusted, so a revalidation that did not land is never reported as success.
  • A hard failure and a Slack alert when existing rows violate a key, which surfaces the orphan data the untrusted key was hiding.
  • A Slack alert on findings and a separate alert if the audit cannot run.

Who it's for

  • DBAs who ran a bulk load or added a key WITH NOCHECK and want the trust flag put back without hand-writing the statements.
  • Platform teams who see query plans ignore a foreign key and want to know which keys are untrusted.
  • Teams evaluating the SQL Server plugin who want an example that reads the catalog and drives ALTER TABLE.

Why orchestrate this with Kestra

Finding untrusted keys is a one-line catalog query, but acting on it safely is not. You want to see the list first, revalidate only when you choose, one key at a time, then confirm the flag actually cleared. You want the run to stop and shout if a key turns out to be hiding orphan rows. Kestra reads the catalog, gates the change behind two inputs, runs each ALTER TABLE on its own, re-reads the catalog and fails loudly if anything is still untrusted. The Slack alert says what was found and whether anything changed. The run history keeps every before and after.

Tested end to end

On Kestra 2.0.5 against SQL Server 2022 on Linux, with a local HTTP sink standing in for Slack. A foreign key was added WITH NOCHECK so it was enabled but untrusted. A second key was given a row that violates it to exercise the failure path.

Run Inputs Result
1 defaults, one untrusted key with clean rows 1 key flagged, Slack alert "No change applied". sys.foreign_keys still showed is_not_trusted = 1, so a default run changed nothing
2 auto_remediate: true, dry_run: true 1 key flagged, still "No change applied". The dry run blocked the write even with auto_remediate on
3 auto_remediate: true, dry_run: false remediate ran one ALTER TABLE ... WITH CHECK CHECK CONSTRAINT. reaudit returned 0 rows. sys.foreign_keys reported is_not_trusted = 0
4 defaults, after run 3 0 keys flagged, clean branch
5 auto_remediate: true, dry_run: false, a key with a violating row apply errored with "conflicted with the FOREIGN KEY constraint", the run FAILED and errors posted to Slack. sys.foreign_keys still showed is_not_trusted = 1 for that key
6 unreachable server audit failed, errors block posted to Slack

Prerequisites

  • A SQL Server database you can reach over JDBC.
  • A login that can read sys.foreign_keys for the audit, plus ALTER on the parent tables (for example db_ddladmin) for revalidation.
  • A Slack incoming webhook.

Secrets

  • SQLSERVER_PASSWORD: password for the login in user. The password input defaults to this secret.
  • SLACK_WEBHOOK_URL: Slack incoming webhook, used by alert and the errors block.
  • In Kestra OSS, provide each one as a base64-encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
url jdbc:sqlserver://localhost:1433;databaseName=app;encrypt=false Database to check. The query reads the connected database
user sa SQL Server login
password {{ secret('SQLSERVER_PASSWORD') }} Password for the login
auto_remediate false Allow the revalidation statements
dry_run true Must be false for a statement to run

Quick start

  1. Add the SQLSERVER_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow, then set url to the database you want to check and set user.
  3. Run it once with the defaults and read the flagged keys.
  4. When you are ready, run with auto_remediate: true and dry_run: false.
  5. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Limit the audit to one schema by adding a WHERE s.name = ... filter so a shared instance is checked in parts.
  • Post the referenced table and the fix statement to Slack so an on-call engineer can act without opening the database.
  • Add a row-count probe for the orphan rows before revalidating, so a key that would fail is reported with the exact bad rows.
  • Loop over several databases on the instance by reading sys.databases first.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.