Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/src/org/labkey/api/ApiModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion api/src/org/labkey/api/data/AbstractTableInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Trigger> _triggers = null;
private Boolean _isTriggerManagedColumnsEnabled = null;

Expand Down Expand Up @@ -2025,6 +2036,7 @@ public void fireRowTrigger(
errors.setRowNumber(rowNumber);

Collection<Trigger> triggers = getTriggers(c);
Map<String, Object> storedRow = existingRecord == null || existingRecord.isEmpty() ? null : new CaseInsensitiveHashMap<>(existingRecord);

// Wrap the row once before the loop
DeltaTrackingMap<Object> trackedRow = null;
Expand All @@ -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())
Expand All @@ -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<Object> 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<String>();
Expand Down
63 changes: 63 additions & 0 deletions api/src/org/labkey/api/data/triggers/FillIfMissingTrigger.java
Original file line number Diff line number Diff line change
@@ -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<String, Object> newRow, ValidationException errors, Map<String, Object> extraContext)
{
fill(newRow);
}

@Override
public void beforeUpdate(TableInfo table, Container c, User user, @Nullable QueryUpdateService.InsertOption insertOption, @Nullable Map<String, Object> newRow, @Nullable Map<String, Object> oldRow, ValidationException errors, Map<String, Object> extraContext)
{
fill(newRow);
}

private void fill(@Nullable Map<String, Object> row)
{
assertNotNull(row);
row.putIfAbsent(column, FILLED);
}
}
114 changes: 114 additions & 0 deletions api/src/org/labkey/api/data/triggers/RecordingTrigger.java
Original file line number Diff line number Diff line change
@@ -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<String> _events = new ArrayList<>();
private final String _idColumn;
private final List<String> _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<String> oldColumns, boolean routed, @Nullable String insertManagedColumn)
{
_idColumn = idColumn;
_oldColumns = oldColumns;
_routed = routed;
_insertManagedColumn = insertManagedColumn;
}

public List<String> 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<String, Object> newRow, ValidationException errors, Map<String, Object> 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<String, Object> newRow, @Nullable Map<String, Object> oldRow, ValidationException errors, Map<String, Object> extraContext)
{
assertNotNull(newRow);
assertNotNull(oldRow);
Map<String, Object> 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<String, Object> newRow, ValidationException errors, Map<String, Object> extraContext)
{
assertNotNull(newRow);
_events.add("afterInsert " + newRow.get(_idColumn));
}

@Override
public void afterUpdate(TableInfo table, Container c, User user, @Nullable Map<String, Object> newRow, @Nullable Map<String, Object> oldRow, ValidationException errors, Map<String, Object> extraContext)
{
assertNotNull(newRow);
assertNotNull(oldRow);
_events.add("afterUpdate " + newRow.get(_idColumn));
}
}
6 changes: 6 additions & 0 deletions api/src/org/labkey/api/data/triggers/ScriptTrigger.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ public boolean canStream()
return _managedColumns;
}

@Override
public boolean isMergeRoutedByExistingRecord()
{
return true;
}

@Override
public boolean isManagedColumnsEnabled()
{
Expand Down
22 changes: 22 additions & 0 deletions api/src/org/labkey/api/data/triggers/Trigger.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> 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.
Expand Down Expand Up @@ -270,6 +285,13 @@ default void rowTrigger(TableInfo table, Container c, User user, TableInfo.Trigg
ValidationException errors, Map<String, Object> extraContext,
@Nullable Map<String, Object> existingRecord) throws ValidationException
{
TableInfo.TriggerType rowEvent = getRowEvent(event, insertOption, existingRecord);
if (rowEvent != event)
{
event = rowEvent;
oldRow = existingRecord;
}

if (before)
{
switch (event)
Expand Down
25 changes: 21 additions & 4 deletions api/src/org/labkey/api/dataiterator/CoerceDataIterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -24,6 +25,7 @@

import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;

/**
* User: matthewb
Expand All @@ -37,19 +39,33 @@
*/
public class CoerceDataIterator extends SimpleTranslator
{
private final Set<String> _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<ColumnInfo> 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<String> getPaddedColumnNames()
{
return _paddedColumnNames;
}

void init(TableInfo target, boolean useImportAliases, boolean outputAllColumns)
void init(TableInfo target, boolean useImportAliases, @Nullable Predicate<ColumnInfo> padColumn)
{
Map<String,ColumnInfo> targetMap = DataIteratorUtil.createTableMap(target, useImportAliases);
Set<String> seen = new CaseInsensitiveHashSet();
Expand All @@ -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());
}
}
}
Expand Down
Loading