Skip to content

Commit

Permalink
fix: added version check before dropping materialized views to keep b…
Browse files Browse the repository at this point in the history
…ackward compatibility (#7716)
  • Loading branch information
AlexMesser committed Jul 24, 2021
1 parent aed26f5 commit 29f1f86
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/driver/postgres/PostgresQueryRunner.ts
Expand Up @@ -23,6 +23,7 @@ import {IsolationLevel} from "../types/IsolationLevel";
import {PostgresDriver} from "./PostgresDriver";
import {ReplicationMode} from "../types/ReplicationMode";
import {BroadcasterResult} from "../../subscriber/BroadcasterResult";
import {VersionUtils} from "../../util/VersionUtils";
import { TypeORMError } from "../../error";
import { QueryResult } from "../../query-runner/QueryResult";

Expand Down Expand Up @@ -1449,17 +1450,21 @@ export class PostgresQueryRunner extends BaseQueryRunner implements QueryRunner

await this.startTransaction();
try {
const version = await this.getVersion()
// drop views
const selectViewDropsQuery = `SELECT 'DROP VIEW IF EXISTS "' || schemaname || '"."' || viewname || '" CASCADE;' as "query" ` +
`FROM "pg_views" WHERE "schemaname" IN (${schemaNamesString}) AND "viewname" NOT IN ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews')`;
const dropViewQueries: ObjectLiteral[] = await this.query(selectViewDropsQuery);
await Promise.all(dropViewQueries.map(q => this.query(q["query"])));

// drop materialized views
const selectMatViewDropsQuery = `SELECT 'DROP MATERIALIZED VIEW IF EXISTS "' || schemaname || '"."' || matviewname || '" CASCADE;' as "query" ` +
`FROM "pg_matviews" WHERE "schemaname" IN (${schemaNamesString})`;
const dropMatViewQueries: ObjectLiteral[] = await this.query(selectMatViewDropsQuery);
await Promise.all(dropMatViewQueries.map(q => this.query(q["query"])));
// Note: materialized views introduced in Postgres 9.3
if (VersionUtils.isGreaterOrEqual(version, "9.3")) {
const selectMatViewDropsQuery = `SELECT 'DROP MATERIALIZED VIEW IF EXISTS "' || schemaname || '"."' || matviewname || '" CASCADE;' as "query" ` +
`FROM "pg_matviews" WHERE "schemaname" IN (${schemaNamesString})`;
const dropMatViewQueries: ObjectLiteral[] = await this.query(selectMatViewDropsQuery);
await Promise.all(dropMatViewQueries.map(q => this.query(q["query"])));
}

// ignore spatial_ref_sys; it's a special table supporting PostGIS
// TODO generalize this as this.driver.ignoreTables
Expand Down Expand Up @@ -2006,6 +2011,14 @@ export class PostgresQueryRunner extends BaseQueryRunner implements QueryRunner
return new Query(sql);
}

/**
* Loads Postgres version.
*/
protected async getVersion(): Promise<string> {
const result = await this.query(`SHOW SERVER_VERSION`);
return result[0]["server_version"];
}

/**
* Builds drop table sql.
*/
Expand Down

0 comments on commit 29f1f86

Please sign in to comment.