Skip to content
5 changes: 3 additions & 2 deletions api/src/org/labkey/api/collections/ArrayListMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}


Expand Down
31 changes: 25 additions & 6 deletions api/src/org/labkey/api/collections/CaseInsensitiveMapWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@

public class CaseInsensitiveMapWrapper<V> extends MapWrapper<String, V> implements Serializable, CaseInsensitiveCollection
{
private final Map<String, String> _correctCaseMap;
private Map<String, String> _correctCaseMap;
// Set when other maps share _correctCaseMap, so re-casing a key here would orphan their entries
private boolean _sharedCaseMap;

public CaseInsensitiveMapWrapper(Map<String, V> map)
{
Expand All @@ -43,11 +45,27 @@ public CaseInsensitiveMapWrapper(Map<String, V> 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<? extends String, ? extends V> 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);
}
}
}
Expand Down Expand Up @@ -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;
}

Expand Down
43 changes: 41 additions & 2 deletions api/src/org/labkey/api/data/StatementUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public enum Operation {insert, update, merge}
private final TableInfo _targetTable;
private Set<String> _keyColumnNames = null; // override the primary key of _table
private Set<String> _skipColumnNames = Set.of();
private Set<String> _omittableColumnNames = Set.of();
private final Set<String> _dontUpdateColumnNames = new CaseInsensitiveHashSet();
private boolean _updateBuiltInColumns = false; // default to false, this should usually be handled by StandardDataIteratorBuilder
private boolean _selectIds = false;
Expand Down Expand Up @@ -151,6 +152,29 @@ public StatementUtils skip(Set<String> skip)
return this;
}

/** Insert columns that get their database default in rows binding {@link #useDefaultParameterName} to 1 */
public StatementUtils omittable(Set<String> 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<String> noupdate)
{
if (null != noupdate)
Expand Down Expand Up @@ -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);
Expand Down
27 changes: 27 additions & 0 deletions api/src/org/labkey/api/dataiterator/AbstractMapDataIterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -114,6 +115,7 @@ public void debugLogInfo(StringBuilder sb)
public static class ListOfMapsDataIterator extends AbstractMapDataIterator
{
protected List<Map<String, Object>> _rows;
private Map<String, BitSet> _omittedColumnRows = Map.of();

protected ListOfMapsDataIterator(DataIteratorContext context, Set<String> colsNames)
{
Expand Down Expand Up @@ -152,6 +154,31 @@ public ListOfMapsDataIterator(DataIteratorContext context, Set<String> colNames,
_cols.add(new BaseColumnInfo(name, JdbcType.OTHER));
}
_rows = initRows(rows);
_omittedColumnRows = findOmittedColumnRows();
context.setOmittedColumnRows(_omittedColumnRows);
}

Map<String, BitSet> getOmittedColumnRows()
{
return _omittedColumnRows;
}

private Map<String, BitSet> findOmittedColumnRows()
{
Map<String, BitSet> 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<Map<String, Object>> initRows(List<Map<String, Object>> rows)
Expand Down
24 changes: 24 additions & 0 deletions api/src/org/labkey/api/dataiterator/DataIteratorContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -61,6 +62,7 @@ public class DataIteratorContext
private final Set<String> _alternateKeys = new CaseInsensitiveHashSet();
private String _dataSource;
private boolean _withLookupRemapping = true;
private Map<String, BitSet> _omittedColumnRows = null;

private final Map<String, Object> _responseInfo = new HashMap<>(); // information from the import/loadRows context to be passed back to the API response object
private Logger _logger;
Expand Down Expand Up @@ -245,6 +247,28 @@ public void addAlternateKeys(Set<String> 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<String, BitSet> 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<String, BitSet> 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<String, BitSet> replaceOmittedColumnRows(@Nullable Map<String, BitSet> omittedColumnRows)
{
Map<String, BitSet> previous = _omittedColumnRows;
_omittedColumnRows = omittedColumnRows;
return previous;
}

public boolean shouldCancel()
{
if (!_errors.hasErrors())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,13 @@ public Builder(Set<String> colNames, List<Map<String, Object>> 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;
}
}
}
20 changes: 18 additions & 2 deletions api/src/org/labkey/api/dataiterator/StatementDataIterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<String, BitSet> _omittedColumnRows = Map.of();
protected int _batchSize = -1;
int _currentBatchSize = 0;
int _currentTxSize = 0;
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -261,6 +263,7 @@ else if (_insertOption.mergeRows)
}
else
{
_omittedColumnRows = resolveOmittedColumnRows();
stmt = getInsertStatement(constants);
}

Expand Down Expand Up @@ -307,6 +310,7 @@ protected ParameterMapStatement getInsertStatement(Map<String, Object> 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)
Expand All @@ -316,6 +320,30 @@ protected ParameterMapStatement getInsertStatement(Map<String, Object> 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<String, BitSet> resolveOmittedColumnRows()
{
Map<String, BitSet> omitted = _context.getOmittedColumnRows();
if (omitted.isEmpty())
return Map.of();

Map<String, ColumnInfo> importMap = ImportAliasable.Helper.createImportMap(_table.getColumns(), false);
Map<String, Integer> columns = DataIteratorUtil.createColumnNameMap(_data);
Map<String, BitSet> 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<String, Object> constants) throws SQLException
{
ParameterMapStatement stmt;
Expand Down
Loading
Loading