Generated banner for Synapse Migration
Generated logo for Synapse Migration

Synapse Migration

MicrosoftOfficialPublished by Microsoft

  • Skill
  • Workflow
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Converts Synapse workspaces to Fabric: Spark items, Lake Databases, Linked Services, and Dedicated SQL Pool schema/procedures for Lakehouse or Warehouse. During Pool-to-Lakehouse migration only, can migrate approved dependent procedure callers after notebook readiness. Excludes standalone pipelines and Warehouse administration. Triggers: Synapse workspace to Fabric, Dedicated SQL Pool to Lakehouse, Dedicated SQL Pool to Fabric Warehouse.
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The synapse-migration skill provides a structured, phased workflow for transitioning Synapse Analytics workspaces to Microsoft Fabric. It covers the migration of Spark items, Lake Databases, Linked Services, and Dedicated SQL Pool schema and stored procedures. The skill emphasizes a dependency-ordered approach, requiring gap assessment and explicit approval before conversion. It distinguishes between migrating to a Fabric Lakehouse (schema and code only, no data movement) and a Fabric Warehouse, while providing specific routing for dependent pipeline callers.

What it does

  • Discovers and classifies Synapse workspace artifacts.
  • Converts Dedicated SQL Pool schema and stored procedures to Spark SQL notebooks or Warehouse objects.
  • Migrates Spark items, including notebooks and Spark Job Definitions, to Fabric equivalents.
  • Maps Linked Services to Fabric Data Connections or OneLake Shortcuts.
  • Manages the migration of approved dependent pipeline callers.
  • Validates persisted definitions and artifacts against established contracts.

When to use it

  • When migrating a full Synapse workspace to Microsoft Fabric.
  • When converting Dedicated SQL Pool schema and procedures to a Lakehouse or Warehouse.
  • When porting Spark pools, notebooks, or Spark Job Definitions to Fabric.
  • When replacing Synapse Linked Services with Fabric-native connectivity.

Advantages

  • Ensures dependency-ordered migration to maintain system integrity.
  • Provides clear routing for different workload types (Lakehouse vs. Warehouse).
  • Enforces strict validation and approval gates for behavior-changing decisions.
  • Supports incremental migration rather than high-risk big-bang cutovers.
  • Standardizes the conversion of T-SQL procedures to executable Spark SQL notebooks.

Usage examples

“Migrate this Dedicated SQL Pool DACPAC to a Fabric Lakehouse and convert the procedures.”
The agent will assess gaps, obtain approval for procedure-to-notebook mappings, create a migration manifest, convert schema/code artifacts, and validate the results.
“Migrate this Dedicated SQL Pool to Fabric Warehouse.”
The agent will assess DDL compatibility, remove unsupported distribution/index declarations, obtain provisioning consent, and prepare for potential data migration.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/microsoft/synapse-migration/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip synapse-migration.zip -d .agents/skills

Documentation by Microsoft

Telemetry — MANDATORY. Every api.fabric.microsoft.com call must carry x-ms-fabric-skill: synapse-migration (az rest: --headers "x-ms-fabric-skill=synapse-migration"), including every LRO poll, fabric_lro and retry. Snippets omit it — add it anyway.

OFFLINE LAKEHOUSE ARTIFACT FAST PATH — DECIDE FIRST. For a no-live-call request with complete supplied inputs and contracts, load only the fast path; do not load migration-planning-reference.md, dedicated-pool-conversion.md, or implementation scripts. Use one generator for artifacts and final-byte hashes, then one verifier. Do not inspect generated files or run post-pass spot checks. For every optional non-null source default, set missingValueBehavior to UseSourceDefault and restore that default before validation. Do not use this path for a Warehouse target; incomplete and large-procedure requests use their own routes.

CRITICAL NOTES

  1. To find workspace details (including its ID) from a workspace name: list all workspaces, then use JMESPath filtering.

  2. To find item details (including its ID) from workspace ID, item type, and item name: list all items of that type in that workspace, then use JMESPath filtering.

  3. Treat a source Dedicated SQL Pool as read-only. Do not run source DDL, DML, stored procedures, or create sample objects.

  4. Dedicated Pool-to-Lakehouse data movement is out of scope. Migrate schema and executable code artifacts only; do not copy source rows or run row-level/business-result equivalence queries. The separate Warehouse route may move data only from a separately approved restored export copy under its own consent gate and restored-source contract.

  5. For Dedicated Pool-to-Lakehouse requests, complete gap assessment, explicit mapping approval, manifest creation, conversion, deployment, and validation in order. Read dedicated-pool-to-lakehouse.md once as the router, then load only the current phase reference.

  6. Stored-procedure 1:1, N:1, and N:N mappings never apply to views. Views remain schema objects; procedures become traceable Spark SQL notebooks with executable %%sql transformation cells.

  7. Dependent ADF/Synapse callers are conditional scope, not automatic scope. Discover them during assessment, require a separate complete-closure approval, and migrate them only after notebook readiness. Route standalone pipeline requests to pipeline-migration.

  8. Before executing a specialized Dedicated Pool workflow, read the matching contract in dedicated-pool-execution-contracts.md. Its validation, hashing, request-body, resume, and completion-language requirements are mandatory.

  9. Keep Lakehouse and Warehouse paths separate. If the target is unclear, ask before loading path-specific resources. Lakehouse conversion never moves source rows; Warehouse data migration requires its own explicit consent gate and restored-source contract.

  10. For a Fabric Warehouse target, explicitly state that the complete DISTRIBUTION and CLUSTERED COLUMNSTORE INDEX declarations are removed because Fabric manages distribution, storage, and indexing; a bare mention of either source clause is insufficient.

  11. Run setup DDL and CETAS only against the separately approved restored export copy after proving it is not the original production source.

Synapse Analytics to Microsoft Fabric Migration

Core Workflow

  1. Discover the Synapse workspace and classify every source artifact.

  2. Choose targets using workload-routing.md.

  3. Assess gaps before conversion, including runtime, library, connectivity, T-SQL, security, and capacity constraints.

  4. Obtain approval for behavior-changing decisions, target placement, and every stored-procedure-to-notebook mapping.

  5. Create or update migration-manifest.json and persist approval, per-object status, hashes, and checkpoints atomically.

  6. Convert and deploy in dependency order, loading only the current phase resource.

  7. Validate persisted definitions and artifacts without executing generated notebooks or pipelines unless a separately approved workflow explicitly requires execution.

  8. Report completed, blocked, skipped, and pending objects without exposing credentials or sensitive values.

For full-workspace orchestration, read migration-orchestrator.md. For a Dedicated Pool-to-Lakehouse migration, use dedicated-pool-to-lakehouse.md as the phase router. For a Warehouse target, load only the matching dw-* resource.

Scope Routing

RequestActionLoad
Full Synapse workspace migrationRun phased discovery and migrationmigration-orchestrator.md
Dedicated SQL Pool schema/code to LakehouseRun the strict assessment-to-validation workflow. For guidance-only notebook publication, explicitly state: "The stored procedures were converted from T-SQL to Spark SQL before publication."dedicated-pool-to-lakehouse.md
Guidance-only Dedicated Pool incremental deployment hardeningAnswer directly from the focused checklist; do not search scripts or load phase resources. State: "For columns with special characters, enable Delta columnMapping selectively and only with approval."dedicated-pool-execution-contracts.md
Large or complex stored procedureFor a complete offline contract, read only the audit resource once, use one run-local generator and one verifier, do not inspect implementation scripts or generated outputs, and stop after successful verificationdedicated-pool-large-procedure-audit.md
Spark poolConvert configuration and libraries to a Fabric Environmentspark-pool-migration.md
Lake Database or HMSCreate or bind the target Lakehouselake-database-migration.md or external-hms-migration.md
Notebook or Spark Job DefinitionPort code, bindings, parameters, and runtime settingsspark-item-migration.md
Linked ServiceChoose a Fabric Data Connection for external services or a OneLake Shortcut for ADLS Gen2/Blobconnectivity-migration.md
Approved dependent procedure callersRun the internal closure-preserving sub-flow after notebook readbackdedicated-pool-dependent-pipelines.md
Standalone pipeline migrationDelegatepipeline-migration
Dedicated SQL Pool to Fabric WarehouseRun the source extraction, DDL compatibility, approval, optional data, security, and validation routedw-source-and-extraction.md, then the matching dw-* phase resource
Standalone Fabric Warehouse administrationDelegatesqldw-cli
Synapse LinkUse Fabric Mirroring; not covered here—

Always report the Lake Database/HMS phase. If none is discovered, mark it NotApplicable (none discovered) while retaining the required target Lakehouse binding.

Load References On Demand

Do not preload all files. Load only the references needed for the current phase:

NeedReference
Routing, phase order, API audiences, quick examples, troubleshooting, or post-migration handoffworkload-routing.md
Dedicated Pool execution variants and response contractsdedicated-pool-execution-contracts.md
Dedicated Pool discoverydedicated-pool-discovery.md
Gap assessment and mapping approvaldedicated-pool-gap-assessment.md
Procedure conversion and notebook shapededicated-pool-conversion.md
Schema/notebook deploymentdedicated-pool-deployment.md
Dedicated Pool validationdedicated-pool-validation.md
Runtime/library compatibilityfeature-parity.md and library-compatibility.md
mssparkutils and connector refactoringutility-api-mapping.md, connector-refactoring.md, and code-patterns.md
Capacity planningcapacity-sizing.md
Dedicated Pool-to-Warehouse source discovery and extractiondw-source-and-extraction.md
Warehouse DDL compatibility and deploymentdw-ddl-compatibility.md
Separately approved Warehouse data migrationdw-data-migration.md
Warehouse security and validationdw-security-validation.md
Validation, reporting, and production readinessvalidation-testing.md, migration-report.md, and security-governance.md

Use COMMON-CLI.md only for shared authentication and az rest mechanics not already covered by the phase resource. Use COMMON-CORE.md only for shared Fabric REST patterns.

Must

  • Preserve every stored-procedure input contract, source default, source decision, and approved target mapping.

  • Block conversion until gap dispositions, notebook names, dependency grouping, and target workspace placement are explicitly approved.

  • Use SqlPackage/DMVs for source discovery, Fabric REST for item management, and Fabric Livy statements for Lakehouse schema and Delta execution.

  • Run the maintained validators required by the selected execution contract; never replace them with ad hoc JSON or cell-shape checks.

  • Choose the Lakehouse or Warehouse target before loading implementation resources; never apply Warehouse data-movement rules to Lakehouse artifact conversion.

  • Before persisting any dependent-pipeline source definition, recursively inspect it for secret-bearing or uncertain properties; block the complete selected closure without writing the artifact or mutating a target when any are found.

  • In every dependent-pipeline response, including guidance-only and pre-approval explanations, state: "Use a TridentNotebook activity with exact target identities typeProperties.notebookId and typeProperties.workspaceId, and pass inputs through typeProperties.notebookParameters." Then state: "After deployment, read back each pipeline with POST /v1/workspaces/{workspaceId}/items/{dataPipelineId}/getDefinition and validate its canonical hash and structural bindings."

  • For every Linked Service response, first state both replacement classes: Fabric Data Connections for external databases/services and OneLake Shortcuts for ADLS Gen2/Blob storage; then identify which class applies.

  • Replace mssparkutils with notebookutils, Linked Services with the correct Fabric connection class, and spark.read.synapsesql() with a supported OneLake or JDBC pattern.

  • Externalize workspace and item IDs through parameters or Variable Libraries.

  • Keep phase status concise, emit bounded heartbeats for long operations, and persist per-object evidence in the manifest.

Prefer

  • OneLake Shortcuts over copying data.

  • Fabric Environments for reproducible libraries and Spark settings.

  • Incremental, dependency-ordered migration over big-bang cutover.

  • Parameterized notebooks and Variable Libraries for environment promotion.

  • Lakehouse SQL Endpoint for compatible Serverless SQL Pool read workloads.

Avoid

  • Do not execute generated notebooks or pipelines as part of artifact migration.

  • Do not broaden a selected dependent-pipeline closure or route that internal sub-flow to pipeline-migration.

  • Do not use sqlcmd against the target Fabric Warehouse; use the registered SQL endpoint tooling required by the Warehouse resource.

  • Do not preserve Synapse distribution/storage hints, PolyBase DDL, Linked Service connection strings, or pool-level library installation patterns verbatim.

  • Do not use target notebooks to orchestrate the migration itself.

  • Do not hardcode workspace IDs, item IDs, credentials, connection strings, or environment-specific paths.

Examples

Prompt: "Migrate this Dedicated SQL Pool DACPAC to a Fabric Lakehouse and convert the procedures."

Response behavior: Assess gaps first, present and obtain approval for the complete procedure-to-notebook mapping and workspace placement, create the manifest, convert approved schema/code artifacts without moving source rows, validate persisted definitions, and report the resolved Lakehouse and artifact evidence.

Prompt: "Migrate this ADF pipeline to Fabric."

Response behavior: Route to pipeline-migration. Keep it here only when the pipeline is an explicitly approved dependent caller discovered inside an active Dedicated Pool-to-Lakehouse migration.

Prompt: "Migrate this Dedicated SQL Pool to Fabric Warehouse."

Response behavior: Keep this inside synapse-migration, assess DDL compatibility, remove unsupported distribution and columnstore declarations, obtain provisioning consent, and ask separately before any restored-source data migration.

For code transformations and edge cases, load workload-routing.md and the phase-specific resource rather than expanding the main instructions.

Files

scripts/dedicated-pool-tool/Program.cs

using System.Diagnostics;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Xml;
using Microsoft.SqlServer.Dac.Model;

try
{
if (args.Length is < 2 or > 3 || (args.Length == 3 && args[2] != "--allow-trusted-project-build"))
{
    Console.Error.WriteLine("Usage: DedicatedPoolTool <input.dacpac|project.zip> <output-directory> [--allow-trusted-project-build]");
    return 2;
}

var inputPath = Path.GetFullPath(args[0]);
var outputPath = Path.GetFullPath(args[1]);
var allowTrustedProjectBuild = args.Length == 3;
if (!File.Exists(inputPath))
{
    Console.Error.WriteLine($"Input does not exist: {inputPath}");
    return 2;
}

Directory.CreateDirectory(outputPath);
var temporaryRoot = Path.Combine(Path.GetTempPath(), $"synapse-migration-{Guid.NewGuid():N}");
Directory.CreateDirectory(temporaryRoot);

try
{
    var dacpacPath = ResolveDacpac(inputPath, temporaryRoot, allowTrustedProjectBuild);
    var warnings = new BoundedBlindSpotCollection();
    (TSqlModel Model, string SelectedMode, string[] Attempts) modelLoad;
    try
    {
        modelLoad = LoadModelWithFallback(dacpacPath, warnings);
    }
    catch (ModelLoadFailureException exception)
    {
        var failureInventory = new
        {
            schemaVersion = 1,
            input = new
            {
                path = Path.GetFileName(inputPath),
                kind = Path.GetExtension(inputPath).Equals(".dacpac", StringComparison.OrdinalIgnoreCase)
                    ? "Dacpac"
                    : "ZippedSqlProject",
                resolvedDacpac = Path.GetFileName(dacpacPath)
            },
            modelLoadOptions = new
            {
                loadAsScriptBackedModel = true,
                preferredMode = "ScriptBacked",
                selectedMode = (string?)null,
                attempts = exception.Attempts,
                queryScope = "UserDefined"
            },
            status = "Blocked",
            blindSpots = warnings.ToArray()
        };
        File.WriteAllText(
            Path.Combine(outputPath, "schema-inventory.json"),
            JsonSerializer.Serialize(failureInventory, new JsonSerializerOptions { WriteIndented = true }));
        throw;
    }
    using var model = modelLoad.Model;
    var identifierComparer = model.CollationComparer;
    var modelMetadata = ExtractModelMetadata(dacpacPath);
    var conversionObjects = new List<object>();
    var evidenceObjects = new List<object>();
    var supportingObjects = new List<object>();
    Directory.CreateDirectory(Path.Combine(outputPath, "source"));

    foreach (var sourceObject in model.GetObjects(DacQueryScopes.UserDefined))
    {
        var objectType = sourceObject.ObjectType.Name ?? "Unclassified";
        var stableId = GetStableId(sourceObject);
        var category = Classify(objectType);

        if (category == ObjectCategory.Supporting)
        {
            supportingObjects.Add(CreateRecord(sourceObject, stableId, objectType, null, null, warnings, identifierComparer));
            continue;
        }

        string? sourceText = null;
        string? scriptError = null;
        try
        {
            sourceText = sourceObject.GetScript();
        }
        catch (Exception exception) when (exception is DacModelException or InvalidOperationException or NotSupportedException)
        {
            scriptError = SanitizeMessage(exception.Message);
            warnings.Add(new
            {
                code = "NonScriptableObject",
                sourceStableId = stableId,
                objectType,
                message = SanitizeMessage(exception.Message)
            });
        }
        if (scriptError is null && string.IsNullOrWhiteSpace(sourceText))
        {
            scriptError = "DacFx returned an empty object script.";
            warnings.Add(new
            {
                code = "NonScriptableObject",
                sourceStableId = stableId,
                objectType,
                message = scriptError
            });
        }

        string? sourcePath = null;
        if (!string.IsNullOrWhiteSpace(sourceText))
        {
            sourcePath = Path.Combine("source", $"{ToEvidenceFileName(stableId)}.sql").Replace('\\', '/');
            File.WriteAllText(Path.Combine(outputPath, sourcePath), sourceText);
        }

        var record = CreateRecord(sourceObject, stableId, objectType, sourcePath, scriptError, warnings, identifierComparer);
        if (category == ObjectCategory.Conversion)
        {
            record["conversionStatus"] = (bool)record["scriptable"]!
                ? "Eligible"
                : "ManualReviewRequired";
            record["sourceContractBlockers"] = Array.Empty<object>();
            conversionObjects.Add(record);
        }
        else
        {
            evidenceObjects.Add(record);
        }
    }

    var sourceContracts = ExtractSourceContracts(model, warnings, identifierComparer);
    ApplySourceContractBlockers(conversionObjects, sourceContracts, identifierComparer);
    var inventory = new
    {
        schemaVersion = 1,
        input = new
        {
            path = Path.GetFileName(inputPath),
            kind = Path.GetExtension(inputPath).Equals(".dacpac", StringComparison.OrdinalIgnoreCase)
                ? "Dacpac"
                : "ZippedSqlProject",
            resolvedDacpac = Path.GetFileName(dacpacPath)
        },
        modelLoadOptions = new
        {
            loadAsScriptBackedModel = string.Equals(
                modelLoad.SelectedMode,
                "ScriptBacked",
                StringComparison.Ordinal),
            preferredMode = "ScriptBacked",
            selectedMode = modelLoad.SelectedMode,
            attempts = modelLoad.Attempts,
            queryScope = "UserDefined"
        },
        modelMetadata,
        objects = conversionObjects,
        evidenceObjects,
        supportingObjects,
        sourceContracts,
        blindSpots = warnings.ToArray()
    };

    var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
    File.WriteAllText(
        Path.Combine(outputPath, "schema-inventory.json"),
        JsonSerializer.Serialize(inventory, jsonOptions));
    Console.WriteLine(Path.Combine(outputPath, "schema-inventory.json"));
    return 0;
}
finally
{
    if (Directory.Exists(temporaryRoot))
    {
        TryDeleteDirectory(temporaryRoot);
    }
}
}
catch (Exception exception)
{
    Console.Error.WriteLine($"Dedicated Pool discovery failed: {SanitizeMessage(exception.Message)}");
    return 1;
}

static (TSqlModel Model, string SelectedMode, string[] Attempts) LoadModelWithFallback(
    string dacpacPath,
    BoundedBlindSpotCollection blindSpots)
{
    var attempts = new List<string> { "ScriptBacked" };
    try
    {
        return (
            TSqlModel.LoadFromDacpac(
                dacpacPath,
                new ModelLoadOptions { LoadAsScriptBackedModel = true }),
            "ScriptBacked",
            attempts.ToArray());
    }
    catch (Exception exception) when (
        exception is DacModelException or InvalidOperationException or NotSupportedException)
    {
        blindSpots.Add(new
        {
            code = "ScriptBackedModelLoadFailed",
            message = SanitizeMessage(exception.Message),
            fallbackMode = "ModelOnly",
            impact = "Object scripts can be unavailable in fallback mode; every missing script is recorded as NonScriptableObject."
        });
    }

    attempts.Add("ModelOnly");
    try
    {
        return (
            TSqlModel.LoadFromDacpac(
                dacpacPath,
                new ModelLoadOptions { LoadAsScriptBackedModel = false }),
            "ModelOnly",
            attempts.ToArray());
    }
    catch (Exception exception)
    {
        blindSpots.Add(new
        {
            code = "ModelOnlyModelLoadFailed",
            message = SanitizeMessage(exception.Message),
            impact = "Discovery could not load the DACPAC in either supported mode."
        });
        throw new ModelLoadFailureException(attempts.ToArray(), exception);
    }
}

static string SanitizeMessage(string message)
{
    return DedicatedPoolMessageSanitizer.Sanitize(message);
}

static void TryDeleteDirectory(string path)
{
    try
    {
        Directory.Delete(path, recursive: true);
    }
    catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
    {
        Console.Error.WriteLine($"Warning: temporary directory cleanup failed: {SanitizeMessage(exception.Message)}");
    }
}

static object ExtractModelMetadata(string dacpacPath)
{
    const int maximumTrackedTypes = 100;
    using var archive = ZipFile.OpenRead(dacpacPath);
    var modelEntry = archive.Entries.SingleOrDefault(entry =>
        entry.FullName.Equals("model.xml", StringComparison.OrdinalIgnoreCase))
        ?? throw new InvalidOperationException("The DACPAC does not contain model.xml.");
    using var stream = modelEntry.Open();
    using var reader = XmlReader.Create(stream, new XmlReaderSettings
    {
        DtdProcessing = DtdProcessing.Prohibit,
        XmlResolver = null
    });

    var elementCount = 0L;
    var untrackedTypeElementCount = 0L;
    var typeCounts = new Dictionary<string, long>(StringComparer.Ordinal);
    while (reader.Read())
    {
        if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "Element")
        {
            continue;
        }

        elementCount++;
        var type = reader.GetAttribute("Type") ?? "Unclassified";
        if (typeCounts.TryGetValue(type, out var count))
        {
            typeCounts[type] = count + 1;
        }
        else if (typeCounts.Count < maximumTrackedTypes)
        {
            typeCounts[type] = 1;
        }
        else
        {
            untrackedTypeElementCount++;
        }
    }

    return new
    {
        source = "model.xml",
        modelXmlBytes = modelEntry.Length,
        compressedModelXmlBytes = modelEntry.CompressedLength,
        elementCount,
        elementTypes = typeCounts
            .OrderBy(pair => pair.Key, StringComparer.Ordinal)
            .Select(pair => new { type = pair.Key, count = pair.Value })
            .ToArray(),
        maximumTrackedTypes,
        untrackedTypeElementCount,
        detail = "Bounded summary only; per-object metadata is emitted in the typed inventory collections."
    };
}

static string ResolveDacpac(string inputPath, string temporaryRoot, bool allowTrustedProjectBuild)
{
    if (Path.GetExtension(inputPath).Equals(".dacpac", StringComparison.OrdinalIgnoreCase))
    {
        return inputPath;
    }

    if (!Path.GetExtension(inputPath).Equals(".zip", StringComparison.OrdinalIgnoreCase))
    {
        throw new ArgumentException("Input must be a .dacpac or .zip file.");
    }

    var extractRoot = Path.Combine(temporaryRoot, "input");
    ExtractZipSafely(inputPath, extractRoot);
    var packagedDacpacs = FindFilesByExtension(extractRoot, ".dacpac");
    if (packagedDacpacs.Length == 1)
    {
        return packagedDacpacs[0];
    }
    if (packagedDacpacs.Length > 1)
    {
        throw new InvalidOperationException("The zip contains multiple DACPAC files; extract the desired DACPAC and pass its path directly.");
    }

    var projects = FindFilesByExtension(extractRoot, ".sqlproj");
    if (projects.Length != 1)
    {
        throw new InvalidOperationException("The zip must contain exactly one DACPAC or one SQL project.");
    }
    if (!allowTrustedProjectBuild)
    {
        throw new InvalidOperationException(
            "The zip contains a SQL project but no DACPAC. Building a SQL project executes its MSBuild targets and is disabled by default. " +
            "Build it in an isolated trusted environment and pass the DACPAC, or explicitly opt in with --allow-trusted-project-build only after reviewing and trusting the project.");
    }

    var buildRoot = Path.Combine(temporaryRoot, "build");
    Directory.CreateDirectory(buildRoot);
    var startInfo = new ProcessStartInfo("dotnet")
    {
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    };
    startInfo.ArgumentList.Add("build");
    startInfo.ArgumentList.Add(projects[0]);
    startInfo.ArgumentList.Add("--nologo");
    startInfo.ArgumentList.Add("--output");
    startInfo.ArgumentList.Add(buildRoot);

    Console.Error.WriteLine($"Building explicitly trusted SQL project '{projects[0]}'; its MSBuild targets and tasks will execute.");
    using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Unable to start dotnet build.");
    var standardOutputTask = process.StandardOutput.ReadToEndAsync();
    var standardErrorTask = process.StandardError.ReadToEndAsync();
    using var buildTimeout = new CancellationTokenSource(TimeSpan.FromMinutes(5));
    try
    {
        process.WaitForExitAsync(buildTimeout.Token).GetAwaiter().GetResult();
    }
    catch (OperationCanceledException)
    {
        process.Kill(entireProcessTree: true);
        Task.WaitAll(standardOutputTask, standardErrorTask);
        throw new TimeoutException("SQL project build exceeded the five-minute discovery limit.");
    }
    Task.WaitAll(standardOutputTask, standardErrorTask);
    var standardOutput = standardOutputTask.Result;
    var standardError = standardErrorTask.Result;
    if (process.ExitCode != 0)
    {
        throw new InvalidOperationException($"SQL project build failed.\n{standardOutput}\n{standardError}");
    }

    var builtDacpacs = FindFilesByExtension(buildRoot, ".dacpac");
    return builtDacpacs.Length == 1
        ? builtDacpacs[0]
        : throw new InvalidOperationException($"SQL project build produced {builtDacpacs.Length} DACPAC files; expected one.");
}

static string[] FindFilesByExtension(string root, string extension)
{
    return Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
        .Where(path => Path.GetExtension(path).Equals(extension, StringComparison.OrdinalIgnoreCase))
        .ToArray();
}

static void ExtractZipSafely(string inputPath, string extractRoot)
{
    Directory.CreateDirectory(extractRoot);
    var extractionPrefix = Path.GetFullPath(extractRoot) + Path.DirectorySeparatorChar;
    var pathComparison = OperatingSystem.IsWindows()
        ? StringComparison.OrdinalIgnoreCase
        : StringComparison.Ordinal;
    using var archive = ZipFile.OpenRead(inputPath);
    foreach (var entry in archive.Entries)
    {
        var destinationPath = Path.GetFullPath(Path.Combine(extractRoot, entry.FullName));
        if (!destinationPath.StartsWith(extractionPrefix, pathComparison))
        {
            throw new InvalidDataException($"Zip entry escapes the extraction directory: {entry.FullName}");
        }

        if (string.IsNullOrEmpty(entry.Name))
        {
            Directory.CreateDirectory(destinationPath);
            continue;
        }

        Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
        entry.ExtractToFile(destinationPath, overwrite: false);
    }
}

static Dictionary<string, object?> CreateRecord(
    TSqlObject sourceObject,
    string stableId,
    string objectType,
    string? sourcePath,
    string? scriptError,
    BoundedBlindSpotCollection blindSpots,
    ModelCollationComparer identifierComparer)
{
    var recordWarnings = scriptError is null
        ? new List<string>()
        : new List<string> { "NonScriptableObject" };
    var dependencies = Array.Empty<string>();
    var dependencyExtractionComplete = true;
    try
    {
        dependencies = sourceObject.GetReferenced()
            .Select(GetStableId)
            .Where(dependency => !identifierComparer.Equals(dependency, stableId))
            .Distinct(identifierComparer)
            .OrderBy(dependency => dependency, identifierComparer)
            .ToArray();
    }
    catch (Exception exception)
    {
        dependencyExtractionComplete = false;
        recordWarnings.Add("DependencyExtractionFailed");
        blindSpots.Add(new
        {
            code = "DependencyExtractionFailed",
            sourceStableId = stableId,
            objectType,
            message = SanitizeMessage(exception.Message)
        });
    }

    return new Dictionary<string, object?>
    {
        ["sourceStableId"] = stableId,
        ["objectType"] = objectType,
        ["sourcePath"] = sourcePath,
        ["scriptable"] = scriptError is null && sourcePath is not null && dependencyExtractionComplete,
        ["scriptError"] = scriptError,
        ["dependencies"] = dependencies,
        ["dependencyExtractionComplete"] = dependencyExtractionComplete,
        ["warnings"] = recordWarnings.ToArray(),
        ["dacFxName"] = sourceObject.Name?.ToString()
    };
}

static void ApplySourceContractBlockers(
    List<object> conversionObjects,
    object[] sourceContracts,
    ModelCollationComparer identifierComparer)
{
    var blockersByProcedure = sourceContracts
        .Where(contract => !string.Equals(
            GetObjectProperty(contract, "status") as string,
            "Resolved",
            StringComparison.Ordinal))
        .GroupBy(
            contract => GetObjectProperty(contract, "referencingObject") as string ?? string.Empty,
            identifierComparer)
        .ToDictionary(group => group.Key, group => group.ToArray(), identifierComparer);

    foreach (var record in conversionObjects.OfType<Dictionary<string, object?>>())
    {
        var stableId = record["sourceStableId"] as string;
        if (string.IsNullOrWhiteSpace(stableId) ||
            !blockersByProcedure.TryGetValue(stableId, out var blockers))
        {
            continue;
        }

        record["scriptable"] = false;
        record["conversionStatus"] = "ManualReviewRequired";
        record["sourceContractBlockers"] = blockers.Select(contract => new
        {
            status = GetObjectProperty(contract, "status"),
            blocker = GetObjectProperty(contract, "blocker"),
            referencedObject = GetObjectProperty(contract, "referencedObject"),
            referencedName = GetObjectProperty(contract, "referencedName"),
            missingColumns = GetObjectProperty(contract, "missingColumns")
        }).ToArray();
    }
}

static object? GetObjectProperty(object value, string propertyName) =>
    value.GetType().GetProperty(propertyName)?.GetValue(value);

static object[] ExtractSourceContracts(
    TSqlModel model,
    BoundedBlindSpotCollection blindSpots,
    ModelCollationComparer identifierComparer)
{
    var contracts = new List<object>();
    foreach (var procedure in model.GetObjects(DacQueryScopes.UserDefined).Where(item => IsProcedure(item.ObjectType.Name)))
    {
        var procedureId = GetStableId(procedure);
        try
        {
            var dependencies = new Dictionary<string, SourceContractAccumulator>(identifierComparer);
            foreach (var relationship in procedure.GetReferencedRelationshipInstances()
                         .Where(item => item.Relationship.Name.Equals("BodyDependencies", StringComparison.OrdinalIgnoreCase)))
            {
                var referenced = relationship.Object;
                if (referenced is null)
                {
                    contracts.Add(new
                    {
                        referencingObject = procedureId,
                        referencedObject = (string?)null,
                        referencedObjectType = "Unknown",
                        referencedName = relationship.ObjectName?.ToString(),
                        referencedColumns = Array.Empty<string>(),
                        discoveredProjection = Array.Empty<string>(),
                        missingColumns = Array.Empty<string>(),
                        status = "UnknownProjection",
                        blocker = "UnresolvedSourceContractReference"
                    });
                    blindSpots.Add(new
                    {
                        code = "UnresolvedSourceContractReference",
                        sourceStableId = procedureId,
                        objectType = procedure.ObjectType.Name,
                        referencedName = relationship.ObjectName?.ToString(),
                        message = "DacFx did not resolve a procedure body dependency to a model object."
                    });
                    continue;
                }
                var referencedType = referenced.ObjectType.Name ?? "Unclassified";
                string? referencedColumn = null;
                if (IsColumn(referencedType))
                {
                    referencedColumn = GetObjectLeafName(referenced);
                    referenced = referenced.GetParent(DacQueryScopes.UserDefined);
                    if (referenced is null)
                    {
                        contracts.Add(new
                        {
                            referencingObject = procedureId,
                            referencedObject = (string?)null,
                            referencedObjectType = "Unknown",
                            referencedName = relationship.ObjectName?.ToString(),
                            referencedColumns = new[] { referencedColumn },
                            discoveredProjection = Array.Empty<string>(),
                            missingColumns = new[] { referencedColumn },
                            status = "UnknownProjection",
                            blocker = "UnresolvedSourceContractParent"
                        });
                        blindSpots.Add(new
                        {
                            code = "UnresolvedSourceContractParent",
                            sourceStableId = procedureId,
                            objectType = procedure.ObjectType.Name,
                            referencedName = relationship.ObjectName?.ToString(),
                            referencedColumn,
                            message = "DacFx did not resolve a referenced column to its parent table or view."
                        });
                        continue;
                    }
                    referencedType = referenced?.ObjectType.Name ?? "Unclassified";
                }
                if (referenced is null || !IsTableOrView(referencedType))
                {
                    contracts.Add(new
                    {
                        referencingObject = procedureId,
                        referencedObject = referenced is null ? null : (string?)GetStableId(referenced),
                        referencedObjectType = referencedType,
                        referencedName = relationship.ObjectName?.ToString(),
                        referencedColumns = string.IsNullOrWhiteSpace(referencedColumn)
                            ? Array.Empty<string>()
                            : new[] { referencedColumn },
                        discoveredProjection = Array.Empty<string>(),
                        missingColumns = string.IsNullOrWhiteSpace(referencedColumn)
                            ? Array.Empty<string>()
                            : new[] { referencedColumn },
                        status = "UnknownProjection",
                        blocker = "UnsupportedSourceContractReference"
                    });
                    continue;
                }

                var referencedId = GetStableId(referenced);
                if (!dependencies.TryGetValue(referencedId, out var dependency))
                {
                    dependency = new SourceContractAccumulator(referenced, NormalizeReferencedType(referencedType));
                    dependencies.Add(referencedId, dependency);
                }
                if (!string.IsNullOrWhiteSpace(referencedColumn))
                {
                    dependency.ReferencedColumns.Add(referencedColumn);
                }
            }

            foreach (var (referencedId, dependency) in dependencies.OrderBy(item => item.Key, identifierComparer))
            {
                var projection = GetOrderedProjection(dependency.ReferencedObject, dependency.ReferencedObjectType);
                var referencedColumns = dependency.ReferencedColumns
                    .Distinct(identifierComparer)
                    .OrderBy(column => column, identifierComparer)
                    .ToArray();
                var missingColumns = referencedColumns
                    .Where(column => !projection.Contains(column, identifierComparer))
                    .ToArray();
                contracts.Add(new
                {
                    referencingObject = procedureId,
                    referencedObject = referencedId,
                    referencedObjectType = dependency.ReferencedObjectType,
                    referencedColumns,
                    discoveredProjection = projection,
                    missingColumns,
                    status = projection.Length == 0
                        ? "UnknownProjection"
                        : missingColumns.Length == 0 ? "Resolved" : "MissingReferencedColumn"
                });
            }
        }
        catch (Exception exception)
        {
            contracts.Add(new
            {
                referencingObject = procedureId,
                referencedObject = (string?)null,
                referencedObjectType = "Unknown",
                referencedColumns = Array.Empty<string>(),
                discoveredProjection = Array.Empty<string>(),
                missingColumns = Array.Empty<string>(),
                status = "UnknownProjection",
                blocker = "SourceContractExtractionFailed"
            });
            blindSpots.Add(new
            {
                code = "SourceContractExtractionFailed",
                sourceStableId = procedureId,
                objectType = procedure.ObjectType.Name,
                message = SanitizeMessage(exception.Message)
            });
        }
    }
    return contracts.ToArray();
}

static string[] GetOrderedProjection(TSqlObject referencedObject, string referencedObjectType)
{
    var sourceObjectType = referencedObject.ObjectType.Name;
    var columns = string.Equals(sourceObjectType, "ExternalTable", StringComparison.OrdinalIgnoreCase)
        ? referencedObject.GetReferenced(ExternalTable.Columns, DacQueryScopes.UserDefined)
        : referencedObjectType == "Table"
            ? referencedObject.GetReferenced(Table.Columns, DacQueryScopes.UserDefined)
            : referencedObject.GetReferenced(View.Columns, DacQueryScopes.UserDefined);
    return columns.Select(GetObjectLeafName).ToArray();
}

static bool IsProcedure(string? objectType) =>
    objectType is not null && objectType.Contains("Procedure", StringComparison.OrdinalIgnoreCase);

static bool IsColumn(string? objectType) =>
    objectType is not null && objectType.Contains("Column", StringComparison.OrdinalIgnoreCase);

static bool IsTableOrView(string? objectType) =>
    objectType is not null &&
    (objectType.Equals("Table", StringComparison.OrdinalIgnoreCase) ||
     objectType.Equals("SqlTable", StringComparison.OrdinalIgnoreCase) ||
     objectType.Equals("ExternalTable", StringComparison.OrdinalIgnoreCase) ||
     objectType.Equals("View", StringComparison.OrdinalIgnoreCase) ||
     objectType.Equals("SqlView", StringComparison.OrdinalIgnoreCase));

static string NormalizeReferencedType(string objectType) =>
    objectType.Equals("View", StringComparison.OrdinalIgnoreCase) ||
    objectType.Equals("SqlView", StringComparison.OrdinalIgnoreCase)
        ? "View"
        : "Table";

static string GetObjectLeafName(TSqlObject sourceObject) =>
    sourceObject.Name?.Parts.LastOrDefault() ?? GetStableId(sourceObject);

static string GetStableId(TSqlObject sourceObject)
{
    var parts = sourceObject.Name?.Parts;
    return parts is { Count: > 0 }
        ? string.Join('.', parts)
        : $"{sourceObject.ObjectType.Name}:unnamed";
}

static ObjectCategory Classify(string objectType)
{
    string[] conversionTypes =
    [
        "Table", "SqlTable", "View", "SqlView", "Procedure", "SqlProcedure",
        "ScalarFunction", "TableValuedFunction", "Synonym", "Sequence",
        "ExternalTable", "ExternalDataSource", "ExternalFileFormat"
    ];
    string[] evidenceTypes =
    [
        "Schema", "Role", "DatabaseRole", "User", "Permission", "SecurityPolicy",
        "WorkloadGroup", "WorkloadClassifier"
    ];
    return conversionTypes.Contains(objectType, StringComparer.OrdinalIgnoreCase)
        ? ObjectCategory.Conversion
        : evidenceTypes.Contains(objectType, StringComparer.OrdinalIgnoreCase)
            ? ObjectCategory.Evidence
            : ObjectCategory.Supporting;
}

static string ToEvidenceFileName(string stableId)
{
    var invalid = Path.GetInvalidFileNameChars().ToHashSet();
    var safeStem = new string(stableId.Select(character => invalid.Contains(character) ? '_' : character).ToArray());
    safeStem = safeStem[..Math.Min(safeStem.Length, 100)];
    var stableHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(stableId))).ToLowerInvariant();
    return $"{safeStem}--{stableHash[..16]}";
}

enum ObjectCategory
{
    Conversion,
    Evidence,
    Supporting
}

sealed class SourceContractAccumulator(TSqlObject referencedObject, string referencedObjectType)
{
    public TSqlObject ReferencedObject { get; } = referencedObject;
    public string ReferencedObjectType { get; } = referencedObjectType;
    public List<string> ReferencedColumns { get; } = new();
}

sealed class ModelLoadFailureException(string[] attempts, Exception innerException)
    : Exception("DacFx could not load the DACPAC in either supported mode.", innerException)
{
    public string[] Attempts { get; } = attempts;
}

sealed class BoundedBlindSpotCollection
{
    private const int MaximumRetainedItems = 999;
    private const int MaximumSerializedBytes = 512 * 1024;
    private readonly List<object> retained = new();
    private int retainedSerializedBytes;
    private int totalObservedCount;

    public void Add(object value)
    {
        totalObservedCount++;
        var serializedBytes = JsonSerializer.SerializeToUtf8Bytes(value).Length;
        if (retained.Count >= MaximumRetainedItems
            || retainedSerializedBytes + serializedBytes > MaximumSerializedBytes)
        {
            return;
        }

        retained.Add(value);
        retainedSerializedBytes += serializedBytes;
    }

    public object[] ToArray()
    {
        var droppedCount = totalObservedCount - retained.Count;
        if (droppedCount == 0)
        {
            var completeEvidence = retained.ToArray();
            if (GetPersistedSize(completeEvidence) <= MaximumSerializedBytes)
            {
                return completeEvidence;
            }

            var lastIndex = retained.Count - 1;
            retainedSerializedBytes -= JsonSerializer.SerializeToUtf8Bytes(retained[lastIndex]).Length;
            retained.RemoveAt(lastIndex);
            droppedCount++;
        }

        while (true)
        {
            var truncationEvidence = new
            {
                code = "BlindSpotEvidenceTruncated",
                totalObservedCount,
                retainedCount = retained.Count,
                droppedCount,
                maximumRetainedItems = MaximumRetainedItems,
                maximumSerializedBytes = MaximumSerializedBytes
            };
            var candidate = retained.Append(truncationEvidence).ToArray();
            if (GetPersistedSize(candidate) <= MaximumSerializedBytes)
            {
                return candidate;
            }

            var lastIndex = retained.Count - 1;
            retainedSerializedBytes -= JsonSerializer.SerializeToUtf8Bytes(retained[lastIndex]).Length;
            retained.RemoveAt(lastIndex);
            droppedCount++;
        }
    }

    private static int GetPersistedSize(object[] evidence) =>
        JsonSerializer.SerializeToUtf8Bytes(
            evidence,
            new JsonSerializerOptions { WriteIndented = true }).Length;
}

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/skills-for-fabric · skills/synapse-migration · commit f8fac11
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
microsoft/skills-for-fabric

AutoGineer is not affiliated with or endorsed by Microsoft or Microsoft.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download synapse-migration.zip