| 22 | | PostgresOptionsWithURI; |
| 23 | |
| 24 | export class PostgresConnector implements Connector { |
| 25 | _dialect: SupportedSQLDatabaseDialect = "postgres"; |
| 26 | |
| 27 | _client: PostgresClient; |
| 28 | _options: PostgresOptions; |
| 29 | _translator: SQLTranslator; |
| 30 | _connected = false; |
| 31 | |
| 32 | /** Create a PostgreSQL connection. */ |
| 33 | constructor(options: PostgresOptions) { |
| 34 | this._options = options; |
| 35 | if ("uri" in options) { |
| 36 | this._client = new PostgresClient(options.uri); |
| 37 | } else { |
| 38 | this._client = new PostgresClient({ |
| 39 | hostname: options.host, |
| 40 | user: options.username, |
| 41 | password: options.password, |
| 42 | database: options.database, |
| 43 | port: options.port ?? 5432, |
| 44 | }); |
| 45 | } |
| 46 | this._translator = new SQLTranslator(this._dialect); |
| 47 | } |
| 48 | |
| 49 | async _makeConnection() { |
| 50 | if (this._connected) { |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | await this._client.connect(); |
| 55 | this._connected = true; |
| 56 | } |
| 57 | |
| 58 | async ping() { |
| 59 | await this._makeConnection(); |
| 60 | |
| 61 | try { |
| 62 | const [result] = ( |
| 63 | await this._client.queryObject("SELECT 1 + 1 as result") |
| 64 | ).rows; |
| 65 | return result === 2; |
| 66 | } catch { |
| 67 | return false; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // deno-lint-ignore no-explicit-any |
| 72 | async query(queryDescription: QueryDescription): Promise<any | any[]> { |
| 73 | await this._makeConnection(); |
| 74 | |
| 75 | const query = this._translator.translateToQuery(queryDescription); |
| 76 | const response = await this._client.queryObject(query); |
| 77 | const results = response.rows as Values[]; |
| 78 | |
| 79 | if (queryDescription.type === "insert") { |
| 80 | return results.length === 1 ? results[0] : results; |
| 81 | } |
nothing calls this directly
no outgoing calls
no test coverage detected