diff --git a/api/src/org/labkey/api/dataiterator/AttachmentDataIterator.java b/api/src/org/labkey/api/dataiterator/AttachmentDataIterator.java index 7552da3fe01..ed32db06929 100644 --- a/api/src/org/labkey/api/dataiterator/AttachmentDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/AttachmentDataIterator.java @@ -131,6 +131,9 @@ public boolean next() throws BatchValidationException continue; } + // Archive files are named by position among same-named values, so every row must take its slot + String archiveName = null == attachmentDir ? null : p.uniquifier.uniquify(str); + if (str.equals(oldAttachmentValue)) // no change continue; @@ -144,7 +147,7 @@ public boolean next() throws BatchValidationException } filename = str; - InputStream aIS = attachmentDir.getDir(p.domainProperty.getName()).getInputStream(p.uniquifier.uniquify(filename)); + InputStream aIS = attachmentDir.getDir(p.domainProperty.getName()).getInputStream(archiveName); if (aIS == null) { errors.addRowError(new ValidationException("Could not find referenced file " + filename, p.domainProperty.getName())); diff --git a/experiment/src/org/labkey/experiment/ExperimentModule.java b/experiment/src/org/labkey/experiment/ExperimentModule.java index 1e1780ba5e7..84979d24407 100644 --- a/experiment/src/org/labkey/experiment/ExperimentModule.java +++ b/experiment/src/org/labkey/experiment/ExperimentModule.java @@ -167,6 +167,7 @@ import org.labkey.experiment.lineage.LineagePerfTest; import org.labkey.experiment.pipeline.ExperimentPipelineProvider; import org.labkey.experiment.pipeline.XarTestPipelineJob; +import org.labkey.experiment.samples.DataClassAttachmentExportImportTestCase; import org.labkey.experiment.samples.DataClassFolderImporter; import org.labkey.experiment.samples.DataClassFolderWriter; import org.labkey.experiment.samples.SampleStatusFolderImporter; @@ -1122,6 +1123,7 @@ public Collection getSummary(Container c) return Set.of( EdgeDiagnosticsTestCase.class, ExperimentController.ContainerScopingTestCase.class, + DataClassAttachmentExportImportTestCase.class, DataColorTable.TestCase.class, DataMapDiffColumnTestCase.class, DomainImpl.TestCase.class, diff --git a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java index 96d6740bc9a..54cd67bc24b 100644 --- a/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java +++ b/experiment/src/org/labkey/experiment/samples/AbstractExpFolderWriter.java @@ -242,7 +242,7 @@ protected boolean isExportable(ColumnInfo col) return col.getPHI().isExportLevelAllowed(_exportPhiLevel); } - protected void writeAttachments(Container c, TableInfo tinfo, VirtualFile dir) throws SQLException, IOException + protected void writeAttachments(Container c, TableInfo tinfo, SimpleFilter filter, Sort sort, VirtualFile dir) throws SQLException, IOException { List attachmentCols = new ArrayList<>(); for (DomainProperty prop : tinfo.getDomain().getProperties()) @@ -268,7 +268,8 @@ protected void writeAttachments(Container c, TableInfo tinfo, VirtualFile dir) t for (ColumnInfo col : attachmentCols) uniquifiers.put(col.getName(), new FileNameUniquifier()); - try (ResultSet rs = QueryService.get().getSelectBuilder(tinfo).columns(selectColumns).select()) + // Import pairs uniquified file names to TSV rows by position, so filter and sort must match the TSV's + try (ResultSet rs = QueryService.get().getSelectBuilder(tinfo).columns(selectColumns).filter(filter).sort(sort).select()) { while (rs.next()) { diff --git a/experiment/src/org/labkey/experiment/samples/DataClassAttachmentExportImportTestCase.java b/experiment/src/org/labkey/experiment/samples/DataClassAttachmentExportImportTestCase.java new file mode 100644 index 00000000000..ca9c4e071bb --- /dev/null +++ b/experiment/src/org/labkey/experiment/samples/DataClassAttachmentExportImportTestCase.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.experiment.samples; + +import org.apache.logging.log4j.Logger; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.labkey.api.admin.FolderArchiveDataTypes; +import org.labkey.api.admin.FolderExportContext; +import org.labkey.api.admin.FolderImportContext; +import org.labkey.api.admin.StaticLoggerGetter; +import org.labkey.api.attachments.AttachmentService; +import org.labkey.api.attachments.InputStreamAttachmentFile; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerManager; +import org.labkey.api.data.TableInfo; +import org.labkey.api.exp.Lsid; +import org.labkey.api.exp.PropertyType; +import org.labkey.api.exp.api.ExpData; +import org.labkey.api.exp.api.ExpDataClass; +import org.labkey.api.exp.api.ExperimentService; +import org.labkey.api.exp.query.ExpSchema; +import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; +import org.labkey.api.query.BatchValidationException; +import org.labkey.api.query.QueryService; +import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.UserSchema; +import org.labkey.api.security.User; +import org.labkey.api.test.TestTimeout; +import org.labkey.api.util.TestContext; +import org.labkey.api.util.logging.LogHelper; +import org.labkey.api.writer.MemoryVirtualFile; +import org.labkey.experiment.api.ExpDataClassAttachmentParent; +import org.labkey.experiment.api.ExperimentServiceImpl; +import org.labkey.folder.xml.FolderDocument; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static java.util.Collections.emptyList; + +// Export numbers duplicate attachment names in DB order but import resolves them in TSV (RowId) order +@TestTimeout(TestTimeout.DEFAULT * 5) +public class DataClassAttachmentExportImportTestCase extends Assert +{ + private static final Logger LOG = LogHelper.getLogger(DataClassAttachmentExportImportTestCase.class, "Data class attachment export/import test"); + + private static final String SOURCE_PROJECT = "DataClassAttachmentExportImportTest Source"; + private static final String TARGET_PROJECT = "DataClassAttachmentExportImportTest Target"; + private static final String DATA_CLASS_NAME = "AttachmentRoundTrip"; + private static final String ATTACHMENT_FIELD = "File"; + private static final String NOTES_FIELD = "Notes"; + private static final String FILE_NAME = "image.png"; + + private static User _user; + private static Container _source; + private static Container _target; + private static ExpDataClass _dataClass; + + @BeforeClass + public static void setup() throws Exception + { + _user = TestContext.get().getUser(); + + deleteTestContainers(); + _source = ContainerManager.ensureContainer(SOURCE_PROJECT, _user); + _target = ContainerManager.ensureContainer(TARGET_PROJECT, _user); + + List props = List.of( + new GWTPropertyDescriptor(ATTACHMENT_FIELD, PropertyType.ATTACHMENT.getTypeUri()), + new GWTPropertyDescriptor(NOTES_FIELD, PropertyType.STRING.getTypeUri()) + ); + _dataClass = ExperimentServiceImpl.get().createDataClass(_source, _user, DATA_CLASS_NAME, null, props, emptyList(), null, null); + } + + @AfterClass + public static void cleanup() + { + _dataClass = null; + _source = null; + _target = null; + _user = null; + + deleteTestContainers(); + } + + private static void deleteTestContainers() + { + for (String path : List.of(SOURCE_PROJECT, TARGET_PROJECT)) + { + Container project = ContainerManager.getForPath(path); + if (null != project) + ContainerManager.deleteAll(project, TestContext.get().getUser()); + } + } + + private static QueryUpdateService sourceUpdateService() + { + UserSchema schema = QueryService.get().getUserSchema(_user, _source, ExpSchema.SCHEMA_EXP_DATA); + assertNotNull("expected the exp.data schema", schema); + TableInfo table = schema.getTable(DATA_CLASS_NAME); + assertNotNull("expected the data class table to resolve", table); + QueryUpdateService qus = table.getUpdateService(); + assertNotNull("expected an update service", qus); + return qus; + } + + private static void insertRow(String name, String content) throws Exception + { + Map row = new CaseInsensitiveHashMap<>(); + row.put("Name", name); + row.put(ATTACHMENT_FIELD, new InputStreamAttachmentFile(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), FILE_NAME)); + + BatchValidationException errors = new BatchValidationException(); + sourceUpdateService().insertRows(_user, _source, List.of(row), errors, null, null); + if (errors.hasErrors()) + throw errors; + } + + private static ExpData getData(ExpDataClass dataClass, String name) + { + ExpData data = ExperimentService.get().getExpData(dataClass, name); + assertNotNull("expected data '" + name + "' in " + dataClass.getContainer().getPath(), data); + return data; + } + + private static String attachmentContent(ExpDataClass dataClass, Container c, String name) throws Exception + { + ExpData data = getData(dataClass, name); + + try (InputStream is = AttachmentService.get().getInputStream(new ExpDataClassAttachmentParent(c, Lsid.parse(data.getLSID())), FILE_NAME)) + { + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Test + public void duplicateAttachmentNamesSurviveExportImport() throws Exception + { + insertRow("First", "first-content"); + insertRow("Second", "second-content"); + + // Postgres writes the updated tuple after Second, so an unsorted select differs from the TSV's RowId order + Map update = new CaseInsensitiveHashMap<>(); + update.put("RowId", getData(_dataClass, "First").getRowId()); + update.put(NOTES_FIELD, "updated"); + BatchValidationException errors = new BatchValidationException(); + sourceUpdateService().updateRows(_user, _source, List.of(update), null, errors, null, null); + if (errors.hasErrors()) + throw errors; + + assertEquals("source First attachment", "first-content", attachmentContent(_dataClass, _source, "First")); + assertEquals("source Second attachment", "second-content", attachmentContent(_dataClass, _source, "Second")); + + MemoryVirtualFile root = new MemoryVirtualFile(); + FolderExportContext exportCtx = new FolderExportContext(_user, _source, Set.of(FolderArchiveDataTypes.DATA_CLASS_DESIGNS, FolderArchiveDataTypes.DATA_CLASS_DATA), "new", new StaticLoggerGetter(LOG)); + DataClassFolderWriter writer = new DataClassFolderWriter.DataClassDataWriter(); + writer.initialize(exportCtx); + writer.write(_source, exportCtx, root); + + FolderDocument folderDoc = FolderDocument.Factory.newInstance(); + folderDoc.addNewFolder(); + FolderImportContext importCtx = new FolderImportContext(_user, _target, folderDoc, null, new StaticLoggerGetter(LOG), root); + DataClassFolderImporter.get().process(null, importCtx, root); + + ExpDataClass imported = ExperimentService.get().getDataClass(_target, DATA_CLASS_NAME); + assertNotNull("expected the data class to be imported", imported); + + assertEquals("imported First attachment", "first-content", attachmentContent(imported, _target, "First")); + assertEquals("imported Second attachment", "second-content", attachmentContent(imported, _target, "Second")); + } +} diff --git a/experiment/src/org/labkey/experiment/samples/DataClassFolderWriter.java b/experiment/src/org/labkey/experiment/samples/DataClassFolderWriter.java index 0449810a26b..243fa3ca461 100644 --- a/experiment/src/org/labkey/experiment/samples/DataClassFolderWriter.java +++ b/experiment/src/org/labkey/experiment/samples/DataClassFolderWriter.java @@ -151,9 +151,10 @@ private void writeDataClassDataFiles(Set dataClasses, FolderExport SimpleFilter filter = SimpleFilter.createContainerFilter(ctx.getContainer()); // Sort by RowId so data get exported (and then imported) in the same order as created (default is the reverse order) - writeTsv(tinfo, columns, filter, new Sort(FieldKey.fromParts("RowId")), dir, DATA_CLASS_PREFIX + dataClass.getName()); + Sort sort = new Sort(FieldKey.fromParts("RowId")); + writeTsv(tinfo, columns, filter, sort, dir, DATA_CLASS_PREFIX + dataClass.getName()); - writeAttachments(ctx.getContainer(), tinfo, dir); + writeAttachments(ctx.getContainer(), tinfo, filter, sort, dir); } } } diff --git a/list/src/org/labkey/list/ListModule.java b/list/src/org/labkey/list/ListModule.java index 21e4d7d4b51..9b383474088 100644 --- a/list/src/org/labkey/list/ListModule.java +++ b/list/src/org/labkey/list/ListModule.java @@ -53,6 +53,8 @@ import org.labkey.list.model.FolderListImporter; import org.labkey.list.model.FolderListWriter; import org.labkey.list.model.IntegerListDomainKind; +import org.labkey.list.model.ListAttachmentExportImportTestCase; +import org.labkey.list.model.ListAttachmentMergeImportTestCase; import org.labkey.list.model.ListAuditProvider; import org.labkey.list.model.ListDef; import org.labkey.list.model.ListManager; @@ -239,6 +241,8 @@ public Collection getProvisionedSchemaNames() public @NotNull Set> getIntegrationTests() { return Set.of( + ListAttachmentExportImportTestCase.class, + ListAttachmentMergeImportTestCase.class, ListQueryUpdateService.AuditBatchTestCase.class, ListQueryUpdateService.GetRowsTestCase.class ); diff --git a/list/src/org/labkey/list/model/ListAttachmentExportImportTestCase.java b/list/src/org/labkey/list/model/ListAttachmentExportImportTestCase.java new file mode 100644 index 00000000000..d460a0af7dc --- /dev/null +++ b/list/src/org/labkey/list/model/ListAttachmentExportImportTestCase.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.list.model; + +import org.apache.logging.log4j.Logger; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.labkey.api.admin.FolderArchiveDataTypes; +import org.labkey.api.admin.FolderExportContext; +import org.labkey.api.admin.StaticLoggerGetter; +import org.labkey.api.attachments.AttachmentService; +import org.labkey.api.attachments.InputStreamAttachmentFile; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerManager; +import org.labkey.api.data.TableInfo; +import org.labkey.api.exp.PropertyType; +import org.labkey.api.exp.list.ListDefinition; +import org.labkey.api.exp.list.ListItem; +import org.labkey.api.exp.list.ListService; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.exp.property.DomainProperty; +import org.labkey.api.exp.property.PropertyService; +import org.labkey.api.query.BatchValidationException; +import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.security.User; +import org.labkey.api.test.TestTimeout; +import org.labkey.api.util.TestContext; +import org.labkey.api.util.logging.LogHelper; +import org.labkey.api.writer.MemoryVirtualFile; +import org.labkey.list.view.ListItemAttachmentParent; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +// Export numbers duplicate attachment names in DB order but import resolves them in PK order +@TestTimeout(TestTimeout.DEFAULT * 5) +public class ListAttachmentExportImportTestCase extends Assert +{ + private static final Logger LOG = LogHelper.getLogger(ListAttachmentExportImportTestCase.class, "List attachment export/import test"); + + private static final String SOURCE_PROJECT = "ListAttachmentExportImportTest Source"; + private static final String TARGET_PROJECT = "ListAttachmentExportImportTest Target"; + private static final String LIST_NAME = "AttachmentRoundTrip"; + private static final String KEY_NAME = "Name"; + private static final String ATTACHMENT_FIELD = "File"; + private static final String FILE_NAME = "image.png"; + + private static User _user; + private static Container _source; + private static Container _target; + private static ListDefinition _list; + + @BeforeClass + public static void setup() throws Exception + { + _user = TestContext.get().getUser(); + + deleteTestContainers(); + _source = ContainerManager.ensureContainer(SOURCE_PROJECT, _user); + _target = ContainerManager.ensureContainer(TARGET_PROJECT, _user); + + _list = ListService.get().createList(_source, LIST_NAME, ListDefinition.KeyType.Varchar); + _list.setKeyName(KEY_NAME); + + Domain domain = _list.getDomain(); + assertNotNull("expected the list domain", domain); + DomainProperty dp = domain.addProperty(); + dp.setName(ATTACHMENT_FIELD); + dp.setType(PropertyService.get().getType(_source, PropertyType.ATTACHMENT.getXmlName())); + dp.setPropertyURI(ListDomainKind.createPropertyURI(LIST_NAME, ATTACHMENT_FIELD, _source, _list.getKeyType()).toString()); + _list.save(_user); + } + + @AfterClass + public static void cleanup() + { + _list = null; + _source = null; + _target = null; + _user = null; + + deleteTestContainers(); + } + + private static void deleteTestContainers() + { + for (String path : List.of(SOURCE_PROJECT, TARGET_PROJECT)) + { + Container project = ContainerManager.getForPath(path); + if (null != project) + ContainerManager.deleteAll(project, TestContext.get().getUser()); + } + } + + private static void insertRow(String key, String content) throws Exception + { + Map row = new CaseInsensitiveHashMap<>(); + row.put(KEY_NAME, key); + row.put(ATTACHMENT_FIELD, new InputStreamAttachmentFile(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), FILE_NAME)); + + BatchValidationException errors = new BatchValidationException(); + TableInfo table = _list.getTable(_user); + assertNotNull("expected the list table to resolve", table); + QueryUpdateService qus = table.getUpdateService(); + assertNotNull("expected an update service", qus); + qus.insertRows(_user, _source, List.of(row), errors, null, null); + if (errors.hasErrors()) + throw errors.getLastRowError(); + } + + private static String attachmentContent(ListDefinition list, Container c, String key) throws Exception + { + ListItem item = list.getListItem(key, _user, c); + assertNotNull("expected list item '" + key + "' in " + c.getPath(), item); + + try (InputStream is = AttachmentService.get().getInputStream(new ListItemAttachmentParent(item.getEntityId(), c), FILE_NAME)) + { + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Test + public void duplicateAttachmentNamesSurviveExportImport() throws Exception + { + // Heap order Zeta, Alpha differs from PK order Alpha, Zeta + insertRow("Zeta", "zeta-content"); + insertRow("Alpha", "alpha-content"); + + assertEquals("source Alpha attachment", "alpha-content", attachmentContent(_list, _source, "Alpha")); + assertEquals("source Zeta attachment", "zeta-content", attachmentContent(_list, _source, "Zeta")); + + MemoryVirtualFile listsDir = new MemoryVirtualFile(); + FolderExportContext ctx = new FolderExportContext(_user, _source, Set.of(FolderArchiveDataTypes.LIST_DATA), "new", new StaticLoggerGetter(LOG)); + assertTrue("expected the list to be exported", new ListWriter().write(_source, _user, listsDir, ctx)); + + List errors = new LinkedList<>(); + new ListImporter().processMany(listsDir, _target, _user, errors, LOG); + assertEquals("import errors", List.of(), errors); + + ListDefinition imported = ListService.get().getList(_target, LIST_NAME); + assertNotNull("expected the list to be imported", imported); + + assertEquals("imported Alpha attachment", "alpha-content", attachmentContent(imported, _target, "Alpha")); + assertEquals("imported Zeta attachment", "zeta-content", attachmentContent(imported, _target, "Zeta")); + } +} diff --git a/list/src/org/labkey/list/model/ListAttachmentMergeImportTestCase.java b/list/src/org/labkey/list/model/ListAttachmentMergeImportTestCase.java new file mode 100644 index 00000000000..61700477243 --- /dev/null +++ b/list/src/org/labkey/list/model/ListAttachmentMergeImportTestCase.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.list.model; + +import org.apache.logging.log4j.Logger; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.labkey.api.admin.FolderArchiveDataTypes; +import org.labkey.api.admin.FolderExportContext; +import org.labkey.api.admin.StaticLoggerGetter; +import org.labkey.api.attachments.AttachmentService; +import org.labkey.api.attachments.InputStreamAttachmentFile; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerManager; +import org.labkey.api.data.TableInfo; +import org.labkey.api.exp.PropertyType; +import org.labkey.api.exp.list.ListDefinition; +import org.labkey.api.exp.list.ListItem; +import org.labkey.api.exp.list.ListService; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.exp.property.DomainProperty; +import org.labkey.api.exp.property.PropertyService; +import org.labkey.api.query.BatchValidationException; +import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.security.User; +import org.labkey.api.test.TestTimeout; +import org.labkey.api.util.TestContext; +import org.labkey.api.util.logging.LogHelper; +import org.labkey.api.writer.MemoryVirtualFile; +import org.labkey.list.view.ListItemAttachmentParent; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +// Merge import must consume a file-name slot for unchanged rows, or later rows read an earlier row's file +@TestTimeout(TestTimeout.DEFAULT * 5) +public class ListAttachmentMergeImportTestCase extends Assert +{ + private static final Logger LOG = LogHelper.getLogger(ListAttachmentMergeImportTestCase.class, "List attachment merge import test"); + + private static final String SOURCE_PROJECT = "ListAttachmentMergeImportTest Source"; + private static final String TARGET_PROJECT = "ListAttachmentMergeImportTest Target"; + private static final String LIST_NAME = "AttachmentMerge"; + private static final String KEY_NAME = "Name"; + private static final String ATTACHMENT_FIELD = "File"; + private static final String FILE_NAME = "image.png"; + + private static User _user; + private static Container _source; + private static Container _target; + private static ListDefinition _list; + + @BeforeClass + public static void setup() throws Exception + { + _user = TestContext.get().getUser(); + + deleteTestContainers(); + _source = ContainerManager.ensureContainer(SOURCE_PROJECT, _user); + _target = ContainerManager.ensureContainer(TARGET_PROJECT, _user); + + _list = ListService.get().createList(_source, LIST_NAME, ListDefinition.KeyType.Varchar); + _list.setKeyName(KEY_NAME); + + Domain domain = _list.getDomain(); + assertNotNull("expected the list domain", domain); + DomainProperty dp = domain.addProperty(); + dp.setName(ATTACHMENT_FIELD); + dp.setType(PropertyService.get().getType(_source, PropertyType.ATTACHMENT.getXmlName())); + dp.setPropertyURI(ListDomainKind.createPropertyURI(LIST_NAME, ATTACHMENT_FIELD, _source, _list.getKeyType()).toString()); + _list.save(_user); + } + + @AfterClass + public static void cleanup() + { + _list = null; + _source = null; + _target = null; + _user = null; + + deleteTestContainers(); + } + + private static void deleteTestContainers() + { + for (String path : List.of(SOURCE_PROJECT, TARGET_PROJECT)) + { + Container project = ContainerManager.getForPath(path); + if (null != project) + ContainerManager.deleteAll(project, TestContext.get().getUser()); + } + } + + private static QueryUpdateService updateService(ListDefinition list) + { + TableInfo table = list.getTable(_user); + assertNotNull("expected the list table to resolve", table); + QueryUpdateService qus = table.getUpdateService(); + assertNotNull("expected an update service", qus); + return qus; + } + + private static void insertRow(String key, String content) throws Exception + { + Map row = new CaseInsensitiveHashMap<>(); + row.put(KEY_NAME, key); + row.put(ATTACHMENT_FIELD, new InputStreamAttachmentFile(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), FILE_NAME)); + + BatchValidationException errors = new BatchValidationException(); + updateService(_list).insertRows(_user, _source, List.of(row), errors, null, null); + if (errors.hasErrors()) + throw errors.getLastRowError(); + } + + private static String attachmentContent(ListDefinition list, Container c, String key) throws Exception + { + ListItem item = list.getListItem(key, _user, c); + assertNotNull("expected list item '" + key + "' in " + c.getPath(), item); + + try (InputStream is = AttachmentService.get().getInputStream(new ListItemAttachmentParent(item.getEntityId(), c), FILE_NAME)) + { + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static void importArchive(MemoryVirtualFile listsDir, boolean merge) throws Exception + { + List errors = new LinkedList<>(); + new ListImporter(new ListImportContext(null, merge)).processMany(listsDir, _target, _user, errors, LOG); + assertEquals("import errors", List.of(), errors); + } + + @Test + public void mergeIntoNonEmptyTargetKeepsAttachmentsAligned() throws Exception + { + insertRow("Alpha", "alpha-content"); + insertRow("Beta", "beta-content"); + + MemoryVirtualFile listsDir = new MemoryVirtualFile(); + FolderExportContext ctx = new FolderExportContext(_user, _source, Set.of(FolderArchiveDataTypes.LIST_DATA), "new", new StaticLoggerGetter(LOG)); + assertTrue("expected the list to be exported", new ListWriter().write(_source, _user, listsDir, ctx)); + + importArchive(listsDir, false); + ListDefinition imported = ListService.get().getList(_target, LIST_NAME); + assertNotNull("expected the list to be imported", imported); + + // Alpha stays unchanged in the merge while Beta is re-inserted from the archive + updateService(imported).deleteRows(_user, _target, List.of(Map.of(KEY_NAME, "Beta")), null, null); + assertNull("expected Beta to be deleted", imported.getListItem("Beta", _user, _target)); + + importArchive(listsDir, true); + + assertEquals("merged Alpha attachment", "alpha-content", attachmentContent(imported, _target, "Alpha")); + assertEquals("merged Beta attachment", "beta-content", attachmentContent(imported, _target, "Beta")); + } +} diff --git a/list/src/org/labkey/list/model/ListWriter.java b/list/src/org/labkey/list/model/ListWriter.java index 7922b549879..4b50060b54e 100644 --- a/list/src/org/labkey/list/model/ListWriter.java +++ b/list/src/org/labkey/list/model/ListWriter.java @@ -16,6 +16,7 @@ package org.labkey.list.model; +import org.jetbrains.annotations.Nullable; import org.junit.Assert; import org.junit.Test; import org.labkey.api.admin.FolderArchiveDataTypes; @@ -189,7 +190,7 @@ private void writeLists(List> listsToExport, Virtua tsvWriter.write(out); } - writeAttachments(ti, def, c, listsDir, exportPhiLevel); + writeAttachments(ti, def, c, listsDir, exportPhiLevel, sort); } } } @@ -263,7 +264,7 @@ private void writeSettings(ListsDocument.Lists.List settings, ListDefinition def if (def.getFileAttachmentIndex()) settings.setFileAttachmentIndex(def.getFileAttachmentIndex()); } - private void writeAttachments(TableInfo ti, ListDefinition def, Container c, VirtualFile listsDir, PHI exportPhiLevel) throws SQLException, IOException + private void writeAttachments(TableInfo ti, ListDefinition def, Container c, VirtualFile listsDir, PHI exportPhiLevel, @Nullable Sort sort) throws SQLException, IOException { List attachmentColumns = new ArrayList<>(); @@ -292,7 +293,8 @@ private void writeAttachments(TableInfo ti, ListDefinition def, Container c, Vir List selectColumns = new ArrayList<>(attachmentColumns); selectColumns.addFirst(ti.getColumn("EntityId")); - try (ResultSet rs = QueryService.get().getSelectBuilder(ti).columns(selectColumns).select(false)) + // Import pairs uniquified file names to TSV rows by position, so this must match the TSV's row order + try (ResultSet rs = QueryService.get().getSelectBuilder(ti).columns(selectColumns).sort(sort).select(false)) { while (rs.next()) { @@ -312,9 +314,10 @@ private void writeAttachments(TableInfo ti, ListDefinition def, Container c, Vir String columnName = attachmentColumn.getName(); VirtualFile columnDir = listDir.getDir(columnName); - FileNameUniquifier uniquifier = uniquifiers.get(columnName); + // Take the slot even if the file is missing; import still counts this row + String archiveName = uniquifiers.get(columnName).uniquify(filename); - try (InputStream is = AttachmentService.get().getInputStream(listItemParent, filename); OutputStream os = columnDir.getOutputStream(uniquifier.uniquify(filename))) + try (InputStream is = AttachmentService.get().getInputStream(listItemParent, filename); OutputStream os = columnDir.getOutputStream(archiveName)) { FileUtil.copyData(is, os); }