From a2ea7ce19148c9df668f8c8c126de6c3f6b5a67d Mon Sep 17 00:00:00 2001 From: CorrectRoadH Date: Wed, 24 May 2023 23:52:27 +0800 Subject: [PATCH] fix: cannot connect non SSL PostgreSQL (#109) --- src/lib/connectors/postgres/index.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/lib/connectors/postgres/index.ts b/src/lib/connectors/postgres/index.ts index 692b838..66e9aee 100644 --- a/src/lib/connectors/postgres/index.ts +++ b/src/lib/connectors/postgres/index.ts @@ -23,14 +23,30 @@ const newPostgresClient = async (connection: Connection) => { key: connection.ssl?.key, }; } else { - // rejectUnauthorized=false to infer sslmode=prefer since hosted PG venders have SSL enabled. clientConfig.ssl = { rejectUnauthorized: false, }; } let client = new Client(clientConfig); - await client.connect(); + + if (connection.ssl) { + await client.connect(); + } else { + try { + await client.connect(); + } catch (error) { + // Because node-postgres didn't implement `sslmode: preferred`. So first try to connect via SSL, otherwise connect via non-SSL. + // Connecting postgres via non-ssl requires `clientConfig.ssl` is undefined. ref: https://github.com/sqlchat/sqlchat/issues/108 + if (error instanceof Error && error.message.includes("The server does not support SSL connections")) { + clientConfig.ssl = undefined; + client = new Client(clientConfig); + await client.connect(); + } else { + throw error; + } + } + } return client; };