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/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/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..a0b56acc1d1 --- /dev/null +++ b/query/src/org/labkey/query/controllers/ImportRowsTestCase.java @@ -0,0 +1,288 @@ +/* + * 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.jetbrains.annotations.NotNull; +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.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: 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"; + private static final String LIST_NAME = "ImportRowsSparseList"; + private static final String STATUS_DEFAULT = "Pending"; + + @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)); + // 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); + } + + @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 + { + 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"); + } + + @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( + 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; + } + + 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", commandName); + command.put("schemaName", "lists"); + command.put("queryName", LIST_NAME); + 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(), + 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)); + } + + 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); + } +} diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index f59d9fe40f8..88e2f937797 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