2222import org .apache .commons .lang .ArrayUtils ;
2323import org .apache .commons .logging .Log ;
2424import org .apache .commons .logging .LogFactory ;
25+ import org .apache .tomcat .jdbc .pool .DataSourceProxy ;
2526import org .wso2 .carbon .CarbonConstants ;
2627import org .wso2 .carbon .base .ServerConfiguration ;
2728import org .wso2 .carbon .user .api .RealmConfiguration ;
5354import java .util .HashMap ;
5455import java .util .List ;
5556import java .util .Map ;
57+ import java .util .Properties ;
5658import java .util .UUID ;
5759
5860import static org .wso2 .carbon .user .core .constants .UserCoreDBConstants .CASE_INSENSITIVE_SQL_STATEMENT_PARAMETER_PLACEHOLDER ;
@@ -79,6 +81,8 @@ public class HybridRoleManager {
7981 private static final String CASE_INSENSITIVE_USERNAME = "CaseInsensitiveUsername" ;
8082
8183 private static final String DB2 = "db2" ;
84+ private static final String POSTGRE_SQL = "PostgreSQL" ;
85+ private static final String POSTGRES_SCHEMA = "postgresSchema" ;
8286
8387 private static boolean hybridRoleAudienceTableExists = false ;
8488
@@ -1533,6 +1537,15 @@ private boolean isTableExists(String tableName) {
15331537 }
15341538 String schemaName = connection .getSchema ();
15351539 String catalogName = connection .getCatalog ();
1540+
1541+ // For PostgreSQL, use the configured schema if available. This handles cases where tables reside in a
1542+ // non-default schema that differs from the first entry in the database user's search path.
1543+ if (POSTGRE_SQL .equalsIgnoreCase (connection .getMetaData ().getDatabaseProductName ())) {
1544+ String postgresSchema = getPostgresSchema ();
1545+ if (org .apache .commons .lang .StringUtils .isNotBlank (postgresSchema )) {
1546+ schemaName = postgresSchema .trim ();
1547+ }
1548+ }
15361549 try (ResultSet resultSet = metaData .getTables (catalogName , schemaName , tableName , new String []{"TABLE" })) {
15371550 if (resultSet .next ()) {
15381551 return true ;
@@ -1545,4 +1558,17 @@ private boolean isTableExists(String tableName) {
15451558 }
15461559 return false ;
15471560 }
1561+
1562+ private String getPostgresSchema () {
1563+
1564+ String customSchema = null ;
1565+ if (!(dataSource instanceof DataSourceProxy )) {
1566+ return null ;
1567+ }
1568+ Properties properties = ((DataSourceProxy ) dataSource ).getDbProperties ();
1569+ if (properties != null ) {
1570+ customSchema = properties .getProperty (POSTGRES_SCHEMA );
1571+ }
1572+ return customSchema ;
1573+ }
15481574}
0 commit comments