From b4875da2d6c32dd74d3812b5059ca34b702a1925 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sat, 7 Nov 2026 08:51:52 -0800 Subject: [PATCH 1/9] GH Issue 1867: Add failing test for importRows dropping later rows' extra columns --- query/src/org/labkey/query/QueryModule.java | 2 + .../query/controllers/ImportRowsTestCase.java | 112 ++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 query/src/org/labkey/query/controllers/ImportRowsTestCase.java diff --git a/query/src/org/labkey/query/QueryModule.java b/query/src/org/labkey/query/QueryModule.java index 8eb000a658d..4437bb151e0 100644 --- a/query/src/org/labkey/query/QueryModule.java +++ b/query/src/org/labkey/query/QueryModule.java @@ -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; @@ -391,6 +392,7 @@ public Set getSchemaNames() ModuleReportCache.TestCase.class, OlapController.TestCase.class, OlapController.ContainerScopingTestCase.class, + ImportRowsTestCase.class, QueryController.SaveRowsTestCase.class, QueryController.TestCase.class, QueryServiceImpl.TestCase.class, diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java new file mode 100644 index 00000000000..7a05a698284 --- /dev/null +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -0,0 +1,112 @@ +/* + * 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.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.labkey.api.data.Container; +import org.labkey.api.data.ContainerManager; +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.list.ListDefinition; +import org.labkey.api.exp.list.ListService; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.query.DetailsURL; +import org.labkey.api.security.User; +import org.labkey.api.util.PageFlowUtil; +import org.labkey.api.util.TestContext; +import org.labkey.api.view.ViewServlet; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.bind.annotation.RequestMethod; + +import java.util.List; +import java.util.Map; + +/** GH Issue 1867: importRows must import every row's values, not just the first row's columns */ +public class ImportRowsTestCase extends Assert +{ + private static final String PROJECT_NAME = "ImportRowsTestProject"; + private static final String LIST_NAME = "ImportRowsSparseList"; + + @Before + public void doSetup() throws Exception + { + doCleanup(); + User user = TestContext.get().getUser(); + Container project = ContainerManager.createContainer(ContainerManager.getRoot(), PROJECT_NAME, user); + ContainerManager.updateSearchable(project, false, user); + + ListDefinition ld = ListService.get().createList(project, LIST_NAME, 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)); + ld.setKeyName("Name"); + ld.save(user); + } + + @After + public void doCleanup() + { + Container project = ContainerManager.getForPath(PROJECT_NAME); + if (project != null) + ContainerManager.deleteAll(project, TestContext.get().getUser()); + } + + @Test + public void testKeysAbsentFromFirstRow() throws Exception + { + User user = TestContext.get().getUser(); + Container project = ContainerManager.getForPath(PROJECT_NAME); + assertNotNull(project); + + JSONArray rows = new JSONArray(); + rows.put(Map.of("Name", "S1")); + rows.put(Map.of("Name", "S2", "Description", "x", "Volume", 5)); + + JSONObject command = new JSONObject(); + command.put("command", "importRows"); + command.put("schemaName", "lists"); + command.put("queryName", LIST_NAME); + command.put("rows", rows); + + JSONObject json = new JSONObject(); + json.put("commands", List.of(command)); + + HttpServletRequest request = ViewServlet.mockRequest(RequestMethod.POST.name(), + DetailsURL.fromString("/query/saveRows.view").copy(project).getActionURL(), user, + Map.of("Content-Type", "application/json"), json.toString()); + MockHttpServletResponse response = ViewServlet.mockDispatch(request, null); + assertEquals("saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); + + ListDefinition ld = ListService.get().getList(project, LIST_NAME); + assertNotNull(ld); + TableInfo table = ld.getTable(user); + assertNotNull(table); + assertEquals("Incorrect row count", 2L, new TableSelector(table).getRowCount()); + assertEquals("Description of S2", "x", new TableSelector(table, PageFlowUtil.set("Description")).getObject("S2", String.class)); + assertEquals("Volume of S2", Integer.valueOf(5), new TableSelector(table, PageFlowUtil.set("Volume")).getObject("S2", Integer.class)); + } +} From 89615aaf3b40430f3f36aa38a87508aa4da4c02a Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sat, 7 Nov 2026 18:06:07 -0800 Subject: [PATCH 2/9] GH Issue 1867: Build importRows columns from every row's keys, not just the first --- query/src/org/labkey/query/controllers/QueryController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index 254baab0dfe..fb70d1e47a7 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -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; @@ -4543,7 +4543,7 @@ public List> saveRows(QueryUpdateService qus, List Date: Sun, 8 Nov 2026 15:20:34 -0800 Subject: [PATCH 3/9] GH Issue 1867: Add failing tests for mixed key casing and omitted-column defaults --- .../query/controllers/ImportRowsTestCase.java | 116 +++++++++++++++--- 1 file changed, 100 insertions(+), 16 deletions(-) diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java index 7a05a698284..31cdf791f5c 100644 --- a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -17,6 +17,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; import org.junit.After; @@ -43,11 +44,12 @@ import java.util.List; import java.util.Map; -/** GH Issue 1867: importRows must import every row's values, not just the first row's columns */ +/** GH Issue 1867: saveRows must keep each row's values when rows differ in which keys they supply or how they case them */ public class ImportRowsTestCase extends Assert { private static final String PROJECT_NAME = "ImportRowsTestProject"; private static final String LIST_NAME = "ImportRowsSparseList"; + private static final String STATUS_DEFAULT = "Pending"; @Before public void doSetup() throws Exception @@ -63,6 +65,8 @@ public void doSetup() throws Exception domain.addProperty(new PropertyStorageSpec("Name", JdbcType.VARCHAR)); domain.addProperty(new PropertyStorageSpec("Description", JdbcType.VARCHAR)); domain.addProperty(new PropertyStorageSpec("Volume", JdbcType.INTEGER)); + // Provisioned as a database DEFAULT, the only kind of default API inserts honor + domain.addProperty(new PropertyStorageSpec("Status", JdbcType.VARCHAR, 50, true, STATUS_DEFAULT)); ld.setKeyName("Name"); ld.save(user); } @@ -78,35 +82,115 @@ public void doCleanup() @Test public void testKeysAbsentFromFirstRow() throws Exception { - User user = TestContext.get().getUser(); + saveRows("importRows", List.of( + Map.of("Name", "S1"), + Map.of("Name", "S2", "Description", "x", "Volume", 5))); + + assertEquals("Incorrect row count", 2L, new TableSelector(getTable()).getRowCount()); + assertValue("S2", "Description", "x"); + assertValue("S2", "Volume", 5); + } + + @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"); + } + + @Test + public void testOmittedColumnDefaultImportRows() throws Exception + { + assertOmittedColumnDefault("importRows"); + } + + @Test + public void testOmittedColumnDefaultInsert() throws Exception + { + assertOmittedColumnDefault("insert"); + } + + 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 void assertOmittedColumnDefault(String command) throws Exception + { + // Proves the database default exists, so a mixed-request failure below is the bug, not the setup + saveRows(command, List.of(Map.of("Name", "S0"))); + assertValue("S0", "Status", STATUS_DEFAULT); + + saveRows(command, List.of( + Map.of("Name", "S1"), + Map.of("Name", "S2", "Status", "Done"))); + + assertValue("S1", "Status", STATUS_DEFAULT); + assertValue("S2", "Status", "Done"); + } + + private static @NotNull Container getProject() + { Container project = ContainerManager.getForPath(PROJECT_NAME); assertNotNull(project); + return project; + } - JSONArray rows = new JSONArray(); - rows.put(Map.of("Name", "S1")); - rows.put(Map.of("Name", "S2", "Description", "x", "Volume", 5)); + private static @NotNull TableInfo getTable() + { + ListDefinition ld = ListService.get().getList(getProject(), LIST_NAME); + assertNotNull(ld); + TableInfo table = ld.getTable(TestContext.get().getUser()); + assertNotNull(table); + return table; + } + private static void saveRows(String commandName, List> rows) throws Exception + { JSONObject command = new JSONObject(); - command.put("command", "importRows"); + command.put("command", commandName); command.put("schemaName", "lists"); command.put("queryName", LIST_NAME); - command.put("rows", rows); + command.put("rows", new JSONArray(rows)); JSONObject json = new JSONObject(); json.put("commands", List.of(command)); HttpServletRequest request = ViewServlet.mockRequest(RequestMethod.POST.name(), - DetailsURL.fromString("/query/saveRows.view").copy(project).getActionURL(), user, + DetailsURL.fromString("/query/saveRows.view").copy(getProject()).getActionURL(), TestContext.get().getUser(), Map.of("Content-Type", "application/json"), json.toString()); MockHttpServletResponse response = ViewServlet.mockDispatch(request, null); - assertEquals("saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); + assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); + } - ListDefinition ld = ListService.get().getList(project, LIST_NAME); - assertNotNull(ld); - TableInfo table = ld.getTable(user); - assertNotNull(table); - assertEquals("Incorrect row count", 2L, new TableSelector(table).getRowCount()); - assertEquals("Description of S2", "x", new TableSelector(table, PageFlowUtil.set("Description")).getObject("S2", String.class)); - assertEquals("Volume of S2", Integer.valueOf(5), new TableSelector(table, PageFlowUtil.set("Volume")).getObject("S2", Integer.class)); + private static void assertValue(String key, String column, @NotNull Object expected) + { + Object actual = new TableSelector(getTable(), PageFlowUtil.set(column)).getObject(key, expected.getClass()); + assertEquals(column + " of " + key, expected, actual); } } From 9b1970dc02f2806c592bcca90c01994e94ee46d0 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Sun, 8 Nov 2026 16:03:17 -0800 Subject: [PATCH 4/9] GH Issue 1867: Keep earlier rows' values under mixed key casing and apply DB defaults to omitted columns --- .../labkey/api/collections/ArrayListMap.java | 5 +- .../CaseInsensitiveMapWrapper.java | 31 ++++++++--- .../query/controllers/QueryController.java | 51 +++++++++++++++++++ 3 files changed, 79 insertions(+), 8 deletions(-) diff --git a/api/src/org/labkey/api/collections/ArrayListMap.java b/api/src/org/labkey/api/collections/ArrayListMap.java index 8d9ce59c5a3..f90b8609864 100644 --- a/api/src/org/labkey/api/collections/ArrayListMap.java +++ b/api/src/org/labkey/api/collections/ArrayListMap.java @@ -231,8 +231,9 @@ public boolean containsKey(Object key) if (I == null) return false; int i = I.intValue(); - Object v = i>=_row.size() ? null : _row.get(i); - return v != DOES_NOT_CONTAINKEY; + // A key added to the shared find map after this row was filled is absent here, not null + Object v = i>=_row.size() ? DOES_NOT_CONTAINKEY : _row.get(i); + return v != DOES_NOT_CONTAINKEY; } diff --git a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java index 8c248062830..1d31ade5fd5 100644 --- a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java +++ b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java @@ -32,7 +32,9 @@ public class CaseInsensitiveMapWrapper extends MapWrapper implements Serializable, CaseInsensitiveCollection { - private final Map _correctCaseMap; + private Map _correctCaseMap; + // Set when other maps share _correctCaseMap, so re-casing a key here would orphan their entries + private boolean _sharedCaseMap; public CaseInsensitiveMapWrapper(Map map) { @@ -43,11 +45,27 @@ public CaseInsensitiveMapWrapper(Map map, @Nullable CaseInsensitiveMa { super(map); _correctCaseMap = caseMapping == null ? new HashMap<>() : caseMapping._correctCaseMap; + // Wrapping the caseMapping itself shares its case map exactly as widely as that map already does + if (caseMapping == map) + _sharedCaseMap = caseMapping._sharedCaseMap; + else if (caseMapping != null) + { + _sharedCaseMap = true; + caseMapping._sharedCaseMap = true; + } for (Map.Entry entry : map.entrySet()) { - if (entry.getKey() != null) + String key = entry.getKey(); + if (key != null) { - _correctCaseMap.put(entry.getKey().toLowerCase(), entry.getKey()); + String existing = _correctCaseMap.get(key.toLowerCase()); + // A wrapped key can't be re-cased, so take a private case map instead of re-casing the shared one + if (_sharedCaseMap && existing != null && !existing.equals(key)) + { + _correctCaseMap = new HashMap<>(_correctCaseMap); + _sharedCaseMap = false; + } + _correctCaseMap.put(key.toLowerCase(), key); } } } @@ -81,9 +99,10 @@ public V put(String key, V value) { ret = remove(correctKey); } - _map.put(key, value); -// assert !_correctCaseMap.containsKey(key.toLowerCase()); - _correctCaseMap.put(null==key?null:key.toLowerCase(), key); + // GH Issue 1867: with a shared case map, store under the existing casing so other maps still find their entries + String storedKey = _sharedCaseMap && correctKey != null ? correctKey : key; + _map.put(storedKey, value); + _correctCaseMap.put(null==key?null:key.toLowerCase(), storedKey); return ret; } diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index fb70d1e47a7..55e2fe94390 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -111,6 +111,7 @@ import org.labkey.api.data.DisplayColumn; import org.labkey.api.data.ExcelWriter; import org.labkey.api.data.ForeignKey; +import org.labkey.api.data.ImportAliasable; import org.labkey.api.data.JdbcMetaDataSelector; import org.labkey.api.data.JdbcType; import org.labkey.api.data.JsonWriter; @@ -353,6 +354,7 @@ import java.util.TreeSet; import java.util.function.BiFunction; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -4909,6 +4911,8 @@ private JSONObject executeJson(TracedOperation op, JSONObject json, CommandType } QueryService.get().setEnvironment(QueryService.Environment.CONTAINER, container); + if (commandType == CommandType.insert || commandType == CommandType.importRows) + applyDatabaseDefaults(table, rowsToProcess); List> responseRows = commandType.saveRows(qus, rowsToProcess, getUser(), container, configParameters, extraContext); if (auditEvent != null) @@ -4999,6 +5003,53 @@ else if (commandType != CommandType.importRows) return response; } + /** GH Issue 1867: a row that omits a column other rows supply gets the database default, as it would if every row omitted it */ + private static void applyDatabaseDefaults(TableInfo table, List> rows) + { + // generate_series is PostgreSQL; external data sources may use other dialects + if (rows.size() < 2 || !table.getSqlDialect().isPostgreSQL()) + return; + + Map importMap = ImportAliasable.Helper.createImportMap(table.getColumns(), false); + Map suppliedKeys = new LinkedHashMap<>(); + List> suppliedByRow = new ArrayList<>(rows.size()); + for (Map row : rows) + { + Set supplied = new HashSet<>(); + for (String key : row.keySet()) + { + ColumnInfo col = importMap.get(key); + if (col != null && col.getJdbcDefaultValue() != null && !col.isAutoIncrement() && !col.isCalculated() && + col.getJdbcType() != JdbcType.ARRAY) + { + supplied.add(col); + suppliedKeys.putIfAbsent(col, key); + } + } + suppliedByRow.add(supplied); + } + + for (Map.Entry entry : suppliedKeys.entrySet()) + { + ColumnInfo col = entry.getKey(); + List> omitting = IntStream.range(0, rows.size()) + .filter(i -> !suppliedByRow.get(i).contains(col)) + .mapToObj(rows::get) + .toList(); + if (omitting.isEmpty()) + continue; + + // The expression comes from the database catalog; selecting one value per row keeps volatile defaults per-row + SQLFragment sql = new SQLFragment().unsafeAppend("SELECT ") + .append(new SQLFragment().setSqlUnsafe(col.getJdbcDefaultValue())) + .unsafeAppend(" FROM generate_series(1, ?)", omitting.size()); + List defaults = new ArrayList<>(omitting.size()); + new SqlSelector(table.getSchema().getScope(), sql).forEach(rs -> defaults.add(rs.getObject(1))); + for (int i = 0; i < omitting.size(); i++) + omitting.get(i).put(entry.getValue(), defaults.get(i)); + } + } + protected boolean allowRowAttachments() { return false; From 0c248ee961054204be640150124c3cea1257adab Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 9 Nov 2026 11:03:02 -0800 Subject: [PATCH 5/9] GH Issue 1867: Add failing tests for omitted-column defaults on insertWithKeys and direct insertRows callers --- .../query/controllers/ImportRowsTestCase.java | 94 ++++++++++++++++++- 1 file changed, 93 insertions(+), 1 deletion(-) diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java index 31cdf791f5c..a0b56acc1d1 100644 --- a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -26,25 +26,33 @@ import org.junit.Test; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; +import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.JdbcType; +import org.labkey.api.data.MultiChoice; 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.query.BatchValidationException; import org.labkey.api.query.DetailsURL; +import org.labkey.api.query.QueryUpdateService; import org.labkey.api.security.User; +import org.labkey.api.test.TestTimeout; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.TestContext; import org.labkey.api.view.ViewServlet; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.bind.annotation.RequestMethod; +import java.util.ArrayList; import java.util.List; import java.util.Map; -/** GH Issue 1867: saveRows must keep each row's values when rows differ in which keys they supply or how they case them */ +/** GH Issue 1867: inserts must keep each row's values, and give each omitted column its default, when rows differ in which keys they supply or how they case them */ +@TestTimeout(TestTimeout.DEFAULT * 5) // Each test creates and deletes a project public class ImportRowsTestCase extends Assert { private static final String PROJECT_NAME = "ImportRowsTestProject"; @@ -67,6 +75,8 @@ public void doSetup() throws Exception domain.addProperty(new PropertyStorageSpec("Volume", JdbcType.INTEGER)); // Provisioned as a database DEFAULT, the only kind of default API inserts honor domain.addProperty(new PropertyStorageSpec("Status", JdbcType.VARCHAR, 50, true, STATUS_DEFAULT)); + // Multi-choice columns are provisioned NOT NULL DEFAULT '{}'; the dialect rejects any other default for ARRAY + domain.addProperty(new PropertyStorageSpec("Tags", JdbcType.ARRAY)).setRangeURI(PropertyType.MULTI_CHOICE.getTypeUri()); ld.setKeyName("Name"); ld.save(user); } @@ -130,6 +140,59 @@ public void testOmittedColumnDefaultInsert() throws Exception assertOmittedColumnDefault("insert"); } + @Test + public void testOmittedColumnDefaultInsertWithKeys() throws Exception + { + saveRows("insertWithKeys", List.of(Map.of("values", Map.of("Name", "S0")))); + assertValue("S0", "Status", STATUS_DEFAULT); + + saveRows("insertWithKeys", List.of( + Map.of("values", Map.of("Name", "S1")), + Map.of("values", Map.of("Name", "S2", "Status", "Done")))); + + assertValue("S1", "Status", STATUS_DEFAULT); + assertValue("S2", "Status", "Done"); + } + + @Test + public void testOmittedColumnDefaultUpdateService() throws Exception + { + insertRows(List.of(row("Name", "S0"))); + assertValue("S0", "Status", STATUS_DEFAULT); + + insertRows(List.of( + row("Name", "S1"), + row("Name", "S2", "Status", "Done"))); + + assertValue("S1", "Status", STATUS_DEFAULT); + assertValue("S2", "Status", "Done"); + } + + @Test + public void testExplicitNullUpdateService() throws Exception + { + insertRows(List.of( + row("Name", "S1", "Status", null), + row("Name", "S2", "Status", "Done", "Description", "x"))); + + assertNull("Status of S1", new TableSelector(getTable(), PageFlowUtil.set("Status")).getObject("S1", String.class)); + assertValue("S2", "Status", "Done"); + } + + @Test + public void testOmittedMultiChoiceDefault() throws Exception + { + saveRows("insert", List.of(Map.of("Name", "S0"))); + assertMultiChoiceValue("S0", List.of()); + + saveRows("insert", List.of( + Map.of("Name", "S1"), + Map.of("Name", "S2", "Tags", List.of("a", "b")))); + + assertMultiChoiceValue("S1", List.of()); + assertMultiChoiceValue("S2", List.of("a", "b")); + } + private void assertMixedKeyCasing(String command) throws Exception { saveRows(command, List.of( @@ -188,6 +251,35 @@ private static void saveRows(String commandName, List> rows) assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); } + private static void insertRows(List> rows) throws Exception + { + User user = TestContext.get().getUser(); + QueryUpdateService qus = getTable().getUpdateService(); + assertNotNull(qus); + BatchValidationException errors = new BatchValidationException(); + qus.insertRows(user, getProject(), new ArrayList<>(rows), errors, null, null); + if (errors.hasErrors()) + throw errors; + } + + /** Unlike Map.of, allows null values */ + private static Map row(Object... keysAndValues) + { + Map row = new CaseInsensitiveHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) + row.put((String) keysAndValues[i], keysAndValues[i + 1]); + return row; + } + + private static void assertMultiChoiceValue(String key, List expected) + { + Object actual = new TableSelector(getTable(), PageFlowUtil.set("Tags")).getObject(key, Object.class); + // The multi-choice converter maps null to an empty array, so check the raw value before converting + assertNotNull("Tags of " + key, actual); + assertEquals("Tags of " + key, MultiChoice.Converter.getInstance().convert(MultiChoice.Array.class, expected), + MultiChoice.Converter.getInstance().convert(MultiChoice.Array.class, actual)); + } + private static void assertValue(String key, String column, @NotNull Object expected) { Object actual = new TableSelector(getTable(), PageFlowUtil.set(column)).getObject(key, expected.getClass()); From 9107e1606e8e42594c7154ae055e641921d4f3d6 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 9 Nov 2026 12:33:52 -0800 Subject: [PATCH 6/9] GH Issue 1867: Give columns a row omits their database default on every insert path Replaces the saveRows-only PostgreSQL backfill with a per-row omitted marker honored by the insert statement, so explicit nulls still store NULL. --- .../org/labkey/api/data/StatementUtils.java | 43 +++++++++++++++- .../dataiterator/AbstractMapDataIterator.java | 27 ++++++++++ .../api/dataiterator/DataIteratorContext.java | 24 +++++++++ .../dataiterator/ListofMapsDataIterator.java | 8 +++ .../dataiterator/StatementDataIterator.java | 20 +++++++- .../TableInsertUpdateDataIterator.java | 28 ++++++++++ .../api/query/AbstractQueryUpdateService.java | 15 ++++++ .../query/controllers/QueryController.java | 51 ------------------- 8 files changed, 161 insertions(+), 55 deletions(-) diff --git a/api/src/org/labkey/api/data/StatementUtils.java b/api/src/org/labkey/api/data/StatementUtils.java index 7055083138c..8627055e368 100644 --- a/api/src/org/labkey/api/data/StatementUtils.java +++ b/api/src/org/labkey/api/data/StatementUtils.java @@ -82,6 +82,7 @@ public enum Operation {insert, update, merge} private final TableInfo _targetTable; private Set _keyColumnNames = null; // override the primary key of _table private Set _skipColumnNames = Set.of(); + private Set _omittableColumnNames = Set.of(); private final Set _dontUpdateColumnNames = new CaseInsensitiveHashSet(); private boolean _updateBuiltInColumns = false; // default to false, this should usually be handled by StandardDataIteratorBuilder private boolean _selectIds = false; @@ -151,6 +152,29 @@ public StatementUtils skip(Set skip) return this; } + /** Insert columns that get their database default in rows binding {@link #useDefaultParameterName} to 1 */ + public StatementUtils omittable(Set omittable) + { + _omittableColumnNames = null==omittable ? Set.of() : omittable; + return this; + } + + public static String useDefaultParameterName(String columnName) + { + return columnName + "$useDefault"; + } + + private boolean isInlineableDefault(@Nullable String defaultValue) + { + if (null == defaultValue) + return false; + if (_dialect.isPostgreSQL()) + return true; + // SQL Server allows sequence and NEWSEQUENTIALID() defaults only in a DEFAULT constraint, not inside CASE + String upper = defaultValue.toUpperCase(); + return _dialect.isSqlServer() && !upper.contains("NEXT VALUE FOR") && !upper.contains("NEWSEQUENTIALID"); + } + public StatementUtils noupdate(Set noupdate) { if (null != noupdate) @@ -750,10 +774,25 @@ else if (column.getName().equalsIgnoreCase(updatable.getObjectURIColumnName()) & } else { - if (null != _skipColumnNames && _skipColumnNames.contains(Objects.toString(remap.get(name),name))) + String inputName = Objects.toString(remap.get(name),name); + if (null != _skipColumnNames && _skipColumnNames.contains(inputName)) continue; ParameterHolder ph = createParameter(column); - appendParameterOrVariable(valueSQL, ph); + if (Operation.insert == _operation && _omittableColumnNames.contains(inputName) && !ph.isConstant && + !column.isAutoIncrement() && isInlineableDefault(column.getJdbcDefaultValue())) + { + // GH Issue 1867: these dialects report the default as an expression, so evaluate it per row rather than splitting the batch by omitted columns + ParameterHolder useDefault = createParameter(useDefaultParameterName(name), JdbcType.INTEGER); + valueSQL.unsafeAppend("CASE WHEN "); + appendParameterOrVariable(valueSQL, useDefault); + valueSQL.unsafeAppend(" = 1 THEN (").append(new SQLFragment().setSqlUnsafe(column.getJdbcDefaultValue())).unsafeAppend(") ELSE "); + appendParameterOrVariable(valueSQL, ph); + valueSQL.unsafeAppend(" END"); + } + else + { + appendParameterOrVariable(valueSQL, ph); + } } cols.add(column); values.add(valueSQL); diff --git a/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java b/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java index 8e7aa4f3943..f4abe055883 100644 --- a/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java @@ -26,6 +26,7 @@ import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; +import java.util.BitSet; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -114,6 +115,7 @@ public void debugLogInfo(StringBuilder sb) public static class ListOfMapsDataIterator extends AbstractMapDataIterator { protected List> _rows; + private Map _omittedColumnRows = Map.of(); protected ListOfMapsDataIterator(DataIteratorContext context, Set colsNames) { @@ -152,6 +154,31 @@ public ListOfMapsDataIterator(DataIteratorContext context, Set colNames, _cols.add(new BaseColumnInfo(name, JdbcType.OTHER)); } _rows = initRows(rows); + _omittedColumnRows = findOmittedColumnRows(); + context.setOmittedColumnRows(_omittedColumnRows); + } + + Map getOmittedColumnRows() + { + return _omittedColumnRows; + } + + private Map findOmittedColumnRows() + { + Map omitted = new CaseInsensitiveHashMap<>(); + for (int col = 1; col < _cols.size(); col++) + { + String name = _cols.get(col).getName(); + BitSet rowNumbers = new BitSet(); + for (int row = 0; row < _rows.size(); row++) + { + if (!_rows.get(row).containsKey(name)) + rowNumbers.set(row + 1); + } + if (!rowNumbers.isEmpty()) + omitted.put(name, rowNumbers); + } + return omitted; } protected List> initRows(List> rows) diff --git a/api/src/org/labkey/api/dataiterator/DataIteratorContext.java b/api/src/org/labkey/api/dataiterator/DataIteratorContext.java index d7ef807b39b..83e5d7940e2 100644 --- a/api/src/org/labkey/api/dataiterator/DataIteratorContext.java +++ b/api/src/org/labkey/api/dataiterator/DataIteratorContext.java @@ -24,6 +24,7 @@ import org.labkey.api.query.QueryImportPipelineJob; import org.labkey.api.query.QueryUpdateService; +import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -61,6 +62,7 @@ public class DataIteratorContext private final Set _alternateKeys = new CaseInsensitiveHashSet(); private String _dataSource; private boolean _withLookupRemapping = true; + private Map _omittedColumnRows = null; private final Map _responseInfo = new HashMap<>(); // information from the import/loadRows context to be passed back to the API response object private Logger _logger; @@ -245,6 +247,28 @@ public void addAlternateKeys(Set alternateKeys) _alternateKeys.addAll(alternateKeys); } + /** GH Issue 1867: by input column name, the row numbers whose source row omits that column, so inserts can give them the database default */ + @NotNull + public Map getOmittedColumnRows() + { + return null == _omittedColumnRows ? Map.of() : _omittedColumnRows; + } + + /** First registration wins: the pipeline's own source is built before any nested pipeline that shares this context */ + public void setOmittedColumnRows(@NotNull Map omittedColumnRows) + { + if (null == _omittedColumnRows) + _omittedColumnRows = omittedColumnRows; + } + + /** Scopes registration to one pipeline: returns the current map, to be restored when that pipeline finishes */ + public @Nullable Map replaceOmittedColumnRows(@Nullable Map omittedColumnRows) + { + Map previous = _omittedColumnRows; + _omittedColumnRows = omittedColumnRows; + return previous; + } + public boolean shouldCancel() { if (!_errors.hasErrors()) diff --git a/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java b/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java index 2587515a049..49da5a412bb 100644 --- a/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java @@ -37,5 +37,13 @@ public Builder(Set colNames, List> rows) { super(new ListofMapsDataIterator(colNames, rows)); } + + @Override + public DataIterator getDataIterator(DataIteratorContext context) + { + // GH Issue 1867: the iterator was built on a throwaway context, so hand its omitted rows to the pipeline's + context.setOmittedColumnRows(((ListofMapsDataIterator) di).getOmittedColumnRows()); + return di; + } } } diff --git a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java index 05ac9bc51b8..e478612f048 100644 --- a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java @@ -35,6 +35,7 @@ import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SqlExecutor; import org.labkey.api.data.SqlSelector; +import org.labkey.api.data.StatementUtils; import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.dialect.ColumnMetaDataReader; @@ -57,6 +58,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.BitSet; import java.util.Collections; import java.util.Map; import java.util.Set; @@ -94,6 +96,8 @@ public class StatementDataIterator extends AbstractDataIterator Integer _rowIdIndex = null; Integer _objectIdIndex = null; Integer _objectUriIndex = null; + // By this iterator's column name, the row numbers whose source row omitted the column + protected Map _omittedColumnRows = Map.of(); protected int _batchSize = -1; int _currentBatchSize = 0; int _currentTxSize = 0; @@ -204,8 +208,11 @@ void init() if (null != to) { FieldKey mvName = col.getMvColumnName(); + BitSet omittedRows = _omittedColumnRows.get(col.getName()); + Parameter useDefault = null == omittedRows ? null : stmt.getParameter(StatementUtils.useDefaultParameterName(to.getName())); bindings.add(new Triple(_data.getSupplier(i), to, - (null != mvName ? getMvParameter(stmt, mvName) : null))); + (null != mvName ? getMvParameter(stmt, mvName) : null), + useDefault, omittedRows)); } } _bindings[set] = bindings.toArray(new Triple[0]); @@ -240,15 +247,19 @@ public void setBatchSize(int batchSize) private static class Triple { - Triple(Supplier from, Parameter to, Parameter mv) + Triple(Supplier from, Parameter to, Parameter mv, @Nullable Parameter useDefault, @Nullable BitSet omittedRows) { this.from = from; this.to = to; this.mv = mv; + this.useDefault = useDefault; + this.omittedRows = omittedRows; } Supplier from; Parameter to; Parameter mv; + Parameter useDefault; + BitSet omittedRows; } @Override @@ -368,7 +379,12 @@ private boolean _next() throws BatchValidationException { Object value = binding.from.get(); if (null == value) + { + // GH Issue 1867: a row that omitted the column gets its database default; an explicit null stays NULL + if (null != binding.useDefault && binding.omittedRows.get(_currentRowNumber)) + binding.useDefault.setValue(1); continue; + } if (value instanceof MvFieldWrapper) { if (null != binding.mv) diff --git a/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java b/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java index 3a40cec8abe..7a5b8224b97 100644 --- a/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java @@ -24,6 +24,7 @@ import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.DbScope; +import org.labkey.api.data.ImportAliasable; import org.labkey.api.data.Parameter; import org.labkey.api.data.ParameterMapStatement; import org.labkey.api.data.RuntimeSQLException; @@ -41,6 +42,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; +import java.util.BitSet; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; @@ -261,6 +263,7 @@ else if (_insertOption.mergeRows) } else { + _omittedColumnRows = resolveOmittedColumnRows(); stmt = getInsertStatement(constants); } @@ -307,6 +310,7 @@ protected ParameterMapStatement getInsertStatement(Map constants //pass in the voc cols in this builder StatementUtils utils = new StatementUtils(StatementUtils.Operation.insert, _table) .skip(_skipColumnNames) + .omittable(_omittedColumnRows.keySet()) .allowSetAutoIncrement(_context.supportsAutoIncrementKey()) .updateBuiltinColumns(false) .selectIds(_selectIds) @@ -316,6 +320,30 @@ protected ParameterMapStatement getInsertStatement(Map constants return stmt; } + /** Re-keys the source's omitted-column rows from input names (which may be aliases) to this iterator's column names */ + private Map resolveOmittedColumnRows() + { + Map omitted = _context.getOmittedColumnRows(); + if (omitted.isEmpty()) + return Map.of(); + + Map importMap = ImportAliasable.Helper.createImportMap(_table.getColumns(), false); + Map columns = DataIteratorUtil.createColumnNameMap(_data); + Map ret = new CaseInsensitiveHashMap<>(); + omitted.forEach((name, rows) -> { + ColumnInfo col = importMap.get(name); + String columnName = null == col ? name : col.getName(); + // A row omits the column only if it lacks every spelling that maps to it + if (columns.containsKey(columnName)) + ret.merge(columnName, rows, (a, b) -> { + BitSet both = (BitSet) a.clone(); + both.and(b); + return both; + }); + }); + return ret; + } + protected ParameterMapStatement getMergeStatement(Map constants) throws SQLException { ParameterMapStatement stmt; diff --git a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java index 5f1efab37e9..4ccae5b98ec 100644 --- a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java +++ b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java @@ -109,6 +109,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; +import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; @@ -400,6 +401,20 @@ protected int _importRowsUsingDIB(User user, Container container, DataIteratorBu } } + // GH Issue 1867: this pipeline's source registers its own omitted rows; a load nested on this context must not use the outer source's + Map outerOmittedRows = context.replaceOmittedColumnRows(null); + try + { + return _pumpImport(user, container, in, outputRows, context, extraScriptContext); + } + finally + { + context.replaceOmittedColumnRows(outerOmittedRows); + } + } + + private int _pumpImport(User user, Container container, DataIteratorBuilder in, @Nullable ArrayList> outputRows, DataIteratorContext context, @Nullable Map extraScriptContext) + { preImportDIBValidation(in, null); boolean skipTriggers = context.getConfigParameterBoolean(ConfigParameters.SkipTriggers) || context.isCrossTypeImport(); diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index 55e2fe94390..fb70d1e47a7 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -111,7 +111,6 @@ import org.labkey.api.data.DisplayColumn; import org.labkey.api.data.ExcelWriter; import org.labkey.api.data.ForeignKey; -import org.labkey.api.data.ImportAliasable; import org.labkey.api.data.JdbcMetaDataSelector; import org.labkey.api.data.JdbcType; import org.labkey.api.data.JsonWriter; @@ -354,7 +353,6 @@ import java.util.TreeSet; import java.util.function.BiFunction; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -4911,8 +4909,6 @@ private JSONObject executeJson(TracedOperation op, JSONObject json, CommandType } QueryService.get().setEnvironment(QueryService.Environment.CONTAINER, container); - if (commandType == CommandType.insert || commandType == CommandType.importRows) - applyDatabaseDefaults(table, rowsToProcess); List> responseRows = commandType.saveRows(qus, rowsToProcess, getUser(), container, configParameters, extraContext); if (auditEvent != null) @@ -5003,53 +4999,6 @@ else if (commandType != CommandType.importRows) return response; } - /** GH Issue 1867: a row that omits a column other rows supply gets the database default, as it would if every row omitted it */ - private static void applyDatabaseDefaults(TableInfo table, List> rows) - { - // generate_series is PostgreSQL; external data sources may use other dialects - if (rows.size() < 2 || !table.getSqlDialect().isPostgreSQL()) - return; - - Map importMap = ImportAliasable.Helper.createImportMap(table.getColumns(), false); - Map suppliedKeys = new LinkedHashMap<>(); - List> suppliedByRow = new ArrayList<>(rows.size()); - for (Map row : rows) - { - Set supplied = new HashSet<>(); - for (String key : row.keySet()) - { - ColumnInfo col = importMap.get(key); - if (col != null && col.getJdbcDefaultValue() != null && !col.isAutoIncrement() && !col.isCalculated() && - col.getJdbcType() != JdbcType.ARRAY) - { - supplied.add(col); - suppliedKeys.putIfAbsent(col, key); - } - } - suppliedByRow.add(supplied); - } - - for (Map.Entry entry : suppliedKeys.entrySet()) - { - ColumnInfo col = entry.getKey(); - List> omitting = IntStream.range(0, rows.size()) - .filter(i -> !suppliedByRow.get(i).contains(col)) - .mapToObj(rows::get) - .toList(); - if (omitting.isEmpty()) - continue; - - // The expression comes from the database catalog; selecting one value per row keeps volatile defaults per-row - SQLFragment sql = new SQLFragment().unsafeAppend("SELECT ") - .append(new SQLFragment().setSqlUnsafe(col.getJdbcDefaultValue())) - .unsafeAppend(" FROM generate_series(1, ?)", omitting.size()); - List defaults = new ArrayList<>(omitting.size()); - new SqlSelector(table.getSchema().getScope(), sql).forEach(rs -> defaults.add(rs.getObject(1))); - for (int i = 0; i < omitting.size(); i++) - omitting.get(i).put(entry.getValue(), defaults.get(i)); - } - } - protected boolean allowRowAttachments() { return false; From 66bdcbd72ce294f99898a414de4d3781b81a4d0b Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Fri, 13 Nov 2026 17:52:00 -0800 Subject: [PATCH 7/9] Reject ragged JSON rows for import API --- .../labkey/api/collections/ArrayListMap.java | 5 +- .../CaseInsensitiveMapWrapper.java | 31 +--- .../org/labkey/api/data/StatementUtils.java | 43 +---- .../dataiterator/AbstractMapDataIterator.java | 27 --- .../api/dataiterator/DataIteratorContext.java | 24 --- .../dataiterator/ListofMapsDataIterator.java | 8 - .../dataiterator/StatementDataIterator.java | 20 +-- .../TableInsertUpdateDataIterator.java | 28 --- .../api/query/AbstractQueryUpdateService.java | 15 -- .../org/labkey/api/query/QueryService.java | 1 + query/src/org/labkey/query/QueryModule.java | 8 + .../query/controllers/ImportRowsTestCase.java | 168 +++++------------- .../query/controllers/QueryController.java | 32 +++- 13 files changed, 93 insertions(+), 317 deletions(-) diff --git a/api/src/org/labkey/api/collections/ArrayListMap.java b/api/src/org/labkey/api/collections/ArrayListMap.java index f90b8609864..8d9ce59c5a3 100644 --- a/api/src/org/labkey/api/collections/ArrayListMap.java +++ b/api/src/org/labkey/api/collections/ArrayListMap.java @@ -231,9 +231,8 @@ public boolean containsKey(Object key) if (I == null) return false; int i = I.intValue(); - // A key added to the shared find map after this row was filled is absent here, not null - Object v = i>=_row.size() ? DOES_NOT_CONTAINKEY : _row.get(i); - return v != DOES_NOT_CONTAINKEY; + Object v = i>=_row.size() ? null : _row.get(i); + return v != DOES_NOT_CONTAINKEY; } diff --git a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java index 1d31ade5fd5..8c248062830 100644 --- a/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java +++ b/api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java @@ -32,9 +32,7 @@ public class CaseInsensitiveMapWrapper extends MapWrapper implements Serializable, CaseInsensitiveCollection { - private Map _correctCaseMap; - // Set when other maps share _correctCaseMap, so re-casing a key here would orphan their entries - private boolean _sharedCaseMap; + private final Map _correctCaseMap; public CaseInsensitiveMapWrapper(Map map) { @@ -45,27 +43,11 @@ public CaseInsensitiveMapWrapper(Map map, @Nullable CaseInsensitiveMa { super(map); _correctCaseMap = caseMapping == null ? new HashMap<>() : caseMapping._correctCaseMap; - // Wrapping the caseMapping itself shares its case map exactly as widely as that map already does - if (caseMapping == map) - _sharedCaseMap = caseMapping._sharedCaseMap; - else if (caseMapping != null) - { - _sharedCaseMap = true; - caseMapping._sharedCaseMap = true; - } for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - if (key != null) + if (entry.getKey() != null) { - String existing = _correctCaseMap.get(key.toLowerCase()); - // A wrapped key can't be re-cased, so take a private case map instead of re-casing the shared one - if (_sharedCaseMap && existing != null && !existing.equals(key)) - { - _correctCaseMap = new HashMap<>(_correctCaseMap); - _sharedCaseMap = false; - } - _correctCaseMap.put(key.toLowerCase(), key); + _correctCaseMap.put(entry.getKey().toLowerCase(), entry.getKey()); } } } @@ -99,10 +81,9 @@ public V put(String key, V value) { ret = remove(correctKey); } - // GH Issue 1867: with a shared case map, store under the existing casing so other maps still find their entries - String storedKey = _sharedCaseMap && correctKey != null ? correctKey : key; - _map.put(storedKey, value); - _correctCaseMap.put(null==key?null:key.toLowerCase(), storedKey); + _map.put(key, value); +// assert !_correctCaseMap.containsKey(key.toLowerCase()); + _correctCaseMap.put(null==key?null:key.toLowerCase(), key); return ret; } diff --git a/api/src/org/labkey/api/data/StatementUtils.java b/api/src/org/labkey/api/data/StatementUtils.java index 8627055e368..7055083138c 100644 --- a/api/src/org/labkey/api/data/StatementUtils.java +++ b/api/src/org/labkey/api/data/StatementUtils.java @@ -82,7 +82,6 @@ public enum Operation {insert, update, merge} private final TableInfo _targetTable; private Set _keyColumnNames = null; // override the primary key of _table private Set _skipColumnNames = Set.of(); - private Set _omittableColumnNames = Set.of(); private final Set _dontUpdateColumnNames = new CaseInsensitiveHashSet(); private boolean _updateBuiltInColumns = false; // default to false, this should usually be handled by StandardDataIteratorBuilder private boolean _selectIds = false; @@ -152,29 +151,6 @@ public StatementUtils skip(Set skip) return this; } - /** Insert columns that get their database default in rows binding {@link #useDefaultParameterName} to 1 */ - public StatementUtils omittable(Set omittable) - { - _omittableColumnNames = null==omittable ? Set.of() : omittable; - return this; - } - - public static String useDefaultParameterName(String columnName) - { - return columnName + "$useDefault"; - } - - private boolean isInlineableDefault(@Nullable String defaultValue) - { - if (null == defaultValue) - return false; - if (_dialect.isPostgreSQL()) - return true; - // SQL Server allows sequence and NEWSEQUENTIALID() defaults only in a DEFAULT constraint, not inside CASE - String upper = defaultValue.toUpperCase(); - return _dialect.isSqlServer() && !upper.contains("NEXT VALUE FOR") && !upper.contains("NEWSEQUENTIALID"); - } - public StatementUtils noupdate(Set noupdate) { if (null != noupdate) @@ -774,25 +750,10 @@ else if (column.getName().equalsIgnoreCase(updatable.getObjectURIColumnName()) & } else { - String inputName = Objects.toString(remap.get(name),name); - if (null != _skipColumnNames && _skipColumnNames.contains(inputName)) + if (null != _skipColumnNames && _skipColumnNames.contains(Objects.toString(remap.get(name),name))) continue; ParameterHolder ph = createParameter(column); - if (Operation.insert == _operation && _omittableColumnNames.contains(inputName) && !ph.isConstant && - !column.isAutoIncrement() && isInlineableDefault(column.getJdbcDefaultValue())) - { - // GH Issue 1867: these dialects report the default as an expression, so evaluate it per row rather than splitting the batch by omitted columns - ParameterHolder useDefault = createParameter(useDefaultParameterName(name), JdbcType.INTEGER); - valueSQL.unsafeAppend("CASE WHEN "); - appendParameterOrVariable(valueSQL, useDefault); - valueSQL.unsafeAppend(" = 1 THEN (").append(new SQLFragment().setSqlUnsafe(column.getJdbcDefaultValue())).unsafeAppend(") ELSE "); - appendParameterOrVariable(valueSQL, ph); - valueSQL.unsafeAppend(" END"); - } - else - { - appendParameterOrVariable(valueSQL, ph); - } + appendParameterOrVariable(valueSQL, ph); } cols.add(column); values.add(valueSQL); diff --git a/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java b/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java index f4abe055883..8e7aa4f3943 100644 --- a/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java @@ -26,7 +26,6 @@ import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; -import java.util.BitSet; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -115,7 +114,6 @@ public void debugLogInfo(StringBuilder sb) public static class ListOfMapsDataIterator extends AbstractMapDataIterator { protected List> _rows; - private Map _omittedColumnRows = Map.of(); protected ListOfMapsDataIterator(DataIteratorContext context, Set colsNames) { @@ -154,31 +152,6 @@ public ListOfMapsDataIterator(DataIteratorContext context, Set colNames, _cols.add(new BaseColumnInfo(name, JdbcType.OTHER)); } _rows = initRows(rows); - _omittedColumnRows = findOmittedColumnRows(); - context.setOmittedColumnRows(_omittedColumnRows); - } - - Map getOmittedColumnRows() - { - return _omittedColumnRows; - } - - private Map findOmittedColumnRows() - { - Map omitted = new CaseInsensitiveHashMap<>(); - for (int col = 1; col < _cols.size(); col++) - { - String name = _cols.get(col).getName(); - BitSet rowNumbers = new BitSet(); - for (int row = 0; row < _rows.size(); row++) - { - if (!_rows.get(row).containsKey(name)) - rowNumbers.set(row + 1); - } - if (!rowNumbers.isEmpty()) - omitted.put(name, rowNumbers); - } - return omitted; } protected List> initRows(List> rows) diff --git a/api/src/org/labkey/api/dataiterator/DataIteratorContext.java b/api/src/org/labkey/api/dataiterator/DataIteratorContext.java index 83e5d7940e2..d7ef807b39b 100644 --- a/api/src/org/labkey/api/dataiterator/DataIteratorContext.java +++ b/api/src/org/labkey/api/dataiterator/DataIteratorContext.java @@ -24,7 +24,6 @@ import org.labkey.api.query.QueryImportPipelineJob; import org.labkey.api.query.QueryUpdateService; -import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -62,7 +61,6 @@ public class DataIteratorContext private final Set _alternateKeys = new CaseInsensitiveHashSet(); private String _dataSource; private boolean _withLookupRemapping = true; - private Map _omittedColumnRows = null; private final Map _responseInfo = new HashMap<>(); // information from the import/loadRows context to be passed back to the API response object private Logger _logger; @@ -247,28 +245,6 @@ public void addAlternateKeys(Set alternateKeys) _alternateKeys.addAll(alternateKeys); } - /** GH Issue 1867: by input column name, the row numbers whose source row omits that column, so inserts can give them the database default */ - @NotNull - public Map getOmittedColumnRows() - { - return null == _omittedColumnRows ? Map.of() : _omittedColumnRows; - } - - /** First registration wins: the pipeline's own source is built before any nested pipeline that shares this context */ - public void setOmittedColumnRows(@NotNull Map omittedColumnRows) - { - if (null == _omittedColumnRows) - _omittedColumnRows = omittedColumnRows; - } - - /** Scopes registration to one pipeline: returns the current map, to be restored when that pipeline finishes */ - public @Nullable Map replaceOmittedColumnRows(@Nullable Map omittedColumnRows) - { - Map previous = _omittedColumnRows; - _omittedColumnRows = omittedColumnRows; - return previous; - } - public boolean shouldCancel() { if (!_errors.hasErrors()) diff --git a/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java b/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java index 49da5a412bb..2587515a049 100644 --- a/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/ListofMapsDataIterator.java @@ -37,13 +37,5 @@ public Builder(Set colNames, List> rows) { super(new ListofMapsDataIterator(colNames, rows)); } - - @Override - public DataIterator getDataIterator(DataIteratorContext context) - { - // GH Issue 1867: the iterator was built on a throwaway context, so hand its omitted rows to the pipeline's - context.setOmittedColumnRows(((ListofMapsDataIterator) di).getOmittedColumnRows()); - return di; - } } } diff --git a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java index e478612f048..05ac9bc51b8 100644 --- a/api/src/org/labkey/api/dataiterator/StatementDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/StatementDataIterator.java @@ -35,7 +35,6 @@ import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SqlExecutor; import org.labkey.api.data.SqlSelector; -import org.labkey.api.data.StatementUtils; import org.labkey.api.data.Table; import org.labkey.api.data.TableInfo; import org.labkey.api.data.dialect.ColumnMetaDataReader; @@ -58,7 +57,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.BitSet; import java.util.Collections; import java.util.Map; import java.util.Set; @@ -96,8 +94,6 @@ public class StatementDataIterator extends AbstractDataIterator Integer _rowIdIndex = null; Integer _objectIdIndex = null; Integer _objectUriIndex = null; - // By this iterator's column name, the row numbers whose source row omitted the column - protected Map _omittedColumnRows = Map.of(); protected int _batchSize = -1; int _currentBatchSize = 0; int _currentTxSize = 0; @@ -208,11 +204,8 @@ void init() if (null != to) { FieldKey mvName = col.getMvColumnName(); - BitSet omittedRows = _omittedColumnRows.get(col.getName()); - Parameter useDefault = null == omittedRows ? null : stmt.getParameter(StatementUtils.useDefaultParameterName(to.getName())); bindings.add(new Triple(_data.getSupplier(i), to, - (null != mvName ? getMvParameter(stmt, mvName) : null), - useDefault, omittedRows)); + (null != mvName ? getMvParameter(stmt, mvName) : null))); } } _bindings[set] = bindings.toArray(new Triple[0]); @@ -247,19 +240,15 @@ public void setBatchSize(int batchSize) private static class Triple { - Triple(Supplier from, Parameter to, Parameter mv, @Nullable Parameter useDefault, @Nullable BitSet omittedRows) + Triple(Supplier from, Parameter to, Parameter mv) { this.from = from; this.to = to; this.mv = mv; - this.useDefault = useDefault; - this.omittedRows = omittedRows; } Supplier from; Parameter to; Parameter mv; - Parameter useDefault; - BitSet omittedRows; } @Override @@ -379,12 +368,7 @@ private boolean _next() throws BatchValidationException { Object value = binding.from.get(); if (null == value) - { - // GH Issue 1867: a row that omitted the column gets its database default; an explicit null stays NULL - if (null != binding.useDefault && binding.omittedRows.get(_currentRowNumber)) - binding.useDefault.setValue(1); continue; - } if (value instanceof MvFieldWrapper) { if (null != binding.mv) diff --git a/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java b/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java index 7a5b8224b97..3a40cec8abe 100644 --- a/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java +++ b/api/src/org/labkey/api/dataiterator/TableInsertUpdateDataIterator.java @@ -24,7 +24,6 @@ import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.DbScope; -import org.labkey.api.data.ImportAliasable; import org.labkey.api.data.Parameter; import org.labkey.api.data.ParameterMapStatement; import org.labkey.api.data.RuntimeSQLException; @@ -42,7 +41,6 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; -import java.util.BitSet; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; @@ -263,7 +261,6 @@ else if (_insertOption.mergeRows) } else { - _omittedColumnRows = resolveOmittedColumnRows(); stmt = getInsertStatement(constants); } @@ -310,7 +307,6 @@ protected ParameterMapStatement getInsertStatement(Map constants //pass in the voc cols in this builder StatementUtils utils = new StatementUtils(StatementUtils.Operation.insert, _table) .skip(_skipColumnNames) - .omittable(_omittedColumnRows.keySet()) .allowSetAutoIncrement(_context.supportsAutoIncrementKey()) .updateBuiltinColumns(false) .selectIds(_selectIds) @@ -320,30 +316,6 @@ protected ParameterMapStatement getInsertStatement(Map constants return stmt; } - /** Re-keys the source's omitted-column rows from input names (which may be aliases) to this iterator's column names */ - private Map resolveOmittedColumnRows() - { - Map omitted = _context.getOmittedColumnRows(); - if (omitted.isEmpty()) - return Map.of(); - - Map importMap = ImportAliasable.Helper.createImportMap(_table.getColumns(), false); - Map columns = DataIteratorUtil.createColumnNameMap(_data); - Map ret = new CaseInsensitiveHashMap<>(); - omitted.forEach((name, rows) -> { - ColumnInfo col = importMap.get(name); - String columnName = null == col ? name : col.getName(); - // A row omits the column only if it lacks every spelling that maps to it - if (columns.containsKey(columnName)) - ret.merge(columnName, rows, (a, b) -> { - BitSet both = (BitSet) a.clone(); - both.and(b); - return both; - }); - }); - return ret; - } - protected ParameterMapStatement getMergeStatement(Map constants) throws SQLException { ParameterMapStatement stmt; diff --git a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java index 4ccae5b98ec..5f1efab37e9 100644 --- a/api/src/org/labkey/api/query/AbstractQueryUpdateService.java +++ b/api/src/org/labkey/api/query/AbstractQueryUpdateService.java @@ -109,7 +109,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; -import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; @@ -401,20 +400,6 @@ protected int _importRowsUsingDIB(User user, Container container, DataIteratorBu } } - // GH Issue 1867: this pipeline's source registers its own omitted rows; a load nested on this context must not use the outer source's - Map outerOmittedRows = context.replaceOmittedColumnRows(null); - try - { - return _pumpImport(user, container, in, outputRows, context, extraScriptContext); - } - finally - { - context.replaceOmittedColumnRows(outerOmittedRows); - } - } - - private int _pumpImport(User user, Container container, DataIteratorBuilder in, @Nullable ArrayList> outputRows, DataIteratorContext context, @Nullable Map extraScriptContext) - { preImportDIBValidation(in, null); boolean skipTriggers = context.getConfigParameterBoolean(ConfigParameters.SkipTriggers) || context.isCrossTypeImport(); diff --git a/api/src/org/labkey/api/query/QueryService.java b/api/src/org/labkey/api/query/QueryService.java index 6a4c61a488b..18e6427863b 100644 --- a/api/src/org/labkey/api/query/QueryService.java +++ b/api/src/org/labkey/api/query/QueryService.java @@ -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"; diff --git a/query/src/org/labkey/query/QueryModule.java b/query/src/org/labkey/query/QueryModule.java index 4437bb151e0..0faa57c9d36 100644 --- a/query/src/org/labkey/query/QueryModule.java +++ b/query/src/org/labkey/query/QueryModule.java @@ -250,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 + )); } diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java index a0b56acc1d1..e257026df81 100644 --- a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -18,6 +18,7 @@ import jakarta.servlet.http.HttpServletRequest; 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.After; @@ -26,20 +27,17 @@ import org.junit.Test; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; -import org.labkey.api.collections.CaseInsensitiveHashMap; import org.labkey.api.data.JdbcType; -import org.labkey.api.data.MultiChoice; 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.query.BatchValidationException; import org.labkey.api.query.DetailsURL; -import org.labkey.api.query.QueryUpdateService; +import org.labkey.api.query.QueryService; import org.labkey.api.security.User; +import org.labkey.api.settings.OptionalFeatureService; import org.labkey.api.test.TestTimeout; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.TestContext; @@ -47,17 +45,15 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.bind.annotation.RequestMethod; -import java.util.ArrayList; import java.util.List; import java.util.Map; -/** GH Issue 1867: inserts must keep each row's values, and give each omitted column its default, when rows differ in which keys they supply or how they case them */ +/** GH Issue 1867: importRows rejects rows that differ in which fields they supply, and no command loses values when rows case a key differently */ @TestTimeout(TestTimeout.DEFAULT * 5) // Each test creates and deletes a project public class ImportRowsTestCase extends Assert { private static final String PROJECT_NAME = "ImportRowsTestProject"; - private static final String LIST_NAME = "ImportRowsSparseList"; - private static final String STATUS_DEFAULT = "Pending"; + private static final String LIST_NAME = "ImportRowsTestList"; @Before public void doSetup() throws Exception @@ -73,10 +69,6 @@ public void doSetup() throws Exception domain.addProperty(new PropertyStorageSpec("Name", JdbcType.VARCHAR)); domain.addProperty(new PropertyStorageSpec("Description", JdbcType.VARCHAR)); domain.addProperty(new PropertyStorageSpec("Volume", JdbcType.INTEGER)); - // Provisioned as a database DEFAULT, the only kind of default API inserts honor - domain.addProperty(new PropertyStorageSpec("Status", JdbcType.VARCHAR, 50, true, STATUS_DEFAULT)); - // Multi-choice columns are provisioned NOT NULL DEFAULT '{}'; the dialect rejects any other default for ARRAY - domain.addProperty(new PropertyStorageSpec("Tags", JdbcType.ARRAY)).setRangeURI(PropertyType.MULTI_CHOICE.getTypeUri()); ld.setKeyName("Name"); ld.save(user); } @@ -90,13 +82,37 @@ public void doCleanup() } @Test - public void testKeysAbsentFromFirstRow() throws Exception + public void testRaggedImportRowsRejected() throws Exception { - saveRows("importRows", List.of( + 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); } @@ -128,71 +144,6 @@ public void testMixedKeyCasingUpdate() throws Exception assertValue("S2", "Description", "b2"); } - @Test - public void testOmittedColumnDefaultImportRows() throws Exception - { - assertOmittedColumnDefault("importRows"); - } - - @Test - public void testOmittedColumnDefaultInsert() throws Exception - { - assertOmittedColumnDefault("insert"); - } - - @Test - public void testOmittedColumnDefaultInsertWithKeys() throws Exception - { - saveRows("insertWithKeys", List.of(Map.of("values", Map.of("Name", "S0")))); - assertValue("S0", "Status", STATUS_DEFAULT); - - saveRows("insertWithKeys", List.of( - Map.of("values", Map.of("Name", "S1")), - Map.of("values", Map.of("Name", "S2", "Status", "Done")))); - - assertValue("S1", "Status", STATUS_DEFAULT); - assertValue("S2", "Status", "Done"); - } - - @Test - public void testOmittedColumnDefaultUpdateService() throws Exception - { - insertRows(List.of(row("Name", "S0"))); - assertValue("S0", "Status", STATUS_DEFAULT); - - insertRows(List.of( - row("Name", "S1"), - row("Name", "S2", "Status", "Done"))); - - assertValue("S1", "Status", STATUS_DEFAULT); - assertValue("S2", "Status", "Done"); - } - - @Test - public void testExplicitNullUpdateService() throws Exception - { - insertRows(List.of( - row("Name", "S1", "Status", null), - row("Name", "S2", "Status", "Done", "Description", "x"))); - - assertNull("Status of S1", new TableSelector(getTable(), PageFlowUtil.set("Status")).getObject("S1", String.class)); - assertValue("S2", "Status", "Done"); - } - - @Test - public void testOmittedMultiChoiceDefault() throws Exception - { - saveRows("insert", List.of(Map.of("Name", "S0"))); - assertMultiChoiceValue("S0", List.of()); - - saveRows("insert", List.of( - Map.of("Name", "S1"), - Map.of("Name", "S2", "Tags", List.of("a", "b")))); - - assertMultiChoiceValue("S1", List.of()); - assertMultiChoiceValue("S2", List.of("a", "b")); - } - private void assertMixedKeyCasing(String command) throws Exception { saveRows(command, List.of( @@ -203,20 +154,6 @@ private void assertMixedKeyCasing(String command) throws Exception assertValue("S2", "Description", "b"); } - private void assertOmittedColumnDefault(String command) throws Exception - { - // Proves the database default exists, so a mixed-request failure below is the bug, not the setup - saveRows(command, List.of(Map.of("Name", "S0"))); - assertValue("S0", "Status", STATUS_DEFAULT); - - saveRows(command, List.of( - Map.of("Name", "S1"), - Map.of("Name", "S2", "Status", "Done"))); - - assertValue("S1", "Status", STATUS_DEFAULT); - assertValue("S2", "Status", "Done"); - } - private static @NotNull Container getProject() { Container project = ContainerManager.getForPath(PROJECT_NAME); @@ -234,6 +171,12 @@ private void assertOmittedColumnDefault(String command) throws Exception } private static void saveRows(String commandName, List> rows) throws Exception + { + MockHttpServletResponse response = postSaveRows(commandName, rows); + assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); + } + + private static MockHttpServletResponse postSaveRows(String commandName, List> rows) throws Exception { JSONObject command = new JSONObject(); command.put("command", commandName); @@ -247,42 +190,13 @@ private static void saveRows(String commandName, List> rows) HttpServletRequest request = ViewServlet.mockRequest(RequestMethod.POST.name(), DetailsURL.fromString("/query/saveRows.view").copy(getProject()).getActionURL(), TestContext.get().getUser(), Map.of("Content-Type", "application/json"), json.toString()); - MockHttpServletResponse response = ViewServlet.mockDispatch(request, null); - assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); - } - - private static void insertRows(List> rows) throws Exception - { - User user = TestContext.get().getUser(); - QueryUpdateService qus = getTable().getUpdateService(); - assertNotNull(qus); - BatchValidationException errors = new BatchValidationException(); - qus.insertRows(user, getProject(), new ArrayList<>(rows), errors, null, null); - if (errors.hasErrors()) - throw errors; - } - - /** Unlike Map.of, allows null values */ - private static Map row(Object... keysAndValues) - { - Map row = new CaseInsensitiveHashMap<>(); - for (int i = 0; i < keysAndValues.length; i += 2) - row.put((String) keysAndValues[i], keysAndValues[i + 1]); - return row; - } - - private static void assertMultiChoiceValue(String key, List expected) - { - Object actual = new TableSelector(getTable(), PageFlowUtil.set("Tags")).getObject(key, Object.class); - // The multi-choice converter maps null to an empty array, so check the raw value before converting - assertNotNull("Tags of " + key, actual); - assertEquals("Tags of " + key, MultiChoice.Converter.getInstance().convert(MultiChoice.Array.class, expected), - MultiChoice.Converter.getInstance().convert(MultiChoice.Array.class, actual)); + return ViewServlet.mockDispatch(request, null); } - private static void assertValue(String key, String column, @NotNull Object expected) + private static void assertValue(String key, String column, @Nullable Object expected) { - Object actual = new TableSelector(getTable(), PageFlowUtil.set(column)).getObject(key, expected.getClass()); + 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); } } diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index fb70d1e47a7..8e23c660c7d 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -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; @@ -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 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 keySpellings = new CaseInsensitiveHashMap<>(); + Set 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) @@ -4816,7 +4822,31 @@ private JSONObject executeJson(TracedOperation op, JSONObject json, CommandType { Map 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()) + { + String spelling = keySpellings.get(key); + if (null == spelling) + { + spelling = key; + keySpellings.put(key, key); + } + Object value = jsonObj.get(key); + conflictingCasing |= rowMap.put(spelling, JSONObject.NULL == value ? null : value) != null; + } + if (requireSquareRows) + { + Set rowKeys = new HashSet<>(rowMap.keySet()); + if (null == firstRowKeys) + firstRowKeys = rowKeys; + else if (!firstRowKeys.equals(rowKeys)) + { + Set 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; From df324483ccdd78a1cd5e9fe6c5e942b09794f470 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 16 Nov 2026 10:04:07 -0800 Subject: [PATCH 8/9] Share one test container across ImportRowsTestCase instead of a project per test --- .../query/controllers/ImportRowsTestCase.java | 62 ++++++++----------- 1 file changed, 27 insertions(+), 35 deletions(-) diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java index e257026df81..d7d4f3165a9 100644 --- a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -21,12 +21,11 @@ import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.After; +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.Container; -import org.labkey.api.data.ContainerManager; import org.labkey.api.data.JdbcType; import org.labkey.api.data.PropertyStorageSpec; import org.labkey.api.data.TableInfo; @@ -38,7 +37,8 @@ import org.labkey.api.query.QueryService; import org.labkey.api.security.User; import org.labkey.api.settings.OptionalFeatureService; -import org.labkey.api.test.TestTimeout; +import org.labkey.api.util.GUID; +import org.labkey.api.util.JunitUtil; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.util.TestContext; import org.labkey.api.view.ViewServlet; @@ -49,21 +49,28 @@ 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 */ -@TestTimeout(TestTimeout.DEFAULT * 5) // Each test creates and deletes a project public class ImportRowsTestCase extends Assert { - private static final String PROJECT_NAME = "ImportRowsTestProject"; - private static final String LIST_NAME = "ImportRowsTestList"; + // 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 doSetup() throws Exception + public void createList() throws Exception { - doCleanup(); User user = TestContext.get().getUser(); - Container project = ContainerManager.createContainer(ContainerManager.getRoot(), PROJECT_NAME, user); - ContainerManager.updateSearchable(project, false, user); - - ListDefinition ld = ListService.get().createList(project, LIST_NAME, ListDefinition.KeyType.Varchar); + ListDefinition ld = ListService.get().createList(JunitUtil.getTestContainer(), _listName, ListDefinition.KeyType.Varchar); Domain domain = ld.getDomain(); assertNotNull(domain); domain.addProperty(new PropertyStorageSpec("Name", JdbcType.VARCHAR)); @@ -73,14 +80,6 @@ public void doSetup() throws Exception ld.save(user); } - @After - public void doCleanup() - { - Container project = ContainerManager.getForPath(PROJECT_NAME); - if (project != null) - ContainerManager.deleteAll(project, TestContext.get().getUser()); - } - @Test public void testRaggedImportRowsRejected() throws Exception { @@ -154,46 +153,39 @@ private void assertMixedKeyCasing(String command) throws Exception assertValue("S2", "Description", "b"); } - private static @NotNull Container getProject() - { - Container project = ContainerManager.getForPath(PROJECT_NAME); - assertNotNull(project); - return project; - } - - private static @NotNull TableInfo getTable() + private @NotNull TableInfo getTable() { - ListDefinition ld = ListService.get().getList(getProject(), LIST_NAME); + ListDefinition ld = ListService.get().getList(JunitUtil.getTestContainer(), _listName); assertNotNull(ld); TableInfo table = ld.getTable(TestContext.get().getUser()); assertNotNull(table); return table; } - private static void saveRows(String commandName, List> rows) throws Exception + private void saveRows(String commandName, List> rows) throws Exception { MockHttpServletResponse response = postSaveRows(commandName, rows); assertEquals(commandName + " via saveRows failed: " + response.getContentAsString(), HttpServletResponse.SC_OK, response.getStatus()); } - private static MockHttpServletResponse postSaveRows(String commandName, List> rows) throws Exception + private MockHttpServletResponse postSaveRows(String commandName, List> rows) throws Exception { JSONObject command = new JSONObject(); command.put("command", commandName); command.put("schemaName", "lists"); - command.put("queryName", LIST_NAME); + command.put("queryName", _listName); command.put("rows", new JSONArray(rows)); JSONObject json = new JSONObject(); json.put("commands", List.of(command)); HttpServletRequest request = ViewServlet.mockRequest(RequestMethod.POST.name(), - DetailsURL.fromString("/query/saveRows.view").copy(getProject()).getActionURL(), TestContext.get().getUser(), + DetailsURL.fromString("/query/saveRows.view").copy(JunitUtil.getTestContainer()).getActionURL(), TestContext.get().getUser(), Map.of("Content-Type", "application/json"), json.toString()); return ViewServlet.mockDispatch(request, null); } - private static void assertValue(String key, String column, @Nullable Object expected) + 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); From 5dbe73af2939d58aa9b869e8246c7e98daaeccd0 Mon Sep 17 00:00:00 2001 From: labkey-jeckels Date: Mon, 16 Nov 2026 13:42:03 -0800 Subject: [PATCH 9/9] Test and handle attachments --- .../query/controllers/ImportRowsTestCase.java | 45 ++++++++++++++++--- .../query/controllers/QueryController.java | 28 +++++++----- 2 files changed, 57 insertions(+), 16 deletions(-) diff --git a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java index d7d4f3165a9..97697fed20b 100644 --- a/query/src/org/labkey/query/controllers/ImportRowsTestCase.java +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -15,7 +15,6 @@ */ package org.labkey.query.controllers; -import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -30,19 +29,25 @@ 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.query.DetailsURL; +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; @@ -76,6 +81,8 @@ public void createList() throws Exception 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); } @@ -116,6 +123,21 @@ public void testRaggedImportRowsAllowedByFlag() throws Exception 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 { @@ -169,6 +191,11 @@ private void saveRows(String commandName, List> rows) throws } private MockHttpServletResponse postSaveRows(String commandName, List> rows) throws Exception + { + return postSaveRows(commandName, rows, null); + } + + private MockHttpServletResponse postSaveRows(String commandName, List> rows, @Nullable MockPart file) throws Exception { JSONObject command = new JSONObject(); command.put("command", commandName); @@ -179,9 +206,17 @@ private MockHttpServletResponse postSaveRows(String commandName, List rowKeys = new HashSet<>(rowMap.keySet()); @@ -4853,8 +4850,6 @@ else if (!firstRowKeys.equals(rowKeys)) // 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++; @@ -5034,7 +5029,18 @@ protected boolean allowRowAttachments() return false; } - private void addRowAttachments(Map rowMap, int rowIndex, @Nullable Integer commandIndex) + private static String getKeySpelling(CaseInsensitiveHashMap keySpellings, String key) + { + String spelling = keySpellings.get(key); + if (null == spelling) + { + spelling = key; + keySpellings.put(key, key); + } + return spelling; + } + + private void addRowAttachments(Map rowMap, int rowIndex, @Nullable Integer commandIndex, CaseInsensitiveHashMap keySpellings) { if (getFileMap() != null) { @@ -5075,7 +5081,7 @@ private void addRowAttachments(Map 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); } } }