diff --git a/api/src/org/labkey/api/audit/query/AbstractAuditDomainKind.java b/api/src/org/labkey/api/audit/query/AbstractAuditDomainKind.java index 119f8117a02..2cbf1986218 100644 --- a/api/src/org/labkey/api/audit/query/AbstractAuditDomainKind.java +++ b/api/src/org/labkey/api/audit/query/AbstractAuditDomainKind.java @@ -429,15 +429,19 @@ public void validate() if (prefix.length() < 12) throw new IllegalStateException("Namespace prefix must be unique and longer than this: " + prefix); - List overlappers = PREFIXES.stream() - .filter(p -> p.startsWith(prefix) || prefix.startsWith(p)) - .map(p -> "\"" + p + "\"") - .toList(); - - if (overlappers.isEmpty()) - PREFIXES.add(prefix); - else - throw new IllegalStateException("Namespace prefix \"" + prefix + "\" overlaps with " + overlappers); + // Providers initialize concurrently + synchronized (PREFIXES) + { + List overlappers = PREFIXES.stream() + .filter(p -> p.startsWith(prefix) || prefix.startsWith(p)) + .map(p -> "\"" + p + "\"") + .toList(); + + if (overlappers.isEmpty()) + PREFIXES.add(prefix); + else + throw new IllegalStateException("Namespace prefix \"" + prefix + "\" overlaps with " + overlappers); + } } public static class TestCase extends Assert diff --git a/api/src/org/labkey/api/data/BaseColumnInfo.java b/api/src/org/labkey/api/data/BaseColumnInfo.java index fcd4d6f4e2a..354a57bf845 100644 --- a/api/src/org/labkey/api/data/BaseColumnInfo.java +++ b/api/src/org/labkey/api/data/BaseColumnInfo.java @@ -1717,7 +1717,7 @@ public static Collection createFromDatabaseMetaData(String schem } } - JdbcMetaDataSelector keySelector = new JdbcMetaDataSelector(locator, (dbmd, locator1) -> dbmd.getImportedKeys(locator1.getCatalogName(), locator1.getSchemaName(), locator1.getTableName())); + JdbcMetaDataSelector keySelector = dialect.getImportedKeysSelector(locator); // load keys in two phases // 1) combine multi-column keys diff --git a/api/src/org/labkey/api/data/dialect/JdbcMetaDataTest.java b/api/src/org/labkey/api/data/dialect/JdbcMetaDataTest.java index eeea8a4605f..cd935fc9dbe 100644 --- a/api/src/org/labkey/api/data/dialect/JdbcMetaDataTest.java +++ b/api/src/org/labkey/api/data/dialect/JdbcMetaDataTest.java @@ -17,15 +17,24 @@ import org.junit.Assert; import org.junit.Test; +import org.labkey.api.audit.AbstractAuditTypeProvider; import org.labkey.api.data.CoreSchema; import org.labkey.api.data.DatabaseTableType; import org.labkey.api.data.DbSchema; import org.labkey.api.data.DbSchemaType; +import org.labkey.api.data.DbScope; +import org.labkey.api.data.JdbcMetaDataSelector; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SqlExecutor; import org.labkey.api.data.TableInfo; import org.labkey.api.data.TableSelector; import org.labkey.api.data.TestSchema; +import org.labkey.api.exp.api.ExperimentService; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; public class JdbcMetaDataTest extends Assert { @@ -45,12 +54,54 @@ public void testTablesWithSpecialCharacters() @Test public void testMaterializedView() { - // SQL Server doesn't support materialized views - if (_testSchema.getSqlDialect().isPostgreSQL()) + new SqlExecutor(_testSchema).execute(SQLFragment.unsafe("REFRESH MATERIALIZED VIEW test.MaterializedView")); + test("MaterializedView", CoreSchema.getInstance().getTableInfoContainers(), DatabaseTableType.MATERIALIZED_VIEW); + } + + @Test + public void testImportedKeysMatchJdbc() throws SQLException + { + DbScope scope = _testSchema.getScope(); + + for (String schemaName : List.of(CoreSchema.getInstance().getSchemaName(), ExperimentService.get().getSchema().getName(), AbstractAuditTypeProvider.SCHEMA_NAME)) + { + for (String tableName : DbSchema.createFromMetaData(scope, schemaName, DbSchemaType.Bare).getTableNames()) + assertImportedKeysMatch(scope, schemaName, tableName); + } + + // Mixed case, LIKE wild cards, a multi-column FK, and a cross-schema FK, on tables visible only to this uncommitted transaction + try (DbScope.Transaction ignored = scope.ensureTransaction()) + { + new SqlExecutor(scope).execute(SQLFragment.unsafe( + "CREATE TABLE test.\"FkParent_%X\" (\"Container\" VARCHAR(36) NOT NULL, \"RowId\" INT NOT NULL, PRIMARY KEY (\"Container\", \"RowId\"));\n" + + "CREATE TABLE test.\"FkChild$Y\" (\"Container\" VARCHAR(36) NOT NULL, \"ParentRowId\" INT, \"ContainerRowId\" INT, " + + "CONSTRAINT \"FK_Child_Parent\" FOREIGN KEY (\"Container\", \"ParentRowId\") REFERENCES test.\"FkParent_%X\" (\"Container\", \"RowId\"), " + + "CONSTRAINT \"FK_Child_Containers\" FOREIGN KEY (\"ContainerRowId\") REFERENCES ").append(CoreSchema.getInstance().getTableInfoContainers()).append(SQLFragment.unsafe(" (RowId))"))); + assertEquals(3, assertImportedKeysMatch(scope, _testSchema.getName(), "FkChild$Y")); + } + } + + /** Asserts the dialect's FK selector returns the rows JDBC getImportedKeys() does, in the same order; returns the row count */ + private static int assertImportedKeysMatch(DbScope scope, String schemaName, String tableName) throws SQLException + { + try (JdbcMetaDataLocator locator = scope.getSqlDialect().getTableResolver().getSingleTableLocator(scope, schemaName, tableName)) + { + List> expected = readImportedKeys(new JdbcMetaDataSelector(locator, (dbmd, l) -> dbmd.getImportedKeys(l.getCatalogName(), l.getSchemaName(), l.getTableName()))); + List> actual = readImportedKeys(scope.getSqlDialect().getImportedKeysSelector(locator)); + assertEquals(schemaName + "." + tableName, expected, actual); + return actual.size(); + } + } + + private static List> readImportedKeys(JdbcMetaDataSelector selector) throws SQLException + { + List> rows = new ArrayList<>(); + try (ResultSet rs = selector.getResultSet()) { - new SqlExecutor(_testSchema).execute(SQLFragment.unsafe("REFRESH MATERIALIZED VIEW test.MaterializedView")); - test("MaterializedView", CoreSchema.getInstance().getTableInfoContainers(), DatabaseTableType.MATERIALIZED_VIEW); + while (rs.next()) + rows.add(List.of(rs.getString("PKTABLE_SCHEM"), rs.getString("PKTABLE_NAME"), rs.getString("PKCOLUMN_NAME"), rs.getString("FKCOLUMN_NAME"), rs.getInt("KEY_SEQ"), rs.getString("FK_NAME"))); } + return rows; } private void test(String viewName, TableInfo expectedTable, DatabaseTableType expectedTableType) diff --git a/api/src/org/labkey/api/data/dialect/SqlDialect.java b/api/src/org/labkey/api/data/dialect/SqlDialect.java index 1efaa4fa3d6..0ac665cf64a 100644 --- a/api/src/org/labkey/api/data/dialect/SqlDialect.java +++ b/api/src/org/labkey/api/data/dialect/SqlDialect.java @@ -41,6 +41,7 @@ import org.labkey.api.data.DbScope; import org.labkey.api.data.DbScope.LabKeyDataSource; import org.labkey.api.data.InClauseGenerator; +import org.labkey.api.data.JdbcMetaDataSelector; import org.labkey.api.data.JdbcMetaDataSelector.JdbcMetaDataResultSetFactory; import org.labkey.api.data.JdbcType; import org.labkey.api.data.LookupColumn; @@ -1592,6 +1593,12 @@ public final ForeignKeyResolver getForeignKeyResolver(DbScope scope, @Nullable S return getTableResolver().getForeignKeyResolver(scope, schemaName, tableName); } + /** Selects the locator's table's foreign keys as a {@link DatabaseMetaData#getImportedKeys} result set, ordered by PK table, FK_NAME, KEY_SEQ */ + public JdbcMetaDataSelector getImportedKeysSelector(JdbcMetaDataLocator locator) + { + return new JdbcMetaDataSelector(locator, (dbmd, l) -> dbmd.getImportedKeys(l.getCatalogName(), l.getSchemaName(), l.getTableName())); + } + // Pass-through by default. Dialects can override if they need special handling. public JdbcMetaDataResultSetFactory getJdbcMetaDataResultSetFactory(JdbcMetaDataResultSetFactory jdbcMetaDataResultSetFactory) { diff --git a/api/src/org/labkey/api/module/ModuleArchiveTestCase.java b/api/src/org/labkey/api/module/ModuleArchiveTestCase.java index c1331e250a2..40045630c7d 100644 --- a/api/src/org/labkey/api/module/ModuleArchiveTestCase.java +++ b/api/src/org/labkey/api/module/ModuleArchiveTestCase.java @@ -141,6 +141,60 @@ public void testHeldUnchangedJarIsKept() throws IOException assertFalse(v2.isModified()); } + @Test + public void testReextractionRewritesOnlyWhatDiffers() throws IOException + { + long now = System.currentTimeMillis(); + ModuleArchive v1 = writeArchive(now - 60_000, Map.of("same.jar", "1", "app.jar", "1", "edited.jar", "1", "sub/old.jar", "1")); + File exploded = v1.extractAll(); + File same = libJar(exploded, "same.jar"); + File edited = libJar(exploded, "edited.jar"); + File old = libJar(exploded, "sub/old.jar"); + File stray = libJar(exploded, "stray.txt"); + long sameLastModified = same.lastModified(); + Files.write(edited.toPath(), innerJar("9")); + Files.writeString(stray.toPath(), "not from the archive"); + + ModuleArchive v2 = writeArchive(now, Map.of("same.jar", "1", "app.jar", "2", "edited.jar", "1")); + v2.extractAll(); + + assertEquals("Unchanged entry was rewritten", sameLastModified, same.lastModified()); + assertEquals("2", readVersion(libJar(exploded, "app.jar"))); + assertEquals("1", readVersion(edited)); + assertFalse(old.exists()); + assertFalse(old.getParentFile().exists()); + assertFalse(stray.exists()); + assertFalse(v2.isModified()); + } + + @Test + public void testCaseOnlyRenameKeepsFile() throws IOException + { + long now = System.currentTimeMillis(); + File exploded = writeArchive(now - 60_000, Map.of("dep.jar", "1", "app.jar", "1")).extractAll(); + + ModuleArchive v2 = writeArchive(now, Map.of("Dep.jar", "1", "App.jar", "2")); + v2.extractAll(); + + assertEquals("1", readVersion(libJar(exploded, "Dep.jar"))); + assertEquals("2", readVersion(libJar(exploded, "App.jar"))); + assertFalse(v2.isModified()); + } + + @Test + public void testFileAndDirectorySwapPlaces() throws IOException + { + long now = System.currentTimeMillis(); + File exploded = writeArchive(now - 60_000, Map.of("a.jar", "1", "b/c.jar", "1")).extractAll(); + + ModuleArchive v2 = writeArchive(now, Map.of("a.jar/d.jar", "2", "b", "2")); + v2.extractAll(); + + assertEquals("2", readVersion(libJar(exploded, "a.jar/d.jar"))); + assertEquals("2", readVersion(libJar(exploded, "b"))); + assertFalse(v2.isModified()); + } + private static File libJar(File exploded, String name) { return FileUtil.appendPath(exploded, org.labkey.api.util.Path.parse("lib/" + name)); diff --git a/api/src/org/labkey/api/security/Encryption.java b/api/src/org/labkey/api/security/Encryption.java index d9edab81b09..686683bde47 100644 --- a/api/src/org/labkey/api/security/Encryption.java +++ b/api/src/org/labkey/api/security/Encryption.java @@ -595,6 +595,20 @@ static void registerHandler(EncryptionMigrationHandler handler) void deleteEncryptedContent(); } + /** A brand-new database holds no legacy-cipher content, so record the current cipher to skip that migration. */ + public static void recordCurrentCipherForNewInstall() + { + if (!isEncryptionPassPhraseSpecified() || !ModuleLoader.getInstance().shouldInsertData()) + return; + + WritablePropertyMap cipherProps = PropertyManager.getNormalStore().getWritableProperties(ENCRYPTION_CIPHER_CATEGORY, true); + if (cipherProps.get(CIPHER_PROPERTY) == null) + { + cipherProps.put(CIPHER_PROPERTY, AESConfig.current.getCipherName()); + cipherProps.save(); + } + } + /** * Examines the database to determine whether algorithm or key migration is pending, and if so installs a * fallback algorithm. This allows HTTP requests to transparently decrypt not-yet-migrated values during the diff --git a/api/src/org/labkey/api/study/security/SecurityEscalationAuditProvider.java b/api/src/org/labkey/api/study/security/SecurityEscalationAuditProvider.java index a848c9a4d38..9b5a0c4acdd 100644 --- a/api/src/org/labkey/api/study/security/SecurityEscalationAuditProvider.java +++ b/api/src/org/labkey/api/study/security/SecurityEscalationAuditProvider.java @@ -275,7 +275,8 @@ public void setStackTrace(String stackTrace) { */ public static abstract class SecurityEscalationAuditDomainKind extends AbstractAuditDomainKind { - private static Set _fields = null; + // Per instance: each subclass's property URIs must come from its own domain URI + private Set _fields = null; protected static final String NAMESPACE_PREFIX = "Audit-"; diff --git a/audit/src/org/labkey/audit/AuditLogImpl.java b/audit/src/org/labkey/audit/AuditLogImpl.java index 6a28e389bf6..59f08308565 100644 --- a/audit/src/org/labkey/audit/AuditLogImpl.java +++ b/audit/src/org/labkey/audit/AuditLogImpl.java @@ -61,6 +61,7 @@ import org.labkey.api.util.Pair; import org.labkey.api.util.StartupListener; import org.labkey.api.util.TestContext; +import org.labkey.api.util.UnexpectedException; import org.labkey.api.util.logging.LogHelper; import org.labkey.api.view.ActionURL; import org.labkey.api.view.HttpView; @@ -77,6 +78,10 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; @@ -89,6 +94,7 @@ public class AuditLogImpl implements AuditLogService, StartupListener private final Queue> _eventTypeQueue = new LinkedList<>(); private final AtomicBoolean _logToDatabase = new AtomicBoolean(false); private static final Object STARTUP_LOCK = new Object(); + private static final int PROVIDER_INIT_THREADS = 8; // Cache the audit events associated with transaction ids. We currently use these for interacting with objects // that were created immediately after they were created, so the cache size does not need to be very large and the defaultTimeToLive can be small. @@ -120,11 +126,7 @@ public String getName() @Override public void moduleStartupComplete(ServletContext servletContext) { - // perform audit provider initialization - for (AuditTypeProvider provider : AuditLogService.get().getAuditProviders()) - { - provider.initializeProvider(User.getAdminServiceUser()); - } + initializeProviders(AuditLogService.get().getAuditProviders(), User.getAdminServiceUser()); // Synchronize so that we can guarantee that all events have already been added to the queue before we // start processing them @@ -140,6 +142,31 @@ public void moduleStartupComplete(ServletContext servletContext) } } + // Each provider touches only its own domain and storage table, in its own transaction, and mostly waits on the database + private static void initializeProviders(List providers, User user) + { + int threads = Math.clamp(providers.size(), 1, PROVIDER_INIT_THREADS); + + try (ExecutorService pool = Executors.newFixedThreadPool(threads, Thread.ofPlatform().name("Audit Provider Init ", 1).factory())) + { + List> futures = providers.stream() + .>map(provider -> pool.submit(() -> provider.initializeProvider(user))) + .toList(); + + for (Future future : futures) + future.get(); + } + catch (ExecutionException e) + { + UnexpectedException.rethrow(e.getCause()); + } + catch (InterruptedException e) + { + Thread.currentThread().interrupt(); + throw UnexpectedException.wrap(e); + } + } + @Override public boolean isViewable() { diff --git a/core/api-src/org/labkey/api/admin/TableXmlUtils.java b/core/api-src/org/labkey/api/admin/TableXmlUtils.java index 6cce2cec998..ef900b2e4b9 100644 --- a/core/api-src/org/labkey/api/admin/TableXmlUtils.java +++ b/core/api-src/org/labkey/api/admin/TableXmlUtils.java @@ -17,17 +17,26 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.junit.Assert; +import org.junit.Test; import org.labkey.api.admin.sitevalidation.SiteValidationResult; import org.labkey.api.admin.sitevalidation.SiteValidationResultList; +import org.labkey.api.collections.CaseInsensitiveHashSet; +import org.labkey.api.data.DatabaseTableType; import org.labkey.api.data.DbSchema; import org.labkey.api.data.DbSchemaType; import org.labkey.api.data.DbScope; +import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SchemaTableInfo; +import org.labkey.api.data.SqlExecutor; import org.labkey.data.xml.ColumnType; import org.labkey.data.xml.TableType; import org.labkey.data.xml.TablesDocument; import org.labkey.data.xml.TablesType; +import java.util.Arrays; +import java.util.List; +import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; @@ -35,6 +44,9 @@ public class TableXmlUtils { private static final Logger _log = LogManager.getLogger(TableXmlUtils.class); + // schema.xml-only tableDbType for objects whose type differs between databases; no DatabaseTableType counterpart + private static final String UNKNOWN_TABLE_TYPE = "UNKNOWN"; + // Careful: don't use DbSchema.get(), schema.getTable(), or schema.getTables() -- we don't want schema.xml applied // and we don't want to cache these TableInfos (because schema.xml hasn't been applied). public static TablesDocument createXmlDocumentFromDatabaseMetaData(DbScope scope, String schemaName, boolean bFull) throws Exception @@ -73,6 +85,41 @@ public void setViewProblem(boolean viewProblem) } } + /** Same answer as {@code compareXmlToMetaData(...).hasViewProblem()}, but reads only table names, not per-table metadata */ + public static boolean hasMissingView(DbSchema schema) + { + try + { + TablesDocument tablesDocFromXml = DbScope.getSchemaXml(schema); + if (null == tablesDocFromXml) + return false; + + Set dbTableNames = new CaseInsensitiveHashSet(DbSchema.createFromMetaData(schema.getScope(), schema.getName(), DbSchemaType.Bare).getTableNames()); + + return getXmlTablesMissingFromDb(tablesDocFromXml.getTables().getTableArray(), dbTableNames).stream() + .anyMatch(TableXmlUtils::isView); + } + catch (Exception e) + { + _log.error("Exception loading schema {}", schema.getDisplayName(), e); + return false; + } + } + + /** XML tables expected in the database but absent from it; UNKNOWN and NOT_IN_DB tables are never expected */ + private static List getXmlTablesMissingFromDb(TableType[] xmlTables, Set dbTableNames) + { + return Arrays.stream(xmlTables) + .filter(xmlTable -> !dbTableNames.contains(xmlTable.getTableName())) + .filter(xmlTable -> !UNKNOWN_TABLE_TYPE.equals(xmlTable.getTableDbType()) && !DatabaseTableType.NOT_IN_DB.name().equals(xmlTable.getTableDbType())) + .toList(); + } + + private static boolean isView(TableType xmlTable) + { + return DatabaseTableType.VIEW.name().equals(xmlTable.getTableDbType()); + } + public static SchemaValidationList compareXmlToMetaData(DbSchema schema, boolean bFull, boolean bCaseSensitive, boolean errorOnXmlMiss) { SchemaValidationList resultList = new SchemaValidationList(); @@ -105,7 +152,6 @@ private static void compareTableDocuments(TablesDocument dbTablesDoc, TableType[] dbTables; TableType[] xmlTables; String xmlTableName; - String xmlTableType; String dbTableName; String dbColName; String xmlColName; @@ -140,28 +186,19 @@ private static void compareTableDocuments(TablesDocument dbTablesDoc, mDbTableOrdinals.put(dbTableName.toLowerCase(), i); } + for (TableType missingTable : getXmlTablesMissingFromDb(xmlTables, new CaseInsensitiveHashSet(mDbTableOrdinals.keySet()))) + { + if (isView(missingTable)) + rlOut.setViewProblem(true); + rlOut.addError("ERROR: TableName \"").append(missingTable.getTableName()).append("\" type \"").append(missingTable.getTableDbType()).append("\" found in XML but not in database."); + } + for (TableType xmlTable : xmlTables) { xmlTableName = xmlTable.getTableName(); - xmlTableType = xmlTable.getTableDbType(); if (!(mDbTableOrdinals.containsKey(xmlTableName.toLowerCase()))) - { - if (xmlTableType.equals("UNKNOWN")) - { - continue; - } - - if (!xmlTableType.equals("NOT_IN_DB")) - { - if ("VIEW".equalsIgnoreCase(xmlTableType)) - { - rlOut.setViewProblem(true); - } - rlOut.addError("ERROR: TableName \"").append(xmlTableName).append("\" type \"").append(xmlTableType).append("\" found in XML but not in database."); - } continue; - } idt = mDbTableOrdinals.get(xmlTableName.toLowerCase()); @@ -169,7 +206,7 @@ private static void compareTableDocuments(TablesDocument dbTablesDoc, compareStringProperty(tt.getTableName(), xmlTable.getTableName(), "TableName", rlOut, bCaseSensitive, schema.getName() + "." + tt.getTableName(), true); // Special value "UNKNOWN" means the type is different on different databases, e.g., some of the tables/views/synonyms in the test schema - if (!"UNKNOWN".equals(xmlTable.getTableDbType())) + if (!UNKNOWN_TABLE_TYPE.equals(xmlTable.getTableDbType())) compareStringProperty(tt.getTableDbType(), xmlTable.getTableDbType(), "TableDbType", rlOut, true, schema.getName() + "." + tt.getTableName(), true); if (bFull) @@ -491,4 +528,38 @@ private static boolean compareBoolProperty(Boolean refProp, Boolean targetProp, rlOut.addWarn("WARNING: property ").append(propName).append(" value '").append(refProp).append("' doesn't match XML value '").append(targetProp).append("' for ").append(problematicItem).append("."); return true; } + + public static class TestCase extends Assert + { + @Test + public void testHasMissingView() + { + List schemasWithViews = DbSchema.getAllSchemasToTest().stream() + .filter(schema -> !getXmlViewNames(schema).isEmpty()) + .toList(); + assertFalse("No schema declares a view", schemasWithViews.isEmpty()); + + for (DbSchema schema : schemasWithViews) + assertFalse(schema.getName(), hasMissingView(schema)); + + // Drop a view on a connection whose transaction is never committed + DbSchema schema = schemasWithViews.getFirst(); + String viewName = getXmlViewNames(schema).getFirst(); + try (DbScope.Transaction ignored = schema.getScope().ensureTransaction()) + { + new SqlExecutor(schema.getScope()).execute(SQLFragment.unsafe("DROP VIEW ").append(schema.getTable(viewName)).append(SQLFragment.unsafe(" CASCADE"))); + assertTrue(schema.getName() + "." + viewName, compareXmlToMetaData(schema, false, false, true).hasViewProblem()); + assertTrue(schema.getName() + "." + viewName, hasMissingView(schema)); + } + } + + private static List getXmlViewNames(DbSchema schema) + { + TablesDocument tablesDoc = DbScope.getSchemaXml(schema); + return null == tablesDoc ? List.of() : Arrays.stream(tablesDoc.getTables().getTableArray()) + .filter(TableXmlUtils::isView) + .map(TableType::getTableName) + .toList(); + } + } } diff --git a/core/src/org/labkey/core/CoreModule.java b/core/src/org/labkey/core/CoreModule.java index 61e4e135774..aa76a785190 100644 --- a/core/src/org/labkey/core/CoreModule.java +++ b/core/src/org/labkey/core/CoreModule.java @@ -909,6 +909,7 @@ public void afterUpdate(ModuleContext moduleContext) if (moduleContext.isNewInstall()) { bootstrap(); + Encryption.recordCurrentCipherForNewInstall(); } // Increment on every core module upgrade to defeat browser caching of static resources. @@ -1028,7 +1029,9 @@ public void startupAfterSpringConfig(ModuleContext moduleContext) // Any containers in the cache have bogus folder types since they aren't registered until startup(). See #10310 ContainerManager.clearCache(); - checkForMissingDbViews(); + // Bootstrap scripts just created the views + if (!moduleContext.isNewInstall()) + checkForMissingDbViews(); ((SecretServiceImpl)SecretService.get()).handleStartupProperties(); ProductConfiguration.handleStartupProperties(); @@ -1384,7 +1387,7 @@ private void checkForMissingDbViews() .flatMap(p -> p.getSchemas().stream() .filter(schema-> SchemaUpdateType.Before.getScript(p, schema) != null || SchemaUpdateType.After.getScript(p, schema) != null) ) - .filter(schema -> TableXmlUtils.compareXmlToMetaData(schema, false, false, true).hasViewProblem()) + .filter(TableXmlUtils::hasMissingView) .findAny() .ifPresent(schema -> { @@ -1557,6 +1560,7 @@ public TabDisplayMode getTabDisplayMode() SqlDialect.LabKeyScopeDialectTestCase.class, SqlScriptController.TestCase.class, TableViewFormTestCase.class, + TableXmlUtils.TestCase.class, UnknownSchemasTest.class, UserController.TestCase.class, ReportsTable.TestCase.class diff --git a/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java b/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java index 7e7084fbb12..88bee6840af 100644 --- a/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java +++ b/core/src/org/labkey/core/dialect/PostgreSql92Dialect.java @@ -27,6 +27,7 @@ import org.labkey.api.data.DbSchemaType; import org.labkey.api.data.DbScope; import org.labkey.api.data.InClauseGenerator; +import org.labkey.api.data.JdbcMetaDataSelector; import org.labkey.api.data.JdbcType; import org.labkey.api.data.ParameterMarkerInClauseGenerator; import org.labkey.api.data.PropertyStorageSpec; @@ -44,6 +45,7 @@ import org.labkey.api.data.dialect.ColumnMetaDataReader; import org.labkey.api.data.dialect.DialectStringHandler; import org.labkey.api.data.dialect.JdbcHelper; +import org.labkey.api.data.dialect.JdbcMetaDataLocator; import org.labkey.api.data.dialect.SqlDialect; import org.labkey.api.data.dialect.StandardJdbcHelper; import org.labkey.api.exp.PropertyType; @@ -59,6 +61,7 @@ import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.Driver; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; @@ -225,6 +228,43 @@ private int getDomainScale(String domainName) throws SQLException }; } + // pgjdbc's getImportedKeys() plans a nine-relation join per call (~4ms); this returns the same rows in ~0.3ms + // Don't look the table up with to_regclass(): it throws when the role lacks USAGE on the schema + private static final String IMPORTED_KEYS_SQL = """ + SELECT + (SELECT n.nspname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = con.confrelid) AS "PKTABLE_SCHEM", + (SELECT c.relname FROM pg_catalog.pg_class c WHERE c.oid = con.confrelid) AS "PKTABLE_NAME", + (SELECT a.attname FROM pg_catalog.pg_attribute a WHERE a.attrelid = con.confrelid AND a.attnum = k.pkattnum) AS "PKCOLUMN_NAME", + (SELECT a.attname FROM pg_catalog.pg_attribute a WHERE a.attrelid = con.conrelid AND a.attnum = k.fkattnum) AS "FKCOLUMN_NAME", + k.n AS "KEY_SEQ", + con.conname AS "FK_NAME" + FROM pg_catalog.pg_constraint con + JOIN pg_catalog.pg_class t ON t.oid = con.conrelid + JOIN pg_catalog.pg_namespace tn ON tn.oid = t.relnamespace + CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(con.conkey), pg_catalog.unnest(con.confkey)) WITH ORDINALITY AS k(fkattnum, pkattnum, n) + WHERE con.contype = 'f' AND tn.nspname = ? AND t.relname = ? + ORDER BY 1, 2, 6, 5"""; + + @Override + public JdbcMetaDataSelector getImportedKeysSelector(JdbcMetaDataLocator locator) + { + return new JdbcMetaDataSelector(locator, (dbmd, l) -> { + PreparedStatement stmt = dbmd.getConnection().prepareStatement(IMPORTED_KEYS_SQL); + try + { + stmt.setString(1, l.getSchemaName()); + stmt.setString(2, l.getTableName()); + stmt.closeOnCompletion(); + return stmt.executeQuery(); + } + catch (SQLException e) + { + stmt.close(); + throw e; + } + }); + } + @Override public void handleCreateDatabaseException(SQLException e) throws ServletException {