Skip to content
Merged
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
1 change: 1 addition & 0 deletions api/src/org/labkey/api/query/QueryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
public interface QueryService
{
String DEPRECATED_DISABLE_MANAGED_TRIGGER_COLUMNS = "queryDisableManagedTriggerColumns";
String DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS = "queryAllowRaggedImportRows";
String EXPERIMENTAL_PRODUCT_ALL_FOLDER_LOOKUPS = "queryProductAllFolderLookups";
String EXPERIMENTAL_PRODUCT_PROJECT_DATA_LISTING_SCOPED = "queryProductProjectDataListingScoped";
String MAX_QUERY_SELECTION = "maxQuerySelection";
Expand Down
10 changes: 10 additions & 0 deletions query/src/org/labkey/query/QueryModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
import org.labkey.query.audit.QueryExportAuditProvider;
import org.labkey.query.audit.QueryUpdateAuditProvider;
import org.labkey.query.controllers.ExpressionAssistantAgentAction;
import org.labkey.query.controllers.ImportRowsTestCase;
import org.labkey.query.controllers.OlapController;
import org.labkey.query.controllers.QueryController;
import org.labkey.query.controllers.QueryMcp;
Expand Down Expand Up @@ -249,6 +250,14 @@ public QuerySchema createSchema(DefaultSchema schema, Module module)
false,
OptionalFeatureService.FeatureType.Deprecated
));
OptionalFeatureService.get().addFeatureFlag(new OptionalFeatureFlag(
QueryService.DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS,
"Allow importRows rows with differing fields",
"By default the importRows API rejects a request whose rows do not all supply the same fields. Enabling this feature accepts such requests, storing NULL for any field a row omits. This option will be removed in a future release of LabKey Server.",
false,
false,
OptionalFeatureService.FeatureType.Deprecated
));
}


Expand Down Expand Up @@ -391,6 +400,7 @@ public Set<String> getSchemaNames()
ModuleReportCache.TestCase.class,
OlapController.TestCase.class,
OlapController.ContainerScopingTestCase.class,
ImportRowsTestCase.class,
QueryController.SaveRowsTestCase.class,
QueryController.TestCase.class,
QueryServiceImpl.TestCase.class,
Expand Down
229 changes: 229 additions & 0 deletions query/src/org/labkey/query/controllers/ImportRowsTestCase.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
/*
* 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.query.controllers;

import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.PropertyStorageSpec;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.exp.PropertyType;
import org.labkey.api.exp.list.ListDefinition;
import org.labkey.api.exp.list.ListService;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainProperty;
import org.labkey.api.exp.property.PropertyService;
import org.labkey.api.query.QueryService;
import org.labkey.api.security.User;
import org.labkey.api.settings.OptionalFeatureService;
import org.labkey.api.util.GUID;
import org.labkey.api.util.JunitUtil;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.TestContext;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.ViewServlet;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPart;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.Map;

/** GH Issue 1867: importRows rejects rows that differ in which fields they supply, and no command loses values when rows case a key differently */
public class ImportRowsTestCase extends Assert
{
// Unique per test so a failed test's rows can't leak into another's assertions
private final String _listName = "ImportRowsTest" + GUID.makeHash();

@BeforeClass
public static void setUp()
{
JunitUtil.deleteTestContainer();
}

@AfterClass
public static void tearDown()
{
JunitUtil.deleteTestContainer();
}

@Before
public void createList() throws Exception
{
User user = TestContext.get().getUser();
ListDefinition ld = ListService.get().createList(JunitUtil.getTestContainer(), _listName, ListDefinition.KeyType.Varchar);
Domain domain = ld.getDomain();
assertNotNull(domain);
domain.addProperty(new PropertyStorageSpec("Name", JdbcType.VARCHAR));
domain.addProperty(new PropertyStorageSpec("Description", JdbcType.VARCHAR));
domain.addProperty(new PropertyStorageSpec("Volume", JdbcType.INTEGER));
DomainProperty attachment = domain.addProperty(new PropertyStorageSpec("Attachment", JdbcType.VARCHAR));
attachment.setType(PropertyService.get().getType(JunitUtil.getTestContainer(), PropertyType.ATTACHMENT.getXmlName()));
ld.setKeyName("Name");
ld.save(user);
}

@Test
public void testRaggedImportRowsRejected() throws Exception
{
MockHttpServletResponse response = postSaveRows("importRows", List.of(
Map.of("Name", "S1"),
Map.of("Name", "S2", "Description", "x", "Volume", 5)));

assertNotEquals("Ragged importRows should fail", HttpServletResponse.SC_OK, response.getStatus());
String body = response.getContentAsString();
assertTrue("Error should name the row and the differing fields: " + body, body.contains("rows[1]") && body.contains("Description") && body.contains("Volume"));
assertEquals("Incorrect row count", 0L, new TableSelector(getTable()).getRowCount());
}

@Test
public void testRaggedImportRowsAllowedByFlag() throws Exception
{
OptionalFeatureService svc = OptionalFeatureService.get();
boolean wasEnabled = svc.isFeatureEnabled(QueryService.DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS);
svc.setFeatureEnabled(QueryService.DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS, true, TestContext.get().getUser());
try
{
saveRows("importRows", List.of(
Map.of("Name", "S1"),
Map.of("Name", "S2", "Description", "x", "Volume", 5)));
}
finally
{
svc.setFeatureEnabled(QueryService.DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS, wasEnabled, TestContext.get().getUser());
}

assertEquals("Incorrect row count", 2L, new TableSelector(getTable()).getRowCount());
assertValue("S1", "Description", null);
assertValue("S2", "Description", "x");
assertValue("S2", "Volume", 5);
}

// Clients send File values as separate multipart parts, so a row with a file omits that key from its JSON
@Test
public void testImportRowsWithPartialAttachments() throws Exception
{
MockPart file = new MockPart("Attachment::0::0", "attachment.txt", "attachment content".getBytes(StringUtilsLabKey.DEFAULT_CHARSET));

MockHttpServletResponse response = postSaveRows("importRows", List.of(
Map.of("Name", "S1"),
Map.of("Name", "S2", "Attachment", JSONObject.NULL)), file);
assertEquals("importRows with attachments failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus());

assertValue("S1", "Attachment", "attachment.txt");
assertValue("S2", "Attachment", null);
}

@Test
public void testMixedKeyCasingImportRows() throws Exception
{
assertMixedKeyCasing("importRows");
}

@Test
public void testMixedKeyCasingInsert() throws Exception
{
assertMixedKeyCasing("insert");
}

@Test
public void testMixedKeyCasingUpdate() throws Exception
{
saveRows("insert", List.of(
Map.of("Name", "S1", "Description", "a"),
Map.of("Name", "S2", "Description", "b")));

saveRows("update", List.of(
Map.of("Name", "S1", "Description", "a2"),
Map.of("Name", "S2", "description", "b2")));

assertValue("S1", "Description", "a2");
assertValue("S2", "Description", "b2");
}

private void assertMixedKeyCasing(String command) throws Exception
{
saveRows(command, List.of(
Map.of("Name", "S1", "Description", "a"),
Map.of("Name", "S2", "description", "b")));

assertValue("S1", "Description", "a");
assertValue("S2", "Description", "b");
}

private @NotNull TableInfo getTable()
{
ListDefinition ld = ListService.get().getList(JunitUtil.getTestContainer(), _listName);
assertNotNull(ld);
TableInfo table = ld.getTable(TestContext.get().getUser());
assertNotNull(table);
return table;
}

private void saveRows(String commandName, List<Map<String, Object>> rows) throws Exception
{
MockHttpServletResponse response = postSaveRows(commandName, rows);
assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus());
}

private MockHttpServletResponse postSaveRows(String commandName, List<Map<String, Object>> rows) throws Exception
{
return postSaveRows(commandName, rows, null);
}

private MockHttpServletResponse postSaveRows(String commandName, List<Map<String, Object>> rows, @Nullable MockPart file) throws Exception
{
JSONObject command = new JSONObject();
command.put("command", commandName);
command.put("schemaName", "lists");
command.put("queryName", _listName);
command.put("rows", new JSONArray(rows));

JSONObject json = new JSONObject();
json.put("commands", List.of(command));

ActionURL url = new ActionURL(QueryController.SaveRowsAction.class, JunitUtil.getTestContainer());
User user = TestContext.get().getUser();
if (null == file)
return ViewServlet.POST(url, user, Map.of("Content-Type", "application/json"), json.toString());

// Mirror @labkey/api: rows travel in a "json" form field, files in their own parts. The mock request reads
// parameters only from its URL, so "json" also goes there to stand in for the container's form-field parsing.
url.addParameter("json", json.toString());
MockHttpServletRequest request = (MockHttpServletRequest) ViewServlet.mockRequest(RequestMethod.POST.name(), url, user, Map.of("Content-Type", "multipart/form-data; boundary=ImportRowsTestCase"), null);
request.addPart(new MockPart("json", json.toString().getBytes(StringUtilsLabKey.DEFAULT_CHARSET)));
request.addPart(file);
return ViewServlet.mockDispatch(request, null);
}

private void assertValue(String key, String column, @Nullable Object expected)
{
Class<?> type = null == expected ? Object.class : expected.getClass();
Object actual = new TableSelector(getTable(), PageFlowUtil.set(column)).getObject(key, type);
assertEquals(column + " of " + key, expected, actual);
}
}
50 changes: 43 additions & 7 deletions query/src/org/labkey/query/controllers/QueryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
import org.labkey.api.dataiterator.DataIteratorBuilder;
import org.labkey.api.dataiterator.DataIteratorContext;
import org.labkey.api.dataiterator.DetailedAuditLogDataIterator;
import org.labkey.api.dataiterator.ListofMapsDataIterator;
import org.labkey.api.dataiterator.MapDataIterator;
import org.labkey.api.exceptions.OptimisticConflictException;
import org.labkey.api.exp.ExperimentException;
import org.labkey.api.exp.api.ProvenanceRecordingParams;
Expand Down Expand Up @@ -223,6 +223,7 @@
import org.labkey.api.settings.AdminConsole;
import org.labkey.api.settings.AppProps;
import org.labkey.api.settings.LookAndFeelProperties;
import org.labkey.api.settings.OptionalFeatureService;
import org.labkey.api.stats.BaseAggregatesAnalyticsProvider;
import org.labkey.api.stats.ColumnAnalyticsProvider;
import org.labkey.api.util.ButtonBuilder;
Expand Down Expand Up @@ -4543,7 +4544,7 @@ public List<Map<String, Object>> saveRows(QueryUpdateService qus, List<Map<Strin
throws SQLException, BatchValidationException
{
BatchValidationException errors = new BatchValidationException();
DataIteratorBuilder it = new ListofMapsDataIterator.Builder(rows.getFirst().keySet(), rows);
DataIteratorBuilder it = MapDataIterator.of(rows);
qus.importRows(user, container, it, errors, configParameters, extraContext);
if (errors.hasErrors())
throw errors;
Expand Down Expand Up @@ -4799,6 +4800,11 @@ private JSONObject executeJson(TracedOperation op, JSONObject json, CommandType
if (commandType == CommandType.insert || commandType == CommandType.insertWithKeys || commandType == CommandType.delete)
f = new RowMapFactory<>();
CaseInsensitiveHashMap<Object> referenceCasing = new CaseInsensitiveHashMap<>();
// GH Issue 1867: row maps share casing state, so a later row's spelling of a key would hide earlier rows' values
CaseInsensitiveHashMap<String> keySpellings = new CaseInsensitiveHashMap<>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Manual testing: Bug. The square-rows check runs before addRowAttachments. @labkey/api's bindSaveRowsCommand deletes File values from each row and sends them as separate multipart parts. So in a list with an attachment field, if row 0 has a File and row 1 sends Attachment: null, the server sees row 0 without the key and row 1 with it. The request gets rejected even though the user sent the same fields in every row.

I wrote up a regression test and it was able to reproduce this problem. Attached is a patch with the test and a suggested fix. Feel free to revise and/or move the test to a different test since it sits in a different repo.

1867FileAttachments.patch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the test into ImportRowsTestCase to keep this in one PR. A little clunky in terms of the multipart submission but I confirmed it fails without the fix and passes with it.

Set<String> firstRowKeys = null;
boolean requireSquareRows = commandType == CommandType.importRows &&
!OptionalFeatureService.get().isFeatureEnabled(QueryService.DEPRECATED_ALLOW_RAGGED_IMPORT_ROWS);
boolean loggedConflictingCasing = false;

for (int idx = 0; idx < rows.length(); ++idx)
Expand All @@ -4816,15 +4822,34 @@ private JSONObject executeJson(TracedOperation op, JSONObject json, CommandType
{
Map<String, Object> rowMap = null == f ? new CaseInsensitiveHashMap<>(new HashMap<>(), referenceCasing) : f.getRowMap();
// Use shallow copy since jsonObj.toMap() will translate contained JSONObjects into Maps, which we don't want
boolean conflictingCasing = JsonUtil.fillMapShallow(jsonObj, rowMap);
boolean conflictingCasing = false;
for (String key : jsonObj.keySet())
{
Object value = jsonObj.get(key);
conflictingCasing |= rowMap.put(getKeySpelling(keySpellings, key), JSONObject.NULL == value ? null : value) != null;
}
// Clients send files as separate parts, so they must be in the row before comparing its fields
if (allowRowAttachments())
addRowAttachments(rowMap, idx, commandIndex, keySpellings);
if (requireSquareRows)
{
Set<String> rowKeys = new HashSet<>(rowMap.keySet());
if (null == firstRowKeys)
firstRowKeys = rowKeys;
else if (!firstRowKeys.equals(rowKeys))
{
Set<String> expected = firstRowKeys;
throw new IllegalArgumentException("rows[" + idx + "] must supply the same fields as rows[0]. Missing: " +
expected.stream().filter(k -> !rowKeys.contains(k)).sorted().toList() + "; unexpected: " +
rowKeys.stream().filter(k -> !expected.contains(k)).sorted().toList() + ".");
}
}
if (conflictingCasing && !loggedConflictingCasing)
{
loggedConflictingCasing = true;
// Issue 52616; GH Issue 1332: log once per request, not once per conflicting row
LOG.error("Row contained conflicting casing for key names in the incoming row: {}", jsonObj);
}
if (allowRowAttachments())
addRowAttachments(rowMap, idx, commandIndex);

rowsToProcess.add(rowMap);
rowsAffected++;
Expand Down Expand Up @@ -5004,7 +5029,18 @@ protected boolean allowRowAttachments()
return false;
}

private void addRowAttachments(Map<String, Object> rowMap, int rowIndex, @Nullable Integer commandIndex)
private static String getKeySpelling(CaseInsensitiveHashMap<String> keySpellings, String key)
{
String spelling = keySpellings.get(key);
if (null == spelling)
{
spelling = key;
keySpellings.put(key, key);
}
return spelling;
}

private void addRowAttachments(Map<String, Object> rowMap, int rowIndex, @Nullable Integer commandIndex, CaseInsensitiveHashMap<String> keySpellings)
{
if (getFileMap() != null)
{
Expand Down Expand Up @@ -5045,7 +5081,7 @@ private void addRowAttachments(Map<String, Object> rowMap, int rowIndex, @Nullab
}

SpringAttachmentFile file = new SpringAttachmentFile(fileEntry.getValue());
rowMap.put(fieldKey, file.isEmpty() ? null : file);
rowMap.put(getKeySpelling(keySpellings, fieldKey), file.isEmpty() ? null : file);
}
}
}
Expand Down
Loading