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 48c69d9d119..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; @@ -1934,11 +1935,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; @@ -2025,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; @@ -2050,7 +2062,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()) @@ -2069,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 -> storedRow.containsKey(col) && ValueUtil.valuesEqual(storedRow.get(col), row.get(col))); + } + if (!added.isEmpty() || !removed.isEmpty()) { var diffs = new ArrayList(); 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/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/data/triggers/ScriptTrigger.java b/api/src/org/labkey/api/data/triggers/ScriptTrigger.java index 00d2b7b7494..f04da30eee7 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/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/ExistingRecordDataIterator.java b/api/src/org/labkey/api/dataiterator/ExistingRecordDataIterator.java index d88fdec4813..64343972150 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) + 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(); @@ -122,6 +126,8 @@ public abstract class ExistingRecordDataIterator extends WrapperDataIterator if (detailed) _dataColumnNames.addAll(map.keySet()); + if (allColumns) + _dataColumnNames.addAll(target.getColumnNameSet()); for (String name : keyNames) { @@ -142,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 @@ -220,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, ", "))); @@ -241,10 +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) + /** + * @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 -> { @@ -264,11 +276,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, skipInvalidKeys); else - return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed); + return new ExistingDataIteratorsTableInfo(new CachingDataIterator(di), target, keys, sharedKeys, context, detailed, allColumns, skipInvalidKeys); } return di; }; @@ -279,18 +291,23 @@ 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, boolean skipInvalidKeys) { - super(in, target, keys, sharedKeys, true, context, detailed); + 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 @@ -304,46 +321,60 @@ 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); 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 "); - 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); } @@ -358,16 +389,22 @@ 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) + { + 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) { @@ -393,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); } @@ -412,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) + 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); + super(in, target, keys, sharedKeys, true, context, detailed, allColumns, skipInvalidKeys); qus = target.getUpdateService(); } @@ -436,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(); @@ -500,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); + 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/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 1e5015e28a5..9b0396bec5e 100644 --- a/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java +++ b/api/src/org/labkey/api/dataiterator/TriggerDataBuilderHelper.java @@ -15,11 +15,16 @@ */ 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; +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; @@ -28,10 +33,12 @@ 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; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; import static org.labkey.api.util.IntegerUtils.asInteger; @@ -45,6 +52,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,36 +145,86 @@ 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(); } - di = LoggingDataIterator.wrap(new CoerceDataIterator(di, context, _target, !context.getInsertOption().updateOnly)); + // 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); + // 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(); + triggerOnlyLookup = 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())); + + // 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 (triggerOnlyLookup) + 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()) { @@ -189,7 +249,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); @@ -205,10 +268,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 @@ -245,9 +310,13 @@ public boolean next() throws BatchValidationException { int rowNumber = asInteger(getInput().get(0)); _currentRow = getInput().getMap(); + Map existingRecord = getExistingRecord(); try { - _target.fireRowTrigger(_c, _user, triggerType, _context.getInsertOption(), true, rowNumber, _currentRow, getOldRow(), _extraContext, getExistingRecord()); + 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; } catch (ValidationException vex) @@ -260,6 +329,20 @@ public boolean next() throws BatchValidationException return false; } + private void carryForward(@Nullable Map existingRecord) throws ValidationException + { + if (_carryForwardColumns.isEmpty() || existingRecord == null || existingRecord.isEmpty()) + return; + + Map existing = new CaseInsensitiveHashMap<>(existingRecord); + for (String col : _carryForwardColumns) + { + 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)); + } + } + @Override public Object get(int i) { @@ -271,6 +354,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; @@ -312,9 +423,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/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 4f84358d8ae..18b0339a36f 100644 --- a/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java +++ b/api/src/org/labkey/api/query/QueryUpdateServiceTestUtil.java @@ -16,13 +16,23 @@ 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.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 @@ -46,6 +56,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(); @@ -73,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/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/experiment/src/org/labkey/experiment/ExperimentModule.java b/experiment/src/org/labkey/experiment/ExperimentModule.java index a9e30864b70..e851e420658 100644 --- a/experiment/src/org/labkey/experiment/ExperimentModule.java +++ b/experiment/src/org/labkey/experiment/ExperimentModule.java @@ -139,6 +139,7 @@ import org.labkey.experiment.api.LogDataType; import org.labkey.experiment.api.Protocol; import org.labkey.experiment.api.SampleIndexDocumentTestCase; +import org.labkey.experiment.api.SampleMergeTestCase; import org.labkey.experiment.api.SampleProvidedAmountAuditTestCase; import org.labkey.experiment.api.SampleTypeFilterSuggestionProvider; import org.labkey.experiment.api.SampleTypeServiceImpl; @@ -1143,6 +1144,7 @@ public Collection getSummary(Container c) LineageTest.class, OntologyManager.TestCase.class, PropertyServiceImpl.TestCase.class, + SampleMergeTestCase.class, SampleProvidedAmountAuditTestCase.class, SampleIndexDocumentTestCase.class, SampleTypeFilterSuggestionProvider.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..3ff2f1f2fd6 --- /dev/null +++ b/experiment/src/org/labkey/experiment/api/SampleMergeTestCase.java @@ -0,0 +1,150 @@ +/* + * 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.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.FillIfMissingTrigger; +import org.labkey.api.data.triggers.RecordingTrigger; +import org.labkey.api.data.triggers.Trigger; +import org.labkey.api.exp.api.ExpSampleType; +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.FieldKey; +import org.labkey.api.query.QueryService; +import org.labkey.api.query.QueryUpdateServiceTestUtil; +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.ArrayList; +import java.util.List; +import java.util.Map; + +/** 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"; + 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"); + mergeIntField(SampleTypeTestHelper.getTable(_c, _user, st), "S-1"); + assertOmittedFieldKept(st); + } + + @Test + public void mergeWithTriggerKeepsOmittedColumns() throws Exception + { + ExpSampleType st = createSampleType("MergeTrigger"); + mergeIntField(tableWithTrigger(st, new Trigger() {}), "S-1"); + assertOmittedFieldKept(st); + } + + @Test + public void mergeRoutesExistingSamplesToUpdateHooks() throws Exception + { + ExpSampleType st = createSampleType("MergeRouted"); + RecordingTrigger trigger = new RecordingTrigger("name", List.of(TEXT_FIELD), true, TEXT_FIELD); + mergeIntField(tableWithTrigger(st, trigger), "S-1", "S-2"); + + trigger.assertEvents("beforeUpdate S-1 old x", "beforeInsert S-2", "afterUpdate S-1", "afterInsert S-2"); + assertOmittedFieldKept(st); + 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 + { + 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; + } + + private TableInfo tableWithTrigger(ExpSampleType st, Trigger trigger) + { + UserSchema schema = QueryService.get().getUserSchema(_user, _c, SamplesSchema.SCHEMA_NAME); + assertNotNull(schema); + return QueryUpdateServiceTestUtil.withTrigger(schema.getTable(st.getName(), null, true, true), _c, trigger); + } + + /** 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)); + assertEquals(names.length, QueryUpdateServiceTestUtil.merge(table, _user, _c, rows)); + } + + private Map getSample(ExpSampleType st, String name) + { + Map row = new TableSelector(SampleTypeTestHelper.getTable(_c, _user, st), 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/ListModule.java b/list/src/org/labkey/list/ListModule.java index d465f5a0796..4f2cd6c68ec 100644 --- a/list/src/org/labkey/list/ListModule.java +++ b/list/src/org/labkey/list/ListModule.java @@ -241,6 +241,7 @@ public Collection getProvisionedSchemaNames() return Set.of( ListQueryUpdateService.AuditBatchTestCase.class, ListQueryUpdateService.GetRowsTestCase.class, + ListQueryUpdateService.MergeTestCase.class, ListQueryUpdateService.BatchedDeleteTestCase.class, ListQueryUpdateService.RowContainerCheckTestCase.class ); diff --git a/list/src/org/labkey/list/model/ListQueryUpdateService.java b/list/src/org/labkey/list/model/ListQueryUpdateService.java index 1d19b03e01e..10ecf09bd33 100644 --- a/list/src/org/labkey/list/model/ListQueryUpdateService.java +++ b/list/src/org/labkey/list/model/ListQueryUpdateService.java @@ -47,6 +47,8 @@ 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; import org.labkey.api.dataiterator.DataIteratorContext; @@ -60,6 +62,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; @@ -75,6 +78,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; @@ -97,6 +101,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; @@ -110,8 +115,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; @@ -1271,13 +1279,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; @@ -1778,4 +1796,231 @@ public void updatesRowsInWorkbookInPlace() throws Exception assertEquals("the workbook row should stay in the workbook", _workbook.getId(), String.valueOf(row.get("container"))); } } + + /** 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 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; + private static ListDefinition _list; + + @BeforeClass + 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, 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 + public static void cleanup() + { + _list = null; + _container = null; + _user = null; + + JunitUtil.deleteTestContainer(); + } + + private TableInfo tableWithTrigger(Trigger trigger) + { + return QueryUpdateServiceTestUtil.withTrigger(new ListQuerySchema(_user, _container).getTable(LIST_NAME, null, true, true), _container, trigger); + } + + /** Sets the text field on insert when it manages that column */ + private static RecordingTrigger recordingTrigger(boolean routed, boolean managesText) + { + return new RecordingTrigger(KEY_NAME, List.of(TEXT_FIELD), routed, managesText ? TEXT_FIELD : null); + } + + private TableInfo listTable() + { + TableInfo table = _list.getTable(_user); + assertNotNull(table); + return table; + } + + 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"))); + } + + /** Writes the int field only, for each key */ + private void mergeIntField(TableInfo table, Integer... keys) throws Exception + { + assertEquals(keys.length, QueryUpdateServiceTestUtil.merge(table, _user, _container, rowsWithKeys(keys))); + } + + private void replaceIntField(TableInfo table, Integer... keys) throws Exception + { + assertEquals(keys.length, QueryUpdateServiceTestUtil.load(table, _user, _container, rowsWithKeys(keys), InsertOption.REPLACE)); + } + + 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)); + } + + @Test + public void mergeWithoutTriggerKeepsOmittedColumns() throws Exception + { + insertRow(1); + mergeIntField(listTable(), 1); + assertOmittedFieldKept(1); + } + + @Test + public void mergeWithTriggerKeepsOmittedColumns() throws Exception + { + insertRow(2); + mergeIntField(tableWithTrigger(new Trigger() {}), 2); + assertOmittedFieldKept(2); + } + + /** @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 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 + 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) + { + 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; + } + + /** @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 + @Test + public void mergeWithRoutedTriggerReportsInvalidKeys() + { + for (InvalidKeyCase c : List.of( + 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))) + QueryUpdateServiceTestUtil.assertSameMergeOutcome(c.name(), listTable(), tableWithTrigger(recordingTrigger(true, false)), _user, _container, c.rows(), c.omitsColumn()); + } + } } 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/DatasetTableImpl.java b/study/src/org/labkey/study/query/DatasetTableImpl.java index 60c69afbc87..59c068d1c88 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; @@ -68,6 +72,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; @@ -104,23 +109,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"; @@ -620,6 +633,76 @@ 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)); + // 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; + 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..ac87618b3e8 100644 --- a/study/src/org/labkey/study/query/DatasetUpdateService.java +++ b/study/src/org/labkey/study/query/DatasetUpdateService.java @@ -41,6 +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.RecordingTrigger; import org.labkey.api.dataiterator.DataIterator; import org.labkey.api.dataiterator.DataIteratorBuilder; import org.labkey.api.dataiterator.DataIteratorContext; @@ -52,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; @@ -60,7 +63,10 @@ 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; import org.labkey.api.security.User; import org.labkey.api.security.UserPrincipal; @@ -1108,6 +1114,98 @@ public void updateRowTest() throws Exception map.get("lsid"); } + private UserSchema studySchema() + { + UserSchema schema = QueryService.get().getUserSchema(_user, _container, StudyQuerySchema.SCHEMA_NAME); + assertNotNull(schema); + return schema; + } + + /** 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); + } + + // 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 */ + @Test + public void mergeRoutesExistingRowsToUpdateHooks() throws Exception + { + createDataset(); + insertS1(); + + 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")); + 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); + assertEquals(2.0d, s1.get("Value1")); + 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) {} + + // 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 = 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"), false), + new UnkeyableCase("unparseable SequenceNum", Map.of(SUBJECT_COLUMN_NAME, "S1", "SequenceNum", "not a number", "Value1", "2.0"), false))) + { + RecordingTrigger trigger = recordingTrigger(); + 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"))); + } + } + + private void insertS1() throws Exception + { + 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 public void createStudy() {