Skip to content
Draft
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,8 @@ public void registerMigrationHandlers(@NotNull DatabaseMigrationService service)
@Override
public void beforeSchema()
{
new SqlExecutor(getSchema()).execute("ALTER TABLE comm.Pages DROP CONSTRAINT FK_Pages_PageVersions");
new SqlExecutor(getSchema()).execute("ALTER TABLE comm.Pages DROP CONSTRAINT FK_Pages_Parent");
new SqlExecutor(getSchema()).execute(SQLFragment.unsafe("ALTER TABLE comm.Pages DROP CONSTRAINT FK_Pages_PageVersions"));
new SqlExecutor(getSchema()).execute(SQLFragment.unsafe("ALTER TABLE comm.Pages DROP CONSTRAINT FK_Pages_Parent"));
}

@Override
Expand All @@ -252,8 +252,8 @@ public List<TableInfo> getTablesToCopy()
@Override
public void afterSchema(DatabaseMigrationConfiguration configuration, DbSchema sourceSchema, DbSchema targetSchema)
{
new SqlExecutor(getSchema()).execute("ALTER TABLE comm.Pages ADD CONSTRAINT FK_Pages_PageVersions FOREIGN KEY (PageVersionId) REFERENCES comm.PageVersions (RowId)");
new SqlExecutor(getSchema()).execute("ALTER TABLE comm.Pages ADD CONSTRAINT FK_Pages_Parent FOREIGN KEY (Parent) REFERENCES comm.Pages (RowId)");
new SqlExecutor(getSchema()).execute(SQLFragment.unsafe("ALTER TABLE comm.Pages ADD CONSTRAINT FK_Pages_PageVersions FOREIGN KEY (PageVersionId) REFERENCES comm.PageVersions (RowId)"));
new SqlExecutor(getSchema()).execute(SQLFragment.unsafe("ALTER TABLE comm.Pages ADD CONSTRAINT FK_Pages_Parent FOREIGN KEY (Parent) REFERENCES comm.Pages (RowId)"));
}

@Override
Expand Down Expand Up @@ -327,6 +327,6 @@ public void enumerateDocuments(SearchService.TaskIndexingQueue queue, final Date
@Override
public void indexDeleted()
{
new SqlExecutor(CommSchema.getInstance().getSchema()).execute("UPDATE comm.announcements SET LastIndexed=NULL");
new SqlExecutor(CommSchema.getInstance().getSchema()).execute(SQLFragment.unsafe("UPDATE comm.announcements SET LastIndexed=NULL"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
import org.labkey.api.data.DataRegionSelection;
import org.labkey.api.data.DisplayColumn;
import org.labkey.api.data.RenderContext;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.data.SqlExecutor;
import org.labkey.api.data.TableInfo;
Expand Down Expand Up @@ -2078,7 +2079,7 @@ private static SimpleFilter getFilter(Settings settings, Permissions perm, boole
if (!displayAll)
{
if (settings.hasExpires())
filter.addWhereClause("Expires IS NULL OR Expires > ?", new Object[]{new Date(System.currentTimeMillis() - DateUtils.MILLIS_PER_DAY)});
filter.addWhereClause(SQLFragment.unsafe("Expires IS NULL OR Expires > ?", new Date(System.currentTimeMillis() - DateUtils.MILLIS_PER_DAY)));
}

return filter;
Expand Down Expand Up @@ -2518,12 +2519,12 @@ public boolean handlePost(SubscriptionBean bean, BindException errors)
// Remove or add the thread-level subscription from the database table
if (bean.isUnsubscribe())
{
new SqlExecutor(CommSchema.getInstance().getSchema()).execute("DELETE FROM comm.userlist WHERE UserId = ? AND MessageId = ?", getUser(), postId);
new SqlExecutor(CommSchema.getInstance().getSchema()).execute(SQLFragment.unsafe("DELETE FROM comm.userlist WHERE UserId = ? AND MessageId = ?", getUser(), postId));
}
else if (!ann.getMemberListIds().contains(getUser().getUserId()))
{
new SqlExecutor(CommSchema.getInstance().getSchema()).execute("INSERT INTO comm.userlist (UserId, MessageId) SELECT ? AS UserId, ? AS MessageId WHERE NOT EXISTS (SELECT * FROM comm.userlist WHERE UserId = ? AND MessageId = ?)",
getUser(), postId, getUser(), postId);
new SqlExecutor(CommSchema.getInstance().getSchema()).execute(SQLFragment.unsafe("INSERT INTO comm.userlist (UserId, MessageId) SELECT ? AS UserId, ? AS MessageId WHERE NOT EXISTS (SELECT * FROM comm.userlist WHERE UserId = ? AND MessageId = ?)",
getUser(), postId, getUser(), postId));
}
return true;
}
Expand Down Expand Up @@ -3155,7 +3156,7 @@ public void testGetThreadHidesUnapprovedThread() throws Exception
User reader = createUserInRole(_folderB, ReaderRole.class);
AnnouncementModel pending = insertDiscussion(_folderB, null, null);
TableInfo announcements = CommSchema.getInstance().getTableInfoAnnouncements();
new SqlExecutor(announcements.getSchema()).execute("UPDATE " + announcements.getSelectName() + " SET Approved = NULL WHERE RowId = ?", pending.getRowId());
new SqlExecutor(announcements.getSchema()).execute(SQLFragment.unsafe("UPDATE ").append(announcements).unsafeAppend(" SET Approved = NULL WHERE RowId = ?", pending.getRowId()));

assertStatus(HttpServletResponse.SC_BAD_REQUEST, getThreadResponse(reader, _folderB, pending));
assertStatus(HttpServletResponse.SC_OK, getThreadResponse(reader, _folderB, _thread));
Expand Down Expand Up @@ -3287,7 +3288,7 @@ public void testSubscriptionTablesRequireAdminOfRowFolder() throws Exception

Map<String, Object> row = new HashMap<>(Map.of("User", victim.getUserId(), "Folder", _folderB.getId(), "EmailOption", EmailOption.MESSAGES_ALL.getValue()));
forumSubscriptionService(adminOfB).insertRows(adminOfB, _folderB, List.of(row), new BatchValidationException(), null, null);
new SqlExecutor(CommSchema.getInstance().getSchema()).execute("INSERT INTO comm.userlist (UserId, MessageId) VALUES (?, ?)", victim.getUserId(), _thread.getRowId());
new SqlExecutor(CommSchema.getInstance().getSchema()).execute(SQLFragment.unsafe("INSERT INTO comm.userlist (UserId, MessageId) VALUES (?, ?)", victim.getUserId(), _thread.getRowId()));

// Both query from A across all folders; only B's admin sees B's rows for another user
assertEquals(Map.of(AnnouncementSchema.FORUM_SUBSCRIPTION_TABLE_NAME, 0L, AnnouncementSchema.ANNOUNCEMENT_SUBSCRIPTION_TABLE_NAME, 0L), subscriptionCounts(adminOfA, victim));
Expand Down Expand Up @@ -3383,7 +3384,7 @@ public void testModerationTablesRequireAdmin() throws Exception
spam.setTitle("Spam");
spam.setBody("body");
spam = AnnouncementManager.insertAnnouncement(_folderB, getAdmin(), spam, null, false);
new SqlExecutor(announcements.getSchema()).execute("UPDATE " + announcements.getSelectName() + " SET Approved = NULL WHERE RowId IN (?, ?)", pending.getRowId(), spam.getRowId());
new SqlExecutor(announcements.getSchema()).execute(SQLFragment.unsafe("UPDATE ").append(announcements).unsafeAppend(" SET Approved = NULL WHERE RowId IN (?, ?)", pending.getRowId(), spam.getRowId()));
AnnouncementManager.markAsSpam(_folderB, spam);
Set<Integer> mine = Set.of(pending.getRowId(), spam.getRowId());

Expand Down Expand Up @@ -3531,7 +3532,7 @@ public void testApiWritesHideUnreadableThread() throws Exception
Container board = createBoard("NormalUnapproved", Settings.SECURE_OFF);
AnnouncementModel pending = insertThread(board);
TableInfo announcements = CommSchema.getInstance().getTableInfoAnnouncements();
new SqlExecutor(announcements.getSchema()).execute("UPDATE " + announcements.getSelectName() + " SET Approved = NULL WHERE RowId = ?", pending.getRowId());
new SqlExecutor(announcements.getSchema()).execute(SQLFragment.unsafe("UPDATE ").append(announcements).unsafeAppend(" SET Approved = NULL WHERE RowId = ?", pending.getRowId()));
assertStatus(HttpServletResponse.SC_OK, post(new ActionURL(DeleteThreadAction.class, board).addParameter("rowId", pending.getRowId()), getAdmin()));
assertNull(AnnouncementManager.getAnnouncement(board, pending.getRowId()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,20 @@ public class AnnouncementDigestProvider implements MessageDigest.Provider

// Retrieve from this container all messages with a body or attachments that were marked as "approved" during the given
// timespan. Messages are grouped by thread and threads are sorted by earliest post within each thread.
private static final String RECENT_ANN_SQL = "SELECT annModel.* FROM\n" +
private static SQLFragment getRecentAnnouncementsSql(Container c, Date min, Date max)
{
return SQLFragment.unsafe("SELECT annModel.* FROM\n" +
"\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(SELECT Approved, CASE WHEN Parent IS NULL THEN EntityId ELSE Parent END AS Thread FROM ").append(_comm.getTableInfoAnnouncements()).unsafeAppend(" annModel LEFT OUTER JOIN\n" +
"\t\t\t(SELECT DISTINCT Parent AS DocParent FROM ").append(_core.getTableInfoDocuments()).unsafeAppend(") 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) X LEFT OUTER JOIN ", c, min, max).append(_comm.getTableInfoAnnouncements()).unsafeAppend(" annModel ON Parent = Thread OR EntityId = Thread LEFT OUTER JOIN\n" +
"\t\t(SELECT DISTINCT Parent AS DocParent FROM ").append(_core.getTableInfoDocuments()).unsafeAppend(") 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";
"ORDER BY Earliest, Thread, Approved", c, min, max);
}

@Override
public void sendDigestForAllContainers(Date start, Date end) throws Exception
Expand Down Expand Up @@ -129,7 +132,7 @@ private void sendDigest(Container c, Date start, Date end) throws Exception

private static Collection<AnnouncementModel> getRecentAnnouncementsInContainer(Container c, Date min, Date max)
{
try (Stream<AnnouncementModel> announcementStream = new SqlSelector(_comm.getSchema(), RECENT_ANN_SQL, c, min, max, c, min, max).uncachedStream(AnnouncementModel.class))
try (Stream<AnnouncementModel> announcementStream = new SqlSelector(_comm.getSchema(), getRecentAnnouncementsSql(c, min, max)).uncachedStream(AnnouncementModel.class))
{
return announcementStream
.filter(SHOULD_SEND_ANNOUNCEMENT_NOTIFICATION)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ public static void markAsSpam(Container c, AnnouncementModel ann)
private static boolean updateApproved(Container c, AnnouncementModel ann, Date date)
{
TableInfo ti = CommSchema.getInstance().getTableInfoAnnouncements();
return new SqlExecutor(ti.getSchema()).execute("UPDATE " + ti.getSelectName() + " SET Approved = ? WHERE Container = ? AND RowId = ? AND Approved IS NULL", date, c, ann.getRowId()) > 0;
return new SqlExecutor(ti.getSchema()).execute(SQLFragment.unsafe("UPDATE ").append(ti).unsafeAppend(" SET Approved = ? WHERE Container = ? AND RowId = ? AND Approved IS NULL", date, c, ann.getRowId())) > 0;
}

// Render and send all the email notifications on a background thread, #13143
Expand Down Expand Up @@ -1016,8 +1016,8 @@ private static boolean isSecure(@NotNull Container c)
public static void setLastIndexed(String entityId, long ms)
{
new SqlExecutor(_comm.getSchema()).execute(
"UPDATE comm.Announcements SET LastIndexed=? WHERE EntityId=?",
new Timestamp(ms), entityId);
SQLFragment.unsafe("UPDATE comm.Announcements SET LastIndexed=? WHERE EntityId=?",
new Timestamp(ms), entityId));
}


Expand Down Expand Up @@ -1067,10 +1067,10 @@ 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 = ?)";
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);
SQLFragment deleteDocuments = SQLFragment.unsafe("DELETE FROM ").append(_core.getTableInfoDocuments()).unsafeAppend(" WHERE Container = ? AND Parent IN (SELECT EntityId FROM ", c).append(_comm.getTableInfoAnnouncements()).unsafeAppend(" WHERE Container = ?)", c);
int docs = new SqlExecutor(_comm.getSchema()).execute(deleteDocuments);
SQLFragment deleteAnnouncements = SQLFragment.unsafe("DELETE FROM ").append(_comm.getTableInfoAnnouncements()).unsafeAppend(" WHERE Container = ?", c);
int pages = new SqlExecutor(_comm.getSchema()).execute(deleteAnnouncements);

if (verifyEmpty)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.jetbrains.annotations.Nullable;
import org.labkey.api.announcements.CommSchema;
import org.labkey.api.data.Container;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.SimpleFilter;
import org.labkey.api.security.User;
import org.labkey.api.security.permissions.ReadPermission;
Expand Down Expand Up @@ -84,12 +85,12 @@ public SimpleFilter getThreadFilter()
if (!hasPermission(SecureMessageBoardReadPermission.class))
{
filter.addWhereClause(
"RowId IN (" +
"SELECT rowid FROM " + CommSchema.getInstance().getTableInfoUserList() + " " +
"JOIN (SELECT latestid, rowid FROM " + CommSchema.getInstance().getTableInfoThreads() + ") t ON messageid=t.latestid " +
SQLFragment.unsafe("RowId IN (" +
"SELECT rowid FROM ").append(CommSchema.getInstance().getTableInfoUserList()).unsafeAppend(" " +
"JOIN (SELECT latestid, rowid FROM ").append(CommSchema.getInstance().getTableInfoThreads()).unsafeAppend(") t ON messageid=t.latestid " +
"WHERE userid=?" +
")",
new Object[]{_user.getUserId()});
_user.getUserId()));
}

return filter;
Expand Down
4 changes: 2 additions & 2 deletions api/src/org/labkey/api/data/AbstractPropertyStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ void deleteProperties(Container c)
deleteProps.unsafeAppend(")");
new SqlExecutor(_prop.getSchema()).execute(deleteProps);

SQLFragment deleteSets = new SQLFragment("DELETE FROM " + _prop.getTableInfoPropertySets() + " WHERE ObjectId = ? AND ");
SQLFragment deleteSets = SQLFragment.unsafe("DELETE FROM ").append(_prop.getTableInfoPropertySets().getSQLName()).unsafeAppend(" WHERE ObjectId = ? AND ");
deleteSets.add(c);
appendWhereFilter(deleteSets);
new SqlExecutor(_prop.getSchema()).execute(deleteSets);
Expand Down Expand Up @@ -254,7 +254,7 @@ public PropertyMap getPropertyMapFromDatabase(User user, Container container, St
@Override
public final Stream<Container> streamMatchingContainers(User user, String category)
{
SQLFragment sql = new SQLFragment("SELECT ObjectId FROM " + _prop.getTableInfoPropertySets() + " WHERE UserId = ? AND Category = ?", user, category);
SQLFragment sql = SQLFragment.unsafe("SELECT ObjectId FROM ").append(_prop.getTableInfoPropertySets().getSQLName()).unsafeAppend(" WHERE UserId = ? AND Category = ?", user, category);

return new SqlSelector(_prop.getSchema(), sql).uncachedStream(String.class)
.map(ContainerManager::getForId)
Expand Down
19 changes: 13 additions & 6 deletions api/src/org/labkey/api/data/Aggregate.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ default String getSQLFunctionName(@Nullable SqlDialect dialect)
return getName();
}

/** @return the SQL function name as a fragment, or null for aggregates with no SQL function */
default @Nullable SQLFragment getNameAsSql(@Nullable SqlDialect dialect)
{
String fn = getSQLFunctionName(dialect);
return null == fn ? null : new SQLFragment().appendIdentifier(fn);
}

/**
* Get the generated SQL for calculating this aggregate (i.e. summary stat) value based on a TableInfo column.
* @param dialect SQL dialect for the running server
Expand Down Expand Up @@ -96,7 +103,7 @@ default SQLFragment getSQLColumnFragment(SqlDialect dialect, SQLFragment columnN
return null;

SQLFragment sb = new SQLFragment();
sb.append(getSQLFunctionName(dialect)).unsafeAppend("(");
sb.append(getNameAsSql(dialect)).unsafeAppend("(");
if (distinct)
sb.unsafeAppend("DISTINCT ");
sb.append(columnNameFragment);
Expand Down Expand Up @@ -182,12 +189,12 @@ public SQLFragment getSQLColumnFragment(SqlDialect dialect, SQLFragment columnNa
* @param jdbcType type of column
* @return cast datatype, if a wider datatype is available
*/
private String castType(JdbcType jdbcType)
private SQLFragment castType(JdbcType jdbcType)
{
return switch (jdbcType)
{
case BIGINT, INTEGER, SMALLINT -> JdbcType.BIGINT.toString();
case DECIMAL, DOUBLE, REAL -> "FLOAT";
case BIGINT, INTEGER, SMALLINT -> SQLFragment.unsafe("BIGINT");
case DECIMAL, DOUBLE, REAL -> SQLFragment.unsafe("FLOAT");
default -> null;
};
}
Expand Down Expand Up @@ -221,7 +228,7 @@ public SQLFragment getSQLColumnFragment(SqlDialect dialect, SQLFragment columnNa
if (jdbcType != null && (jdbcType.equals(JdbcType.INTEGER) || jdbcType.equals(JdbcType.BIGINT) || jdbcType.equals(JdbcType.SMALLINT)))
{
SQLFragment sb = new SQLFragment();
sb.append(getSQLFunctionName(dialect)).unsafeAppend("(");
sb.append(getNameAsSql(dialect)).unsafeAppend("(");
if (distinct)
sb.unsafeAppend("DISTINCT ");
sb.unsafeAppend("CAST(").append(columnNameFragment).unsafeAppend(" AS FLOAT)");
Expand Down Expand Up @@ -465,7 +472,7 @@ public SQLFragment toLabKeySQL(SQLFragment tableInnerSql, @NotNull SqlDialect di
return _type.getSQLColumnFragment(null, getFieldKey().toSQLString(), alias, JdbcType.INTEGER, _distinct, tableInnerSql);

SQLFragment sb = new SQLFragment();
sb.append(_type.getSQLFunctionName(null)).unsafeAppend("(");
sb.append(_type.getNameAsSql(null)).unsafeAppend("(");
if (_distinct)
sb.unsafeAppend("DISTINCT ");
sb.appendIdentifier(getFieldKey().toSQLString());
Expand Down
Loading