From 2d371d60f806094164758788edac587e94dccfc6 Mon Sep 17 00:00:00 2001 From: Dhanushka <128372449+data-envoy@users.noreply.github.com> Date: Sat, 1 Apr 2023 12:32:03 +0100 Subject: [PATCH] Add a schemaExists check The schemaExists check doesn't need `CREATE ON DATABASE` permissions. So it avoids throwing an error in case where both: - The schema already exists - The user doesn't have `CREATE ON DATABASE` permission --- .../src/lib/db/sql-client/lib/pg/PgClient.ts | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/packages/nocodb/src/lib/db/sql-client/lib/pg/PgClient.ts b/packages/nocodb/src/lib/db/sql-client/lib/pg/PgClient.ts index aa26cbe8d8..d4cd492d2c 100644 --- a/packages/nocodb/src/lib/db/sql-client/lib/pg/PgClient.ts +++ b/packages/nocodb/src/lib/db/sql-client/lib/pg/PgClient.ts @@ -474,17 +474,22 @@ class PGClient extends KnexClient { ]); } - // if (this.connectionConfig.searchPath && this.connectionConfig.searchPath[0]) { - await this.sqlClient.raw( - ` CREATE SCHEMA IF NOT EXISTS ?? AUTHORIZATION ?? `, - [ - (this.connectionConfig.searchPath && - this.connectionConfig.searchPath[0]) || - 'public', - this.connectionConfig.connection.user, - ] - ); - // } + const schemaName = this.connectionConfig.searchPath?.[0] || 'public' + + // Check schemaExists because `CREATE SCHEMA IF NOT EXISTS` requires permissions of `CREATE ON DATABASE` + const schemaExists = !!( + await this.sqlClient.raw( + `SELECT schema_name FROM information_schema.schemata WHERE schema_name = ?`, + [schemaName] + ) + ).rows?.[0]; + + if(!schemaExists) { + await this.sqlClient.raw( + `CREATE SCHEMA IF NOT EXISTS ?? AUTHORIZATION ?? `, + [schemaName, this.connectionConfig.connection.user] + ); + } // this.sqlClient = knex(this.connectionConfig); } catch (e) {