( columnRef: UnqualifiedColumnReference, tables: TableSchema[] )
| 24 | } |
| 25 | |
| 26 | export function resolveUnqualifiedColumnRef( |
| 27 | columnRef: UnqualifiedColumnReference, |
| 28 | tables: TableSchema[] |
| 29 | ): QualifiedColumnReference { |
| 30 | if (columnRef.any) { |
| 31 | if (columnRef.tableRefsInScope.length === 1) { |
| 32 | const tableName = getTableByName(tables, columnRef.tableRefsInScope[0].tableName).tableName |
| 33 | return { |
| 34 | ...columnRef, |
| 35 | tableName |
| 36 | } |
| 37 | } else { |
| 38 | throw new Error( |
| 39 | `Cannot resolve column reference originating from non-inferrable spread expression.` |
| 40 | ) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | let tablesInScopeSchemas: TableSchema[] = [] |
| 45 | |
| 46 | for (const availableTableRef of columnRef.tableRefsInScope) { |
| 47 | tablesInScopeSchemas = [ |
| 48 | ...tablesInScopeSchemas, |
| 49 | ...tables.filter( |
| 50 | schema => |
| 51 | schema.tableName === availableTableRef.tableName && |
| 52 | !tablesInScopeSchemas.find( |
| 53 | presentSchema => presentSchema.tableName === availableTableRef.tableName |
| 54 | ) |
| 55 | ) |
| 56 | ] |
| 57 | } |
| 58 | |
| 59 | const inScopeSchemasContainingColumn = tablesInScopeSchemas.filter( |
| 60 | schema => schema.columnNames.indexOf(columnRef.columnName) > -1 |
| 61 | ) |
| 62 | |
| 63 | if (inScopeSchemasContainingColumn.length === 0) { |
| 64 | const tablesInScopeNames = tablesInScopeSchemas.map(schema => `"${schema.tableName}"`) |
| 65 | throw new Error( |
| 66 | `No table in the query's scope has a column "${columnRef.columnName}".\n` + |
| 67 | `Tables in scope: ${ |
| 68 | tablesInScopeNames.length > 0 ? tablesInScopeNames.join(", ") : "(none)" |
| 69 | }` + |
| 70 | inScopeSchemasContainingColumn.map(schema => schema.tableName).join(", ") |
| 71 | ) |
| 72 | } else if (inScopeSchemasContainingColumn.length > 1) { |
| 73 | throw new Error( |
| 74 | `Unqualified column reference "${ |
| 75 | columnRef.columnName |
| 76 | }" matches more than one referenced table: ` + |
| 77 | inScopeSchemasContainingColumn.map(schema => schema.tableName).join(", ") |
| 78 | ) |
| 79 | } |
| 80 | |
| 81 | return { |
| 82 | ...columnRef, |
| 83 | tableName: inScopeSchemasContainingColumn[0].tableName |
no test coverage detected