Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ public class AnnouncementDigestProvider implements MessageDigest.Provider
"\t(\n" +
"\tSELECT Thread, MIN(Approved) AS Earliest FROM\n" +
"\t\t(SELECT Approved, CASE WHEN Parent IS NULL THEN EntityId ELSE Parent END AS Thread FROM " + _comm.getTableInfoAnnouncements() + " annModel LEFT OUTER JOIN\n" +
"\t\t\t(SELECT DISTINCT Parent AS DocParent FROM " + _core.getTableInfoDocuments() + ") doc ON annModel.EntityId = DocParent\n" +
"\t\t\t(SELECT DISTINCT Parent AS DocParent FROM " + _core.getTableInfoAttachmentPointers() + ") doc ON annModel.EntityId = DocParent\n" +
"\t\t\tWHERE Container = ? AND Approved >= ? AND Approved < ? AND (Body IS NOT NULL OR DocParent IS NOT NULL)) x\n" +
"\tGROUP BY Thread\n" +
"\t) X LEFT OUTER JOIN " + _comm.getTableInfoAnnouncements() + " annModel ON Parent = Thread OR EntityId = Thread LEFT OUTER JOIN\n" +
"\t\t(SELECT DISTINCT Parent AS DocParent FROM " + _core.getTableInfoDocuments() + ") doc ON annModel.EntityId = DocParent\n" +
"\t\t(SELECT DISTINCT Parent AS DocParent FROM " + _core.getTableInfoAttachmentPointers() + ") doc ON annModel.EntityId = DocParent\n" +
"WHERE Container = ? AND Approved >= ? AND Approved < ? AND (Body IS NOT NULL OR DocParent IS NOT NULL)\n" +
"ORDER BY Earliest, Thread, Approved";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,7 @@ public static Map<String, Integer> updateContainer(List<String> discussionSrcIds
SimpleFilter filter = new SimpleFilter(FieldKey.fromParts("discussionSrcIdentifier"), discussionSrcIds, CompareType.IN);
TableSelector selector = new TableSelector(_comm.getTableInfoAnnouncements(), Collections.singleton("entityId"), filter, null);
Map<String, Integer> updateCounts = new HashMap<>();
updateCounts.put("attachments", Table.updateContainer(_core.getTableInfoDocuments(), "parent", selector.getArrayList(String.class), targetContainer, user, false));
updateCounts.put("attachments", Table.updateContainer(_core.getTableInfoAttachmentPointers(), "parent", selector.getArrayList(String.class), targetContainer, user, false));
updateCounts.put("announcements", Table.updateContainer(_comm.getTableInfoAnnouncements(), "discussionSrcIdentifier", discussionSrcIds, targetContainer, user, false));
return updateCounts;
}
Expand Down Expand Up @@ -952,15 +952,15 @@ public void setLastIndexed(long ms, long modified)
// Get the attachments... unfortunately, they're attached to individual announcementModels, not to the thread,
// so we need a different query.
// find all messages that have attachments
sql = SQLFragment.unsafe("SELECT a.EntityId, MIN(CAST(a.Parent AS VARCHAR(36))) as parent, MIN(a.Title) AS title FROM ").append(_comm.getTableInfoAnnouncements()).unsafeAppend(" a INNER JOIN core.Documents d ON a.entityid = d.parent");
sql = SQLFragment.unsafe("SELECT a.EntityId, MIN(CAST(a.Parent AS VARCHAR(36))) as parent, MIN(a.Title) AS title FROM ").append(_comm.getTableInfoAnnouncements()).unsafeAppend(" a INNER JOIN ").append(CoreSchema.getInstance().getTableInfoAttachmentPointers(), "d").unsafeAppend(" ON a.entityid = d.parent");
sql.unsafeAppend("\nWHERE a.container = ?", c);
if (null != threadId)
{
sql.unsafeAppend(" AND (a.entityId = ? OR a.parent = ?)", threadId, threadId);
}
else
{
SQLFragment modified = new SearchService.LastIndexedClause(CoreSchema.getInstance().getTableInfoDocuments(), modifiedSince, "d").toSQLFragment(null, null);
SQLFragment modified = new SearchService.LastIndexedClause(CoreSchema.getInstance().getTableInfoAttachmentPointers(), modifiedSince, "d").toSQLFragment(null, null);
if (!modified.isEmpty())
sql.unsafeAppend(" AND ").append(modified);
}
Expand Down Expand Up @@ -1075,7 +1075,7 @@ public static class TestCase extends Assert
{
private void purgeAnnouncements(Container c, boolean verifyEmpty)
{
String deleteDocuments = "DELETE FROM " + _core.getTableInfoDocuments() + " WHERE Container = ? AND Parent IN (SELECT EntityId FROM " + _comm.getTableInfoAnnouncements() + " WHERE Container = ?)";
String deleteDocuments = "DELETE FROM " + _core.getTableInfoAttachmentPointers() + " WHERE Container = ? AND Parent IN (SELECT EntityId FROM " + _comm.getTableInfoAnnouncements() + " WHERE Container = ?)";
int docs = new SqlExecutor(_comm.getSchema()).execute(deleteDocuments, c, c);
String deleteAnnouncements = "DELETE FROM " + _comm.getTableInfoAnnouncements() + " WHERE Container = ?";
int pages = new SqlExecutor(_comm.getSchema()).execute(deleteAnnouncements, c);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public static AttachmentParentType get()
}

@Override
public @NotNull SQLFragment getSelectEntityIdAndDescriptionSql()
public @NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql()
{
return SQLFragment.unsafe("SELECT EntityId, Title AS Description FROM ").append(CommSchema.getInstance().getTableInfoAnnouncements(), "ann");
return SQLFragment.unsafe("SELECT EntityId, Container, Title AS Description FROM ").append(CommSchema.getInstance().getTableInfoAnnouncements(), "ann");
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<query xmlns="http://labkey.org/data/xml/query" hidden="true">
<metadata>
<tables xmlns="http://labkey.org/data/xml">
<table tableName="DocumentsGroupedByParentType" tableDbType="NOT_IN_DB">
<table tableName="AttachmentsGroupedByParentType" tableDbType="NOT_IN_DB">
<columns>
<column columnName="Count">
<url replaceMissing="blankValue">query-executeQuery.view?schemaName=core&amp;queryName=Documents&amp;query.ParentType~eq=${ParentType}&amp;query.containerFilterName=${containerFilterName}</url>
<url replaceMissing="blankValue">query-executeQuery.view?schemaName=core&amp;queryName=Attachments&amp;query.ParentType~eq=${ParentType}&amp;query.containerFilterName=${containerFilterName}</url>
<formatString>#,##0</formatString>
</column>
</columns>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
SELECT ParentType, COUNT(*) AS "Count"
FROM Documents
FROM Attachments
GROUP BY ParentType
ORDER BY ParentType
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<query xmlns="http://labkey.org/data/xml/query" hidden="true">
<metadata>
<tables xmlns="http://labkey.org/data/xml">
<table tableName="DocumentsGroupedByParentType" tableDbType="NOT_IN_DB">
<table tableName="AttachmentsGroupedByParentType" tableDbType="NOT_IN_DB">
<columns>
<column columnName="Count">
<url replaceMissing="blankValue">admin-attachmentsForType.view?core.ParentType~eq=${ParentType}&amp;core.containerFilterName=${containerFilterName}</url>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
-- Identical to DocumentsGroupedByParentType, but this query's .query.xml provides an admin-console-specific Count URL
-- Identical to AttachmentsGroupedByParentType, but this query's .query.xml provides an admin-console-specific Count URL
SELECT ParentType, COUNT(*) AS "Count"
FROM Documents
FROM Attachments
GROUP BY ParentType
ORDER BY ParentType
6 changes: 6 additions & 0 deletions api/src/org/labkey/api/attachments/AttachmentFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,10 @@ public interface AttachmentFile extends FileStream
InputStream openInputStream() throws IOException;
@Override
void closeInputStream() throws IOException;

/** Whether openInputStream() can be called again after closeInputStream(); if not, storing a file buffers it to hash it */
default boolean isReopenable()
{
return false;
}
}
26 changes: 14 additions & 12 deletions api/src/org/labkey/api/attachments/AttachmentParentType.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
*/
public interface AttachmentParentType
{
SQLFragment NO_ROWS = SQLFragment.unsafe("SELECT NULL AS EntityId, NULL AS Description WHERE 1 = 0");
SQLFragment PARENT_CONTAINER_SQL = SQLFragment.unsafe("SELECT EntityId, COALESCE(Name, '<Root>') AS Description FROM ")
SQLFragment NO_ROWS = SQLFragment.unsafe("SELECT NULL AS EntityId, NULL AS Container, NULL AS Description WHERE 1 = 0");
SQLFragment PARENT_CONTAINER_SQL = SQLFragment.unsafe("SELECT EntityId, EntityId AS Container, COALESCE(Name, '<Root>') AS Description FROM ")
.append(CoreSchema.getInstance().getTableInfoContainers());

AttachmentParentType UNKNOWN = new AttachmentParentType()
Expand All @@ -39,7 +39,7 @@ public String getUniqueName()
}

@Override
public @NotNull SQLFragment getSelectEntityIdAndDescriptionSql()
public @NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql()
{
return NO_ROWS;
}
Expand All @@ -50,10 +50,10 @@ public String getUniqueName()

/**
* Append to the where clause of a query that wants to select attachments of the implementing type from the
* core.Documents table
* core.AttachmentPointers table
* @param sql Implementers MUST append a valid where clause to this SQLFragment
* @param parentColumn Column identifier for use in where clause. Usually represents 'core.Documents.Parent'
* @param documentNameColumn Column identifier for use in where clause. Usually represents 'core.Documents.DocumentName'
* @param parentColumn Column identifier for use in where clause. Usually represents 'core.AttachmentPointers.Parent'
* @param documentNameColumn Column identifier for use in where clause. Usually represents 'core.AttachmentPointers.Name'
*/
default void addWhereSql(SQLFragment sql, String parentColumn, String documentNameColumn)
{
Expand All @@ -63,22 +63,24 @@ default void addWhereSql(SQLFragment sql, String parentColumn, String documentNa

/**
* Return a SQLFragment that selects just the EntityId of rows that might be attachment parents from the table(s)
* that provide attachments of this type, without involving the core.Documents table.
* that provide attachments of this type, without involving the core.AttachmentPointers table.
*/
default @NotNull SQLFragment getSelectParentEntityIdsSql()
{
SQLFragment selectSql = getSelectEntityIdAndDescriptionSql();
SQLFragment selectSql = getSelectEntityIdContainerAndDescriptionSql();

// The returned SQL is always used inside a subselect, so the alias doesn't have to be unique
return SQLFragment.unsafe("SELECT EntityId FROM (").append(selectSql).unsafeAppend(") x");
}

/**
* Return a SQLFragment that selects the EntityId and an appropriate Description of all rows that might be
* attachment parents from the table(s) that provide attachment parents of this type, without involving the
* core.Documents table. For example, {@code SELECT EntityId, Title AS Description FROM comm.Announcements}.
* Return a SQLFragment that selects the EntityId, Container, and an appropriate Description of all rows that
* might be attachment parents from the table(s) that provide attachment parents of this type, without involving
* the core.AttachmentPointers table. Container must match what this type's AttachmentParent returns from
* getContainerId(), since attachment lookups filter on it. For example,
* {@code SELECT EntityId, Container, Title AS Description FROM comm.Announcements}.
* If the method determines that no parents exist, then return a valid query that selects no rows, for example,
* {@code NO_ROWS}.
*/
@NotNull SQLFragment getSelectEntityIdAndDescriptionSql();
@NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql();
}
25 changes: 23 additions & 2 deletions api/src/org/labkey/api/attachments/AttachmentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,19 @@ static AttachmentService get()

void addAttachments(AttachmentParent parent, List<AttachmentFile> files, @NotNull User user) throws IOException;

/**
* Names each attachment by its content hash plus the file's original extension. A name the parent already has is
* reused rather than reported as a duplicate. Not supported for AttachmentDirectory parents.
* @return the attachment names, in the order of files
*/
@NotNull List<String> addAttachmentsNamedByHash(AttachmentParent parent, List<AttachmentFile> files, @NotNull User user) throws IOException;

void deleteAttachments(AttachmentParent parent);

void deleteAttachments(Collection<AttachmentParent> parents);

void validateAttachmentSizes(AttachmentParent parent, List<AttachmentFile> files) throws IOException;
/** Forgets the parent's attachments but leaves an AttachmentDirectory's files on disk, e.g., when unregistering it */
void deleteAttachmentRecords(AttachmentParent parent);

/**
* Deletes the attachments with the given names from the given AttachmentParent.
Expand All @@ -90,8 +98,20 @@ static AttachmentService get()

void renameAttachment(AttachmentParent parent, String oldName, String newName, User auditUser) throws IOException;

/**
* Gives the parent a copy of the attachment under a new name, sharing its content.
* Not supported for AttachmentDirectory parents.
*/
void copyAttachment(AttachmentParent parent, Attachment a, String newName, User auditUser) throws IOException;

/**
* Gives the destination the source's attachments under the same names, sharing their content rather than copying it.
* Not supported for AttachmentDirectory parents.
* @param names the attachments to copy, or null for all of them
* @throws DuplicateFilenameException if the destination already has any of those names
*/
void copyAttachments(AttachmentParent source, AttachmentParent destination, @Nullable Collection<String> names, @NotNull User user) throws IOException;

int moveAttachments(Container newContainer, List<AttachmentParent> parents, User auditUser) throws IOException;

@NotNull
Expand Down Expand Up @@ -142,7 +162,8 @@ static AttachmentService get()
HttpView<?> getFindAttachmentParentsView();

/**
* Logs the first 20 orphaned attachments it detects. Returns the total number of orphaned attachments detected.
* Logs the first 20 orphaned attachments it detects, and the first 20 whose container doesn't match their parent's.
* Returns the total number of both detected.
*/
int logOrphanedAttachments();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ public String getContentType()
return _contentType;
}

@Override
public boolean isReopenable()
{
return true;
}

@Override
public String getFilename()
{
Expand Down
6 changes: 6 additions & 0 deletions api/src/org/labkey/api/attachments/FileAttachmentFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ public String getError()
return null;
}

@Override
public boolean isReopenable()
{
return true;
}

@Override
public String getFilename()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void addWhereSql(SQLFragment sql, String parentColumn, String documentNam
}

@Override
public @NotNull SQLFragment getSelectEntityIdAndDescriptionSql()
public @NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql()
{
return PARENT_CONTAINER_SQL;
}
Expand Down
6 changes: 6 additions & 0 deletions api/src/org/labkey/api/attachments/SpringAttachmentFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ public SpringAttachmentFile(MultipartFile file, @Nullable String newName)

}

@Override
public boolean isReopenable()
{
return true;
}

@Override
public String getFilename()
{
Expand Down
8 changes: 4 additions & 4 deletions api/src/org/labkey/api/data/CoreSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ public TableInfo getTableInfoLogins()
return getSchema().getTable("Logins");
}

public TableInfo getTableInfoDocuments()
public TableInfo getTableInfoAttachments()
{
return getSchema().getTable("Documents");
return getSchema().getTable("Attachments");
}

public TableInfo getTableInfoAttachmentPointer()
public TableInfo getTableInfoAttachmentPointers()
{
return getSchema().getTable("AttachmentPointer");
return getSchema().getTable("AttachmentPointers");
}

public TableInfo getTableInfoUsers()
Expand Down
9 changes: 5 additions & 4 deletions api/src/org/labkey/api/data/TempTableInClauseGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,11 @@ else if (jdbcType == JdbcType.VARCHAR)
if (null == sortedParameters)
return null;

String cacheKey = getCacheKey(jdbcType, sortedParameters);
DbSchema tempSchema = _tempSchemaSupplier.get();
Comment thread
labkey-adam marked this conversation as resolved.
Resolved
String cacheKey = getCacheKey(tempSchema, jdbcType, sortedParameters);
TempTableInfo tempTableInfo = _tempTableCache.get(cacheKey);
if (tempTableInfo == null)
{
DbSchema tempSchema = _tempSchemaSupplier.get();
tempTableInfo = new TempTableInfo(tempSchema, "InClause", Collections.singletonList(new BaseColumnInfo("Id", jdbcType, 0, false)), null);
SQLFragment sqlCreate = SQLFragment.unsafe("CREATE TABLE ");
sqlCreate.append(tempTableInfo)
Expand Down Expand Up @@ -255,14 +255,15 @@ else if (i instanceof Integer)
return params;
}

private String getCacheKey(@NotNull JdbcType jdbcType, @NotNull Collection<?> params)
// Temp tables exist only in the database that created them, so the key includes the data source
private String getCacheKey(@NotNull DbSchema tempSchema, @NotNull JdbcType jdbcType, @NotNull Collection<?> params)
{
StringBuilder paramBuilder = new StringBuilder();
for (Object param : params)
paramBuilder.append(param);

// Hash the param string to avoid very large cache keys filling up memory
return jdbcType.name() + "_" + params.size() + "_" + HashHelpers.hash(paramBuilder.toString());
return tempSchema.getScope().getDataSourceName() + "_" + jdbcType.name() + "_" + params.size() + "_" + HashHelpers.hash(paramBuilder.toString());
}

public static class TestCase
Expand Down
4 changes: 2 additions & 2 deletions api/src/org/labkey/api/exp/api/ExpRunAttachmentType.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ private ExpRunAttachmentType()
}

@Override
public @NotNull SQLFragment getSelectEntityIdAndDescriptionSql()
public @NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql()
{
return SQLFragment.unsafe("SELECT EntityId, Name AS Description FROM ").append(ExperimentService.get().getTinfoExperimentRun(), "er");
return SQLFragment.unsafe("SELECT EntityId, Container, Name AS Description FROM ").append(ExperimentService.get().getTinfoExperimentRun(), "er");
}
}
6 changes: 4 additions & 2 deletions api/src/org/labkey/api/files/FileSystemAttachmentType.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ private FileSystemAttachmentType()
}

@Override
public @NotNull SQLFragment getSelectEntityIdAndDescriptionSql()
public @NotNull SQLFragment getSelectEntityIdContainerAndDescriptionSql()
{
return SQLFragment.unsafe("SELECT EntityId, Name AS Description FROM ").append(CoreSchema.getInstance().getMappedDirectories(), "md");
// A folder's default file root has no MappedDirectories row; its attachments use the container's EntityId
return SQLFragment.unsafe("SELECT EntityId, Container, Name AS Description FROM ").append(CoreSchema.getInstance().getMappedDirectories(), "md")
.unsafeAppend(" UNION ").append(PARENT_CONTAINER_SQL);
}
}
Loading