| 22 | } |
| 23 | |
| 24 | export default class CockroachDB implements SchemaInspector { |
| 25 | knex: Knex; |
| 26 | schema: string; |
| 27 | protected explodedSchema: string[]; |
| 28 | protected databaseName: string | undefined; |
| 29 | |
| 30 | constructor(knex: Knex) { |
| 31 | this.knex = knex; |
| 32 | const config = knex.client.config; |
| 33 | |
| 34 | if (!config.searchPath) { |
| 35 | this.schema = 'public'; |
| 36 | this.explodedSchema = [this.schema]; |
| 37 | } else if (typeof config.searchPath === 'string') { |
| 38 | this.schema = config.searchPath; |
| 39 | this.explodedSchema = [config.searchPath]; |
| 40 | } else { |
| 41 | this.schema = config.searchPath[0]; |
| 42 | this.explodedSchema = config.searchPath; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // CockroachDB specific |
| 47 | // =============================================================================================== |
| 48 | |
| 49 | private async getDatabaseName(): Promise<string> { |
| 50 | // dont query the database multiple times if we need the db name multiple times |
| 51 | if (!this.databaseName) { |
| 52 | const result = await this.knex.raw<{ rows: { db: string }[] }>(`SELECT current_database() AS db`); |
| 53 | this.databaseName = result.rows[0]!.db; |
| 54 | } |
| 55 | |
| 56 | return this.databaseName; |
| 57 | } |
| 58 | |
| 59 | private async resolveTableSchema(table: string): Promise<string> { |
| 60 | const row = await this.knex |
| 61 | .select<{ table_schema: string }>('table_schema') |
| 62 | .from('information_schema.tables') |
| 63 | .whereIn('table_schema', this.explodedSchema) |
| 64 | .andWhere({ table_name: table, table_type: 'BASE TABLE' }) |
| 65 | .first(); |
| 66 | |
| 67 | return row?.table_schema ?? this.explodedSchema[0]!; |
| 68 | } |
| 69 | |
| 70 | private sanitizeIdentifier(schema: string, name: string): string { |
| 71 | const wrappedSchema = this.knex.client.wrapIdentifier(schema); |
| 72 | const wrapperName = this.knex.client.wrapIdentifier(name); |
| 73 | return `${wrappedSchema}.${wrapperName}`; |
| 74 | } |
| 75 | |
| 76 | /** |
| 77 | * Set the schema to be used in other methods |
| 78 | */ |
| 79 | withSchema(schema: string): this { |
| 80 | this.schema = schema; |
| 81 | this.explodedSchema = [this.schema]; |
nothing calls this directly
no outgoing calls
no test coverage detected