From f590233e2562243c149f7eca693ca14420ccc7e9 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sat, 7 Nov 2026 07:43:07 -0800 Subject: [PATCH 1/7] Fix MERGE with trigger --- .../TriggerDataBuilderHelper.java | 5 +- .../labkey/experiment/ExperimentModule.java | 2 + .../experiment/api/SampleMergeTestCase.java | 146 ++++++++++++++++++ list/src/org/labkey/list/ListModule.java | 3 +- .../list/model/ListQueryUpdateService.java | 119 ++++++++++++++ 5 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java diff --git a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java index 1e5015e28a5..be07aaaa75e 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -149,7 +149,10 @@ public DataIterator getDataIterator(DataIteratorContext context) sharedKeys = expTable.getExistingRecordSharedKeyColumnNames(); } - di = LoggingDataIterator.wrap(new CoerceDataIterator(di, context, _target, !context.getInsertOption().updateOnly)); + // GH Issue 1048: null padding would make MERGE overwrite every column the input omitted + QueryUpdateService.InsertOption option = context.getInsertOption(); + boolean padMissingColumns = !option.updateOnly && (!option.mergeRows || option.replace); + di = LoggingDataIterator.wrap(new CoerceDataIterator(di, context, _target, padMissingColumns)); context.setWithLookupRemapping(false); // Skip existing records diff --git a/experiment/src/org/labkey/experiment/ExperimentModule.java b/experiment/src/org/labkey/experiment/ExperimentModule.java index 1e1780ba5e7..b09d8f7f4cd 100644 --- a/experiment/src/org/labkey/experiment/ExperimentModule.java +++ b/experiment/src/org/labkey/experiment/ExperimentModule.java @@ -137,6 +137,7 @@ import org.labkey.experiment.api.LineageTest; import org.labkey.experiment.api.LogDataType; import org.labkey.experiment.api.Protocol; +import org.labkey.experiment.api.SampleMergeTestCase; import org.labkey.experiment.api.SampleProvidedAmountAuditTestCase; import org.labkey.experiment.api.SampleTypeFilterSuggestionProvider; import org.labkey.experiment.api.SampleTypeServiceImpl; @@ -1140,6 +1141,7 @@ public Collection getSummary(Container c) LineageTest.class, OntologyManager.TestCase.class, PropertyServiceImpl.TestCase.class, + SampleMergeTestCase.class, SampleProvidedAmountAuditTestCase.class, SampleTypeFilterSuggestionProvider.TestCase.class, SampleTypeServiceImpl.TestCase.class, diff --git a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java new file mode 100644 index 00000000000..f73977d1430 --- /dev/null +++ b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java @@ -0,0 +1,146 @@ +/* + * 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.api; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.AbstractTableInfo; +import org.labkey.api.data.Container; +import org.labkey.api.data.SimpleFilter; +import org.labkey.api.data.TableInfo; +import org.labkey.api.data.TableSelector; +import org.labkey.api.data.triggers.Trigger; +import org.labkey.api.dataiterator.MapDataIterator; +import org.labkey.api.exp.api.ExpSampleType; +import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.query.SamplesSchema; +import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; +import org.labkey.api.query.BatchValidationException; +import org.labkey.api.query.FieldKey; +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.util.JunitUtil; +import org.labkey.api.util.TestContext; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** GH Issue 1048: MERGE must leave sample columns the input omits unchanged, with or without a trigger on the table. */ +public class SampleMergeTestCase extends Assert +{ + private static final String INT_FIELD = "A"; + private static final String TEXT_FIELD = "B"; + + private static Container _c; + private static User _user; + + @BeforeClass + public static void setUp() + { + JunitUtil.deleteTestContainer(); + _c = JunitUtil.getTestContainer(); + _user = TestContext.get().getUser(); + } + + @AfterClass + public static void tearDown() + { + JunitUtil.deleteTestContainer(); + } + + @Test + public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception + { + ExpSampleType st = createSampleType("MergeNoTrigger"); + insertSample(st); + mergeIntField(table(st, false)); + assertOmittedFieldKept(st); + } + + @Test + public void mergeWithTriggerKeepsOmittedColumns() throws Exception + { + ExpSampleType st = createSampleType("MergeTrigger"); + insertSample(st); + mergeIntField(table(st, true)); + assertOmittedFieldKept(st); + } + + private ExpSampleType createSampleType(String name) throws Exception + { + List props = List.of( + new GWTPropertyDescriptor("name", "string"), + new GWTPropertyDescriptor(INT_FIELD, "int"), + new GWTPropertyDescriptor(TEXT_FIELD, "string")); + return SampleTypeService.get().createSampleType(_c, _user, name, null, props, Collections.emptyList(), -1, -1, -1, -1, null); + } + + /** Cached tables are locked, so only one built for write accepts another trigger factory */ + private TableInfo table(ExpSampleType st, boolean withTrigger) + { + UserSchema schema = QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME); + assertNotNull(schema); + TableInfo table = schema.getTable(st.getName(), null, true, withTrigger); + assertNotNull(table); + if (withTrigger) + { + AbstractTableInfo writable = (AbstractTableInfo) table; + writable.addTriggerFactory((_, _, _) -> List.of(new Trigger() {})); + writable.resetTriggers(_c); + assertTrue(writable.hasTriggers(_c)); + } + + return table; + } + + private QueryUpdateService updateService(TableInfo table) + { + QueryUpdateService qus = table.getUpdateService(); + assertNotNull(qus); + return qus; + } + + private void insertSample(ExpSampleType st) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + updateService(table(st, false)).insertRows(_user, _c, List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); + if (errors.hasErrors()) + throw errors; + } + + private void mergeIntField(TableInfo table) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + int count = updateService(table).mergeRows(_user, _c, MapDataIterator.of(List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 2))), errors, null, null); + if (errors.hasErrors()) + throw errors; + assertEquals(1, count); + } + + private void assertOmittedFieldKept(ExpSampleType st) + { + Map row = new TableSelector(table(st, false), new SimpleFilter(FieldKey.fromParts("name"), "S-1"), null).getMap(); + assertNotNull(row); + assertEquals(2, ((Number) row.get(INT_FIELD)).intValue()); + assertEquals("MERGE nulled a column it was not given", "x", row.get(TEXT_FIELD)); + } +} diff --git a/list/src/org/labkey/list/ListModule.java b/list/src/org/labkey/list/ListModule.java index 21e4d7d4b51..e7c51617a68 100644 --- a/list/src/org/labkey/list/ListModule.java +++ b/list/src/org/labkey/list/ListModule.java @@ -240,7 +240,8 @@ public Collection getProvisionedSchemaNames() { return Set.of( ListQueryUpdateService.AuditBatchTestCase.class, - ListQueryUpdateService.GetRowsTestCase.class + ListQueryUpdateService.GetRowsTestCase.class, + ListQueryUpdateService.MergeTestCase.class ); } } diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index 7875870c8c6..4766d7af049 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -35,6 +35,7 @@ import org.labkey.api.data.BatchSize; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.CompareType; +import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; import org.labkey.api.data.ContainerManager; @@ -45,10 +46,12 @@ import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; +import org.labkey.api.data.triggers.Trigger; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; import org.labkey.api.dataiterator.DetailedAuditLogDataIterator; import org.labkey.api.dataiterator.ImportProgress; +import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.exp.ObjectProperty; import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.list.ListDefinition; @@ -1244,4 +1247,120 @@ public void matchesGetRowInKeyOrder() throws Exception } } } + /** GH Issue 1048: MERGE must leave columns the input omits unchanged, with or without a trigger on the table. */ + @TestTimeout(TestTimeout.DEFAULT * 5) + public static class MergeTestCase extends Assert + { + private static final String PROJECT_NAME = "ListMergeTest Project"; + private static final String LIST_NAME = "Merge list"; + private static final String KEY_NAME = "Key"; + private static final String INT_FIELD = "A"; + private static final String TEXT_FIELD = "B"; + + private static User _user; + private static Container _container; + private static ListDefinition _list; + + @BeforeClass + public static void setup() throws Exception + { + _user = TestContext.get().getUser(); + + deleteTestContainer(); + _container = ContainerManager.ensureContainer(PROJECT_NAME, _user); + + _list = ListService.get().createList(_container, LIST_NAME, ListDefinition.KeyType.Integer); + _list.setKeyName(KEY_NAME); + addField(INT_FIELD, PropertyType.INTEGER); + addField(TEXT_FIELD, PropertyType.STRING); + _list.save(_user); + } + + private static void addField(String name, PropertyType type) + { + Domain domain = _list.getDomain(); + assertNotNull(domain); + DomainProperty dp = domain.addProperty(); + dp.setName(name); + dp.setType(PropertyService.get().getType(_container, type.getXmlName())); + dp.setPropertyURI(ListDomainKind.createPropertyURI(LIST_NAME, name, _container, _list.getKeyType()).toString()); + } + + @AfterClass + public static void cleanup() + { + _list = null; + _container = null; + _user = null; + + deleteTestContainer(); + } + + private static void deleteTestContainer() + { + Container project = ContainerManager.getForPath(PROJECT_NAME); + + if (null != project) + ContainerManager.deleteAll(project, TestContext.get().getUser()); + } + + /** Cached tables are locked, so only one built for write accepts another trigger factory */ + private TableInfo tableWithTrigger() + { + AbstractTableInfo table = (AbstractTableInfo) new ListQuerySchema(_user, _container).getTable(LIST_NAME, null, true, true); + table.addTriggerFactory((_, _, _) -> List.of(new Trigger() {})); + table.resetTriggers(_container); + assertTrue(table.hasTriggers(_container)); + + return table; + } + + private void insertRow(int key) throws Exception + { + TableInfo table = _list.getTable(_user); + assertNotNull(table); + + BatchValidationException errors = new BatchValidationException(); + table.getUpdateService().insertRows(_user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); + if (errors.hasErrors()) + throw errors; + } + + private void mergeIntField(TableInfo table, int key) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) + { + int count = table.getUpdateService().mergeRows(_user, _container, MapDataIterator.of(List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 2))), errors, null, null); + if (errors.hasErrors()) + throw errors; + assertEquals(1, count); + tx.commit(); + } + } + + private void assertOmittedFieldKept(int key) + { + Map row = new TableSelector(_list.getTable(_user), new SimpleFilter(FieldKey.fromParts(KEY_NAME), key), null).getMap(); + assertNotNull(row); + assertEquals(2, ((Number) row.get(INT_FIELD)).intValue()); + assertEquals("MERGE nulled a column it was not given", "x", row.get(TEXT_FIELD)); + } + + @Test + public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception + { + insertRow(1); + mergeIntField(_list.getTable(_user), 1); + assertOmittedFieldKept(1); + } + + @Test + public void mergeWithTriggerKeepsOmittedColumns() throws Exception + { + insertRow(2); + mergeIntField(tableWithTrigger(), 2); + assertOmittedFieldKept(2); + } + } } From 558644798f170088f2a427b7c19d3af65690820c Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 9 Nov 2026 18:00:58 -0800 Subject: [PATCH 2/7] Kanban #1794: Fire update triggers for merged rows that match an existing row Script triggers now get beforeUpdate/afterUpdate with the existing row for merge and replace rows whose key already exists, on lists, sample types, data classes, and study datasets. --- .../labkey/api/data/AbstractTableInfo.java | 12 +- .../api/data/triggers/ScriptTrigger.java | 6 + .../org/labkey/api/data/triggers/Trigger.java | 22 +++ .../ExistingRecordDataIterator.java | 46 ++++- .../api/dataiterator/MergeKeyColumns.java | 31 +++ .../TriggerDataBuilderHelper.java | 126 +++++++++++-- .../experiment/api/SampleMergeTestCase.java | 104 ++++++++-- .../list/model/ListQueryUpdateService.java | 178 ++++++++++++++++-- .../labkey/study/query/DatasetTableImpl.java | 81 +++++++- .../study/query/DatasetUpdateService.java | 92 +++++++++ 10 files changed, 646 insertions(+), 52 deletions(-) create mode 100644 api/src/org/labkey/api/dataiterator/MergeKeyColumns.java diff --git a/api/src/org/labkey/api/data/AbstractTableInfo.java b/api/src/org/labkey/api/data/AbstractTableInfo.java index 48c69d9d119..0c3f4383de0 100644 --- a/api/src/org/labkey/api/data/AbstractTableInfo.java +++ b/api/src/org/labkey/api/data/AbstractTableInfo.java @@ -1934,11 +1934,21 @@ public final boolean canStreamTriggers(Container c) columns.addAll(managedColumns.update()); else columns.addAll(managedColumns.insert()); + + // A routed MERGE batch mixes insert and update rows + if (insertOption.mergeRows && trigger.isMergeRoutedByExistingRecord()) + columns.addAll(managedColumns.update()); } return columns.isEmpty() ? null : columns; } + /** True when a MERGE into this table fires update hooks for rows that already exist. */ + public boolean isMergeRoutedByExistingRecord(@Nullable Container c) + { + return getTriggers(c).stream().anyMatch(Trigger::isMergeRoutedByExistingRecord); + } + private Collection _triggers = null; private Boolean _isTriggerManagedColumnsEnabled = null; @@ -2050,7 +2060,7 @@ public void fireRowTrigger( if (trackedRow != null && script.isManagedColumnsEnabled()) { var managed = script.getManagedColumns(); - var managedCols = managed != null ? managed.getColumns(type) : null; + var managedCols = managed != null ? managed.getColumns(script.getRowEvent(type, insertOption, existingRecord)) : null; // Verify the trigger did not add or remove columns that are not managed if (trackedRow.hasStructuralChanges()) diff --git a/api/src/org/labkey/api/data/triggers/ScriptTrigger.java b/api/src/org/labkey/api/data/triggers/ScriptTrigger.java index 94e88974c9e..5397930d070 100644 --- a/api/src/org/labkey/api/data/triggers/ScriptTrigger.java +++ b/api/src/org/labkey/api/data/triggers/ScriptTrigger.java @@ -140,6 +140,12 @@ public boolean canStream() return _managedColumns; } + @Override + public boolean isMergeRoutedByExistingRecord() + { + return true; + } + @Override public boolean isManagedColumnsEnabled() { diff --git a/api/src/org/labkey/api/data/triggers/Trigger.java b/api/src/org/labkey/api/data/triggers/Trigger.java index 82526fcf757..a0da1f1ff4a 100644 --- a/api/src/org/labkey/api/data/triggers/Trigger.java +++ b/api/src/org/labkey/api/data/triggers/Trigger.java @@ -150,6 +150,21 @@ default boolean isManagedColumnsEnabled() return true; } + /** When true, MERGE and REPLACE rows that match an existing record fire the update hooks with that record as the old row. */ + default boolean isMergeRoutedByExistingRecord() + { + return false; + } + + /** The event this trigger handles for a row, after routing MERGE rows by {@link #isMergeRoutedByExistingRecord()}. */ + default TableInfo.TriggerType getRowEvent(TableInfo.TriggerType event, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map existingRecord) + { + if (event == TableInfo.TriggerType.INSERT && insertOption != null && insertOption.mergeRows + && existingRecord != null && !existingRecord.isEmpty() && isMergeRoutedByExistingRecord()) + return TableInfo.TriggerType.UPDATE; + return event; + } + /** * Ensures all columns declared by {@link #getManagedColumns()} are present in {@code newRow} * before INSERT trigger fires. @@ -270,6 +285,13 @@ default void rowTrigger(TableInfo table, Container c, User user, TableInfo.Trigg ValidationException errors, Map extraContext, @Nullable Map existingRecord) throws ValidationException { + TableInfo.TriggerType rowEvent = getRowEvent(event, insertOption, existingRecord); + if (rowEvent != event) + { + event = rowEvent; + oldRow = existingRecord; + } + if (before) { switch (event) diff --git a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java index e8311f10a96..009703989e3 100644 --- a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java @@ -88,7 +88,7 @@ public abstract class ExistingRecordDataIterator extends WrapperDataIterator final DataIteratorContext _context; - ExistingRecordDataIterator(DataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useMark, DataIteratorContext context, boolean detailed) + ExistingRecordDataIterator(DataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useMark, DataIteratorContext context, boolean detailed, boolean allColumns) { super(in); _context = context; @@ -122,6 +122,8 @@ public abstract class ExistingRecordDataIterator extends WrapperDataIterator if (detailed) _dataColumnNames.addAll(map.keySet()); + if (allColumns) + _dataColumnNames.addAll(target.getColumnNameSet()); for (String name : keyNames) { @@ -245,6 +247,12 @@ public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableIn } public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useGetRows) + { + return createBuilder(dib, target, keys, sharedKeys, useGetRows, false); + } + + /** @param allColumns fetch every stored column of existing rows, keyed by column name, not just those needed for keys and auditing */ + public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useGetRows, boolean allColumns) { return context -> { @@ -264,11 +272,11 @@ public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableIn AuditBehaviorType auditType = AuditBehaviorType.NONE; if (target.supportsAuditTracking()) auditType = target.getEffectiveAuditBehavior((AuditBehaviorType) context.getConfigParameter(DetailedAuditLogDataIterator.AuditConfigs.AuditBehavior)); - boolean detailed = auditType == DETAILED || hasAttachmentProperties; + boolean detailed = auditType == DETAILED || hasAttachmentProperties || allColumns; if (useGetRows) - return new ExistingDataIteratorsGetRows(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed); + return new ExistingDataIteratorsGetRows(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns); else - return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed); + return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns); } return di; }; @@ -279,12 +287,15 @@ public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableIn static class ExistingDataIteratorsTableInfo extends ExistingRecordDataIterator { final Set allowedContainers = new HashSet<>(); + /** When set, select these by column name instead of the storage columns, matching the rows updateRows() passes as oldRow */ + final @Nullable List _namedColumns; - ExistingDataIteratorsTableInfo(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed) + ExistingDataIteratorsTableInfo(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns) { - super(in, target, keys, sharedKeys, true, context, detailed); + super(in, target, keys, sharedKeys, true, context, detailed, allColumns); if (c != null) allowedContainers.add(c.getId()); + _namedColumns = allColumns ? target.getColumns().stream().filter(col -> !col.isCalculated() && !col.isUnselectable()).toList() : null; } private Pair> getSelectExistingSql(int rows) throws BatchValidationException @@ -334,7 +345,15 @@ private Pair> getSelectExistingSql(int rows) t sqlf.unsafeAppend(",").unsafeAppend("key").appendValue(p); sqlf.unsafeAppend("))\n"); - sqlf.unsafeAppend("SELECT _key_columns_._row_number_, _target_.* FROM "); + sqlf.unsafeAppend("SELECT _key_columns_._row_number_"); + if (_namedColumns == null) + sqlf.unsafeAppend(", _target_.*"); + else + { + for (int i = 0; i < _namedColumns.size(); i++) + sqlf.unsafeAppend(", (").append(_namedColumns.get(i).getValueSql("_target_")).unsafeAppend(") AS _col").appendValue(i); + } + sqlf.unsafeAppend(" FROM "); sqlf.unsafeAppend("_key_columns_ INNER JOIN "); sqlf.append(target.getFromSQL("_target_ ")); sqlf.unsafeAppend(" ON "); @@ -368,6 +387,13 @@ protected void prefetchExisting() throws BatchValidationException for (Map map : list) { Integer r = asInteger(map.get("_row_number_")); + if (_namedColumns != null) + { + Map named = new CaseInsensitiveHashMap<>(); + for (int i = 0; i < _namedColumns.size(); i++) + named.put(_namedColumns.get(i).getName(), map.get("_col" + i)); + map = named; + } if (_verifyExisting) { @@ -412,9 +438,9 @@ static class ExistingDataIteratorsGetRows extends ExistingRecordDataIterator { final QueryUpdateService qus; - ExistingDataIteratorsGetRows(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed) + ExistingDataIteratorsGetRows(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns) { - super(in, target, keys, sharedKeys, true, context, detailed); + super(in, target, keys, sharedKeys, true, context, detailed, allColumns); qus = target.getUpdateService(); } @@ -500,7 +526,7 @@ private DataIterator makeModulesDI() assertFalse(di.supportsGetExistingRecord()); var context = new DataIteratorContext(); context.setInsertOption(QueryUpdateService.InsertOption.INSERT); - DataIterator existing = new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), CoreSchema.getInstance().getTableInfoModules(), null, null, context, true); + DataIterator existing = new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), CoreSchema.getInstance().getTableInfoModules(), null, null, context, true, false); assertTrue(existing.supportsGetExistingRecord()); return existing; } diff --git a/api/src/org/labkey/api/dataiterator/MergeKeyColumns.java b/api/src/org/labkey/api/dataiterator/MergeKeyColumns.java new file mode 100644 index 00000000000..5c0bf45c09c --- /dev/null +++ b/api/src/org/labkey/api/dataiterator/MergeKeyColumns.java @@ -0,0 +1,31 @@ +/* + * 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.api.dataiterator; + +import org.jetbrains.annotations.Nullable; + +import java.util.Set; + +/** Input rows plus the columns that match each one to the existing row a MERGE will update */ +public record MergeKeyColumns(DataIterator input, Set columnNames) +{ + /** A table whose MERGE key is computed during import, after the before triggers fire */ + public interface Provider + { + /** @return the input with its key columns added, or null when the input can't identify existing rows */ + @Nullable MergeKeyColumns addMergeKeyColumns(DataIterator input, DataIteratorContext context); + } +} diff --git a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java index be07aaaa75e..c075406d2ae 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -15,6 +15,9 @@ */ package org.labkey.api.dataiterator; +import org.jetbrains.annotations.Nullable; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; @@ -28,6 +31,7 @@ import org.labkey.api.security.User; import java.util.Collection; +import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -45,6 +49,9 @@ public class TriggerDataBuilderHelper final boolean _useImportAliases; /** Only fire complete() if we got far enough to fire init() */ boolean firedInit = false; + /** Existing records of rows routed to update, held from the before trigger until the after trigger */ + final Map> _routedExistingRecords = new HashMap<>(); + boolean _routeMerge = false; public TriggerDataBuilderHelper(TableInfo target, Container c, User user, Map extraContext, boolean useImportAliases) { @@ -135,39 +142,75 @@ public DataIterator getDataIterator(DataIteratorContext context) return di; di = LoggingDataIterator.wrap(di); + QueryUpdateService.InsertOption option = context.getInsertOption(); + boolean routeMerge = option.mergeRows && _target instanceof AbstractTableInfo t && t.isMergeRoutedByExistingRecord(_c); + _routeMerge = routeMerge; + // Incorporate columns managed by triggers that may not overlap with the requested column set - di = getManagedColumnsDataIterator(di, context); + Set managedOnlyColumns = new CaseInsensitiveHashSet(); + di = getManagedColumnsDataIterator(di, context, managedOnlyColumns); Set existingRecordKeyColumnNames = null; Set sharedKeys = null; - boolean isMergeOrUpdate = context.getInsertOption().allowUpdate; + boolean isMergeOrUpdate = option.allowUpdate; if (isMergeOrUpdate && _target instanceof ExpTable expTable) { - Map colNameMap = DataIteratorUtil.createColumnNameMap(di); - existingRecordKeyColumnNames = expTable.getExistingRecordKeyColumnNames(context, colNameMap); + existingRecordKeyColumnNames = expTable.getExistingRecordKeyColumnNames(context, DataIteratorUtil.createColumnNameMap(di)); sharedKeys = expTable.getExistingRecordSharedKeyColumnNames(); } + // Rows routed to update keep trigger-managed values the input omits, since beforeUpdate may not set them + Set carryForwardColumns = routeMerge ? managedOnlyColumns : Set.of(); + // GH Issue 1048: null padding would make MERGE overwrite every column the input omitted - QueryUpdateService.InsertOption option = context.getInsertOption(); boolean padMissingColumns = !option.updateOnly && (!option.mergeRows || option.replace); di = LoggingDataIterator.wrap(new CoerceDataIterator(di, context, _target, padMissingColumns)); context.setWithLookupRemapping(false); + // The import pipeline doesn't expect an existing record from a lookup made only to route triggers + boolean routingOnlyLookup = false; + if (routeMerge && existingRecordKeyColumnNames == null) + { + MergeKeyColumns keys = getMergeKeyColumns(di, context); + if (keys != null) + { + di = keys.input(); + existingRecordKeyColumnNames = keys.columnNames(); + routingOnlyLookup = true; + } + } + // Skip existing records - if (!context.getInsertOption().allowUpdate || existingRecordKeyColumnNames == null) - return LoggingDataIterator.wrap(new BeforeIterator(new CachingDataIterator(di), context)); + if (!option.allowUpdate || existingRecordKeyColumnNames == null) + return LoggingDataIterator.wrap(new BeforeIterator(new CachingDataIterator(di), context, Set.of())); // Merge request but merge is not supported - if (context.getInsertOption().mergeRows && !_target.supportsInsertOption(QueryUpdateService.InsertOption.MERGE)) - return LoggingDataIterator.wrap(new BeforeIterator(di, context)); + if (option.mergeRows && !_target.supportsInsertOption(QueryUpdateService.InsertOption.MERGE)) + return LoggingDataIterator.wrap(new BeforeIterator(di, context, Set.of())); + + // Rows routed to update get the whole existing row as oldRow + di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, _target instanceof ExpTable, routeMerge).getDataIterator(context); + DataIterator before = new BeforeIterator(new CachingDataIterator(di), context, carryForwardColumns); + if (routingOnlyLookup) + before = new HiddenExistingRecordDataIterator(before); + return LoggingDataIterator.wrap(before); + } - di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, true).getDataIterator(context); - return LoggingDataIterator.wrap(new BeforeIterator(new CachingDataIterator(di), context)); + /** Columns that match each input row to the row MERGE will update: the table's computed key, alternate keys, or primary key */ + private @Nullable MergeKeyColumns getMergeKeyColumns(DataIterator di, DataIteratorContext context) + { + if (_target instanceof MergeKeyColumns.Provider provider) + return provider.addMergeKeyColumns(di, context); + + Collection keys = context.getAlternateKeys().isEmpty() ? _target.getPkColumnNames() : context.getAlternateKeys(); + Map colNameMap = DataIteratorUtil.createColumnNameMap(di); + if (keys.isEmpty() || !keys.stream().allMatch(colNameMap::containsKey)) + return null; + return new MergeKeyColumns(di, new CaseInsensitiveHashSet(keys)); } - private DataIterator getManagedColumnsDataIterator(DataIterator di, DataIteratorContext context) + private DataIterator getManagedColumnsDataIterator(DataIterator di, DataIteratorContext context, Set addedColumns) { if (QueryService.get().isTriggerManagedColumnsEnabled()) { @@ -192,7 +235,10 @@ private DataIterator getManagedColumnsDataIterator(DataIterator di, DataIterator for (var column : columns) { if (!columnNameMap.containsKey(column.getName())) + { translator.addColumn(column, (Supplier) () -> null); + addedColumns.add(column.getName()); + } } di = translator.getDataIterator(context); @@ -208,10 +254,12 @@ class BeforeIterator extends TriggerDataIterator { boolean _firstRow = true; Map _currentRow = null; + final Set _carryForwardColumns; - BeforeIterator(DataIterator di, DataIteratorContext context) + BeforeIterator(DataIterator di, DataIteratorContext context, Set carryForwardColumns) { super(di, context); + _carryForwardColumns = carryForwardColumns; } @Override @@ -248,9 +296,13 @@ public boolean next() throws BatchValidationException { int rowNumber = asInteger(getInput().get(0)); _currentRow = getInput().getMap(); + Map existingRecord = getExistingRecord(); + carryForward(existingRecord); + if (_routeMerge && existingRecord != null && !existingRecord.isEmpty()) + _routedExistingRecords.put(rowNumber, existingRecord); try { - _target.fireRowTrigger(_c, _user, triggerType, _context.getInsertOption(), true, rowNumber, _currentRow, getOldRow(), _extraContext, getExistingRecord()); + _target.fireRowTrigger(_c, _user, triggerType, _context.getInsertOption(), true, rowNumber, _currentRow, getOldRow(), _extraContext, existingRecord); return true; } catch (ValidationException vex) @@ -263,6 +315,19 @@ public boolean next() throws BatchValidationException return false; } + private void carryForward(@Nullable Map existingRecord) + { + if (_carryForwardColumns.isEmpty() || existingRecord == null || existingRecord.isEmpty()) + return; + + Map existing = new CaseInsensitiveHashMap<>(existingRecord); + for (String col : _carryForwardColumns) + { + if (existing.containsKey(col)) + _currentRow.put(col, existing.get(col)); + } + } + @Override public Object get(int i) { @@ -274,6 +339,34 @@ public Object get(int i) } } + /** Hides the existing record column and accessor from the iterators downstream */ + static class HiddenExistingRecordDataIterator extends WrapperDataIterator + { + HiddenExistingRecordDataIterator(DataIterator di) + { + super(di); + } + + @Override + public int getColumnCount() + { + int count = _delegate.getColumnCount(); + return ExistingRecordDataIterator.EXISTING_RECORD_COLUMN_NAME.equals(_delegate.getColumnInfo(count).getName()) ? count - 1 : count; + } + + @Override + public boolean supportsGetExistingRecord() + { + return false; + } + + @Override + public Map getExistingRecord() + { + return null; + } + } + class After implements DataIteratorBuilder { final DataIteratorBuilder _in; @@ -315,9 +408,12 @@ public boolean next() throws BatchValidationException { int rowNumber = asInteger(getInput().get(0)); Map newRow = getInput().getMap(); + Map existingRecord = _routedExistingRecords.remove(rowNumber); + if (existingRecord == null) + existingRecord = getExistingRecord(); try { - _target.fireRowTrigger(_c, _user, getTriggerType(), _context.getInsertOption(), false, rowNumber, newRow, getOldRow(), _extraContext, getExistingRecord()); + _target.fireRowTrigger(_c, _user, getTriggerType(), _context.getInsertOption(), false, rowNumber, newRow, getOldRow(), _extraContext, existingRecord); } catch (ValidationException vex) { diff --git a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java index f73977d1430..f928549a9bf 100644 --- a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java +++ b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java @@ -15,6 +15,7 @@ */ package org.labkey.experiment.api; +import org.jetbrains.annotations.Nullable; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; @@ -36,15 +37,18 @@ import org.labkey.api.query.QueryService; import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.UserSchema; +import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.util.JunitUtil; import org.labkey.api.util.TestContext; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; -/** GH Issue 1048: MERGE must leave sample columns the input omits unchanged, with or without a trigger on the table. */ +/** GH Issue 1048: MERGE must leave sample columns the input omits unchanged, and script triggers see existing samples as updates. */ public class SampleMergeTestCase extends Assert { private static final String INT_FIELD = "A"; @@ -72,7 +76,7 @@ public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception { ExpSampleType st = createSampleType("MergeNoTrigger"); insertSample(st); - mergeIntField(table(st, false)); + mergeIntField(table(st, null), "S-1"); assertOmittedFieldKept(st); } @@ -81,10 +85,73 @@ public void mergeWithTriggerKeepsOmittedColumns() throws Exception { ExpSampleType st = createSampleType("MergeTrigger"); insertSample(st); - mergeIntField(table(st, true)); + mergeIntField(table(st, new Trigger() {}), "S-1"); assertOmittedFieldKept(st); } + @Test + public void mergeRoutesExistingSamplesToUpdateHooks() throws Exception + { + ExpSampleType st = createSampleType("MergeRouted"); + insertSample(st); + RecordingTrigger trigger = new RecordingTrigger(); + mergeIntField(table(st, trigger), "S-1", "S-2"); + + assertEquals(Set.of("beforeUpdate S-1 old x", "beforeInsert S-2", "afterUpdate S-1", "afterInsert S-2"), Set.copyOf(trigger.events)); + assertEquals(4, trigger.events.size()); + assertOmittedFieldKept(st); + assertEquals("computed", getSample(st, "S-2").get(TEXT_FIELD)); + } + + /** Opts into MERGE routing and manages the text field on insert */ + private static class RecordingTrigger implements Trigger + { + final List events = new ArrayList<>(); + + @Override + public boolean isMergeRoutedByExistingRecord() + { + return true; + } + + @Override + public @Nullable ManagedColumns getManagedColumns() + { + return new ManagedColumns(Set.of(TEXT_FIELD), Set.of(), null); + } + + @Override + public void beforeInsert(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("beforeInsert " + newRow.get("name")); + newRow.put(TEXT_FIELD, "computed"); + } + + @Override + public void beforeUpdate(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + events.add("beforeUpdate " + newRow.get("name") + " old " + new CaseInsensitiveHashMap<>(oldRow).get(TEXT_FIELD)); + } + + @Override + public void afterInsert(TableInfo table, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("afterInsert " + newRow.get("name")); + } + + @Override + public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + events.add("afterUpdate " + newRow.get("name")); + } + } + private ExpSampleType createSampleType(String name) throws Exception { List props = List.of( @@ -95,16 +162,16 @@ private ExpSampleType createSampleType(String name) throws Exception } /** Cached tables are locked, so only one built for write accepts another trigger factory */ - private TableInfo table(ExpSampleType st, boolean withTrigger) + private TableInfo table(ExpSampleType st, @Nullable Trigger trigger) { UserSchema schema = QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME); assertNotNull(schema); - TableInfo table = schema.getTable(st.getName(), null, true, withTrigger); + TableInfo table = schema.getTable(st.getName(), null, true, trigger != null); assertNotNull(table); - if (withTrigger) + if (trigger != null) { AbstractTableInfo writable = (AbstractTableInfo) table; - writable.addTriggerFactory((_, _, _) -> List.of(new Trigger() {})); + writable.addTriggerFactory((_, _, _) -> List.of(trigger)); writable.resetTriggers(_c); assertTrue(writable.hasTriggers(_c)); } @@ -122,24 +189,35 @@ private QueryUpdateService updateService(TableInfo table) private void insertSample(ExpSampleType st) throws Exception { BatchValidationException errors = new BatchValidationException(); - updateService(table(st, false)).insertRows(_user, _c, List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); + updateService(table(st, null)).insertRows(_user, _c, List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); if (errors.hasErrors()) throw errors; } - private void mergeIntField(TableInfo table) throws Exception + /** Writes the int field only, for each sample name */ + private void mergeIntField(TableInfo table, String... names) throws Exception { + List> rows = new ArrayList<>(); + for (String name : names) + rows.add(CaseInsensitiveHashMap.of("name", name, INT_FIELD, 2)); + BatchValidationException errors = new BatchValidationException(); - int count = updateService(table).mergeRows(_user, _c, MapDataIterator.of(List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 2))), errors, null, null); + int count = updateService(table).mergeRows(_user, _c, MapDataIterator.of(rows), errors, null, null); if (errors.hasErrors()) throw errors; - assertEquals(1, count); + assertEquals(names.length, count); } - private void assertOmittedFieldKept(ExpSampleType st) + private Map getSample(ExpSampleType st, String name) { - Map row = new TableSelector(table(st, false), new SimpleFilter(FieldKey.fromParts("name"), "S-1"), null).getMap(); + Map row = new TableSelector(table(st, null), new SimpleFilter(FieldKey.fromParts("name"), name), null).getMap(); assertNotNull(row); + return row; + } + + private void assertOmittedFieldKept(ExpSampleType st) + { + Map row = getSample(st, "S-1"); assertEquals(2, ((Number) row.get(INT_FIELD)).intValue()); assertEquals("MERGE nulled a column it was not given", "x", row.get(TEXT_FIELD)); } diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index 4766d7af049..56f88ffb324 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -71,6 +71,7 @@ import org.labkey.api.query.InvalidKeyException; import org.labkey.api.query.PropertyValidationError; import org.labkey.api.query.QueryService; +import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; import org.labkey.api.query.ValidationError; import org.labkey.api.query.ValidationException; @@ -104,6 +105,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; import static org.labkey.api.data.BatchSize.Kind.AUDIT; @@ -1247,7 +1249,7 @@ public void matchesGetRowInKeyOrder() throws Exception } } } - /** GH Issue 1048: MERGE must leave columns the input omits unchanged, with or without a trigger on the table. */ + /** GH Issue 1048: MERGE must leave columns the input omits unchanged, and script triggers see existing rows as updates. */ @TestTimeout(TestTimeout.DEFAULT * 5) public static class MergeTestCase extends Assert { @@ -1305,44 +1307,139 @@ private static void deleteTestContainer() } /** Cached tables are locked, so only one built for write accepts another trigger factory */ - private TableInfo tableWithTrigger() + private TableInfo tableWithTrigger(Trigger trigger) { AbstractTableInfo table = (AbstractTableInfo) new ListQuerySchema(_user, _container).getTable(LIST_NAME, null, true, true); - table.addTriggerFactory((_, _, _) -> List.of(new Trigger() {})); + assertNotNull(table); + table.addTriggerFactory((_, _, _) -> List.of(trigger)); table.resetTriggers(_container); assertTrue(table.hasTriggers(_container)); return table; } - private void insertRow(int key) throws Exception + /** Records which hook saw each key; sets the text field on insert when it manages that column */ + private static class RecordingTrigger implements Trigger + { + final List events = new ArrayList<>(); + final boolean _routed; + final boolean _managesText; + + RecordingTrigger(boolean routed, boolean managesText) + { + _routed = routed; + _managesText = managesText; + } + + @Override + public boolean isMergeRoutedByExistingRecord() + { + return _routed; + } + + @Override + public @Nullable ManagedColumns getManagedColumns() + { + return _managesText ? new ManagedColumns(Set.of(TEXT_FIELD), Set.of(), null) : null; + } + + @Override + public void beforeInsert(TableInfo table, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("beforeInsert " + newRow.get(KEY_NAME)); + if (_managesText) + newRow.put(TEXT_FIELD, "computed"); + } + + @Override + public void beforeUpdate(TableInfo table, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + events.add("beforeUpdate " + newRow.get(KEY_NAME) + " old " + new CaseInsensitiveHashMap<>(oldRow).get(TEXT_FIELD)); + } + + @Override + public void afterInsert(TableInfo table, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("afterInsert " + newRow.get(KEY_NAME)); + } + + @Override + public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + events.add("afterUpdate " + newRow.get(KEY_NAME)); + } + } + + private TableInfo listTable() { TableInfo table = _list.getTable(_user); assertNotNull(table); + return table; + } + + private QueryUpdateService updateService(TableInfo table) + { + QueryUpdateService qus = table.getUpdateService(); + assertNotNull(qus); + return qus; + } + private void insertRow(int key) throws Exception + { BatchValidationException errors = new BatchValidationException(); - table.getUpdateService().insertRows(_user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); + updateService(listTable()).insertRows(_user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); if (errors.hasErrors()) throw errors; } - private void mergeIntField(TableInfo table, int key) throws Exception + private void mergeIntField(TableInfo table, int... keys) throws Exception { + load(table, InsertOption.MERGE, keys); + } + + /** Writes the int field only, for each key */ + private void load(TableInfo table, InsertOption option, int... keys) throws Exception + { + List> rows = new ArrayList<>(); + for (int key : keys) + rows.add(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 2)); + BatchValidationException errors = new BatchValidationException(); + DataIteratorContext context = new DataIteratorContext(errors); + context.setInsertOption(option); try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) { - int count = table.getUpdateService().mergeRows(_user, _container, MapDataIterator.of(List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 2))), errors, null, null); + int count = updateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); if (errors.hasErrors()) throw errors; - assertEquals(1, count); + assertEquals(keys.length, count); tx.commit(); } } - private void assertOmittedFieldKept(int key) + /** Rows are batched, so hooks for different rows may interleave */ + private void assertEvents(RecordingTrigger trigger, String... expected) { - Map row = new TableSelector(_list.getTable(_user), new SimpleFilter(FieldKey.fromParts(KEY_NAME), key), null).getMap(); + assertEquals(Set.of(expected), Set.copyOf(trigger.events)); + assertEquals(expected.length, trigger.events.size()); + } + + private Map getRow(int key) + { + Map row = new TableSelector(listTable(), new SimpleFilter(FieldKey.fromParts(KEY_NAME), key), null).getMap(); assertNotNull(row); + return row; + } + + private void assertOmittedFieldKept(int key) + { + Map row = getRow(key); assertEquals(2, ((Number) row.get(INT_FIELD)).intValue()); assertEquals("MERGE nulled a column it was not given", "x", row.get(TEXT_FIELD)); } @@ -1351,7 +1448,7 @@ private void assertOmittedFieldKept(int key) public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception { insertRow(1); - mergeIntField(_list.getTable(_user), 1); + mergeIntField(listTable(), 1); assertOmittedFieldKept(1); } @@ -1359,8 +1456,65 @@ public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception public void mergeWithTriggerKeepsOmittedColumns() throws Exception { insertRow(2); - mergeIntField(tableWithTrigger(), 2); + mergeIntField(tableWithTrigger(new Trigger() {}), 2); assertOmittedFieldKept(2); } + + @Test + public void mergeRoutesExistingRowsToUpdateHooks() throws Exception + { + insertRow(3); + RecordingTrigger trigger = new RecordingTrigger(true, false); + mergeIntField(tableWithTrigger(trigger), 3, 4); + + assertEvents(trigger, "beforeUpdate 3 old x", "beforeInsert 4", "afterUpdate 3", "afterInsert 4"); + assertOmittedFieldKept(3); + } + + @Test + public void mergeWithoutRoutingFiresInsertHooks() throws Exception + { + insertRow(5); + RecordingTrigger trigger = new RecordingTrigger(false, false); + mergeIntField(tableWithTrigger(trigger), 5, 6); + + assertEvents(trigger, "beforeInsert 5", "beforeInsert 6", "afterInsert 5", "afterInsert 6"); + assertOmittedFieldKept(5); + } + + @Test + public void mergeKeepsInsertManagedColumnOnUpdatedRows() throws Exception + { + insertRow(7); + RecordingTrigger trigger = new RecordingTrigger(true, true); + mergeIntField(tableWithTrigger(trigger), 7, 8); + + assertEvents(trigger, "beforeUpdate 7 old x", "beforeInsert 8", "afterUpdate 7", "afterInsert 8"); + assertOmittedFieldKept(7); + assertEquals("computed", getRow(8).get(TEXT_FIELD)); + } + + @Test + public void replaceRoutesExistingRowsToUpdateHooks() throws Exception + { + insertRow(9); + RecordingTrigger trigger = new RecordingTrigger(true, false); + load(tableWithTrigger(trigger), InsertOption.REPLACE, 9, 10); + + assertEvents(trigger, "beforeUpdate 9 old x", "beforeInsert 10", "afterUpdate 9", "afterInsert 10"); + assertNull("REPLACE keeps a column it was not given", getRow(9).get(TEXT_FIELD)); + } + + @Test + public void replaceKeepsInsertManagedColumnOnUpdatedRows() throws Exception + { + insertRow(11); + RecordingTrigger trigger = new RecordingTrigger(true, true); + load(tableWithTrigger(trigger), InsertOption.REPLACE, 11, 12); + + assertEvents(trigger, "beforeUpdate 11 old x", "beforeInsert 12", "afterUpdate 11", "afterInsert 12"); + assertEquals("REPLACE nulled a trigger-managed column", "x", getRow(11).get(TEXT_FIELD)); + assertEquals("computed", getRow(12).get(TEXT_FIELD)); + } } } diff --git a/study/src/org/labkey/study/query/DatasetTableImpl.java b/study/src/org/labkey/study/query/DatasetTableImpl.java index 3c10c26e0c5..8c6fcbbf7a5 100644 --- a/study/src/org/labkey/study/query/DatasetTableImpl.java +++ b/study/src/org/labkey/study/query/DatasetTableImpl.java @@ -20,6 +20,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.labkey.api.assay.AbstractAssayProvider; import org.labkey.api.assay.AssayTableMetadata; import org.labkey.api.collections.CaseInsensitiveHashSet; @@ -45,6 +46,9 @@ import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.dataiterator.DataIterator; import org.labkey.api.dataiterator.DataIteratorContext; +import org.labkey.api.dataiterator.DataIteratorUtil; +import org.labkey.api.dataiterator.MergeKeyColumns; +import org.labkey.api.dataiterator.SimpleTranslator; import org.labkey.api.exp.PropertyDescriptor; import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.property.Domain; @@ -67,6 +71,7 @@ import org.labkey.api.query.SchemaKey; import org.labkey.api.query.UserIdQueryForeignKey; import org.labkey.api.query.UserSchema; +import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.security.UserPrincipal; import org.labkey.api.security.permissions.DeletePermission; @@ -102,23 +107,31 @@ import org.labkey.study.importer.StudyImportContext; import org.labkey.study.model.DatasetDataIteratorBuilder; import org.labkey.study.model.DatasetDefinition; +import org.labkey.study.model.DatasetLsidImportHelper; +import org.labkey.study.model.ParticipantIdImportHelper; +import org.labkey.study.model.SequenceNumImportHelper; +import org.labkey.study.model.StudyImpl; import org.labkey.study.writer.StudyArchiveDataTypes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.concurrent.Callable; import java.util.function.Predicate; +import java.util.function.Supplier; import static org.labkey.api.util.IntegerUtils.asLongElseNull; /** Wraps a DatasetSchemaTableInfo and makes it Query-ized. Represents a single dataset's data */ -public class DatasetTableImpl extends BaseStudyTable implements DatasetTable +public class DatasetTableImpl extends BaseStudyTable implements DatasetTable, MergeKeyColumns.Provider { public static final String QCSTATE_ID_COLNAME = "QCState"; public static final String QCSTATE_LABEL_COLNAME = "QCStateLabel"; @@ -613,6 +626,72 @@ public Dataset getDataset() return _dsd; } + private static final String LSID_COLUMN = "lsid"; + + /** Adds the LSID that dataset import computes from participant, visit, and key, so triggers can route MERGE rows */ + @Override + public @Nullable MergeKeyColumns addMergeKeyColumns(DataIterator input, DataIteratorContext context) + { + Map inputMap = DataIteratorUtil.createColumnAndPropertyMap(input); + StudyImpl study = _dsd.getStudy(); + boolean timeKey = !study.getTimepointType().isVisitBased() && _dsd.getUseTimeKeyField(); + Integer ptidIndex = DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn(study.getSubjectColumnName())); + Integer seqIndex = DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn("SequenceNum")); + Integer dateIndex = DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn("Date")); + String keyName = _dsd.getKeyPropertyName(); + Integer keyIndex = keyName == null ? null : DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn(keyName)); + Integer containerIndex = inputMap.get("Container"); + + if (ptidIndex == null) + return null; + if (!_dsd.isDemographicData()) + { + if (seqIndex == null && dateIndex == null) + return null; + if (timeKey ? dateIndex == null : keyName != null && keyIndex == null) + return null; + } + + Callable ptid; + try + { + ptid = new ParticipantIdImportHelper(study, getUserSchema().getUser(), _dsd).getCallable(input, ptidIndex); + } + catch (ValidationException e) + { + return null; + } + Callable seq = new SequenceNumImportHelper(study, _dsd).getCallable(input, seqIndex, dateIndex); + DatasetLsidImportHelper lsid = new DatasetLsidImportHelper(_dsd); + + SimpleTranslator translator = new SimpleTranslator(input, context); + translator.setDebugName("DatasetTableImpl.addMergeKeyColumns"); + // Import recomputes the LSID and ignores any supplied one, so this does too + translator.selectAll(new CaseInsensitiveHashSet(LSID_COLUMN)); + translator.addColumn(new BaseColumnInfo(LSID_COLUMN, JdbcType.VARCHAR), (Supplier) () -> { + try + { + Object participant = ptid.call(); + Object sequenceNum = seq.call(); + Object date = dateIndex == null ? null : input.get(dateIndex); + if (participant != null && (_dsd.isDemographicData() || sequenceNum instanceof Number)) + { + return lsid.translateLsid(participant.toString(), sequenceNum instanceof Number n ? n.doubleValue() : null, + date instanceof Date d ? d : null, keyIndex == null ? null : input.get(keyIndex), + containerIndex == null ? null : Objects.toString(input.get(containerIndex), null)); + } + } + catch (Exception ignored) + { + // Import reports the bad value; the row just won't match an existing one + } + // A null key is a row error, and duplicate keys are too, so give unmatched rows a key of their own + return "unmatched:" + input.get(0); + }); + + return new MergeKeyColumns(translator, Set.of(LSID_COLUMN)); + } + @Override public DataIterator getPrimaryKeyDataIterator(DataIterator dit, DataIteratorContext context) { diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index f8437a699f7..dc2fb82b797 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -28,6 +28,7 @@ import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.collections.ResultSetRowMapFactory; +import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.BaseColumnInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; @@ -41,6 +42,7 @@ import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; +import org.labkey.api.data.triggers.Trigger; import org.labkey.api.dataiterator.DataIterator; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; @@ -61,6 +63,7 @@ import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; import org.labkey.api.query.SimpleValidationError; +import org.labkey.api.query.UserSchema; import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.security.UserPrincipal; @@ -1108,6 +1111,95 @@ public void updateRowTest() throws Exception map.get("lsid"); } + /** GH Issue 1048: MERGE keeps omitted columns, and triggers that route MERGE see existing rows as updates */ + @Test + public void mergeRoutesExistingRowsToUpdateHooks() throws Exception + { + createDataset(); + insertS1(); + + UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); + assertNotNull(schema); + AbstractTableInfo table = (AbstractTableInfo) schema.getTable(DATASET_NAME, null, true, true); + assertNotNull(table); + List events = new ArrayList<>(); + table.addTriggerFactory((_, _, _) -> List.of(new Trigger() + { + @Override + public boolean isMergeRoutedByExistingRecord() + { + return true; + } + + @Override + public void beforeInsert(TableInfo t, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("beforeInsert " + newRow.get(SUBJECT_COLUMN_NAME)); + } + + @Override + public void beforeUpdate(TableInfo t, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + // oldRow uses query column names, as in updateRows(), not storage names like participantid + Map old = new CaseInsensitiveHashMap<>(oldRow); + events.add("beforeUpdate " + newRow.get(SUBJECT_COLUMN_NAME) + " old " + old.get(SUBJECT_COLUMN_NAME) + " " + old.get("Field1")); + } + + @Override + public void afterInsert(TableInfo t, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + events.add("afterInsert " + newRow.get(SUBJECT_COLUMN_NAME)); + } + + @Override + public void afterUpdate(TableInfo t, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + events.add("afterUpdate " + newRow.get(SUBJECT_COLUMN_NAME)); + } + })); + table.resetTriggers(_container); + + QueryUpdateService qus = table.getUpdateService(); + assertNotNull(qus); + BatchValidationException errors = new BatchValidationException(); + List> rows = List.of( + Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Value1", "2.0"), + Map.of(SUBJECT_COLUMN_NAME, "S2", "SequenceNum", "1.2345", "Value1", "2.0")); + int count = qus.mergeRows(_user, _container, MapDataIterator.of(rows), errors, null, null); + if (errors.hasErrors()) + fail(errors.getMessage()); + assertEquals(2, count); + + // Rows are batched, so hooks for different rows may interleave + assertEquals(Set.of("beforeUpdate S1 old S1 x", "beforeInsert S2", "afterUpdate S1", "afterInsert S2"), Set.copyOf(events)); + assertEquals(4, events.size()); + + Map s1 = new TableSelector(table, new SimpleFilter(FieldKey.fromParts(SUBJECT_COLUMN_NAME), "S1"), null).getMap(); + assertNotNull(s1); + assertEquals(2.0d, s1.get("Value1")); + assertEquals("MERGE nulled a column it was not given", "x", s1.get("Field1")); + } + + private void insertS1() throws Exception + { + UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); + assertNotNull(schema); + TableInfo t = schema.getTable(DATASET_NAME); + assertNotNull(t); + QueryUpdateService qus = t.getUpdateService(); + assertNotNull(qus); + BatchValidationException errors = new BatchValidationException(); + qus.insertRows(_user, _container, List.of(Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Field1", "x", "Value1", "1.0")), errors, null, null); + if (errors.hasErrors()) + fail(errors.getMessage()); + } + @Before public void createStudy() { From 3a618330d4fb3549d1a306fb6e324f2aa1fa053d Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Thu, 26 Nov 2026 15:31:04 -0800 Subject: [PATCH 3/7] Code review suggestions --- .../ExistingRecordDataIterator.java | 93 +++++++++++-------- .../TriggerDataBuilderHelper.java | 3 +- .../labkey/experiment/ExpDataIterators.java | 2 +- .../list/model/ListQueryUpdateService.java | 53 +++++++++++ .../labkey/study/query/DatasetTableImpl.java | 6 +- .../study/query/DatasetUpdateService.java | 68 ++++++++++++-- 6 files changed, 177 insertions(+), 48 deletions(-) diff --git a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java index 10f15a1734a..7a6d8d91e3f 100644 --- a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java @@ -48,6 +48,7 @@ import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -87,11 +88,14 @@ public abstract class ExistingRecordDataIterator extends WrapperDataIterator final Set _pkKeysSeen = new HashSet<>(); final DataIteratorContext _context; + /** Leave rows with blank or duplicate keys unmatched instead of reporting them, for a lookup whose caller reports them itself */ + final boolean _skipInvalidKeys; - ExistingRecordDataIterator(DataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useMark, DataIteratorContext context, boolean detailed, boolean allColumns) + ExistingRecordDataIterator(DataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useMark, DataIteratorContext context, boolean detailed, boolean allColumns, boolean skipInvalidKeys) { super(in); _context = context; + _skipInvalidKeys = skipInvalidKeys; QueryUpdateService.InsertOption option = context.getInsertOption(); @@ -222,6 +226,8 @@ public boolean next() throws BatchValidationException protected void checkDuplicateKeys(List pkKeys) { + if (_skipInvalidKeys) + return; Object pkKeysObj = pkKeys.size() == 1 ? pkKeys.getFirst() : pkKeys; if (_pkKeysSeen.contains(pkKeysObj)) _context.getErrors().addRowError(new ValidationException("Duplicate key provided: " + StringUtils.join(pkKeys, ", "))); @@ -243,16 +249,14 @@ public Map getExistingRecord() public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys) { - return createBuilder(dib, target, keys, null, false); + return createBuilder(dib, target, keys, null, false, false, false); } - public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useGetRows) - { - return createBuilder(dib, target, keys, sharedKeys, useGetRows, false); - } - - /** @param allColumns fetch every stored column of existing rows, keyed by column name, not just those needed for keys and auditing */ - public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useGetRows, boolean allColumns) + /** + * @param allColumns fetch every stored column of existing rows, keyed by column name, not just those needed for keys and auditing + * @param skipInvalidKeys leave rows with blank or duplicate keys unmatched instead of adding row errors + */ + public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, boolean useGetRows, boolean allColumns, boolean skipInvalidKeys) { return context -> { @@ -274,9 +278,9 @@ public static DataIteratorBuilder createBuilder(DataIteratorBuilder dib, TableIn auditType = target.getEffectiveAuditBehavior((AuditBehaviorType) context.getConfigParameter(DetailedAuditLogDataIterator.AuditConfigs.AuditBehavior)); boolean detailed = auditType == DETAILED || hasAttachmentProperties || allColumns; if (useGetRows) - return new ExistingDataIteratorsGetRows(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns); + return new ExistingDataIteratorsGetRows(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns, skipInvalidKeys); else - return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns); + return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns, skipInvalidKeys); } return di; }; @@ -290,18 +294,20 @@ static class ExistingDataIteratorsTableInfo extends ExistingRecordDataIterator /** When set, select these by column name instead of the storage columns, matching the rows updateRows() passes as oldRow */ final @Nullable List _namedColumns; - ExistingDataIteratorsTableInfo(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns) + ExistingDataIteratorsTableInfo(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns, boolean skipInvalidKeys) { - super(in, target, keys, sharedKeys, true, context, detailed, allColumns); + super(in, target, keys, sharedKeys, true, context, detailed, allColumns, skipInvalidKeys); if (c != null) allowedContainers.add(c.getId()); _namedColumns = allColumns ? target.getColumns().stream().filter(col -> !col.isCalculated() && !col.isUnselectable()).toList() : null; } - private Pair> getSelectExistingSql(int rows) throws BatchValidationException + /** @return null when no row in the batch has a complete key */ + private @Nullable Pair> getSelectExistingSql(int rows) throws BatchValidationException { SQLFragment sqlf = SQLFragment.unsafe("WITH _key_columns_ AS (\nSELECT * FROM (VALUES \n"); - String comma = ""; + var comma = SQLFragment.sep("", "\n,"); + boolean anyKey = false; Map rowNumContainers = new IntHashMap<>(); String container; do @@ -315,31 +321,38 @@ private Pair> getSelectExistingSql(int rows) t container = (String) containerObj; } - sqlf.append(comma).unsafeAppend("(").appendValue(lastPrefetchRowNumber); - comma = "\n,"; + SQLFragment tuple = new SQLFragment().unsafeAppend("(").appendValue(lastPrefetchRowNumber); List pkKeys = new ArrayList<>(); + boolean blankKey = false; for (int p = 0; p < pkColumns.size(); p++) { - sqlf.unsafeAppend(",?"); Object pkVal = pkSuppliers.get(p).get(); // Issue 52922: Rows with blank key in the file are getting ignored in update from file if (pkVal == null) { - _context.getErrors().addRowError(new ValidationException(pkColumns.get(p).getColumnName() + " value not provided on row " + lastPrefetchRowNumber)); - continue; + if (!_skipInvalidKeys) + _context.getErrors().addRowError(new ValidationException(pkColumns.get(p).getColumnName() + " value not provided on row " + lastPrefetchRowNumber)); + blankKey = true; + break; } - sqlf.add(pkVal); + tuple.unsafeAppend(",?").add(pkVal); if (!_sharedKeys.contains(pkColumns.get(p).getColumnName())) pkKeys.add(pkVal.toString()); } - sqlf.unsafeAppend(")"); + if (blankKey) + continue; + sqlf.append(comma.next()).append(tuple).unsafeAppend(")"); + anyKey = true; checkDuplicateKeys(pkKeys); rowNumContainers.put(lastPrefetchRowNumber, container); } while (--rows > 0 && _delegate.next()); + if (!anyKey) + return null; + sqlf.unsafeAppend("\n) AS _values_ (_row_number_"); for (int p = 0; p < pkColumns.size(); p++) sqlf.unsafeAppend(",").unsafeAppend("key").appendValue(p); @@ -357,12 +370,11 @@ private Pair> getSelectExistingSql(int rows) t sqlf.unsafeAppend("_key_columns_ INNER JOIN "); sqlf.append(target.getFromSQL("_target_ ")); sqlf.unsafeAppend(" ON "); - String and = ""; + var and = SQLFragment.sep("", " AND "); for (int p = 0; p < pkColumns.size(); p++) { - sqlf.append(and); + sqlf.append(and.next()); sqlf.unsafeAppend("(_key_columns_.key").appendValue(p).unsafeAppend("=(").append(pkColumns.get(p).getValueSql("_target_")).unsafeAppend("))"); - and = " AND "; } return new Pair<>(sqlf, rowNumContainers); } @@ -377,14 +389,13 @@ protected void prefetchExisting() throws BatchValidationException // fetch N new rows into the existingRecords map Pair> selectRowsSql = getSelectExistingSql(50); - SQLFragment select = selectRowsSql.first; - Map rowNumContainers = selectRowsSql.second; - var list = new SqlSelector(target.getSchema(), select, QueryLogging.noValidationNeededQueryLogging()).getArrayList(Map.class); + Map rowNumContainers = selectRowsSql == null ? new IntHashMap<>() : selectRowsSql.second; + Collection> list = selectRowsSql == null ? List.of() : new SqlSelector(target.getSchema(), selectRowsSql.first, QueryLogging.noValidationNeededQueryLogging()).getMapCollection(); existingRecords.clear(); for (int r=rowNumber ; r<=lastPrefetchRowNumber ;r++) existingRecords.put(r,Map.of()); - for (Map map : list) + for (Map map : list) { Integer r = asInteger(map.get("_row_number_")); if (_namedColumns != null) @@ -419,7 +430,7 @@ else if (map.containsKey("folder")) map.remove("_row_number_"); map.remove("_row"); // I think CachedResultSet adds "_row" - existingRecords.put(r,(Map)map); + existingRecords.put(r, map); rowNumContainers.remove(r); } @@ -438,9 +449,9 @@ static class ExistingDataIteratorsGetRows extends ExistingRecordDataIterator { final QueryUpdateService qus; - ExistingDataIteratorsGetRows(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns) + ExistingDataIteratorsGetRows(CachingDataIterator in, TableInfo target, @Nullable Set keys, @Nullable Set sharedKeys, DataIteratorContext context, boolean detailed, boolean allColumns, boolean skipInvalidKeys) { - super(in, target, keys, sharedKeys, true, context, detailed, allColumns); + super(in, target, keys, sharedKeys, true, context, detailed, allColumns, skipInvalidKeys); qus = target.getUpdateService(); } @@ -462,29 +473,37 @@ protected void prefetchExisting() throws BatchValidationException lastPrefetchRowNumber = asInteger(_delegate.get(0)); Map keyMap = CaseInsensitiveHashMap.of(); List pkKeys = new ArrayList<>(); + existingRecords.put(lastPrefetchRowNumber, Map.of()); + boolean blankKey = false; for (int p=0 ; p 0 && _delegate.next()); - Map> rowsMap = qus.getExistingRows(user, c, keysMap, _checkCrossFolderData, _verifyExisting, _dataColumnNames); + Map> rowsMap = keysMap.isEmpty() ? Map.of() : qus.getExistingRows(user, c, keysMap, _checkCrossFolderData, _verifyExisting, _dataColumnNames); for (Map.Entry> rowMap : rowsMap.entrySet()) { Map map = rowMap.getValue(); @@ -526,7 +545,7 @@ private DataIterator makeModulesDI() context.setInsertOption(QueryUpdateService.InsertOption.INSERT); DataIterator di = MapDataIterator.of(Set.of("Name"), namesArrayList).getDataIterator(context); assertFalse(di.supportsGetExistingRecord()); - DataIterator existing = new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), CoreSchema.getInstance().getTableInfoModules(), null, null, context, true, false); + DataIterator existing = new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), CoreSchema.getInstance().getTableInfoModules(), null, null, context, true, false, false); assertTrue(existing.supportsGetExistingRecord()); return existing; } diff --git a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java index c075406d2ae..2d557201d67 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -190,7 +190,8 @@ public DataIterator getDataIterator(DataIteratorContext context) return LoggingDataIterator.wrap(new BeforeIterator(di, context, Set.of())); // Rows routed to update get the whole existing row as oldRow - di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, _target instanceof ExpTable, routeMerge).getDataIterator(context); + // A routing-only lookup leaves blank and duplicate keys unmatched, so the import reports them as it would without triggers + di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, _target instanceof ExpTable, routeMerge, routingOnlyLookup).getDataIterator(context); DataIterator before = new BeforeIterator(new CachingDataIterator(di), context, carryForwardColumns); if (routingOnlyLookup) before = new HiddenExistingRecordDataIterator(before); diff --git a/experiment/src/org/labkey/experiment/ExpDataIterators.java b/experiment/src/org/labkey/experiment/ExpDataIterators.java index bae8f826511..abf3e631148 100644 --- a/experiment/src/org/labkey/experiment/ExpDataIterators.java +++ b/experiment/src/org/labkey/experiment/ExpDataIterators.java @@ -2420,7 +2420,7 @@ private DataIterator build(DataIterator input, DataIteratorContext context) // Since we support detailed audit logging, add the ExistingRecordDataIterator here just before TableInsertDataIterator. // This is a NOOP unless we are merging/updating and detailed logging is enabled - DataIteratorBuilder dib = ExistingRecordDataIterator.createBuilder(step1, _expTable, keyColumns, _expTable.getExistingRecordSharedKeyColumnNames(), true); + DataIteratorBuilder dib = ExistingRecordDataIterator.createBuilder(step1, _expTable, keyColumns, _expTable.getExistingRecordSharedKeyColumnNames(), true, false, false); if (isSample) { diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index 54dd1bf0dce..b3858c97919 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -2047,5 +2047,58 @@ public void replaceKeepsInsertManagedColumnOnUpdatedRows() throws Exception assertEquals("REPLACE nulled a trigger-managed column", "x", getRow(11).get(TEXT_FIELD)); assertEquals("computed", getRow(12).get(TEXT_FIELD)); } + + /** Rows writing the int field, one per key; a null key is a row with a blank key */ + private static List> rowsWithKeys(Integer... keys) + { + List> rows = new ArrayList<>(); + for (Integer key : keys) + { + Map row = new CaseInsensitiveHashMap<>(); + row.put(KEY_NAME, key); + row.put(INT_FIELD, 2); + rows.add(row); + } + return rows; + } + + /** Merges the rows and returns the row error message, or the exception if MERGE threw */ + private String mergeOutcome(TableInfo table, List> rows) + { + BatchValidationException errors = new BatchValidationException(); + DataIteratorContext context = new DataIteratorContext(errors); + context.setInsertOption(InsertOption.MERGE); + try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) + { + updateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); + } + catch (Exception e) + { + return "threw " + e; + } + assertTrue("Expected a row error", errors.hasErrors()); + // ValidatorIterator leaves an empty error on a later row whose field error it already reported, depending on read-ahead + return errors.getRowErrors().stream().filter(ValidationException::hasErrors).map(ValidationException::getMessage).collect(Collectors.joining("\n")); + } + + record InvalidKeyCase(String name, List> rows, boolean rowError) {} + + // A routing-only lookup must leave these to the import, which handles them the same way with or without triggers + @Test + public void mergeWithRoutedTriggerReportsInvalidKeys() + { + for (InvalidKeyCase c : List.of( + new InvalidKeyCase("one blank key", rowsWithKeys(13, null, 14), true), + new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15), true), + new InvalidKeyCase("every key blank", rowsWithKeys(null, null), true), + // Throws without triggers too + new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2)), false))) + { + String withoutTrigger = mergeOutcome(listTable(), c.rows()); + String withTrigger = mergeOutcome(tableWithTrigger(new RecordingTrigger(true, false)), c.rows()); + assertEquals(c.name(), withoutTrigger, withTrigger); + assertEquals(c.name() + ": " + withoutTrigger, c.rowError(), !withoutTrigger.startsWith("threw ")); + } + } } } diff --git a/study/src/org/labkey/study/query/DatasetTableImpl.java b/study/src/org/labkey/study/query/DatasetTableImpl.java index 0f6cb3ae934..59c068d1c88 100644 --- a/study/src/org/labkey/study/query/DatasetTableImpl.java +++ b/study/src/org/labkey/study/query/DatasetTableImpl.java @@ -647,7 +647,11 @@ public Dataset getDataset() Integer dateIndex = DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn("Date")); String keyName = _dsd.getKeyPropertyName(); Integer keyIndex = keyName == null ? null : DatasetDataIteratorBuilder.findColumnInMap(inputMap, getColumn(keyName)); - Integer containerIndex = inputMap.get("Container"); + // Import honors a supplied Container only in this case, so the LSID must too + Integer suppliedContainerIndex = inputMap.get("Container"); + boolean targetMultiple = Boolean.TRUE == context.getConfigParameters().get(QueryUpdateService.ConfigParameters.TargetMultipleContainers); + JdbcType containerType = suppliedContainerIndex == null ? null : input.getColumnInfo(suppliedContainerIndex).getJdbcType(); + Integer containerIndex = study.isDataspaceStudy() && targetMultiple && (JdbcType.GUID == containerType || JdbcType.VARCHAR == containerType) ? suppliedContainerIndex : null; if (ptidIndex == null) return null; diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index dc2fb82b797..d3434be4b53 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -1111,18 +1111,13 @@ public void updateRowTest() throws Exception map.get("lsid"); } - /** GH Issue 1048: MERGE keeps omitted columns, and triggers that route MERGE see existing rows as updates */ - @Test - public void mergeRoutesExistingRowsToUpdateHooks() throws Exception + /** A table whose trigger routes MERGE by existing record and records which hook saw each subject */ + private TableInfo tableWithRoutedTrigger(List events) { - createDataset(); - insertS1(); - UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); assertNotNull(schema); AbstractTableInfo table = (AbstractTableInfo) schema.getTable(DATASET_NAME, null, true, true); assertNotNull(table); - List events = new ArrayList<>(); table.addTriggerFactory((_, _, _) -> List.of(new Trigger() { @Override @@ -1164,12 +1159,24 @@ public void afterUpdate(TableInfo t, Container c, User user, @Nullable Map events = new ArrayList<>(); + TableInfo table = tableWithRoutedTrigger(events); QueryUpdateService qus = table.getUpdateService(); assertNotNull(qus); BatchValidationException errors = new BatchValidationException(); List> rows = List.of( - Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Value1", "2.0"), + // Import ignores a supplied Container outside a dataspace study, so routing must too + Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Value1", "2.0", "Container", _container.getPath()), Map.of(SUBJECT_COLUMN_NAME, "S2", "SequenceNum", "1.2345", "Value1", "2.0")); int count = qus.mergeRows(_user, _container, MapDataIterator.of(rows), errors, null, null); if (errors.hasErrors()) @@ -1186,6 +1193,51 @@ public void afterUpdate(TableInfo t, Container c, User user, @Nullable Map> rows) + { + QueryUpdateService qus = table.getUpdateService(); + assertNotNull(qus); + BatchValidationException errors = new BatchValidationException(); + try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) + { + qus.mergeRows(_user, _container, MapDataIterator.of(rows), errors, null, null); + } + catch (Exception e) + { + return "threw " + e; + } + assertTrue("Expected a row error", errors.hasErrors()); + return errors.getMessage(); + } + + record UnkeyableCase(String name, Map row, boolean rowError) {} + + // Rows the routing lookup can't key must reach the import, which handles them the same way with or without triggers + @Test + public void mergeWithRoutedTriggerReportsUnkeyableRows() throws Exception + { + createDataset(); + insertS1(); + + UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); + assertNotNull(schema); + for (UnkeyableCase c : List.of( + new UnkeyableCase("no subject column", Map.of("SequenceNum", "1.2345", "Value1", "2.0"), true), + new UnkeyableCase("no SequenceNum or Date column", Map.of(SUBJECT_COLUMN_NAME, "S1", "Value1", "2.0"), true), + new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0"), true), + // Throws without triggers too + new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0"), false))) + { + String withoutTrigger = mergeOutcome(schema.getTable(DATASET_NAME), List.of(c.row())); + List events = new ArrayList<>(); + String withTrigger = mergeOutcome(tableWithRoutedTrigger(events), List.of(c.row())); + assertEquals(c.name(), withoutTrigger, withTrigger); + assertEquals(c.name() + ": " + withoutTrigger, c.rowError(), !withoutTrigger.startsWith("threw ")); + assertFalse(c.name() + ": an unkeyable row was routed to update: " + events, events.stream().anyMatch(e -> e.startsWith("beforeUpdate"))); + } + } + private void insertS1() throws Exception { UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); From d34e40dbc13c25bddd6667f7534a208c0cfef9e9 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 27 Nov 2026 08:20:34 -0800 Subject: [PATCH 4/7] Test simplification and error reporting improvements --- .../api/data/triggers/RecordingTrigger.java | 114 +++++++++++ .../ExistingRecordDataIterator.java | 2 +- .../api/query/QueryUpdateServiceTestUtil.java | 15 ++ .../experiment/api/SampleMergeTestCase.java | 125 ++---------- .../list/model/ListQueryUpdateService.java | 187 +++++------------- .../study/model/SequenceNumImportHelper.java | 3 + .../study/query/DatasetUpdateService.java | 115 +++-------- 7 files changed, 230 insertions(+), 331 deletions(-) create mode 100644 api/src/org/labkey/api/data/triggers/RecordingTrigger.java diff --git a/api/src/org/labkey/api/data/triggers/RecordingTrigger.java b/api/src/org/labkey/api/data/triggers/RecordingTrigger.java new file mode 100644 index 00000000000..66dc30259c9 --- /dev/null +++ b/api/src/org/labkey/api/data/triggers/RecordingTrigger.java @@ -0,0 +1,114 @@ +/* + * 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.api.data.triggers; + +import org.jetbrains.annotations.Nullable; +import org.labkey.api.collections.CaseInsensitiveHashMap; +import org.labkey.api.data.Container; +import org.labkey.api.data.TableInfo; +import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.ValidationException; +import org.labkey.api.security.User; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** Test trigger that records which row hook saw each row, e.g. "beforeUpdate 3 old x" */ +public class RecordingTrigger implements Trigger +{ + public static final String COMPUTED = "computed"; + + private final List _events = new ArrayList<>(); + private final String _idColumn; + private final List _oldColumns; + private final boolean _routed; + private final @Nullable String _insertManagedColumn; + + /** + * @param oldColumns oldRow values to record on beforeUpdate + * @param insertManagedColumn declared managed and set to {@link #COMPUTED} on insert, if not null + */ + public RecordingTrigger(String idColumn, List oldColumns, boolean routed, @Nullable String insertManagedColumn) + { + _idColumn = idColumn; + _oldColumns = oldColumns; + _routed = routed; + _insertManagedColumn = insertManagedColumn; + } + + public List getRecorded() + { + return _events; + } + + /** Rows are batched, so hooks for different rows may interleave */ + public void assertEvents(String... expected) + { + assertEquals(Set.of(expected), Set.copyOf(_events)); + assertEquals(expected.length, _events.size()); + } + + @Override + public boolean isMergeRoutedByExistingRecord() + { + return _routed; + } + + @Override + public @Nullable ManagedColumns getManagedColumns() + { + return _insertManagedColumn == null ? null : new ManagedColumns(Set.of(_insertManagedColumn), Set.of(), null); + } + + @Override + public void beforeInsert(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + _events.add("beforeInsert " + newRow.get(_idColumn)); + if (_insertManagedColumn != null) + newRow.put(_insertManagedColumn, COMPUTED); + } + + @Override + public void beforeUpdate(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + Map old = new CaseInsensitiveHashMap<>(oldRow); + _events.add("beforeUpdate " + newRow.get(_idColumn) + " old " + _oldColumns.stream().map(col -> String.valueOf(old.get(col))).collect(Collectors.joining(" "))); + } + + @Override + public void afterInsert(TableInfo table, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + _events.add("afterInsert " + newRow.get(_idColumn)); + } + + @Override + public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + _events.add("afterUpdate " + newRow.get(_idColumn)); + } +} diff --git a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java index 7a6d8d91e3f..64343972150 100644 --- a/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java @@ -148,7 +148,7 @@ public abstract class ExistingRecordDataIterator extends WrapperDataIterator } if (pkColumns.isEmpty()) - throw new IllegalArgumentException("At least one key column is required."); + context.getErrors().addRowError(new ValidationException("At least one key column is required: " + StringUtils.join(keyNames, ", "))); } @Override diff --git a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java index 4f84358d8ae..40e570a8577 100644 --- a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java +++ b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java @@ -16,8 +16,11 @@ package org.labkey.api.query; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.Container; import org.labkey.api.data.TableInfo; +import org.labkey.api.data.triggers.Trigger; import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.security.User; @@ -46,6 +49,18 @@ public class QueryUpdateServiceTestUtil return table; } + /** Cached tables are locked, so pass one built for write, e.g. {@code schema.getTable(name, null, true, true)} */ + public static @NotNull TableInfo withTrigger(@Nullable TableInfo writable, Container c, Trigger trigger) + { + if (!(writable instanceof AbstractTableInfo table)) + throw new IllegalArgumentException("Can't attach a trigger to " + writable); + table.addTriggerFactory((_, _, _) -> List.of(trigger)); + table.resetTriggers(c); + if (!table.hasTriggers(c)) + throw new IllegalStateException("Trigger not attached to " + table.getName()); + return table; + } + public static List> insert(TableInfo table, User user, Container c, List> rows) throws Exception { BatchValidationException errors = new BatchValidationException(); diff --git a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java index f928549a9bf..b8889424a08 100644 --- a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java +++ b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java @@ -15,38 +15,32 @@ */ package org.labkey.experiment.api; -import org.jetbrains.annotations.Nullable; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.labkey.api.collections.CaseInsensitiveHashMap; -import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.Container; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; +import org.labkey.api.data.triggers.RecordingTrigger; import org.labkey.api.data.triggers.Trigger; -import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.exp.api.ExpSampleType; -import org.labkey.api.exp.api.SampleTypeService; +import org.labkey.api.exp.api.SampleTypeTestHelper; import org.labkey.api.exp.query.SamplesSchema; import org.labkey.api.gwt.client.model.GWTPropertyDescriptor; -import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryService; -import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; import org.labkey.api.query.UserSchema; -import org.labkey.api.query.ValidationException; import org.labkey.api.security.User; import org.labkey.api.util.JunitUtil; import org.labkey.api.util.TestContext; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Set; /** GH Issue 1048: MERGE must leave sample columns the input omits unchanged, and script triggers see existing samples as updates. */ public class SampleMergeTestCase extends Assert @@ -75,8 +69,7 @@ public static void tearDown() public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception { ExpSampleType st = createSampleType("MergeNoTrigger"); - insertSample(st); - mergeIntField(table(st, null), "S-1"); + mergeIntField(SampleTypeTestHelper.getTable(_c, _user, st), "S-1"); assertOmittedFieldKept(st); } @@ -84,8 +77,7 @@ public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception public void mergeWithTriggerKeepsOmittedColumns() throws Exception { ExpSampleType st = createSampleType("MergeTrigger"); - insertSample(st); - mergeIntField(table(st, new Trigger() {}), "S-1"); + mergeIntField(tableWithTrigger(st, new Trigger() {}), "S-1"); assertOmittedFieldKept(st); } @@ -93,105 +85,27 @@ public void mergeWithTriggerKeepsOmittedColumns() throws Exception public void mergeRoutesExistingSamplesToUpdateHooks() throws Exception { ExpSampleType st = createSampleType("MergeRouted"); - insertSample(st); - RecordingTrigger trigger = new RecordingTrigger(); - mergeIntField(table(st, trigger), "S-1", "S-2"); + RecordingTrigger trigger = new RecordingTrigger("name", List.of(TEXT_FIELD), true, TEXT_FIELD); + mergeIntField(tableWithTrigger(st, trigger), "S-1", "S-2"); - assertEquals(Set.of("beforeUpdate S-1 old x", "beforeInsert S-2", "afterUpdate S-1", "afterInsert S-2"), Set.copyOf(trigger.events)); - assertEquals(4, trigger.events.size()); + trigger.assertEvents("beforeUpdate S-1 old x", "beforeInsert S-2", "afterUpdate S-1", "afterInsert S-2"); assertOmittedFieldKept(st); - assertEquals("computed", getSample(st, "S-2").get(TEXT_FIELD)); - } - - /** Opts into MERGE routing and manages the text field on insert */ - private static class RecordingTrigger implements Trigger - { - final List events = new ArrayList<>(); - - @Override - public boolean isMergeRoutedByExistingRecord() - { - return true; - } - - @Override - public @Nullable ManagedColumns getManagedColumns() - { - return new ManagedColumns(Set.of(TEXT_FIELD), Set.of(), null); - } - - @Override - public void beforeInsert(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("beforeInsert " + newRow.get("name")); - newRow.put(TEXT_FIELD, "computed"); - } - - @Override - public void beforeUpdate(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - events.add("beforeUpdate " + newRow.get("name") + " old " + new CaseInsensitiveHashMap<>(oldRow).get(TEXT_FIELD)); - } - - @Override - public void afterInsert(TableInfo table, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("afterInsert " + newRow.get("name")); - } - - @Override - public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - events.add("afterUpdate " + newRow.get("name")); - } + assertEquals(RecordingTrigger.COMPUTED, getSample(st, "S-2").get(TEXT_FIELD)); } + /** Creates the sample type with sample S-1 */ private ExpSampleType createSampleType(String name) throws Exception { - List props = List.of( - new GWTPropertyDescriptor("name", "string"), - new GWTPropertyDescriptor(INT_FIELD, "int"), - new GWTPropertyDescriptor(TEXT_FIELD, "string")); - return SampleTypeService.get().createSampleType(_c, _user, name, null, props, Collections.emptyList(), -1, -1, -1, -1, null); + ExpSampleType st = SampleTypeTestHelper.create(_c, _user, name, new GWTPropertyDescriptor(INT_FIELD, "int"), new GWTPropertyDescriptor(TEXT_FIELD, "string")); + SampleTypeTestHelper.insert(_c, _user, st, List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 1, TEXT_FIELD, "x"))); + return st; } - /** Cached tables are locked, so only one built for write accepts another trigger factory */ - private TableInfo table(ExpSampleType st, @Nullable Trigger trigger) + private TableInfo tableWithTrigger(ExpSampleType st, Trigger trigger) { UserSchema schema = QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME); assertNotNull(schema); - TableInfo table = schema.getTable(st.getName(), null, true, trigger != null); - assertNotNull(table); - if (trigger != null) - { - AbstractTableInfo writable = (AbstractTableInfo) table; - writable.addTriggerFactory((_, _, _) -> List.of(trigger)); - writable.resetTriggers(_c); - assertTrue(writable.hasTriggers(_c)); - } - - return table; - } - - private QueryUpdateService updateService(TableInfo table) - { - QueryUpdateService qus = table.getUpdateService(); - assertNotNull(qus); - return qus; - } - - private void insertSample(ExpSampleType st) throws Exception - { - BatchValidationException errors = new BatchValidationException(); - updateService(table(st, null)).insertRows(_user, _c, List.of(CaseInsensitiveHashMap.of("name", "S-1", INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); - if (errors.hasErrors()) - throw errors; + return QueryUpdateServiceTestUtil.withTrigger(schema.getTable(st.getName(), null, true, true), _c, trigger); } /** Writes the int field only, for each sample name */ @@ -200,17 +114,12 @@ private void mergeIntField(TableInfo table, String... names) throws Exception List> rows = new ArrayList<>(); for (String name : names) rows.add(CaseInsensitiveHashMap.of("name", name, INT_FIELD, 2)); - - BatchValidationException errors = new BatchValidationException(); - int count = updateService(table).mergeRows(_user, _c, MapDataIterator.of(rows), errors, null, null); - if (errors.hasErrors()) - throw errors; - assertEquals(names.length, count); + assertEquals(names.length, QueryUpdateServiceTestUtil.merge(table, _user, _c, rows)); } private Map getSample(ExpSampleType st, String name) { - Map row = new TableSelector(table(st, null), new SimpleFilter(FieldKey.fromParts("name"), name), null).getMap(); + Map row = new TableSelector(SampleTypeTestHelper.getTable(_c, _user, st), new SimpleFilter(FieldKey.fromParts("name"), name), null).getMap(); assertNotNull(row); return row; } diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index b3858c97919..bd58e7515bc 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -47,6 +47,7 @@ import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; import org.labkey.api.data.WorkbookContainerType; +import org.labkey.api.data.triggers.RecordingTrigger; import org.labkey.api.data.triggers.Trigger; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; @@ -98,6 +99,7 @@ import org.labkey.api.usageMetrics.ExperimentMetricArea; import org.labkey.api.usageMetrics.SimpleMetricsService; import org.labkey.api.util.GUID; +import org.labkey.api.util.JunitUtil; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.Pair; import org.labkey.api.util.StringUtilsLabKey; @@ -1272,13 +1274,23 @@ abstract static class ListTestSupport extends Assert /** A list with an auto-increment key and one string field */ static ListDefinition createList(Container c, User user, String listName) throws Exception { - ListDefinition list = ListService.get().createList(c, listName, ListDefinition.KeyType.AutoIncrementInteger); + return createList(c, user, listName, ListDefinition.KeyType.AutoIncrementInteger, Map.of(VALUE_FIELD, PropertyType.STRING)); + } + + static ListDefinition createList(Container c, User user, String listName, ListDefinition.KeyType keyType, Map fields) throws Exception + { + ListDefinition list = ListService.get().createList(c, listName, keyType); list.setKeyName(KEY_NAME); - DomainProperty dp = list.getDomain().addProperty(); - dp.setName(VALUE_FIELD); - dp.setType(PropertyService.get().getType(c, PropertyType.STRING.getXmlName())); - dp.setPropertyURI(ListDomainKind.createPropertyURI(listName, VALUE_FIELD, c, list.getKeyType()).toString()); + Domain domain = list.getDomain(); + assertNotNull(domain); + for (Map.Entry field : fields.entrySet()) + { + DomainProperty dp = domain.addProperty(); + dp.setName(field.getKey()); + dp.setType(PropertyService.get().getType(c, field.getValue().getXmlName())); + dp.setPropertyURI(ListDomainKind.createPropertyURI(listName, field.getKey(), c, list.getKeyType()).toString()); + } list.save(user); return list; @@ -1782,11 +1794,9 @@ public void updatesRowsInWorkbookInPlace() throws Exception /** GH Issue 1048: MERGE must leave columns the input omits unchanged, and script triggers see existing rows as updates. */ @TestTimeout(TestTimeout.DEFAULT * 5) - public static class MergeTestCase extends Assert + public static class MergeTestCase extends ListTestSupport { - private static final String PROJECT_NAME = "ListMergeTest Project"; private static final String LIST_NAME = "Merge list"; - private static final String KEY_NAME = "Key"; private static final String INT_FIELD = "A"; private static final String TEXT_FIELD = "B"; @@ -1798,25 +1808,9 @@ public static class MergeTestCase extends Assert public static void setup() throws Exception { _user = TestContext.get().getUser(); - - deleteTestContainer(); - _container = ContainerManager.ensureContainer(PROJECT_NAME, _user); - - _list = ListService.get().createList(_container, LIST_NAME, ListDefinition.KeyType.Integer); - _list.setKeyName(KEY_NAME); - addField(INT_FIELD, PropertyType.INTEGER); - addField(TEXT_FIELD, PropertyType.STRING); - _list.save(_user); - } - - private static void addField(String name, PropertyType type) - { - Domain domain = _list.getDomain(); - assertNotNull(domain); - DomainProperty dp = domain.addProperty(); - dp.setName(name); - dp.setType(PropertyService.get().getType(_container, type.getXmlName())); - dp.setPropertyURI(ListDomainKind.createPropertyURI(LIST_NAME, name, _container, _list.getKeyType()).toString()); + JunitUtil.deleteTestContainer(); + _container = JunitUtil.getTestContainer(); + _list = createList(_container, _user, LIST_NAME, ListDefinition.KeyType.Integer, Map.of(INT_FIELD, PropertyType.INTEGER, TEXT_FIELD, PropertyType.STRING)); } @AfterClass @@ -1826,85 +1820,18 @@ public static void cleanup() _container = null; _user = null; - deleteTestContainer(); - } - - private static void deleteTestContainer() - { - Container project = ContainerManager.getForPath(PROJECT_NAME); - - if (null != project) - ContainerManager.deleteAll(project, TestContext.get().getUser()); + JunitUtil.deleteTestContainer(); } - /** Cached tables are locked, so only one built for write accepts another trigger factory */ private TableInfo tableWithTrigger(Trigger trigger) { - AbstractTableInfo table = (AbstractTableInfo) new ListQuerySchema(_user, _container).getTable(LIST_NAME, null, true, true); - assertNotNull(table); - table.addTriggerFactory((_, _, _) -> List.of(trigger)); - table.resetTriggers(_container); - assertTrue(table.hasTriggers(_container)); - - return table; + return QueryUpdateServiceTestUtil.withTrigger(new ListQuerySchema(_user, _container).getTable(LIST_NAME, null, true, true), _container, trigger); } - /** Records which hook saw each key; sets the text field on insert when it manages that column */ - private static class RecordingTrigger implements Trigger + /** Sets the text field on insert when it manages that column */ + private static RecordingTrigger recordingTrigger(boolean routed, boolean managesText) { - final List events = new ArrayList<>(); - final boolean _routed; - final boolean _managesText; - - RecordingTrigger(boolean routed, boolean managesText) - { - _routed = routed; - _managesText = managesText; - } - - @Override - public boolean isMergeRoutedByExistingRecord() - { - return _routed; - } - - @Override - public @Nullable ManagedColumns getManagedColumns() - { - return _managesText ? new ManagedColumns(Set.of(TEXT_FIELD), Set.of(), null) : null; - } - - @Override - public void beforeInsert(TableInfo table, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("beforeInsert " + newRow.get(KEY_NAME)); - if (_managesText) - newRow.put(TEXT_FIELD, "computed"); - } - - @Override - public void beforeUpdate(TableInfo table, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - events.add("beforeUpdate " + newRow.get(KEY_NAME) + " old " + new CaseInsensitiveHashMap<>(oldRow).get(TEXT_FIELD)); - } - - @Override - public void afterInsert(TableInfo table, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("afterInsert " + newRow.get(KEY_NAME)); - } - - @Override - public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - events.add("afterUpdate " + newRow.get(KEY_NAME)); - } + return new RecordingTrigger(KEY_NAME, List.of(TEXT_FIELD), routed, managesText ? TEXT_FIELD : null); } private TableInfo listTable() @@ -1914,19 +1841,9 @@ private TableInfo listTable() return table; } - private QueryUpdateService updateService(TableInfo table) - { - QueryUpdateService qus = table.getUpdateService(); - assertNotNull(qus); - return qus; - } - private void insertRow(int key) throws Exception { - BatchValidationException errors = new BatchValidationException(); - updateService(listTable()).insertRows(_user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x")), errors, null, null); - if (errors.hasErrors()) - throw errors; + QueryUpdateServiceTestUtil.insert(listTable(), _user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x"))); } private void mergeIntField(TableInfo table, int... keys) throws Exception @@ -1946,7 +1863,7 @@ private void load(TableInfo table, InsertOption option, int... keys) throws Exce context.setInsertOption(option); try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) { - int count = updateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); + int count = QueryUpdateServiceTestUtil.getUpdateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); if (errors.hasErrors()) throw errors; assertEquals(keys.length, count); @@ -1954,13 +1871,6 @@ private void load(TableInfo table, InsertOption option, int... keys) throws Exce } } - /** Rows are batched, so hooks for different rows may interleave */ - private void assertEvents(RecordingTrigger trigger, String... expected) - { - assertEquals(Set.of(expected), Set.copyOf(trigger.events)); - assertEquals(expected.length, trigger.events.size()); - } - private Map getRow(int key) { Map row = new TableSelector(listTable(), new SimpleFilter(FieldKey.fromParts(KEY_NAME), key), null).getMap(); @@ -1995,10 +1905,10 @@ public void mergeWithTriggerKeepsOmittedColumns() throws Exception public void mergeRoutesExistingRowsToUpdateHooks() throws Exception { insertRow(3); - RecordingTrigger trigger = new RecordingTrigger(true, false); + RecordingTrigger trigger = recordingTrigger(true, false); mergeIntField(tableWithTrigger(trigger), 3, 4); - assertEvents(trigger, "beforeUpdate 3 old x", "beforeInsert 4", "afterUpdate 3", "afterInsert 4"); + trigger.assertEvents("beforeUpdate 3 old x", "beforeInsert 4", "afterUpdate 3", "afterInsert 4"); assertOmittedFieldKept(3); } @@ -2006,10 +1916,10 @@ public void mergeRoutesExistingRowsToUpdateHooks() throws Exception public void mergeWithoutRoutingFiresInsertHooks() throws Exception { insertRow(5); - RecordingTrigger trigger = new RecordingTrigger(false, false); + RecordingTrigger trigger = recordingTrigger(false, false); mergeIntField(tableWithTrigger(trigger), 5, 6); - assertEvents(trigger, "beforeInsert 5", "beforeInsert 6", "afterInsert 5", "afterInsert 6"); + trigger.assertEvents("beforeInsert 5", "beforeInsert 6", "afterInsert 5", "afterInsert 6"); assertOmittedFieldKept(5); } @@ -2017,22 +1927,22 @@ public void mergeWithoutRoutingFiresInsertHooks() throws Exception public void mergeKeepsInsertManagedColumnOnUpdatedRows() throws Exception { insertRow(7); - RecordingTrigger trigger = new RecordingTrigger(true, true); + RecordingTrigger trigger = recordingTrigger(true, true); mergeIntField(tableWithTrigger(trigger), 7, 8); - assertEvents(trigger, "beforeUpdate 7 old x", "beforeInsert 8", "afterUpdate 7", "afterInsert 8"); + trigger.assertEvents("beforeUpdate 7 old x", "beforeInsert 8", "afterUpdate 7", "afterInsert 8"); assertOmittedFieldKept(7); - assertEquals("computed", getRow(8).get(TEXT_FIELD)); + assertEquals(RecordingTrigger.COMPUTED, getRow(8).get(TEXT_FIELD)); } @Test public void replaceRoutesExistingRowsToUpdateHooks() throws Exception { insertRow(9); - RecordingTrigger trigger = new RecordingTrigger(true, false); + RecordingTrigger trigger = recordingTrigger(true, false); load(tableWithTrigger(trigger), InsertOption.REPLACE, 9, 10); - assertEvents(trigger, "beforeUpdate 9 old x", "beforeInsert 10", "afterUpdate 9", "afterInsert 10"); + trigger.assertEvents("beforeUpdate 9 old x", "beforeInsert 10", "afterUpdate 9", "afterInsert 10"); assertNull("REPLACE keeps a column it was not given", getRow(9).get(TEXT_FIELD)); } @@ -2040,12 +1950,12 @@ public void replaceRoutesExistingRowsToUpdateHooks() throws Exception public void replaceKeepsInsertManagedColumnOnUpdatedRows() throws Exception { insertRow(11); - RecordingTrigger trigger = new RecordingTrigger(true, true); + RecordingTrigger trigger = recordingTrigger(true, true); load(tableWithTrigger(trigger), InsertOption.REPLACE, 11, 12); - assertEvents(trigger, "beforeUpdate 11 old x", "beforeInsert 12", "afterUpdate 11", "afterInsert 12"); + trigger.assertEvents("beforeUpdate 11 old x", "beforeInsert 12", "afterUpdate 11", "afterInsert 12"); assertEquals("REPLACE nulled a trigger-managed column", "x", getRow(11).get(TEXT_FIELD)); - assertEquals("computed", getRow(12).get(TEXT_FIELD)); + assertEquals(RecordingTrigger.COMPUTED, getRow(12).get(TEXT_FIELD)); } /** Rows writing the int field, one per key; a null key is a row with a blank key */ @@ -2070,7 +1980,7 @@ private String mergeOutcome(TableInfo table, List> rows) context.setInsertOption(InsertOption.MERGE); try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) { - updateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); + QueryUpdateServiceTestUtil.getUpdateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); } catch (Exception e) { @@ -2081,23 +1991,22 @@ private String mergeOutcome(TableInfo table, List> rows) return errors.getRowErrors().stream().filter(ValidationException::hasErrors).map(ValidationException::getMessage).collect(Collectors.joining("\n")); } - record InvalidKeyCase(String name, List> rows, boolean rowError) {} + record InvalidKeyCase(String name, List> rows) {} // A routing-only lookup must leave these to the import, which handles them the same way with or without triggers @Test public void mergeWithRoutedTriggerReportsInvalidKeys() { for (InvalidKeyCase c : List.of( - new InvalidKeyCase("one blank key", rowsWithKeys(13, null, 14), true), - new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15), true), - new InvalidKeyCase("every key blank", rowsWithKeys(null, null), true), - // Throws without triggers too - new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2)), false))) + new InvalidKeyCase("one blank key", rowsWithKeys(13, null, 14)), + new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15)), + new InvalidKeyCase("every key blank", rowsWithKeys(null, null)), + new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2))))) { String withoutTrigger = mergeOutcome(listTable(), c.rows()); - String withTrigger = mergeOutcome(tableWithTrigger(new RecordingTrigger(true, false)), c.rows()); + String withTrigger = mergeOutcome(tableWithTrigger(recordingTrigger(true, false)), c.rows()); assertEquals(c.name(), withoutTrigger, withTrigger); - assertEquals(c.name() + ": " + withoutTrigger, c.rowError(), !withoutTrigger.startsWith("threw ")); + assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); } } } diff --git a/study/src/org/labkey/study/model/SequenceNumImportHelper.java b/study/src/org/labkey/study/model/SequenceNumImportHelper.java index b16fa59b6f4..c441dc3e41c 100644 --- a/study/src/org/labkey/study/model/SequenceNumImportHelper.java +++ b/study/src/org/labkey/study/model/SequenceNumImportHelper.java @@ -112,6 +112,9 @@ public Callable getCallable(@NotNull final DataIterator it, @Nullable fi // DataIterator will catch this and report an error, and we shouldn't usually be getting strings here } Double sequencenum = translateSequenceNum(seq, date); + // Report it here; the LSID and ParticipantSequenceNum columns convert this value before any later converter would + if (null == sequencenum && seq instanceof String s && !StringUtils.isBlank(s)) + throw new ValidationException(ConvertHelper.getStandardConversionErrorMessage(seq, "SequenceNum", Double.class)); return null == sequencenum ? seq : sequencenum; }; } diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index d3434be4b53..bb823b86e1d 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -28,7 +28,6 @@ import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.collections.ResultSetRowMapFactory; -import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.BaseColumnInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; @@ -42,7 +41,7 @@ import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; -import org.labkey.api.data.triggers.Trigger; +import org.labkey.api.data.triggers.RecordingTrigger; import org.labkey.api.dataiterator.DataIterator; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; @@ -62,6 +61,8 @@ import org.labkey.api.query.QueryService; import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; +import org.labkey.api.query.QueryUpdateServiceTestUtil; +import org.labkey.api.query.SchemaKey; import org.labkey.api.query.SimpleValidationError; import org.labkey.api.query.UserSchema; import org.labkey.api.query.ValidationException; @@ -1111,55 +1112,23 @@ public void updateRowTest() throws Exception map.get("lsid"); } - /** A table whose trigger routes MERGE by existing record and records which hook saw each subject */ - private TableInfo tableWithRoutedTrigger(List events) + private UserSchema studySchema() { UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); assertNotNull(schema); - AbstractTableInfo table = (AbstractTableInfo) schema.getTable(DATASET_NAME, null, true, true); - assertNotNull(table); - table.addTriggerFactory((_, _, _) -> List.of(new Trigger() - { - @Override - public boolean isMergeRoutedByExistingRecord() - { - return true; - } - - @Override - public void beforeInsert(TableInfo t, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("beforeInsert " + newRow.get(SUBJECT_COLUMN_NAME)); - } - - @Override - public void beforeUpdate(TableInfo t, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - // oldRow uses query column names, as in updateRows(), not storage names like participantid - Map old = new CaseInsensitiveHashMap<>(oldRow); - events.add("beforeUpdate " + newRow.get(SUBJECT_COLUMN_NAME) + " old " + old.get(SUBJECT_COLUMN_NAME) + " " + old.get("Field1")); - } + return schema; + } - @Override - public void afterInsert(TableInfo t, Container c, User user, @Nullable Map newRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - events.add("afterInsert " + newRow.get(SUBJECT_COLUMN_NAME)); - } + /** A table whose trigger routes MERGE by existing record and records which hook saw each subject */ + private TableInfo tableWithRoutedTrigger(RecordingTrigger trigger) + { + return QueryUpdateServiceTestUtil.withTrigger(studySchema().getTable(DATASET_NAME, null, true, true), _container, trigger); + } - @Override - public void afterUpdate(TableInfo t, Container c, User user, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) - { - assertNotNull(newRow); - assertNotNull(oldRow); - events.add("afterUpdate " + newRow.get(SUBJECT_COLUMN_NAME)); - } - })); - table.resetTriggers(_container); - return table; + // oldRow uses query column names, as in updateRows(), not storage names like participantid + private static RecordingTrigger recordingTrigger() + { + return new RecordingTrigger(SUBJECT_COLUMN_NAME, List.of(SUBJECT_COLUMN_NAME, "Field1"), true, null); } /** GH Issue 1048: MERGE keeps omitted columns, and triggers that route MERGE see existing rows as updates */ @@ -1169,23 +1138,14 @@ public void mergeRoutesExistingRowsToUpdateHooks() throws Exception createDataset(); insertS1(); - List events = new ArrayList<>(); - TableInfo table = tableWithRoutedTrigger(events); - QueryUpdateService qus = table.getUpdateService(); - assertNotNull(qus); - BatchValidationException errors = new BatchValidationException(); + RecordingTrigger trigger = recordingTrigger(); + TableInfo table = tableWithRoutedTrigger(trigger); List> rows = List.of( // Import ignores a supplied Container outside a dataspace study, so routing must too Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Value1", "2.0", "Container", _container.getPath()), Map.of(SUBJECT_COLUMN_NAME, "S2", "SequenceNum", "1.2345", "Value1", "2.0")); - int count = qus.mergeRows(_user, _container, MapDataIterator.of(rows), errors, null, null); - if (errors.hasErrors()) - fail(errors.getMessage()); - assertEquals(2, count); - - // Rows are batched, so hooks for different rows may interleave - assertEquals(Set.of("beforeUpdate S1 old S1 x", "beforeInsert S2", "afterUpdate S1", "afterInsert S2"), Set.copyOf(events)); - assertEquals(4, events.size()); + assertEquals(2, QueryUpdateServiceTestUtil.merge(table, _user, _container, rows)); + trigger.assertEvents("beforeUpdate S1 old S1 x", "beforeInsert S2", "afterUpdate S1", "afterInsert S2"); Map s1 = new TableSelector(table, new SimpleFilter(FieldKey.fromParts(SUBJECT_COLUMN_NAME), "S1"), null).getMap(); assertNotNull(s1); @@ -1196,8 +1156,7 @@ public void mergeRoutesExistingRowsToUpdateHooks() throws Exception /** Merges the rows and returns the row error message, or the exception if MERGE threw */ private String mergeOutcome(TableInfo table, List> rows) { - QueryUpdateService qus = table.getUpdateService(); - assertNotNull(qus); + QueryUpdateService qus = QueryUpdateServiceTestUtil.getUpdateService(table); BatchValidationException errors = new BatchValidationException(); try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) { @@ -1211,7 +1170,7 @@ private String mergeOutcome(TableInfo table, List> rows) return errors.getMessage(); } - record UnkeyableCase(String name, Map row, boolean rowError) {} + record UnkeyableCase(String name, Map row) {} // Rows the routing lookup can't key must reach the import, which handles them the same way with or without triggers @Test @@ -1220,36 +1179,26 @@ public void mergeWithRoutedTriggerReportsUnkeyableRows() throws Exception createDataset(); insertS1(); - UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); - assertNotNull(schema); + UserSchema schema = studySchema(); for (UnkeyableCase c : List.of( - new UnkeyableCase("no subject column", Map.of("SequenceNum", "1.2345", "Value1", "2.0"), true), - new UnkeyableCase("no SequenceNum or Date column", Map.of(SUBJECT_COLUMN_NAME, "S1", "Value1", "2.0"), true), - new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0"), true), - // Throws without triggers too - new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0"), false))) + new UnkeyableCase("no subject column", Map.of("SequenceNum", "1.2345", "Value1", "2.0")), + new UnkeyableCase("no SequenceNum or Date column", Map.of(SUBJECT_COLUMN_NAME, "S1", "Value1", "2.0")), + new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0")), + new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0")))) { String withoutTrigger = mergeOutcome(schema.getTable(DATASET_NAME), List.of(c.row())); - List events = new ArrayList<>(); - String withTrigger = mergeOutcome(tableWithRoutedTrigger(events), List.of(c.row())); + RecordingTrigger trigger = recordingTrigger(); + String withTrigger = mergeOutcome(tableWithRoutedTrigger(trigger), List.of(c.row())); assertEquals(c.name(), withoutTrigger, withTrigger); - assertEquals(c.name() + ": " + withoutTrigger, c.rowError(), !withoutTrigger.startsWith("threw ")); - assertFalse(c.name() + ": an unkeyable row was routed to update: " + events, events.stream().anyMatch(e -> e.startsWith("beforeUpdate"))); + assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); + assertFalse(c.name() + ": an unkeyable row was routed to update: " + trigger.getRecorded(), trigger.getRecorded().stream().anyMatch(e -> e.startsWith("beforeUpdate"))); } } private void insertS1() throws Exception { - UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); - assertNotNull(schema); - TableInfo t = schema.getTable(DATASET_NAME); - assertNotNull(t); - QueryUpdateService qus = t.getUpdateService(); - assertNotNull(qus); - BatchValidationException errors = new BatchValidationException(); - qus.insertRows(_user, _container, List.of(Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Field1", "x", "Value1", "1.0")), errors, null, null); - if (errors.hasErrors()) - fail(errors.getMessage()); + TableInfo t = QueryUpdateServiceTestUtil.getTable(_user, _container, SchemaKey.fromParts(StudyQuerySchema.SCHEMA_NAME), DATASET_NAME); + QueryUpdateServiceTestUtil.insert(t, _user, _container, List.of(Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Field1", "x", "Value1", "1.0"))); } @Before From 66f5e3221c9c4f8c500b362255d20f6658199275 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 27 Nov 2026 17:09:45 -0800 Subject: [PATCH 5/7] Kanban #1794: Keep stored values for columns a merge omits so triggers see the whole row Merge pads omitted columns with each matched row's stored value instead of leaving them out, so existing triggers that fill or copy omitted columns keep working. --- .../labkey/api/data/AbstractTableInfo.java | 24 +++++ .../data/triggers/FillIfMissingTrigger.java | 63 +++++++++++++ .../api/dataiterator/CoerceDataIterator.java | 25 ++++- .../TriggerDataBuilderHelper.java | 42 ++++++--- .../experiment/api/SampleMergeTestCase.java | 17 ++++ .../list/model/ListQueryUpdateService.java | 93 +++++++++++++++++-- .../study/query/DatasetUpdateService.java | 16 ++-- 7 files changed, 249 insertions(+), 31 deletions(-) create mode 100644 api/src/org/labkey/api/data/triggers/FillIfMissingTrigger.java diff --git a/api/src/org/labkey/api/data/AbstractTableInfo.java b/api/src/org/labkey/api/data/AbstractTableInfo.java index 0c3f4383de0..978a285b7c6 100644 --- a/api/src/org/labkey/api/data/AbstractTableInfo.java +++ b/api/src/org/labkey/api/data/AbstractTableInfo.java @@ -95,6 +95,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -2035,6 +2036,7 @@ public void fireRowTrigger( errors.setRowNumber(rowNumber); Collection triggers = getTriggers(c); + Map storedRow = existingRecord == null || existingRecord.isEmpty() ? null : new CaseInsensitiveHashMap<>(existingRecord); // Wrap the row once before the loop DeltaTrackingMap trackedRow = null; @@ -2079,6 +2081,13 @@ public void fireRowTrigger( } } + // Copying a stored value into the row, e.g. oldRow into a MERGE row, changes nothing the write would lose + if (storedRow != null) + { + DeltaTrackingMap row = trackedRow; + added.removeIf(col -> isStoredValue(storedRow, col, row.get(col))); + } + if (!added.isEmpty() || !removed.isEmpty()) { var diffs = new ArrayList(); @@ -2121,6 +2130,21 @@ public void fireRowTrigger( throw errors; } + private static boolean isStoredValue(Map storedRow, String col, Object value) + { + if (!storedRow.containsKey(col)) + return false; + Object stored = storedRow.get(col); + if (Objects.equals(stored, value)) + return true; + // Script triggers hand values back converted, e.g. an integer as a double + if (stored instanceof Number a && value instanceof Number b) + return a.doubleValue() == b.doubleValue(); + if (stored instanceof Date a && value instanceof Date b) + return a.getTime() == b.getTime(); + return false; + } + public void checkLocked() { if (_locked) diff --git a/api/src/org/labkey/api/data/triggers/FillIfMissingTrigger.java b/api/src/org/labkey/api/data/triggers/FillIfMissingTrigger.java new file mode 100644 index 00000000000..d6a33268931 --- /dev/null +++ b/api/src/org/labkey/api/data/triggers/FillIfMissingTrigger.java @@ -0,0 +1,63 @@ +/* + * 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.api.data.triggers; + +import org.jetbrains.annotations.Nullable; +import org.labkey.api.data.Container; +import org.labkey.api.data.TableInfo; +import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.ValidationException; +import org.labkey.api.security.User; + +import java.util.Map; + +import static org.junit.Assert.assertNotNull; + +/** Test trigger that fills a column with no value, like a script's {@code row.X = row.X || 'filled'}, without declaring it managed */ +public record FillIfMissingTrigger(String column, boolean routed, boolean managedColumnsEnabled) implements Trigger +{ + public static final String FILLED = "filled"; + + @Override + public boolean isMergeRoutedByExistingRecord() + { + return routed; + } + + @Override + public boolean isManagedColumnsEnabled() + { + return managedColumnsEnabled; + } + + @Override + public void beforeInsert(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, ValidationException errors, Map extraContext) + { + fill(newRow); + } + + @Override + public void beforeUpdate(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + fill(newRow); + } + + private void fill(@Nullable Map row) + { + assertNotNull(row); + row.putIfAbsent(column, FILLED); + } +} diff --git a/api/src/org/labkey/api/dataiterator/CoerceDataIterator.java b/api/src/org/labkey/api/dataiterator/CoerceDataIterator.java index 3ef08e51604..543a1048d57 100644 --- a/api/src/org/labkey/api/dataiterator/CoerceDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/CoerceDataIterator.java @@ -15,6 +15,7 @@ */ package org.labkey.api.dataiterator; +import org.jetbrains.annotations.Nullable; import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.JdbcType; @@ -24,6 +25,7 @@ import java.util.Map; import java.util.Set; +import java.util.function.Predicate; /** * User: matthewb @@ -37,19 +39,33 @@ */ public class CoerceDataIterator extends SimpleTranslator { + private final Set _paddedColumnNames = new CaseInsensitiveHashSet(); + public CoerceDataIterator(DataIterator source, DataIteratorContext context, TableInfo target) { this(source, context, target, true); } public CoerceDataIterator(DataIterator source, DataIteratorContext context, TableInfo target, boolean outputAllColumns) + { + this(source, context, target, outputAllColumns ? _ -> true : null); + } + + /** @param padColumn which insertable columns the input lacks get a null column, or null to add none */ + public CoerceDataIterator(DataIterator source, DataIteratorContext context, TableInfo target, @Nullable Predicate padColumn) { super(source, context); setDebugName("Coerce before trigger script"); - init(target, context.getInsertOption().useImportAliases, outputAllColumns); + init(target, context.getInsertOption().useImportAliases, padColumn); + } + + /** The null columns added for columns the input lacks */ + public Set getPaddedColumnNames() + { + return _paddedColumnNames; } - void init(TableInfo target, boolean useImportAliases, boolean outputAllColumns) + void init(TableInfo target, boolean useImportAliases, @Nullable Predicate padColumn) { Map targetMap = DataIteratorUtil.createTableMap(target, useImportAliases); Set seen = new CaseInsensitiveHashSet(); @@ -75,16 +91,17 @@ else if (to.isMultiValued() || to.getFk() instanceof MultiValuedForeignKey) addColumn(i); } } - if (outputAllColumns) + if (padColumn != null) { // add null column for all insertable not seen columns for (ColumnInfo to : target.getColumns()) { if (seen.contains(to.getName())) continue; - if (!to.isUserEditable() || to.isAutoIncrement()) + if (!to.isUserEditable() || to.isAutoIncrement() || !padColumn.test(to)) continue; addNullColumn(to.getName(), to.getJdbcType()); + _paddedColumnNames.add(to.getName()); } } } diff --git a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java index 2d557201d67..1e1328773a2 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -21,8 +21,10 @@ import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; +import org.labkey.api.data.MultiValuedForeignKey; import org.labkey.api.data.TableInfo; import org.labkey.api.data.triggers.Trigger; +import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.query.ExpTable; import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.QueryService; @@ -36,6 +38,7 @@ import java.util.Objects; import java.util.Set; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; import static org.labkey.api.util.IntegerUtils.asInteger; @@ -160,24 +163,33 @@ public DataIterator getDataIterator(DataIteratorContext context) sharedKeys = expTable.getExistingRecordSharedKeyColumnNames(); } - // Rows routed to update keep trigger-managed values the input omits, since beforeUpdate may not set them - Set carryForwardColumns = routeMerge ? managedOnlyColumns : Set.of(); - - // GH Issue 1048: null padding would make MERGE overwrite every column the input omitted - boolean padMissingColumns = !option.updateOnly && (!option.mergeRows || option.replace); - di = LoggingDataIterator.wrap(new CoerceDataIterator(di, context, _target, padMissingColumns)); + // GH Issue 1048: MERGE pads omitted columns with each matched row's stored value, so triggers see the whole row and the write leaves those columns unchanged + boolean keepStoredValues = option.mergeRows && !option.replace; + // Stored values of these don't round-trip through import + Predicate padColumn = option.updateOnly ? null : !keepStoredValues ? _ -> true : + col -> !col.isCalculated() && !col.isUnselectable() && !col.isMultiValued() && !(col.getFk() instanceof MultiValuedForeignKey) && + col.getPropertyType() != PropertyType.ATTACHMENT && col.getPropertyType() != PropertyType.FILE_LINK; + CoerceDataIterator coerce = new CoerceDataIterator(di, context, _target, padColumn); + di = LoggingDataIterator.wrap(coerce); context.setWithLookupRemapping(false); - // The import pipeline doesn't expect an existing record from a lookup made only to route triggers - boolean routingOnlyLookup = false; - if (routeMerge && existingRecordKeyColumnNames == null) + // Rows that match an existing record keep its values for trigger-managed and padded columns the input omits + Set carryForwardColumns = new CaseInsensitiveHashSet(); + if (routeMerge || keepStoredValues) + carryForwardColumns.addAll(managedOnlyColumns); + if (keepStoredValues) + carryForwardColumns.addAll(coerce.getPaddedColumnNames()); + + // The import pipeline doesn't expect an existing record from a lookup made only for the triggers + boolean triggerOnlyLookup = false; + if ((routeMerge || !carryForwardColumns.isEmpty()) && existingRecordKeyColumnNames == null) { MergeKeyColumns keys = getMergeKeyColumns(di, context); if (keys != null) { di = keys.input(); existingRecordKeyColumnNames = keys.columnNames(); - routingOnlyLookup = true; + triggerOnlyLookup = true; } } @@ -189,11 +201,12 @@ public DataIterator getDataIterator(DataIteratorContext context) if (option.mergeRows && !_target.supportsInsertOption(QueryUpdateService.InsertOption.MERGE)) return LoggingDataIterator.wrap(new BeforeIterator(di, context, Set.of())); - // Rows routed to update get the whole existing row as oldRow - // A routing-only lookup leaves blank and duplicate keys unmatched, so the import reports them as it would without triggers - di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, _target instanceof ExpTable, routeMerge, routingOnlyLookup).getDataIterator(context); + // Routed rows get the whole existing row as oldRow, and carried-forward columns need their stored values + // A trigger-only lookup leaves blank and duplicate keys unmatched, so the import reports them as it would without triggers + boolean allColumns = routeMerge || !carryForwardColumns.isEmpty(); + di = ExistingRecordDataIterator.createBuilder(di, _target, existingRecordKeyColumnNames, sharedKeys, _target instanceof ExpTable, allColumns, triggerOnlyLookup).getDataIterator(context); DataIterator before = new BeforeIterator(new CachingDataIterator(di), context, carryForwardColumns); - if (routingOnlyLookup) + if (triggerOnlyLookup) before = new HiddenExistingRecordDataIterator(before); return LoggingDataIterator.wrap(before); } @@ -324,6 +337,7 @@ private void carryForward(@Nullable Map existingRecord) Map existing = new CaseInsensitiveHashMap<>(existingRecord); for (String col : _carryForwardColumns) { + assert existing.containsKey(col) : "Existing record lacks " + col + ", so MERGE would null it"; if (existing.containsKey(col)) _currentRow.put(col, existing.get(col)); } diff --git a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java index b8889424a08..3ff2f1f2fd6 100644 --- a/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java +++ b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java @@ -24,6 +24,7 @@ import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; +import org.labkey.api.data.triggers.FillIfMissingTrigger; import org.labkey.api.data.triggers.RecordingTrigger; import org.labkey.api.data.triggers.Trigger; import org.labkey.api.exp.api.ExpSampleType; @@ -93,6 +94,22 @@ public void mergeRoutesExistingSamplesToUpdateHooks() throws Exception assertEquals(RecordingTrigger.COMPUTED, getSample(st, "S-2").get(TEXT_FIELD)); } + @Test + public void mergeLetsTriggersFillOmittedColumns() throws Exception + { + for (boolean routed : List.of(true, false)) + { + for (boolean managedColumnsEnabled : List.of(true, false)) + { + String label = "routed " + routed + ", managed columns enabled " + managedColumnsEnabled; + ExpSampleType st = createSampleType("MergeFill" + routed + managedColumnsEnabled); + mergeIntField(tableWithTrigger(st, new FillIfMissingTrigger(TEXT_FIELD, routed, managedColumnsEnabled)), "S-1", "S-2"); + assertEquals(label + ": existing sample lost its stored value", "x", getSample(st, "S-1").get(TEXT_FIELD)); + assertEquals(label + ": new sample lost the trigger's value", FillIfMissingTrigger.FILLED, getSample(st, "S-2").get(TEXT_FIELD)); + } + } + } + /** Creates the sample type with sample S-1 */ private ExpSampleType createSampleType(String name) throws Exception { diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index bd58e7515bc..039c2b63fd6 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -47,6 +47,7 @@ import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; import org.labkey.api.data.WorkbookContainerType; +import org.labkey.api.data.triggers.FillIfMissingTrigger; import org.labkey.api.data.triggers.RecordingTrigger; import org.labkey.api.data.triggers.Trigger; import org.labkey.api.dataiterator.DataIteratorBuilder; @@ -62,6 +63,7 @@ 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.Lookup; import org.labkey.api.exp.property.PropertyValidatorDef; import org.labkey.api.exp.property.PropertyService; import org.labkey.api.exp.property.ValidatorContext; @@ -77,6 +79,7 @@ import org.labkey.api.query.QueryUpdateService; import org.labkey.api.query.QueryUpdateServiceException; import org.labkey.api.query.QueryUpdateServiceTestUtil; +import org.labkey.api.query.SchemaKey; import org.labkey.api.query.UserSchema; import org.labkey.api.query.ValidationError; import org.labkey.api.query.ValidationException; @@ -113,8 +116,11 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Calendar; import java.util.Collection; import java.util.Collections; +import java.util.Date; +import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -1799,6 +1805,8 @@ public static class MergeTestCase extends ListTestSupport private static final String LIST_NAME = "Merge list"; private static final String INT_FIELD = "A"; private static final String TEXT_FIELD = "B"; + private static final String DATE_FIELD = "C"; + private static final String LOOKUP_FIELD = "D"; private static User _user; private static Container _container; @@ -1810,7 +1818,13 @@ public static void setup() throws Exception _user = TestContext.get().getUser(); JunitUtil.deleteTestContainer(); _container = JunitUtil.getTestContainer(); - _list = createList(_container, _user, LIST_NAME, ListDefinition.KeyType.Integer, Map.of(INT_FIELD, PropertyType.INTEGER, TEXT_FIELD, PropertyType.STRING)); + _list = createList(_container, _user, LIST_NAME, ListDefinition.KeyType.Integer, Map.of(INT_FIELD, PropertyType.INTEGER, TEXT_FIELD, PropertyType.STRING, DATE_FIELD, PropertyType.DATE_TIME, LOOKUP_FIELD, PropertyType.INTEGER)); + Domain domain = _list.getDomain(true); + assertNotNull(domain); + DomainProperty lookup = domain.getPropertyByName(LOOKUP_FIELD); + assertNotNull(lookup); + lookup.setLookup(new Lookup(null, SchemaKey.fromParts("core"), "Users")); + domain.save(_user); } @AfterClass @@ -1958,6 +1972,67 @@ public void replaceKeepsInsertManagedColumnOnUpdatedRows() throws Exception assertEquals(RecordingTrigger.COMPUTED, getRow(12).get(TEXT_FIELD)); } + @Test + public void mergeLetsTriggersFillOmittedColumns() throws Exception + { + int key = 20; + for (boolean routed : List.of(true, false)) + { + for (boolean managedColumnsEnabled : List.of(true, false)) + { + String label = "routed " + routed + ", managed columns enabled " + managedColumnsEnabled; + insertRow(key); + mergeIntField(tableWithTrigger(new FillIfMissingTrigger(TEXT_FIELD, routed, managedColumnsEnabled)), key, key + 1); + assertEquals(label + ": existing row lost its stored value", "x", getRow(key).get(TEXT_FIELD)); + assertEquals(label + ": new row lost the trigger's value", FillIfMissingTrigger.FILLED, getRow(key + 1).get(TEXT_FIELD)); + key += 2; + } + } + } + + /** Copies every stored value the row lacks into it, as some module scripts do to validate the whole row */ + private static class CopyOldRowTrigger implements Trigger + { + @Override + public boolean isMergeRoutedByExistingRecord() + { + return true; + } + + @Override + public void beforeUpdate(TableInfo table, Container c, User user, @Nullable InsertOption insertOption, @Nullable Map newRow, @Nullable Map oldRow, ValidationException errors, Map extraContext) + { + assertNotNull(newRow); + assertNotNull(oldRow); + oldRow.forEach((col, value) -> { + if (value != null && !newRow.containsKey(col)) + newRow.put(col, value); + }); + } + } + + /** Stored values reach the write as they were read, so check the types that convert on the way in */ + @Test + public void mergeKeepsOmittedLookupAndDateColumns() throws Exception + { + Date date = new GregorianCalendar(2026, Calendar.MARCH, 4, 5, 6, 7).getTime(); + QueryUpdateServiceTestUtil.insert(listTable(), _user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, 40, INT_FIELD, 1, TEXT_FIELD, "x", DATE_FIELD, date, LOOKUP_FIELD, _user.getUserId()))); + mergeIntField(tableWithTrigger(new Trigger() {}), 40); + + assertOmittedFieldKept(40); + Map row = getRow(40); + assertEquals("MERGE changed an omitted date", date.getTime(), ((Date) row.get(DATE_FIELD)).getTime()); + assertEquals("MERGE changed an omitted lookup", _user.getUserId(), ((Number) row.get(LOOKUP_FIELD)).intValue()); + } + + @Test + public void mergeLetsTriggersCopyOldRow() throws Exception + { + insertRow(30); + mergeIntField(tableWithTrigger(new CopyOldRowTrigger()), 30); + assertOmittedFieldKept(30); + } + /** Rows writing the int field, one per key; a null key is a row with a blank key */ private static List> rowsWithKeys(Integer... keys) { @@ -1991,22 +2066,26 @@ private String mergeOutcome(TableInfo table, List> rows) return errors.getRowErrors().stream().filter(ValidationException::hasErrors).map(ValidationException::getMessage).collect(Collectors.joining("\n")); } - record InvalidKeyCase(String name, List> rows) {} + /** @param omitsColumn MERGE pads the missing column with null for the triggers, so import reports a missing value rather than a missing column */ + record InvalidKeyCase(String name, List> rows, boolean omitsColumn) {} // A routing-only lookup must leave these to the import, which handles them the same way with or without triggers @Test public void mergeWithRoutedTriggerReportsInvalidKeys() { for (InvalidKeyCase c : List.of( - new InvalidKeyCase("one blank key", rowsWithKeys(13, null, 14)), - new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15)), - new InvalidKeyCase("every key blank", rowsWithKeys(null, null)), - new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2))))) + new InvalidKeyCase("one blank key", rowsWithKeys(13, null, 14), false), + new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15), false), + new InvalidKeyCase("every key blank", rowsWithKeys(null, null), false), + new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2)), true))) { String withoutTrigger = mergeOutcome(listTable(), c.rows()); String withTrigger = mergeOutcome(tableWithTrigger(recordingTrigger(true, false)), c.rows()); - assertEquals(c.name(), withoutTrigger, withTrigger); assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); + if (c.omitsColumn()) + assertFalse(c.name() + ": " + withTrigger, withTrigger.startsWith("threw ")); + else + assertEquals(c.name(), withoutTrigger, withTrigger); } } } diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index bb823b86e1d..2c3f486ed63 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -1170,7 +1170,8 @@ private String mergeOutcome(TableInfo table, List> rows) return errors.getMessage(); } - record UnkeyableCase(String name, Map row) {} + /** @param omitsColumn MERGE pads the missing column with null for the triggers, so import reports a missing value rather than a missing column */ + record UnkeyableCase(String name, Map row, boolean omitsColumn) {} // Rows the routing lookup can't key must reach the import, which handles them the same way with or without triggers @Test @@ -1181,16 +1182,19 @@ public void mergeWithRoutedTriggerReportsUnkeyableRows() throws Exception UserSchema schema = studySchema(); for (UnkeyableCase c : List.of( - new UnkeyableCase("no subject column", Map.of("SequenceNum", "1.2345", "Value1", "2.0")), - new UnkeyableCase("no SequenceNum or Date column", Map.of(SUBJECT_COLUMN_NAME, "S1", "Value1", "2.0")), - new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0")), - new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0")))) + new UnkeyableCase("no subject column", Map.of("SequenceNum", "1.2345", "Value1", "2.0"), true), + new UnkeyableCase("no SequenceNum or Date column", Map.of(SUBJECT_COLUMN_NAME, "S1", "Value1", "2.0"), true), + new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0"), false), + new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0"), false))) { String withoutTrigger = mergeOutcome(schema.getTable(DATASET_NAME), List.of(c.row())); RecordingTrigger trigger = recordingTrigger(); String withTrigger = mergeOutcome(tableWithRoutedTrigger(trigger), List.of(c.row())); - assertEquals(c.name(), withoutTrigger, withTrigger); assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); + if (c.omitsColumn()) + assertFalse(c.name() + ": " + withTrigger, withTrigger.startsWith("threw ")); + else + assertEquals(c.name(), withoutTrigger, withTrigger); assertFalse(c.name() + ": an unkeyable row was routed to update: " + trigger.getRecorded(), trigger.getRecorded().stream().anyMatch(e -> e.startsWith("beforeUpdate"))); } } From 6cee970763f2b2f1c27e98d002f441122d905ae4 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sat, 28 Nov 2026 10:18:20 -0800 Subject: [PATCH 6/7] Share merge value comparison, report missing carried-forward columns as row errors Moves the stored-vs-submitted value comparison into ValueUtil for managed-column checks, and consolidates the list and dataset merge tests onto shared helpers. --- api/src/org/labkey/api/ApiModule.java | 2 + .../labkey/api/data/AbstractTableInfo.java | 19 +-- .../TriggerDataBuilderHelper.java | 14 +- .../exp/api/DefaultExperimentSaveHandler.java | 43 +----- .../api/query/QueryUpdateServiceTestUtil.java | 55 +++++++ api/src/org/labkey/api/util/ValueUtil.java | 111 ++++++++++++++ .../list/model/ListQueryUpdateService.java | 138 +++++------------- .../study/query/DatasetUpdateService.java | 27 +--- 8 files changed, 217 insertions(+), 192 deletions(-) create mode 100644 api/src/org/labkey/api/util/ValueUtil.java diff --git a/api/src/org/labkey/api/ApiModule.java b/api/src/org/labkey/api/ApiModule.java index 9a4ef7b11a5..db16c32c7e3 100644 --- a/api/src/org/labkey/api/ApiModule.java +++ b/api/src/org/labkey/api/ApiModule.java @@ -224,6 +224,7 @@ import org.labkey.api.util.TracedOperation; import org.labkey.api.util.URIUtil; import org.labkey.api.util.URLHelper; +import org.labkey.api.util.ValueUtil; import org.labkey.api.util.VersionNumber; import org.labkey.api.util.XmlBeansUtil; import org.labkey.api.util.emailTemplate.EmailTemplate; @@ -538,6 +539,7 @@ public void registerServlets(ServletContext servletCtx) URIUtil.TestCase.class, UsageMetrics.TestCase.class, ValidEmail.TestCase.class, + ValueUtil.TestCase.class, VersionNumber.TestCase.class, ViewContext.TestCase.class, XmlBeansUtil.TestCase.class diff --git a/api/src/org/labkey/api/data/AbstractTableInfo.java b/api/src/org/labkey/api/data/AbstractTableInfo.java index 978a285b7c6..acc7fecf742 100644 --- a/api/src/org/labkey/api/data/AbstractTableInfo.java +++ b/api/src/org/labkey/api/data/AbstractTableInfo.java @@ -74,6 +74,7 @@ import org.labkey.api.util.SimpleNamedObject; import org.labkey.api.util.StringExpression; import org.labkey.api.util.StringExpressionFactory; +import org.labkey.api.util.ValueUtil; import org.labkey.api.util.logging.LogHelper; import org.labkey.api.view.ActionURL; import org.labkey.api.view.ViewContext; @@ -95,7 +96,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -2085,7 +2085,7 @@ public void fireRowTrigger( if (storedRow != null) { DeltaTrackingMap row = trackedRow; - added.removeIf(col -> isStoredValue(storedRow, col, row.get(col))); + added.removeIf(col -> storedRow.containsKey(col) && ValueUtil.valuesEqual(storedRow.get(col), row.get(col))); } if (!added.isEmpty() || !removed.isEmpty()) @@ -2130,21 +2130,6 @@ public void fireRowTrigger( throw errors; } - private static boolean isStoredValue(Map storedRow, String col, Object value) - { - if (!storedRow.containsKey(col)) - return false; - Object stored = storedRow.get(col); - if (Objects.equals(stored, value)) - return true; - // Script triggers hand values back converted, e.g. an integer as a double - if (stored instanceof Number a && value instanceof Number b) - return a.doubleValue() == b.doubleValue(); - if (stored instanceof Date a && value instanceof Date b) - return a.getTime() == b.getTime(); - return false; - } - public void checkLocked() { if (_locked) diff --git a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java index 1e1328773a2..9b0396bec5e 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -311,11 +311,11 @@ public boolean next() throws BatchValidationException int rowNumber = asInteger(getInput().get(0)); _currentRow = getInput().getMap(); Map existingRecord = getExistingRecord(); - carryForward(existingRecord); - if (_routeMerge && existingRecord != null && !existingRecord.isEmpty()) - _routedExistingRecords.put(rowNumber, existingRecord); try { + carryForward(existingRecord); + if (_routeMerge && existingRecord != null && !existingRecord.isEmpty()) + _routedExistingRecords.put(rowNumber, existingRecord); _target.fireRowTrigger(_c, _user, triggerType, _context.getInsertOption(), true, rowNumber, _currentRow, getOldRow(), _extraContext, existingRecord); return true; } @@ -329,7 +329,7 @@ public boolean next() throws BatchValidationException return false; } - private void carryForward(@Nullable Map existingRecord) + private void carryForward(@Nullable Map existingRecord) throws ValidationException { if (_carryForwardColumns.isEmpty() || existingRecord == null || existingRecord.isEmpty()) return; @@ -337,9 +337,9 @@ private void carryForward(@Nullable Map existingRecord) Map existing = new CaseInsensitiveHashMap<>(existingRecord); for (String col : _carryForwardColumns) { - assert existing.containsKey(col) : "Existing record lacks " + col + ", so MERGE would null it"; - if (existing.containsKey(col)) - _currentRow.put(col, existing.get(col)); + if (!existing.containsKey(col)) + throw new ValidationException("Can't keep the stored value of omitted column " + col + "; include it in the input"); + _currentRow.put(col, existing.get(col)); } } diff --git a/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java b/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java index ea534b4bb56..26f7fb45ce8 100644 --- a/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java +++ b/api/src/org/labkey/api/exp/api/DefaultExperimentSaveHandler.java @@ -46,21 +46,19 @@ import org.labkey.api.security.permissions.Permission; import org.labkey.api.security.permissions.ReadPermission; import org.labkey.api.util.JsonUtil; +import org.labkey.api.util.ValueUtil; import org.labkey.api.view.NotFoundException; import org.labkey.api.view.UnauthorizedException; import org.labkey.api.view.ViewBackgroundInfo; import org.labkey.api.view.ViewContext; -import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -793,7 +791,7 @@ private boolean propertiesWouldChange(ViewContext context, ExpMaterial material, { // Submitted side is already coerced to the property's Java type; coerce the stored side the same way. Object storedValue = normalizeStored(entry.getKey(), material.getProperty(entry.getKey())); - if (!valuesEqual(storedValue, entry.getValue())) + if (!ValueUtil.valuesEqual(storedValue, entry.getValue())) return true; } return false; @@ -817,43 +815,6 @@ private static Object normalizeStored(PropertyDescriptor pd, Object value) } } - private static boolean valuesEqual(Object stored, Object submitted) - { - if (Objects.equals(stored, submitted)) - return true; - if (stored == null || submitted == null) - return false; - if (stored instanceof Date && submitted instanceof Date) - return ((Date) stored).getTime() == ((Date) submitted).getTime(); - if (stored instanceof Number && submitted instanceof Number) - { - if (stored instanceof BigDecimal || submitted instanceof BigDecimal) - return new BigDecimal(stored.toString()).compareTo(new BigDecimal(submitted.toString())) == 0; - return ((Number) stored).doubleValue() == ((Number) submitted).doubleValue(); - } - if (stored instanceof Collection && submitted instanceof Collection) - { - List remaining = new ArrayList<>((Collection) stored); - for (Object s : (Collection) submitted) - { - boolean found = false; - for (int i = 0; i < remaining.size(); i++) - { - if (valuesEqual(remaining.get(i), s)) - { - remaining.remove(i); - found = true; - break; - } - } - if (!found) - return false; - } - return remaining.isEmpty(); - } - return false; - } - @Override public ExpData handleData(ViewContext context, JSONObject dataObject) throws ValidationException { diff --git a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java index 40e570a8577..18b0339a36f 100644 --- a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java +++ b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java @@ -19,13 +19,20 @@ import org.jetbrains.annotations.Nullable; import org.labkey.api.data.AbstractTableInfo; import org.labkey.api.data.Container; +import org.labkey.api.data.DbScope; import org.labkey.api.data.TableInfo; import org.labkey.api.data.triggers.Trigger; +import org.labkey.api.dataiterator.DataIteratorContext; import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.security.User; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** Test helpers that call a QueryUpdateService and throw its validation errors instead of returning them */ public class QueryUpdateServiceTestUtil @@ -88,6 +95,54 @@ public static int merge(TableInfo table, User user, Container c, List> rows, QueryUpdateService.InsertOption option) throws Exception + { + BatchValidationException errors = new BatchValidationException(); + DataIteratorContext context = new DataIteratorContext(errors); + context.setInsertOption(option); + try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) + { + int count = getUpdateService(table).loadRows(user, c, MapDataIterator.of(rows), context, null); + if (errors.hasErrors()) + throw errors; + tx.commit(); + return count; + } + } + + /** Merges the rows, rolls back, and returns the row error messages, or the exception if MERGE threw */ + public static String mergeOutcome(TableInfo table, User user, Container c, List> rows) + { + BatchValidationException errors = new BatchValidationException(); + try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) + { + getUpdateService(table).mergeRows(user, c, MapDataIterator.of(rows), errors, null, null); + } + catch (Exception e) + { + return "threw " + e; + } + assertTrue("Expected a row error", errors.hasErrors()); + // ValidatorIterator leaves an empty error on a later row whose field error it already reported, depending on read-ahead + return errors.getRowErrors().stream().filter(ValidationException::hasErrors).map(ValidationException::getMessage).collect(Collectors.joining("\n")); + } + + /** + * Asserts a trigger doesn't change how MERGE reports the rows + * @param omitsColumn MERGE pads the missing column with null for the triggers, so import reports a missing value rather than a missing column + */ + public static void assertSameMergeOutcome(String name, TableInfo plain, TableInfo triggered, User user, Container c, List> rows, boolean omitsColumn) + { + String withoutTrigger = mergeOutcome(plain, user, c, rows); + String withTrigger = mergeOutcome(triggered, user, c, rows); + assertFalse(name + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); + if (omitsColumn) + assertFalse(name + ": " + withTrigger, withTrigger.startsWith("threw ")); + else + assertEquals(name, withoutTrigger, withTrigger); + } + public static List> delete(TableInfo table, User user, Container c, List> keys) throws Exception { return getUpdateService(table).deleteRows(user, c, keys, null, null); diff --git a/api/src/org/labkey/api/util/ValueUtil.java b/api/src/org/labkey/api/util/ValueUtil.java new file mode 100644 index 00000000000..5f7fd64f9fe --- /dev/null +++ b/api/src/org/labkey/api/util/ValueUtil.java @@ -0,0 +1,111 @@ +/* + * 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.api.util; + +import org.jetbrains.annotations.Nullable; +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +public class ValueUtil +{ + private ValueUtil() + { + } + + /** Whether a stored value and a submitted one are the same, ignoring numeric type, Date subclass, and collection order */ + public static boolean valuesEqual(@Nullable Object stored, @Nullable Object submitted) + { + if (Objects.equals(stored, submitted)) + return true; + if (stored == null || submitted == null) + return false; + if (stored instanceof Date a && submitted instanceof Date b) + return a.getTime() == b.getTime(); + if (stored instanceof Number a && submitted instanceof Number b) + { + if (!(a instanceof BigDecimal || b instanceof BigDecimal) && (isFloatingPoint(a) || isFloatingPoint(b))) + return a.doubleValue() == b.doubleValue(); + // Doubles can't distinguish longs above 2^53 + return new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString())) == 0; + } + if (stored instanceof Collection a && submitted instanceof Collection b) + { + List remaining = new ArrayList<>(a); + for (Object s : b) + { + boolean found = false; + for (int i = 0; i < remaining.size(); i++) + { + if (valuesEqual(remaining.get(i), s)) + { + remaining.remove(i); + found = true; + break; + } + } + if (!found) + return false; + } + return remaining.isEmpty(); + } + return false; + } + + private static boolean isFloatingPoint(Number n) + { + return n instanceof Double || n instanceof Float; + } + + public static class TestCase extends Assert + { + private record Case(String name, Object stored, Object submitted, boolean equal) {} + + @Test + public void testValuesEqual() + { + long big = (1L << 53) + 1; + Date now = new Date(); + for (Case c : List.of( + new Case("both null", null, null, true), + new Case("one null", null, 1, false), + new Case("Integer vs Long", 5, 5L, true), + new Case("Integer vs different Long", 5, 6L, false), + new Case("Double vs BigDecimal", 1.5, new BigDecimal("1.50"), true), + new Case("Float vs Double", 0.5f, 0.5, true), + new Case("Integer vs Double", 2, 2.0, true), + new Case("longs above 2^53 differing by 1", big, big + 1, false), + new Case("Long vs BigDecimal above 2^53", big, new BigDecimal(big), true), + new Case("Timestamp vs Date", new Timestamp(now.getTime()), now, true), + new Case("Dates differing by 1ms", new Date(now.getTime() + 1), now, false), + new Case("reordered list", List.of(1, 2, 2), List.of(2, 1, 2L), true), + new Case("list with different duplicates", List.of(1, 1, 2), List.of(1, 2, 2), false), + new Case("list of different size", List.of(1, 2), List.of(1, 2, 3), false), + new Case("String vs Integer", "1", 1, false))) + { + assertEquals(c.name(), c.equal(), valuesEqual(c.stored(), c.submitted())); + assertEquals(c.name() + " (reversed)", c.equal(), valuesEqual(c.submitted(), c.stored())); + } + } + } +} diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index 039c2b63fd6..10ecf09bd33 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -54,7 +54,6 @@ import org.labkey.api.dataiterator.DataIteratorContext; import org.labkey.api.dataiterator.DetailedAuditLogDataIterator; import org.labkey.api.dataiterator.ImportProgress; -import org.labkey.api.dataiterator.MapDataIterator; import org.labkey.api.exceptions.OptimisticConflictException; import org.labkey.api.exp.ObjectProperty; import org.labkey.api.exp.PropertyType; @@ -1860,29 +1859,15 @@ private void insertRow(int key) throws Exception QueryUpdateServiceTestUtil.insert(listTable(), _user, _container, List.of(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 1, TEXT_FIELD, "x"))); } - private void mergeIntField(TableInfo table, int... keys) throws Exception + /** Writes the int field only, for each key */ + private void mergeIntField(TableInfo table, Integer... keys) throws Exception { - load(table, InsertOption.MERGE, keys); + assertEquals(keys.length, QueryUpdateServiceTestUtil.merge(table, _user, _container, rowsWithKeys(keys))); } - /** Writes the int field only, for each key */ - private void load(TableInfo table, InsertOption option, int... keys) throws Exception + private void replaceIntField(TableInfo table, Integer... keys) throws Exception { - List> rows = new ArrayList<>(); - for (int key : keys) - rows.add(CaseInsensitiveHashMap.of(KEY_NAME, key, INT_FIELD, 2)); - - BatchValidationException errors = new BatchValidationException(); - DataIteratorContext context = new DataIteratorContext(errors); - context.setInsertOption(option); - try (DbScope.Transaction tx = table.getSchema().getScope().ensureTransaction()) - { - int count = QueryUpdateServiceTestUtil.getUpdateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); - if (errors.hasErrors()) - throw errors; - assertEquals(keys.length, count); - tx.commit(); - } + assertEquals(keys.length, QueryUpdateServiceTestUtil.load(table, _user, _container, rowsWithKeys(keys), InsertOption.REPLACE)); } private Map getRow(int key) @@ -1915,61 +1900,37 @@ public void mergeWithTriggerKeepsOmittedColumns() throws Exception assertOmittedFieldKept(2); } - @Test - public void mergeRoutesExistingRowsToUpdateHooks() throws Exception - { - insertRow(3); - RecordingTrigger trigger = recordingTrigger(true, false); - mergeIntField(tableWithTrigger(trigger), 3, 4); - - trigger.assertEvents("beforeUpdate 3 old x", "beforeInsert 4", "afterUpdate 3", "afterInsert 4"); - assertOmittedFieldKept(3); - } - - @Test - public void mergeWithoutRoutingFiresInsertHooks() throws Exception - { - insertRow(5); - RecordingTrigger trigger = recordingTrigger(false, false); - mergeIntField(tableWithTrigger(trigger), 5, 6); - - trigger.assertEvents("beforeInsert 5", "beforeInsert 6", "afterInsert 5", "afterInsert 6"); - assertOmittedFieldKept(5); - } - - @Test - public void mergeKeepsInsertManagedColumnOnUpdatedRows() throws Exception - { - insertRow(7); - RecordingTrigger trigger = recordingTrigger(true, true); - mergeIntField(tableWithTrigger(trigger), 7, 8); - - trigger.assertEvents("beforeUpdate 7 old x", "beforeInsert 8", "afterUpdate 7", "afterInsert 8"); - assertOmittedFieldKept(7); - assertEquals(RecordingTrigger.COMPUTED, getRow(8).get(TEXT_FIELD)); - } - - @Test - public void replaceRoutesExistingRowsToUpdateHooks() throws Exception - { - insertRow(9); - RecordingTrigger trigger = recordingTrigger(true, false); - load(tableWithTrigger(trigger), InsertOption.REPLACE, 9, 10); - - trigger.assertEvents("beforeUpdate 9 old x", "beforeInsert 10", "afterUpdate 9", "afterInsert 10"); - assertNull("REPLACE keeps a column it was not given", getRow(9).get(TEXT_FIELD)); - } + /** @param events with %1$d for the existing row's key and %2$d for the new row's */ + record HookCase(String name, InsertOption option, boolean routed, boolean managesText, @Nullable String existingText, @Nullable String newText, String... events) {} @Test - public void replaceKeepsInsertManagedColumnOnUpdatedRows() throws Exception - { - insertRow(11); - RecordingTrigger trigger = recordingTrigger(true, true); - load(tableWithTrigger(trigger), InsertOption.REPLACE, 11, 12); - - trigger.assertEvents("beforeUpdate 11 old x", "beforeInsert 12", "afterUpdate 11", "afterInsert 12"); - assertEquals("REPLACE nulled a trigger-managed column", "x", getRow(11).get(TEXT_FIELD)); - assertEquals(RecordingTrigger.COMPUTED, getRow(12).get(TEXT_FIELD)); + public void loadFiresHooksAndKeepsColumns() throws Exception + { + String[] routedEvents = {"beforeUpdate %1$d old x", "beforeInsert %2$d", "afterUpdate %1$d", "afterInsert %2$d"}; + int key = 3; + for (HookCase c : List.of( + new HookCase("MERGE, routed", InsertOption.MERGE, true, false, "x", null, routedEvents), + new HookCase("MERGE, not routed", InsertOption.MERGE, false, false, "x", null, "beforeInsert %1$d", "beforeInsert %2$d", "afterInsert %1$d", "afterInsert %2$d"), + new HookCase("MERGE, routed, managed", InsertOption.MERGE, true, true, "x", RecordingTrigger.COMPUTED, routedEvents), + new HookCase("REPLACE, routed", InsertOption.REPLACE, true, false, null, null, routedEvents), + new HookCase("REPLACE, routed, managed", InsertOption.REPLACE, true, true, "x", RecordingTrigger.COMPUTED, routedEvents))) + { + int existingKey = key, newKey = key + 1; + insertRow(existingKey); + RecordingTrigger trigger = recordingTrigger(c.routed(), c.managesText()); + TableInfo table = tableWithTrigger(trigger); + if (c.option() == InsertOption.MERGE) + mergeIntField(table, existingKey, newKey); + else + replaceIntField(table, existingKey, newKey); + + trigger.assertEvents(Arrays.stream(c.events()).map(e -> e.formatted(existingKey, newKey)).toArray(String[]::new)); + Map existing = getRow(existingKey); + assertEquals(c.name(), 2, ((Number) existing.get(INT_FIELD)).intValue()); + assertEquals(c.name() + ": existing row", c.existingText(), existing.get(TEXT_FIELD)); + assertEquals(c.name() + ": new row", c.newText(), getRow(newKey).get(TEXT_FIELD)); + key += 2; + } } @Test @@ -2047,26 +2008,7 @@ private static List> rowsWithKeys(Integer... keys) return rows; } - /** Merges the rows and returns the row error message, or the exception if MERGE threw */ - private String mergeOutcome(TableInfo table, List> rows) - { - BatchValidationException errors = new BatchValidationException(); - DataIteratorContext context = new DataIteratorContext(errors); - context.setInsertOption(InsertOption.MERGE); - try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) - { - QueryUpdateServiceTestUtil.getUpdateService(table).loadRows(_user, _container, MapDataIterator.of(rows), context, null); - } - catch (Exception e) - { - return "threw " + e; - } - assertTrue("Expected a row error", errors.hasErrors()); - // ValidatorIterator leaves an empty error on a later row whose field error it already reported, depending on read-ahead - return errors.getRowErrors().stream().filter(ValidationException::hasErrors).map(ValidationException::getMessage).collect(Collectors.joining("\n")); - } - - /** @param omitsColumn MERGE pads the missing column with null for the triggers, so import reports a missing value rather than a missing column */ + /** @param omitsColumn see {@link QueryUpdateServiceTestUtil#assertSameMergeOutcome} */ record InvalidKeyCase(String name, List> rows, boolean omitsColumn) {} // A routing-only lookup must leave these to the import, which handles them the same way with or without triggers @@ -2078,15 +2020,7 @@ public void mergeWithRoutedTriggerReportsInvalidKeys() new InvalidKeyCase("duplicate keys", rowsWithKeys(15, 15), false), new InvalidKeyCase("every key blank", rowsWithKeys(null, null), false), new InvalidKeyCase("no key column", List.of(CaseInsensitiveHashMap.of(INT_FIELD, 2)), true))) - { - String withoutTrigger = mergeOutcome(listTable(), c.rows()); - String withTrigger = mergeOutcome(tableWithTrigger(recordingTrigger(true, false)), c.rows()); - assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); - if (c.omitsColumn()) - assertFalse(c.name() + ": " + withTrigger, withTrigger.startsWith("threw ")); - else - assertEquals(c.name(), withoutTrigger, withTrigger); - } + QueryUpdateServiceTestUtil.assertSameMergeOutcome(c.name(), listTable(), tableWithTrigger(recordingTrigger(true, false)), _user, _container, c.rows(), c.omitsColumn()); } } } diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index 2c3f486ed63..aa6d7950ba9 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -1153,24 +1153,7 @@ public void mergeRoutesExistingRowsToUpdateHooks() throws Exception assertEquals("MERGE nulled a column it was not given", "x", s1.get("Field1")); } - /** Merges the rows and returns the row error message, or the exception if MERGE threw */ - private String mergeOutcome(TableInfo table, List> rows) - { - QueryUpdateService qus = QueryUpdateServiceTestUtil.getUpdateService(table); - BatchValidationException errors = new BatchValidationException(); - try (DbScope.Transaction _ = table.getSchema().getScope().ensureTransaction()) - { - qus.mergeRows(_user, _container, MapDataIterator.of(rows), errors, null, null); - } - catch (Exception e) - { - return "threw " + e; - } - assertTrue("Expected a row error", errors.hasErrors()); - return errors.getMessage(); - } - - /** @param omitsColumn MERGE pads the missing column with null for the triggers, so import reports a missing value rather than a missing column */ + /** @param omitsColumn see {@link QueryUpdateServiceTestUtil#assertSameMergeOutcome} */ record UnkeyableCase(String name, Map row, boolean omitsColumn) {} // Rows the routing lookup can't key must reach the import, which handles them the same way with or without triggers @@ -1187,14 +1170,8 @@ public void mergeWithRoutedTriggerReportsUnkeyableRows() throws Exception new UnkeyableCase("blank subject", CaseInsensitiveHashMap.of(SUBJECT_COLUMN_NAME, null, "SequenceNum", "1.2345", "Value1", "2.0"), false), new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0"), false))) { - String withoutTrigger = mergeOutcome(schema.getTable(DATASET_NAME), List.of(c.row())); RecordingTrigger trigger = recordingTrigger(); - String withTrigger = mergeOutcome(tableWithRoutedTrigger(trigger), List.of(c.row())); - assertFalse(c.name() + ": " + withoutTrigger, withoutTrigger.startsWith("threw ")); - if (c.omitsColumn()) - assertFalse(c.name() + ": " + withTrigger, withTrigger.startsWith("threw ")); - else - assertEquals(c.name(), withoutTrigger, withTrigger); + QueryUpdateServiceTestUtil.assertSameMergeOutcome(c.name(), schema.getTable(DATASET_NAME), tableWithRoutedTrigger(trigger), _user, _container, List.of(c.row()), c.omitsColumn()); assertFalse(c.name() + ": an unkeyable row was routed to update: " + trigger.getRecorded(), trigger.getRecorded().stream().anyMatch(e -> e.startsWith("beforeUpdate"))); } } From 35893b7a58bd1698bad8a9fcdbdad55d34880883 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sun, 29 Nov 2026 16:18:41 -0800 Subject: [PATCH 7/7] Test that trigger imports set dataset QC state from QCStateLabel --- .../study/query/DatasetUpdateService.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/study/src/org/labkey/study/query/DatasetUpdateService.java b/study/src/org/labkey/study/query/DatasetUpdateService.java index aa6d7950ba9..ac87618b3e8 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -53,6 +53,8 @@ import org.labkey.api.exp.PropertyType; import org.labkey.api.exp.property.DomainProperty; import org.labkey.api.gwt.client.AuditBehaviorType; +import org.labkey.api.qc.DataState; +import org.labkey.api.qc.QCStateManager; import org.labkey.api.query.BatchValidationException; import org.labkey.api.query.DefaultQueryUpdateService; import org.labkey.api.query.DefaultSchema; @@ -1153,6 +1155,28 @@ public void mergeRoutesExistingRowsToUpdateHooks() throws Exception assertEquals("MERGE nulled a column it was not given", "x", s1.get("Field1")); } + // Import reads QCStateLabel only when the input has no QCState column, so triggers mustn't pad QCState + @Test + public void triggerImportSetsQCStateFromLabel() throws Exception + { + createDataset(); + TableInfo plain = studySchema().getTable(DATASET_NAME); + QueryUpdateServiceTestUtil.insert(plain, _user, _container, List.of(Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", "Field1", "x", DatasetTableImpl.QCSTATE_LABEL_COLNAME, "Before"))); + + for (QueryUpdateService.InsertOption option : List.of(QueryUpdateService.InsertOption.MERGE, QueryUpdateService.InsertOption.REPLACE)) + { + String label = "After " + option; + QueryUpdateServiceTestUtil.load(tableWithRoutedTrigger(recordingTrigger()), _user, _container, + List.of(Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "1.2345", DatasetTableImpl.QCSTATE_LABEL_COLNAME, label)), option); + + Number stored = new TableSelector(plain, PageFlowUtil.set(DatasetTableImpl.QCSTATE_ID_COLNAME), new SimpleFilter(FieldKey.fromParts(SUBJECT_COLUMN_NAME), "S1"), null).getObject(Long.class); + DataState expected = QCStateManager.getInstance().getStateForLabel(_container, label); + assertNotNull(option + ": QC state not created", expected); + assertNotNull(option + ": QC state not stored", stored); + assertEquals(option + ": QCStateLabel ignored", expected.getRowId(), stored.longValue()); + } + } + /** @param omitsColumn see {@link QueryUpdateServiceTestUtil#assertSameMergeOutcome} */ record UnkeyableCase(String name, Map row, boolean omitsColumn) {}