All files / src/abap/5_syntax/expressions select.ts

89.74% Statements 569/634
81.06% Branches 214/264
100% Functions 19/19
89.74% Lines 569/634

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 6351x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 171x 171x 171x 171x 2x 2x 2x 171x 171x 1x 1x 1x 1x 170x 170x 170x 171x 171x 1x 1x 1x 1x 169x 169x 169x 169x 169x 169x 171x 10x 10x 10x 169x 171x 164x 164x 169x 169x 169x 171x 171x 171x 11x 11x 11x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x 2x 5x 3x 3x 3x 3x 5x 5x 11x 166x 166x 171x     166x 166x 171x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 3x 3x 3x 17x 17x 17x 17x 171x 10x 10x 10x 10x 166x 171x 107x 107x 166x 166x 171x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 13x 166x 171x 64x 64x 166x 171x 10x 10x 171x 1x 1x 8x 8x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 183x 183x 3x 3x 180x 180x 180x 180x 180x 183x 22x 22x 158x 158x 183x 3x 3x 155x 155x 183x 96x 27x 27x 96x 128x 128x 128x 183x 18x 18x 110x 110x 110x 1x 1x 64x 64x 64x 84x 84x 11x 84x 57x 73x 14x 14x 2x 2x 2x 64x 1x 1x 169x 169x 169x 169x 169x 169x 68x 68x 68x 68x 68x 1x 1x 1x 68x 48x 48x 68x 68x 101x 101x 169x 78x 78x 55x 78x 23x       23x 78x 78x 23x 23x 169x 9x 9x 9x         9x 9x 18x 18x 18x 18x 18x 6x         6x 6x 6x 6x 6x 2x 2x 6x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 6x 6x 6x 18x 18x 18x 14x 14x 14x 1x 1x 3x 3x 3x 3x 3x     3x 1x 1x 55x 55x 55x 55x 52x 52x 3x 3x 52x 52x 18x 18x   18x 18x 18x 18x 52x 25x 52x 6x 6x 6x 4x 6x                 2x 6x 1x 1x 1x 1x 1x 1x 1x 1x 6x     6x 55x 2x 2x               2x     2x 2x 2x     2x 2x   3x 1x 1x 55x 1x 1x 48x 48x 48x 48x 48x 48x 5x 5x 1x 1x 2x 2x     2x 2x 1x 1x 4x 4x 4x 5x 6x 6x 1x 1x 1x 5x 6x 2x 2x 6x 6x 6x 2x 48x     43x 48x 33x 33x 33x 10x 48x     10x 48x 1x 1x 9x 48x 8x 8x     8x 8x 1x 1x 1x 1x 1x 1x 11x 11x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 18x 18x 8x 8x 8x 10x 18x     18x 18x 10x 10x 1x 1x 1x 41x 11x 41x     30x 30x 30x 41x 41x 20x 20x 10x 10x 1x 1x 1x 13x 13x 13x     13x 13x 11x 11x 1x 1x 10x 11x   11x 10x 10x 10x 10x 10x   13x 2x 2x 2x 2x           1x 1x 12x 12x     12x 12x 11x 12x 1x 1x     1x 1x 18x 18x 18x 25x 25x 25x 25x 25x 18x 18x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 2x 2x 2x 14x 14x 16x 14x 14x 16x 2x 2x 1x 1x 170x 170x 170x 51x 51x 170x 170x 5x 5x 170x 170x 170x 122x 122x 122x 23x 23x 122x 122x 170x 170x 86x 86x 170x 170x 170x 1x  
import * as Expressions from "../../2_statements/expressions";
import {ExpressionNode} from "../../nodes";
import {CurrentScope} from "../_current_scope";
import {CharacterType, DateType, Integer8Type, IntegerType, IStructureComponent, ITableOptions, NumericType, StringType,
  StructureType, TableKeyType, TableType, TimeType, UnknownType, VoidType} from "../../types/basic";
import {InlineData} from "./inline_data";
import {Target} from "./target";
import {SQLFrom} from "./sql_from";
import {SQLForAllEntries} from "./sql_for_all_entries";
import {ScopeType} from "../_scope_type";
import {SQLSource} from "./sql_source";
import {SQLCompare} from "./sql_compare";
import {DatabaseTableSource} from "./database_table";
import {AbstractType} from "../../types/basic/_abstract_type";
import {SQLOrderBy} from "./sql_order_by";
import {Dynamic} from "./dynamic";
import {ReferenceType} from "../_reference";
import {SyntaxInput, syntaxIssue} from "../_syntax_input";
import {LanguageVersion, Release, releaseAtLeast} from "../../../version";
import {IEdit} from "../../../edit_helper";
import {checkDatabaseFields} from "./_check_database_fields";
 
type FieldList = {code: string, as: string, expression: ExpressionNode}[];
type DatabaseSourceInfo = {source: DatabaseTableSource, name: string, alias: string};
type FieldTypeLookup = (code: string) => AbstractType | undefined;
const isSimple = /^\w+$/;
// SQL functions where the result has the same type as the first argument
const sameTypeAsFirstArgument = new Set(["UPPER", "LOWER", "LTRIM", "RTRIM"]);
 
export class Select {
  public static runSyntax(node: ExpressionNode, input: SyntaxInput, skipImplicitInto = false, selectLoop = false): void {
    const token = node.getFirstToken();
 
    let from = node.findDirectExpression(Expressions.SQLFrom);
    if (from === undefined) {
      // huh, sometimes the select expression is wrapped
      from = node.findFirstExpression(Expressions.SQLFrom);
    }
    const dbSources = from ? SQLFrom.runSyntax(from, input) : [];
    if (from === undefined) {
      const message = `Missing FROM`;
      input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
      return;
    }
 
    const fields = this.findFields(node, input);
    if (fields.length === 0
        && node.findDirectExpression(Expressions.SQLFieldListLoop) === undefined
        && node.findDirectExpression(Expressions.SQLAggregation) === undefined) {
      const message = `SELECT: fields missing`;
      input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
      return;
    }
 
    checkDatabaseFields(fields.map(field => field.code), dbSources, input, node.getFirstToken());
 
    const intoExpression = this.handleInto(node, input, fields, dbSources, from);
 
    const fae = node.findDirectExpression(Expressions.SQLForAllEntries);
    if (fae) {
      input.scope.push(ScopeType.OpenSQL, "SELECT", token.getStart(), input.filename);
      SQLForAllEntries.runSyntax(fae, input);
    }
 
    for (const t of node.findAllExpressions(Expressions.Target)) {
      Target.runSyntax(t, input);
    }
 
    // check implicit into, the target field is implict equal to the table name
    if (skipImplicitInto === false
        && node.findDirectExpression(Expressions.SQLIntoTable) === undefined
        && node.findDirectExpression(Expressions.SQLIntoList) === undefined
        && node.findDirectExpression(Expressions.SQLIntoStructure) === undefined) {
      const fields = node.findFirstExpression(Expressions.SQLAggregation)?.concatTokens();
      const c = new RegExp(/^count\(\s*\*\s*\)$/, "i");
      if (fields === undefined || c.test(fields) === false) {
        let body = from?.findDirectExpression(Expressions.SQLFromBody);
        while (body) {
          const inner = body.findDirectExpression(Expressions.SQLFromBody);
          if (inner === undefined) {
            break;
          }
          body = inner;
        }
        const nameToken = body?.findDirectExpression(Expressions.SQLFromSource);
        if (nameToken) {
          const found = input.scope.findVariable(nameToken.concatTokens());
          if (found) {
            input.scope.addReference(nameToken.getFirstToken(), found, ReferenceType.DataWriteReference, input.filename);
          } else {
            const message = `Target variable ${nameToken.concatTokens()} not found in scope`;
            input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
            return;
          }
        }
      }
    }
 
    // OFFSET
    for (const s of node.findDirectExpressions(Expressions.SQLSource)) {
      SQLSource.runSyntax(s, input);
    }
    const upToWhere = node.findDirectExpression(Expressions.SQLCond);
    const isCloud = input.scope.getLanguageVersion() === LanguageVersion.Cloud;
    for (const up of node.findDirectExpressions(Expressions.SQLUpTo)) {
      // in classic Open SQL (INTO before WHERE) "UP TO" is allowed before INTO,
      // in strict Open SQL (INTO after WHERE) "UP TO" must be placed after INTO
      const intoAfterWhere = upToWhere !== undefined
        && intoExpression !== undefined
        && intoExpression.getFirstToken().getStart().isAfter(upToWhere.getFirstToken().getStart());
      if (intoExpression
          && this.isStrictMode(node, input)
          && (isCloud || (this.upToUsesHostVariable(up) && intoAfterWhere))
          && (selectLoop === false || isCloud)
          && from.getFirstToken().getStart().isBefore(up.getFirstToken().getStart())
          && up.getFirstToken().getStart().isBefore(intoExpression.getFirstToken().getStart())) {
        const message = `The addition "UP TO n ROWS" must only be placed after the INTO/APPENDING clause.`;
        input.issues.push(syntaxIssue(input, up.getFirstToken(), message, this.buildUpToRowsFix(node, input, up, intoExpression)));
      }
      for (const s of up.findDirectExpressions(Expressions.SQLSource)) {
        SQLSource.runSyntax(s, input);
      }
    }
    for (const fae of node.findDirectExpressions(Expressions.SQLForAllEntries)) {
      for (const s of fae.findDirectExpressions(Expressions.SQLSource)) {
        SQLSource.runSyntax(s, input);
      }
    }
 
    for (const s of node.findAllExpressions(Expressions.SQLCompare)) {
      SQLCompare.runSyntax(s, input, dbSources);
    }
 
    const orderBy = node.findDirectExpression(Expressions.SQLOrderBy);
    if (orderBy) {
      SQLOrderBy.runSyntax(orderBy, input);
 
      const where = node.findDirectExpression(Expressions.SQLCond);
      if (intoExpression
          && where
          && intoExpression.getFirstToken().getStart().isBefore(orderBy.getFirstToken().getStart())
          && where.getFirstToken().getStart().isBefore(orderBy.getFirstToken().getStart())
          && where.getFirstToken().getStart().isBefore(intoExpression.getFirstToken().getStart())) {
        const message = `ORDER BY must be before INTO, after WHERE`;
        input.issues.push(syntaxIssue(input, orderBy.getFirstToken(), message));
      }
    }
 
    if (this.isStrictMode(node, input)) {
      this.strictModeChecks(node, input);
    }
 
    if (input.scope.getType() === ScopeType.OpenSQL) {
      input.scope.pop(node.getLastToken().getEnd());
    }
  }
 
  private static upToUsesHostVariable(up: ExpressionNode): boolean {
    return up.findFirstExpression(Expressions.SQLSource)?.getFirstToken().getStr() === "@";
  }
 
  private static buildUpToRowsFix(node: ExpressionNode,
                                  input: SyntaxInput,
                                  up: ExpressionNode,
                                  intoExpression: ExpressionNode): IEdit {
    const tokens = node.getTokens();
    const upLast = up.getLastToken();
    const next = tokens[tokens.findIndex(t => t === upLast) + 1];
    const deleteEnd = next?.getStart() || upLast.getEnd();
    const range = {start: up.getFirstToken().getStart(), end: deleteEnd};
 
    return {
      [input.filename]: [
        {
          range: {start: intoExpression.getLastToken().getEnd(), end: intoExpression.getLastToken().getEnd()},
          newText: " " + up.concatTokens(),
        },
        {
          range,
          newText: "",
        },
      ],
    };
  }
 
  // there are multiple rules, but gotta start somewhere
  private static isStrictMode(node: ExpressionNode, input: SyntaxInput) {
    // strict OpenSQL is always required in the cloud language version
    if (input.scope.getLanguageVersion() === LanguageVersion.Cloud) {
      return true;
    }
 
    const into = node.findDirectExpressionsMulti([Expressions.SQLIntoList, Expressions.SQLIntoStructure, Expressions.SQLIntoTable])[0];
    const where = node.findDirectExpression(Expressions.SQLCond);
 
    // INTO is after WHERE
    if (into && where && into.getFirstToken().getStart().isAfter(where.getFirstToken().getStart())) {
      return true;
    }
 
    // FIELDS is used
    if (node.findFirstExpression(Expressions.SQLFields)) {
      return true;
    }
 
    // any field is escaped with @
    for (const source of node.findAllExpressions(Expressions.SQLSource)) {
      if (source.getFirstToken().getStr() === "@") {
        return true;
      }
    }
 
    // comma used in FROM
    const fieldList = node.findFirstExpression(Expressions.SQLFieldList);
    if (fieldList && fieldList.findDirectTokenByText(",")) {
      return true;
    }
 
    return false;
  }
 
  private static strictModeChecks(node: ExpressionNode, input: SyntaxInput) {
 
    const sources = node.findAllExpressions(Expressions.SQLSource);
    for (const source of sources) {
      const first = source.getFirstChild();
      if (first?.get() instanceof Expressions.SQLAliasField) {
        continue;
      } else if (first?.getFirstToken().getStr() === "@") {
        continue;
      } else if (first?.getChildren()[0].get() instanceof Expressions.Constant) {
        continue;
      }
      const message = `SELECT: "${source.concatTokens()}" must be escaped with @ in strict mode`;
      input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
    }
  }
 
  private static handleInto(node: ExpressionNode,
                            input: SyntaxInput,
                            fields: FieldList,
                            dbSources: DatabaseTableSource[],
                            from: ExpressionNode): ExpressionNode | undefined {
    const intoTable = node.findDirectExpression(Expressions.SQLIntoTable);
    if (intoTable) {
      const inline = intoTable.findFirstExpression(Expressions.InlineData);
      if (inline
          && intoTable.findDirectTokenByText("INTO") !== undefined
          && intoTable.findDirectTokenByText("CORRESPONDING") !== undefined
          && !releaseAtLeast(input.scope.getRelease(), Release.v755)) {
        const message = "INTO CORRESPONDING FIELDS OF TABLE with an inline declaration requires 7.55";
        input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
      }
      if (inline) {
        InlineData.runSyntax(inline, input, this.buildTableType(fields, dbSources, input.scope, from));
      }
      return intoTable;
    }
 
    const intoStructure = node.findDirectExpression(Expressions.SQLIntoStructure);
    if (intoStructure) {
      const inlineList = intoStructure.findAllExpressions(Expressions.InlineData);
      if (inlineList.length === 1) {
        InlineData.runSyntax(inlineList[0], input, this.buildStructureType(fields, dbSources, input.scope, from));
      } else {
        for (const inline of inlineList) {
          // todo, for now these are voided
          InlineData.runSyntax(inline, input, VoidType.get("SELECT_todo1"));
        }
      }
      return intoStructure;
    }
 
    const intoList = node.findDirectExpression(Expressions.SQLIntoList);
    if (intoList) {
      const isDynamic = fields.length === 1 && fields[0].expression.findDirectExpression(Expressions.Dynamic) !== undefined;
      const targets = intoList.findDirectExpressions(Expressions.SQLTarget);
      if (targets.length !== fields.length && isDynamic !== true) {
        const message = `number of fields selected vs list does not match`;
        input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
        return;
      }
 
      for (let i = 0; i < targets.length; i++) {
        const target = targets[i];
        const field = fields[i];
 
        const inline = target.findFirstExpression(Expressions.InlineData);
        if (inline) {
          if (isDynamic) {
            const message = `dynamic field list, inlining not possible`;
            input.issues.push(syntaxIssue(input, node.getFirstToken(), message));
            return;
          }
 
          let type: AbstractType = VoidType.get("SELECT_todo2");
 
          const fn = this.findFunctionColumn(field, false);
          if (fn) {
            const sourceInfos = this.buildDatabaseSourceInfos(from, dbSources);
            type = this.inferFunctionType(fn, code => this.findFieldType(code, sourceInfos, input.scope)) || type;
          } else if (isSimple.test(field.code)) {
            for (const dbSource of dbSources) {
              if (dbSource === undefined) {
                continue;
              }
              const dbType = dbSource.parseType(input.scope.getRegistry());
              if (dbType instanceof StructureType) {
                const found = dbType.getComponentByName(field.code);
                if (found) {
                  type = found;
                  break;
                }
              }
            }
          }
 
          InlineData.runSyntax(inline, input, type);
        }
      }
      return intoList;
    }
 
    return undefined;
  }
 
  private static countResultType(scope: CurrentScope): AbstractType {
    if (releaseAtLeast(scope.getRelease(), Release.v750)
        || scope.getOpenABAP()
        || scope.getLanguageVersion() === LanguageVersion.Cloud) {
      return new Integer8Type();
    } else {
      return IntegerType.get();
    }
  }
 
  private static buildStructureType(fields: FieldList,
                                    dbSources: DatabaseTableSource[],
                                    scope: CurrentScope,
                                    from: ExpressionNode): AbstractType | undefined {
    if (fields.length === 1 && dbSources.length === 1) {
      // COUNT( * ) yields an integer regardless of the (possibly dynamic) table
      if (/^count\(\s*\*\s*\)$/i.test(fields[0].code)) {
        return this.countResultType(scope);
      }
      const dbType = dbSources[0]?.parseType(scope.getRegistry());
      if (dbType === undefined) {
        const name = dbSources[0]?.getName() || "buildStructureTypeError";
        if (scope.getRegistry().inErrorNamespace(name) === true) {
          return new UnknownType("Select, " + name + " not found");
        } else {
          return VoidType.get(dbSources[0]?.getName());
        }
      }
      if (fields[0].code === "*") {
        return dbType;
      } else {
        if (dbType instanceof StructureType) {
          const field = dbType.getComponentByName(fields[0].code);
          if (field) {
            return field;
          } else if (fields[0].code === "COUNT(*)") {
            if (releaseAtLeast(scope.getRelease(), Release.v750)
                || scope.getOpenABAP()
                || scope.getLanguageVersion() === LanguageVersion.Cloud) {
              return new Integer8Type();
            } else {
              return IntegerType.get();
            }
          }
          const fn = this.findFunctionColumn(fields[0], false);
          if (fn) {
            const sourceInfos = this.buildDatabaseSourceInfos(from, dbSources);
            const type = this.inferFunctionType(fn, code => this.findFieldType(code, sourceInfos, scope));
            if (type) {
              return type;
            }
          }
          // todo: aggregated/calculated values
          return VoidType.get("SELECT_todo11");
        } else {
          return VoidType.get("SELECT_todo10");
        }
      }
    } else if (dbSources.length === 1) {
      const dbType = dbSources[0]?.parseType(scope.getRegistry());
      if (dbType === undefined) {
        const name = dbSources[0]?.getName() || "buildStructureTypeError";
        if (scope.getRegistry().inErrorNamespace(name) === true) {
          return new UnknownType("Select, " + name + " not found");
        } else {
          return VoidType.get(dbSources[0]?.getName());
        }
      }
      if (!(dbType instanceof StructureType)) {
        return VoidType.get("SELECT_todo14");
      }
      if (this.allFieldsSupported(fields) === true) {
        const components = this.buildSingleSourceComponents(fields, dbType, from, dbSources, scope);
        if (components === undefined) {
          return VoidType.get("SELECT_todo9");
        }
        return new StructureType(components);
      }
      return VoidType.get("SELECT_todo12");
    } else {
      return VoidType.get("SELECT_todo13");
    }
  }
 
  private static buildTableType(fields: FieldList,
                                dbSources: DatabaseTableSource[],
                                scope: CurrentScope,
                                from: ExpressionNode) {
    const tableOptions: ITableOptions = {withHeader: false, keyType: TableKeyType.empty};
 
    if (dbSources.length > 1) {
      const sourceInfos = this.buildDatabaseSourceInfos(from, dbSources);
      if (fields.length === 1 && fields[0].code === "*") {
        const components: IStructureComponent[] = [];
        for (const info of sourceInfos) {
          const type = info.source?.parseType(scope.getRegistry());
          if (!(type instanceof StructureType)) {
            return VoidType.get("SELECT_todo3");
          }
          components.push({name: info.alias || info.name, type});
        }
        return new TableType(new StructureType(components), tableOptions, undefined);
      }
 
      const lookup: FieldTypeLookup = code => this.findFieldType(code, sourceInfos, scope);
      const components: IStructureComponent[] = [];
      for (const field of fields) {
        const fn = this.findFunctionColumn(field);
        if (fn) {
          components.push({name: field.as, type: this.inferFunctionType(fn, lookup) || VoidType.get("SELECT_function")});
          continue;
        }
        const type = lookup(field.code);
        if (type === undefined) {
          return VoidType.get("SELECT_todo3");
        }
        const name = field.as || field.code.split("~").pop()!;
        components.push({name, type});
      }
      return new TableType(new StructureType(components), tableOptions, undefined);
    } else if (dbSources.length !== 1) {
      return VoidType.get("SELECT_todo3");
    }
 
    if (dbSources[0] === undefined) {
      // then its a voided table
      return new TableType(VoidType.get("SELECT_todo4"), tableOptions, undefined);
    }
    const dbType = dbSources[0].parseType(scope.getRegistry());
    if (!(dbType instanceof StructureType)) {
      return VoidType.get("SELECT_todo5");
    }
 
    if (fields.length === 1 && fields[0].code === "*") {
      return new TableType(dbType, tableOptions, undefined);
    }
 
    if (this.allFieldsSupported(fields) === true) {
      const components = this.buildSingleSourceComponents(fields, dbType, from, dbSources, scope);
      if (components === undefined) {
        return VoidType.get("SELECT_todo6");
      }
      return new TableType(new StructureType(components), tableOptions, undefined);
    }
 
    return VoidType.get("SELECT_todo7");
  }
 
  /** plain field names, or SQL function columns with an alias */
  private static allFieldsSupported(fields: FieldList): boolean {
    return fields.every(f => isSimple.test(f.code) || this.findFunctionColumn(f) !== undefined);
  }
 
  /** returns undefined if a plain field is not found in the database table */
  private static buildSingleSourceComponents(fields: FieldList,
                                             dbType: StructureType,
                                             from: ExpressionNode,
                                             dbSources: DatabaseTableSource[],
                                             scope: CurrentScope): IStructureComponent[] | undefined {
    const sourceInfos = this.buildDatabaseSourceInfos(from, dbSources);
    const lookup: FieldTypeLookup = code => this.findFieldType(code, sourceInfos, scope);
    const components: IStructureComponent[] = [];
    for (const field of fields) {
      const fn = this.findFunctionColumn(field);
      if (fn) {
        components.push({name: field.as, type: this.inferFunctionType(fn, lookup) || VoidType.get("SELECT_function")});
        continue;
      }
      const type = dbType.getComponentByName(field.code);
      if (type === undefined) {
        return undefined;
      }
      components.push({name: field.as || field.code, type});
    }
    return components;
  }
 
  /** returns the SQLFunction node if the field list entry is a single SQL function call */
  private static findFunctionColumn(field: FieldList[number], requireAlias = true): ExpressionNode | undefined {
    if (requireAlias === true && field.as === "") {
      return undefined;
    } else if (!(field.expression.get() instanceof Expressions.SQLField)) {
      return undefined;
    }
    const children = field.expression.getChildren().filter(c =>
      !(c.get() instanceof Expressions.SQLAsName) && c.concatTokens().toUpperCase() !== "AS");
    if (children.length === 1
        && children[0] instanceof ExpressionNode
        && children[0].get() instanceof Expressions.SQLFunction) {
      return children[0];
    }
    return undefined;
  }
 
  /** infers the result type of a SQL function, returns undefined if not possible */
  private static inferFunctionType(fn: ExpressionNode, lookup: FieldTypeLookup): AbstractType | undefined {
    const name = fn.getFirstToken().getStr().toUpperCase();
    const inputs = fn.findDirectExpressions(Expressions.SQLFunctionInput);
    if (inputs.length === 0) {
      return undefined;
    }
 
    if (name === "SUBSTRING" && inputs.length === 3) {
      const len = inputs[2].concatTokens();
      if (/^\d+$/.test(len) === false || parseInt(len, 10) <= 0) {
        return undefined;
      }
      const argType = this.inferFunctionInputType(inputs[0], lookup);
      if (argType instanceof StringType) {
        return argType;
      } else if (argType instanceof CharacterType
          || argType instanceof NumericType
          || argType instanceof DateType
          || argType instanceof TimeType) {
        return new CharacterType(parseInt(len, 10));
      }
      return undefined;
    } else if (sameTypeAsFirstArgument.has(name)) {
      const argType = this.inferFunctionInputType(inputs[0], lookup);
      if (argType instanceof CharacterType || argType instanceof StringType) {
        return argType;
      }
      return undefined;
    }

    return undefined;
  }
 
  private static inferFunctionInputType(input: ExpressionNode, lookup: FieldTypeLookup): AbstractType | undefined {
    const children = input.getChildren();
    if (children.length !== 1 || !(children[0] instanceof ExpressionNode)) {
      return undefined;
    }
    const child = children[0];
    if (child.get() instanceof Expressions.SQLFieldName || child.get() instanceof Expressions.SQLAliasField) {
      return lookup(child.concatTokens().toUpperCase());
    } else if (child.get() instanceof Expressions.SQLFunction) {
      return this.inferFunctionType(child, lookup);
    }
    return undefined;
  }
 
  private static buildDatabaseSourceInfos(from: ExpressionNode,
                                          dbSources: DatabaseTableSource[]): DatabaseSourceInfo[] {
    const fromSources = from.findAllExpressions(Expressions.SQLFromSource);
    return dbSources.map((source, index) => {
      const fromSource = fromSources[index];
      const name = fromSource?.findFirstExpression(Expressions.DatabaseTable)
        ?.getFirstToken().getStr().replace(/^\*/, "").toUpperCase() || "";
      const alias = fromSource?.findDirectExpression(Expressions.SQLAsName)?.concatTokens().toUpperCase() || "";
      return {source, name, alias};
    });
  }
 
  private static findFieldType(code: string,
                               sourceInfos: DatabaseSourceInfo[],
                               scope: CurrentScope): AbstractType | undefined {
    const separator = code.indexOf("~");
    const qualifier = separator >= 0 ? code.substring(0, separator) : undefined;
    const fieldName = separator >= 0 ? code.substring(separator + 1) : code;
    const candidates = qualifier === undefined
      ? sourceInfos
      : sourceInfos.filter(info => info.alias === qualifier || info.name === qualifier);
 
    for (const candidate of candidates) {
      let type = candidate.source?.parseType(scope.getRegistry());
      for (const component of fieldName.split("-")) {
        if (!(type instanceof StructureType)) {
          type = undefined;
          break;
        }
        type = type.getComponentByName(component);
      }
      if (type) {
        return type;
      }
    }
    return undefined;
  }
 
  private static findFields(node: ExpressionNode, input: SyntaxInput): FieldList {
    let expr = node.findFirstExpression(Expressions.SQLFieldList);
    // a single field can be wrapped in a nested SQLFieldList
    while (expr && expr.getChildren().length === 1 && expr.getFirstChild()?.get() instanceof Expressions.SQLFieldList) {
      expr = expr.getFirstChild() as ExpressionNode;
    }
    const ret = [];
    if (expr?.getFirstChild()?.get() instanceof Expressions.Dynamic) {
      Dynamic.runSyntax(expr.getFirstChild() as ExpressionNode, input);
    }
 
    // eslint-disable-next-line max-len
    for (const field of expr?.findDirectExpressionsMulti([Expressions.SQLField, Expressions.SQLFieldName, Expressions.SQLAggregation]) || []) {
      let code = field.concatTokens().toUpperCase();
      const as = field.findDirectExpression(Expressions.SQLAsName)?.concatTokens() || "";
      if (as !== "") {
        code = code.replace(" AS " + as.toUpperCase(), "");
      }
      ret.push({code, as, expression: field});
    }
 
    if (ret.length === 0 && expr) {
      ret.push({code: expr.concatTokens(), as: "", expression: expr});
    }
 
    return ret;
  }
}