| 4 | import { reportError } from "../services/initialization-error-service"; |
| 5 | |
| 6 | export class PostgresEngine implements DatabaseEngine { |
| 7 | public connection: knexlib.Knex | null = null; |
| 8 | |
| 9 | constructor(connector: knexlib.Knex) { |
| 10 | this.connection = connector; |
| 11 | } |
| 12 | |
| 13 | getType(): KnexClient { |
| 14 | return 'postgres'; |
| 15 | } |
| 16 | |
| 17 | getConnection(): knexlib.Knex | null { |
| 18 | return this.connection |
| 19 | } |
| 20 | |
| 21 | async isOkay(): Promise<boolean> { |
| 22 | if (!this.connection) return false; |
| 23 | |
| 24 | try { |
| 25 | await this.connection.raw('SELECT VERSION()'); |
| 26 | return true; |
| 27 | } catch (error) { |
| 28 | reportError(`PostgreSQL OK-check error: ${error}`); |
| 29 | return false; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | async disconnect(): Promise<void> { |
| 34 | if (this.connection) this.connection.destroy(() => null); |
| 35 | } |
| 36 | |
| 37 | async getTableCreationSql(table: string): Promise<string> { |
| 38 | if (!this.connection) { |
| 39 | throw new Error('Not connected to the database'); |
| 40 | } |
| 41 | |
| 42 | const { schemaName, tableName } = getTableSchema(table); |
| 43 | |
| 44 | const tableCreationSql = await this.connection.raw(` |
| 45 | SELECT |
| 46 | 'CREATE TABLE ' || quote_ident(table_schema) || '.' || quote_ident(table_name) || ' (' || |
| 47 | string_agg(column_name || ' ' || |
| 48 | CASE |
| 49 | WHEN data_type = 'character varying' THEN |
| 50 | 'character varying(' || character_maximum_length || ')' |
| 51 | ELSE |
| 52 | data_type |
| 53 | END, ', ' ORDER BY ordinal_position) || |
| 54 | ');' AS create_sql |
| 55 | FROM |
| 56 | information_schema.columns |
| 57 | WHERE |
| 58 | table_name = ? AND table_schema = ? |
| 59 | GROUP BY |
| 60 | table_name, table_schema |
| 61 | `, [tableName, schemaName]) as any; |
| 62 | |
| 63 | const sql = tableCreationSql.rows[0]?.create_sql || ''; |
nothing calls this directly
no outgoing calls
no test coverage detected