diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
index 77e7c495..8bb7b77f 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
@@ -323,6 +323,14 @@ public interface ITemplateEngineRepository
/// The site's instances, shallow and untracked.
Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
+ ///
+ /// MGT-5: every instance's (Id, UniqueName) — the name index bundle export resolves
+ /// --instances against, instead of loading every instance with its child collections.
+ ///
+ /// Cancellation token.
+ /// One (Id, UniqueName) pair per instance.
+ Task> GetInstanceNamesAsync(CancellationToken cancellationToken = default);
+
///
/// TPL-4: whether a template other than named
/// (case-insensitively) already sits in
diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
index 8658168d..344bfdf4 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
@@ -553,6 +553,16 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.ToListAsync(cancellationToken);
}
+ ///
+ public async Task> GetInstanceNamesAsync(CancellationToken cancellationToken = default)
+ {
+ var rows = await _context.Instances
+ .AsNoTracking()
+ .Select(i => new { i.Id, i.UniqueName })
+ .ToListAsync(cancellationToken);
+ return rows.Select(r => (r.Id, r.UniqueName)).ToList();
+ }
+
///
public async Task TemplateNameExistsInFolderAsync(
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default)
diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs
index 923e6e47..040492cf 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs
@@ -4380,7 +4380,10 @@ public class ManagementActor : ReceiveActor
var inboundRepo = sp.GetRequiredService();
var siteRepo = sp.GetRequiredService();
- var templates = await templateRepo.GetAllTemplatesAsync();
+ // MGT-5: names resolve against narrow (Id, Name) projections — the exporter loads the
+ // selected rows itself, so the full tracked template graph and every instance with its
+ // child collections were materialised here only to map names to ids.
+ var templates = await templateRepo.GetTemplateStubsAsync();
var sharedScripts = await templateRepo.GetAllSharedScriptsAsync();
var externalSystems = await externalRepo.GetAllExternalSystemsAsync();
var dbConnections = await externalRepo.GetAllDatabaseConnectionsAsync();
@@ -4393,7 +4396,7 @@ public class ManagementActor : ReceiveActor
// Site/instance-scoped selection. Sites match on SiteIdentifier
// (preferred) or Name; instances match on UniqueName.
var sites = await siteRepo.GetAllSitesAsync();
- var instances = await templateRepo.GetAllInstancesAsync();
+ var instances = await templateRepo.GetInstanceNamesAsync();
int[] ResolveIds(IReadOnlyList all, IReadOnlyList? names,
Func getName, Func getId, string entityType)
diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.Derived.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.Derived.cs
index 210a9d71..ff8ee890 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.Derived.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.Derived.cs
@@ -207,8 +207,28 @@ public sealed partial class BundleImporter
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
var service = new TemplateService(_templateRepo, _auditService);
+ // TRN-11: every owner/base root name was looked up with its own
+ // `t.Name.ToLower() == lower` query (unindexable) — twice per derived template. The
+ // (Id, Name, IsDerived) projection of the whole table is loaded ONCE into a
+ // case-insensitive index instead (narrow: no members, no script bodies). This loop
+ // only ever creates or deletes DERIVED templates, so a hit on a base row is always
+ // current; a name with no base row in the index falls back to the live query, so the
+ // derived-only / not-found diagnostics still see what earlier rows wrote.
+ Dictionary>? templateRowsByName = null;
async Task> Named(string name)
{
+ if (templateRowsByName is null)
+ {
+ var all = await _dbContext.Templates.AsNoTracking()
+ .Select(t => new TemplateRow(t.Id, t.Name, t.IsDerived))
+ .ToListAsync(ct).ConfigureAwait(false);
+ templateRowsByName = all
+ .GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
+ .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
+ }
+ if (templateRowsByName.TryGetValue(name, out var cached) && cached.Any(r => !r.IsDerived))
+ return cached;
+
var lower = name.ToLower();
return await _dbContext.Templates.AsNoTracking()
.Where(t => t.Name.ToLower() == lower)
diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
index 80256d36..2c1f5c97 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
@@ -5369,6 +5369,8 @@ public sealed partial class BundleImporter : IBundleImporter
}
}
+ // TRN-11: one connection read per target site, not one per referencing row.
+ var targetConnNamesBySiteId = new Dictionary>();
foreach (var (site, name) in referencedConnections)
{
if (bundleConnectionRefs.Contains((site, name))) continue; // carried → creatable
@@ -5379,8 +5381,13 @@ public sealed partial class BundleImporter : IBundleImporter
&& mapping.TargetConnectionName is { Length: > 0 } tn
? tn
: name;
- var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
- if (!conns.Any(c => string.Equals(c.Name, targetName, StringComparison.Ordinal)))
+ if (!targetConnNamesBySiteId.TryGetValue(targetSite.Id, out var connNames))
+ {
+ var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
+ connNames = new HashSet(conns.Select(c => c.Name), StringComparer.Ordinal);
+ targetConnNamesBySiteId[targetSite.Id] = connNames;
+ }
+ if (!connNames.Contains(targetName))
{
errors.Add(
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs
index a754a4f9..a24ab5e1 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs
@@ -4062,14 +4062,15 @@ public class ManagementActorTests : TestKit, IDisposable
// The repository fan-out HandleExportBundle does at the top of its body.
// Tests that only exercise role gating still need these resolved.
- _templateRepo.GetAllTemplatesAsync(Arg.Any())
- .Returns(new List());
+ // MGT-5: template and instance names resolve against narrow projections.
+ _templateRepo.GetTemplateStubsAsync(Arg.Any())
+ .Returns(new List());
_templateRepo.GetAllSharedScriptsAsync(Arg.Any())
.Returns(new List());
// Export now also fans out to instances (template repo) and sites
// (site repo) for the site/instance-scoped selection.
- _templateRepo.GetAllInstancesAsync(Arg.Any())
- .Returns(new List());
+ _templateRepo.GetInstanceNamesAsync(Arg.Any())
+ .Returns(new List<(int, string)>());
var siteRepo = Substitute.For();
siteRepo.GetAllSitesAsync(Arg.Any())
@@ -4161,8 +4162,8 @@ public class ManagementActorTests : TestKit, IDisposable
// curated message must surface verbatim to the caller.
AddBundleSubstitutes();
// No templates in the repo; the export selection names one anyway.
- _templateRepo.GetAllTemplatesAsync(Arg.Any())
- .Returns(new List());
+ _templateRepo.GetTemplateStubsAsync(Arg.Any())
+ .Returns(new List());
var cmd = new ExportBundleCommand(
All: false,
@@ -4187,6 +4188,36 @@ public class ManagementActorTests : TestKit, IDisposable
Assert.Contains("DoesNotExist", response.Error);
}
+ ///
+ /// MGT-5 (WP6 6.7): export resolves names against the (Id, Name) projections and never
+ /// materialises the full template graph or every instance with its child collections.
+ ///
+ [Fact]
+ public void ExportBundleCommand_ResolvesNamesFromProjections_NotFullGraphs()
+ {
+ var (exporter, _) = AddBundleSubstitutes();
+ _templateRepo.GetTemplateStubsAsync(Arg.Any())
+ .Returns(new List { new(7, "PumpBase", null, null, false, null) });
+ Commons.Types.Transport.ExportSelection? captured = null;
+ exporter.ExportAsync(
+ Arg.Do(s => captured = s),
+ Arg.Any(), Arg.Any(), Arg.Any(),
+ Arg.Any())
+ .Returns(_ => Task.FromResult(new MemoryStream(new byte[] { 1 })));
+
+ var cmd = new ExportBundleCommand(
+ All: false, TemplateNames: new[] { "PumpBase" }, SharedScriptNames: null,
+ ExternalSystemNames: null, DatabaseConnectionNames: null,
+ NotificationListNames: null, SmtpConfigurationNames: null, ApiMethodNames: null,
+ IncludeDependencies: false, Passphrase: null, SourceEnvironment: "test-env");
+ CreateActor().Tell(Envelope(cmd, "Designer"));
+
+ ExpectMsg(TimeSpan.FromSeconds(5));
+ Assert.Equal(new[] { 7 }, captured!.TemplateIds);
+ _templateRepo.DidNotReceive().GetAllTemplatesAsync(Arg.Any());
+ _templateRepo.DidNotReceive().GetAllInstancesAsync(Arg.Any());
+ }
+
/// Verifies that export bundle command, when with site and instance names, resolves to ids.
[Fact]
public void ExportBundleCommand_WithSiteAndInstanceNames_ResolvesToIds()
@@ -4204,12 +4235,8 @@ public class ManagementActorTests : TestKit, IDisposable
new("North Plant", "NORTH-01") { Id = 11 },
new("East Plant", "EAST-02") { Id = 22 },
});
- _templateRepo.GetAllInstancesAsync(Arg.Any())
- .Returns(new List
- {
- new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
- new("NORTH-01.Pump2") { Id = 102, SiteId = 11, TemplateId = 1 },
- });
+ _templateRepo.GetInstanceNamesAsync(Arg.Any())
+ .Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (102, "NORTH-01.Pump2") });
Commons.Types.Transport.ExportSelection? captured = null;
exporter.ExportAsync(
@@ -4255,12 +4282,8 @@ public class ManagementActorTests : TestKit, IDisposable
new("North Plant", "NORTH-01") { Id = 11 },
new("East Plant", "EAST-02") { Id = 22 },
});
- _templateRepo.GetAllInstancesAsync(Arg.Any())
- .Returns(new List
- {
- new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
- new("EAST-02.Pump9") { Id = 909, SiteId = 22, TemplateId = 1 },
- });
+ _templateRepo.GetInstanceNamesAsync(Arg.Any())
+ .Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (909, "EAST-02.Pump9") });
Commons.Types.Transport.ExportSelection? captured = null;
exporter.ExportAsync(