001package gudusoft.gsqlparser; 002 003 004import gudusoft.gsqlparser.compiler.*; 005import gudusoft.gsqlparser.nodes.*; 006import gudusoft.gsqlparser.nodes.dax.TDaxFunction; 007import gudusoft.gsqlparser.nodes.teradata.THashByClause; 008import gudusoft.gsqlparser.sqlenv.IdentifierService; 009import gudusoft.gsqlparser.sqlenv.TSQLEnv; 010import gudusoft.gsqlparser.sqlenv.TSQLFunction; 011import gudusoft.gsqlparser.sqlenv.TSQLTable; 012import gudusoft.gsqlparser.resolver2.metadata.ParseTimeCatalog; 013import gudusoft.gsqlparser.stmt.*; 014import gudusoft.gsqlparser.stmt.dax.TDaxStmt; 015import gudusoft.gsqlparser.stmt.oracle.*; 016import gudusoft.gsqlparser.sqlenv.ESQLDataObjectType; 017import gudusoft.gsqlparser.util.OraclePseudoColumnUtil; 018import gudusoft.gsqlparser.util.SQLUtil; 019import gudusoft.gsqlparser.util.functionChecker; 020import gudusoft.gsqlparser.util.keywordChecker; 021 022import java.util.ArrayDeque; 023import java.util.ArrayList; 024import java.util.Collections; 025import java.util.Deque; 026import java.util.IdentityHashMap; 027import java.util.List; 028import java.util.Map; 029import java.util.Set; 030import java.util.Stack; 031import java.util.TreeMap; 032import java.security.MessageDigest; 033import java.security.NoSuchAlgorithmException; 034import java.nio.charset.StandardCharsets; 035 036/** 037 * TCustomSqlStatement is the root class for all SQL statements. 038 */ 039public class TCustomSqlStatement extends TParseTreeNode implements IRelation{ 040 041 private String sqlHash; 042 043 public void setSqlHash(String sqlHash) { 044 this.sqlHash = sqlHash; 045 } 046 047 /** 048 * Returns a stable, vendor-aware hash of this statement's SQL text for 049 * lineage grouping and statement identity. 050 * <p> 051 * Purpose: 052 * <ul> 053 * <li>Provide a deterministic identifier for a statement that is 054 * insensitive to formatting (whitespace, comments, keyword case).</li> 055 * <li>Act as the first component of a recommended {@code statementKey} 056 * for lineage grouping: {@code statementKey = sqlHash + "#" + queryId}.</li> 057 * </ul> 058 * How it works: 059 * <ul> 060 * <li>Builds a normalized textual representation of the statement by 061 * iterating the token chain between {@code getStartToken()} and 062 * {@code getEndToken()}.</li> 063 * <li>Normalization rules (Profile A by default): remove comments; 064 * collapse spacing deterministically; uppercase keywords; handle 065 * identifiers by the current vendor's case-sensitivity 066 * ({@link gudusoft.gsqlparser.sqlenv.TSQLEnv#columnCollationCaseSensitive}). 067 * For delimited identifiers (quoted identifiers), the quotes are 068 * removed via {@link gudusoft.gsqlparser.TBaseType#removeQuoteChar(String)} 069 * before case normalization. String literals are kept as-is.</li> 070 * <li>The hash input is prefixed by a normalization version and the 071 * current vendor, so future evolution of the normalizer will not break 072 * previously computed values: {@code normVersion + "\n" + vendor + "\n" + normalizedSql}.</li> 073 * <li>Hash function: SHA-256 (lowercase hex).</li> 074 * </ul> 075 * Usage: 076 * <ul> 077 * <li>Call {@code getSqlHash(false)} for cached result or lazy 078 * calculation with Profile A (identity-safe) normalization.</li> 079 * <li>Call {@code getSqlHash(true)} to force recalculation (e.g., after 080 * mutating the underlying token chain).</li> 081 * <li>If you need a grouping-friendly variant (masking certain literal 082 * classes), use {@link #computeSqlHash(SqlNormalizationProfile, String)} 083 * with {@link SqlNormalizationProfile#GROUPING_FRIENDLY}.</li> 084 * </ul> 085 * 086 * @param forceReCalculate if true, recompute the hash even if a cached 087 * value exists 088 * @return lowercase hex SHA-256 hash of the normalized SQL text 089 */ 090 public String getSqlHash(boolean forceReCalculate) { 091 if (sqlHash != null && !forceReCalculate) { 092 return sqlHash; 093 } 094 // Default: Profile A (identity-safe) 095 this.sqlHash = computeSqlHash(SqlNormalizationProfile.IDENTITY_SAFE, DEFAULT_SQLHASH_NORM_VERSION); 096 return this.sqlHash; 097 } 098 099 /** 100 * Backward compatible overload equivalent to {@code getSqlHash(false)}. 101 */ 102 public String getSqlHash() { 103 return getSqlHash(false); 104 } 105 106 /** 107 * Normalization profiles for SQL hashing. 108 * <ul> 109 * <li>IDENTITY_SAFE: Remove comments and normalize spacing/case only. 110 * Literal values are preserved. Operator synonyms are minimally 111 * unified (e.g., {@code !=} to {@code <>}).</li> 112 * <li>GROUPING_FRIENDLY: In addition to IDENTITY_SAFE, date/time 113 * string literals are normalized to {@code '1970-01-01'} to aid 114 * grouping across different runs where only timestamps vary.</li> 115 * </ul> 116 */ 117 public enum SqlNormalizationProfile { 118 IDENTITY_SAFE, 119 GROUPING_FRIENDLY 120 } 121 122 private static final String DEFAULT_SQLHASH_NORM_VERSION = "sqlHash.norm.v1"; 123 124 /** 125 * Compute a SQL hash using the given normalization profile and version. 126 * See {@link #getSqlHash(boolean)} for details. 127 * 128 * @param profile normalization profile 129 * @param normVersion version tag embedded in the hash input 130 * @return lowercase hex SHA-256 hash 131 */ 132 public String computeSqlHash(SqlNormalizationProfile profile, String normVersion) { 133 String normalized = toNormalizedSql(profile); 134 String input = normVersion + "\n" + String.valueOf(this.dbvendor) + "\n" + normalized; 135 return sha256Hex(input); 136 } 137 138 /** 139 * Produce a normalized textual representation of this statement according 140 * to the supplied profile. The method is non-mutating: it does not alter 141 * token texts or statuses permanently. 142 * 143 * Rules applied: 144 * - Remove comments. 145 * - Remove trailing semicolon. 146 * - Deterministic spacing around punctuation/operators. 147 * - Uppercase keywords, keep string literals as-is. 148 * - Identifiers: if the vendor's column collation is case sensitive, keep 149 * identifier case; otherwise uppercase. For quoted identifiers, remove 150 * quoting via {@link TBaseType#removeQuoteChar(String)} prior to case 151 * handling. 152 * - Minimal operator unification: {@code "!="} becomes {@code "<>"}. 153 * - Profile B adds date/time string masking: {@code '1970-01-01'}. 154 * 155 * @param profile normalization profile 156 * @return normalized SQL string 157 */ 158 public String toNormalizedSql(SqlNormalizationProfile profile) { 159 TSourceToken start = getStartToken(); 160 TSourceToken end = getEndToken(); 161 if (start == null || end == null) { 162 return String.valueOf(this.toString()); 163 } 164 165 boolean idCaseSensitive = Boolean.TRUE.equals(TSQLEnv.columnCollationCaseSensitive.get(this.dbvendor)); 166 167 StringBuilder sb = new StringBuilder(256); 168 TokenClass prevClass = null; 169 char lastAppended = '\0'; 170 171 // We may need to skip a single trailing semicolon that is the end token 172 // Detect once to simplify checks in the loop 173 boolean endIsSemicolon = (end.toString().equals(";")); 174 175 TSourceToken cur = start; 176 while (cur != null) { 177 // Skip tokens that should not contribute 178 if (isComment(cur)) { 179 // skip comments 180 } else if (cur == end && endIsSemicolon) { 181 // drop trailing semicolon 182 } else if (cur.tokenstatus == ETokenStatus.tsdeleted || cur.tokenstatus == ETokenStatus.tsignorebyyacc) { 183 // ignore deleted/ignored tokens 184 } else { 185 String text = normalizeTokenText(cur, idCaseSensitive, profile); 186 if (text != null && !text.isEmpty()) { 187 TokenClass clazz = classify(cur, text); 188 if (shouldAddSpaceBefore(prevClass, clazz, lastAppended)) { 189 sb.append(' '); 190 lastAppended = ' '; 191 } 192 sb.append(text); 193 lastAppended = text.charAt(text.length() - 1); 194 prevClass = clazz; 195 } 196 } 197 198 if (cur == end) { 199 break; 200 } else { 201 cur = cur.getNextTokenInChain(); 202 } 203 } 204 205 // Trim any trailing single space for cleanliness 206 int len = sb.length(); 207 if (len > 0 && sb.charAt(len - 1) == ' ') { 208 sb.setLength(len - 1); 209 } 210 return sb.toString(); 211 } 212 213 private static boolean isComment(TSourceToken t) { 214 return t.tokentype == ETokenType.ttsimplecomment || t.tokentype == ETokenType.ttbracketedcomment; 215 } 216 217 private enum TokenClass { WORD, OP, DOT, COMMA, PAREN_LEFT, PAREN_RIGHT, SEMICOLON, OTHER } 218 219 private static TokenClass classify(TSourceToken t, String normalizedText) { 220 switch (t.tokentype) { 221 case ttidentifier: 222 case ttdqstring: 223 case ttdbstring: 224 case ttbrstring: 225 case ttnumber: 226 case ttsqstring: 227 case ttkeyword: 228 case ttnonreservedkeyword: 229 case ttbindvar: 230 case ttsqlvar: 231 case ttsubstitutionvar: 232 return TokenClass.WORD; 233 case ttperiod: 234 return TokenClass.DOT; 235 case ttcomma: 236 return TokenClass.COMMA; 237 case ttleftparenthesis: 238 return TokenClass.PAREN_LEFT; 239 case ttrightparenthesis: 240 return TokenClass.PAREN_RIGHT; 241 case ttsemicolon: 242 case ttsemicolon2: 243 case ttsemicolon3: 244 return TokenClass.SEMICOLON; 245 case ttequals: 246 case ttplussign: 247 case ttminussign: 248 case ttasterisk: 249 case ttslash: 250 case ttgreaterthan: 251 case ttlessthan: 252 case ttsinglecharoperator: 253 case ttmulticharoperator: 254 case ttconcatenationop: 255 return TokenClass.OP; 256 default: 257 break; 258 } 259 // Heuristic: treat UNKNOWN single-char punctuation as operator 260 if (normalizedText.length() == 1 && !Character.isLetterOrDigit(normalizedText.charAt(0))) { 261 return TokenClass.OP; 262 } 263 return TokenClass.OTHER; 264 } 265 266 private static boolean shouldAddSpaceBefore(TokenClass prev, TokenClass curr, char lastAppended) { 267 if (prev == null) return false; 268 if (lastAppended == '\0') return false; 269 270 // No space rules 271 if (curr == TokenClass.DOT || curr == TokenClass.COMMA || curr == TokenClass.PAREN_RIGHT) return false; 272 if (prev == TokenClass.DOT || prev == TokenClass.PAREN_LEFT) return false; 273 274 // Space around operators and between words 275 if (prev == TokenClass.OP && (curr == TokenClass.WORD || curr == TokenClass.PAREN_LEFT)) return true; 276 if ((prev == TokenClass.WORD || prev == TokenClass.PAREN_RIGHT) && (curr == TokenClass.OP || curr == TokenClass.WORD)) return true; 277 278 // After comma ensure a space before next word 279 if (prev == TokenClass.COMMA && (curr == TokenClass.WORD || curr == TokenClass.PAREN_LEFT)) return true; 280 281 // Default: no space 282 return false; 283 } 284 285 private String normalizeTokenText(TSourceToken t, boolean idCaseSensitive, SqlNormalizationProfile profile) { 286 String s = t.toString(); 287 288 // Minimal operator unification: != => <> 289 if (t.tokentype == ETokenType.ttmulticharoperator || t.tokentype == ETokenType.ttsinglecharoperator || 290 t.tokentype == ETokenType.ttgreaterthan || t.tokentype == ETokenType.ttlessthan) { 291 if ("!=".equals(s)) { 292 return "<>"; 293 } 294 return s; 295 } 296 297 switch (t.tokentype) { 298 case ttsimplecomment: 299 case ttbracketedcomment: 300 return null; // removed 301 case ttkeyword: 302 case ttnonreservedkeyword: 303 return s.toUpperCase(java.util.Locale.ROOT); 304 case ttidentifier: { 305 // regular identifier 306 return idCaseSensitive ? s : s.toUpperCase(java.util.Locale.ROOT); 307 } 308 case ttdqstring: 309 case ttdbstring: 310 case ttbrstring: { 311 // delimited/quoted identifier -> remove quotes, then apply case rule 312 String unquoted = TBaseType.removeQuoteChar(s); 313 return idCaseSensitive ? unquoted : unquoted.toUpperCase(java.util.Locale.ROOT); 314 } 315 case ttsqstring: { 316 if (profile == SqlNormalizationProfile.GROUPING_FRIENDLY && looksLikeDateOrTimestampLiteral(s)) { 317 return "'1970-01-01'"; 318 } 319 return s; // keep string literal as-is 320 } 321 default: 322 return s; 323 } 324 } 325 326 private static boolean looksLikeDateOrTimestampLiteral(String s) { 327 // Very lightweight check for common SQL string date/timestamp formats, e.g. '2025-09-14' or '2025-09-14 12:34:56' 328 // Input includes surrounding quotes per token text. 329 if (s == null || s.length() < 2) return false; 330 if (!(s.charAt(0) == '\'' && s.charAt(s.length() - 1) == '\'')) return false; 331 String inner = s.substring(1, s.length() - 1).trim(); 332 // yyyy-mm-dd or yyyy-mm-dd hh:mm[:ss[.fff]] 333 if (inner.matches("\\d{4}-\\d{2}-\\d{2}")) return true; 334 if (inner.matches("\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?")) return true; 335 return false; 336 } 337 338 private static String sha256Hex(String input) { 339 try { 340 MessageDigest md = MessageDigest.getInstance("SHA-256"); 341 byte[] out = md.digest(input.getBytes(StandardCharsets.UTF_8)); 342 char[] hex = new char[out.length * 2]; 343 final char[] digits = "0123456789abcdef".toCharArray(); 344 for (int i = 0, j = 0; i < out.length; i++) { 345 int b = out[i] & 0xFF; 346 hex[j++] = digits[(b >>> 4) & 0x0F]; 347 hex[j++] = digits[b & 0x0F]; 348 } 349 return new String(hex); 350 } catch (NoSuchAlgorithmException e) { 351 // Should never happen on a standard JVM 352 throw new RuntimeException("SHA-256 not available", e); 353 } 354 } 355 356 private String queryId; 357 358 public void setQueryId(String queryId) { 359 this.queryId = queryId; 360 } 361 362 /** 363 * Retrieves the unique and stable identifier for this SQL statement. 364 * <p> 365 * The queryId provides a reliable way to reference any statement, including subqueries, 366 * within a parsed SQL script. It is generated hierarchically based on the statement's 367 * position within the Abstract Syntax Tree (AST), ensuring that the ID is reproducible 368 * across identical SQL inputs. 369 * <p> 370 * <b>ID Format:</b> 371 * <ul> 372 * <li>A top-level statement has an ID like {@code "stmt_0_select"}, where {@code 0} is the index 373 * of the statement in the script and {@code select} is the statement type.</li> 374 * <li>A nested statement will have a path-like ID that includes its parent's ID. For example, 375 * an {@code INSERT} statement containing a {@code SELECT} subquery might have an ID for the 376 * subquery like {@code "stmt_0_insert#stmt_1_select"}.</li> 377 * </ul> 378 * This identifier is particularly useful for tasks like data lineage analysis, where tracking 379 * the origin and transformation of data through various statements is required. 380 * 381 * @return The unique query identifier string for this statement, or {@code null} if it has not been set. 382 */ 383 public String getQueryId() { 384 return queryId; 385 } 386 387 public void setUsingVariableList(TColumnDefinitionList usingVariableList) { 388 this.usingVariableList = usingVariableList; 389 } 390 391 private TColumnDefinitionList usingVariableList; 392 393 /* 394 * Variables defined in teradata using clause. 395 * */ 396 public TColumnDefinitionList getUsingVariableList() { 397 return usingVariableList; 398 } 399 400 protected ArrayList<TAttributeNode> relationAttributes = new ArrayList<>(); 401 402 @Override 403 public ArrayList<TAttributeNode> getAttributes(){ 404 // if (relationAttributes.size() != 0) return relationAttributes; 405 relationAttributes.clear(); 406 for(TTable table:relations){ 407 //relationAttributes.addAll(table.getAttributes()); 408 TAttributeNode.addAllNodesToList(table.getAttributes(),relationAttributes); 409 } 410 411 return relationAttributes; 412 } 413 414 @Override 415 public String getRelationName(){ 416 return null; 417 } 418 419 @Override 420 public int size(){ 421 return relationAttributes.size(); 422 } 423 424 @Override 425 public String toScript(){ 426 String ret = super.toScript(); 427 if ((ret == null)||(ret.isEmpty())){ 428 ret = this.toString(); 429 }else{ 430 if ((this.getEndToken() != null) && (this.getEndToken().tokencode == ';')) { 431 if (!ret.endsWith(";")){ 432 ret = ret + ";"; 433 } 434 } 435 } 436 return ret; 437 } 438 439 protected TFromClause fromClause; 440 441 public void setFromClause(TFromClause fromClause) { 442 this.fromClause = fromClause; 443 } 444 445 public TFromClause getFromClause() { 446 return fromClause; 447 } 448 449 /** 450 * Relations that used in from clause of select statement. 451 * Or tables of other statements such as insert, update, delete and etc 452 * 453 * Please use this property to get the relations instead of {@link #getTables()} and {@link #getJoins()}after version 2.7.4.0 454 * 455 * when a join is used in from clause, then the table in getRelations() is type of ETableSource.join, and you can 456 * use TTable.getJoinExpr() to get this join. 457 * 458 * @return 459 */ 460 public ArrayList<TTable> getRelations() { 461 return relations; 462 } 463 464 private ArrayList<TTable> relations = new ArrayList<>(); 465 466 protected TTable fromSourceTable; 467 468 /** 469 * This is table in from clause if only one table is listed in the from clause, 470 * If more than one table is listed in from clause, please check {@link #getFromSourceJoin()} instead. 471 * 472 * @return table in from clause 473 */ 474 public TTable getFromSourceTable() { 475 return fromSourceTable; 476 } 477 478 /** 479 * This is a join in from clause, including left and right relation. 480 * If only a single table is listed in from clause, please use {@link #getFromSourceTable()} instead 481 * @return 482 */ 483 public TJoinExpr getFromSourceJoin() { 484 return fromSourceJoin; 485 } 486 487 protected TJoinExpr fromSourceJoin; 488 489 private String asCanonicalText = null; 490 491 /** 492 * this method return a canonical form of a SQL statement in plan text. 493 * <br>1. remove all comment inside SQL query. 494 * <br>2. remove redundant parenthesis at the begin/end of a select statement. 495 * <br>3. replace all number in where clause with 999 constant 496 * <br>4. replace all string constant in where clause with 'placeholder_str' 497 * <br>5. all number elements in a list such as (1,2,3,4) will be change to a single element (999) 498 * <br>6. all string elements in a list such as ('a','b','c','d') will be change to a single element ('placeholder_str') 499 * 500 * @return a canonical form of a SQL statement in plan text. 501 */ 502 public String asCanonical(){ 503 if (asCanonicalText != null) return asCanonicalText; 504 505 String ret = null; 506 TSourceToken lcStartToken = getStartToken(); 507 if (lcStartToken == null) return toString(); 508 TSourceToken lcEndToken = getEndToken(); 509 if (lcEndToken == null) return toString(); 510 511 // remove the ; token at the end of statement 512 if (lcEndToken.tokencode == ';') lcEndToken.tokenstatus = ETokenStatus.tsdeleted; 513 514 515 // remove ( ) at the begin and end of the statement 516 TSourceToken lcCurrentToken = lcStartToken; 517 while (lcCurrentToken != null){ 518 if (lcCurrentToken.tokencode != '(') { 519 break; 520 }else{ 521 if (lcCurrentToken.getLinkToken() != null){ 522 lcCurrentToken.tokenstatus = ETokenStatus.tsdeleted; 523 lcCurrentToken.getLinkToken().tokenstatus = ETokenStatus.tsdeleted; 524 } 525 } 526 527 if (lcCurrentToken.equals(lcEndToken)){ 528 break; 529 }else{ 530 lcCurrentToken = lcCurrentToken.getNextTokenInChain(); 531 } 532 } 533 534 // change constant to placeholder, all number change to 999 and string constant change to placeholder_str 535 constantVisitor cv = new constantVisitor(); 536 this.acceptChildren(cv); 537 538 539 boolean chainUnchanged = true, includingComment = false; 540 StringBuffer sb = new StringBuffer(""); 541 TSourceToken lcPrevSt = null; 542 boolean ignoreNextReturnToken = false, isChainModified = false; 543 544 lcCurrentToken = lcStartToken; 545 while (lcCurrentToken != null){ 546 if((lcCurrentToken.tokenstatus == ETokenStatus.tsdeleted) 547 ||(!includingComment && ((lcCurrentToken.tokencode == TBaseType.cmtslashstar) ||(lcCurrentToken.tokencode == TBaseType.cmtdoublehyphen))) 548 ){ 549 // ignore this token, do nothing 550 //System.out.println("out: ignore deleted token:"+lcCurrentToken.astext); 551 }else{ 552 // 553 sb.append(lcCurrentToken.toString()); 554 if (lcCurrentToken.isChangedInAsCanonical()){ 555 lcCurrentToken.restoreText(); 556 } 557 } 558 559 if (lcCurrentToken.equals(lcEndToken)){ 560 break; 561 }else{ 562 lcCurrentToken = lcCurrentToken.getNextTokenInChain(); 563 } 564 565 } 566 asCanonicalText = sb.toString(); 567 return asCanonicalText; 568 } 569 570 private TCTE cteIncludeThisStmt = null; 571 572 public void setCteIncludeThisStmt(TCTE cteIncludeThisStmt) { 573 this.cteIncludeThisStmt = cteIncludeThisStmt; 574 } 575 576 public TCTE getCteIncludeThisStmt() { 577 return cteIncludeThisStmt; 578 } 579 580 private TreeMap<String,TResultColumn> expandedResultColumns = null; 581 582 public TreeMap<String,TResultColumn> getExpandedResultColumns() { 583 if (expandedResultColumns == null){ 584 expandedResultColumns = new TreeMap<>(); 585 } 586 return expandedResultColumns; 587 } 588 589 public TSQLFunction searchFunctionInSQLEnv(String functionName){ 590 if (getSqlEnv() == null) return null; 591 return getSqlEnv().searchFunction(functionName); 592 } 593 594 public TSQLEnv getSqlEnv() { 595 if (getGlobalScope() == null) return null; 596 return getGlobalScope().getSqlEnv(); 597 } 598 599 public TGlobalScope getGlobalScope() { 600 TGlobalScope lcResult = null; 601 // the frames are popped once the statement is parsed: lineage asks after that 602 if ((frameStack != null) && (!frameStack.isEmpty())){ 603 if (frameStack.get(0) != null){ 604 lcResult = (TGlobalScope)frameStack.get(0).getScope(); 605 } 606 } 607 return lcResult; 608 } 609 610 private Stack<TFrame> frameStack; 611 612 public void setFrameStack(Stack<TFrame> frameStack) { 613 this.frameStack = frameStack; 614 } 615 616 public Stack<TFrame> getFrameStack() { 617 return frameStack; 618 } 619 620 private TPTNodeList<TColumnWithSortOrder> indexColumns = null; 621 622 public TPTNodeList<TColumnWithSortOrder> getIndexColumns() { 623 return indexColumns; 624 } 625 626 private Stack<TObjectName> variableStack = null; 627 628 public void setVariableStack(Stack<TObjectName> variableStack) { 629 this.variableStack = variableStack; 630 } 631 632 public Stack<TObjectName> getVariableStack() { 633 if (variableStack == null){ 634 variableStack = new Stack<TObjectName>(); 635 } 636 637 return variableStack; 638 } 639 640 private Stack<TDaxFunction> daxFunctionStack = null; 641 642 public Stack<TDaxFunction> getDaxFunctionStack() { 643 if (daxFunctionStack == null){ 644 daxFunctionStack = new Stack<TDaxFunction>(); 645 } 646 return daxFunctionStack; 647 } 648 649 private TObjectName labelName; 650 651 public void setLabelName(TObjectName lName) { 652 labelName = lName; 653 if (labelName != null){ 654 //labelName.setObjectType(TObjectName.ttobjLabelName); 655 labelName.setDbObjectType(EDbObjectType.label); 656 } 657 } 658 659 /** 660 * 661 * @return label name used in plsql statement. 662 */ 663 public TObjectName getLabelName() { 664 665 return labelName; 666 } 667 668 669 private TObjectName endlabelName; 670 671 public void setEndlabelName(TObjectName endlabelName) { 672 this.endlabelName = endlabelName; 673 } 674 675 public TObjectName getEndlabelName() { 676 677 return endlabelName; 678 } 679 680 /** 681 * Type of this statement. 682 */ 683 public ESqlStatementType sqlstatementtype; 684 /** 685 * Source tokens included in this statement. only source tokens available when this is a top level statement, otherwise, there is no source token in this statement. 686 * Please check {@link gudusoft.gsqlparser.nodes.TParseTreeNode#getStartToken()}, and {@link gudusoft.gsqlparser.nodes.TParseTreeNode#getEndToken()} of this statement. 687 */ 688 public TSourceTokenList sourcetokenlist; 689 690 public TSourceTokenList getTokenList() { 691 return sourcetokenlist; 692 } 693 /** 694 * Parser used to parse this statement. 695 */ 696 public TCustomParser parser; 697 /** 698 * PLSQL parser used to parse this statement. 699 */ 700 public TCustomParser plsqlparser; 701 /** 702 * Tag used by parser internally. 703 */ 704 public int dummytag; 705 706 /** 707 * target table in the delete/insert/update/create table statement. 708 * @see #joins 709 * @see TSelectSqlStatement 710 * @see TDeleteSqlStatement 711 * @see TUpdateSqlStatement 712 * @see TCreateTableSqlStatement 713 * @see gudusoft.gsqlparser.stmt.TMergeSqlStatement 714 */ 715 public TTable getTargetTable() { 716 return targetTable; 717 } 718 719 public void setTargetTable(TTable targetTable) { 720 setNewSubNode(this.targetTable,targetTable,getAnchorNode()); 721 this.targetTable = targetTable; 722 } 723 724 private TTable targetTable ; 725 726 /** 727 * joins represents table sources in the from clause. All structure information was reserved. 728 * <p>SQL 1: 729 * <p><blockquote><pre>select f from t1</pre></blockquote> 730 * <p>size of joins will be 1, t1 can be fetch via joins.getJoin(0).getTable() 731 * <p> 732 * <p>SQL 2: 733 * <p><blockquote><pre>select f from t1,t2</pre></blockquote> 734 * <p>size of joins will be 2, 735 * <p>t1 can be fetch via joins.getJoin(0).getTable() 736 * <p>t2 can be fetch via joins.getJoin(1).getTable() 737 * <p> 738 * <p>SQL 3: 739 * <p><blockquote><pre>select f from t1 join t2 on t1.f1 = t2.f1</pre></blockquote> 740 * <p>size of joins will be 1, 741 * <p>t1 information can be fetch via joins.getJoin(0).getTable() 742 * <p>In order to access t2, we need to introduce a new class {@link TJoinItem} which includes all information about t2 and join condition. 743 * <p>There is a property named joinItems of {@link TJoin} which is type of {@link TJoinItemList} that includes a list of {@link TJoinItem}. 744 * <p>this property can be access via {@link gudusoft.gsqlparser.nodes.TJoin#getJoinItems()}. 745 * <p>Now, t2 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(0).getTable() 746 * <p> 747 * <p>SQL 4: 748 * <p><blockquote><pre>select f from t1 join t2 on t1.f1 = t2.f1 join t3 on t1.f1 = t3.f1</pre></blockquote> 749 * <p>size of joins will be 1, 750 * <p>t1 can be fetch via joins.getJoin(0).getTable() 751 * <p>t2 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(0).getTable() 752 * <p>t3 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(1).getTable() 753 * 754 * @see #tables 755 */ 756 public TJoinList joins; 757 758 /** 759 * Provides a quick way to access all tables involved in this SQL statement. 760 * <p>It stores all tables in a flat way while {@link #joins} stores all tables in a hierarchical structure. 761 * <p>joins only represents tables in from clause of select/delete statement, and tables in update/insert statement. 762 * <p>{@link #tables} includes all tables in all types of SQL statements such as tables involved in a create table or create trigger statements. 763 */ 764 public TTableList tables; 765 766 public TJoinList getJoins() { 767 return joins; 768 } 769 770 public TTableList getTables() { 771 return tables; 772 } 773 774 /** 775 * Saves all first level sub statements. 776 * <p>By iterating statements recursively, you can fetch all included statements in an easy way. 777 * <p><blockquote><pre> 778 * select f1+(select f2 from t2) from t1 779 * where f2 > all (select f3 from t3 where f4 = (select f5 from t4))</pre> 780 * </blockquote> 781 * <p> Statements included in above SQL was save in a hierarchical way like this: 782 * <ul> 783 * <li>(select f2 from t2)</li> 784 * <li>(select f3 from t3 where f4 = (select f5 from t4)) 785 * <ul> 786 * <li>(select f5 from t4)</li> 787 * </ul> 788 * </li> 789 * </ul> 790 * <p>If this statement is a create procedure/function statement, then all declaration statements and statements in 791 * procedure body can also be fetched quickly by iterating this property recursively. 792 * 793 * 794 */ 795 public TStatementList getStatements() { 796 if (statements == null){ 797 statements = new TStatementList(); 798 } 799 return statements; 800 } 801 802 private TStatementList statements; 803 804 public void setCteList(TCTEList cteList) { 805 setNewSubNode(this.cteList,cteList,getAnchorNode()); 806 this.cteList = cteList; 807 } 808 809 /** 810 * Multiple common table expressions {@link TCTE} can be specified following the single WITH keyword. 811 *<p> Each common table expression specified can also be referenced by name in the FROM clause of subsequent common table expressions. 812 * 813 * <p>Used in select, delete, update statement. 814 * @return List of common table expression. 815 */ 816 817 public TCTEList getCteList() { 818 819 return cteList; 820 } 821 822 private TCTEList cteList = null; 823 824 public void setResultColumnList(TResultColumnList resultColumnList) { 825 setNewSubNode(this.resultColumnList,resultColumnList,getAnchorNode()); 826 this.resultColumnList = resultColumnList; 827 } 828 829 /** 830 * In select statement, this method returns Items in select_list. 831 * Can be *, expr, and name.* 832 * <br><br> 833 * In update statement, this method returns assignments in set clause. 834 * 835 * @return select list of select statement or assignments of update statement. 836 */ 837 public TResultColumnList getResultColumnList() { 838 839 return resultColumnList; 840 } 841 842 private TResultColumnList resultColumnList = null; 843 844 private TWhereClause whereClause = null; 845 private TTopClause topClause = null; 846 private TOutputClause outputClause = null; 847 private TReturningClause returningClause = null; 848 849 public void setReturningClause(TReturningClause returningClause) { 850 setNewSubNode(this.returningClause,returningClause,getAnchorNode()); 851 this.returningClause = returningClause; 852 } 853 854 /** 855 * @return {@link TReturningClause returning clause.} 856 */ 857 858 public TReturningClause getReturningClause() { 859 860 return returningClause; 861 } 862 863 public void setOutputClause(TOutputClause outputClause) { 864 setNewSubNode(this.outputClause,outputClause,getAnchorNode()); 865 this.outputClause = outputClause; 866 } 867 868 /** 869 * @return output clause. 870 */ 871 872 public TOutputClause getOutputClause() { 873 874 return outputClause; 875 } 876 877 public void setTopClause(TTopClause topClause) { 878 setNewSubNode(this.topClause,topClause,getAnchorNode()); 879 this.topClause = topClause; 880 } 881 882 /** 883 * @return {@link TTopClause top clause.} 884 */ 885 public TTopClause getTopClause() { 886 return topClause; 887 } 888 889 public void setWhereClause(TWhereClause newWhereClause){ 890 setNewSubNode(this.whereClause ,newWhereClause,getAnchorNode()); 891 this.whereClause = newWhereClause; 892 } 893 894 895 /** 896 * @deprecated As of 2.0.9.0, use {@link #setWhereClause(TWhereClause)} instead 897 * Or, use {@link TWhereClause#setText(String)} 898 * 899 * @param condition 900 * @return 901 */ 902 public TWhereClause addWhereClause(String condition){ 903 return this.whereClause; 904 } 905 906 /** 907 * restrict the rows selected to those that satisfy one or more conditions. 908 * used in select, delete, update statement. 909 * @return {@link TWhereClause where clause.} 910 */ 911 public TWhereClause getWhereClause() { 912 return whereClause; 913 } 914 915 public void setAlreadyAddToParent(boolean alreadyAddToParent) { 916 this.alreadyAddToParent = alreadyAddToParent; 917 } 918 919 private boolean alreadyAddToParent = false; 920 921 /** True while a table's point in time (AS OF, AT) is parsed; see linkColumnToTable. */ 922 private boolean parsingPointInTime = false; 923 924 private boolean ableToIncludeCTE(ESqlStatementType sst){ 925 return ((sst == ESqlStatementType.sstselect) 926 ||(sst == ESqlStatementType.sstupdate) 927 ||(sst == ESqlStatementType.sstinsert) 928 ||(sst == ESqlStatementType.sstdelete) 929 ); 930 } 931 932 private TCTEList cteListInAllLevels = new TCTEList(); 933 934 protected TCTEList searchCTEList(Boolean stopAtFirstFinding){ 935 cteListInAllLevels.clear(); 936 if (cteList != null ) { 937 cteListInAllLevels.addAll(cteList); 938 if (stopAtFirstFinding) return cteListInAllLevels; 939 } 940 941 TCustomSqlStatement lcParent = this.parentStmt; 942 while (lcParent != null){ 943 if (!ableToIncludeCTE(lcParent.sqlstatementtype)) break; 944 945 if (lcParent.cteList != null) { 946 cteListInAllLevels.addAll(lcParent.cteList); 947 if (stopAtFirstFinding) break; 948 } 949 lcParent = lcParent.parentStmt; 950 } 951 return cteListInAllLevels; 952 } 953 954 955// protected TCTEList searchCTEList(){ 956// TCTEList ret = null; 957// if (cteList != null ) {return cteList;} 958// TCustomSqlStatement lcParent = this.parentStmt; 959// while (lcParent != null){ 960// if (!ableToIncludeCTE(lcParent.sqlstatementtype)) break; 961// ret = lcParent.cteList; 962// if (ret != null) break; 963// lcParent = lcParent.parentStmt; 964// } 965// return ret; 966// } 967 968 public TCustomSqlStatement getParentStmt() { 969 return parentStmt; 970 } 971 972 public TParseTreeNode getParentObjectName(){ 973 TParseTreeNode result = super.getParentObjectName(); 974 if (result != null) return result; 975 return getParentStmt(); 976 } 977 978 public void setParentStmt(TCustomSqlStatement parentStmt) { 979 if (!alreadyAddToParent){ 980 this.parentStmt = parentStmt; 981 if (this.parentStmt != null){ 982 parentStmt.getStatements().add(this); 983 alreadyAddToParent = true; 984 } 985 } 986 } 987 988 public void setParentStmtToNull() { 989 this.parentStmt = null; 990 } 991 992 private TCustomSqlStatement ancestorStmt = null; 993 994 public TCustomSqlStatement getAncestorStmt() { 995 TCustomSqlStatement lcRet = this; 996 while (lcRet.getParentStmt() != null){ 997 lcRet = lcRet.getParentStmt(); 998 } 999 return lcRet; 1000 } 1001 1002 /** 1003 * parent statement of this statement if any 1004 */ 1005 private TCustomSqlStatement parentStmt = null; 1006 1007 /** 1008 * Original Parse tree node from parser 1009 */ 1010 public TParseTreeNode rootNode; 1011 1012 private Stack symbolTable = null; 1013 1014 /** 1015 * 1016 * @deprecated since ver 2.5.3.5, please use {@link TStmtScope} instead 1017 */ 1018 public Stack getSymbolTable() { 1019 if (symbolTable == null){ 1020 symbolTable = new Stack(); 1021 } 1022 return symbolTable; 1023 } 1024 1025 public TSourceToken semicolonended; 1026 public boolean isctequery; 1027 private ArrayList <TSyntaxError> syntaxErrors; 1028 1029 public ArrayList<TSyntaxError> getSyntaxErrors() { 1030 return syntaxErrors; 1031 } 1032 1033 public String getErrormessage(){ 1034 1035 String s="",hint="Syntax error"; 1036 TSyntaxError t; 1037 for (int i= 0; i< syntaxErrors.size(); i++) 1038 { 1039 t = (TSyntaxError) syntaxErrors.get(i); 1040 if (t.hint.length() > 0) hint = t.hint; 1041 s= s+hint+"("+t.errorno+") near: "+t.tokentext; 1042 s=s+"("+t.lineNo; 1043 s=s+","+t.columnNo +")"; 1044 //s=s+" expected tokentext:"+t.hint; 1045 1046 // break;//get only one message, remove this one and uncomment next line to get all error messages 1047 if (i != syntaxErrors.size() - 1) 1048 s = s +TBaseType.linebreak; 1049 } 1050 1051 return s; 1052 } 1053 1054 public ArrayList<TSyntaxError> getSyntaxHints() { 1055 return syntaxHints; 1056 } 1057 1058 private ArrayList <TSyntaxError> syntaxHints; 1059 1060 protected boolean isparsed; 1061 TSourceToken _semicolon; 1062 1063 /** 1064 * Number of syntax errors for this statement. 1065 * @return 0 means no syntax error. 1066 */ 1067 public int getErrorCount() { 1068 return syntaxErrors.size(); 1069 } 1070 1071 1072 public TCustomSqlStatement(EDbVendor dbvendor){ 1073 super(); 1074 this.dbvendor = dbvendor; 1075 sqlstatementtype = ESqlStatementType.sstunknown; 1076 dummytag = 0; 1077 sourcetokenlist = new TSourceTokenList(); 1078 syntaxErrors = new ArrayList<TSyntaxError>(4); 1079 syntaxHints = new ArrayList<TSyntaxError>(4); 1080 tables = new TTableList(); 1081 joins = new TJoinList(); 1082 indexColumns = new TPTNodeList<TColumnWithSortOrder>(); 1083 } 1084 1085 /** 1086 * Log error messages if syntax errors found while parsing this statement. 1087 * @param se syntax error structure. 1088 * @return type of error 1089 */ 1090 public EActionOnParseError parseerrormessagehandle(TSyntaxError se){ 1091 if (se.errortype == EErrorType.sphint){ 1092 this.getAncestorStmt().syntaxHints.add(se); 1093 }else 1094 this.getAncestorStmt().syntaxErrors.add(se); 1095 return EActionOnParseError.aopcontinue; 1096 } 1097 1098 public int parsestatement(TCustomSqlStatement pparentsql,boolean isparsetreeavailable){ 1099 return parsestatement(pparentsql,isparsetreeavailable,false); 1100 } 1101 1102 /** 1103 * Parse this statement. 1104 * @param pparentsql 1105 * @param isparsetreeavailable 1106 * @return parse result, zero means no syntax error found. 1107 */ 1108 public int parsestatement(TCustomSqlStatement pparentsql,boolean isparsetreeavailable, boolean onlyNeedRawParseTree){ 1109 int ret = 0; 1110 isparsed = false; 1111 if (!isparsetreeavailable){ 1112 ret = checksyntax(pparentsql); 1113 } 1114 if (ret == 0) 1115 { 1116 isparsed = true; 1117 if (!onlyNeedRawParseTree){ 1118 ret = doParseStatement(pparentsql); 1119 } 1120 }else if ((dbvendor == EDbVendor.dbvsybase)||(dbvendor == EDbVendor.dbvsybasease || dbvendor == EDbVendor.dbvsqlanywhere || dbvendor == EDbVendor.dbvsybaseiq)){ 1121 if ((this.rootNode != null)&& 1122 ((sqlstatementtype == ESqlStatementType.sstmssqlcreateprocedure) 1123 ||(sqlstatementtype == ESqlStatementType.sstmssqlcreatefunction) 1124 ||(sqlstatementtype == ESqlStatementType.sstcreatetrigger) 1125 )){ 1126 if (!onlyNeedRawParseTree){ 1127 doParseStatement(pparentsql); 1128 } 1129 1130 } 1131 } 1132 return ret; 1133 } 1134 1135 public boolean OracleStatementCanBeSeparatedByBeginEndPair(){ 1136 return ( 1137 1138 (this.sqlstatementtype == ESqlStatementType.sstplsql_createprocedure) 1139 //|| (this.sqlstatementtype == ESqlStatementType.sst_block_with_label) 1140 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createfunction) 1141 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createpackage) 1142 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtype_placeholder) 1143 ||(this.sqlstatementtype == ESqlStatementType.sstoraclecreatepackagebody) 1144 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtrigger) 1145// ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtypebody) 1146// ||(this.sqlstatementtype == ESqlStatementType.sstplsql_tabletypedef) 1147 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_varraytypedef) 1148 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createprocedure) 1149 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_execimmestmt) 1150 ||(this.sqlstatementtype == ESqlStatementType.sstoraclecreatelibrary) 1151 ); 1152 } 1153 1154 public boolean VerticaStatementCanBeSeparatedByBeginEndPair(){ 1155 return ( 1156 1157 (this.sqlstatementtype == ESqlStatementType.sstcreatefunction) 1158 ); 1159 } 1160 1161 public boolean isnzplsql(){ 1162 return ( 1163 (this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1164 ); 1165 } 1166 1167 public boolean ispgplsql(){ 1168 return (this instanceof TCommonBlock) 1169 ||(this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1170 ||(this.sqlstatementtype == ESqlStatementType.sstcreatefunction) 1171 ||(this.sqlstatementtype == ESqlStatementType.sstDoExecuteBlock) 1172 ; 1173 } 1174 1175 public boolean isGaussDBStoredProcedure(){ 1176 return (this instanceof TCommonBlock) 1177 ||(this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1178 ||(this.sqlstatementtype == ESqlStatementType.sstcreatefunction) 1179 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createpackage) 1180 ||(this.sqlstatementtype == ESqlStatementType.sstoraclecreatepackagebody) 1181 ||(this.sqlstatementtype == ESqlStatementType.sstDoExecuteBlock) 1182 ||(this.sqlstatementtype == ESqlStatementType.sstcreatetrigger) 1183 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtypebody) 1184 ; 1185 } 1186 1187 public boolean isdatabricksplsql(){ 1188 return (this instanceof TCommonBlock) 1189 ; 1190 } 1191 1192 public boolean isgreeplumplsql(){ 1193 return (this instanceof TCommonBlock) 1194 ||(this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1195 ||(this.sqlstatementtype == ESqlStatementType.sstcreatefunction) 1196 ||(this.sqlstatementtype == ESqlStatementType.sstDoExecuteBlock) 1197 ; 1198 } 1199 1200 public boolean isathenaplsql(){ 1201 return (this instanceof TCommonBlock) 1202 ; 1203 } 1204 1205 public boolean isprestoplsql(){ 1206 return (this instanceof TCommonBlock) 1207 ; 1208 } 1209 1210 public boolean issnowflakeplsql(){ 1211 return ((this instanceof TCommonBlock) 1212 ||(this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1213 ); 1214 } 1215 1216 public boolean isBigQueryplsql(){ 1217 return ((this instanceof TCommonBlock) 1218 ||(this.sqlstatementtype == ESqlStatementType.sstcreateprocedure) 1219 ); 1220 } 1221 1222 public boolean isverticaplsql(){ 1223 return ( 1224 (this.sqlstatementtype == ESqlStatementType.sstcreatefunction) 1225 ); 1226 } 1227 1228 public boolean isoracleplsql(){ 1229 return ( 1230 (this.sqlstatementtype == ESqlStatementType.sst_plsql_block) 1231 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createprocedure) 1232 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createfunction) 1233 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createpackage) 1234 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtype_placeholder) 1235 ||(this.sqlstatementtype == ESqlStatementType.sstoraclecreatepackagebody) 1236 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtrigger) 1237 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createtypebody) 1238 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_tabletypedef) 1239 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_varraytypedef) 1240 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_createprocedure) 1241 ||(this.sqlstatementtype == ESqlStatementType.sstplsql_execimmestmt) 1242 ||(this.sqlstatementtype == ESqlStatementType.sstoraclecreatelibrary) 1243 ); 1244 } 1245 1246 int checksyntax(TCustomSqlStatement psql){ 1247 return dochecksyntax(psql); 1248 } 1249 1250 protected int dochecksyntax(TCustomSqlStatement psql){ 1251 int ret = -1; 1252 clear(); 1253 if (sourcetokenlist.size() == 0) return ret; 1254 1255// TCustomParser lcparser; 1256// lcparser = new TLzParserOracleSql(sourcetokenlist); 1257// lcparser.sql = this; 1258// ret = lcparser.yyparse(); 1259 1260 1261 if (((this.dbvendor == EDbVendor.dbvoracle)||(this.dbvendor == EDbVendor.dbvoceanbase))&&(this.isoracleplsql()&&(plsqlparser!=null)) 1262// || ((this.dbvendor == EDbVendor.dbvgaussdb) // gaussdb 中用 oracle plsql 写的存储过程,用 oracle plsql parser 来解析 1263// &&( 1264// ((this instanceof TCreateFunctionStmt)&&(((TCreateFunctionStmt)this).isGaussDBSpInOracle())) 1265// ||((this instanceof TCreateProcedureStmt)&&(((TCreateProcedureStmt)this).isGaussDBSpInOracle())) 1266// ||(this instanceof TPlsqlCreatePackage) 1267// ) 1268// ) 1269 ){ 1270 plsqlparser.sql = this; 1271// if (this.dbvendor == EDbVendor.dbvgaussdb){ 1272// // 原来用 gaussDB lexer tokenize 的 token 需要用 Oracle lexer 重新 tokenize 一边 1273// String sqlText=""; 1274// for(int k = 0;k<sourcetokenlist.size();k++){ 1275// sqlText = sqlText + sourcetokenlist.get(k).toString(); 1276// } 1277// // TODO, need to use singleton pattern to get a single instance of Oracle parser. 1278// TGSqlParser sqlParser = new TGSqlParser(EDbVendor.dbvoracle); 1279// // keep coordinate of the origin query 1280// long originalLineNo = sourcetokenlist.get(0).lineNo; 1281// long originalColumnNo = sourcetokenlist.get(0).columnNo; 1282// sqlParser.sqltext = TBaseType.stringBlock((int) originalLineNo - 1,(int) originalColumnNo - 1)+ sqlText;; 1283// 1284// int r = sqlParser.getrawsqlstatements(); 1285// sourcetokenlist.clear(); 1286// for(int k=0;k<sqlParser.sourcetokenlist.size();k++){ 1287// sourcetokenlist.add(sqlParser.sourcetokenlist.get(k)); 1288// } 1289// } 1290 1291 plsqlparser.sourcetokenlist = sourcetokenlist; 1292 1293 if ((this instanceof TCommonStoredProcedureSqlStatement) 1294 &&((TCommonStoredProcedureSqlStatement)this).isWrapped()){ 1295 // don't parse wrapped oracle plsql 1296 ret = 0; 1297 this.rootNode = this; 1298 }else { 1299 ret = plsqlparser.yyparse(); 1300 this.rootNode = plsqlparser.rootNode; 1301 } 1302 } 1303 else{ 1304 if ((this.sqlstatementtype == ESqlStatementType.sstExplain)&&(dbvendor != EDbVendor.dbvhana)){ 1305 // EXPLAIN PLAN ... FOR statement; only parse token after FOR keyword 1306 boolean isFoundStopToken = false; 1307 1308 for(int k=0;k<sourcetokenlist.size();k++){ 1309 TSourceToken st = sourcetokenlist.get(k); 1310 switch (dbvendor){ 1311 case dbvoracle: 1312 if (st.tokencode == TBaseType.rrw_for) { 1313 st.tokencode = TBaseType.sqlpluscmd; 1314 isFoundStopToken = true; 1315 } 1316 break; 1317 case dbvdameng: 1318 if (st.tokencode == TBaseType.rrw_for) { 1319 st.tokencode = TBaseType.sqlpluscmd; 1320 isFoundStopToken = true; 1321 } 1322 break; 1323 case dbvredshift: 1324 if (st.tokencode == TBaseType.rrw_explain){ 1325 st.tokencode = TBaseType.sqlpluscmd; 1326 TSourceToken nextst = st.nextSolidToken(); 1327 if (nextst.tokencode == TBaseType.rrw_redshift_verbose){ 1328 nextst.tokencode = TBaseType.sqlpluscmd; 1329 //System.out.println("Found verbose after explain"); 1330 } 1331 isFoundStopToken = true; 1332 } 1333 break; 1334 case dbvvertica: 1335 if ((st.tokencode == TBaseType.rrw_select) 1336 ||(st.tokencode == TBaseType.rrw_insert) 1337 ||(st.tokencode == TBaseType.rrw_update) 1338 ||(st.tokencode == TBaseType.rrw_merge) 1339 ) 1340 { 1341 isFoundStopToken = true; 1342 } 1343 break; 1344 case dbvclickhouse: 1345 case dbvmysql: 1346 case dbvoceanbase: 1347 case dbvsparksql: 1348 case dbvdatabricks: 1349 if ((st.tokencode == TBaseType.rrw_select) 1350 ||(st.tokencode == TBaseType.rrw_insert) 1351 ||(st.tokencode == TBaseType.rrw_update) 1352 ||(st.tokencode == TBaseType.rrw_delete) 1353 ||(st.tokencode == TBaseType.rrw_replace) 1354 ||(st.tokencode == TBaseType.rrw_with) 1355 ||(st.tokencode == TBaseType.rrw_create) 1356 ||(st.tokencode == '(') 1357 ) 1358 { 1359 isFoundStopToken = true; 1360 } 1361 break; 1362 case dbvpostgresql: 1363 if ((st.tokencode == TBaseType.rrw_select) 1364 ||(st.tokencode == TBaseType.rrw_insert) 1365 ||(st.tokencode == TBaseType.rrw_update) 1366 ||(st.tokencode == TBaseType.rrw_delete) 1367 ||(st.tokencode == TBaseType.rrw_replace) 1368 ||(st.tokencode == TBaseType.rrw_with) 1369 ||(st.tokencode == TBaseType.rrw_create) 1370 ||(st.tokencode == TBaseType.rrw_execute) 1371 ) 1372 { 1373 isFoundStopToken = true; 1374 }else if (st.tokencode == '('){ 1375 // Check if this '(' starts EXPLAIN options like (COSTS FALSE) 1376 // or a subquery like (SELECT ...) 1377 TSourceToken nextSolid = sourcetokenlist.nextsolidtoken(k, 1, false); 1378 if (nextSolid != null 1379 && nextSolid.tokencode != TBaseType.rrw_select 1380 && nextSolid.tokencode != TBaseType.rrw_insert 1381 && nextSolid.tokencode != TBaseType.rrw_update 1382 && nextSolid.tokencode != TBaseType.rrw_delete 1383 && nextSolid.tokencode != TBaseType.rrw_with){ 1384 // Options list: skip past closing ')' 1385 int depth = 1; 1386 st.tokencode = TBaseType.sqlpluscmd; 1387 for (k = k + 1; k < sourcetokenlist.size() && depth > 0; k++){ 1388 TSourceToken inner = sourcetokenlist.get(k); 1389 if (inner.tokencode == '(') depth++; 1390 else if (inner.tokencode == ')') depth--; 1391 inner.tokencode = TBaseType.sqlpluscmd; 1392 } 1393 k--; // adjust for loop increment 1394 }else{ 1395 isFoundStopToken = true; 1396 } 1397 } 1398 break; 1399 case dbvduckdb: 1400 if ((st.tokencode == TBaseType.rrw_select) 1401 ||(st.tokencode == TBaseType.rrw_insert) 1402 ||(st.tokencode == TBaseType.rrw_update) 1403 ||(st.tokencode == TBaseType.rrw_delete) 1404 ||(st.tokencode == TBaseType.rrw_replace) 1405 ||(st.tokencode == TBaseType.rrw_with) 1406 ||(st.tokencode == TBaseType.rrw_create) 1407 ||(st.tokencode == TBaseType.rrw_alter) 1408 ||(st.tokencode == TBaseType.rrw_merge) 1409 ||(st.tokencode == '(') 1410 ) 1411 { 1412 isFoundStopToken = true; 1413 } 1414 break; 1415 case dbvflink: 1416 // Flink EXPLAIN can have: EXPLAIN (options) stmt or EXPLAIN options stmt 1417 // Don't stop at '(' because it might be part of EXPLAIN (ESTIMATED_COST, ...) 1418 if ((st.tokencode == TBaseType.rrw_select) 1419 ||(st.tokencode == TBaseType.rrw_insert) 1420 ||(st.tokencode == TBaseType.rrw_update) 1421 ||(st.tokencode == TBaseType.rrw_delete) 1422 ||(st.tokencode == TBaseType.rrw_replace) 1423 ||(st.tokencode == TBaseType.rrw_with) 1424 ||(st.tokencode == TBaseType.rrw_create) 1425 ) 1426 { 1427 isFoundStopToken = true; 1428 } 1429 break; 1430 case dbvcouchbase: 1431 if (st.tokencode == TBaseType.rrw_explain){ 1432 st.tokencode = TBaseType.sqlpluscmd; 1433 isFoundStopToken = true; 1434 } 1435 break; 1436 case dbvpresto: 1437 case dbvathena: 1438 case dbvnetezza: 1439 if ((st.tokencode == TBaseType.rrw_select) 1440 ||(st.tokencode == TBaseType.rrw_insert) 1441 ||(st.tokencode == TBaseType.rrw_update) 1442 ||(st.tokencode == TBaseType.rrw_delete) 1443 ) 1444 { 1445 isFoundStopToken = true; 1446 } 1447 break; 1448 case dbvteradata: 1449 if ((st.tokencode == TBaseType.rrw_select) 1450 ||(st.tokencode == TBaseType.rrw_insert) 1451 ||(st.tokencode == TBaseType.rrw_update) 1452 ||(st.tokencode == TBaseType.rrw_delete) 1453 ||(st.tokencode == TBaseType.rrw_teradata_collect) 1454 ) 1455 { 1456 isFoundStopToken = true; 1457 } 1458 break; 1459 }//switch 1460 1461 if (isFoundStopToken) break; 1462 st.tokencode = TBaseType.sqlpluscmd; 1463 } 1464 }else if (this.sqlstatementtype == ESqlStatementType.sstProfile){ 1465 for(int k=0;k<sourcetokenlist.size();k++) { 1466 TSourceToken st = sourcetokenlist.get(k); 1467 if (dbvendor == EDbVendor.dbvvertica){ 1468 if ((st.tokencode == TBaseType.rrw_select) 1469 ||(st.tokencode == TBaseType.rrw_insert) 1470 ||(st.tokencode == TBaseType.rrw_update) 1471 ||(st.tokencode == TBaseType.rrw_merge) 1472 ) 1473 { 1474 break; 1475 } 1476 } 1477 st.tokencode = TBaseType.sqlpluscmd; 1478 } 1479 }else if (this.sqlstatementtype == ESqlStatementType.sstprepare){ 1480 if ((dbvendor == EDbVendor.dbvcouchbase)||(dbvendor == EDbVendor.dbvpresto)||(dbvendor == EDbVendor.dbvathena)){ 1481 int keywordCount = 0; 1482 for(int k=0;k<sourcetokenlist.size();k++) { 1483 TSourceToken st = sourcetokenlist.get(k); 1484 if (st.tokencode == TBaseType.rrw_prepare) 1485 { 1486 keywordCount++; 1487 }else if ((st.tokentype == ETokenType.ttkeyword) 1488 &&(st.tokencode != TBaseType.rrw_from) 1489 &&(st.tokencode != TBaseType.rrw_as)){ 1490 keywordCount++; 1491 if (keywordCount > 1) break; 1492 } 1493 st.tokencode = TBaseType.sqlpluscmd; 1494 } 1495 } 1496 } 1497 1498 if (parser == null){ 1499 // statement such as select/insert and etc inside plsql 1500 if (psql != null){ 1501 parser = psql.getTopStatement().parser; 1502 this.setParentStmt(psql); 1503 } 1504 // parser = new TParserOracleSql(null); 1505 //parser.lexer = new TLexerOracle(); 1506 //parser.lexer.delimiterchar = '/'; 1507 } 1508 parser.sql = this; 1509 parser.sourcetokenlist = sourcetokenlist; 1510 ret = parser.yyparse(); 1511 this.rootNode = parser.rootNode; 1512 } 1513 1514 if (ret == 0){ 1515 ret = syntaxErrors.size(); 1516 } 1517 // if (rootNode == null) { 1518 if (rootNode == null) { 1519 // EXPLAIN FOR CONNECTION has no inner statement to parse - this is valid 1520 if (this.sqlstatementtype == ESqlStatementType.sstExplain && isExplainForConnection()) { 1521 ret = 0; 1522 } else { 1523 ret = TBaseType.MSG_ERROR_NO_ROOT_NODE; 1524 // todo , uncomment next line when all sql statements in .y file was processed 1525 parseerrormessagehandle( new TSyntaxError("no root node",0,0,"no_root_node",EErrorType.sperror,TBaseType.MSG_ERROR_NO_ROOT_NODE,this,-1)); 1526 } 1527 } 1528 return ret; 1529 } 1530 1531 private boolean isExplainForConnection() { 1532 if (sourcetokenlist == null) return false; 1533 for (int i = 0; i < sourcetokenlist.size() - 1; i++) { 1534 TSourceToken st = sourcetokenlist.get(i); 1535 if (st.toString().equalsIgnoreCase("for")) { 1536 TSourceToken next = sourcetokenlist.nextsolidtoken(i, 1, false); 1537 if (next != null && next.toString().equalsIgnoreCase("connection")) { 1538 return true; 1539 } 1540 } 1541 } 1542 return false; 1543 } 1544 1545 public void clearError(){ 1546 syntaxErrors.clear(); 1547 syntaxHints.clear(); 1548 } 1549 1550 void clear(){ 1551 syntaxErrors.clear(); 1552 syntaxHints.clear(); 1553// todo all subclass should add super() 1554 } 1555 1556 public void setStmtScope(TStmtScope stmtScope) { 1557 this.stmtScope = stmtScope; 1558 } 1559 1560 public TStmtScope getStmtScope() { 1561 return stmtScope; 1562 } 1563 1564 /** 1565 * Original SQL fragment of this statement. 1566 * @return Original statement text. 1567 */ 1568 1569 /* 1570 public String toString(){ 1571 StringBuffer sb = new StringBuffer(""); 1572 for(int i=0; i<sourcetokenlist.size();i++){ 1573 sb.append(sourcetokenlist.get(i).toString()); 1574 } 1575 return sb.toString(); 1576 } 1577 */ 1578 protected TStmtScope stmtScope = null; 1579 void buildsql(){} 1580 public int doParseStatement(TCustomSqlStatement psql){ 1581 if (psql != null){ 1582 this.setParentStmt(psql); 1583 this.setFrameStack(psql.getFrameStack()); 1584 psql.stmtScope.incrementCurrentStmtIndex(); 1585 this.queryId = String.format("%s#stmt_%d_%s", psql.getQueryId(),psql.stmtScope.getCurrentStmtIndex(), this.sqlstatementtype); 1586 stmtScope = new TStmtScope(psql.stmtScope,this); 1587 // psql.statements.add(this); 1588 }else{ 1589 stmtScope = new TStmtScope(this); 1590 1591 // global scope 1592 this.getFrameStack().peek().getScope().incrementCurrentStmtIndex(); 1593 this.queryId = String.format("stmt_%d_%s",this.getFrameStack().peek().getScope().getCurrentStmtIndex(), this.sqlstatementtype); 1594 } 1595 1596 if ((this.getStartToken() == null)&&(rootNode != null)){ 1597 this.setStartToken(rootNode.getStartToken()); 1598 } 1599 if ((this.getEndToken() == null)&&(rootNode != null)){ 1600 this.setEndToken(rootNode.getEndToken()); 1601 } 1602 1603 if(this.getGsqlparser() == null){ 1604 if (rootNode != null){ 1605 this.setGsqlparser(rootNode.getGsqlparser()); 1606 } 1607 } 1608 return 0; 1609 } 1610 1611 void addtokentolist(TSourceToken st){ 1612 st.stmt = this; 1613 sourcetokenlist.add(st); 1614 } 1615 1616 public TTable analyzeTablename(TObjectName tableName){ 1617 TTable lcTable = new TTable(); 1618 lcTable.setTableType(ETableSource.objectname); 1619 lcTable.setStartToken(tableName.getStartToken()); 1620 lcTable.setEndToken(tableName.getEndToken()); 1621 lcTable.setGsqlparser(this.getGsqlparser()); 1622 lcTable.setTableName(tableName); 1623 1624 tables.addTable(lcTable); 1625 return lcTable; 1626 } 1627 1628 /** 1629 * Unbinds a DML target that reads no CTE although a CTE has its name, by {@link TCTEList#isTableOnlyTarget} (the 1630 * PostgreSQL family); called once the target's effect type is set. 1631 */ 1632 protected void unbindCteTarget(TTable target) { 1633 if (target != null && target.isCTEName() && TCTEList.isTableOnlyTarget(target, dbvendor)) { 1634 target.setCTEName(false); 1635 target.setCTE(null); 1636 target.setCteColomnReferences(null); 1637 } 1638 } 1639 1640 /** Whether {@code pTable} reads a CTE, binding it as {@link #bindCte} does. */ 1641 protected boolean isTableACTE(TTable pTable){ 1642 return bindCte(pTable); 1643 } 1644 1645 /** 1646 * Binds {@code table} to the CTE its name reads, or to none: {@link TTable#isCTEName()}, {@link TTable#getCTE()} 1647 * and {@link TTable#getCteColomnReferences()} are set together (redundancy plan C3c (d)). This statement's WITH 1648 * is asked first, then each enclosing statement's, nearest first, by {@link TCTEList#findVisible}, the lookup 1649 * resolver2 reads CTEs by too. Both the FROM items (analyzeFromTable) and every table added to a statement 1650 * (addToTables: implicit tables, DML targets) are bound here. 1651 */ 1652 private boolean bindCte(TTable table) { 1653 TCTE cte = null; 1654 if (table != null && table.getTableName() != null) { 1655 String name = table.getTableName().toString(); 1656 IdentifierService names = null; 1657 for (TCustomSqlStatement level = this; level != null && cte == null; level = level.parentStmt) { 1658 if (level.cteList != null) { 1659 if (names == null) { 1660 names = IdentifierService.forAnalysis(getSqlEnv(), dbvendor); 1661 } 1662 cte = level.cteList.findVisible(name, table, dbvendor, names); 1663 } 1664 } 1665 } 1666 if (table != null) { 1667 table.setCTE(cte); 1668 table.setCTEName(cte != null); 1669 table.setCteColomnReferences(cte == null ? null : cte.getColumnList()); 1670 } 1671 return cte != null; 1672 } 1673 1674 public TTable findTable(ETableEffectType[] tableEffectTypes){ 1675 TTable lcResult = null; 1676 for(int i=0;i<tables.size();i++){ 1677 for(int j=0;j<tableEffectTypes.length;j++){ 1678 if (tables.getTable(i).getEffectType() == tableEffectTypes[j]){ 1679 lcResult = tables.getTable(i); 1680 return lcResult; 1681 } 1682 } 1683 } 1684 return lcResult; 1685 } 1686 public void addToTables(TTable pTable){ 1687 tables.addTable(pTable); 1688 if (isTableACTE(pTable)) return; 1689 1690 if (pTable.getTableName() == null) return; 1691 if (pTable.getTableName().getTableToken() == null) return; 1692 if ((pTable.getTableName().getTableString().toString().equalsIgnoreCase("inserted"))||(pTable.getTableName().getTableString().toString().equalsIgnoreCase("deleted"))){ 1693 if ((getAncestorStmt().sqlstatementtype == ESqlStatementType.sstcreatetrigger) 1694 ||(getAncestorStmt().sqlstatementtype == ESqlStatementType.sstmssqlaltertrigger)){ 1695 //pTable.setLinkTable(true); 1696 ETableEffectType[] effectTypes = new ETableEffectType[]{ 1697 ETableEffectType.tetTriggerOn,ETableEffectType.tetTriggerInsert,ETableEffectType.tetTriggerDelete,ETableEffectType.tetTriggerUpdate,ETableEffectType.tetTriggerInsteadOf 1698 }; 1699 pTable.setLinkTable(getAncestorStmt().findTable(effectTypes)); 1700 } 1701 } 1702 1703 } 1704 1705 public TJoin analyzeTableOrJoin(TFromTable pfromTable){ 1706 TFromTable lcFromTable = pfromTable; 1707 TJoin lcJoin; 1708 TTable lcTable; 1709 1710 if (lcFromTable.getFromtableType() != ETableSource.join){ 1711 lcJoin = new TJoin(); 1712 lcTable = analyzeFromTable(lcFromTable,true); 1713 lcTable.setEffectType(ETableEffectType.tetSelect); 1714 lcJoin.setTable(lcTable); 1715 lcJoin.setStartToken(lcJoin.getTable().getStartToken()); 1716 lcJoin.setEndToken(lcJoin.getTable().getEndToken()); 1717 lcJoin.setGsqlparser(getGsqlparser()); 1718 this.fromSourceTable = lcTable; 1719 this.getRelations().add(lcTable); 1720 }else{ 1721 this.fromSourceJoin = lcFromTable.getJoinExpr(); 1722 1723 this.fromSourceTable = new TTable(); 1724 this.fromSourceTable.setTableType(ETableSource.join); 1725 this.fromSourceTable.setAliasClause(lcFromTable.getJoinExpr().getAliasClause()); 1726 this.fromSourceTable.setStartToken(lcFromTable.getStartToken()); 1727 this.fromSourceTable.setEndToken(lcFromTable.getEndToken()); 1728 this.fromSourceTable.setGsqlparser(lcFromTable.getGsqlparser()); 1729 this.fromSourceTable.setJoinExpr(this.fromSourceJoin); 1730 this.getRelations().add(this.fromSourceTable); 1731 1732 lcJoin = analyzeJoin(lcFromTable.getJoinExpr(),null,true); 1733 lcJoin.doParse(this, ESqlClause.join); 1734 1735 if (lcFromTable.getLateralViewList() != null){ 1736 for(TLateralView lateralView:lcFromTable.getLateralViewList()){ 1737 TTable t = lateralView.createATable(this); 1738 addToTables(t); 1739 this.relations.add(t); 1740 } 1741 } 1742 } 1743 1744 return lcJoin; 1745 } 1746 1747 public TTable analyzeFromTable(TFromTable pfromTable, Boolean addToTableList){ 1748 return analyzeFromTable(pfromTable,addToTableList,ESqlClause.unknown); 1749 } 1750 1751 public TTable analyzeFromTable(TFromTable pfromTable, Boolean addToTableList, ESqlClause pLocation){ 1752 TTable lcTable = new TTable(); 1753 lcTable.setTableType(pfromTable.getFromtableType()); 1754 lcTable.setAliasClause(pfromTable.getAliasClause()); 1755 lcTable.setStartToken(pfromTable.getStartToken()); 1756 lcTable.setEndToken(pfromTable.getEndToken()); 1757 lcTable.setGsqlparser(pfromTable.getGsqlparser()); 1758 lcTable.setTableHintList(pfromTable.getTableHintList()); 1759 lcTable.setTableSample(pfromTable.getTableSample()); 1760 lcTable.setLateralViewList(pfromTable.getLateralViewList()); 1761 lcTable.setTableProperties(pfromTable.getTableProperties()); 1762 lcTable.setPivotedTable(pfromTable.getPivotedTable()); 1763 lcTable.setParenthesisCount(pfromTable.getParenthesisCount()); 1764 lcTable.setParenthesisAfterAliasCount(pfromTable.getParenthesisAfterAliasCount()); 1765 lcTable.setTableKeyword(pfromTable.isTableKeyword()); 1766 lcTable.setOnlyKeyword(pfromTable.isOnlyKeyword()); 1767 lcTable.setArrayIndexAlias(pfromTable.getArrayIndexAlias()); 1768 lcTable.setSuperUnpivot(pfromTable.isSuperUnpivot()); 1769 lcTable.setTableOperatorInputAlias(pfromTable.getTableOperatorInputAlias()); 1770 lcTable.setTableOperatorPartitionBy(pfromTable.getTableOperatorPartitionBy()); 1771 lcTable.setTableOperatorOrderBy(pfromTable.getTableOperatorOrderBy()); 1772 lcTable.setFlashback(pfromTable.getFlashback()); 1773 lcTable.setPxGranule(pfromTable.getPxGranule()); 1774 lcTable.setTimeTravelClause(pfromTable.getTimeTravelClause()); 1775 //lcTable.setPartitionClause(pfromTable.getPartitionClause()); 1776 1777 if(getFrameStack().firstElement() != null){ 1778 TFrame stackFrame = getFrameStack().firstElement(); 1779 TGlobalScope globalScope = (TGlobalScope)stackFrame.getScope(); 1780 lcTable.setSqlEnv(globalScope.getSqlEnv()); 1781 } 1782 1783 switch(lcTable.getTableType()){ 1784 case objectname:{ 1785 // tables.addTableByTableRefernce(pfromTable.getTableObjectName()); 1786 boolean insertedInTrigger = false; 1787 if (getTopStatement().sqlstatementtype == ESqlStatementType.sstcreatetrigger){ 1788 insertedInTrigger = (pfromTable.getTableObjectName().toString().compareToIgnoreCase("inserted")==0); 1789 } 1790 1791 if (insertedInTrigger){ 1792 // change table name from inserted to onTable name in create trigger 1793 lcTable.setTableName(((TCreateTriggerStmt)getTopStatement()).getOnTable().getTableName()); 1794 //lcTable.setLinkTable(true); 1795 lcTable.setLinkTable(((TCreateTriggerStmt)getTopStatement()).getOnTable()); 1796 1797 }else{ 1798 lcTable.setTableName(pfromTable.getTableObjectName()); 1799 lcTable.getTableName().setSqlEnv(getSqlEnv()); 1800 1801// if (getSqlEnv().getDefaultCatalogName() != null){ 1802// if (lcTable.getTableName().getDatabaseToken() == null){ 1803// lcTable.getTableName().setDatabaseToken(new TSourceToken(getSqlEnv().getDefaultCatalogName()),true); 1804// } 1805// } 1806 1807// if ((lcTable.getTableName().getSchemaToken() == null)&&(TSQLEnv.supportSchema(this.dbvendor))){ 1808// // let find schema name for this table in env 1809// TSQLTable t = getSqlEnv().searchTable(".."+lcTable.getFullName()); 1810// if (t != null){ 1811// TSQLSchema s = t.getSchema(); 1812// if (s != null){ 1813// lcTable.getTableName().setSchemaToken(new TSourceToken(s.getName()),true); 1814// } 1815// } 1816// } 1817 1818 } 1819 // a CTE name or a table name (redundancy plan C3c (d)) 1820 bindCte(lcTable); 1821 1822 break; 1823 } 1824 case tableExpr:{ 1825 ESqlClause location = ESqlClause.tableExpr; //ESqlClause.resultColumn; 1826 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1827 // change location here 1828 } 1829 lcTable.setTableExpr(pfromTable.getTableExpr()); 1830 lcTable.getTableExpr().doParse(this,location); 1831 // Oracle's and Informix's TABLE(d.emps): the operand is a collection column, not a table 1832 if ((dbvendor == EDbVendor.dbvoracle || dbvendor == EDbVendor.dbvinformix) 1833 && lcTable.getTableExpr().getExpressionType() == EExpressionType.simple_object_name_t 1834 && lcTable.getTableExpr().getObjectOperand() != null) { 1835 lcTable.getTableExpr().getObjectOperand().reinterpretTableAsColumn(); 1836 } 1837 // teradata: SELECT table1.* FROM table(strtok_split_to_table(1, 'dm-calcite-raven/td/bq', '-') RETURNS (outkey integer, tokennum integer, token varchar(20)) ) as table1; 1838 // RETURNS (outkey integer, tokennum integer, token varchar(20)) 1839 lcTable.setColumnDefinitions(pfromTable.getColumnDefinitions()); 1840 // Teradata table function HASH BY and LOCAL ORDER BY clauses 1841 lcTable.setHashByClause(pfromTable.getHashByClause()); 1842 lcTable.setLocalOrderBy(pfromTable.getLocalOrderBy()); 1843 break; 1844 } 1845 case subquery:{ 1846// if (pfromTable.getSubquerynode().isHiveFromQuery()){ 1847// THiveFromQuery fromQuery = new THiveFromQuery(dbvendor); 1848// lcTable.setHiveFromQuery(fromQuery); 1849// fromQuery.rootNode = pfromTable.getSubquerynode(); 1850// fromQuery.setStartToken(pfromTable.getSubquerynode()); 1851// fromQuery.setEndToken(pfromTable.getSubquerynode()); 1852// fromQuery.setLabelName(this.labelName); 1853// fromQuery.doParseStatement(this); 1854// }else{ 1855// lcTable.subquery = new TSelectSqlStatement(dbvendor); 1856// lcTable.subquery.rootNode = pfromTable.getSubquerynode(); 1857// lcTable.subquery.setLocation(ESqlClause.elTable); 1858// //lcTable.subquery.resultColumnList = ((TSelectSqlNode)lcTable.subquery.rootNode).getResultColumnList(); 1859// lcTable.subquery.doParseStatement(this); 1860// } 1861 1862 lcTable.subquery = new TSelectSqlStatement(dbvendor); 1863 lcTable.subquery.rootNode = pfromTable.getSubquerynode(); 1864 if (pLocation == ESqlClause.unknown){ 1865 lcTable.subquery.setLocation(ESqlClause.elTable); 1866 }else{ 1867 lcTable.subquery.setLocation(pLocation); 1868 } 1869 //lcTable.subquery.resultColumnList = ((TSelectSqlNode)lcTable.subquery.rootNode).getResultColumnList(); 1870 lcTable.subquery.doParseStatement(this); 1871 1872 break; 1873 } 1874 case function:{ 1875 ESqlClause location = ESqlClause.tableFunction;// resultColumn; 1876 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1877 // change location here 1878 } 1879 lcTable.setFuncCall(pfromTable.getFuncCall()); 1880 lcTable.getFuncCall().doParse(this,location); 1881 break; 1882 } 1883 case containsTable:{ 1884 ESqlClause location = ESqlClause.containsTable;//resultColumn; 1885 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1886 // change location here 1887 } 1888 lcTable.setContainsTable(pfromTable.getContainsTable()); 1889 lcTable.getContainsTable().doParse(this,location); 1890 break; 1891 } 1892 1893 case openrowset:{ 1894 ESqlClause location = ESqlClause.openrowset;//resultColumn; 1895 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1896 // change location here 1897 } 1898 lcTable.setOpenRowSet(pfromTable.getOpenRowSet()); 1899 lcTable.getOpenRowSet().doParse(this,location); 1900 break; 1901 } 1902 1903 case openxml:{ 1904 ESqlClause location = ESqlClause.openxml;//resultColumn; 1905 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1906 // change location here 1907 } 1908 lcTable.setOpenXML(pfromTable.getOpenXML()); 1909 lcTable.getOpenXML().doParse(this,location); 1910 break; 1911 } 1912 1913 case opendatasource:{ 1914 ESqlClause location = ESqlClause.opendatasource;//resultColumn; 1915 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1916 // change location here 1917 } 1918 lcTable.setOpenDatasource(pfromTable.getOpenDatasource()); 1919 lcTable.getOpenDatasource().doParse(this,location); 1920 break; 1921 } 1922 1923 case openquery:{ 1924 ESqlClause location = ESqlClause.openquery;//resultColumn; 1925 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1926 // change location here 1927 } 1928 lcTable.setOpenquery(pfromTable.getOpenQuery()); 1929 lcTable.getOpenquery().doParse(this,location); 1930 lcTable.setSubquery(lcTable.getOpenquery().getSubquery()); 1931 break; 1932 } 1933 1934 case datachangeTable:{ 1935 ESqlClause location = ESqlClause.datachangeTable;//resultColumn; 1936 if (sqlstatementtype == ESqlStatementType.sstinsert ){ 1937 // change location here 1938 } 1939 lcTable.setDatachangeTable(pfromTable.getDatachangeTable()); 1940 lcTable.getDatachangeTable().doParse(this,location); 1941 break; 1942 } 1943 case rowList:{ 1944 ESqlClause location = ESqlClause.rowList;//resultColumn; 1945 lcTable.setValueClause(pfromTable.getValueClause()); 1946 lcTable.getValueClause().doParse(this,location); 1947 break; 1948 } 1949 case pivoted_table:{ 1950 ESqlClause location = ESqlClause.pivoted_table;//resultColumn; 1951 lcTable.getPivotedTable().doParse(this,location); 1952 addToTableList = false; 1953 targetTable = lcTable; 1954 break; 1955 } 1956 case xmltable:{ 1957 ESqlClause location = ESqlClause.xmltable;//resultColumn; 1958 lcTable.setXmlTable(pfromTable.getXmlTable()); 1959 lcTable.getXmlTable().doParse(this,location); 1960 break; 1961 } 1962 1963 case informixOuter:{ 1964 ESqlClause location = ESqlClause.outerTable;//resultColumn; 1965 lcTable.setOuterClause(pfromTable.getOuterClause()); 1966 lcTable.getOuterClause().doParse(this,location); 1967 break; 1968 } 1969 1970 case table_ref_list:{ 1971 lcTable.setFromTableList(pfromTable.getFromTableList()); 1972 break; 1973 } 1974// case hiveFromQuery:{ 1975// THiveFromQuery fromQuery = new THiveFromQuery(EDbVendor.dbvhive); 1976// fromQuery.rootNode = pfromTable.getFromQuerySqlNode(); 1977// fromQuery.doParseStatement(this); 1978// lcTable.setHiveFromQuery(fromQuery); 1979// break; 1980// } 1981 case output_merge:{ 1982 TMergeSqlStatement outputMerge = new TMergeSqlStatement(EDbVendor.dbvmssql); 1983 outputMerge.rootNode = pfromTable.getMergeSqlNode(); 1984 outputMerge.doParseStatement(this); 1985 lcTable.setOutputMerge(outputMerge); 1986 break; 1987 } 1988 case td_unpivot:{ 1989 // Set the TD_UNPIVOT output table before doParse so that VALUE_COLUMNS and 1990 // UNPIVOT_COLUMN can be linked to it (they are output columns of TD_UNPIVOT) 1991 pfromTable.getTdUnpivot().setTdUnpivotOutputTable(lcTable); 1992 pfromTable.getTdUnpivot().doParse(this,ESqlClause.tdUnPivot); 1993 lcTable.setTdUnpivot(pfromTable.getTdUnpivot()); 1994 break; 1995 } 1996 case unnest:{ 1997 pfromTable.getUnnestClause().doParse(this,ESqlClause.elTable); 1998 lcTable.setUnnestClause(pfromTable.getUnnestClause()); 1999 if (lcTable.getAliasClause() != null){ 2000 if (lcTable.getAliasClause().getColumns() != null){ 2001 for(TObjectName pColumn:lcTable.getAliasClause().getColumns()){ 2002 lcTable.getLinkedColumns().addObjectName(pColumn); 2003 pColumn.setSourceTable(lcTable); 2004 } 2005 }else if (lcTable.getAliasClause().getAliasName() != null){ 2006// SELECT * 2007// FROM UNNEST(['foo', 'bar', 'baz', 'qux', 'corge', 'garply', 'waldo', 'fred']) AS element 2008// WITH OFFSET AS offset 2009 2010 // add element as column of unnest table. 2011 TObjectName newColumn = TObjectName.createObjectName(this.dbvendor,EDbObjectType.column,lcTable.getAliasClause().getAliasName().getStartToken()); 2012 lcTable.getLinkedColumns().addObjectName(newColumn); 2013 newColumn.setSourceTable(lcTable); 2014 } 2015 } 2016 2017 if (lcTable.getUnnestClause().getWithOffset() != null){ 2018 if (lcTable.getUnnestClause().getWithOffsetAlais() != null){ 2019 // with offset as offsetAlias 2020 TAliasClause aliasClause = lcTable.getUnnestClause().getWithOffsetAlais(); 2021 if (aliasClause.getAliasName() != null){ 2022 TObjectName newColumn = TObjectName.createObjectName(this.dbvendor,EDbObjectType.column,aliasClause.getAliasName().getStartToken()); 2023 lcTable.getLinkedColumns().addObjectName(newColumn); 2024 newColumn.setSourceTable(lcTable); 2025 } 2026 }else{ 2027 // with offset 2028 TObjectName newColumn = TObjectName.createObjectName(this.dbvendor,EDbObjectType.column,new TSourceToken("offset")); 2029 lcTable.getLinkedColumns().addObjectName(newColumn); 2030 newColumn.setSourceTable(lcTable); 2031 } 2032 } 2033 2034 // link columns in the select list to unnest() 2035 // select emp_id,name,state,city,zipcode from `absolute-runner-302907.gudu_sqlflow.ADDRESS_NESTED`, UNNEST(address) 2036 if (lcTable.getUnnestClause().getDerivedColumnList() != null){ 2037 TObjectNameList derivedColumns = lcTable.getUnnestClause().getDerivedColumnList(); 2038 for(int i=0;i<derivedColumns.size();i++){ 2039 //System.out.println(derivedColumns.getObjectName(i).toString()); 2040 lcTable.getLinkedColumns().addObjectName(derivedColumns.getObjectName(i)); 2041 } 2042 } 2043 2044 break; 2045 } 2046 case jsonTable:{ 2047 ESqlClause location = ESqlClause.jsonTable;//resultColumn; 2048 lcTable.setJsonTable(pfromTable.getJsonTable()); 2049 lcTable.getJsonTable().doParse(this,location); 2050 break; 2051 } 2052 case externalTable: 2053 lcTable.setTableName(pfromTable.getTableObjectName()); 2054 lcTable.setColumnDefinitions(pfromTable.getColumnDefinitions()); 2055 lcTable.getColumnDefinitions().doParse(this,pLocation); 2056 lcTable.setTableType(ETableSource.externalTable); // tableType is reset in setTableName() method, so we reset it here 2057 break; 2058 case caseJoin: 2059 lcTable.setCaseJoin(pfromTable.getCaseJoin()); 2060 lcTable.getCaseJoin().doParse(this,pLocation); 2061 break; 2062 case stageReference: 2063 lcTable.setStageReference(pfromTable.getStageReference()); 2064 lcTable.getStageReference().doParse(this,pLocation); 2065 2066 lcTable.setTableName(lcTable.getStageReference().getStageName()); 2067 lcTable.setTableType(ETableSource.stageReference); 2068 lcTable.getTableName().setSqlEnv(getSqlEnv()); 2069 2070 break; 2071 2072 }//switch 2073 2074// if (pfromTable.getPivotClause() != null){ 2075// lcTable.setPivotClause(pfromTable.getPivotClause()); 2076// lcTable.getPivotClause().doParse(this,ESqlClause.resultColumn); 2077// } 2078 2079 if (lcTable.getTableOperatorPartitionBy() != null) { 2080 lcTable.getTableOperatorPartitionBy().doParse(this, ESqlClause.unknown); 2081 } 2082 if (lcTable.getTableOperatorOrderBy() != null) { 2083 lcTable.getTableOperatorOrderBy().doParse(this, ESqlClause.unknown); 2084 } 2085 lcTable.setPartitionExtensionClause(pfromTable.getPartitionExtensionClause()); 2086 2087 //tables.addTable(lcTable); 2088 if (addToTableList) { 2089 addToTables(lcTable); 2090 } 2091 2092 // AS OF (SELECT ...) (Oracle flashback, Teradata temporal) and AT(TIMESTAMP => (SELECT ...)) (Snowflake time 2093 // travel): the point in time is an expression whose subqueries are statements of their own (Mantis 4920) 2094 TExpression pointInTime = lcTable.getPointInTime(); 2095 if (pointInTime != null) { 2096 parsingPointInTime = true; 2097 try { 2098 pointInTime.doParse(this, ESqlClause.unknown); 2099 } finally { 2100 parsingPointInTime = false; 2101 } 2102 } 2103 2104 if (lcTable.getTableHintList() != null){ 2105 for(int i=0;i<lcTable.getTableHintList().size();i++){ 2106 TTableHint hint = lcTable.getTableHintList().getElement(i); 2107 hint.setOwnerTable(lcTable); 2108 hint.doParse(this,ESqlClause.tableHint); 2109 } 2110 } 2111 2112 if (lcTable.getLateralViewList() != null){ 2113 for(TLateralView lateralView:lcTable.getLateralViewList()){ 2114 TTable t = lateralView.createATable(this); 2115 addToTables(t); 2116 this.relations.add(t); 2117 } 2118 } 2119 2120 if (lcTable.getAliasClause() != null){ 2121 if (lcTable.getAliasClause().toString().equalsIgnoreCase("and")){ 2122 // end keyword can't be alias name 2123 TSourceToken st1 = lcTable.getAliasClause().getStartToken(); 2124 TSyntaxError err = new TSyntaxError(st1.toString() 2125 ,st1.lineNo,st1.columnNo 2126 ,String.format("AND keyword can't be table alias") 2127 ,EErrorType.sperror 2128 ,TBaseType.MSG_ERROR_AND_KEYWORD_CANT_USED_AS_TABLE_ALIAS 2129 ,this,st1.posinlist); 2130 this.parseerrormessagehandle( err); 2131 2132 } 2133 } 2134 2135 return lcTable; 2136 } 2137 2138 public TJoin analyzeJoin(TJoinExpr pJoinExpr,TJoin pJoin,Boolean isSub){ 2139 TJoin retval = pJoin; 2140 TJoinItem lcJoinItem = null ; 2141 2142 if (pJoinExpr == null) {return retval;} 2143 2144 if (pJoinExpr.getJointype() == EJoinType.nested) 2145 { 2146 if (isSub) 2147 { 2148 if (retval == null) { // top level, left side is a join 2149 retval = new TJoin(); 2150 retval.setStartToken(pJoinExpr.getStartToken()); 2151 retval.setEndToken(pJoinExpr.getEndToken()); 2152 } 2153 2154 pJoinExpr.setJointype(pJoinExpr.original_jontype); 2155 retval.setJoin(analyzeJoin(pJoinExpr,null,true)); 2156 //retval =analyzeJoin(pJoinExpr,null,true); 2157 retval.setKind(TBaseType.join_source_join); 2158 retval.getJoin().setAliasClause(pJoinExpr.getAliasClause()); 2159 retval.getJoin().setWithParen(true); 2160 retval.getJoin().setNestedParen(pJoinExpr.getNestedParen()); 2161 } 2162 else 2163 { 2164 if (retval == null) 2165 { 2166 retval = new TJoin(); 2167 retval.setStartToken(pJoinExpr.getStartToken()); 2168 retval.setEndToken(pJoinExpr.getEndToken()); 2169 retval.setGsqlparser(this.getGsqlparser()); 2170 } 2171 else 2172 { 2173 } 2174 pJoinExpr.setJointype(pJoinExpr.original_jontype); 2175 retval = analyzeJoin(pJoinExpr,retval,false); 2176 //retval.setJoin(analyzeJoin(pJoinExpr,retval,false)); 2177 //retval = analyzeJoin(pJoinExpr,retval,false); 2178 //retval.setKind(TBaseType.join_source_join); 2179 //retval.setKind(TBaseType.join_source_table); 2180 //retval.setAliasClause(pJoinExpr.getAliasClause()); 2181 retval.setAliasClause(pJoinExpr.getAliasClause()); 2182 retval.setWithParen(true); 2183 retval.setNestedParen(pJoinExpr.getNestedParen()); 2184 } 2185 return retval; 2186 } 2187 2188 if (pJoinExpr.getLeftOperand().getFromtableType() != ETableSource.join){ 2189 if (retval == null) { 2190 retval = new TJoin(); 2191 retval.setStartToken(pJoinExpr.getStartToken()); 2192 retval.setEndToken(pJoinExpr.getEndToken()); 2193 retval.setGsqlparser(this.getGsqlparser()); 2194 2195 // retval.setStartToken(pJoinExpr.getLeftOperand().getStartToken()); 2196 // retval.setEndToken(pJoinExpr.getLeftOperand().getEndToken()); 2197 } 2198 TTable lcTable = analyzeFromTable(pJoinExpr.getLeftOperand(),true,ESqlClause.join); 2199 lcTable.setEffectType(ETableEffectType.tetSelect); 2200 retval.setTable(lcTable); 2201 //retval.joinTable.OwnerJoin = result; 2202 retval.setKind(TBaseType.join_source_table); 2203 pJoinExpr.setLeftTable(lcTable); 2204 }else{ 2205 TJoinExpr lcJoinItemJoinExpr = pJoinExpr.getLeftOperand().getJoinExpr(); 2206 //if (lcJoinItemJoinExpr.getJointype() == TBaseType.join_nested){ 2207 // lcJoinItemJoinExpr.setJointype(lcJoinItemJoinExpr.original_jontype); 2208 //} 2209 2210 if (retval != null) { 2211 retval = analyzeJoin(lcJoinItemJoinExpr,retval,true); 2212 } else { 2213 retval = analyzeJoin(lcJoinItemJoinExpr,retval,isSub); 2214 } 2215 retval.setStartToken(lcJoinItemJoinExpr.getStartToken()); 2216 retval.setEndToken(lcJoinItemJoinExpr.getEndToken()); 2217 2218 2219 TTable lcTable = new TTable(); 2220 lcTable.setTableType(pJoinExpr.getLeftOperand().getFromtableType()); 2221 lcTable.setAliasClause(lcJoinItemJoinExpr.getAliasClause()); 2222 lcTable.setStartToken(lcJoinItemJoinExpr.getStartToken()); 2223 lcTable.setEndToken(lcJoinItemJoinExpr.getEndToken()); 2224 pJoinExpr.setLeftTable(lcTable); 2225 lcTable.setJoinExpr(lcJoinItemJoinExpr); 2226 } 2227 2228 if (pJoinExpr.getRightOperand().getFromtableType() != ETableSource.join){ 2229 if (retval != null) 2230 { 2231 lcJoinItem = new TJoinItem(); 2232 TTable lcTable = analyzeFromTable(pJoinExpr.getRightOperand(),true,ESqlClause.join); 2233 lcTable.setEffectType(ETableEffectType.tetSelect); 2234 lcJoinItem.setTable(lcTable); 2235 lcJoinItem.setStartToken(lcJoinItem.getTable().getStartToken()); 2236 lcJoinItem.setEndToken(lcJoinItem.getTable().getEndToken()); 2237 // lcJoinItem.JoinItemTable.OwnerJoinItem := lcJoinItem; 2238 lcJoinItem.setKind(TBaseType.join_source_table); 2239 retval.getJoinItems().addJoinItem(lcJoinItem); 2240 pJoinExpr.setRightTable(lcTable); 2241 } 2242 }else{ 2243 if (retval != null) 2244 { 2245 lcJoinItem = new TJoinItem(); 2246 lcJoinItem.setKind(TBaseType.join_source_join); 2247 TJoinExpr lcJoinItemJoinExpr = pJoinExpr.getRightOperand().getJoinExpr(); 2248 //if (lcJoinItemJoinExpr.getJointype() == TBaseType.join_nested){ 2249 // lcJoinItemJoinExpr.setJointype(lcJoinItemJoinExpr.original_jontype); 2250 //} 2251 lcJoinItem.setJoin(analyzeJoin(pJoinExpr.getRightOperand().getJoinExpr(),null,false)); 2252 lcJoinItem.getJoin().setAliasClause(lcJoinItemJoinExpr.getAliasClause()); 2253 lcJoinItem.setStartToken(lcJoinItem.getJoin().getStartToken()); 2254 lcJoinItem.setEndToken(lcJoinItem.getJoin().getEndToken()); 2255 retval.getJoinItems().addJoinItem(lcJoinItem); 2256 2257 TTable lcTable = new TTable(); 2258 lcTable.setTableType(pJoinExpr.getRightOperand().getFromtableType()); 2259 lcTable.setAliasClause(lcJoinItemJoinExpr.getAliasClause()); 2260 lcTable.setStartToken(lcJoinItemJoinExpr.getStartToken()); 2261 lcTable.setEndToken(lcJoinItemJoinExpr.getEndToken()); 2262 pJoinExpr.setRightTable(lcTable); 2263 lcTable.setJoinExpr(lcJoinItemJoinExpr); 2264 } 2265 } 2266 2267 if (lcJoinItem == null) return retval; 2268 2269 lcJoinItem.setJoinType(pJoinExpr.getJointype()); 2270 lcJoinItem.setUsingColumns(pJoinExpr.usingColumns); 2271 if ((lcJoinItem.getUsingColumns() != null) && (tables.size()>1)){ 2272 TObjectName crf ; 2273 for (int i=0;i<lcJoinItem.getUsingColumns().size();i++){ 2274 crf = lcJoinItem.getUsingColumns().getObjectName(i); 2275 // link this column to last 2 tables 2276 tables.getTable(tables.size()-1).getObjectNameReferences().addObjectName(crf); 2277 tables.getTable(tables.size()-2).getObjectNameReferences().addObjectName(crf); 2278 2279 tables.getTable(tables.size()-1).getLinkedColumns().addObjectName(crf); 2280 crf.setSourceTable(tables.getTable(tables.size()-1)); 2281 tables.getTable(tables.size()-2).getLinkedColumns().addObjectName(crf); 2282 crf.setSourceTable(tables.getTable(tables.size()-2)); 2283 2284 } 2285 lcJoinItem.setEndToken(lcJoinItem.getUsingColumns().getEndToken()); 2286 } 2287 lcJoinItem.setOnCondition(pJoinExpr.onCondition); 2288 if (lcJoinItem.getOnCondition() != null) 2289 { 2290 lcJoinItem.getOnCondition().doParse(this,ESqlClause.joinCondition); 2291 lcJoinItem.setEndToken(lcJoinItem.getOnCondition().getEndToken()); 2292 } 2293 2294 2295 return retval; 2296 } 2297 2298 public boolean locateVariableOrParameter(TObjectName cr){ 2299 return locateVariableOrParameter(cr,false); 2300 } 2301 2302 /** 2303 * Whether this statement is MySQL SQL: {@link EDbVendor#dbvmysql}, or {@link EDbVendor#dbvoceanbase} in a MySQL or 2304 * system tenant ({@link TGSqlParser#getOBTenantMode()}). 2305 * 2306 * @return true for MySQL SQL 2307 */ 2308 public boolean isMySQLDialect(){ 2309 return isMySQLDialect(dbvendor, getGsqlparser()); 2310 } 2311 2312 /** 2313 * Whether SQL of {@code vendor} parsed by {@code parser} is MySQL SQL: {@link EDbVendor#dbvmysql}, or 2314 * {@link EDbVendor#dbvoceanbase} in a MySQL or system tenant. For code that holds a node rather than a statement 2315 * (resolver2's ScopeBuilder, TObjectName), which reaches the parser through {@code getGsqlparser()}. 2316 * 2317 * @param vendor the SQL's vendor 2318 * @param parser the parser that produced it, or null when unknown (read as a MySQL tenant) 2319 * @return true for MySQL SQL 2320 */ 2321 public static boolean isMySQLDialect(EDbVendor vendor, TGSqlParser parser){ 2322 if (vendor == EDbVendor.dbvmysql) return true; 2323 if (vendor != EDbVendor.dbvoceanbase) return false; 2324 return (parser == null) || (parser.getOBTenantMode() != EOBTenantMode.ORACLE); 2325 } 2326 2327 public boolean locateVariableOrParameter(TObjectName cr, boolean checkVariableDeclaredInProcedure){ 2328 boolean ret = false; 2329 if (cr.getDbObjectType() == EDbObjectType.variable) return true; 2330 if (cr.toString().equalsIgnoreCase("*")) return false; 2331 //search variable in framestack 2332 2333 TVariable symbolVariable = null; 2334 2335 if (cr.getTableToken() != null){ 2336 // record_variable.column 2337 symbolVariable = TSymbolTableManager.searchSymbolVariable(this.getFrameStack(),cr.getTableToken().toString()); 2338 if (symbolVariable != null){ 2339 cr.getTableToken().setDbObjectType(EDbObjectType.variable); 2340 //TTable sourceTable = new TTable(new TObjectName(EDbObjectType.table,symbolVariable.getVariableName().getStartToken())); 2341 TTable sourceTable = new TTable(TObjectName.createObjectName (this.dbvendor, EDbObjectType.variable,symbolVariable.getVariableName().getStartToken())); 2342 sourceTable.getLinkedColumns().addObjectName(cr); 2343 cr.setSourceTable(sourceTable); 2344 // symbolVariable.getVariableName().getReferencedObjects().addObjectName(cr); 2345 // System.out.println("find variable:"+cr.toString()); 2346 cr.setResolveStatus(TBaseType.RESOLVED_AND_FOUND); // set resolve status to resolved,避免在 TAttributeResolver 中关联到其他 table 2347 return true; 2348 } 2349 2350 }else{ 2351 // variable 2352 symbolVariable = TSymbolTableManager.searchSymbolVariable(this.getFrameStack(),cr.toString()); 2353 if (symbolVariable != null){ 2354 cr.setDbObjectType(EDbObjectType.variable); 2355 symbolVariable.getVariableName().getReferencedObjects().addObjectName(cr); 2356 return true; 2357 } 2358 } 2359 2360 // check parameters in plsql and MySQL routines only, may add support for sql server later. 2361 // MySQL includes an OceanBase MySQL/system tenant (Mantis 4813): a DECLAREd variable of the routine is read 2362 // as that variable there too, also when a table of the statement has a column of the same name. 2363 if(! ((dbvendor == EDbVendor.dbvoracle)||isMySQLDialect())) return false; 2364 if (cr.getObjectType() == TObjectName.ttobjVariable) return true; 2365 2366 Stack symbolTable = this.getTopStatement().getSymbolTable(); 2367 TSymbolTableItem item = null; 2368 TObjectName objName = null; 2369 TObjectName qualifiedName = null; // function/procedure name or label name of plsql block 2370 for (int i = symbolTable.size()-1;i>=0;i--){ 2371 item = (TSymbolTableItem)symbolTable.get(i); 2372 if (item.getData() instanceof TParameterDeclaration){ 2373 objName = ((TParameterDeclaration)item.getData()).getParameterName(); 2374 }else if (item.getData() instanceof TVarDeclStmt){ 2375 objName = ((TVarDeclStmt)item.getData()).getElementName(); 2376 }else if (item.getData() instanceof TObjectName){ 2377 objName = (TObjectName)item.getData(); 2378 } 2379 2380 if (objName == null) continue; 2381 2382 // strip quote characters so a quoted declaration ("P_DATE" IN NUMBER) 2383 // still matches an unquoted reference P_DATE (MantisBT 4504) 2384 if (TBaseType.getTextWithoutQuoted(cr.toString()) 2385 .compareToIgnoreCase(TBaseType.getTextWithoutQuoted(objName.toString())) == 0){ 2386 ret = true; 2387 if (checkVariableDeclaredInProcedure) break; // return true if variable declared in procedure 2388 // a base table of the statement whose catalog gives it the column makes the name that column, whichever 2389 // table it is (redundancy plan C3e: this loop stepped the symbol index, so it checked the first table 2390 // only, and no table once the symbol's place reached the number of tables) 2391 for(int j=0;j<tables.size();j++){ 2392 TTable lcTable = tables.getTable(j); 2393 if (lcTable.isBaseTable()){ 2394 if (fireOnMetaDatabaseTableColumn( 2395 lcTable.getPrefixServer() 2396 ,lcTable.getPrefixDatabase() 2397 ,lcTable.getPrefixSchema() 2398 ,lcTable.getName() 2399 ,cr.getColumnNameOnly())){ 2400 ret = false; 2401 break; 2402 } 2403 } 2404 } 2405 2406 if (ret) break; 2407 }else if (cr.toString().indexOf(".")>0){ 2408 // qualified object reference, compare it with procedure/function/block label prefixed 2409 if (item.getStmt() instanceof TPlsqlCreateFunction){ 2410 qualifiedName = ((TPlsqlCreateFunction)item.getStmt()).getFunctionName(); 2411 }else if (item.getStmt() instanceof TPlsqlCreateProcedure){ 2412 qualifiedName = ((TPlsqlCreateProcedure)item.getStmt()).getProcedureName(); 2413 }else if (item.getStmt() instanceof TCommonBlock){ 2414 qualifiedName = ((TCommonBlock)item.getStmt()).getLabelName(); 2415 } 2416 2417 if (qualifiedName != null){ 2418 if (TBaseType.getTextWithoutQuoted(cr.toString()).compareToIgnoreCase( 2419 TBaseType.getTextWithoutQuoted(qualifiedName.toString()) + '.' 2420 + TBaseType.getTextWithoutQuoted(objName.toString())) == 0){ 2421 ret = true; 2422 } 2423 } 2424 2425 if (ret ) break; 2426 } 2427 2428 } 2429 if (ret){ 2430 //add this parameter or variable reference to original parameter/variable 2431 objName.getReferencedObjects().addObjectName(cr); 2432 cr.setObjectType(TObjectName.ttobjVariable); 2433 } 2434 return ret; 2435 } 2436 2437 /** 2438 * @deprecated since 2.3.8.2, use {@link TTable#getExpandedStarColumns()} instead. 2439 * 2440 * @param lcTable 2441 * @return 2442 */ 2443 public ArrayList<String> getColumnsInTable(TTable lcTable){ 2444 if (lcTable.isCTEName()){ 2445 ArrayList<String> columns = new ArrayList<>(); 2446 if (lcTable.getCteColomnReferences()!=null){ 2447 for(TObjectName n:lcTable.getCteColomnReferences()){ 2448 columns.add(n.toString()); 2449 } 2450 }else if (lcTable.getCTE().getSubquery() != null && lcTable.getCTE().getSubquery().getResultColumnList() != null){ 2451 for(TResultColumn resultColumn:lcTable.getCTE().getSubquery().getResultColumnList()){ 2452 columns.add(resultColumn.getDisplayName()); 2453 } 2454 } 2455 return columns; 2456 }else{ 2457 return getColumnsInTable( 2458 lcTable.getPrefixServer() 2459 ,lcTable.getPrefixDatabase() 2460 ,lcTable.getPrefixSchema() 2461 ,lcTable.getName() 2462 ); 2463 } 2464 } 2465 2466 2467 /** 2468 * @deprecated since 2.3.8.2, use {@link TTable#getExpandedStarColumns()} instead. 2469 * 2470 * @param pServer 2471 * @param pDatabase 2472 * @param pSchema 2473 * @param pTable 2474 * @return 2475 */ 2476 public ArrayList<String> getColumnsInTable(String pServer,String pDatabase,String pSchema,String pTable){ 2477 TFrame stackFrame = getFrameStack().firstElement(); 2478 TGlobalScope globalScope = (TGlobalScope)stackFrame.getScope(); 2479 2480 if (globalScope.getSqlEnv() != null){ 2481 return globalScope.getSqlEnv().getColumnsInTable(pDatabase+"."+pSchema+"."+pTable,false); 2482 }else{ 2483 return null; 2484 } 2485 } 2486 2487 2488 public boolean fireOnMetaDatabaseTableColumn(String pServer,String pDatabase,String pSchema,String pTable,String pColumn){ 2489// boolean lcResult = false; 2490// if (this.getGsqlparser().getMetaDatabase() != null){ 2491// lcResult = this.getGsqlparser().getMetaDatabase().checkColumn(pServer,pDatabase,pSchema,pTable,pColumn); 2492// } 2493 2494 TFrame stackFrame = getFrameStack().firstElement(); 2495 TGlobalScope globalScope = (TGlobalScope)stackFrame.getScope(); 2496 2497 // A table the script declared before this statement, which the catalog gets only after the parse (Mantis 4797). 2498 TSQLTable declared = ParseTimeCatalog.searchTable(this, pDatabase, pSchema, pTable); 2499 if (declared != null) return declared.searchColumn(pColumn); 2500 2501 if (globalScope.getSqlEnv() != null){ 2502 // System.out.println(globalScope.getSqlEnv().toString()); 2503 2504 return globalScope.getSqlEnv().columnInTable(pDatabase+"."+pSchema+"."+pTable,pColumn); 2505 }else{ 2506 return false; 2507 } 2508 2509// return lcResult; 2510 } 2511 2512 /** 2513 * The tables of this statement after the one at {@code index}, which the catalog gives the unqualified column 2514 * {@code pColumn}, that the catalog gives it too: with one of them the name is ambiguous. Empty when a join merges 2515 * the columns of that name (USING it, or NATURAL). A reference to the same table under the same name is the same 2516 * relation, as the target of an UPDATE or DELETE that its FROM names again. 2517 */ 2518 private List<TTable> otherTablesWithColumn(TObjectName pColumn, int index){ 2519 List<TTable> lcOthers = null; 2520 TTable lcTable = tables.getTable(index); 2521 TSQLTable lcFirst = null; 2522 for (int j = index + 1; j < tables.size(); j++){ 2523 TTable lcOther = tables.getTable(j); 2524 if ((!lcOther.isBaseTable()) || (lcOther.getEffectType() == ETableEffectType.tetSelectInto) 2525 || (lcOther.getEffectType() == ETableEffectType.tetImplicitLateralDerivedTable)) continue; 2526 if (!fireOnMetaDatabaseTableColumn(lcOther.getPrefixServer(), lcOther.getPrefixDatabase(), 2527 lcOther.getPrefixSchema(), lcOther.getName(), pColumn.getColumnNameOnly())) continue; 2528 if (lcFirst == null) lcFirst = metadataTableOf(lcTable); 2529 if ((lcFirst != null) && (lcFirst == metadataTableOf(lcOther)) && SQLUtil.compareIdentifier(dbvendor, 2530 ESQLDataObjectType.dotTable, exposedName(lcOther), exposedName(lcTable))) continue; 2531 if (lcOthers == null) lcOthers = new ArrayList<>(); 2532 lcOthers.add(lcOther); 2533 } 2534 if ((lcOthers == null) || mergesJoinColumn(pColumn)) return Collections.emptyList(); 2535 return lcOthers; 2536 } 2537 2538 /** 2539 * Whether this is a SELECT written as a derived table in a FROM clause, LATERAL or not, as resolver2 tells it from 2540 * a subquery in an expression ({@code SelectScope.isCorrelated()}): where its own tables may have a name, the 2541 * name is theirs. 2542 */ 2543 private boolean isDerivedTableInFrom(){ 2544 if (!(this instanceof TSelectSqlStatement)) return false; 2545 ESqlClause lcLocation = ((TSelectSqlStatement) this).getLocation(); 2546 return (lcLocation == ESqlClause.join) || (lcLocation == ESqlClause.elTable); 2547 } 2548 2549 /** The name a statement reads {@code table} by: its alias, else its own name. */ 2550 private static String exposedName(TTable table){ 2551 return table.getAliasName().isEmpty() ? table.getName() : table.getAliasName(); 2552 } 2553 2554 /** 2555 * Whether the catalog proves {@code table} has no column named like the unqualified {@code pColumn}: a base table 2556 * whose columns it all knows ({@link TSQLTable#hasAllColumnsKnown()}). 2557 */ 2558 private boolean provablyLacksColumn(TTable table, TObjectName pColumn){ 2559 if ((table == null) || (!table.isBaseTable()) || pColumn.isQualified()) return false; 2560 TSQLTable lcMetadata = metadataTableOf(table); 2561 return (lcMetadata != null) && lcMetadata.hasAllColumnsKnown() 2562 && (!lcMetadata.searchColumn(pColumn.getColumnNameOnly())); 2563 } 2564 2565 /** The catalog table whose columns {@link #fireOnMetaDatabaseTableColumn} reads for {@code table}, or null. */ 2566 private TSQLTable metadataTableOf(TTable table){ 2567 TSQLTable declared = ParseTimeCatalog.searchTable(this, table.getPrefixDatabase(), table.getPrefixSchema(), 2568 table.getName()); 2569 if (declared != null) return declared; 2570 TSQLEnv lcEnv = ((getFrameStack() != null) && (!getFrameStack().isEmpty())) 2571 ? ((TGlobalScope) getFrameStack().firstElement().getScope()).getSqlEnv() : getSqlEnv(); 2572 return (lcEnv == null) ? null 2573 : lcEnv.searchTable(table.getPrefixDatabase() + "." + table.getPrefixSchema() + "." + table.getName()); 2574 } 2575 2576 /** Whether a join of this statement merges the columns named {@code pColumnName}: USING that name, or NATURAL. */ 2577 public boolean mergesJoinColumn(String pColumnName){ 2578 if (pColumnName == null) return false; 2579 return joinsMerge(pColumnName, false); 2580 } 2581 2582 /** Whether a join of this statement merges the columns named like {@code pColumn}: USING that name, or NATURAL. */ 2583 public boolean mergesJoinColumn(TObjectName pColumn){ 2584 return joinsMerge(pColumn.getColumnNameOnly(), false); 2585 } 2586 2587 /** Whether a join of this statement merges any column: a USING join, or a NATURAL one. */ 2588 public boolean hasMergingJoin(){ 2589 return joinsMerge(null, true); 2590 } 2591 2592 /** 2593 * Searches the joins {@link #joinColumnExposures} walks for one that merges {@code pColumnName}, or any column when 2594 * {@code pAnyColumn}: the join expressions under the relations, and the legacy joins with the joins nested in them 2595 * and in their items (Teradata {@code ABORT FROM (a JOIN b USING (c))} has only the legacy ones), without recursion. 2596 */ 2597 private boolean joinsMerge(String pColumnName, boolean pAnyColumn){ 2598 Deque<TJoinExpr> lcPending = new ArrayDeque<>(); 2599 for (TTable lcRelation : getRelations()) pushJoinExpr(lcPending, lcRelation); 2600 Deque<TJoin> lcLegacy = new ArrayDeque<>(); 2601 for (int i = 0; (joins != null) && (i < joins.size()); i++){ 2602 if (joins.getJoin(i) != null) lcLegacy.push(joins.getJoin(i)); 2603 } 2604 while (!lcPending.isEmpty() || !lcLegacy.isEmpty()){ 2605 if (!lcPending.isEmpty()){ 2606 TJoinExpr lcJoin = lcPending.pop(); 2607 if (joinMerges(lcJoin.getJointype(), lcJoin.getUsingColumns(), pColumnName, pAnyColumn)) return true; 2608 pushJoinExpr(lcPending, lcJoin.getLeftTable()); 2609 pushJoinExpr(lcPending, lcJoin.getRightTable()); 2610 continue; 2611 } 2612 TJoin lcJoin = lcLegacy.pop(); 2613 pushJoinExpr(lcPending, lcJoin.getTable()); 2614 if (lcJoin.getJoin() != null) lcLegacy.push(lcJoin.getJoin()); 2615 for (int k = 0; (lcJoin.getJoinItems() != null) && (k < lcJoin.getJoinItems().size()); k++){ 2616 TJoinItem lcItem = lcJoin.getJoinItems().getJoinItem(k); 2617 if (lcItem == null) continue; 2618 if (joinMerges(lcItem.getJoinType(), lcItem.getUsingColumns(), pColumnName, pAnyColumn)) return true; 2619 pushJoinExpr(lcPending, lcItem.getTable()); 2620 if (lcItem.getJoin() != null) lcLegacy.push(lcItem.getJoin()); 2621 } 2622 } 2623 return false; 2624 } 2625 2626 private static void pushJoinExpr(Deque<TJoinExpr> pPending, TTable pTable){ 2627 if ((pTable != null) && (pTable.getJoinExpr() != null)) pPending.push(pTable.getJoinExpr()); 2628 } 2629 2630 private boolean joinMerges(EJoinType joinType, TObjectNameList usingColumns, String pColumnName, 2631 boolean pAnyColumn){ 2632 if (!pAnyColumn) return mergesJoinColumn(joinType, usingColumns, pColumnName); 2633 // a USING list merges its columns; without one, the name test is the NATURAL test 2634 return ((usingColumns != null) && (usingColumns.size() > 0)) || mergesJoinColumn(joinType, null, null); 2635 } 2636 2637 /** 2638 * One column an unqualified name can read in the FROM clause of a statement: the relations a chain of USING or 2639 * NATURAL joins merged into it ({@link #getMembers()}), and those whose column its value is ({@link #getOwners()}), 2640 * left first. A relation that no join merges is a column of its own. 2641 */ 2642 public static final class JoinColumnExposure { 2643 private final List<TTable> members = new ArrayList<>(); 2644 private final List<TTable> owners = new ArrayList<>(); 2645 2646 private JoinColumnExposure(){ 2647 } 2648 2649 public List<TTable> getMembers(){ 2650 return Collections.unmodifiableList(members); 2651 } 2652 2653 /** INNER and LEFT joins keep the left side's owners, RIGHT the right side's, FULL both (COALESCE). */ 2654 public List<TTable> getOwners(){ 2655 return Collections.unmodifiableList(owners); 2656 } 2657 2658 public boolean hasMember(TTable pTable){ 2659 for (TTable lcTable : members){ 2660 if (lcTable == pTable) return true; 2661 } 2662 return false; 2663 } 2664 } 2665 2666 /** 2667 * The columns an unqualified name can read in this statement's FROM clause, one per {@link JoinColumnExposure}: 2668 * {@code pCandidates} are the relations that have the column (TSQLResolver2's candidates), {@code pDeclared} those 2669 * that declare it. A USING join on the name, or a NATURAL join of two sides that both declare it, merges the one 2670 * column of each side into one, whose value comes from the left side for INNER and LEFT, the right side for RIGHT 2671 * and both sides for FULL; any other join keeps both sides' columns (a NATURAL join of a side whose columns are 2672 * unknown proves nothing). Two or more exposures make the name ambiguous (root-cause program step 5). 2673 */ 2674 public List<JoinColumnExposure> joinColumnExposures(String pColumnName, java.util.Collection<TTable> pCandidates, 2675 java.util.Collection<TTable> pDeclared){ 2676 Set<TTable> lcCandidates = Collections.newSetFromMap(new IdentityHashMap<TTable, Boolean>()); 2677 if (pCandidates != null) lcCandidates.addAll(pCandidates); 2678 Set<TTable> lcDeclared = Collections.newSetFromMap(new IdentityHashMap<TTable, Boolean>()); 2679 if (pDeclared != null) lcDeclared.addAll(pDeclared); 2680 List<JoinColumnExposure> lcOut = new ArrayList<>(); 2681 boolean lcJoinExprs = false; 2682 for (TTable lcRelation : getRelations()){ 2683 if ((lcRelation != null) && (lcRelation.getJoinExpr() != null)) lcJoinExprs = true; 2684 } 2685 if (lcJoinExprs || (joins == null)){ 2686 for (TTable lcRelation : getRelations()){ 2687 if (lcRelation != null) lcOut.addAll(exposuresOf(lcRelation, pColumnName, lcCandidates, lcDeclared)); 2688 } 2689 return lcOut; 2690 } 2691 for (int i = 0; i < joins.size(); i++){ 2692 if (joins.getJoin(i) != null) lcOut.addAll(exposuresOf(joins.getJoin(i), pColumnName, lcCandidates, lcDeclared)); 2693 } 2694 return lcOut; 2695 } 2696 2697 /** The exposures of one FROM item: a relation, or a join expression evaluated bottom-up without recursion. */ 2698 private List<JoinColumnExposure> exposuresOf(TTable pItem, String pColumnName, Set<TTable> pCandidates, 2699 Set<TTable> pDeclared){ 2700 Map<TTable, List<JoinColumnExposure>> lcDone = new IdentityHashMap<>(); 2701 Deque<TTable> lcPending = new ArrayDeque<>(); 2702 lcPending.push(pItem); 2703 while (!lcPending.isEmpty()){ 2704 TTable lcNode = lcPending.peek(); 2705 TJoinExpr lcJoin = lcNode.getJoinExpr(); 2706 if (lcJoin == null){ 2707 lcPending.pop(); 2708 lcDone.put(lcNode, leafExposures(lcNode, pCandidates)); 2709 continue; 2710 } 2711 TTable lcLeft = lcJoin.getLeftTable(), lcRight = lcJoin.getRightTable(); 2712 if ((lcLeft != null) && !lcDone.containsKey(lcLeft)){ 2713 lcPending.push(lcLeft); 2714 continue; 2715 } 2716 if ((lcRight != null) && !lcDone.containsKey(lcRight)){ 2717 lcPending.push(lcRight); 2718 continue; 2719 } 2720 lcPending.pop(); 2721 lcDone.put(lcNode, mergeExposures(lcLeft == null ? null : lcDone.get(lcLeft), 2722 lcRight == null ? null : lcDone.get(lcRight), lcJoin.getJointype(), 2723 mergesJoinColumn(lcJoin.getJointype(), lcJoin.getUsingColumns(), pColumnName), pDeclared)); 2724 } 2725 return lcDone.get(pItem); 2726 } 2727 2728 /** The exposures of a legacy join: its start, then each item joined to everything before it. */ 2729 private List<JoinColumnExposure> exposuresOf(TJoin pJoin, String pColumnName, Set<TTable> pCandidates, 2730 Set<TTable> pDeclared){ 2731 List<JoinColumnExposure> lcLeft = new ArrayList<>(); 2732 if (pJoin.getTable() != null) lcLeft.addAll(exposuresOf(pJoin.getTable(), pColumnName, pCandidates, pDeclared)); 2733 if (pJoin.getJoin() != null) lcLeft.addAll(exposuresOf(pJoin.getJoin(), pColumnName, pCandidates, pDeclared)); 2734 for (int k = 0; (pJoin.getJoinItems() != null) && (k < pJoin.getJoinItems().size()); k++){ 2735 TJoinItem lcItem = pJoin.getJoinItems().getJoinItem(k); 2736 if (lcItem == null) continue; 2737 List<JoinColumnExposure> lcRight = new ArrayList<>(); 2738 if (lcItem.getTable() != null) lcRight.addAll(exposuresOf(lcItem.getTable(), pColumnName, pCandidates, pDeclared)); 2739 if (lcItem.getJoin() != null) lcRight.addAll(exposuresOf(lcItem.getJoin(), pColumnName, pCandidates, pDeclared)); 2740 lcLeft = mergeExposures(lcLeft, lcRight, lcItem.getJoinType(), 2741 mergesJoinColumn(lcItem.getJoinType(), lcItem.getUsingColumns(), pColumnName), pDeclared); 2742 } 2743 return lcLeft; 2744 } 2745 2746 private static List<JoinColumnExposure> leafExposures(TTable pTable, Set<TTable> pCandidates){ 2747 List<JoinColumnExposure> lcOut = new ArrayList<>(); 2748 if (pCandidates.contains(pTable)){ 2749 JoinColumnExposure lcOne = new JoinColumnExposure(); 2750 lcOne.members.add(pTable); 2751 lcOne.owners.add(pTable); 2752 lcOut.add(lcOne); 2753 } 2754 return lcOut; 2755 } 2756 2757 /** 2758 * A join of two sides' exposures: a join that merges the name merges the one column of each side, and keeps both 2759 * otherwise, or when a side does not have exactly one column of the name (an invalid USING proves nothing). 2760 */ 2761 private static List<JoinColumnExposure> mergeExposures(List<JoinColumnExposure> pLeft, 2762 List<JoinColumnExposure> pRight, EJoinType pJoinType, boolean pMerges, Set<TTable> pDeclared){ 2763 // the sides' lists are not read again: the left one is extended in place, so a long chain copies nothing 2764 List<JoinColumnExposure> lcOut = pLeft != null ? pLeft : new ArrayList<JoinColumnExposure>(); 2765 boolean lcNatural = (pJoinType != null) && pJoinType.name().startsWith("natural"); 2766 if (pMerges && lcNatural && (pLeft != null) && (pRight != null)){ 2767 // a NATURAL join merges the columns both sides HAVE: only declared columns say so 2768 for (JoinColumnExposure lcSide : pLeft) if (!pDeclared.containsAll(lcSide.members)) pMerges = false; 2769 for (JoinColumnExposure lcSide : pRight) if (!pDeclared.containsAll(lcSide.members)) pMerges = false; 2770 } 2771 if (!pMerges || (pLeft == null) || (pRight == null) || (pLeft.size() != 1) || (pRight.size() != 1)){ 2772 if (pRight != null) lcOut.addAll(pRight); 2773 return lcOut; 2774 } 2775 JoinColumnExposure lcLeft = pLeft.get(0), lcRight = pRight.get(0); 2776 JoinColumnExposure lcMerged = lcLeft; 2777 lcMerged.members.addAll(lcRight.members); 2778 int lcSide = mergedValueSide(pJoinType); 2779 if (lcSide == MERGED_FROM_RIGHT) lcMerged.owners.clear(); 2780 if (lcSide != MERGED_FROM_LEFT) lcMerged.owners.addAll(lcRight.owners); 2781 return lcOut; 2782 } 2783 2784 private static final int MERGED_FROM_LEFT = 0, MERGED_FROM_RIGHT = 1, MERGED_FROM_BOTH = 2; 2785 2786 /** The side a merged column's value comes from: the left for INNER and LEFT, the right for RIGHT, both for FULL. */ 2787 private static int mergedValueSide(EJoinType pJoinType){ 2788 if (pJoinType != null){ 2789 switch (pJoinType){ 2790 case right: case rightouter: case natural_right: case natural_rightouter: 2791 return MERGED_FROM_RIGHT; 2792 case full: case fullouter: case natural_full: case natural_fullouter: 2793 return MERGED_FROM_BOTH; 2794 default: 2795 break; 2796 } 2797 } 2798 return MERGED_FROM_LEFT; 2799 } 2800 2801 /** 2802 * The order of the columns {@code SELECT *} reads over a JOIN ... USING or a NATURAL JOIN (Mantis 5056), measured 2803 * 2026-10-25 over derived tables of literals: 2804 * <ul> 2805 * <li>{@link #USING_FIRST}, PostgreSQL 16.15 and Oracle 23ai: the merged columns first, in the USING list's order 2806 * (a NATURAL join's in the left side's order), then the left side's other columns, then the right side's, 2807 * for every join type;</li> 2808 * <li>{@link #FIRST_TABLE}, MySQL 8.4: the merged columns first in the first table's order, then the first 2809 * table's other columns, then the other side's; a RIGHT JOIN's first table is its right side;</li> 2810 * <li>{@link #LEFT_SLOT}, DuckDB 1.4.4: the left side's columns in place, a merged column in the left side's 2811 * slot, then the right side's other columns. A vendor whose order was not measured keeps it.</li> 2812 * </ul> 2813 */ 2814 public enum StarJoinOrder { 2815 LEFT_SLOT, USING_FIRST, FIRST_TABLE; 2816 2817 public static StarJoinOrder of(EDbVendor pVendor){ 2818 if ((pVendor == EDbVendor.dbvpostgresql) || (pVendor == EDbVendor.dbvoracle)) return USING_FIRST; 2819 if (pVendor == EDbVendor.dbvmysql) return FIRST_TABLE; 2820 return LEFT_SLOT; 2821 } 2822 } 2823 2824 /** 2825 * One column {@code SELECT *} reads over a FROM item (Mantis 5052, 5056), or a run: the columns of a relation 2826 * whose columns are not known, without the merged names it is known to have. 2827 */ 2828 public static final class StarJoinColumn { 2829 private final String name; 2830 private final TTable relation; 2831 private final List<TTable> members = new ArrayList<>(); 2832 private final List<TTable> owners = new ArrayList<>(); 2833 private final List<String> excluded = new ArrayList<>(); 2834 private final List<TTable> candidates = new ArrayList<>(); 2835 private boolean merged; 2836 private boolean placed = true; 2837 2838 private StarJoinColumn(String pName, TTable pRelation){ 2839 name = pName; 2840 relation = pRelation; 2841 } 2842 2843 private static StarJoinColumn named(String pName, TTable pTable){ 2844 StarJoinColumn lcColumn = new StarJoinColumn(pName, null); 2845 lcColumn.members.add(pTable); 2846 lcColumn.owners.add(pTable); 2847 return lcColumn; 2848 } 2849 2850 /** The column's name; null for a run. */ 2851 public String getName(){ 2852 return name; 2853 } 2854 2855 public boolean isRun(){ 2856 return relation != null; 2857 } 2858 2859 /** A run's relation. */ 2860 public TTable getRelation(){ 2861 return relation; 2862 } 2863 2864 /** The relations whose column this is, left first: two or more for a merged column. */ 2865 public List<TTable> getMembers(){ 2866 return Collections.unmodifiableList(members); 2867 } 2868 2869 /** The relations whose column its value is: the merge's owners for a merged column. */ 2870 public List<TTable> getOwners(){ 2871 return Collections.unmodifiableList(owners); 2872 } 2873 2874 public boolean isMerged(){ 2875 return merged || members.size() > 1; 2876 } 2877 2878 /** 2879 * The relations one of which a merged column's value is the column of, where a side the value is read from 2880 * holds the name through two or more relations whose columns are not known: the USING list proves the side has 2881 * it, never which relation does. Empty otherwise. 2882 */ 2883 public List<TTable> getCandidates(){ 2884 return Collections.unmodifiableList(candidates); 2885 } 2886 2887 /** The merged names a run leaves out: its relation's columns that a join merged into a column of its own. */ 2888 public List<String> getExcluded(){ 2889 return Collections.unmodifiableList(excluded); 2890 } 2891 2892 /** 2893 * Whether the column stands where the list puts it once every column before it is placed: false for a merged 2894 * column whose place among the merged columns follows a relation whose columns are not known. 2895 */ 2896 public boolean isPlaced(){ 2897 return placed; 2898 } 2899 } 2900 2901 /** 2902 * The columns {@code SELECT *} reads over this statement's FROM clause, in order: its relations side by side, each 2903 * join merging once the columns its USING list or NATURAL keyword merges, with the merge's owners as in 2904 * {@link #joinColumnExposures} (INNER and LEFT the left side's, RIGHT the right side's, FULL both), placed as 2905 * {@link StarJoinOrder#of} the vendor says. {@code pColumns} gives a relation's column names in order, or null when 2906 * they are not known, which makes the relation a run. A USING name is a column of both sides even then; a NATURAL 2907 * join of a side with a run merges nothing, because no declaration proves the shared names. 2908 */ 2909 public List<StarJoinColumn> starJoinColumns(java.util.function.Function<TTable, List<String>> pColumns){ 2910 List<StarJoinColumn> lcOut = new ArrayList<>(); 2911 boolean lcJoinExprs = false; 2912 for (TTable lcRelation : getRelations()){ 2913 if ((lcRelation != null) && (lcRelation.getJoinExpr() != null)) lcJoinExprs = true; 2914 } 2915 if (lcJoinExprs || (joins == null)){ 2916 for (TTable lcRelation : getRelations()){ 2917 if (lcRelation != null) lcOut.addAll(starColumnsOf(lcRelation, pColumns)); 2918 } 2919 return lcOut; 2920 } 2921 for (int i = 0; i < joins.size(); i++){ 2922 if (joins.getJoin(i) != null) lcOut.addAll(starColumnsOf(joins.getJoin(i), pColumns)); 2923 } 2924 return lcOut; 2925 } 2926 2927 /** {@link #starJoinColumns} of one FROM item: a relation, or a join expression evaluated bottom-up without recursion. */ 2928 public List<StarJoinColumn> starColumnsOf(TTable pItem, java.util.function.Function<TTable, List<String>> pColumns){ 2929 Map<TTable, List<StarJoinColumn>> lcDone = new IdentityHashMap<>(); 2930 Deque<TTable> lcPending = new ArrayDeque<>(); 2931 lcPending.push(pItem); 2932 while (!lcPending.isEmpty()){ 2933 TTable lcNode = lcPending.peek(); 2934 TJoinExpr lcJoin = lcNode.getJoinExpr(); 2935 if (lcJoin == null){ 2936 lcPending.pop(); 2937 lcDone.put(lcNode, leafStarColumns(lcNode, pColumns)); 2938 continue; 2939 } 2940 TTable lcLeft = lcJoin.getLeftTable(), lcRight = lcJoin.getRightTable(); 2941 if ((lcLeft != null) && !lcDone.containsKey(lcLeft)){ 2942 lcPending.push(lcLeft); 2943 continue; 2944 } 2945 if ((lcRight != null) && !lcDone.containsKey(lcRight)){ 2946 lcPending.push(lcRight); 2947 continue; 2948 } 2949 lcPending.pop(); 2950 lcDone.put(lcNode, joinStarColumns(lcLeft == null ? new ArrayList<StarJoinColumn>() : lcDone.get(lcLeft), 2951 lcRight == null ? new ArrayList<StarJoinColumn>() : lcDone.get(lcRight), lcJoin.getJointype(), 2952 lcJoin.getUsingColumns())); 2953 } 2954 return lcDone.get(pItem); 2955 } 2956 2957 /** {@link #starJoinColumns} of a legacy join: its start, then each item joined to everything before it. */ 2958 private List<StarJoinColumn> starColumnsOf(TJoin pJoin, java.util.function.Function<TTable, List<String>> pColumns){ 2959 List<StarJoinColumn> lcLeft = new ArrayList<>(); 2960 if (pJoin.getTable() != null) lcLeft.addAll(starColumnsOf(pJoin.getTable(), pColumns)); 2961 if (pJoin.getJoin() != null) lcLeft.addAll(starColumnsOf(pJoin.getJoin(), pColumns)); 2962 for (int k = 0; (pJoin.getJoinItems() != null) && (k < pJoin.getJoinItems().size()); k++){ 2963 TJoinItem lcItem = pJoin.getJoinItems().getJoinItem(k); 2964 if (lcItem == null) continue; 2965 List<StarJoinColumn> lcRight = new ArrayList<>(); 2966 if (lcItem.getTable() != null) lcRight.addAll(starColumnsOf(lcItem.getTable(), pColumns)); 2967 if (lcItem.getJoin() != null) lcRight.addAll(starColumnsOf(lcItem.getJoin(), pColumns)); 2968 lcLeft = joinStarColumns(lcLeft, lcRight, lcItem.getJoinType(), lcItem.getUsingColumns()); 2969 } 2970 return lcLeft; 2971 } 2972 2973 private static List<StarJoinColumn> leafStarColumns(TTable pTable, 2974 java.util.function.Function<TTable, List<String>> pColumns){ 2975 List<StarJoinColumn> lcOut = new ArrayList<>(); 2976 List<String> lcNames = pColumns.apply(pTable); 2977 if (lcNames == null){ 2978 lcOut.add(new StarJoinColumn(null, pTable)); 2979 return lcOut; 2980 } 2981 for (String lcName : lcNames) lcOut.add(StarJoinColumn.named(lcName, pTable)); 2982 return lcOut; 2983 } 2984 2985 /** 2986 * One join of two sides' star columns. Each merged name must be one column of each side, or the run of a side that 2987 * has no column of the name and one run; a name that is not merges nothing (an invalid USING proves nothing). 2988 */ 2989 private List<StarJoinColumn> joinStarColumns(List<StarJoinColumn> pLeft, List<StarJoinColumn> pRight, 2990 EJoinType pJoinType, TObjectNameList pUsing){ 2991 List<String> lcNames = new ArrayList<>(); 2992 if ((pUsing != null) && (pUsing.size() > 0)){ 2993 for (int i = 0; i < pUsing.size(); i++){ 2994 TObjectName lcName = pUsing.getObjectName(i); 2995 if ((lcName != null) && (lcName.getColumnNameOnly() != null)) lcNames.add(lcName.getColumnNameOnly()); 2996 } 2997 } else if ((pJoinType != null) && pJoinType.name().startsWith("natural") 2998 && (runOf(pLeft) == null) && (runOf(pRight) == null)){ 2999 for (StarJoinColumn lcColumn : pLeft){ 3000 if ((starColumnOf(pLeft, lcColumn.name) == lcColumn) && (starColumnOf(pRight, lcColumn.name) != null)){ 3001 lcNames.add(lcColumn.name); 3002 } 3003 } 3004 } 3005 // each merged name with the side columns it merges; a side column found through a run is a new column of it 3006 Map<StarJoinColumn, StarJoinColumn> lcMergedOf = new IdentityHashMap<>(); 3007 List<StarJoinColumn> lcMerged = new ArrayList<>(); 3008 List<StarJoinColumn> lcLeftOf = new ArrayList<>(), lcRightOf = new ArrayList<>(); 3009 for (String lcName : lcNames){ 3010 StarJoinColumn lcLeft = sideColumn(pLeft, lcName), lcRight = sideColumn(pRight, lcName); 3011 if ((lcLeft == null) || (lcRight == null) || lcMergedOf.containsKey(lcLeft) || lcMergedOf.containsKey(lcRight)){ 3012 continue; 3013 } 3014 excludeThroughRun(pLeft, lcLeft, lcName); 3015 excludeThroughRun(pRight, lcRight, lcName); 3016 StarJoinColumn lcColumn = new StarJoinColumn(lcName, null); 3017 lcColumn.merged = true; 3018 lcColumn.members.addAll(lcLeft.members); 3019 lcColumn.members.addAll(lcRight.members); 3020 int lcSide = mergedValueSide(pJoinType); 3021 if (lcSide != MERGED_FROM_RIGHT){ 3022 lcColumn.owners.addAll(lcLeft.owners); 3023 lcColumn.candidates.addAll(lcLeft.candidates); 3024 } 3025 if (lcSide != MERGED_FROM_LEFT){ 3026 lcColumn.owners.addAll(lcRight.owners); 3027 lcColumn.candidates.addAll(lcRight.candidates); 3028 } 3029 // a side that holds the name through several relations of unknown columns gives it no known place 3030 if (lcLeft.members.isEmpty() || lcRight.members.isEmpty()) lcColumn.placed = false; 3031 lcMergedOf.put(lcLeft, lcColumn); 3032 lcMergedOf.put(lcRight, lcColumn); 3033 lcMerged.add(lcColumn); 3034 lcLeftOf.add(lcLeft); 3035 lcRightOf.add(lcRight); 3036 } 3037 List<StarJoinColumn> lcOut = new ArrayList<>(); 3038 StarJoinOrder lcOrder = StarJoinOrder.of(dbvendor); 3039 if (lcMerged.isEmpty() || (lcOrder == StarJoinOrder.LEFT_SLOT)){ 3040 for (StarJoinColumn lcColumn : pLeft){ 3041 StarJoinColumn lcColumnMerged = lcMergedOf.get(lcColumn); 3042 lcOut.add(lcColumnMerged != null ? lcColumnMerged : lcColumn); 3043 if (lcColumn.isRun()){ 3044 // a merged column found through a run has no known slot in it: after the run 3045 for (int i = 0; i < lcMerged.size(); i++){ 3046 if (!pLeft.contains(lcLeftOf.get(i)) && !lcLeftOf.get(i).members.isEmpty() 3047 && (lcLeftOf.get(i).members.get(0) == lcColumn.relation)){ 3048 lcOut.add(lcMerged.get(i)); 3049 } 3050 } 3051 } 3052 } 3053 // one found through several runs: after the left side, unplaced 3054 for (int i = 0; i < lcMerged.size(); i++){ 3055 if (lcLeftOf.get(i).members.isEmpty()) lcOut.add(lcMerged.get(i)); 3056 } 3057 for (StarJoinColumn lcColumn : pRight){ 3058 if (!lcMergedOf.containsKey(lcColumn)) lcOut.add(lcColumn); 3059 } 3060 return lcOut; 3061 } 3062 boolean lcRightFirst = (lcOrder == StarJoinOrder.FIRST_TABLE) && (mergedValueSide(pJoinType) == MERGED_FROM_RIGHT); 3063 List<StarJoinColumn> lcFirst = lcRightFirst ? pRight : pLeft, lcSecond = lcRightFirst ? pLeft : pRight; 3064 if (lcOrder == StarJoinOrder.USING_FIRST){ 3065 lcOut.addAll(lcMerged); 3066 } else { 3067 // the first table's order: its columns as they stand, a column found through its run unplaced among them 3068 List<StarJoinColumn> lcFirstOf = lcRightFirst ? lcRightOf : lcLeftOf; 3069 List<StarJoinColumn> lcThroughRuns = new ArrayList<>(); 3070 for (StarJoinColumn lcColumn : lcFirst){ 3071 int i = lcFirstOf.indexOf(lcColumn); 3072 if (i >= 0) lcOut.add(lcMerged.get(i)); 3073 } 3074 for (int i = 0; i < lcMerged.size(); i++){ 3075 if (!lcFirst.contains(lcFirstOf.get(i))) lcThroughRuns.add(lcMerged.get(i)); 3076 } 3077 if ((lcThroughRuns.size() > 0) && (lcMerged.size() > 1)){ 3078 for (StarJoinColumn lcColumn : lcThroughRuns) lcColumn.placed = false; 3079 } 3080 lcOut.addAll(lcThroughRuns); 3081 } 3082 for (StarJoinColumn lcColumn : lcFirst){ 3083 if (!lcMergedOf.containsKey(lcColumn)) lcOut.add(lcColumn); 3084 } 3085 for (StarJoinColumn lcColumn : lcSecond){ 3086 if (!lcMergedOf.containsKey(lcColumn)) lcOut.add(lcColumn); 3087 } 3088 return lcOut; 3089 } 3090 3091 /** The one run of a side, or null when it has none or several. */ 3092 private static StarJoinColumn runOf(List<StarJoinColumn> pSide){ 3093 StarJoinColumn lcRun = null; 3094 for (StarJoinColumn lcColumn : pSide){ 3095 if (!lcColumn.isRun()) continue; 3096 if (lcRun != null) return null; 3097 lcRun = lcColumn; 3098 } 3099 return lcRun; 3100 } 3101 3102 /** The one column of a side named {@code pName}, or null when it has none or several. */ 3103 private StarJoinColumn starColumnOf(List<StarJoinColumn> pSide, String pName){ 3104 StarJoinColumn lcFound = null; 3105 for (StarJoinColumn lcColumn : pSide){ 3106 if (lcColumn.isRun() || !SQLUtil.compareIdentifier(dbvendor, ESQLDataObjectType.dotColumn, lcColumn.name, pName)){ 3107 continue; 3108 } 3109 if (lcFound != null) return null; 3110 lcFound = lcColumn; 3111 } 3112 return lcFound; 3113 } 3114 3115 /** 3116 * The column of a side a merged name reads: its one column of the name, or, when it has none but exactly one run, 3117 * a new column of the run's relation (the run leaves the name out once the merge is made, excludeThroughRun). 3118 */ 3119 private StarJoinColumn sideColumn(List<StarJoinColumn> pSide, String pName){ 3120 boolean lcAny = false; 3121 List<TTable> lcRuns = new ArrayList<>(); 3122 for (StarJoinColumn lcColumn : pSide){ 3123 if (!lcColumn.isRun() && SQLUtil.compareIdentifier(dbvendor, ESQLDataObjectType.dotColumn, lcColumn.name, pName)){ 3124 lcAny = true; 3125 } 3126 if (lcColumn.isRun()) lcRuns.add(lcColumn.relation); 3127 } 3128 if (lcAny) return starColumnOf(pSide, pName); 3129 if (lcRuns.size() == 1) return StarJoinColumn.named(pName, lcRuns.get(0)); 3130 if (lcRuns.isEmpty()) return null; 3131 // several runs: the USING list proves the side has the name, a column of one of their relations, unknown which 3132 StarJoinColumn lcColumn = new StarJoinColumn(pName, null); 3133 lcColumn.candidates.addAll(lcRuns); 3134 return lcColumn; 3135 } 3136 3137 /** A merged column found through a side's run, or one of its runs: each such run leaves the name out. */ 3138 private static void excludeThroughRun(List<StarJoinColumn> pSide, StarJoinColumn pColumn, String pName){ 3139 if (pSide.contains(pColumn)) return; 3140 for (StarJoinColumn lcRun : pSide){ 3141 if (lcRun.isRun() && (pColumn.members.isEmpty() || pColumn.members.get(0) == lcRun.relation)){ 3142 lcRun.excluded.add(pName); 3143 } 3144 } 3145 } 3146 3147 private boolean mergesJoinColumn(EJoinType joinType, TObjectNameList usingColumns, String pColumnName){ 3148 if (joinType != null){ 3149 switch (joinType){ 3150 case natural: case natural_full: case natural_fullouter: case natural_inner: case natural_left: 3151 case natural_right: case natural_leftouter: case natural_rightouter: 3152 return true; 3153 default: 3154 break; 3155 } 3156 } 3157 if (usingColumns == null) return false; 3158 for (int i = 0; i < usingColumns.size(); i++){ 3159 TObjectName lcName = usingColumns.getObjectName(i); 3160 if ((lcName != null) && SQLUtil.compareIdentifier(dbvendor, ESQLDataObjectType.dotColumn, 3161 lcName.getColumnNameOnly(), pColumnName)) return true; 3162 } 3163 return false; 3164 } 3165 3166 public TTable getFirstPhysicalTable(){ 3167 TTable ret = null; 3168 if (tables.size() == 0) return null; 3169 for(int i=0;i<tables.size();i++){ 3170 if (tables.getTable(i).isBaseTable()) { 3171 ret = tables.getTable(i); 3172 break; 3173 } 3174 } 3175 return ret; 3176 } 3177 private TObjectNameList orphanColumns = null; 3178 3179 public TObjectNameList getOrphanColumns() { 3180 if (orphanColumns == null) orphanColumns = new TObjectNameList(); 3181 return orphanColumns; 3182 } 3183 3184 /** 3185 * Whether the qualifier of a qualified name names this table, by its alias or its name (with the schema when both 3186 * write one): PVT.x names the PIVOT result PVT, s.x names sales s, z.x names neither. 3187 */ 3188 /** 3189 * Whether an unaliased table's name is another table's alias, as {@code A} in 3190 * {@code DELETE A FROM t1 AS A}: only a one-part name can be one ({@code [ds.t1]} is one delimited name, 3191 * never the table {@code ds.t1}), compared as an alias under the analysis's name service (redundancy plan C3b). 3192 */ 3193 protected static boolean isNamedByAlias(IdentifierService names, TTable unaliased, TTable aliased){ 3194 TObjectName name = unaliased.getTableName(); 3195 if ((name == null) || (aliased.getAliasClause() == null) || (name.getSchemaToken() != null) 3196 || (name.getDatabaseToken() != null) || (name.getServerToken() != null)) return false; 3197 // the comparator resolver2 shares (redundancy plan C4b): a one-part name against an exposed name, as an alias 3198 return gudusoft.gsqlparser.nodes.TableQualifierMatch.namesByExposedName(names, 3199 java.util.Collections.singletonList(unaliased.toString()), aliased.getAliasClause().toString()); 3200 } 3201 3202 public static boolean qualifierNamesTable(EDbVendor vendor, TObjectName column, TTable table){ 3203 if ((column == null) || (table == null) || !column.isQualified()) return false; 3204 String qualifier = column.getTableString(); 3205 boolean aliased = (table.getAliasName() != null) && (!table.getAliasName().isEmpty()); 3206 // the alias through the comparator resolver2 shares (redundancy plan C4b), under the vendor's defaults 3207 if (aliased && gudusoft.gsqlparser.nodes.TableQualifierMatch.namesByExposedName( 3208 IdentifierService.forAnalysis(null, vendor), java.util.Collections.singletonList(qualifier), 3209 table.getAliasName())) return true; 3210 String schema = column.getSchemaString(); 3211 // a bare qualifier over an unaliased table names its exposed name, an implicit alias; a qualifier with a schema, 3212 // or the name of an aliased table, is the table's name (BigQuery compares an alias without case, a table with it) 3213 ESQLDataObjectType role = !aliased && SQLUtil.isEmpty(schema) ? ESQLDataObjectType.dotTableAlias 3214 : ESQLDataObjectType.dotTable; 3215 if ((table.getName() == null) || !SQLUtil.sameName(vendor, role, table.getName(), qualifier)) return false; 3216 String tableSchema = (table.getTableName() == null) ? null : table.getTableName().getSchemaString(); 3217 return SQLUtil.isEmpty(schema) || SQLUtil.isEmpty(tableSchema) 3218 || SQLUtil.sameName(vendor, ESQLDataObjectType.dotSchema, tableSchema, schema); 3219 } 3220 3221 /** Dialects whose triggers and OUTPUT clauses read the rows inserted and deleted. */ 3222 private static final java.util.EnumSet<EDbVendor> INSERTED_DELETED_VENDORS = java.util.EnumSet.of( 3223 EDbVendor.dbvmssql, EDbVendor.dbvazuresql, EDbVendor.dbvsybase, EDbVendor.dbvsybasease, 3224 EDbVendor.dbvsybaseiq); 3225 3226 /** 3227 * Whether a fallback may place a qualified name in {@code table}. A qualified name binds only to what its qualifier 3228 * names: z.qtysold FROM sales s has no source (owner ruling 2026-10-24, root-cause program step 5), where the 3229 * fallbacks used to read sales.qtysold. Besides a qualifier that names the table ({@link #qualifierNamesTable}), 3230 * the readings a qualifier has stay: Teradata's implicit table; a trigger row (NEW, OLD, a REFERENCING name; Oracle's 3231 * rows TPlsqlCreateTrigger.correlationOf binds before any fallback) and SQL Server's inserted and deleted; and the 3232 * field of a column head (info.name), where the catalog declares the column head, or the dialect reads fields 3233 * (NestedAccessProfile.readsColumnHeadFields) and the catalog does not prove the table has no such column. SQL Server reads 3234 * the property of a column (g.STX) only of a column the catalog declares. 3235 */ 3236 public boolean mayPlaceQualifiedName(TObjectName column, TTable table){ 3237 return mayPlaceQualifiedName(column, table, null); 3238 } 3239 3240 /** 3241 * {@link #mayPlaceQualifiedName(TObjectName, TTable)}, reading {@code catalog} where the statement no longer has 3242 * its own (its frames are popped once it is parsed; lineage passes the catalog it analyzes with). 3243 */ 3244 public boolean mayPlaceQualifiedName(TObjectName column, TTable table, TSQLEnv catalog){ 3245 if ((column == null) || !column.isQualified()) return true; 3246 if (qualifierNamesTable(dbvendor, column, table)) return true; 3247 if (dbvendor == EDbVendor.dbvteradata) return true; 3248 if (namesTriggerOrOutputRow(column)) return true; 3249 boolean lcFieldDialect = gudusoft.gsqlparser.nodes.structured.NestedAccessProfile.forVendor(dbvendor).readsColumnHeadFields(); 3250 if (!lcFieldDialect && (dbvendor != EDbVendor.dbvmssql) && (dbvendor != EDbVendor.dbvazuresql)) return false; 3251 TSQLTable lcMetadata = ((table == null) || !table.isBaseTable()) ? null : metadataTableOf(table); 3252 if ((lcMetadata == null) && (catalog != null) && (table != null) && table.isBaseTable()){ 3253 lcMetadata = catalog.searchTable(table.getPrefixDatabase() + "." + table.getPrefixSchema() + "." + table.getName()); 3254 } 3255 String lcHead = headOf(column); 3256 if ((lcMetadata != null) && (lcHead != null) && lcMetadata.searchColumn(lcHead)) { 3257 return headAdmitsFields(lcMetadata.getColumn(lcHead), column); 3258 } 3259 if ((lcMetadata != null) && lcMetadata.hasAllColumnsKnown()) return false; 3260 return lcFieldDialect; 3261 } 3262 3263 /** 3264 * Whether the type the catalog declares for the column head admits the fields the name reads below it, as resolver2 3265 * asks (DeclaredTypeReader.admitsFieldPath): an INT has none, a STRUCT whose fields are listed has those. 3266 */ 3267 private boolean headAdmitsFields(gudusoft.gsqlparser.sqlenv.TSQLColumn head, TObjectName column){ 3268 if ((head == null) || (head.getColumnDataType() == null)) return true; 3269 // a STRUCT-tree dialect's fields are its lineage tree's, by the declaration in force (rule R10), as resolver2's 3270 if (gudusoft.gsqlparser.nodes.structured.NestedAccessProfile.forVendor(dbvendor).buildsDeclaredTree()) return true; 3271 boolean lcWildcard = column.isWildcard(); 3272 java.util.List<TSourceToken> lcChain = lcWildcard ? column.getStarQualifierChain() : column.getIdentifierChain(); 3273 java.util.List<String> lcFields = new java.util.ArrayList<String>(); 3274 for (int i = 1; i < lcChain.size(); i++) lcFields.add(lcChain.get(i).toString()); 3275 // the wildcard's segment: admitsFieldPath does not compare it as a name 3276 if (lcWildcard) lcFields.add("*"); 3277 if (lcFields.isEmpty()) return true; 3278 return gudusoft.gsqlparser.common.structured.DeclaredTypeReader.admitsFieldPath(dbvendor, 3279 head.getColumnDataType(), lcFields, lcWildcard); 3280 } 3281 3282 /** The first part of a qualified name: the column whose field head.field would read. */ 3283 private static String headOf(TObjectName column){ 3284 if ((column.getDatabaseToken() != null) && (!column.getDatabaseString().isEmpty())) return column.getDatabaseString(); 3285 if ((column.getSchemaString() != null) && (!column.getSchemaString().isEmpty())) return column.getSchemaString(); 3286 return column.getTableString(); 3287 } 3288 3289 /** NEW, OLD or a REFERENCING name of the enclosing trigger (not Oracle's), or SQL Server's inserted and deleted. */ 3290 private boolean namesTriggerOrOutputRow(TObjectName column){ 3291 TSourceToken lcQualifier = column.getTableToken(); 3292 if (lcQualifier == null) return false; 3293 // the colon of :n.x marks a bind variable, it is no part of the name 3294 String lcName = (lcQualifier.tokentype == ETokenType.ttbindvar) ? lcQualifier.toString().substring(1) : lcQualifier.toString(); 3295 // keywords and pseudo-row names, compared as written: they are no identifiers of the catalog 3296 String lcUpper = lcName.toUpperCase(java.util.Locale.ROOT); 3297 if (INSERTED_DELETED_VENDORS.contains(dbvendor) && (lcUpper.equals("INSERTED") || lcUpper.equals("DELETED"))) return true; 3298 if (dbvendor == EDbVendor.dbvoracle) return false; 3299 if (lcUpper.equals("NEW") || lcUpper.equals("OLD")) return true; 3300 for (TCustomSqlStatement lcStmt = this; lcStmt != null; lcStmt = lcStmt.getParentStmt()){ 3301 if (!(lcStmt instanceof TCreateTriggerStmt)) continue; 3302 TTriggeringClause lcClause = ((TCreateTriggerStmt) lcStmt).getTriggeringClause(); 3303 if ((lcClause == null) || (lcClause.getReferencingClause() == null) 3304 || (lcClause.getReferencingClause().getReferencingItems() == null)) continue; 3305 for (TTriggerReferencingItem lcItem : lcClause.getReferencingClause().getReferencingItems()){ 3306 if ((lcItem.getCorrelationName() != null) && SQLUtil.sameName(dbvendor, ESQLDataObjectType.dotTable, 3307 lcItem.getCorrelationName().toString(), lcName)) return true; 3308 } 3309 } 3310 return false; 3311 } 3312 3313 /** A qualified name the guess declines to place is an orphan column: a column, of no table. */ 3314 private boolean declineQualifiedGuess(TObjectName pColumn){ 3315 pColumn.setDbObjectTypeDirectly(EDbObjectType.column); 3316 getOrphanColumns().addObjectName(pColumn); 3317 pColumn.setOrphanColumn(true); 3318 pColumn.setOwnStmt(this); 3319 return false; 3320 } 3321 3322 protected boolean linkToFirstTable(TObjectName pColumn,int pCandidateTableCnt){ 3323 boolean lcResult = false; 3324 // ClickHouse expression-CTE alias resolved by an outer scope during 3325 // the parent-walk: the reference is a scalar symbol — guessing it onto 3326 // this scope's first table would fabricate lineage (and did, when 3327 // metadata ruled the inner table out and the outer WITH alias won). 3328 if ((pColumn.getExpressionCteRef() != null) && (pColumn.getSourceTable() == null)){ 3329 return true; 3330 } 3331 if ((dbvendor == EDbVendor.dbvteradata)&&(pColumn.isQualified())&&(pColumn.getTableToken().getDbObjectType() != EDbObjectType.subquery_alias)){ 3332 // update table1 set col = 'value' where table1.id = table2.id2 3333 boolean isFoundLinkedTable = false; 3334 TCustomSqlStatement lcSql = this; 3335 while (lcSql != null){ 3336 int i = 0; 3337 i = lcSql.tables.searchTableByNameOrAlias(pColumn.getTableToken().toString()); 3338 isFoundLinkedTable = ( i != -1); 3339 if (isFoundLinkedTable) { 3340 if (lcSql.tables.getTable(i).getEffectType() == ETableEffectType.tetImplicitLateralDerivedTable ){ 3341 // 如果不查重table,会导致 employee.first_name 中的 employee 被第二次加到 tables 中 3342// DELETE FROM foodmart.trimmed_employee ACT 3343// WHERE ACT.employee_id = employee.employee_id 3344// AND employee.first_name = 'Walter' 3345// AND trimmed_salary.employee_id = -1 3346 3347 TTable newTable = lcSql.tables.getTable(i); 3348 newTable.getLinkedColumns().addObjectName(pColumn); 3349 pColumn.setSourceTable(newTable); 3350 pColumn.setValidate_column_status(TBaseType.COLUMN_LINKED_TO_TABLE_IN_OLD_ALGORITHM); 3351 } 3352 break; 3353 } 3354 lcSql = lcSql.getParentStmt(); 3355 } 3356 if (!isFoundLinkedTable){ 3357 TTable newTable = null; 3358 if (pColumn.getDatabaseToken() == null){ 3359 3360 //newTable = new TTable(new TObjectName(EDbObjectType.table,pColumn.getTableToken())); 3361 newTable = new TTable(TObjectName.createObjectName (this.dbvendor, EDbObjectType.table,pColumn.getTableToken())); 3362 newTable.setStartToken(pColumn.getTableToken()); 3363 newTable.setEndToken(pColumn.getTableToken()); 3364 }else{ 3365 3366 //newTable = new TTable(new TObjectName(EDbObjectType.table,pColumn.getSchemaToken(), pColumn.getTableToken())); 3367 newTable = new TTable(TObjectName.createObjectName (this.dbvendor,EDbObjectType.table,pColumn.getDatabaseToken(), pColumn.getTableToken())); 3368 newTable.setStartToken(pColumn.getSchemaToken()); 3369 newTable.setEndToken(pColumn.getTableToken()); 3370 } 3371 3372 newTable.setTableType(ETableSource.objectname); 3373 newTable.setEffectType(ETableEffectType.tetImplicitLateralDerivedTable); 3374 newTable.getLinkedColumns().addObjectName(pColumn); 3375 pColumn.setSourceTable(newTable); 3376 pColumn.setValidate_column_status(TBaseType.COLUMN_LINKED_TO_TABLE_IN_OLD_ALGORITHM); 3377 this.addToTables(newTable); 3378 3379 // 2024 年 3380 // 不能加入到 relations 中,否则会导致 下面 SQL 中 star column 同时链接到 SPCOMM.L_FIXED_RATE_PLAN_REF, ipshare_ofccplv.cprof_d_period_dates_ref 3381 // 从而导致 本来不该有的歧义产生 3382 3383 // UPDATE b_rate_plan 3384 //FROM 3385 //( 3386 //SELECT * FROM SPCOMM.L_FIXED_RATE_PLAN_REF 3387 //WHERE rate_plan_ref_eff_dt<= ipshare_ofccplv.cprof_d_period_dates_ref.PERIOD 3388 //) AS ref 3389 //SET accs_fee = REF.accs_fee, 3390 //SVC_TYPE = REF.prod_grp_lvl_1, 3391 //rate_plan_lvl3 = REF.rate_plan_lvl_3, 3392 //prod_grp_lvl3 = REF.prod_grp_lvl_2 3393 //WHERE b_rate_plan.svc_type IS NULL 3394 3395 // 2025/2/25, v3.0.4.8 3396 // 需要加入到 relations 中,新的 gudusoft.gsqlparser.resolver package 中的算法会处理这种情况 3397 // teradata 的隐式横向派生表不能加入到关系解析器中 3398 // this.getRelations().add(newTable); 3399 } 3400 return true; 3401 } 3402 // a qualified name reaches this guess only when its qualifier named no table: it is placed only in a table the 3403 // qualifier still names (a PIVOT result PVT for PVT.x) or where the qualifier has another reading 3404 // (mayPlaceQualifiedName) 3405 if (pColumn.getCandidateTables().size() == 1){ 3406 TTable table = pColumn.getCandidateTables().getTable(0); 3407 if (!mayPlaceQualifiedName(pColumn, table)) return declineQualifiedGuess(pColumn); 3408 table.getLinkedColumns().addObjectName(pColumn); 3409 pColumn.setSourceTable(table); 3410 lcResult = true; 3411 } 3412 else if ((tables.size() == 1) || (pCandidateTableCnt == 1)){ 3413 TTable table = tables.getTable(0); 3414 if (!mayPlaceQualifiedName(pColumn, table)) return declineQualifiedGuess(pColumn); 3415 3416 if(table.getTableType() == ETableSource.function){ 3417 //lcResult = linkToFunctionTable(table, pColumn); 3418 int iRet = table.getFuncCall().isColumnInThisTableFunction(this.getSqlEnv(),this.dbvendor,pColumn); 3419 if ( iRet == TBaseType.COLUMN_IN_TABEL_FUNCTION_YES){ 3420 lcResult = true; 3421 table.getLinkedColumns().addObjectName(pColumn); 3422 pColumn.setSourceTable(table); 3423 lcResult = true; 3424 }else if ( iRet == TBaseType.COLUMN_IN_TABEL_FUNCTION_NO){ 3425 lcResult = false; 3426 }else{ 3427 table.getLinkedColumns().addObjectName(pColumn); 3428 pColumn.setSourceTable(table); 3429 lcResult = true; 3430 } 3431 }else if(table.getTableType() == ETableSource.subquery){ 3432 if (! table.getSubquery().searchColumnInResultSet(pColumn,(tables.size()==1))){ 3433 getOrphanColumns().addObjectName(pColumn); 3434 pColumn.setOrphanColumn(true); 3435 pColumn.setOwnStmt(this); 3436 TSourceToken st = pColumn.getStartToken(); 3437 if (TBaseType.DUMP_RESOLVER_LOG_TO_CONSOLE){ 3438 TBaseType.log(String.format("Add orphan column <%s> to statement in old algorithm in subquery %s",pColumn.toString(),table.getAliasName()),TLog.WARNING,table); 3439 } 3440 this.parseerrormessagehandle(new TSyntaxError(st.getAstext(), st.lineNo, st.columnNo 3441 ,"find orphan column", EErrorType.sphint 3442 , TBaseType.MSG_HINT_FIND_ORPHAN_COLUMN,this,st.posinlist,pColumn)); 3443 } 3444 } 3445 else{ 3446 table.getLinkedColumns().addObjectName(pColumn); 3447 pColumn.setSourceTable(table); 3448 lcResult = true; 3449 if ((dbvendor == EDbVendor.dbvbigquery)&&(pCandidateTableCnt == 0) && (pColumn.isQualified())){ 3450 // bigquery struct column used in query 3451// create view test as (SELECT rollNo, 3452// info.name as n1, 3453// info2.name as n2, 3454// info.age from my_first_dataset.student_records); 3455 3456 pColumn.columnToProperty(); 3457 } 3458 } 3459 }else if (tables.size() > 1){ 3460 // if there is only a table without table alias, then, link to this table 3461 boolean foundOnlyOneTable = false; 3462 TTable tableWithoutAlias = null; 3463 for(TTable table:tables){ 3464 if (table.isCTEName()) continue; // CTE 即便没有 指定alias,也不作为考虑对象 3465 if (table.getAliasClause() == null){ 3466 tableWithoutAlias = table; 3467 if (foundOnlyOneTable){ 3468 foundOnlyOneTable = false; 3469 break; 3470 }else{ 3471 foundOnlyOneTable = true; 3472 } 3473 } 3474 } 3475 3476 // A guess among several tables never takes one the catalog proves has no such column (Mantis 4797). 3477 boolean lcFoundGuess = foundOnlyOneTable && !provablyLacksColumn(tableWithoutAlias, pColumn); 3478 if (lcFoundGuess && mayPlaceQualifiedName(pColumn, tableWithoutAlias)){ 3479 tableWithoutAlias.getLinkedColumns().addObjectName(pColumn); 3480 pColumn.setSourceTable(tableWithoutAlias); 3481 lcResult = true; 3482 }else{ 3483 if (lcFoundGuess){ 3484 // the guess was declined for a qualified name: it stays a column, of no table 3485 pColumn.setDbObjectTypeDirectly(EDbObjectType.column); 3486 } 3487 getOrphanColumns().addObjectName(pColumn); 3488 pColumn.setOrphanColumn(true); 3489 pColumn.setOwnStmt(this); 3490 TSourceToken st = pColumn.getStartToken(); 3491 if (TBaseType.DUMP_RESOLVER_LOG_TO_CONSOLE){ 3492 TBaseType.log(String.format("Add orphan column <%s> to statement in old algorithm ",pColumn.toString()),TLog.WARNING,this); 3493 } 3494 3495 this.parseerrormessagehandle(new TSyntaxError(st.getAstext(), st.lineNo, st.columnNo 3496 ,"find orphan column", EErrorType.sphint 3497 , TBaseType.MSG_HINT_FIND_ORPHAN_COLUMN,this,st.posinlist,pColumn)); 3498 } 3499 3500 } 3501 return lcResult; 3502 } 3503 3504 private boolean linkToFunctionTable(TTable table, TObjectName pColumn) { 3505 if(table.getTableName().toString().toUpperCase(java.util.Locale.ROOT).equals("STRING_SPLIT")){ 3506 if(pColumn.getColumnNameOnly().toUpperCase(java.util.Locale.ROOT).equals("VALUE")){ 3507 table.getLinkedColumns().addObjectName(pColumn); 3508 pColumn.setSourceTable(table); 3509 return true; 3510 } 3511 else return false; 3512 } 3513 else { 3514 table.getLinkedColumns().addObjectName(pColumn); 3515 pColumn.setSourceTable(table); 3516 return true; 3517 } 3518 } 3519 3520 3521 private TTable findInsertedOrDeleteTable(TTable table) { 3522 if (table == null) return null; 3523 3524 // Check if this table is 'inserted' by examining both name and toString() 3525 // The inserted table might have different representations 3526 String tableName = table.getName(); 3527 String tableString = table.toString(); 3528 3529 if ("inserted".equalsIgnoreCase(tableName) || 3530 "inserted".equalsIgnoreCase(tableString) || 3531 "deleted".equalsIgnoreCase(tableName) || 3532 "deleted".equalsIgnoreCase(tableString)) { 3533 return table; 3534 } 3535 3536 // If this is a join table, recursively check its components 3537 if (table.getTableType() == ETableSource.join && table.getJoinExpr() != null) { 3538 TJoinExpr joinExpr = table.getJoinExpr(); 3539 3540 // Check left side recursively 3541 TTable leftResult = findInsertedOrDeleteTable(joinExpr.getLeftTable()); 3542 if (leftResult != null) { 3543 return leftResult; 3544 } 3545 3546 // Check right side recursively 3547 TTable rightResult = findInsertedOrDeleteTable(joinExpr.getRightTable()); 3548 if (rightResult != null) { 3549 return rightResult; 3550 } 3551 } 3552 3553 return null; 3554 } 3555 3556 3557 boolean isSQLServerInsertedDelete(TObjectName pColumn){ 3558 if (dbvendor != EDbVendor.dbvmssql) return false; 3559 3560 // only process sql server inserted delete column, if not then return false 3561 // if (!((pColumn.toString().toUpperCase().startsWith("INSERTED"))||(pColumn.toString().toUpperCase().startsWith("DELETED")))) return false; 3562 if (!((pColumn.getStartToken().tokencode == TBaseType.rrw_sqlserver_INSERTED ) 3563 ||(pColumn.getStartToken().tokencode == TBaseType.rrw_sqlserver_DELETED ))) return false; 3564 3565 // we need to get the target table in this statement's from clause which can be complex join, so we need to iterate all tables in this statement's from clause 3566 // to find the target table in the literal as 'inserted' or 'deleted'. 3567 3568 TTable lcTargetTable = null; 3569 for(TTable table : this.getRelations()){ 3570 lcTargetTable = findInsertedOrDeleteTable(table); 3571 if (lcTargetTable != null){ 3572 break; 3573 } 3574 } 3575 3576 if (lcTargetTable == null) return false; 3577 3578 3579 if (lcTargetTable.getLinkTable() != null){ 3580 lcTargetTable.getLinkTable().getLinkedColumns().addObjectName(pColumn); 3581 pColumn.setSourceTable(lcTargetTable.getLinkTable()); 3582 3583 pColumn.setResolveStatus(TBaseType.RESOLVED_AND_FOUND); // 避免在 // TAttributeResolver 中再次进行处理,关联到其他 table 3584 3585 }else{ 3586 lcTargetTable.getLinkedColumns().addObjectName(pColumn); 3587 pColumn.setSourceTable(lcTargetTable); 3588 pColumn.setResolveStatus(TBaseType.RESOLVED_AND_FOUND); // 避免在 // TAttributeResolver 中再次进行处理,关联到其他 table 3589 } 3590 return true; 3591 3592 } 3593 3594 /** 3595 * A name an Oracle trigger reads through a correlation name, :NEW.b in its body or NEW.b in its WHEN condition, is 3596 * a column of the row that name denotes ({@link TPlsqlCreateTrigger#correlationOf}), never one of the statement it 3597 * is read in: INSERT INTO t5 VALUES (:new.b) in a trigger on t4 reads t4.b. A name with no such row (NEW of a 3598 * trigger on a nested table) stays unlinked. 3599 */ 3600 boolean isOracleNewOldTable(TObjectName pColumn){ 3601 if (dbvendor != EDbVendor.dbvoracle) return false; 3602 if (!(pColumn.isQualified())) return false; 3603 TCustomSqlStatement lcStmt = this; 3604 while ((lcStmt != null) && !(lcStmt instanceof TPlsqlCreateTrigger)){ 3605 lcStmt = lcStmt.getParentStmt(); 3606 } 3607 if (lcStmt == null) return false; 3608 TPlsqlCreateTrigger lcTrigger = (TPlsqlCreateTrigger) lcStmt; 3609 ETriggerReferencingType lcRow = lcTrigger.correlationOf(pColumn); 3610 if (lcRow == null) return false; 3611 TTable lcTable = lcTrigger.correlationTable(lcRow); 3612 if (lcTable != null){ 3613 lcTable.getLinkedColumns().addObjectName(pColumn); 3614 pColumn.setSourceTable(lcTable); 3615 } 3616 return true; 3617 } 3618 3619 public boolean searchDaxVariableInStack(TObjectName pName){ 3620 boolean ret = false; 3621 if (getVariableStack().size() == 0) return false; 3622 if (pName.getDbObjectType() == EDbObjectType.column) return false; 3623 for(int i=0;i<variableStack.size();i++){ 3624 if (pName.toString().equalsIgnoreCase(((TObjectName) variableStack.get(i)).toString())){ 3625 ret = true; 3626 break; 3627 } 3628 } 3629 return ret; 3630 } 3631 3632 boolean linkColumnToTableDax(TObjectName pColumn, ESqlClause pLocation){ 3633 boolean lcResult = true ; 3634 TDaxFunction daxFunction = null; 3635 if (searchDaxVariableInStack(pColumn)) return false; 3636 if (getDaxFunctionStack().size() > 0){ 3637 daxFunction = daxFunctionStack.peek(); 3638 } 3639 3640 if (pColumn.getTableToken() != null){ 3641 //TTable sourceTable = new TTable(new TObjectName(EDbObjectType.table,pColumn.getTableToken())); 3642 TTable sourceTable = new TTable(TObjectName.createObjectName (this.dbvendor,EDbObjectType.table,pColumn.getTableToken())); 3643 sourceTable.getLinkedColumns().addObjectName(pColumn); 3644 addToTables(sourceTable); 3645 if ((daxFunction != null) && (daxFunction.getDefaultTable() == null)){ 3646 daxFunction.setDefaultTable(sourceTable); 3647 } 3648 }else{ 3649 if ((daxFunction != null) &&(daxFunction.getDefaultTable() != null)){ 3650 daxFunction.getDefaultTable().getLinkedColumns().addObjectName(pColumn); 3651 }else{ 3652 ((TDaxStmt)this).getDefaultTable().getLinkedColumns().addObjectName(pColumn); 3653 } 3654 } 3655 return lcResult; 3656 } 3657 3658 /** 3659 * 将列引用解析并绑定到其来源(表、子查询、CTE、表函数、OPENQUERY/UNNEST 等)。 3660 * 3661 * 功能概述: 3662 * 1) 针对 DAX 语法直接走 DAX 分支。 3663 * 2) 已绑定或标记“延迟到列解析器”的列直接返回。 3664 * 3) 设定列所在语法位置,并校验列名/保留字(含 MySQL true/false/default、内置函数等)。 3665 * 4) 处理厂商伪表/特殊前缀(Oracle :new/:old;SQL Server INSERTED/DELETED)。 3666 * 5) Insert All/VALUES 场景:优先在子查询结果集中/变量或过程参数中匹配。 3667 * 6) 在当前语句的 FROM 表集合中查找并建立绑定: 3668 * - 限定列 table.col:按别名/表名匹配;对子查询/CTE/OPENQUERY 进一步在结果集中定位源列; 3669 * 命中后写入 linkedColumns,必要时将 TableToken 标记为 subquery_alias。 3670 * - 非限定列 col: 3671 * a. 先尝试同层 SELECT 列别名(支持 LATERAL 语义且位置在别名之后); 3672 * b. 处理通配符“*”:收集所有来源表; 3673 * c. 基础表通过元数据回调 fireOnMetaDatabaseTableColumn 校验;未命中则记录候选; 3674 * d. 子查询/CTE/函数/UNNEST/PIVOT 分别按各自规则匹配。 3675 * 7) 命中后将列加入表的 linkedColumns 并设置 sourceTable/sourceColumn,必要时维持 isContinue 以继续匹配“*”。 3676 * 8) 若未命中:尝试变量/参数;再按条件(语句类型/位置/是否限定等)向上一层语句递归查找(维护 searchLevel)。 3677 * 9) 仍未命中:在顶层(searchLevel==0)按“候选唯一/或首表”兜底策略 {@link #linkToFirstTable(TObjectName, int)}。 3678 * 3679 * 参数: 3680 * @param pColumn 需要绑定的列名对象(方法会更新其 location、sourceTable、sourceColumn 等) 3681 * @param pLocation 列出现的语法位置(如 selectList、where、insertValues 等) 3682 * 3683 * 返回值: 3684 * @return 成功绑定到某个来源返回 true;未能绑定或被识别为变量/保留字等返回 false 3685 * 3686 * 厂商兼容: 3687 * - Oracle: 处理 :new/:old,Insert All 的 values 子句源自子查询的匹配 3688 * - SQL Server: 处理 INSERTED/DELETED 伪表 3689 * - MySQL: 对保留字/布尔字面量/内置函数名的特殊判断 3690 * - DAX: 委托 {@link #linkColumnToTableDax(TObjectName, ESqlClause)} 3691 * 3692 * 副作用: 3693 * - 更新 pColumn 的 location/searchLevel/sourceTable/sourceColumn/validate 状态 3694 * - 向命中的表写入 linkedColumns 或向别名列写入 targetColumns 3695 * - 对“*”列填充 sourceTableList;对子查询命中时可能将 TableToken 标为 subquery_alias 3696 * - 记录候选表数量并填充 pColumn.candidateTables,用于后续兜底 3697 * 3698 * 复杂度与顺序: 3699 * - 优先使用同层信息(别名/元数据/子查询结果),再逐层向外查找;避免无谓的上层搜索 3700 * 3701 * 注意: 3702 * - 本方法完成“旧算法”的快速联接,新的解析/消歧逻辑在解析器(如 TStmtScope/TAttributeResolver)中继续处理 3703 */ 3704 /** 3705 * ClickHouse only: the expression-CTE ({@code WITH <expr> AS ident}) whose 3706 * alias matches the unqualified column reference, or null. The search 3707 * covers this statement's own WITH list and ascends ONLY through 3708 * set-operation membership (a compound query's WITH list is shared with 3709 * its members). It must NOT walk arbitrary lexical parents: ClickHouse 3710 * resolves closest-scope-first, so an outer alias may only win after this 3711 * scope's own tables failed — which the existing parent-walk recursion in 3712 * linkColumnToTable already provides (the recursion re-enters this check 3713 * at the parent's own level). A reference located inside a CTE's own 3714 * defining expression never matches that CTE (it is a column named like 3715 * the alias, not a self-reference). 3716 */ 3717 private TCTE findExpressionCteInList(TCTEList lcCteList, TObjectName pColumn){ 3718 if (lcCteList == null) return null; 3719 for(int i=0;i<lcCteList.size();i++){ 3720 TCTE lcCte = lcCteList.getCTE(i); 3721 if ((lcCte.getExpression() == null) || (lcCte.getTableName() == null)) continue; 3722 if ((pColumn.getStartToken() != null) 3723 && (lcCte.getExpression().getStartToken() != null) 3724 && (lcCte.getExpression().getEndToken() != null) 3725 && (pColumn.getStartToken().posinlist >= lcCte.getExpression().getStartToken().posinlist) 3726 && (pColumn.getStartToken().posinlist <= lcCte.getExpression().getEndToken().posinlist)){ 3727 continue; 3728 } 3729 if (SQLUtil.sameName(dbvendor, ESQLDataObjectType.dotColumn, 3730 pColumn.toString(), lcCte.getTableName().toString())){ 3731 return lcCte; 3732 } 3733 } 3734 return null; 3735 } 3736 3737 private TCTE findExpressionCteForAlias(TObjectName pColumn){ 3738 TCustomSqlStatement stmt = this; 3739 while (stmt != null){ 3740 TCTE found = findExpressionCteInList(stmt.getCteList(), pColumn); 3741 if (found != null) return found; 3742 if (!((stmt instanceof TSelectSqlStatement) 3743 && ((TSelectSqlStatement)stmt).isChildOfCombinedQuery())) break; 3744 stmt = stmt.parentStmt; 3745 } 3746 return null; 3747 } 3748 3749 /** 3750 * ClickHouse only: like {@link #findExpressionCteForAlias} but across every 3751 * enclosing statement. Used ONLY where the local scope has already failed 3752 * to PROVE the column (e.g. an unverifiable table-function column) — a 3753 * proven outer alias then outranks the local guess. 3754 */ 3755 private TCTE findExpressionCteForAliasInAnyScope(TObjectName pColumn){ 3756 for(TCustomSqlStatement stmt = this; stmt != null; stmt = stmt.parentStmt){ 3757 TCTE found = findExpressionCteInList(stmt.getCteList(), pColumn); 3758 if (found != null) return found; 3759 } 3760 return null; 3761 } 3762 3763 public boolean linkColumnToTable(TObjectName pColumn, ESqlClause pLocation){ 3764 boolean lcResult = false,isContinue = false; 3765 int candidateTableCnt = 0; 3766 if (pColumn == null) return false; 3767 if (dbvendor == EDbVendor.dbvdax){ 3768 return linkColumnToTableDax(pColumn,pLocation); 3769 } 3770 3771 // Skip alias definition columns - they define column names in alias clauses, not column references 3772 // Example: In "AS x (numbers, animals)", numbers and animals are column_alias type 3773 if (pColumn.getDbObjectType() == EDbObjectType.column_alias) { 3774 return true; 3775 } 3776 3777 if (pColumn.getSourceTable() != null) { 3778 lcResult = true; 3779 return lcResult; 3780 } 3781 3782 if (pColumn.getResolveStatus() == TBaseType.RESOLVE_DELAY_TO_COLUMN_RESOLVER) return true; 3783 3784 pColumn.setLocation(pLocation); 3785 3786 if (! pColumn.isValidColumnName(dbvendor)) { 3787 if (pColumn.isReservedKeyword()){ 3788 if ( 3789 ((pColumn.getStartToken().tokencode != TBaseType.rrw_mysql_true)&&(!(pColumn.getStartToken().toString().equalsIgnoreCase("true")))) 3790 &&((pColumn.getStartToken().tokencode != TBaseType.rrw_mysql_false)&&(!(pColumn.getStartToken().toString().equalsIgnoreCase("false")))) 3791 &&(pColumn.getStartToken().tokencode != TBaseType.rrw_mysql_default) 3792 &&(pColumn.getStartToken().tokencode != TBaseType.rrw_on)&&(!(pColumn.getStartToken().toString().equalsIgnoreCase("on"))) 3793 ) { 3794 boolean mysqlBuiltFunction = false; 3795 if (dbvendor == EDbVendor.dbvmysql){ 3796 mysqlBuiltFunction = functionChecker.isBuiltInFunction(pColumn.toString(),EDbVendor.dbvmysql,"6.0"); 3797 } 3798 if (!mysqlBuiltFunction){ 3799 TSourceToken st1 = pColumn.getStartToken(); 3800 TSyntaxError err = new TSyntaxError(st1.toString() 3801 , st1.lineNo, st1.columnNo 3802 , String.format("Reserved keyword can't be column name") 3803 , EErrorType.sperror 3804 , TBaseType.MSG_ERROR_RESERVED_KEYWORD_CANT_USED_AS_COLUMN_NAME 3805 ,this,st1.posinlist); 3806 this.parseerrormessagehandle(err); 3807 } 3808 } 3809 } 3810 return false; 3811 } 3812 3813 if (isOracleNewOldTable(pColumn)) return true; 3814 if (isSQLServerInsertedDelete(pColumn)) return true; 3815 3816 // oracle insert all statement, 3817 // WHEN id <= 3 THEN INTO dest_tab1 VALUES(id, description1) 3818 // column in values clause must be in the subquery of insert all statement 3819 if (pColumn.getLocation() == ESqlClause.insertValues){ 3820 if (this instanceof TInsertSqlStatement){ 3821 TInsertSqlStatement insertSqlStatement = (TInsertSqlStatement)this; 3822 // INSERT FIRST reads its subquery the same way; testing isInsertAll() alone bound 3823 // an INSERT FIRST VALUES name to the insert target instead 3824 if (insertSqlStatement.isMultiTableInsert() && insertSqlStatement.getSubQuery() != null){ 3825 // if (pColumn.getStartToken().tokencode == TBaseType.rrw_snowflake_default) return true; 3826 lcResult = insertSqlStatement.getSubQuery().searchColumnInResultSet(pColumn, true); 3827 } 3828 } 3829 3830 if (lcResult) return true; 3831 3832 // value in values clause maybe parameter of the procedure/function parameter 3833 lcResult = locateVariableOrParameter(pColumn,true); 3834 if (lcResult) return true; 3835 } 3836 3837 // ClickHouse expression-CTE alias: WITH <expr> AS ident makes ident a 3838 // scalar symbol of the consuming query, not a column of its FROM 3839 // tables (default ClickHouse semantics: the alias shadows a 3840 // same-named table column). Binding it to a table would fabricate 3841 // lineage; resolve it to the CTE instead, before any table search. 3842 if ((dbvendor == EDbVendor.dbvclickhouse) && (!pColumn.isQualified())){ 3843 TCTE lcExprCte = findExpressionCteForAlias(pColumn); 3844 if (lcExprCte != null){ 3845 pColumn.setExpressionCteRef(lcExprCte); 3846 pColumn.setResolveStatus(TBaseType.RESOLVED_AND_FOUND); 3847 return false; 3848 } 3849 } 3850 3851 // SAP IQ and SQL Anywhere: a name this SELECT block provably cannot resolve is the alias of an enclosing 3852 // block (Mantis 4752). The rule is shared with resolver2: TSelectSqlStatement.findEnclosingAliasDefinition. 3853 if ((pColumn.searchLevel == 0) && (this instanceof TSelectSqlStatement) && (!pColumn.isQualified())){ 3854 // getSqlEnv() needs a frame; without one no table's columns are known, which only keeps names columns 3855 TSQLEnv lcSqlEnv = ((getFrameStack() != null) && (!getFrameStack().isEmpty())) ? getSqlEnv() : null; 3856 TResultColumn lcOuterAlias = ((TSelectSqlStatement) this).findEnclosingAliasDefinition(pColumn, lcSqlEnv); 3857 if (lcOuterAlias != null){ 3858 pColumn.setSourceColumn(lcOuterAlias); 3859 lcOuterAlias.getTargetColumns().addObjectName(pColumn); 3860 pColumn.setValidate_column_status(TBaseType.COLUMN_LINKED_TO_COLUMN_ALIAS_IN_OLD_ALGORITHM); 3861 return true; 3862 } 3863 } 3864 3865 // MySQL reads a name declared as a local variable or a parameter of the routine as that variable, also when a 3866 // table of the statement has a column of that name ("Local Variable Scope and Resolution"); other dialects, 3867 // Oracle documented among them, read the column. The catalog knows more columns since Mantis 4797. 3868 if (isMySQLDialect() && (!pColumn.isQualified()) && (!pColumn.isColumnOnly()) 3869 && locateVariableOrParameter(pColumn, true)){ 3870 return false; 3871 } 3872 3873 // A point in time (AS OF, AT) is evaluated once, before any row is read, so it names no column of a table of 3874 // the statement (Oracle allows no column in AS OF): a declared variable or parameter there is that variable. 3875 if (parsingPointInTime && (!pColumn.isQualified()) && (!pColumn.isColumnOnly()) 3876 && locateVariableOrParameter(pColumn, true)){ 3877 return false; 3878 } 3879 3880 boolean foundInMetaData = false; 3881 // the analysis's name service, as the lookups of linkColumnReferenceToTable use (redundancy plan C3b) 3882 IdentifierService names = IdentifierService.forAnalysis(getSqlEnv(), dbvendor); 3883 3884 for(int i=0;i<tables.size();i++){ 3885 TTable lcTable = tables.getTable(i); 3886 if (lcTable.getEffectType() == ETableEffectType.tetSelectInto) continue; 3887 if (lcTable.getEffectType() == ETableEffectType.tetImplicitLateralDerivedTable) continue; 3888 3889 if (pColumn.isQualified()){ 3890 lcResult = pColumn.resolveWithThisTable(lcTable, names); 3891 if ((lcResult) && (lcTable.getTableType() == ETableSource.subquery)){ 3892 pColumn.getTableToken().setDbObjectType(EDbObjectType.subquery_alias); 3893 3894 int lcPos = lcTable.searchColumnInAlias(pColumn); 3895 lcResult = lcPos>=0; 3896 if (lcResult){ 3897 // 在 alias 中找到 source column, 还需要对应到 subquery select 中的 select list 3898 // sql 见 https://e.gitee.com/gudusoft/projects/151613/tasks/list?issue=I8JR0W#note_23051633 3899 if ((lcTable.getSubquery() != null)&&(lcTable.getSubquery().getResultColumnList() != null)){ 3900 pColumn.setSourceColumn(lcTable.getSubquery().getResultColumnList().getResultColumn(lcPos)); 3901 } 3902 }else{ 3903 lcResult = lcTable.getSubquery().searchColumnInResultSet(pColumn,true); 3904 } 3905 // lcTable.getSubquery().searchColumnInResultSet(pColumn,true); 3906 3907 }else if ((lcResult) && (lcTable.isCTEName())){ 3908 lcTable.getCTE().searchColumnInResultSet(this,lcTable,pColumn,true); 3909 }else if ((lcResult) && (lcTable.getTableType() == ETableSource.openquery)&&(lcTable.getSubquery() != null)){ 3910 pColumn.getTableToken().setDbObjectType(EDbObjectType.subquery_alias); 3911 lcTable.getSubquery().searchColumnInResultSet(pColumn,true); 3912// }else if ((lcResult) && (lcTable.getTableType() == ETableSource.unnest)&&(lcTable.getUnnestClause() != null)){ 3913// pColumn.getTableToken().setDbObjectType(EDbObjectType.subquery_alias); 3914// lcTable.getSubquery().searchColumnInResultSet(pColumn,true); 3915 } 3916 if (lcResult&&pColumn.toString().endsWith("*")){ 3917 pColumn.getSourceTableList().add(lcTable); 3918// ArrayList<String> lcColumns = getColumnsInTable(lcTable); 3919// if (lcColumns != null){ 3920// pColumn.getColumnsLinkedToStarColumn().addAll(lcColumns); 3921// } 3922 } 3923 }else { 3924 // column not qualified 3925 3926 // check if this is the column alias in current select list. 3927 // The binding rule itself lives in TResultColumnList.findLateralAliasDefinition() 3928 // so that this path and resolver2's handleSelectListAliasResolution() can never 3929 // disagree about what counts as an alias reference (MantisBT 4659). 3930 // In SAP IQ and SQL Anywhere an enclosing block's alias is taken only at searchLevel 0, by the rule 3931 // shared with resolver2 (findEnclosingAliasDefinition): searching upward here does not prove that 3932 // the blocks in between have no column of that name (Mantis 4752). 3933 if((!lcResult)&& ((!pColumn.isQualified()) && (this instanceof TSelectSqlStatement)&&(getResultColumnList() !=null)) 3934 && !((pColumn.searchLevel > 0) && TSQLEnv.isAliasOccludingColumn(dbvendor))){ 3935 TResultColumn lcField = getResultColumnList().findLateralAliasDefinition(dbvendor, pColumn); 3936 if (lcField != null){ 3937 pColumn.setSourceColumn(lcField); 3938 lcField.getTargetColumns().addObjectName(pColumn); 3939 pColumn.setValidate_column_status(TBaseType.COLUMN_LINKED_TO_COLUMN_ALIAS_IN_OLD_ALGORITHM); 3940 return true; 3941 } 3942 } 3943 3944 if (pColumn.getColumnNameOnly().equalsIgnoreCase("*")){ 3945 lcResult = true; 3946 isContinue = true; // in order to match next table in the from clause 3947 pColumn.getSourceTableList().add(lcTable); 3948// ArrayList<String> lcColumns = getColumnsInTable(lcTable); 3949// if (lcColumns != null){ 3950// pColumn.getColumnsLinkedToStarColumn().addAll(lcColumns); 3951// } 3952 }else if (lcTable.isBaseTable()){ 3953 lcResult = fireOnMetaDatabaseTableColumn( 3954 lcTable.getPrefixServer() 3955 ,lcTable.getPrefixDatabase() 3956 ,lcTable.getPrefixSchema() 3957 ,lcTable.getName() 3958 ,pColumn.getColumnNameOnly()); 3959 if (! lcResult) { 3960 candidateTableCnt++; 3961 pColumn.getCandidateTables().addTable(lcTable); 3962 }else{ 3963 List<TTable> lcOthers = otherTablesWithColumn(pColumn, i); 3964 if (!lcOthers.isEmpty()){ 3965 // The catalog gives two tables of the statement this column: the name is ambiguous, and 3966 // neither table is proven to be its own. The script's declarations made this reachable 3967 // without caller metadata (Mantis 4797). 3968 lcResult = false; 3969 candidateTableCnt++; 3970 pColumn.getCandidateTables().addTable(lcTable); 3971 for (TTable lcOther : lcOthers){ 3972 candidateTableCnt++; 3973 pColumn.getCandidateTables().addTable(lcOther); 3974 } 3975 break; 3976 } 3977 foundInMetaData = true; 3978 isContinue = false; 3979 } 3980 3981 }else if ((lcTable.getTableType() == ETableSource.subquery) 3982 ||((lcTable.getTableType() == ETableSource.openquery)&&(lcTable.getSubquery() != null))){ 3983 3984 lcResult = lcTable.searchColumnInAlias(pColumn)>=0; 3985 if (!lcResult){ 3986 lcResult = lcTable.getSubquery().searchColumnInResultSet(pColumn,(tables.size() == 1) 3987 &&(pColumn.getCandidateTables().size() == 0)); 3988 if (! lcResult) { 3989 candidateTableCnt++; 3990 pColumn.getCandidateTables().addTable(lcTable); 3991 } 3992 } 3993 3994 3995// if (lcTable.isIncludeColumnAlias()){ 3996// // System.out.println("subquery with alias:"+lcTable.getAliasClause().toString()+", skip search:"+pColumn.toString()); 3997// 3998// }else{ 3999// lcResult = lcTable.getSubquery().searchColumnInResultSet(pColumn,(tables.size() == 1)&&(pColumn.getCandidateTables().size() == 0)); 4000// if (! lcResult) candidateTableCnt++; 4001// } 4002 }else if (lcTable.isCTEName()){ 4003 lcResult = lcTable.getCTE().searchColumnInResultSet(this,lcTable,pColumn,tables.size() == 1); 4004 if (! lcResult) { 4005 candidateTableCnt++; 4006 pColumn.getCandidateTables().addTable(lcTable); 4007 } 4008 }else if (lcTable.getTableType() == ETableSource.function){ 4009 // search in this table function 4010 if(tables.size() == 1){ 4011 int lcInTableFunction = lcTable.getFuncCall().isColumnInThisTableFunction(this.getSqlEnv(),this.dbvendor,pColumn); 4012 lcResult = ( lcInTableFunction != TBaseType.COLUMN_IN_TABEL_FUNCTION_NO); 4013 // ClickHouse: an unverifiable table-function column 4014 // (NOTSURE) must not outrank an expression-CTE alias 4015 // visible in an enclosing scope — the alias is proven, 4016 // the guessed column is not. Leaving it unmatched lets 4017 // the parent-walk resolve the alias. 4018 if (lcResult && (lcInTableFunction == TBaseType.COLUMN_IN_TABEL_FUNCTION_NOTSURE) 4019 && (dbvendor == EDbVendor.dbvclickhouse) && (!pColumn.isQualified()) 4020 && (findExpressionCteForAliasInAnyScope(pColumn) != null)){ 4021 lcResult = false; 4022 } 4023 } 4024 else{ 4025 lcResult = ( lcTable.getFuncCall().isColumnInThisTableFunction(this.getSqlEnv(),this.dbvendor,pColumn) 4026 == TBaseType.COLUMN_IN_TABEL_FUNCTION_YES); 4027 } 4028 }else if (lcTable.getTableType() == ETableSource.tableExpr 4029 && lcTable.getTableExpr().getExpressionType() == EExpressionType.function_t 4030 && lcTable.getTableExpr().getFunctionCall() != null){ 4031 // search in this table function 4032 lcResult = ( lcTable.getTableExpr().getFunctionCall().isColumnInThisTableFunction(this.getSqlEnv(),this.dbvendor,pColumn) 4033 == TBaseType.COLUMN_IN_TABEL_FUNCTION_YES); 4034 }else if (lcTable.getTableType() == ETableSource.pivoted_table){ 4035 lcResult = fireOnMetaDatabaseTableColumn( 4036 lcTable.getPrefixServer() 4037 ,lcTable.getPrefixDatabase() 4038 ,lcTable.getPrefixSchema() 4039 ,lcTable.getName() 4040 ,pColumn.getColumnNameOnly()); 4041 if (lcResult){ 4042 foundInMetaData = true; 4043 isContinue = false; 4044 } 4045 }else if (lcTable.getTableType() == ETableSource.unnest){ 4046 for(TObjectName objectName:lcTable.getLinkedColumns()){ 4047 if (SQLUtil.compareIdentifier(this.dbvendor, ESQLDataObjectType.dotColumn, objectName.toString(), pColumn.toString())){ 4048 lcResult = true; 4049 break; 4050 } 4051 } 4052 4053 if (!lcResult){ 4054 if (lcTable.getAliasClause() == null){ 4055 // this unnest() clause generate column with default name: "value" 4056 if (pColumn.toString().equalsIgnoreCase("value")){ 4057 lcResult = true; 4058 } 4059 }else{ 4060 } 4061 } 4062 // A field of the STRUCTs the array holds, UNNEST([STRUCT(0 AS a, 1 AS b)]) (Mantis 4797). 4063 if ((!lcResult) && TSelectSqlStatement.unnestHasStructField(lcTable, pColumn.getColumnNameOnly())){ 4064 lcResult = true; 4065 } 4066 }//unnest 4067 } 4068 4069 if (lcResult) { 4070 lcTable.getLinkedColumns().addObjectName(pColumn); 4071 pColumn.setSourceTable(lcTable); 4072 // A real table binding in this scope outranks an alias mark a 4073 // wider-scope pre-pass may have left (ClickHouse closest-scope). 4074 pColumn.setExpressionCteRef(null); 4075 // pColumn.setValidate_column_status(TBaseType.COLUMN_LINKED_TO_TABLE_IN_OLD_ALGORITHM); 4076 if (!isContinue) break; 4077 } 4078 } 4079 4080 if ((lcResult) && (foundInMetaData)) return true; 4081 4082 // check variable after metadata checking 4083 if ((!pColumn.isColumnOnly()) && locateVariableOrParameter(pColumn)) return false; 4084 4085 // check if this is the column alias in current select list. 4086// if((!lcResult)&& ((!pColumn.isPrefixed()) && (this instanceof TSelectSqlStatement)&&(getResultColumnList() !=null))){ 4087// for(int j=0;j<getResultColumnList().size();j++){ 4088// TResultColumn lcField = getResultColumnList().getResultColumn(j); 4089// lcResult = lcField.isMatchedUsingAlias(pColumn); 4090// if ((lcResult)&&(pColumn.getStartToken().posinlist > lcField.getAliasClause().getStartToken().posinlist)){ 4091// pColumn.setSourceColumn(lcField); 4092// lcField.getTargetColumns().addObjectName(pColumn); 4093// break; 4094// }else{ 4095// lcResult = false; 4096// } 4097// } 4098// } 4099 4100 if (lcResult) return true; 4101 4102 boolean isSearchUpLevel = (this.parentStmt != null); 4103 4104 if ((isSearchUpLevel) && (sqlstatementtype == ESqlStatementType.sstselect)){ 4105 isSearchUpLevel = (pColumn.isQualified() 4106 || ( 4107// (((TSelectSqlStatement)(this)).getLocation() != ESqlClause.elTable) && 4108 (! ((TSelectSqlStatement)(this)).isQueryOfCTE()) 4109 ) 4110 ) 4111 && (parentStmt.sqlstatementtype != ESqlStatementType.sstinsert) 4112 && (!((pColumn.getLocation() == ESqlClause.selectList)&&(((TSelectSqlStatement)(this)).getLocation() == ESqlClause.join))) 4113 && ((((TSelectSqlStatement)(this)).getLocation() != ESqlClause.pivot_in)) 4114 && (!((parentStmt.sqlstatementtype == ESqlStatementType.sstcreatetable))) 4115 && (!((parentStmt.sqlstatementtype == ESqlStatementType.sstcreateview))) 4116// && (!((pColumn.getLocation() == ESqlClause.selectList)&&(parentStmt.sqlstatementtype == ESqlStatementType.sstcreatetable))) 4117// && (!((pColumn.getLocation() == ESqlClause.selectList)&&(parentStmt.sqlstatementtype == ESqlStatementType.sstcreateview))) 4118 && (! ((pColumn.getLocation() == ESqlClause.selectList) 4119 &&(candidateTableCnt == 1) && (this instanceof TSelectSqlStatement) 4120 && (((TSelectSqlStatement)(this)).getLocation() == ESqlClause.elTable) 4121 ) ) // ref:mantis: #2628 4122 // && ( ((TSelectSqlStatement)(this.parentStmt)).getSetOperatorType() == ESetOperatorType.none) 4123 ; 4124 4125 // An unqualified name is this block's own while one of its tables may have the column (Mantis 4797): a 4126 // derived table in FROM sees neither the FROM items next to it nor the enclosing block, and a subquery in 4127 // an expression reads its own tables first. A subquery's name compared with a column of its own tables is 4128 // the enclosing block's when its own tables do not prove it and the enclosing block does, by the rule 4129 // resolver2 applies too (TSelectSqlStatement.outerCorrelationTable): in (SELECT max(v) FROM 4130 // customfieldvalues WHERE resourceid = resumeid) under FROM (SELECT id AS resumeid FROM resumes) r, 4131 // resumeid is r's; in (select Jahr from m_version_table2 where Jahr234 = year(now())) both are 4132 // m_version_table2's. 4133 if (isSearchUpLevel && (!pColumn.isQualified())){ 4134 TSQLEnv lcSqlEnv = ((getFrameStack() != null) && (!getFrameStack().isEmpty())) ? getSqlEnv() : null; 4135 TSelectSqlStatement lcSelect = (TSelectSqlStatement) this; 4136 isSearchUpLevel = !lcSelect.mayExposeColumn(pColumn.getColumnNameOnly(), lcSqlEnv) 4137 || ((!isDerivedTableInFrom()) 4138 && (TSelectSqlStatement.outerCorrelationTable(pColumn, lcSelect, lcSqlEnv) != null)) 4139 // ClickHouse prefers an alias to a column (prefer_column_name_to_alias = 0): an enclosing 4140 // expression-CTE alias of the name wins over a table here that may have the column. 4141 || ((dbvendor == EDbVendor.dbvclickhouse) && (findExpressionCteForAliasInAnyScope(pColumn) != null)); 4142 } 4143 } 4144 4145 if (isSearchUpLevel&&(pColumn.isContinueToSearch())){ // only search one level up, c:\prg\gsp_sqlfiles\TestCases\java\oracle\dbobject\berger_sqltest_04.sql 4146 boolean increaseLevel = true; 4147 if (parentStmt instanceof TSelectSqlStatement){ 4148 if( ((TSelectSqlStatement)parentStmt).getSetOperatorType() != ESetOperatorType.none){ 4149 increaseLevel = false; 4150 } 4151 } 4152 if (increaseLevel){ 4153 pColumn.searchLevel++; 4154 } 4155 4156 lcResult = parentStmt.linkColumnToTable(pColumn,pLocation); 4157 4158 if (increaseLevel){ 4159 pColumn.searchLevel--; 4160 } 4161 } 4162 4163 if ((! lcResult) && (pColumn.searchLevel == 0)) { 4164 if (this.sqlstatementtype == ESqlStatementType.sstselect){ 4165 if( ((TSelectSqlStatement)this).getSetOperatorType() == ESetOperatorType.none){ 4166 // USING _spVV0 (INTEGER) 4167 // INSERT INTO table3 4168 // SELECT :_spVV0,x. *,m.col3 4169 // from (( select table1.col1, (table1.col1 + table5.col2) c from table1 4170 // union all select col3,col4 from table2) x 4171 // cross join (select id from table2) m ) 4172 4173 // table5 in the above sql only link to the nearest level sql, but not to up-level which is union all 4174 4175 linkToFirstTable(pColumn,candidateTableCnt); 4176 } 4177 }else{ 4178 linkToFirstTable(pColumn,candidateTableCnt); 4179 } 4180 } 4181 4182 return lcResult; 4183 } 4184 4185 4186 /** 4187 * 4188 * @deprecated As of v1.6.0.1, use {@link #linkColumnToTable} instead 4189 */ 4190 /** 4191 * True when {@code cr} is an Oracle pseudocolumn rather than a reference to 4192 * a column of a table, judged only on what the statement itself proves. 4193 * 4194 * <p>The name list lives in {@link OraclePseudoColumnUtil}; this method 4195 * supplies the statement context that decides the non-reserved names. 4196 * Nothing here consults a catalog, so names that are indistinguishable from 4197 * a real column without one - {@code ORA_ROWSCN}, {@code OBJECT_ID}, 4198 * {@code OBJECT_VALUE}, {@code XMLDATA}, {@code COLUMN_VALUE} - are 4199 * deliberately not claimed. {@code OBJECT_ID} in particular is a real 4200 * column of {@code ALL_OBJECTS}, and claiming it would silently drop that 4201 * lineage.</p> 4202 * 4203 * @param cr the column reference being linked 4204 * @return true if {@code cr} is provably a pseudocolumn 4205 */ 4206 protected boolean isOraclePseudoColumnReference(TObjectName cr){ 4207 if (dbvendor != EDbVendor.dbvoracle) return false; 4208 if (cr == null) return false; 4209 // getColumnNameOnly() is the raw text of the LAST segment, quotes 4210 // included, so a quoted "ROWID" simply fails to match the name list - 4211 // which is the correct outcome, since "ROWID" and ROWID are different 4212 // names in Oracle. Do NOT add a getQuoteType() guard here: that method 4213 // reports the quote state of the FIRST segment, so it would reject 4214 // "seq".NEXTVAL, whose terminal segment is unquoted and really is the 4215 // sequence pseudocolumn. 4216 String nameOnly = cr.getColumnNameOnly(); 4217 if (nameOnly == null || nameOnly.length() == 0) return false; 4218 4219 // Reserved words with no owning table (ROWNUM, LEVEL). Oracle rejects 4220 // an unquoted column of these names, so no qualifier or clause can make 4221 // this a real column reference. ROWID is deliberately NOT here: it is 4222 // scoped to one table, keeps its attribution, and is retyped in 4223 // TObjectName.setSourceTable() instead. 4224 if (OraclePseudoColumnUtil.isDetachedReservedPseudoColumn(nameOnly)) return true; 4225 4226 // CONNECT_BY_ISLEAF / CONNECT_BY_ISCYCLE are not reserved. They are 4227 // pseudocolumns only inside a hierarchical query, and only unqualified: 4228 // Oracle has no table to qualify them with, so t.CONNECT_BY_ISLEAF is a 4229 // reference to a column somebody created called CONNECT_BY_ISLEAF. 4230 if (OraclePseudoColumnUtil.isConnectByPseudoColumn(nameOnly) 4231 && cr.getTableToken() == null 4232 && hasHierarchicalQueryClause()) return true; 4233 4234 // VERSIONS_* are only pseudocolumns when the table they come from 4235 // carries a flashback VERSIONS clause. 4236 if (OraclePseudoColumnUtil.isVersionsPseudoColumn(nameOnly) 4237 && hasFlashbackVersionsClause(cr.getTableString())) return true; 4238 4239 return false; 4240 } 4241 4242 /** 4243 * True when {@code cr} is {@code [schema.]sequence.NEXTVAL} or 4244 * {@code [schema.]sequence.CURRVAL}. 4245 * 4246 * <p>Neither name is reserved, so this needs the qualifier to be something 4247 * other than a table or alias in scope: {@code x.CURRVAL} where {@code x} 4248 * is a table alias is an ordinary reference to a column named 4249 * {@code CURRVAL}, and an unqualified {@code CURRVAL} likewise.</p> 4250 * 4251 * <p>Kept separate from {@link #isOraclePseudoColumnReference} because the 4252 * two get different treatment - see the call site.</p> 4253 * 4254 * @param cr the column reference being linked 4255 * @return true if {@code cr} is a sequence pseudocolumn 4256 */ 4257 protected boolean isOracleSequencePseudoColumnReference(TObjectName cr){ 4258 if (dbvendor != EDbVendor.dbvoracle) return false; 4259 if (cr == null) return false; 4260 // See isOraclePseudoColumnReference(): quote state is segment-specific 4261 // and already carried by getColumnNameOnly(); getQuoteType() reads the 4262 // wrong segment for a qualified name. 4263 String nameOnly = cr.getColumnNameOnly(); 4264 if (nameOnly == null || nameOnly.length() == 0) return false; 4265 return OraclePseudoColumnUtil.isSequencePseudoColumn(nameOnly) 4266 && cr.getTableToken() != null 4267 && !isTableOrAliasInScope(cr.getTableString()); 4268 } 4269 4270 /** 4271 * True when this statement (or the statement it belongs to) carries an 4272 * Oracle {@code CONNECT BY}. 4273 */ 4274 private boolean hasHierarchicalQueryClause(){ 4275 // Deliberately NOT walking up to the parent statement. CONNECT BY 4276 // pseudocolumns belong to the query that carries the clause; they are 4277 // not visible to a subquery nested inside it. Walking up would claim 4278 // CONNECT_BY_ISLEAF in 4279 // SELECT (SELECT CONNECT_BY_ISLEAF FROM other) FROM t CONNECT BY ... 4280 // where it is an ordinary column of "other", and drop that edge. 4281 if (this instanceof TSelectSqlStatement){ 4282 return ((TSelectSqlStatement)this).getHierarchicalClause() != null; 4283 } 4284 return false; 4285 } 4286 4287 /** 4288 * True when any table in scope carries a flashback {@code VERSIONS BETWEEN} 4289 * clause, which is what makes the {@code VERSIONS_*} pseudocolumns 4290 * available. 4291 */ 4292 private boolean hasFlashbackVersionsClause(String qualifier){ 4293 // Same scoping rule as hasHierarchicalQueryClause(): the VERSIONS_* 4294 // pseudocolumns come from a table in THIS statement's FROM clause, so 4295 // no parent-chain walk. An inner subquery of a version query does not 4296 // inherit them. 4297 if (tables == null) return false; 4298 // When the reference names a table, only THAT table's clause counts. 4299 // In "FROM x VERSIONS BETWEEN ... , y", y.VERSIONS_XID is an ordinary 4300 // column of y - y is not being version-queried. 4301 if (qualifier != null && qualifier.length() > 0){ 4302 int idx = tables.searchTableByNameOrAlias(qualifier); 4303 if (idx < 0) return false; 4304 TFlashback flashback = tables.getTable(idx).getFlashback(); 4305 return flashback != null && flashback.isVersionsQuery(); 4306 } 4307 for (int i = 0; i < tables.size(); i++){ 4308 TFlashback flashback = tables.getTable(i).getFlashback(); 4309 if (flashback != null && flashback.isVersionsQuery()) return true; 4310 } 4311 return false; 4312 } 4313 4314 /** 4315 * True when {@code name} matches a table name or alias visible to this 4316 * statement. Used to tell {@code sequence.CURRVAL} from 4317 * {@code tablealias.CURRVAL}. 4318 */ 4319 private boolean isTableOrAliasInScope(String name){ 4320 if (name == null || name.length() == 0) return false; 4321 TCustomSqlStatement stmt = this; 4322 while (stmt != null){ 4323 if (stmt.tables != null && stmt.tables.searchTableByNameOrAlias(name) >= 0) return true; 4324 stmt = stmt.getParentStmt(); 4325 } 4326 return false; 4327 } 4328 4329 public void linkColumnReferenceToTable(TObjectName cr, ESqlClause plocation){ 4330 // this is the column name, link it to table 4331 if (cr == null) return; 4332 cr.setLocation(plocation); 4333 if (cr.getObjectType() == TObjectName.ttobjVariable) return; 4334 if (cr.getObjectType() == TObjectName.ttobjColumnAlias) return; 4335 if ((this.dbvendor == EDbVendor.dbvsybase)||(this.dbvendor == EDbVendor.dbvsybasease || this.dbvendor == EDbVendor.dbvsqlanywhere || this.dbvendor == EDbVendor.dbvsybaseiq)){ 4336 TSourceToken pt = cr.getPartToken(); 4337 if ( pt != null){ 4338 if (pt.tokentype == ETokenType.ttdqstring){ 4339 //"0123", quoted string start with a number can't a column 4340 if ((pt.toString().charAt(1) >= '0') 4341 &&(pt.toString().charAt(1) <= '9')){ 4342 return; 4343 }else if (pt.toString().length() == 2){ 4344 //"", empty 4345 return; 4346 }else if (pt.toString().substring(1,pt.toString().length()-1).trim().length() == 0){ 4347 //" " 4348 return; 4349 } 4350 } 4351 } 4352 } 4353 4354 4355 if (cr.getPartToken() != null){ 4356 if (cr.getPartToken().tokentype == ETokenType.ttkeyword){ 4357 boolean reservedKeyword = false; 4358 switch (dbvendor){ 4359 case dbvmssql: 4360 //reservedKeyword = ! this.getGsqlparser().getFlexer().canBeColumnName(cr.getPartToken().tokencode); 4361 reservedKeyword = ! TLexerMssql.canBeColumnName(cr.getPartToken().tokencode); 4362 break; 4363 case dbvsybase: 4364 reservedKeyword = keywordChecker.isKeyword(cr.getPartToken().toString(), EDbVendor.dbvsybase, "15.7", true); 4365 break; 4366 case dbvsybasease: 4367 // Shares dbvsybase's keyword DATA file (it is the ASE 4368 // reserved-word list); independent case block per HC-5. 4369 reservedKeyword = keywordChecker.isKeyword(cr.getPartToken().toString(), EDbVendor.dbvsybase, "15.7", true); 4370 break; 4371 case dbvsqlanywhere: 4372 // Same shared keyword DATA file; independent case per HC-5. 4373 reservedKeyword = keywordChecker.isKeyword(cr.getPartToken().toString(), EDbVendor.dbvsybase, "15.7", true); 4374 break; 4375 case dbvsybaseiq: 4376 // Same again; independent case per HC-5. 4377 reservedKeyword = keywordChecker.isKeyword(cr.getPartToken().toString(), EDbVendor.dbvsybase, "15.7", true); 4378 break; 4379 default: 4380 break; 4381 } 4382 if (reservedKeyword) return; 4383 } 4384 } 4385 4386 // let's check is this columnreference is variable or parameter of plsql function/procedure 4387 // if (locateVariableOrParameter(cr)) return; 4388 4389// if ((cr.getPartToken() != null)&&((dbvendor == EDbVendor.dbvmssql)||(dbvendor == EDbVendor.dbvsybase))){ 4390// if ((cr.getPartToken().tokentype == ETokenType.ttkeyword)&&(!(this.getGsqlparser().getFlexer().canBeColumnName(cr.getPartToken().tokencode)))){ 4391// // keyword can't be column name: 4392// //select * From dbo.table Where DATEDIFF(day, create_date, expiry_date) < 14 4393// return; 4394// } 4395// } 4396 4397 if ((cr.toString().startsWith("@"))) 4398// if ((cr.toString().endsWith("*"))||(cr.toString().startsWith("@"))) 4399 { 4400 cr.setObjectType(TObjectName.ttobjNotAObject); 4401 return; 4402 } 4403 4404 if (dbvendor == EDbVendor.dbvoracle){ 4405 if ( //(cr.toString().compareToIgnoreCase ("rowid") == 0)|| 4406 (cr.toString().compareToIgnoreCase ("sysdate") == 0) 4407 || (cr.toString().compareToIgnoreCase ("nextval") == 0) 4408 || (cr.toString().compareToIgnoreCase ("rownum") == 0) 4409 || (cr.toString().compareToIgnoreCase ("level") == 0) 4410 ){ 4411 cr.setObjectType(TObjectName.ttobjNotAObject); 4412 if (cr.getDbObjectType() == EDbObjectType.unknown){ 4413 cr.setDbObjectType(EDbObjectType.notAColumn); 4414 } 4415 return; 4416 } 4417 // The comparisons above are against the whole rendered text, so they 4418 // only ever fire for a bare, unqualified name. Oracle documents 18 4419 // pseudocolumns and most of them reach here qualified (X.ROWID, 4420 // SEQ.CURRVAL) or under a spelling the list never had. Left alone 4421 // they fall through to checkColumnReferenceInTables() below and get 4422 // bound to a table in the FROM clause, which asserts that e.g. 4423 // ORA_ROWSCN is a column of that table (Mantis #4675). 4424 if (isOracleSequencePseudoColumnReference(cr)){ 4425 // [schema.]sequence.NEXTVAL|CURRVAL. Detach it from the FROM 4426 // clause but leave dbObjectType alone, which keeps CURRVAL on 4427 // the exact footing NEXTVAL has always had (unknown, no source 4428 // table). Promoting these to notAColumn would reclassify them 4429 // from column references to constants in DataFlowAnalyzer and 4430 // move existing lineage output; the defect reported was CURRVAL 4431 // being bound to an unrelated table, not its type. 4432 // Deliberately no setSourceTable(null) here: nothing has linked 4433 // this reference yet, and that setter has a side effect of 4434 // forcing dbObjectType to column, which is exactly the type we 4435 // are trying to leave alone. 4436 cr.setObjectType(TObjectName.ttobjNotAObject); 4437 cr.setValidate_column_status(TBaseType.VALIDATED_CAN_NOT_BE_A_COLUMN_NAME); 4438 return; 4439 } 4440 if (isOraclePseudoColumnReference(cr)){ 4441 cr.setObjectType(TObjectName.ttobjNotAObject); 4442 cr.setSourceTable(null); 4443 cr.setValidate_column_status(TBaseType.MARKED_NOT_A_COLUMN_IN_COLUMN_RESOLVER); 4444 cr.setDbObjectTypeDirectly(EDbObjectType.notAColumn); 4445 return; 4446 } 4447 } 4448 4449 if (((cr.toString().toUpperCase(java.util.Locale.ROOT).startsWith("INSERTED"))||(cr.toString().toUpperCase(java.util.Locale.ROOT).startsWith("DELETED")))&&(plocation == ESqlClause.output)&&(targetTable != null)){ 4450 targetTable.getObjectNameReferences().addObjectName(cr); 4451 return; 4452 } 4453 4454 // a name read through a correlation name of the trigger references the table of that row 4455 // (TPlsqlCreateTrigger.correlationOf); NEW of a trigger on a nested table is no row of a table 4456 if ((dbvendor == EDbVendor.dbvoracle) && (this.getTopStatement() instanceof TPlsqlCreateTrigger)){ 4457 TPlsqlCreateTrigger lcTrigger = (TPlsqlCreateTrigger) this.getTopStatement(); 4458 ETriggerReferencingType lcRow = lcTrigger.correlationOf(cr); 4459 if (lcRow != null){ 4460 TTable lcRowTable = lcTrigger.correlationTable(lcRow); 4461 if (lcRowTable != null){ 4462 lcRowTable.getObjectNameReferences().addObjectName(cr); 4463 } 4464 return; 4465 } 4466 } 4467 4468 4469 4470 // the analysis's name service: the identifier profile frozen for this parse (redundancy plan C3b) 4471 IdentifierService names = IdentifierService.forAnalysis(getSqlEnv(), dbvendor); 4472 int ret = this.tables.checkColumnReferenceInTables(cr, names); 4473 if (ret >= 0) { 4474 TTable lcTable = this.tables.getTable(ret); 4475 if (lcTable.isBaseTable()){ 4476 lcTable.getObjectNameReferences().addObjectName(cr); 4477 }else if (lcTable.isCTEName()){ 4478 //WITH temp 4479 // AS (SELECT * 4480 // FROM sysibm.systables), 4481 // temp1 4482 // AS (SELECT * 4483 // FROM sysibm.syscolumns) 4484 //SELECT * 4485 //FROM temp A 4486 // INNER JOIN temp1 B 4487 // ON A.creator = B.tbcreator 4488 // AND A.name = B.tbname 4489 TCTE lccte = lcTable.getCTE(); // the CTE the table reads (redundancy plan C3c (d)) 4490 if (lccte != null){ 4491 TObjectName objectName = new TObjectName(); 4492 objectName.init(cr.getPartToken()); 4493 if (lccte.getSubquery() != null){ 4494 lccte.getSubquery().linkColumnReferenceToTable(objectName,plocation); 4495 } 4496 } 4497 }else if (lcTable.getTableType() == ETableSource.subquery){ 4498 // link s2t1a1 to subselect2table1 via s2 4499 //select 4500 // s2.s2t1a1 4501 //from 4502 // ( 4503 // select s2t1.* 4504 // from subselect2table1 s2t1 4505 // ) s2 4506 TSelectSqlStatement subquery = lcTable.getSubquery(); 4507 4508 if(((subquery.getValueClause() == null))&&(!subquery.isCombinedQuery())&&(subquery.getResultColumnList() != null)&&(subquery.getResultColumnList().size() == 1)){ 4509 TResultColumn lcColumn = subquery.getResultColumnList().getResultColumn(0); 4510 if (lcColumn.toString().endsWith("*")){ 4511 boolean isfound = false; 4512 4513 for(int i=0;i<subquery.tables.size();i++){ 4514 if (subquery.tables.getTable(i).getTableType() == ETableSource.subquery) continue; 4515 String columnStr = null; 4516 if (cr.getPartToken() != null){ 4517 //cr.getObjectType() is not ttObjColumn, so we can't use 4518 // getColumnToken, this is a bug, need to check it later. 4519 columnStr = cr.getPartToken().toString(); 4520 } 4521 if (this.fireOnMetaDatabaseTableColumn( 4522 subquery.tables.getTable(i).getTableName().getServerString(), 4523 subquery.tables.getTable(i).getTableName().getDatabaseString(), 4524 subquery.tables.getTable(i).getTableName().getSchemaString(), 4525 subquery.tables.getTable(i).getName(),columnStr)){ 4526 subquery.tables.getTable(i).getObjectNameReferences().addObjectName(cr); 4527 isfound = true; 4528 break; 4529 } 4530 } 4531 4532 4533 4534 if (!isfound) 4535 { 4536 if(subquery.tables.size() > 1){ 4537 cr.setTableDetermined(false); 4538 } 4539 for(int i=0;i<subquery.tables.size();i++){ 4540 subquery.tables.getTable(i).getObjectNameReferences().addObjectName(cr); 4541 } 4542 } 4543 4544 } // "*" 4545 } 4546 } 4547 }else if (ret == -2){ 4548 // no qualifier before column, check is this column of a cte, if not,set it to non-cte table 4549 boolean isfound = false; 4550 for (int i=0;i<this.tables.size();i++){ 4551 if ((this.tables.getTable(i).isCTEName()) &&(this.tables.getTable(i).getCteColomnReferences() != null)){ 4552 if (this.tables.getTable(i).getCteColomnReferences().searchColumnReference(cr) >= 0){ 4553 this.tables.getTable(i).getObjectNameReferences().addObjectName(cr); 4554 isfound = true; 4555 break; 4556 } 4557 } 4558 } 4559 4560 // no qualifier before column, but we still need to check uplevel table like this: 4561 //SELECT 4562 // col1 , 4563 // 4564 // ( SELECT col2 4565 // FROM tab1 4566 // WHERE col2 = col1 ) 4567 // FROM tab2 4568 // we need to link col1 to tab2 in up level, but not to tab1 4569 if ((!isfound) &&( 4570 (cr.getLocation() != ESqlClause.resultColumn) 4571 &&(cr.getLocation() != ESqlClause.insertColumn) 4572 &&(cr.getLocation() != ESqlClause.mergeInsert) 4573 &&(cr.getLocation() != ESqlClause.selectList) 4574 ) ){ // code #111 4575 TCustomSqlStatement lcParent = null; 4576 lcParent = this.getParentStmt(); 4577 while ( lcParent != null) { 4578 TTable lcTable; 4579 //ret = lcParent.tables.checkColumnReferenceInTables(cr); 4580 if (lcParent.sqlstatementtype != ESqlStatementType.sstselect) { 4581 break; 4582 } 4583 for (int i=0;i<lcParent.tables.size();i++){ 4584 lcTable = lcParent.tables.getTable(i); 4585 if (lcTable.getTableType() == ETableSource.objectname) { 4586 for(int k = 0; k< lcTable.getObjectNameReferences().size();k++){ 4587 if (lcTable.getObjectNameReferences().getObjectName(k).isTableDetermined()){ 4588 if (SQLUtil.compareIdentifier(this.dbvendor, ESQLDataObjectType.dotColumn, cr.toString(), lcTable.getObjectNameReferences().getObjectName(k).toString())){ 4589 isfound = true; 4590 break; 4591 } 4592 } 4593 } 4594 if (isfound) break; 4595 } 4596 } 4597 4598 if (isfound){ 4599 break; 4600 }else{ 4601 lcParent = lcParent.getParentStmt(); 4602 } 4603 } // while 4604 4605 } // end of code #111 4606 4607 if (!isfound){ 4608 isfound = checkNonQualifiedColumnReferenceInSubQueryOfUplevelStmt(cr 4609 , ((plocation == ESqlClause.resultColumn) 4610 ||(plocation == ESqlClause.insertColumn) 4611 ||(plocation == ESqlClause.mergeInsert) 4612 ||(plocation == ESqlClause.selectList) 4613 ) 4614 ); 4615 } 4616 4617 if ((!isfound)&&(this.tables.size() > 0)){ 4618 int candidate = 0, firstCandidate = -1; 4619 // add this column reference to first non-cte( or cte with column list is null) and non-subquery table 4620 for (int i=0;i<this.tables.size();i++){ 4621 // no qualified column can't belong to a table with alias, that column must be qualified if it's belong to a table with alias 4622 //if (this.tables.getTable(i).aliasClause != null) continue; 4623 if ( 4624 ( 4625 (!this.tables.getTable(i).isCTEName()) 4626 ||((this.tables.getTable(i).isCTEName())&&(this.tables.getTable(i).getCteColomnReferences() == null)) 4627 )&&((this.tables.getTable(i).getTableType() != ETableSource.subquery)) 4628 ) 4629 { 4630 candidate++; 4631 if (firstCandidate == -1) firstCandidate = i; 4632 if (this.fireOnMetaDatabaseTableColumn( 4633 this.tables.getTable(i).getTableName().getServerString(), 4634 this.tables.getTable(i).getTableName().getDatabaseString(), 4635 this.tables.getTable(i).getTableName().getSchemaString(), 4636 this.tables.getTable(i).getName(),cr.toString())){ 4637 this.tables.getTable(i).getObjectNameReferences().addObjectName(cr); 4638 isfound = true; 4639 break; 4640 } 4641 else{ 4642 this.tables.getTable(i).getObjectNameReferences().addObjectName(cr); 4643 if (this.tables.size() > 1){ 4644 cr.setTableDetermined(false); 4645 } 4646 isfound = true; 4647 break; 4648 } 4649 } 4650 } 4651 if ((!isfound) && (candidate == 1)){ 4652 this.tables.getTable(firstCandidate).getObjectNameReferences().addObjectName(cr); 4653 } 4654 } 4655 }else if (ret == -1){ 4656 TCustomSqlStatement lcParent = null; 4657 lcParent = this.getParentStmt(); 4658 while ( lcParent != null) { 4659 ret = lcParent.tables.checkColumnReferenceInTables(cr, names); 4660 if (ret >= 0){ 4661 lcParent.tables.getTable(ret).getObjectNameReferences().addObjectName(cr); 4662 break; 4663 }else{ 4664 lcParent = lcParent.getParentStmt(); 4665 } 4666 } // while 4667 } //-1 4668 4669 } 4670 4671 /** 4672 * Found out is a non qualified column is a column in uplevel subquery table like this: 4673 * take ma_parkey for example: ma_parkey is not a physical column 4674 * 4675 SELECT c_mandant 4676 , CASE WHEN EXISTS (SELECT 1 4677 FROM CDS_H_GRUPPE GRP1 4678 WHERE GRP1.c_mandant = c_mandant 4679 AND GRP1.parkey1 = ma_parkey) 4680 THEN 1 4681 ELSE NULL 4682 END MA_ME 4683 FROM (SELECT c_mandant 4684 , CASE WHEN funktionscode = 'U' 4685 THEN parkey1 4686 ELSE parkey2 4687 END MA_PARKEY 4688 FROM 4689 CDS_H_GRUPPE 4690 ) 4691 */ 4692 public boolean checkNonQualifiedColumnReferenceInSubQueryOfUplevelStmt(TObjectName crf,boolean sameLevelOnly){ 4693 boolean ret = false; 4694 4695 TCustomSqlStatement lcParent = null; 4696 lcParent = this;//getParentStmt(); 4697 // the reference's text, rendered the first time a subquery needs it (redundancy plan P5); with no subquery 4698 // table it is never rendered, as before. It is reused only when no rendering in between can change it: the 4699 // first pass of toString() marks only newline tokens, so a reference whose tokens hold no newline keeps its 4700 // text. One that holds a newline is rendered again for every table, as it was (Codex review of P5: an 4701 // enclosing expression on an edited chain can delete a newline inside the reference) 4702 String crfText = null; 4703 boolean crfRendered = false; 4704 boolean crfTextStable = false; 4705 while ( lcParent != null) { 4706 TTable lcTable; 4707 for (int i=0;i<lcParent.tables.size();i++){ 4708 lcTable = lcParent.tables.getTable(i); 4709 4710 if ((lcTable.getTableType() != ETableSource.subquery)) {continue;} 4711 4712 if (!crfRendered || !crfTextStable) { 4713 crfText = crf.toString(); 4714 if (!crfRendered) { 4715 crfTextStable = holdsNoNewline(crf); 4716 crfRendered = true; 4717 } 4718 } 4719 ret = isColumnNameInSelectList(crfText,lcTable.subquery); 4720 if (ret) {break;} 4721 4722 } 4723 if (ret) {break;} 4724 else{ 4725 if (sameLevelOnly){ 4726 lcParent = null; 4727 }else{ 4728 lcParent = lcParent.getParentStmt(); 4729 } 4730 } 4731 } // while 4732 4733 return ret; 4734 } 4735 4736 /** Whether the tokens of {@code node}, start to end, hold no newline token; false where its bounds are unknown. */ 4737 private static boolean holdsNoNewline(TParseTreeNode node) { 4738 TSourceToken current = node.getStartToken(); 4739 TSourceToken end = node.getEndToken(); 4740 if (current == null || end == null) { 4741 return false; 4742 } 4743 while (current != null) { 4744 if (current.tokentype == ETokenType.ttreturn) { 4745 return false; 4746 } 4747 if (current.equals(end)) { 4748 return true; 4749 } 4750 current = current.getNextTokenInChain(); 4751 } 4752 return false; 4753 } 4754 4755 private boolean isColumnNameInSelectList(String pColumn, TSelectSqlStatement pSelect){ 4756 // Iterative rewrite of the original recursive descent. Provably identical 4757 // output: it visits exactly the same set of leaf (non-combined) SELECTs as 4758 // the recursion, in the same left-before-right order, and applies the 4759 // identical per-column test (alias match, else expr match, case-insensitive). 4760 // The only reason for the change is that UNION trees are left-leaning and 4761 // can be thousands of branches deep, so recursive descent risks 4762 // StackOverflowError (see repo CLAUDE.md: iterative UNION traversal). 4763 Deque<TSelectSqlStatement> pending = new ArrayDeque<>(); 4764 pending.push(pSelect); 4765 while (!pending.isEmpty()) { 4766 TSelectSqlStatement select = pending.pop(); 4767 if (select == null) { 4768 continue; 4769 } 4770 if (select.isCombinedQuery()) { 4771 // Push right then left so left is popped/processed first, matching 4772 // the recursion's "check left before right" order. 4773 pending.push(select.getRightStmt()); 4774 pending.push(select.getLeftStmt()); 4775 continue; 4776 } 4777 if (select.getResultColumnList() != null){ //if it's a db2 value row, then getResultColumnList() will be null 4778 TResultColumnList resultColumns = select.getResultColumnList(); 4779 for(int j=0;j<resultColumns.size();j++){ 4780 TResultColumn lcColumn = resultColumns.getResultColumn(j); 4781 boolean ret = false; 4782 if (lcColumn.getAliasClause() != null){ 4783 ret = SQLUtil.compareIdentifier(this.dbvendor, ESQLDataObjectType.dotColumn, pColumn, lcColumn.getAliasClause().toString()); 4784 } 4785 if (ret) return true; 4786 // the expression's text compared without building it (redundancy plan P5); a null pColumn throws 4787 // after the expression rendered, as it did 4788 ret = pColumn != null ? lcColumn.getExpr().textEqualsIgnoreCase(pColumn) 4789 : pColumn.equalsIgnoreCase(lcColumn.getExpr().toString()); // non-identifier-compare: rendered SQL text 4790 if (ret) return true; 4791 } 4792 } 4793 } 4794 return false; 4795 } 4796 4797 public TCustomSqlStatement getTopStatement(){ 4798 TCustomSqlStatement ret = this; 4799 while (ret.getParentStmt() != null){ 4800 ret = ret.getParentStmt(); 4801 } 4802 return ret; 4803 } 4804 4805 4806// public String toScript(){ 4807// if (!isChanged()){ 4808// return this.toString(); 4809// } 4810// return super.toScript(); 4811// } 4812 4813} 4814 4815class constantVisitor extends TParseTreeVisitor { 4816 private boolean inWhere = false,inExprList = false; 4817 public void preVisit(TWhereClause node){ 4818 inWhere = true; 4819 } 4820 4821 public void postVisit(TWhereClause node){ 4822 inWhere = false; 4823 } 4824 4825 public void preVisit(TExpression node){ 4826 if (inWhere){ 4827 switch (node.getExpressionType()){ 4828 case list_t: 4829 inExprList = true; 4830 boolean isNumber = true; 4831 if (node.getExprList().size() > 0){ 4832 // check the type of the constant in the expr list 4833 TExpression expr = node.getExprList().getExpression(0); 4834 if (expr.getExpressionType() == EExpressionType.simple_constant_t){ 4835 if (expr.getConstantOperand().getLiteralType() == ELiteralType.etString){ 4836 isNumber = false; 4837 } 4838 } 4839 } 4840 4841 TSourceToken lcStartToken = node.getStartToken(); 4842 TSourceToken lcEndToken = node.getEndToken(); 4843 int tokenPos = 0; 4844 if ((lcEndToken != null) && (lcStartToken != null)){ 4845 TSourceToken lcCurrentToken = lcStartToken; 4846 while (lcCurrentToken != null){ 4847 4848 if (lcCurrentToken.equals(lcEndToken)){ 4849 break; 4850 }else{ 4851 4852 if (tokenPos == 1){ 4853 if (isNumber){ 4854 lcCurrentToken.setTextWithBackup("999"); 4855 }else{ 4856 lcCurrentToken.setTextWithBackup("'placeholder_str'"); 4857 } 4858 }else if (tokenPos > 1){ 4859 lcCurrentToken.tokenstatus = ETokenStatus.tsdeleted; 4860 } 4861 4862 lcCurrentToken = lcCurrentToken.getNextTokenInChain(); 4863 tokenPos++; 4864 } 4865 } 4866 } 4867 4868 break; 4869 } 4870 } // where 4871 } 4872 4873 public void postVisit(TExpression node){ 4874 if (inWhere){ 4875 switch (node.getExpressionType()){ 4876 case list_t: 4877 inExprList = false; 4878 break; 4879 } 4880 } 4881 } 4882 4883 public void preVisit(TConstant node){ 4884 if (inWhere&&(!inExprList)){ 4885 switch (node.getLiteralType()){ 4886 case etNumber: 4887 case etFloat: 4888 node.getStartToken().setTextWithBackup("999"); 4889 break; 4890 case etString: 4891 node.getStartToken().setTextWithBackup("'placeholder_str'"); 4892 break; 4893 } 4894 } 4895 } 4896 4897 public void preVisit(TFunctionCall node){ 4898 if (TBaseType.as_canonical_f_decrypt_replace_password){ 4899 int i = TBaseType.searchCryptFunction(node.getFunctionName().toString()); 4900 4901 if (i>0){ // find this function 4902 if (node.getArgs().size() >= i){ 4903 TExpression secondArg = node.getArgs().getExpression(i-1); 4904 if (secondArg.getExpressionType() == EExpressionType.simple_constant_t){ 4905 TConstant constant = secondArg.getConstantOperand(); 4906 constant.getValueToken().setTextWithBackup("'***'"); 4907 //System.out.println(node.toString()+":"+constant.toString()); 4908 }else if (secondArg.getExpressionType() == EExpressionType.simple_object_name_t){ 4909 TObjectName objectName = secondArg.getObjectOperand(); 4910 objectName.getStartToken().setTextWithBackup("'***'"); 4911 //System.out.println(node.toString()+":"+constant.toString()); 4912 } 4913 } 4914 } 4915 4916 } 4917 } 4918 4919 void processConstant(TConstant node){ 4920 switch (node.getLiteralType()){ 4921 case etNumber: 4922 case etFloat: 4923 node.getStartToken().setTextWithBackup("999"); 4924 break; 4925 case etString: 4926 node.getStartToken().setTextWithBackup("'placeholder_str'"); 4927 break; 4928 } 4929 } 4930 4931}