Repository navigation
Speed up building temp tables for large IN clauses #8382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
|
||
|
|
@@ -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. | ||
|
|
@@ -132,51 +134,48 @@ else if (jdbcType == JdbcType.VARCHAR) | |
| if (null == sortedParameters) | ||
| return null; | ||
|
|
||
| String cacheKey = getCacheKey(jdbcType, sortedParameters); | ||
| DbSchema tempSchema = _tempSchemaSupplier.get(); | ||
| // 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; | ||
|
|
@@ -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) | ||
|
|
@@ -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()); | ||
|
|
@@ -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() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we add a test for testNotUnlogged?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| { | ||
| 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() | ||
| { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
|
||
There was a problem hiding this comment.
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.