Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions api/src/org/labkey/api/cache/CacheManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,23 @@ public class CacheManager
);

@SuppressWarnings("unchecked")
private static <K, V> SimpleCache<K, V> getSimpleCache(@NotNull Class<K> keyClass, int limit, long defaultTimeToLive, String debugName, boolean temporary)
private static <K, V> SimpleCache<K, V> getSimpleCache(@NotNull Class<K> keyClass, int limit, long defaultTimeToLive, long defaultTimeToIdle, String debugName, boolean temporary)
{
SimpleCache<?, ?> cache = PROVIDER.getSimpleCache(debugName, limit, defaultTimeToLive, UNLIMITED, temporary);
SimpleCache<?, ?> cache = PROVIDER.getSimpleCache(debugName, limit, defaultTimeToLive, defaultTimeToIdle, temporary);
Function<SimpleCache<?, ?>, SimpleCache<?, ?>> mapping = KEY_MAPPINGS.get(keyClass);
return (SimpleCache<K, V>) (null == mapping ? cache : mapping.apply(cache));
}

/** Returns a cache implementation specialized for keyClass, if one is registered */
public static <K, V> TrackingCache<K, V> getCache(@NotNull Class<K> keyClass, int limit, long defaultTimeToLive, String debugName)
{
CacheWrapper<K, V> cache = new CacheWrapper<>(getSimpleCache(keyClass, limit, defaultTimeToLive, debugName, false), keyClass, debugName, null, Thread.currentThread().getStackTrace());
return getCache(keyClass, limit, defaultTimeToLive, UNLIMITED, debugName);
}

/** Like {@link #getCache(Class, int, long, String)}, but entries also expire defaultTimeToIdle ms after their last get or put */
public static <K, V> TrackingCache<K, V> getCache(@NotNull Class<K> keyClass, int limit, long defaultTimeToLive, long defaultTimeToIdle, String debugName)
{
CacheWrapper<K, V> cache = new CacheWrapper<>(getSimpleCache(keyClass, limit, defaultTimeToLive, defaultTimeToIdle, debugName, false), keyClass, debugName, null, Thread.currentThread().getStackTrace());
addToKnownCaches(cache); // Permanent cache -- hold onto it
LabKeyManagement.register(cache.createDynamicMBean(), debugName, "Cache");
return cache;
Expand All @@ -109,7 +115,7 @@ public static <K, V> BlockingCache<K, V> getBlockingCache(@NotNull Class<K> keyC
// Temporary caches must be closed when no longer needed. Their statistics can accumulate to another cache's stats.
public static <K, V> Cache<K, V> getTemporaryCache(@NotNull Class<K> keyClass, int limit, long defaultTimeToLive, String debugName, @Nullable Stats stats)
{
return new CacheWrapper<>(getSimpleCache(keyClass, limit, defaultTimeToLive, debugName, true), keyClass, debugName, stats, null);
return new CacheWrapper<>(getSimpleCache(keyClass, limit, defaultTimeToLive, UNLIMITED, debugName, true), keyClass, debugName, stats, null);
}

private static final Cache<String, Object> SHARED_CACHE = getCache(String.class, 10000, DEFAULT_TIMEOUT, "Shared");
Expand Down
125 changes: 94 additions & 31 deletions api/src/org/labkey/api/data/TempTableInClauseGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.labkey.api.action.SpringActionController;
import org.labkey.api.cache.Cache;
import org.labkey.api.cache.CacheManager;
import org.labkey.api.data.dialect.SqlDialect;
import org.labkey.api.util.GUID;
import org.labkey.api.util.HashHelpers;

Expand All @@ -43,7 +45,7 @@
public class TempTableInClauseGenerator implements InClauseGenerator
{
private static final Cache<String, TempTableInfo> _tempTableCache =
CacheManager.getCache(String.class, 200, CacheManager.MINUTE * 5, "IN clause temp tables");
CacheManager.getCache(String.class, 200, CacheManager.HOUR, CacheManager.MINUTE * 5, "IN clause temp tables");

// Need to set a supplier instead of setting the default temp schema directly because this class is constructed at
// dialect init time, before schemas can be referenced.
Expand Down Expand Up @@ -132,51 +134,48 @@ else if (jdbcType == JdbcType.VARCHAR)
if (null == sortedParameters)
return null;

String cacheKey = getCacheKey(jdbcType, sortedParameters);
DbSchema tempSchema = _tempSchemaSupplier.get();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heads up, this may conflict with similar changes in #8381 which is targeting develop.

// UnloggedTableGeneration only detects resets in the LabKey database
boolean unlogged = tempSchema.getScope().isLabKeyScope();
// Scope by database and schema, so an external temp schema never reuses a LabKey table or vice versa
String cacheKey = tempSchema.getScope().getDataSourceName() + "_" + tempSchema.getName() + "_" + getCacheKey(jdbcType, sortedParameters);
// A reset empties the table, so a new generation must not hit the old entry
if (unlogged)
cacheKey += "_" + UnloggedTableGeneration.current();
TempTableInfo tempTableInfo = _tempTableCache.get(cacheKey);
if (tempTableInfo == null)
{
DbSchema tempSchema = _tempSchemaSupplier.get();
SqlDialect dialect = tempSchema.getSqlDialect();
tempTableInfo = new TempTableInfo(tempSchema, "InClause", Collections.singletonList(new BaseColumnInfo("Id", jdbcType, 0, false)), null);
SQLFragment sqlCreate = new SQLFragment("CREATE TABLE ");
SQLFragment sqlCreate = SQLFragment.unsafe(unlogged ? "CREATE UNLOGGED TABLE " : "CREATE TABLE ");
sqlCreate.append(tempTableInfo)
.unsafeAppend("\n(Id ")
.append(tempSchema.getSqlDialect().getSqlTypeName(jdbcType))
.append(jdbcType == JdbcType.VARCHAR ? "(450)" : "")
.append(dialect.getSqlTypeNameAsSql(jdbcType))
.unsafeAppend(jdbcType == JdbcType.VARCHAR ? "(450)" : "")
.unsafeAppend(")");

// When the in clause receives more parameters than it is set to handle, a temporary table is created to handle the overflow.
// While the associated mutating operations are necessary, they are not a viable CSRF attack vector.
try (var ignored = SpringActionController.ignoreSqlUpdates())
{
new SqlExecutor(tempSchema).execute(sqlCreate);
}
tempTableInfo.track();
String tableName = tempTableInfo.getSelectName();
String sql1 = "INSERT INTO " + tableName + " (Id) VALUES (?)";
String sql100 = "INSERT INTO " + tableName + " (Id) VALUES (?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?)";
try
{
try (var ignored = SpringActionController.ignoreSqlUpdates())
tempTableInfo.track();
String tableName = tempTableInfo.getSelectName();
if (dialect.supportsArrays())
{
if (jdbcType == JdbcType.VARCHAR)
Table.batchExecute1String(tempSchema, sql1, (ArrayList<String>) sortedParameters);
else if (jdbcType == JdbcType.INTEGER)
Table.batchExecute1Integer(tempSchema, sql1, sql100, (ArrayList<Integer>) sortedParameters);
else
Table.batchExecute1Long(tempSchema, sql1, sql100, (ArrayList<Long>) sortedParameters);
// One array-bound statement is several times faster than batched single-row INSERTs
new SqlExecutor(tempSchema).execute(SQLFragment.unsafe("INSERT INTO " + tableName + " (Id) ")
.append(dialect.array_unnest(jdbcType, sortedParameters)));
}
else
{
batchInsert(tempSchema, tableName, jdbcType, sortedParameters);
}
}
catch (SQLException e)
{
throw new RuntimeSQLException(e);
}

String indexSql = "CREATE INDEX IX_Id" + new GUID().toStringNoDashes() + " ON " + tableName + "(Id)";
try (var ignored = SpringActionController.ignoreSqlUpdates())
{
new SqlExecutor(tempSchema).execute(indexSql);
tempSchema.getSqlDialect().updateStatistics(tempTableInfo); // Immediately analyze the newly populated & indexed table
// UNIQUE lets the planner skip de-duplicating ids, but non-PostgreSQL collations may equate values the case-sensitive TreeSet kept apart
String unique = dialect.supportsArrays() ? "UNIQUE " : "";
new SqlExecutor(tempSchema).execute("CREATE " + unique + "INDEX IX_Id" + new GUID().toStringNoDashes() + " ON " + tableName + "(Id)");
dialect.updateStatistics(tempTableInfo); // Immediately analyze the newly populated & indexed table
}

TempTableInfo cacheEntry = tempTableInfo;
Expand All @@ -191,6 +190,25 @@ else if (jdbcType == JdbcType.INTEGER)
return tempTableInfo;
}

@SuppressWarnings("unchecked")
private static void batchInsert(DbSchema tempSchema, String tableName, JdbcType jdbcType, List<?> sortedParameters)
{
String sql1 = "INSERT INTO " + tableName + " (Id) VALUES (?)";
String sql100 = "INSERT INTO " + tableName + " (Id) VALUES (?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?),(?)";
try
{
if (jdbcType == JdbcType.VARCHAR)
Table.batchExecute1String(tempSchema, sql1, (List<String>) sortedParameters);
else if (jdbcType == JdbcType.INTEGER)
Table.batchExecute1Integer(tempSchema, sql1, sql100, (List<Integer>) sortedParameters);
else
Table.batchExecute1Long(tempSchema, sql1, sql100, (List<Long>) sortedParameters);
}
catch (SQLException e)
{
throw new RuntimeSQLException(e);
}
}

// unique and ordered list
private List<String> collectStrings(@NotNull Collection<?> paramsCollection)
Expand Down Expand Up @@ -258,8 +276,12 @@ else if (i instanceof Integer)
private String getCacheKey(@NotNull JdbcType jdbcType, @NotNull Collection<?> params)
{
StringBuilder paramBuilder = new StringBuilder();
// Length-prefix each value so different lists can't concatenate to the same string
for (Object param : params)
paramBuilder.append(param);
{
String s = String.valueOf(param);
paramBuilder.append(null == param ? -1 : s.length()).append(':').append(s);
}

// Hash the param string to avoid very large cache keys filling up memory
return jdbcType.name() + "_" + params.size() + "_" + HashHelpers.hash(paramBuilder.toString());
Expand Down Expand Up @@ -290,6 +312,47 @@ public void testString()
Assert.assertEquals("Validate SQL matches, indicated cached results", firstSQL, secondSQL);
}

@Test
public void testTypesWithNull()
{
record Case(String values, List<?> params) {}
for (Case c : List.of(
new Case("SELECT 'a' UNION SELECT 'b' UNION SELECT 'g'", Arrays.asList("d", "a", null, "b", "a")),
new Case("SELECT 1 UNION SELECT 2 UNION SELECT 7", Arrays.asList(4, 1, null, 2, 1)),
new Case("SELECT CAST(1 AS BIGINT) UNION SELECT 2 UNION SELECT 7", Arrays.asList(4L, 1L, null, 2L, 1L))))
{
SQLFragment sql = SQLFragment.unsafe("SELECT a FROM (" + c.values() + ") b(a) WHERE a ");
SQLFragment inClause = new TempTableInClauseGenerator().appendInClauseSql(sql, c.params());
Assert.assertNotNull(c.values(), inClause);
Assert.assertEquals(c.values(), 2, new SqlSelector(_scope, inClause).getRowCount());
}
}

@Test
public void testUnlogged()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a test for testNotUnlogged?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not seeing an easy way to do that, as it would require an external data source to be configured. The UNLOGGED difference is small in terms of codepath differences, so I think it's low risk.

{
Assume.assumeTrue(_scope.getSqlDialect().isPostgreSQL());
TempTableInfo tti = new TempTableInClauseGenerator().getTempTableInfo(STRINGS);
Assert.assertNotNull(tti);
SQLFragment sql = SQLFragment.unsafe("SELECT relpersistence FROM pg_class WHERE oid = CAST(? AS regclass)").add(tti.getSelectName());
Assert.assertEquals("u", new SqlSelector(_scope, sql).getObject(String.class));
}

@Test
public void testUnloggedReset()
{
Assume.assumeTrue(_scope.getSqlDialect().isPostgreSQL());
SQLFragment sql = SQLFragment.unsafe("SELECT a from (SELECT 'a' AS a UNION SELECT 'b' AS a UNION SELECT 'g' AS a) b WHERE a ");
// A value unique to this run keeps the TRUNCATE off any table another caller shares
List<String> values = List.of("a", "b", new GUID().toString());
TempTableInfo before = new TempTableInClauseGenerator().getTempTableInfo(values);
Assert.assertNotNull(before);
new SqlExecutor(_scope).execute(SQLFragment.unsafe("TRUNCATE ").append(before));
UnloggedTableGeneration.simulateResetForTest();
SQLFragment after = new TempTableInClauseGenerator().appendInClauseSql(new SQLFragment(sql), values);
Assert.assertEquals("A reset must rebuild the emptied temp table", 2, new SqlSelector(_scope, after).getRowCount());
}

@Test
public void testJdbcParameterValues()
{
Expand Down
4 changes: 3 additions & 1 deletion api/src/org/labkey/api/data/UnloggedTableGeneration.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ private UnloggedTableGeneration()
*/
public static String current()
{
if (HeartBeat.currentTimeMillis() - _lastCheck > CHECK_INTERVAL && _checkLock.tryLock())
if (HeartBeat.currentTimeMillis() - _lastCheck > CHECK_INTERVAL)
{
// Block rather than skip: a reader returning the old generation mid-check could reuse an emptied table
_checkLock.lock();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a more conservative approach to avoid reading a truncated table after a DB switch. I'm lukewarm on how much to worry about this failover scenario.

try
{
if (HeartBeat.currentTimeMillis() - _lastCheck > CHECK_INTERVAL)
Expand Down
7 changes: 7 additions & 0 deletions api/src/org/labkey/api/data/dialect/SqlDialect.java
Original file line number Diff line number Diff line change
Expand Up @@ -2628,6 +2628,13 @@ public SQLFragment array_not_same_array(SQLFragment a, SQLFragment b)
throw new UnsupportedOperationException(getClass().getSimpleName() + " does not implement");
}

// SELECT returning one row per element of the bound array
public SQLFragment array_unnest(JdbcType elementType, Collection<?> values)
{
assert !supportsArrays();
throw new UnsupportedOperationException(getClass().getSimpleName() + " does not implement");
}

// true if the array a contains, for EACH given value, some element matching it with a case-insensitive substring
public SQLFragment array_element_like(SQLFragment a, String... values)
{
Expand Down
12 changes: 12 additions & 0 deletions core/src/org/labkey/core/dialect/PostgreSql92Dialect.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import org.labkey.core.admin.sql.ScriptReorderer;
import org.springframework.jdbc.BadSqlGrammarException;

import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Driver;
Expand Down Expand Up @@ -1314,6 +1315,17 @@ public boolean supportsArrays()
return true;
}

@Override
public SQLFragment array_unnest(JdbcType elementType, Collection<?> values)
{
// A typed array lets the JDBC driver pick the element type even when the first element is null
Object[] array = values.toArray(n -> (Object[]) Array.newInstance(elementType.getJavaClass(), n));
return SQLFragment.unsafe("SELECT unnest(CAST(? AS ")
.append(getSqlTypeNameAsSql(elementType))
.unsafeAppend("[]))")
.add(array);
}

@Override
public SQLFragment array_construct(SQLFragment[] elements)
{
Expand Down