| 1 | import type { DbEngineAdapter, DbHostConn } from "./index"; |
| 2 | |
| 3 | function quoteIdent(name: |
| 4 | return `"${name |
| 5 | } |
| 6 | |
| 7 | // Postgres DDL (CREATE/ALTER ROLE) doesn't accept bind parameters ($1) for the |
| 8 | // password literal, so it must be inlined as an escaped string literal instead. |
| 9 | function quoteLiteral(value: |
| 10 | return `'${value |
| 11 | } |
| 12 | |
| 13 | function clientConfig(conn: |
| 14 | return { |
| 15 | host: conn.host |
| 16 | port: conn.port |
| 17 | user: conn.username |
| 18 | password: conn.password |
| 19 | database: "postgres", |
| 20 | // Mirrors libpq's sslmode=require: encrypt the connection, don't validate the |
| 21 | // server certificate (operator-managed hosts commonly use self-signed certs). |
| 22 | ssl: conn.ssl |
| 23 | }; |
| 24 | } |
| 25 | |
| 26 | export const postgresqlAdapter: |
| 27 | defaultPort: 5432, |
| 28 | |
| 29 | async testConnection(conn |
| 30 | try { |
| 31 | const { Client |
| 32 | const client = |
| 33 | await client.connect |
| 34 | await client.query |
| 35 | await client.end |
| 36 | return { ok: |
| 37 | } catch (err) |
| 38 | return { ok: |
| 39 | } |
| 40 | }, |
| 41 | |
| 42 | async createDatabase(conn |
| 43 | const { Client |
| 44 | const client = |
| 45 | await client.connect |
| 46 | try { |
| 47 | await client.query |
| 48 | `CREATE ROLE ${quoteIdent(opts |
| 49 | ); |
| 50 | await client.query |
| 51 | `CREATE DATABASE ${quoteIdent(opts |
| 52 | ); |
| 53 | await client.query |
| 54 | `GRANT ALL PRIVILEGES ON DATABASE ${quoteIdent(opts |
| 55 | ); |
| 56 | } finally { |
| 57 | await client.end |
| 58 | } |
| 59 | }, |
| 60 | |
| 61 | async rotatePassword(conn |
| 62 | const { Client |
| 63 | const client = |
| 64 | await client.connect |
| 65 | try { |
| 66 | await client.query |
| 67 | `ALTER ROLE ${quoteIdent(opts |
| 68 | ); |
| 69 | } finally { |
| 70 | await client.end |
| 71 | } |
| 72 | }, |
| 73 | |
| 74 | async dropDatabase(conn |
| 75 | const { Client |
| 76 | const client = |
| 77 | await client.connect |
| 78 | try { |
| 79 | await client.query |
| 80 | await client.query |
| 81 | } finally { |
| 82 | await client.end |
| 83 | } |
| 84 | }, |
| 85 | |
| 86 | formatConnectionString(opts) { |
| 87 | return `postgresql://${encodeURIComponent |
| 88 | }, |
| 89 | }; |