Skip to content

Commit

Permalink
Merge pull request #3009 from liquibase/pg-searchpath-parsing
Browse files Browse the repository at this point in the history
Ensure Postgresql search_path entries are quoted correctly
  • Loading branch information
nvoxland committed Jul 12, 2022
2 parents 13fea61 + c26ae49 commit 3bf2706
Showing 1 changed file with 17 additions and 4 deletions.
@@ -1,5 +1,6 @@
package liquibase.database.core;

import liquibase.GlobalConfiguration;
import liquibase.Scope;
import liquibase.database.Database;
import liquibase.database.OfflineConnection;
Expand All @@ -8,6 +9,7 @@
import liquibase.executor.ExecutorService;
import liquibase.statement.core.RawSqlStatement;
import liquibase.structure.core.Schema;
import liquibase.util.StringUtil;

public class DatabaseUtils {
/**
Expand Down Expand Up @@ -39,11 +41,22 @@ public static void initializeDatabase(String defaultCatalogName, String defaultS
String searchPath = executor.queryForObject(new RawSqlStatement("SHOW SEARCH_PATH"), String.class);

if (!searchPath.equals(defaultCatalogName) && !searchPath.startsWith(defaultSchemaName + ",") && !searchPath.startsWith("\"" + defaultSchemaName + "\",")) {
if (database instanceof CockroachDatabase) {
// CockroachDB doesn't support unquoted `$user` type values
searchPath = searchPath.replaceAll("(\\$\\w+)", "'$1'");
String finalSearchPath;
if (GlobalConfiguration.PRESERVE_SCHEMA_CASE.getCurrentValue()) {
finalSearchPath = ((PostgresDatabase) database).quoteObject(defaultSchemaName, Schema.class);
} else {
finalSearchPath = defaultSchemaName;
}
executor.execute(new RawSqlStatement("SET SEARCH_PATH TO " + database.escapeObjectName(defaultSchemaName, Schema.class) + ", " + searchPath));

//If existing search path entries are not quoted, quote them. Some databases do not show them as quoted even though they need to be (like $user or case sensitive schemas)
finalSearchPath += ", " + StringUtil.join(StringUtil.splitAndTrim(searchPath, ","), ",", (StringUtil.StringUtilFormatter<String>) obj -> {
if (obj.startsWith("\"")) {
return obj;
}
return ((PostgresDatabase) database).quoteObject(obj, Schema.class);
});

executor.execute(new RawSqlStatement("SET SEARCH_PATH TO " + finalSearchPath));
}

} else if (database instanceof AbstractDb2Database) {
Expand Down

0 comments on commit 3bf2706

Please sign in to comment.