From c059559080936f0feb3b00c395dc225c0c0822df Mon Sep 17 00:00:00 2001 From: Marty Pradere Date: Wed, 18 Nov 2026 15:00:57 -0700 Subject: [PATCH 1/2] Add shared project and protocol at time lookup columns Multi-valued lookups to the projects and protocols an animal held on each record's date, added by the center customizers that opt in. --- .../ehr/table/AssignmentAtTimeColumns.java | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java diff --git a/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java b/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java new file mode 100644 index 000000000..966da7d91 --- /dev/null +++ b/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2026 LabKey Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.labkey.api.ehr.table; + +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.labkey.api.data.AbstractTableInfo; +import org.labkey.api.data.BaseColumnInfo; +import org.labkey.api.data.ColumnInfo; +import org.labkey.api.data.MultiValuedForeignKey; +import org.labkey.api.data.TableInfo; +import org.labkey.api.data.WrappedColumn; +import org.labkey.api.query.LookupForeignKey; +import org.labkey.api.query.QueryDefinition; +import org.labkey.api.query.QueryException; +import org.labkey.api.query.QueryService; +import org.labkey.api.query.UserSchema; +import org.labkey.api.util.logging.LogHelper; + +import java.util.ArrayList; +import java.util.List; + +/** + * Multi-valued lookups to the projects (study.assignment) and protocols (study.protocolAssignment) an animal held on + * each record's date. The protocol comes from protocolAssignment, not assignment.project.protocol, for centers that + * assign the two independently. + */ +public final class AssignmentAtTimeColumns +{ + private static final Logger LOG = LogHelper.getLogger(AssignmentAtTimeColumns.class, "Project and protocol at time lookup columns"); + + public static final String PROJECT_AT_TIME = "projectAtTime"; + public static final String PROTOCOL_AT_TIME = "protocolAtTime"; + + private AssignmentAtTimeColumns() + { + } + + public static void addProjectAtTimeCol(@NotNull AbstractTableInfo ds, @NotNull UserSchema ehrStudySchema) + { + addAtTimeLookupCol(ds, ehrStudySchema, PROJECT_AT_TIME, "Project At Time", "assignment", "project", "name"); + } + + public static void addProtocolAtTimeCol(@NotNull AbstractTableInfo ds, @NotNull UserSchema ehrStudySchema) + { + addAtTimeLookupCol(ds, ehrStudySchema, PROTOCOL_AT_TIME, "Protocol At Time", "protocolAssignment", "protocol", "title"); + } + + private static void addAtTimeLookupCol(AbstractTableInfo ds, UserSchema ehrStudySchema, String name, String label, + String sourceDataset, String valueCol, String displayField) + { + if (ds.getColumn(name, false) != null || ds.getColumn("Id") == null || ds.getColumn("date") == null) + return; + + if ("demographics".equalsIgnoreCase(ds.getName()) && "study".equalsIgnoreCase(ds.getPublicSchemaName())) + return; + + List pks = ds.getPkColumns(); + final UserSchema targetSchema = ds.getUserSchema(); + if (pks.size() != 1 || targetSchema == null) + return; + + if (ehrStudySchema.getTableNames().stream().noneMatch(sourceDataset::equalsIgnoreCase)) + return; + + final ColumnInfo pkCol = pks.getFirst(); + final String schemaName = ds.getPublicSchemaName(); + final String queryName = ds.getName(); + final String ehrPath = ehrStudySchema.getContainer().getPath(); + + WrappedColumn col = new WrappedColumn(pkCol, name); + col.setLabel(label); + col.setReadOnly(true); + col.setUserEditable(false); + // The junction's value column keeps the source dataset's lookup, which the multi-valued FK resolves through; + // values with no matching target row are dropped. + col.setFk(new MultiValuedForeignKey(new LookupForeignKey(pkCol.getName()) + { + @Override + public TableInfo getLookupTableInfo() + { + QueryDefinition qd = QueryService.get().createQueryDef(targetSchema.getUser(), targetSchema.getContainer(), targetSchema, queryName + "_" + name); + // Date precision with an inclusive end, matching AssignmentAtTimeForeignKey. + qd.setSql("SELECT DISTINCT\n" + + "sd." + pkCol.getFieldKey().toSQLString() + ",\n" + + "src." + valueCol + "\n" + + "FROM \"" + schemaName + "\".\"" + queryName + "\" sd\n" + + "JOIN \"" + ehrPath + "\".study." + sourceDataset + " src\n" + + " ON (src.id = sd.id AND CAST(src.date AS DATE) <= CAST(sd.date AS DATE)\n" + + " AND (src.enddate IS NULL OR CAST(sd.date AS DATE) <= CAST(src.enddate AS DATE))\n" + + " AND src.qcstate.publicdata = true)"); + qd.setIsTemporary(true); + + List errors = new ArrayList<>(); + TableInfo ti = qd.getTable(errors, true); + if (!errors.isEmpty() || ti == null) + { + LOG.warn("Error creating {} junction for: {}.{} in container: {}", name, schemaName, queryName, targetSchema.getContainer().getPath()); + errors.forEach(e -> LOG.error("Lookup table QueryException: {}", e.getMessage(), e)); + return null; + } + + ((BaseColumnInfo) ti.getColumn(pkCol.getName())).setKeyField(true); + return ti; + } + }, valueCol, displayField)); + + ds.addColumn(col); + } +} From 77d8fd4c7d0a388d02799a3898b29b5a2e7b2e9d Mon Sep 17 00:00:00 2001 From: Marty Pradere Date: Thu, 19 Nov 2026 05:13:58 -0700 Subject: [PATCH 2/2] Match project/protocol at time by timestamp and honor container filter Also resolves values through each target's title column, skips the source dataset itself, and lists study tables once per dataset. --- .../ehr/table/AssignmentAtTimeColumns.java | 78 ++++++++++++------- 1 file changed, 49 insertions(+), 29 deletions(-) diff --git a/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java b/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java index 966da7d91..d11de29cb 100644 --- a/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java +++ b/ehr/api-src/org/labkey/api/ehr/table/AssignmentAtTimeColumns.java @@ -18,6 +18,7 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.labkey.api.data.AbstractTableInfo; +import org.labkey.api.collections.CaseInsensitiveHashSet; import org.labkey.api.data.BaseColumnInfo; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.MultiValuedForeignKey; @@ -32,6 +33,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; /** * Multi-valued lookups to the projects (study.assignment) and protocols (study.protocolAssignment) an animal held on @@ -42,67 +44,85 @@ public final class AssignmentAtTimeColumns { private static final Logger LOG = LogHelper.getLogger(AssignmentAtTimeColumns.class, "Project and protocol at time lookup columns"); - public static final String PROJECT_AT_TIME = "projectAtTime"; - public static final String PROTOCOL_AT_TIME = "protocolAtTime"; - - private AssignmentAtTimeColumns() + public enum AtTimeColumn { - } + PROJECT("projectAtTime", "Project At Time", "assignment", "project"), + PROTOCOL("protocolAtTime", "Protocol At Time", "protocolAssignment", "protocol"); - public static void addProjectAtTimeCol(@NotNull AbstractTableInfo ds, @NotNull UserSchema ehrStudySchema) - { - addAtTimeLookupCol(ds, ehrStudySchema, PROJECT_AT_TIME, "Project At Time", "assignment", "project", "name"); + private final String _name; + private final String _label; + private final String _sourceDataset; + private final String _valueCol; + + AtTimeColumn(String name, String label, String sourceDataset, String valueCol) + { + _name = name; + _label = label; + _sourceDataset = sourceDataset; + _valueCol = valueCol; + } } - public static void addProtocolAtTimeCol(@NotNull AbstractTableInfo ds, @NotNull UserSchema ehrStudySchema) + private AssignmentAtTimeColumns() { - addAtTimeLookupCol(ds, ehrStudySchema, PROTOCOL_AT_TIME, "Protocol At Time", "protocolAssignment", "protocol", "title"); } - private static void addAtTimeLookupCol(AbstractTableInfo ds, UserSchema ehrStudySchema, String name, String label, - String sourceDataset, String valueCol, String displayField) + public static void addAtTimeCols(@NotNull AbstractTableInfo ds, @NotNull UserSchema ehrStudySchema, @NotNull AtTimeColumn... cols) { - if (ds.getColumn(name, false) != null || ds.getColumn("Id") == null || ds.getColumn("date") == null) + if (ds.getColumn("Id") == null || ds.getColumn("date") == null || !"study".equalsIgnoreCase(ds.getPublicSchemaName())) return; - if ("demographics".equalsIgnoreCase(ds.getName()) && "study".equalsIgnoreCase(ds.getPublicSchemaName())) + UserSchema targetSchema = ds.getUserSchema(); + if ("demographics".equalsIgnoreCase(ds.getName()) || ds.getPkColumns().size() != 1 || targetSchema == null) return; - List pks = ds.getPkColumns(); - final UserSchema targetSchema = ds.getUserSchema(); - if (pks.size() != 1 || targetSchema == null) - return; + Set ehrStudyTables = null; + for (AtTimeColumn col : cols) + { + if (ds.getColumn(col._name, false) != null || col._sourceDataset.equalsIgnoreCase(ds.getName())) + continue; - if (ehrStudySchema.getTableNames().stream().noneMatch(sourceDataset::equalsIgnoreCase)) - return; + if (ehrStudyTables == null) + ehrStudyTables = new CaseInsensitiveHashSet(ehrStudySchema.getTableNames()); - final ColumnInfo pkCol = pks.getFirst(); + if (ehrStudyTables.contains(col._sourceDataset)) + addAtTimeLookupCol(ds, targetSchema, ehrStudySchema, col); + } + } + + private static void addAtTimeLookupCol(AbstractTableInfo ds, UserSchema targetSchema, UserSchema ehrStudySchema, AtTimeColumn atTimeCol) + { + final ColumnInfo pkCol = ds.getPkColumns().getFirst(); final String schemaName = ds.getPublicSchemaName(); final String queryName = ds.getName(); final String ehrPath = ehrStudySchema.getContainer().getPath(); + final String name = atTimeCol._name; + final String valueCol = atTimeCol._valueCol; WrappedColumn col = new WrappedColumn(pkCol, name); - col.setLabel(label); + col.setLabel(atTimeCol._label); col.setReadOnly(true); col.setUserEditable(false); - // The junction's value column keeps the source dataset's lookup, which the multi-valued FK resolves through; - // values with no matching target row are dropped. + // The junction's value column keeps the source dataset's lookup, which the multi-valued FK resolves through to + // the target's title column; values with no matching target row are dropped. col.setFk(new MultiValuedForeignKey(new LookupForeignKey(pkCol.getName()) { @Override public TableInfo getLookupTableInfo() { QueryDefinition qd = QueryService.get().createQueryDef(targetSchema.getUser(), targetSchema.getContainer(), targetSchema, queryName + "_" + name); - // Date precision with an inclusive end, matching AssignmentAtTimeForeignKey. + // Full timestamps with an exclusive end, like housingAtTime; AssignmentAtTimeForeignKey matches by date instead. + // The source is pinned to the EHR container so the dataset's container filter doesn't widen it. qd.setSql("SELECT DISTINCT\n" + "sd." + pkCol.getFieldKey().toSQLString() + ",\n" + "src." + valueCol + "\n" + "FROM \"" + schemaName + "\".\"" + queryName + "\" sd\n" + - "JOIN \"" + ehrPath + "\".study." + sourceDataset + " src\n" + - " ON (src.id = sd.id AND CAST(src.date AS DATE) <= CAST(sd.date AS DATE)\n" + - " AND (src.enddate IS NULL OR CAST(sd.date AS DATE) <= CAST(src.enddate AS DATE))\n" + + "JOIN \"" + ehrPath + "\".study." + atTimeCol._sourceDataset + "[ContainerFilter='Current'] src\n" + + " ON (src.id = sd.id AND src.date <= sd.date\n" + + " AND (src.enddate IS NULL OR sd.date < src.enddate)\n" + " AND src.qcstate.publicdata = true)"); qd.setIsTemporary(true); + qd.setContainerFilter(ds.getContainerFilter()); List errors = new ArrayList<>(); TableInfo ti = qd.getTable(errors, true); @@ -116,7 +136,7 @@ public TableInfo getLookupTableInfo() ((BaseColumnInfo) ti.getColumn(pkCol.getName())).setKeyField(true); return ti; } - }, valueCol, displayField)); + }, valueCol)); ds.addColumn(col); }