Metadata-Version: 2.4
Name: coop-schema-compare
Version: 0.1.19
Summary: Deterministic schema compare between SQL environments (Fabric Warehouse, Azure SQL) with an ordered promotion script. Reads only; applies nothing.
Author: Cooptimize
License: MIT License
        
        Copyright (c) 2026 Cooptimize / Aaron Jennings
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/kabukisensei/coop-schema-compare
Keywords: fabric,warehouse,azure-sql,schema,compare,deployment
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Database
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyodbc>=5.0
Provides-Extra: dev
Requires-Dist: ruff==0.16.1; extra == "dev"
Dynamic: license-file

# coop-schema-compare

Deterministic schema compare between two SQL schemas, live or as code, with an
ordered promotion script. Built for Microsoft Fabric Warehouse, where the
built-in deployment pipeline gives you no script to read; it works the same on
Azure SQL Database, Fabric SQL database and SQL Server. A side is a live
database (by SQL endpoint or by Fabric workspace and Warehouse or Lakehouse name), a
committed snapshot, or a repo folder of `.sql` files, in any pairing: repo
against repo, live against live, repo against live. It **reads only and applies
nothing**: the output is a report and a script a person reviews and runs through
their own deployment path.

Part of the coop suite (see [coop-agent](https://github.com/kabukisensei/coop-agent)).
coop calls it as its `schema_compare` tool; you can run it yourself.

## Install

```powershell
pipx install coop-schema-compare
```

Needs Python 3.10+, the Microsoft ODBC Driver 18 for SQL Server, and either an
access token in `SQL_ACCESS_TOKEN` or the Azure CLI signed in (`az login`).

## Use

```powershell
# dev against prod, live on both sides, named by workspace and warehouse (or lakehouse)
coop-schema-compare compare "fabric://Contoso Dev/QE_WH" "fabric://Contoso Prod/QE_WH" --source-environment dev --target-environment prod

# the same by SQL endpoint host
coop-schema-compare compare contoso-dev.datawarehouse.fabric.microsoft.com/QE_WH contoso-prod.datawarehouse.fabric.microsoft.com/QE_WH --source-environment dev --target-environment prod

# the repo (schema as code) against the live prod Warehouse
coop-schema-compare compare .\warehouse\QE_WH.Warehouse "fabric://Contoso Prod/QE_WH" --target-environment prod

# two branches of the repo, checked out side by side: no connection
coop-schema-compare diff ..\QE_WH-main\warehouse ..\QE_WH-feature\warehouse

# commit a snapshot of each side, then diff the folders offline (no connection)
coop-schema-compare snapshot "fabric://Contoso Dev/QE_WH" --out catalog/dev --environment dev
coop-schema-compare snapshot "fabric://Contoso Prod/QE_WH" --out catalog/prod --environment prod
coop-schema-compare diff catalog/dev catalog/prod
```

A side is one of:

| Form | Reads |
| --- | --- |
| `server/database` | the live catalog over an encrypted, token-authenticated connection |
| `fabric://<workspace>/<item>` | the same, with the SQL endpoint looked up through the Fabric REST API; workspace and item by id or display name; a Warehouse first, else a Lakehouse (its SQL analytics endpoint, kind `fabric_lakehouse`) |
| a snapshot folder | the folder `snapshot` or coop's `coop catalog snapshot` wrote (it holds `manifest.json`); no connection |
| any other folder | the repo: every `.sql` file under it, read as code; no connection |

The snapshot layout is the one coop's `coop catalog snapshot` writes, so either
tool's folder is a valid side for the other.

### The repo side

A repo side is a folder of T-SQL source: a Fabric Warehouse Git export or SQL
database project (one file per object under folders such as `dbo/Tables/`), or
a hand-kept `sql/` folder. Files are read in path order and split on `GO`; a
batch counts when its first statement is `CREATE SCHEMA`, `CREATE TABLE`, or
`CREATE [OR ALTER] VIEW | PROCEDURE | FUNCTION`. Everything else (post-deployment
scripts, `ALTER`, `INSERT`, `.sqlproj`, the `bin/` and `obj/` folders) is
ignored, and the report notes how many files held no object, so a mis-pointed
folder is visible. Table columns are read from the column list with the type
rendered as the live catalog renders it (`decimal(18, 2)`, `varchar(max)`; a
length or precision the source leaves out gets the engine default, `varchar(1)`
or `datetime2(7)`, as the engine itself would store it; write them out for an
exact compare). A column of an alias type (`CREATE TYPE s.Phone FROM
nvarchar(20) NOT NULL` anywhere in the folder) reads as its base type, which is
how the live catalog reports it; `sysname` reads as `nvarchar(128)`. A column of
a type the folder does not create is not read: its table's columns compare by
hand, and the notes say so. An `IDENTITY` column is read as identity on both sides (the live
side from `sys.identity_columns`) and is `NOT NULL` when it says neither, as the engine
makes it; `IDENTITY NULL`, which the engine refuses, is not read. Files are UTF-8, with
or without a byte order mark, or UTF-16 with one (as SSMS saves them); a file in any
other encoding is not read, so the side is partial. Constraints and defaults are out of scope, as
on the live side. A table with a computed column (`Total AS Id * 2`) compares by
hand: the live side reports the column's result type, which the reader does not
derive, so no ALTER or rebuild is scripted for it. Unquoted names are read in
any script (`dbo.Café`, `Ventes.Résumé`); a `CREATE` whose name the reader cannot
read whole makes the side partial, so an object it lacks compares as `unknown`,
never as removed. A view, procedure, function or trigger compares by
its text with a leading comment banner, `OR ALTER` and a trailing `;` ignored,
so a file and the catalog's copy of the same object match.

`compare` and `diff` write three files under `--out` (default
`./schema-compare/<source>-to-<target>/`):

- `report.md`: both sides' object counts, the choices the run used, and one
  entry per object: its kind, the detected change, the deployment action and
  each column change, with destructive ones in bold.
- `report-detail.md`: what differs in each object, for a reviewer, written in
  the same run from the catalogs already read (no extra read, connection or
  approval) and linked from `report.md` and back. It lists every difference,
  shows each changed view, procedure, function or trigger as a bounded diff
  (`-` target before, `+` source after), shows a small change shared by
  several objects once with every object named, and says when a change is
  formatting or comments only (checked with string literals and quoted names
  kept). Tables carry the compare's own column changes and the plan's
  destructive and manual flags; nothing is classified a second time. A
  definition that could not be read whole is listed as unknown with the side
  named, never as a drop or a match. Output is capped per object and in total
  and says what it left out. It can hold client SQL: read it before sharing.
  A run that cannot write it says so in the notes, links nothing and removes
  an earlier file of its own.
- `deploy.sql`: the promotion script, built from the same per-object record so
  the two files agree. Sections run in order: new schemas, new tables, table
  changes, then functions, views, procedures and triggers as `CREATE OR ALTER` in
  dependency order across kinds (`schema.name` references resolve exactly, a
  bare name only when one object has it), modules waiting on a manual table
  rebuild, removals, and what a person must do. An object replaced by another
  kind (a view that became a table, or the reverse) is dropped and recreated
  inside the section its new kind belongs to, so dependents still find it.
  Every object gets its own comment-only note batch, so notes never end up
  inside a saved view or procedure. A line break in a name or a note is written
  as `\n` in the note, so comment text stays inside its comment. A statement with
  a line that reads as `GO` or a sqlcmd command (inside a literal or a quoted
  name) is a manual step, commented out, so the tool running the script never
  splits it.

Destructive statements (a DROP, a dropped column, a type change that can lose
a value, a column made `NOT NULL`, a `NOT NULL` column added to an existing
table, a table rebuilt by policy) are **runnable** by default, because the
person reviews and runs the script. The report and the note batch mark each one
DESTRUCTIVE. `--destructive commented` prefixes every destructive statement
line with exactly `--`, so removing those two characters restores it byte for
byte. The tool never runs the script. A type change that cannot lose a value is
not destructive: a longer length of the same type when both are lengths SQL
Server accepts (`(max)` is 2^31-1 bytes on `varchar`, `nvarchar` and `varbinary`
only; a finite `nvarchar` is at most 4000, and the other finite lengths are at
most 8000), `varchar` to `nvarchar` when every source character fits in a real
`nvarchar` (`varchar(8000)` fits in `nvarchar(max)`; `varchar(max)` does not,
because `nvarchar(max)` holds 1,073,741,823 characters and `varchar(max)` holds
2,147,483,647 bytes), a `decimal` or `numeric` of the same name whose precision
is 1-38, whose scale is at most that precision, whose scale does not drop and
whose integer digits (precision minus scale) do not drop, and `tinyint` to
`smallint` to `int` to `bigint`. Making a `NOT NULL` column nullable is not
destructive. A shorter length, a length or precision SQL Server rejects
(`char(max)`, `nvarchar(8000)`), another type, a scale that drops a digit, or a
collation clause is destructive.

Tables follow the target's ALTER rules. A Fabric Warehouse adds nullable
columns and drops columns in place; a retyped column, a nullability change or
an identity change needs a rebuild. By default that is a manual rebuild note
with the source shape (keep the rows with `CREATE TABLE AS SELECT`); name the
table's schema with `--rebuild-tables-in NAME` (repeatable) to script
`DROP TABLE` + `CREATE TABLE` instead, empty, which suits dimension and fact
schemas reloaded by their pipelines. A rebuilt table's DML triggers go with it,
so the script creates the source's triggers on it again after the rebuild
(and a manual rebuild gets them as a commented-out step). A Lakehouse SQL endpoint cannot create,
change or drop tables with T-SQL, so every table change there, a new or
removed table included, is a note for a person. Identity is scripted
in the target's form: `bigint IDENTITY` with no seed or increment on Fabric.

`deploy.sql` ends with a `-- coop generated: sha256 ...` line.
When a rerun finds the file edited since it was written, the edited copy is
kept as `deploy.edited-<stamp>.sql` before the new one is written: the bytes
of the file as it was, in whatever encoding it was saved, under a name no file
holds yet (`deploy.edited-<stamp>-2.sql` when the first is taken). When the
copy cannot be written, the run stops with `internal_error` and `deploy.sql`
is left as it was.

Direction is "what the target needs to match the source". A difference that
changes no behaviour is labelled rather than hidden: a module that differs only
in whitespace, line breaks or comments shows as "(formatting only)" and a table
whose columns are merely reordered as "(column order only)", in the report, the
console and the result's `cosmetic` count; both are still scripted so the target
comes to match the source and stops being listed. A view or procedure
reformatted by an editor is not a change: definitions are compared with line
endings and runs of whitespace folded outside string literals and quoted
names, a leading comment banner dropped and `CREATE`, `CREATE OR ALTER` and
`ALTER` read alike. Whitespace inside a string literal or a quoted name is a
change, line endings included: `N'a<CR LF>b'` and `N'a<LF>b'` are different
values. Comments and string literals never order the script; objects that name
each other in a circle go to the manual section for a person to order. The
schemas every database has (`dbo`, `guest`, `sys`, `INFORMATION_SCHEMA`) are
never created or dropped; the objects in them still compare.

## What is compared

Schemas; tables (each column's name, type, nullability and position); views,
procedures, functions and DML triggers by definition. A trigger is read from its
own file or from its table's file after the table's `GO` (the DacFx and sqlsc
layout), and on the live side from `sys.sql_modules` like the other modules; it
is dropped before its table. Constraints, indexes, permissions and row data are
out of scope on both sides, and the report says so. When a repo side could not be
read whole (more files than the limit, an oversized or unreadable file, a
folder that could not be listed), an
object it lacks compares as `unknown`, never as removed, and the report's notes
say which files were skipped.

Every schema is compared unless `compare` or `diff` is narrowed:
`--schema NAME` keeps only the schemas named and `--exclude-schema NAME` leaves
one out (each repeatable; `--exclude-schema` wins; names match without regard
to case). Both sides are filtered before the diff, so a left-out schema is
never added, altered or dropped, and the report's notes name the filter.

```powershell
coop-schema-compare compare "fabric://Contoso Dev/QE_WH" "fabric://Contoso Prod/QE_WH" --schema sales --schema finance
```

## Exit codes and output

`0` the compare ran; `--fail-on-diff` gives `2` on any difference and
`--fail-on-destructive` gives `3` on a destructive one, or when `deploy.sql`
holds a destructive step (a `--rebuild-tables-in` DROP + CREATE included,
commented out or not), for CI gates; either
flag gives `2` when a side was not read whole (a list cut at the compare cap,
objects a snapshot skipped, a definition longer than the compare cap, which
is recorded as unknown rather than cut, a listed view, procedure, function or trigger
whose definition the catalog did not give, which is unknown on both sides
rather than equal, or a compared table with a column the
reader could not read): the JSON says `"complete": false`, and an
object such a side may hold is an `unknown` change, never an add or a drop.
A name on one side that the other side spells only in other letter case
(`dbo.Orders` and `dbo.orders`) is also `unknown`, marked `"case_only": true`:
it is the same object where the target's names ignore case and two where they
do not, so it is never scripted as a CREATE plus a DROP, and either flag gives
`2` for it.
`1` on an error, printed as a short state (`connection_failed`, `side_invalid`,
`pyodbc_unavailable`, `odbc_driver_unavailable`, `az_unavailable`,
`snapshot_missing`, `snapshot_incomplete` (a file the manifest lists is
missing, unreadable, outside the folder or without its snapshot header, or
the manifest's `files` list is not there or is not a list, or its `schemas`,
`truncated`, `skipped`, `oversized` or `unread` field is there and is not what
the writer wrote: a list, an object for `truncated`),
`output_not_snapshot`, `workspace_not_found`,
`warehouse_not_found`, `fabric_forbidden`). `--json` prints the result as one
object. No token, credential, server name, driver text or exception text is ever
printed or written.

## Authentication

The token for `https://database.windows.net/` is read from `SQL_ACCESS_TOKEN`
(or the variable `--token-env` names). When it is empty, the Azure CLI mints one
(`az account get-access-token`, `--tenant` to pin the tenant). The token goes to
the driver as a connection attribute and nowhere else. A `fabric://` side also
needs a token for `https://api.fabric.microsoft.com`, from `FABRIC_ACCESS_TOKEN`
(or `--fabric-token-env`) or the Azure CLI the same way; it is used for two
read-only GETs (list workspaces, list the workspace's warehouses) and nothing
else. Folder sides need no token.

## Why not SqlPackage or a deployment pipeline

Fabric deployment pipelines and Git integration promote a Warehouse through
DacFx: no script to read or edit, a column change drops and recreates the table,
permissions do not travel, and both sides must be workspaces in one tenant and
pipeline. SqlPackage supports the Warehouse but is a separate .NET tool on each
machine with a publish you cannot review line by line. This tool gives you the
plain script instead. SqlPackage remains the right tool for a full-fidelity
dacpac of a large estate.

## Develop

```sh
python -m pip install -e .
python -m unittest discover -s tests -v
```

Tests run offline with fake cursors; no database or network is needed.

## Releasing

`__version__` in `src/coop_schema_compare/__init__.py` is the one place the version is written (`pyproject.toml` reads it). To release: bump it, merge, then push the matching tag (`git tag v0.1.8 && git push origin v0.1.8`). `.github/workflows/publish.yml` checks the tag against `__version__`, builds, publishes to PyPI by trusted publishing and creates the GitHub Release. After the release is published, the workflow prints the coop-website sync command to run by hand (`bash scripts/sync-release.sh coop-schema-compare X.Y.Z` in a site clone, which opens the site's sync pull request: badge, pins, changelog); the site's reusable sync workflow lives in a private repository, which a public repository like this one cannot call. Releases happen only when Aaron asks for one and names the version.
