package liquibase.ext;

import com.atlassian.stash.internal.backup.DatabaseTable;
import liquibase.database.core.PostgresDatabase;

/**
 * An extension of {@link PostgresDatabase} that overrides the algorithm for determining whether a table is a
 * system table.
 */
public class CustomPostgresDatabase extends PostgresDatabase {
    /**
     * This implementation ensures that instances of this class will be used
     * instead of instances of the {@link PostgresDatabase} parent class.
     */
    @Override
    public int getPriority() {
        return super.getPriority() + 1;
    }

    /**
     * This implementation applies two additional rules to the normal system table algorithm:
     * <ul>
     * <li>Tables listed in as {@link DatabaseTable application tables} are not system tables; and</li>
     * <li>Tables belonging to ActiveObjects are system tables. This rule is necessary because PostgreSQL automatically
     * lower-cases all table names and column names in SQL statements it is asked to execute, and ActiveObjects has
     * upper-case table names and column names. It's a horrible kludge really, but better than the mess we got
     * ourselves into by overriding the {@link #escapeDatabaseObject(String)} method.</li>
     * </ul>
     */
    @Override
    public boolean isSystemTable(String catalogName, String schemaName, String tableName) {
        return !DatabaseTable.isKnownTable(tableName) &&
               (isActiveObjectsTable(tableName) || super.isSystemTable(catalogName, schemaName, tableName));
    }

    protected boolean isActiveObjectsTable(String tableName) {
        return tableName.startsWith("AO_");
    }
}
