All files / src/objects data_definition.ts

98.1% Statements 310/316
85.51% Branches 124/145
100% Functions 22/22
98.1% Lines 310/316

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 3171x 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 206x 206x 206x 206x 206x 206x 206x 918x 918x 206x 206x 4x 4x 4x 4x 4x 206x 206x 232x 232x 232x 206x 206x 233x 233x 233x 206x 206x 11x 11x 11x 206x 206x 206x 76x 76x 76x 206x 206x 49x 49x 45x 45x 45x 49x 49x 206x 206x 80x 80x 206x 206x 3x 3x 3x 206x 206x 235x 235x 235x 235x 235x 235x 206x 206x 352x 352x 206x 206x 37x 37x 206x 206x 5x 5x 5x 5x 26x 11x 11x 26x 5x 5x 206x 206x 817x 610x 610x 207x 207x 207x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 817x 197x 852x 74x 74x 852x 197x 197x 197x 852x 197x 197x 817x 10x 10x 207x 207x 207x 207x 206x 206x 149x 149x 206x 206x 206x 206x 206x 207x 197x 197x 10x 207x     10x 10x 10x 10x 207x 207x 206x 206x 206x 414x 414x 164x 164x 164x 43x 43x 164x 414x 414x 206x 206x 207x 23x 23x 23x 23x 23x 23x 184x 206x 206x 206x 207x 19x 19x 19x 19x 19x 207x 207x 206x 206x 197x 197x 38x 38x 197x 38x 38x 197x 197x 393x 393x 393x 393x 393x 384x 384x 45x 45x 45x 384x 328x 328x 328x 384x 232x 232x 384x 393x 1x 1x 1x 1x 1x 393x     393x 393x 393x 393x 31x 31x 362x 362x 393x 30x 30x 362x 362x 362x 362x 362x 362x 362x 362x 362x 197x 206x 206x 197x 165x 165x 165x 165x 197x 197x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 197x 197x 42x 42x     42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 197x 206x  
import {Comment} from "../abap/1_lexer/tokens";
import {Combi, regex, seq, starPrio} from "../abap/2_statements/combi";
import {ExpressionNode} from "../abap/nodes";
import {AbstractType} from "../abap/types/basic/_abstract_type";
import {CDSDetermineTypes} from "../cds/cds_determine_types";
import {CDSLexer} from "../cds/cds_lexer";
import {defaultRelease} from "../version";
import {CDSParser} from "../cds/cds_parser";
import {CDSAnnotate, CDSAnnotation, CDSAs, CDSAssociation, CDSDefineProjection, CDSElement, CDSName, CDSPrefixedName, CDSRelation, CDSSelect, CDSSource} from "../cds/expressions";
import {IRegistry} from "../_iregistry";
import {AbstractObject} from "./_abstract_object";
import {IParseResult} from "./_iobject";
 
export type ParsedDataDefinition = {
  sqlViewName: string | undefined;
  definitionName: string | undefined;
  /** SOURCE_TYPE from the abapGit XML, eg. "W" view entity, "P" projection view, "V" DDIC-based view */
  sourceType: string | undefined;
  description: string | undefined;
  /** name is the name of the element, nameInSource the name in the source, if aliased via "as" */
  fields: {key: boolean, name: string, nameInSource?: string, prefix: string, annotations: string[]}[];
  sources: {name: string, as: string | undefined}[];
  associations: {name: string, as: string | undefined}[],
  relations: {name: string, as: string | undefined}[];
  tree: ExpressionNode | undefined;
};
 
export class DataDefinition extends AbstractObject {
  private parserError: boolean | undefined = undefined;
  private parsedData: ParsedDataDefinition | undefined = undefined;
  private typeCache: AbstractType | undefined = undefined;
  private typeCacheData: ParsedDataDefinition | undefined = undefined;
 
  public getType(): string {
    return "DDLS";
  }
 
  public getAllowedNaming() {
    return {
      maxLength: 40,
      allowNamespace: true,
    };
  }
 
  public getSQLViewName(): string | undefined {
    this.parse();
    return this.parsedData?.sqlViewName;
  }
 
  public getDefinitionName(): string | undefined {
    this.parse();
    return this.parsedData?.definitionName;
  }
 
  public getDescription(): string | undefined {
    this.parse();
    return this.parsedData?.description;
  }
 
  /** SOURCE_TYPE from the abapGit XML, eg. "W" view entity, "P" projection view, "V" DDIC-based view */
  public getSourceType(): string | undefined {
    this.parse();
    return this.parsedData?.sourceType;
  }
 
  public parseType(reg: IRegistry): AbstractType {
    this.parse();
    if (this.typeCache === undefined || this.typeCacheData !== this.parsedData) {
      this.typeCacheData = this.parsedData;
      this.typeCache = new CDSDetermineTypes().parseType(reg, this.parsedData!, this.getName());
    }
    return this.typeCache;
  }
 
  public getParsedData() {
    return this.parsedData;
  }
 
  public listSources() {
    this.parse();
    return this.parsedData?.sources;
  }
 
  public setDirty(): void {
    this.parsedData = undefined;
    this.typeCache = undefined;
    this.typeCacheData = undefined;
    this.parserError = undefined;
    super.setDirty();
  }
 
  public findSourceFile() {
    return this.getFiles().find(f => f.getFilename().endsWith(".asddls") || f.getFilename().endsWith(".acds"));
  }
 
  public hasParserError() {
    return this.parserError;
  }
 
  public listKeys(): string[] {
    this.parse();
 
    const ret: string[] = [];
    for (const field of this.parsedData?.fields || []) {
      if (field.key === true) {
        ret.push(field.name);
      }
    }
    return ret;
  }
 
  public parse(): IParseResult {
    if (this.isDirty() === false) {
      return {updated: false, runtime: 0};
    }
 
    const start = Date.now();
 
    const ddls = this.parseRaw2()?.abapGit?.["asx:abap"]?.["asx:values"]?.DDLS;
    this.parsedData = {
      sqlViewName: undefined,
      definitionName: undefined,
      sourceType: typeof ddls?.SOURCE_TYPE === "string" ? ddls.SOURCE_TYPE.trim() : undefined,
      description: undefined,
      fields: [],
      sources: [],
      relations: [],
      associations: [],
      tree: undefined,
    };
 
    this.parsedData.tree = new CDSParser().parse(this.findSourceFile());
    const leadingAnnotations = this.findLeadingAnnotations(this.parsedData.tree);
    this.findSQLViewName(leadingAnnotations);
    this.parsedData.description = this.findDescription(leadingAnnotations, ddls?.DDTEXT);
    if (this.parsedData.tree) {
      for (const c of this.parsedData.tree?.getChildren() || []) {
        if (c.get() instanceof CDSAnnotation) {
          continue;
        }
        if (c instanceof ExpressionNode) {
          this.parsedData.definitionName = c.findFirstExpression(CDSName)?.concatTokens().replace(/ /g, "");
          break;
        }
      }
      this.findSourcesAndRelations(this.parsedData.tree);
      this.findFieldNames(this.parsedData.tree);
    } else {
      this.parserError = true;
    }
 
    this.dirty = false;
    return {updated: true, runtime: Date.now() - start};
  }
 
  public getTree() {
    return this.parsedData?.tree;
  }
 
//////////
 
  /** annotations before the entity definition, ie. not the ones on elements or parameters */
  private findLeadingAnnotations(tree: ExpressionNode | undefined): readonly ExpressionNode[] {
    if (tree !== undefined) {
      return tree.findDirectExpressions(CDSAnnotation);
    }
    const file = this.findSourceFile();
    if (file === undefined) {
      return [];
    }
    // Keep header annotations available even when the definition body cannot be parsed.
    const tokens = CDSLexer.run(file).filter(t => !(t instanceof Comment));
    const leadingAnnotations = seq(starPrio(CDSAnnotation), starPrio(regex(/.*/)));
    return Combi.run(leadingAnnotations, tokens, defaultRelease)
      ?.filter((n): n is ExpressionNode => n instanceof ExpressionNode && n.get() instanceof CDSAnnotation) || [];
  }
 
  /** values of the leading annotations with the given name, as written in the source */
  private findLeadingAnnotationValues(annotations: readonly ExpressionNode[], name: string): string[] {
    const ret: string[] = [];
    for (const annotation of annotations) {
      const tokens = annotation.getTokens().map(t => t.getStr());
      const colon = tokens.indexOf(":");
      if (colon >= 0 && tokens.slice(0, colon).join("") === name) {
        ret.push(tokens.slice(colon + 1).join(" "));
      }
    }
    return ret;
  }
 
  private findSQLViewName(annotations: readonly ExpressionNode[]): void {
    for (const value of this.findLeadingAnnotationValues(annotations, "@AbapCatalog.sqlViewName")) {
      const match = value.match(/^'([\w/]+)'$/);
      if (match) {
        this.parsedData!.sqlViewName = match[1].toUpperCase();
        return;
      }
    }
  }
 
  /** entity level EndUserText.label annotation, with fallback to DDTEXT from the abapGit XML */
  private findDescription(annotations: readonly ExpressionNode[], ddtext: unknown): string | undefined {
    for (const value of this.findLeadingAnnotationValues(annotations, "@EndUserText.label")) {
      const match = value.match(/^'([\s\S]*)'$/);
      if (match) {
        return match[1].replace(/\\(['\\])/g, "$1");
      }
    }
    return typeof ddtext === "string" && ddtext !== "" ? ddtext : undefined;
  }
 
  private findFieldNames(tree: ExpressionNode) {
    let expr = tree.findFirstExpression(CDSSelect);
    if (expr === undefined) {
      expr = tree.findFirstExpression(CDSAnnotate);
    }
    if (expr === undefined) {
      expr = tree.findFirstExpression(CDSDefineProjection);
    }
 
    for (const e of expr?.findDirectExpressions(CDSElement) || []) {
      let prefix = "";
      let nameInSource: string | undefined = undefined;
      let found = e.findDirectExpression(CDSAs)?.findDirectExpression(CDSName);
      const list = e.findDirectExpression(CDSPrefixedName)?.findAllExpressions(CDSName);
      if (list !== undefined) {
        const redirected = e.concatTokens().toUpperCase().includes(" REDIRECTED TO ");
        if (list.length > 1 && redirected === false) {
          // "prefix.field" is looked up as "field" in "prefix", also when aliased via "as"
          prefix = list[0].concatTokens();
          nameInSource = list[list.length - 1].concatTokens();
        } else if (list.length === 1 && redirected === false) {
          // unprefixed "field" is looked up in the sources, also when aliased via "as"
          nameInSource = list[0].concatTokens();
        }
        if (found === undefined) {
          found = redirected === true ? list[0] : list[list.length - 1];
        }
      }
      if (found === undefined) {
        // typed virtual element: VIRTUAL <name> : <type>
        if (e.findDirectTokenByText("VIRTUAL") !== undefined) {
          found = e.findFirstExpression(CDSName);
        }
      }
      if (found === undefined) {
        continue;
      }
 
      const name = found?.concatTokens();
      if (this.parsedData?.associations.some(a =>
        a.name.toUpperCase() === name.toUpperCase() || a.as?.toUpperCase() === name.toUpperCase())) {
        continue;
      }
 
      const annotations: string[] = [];
      for (const a of e.findDirectExpressions(CDSAnnotation)) {
        annotations.push(a.concatTokens());
      }
 
      this.parsedData!.fields.push({
        name: name,
        nameInSource: nameInSource,
        annotations: annotations,
        prefix: prefix,
        key: e.findDirectTokenByText("KEY") !== undefined,
      });
    }
  }
 
  private findSourcesAndRelations(tree: ExpressionNode) {
    for (const e of tree.findAllExpressions(CDSSource)) {
      const name = e.getFirstChild()?.concatTokens().toUpperCase().replace(/ /g, "") || "ERROR";
      const as = e.findDirectExpression(CDSAs)?.findDirectExpression(CDSName)?.concatTokens().toUpperCase();
      this.parsedData!.sources.push({name, as});
    }
 
    for (const e of tree.findAllExpressions(CDSRelation)) {
      // For namespace-prefixed names like /PF1/C_VH_TRANSTYPE, getFirstToken() only yields "/".
      // Collect all tokens NOT part of the CDSAs child to reconstruct the full name.
      const asNode = e.findDirectExpression(CDSAs);
      const asTokenSet = new Set(
        asNode ? asNode.getTokens().map(t => `${t.getStart().getRow()}:${t.getStart().getCol()}`) : [],
      );
      const name = e.getTokens()
        .filter(t => !asTokenSet.has(`${t.getStart().getRow()}:${t.getStart().getCol()}`))
        .map(t => t.getStr())
        .join("") || "ERROR";
      const as = asNode?.findDirectExpression(CDSName)?.getFirstToken().getStr();
      this.parsedData!.relations.push({name, as});
    }
 
    for (const e of tree.findAllExpressions(CDSAssociation)) {
      const j = e.findDirectExpression(CDSRelation);
      if (j === undefined) {
        continue;
      }
      // CDSRelation: seq(opt(/NS/), entityName, opt(CDSAs))
      // For namespace-prefixed names like /PF1/C_VH_TRANSTYPE, getFirstToken() only yields "/"
      // Collect all tokens that are NOT part of the CDSAs child to reconstruct the full name
      const asNode = j.findDirectExpression(CDSAs);
      const asTokenSet = new Set(
        asNode ? asNode.getTokens().map(t => `${t.getStart().getRow()}:${t.getStart().getCol()}`) : [],
      );
      const name = j.getTokens()
        .filter(t => !asTokenSet.has(`${t.getStart().getRow()}:${t.getStart().getCol()}`))
        .map(t => t.getStr())
        .join("") || "ERROR";
      const as = asNode?.findDirectExpression(CDSName)?.getFirstToken().getStr();
      this.parsedData!.associations.push({
        name: name,
        as: as,
      });
    }
  }
}