| 26 | } |
| 27 | |
| 28 | export default class SQLite implements SchemaInspector { |
| 29 | knex: Knex; |
| 30 | |
| 31 | constructor(knex: Knex) { |
| 32 | this.knex = knex; |
| 33 | } |
| 34 | |
| 35 | // Overview |
| 36 | // =============================================================================================== |
| 37 | |
| 38 | async overview(): Promise<SchemaOverview> { |
| 39 | const tablesWithAutoIncrementPrimaryKeys = ( |
| 40 | await this.knex.select('name').from('sqlite_master').whereRaw(`sql LIKE "%AUTOINCREMENT%"`) |
| 41 | ).map(({ name }) => name); |
| 42 | |
| 43 | const tables = await this.tables(); |
| 44 | const overview: SchemaOverview = {}; |
| 45 | |
| 46 | for (const table of tables) { |
| 47 | const columns = await this.knex.raw<RawColumn[]>(`PRAGMA table_xinfo(??)`, table); |
| 48 | |
| 49 | if (table in overview === false) { |
| 50 | const primaryKeys = columns.filter((column) => column.pk !== 0); |
| 51 | |
| 52 | overview[table] = { |
| 53 | primary: primaryKeys.length !== 1 ? (undefined as any) : primaryKeys[0]!.name!, |
| 54 | columns: {}, |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | for (const column of columns) { |
| 59 | overview[table]!.columns[column.name] = { |
| 60 | table_name: table, |
| 61 | column_name: column.name, |
| 62 | default_value: |
| 63 | column.pk === 1 && tablesWithAutoIncrementPrimaryKeys.includes(table) |
| 64 | ? 'AUTO_INCREMENT' |
| 65 | : parseDefaultValue(column.dflt_value), |
| 66 | is_nullable: column.notnull == 0, |
| 67 | is_generated: column.hidden !== 0, |
| 68 | data_type: extractType(column.type), |
| 69 | max_length: extractMaxLength(column.type), |
| 70 | numeric_precision: null, |
| 71 | numeric_scale: null, |
| 72 | }; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return overview; |
| 77 | } |
| 78 | |
| 79 | // Tables |
| 80 | // =============================================================================================== |
| 81 | |
| 82 | /** |
| 83 | * List all existing tables in the current schema/database |
| 84 | */ |
| 85 | async tables(): Promise<string[]> { |
nothing calls this directly
no outgoing calls
no test coverage detected