diff --git a/CLAUDE.md b/CLAUDE.md index 92499ac48..b5c229a03 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -271,6 +271,11 @@ shipped. `Core.AlarmHistorian` now carries a surgical direct pin of SQLite 3.50.2+ patch), overriding the `2.1.11` that `Microsoft.Data.Sqlite` pulls transitively. `dotnet restore`/`build` is clean with the audit active. +**Before upgrading a populated ConfigDb, run the upgrade preflight** (`src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight`, +exe `otopcua-preflight`, `OTOPCUA_CONFIG_CONNECTION`): read-only; names every row a pending migration's pre-check or the +next deploy would refuse; exit 1 on any. A new constraint-adding migration must add its row-naming twin to +`ControlPlane/Preflight/MigrationPreChecks.cs`. See `docs/v2/upgrade-preflight.md`. + Test projects live under `tests//` (Core, Server, Drivers, Drivers/Cli, Client, Tooling) — there is no single unit-test project. Unit suites are named `*.Tests`; integration suites are `*.IntegrationTests` diff --git a/README.md b/README.md index af26c5fe0..b22bcc99d 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ per-protocol driver CLIs in [docs/DriverClis.md](docs/DriverClis.md). | Configuration (appsettings + env vars) | [docs/Configuration.md](docs/Configuration.md) | | Service hosting and role gating | [docs/ServiceHosting.md](docs/ServiceHosting.md) | | Security (transport, LDAP, API keys, ACLs) | [docs/security.md](docs/security.md) | -| ZTag / SAPID reservations | [docs/Reservations.md](docs/Reservations.md) | +| ZTag / SAPID uniqueness (reservation ledger retired) | [docs/Reservations.md](docs/Reservations.md) | | AdminUI | [docs/v2/admin-ui.md](docs/v2/admin-ui.md) | | Test and deployment infrastructure | [infra/README.md](infra/README.md) | | Dev environment | [docs/v2/dev-environment.md](docs/v2/dev-environment.md) | diff --git a/ZB.MOM.WW.OtOpcUa.slnx b/ZB.MOM.WW.OtOpcUa.slnx index ee8036a72..f738137ca 100644 --- a/ZB.MOM.WW.OtOpcUa.slnx +++ b/ZB.MOM.WW.OtOpcUa.slnx @@ -80,6 +80,7 @@ + diff --git a/docs/README.md b/docs/README.md index 7f01ad5da..c420cbf68 100644 --- a/docs/README.md +++ b/docs/README.md @@ -85,11 +85,12 @@ Integration-test fixtures: [Modbus](drivers/Modbus-Test-Fixture.md) · [S7](driv | [ServiceHosting.md](ServiceHosting.md) | Single fused `OtOpcUa.Host` binary install/uninstall with role gating, Traefik, script-worker isolation | | [security.md](security.md) | Transport security profiles, LDAP (AdminUI), data-plane API keys, ACLs, role grants, OTOPCUA0001 analyzer | | [Redundancy.md](Redundancy.md) | `RedundancyStateActor`, `ServiceLevelCalculator`, per-cluster meshes, deploy acks, Prometheus metrics | -| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID external-ID reservations — publish-time claim, release flow | +| [Reservations.md](Reservations.md) | Fleet-wide ZTag / SAPID uniqueness — authoring check, deploy gate, unique indexes (reservation ledger retired, #1049) | | [v2/admin-ui.md](v2/admin-ui.md) | AdminUI spec | | [StatusDashboard.md](StatusDashboard.md) | Pointer — superseded by [v2/admin-ui.md](v2/admin-ui.md) | | [ui-consistency-validation.md](ui-consistency-validation.md) | Shared UI consistency validation record (2026-11) | | [v2/dev-environment.md](v2/dev-environment.md) | Dev-box bootstrap + endpoint inventory | +| [v2/upgrade-preflight.md](v2/upgrade-preflight.md) | `otopcua-preflight` — read-only pre-upgrade ConfigDb check (migration pre-checks, deploy gate, script gate) | | [v2/redundancy-interop-playbook.md](v2/redundancy-interop-playbook.md) | Redundancy interop playbook | ### Client tooling diff --git a/docs/Raw.md b/docs/Raw.md index 13c373c0d..1acfae4f0 100644 --- a/docs/Raw.md +++ b/docs/Raw.md @@ -150,7 +150,7 @@ The parent links of the config tables (Tag→Device/TagGroup, Device→DriverIns **logical** foreign keys only, and the service-layer "is it empty?" delete checks are not serialised against a concurrent add. The deploy gate (`DraftValidator.ValidateDanglingReferences`) therefore names every orphan as `DanglingReference` instead of letting each composer silently skip a row with no path. Also enforced at the gate: fleet-wide `Equipment.ZTag` / `SAPID` uniqueness (`BadDuplicateExternalIdentifier`; see -`docs/Reservations.md`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing +`docs/Reservations.md`; since #1049 also the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID`) and duplicate owned historian tagnames (`HistorianTagnameDuplicate`, `.claude/rules/historian.md`). The never-firing `PathTooLong` and `EquipmentUuidImmutable` rules were deleted (the UnsSegment charset already bounds the path at 164 chars; no prior-generation table exists to diff). diff --git a/docs/Reservations.md b/docs/Reservations.md index 4c5531f8a..34129c2bc 100644 --- a/docs/Reservations.md +++ b/docs/Reservations.md @@ -1,154 +1,31 @@ -# External-ID Reservations +# External-ID (ZTag / SAPID) uniqueness -> **Status (lmxopcua#998, 2026-12): the reservation ledger has no writer.** `sp_PublishGeneration`, the only code -> that inserted `ExternalIdReservation` rows, was retired with the generation model (it now only `RAISERROR`s), so the -> table stays empty and the pre-flight below can only fire against rows an operator inserted by hand. **Fleet-wide -> ZTag / SAPID uniqueness is now enforced by the deploy gate itself**: `DraftValidator.ValidateEquipmentExternalIdUniqueness` -> groups every equipment row in the (whole-DB) draft snapshot by trimmed, case-insensitive ZTag and by SAPID and -> reports each duplicate as `BadDuplicateExternalIdentifier` naming the other equipment (same cluster or not). -> Blank values mean "no identifier". The permanent-claim semantics described below (a retired asset's id staying -> reserved) are **not** provided; the table, `/reservations` page and release procedure remain for any rows that -> already exist. The equipment page's field hint says "rejected when you deploy", matching this. A filtered unique -> index on `Equipment.ZTag` / `SAPID` was not added (needs a duplicate pre-clean migration); the gate is the authority. +> **The reservation ledger is retired (lmxopcua#1049, 2026-12).** `ExternalIdReservation`, the `/reservations` +> page, `sp_ReleaseExternalIdReservation` and the deploy gate's reservation pre-flight are gone. The ledger's only +> writer, `sp_PublishGeneration`, was retired with the generation model, so the table stayed empty and the +> pre-flight could never fire (review 2026-12-02, C-3). The permanent "a retired asset's id stays claimed" semantics +> of decision #124 were therefore never in force in v3, and are not provided now. -The reservation subsystem guarantees that an asset's **external identifiers** -— its `ZTag` and `SAPID` — belong to exactly one piece of equipment across the -entire fleet, for all time. It is the mechanism that stops two pieces of -equipment (in the same cluster or different clusters, in the current generation -or an old one) from silently claiming the same plant tag. +An equipment's **external identifiers** — its `ZTag` (ERP id) and `SAPID` (SAP PM id) — are unique **fleet-wide**: +no two `Equipment` rows, in the same cluster or different clusters, may carry the same value. Both are optional; a +blank value means "no identifier". -This is **decision #124** in `docs/v2/plan.md`. +## Where it is enforced -## What a reservation is +| Layer | What | Comparison | +|---|---|---| +| Authoring (`UnsTreeService`) | Equipment create / update / CSV import refuse a value another equipment holds and name that equipment; an import names each clashing row (against the DB or an earlier row of the same file) and still imports the clean rows. Values are stored trimmed; blank is stored as `NULL`. | Trimmed; the DB's case-insensitive collation | +| Deploy gate (`DraftValidator.ValidateEquipmentExternalIdUniqueness`) | The authority: every duplicate in the whole-DB draft snapshot is reported as `BadDuplicateExternalIdentifier`, naming the other equipment. | Trimmed, case-insensitive, blank = none | +| Storage (`UX_Equipment_ZTag`, `UX_Equipment_SAPID`) | Filtered UNIQUE indexes, `WHERE [ZTag] IS NOT NULL AND [ZTag] <> N''` (same for `SAPID`) — the backstop for a concurrent save or a hand edit. Never stricter than the gate. | Column collation (case-insensitive) | -An `ExternalIdReservation` row is a permanent, fleet-wide claim on one -identifier value by one `EquipmentUuid`. There are two kinds -(`ReservationKind`): +## Upgrading a populated ConfigDb -| Kind | What it is | -|---------|------------| -| `ZTag` | The plant's tag identity for a physical asset. | -| `SAPID` | The asset's SAP record ID. | - -An `Equipment` row may carry a `ZTag`, a `SAPID`, both, or neither. Whenever it -carries one and the generation is published, a reservation is created for that -value. - -## Why it sits outside the generation flow - -Every other part of the configuration is **generation-versioned** — authored in -a draft, promoted by publish, superseded by the next publish, and reversible by -rollback. Reservations deliberately are **not**. - -The reason: a single ZTag can legitimately appear in many places at once — the -current published generation, several superseded generations, and a piece of -equipment that has since been disabled. A per-generation uniqueness index would -fail the instant you roll back to an older generation or re-enable disabled -equipment, because the "old" copy of the identifier is still on disk. - -So the reservation table is a flat, fleet-wide ledger that lives *beside* the -generation flow. It is append-mostly: rows are created, their `LastPublishedAt` -is refreshed, and they are eventually *released* — but never silently deleted. - -## The table - -`ExternalIdReservation` (Config DB): - -| Column | Notes | -|--------------------|-------| -| `ReservationId` | Surrogate PK (`NEWSEQUENTIALID()`). | -| `Kind` | `ZTag` or `SAPID`. | -| `Value` | The reserved identifier string. | -| `EquipmentUuid` | The equipment that owns the claim. Stays bound even when that equipment is disabled. | -| `ClusterId` | The first cluster to publish the reservation. | -| `FirstPublishedAt` / `FirstPublishedBy` | When and by whom the claim was first made. | -| `LastPublishedAt` | Refreshed on every subsequent publish that re-asserts the same `(Kind, Value, EquipmentUuid)`. | -| `ReleasedAt` / `ReleasedBy` / `ReleaseReason` | Non-null once an Administrator explicitly releases the claim. `ReleasedBy` is the LDAP operator name (passed explicitly as `@ReleasedBy`; not `SUSER_SNAME()`). A row with `ReleasedAt IS NULL` is *active*. | - -There is no foreign key from `EquipmentUuid` / `ClusterId` to their tables — by -design, so a reservation survives the deletion or disabling of the equipment -that owns it. - -## Lifecycle - -### 1. Authoring - -You give an `Equipment` row a `ZTag` and/or `SAPID` in a **draft** generation — -either by hand in the draft editor or via equipment CSV import. Nothing is -reserved yet; the draft is just a proposal. - -> Equipment CSV import does **not** pre-check reservation conflicts (tracked as -> task #197). A conflict introduced by import surfaces at publish time, below. - -### 2. Publish precheck - -`sp_PublishGeneration` runs the draft validation first. If a `ZTag` or `SAPID` -in the draft is already reserved — `ReleasedAt IS NULL` — by a **different** -`EquipmentUuid`, the publish is rejected: - -``` -BadDuplicateExternalIdentifier: a ZTag in the draft is reserved by a -different EquipmentUuid -``` - -The same value owned by the *same* `EquipmentUuid` is fine — that is just the -asset keeping its identifier across generations. - -### 3. Publish (the reservation is created) - -When the publish succeeds, `sp_PublishGeneration` runs a `MERGE` into -`ExternalIdReservation` for every `ZTag`/`SAPID` in the published generation: - -- **New** `(Kind, Value, EquipmentUuid)` → a reservation row is **inserted**. - `FirstPublishedBy` is the publishing user; `ClusterId` is the publishing - cluster. -- **Already present** → only `LastPublishedAt` is bumped. - -So the *first* publish of an equipment carrying a ZTag is what claims that ZTag -for the fleet. After that the claim is permanent — it survives the equipment -being disabled, the generation being superseded, or a rollback. - -### 4. Release - -Reusing an identifier for a **different** piece of equipment requires an -Administrator to explicitly release the existing claim. Release runs -`sp_ReleaseExternalIdReservation`, which: - -- Requires a non-empty **reason** — a hard audit invariant; the procedure - raises an error without one. -- Requires a non-empty **`@ReleasedBy`** — the LDAP operator name supplied - by the caller; the procedure raises an error without it. -- Stamps `ReleasedAt`, `ReleasedBy` (the supplied operator name), and - `ReleaseReason` rather than deleting the row, so the history is preserved. -- Once released, the `(Kind, Value)` pair is free — a different - `EquipmentUuid` can claim it on a future publish. - -Release the claim **only** when the physical asset is permanently retired and -its identifier genuinely needs to be reused. A reservation is meant to be -permanent for the life of the asset. - -## The Admin page - -`/reservations` (Admin UI) is the operator surface. It requires authentication -(`[Authorize]`) but is not restricted to a specific Admin UI role — any signed-in -user can view it. - -The page is a **read-only list** of `ExternalIdReservation` rows, ordered by Kind -then Value. It shows Kind, Value, owning `EquipmentUuid`, and Cluster. Since -#996 (review A-8) it lists **active** rows by default (a "Show released" toggle -adds the released ones and a Released column), reads only the displayed columns -(`ReservationListQuery`) and shows at most 200 rows with a "Showing N of M" -header — released rows accumulate for the life of the database. There is no -Release action and no Release dialog on this page. - -You cannot *create* a reservation from this page — reservations only ever come -into existence as a side-effect of publishing a generation. The release flow -is described in `docs/v2/admin-ui.md` § "Release an external-ID reservation" -and runs via `sp_ReleaseExternalIdReservation`. +Migration `ScriptForeignKeysAndExternalIdUniqueness` creates the unique indexes and drops the ledger. It refuses +(error 51049, nothing changed) while any non-blank ZTag or SAPID is duplicated, or while `ExternalIdReservation` +still holds rows (export them if their history matters, then delete them). Run the upgrade preflight first — it lists +exactly those rows: [docs/v2/upgrade-preflight.md](v2/upgrade-preflight.md). ## Related -- `docs/v2/plan.md` — decision #124 (reservations outside the generation flow). -- `docs/v2/admin-ui.md` — § "Release an external-ID reservation". -- `docs/v2/config-db-schema.md` — full Config DB schema. -- `OpcUaServer.md` — generations, draft/publish flow. +- `docs/v2/plan.md` — decision #124 (the original reservation design, historical). +- `docs/Raw.md` — the other deploy-gate uniqueness rules (#998). diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index ef0ef13ea..23a0d97f6 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -362,7 +362,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT - **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name. - Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`. - **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`. -- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`. +- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`). Since lmxopcua#1040 the database refuses it too: `FK_VirtualTag_Script` / `FK_ScriptedAlarm_Script` (Restrict) onto the `Script.ScriptId` alternate key, so a concurrent bind cannot leave a dangling row and an in-use delete fails; `UnsTreeService` refuses a missing script by name before the FK would. Calculation tags name their script inside `TagConfig` JSON, so only the delete guard and the gate (`CalculationScriptNotFound`) cover them. As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`. - **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. A tick that lands within half an interval of the last timer evaluation is dropped too (#1061): Akka's scheduler delivers every tick it missed during a stall of its thread (GC pause, CPU starvation) as one burst when it resumes, which used to run the script once per missed tick. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`. - **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound. - **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)). diff --git a/docs/drivers/Sql.md b/docs/drivers/Sql.md index c79f1b4fe..ae6a1543a 100644 --- a/docs/drivers/Sql.md +++ b/docs/drivers/Sql.md @@ -223,9 +223,11 @@ row: `SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the - parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL - reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical - rules remain as a second, independent layer. + parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast of a literal or an + expression (`'a'::text`, `(v)::numeric`), `LIMIT`, `ILIKE`, a T-SQL reserved word used as a bare alias + (`AS top`) — is refused on Odbc, so quote or rename it. (`col::type` between two bare identifiers happens + to PARSE as T-SQL static-member syntax and is accepted.) The lexical rules remain as a second, independent + layer. - **It executes in a read-only transaction where the provider has one** — always rolled back regardless: PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A @@ -246,7 +248,11 @@ row: **must** connect with a `SELECT`-only login (see [Database login](#database-login-required)). - A tag naming a query the driver config does not declare is **skipped** at Initialize (it reads `BadNodeIdUnknown`, and `/hosts` names the missing query). One unusable `queries` entry **fails the - driver** instead, because every tag that names it would otherwise go dark unexplained. + driver** instead, because every tag that names it would otherwise go dark unexplained. Since lmxopcua#1058 + the **deploy gate refuses it first** (`SqlNamedQueryInvalid`, naming the driver instance): it runs the same + `SqlNamedQueryRules.Describe` over the same merged config with the instance's provider. Before upgrading + a deployment that has Odbc drivers, run the [upgrade preflight](../v2/upgrade-preflight.md), which lists + every stored query the new guard refuses. - Query tags read no table, so they need **no catalog gate** — a driver serving only named queries skips the catalog load entirely. Nothing from a Query tag is ever quoted into SQL. diff --git a/docs/v2/config-db-schema.md b/docs/v2/config-db-schema.md index bdd7d69b2..7895825a4 100644 --- a/docs/v2/config-db-schema.md +++ b/docs/v2/config-db-schema.md @@ -447,7 +447,9 @@ CREATE INDEX IX_Equipment_Generation_MachineCode ON dbo.Equipment (GenerationId, MachineCode); ``` -**Note on ZTag/SAPID uniqueness**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe. +> **Current (v3, lmxopcua#1049):** the reservation ledger below is retired and dropped. Uniqueness is enforced by `UnsTreeService`, the deploy gate (`BadDuplicateExternalIdentifier`) and the filtered unique indexes `UX_Equipment_ZTag` / `UX_Equipment_SAPID` — see `docs/Reservations.md`. + +**Note on ZTag/SAPID uniqueness (historical v2 design)**: per-generation indexes above are non-unique (only `IX_*`, not `UX_*`). Fleet-wide uniqueness lives in the `ExternalIdReservation` table (see below). Per-generation indexes exist only for fast lookup; uniqueness is enforced at publish time against the reservation table, which is rollback-safe. **Identifier responsibilities** — equipment carries five distinct identifiers, each with a different audience: @@ -572,7 +574,7 @@ The migrations widen `NodeAcl.ScopeKind` to 32 characters for mapping-specific g The database stores references for outbound connection credentials. See [Data connections](../DataConnections.md) for authorization and credential provisioning. -### `ExternalIdReservation` +### `ExternalIdReservation` (retired — dropped by migration `ScriptForeignKeysAndExternalIdUniqueness`, lmxopcua#1049) ```sql CREATE TABLE dbo.ExternalIdReservation ( diff --git a/docs/v2/upgrade-preflight.md b/docs/v2/upgrade-preflight.md new file mode 100644 index 000000000..e02656769 --- /dev/null +++ b/docs/v2/upgrade-preflight.md @@ -0,0 +1,83 @@ +# Upgrade preflight (`otopcua-preflight`) + +A **read-only** check of an OtOpcUa ConfigDb, run from the **new** build **before** its migrations are applied. +It reports every row that the upgrade — or the first deploy after it — would refuse, so the clean-up happens +before the maintenance window instead of in the middle of it. It issues only `SELECT`s. + +Introduced for the 2026-12-02 review remediation follow-ups lmxopcua#1013, #1015, #1021 and #1058. + +## What it checks + +| Section | What | Severity | Issue | +|---|---|---|---| +| `schema` | Applied vs pending migrations; tables/columns a pending migration creates (read as empty/default — see below); whether `ALLOW_SNAPSHOT_ISOLATION` is on. | Info / Warning | — | +| `migration:ConfigurationGapsIndexesAndRowVersions` | Duplicate `NodeAcl` rows per (cluster, principal, scope kind, scope id) — typically several Cluster-scope rows for one principal — and duplicate `LdapGroupRoleMapping` rows per (group, cluster), incl. system-wide. The migration THROWs on either. | Blocking | #1021 | +| `migration:ScriptForeignKeysAndExternalIdUniqueness` | `Script.ScriptId` NULL; a VirtualTag / ScriptedAlarm naming a script that does not exist; a non-blank ZTag or SAPID on more than one equipment (case-insensitive, as the new unique index); any `ExternalIdReservation` row (the table is dropped). The migration THROWs on any of them. | Blocking | #1040, #1049 | +| `deploy-gate` | The deploy gate's own rule pass (`DeployGateRules` — the code `AdminOperationsActor` runs): every `DraftValidator` rule, incl. the #978 rules `VirtualTagNameInvalid`, `UnsEffectiveNameInvalid` (illegal VirtualTag names / display-name overrides), `VirtualTagScriptNotFound`, `ScriptedAlarmScriptNotFound` (dangling script references), the #998 rules (`BadDuplicateExternalIdentifier`, `DanglingReference`, `HistorianTagnameDuplicate`), and `SqlNamedQueryInvalid`; the per-cluster topology check; the TagConfig inspection (Warning unless `--tagconfig-mode Error`). | Blocking (rules) / Warning | #1015, #1058 | +| `script-gate` | Every script the runtime will compile (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags, `{{equip}}` resolved) through the Roslyn compile + sandbox allow-list (`RoslynDeployScriptChecker`, as the deploy gate). Also every **unused** stored script, compiled as a value script — a Warning, since binding it later would be refused. | Blocking (Error mode) / Warning | #1013 | + +`SqlNamedQueryInvalid` (#1058) is a deploy-gate rule added with the preflight: the Sql driver checks every named +query with `SqlNamedQueryRules.Describe` under its provider at construction and one refused query fails the whole +driver. Since #974 that includes a T-SQL ScriptDom parse for SqlServer, Odbc and no-provider configs, so an **Odbc** +query written in another dialect (`LIMIT`, `ILIKE`, `'a'::text`, `(x)::numeric`) is refused — the deploy gate now +says so before the driver goes dark. (A bare `col::type` parses as T-SQL static-member syntax and is accepted.) + +### Reading an older schema + +The preflight reads the snapshot through **this build's** EF model, but the database is still on the old schema. +A table a pending migration creates is mapped to a typed zero-row query (it will be empty right after the +migration); a column a pending migration adds is left out of the model (the property keeps its default). The +`schema` section lists exactly which. A schema change the tolerance cannot bridge (e.g. a NULL in a column the new +model requires) is reported as `deploy-gate/SnapshotUnreadable`; fix the migration pre-check findings and re-run. + +Only v3 ConfigDbs (with `20260715230637_V3Initial` applied) are accepted; anything else exits 2. + +## Running it + +Build or publish it from the **new** source tree (it must carry the new rules and migrations): + +```bash +dotnet publish src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight -c Release -o out/preflight +# Windows target: add -r win-x64 --self-contained to run it on the box without an SDK +``` + +Pass the connection string through the environment (a command-line argument is visible in the process list and +shell history). A login with `db_datareader` on the ConfigDb is enough. + +```bash +export OTOPCUA_CONFIG_CONNECTION='Server=,;Database=;User Id=;Password=<...>;TrustServerCertificate=True' +out/preflight/otopcua-preflight # human-readable; Blocking + Warning findings +out/preflight/otopcua-preflight --verbose # + Info (pending migrations, clean sections) +out/preflight/otopcua-preflight --json > preflight.json +``` + +| Option | Default | Meaning | +|---|---|---| +| `--connection ""` | `OTOPCUA_CONFIG_CONNECTION` | ConfigDb connection string | +| `--tagconfig-mode Warn\|Error` | `Warn` | the target's `Deployment:TagConfigValidationMode` | +| `--script-gate Error\|Warn\|Off` | `Error` | the target's `Deployment:ScriptCompileGateMode` | +| `--no-unused-scripts` | off | skip compiling scripts nothing uses | +| `--json` / `--verbose` | off | output format | + +**Exit codes:** `0` nothing blocks the upgrade or the next deploy · `1` at least one Blocking finding · `2` usage +error, unreachable database, or not a v3 ConfigDb. + +## Upgrade procedure + +1. On the running (old) build's ConfigDb, run the preflight from the new build. It is read-only and safe to run + against a live database; under SNAPSHOT isolation it does not block editors. +2. Fix every Blocking finding through the AdminUI (re-point or delete the VirtualTag/ScriptedAlarm, clear the + duplicate ZTag, merge the duplicate ACL rows, rewrite the Odbc query, fix the script) — or, for + `ExternalIdReservation` rows, export them if their history matters and delete them. Re-run until exit 0. +3. Apply the new build (its migrations). A migration that still finds a bad row THROWs (error 50998 / 51049) and + changes nothing; re-run the preflight to see why. +4. Deploy. The deploy gate runs the same rules the preflight ran. + +## Results recorded + +| Date | Target | Schema at | Result | +|---|---|---|---| +| 2026-12-03 | docker-dev ConfigDb `OtOpcUa` (read from a copy of the stopped rig's SQL volume; the rig was not touched) | `EnableSnapshotIsolation` (6 pending) | exit 0 — both migration pre-checks clean, deploy gate clean, 3 in-use scripts compile; no Sql drivers | +| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaCfg_gate_scratch` | `V3Initial` (14 pending) | exit 0 — empty config; the NodeAcl duplicate pre-check could not run on the pre-#520 `LdapGroup` column (Warning) | +| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaConfig`, `OtOpcUaConfig_Dev` | v2 schema | exit 2 — not v3 ConfigDbs (nothing to check) | +| — | **production (wonder-app-vd03 / vq03 / vq04)** | — | **not run — user-gated.** Remote commands on the wonder boxes are on hold (see `CLAUDE.md`); an operator with SQL access runs step 1 there. | diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs index 9dc797509..06d1f2606 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs @@ -97,8 +97,7 @@ public static class EquipmentReferenceMap var names = new HashSet(StringComparer.Ordinal); foreach (var r in references) { - var effectiveName = r.DisplayNameOverride - ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null); + var effectiveName = EffectiveName(r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null); if (!string.IsNullOrEmpty(effectiveName)) names.Add(effectiveName); } return names; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ExternalIdReservation.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ExternalIdReservation.cs deleted file mode 100644 index 391648130..000000000 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/ExternalIdReservation.cs +++ /dev/null @@ -1,44 +0,0 @@ -using ZB.MOM.WW.OtOpcUa.Configuration.Enums; - -namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities; - -/// -/// Fleet-wide rollback-safe reservation of ZTag and SAPID. NOT generation-versioned. -/// Exists outside generation flow specifically because old generations and disabled equipment can -/// still hold the same external IDs; per-generation uniqueness indexes fail under rollback/re-enable. -/// -public sealed class ExternalIdReservation -{ - /// Gets or sets the unique reservation identifier. - public Guid ReservationId { get; set; } - - /// Gets or sets the kind of reservation (ZTag or SAPID). - public required ReservationKind Kind { get; set; } - - /// Gets or sets the reserved external ID value. - public required string Value { get; set; } - - /// The equipment that owns this reservation. Stays bound even when equipment is disabled. - public Guid EquipmentUuid { get; set; } - - /// First cluster to publish this reservation. - public required string ClusterId { get; set; } - - /// Gets or sets the timestamp when the reservation was first published. - public DateTime FirstPublishedAt { get; set; } = DateTime.UtcNow; - - /// Gets or sets the identifier of the user or system that first published the reservation. - public required string FirstPublishedBy { get; set; } - - /// Gets or sets the timestamp of the most recent publication. - public DateTime LastPublishedAt { get; set; } = DateTime.UtcNow; - - /// Non-null when explicitly released by FleetAdmin (audit-logged, requires reason). - public DateTime? ReleasedAt { get; set; } - - /// Gets or sets the identifier of the user or system that released the reservation. - public string? ReleasedBy { get; set; } - - /// Gets or sets the reason for releasing the reservation. - public string? ReleaseReason { get; set; } -} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/ReservationKind.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/ReservationKind.cs deleted file mode 100644 index 88f8b0ffd..000000000 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/ReservationKind.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums; - -/// External-ID reservation kind. -public enum ReservationKind -{ - ZTag, - SAPID, -} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.Designer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.Designer.cs new file mode 100644 index 000000000..3b6e0203d --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.Designer.cs @@ -0,0 +1,1981 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.OtOpcUa.Configuration; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + [DbContext(typeof(OtOpcUaConfigDbContext))] + [Migration("20261203200204_ScriptForeignKeysAndExternalIdUniqueness")] + partial class ScriptForeignKeysAndExternalIdUniqueness + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey", b => + { + b.Property("ApiKeyRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ApiKeyId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedUtc") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpiresUtc") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("ApiKeyRowId"); + + b.HasIndex("ApiKeyId") + .IsUnique() + .HasDatabaseName("UX_ApiKey_ApiKeyId"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_ApiKey_Principal"); + + b.ToTable("ApiKey", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AkkaPort") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(4053); + + b.Property("ApplicationUri") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("DashboardPort") + .HasColumnType("int"); + + b.Property("DriverConfigOverridesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GrpcPort") + .HasColumnType("int"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("LastSeenAt") + .HasColumnType("datetime2(3)"); + + b.Property("MaintenanceMode") + .HasColumnType("bit"); + + b.Property("OpcUaPort") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ServiceLevelBase") + .HasColumnType("tinyint"); + + b.HasKey("NodeId"); + + b.HasIndex("ApplicationUri") + .IsUnique() + .HasDatabaseName("UX_ClusterNode_ApplicationUri"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_ClusterNode_ClusterId"); + + b.ToTable("ClusterNode", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("NodeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RotatedAt") + .HasColumnType("datetime2(3)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.HasKey("CredentialId"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ClusterNodeCredential_Value") + .HasFilter("[Enabled] = 1"); + + b.HasIndex("NodeId", "Enabled") + .HasDatabaseName("IX_ClusterNodeCredential_NodeId"); + + b.ToTable("ClusterNodeCredential", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigAuditLog", b => + { + b.Property("AuditId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AuditId")); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GenerationId") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Outcome") + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.HasKey("AuditId"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("UX_ConfigAuditLog_EventId") + .HasFilter("[EventId] IS NOT NULL"); + + b.HasIndex("GenerationId") + .HasDatabaseName("IX_ConfigAuditLog_Generation") + .HasFilter("[GenerationId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_ConfigAuditLog_Cluster_Time"); + + b.ToTable("ConfigAuditLog", null, t => + { + t.HasCheckConstraint("CK_ConfigAuditLog_DetailsJson_IsJson", "DetailsJson IS NULL OR ISJSON(DetailsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigEdit", b => + { + b.Property("EditId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("EditedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("EditedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EntityId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("FieldsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceNode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EditId"); + + b.HasIndex("EditedAtUtc") + .HasDatabaseName("IX_ConfigEdit_EditedAt"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_ConfigEdit_Execution") + .HasFilter("[ExecutionId] IS NOT NULL"); + + b.HasIndex("EntityType", "EntityId") + .HasDatabaseName("IX_ConfigEdit_Entity"); + + b.ToTable("ConfigEdit", null, t => + { + t.HasCheckConstraint("CK_ConfigEdit_FieldsJson_IsJson", "ISJSON(FieldsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.Property("DataConnectionRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Consistency") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("EligibleTargetNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.PrimitiveCollection("Endpoints") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExpectedClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExpectedNodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistoryTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMessageBytes") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxPendingBytes") + .HasColumnType("bigint"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretReference") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("SecretScopeClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TargetMode") + .HasColumnType("int"); + + b.Property("TimeoutMilliseconds") + .HasColumnType("int"); + + b.HasKey("DataConnectionRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataConnectionId") + .IsUnique() + .HasFilter("[DataConnectionId] IS NOT NULL"); + + b.ToTable("DataConnection", null, t => + { + t.HasCheckConstraint("CK_DataConnection_Limits", "[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0 AND [HistoryTimeoutMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnectionScopeState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Fingerprint") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("DataConnectionScopeState", null, t => + { + t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + b.HasData( + new + { + Id = 1, + ScopeVersion = 0L + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.Property("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowGalaxyServiceAck") + .HasColumnType("bit"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DataExportId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxConcurrentHistoryReads") + .HasColumnType("int"); + + b.Property("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryResponseBytes") + .HasColumnType("int"); + + b.Property("MaxHistoryValuesPerPage") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RootKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DataExportRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataExportId") + .IsUnique() + .HasFilter("[DataExportId] IS NOT NULL"); + + b.ToTable("DataExport", null, t => + { + t.HasCheckConstraint("CK_DataExport_Limits", "[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0 AND [MaxConcurrentHistoryReads] > 0 AND [MaxHistoryValuesPerPage] > 0 AND [MaxHistoryResponseBytes] > 0 AND [MaxConditions] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", b => + { + b.Property("DeploymentId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ArtifactBlob") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("CreatedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SealedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("DeploymentId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_Deployment_CreatedAt"); + + b.HasIndex("Status") + .HasDatabaseName("IX_Deployment_Status"); + + b.ToTable("Deployment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Device", b => + { + b.Property("DeviceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DeviceRowId"); + + b.HasIndex("DeviceId") + .IsUnique() + .HasDatabaseName("UX_Device_LogicalId") + .HasFilter("[DeviceId] IS NOT NULL"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_Device_Driver"); + + b.HasIndex("DriverInstanceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Device_Driver_Name"); + + b.ToTable("Device", null, t => + { + t.HasCheckConstraint("CK_Device_DeviceConfig_IsJson", "ISJSON(DeviceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.Property("DriverInstanceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DriverInstanceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ResilienceConfig") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DriverInstanceRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_DriverInstance_Cluster"); + + b.HasIndex("DriverInstanceId") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_LogicalId") + .HasFilter("[DriverInstanceId] IS NOT NULL"); + + b.HasIndex("RawFolderId") + .HasDatabaseName("IX_DriverInstance_RawFolder"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_ClusterRoot_Name") + .HasFilter("[RawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "RawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_Folder_Name") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.ToTable("DriverInstance", null, t => + { + t.HasCheckConstraint("CK_DriverInstance_DriverConfig_IsJson", "ISJSON(DriverConfig) = 1"); + + t.HasCheckConstraint("CK_DriverInstance_ResilienceConfig_IsJson", "ResilienceConfig IS NULL OR ISJSON(ResilienceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Equipment", b => + { + b.Property("EquipmentRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AssetLocation") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("DeviceManualUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentClassRef") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("HardwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MachineCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Manufacturer") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ManufacturerUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Model") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SAPID") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SerialNumber") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SoftwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("UnsLineId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("YearOfConstruction") + .HasColumnType("smallint"); + + b.Property("ZTag") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EquipmentRowId"); + + b.HasIndex("EquipmentId") + .IsUnique() + .HasDatabaseName("UX_Equipment_LogicalId") + .HasFilter("[EquipmentId] IS NOT NULL"); + + b.HasIndex("EquipmentUuid") + .IsUnique() + .HasDatabaseName("UX_Equipment_Uuid"); + + b.HasIndex("MachineCode") + .HasDatabaseName("IX_Equipment_MachineCode"); + + b.HasIndex("SAPID") + .IsUnique() + .HasDatabaseName("UX_Equipment_SAPID") + .HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''"); + + b.HasIndex("UnsLineId") + .HasDatabaseName("IX_Equipment_Line"); + + b.HasIndex("ZTag") + .IsUnique() + .HasDatabaseName("UX_Equipment_ZTag") + .HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''"); + + b.HasIndex("UnsLineId", "Name") + .IsUnique() + .HasDatabaseName("UX_Equipment_LinePath"); + + b.ToTable("Equipment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("IsSystemWide") + .HasColumnType("bit"); + + b.Property("LdapGroup") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("ClusterId"); + + b.HasIndex("LdapGroup") + .HasDatabaseName("IX_LdapGroupRoleMapping_Group"); + + b.HasIndex("LdapGroup", "ClusterId") + .IsUnique() + .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster"); + + b.ToTable("LdapGroupRoleMapping", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeAcl", b => + { + b.Property("NodeAclRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("NodeAclId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PermissionFlags") + .HasColumnType("int"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ScopeKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("NodeAclRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_NodeAcl_Cluster"); + + b.HasIndex("NodeAclId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_LogicalId") + .HasFilter("[NodeAclId] IS NOT NULL"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_NodeAcl_Principal"); + + b.HasIndex("ScopeKind", "ScopeId") + .HasDatabaseName("IX_NodeAcl_Scope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_PrincipalScope"); + + b.ToTable("NodeAcl", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DeploymentId") + .HasColumnType("uniqueidentifier"); + + b.Property("AppliedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("StartedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("NodeId", "DeploymentId"); + + b.HasIndex("DeploymentId") + .HasDatabaseName("IX_NodeDeploymentState_Deployment"); + + b.HasIndex("Status") + .HasDatabaseName("IX_NodeDeploymentState_Status"); + + b.ToTable("NodeDeploymentState", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.PollGroup", b => + { + b.Property("PollGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("IntervalMs") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("PollGroupRowId"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_PollGroup_Driver"); + + b.HasIndex("PollGroupId") + .IsUnique() + .HasDatabaseName("UX_PollGroup_LogicalId") + .HasFilter("[PollGroupId] IS NOT NULL"); + + b.ToTable("PollGroup", null, t => + { + t.HasCheckConstraint("CK_PollGroup_IntervalMs_Min", "IntervalMs >= 50"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.Property("RawFolderRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentRawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("RawFolderRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_RawFolder_Cluster"); + + b.HasIndex("RawFolderId") + .IsUnique() + .HasDatabaseName("UX_RawFolder_LogicalId") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_ClusterRoot_Name") + .HasFilter("[ParentRawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "ParentRawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_Parent_Name") + .HasFilter("[ParentRawFolderId] IS NOT NULL"); + + b.ToTable("RawFolder", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.Property("RemoteNamespaceMappingRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("BranchName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ConditionMethodTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionSnapshotTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionStaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpectedArrayElementKind") + .HasColumnType("int"); + + b.Property("ExpectedValueKind") + .HasColumnType("int"); + + b.Property("LocalParentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LocalParentKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryAssemblyBytesPerRequest") + .HasColumnType("int"); + + b.Property("MaxProjectionDepth") + .HasColumnType("int"); + + b.Property("MaxProjectionNodes") + .HasColumnType("int"); + + b.Property("MetadataLeaseMilliseconds") + .HasColumnType("int"); + + b.Property("PublishingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("RemoteIdentifier") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteIdentifierKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RemoteNamespaceMappingId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RemoteNamespaceUri") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteRealm") + .HasColumnType("int"); + + b.Property("RemoteRootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SamplingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("StaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("WriteThrough") + .HasColumnType("bit"); + + b.HasKey("RemoteNamespaceMappingRowId"); + + b.HasIndex("RemoteNamespaceMappingId") + .IsUnique() + .HasFilter("[RemoteNamespaceMappingId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Realm", "LocalParentKind", "LocalParentId", "BranchName") + .IsUnique(); + + b.ToTable("RemoteNamespaceMapping", null, t => + { + t.HasCheckConstraint("CK_RemoteNamespaceMapping_Limits", "[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0 AND [MaxHistoryAssemblyBytesPerRequest] > 0 AND [MaxConditions] > 0 AND [ConditionStaleTimeoutMilliseconds] > 0 AND [ConditionMethodTimeoutMilliseconds] > 0 AND [ConditionSnapshotTimeoutMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", b => + { + b.Property("ScriptRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SourceCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ScriptRowId"); + + b.HasAlternateKey("ScriptId") + .HasName("UX_Script_LogicalId"); + + b.HasIndex("SourceHash") + .HasDatabaseName("IX_Script_SourceHash"); + + b.ToTable("Script", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.Property("ScriptedAlarmRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AlarmType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistorizeToAveva") + .HasColumnType("bit"); + + b.Property("MessageTemplate") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PredicateScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Retain") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptedAlarmId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Severity") + .HasColumnType("int"); + + b.HasKey("ScriptedAlarmRowId"); + + b.HasIndex("PredicateScriptId") + .HasDatabaseName("IX_ScriptedAlarm_Script"); + + b.HasIndex("ScriptedAlarmId") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_LogicalId") + .HasFilter("[ScriptedAlarmId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_EquipmentPath"); + + b.ToTable("ScriptedAlarm", null, t => + { + t.HasCheckConstraint("CK_ScriptedAlarm_AlarmType", "AlarmType IN ('AlarmCondition','LimitAlarm','OffNormalAlarm','DiscreteAlarm')"); + + t.HasCheckConstraint("CK_ScriptedAlarm_Severity_Range", "Severity BETWEEN 1 AND 1000"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Enterprise") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("ModifiedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ModifiedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NodeCount") + .HasColumnType("tinyint"); + + b.Property("Notes") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RedundancyMode") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("Site") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("ClusterId"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("UX_ServerCluster_Name"); + + b.HasIndex("Site") + .HasDatabaseName("IX_ServerCluster_Site"); + + b.ToTable("ServerCluster", null, t => + { + t.HasCheckConstraint("CK_ServerCluster_RedundancyMode_NodeCount", "((NodeCount = 1 AND RedundancyMode = 'None') OR (NodeCount = 2 AND RedundancyMode IN ('Warm', 'Hot')))"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Tag", b => + { + b.Property("TagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AccessLevel") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TagConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("WriteIdempotent") + .HasColumnType("bit"); + + b.HasKey("TagRowId"); + + b.HasIndex("TagId") + .IsUnique() + .HasDatabaseName("UX_Tag_LogicalId") + .HasFilter("[TagId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Device_Name") + .HasFilter("[TagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "TagGroupId") + .HasDatabaseName("IX_Tag_Device"); + + b.HasIndex("DeviceId", "TagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Group_Name") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.ToTable("Tag", null, t => + { + t.HasCheckConstraint("CK_Tag_TagConfig_IsJson", "ISJSON(TagConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.TagGroup", b => + { + b.Property("TagGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentTagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("TagGroupRowId"); + + b.HasIndex("DeviceId") + .HasDatabaseName("IX_TagGroup_Device"); + + b.HasIndex("TagGroupId") + .IsUnique() + .HasDatabaseName("UX_TagGroup_LogicalId") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_DeviceRoot_Name") + .HasFilter("[ParentTagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "ParentTagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_Parent_Name") + .HasFilter("[ParentTagGroupId] IS NOT NULL"); + + b.ToTable("TagGroup", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.Property("UnsAreaRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsAreaRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_UnsArea_Cluster"); + + b.HasIndex("UnsAreaId") + .IsUnique() + .HasDatabaseName("UX_UnsArea_LogicalId") + .HasFilter("[UnsAreaId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsArea_ClusterName"); + + b.ToTable("UnsArea", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsLine", b => + { + b.Property("UnsLineRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsLineId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsLineRowId"); + + b.HasIndex("UnsAreaId") + .HasDatabaseName("IX_UnsLine_Area"); + + b.HasIndex("UnsLineId") + .IsUnique() + .HasDatabaseName("UX_UnsLine_LogicalId") + .HasFilter("[UnsLineId] IS NOT NULL"); + + b.HasIndex("UnsAreaId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsLine_AreaName"); + + b.ToTable("UnsLine", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsTagReference", b => + { + b.Property("UnsTagReferenceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DisplayNameOverride") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsTagReferenceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsTagReferenceRowId"); + + b.HasIndex("EquipmentId") + .HasDatabaseName("IX_UnsTagReference_Equipment"); + + b.HasIndex("TagId") + .HasDatabaseName("IX_UnsTagReference_Tag"); + + b.HasIndex("UnsTagReferenceId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_LogicalId") + .HasFilter("[UnsTagReferenceId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "TagId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_Equip_Tag"); + + b.ToTable("UnsTagReference", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.Property("VirtualTagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ChangeTriggered") + .HasColumnType("bit"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Historize") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TimerIntervalMs") + .HasColumnType("int"); + + b.Property("VirtualTagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("VirtualTagRowId"); + + b.HasIndex("ScriptId") + .HasDatabaseName("IX_VirtualTag_Script"); + + b.HasIndex("VirtualTagId") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_LogicalId") + .HasFilter("[VirtualTagId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_EquipmentPath"); + + b.ToTable("VirtualTag", null, t => + { + t.HasCheckConstraint("CK_VirtualTag_TimerInterval_Min", "TimerIntervalMs IS NULL OR TimerIntervalMs >= 50"); + + t.HasCheckConstraint("CK_VirtualTag_Trigger_AtLeastOne", "ChangeTriggered = 1 OR TimerIntervalMs IS NOT NULL"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany("Nodes") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany("Credentials") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", "Deployment") + .WithMany() + .HasForeignKey("DeploymentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Deployment"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany("RawFolders") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("PredicateScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_ScriptedAlarm_Script"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("ScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_VirtualTag_Script"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Navigation("Credentials"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Navigation("Nodes"); + + b.Navigation("RawFolders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.cs new file mode 100644 index 000000000..6f2670845 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261203200204_ScriptForeignKeysAndExternalIdUniqueness.cs @@ -0,0 +1,267 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + /// + /// lmxopcua#1040 + lmxopcua#1049 (follow-ups of the 2026-12-02 review, #978 C-2 and #998 C-3). + /// + /// Real FKs FK_VirtualTag_Script / FK_ScriptedAlarm_Script (ON DELETE NO ACTION) onto + /// Script.ScriptId, which becomes NOT NULL and an alternate key (the unique constraint + /// UX_Script_LogicalId replaces the filtered unique index of the same name). + /// Filtered UNIQUE indexes UX_Equipment_ZTag / UX_Equipment_SAPID (blank = no identifier, + /// as the deploy gate) replace the non-unique IX_Equipment_ZTag / IX_Equipment_SAPID. + /// ExternalIdReservation and sp_ReleaseExternalIdReservation are dropped: the ledger has + /// had no writer since the generation model retired. + /// + /// Pre-check, never a silent clean. Each change would fail half-way (or delete history) over rows + /// that break it, so runs first and THROWs one error naming every offending row class: + /// a NULL Script.ScriptId, a VirtualTag / ScriptedAlarm naming a missing script, a duplicated non-blank + /// ZTag or SAPID, and any ExternalIdReservation row. Nothing is altered until the operator fixes them; the + /// preflight tool (docs/v2/upgrade-preflight.md) lists the same rows ahead of the upgrade. + /// + public partial class ScriptForeignKeysAndExternalIdUniqueness : Migration + { + /// The read-only pre-check; THROWs 51049 naming every problem class, or does nothing. + internal const string PreCheckSql = @" +DECLARE @problems nvarchar(max) = N''; +DECLARE @n int, @sample nvarchar(max); + +SELECT @n = COUNT(*) FROM [Script] WHERE [ScriptId] IS NULL; +IF @n > 0 SET @problems += CONCAT(N' [', @n, N' Script row(s) with a NULL ScriptId: give each a unique ScriptId or delete it]'); + +SET @sample = N''; +SELECT @n = COUNT(*) FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]); +SELECT TOP (5) @sample += CONCAT(N' ', v.[VirtualTagId], N'->', v.[ScriptId]) +FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = v.[ScriptId]) ORDER BY v.[VirtualTagId]; +IF @n > 0 SET @problems += CONCAT(N' [', @n, N' VirtualTag row(s) name a script that does not exist (VirtualTagId->ScriptId:', @sample, N'): point them at an existing script or delete them]'); + +SET @sample = N''; +SELECT @n = COUNT(*) FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]); +SELECT TOP (5) @sample += CONCAT(N' ', a.[ScriptedAlarmId], N'->', a.[PredicateScriptId]) +FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.[ScriptId] = a.[PredicateScriptId]) ORDER BY a.[ScriptedAlarmId]; +IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ScriptedAlarm row(s) name a predicate script that does not exist (ScriptedAlarmId->PredicateScriptId:', @sample, N'): point them at an existing script or delete them]'); + +SET @sample = N''; +SELECT @n = COUNT(*) FROM (SELECT [ZTag] FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d; +SELECT TOP (5) @sample += CONCAT(N' ''', d.[ZTag], N''' x', d.c) +FROM (SELECT [ZTag], COUNT(*) AS c FROM [Equipment] WHERE [ZTag] IS NOT NULL AND [ZTag] <> N'' GROUP BY [ZTag] HAVING COUNT(*) > 1) d ORDER BY d.[ZTag]; +IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ZTag value(s) are set on more than one Equipment row (', @sample, N'): keep each ZTag on one equipment and clear or change the others]'); + +SET @sample = N''; +SELECT @n = COUNT(*) FROM (SELECT [SAPID] FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d; +SELECT TOP (5) @sample += CONCAT(N' ''', d.[SAPID], N''' x', d.c) +FROM (SELECT [SAPID], COUNT(*) AS c FROM [Equipment] WHERE [SAPID] IS NOT NULL AND [SAPID] <> N'' GROUP BY [SAPID] HAVING COUNT(*) > 1) d ORDER BY d.[SAPID]; +IF @n > 0 SET @problems += CONCAT(N' [', @n, N' SAPID value(s) are set on more than one Equipment row (', @sample, N'): keep each SAPID on one equipment and clear or change the others]'); + +IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL +BEGIN + SELECT @n = COUNT(*) FROM [ExternalIdReservation]; + IF @n > 0 SET @problems += CONCAT(N' [', @n, N' ExternalIdReservation row(s): the ledger is retired and its table is dropped by this migration; export the rows if you need their history, DELETE FROM [ExternalIdReservation], then re-run]'); +END + +IF LEN(@problems) > 0 +BEGIN + DECLARE @msg nvarchar(2048) = LEFT(CONCAT(N'ScriptForeignKeysAndExternalIdUniqueness (lmxopcua#1040/#1049) refused - nothing was changed:', @problems), 2048); + THROW 51049, @msg, 1; +END +"; + + // sp_ReleaseExternalIdReservation as V3Initial created it — re-created by Down only. + private const string ReleaseExternalIdReservationProc = @" +CREATE OR ALTER PROCEDURE dbo.sp_ReleaseExternalIdReservation + @Kind nvarchar(16), + @Value nvarchar(64), + @ReleaseReason nvarchar(512) +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + + IF @ReleaseReason IS NULL OR LEN(@ReleaseReason) = 0 + BEGIN + RAISERROR('ReleaseReason is required', 16, 1); + RETURN; + END + + UPDATE dbo.ExternalIdReservation + SET ReleasedAt = SYSUTCDATETIME(), + ReleasedBy = SUSER_SNAME(), + ReleaseReason = @ReleaseReason + WHERE Kind = @Kind AND Value = @Value AND ReleasedAt IS NULL; + + IF @@ROWCOUNT = 0 + BEGIN + RAISERROR('No active reservation found for (%s, %s)', 16, 1, @Kind, @Value); + RETURN; + END + + INSERT dbo.ConfigAuditLog (Principal, EventType, DetailsJson) + VALUES (SUSER_SNAME(), 'ExternalIdReleased', + CONCAT('{""kind"":""', STRING_ESCAPE(@Kind, 'json'), + '"",""value"":""', STRING_ESCAPE(@Value, 'json'), '""}')); +END +"; + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(PreCheckSql); + + migrationBuilder.Sql("IF OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation', N'P') IS NOT NULL DROP PROCEDURE dbo.sp_ReleaseExternalIdReservation;"); + + migrationBuilder.DropTable( + name: "ExternalIdReservation"); + + migrationBuilder.DropIndex( + name: "UX_Script_LogicalId", + table: "Script"); + + migrationBuilder.DropIndex( + name: "IX_Equipment_SAPID", + table: "Equipment"); + + migrationBuilder.DropIndex( + name: "IX_Equipment_ZTag", + table: "Equipment"); + + migrationBuilder.AlterColumn( + name: "ScriptId", + table: "Script", + type: "nvarchar(64)", + maxLength: 64, + nullable: false, + oldClrType: typeof(string), + oldType: "nvarchar(64)", + oldMaxLength: 64, + oldNullable: true); + + migrationBuilder.AddUniqueConstraint( + name: "UX_Script_LogicalId", + table: "Script", + column: "ScriptId"); + + migrationBuilder.CreateIndex( + name: "UX_Equipment_SAPID", + table: "Equipment", + column: "SAPID", + unique: true, + filter: "[SAPID] IS NOT NULL AND [SAPID] <> N''"); + + migrationBuilder.CreateIndex( + name: "UX_Equipment_ZTag", + table: "Equipment", + column: "ZTag", + unique: true, + filter: "[ZTag] IS NOT NULL AND [ZTag] <> N''"); + + migrationBuilder.AddForeignKey( + name: "FK_ScriptedAlarm_Script", + table: "ScriptedAlarm", + column: "PredicateScriptId", + principalTable: "Script", + principalColumn: "ScriptId", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_VirtualTag_Script", + table: "VirtualTag", + column: "ScriptId", + principalTable: "Script", + principalColumn: "ScriptId", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ScriptedAlarm_Script", + table: "ScriptedAlarm"); + + migrationBuilder.DropForeignKey( + name: "FK_VirtualTag_Script", + table: "VirtualTag"); + + migrationBuilder.DropUniqueConstraint( + name: "UX_Script_LogicalId", + table: "Script"); + + migrationBuilder.DropIndex( + name: "UX_Equipment_SAPID", + table: "Equipment"); + + migrationBuilder.DropIndex( + name: "UX_Equipment_ZTag", + table: "Equipment"); + + migrationBuilder.AlterColumn( + name: "ScriptId", + table: "Script", + type: "nvarchar(64)", + maxLength: 64, + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(64)", + oldMaxLength: 64); + + migrationBuilder.CreateTable( + name: "ExternalIdReservation", + columns: table => new + { + ReservationId = table.Column(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"), + ClusterId = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + EquipmentUuid = table.Column(type: "uniqueidentifier", nullable: false), + FirstPublishedAt = table.Column(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"), + FirstPublishedBy = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Kind = table.Column(type: "nvarchar(16)", maxLength: 16, nullable: false), + LastPublishedAt = table.Column(type: "datetime2(3)", nullable: false, defaultValueSql: "SYSUTCDATETIME()"), + ReleaseReason = table.Column(type: "nvarchar(512)", maxLength: 512, nullable: true), + ReleasedAt = table.Column(type: "datetime2(3)", nullable: true), + ReleasedBy = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: true), + Value = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ExternalIdReservation", x => x.ReservationId); + }); + + migrationBuilder.CreateIndex( + name: "UX_Script_LogicalId", + table: "Script", + column: "ScriptId", + unique: true, + filter: "[ScriptId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_Equipment_SAPID", + table: "Equipment", + column: "SAPID", + filter: "[SAPID] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_Equipment_ZTag", + table: "Equipment", + column: "ZTag", + filter: "[ZTag] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_ExternalIdReservation_Equipment", + table: "ExternalIdReservation", + column: "EquipmentUuid"); + + migrationBuilder.CreateIndex( + name: "UX_ExternalIdReservation_KindValue_Active", + table: "ExternalIdReservation", + columns: new[] { "Kind", "Value" }, + unique: true, + filter: "[ReleasedAt] IS NULL"); + + migrationBuilder.Sql(ReleaseExternalIdReservationProc); + migrationBuilder.Sql(@" +IF DATABASE_PRINCIPAL_ID('OtOpcUaAdmin') IS NOT NULL + GRANT EXECUTE ON OBJECT::dbo.sp_ReleaseExternalIdReservation TO OtOpcUaAdmin;"); + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs index 2e5fe4637..fb8a8b17d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs @@ -864,15 +864,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations .HasDatabaseName("IX_Equipment_MachineCode"); b.HasIndex("SAPID") - .HasDatabaseName("IX_Equipment_SAPID") - .HasFilter("[SAPID] IS NOT NULL"); + .IsUnique() + .HasDatabaseName("UX_Equipment_SAPID") + .HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''"); b.HasIndex("UnsLineId") .HasDatabaseName("IX_Equipment_Line"); b.HasIndex("ZTag") - .HasDatabaseName("IX_Equipment_ZTag") - .HasFilter("[ZTag] IS NOT NULL"); + .IsUnique() + .HasDatabaseName("UX_Equipment_ZTag") + .HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''"); b.HasIndex("UnsLineId", "Name") .IsUnique() @@ -881,70 +883,6 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.ToTable("Equipment", (string)null); }); - modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ExternalIdReservation", b => - { - b.Property("ReservationId") - .ValueGeneratedOnAdd() - .HasColumnType("uniqueidentifier") - .HasDefaultValueSql("NEWSEQUENTIALID()"); - - b.Property("ClusterId") - .IsRequired() - .HasMaxLength(64) - .HasColumnType("nvarchar(64)"); - - b.Property("EquipmentUuid") - .HasColumnType("uniqueidentifier"); - - b.Property("FirstPublishedAt") - .ValueGeneratedOnAdd() - .HasColumnType("datetime2(3)") - .HasDefaultValueSql("SYSUTCDATETIME()"); - - b.Property("FirstPublishedBy") - .IsRequired() - .HasMaxLength(128) - .HasColumnType("nvarchar(128)"); - - b.Property("Kind") - .IsRequired() - .HasMaxLength(16) - .HasColumnType("nvarchar(16)"); - - b.Property("LastPublishedAt") - .ValueGeneratedOnAdd() - .HasColumnType("datetime2(3)") - .HasDefaultValueSql("SYSUTCDATETIME()"); - - b.Property("ReleaseReason") - .HasMaxLength(512) - .HasColumnType("nvarchar(512)"); - - b.Property("ReleasedAt") - .HasColumnType("datetime2(3)"); - - b.Property("ReleasedBy") - .HasMaxLength(128) - .HasColumnType("nvarchar(128)"); - - b.Property("Value") - .IsRequired() - .HasMaxLength(64) - .HasColumnType("nvarchar(64)"); - - b.HasKey("ReservationId"); - - b.HasIndex("EquipmentUuid") - .HasDatabaseName("IX_ExternalIdReservation_Equipment"); - - b.HasIndex("Kind", "Value") - .IsUnique() - .HasDatabaseName("UX_ExternalIdReservation_KindValue_Active") - .HasFilter("[ReleasedAt] IS NULL"); - - b.ToTable("ExternalIdReservation", (string)null); - }); - modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => { b.Property("Id") @@ -1362,6 +1300,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations .HasColumnType("rowversion"); b.Property("ScriptId") + .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); @@ -1376,10 +1315,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.HasKey("ScriptRowId"); - b.HasIndex("ScriptId") - .IsUnique() - .HasDatabaseName("UX_Script_LogicalId") - .HasFilter("[ScriptId] IS NOT NULL"); + b.HasAlternateKey("ScriptId") + .HasName("UX_Script_LogicalId"); b.HasIndex("SourceHash") .HasDatabaseName("IX_Script_SourceHash"); @@ -1991,6 +1928,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations .IsRequired(); }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("PredicateScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_ScriptedAlarm_Script"); + }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => { b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") @@ -2002,6 +1950,17 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.Navigation("Cluster"); }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("ScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_VirtualTag_Script"); + }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => { b.Navigation("Credentials"); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs index c0ccccd8b..40c572d87 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs @@ -50,8 +50,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions ApiKeys => Set(); /// Gets the DbSet of configuration audit logs. public DbSet ConfigAuditLogs => Set(); - /// Gets the DbSet of external ID reservations. - public DbSet ExternalIdReservations => Set(); /// Gets the DbSet of LDAP group role mappings. public DbSet LdapGroupRoleMappings => Set(); /// Gets the DbSet of scripts. @@ -104,7 +102,6 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.EquipmentId).IsUnique().HasDatabaseName("UX_Equipment_LogicalId"); e.HasIndex(x => new { x.UnsLineId, x.Name }).IsUnique().HasDatabaseName("UX_Equipment_LinePath"); e.HasIndex(x => x.EquipmentUuid).IsUnique().HasDatabaseName("UX_Equipment_Uuid"); - e.HasIndex(x => x.ZTag).HasFilter("[ZTag] IS NOT NULL").HasDatabaseName("IX_Equipment_ZTag"); - e.HasIndex(x => x.SAPID).HasFilter("[SAPID] IS NOT NULL").HasDatabaseName("IX_Equipment_SAPID"); + // lmxopcua#1049 (#998 C-3 follow-up): ZTag and SAPID are unique fleet-wide. The deploy gate + // (DraftValidator.ValidateEquipmentExternalIdUniqueness, trimmed + case-insensitive, blank = none) stays + // the authority that names every duplicate; these filtered UNIQUE indexes are the storage backstop, so a + // concurrent save or a hand edit cannot persist a second claim. The filter matches the gate's "blank + // means no identifier" (SQL Server compares '' and ' ' equal, so both are exempt); the column + // collation is case-insensitive, as the gate is. ExternalIdReservation is retired (same issue). + e.HasIndex(x => x.ZTag).IsUnique() + .HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''").HasDatabaseName("UX_Equipment_ZTag"); + e.HasIndex(x => x.SAPID).IsUnique() + .HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''").HasDatabaseName("UX_Equipment_SAPID"); e.HasIndex(x => x.MachineCode).HasDatabaseName("IX_Equipment_MachineCode"); }); } @@ -612,34 +617,11 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions(e => - { - e.ToTable("ExternalIdReservation"); - e.HasKey(x => x.ReservationId); - e.Property(x => x.ReservationId).HasDefaultValueSql("NEWSEQUENTIALID()"); - e.Property(x => x.Kind).HasConversion().HasMaxLength(16); - e.Property(x => x.Value).HasMaxLength(64); - e.Property(x => x.ClusterId).HasMaxLength(64); - e.Property(x => x.FirstPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()"); - e.Property(x => x.FirstPublishedBy).HasMaxLength(128); - e.Property(x => x.LastPublishedAt).HasColumnType("datetime2(3)").HasDefaultValueSql("SYSUTCDATETIME()"); - e.Property(x => x.ReleasedAt).HasColumnType("datetime2(3)"); - e.Property(x => x.ReleasedBy).HasMaxLength(128); - e.Property(x => x.ReleaseReason).HasMaxLength(512); - - // Active reservations unique per (Kind, Value) — filtered index lets released rows coexist with a new reservation of the same value. - // The UX_ filtered index covers active-reservation lookups; history queries over released rows - // fall back to the table scan (released rows are rare + small). No separate non-unique (Kind, Value) - // index is declared because EF Core merges duplicate column sets into a single index, which would - // clobber the filtered-unique name. - e.HasIndex(x => new { x.Kind, x.Value }).IsUnique() - .HasFilter("[ReleasedAt] IS NULL") - .HasDatabaseName("UX_ExternalIdReservation_KindValue_Active"); - e.HasIndex(x => x.EquipmentUuid).HasDatabaseName("IX_ExternalIdReservation_Equipment"); - }); - } + // ConfigureExternalIdReservation is GONE (lmxopcua#1049). The ledger's only writer was sp_PublishGeneration, + // retired with the generation model, so the table stayed empty and the reservation pre-flight could not fire. + // Fleet-wide ZTag / SAPID uniqueness is the deploy gate's DraftValidator rule plus the filtered unique indexes + // on Equipment (ConfigureEquipment). Migration ScriptForeignKeysAndExternalIdUniqueness drops the table and + // sp_ReleaseExternalIdReservation, refusing (THROW) while any row exists so no history is silently deleted. // ConfigureDriverHostStatus is GONE. The DriverHostStatus table held per-host // connectivity that a publisher hosted service was supposed to upsert from each driver node. That @@ -729,7 +711,10 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.Language).HasMaxLength(16); e.Property(x => x.RowVersion).IsRowVersion(); - e.HasIndex(x => x.ScriptId).IsUnique().HasDatabaseName("UX_Script_LogicalId"); + // The logical id is the principal key of VirtualTag.ScriptId / ScriptedAlarm.PredicateScriptId + // (lmxopcua#1040). An alternate key is a unique constraint, so it replaces the former unique index of + // the same name instead of sitting beside it. + e.HasAlternateKey(x => x.ScriptId).HasName("UX_Script_LogicalId"); e.HasIndex(x => x.SourceHash).HasDatabaseName("IX_Script_SourceHash"); }); } @@ -757,6 +742,15 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions x.VirtualTagId).IsUnique().HasDatabaseName("UX_VirtualTag_LogicalId"); e.HasIndex(x => new { x.EquipmentId, x.Name }).IsUnique().HasDatabaseName("UX_VirtualTag_EquipmentPath"); e.HasIndex(x => x.ScriptId).HasDatabaseName("IX_VirtualTag_Script"); + + // lmxopcua#1040 (#978 C-2 follow-up): a real FK. The deploy gate's VirtualTagScriptNotFound rule and the + // /scripts in-use delete guard still name the problem; this makes the database refuse it too (a delete + // racing a new reference, a hand edit). Restrict: deleting an in-use script is an error, never a cascade. + e.HasOne