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; };