|
| 1 | +package com.dbaagent.config; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import org.springframework.context.annotation.Bean; |
| 5 | +import org.springframework.context.annotation.Configuration; |
| 6 | +import org.springframework.context.annotation.DependsOn; |
| 7 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 8 | + |
| 9 | +import javax.sql.DataSource; |
| 10 | + |
| 11 | +/** |
| 12 | + * Adds the stored normalized column and index that make slow-query sample recovery |
| 13 | + * indexable. |
| 14 | + * |
| 15 | + * <p>{@code QueryLineageRepository.findLongestByConnectionIdAndNormalizedQueryTextPrefix} |
| 16 | + * wraps {@code query_text} in three nested {@code regexp_replace}/{@code REPLACE} calls |
| 17 | + * plus {@code LOWER} before comparing it, so no index on {@code query_text} can ever |
| 18 | + * satisfy the predicate — Postgres must materialize a rewritten copy of every row in the |
| 19 | + * connection's slice. {@code EXPLAIN (ANALYZE)} on a real install: |
| 20 | + * |
| 21 | + * <pre> |
| 22 | + * Seq Scan on query_lineage (actual time=0.244..35.826 rows=422 loops=1) |
| 23 | + * Execution Time: 36.179 ms -- at 1,093 rows |
| 24 | + * Execution Time: 1111.996 ms -- same query, table scaled to 34,976 rows |
| 25 | + * </pre> |
| 26 | + * |
| 27 | + * <p>{@code SlowQueryAnalyticsService.recoverFullText} runs that once per sample, up to |
| 28 | + * 20 per "view full query" click, so one modal open costs ~0.7 s today and ~22 s at 35k |
| 29 | + * rows. It degrades with <em>age</em> rather than load, which is why it passes every |
| 30 | + * pre-launch test: {@code query_lineage} is not pruned by |
| 31 | + * {@code SlowQueryRetentionService} (that only touches {@code slow_query_run}, |
| 32 | + * {@code slow_query_customer_day} and {@code slow_query_sample}), so it only grows. |
| 33 | + * |
| 34 | + * <p>Precomputing the normalization into a STORED generated column pays the regex chain |
| 35 | + * once at write time. Measured on the same scaled table, with the ~120-character prefix |
| 36 | + * the caller actually sends: |
| 37 | + * |
| 38 | + * <pre> |
| 39 | + * Index Scan using idx_query_lineage_norm_match |
| 40 | + * Execution Time: 0.428 ms -- vs 1111.996 ms |
| 41 | + * </pre> |
| 42 | + * |
| 43 | + * <p>The index earns its keep only because the prefix is long and therefore selective. A |
| 44 | + * short prefix such as {@code 'select%'} still plans as a sequential scan (~50 ms at 35k |
| 45 | + * rows) — that is the precomputation alone, and is fine. Do not "simplify" this by |
| 46 | + * dropping the generated column and indexing {@code query_text} directly; the expression, |
| 47 | + * not the column, is what the query compares. |
| 48 | + * |
| 49 | + * <p>There is no Flyway runtime in this repo (see CLAUDE.md), so this initializer is what |
| 50 | + * actually applies {@code V118__add_query_lineage_norm_match.sql}. Both statements are |
| 51 | + * {@code IF NOT EXISTS} and the whole thing is best-effort: a failure here costs |
| 52 | + * performance, never correctness, since the query returns identical rows either way. |
| 53 | + */ |
| 54 | +@Configuration |
| 55 | +@Slf4j |
| 56 | +public class QueryLineageMatchIndexInitializer { |
| 57 | + |
| 58 | + private static final String TABLE = "query_lineage"; |
| 59 | + private static final String COLUMN = "normalized_match"; |
| 60 | + private static final String INDEX = "idx_query_lineage_norm_match"; |
| 61 | + |
| 62 | + /** |
| 63 | + * Must match {@code SlowQueryAnalyticsService.normalizeForMatching} exactly, and the |
| 64 | + * expression already inlined in the repository query. If one changes, all three do. |
| 65 | + */ |
| 66 | + private static final String NORMALIZE_EXPR = |
| 67 | + "lower(regexp_replace(regexp_replace(" |
| 68 | + + "replace(query_text, '`', ''), " |
| 69 | + + "'\\s*([.,();])\\s*', '\\1', 'g'), " |
| 70 | + + "'\\s+', ' ', 'g'))"; |
| 71 | + |
| 72 | + @Bean("queryLineageMatchIndexBootstrap") |
| 73 | + @DependsOn("entityManagerFactory") |
| 74 | + public Object queryLineageMatchIndexBootstrap(DataSource dataSource) { |
| 75 | + JdbcTemplate jdbc = new JdbcTemplate(dataSource); |
| 76 | + |
| 77 | + if (!tableExists(jdbc, TABLE)) { |
| 78 | + return new Object(); |
| 79 | + } |
| 80 | + |
| 81 | + try { |
| 82 | + jdbc.execute("ALTER TABLE " + TABLE + " ADD COLUMN IF NOT EXISTS " + COLUMN |
| 83 | + + " text GENERATED ALWAYS AS (" + NORMALIZE_EXPR + ") STORED"); |
| 84 | + } catch (RuntimeException e) { |
| 85 | + // Generated columns need Postgres 12+. Older servers keep the sequential scan, |
| 86 | + // which is slow but correct, so this must not stop the application. |
| 87 | + log.warn("Could not add {}.{} ({}); sample recovery stays on a sequential scan", |
| 88 | + TABLE, COLUMN, e.getMessage()); |
| 89 | + return new Object(); |
| 90 | + } |
| 91 | + |
| 92 | + try { |
| 93 | + // text_pattern_ops so a LIKE 'prefix%' comparison can use the index under any |
| 94 | + // collation; the default opclass only helps in the C collation. |
| 95 | + jdbc.execute("CREATE INDEX IF NOT EXISTS " + INDEX + " ON " + TABLE |
| 96 | + + " (connection_id, " + COLUMN + " text_pattern_ops)"); |
| 97 | + } catch (RuntimeException e) { |
| 98 | + log.warn("Could not create {}: {}", INDEX, e.getMessage()); |
| 99 | + } |
| 100 | + |
| 101 | + return new Object(); |
| 102 | + } |
| 103 | + |
| 104 | + private static boolean tableExists(JdbcTemplate jdbc, String table) { |
| 105 | + try { |
| 106 | + Integer found = jdbc.queryForObject( |
| 107 | + "SELECT COUNT(*) FROM information_schema.tables " |
| 108 | + + "WHERE table_schema = current_schema() AND table_name = ?", |
| 109 | + Integer.class, table); |
| 110 | + return found != null && found > 0; |
| 111 | + } catch (RuntimeException e) { |
| 112 | + log.warn("Could not check for table {}: {}", table, e.getMessage()); |
| 113 | + return false; |
| 114 | + } |
| 115 | + } |
| 116 | +} |
0 commit comments