Class TCustomSqlStatement
- All Implemented Interfaces:
IRelation,Visitable,Iterator<TSourceToken>
- Direct Known Subclasses:
TAllocateStmt,TAlterAccessPolicy,TAlterAccountStmt,TAlterAuditPolicyStmt,TAlterAuthentication,TAlterConstraintStmt,TAlterCredentialStmt,TAlterDatabaseStmt,TAlterFaultGroup,TAlterFileFormatStmt,TAlterFulltextIndexStmt,TAlterFunctionStmt,TAlterGroup,TAlterIndexStmt,TAlterJWTProviderStmt,TAlterLDAPProviderStmt,TAlterLibraryStmt,TAlterMaterializedViewStmt,TAlterNetworkInterface,TAlterNetworkPolicyStmt,TAlterNode,TAlterPackageStmt,TAlterPartitionFunctionStmt,TAlterPartitionSchemeSqlStatement,TAlterPartitionSchemeStmt,TAlterPipeStmt,TAlterProcedureStmt,TAlterProfile,TAlterProjectionRename,TAlterPSEStmt,TAlterRelation,TAlterRemoteSourceStmt,TAlterResourceMonitorStmt,TAlterResourcePool,TAlterRoleStmt,TAlterSAMLProviderStmt,TAlterSchemaStmt,TAlterSequenceStatement,TAlterSessionStatement,TAlterShareStmt,TAlterStageStmt,TAlterStatisticsStmt,TAlterSubnet,TAlterSynonymStmt,TAlterSystemStmt,TAlterTaskStmt,TAlterTriggerStmt,TAlterTypeStatement,TAlterUserGroupStmt,TAlterUserStmt,TAlterVirtualTableStmt,TAlterWarehouseStmt,TAlterWorkloadClassStmt,TAlterWorkloadMappingStmt,TAlterZoneStmt,TAnalyzeStmt,TAssignStmt,TBackupCancelStmt,TBackupCatalogDeleteStmt,TBackupCheckStmt,TBackupDataStmt,TBackupListDataStmt,TBasicStmt,TBeginTran,TBlockSqlStatement,TBreakStmt,TCacheTable,TCallStatement,TCaseStmt,TCheckWorkload,TCloseStmt,TCommentOnSqlStmt,TCommitStmt,TComputeStats,TConnectStmt,TConvertToDeltaStmt,TCopyStmt,TCreateAccessPolicy,TCreateAliasStmt,TCreateAuditPolicyStmt,TCreateAuthentication,TCreateCatalogStmt,TCreateCertificateStmt,TCreateCollectionStmt,TCreateCredentialStmt,TCreateDatabaseLinkStmt,TCreateDatabaseSqlStatement,TCreateEventSession,TCreateExtensionStmt,TCreateExternalDataSourceStmt,TCreateExternalLanguage,TCreateExternalLocationStmt,TCreateFaultGroup,TCreateFileFormatStmt,TCreateFulltextIndexStmt,TCreateGraphWorkspaceStmt,TCreateGroup,TCreateHCatalogSchema,TCreateIndexSqlStatement,TCreateJWTProviderStmt,TCreateLDAPProviderStmt,TCreateMasterKeyStmt,TCreateMaterializedSqlStatement,TCreateMaterializedViewLogSqlStatement,TCreateModelSqlStatement,TCreateNetworkPolicyStmt,TCreatePartitionFunctionStmt,TCreatePartitionSchemeSqlStatement,TCreatePartitionSchemeStmt,TCreatePipeStmt,TCreatePSEStmt,TCreateRemoteSourceStmt,TCreateResourceMonitorStmt,TCreateRoleStmt,TCreateSAMLProviderStmt,TCreateSemanticViewStmt,TCreateSequenceStmt,TCreateShareStmt,TCreateStageStmt,TCreateStatistics,TCreateStreamStmt,TCreateStructuredPrivilegeStmt,TCreateSubnet,TCreateSynonymStmt,TCreateTablespaceStmt,TCreateTableSqlStatement,TCreateTaskStmt,TCreateTypeStmt,TCreateUserGroupStmt,TCreateUserStmt,TCreateViewSqlStatement,TCreateVirtualFunctionStmt,TCreateVirtualProcedureStmt,TCreateVirtualTableStmt,TCreateWarehouseStmt,TCreateWorkloadClassStmt,TCreateWorkloadMappingStmt,TCreateZoneStmt,TCursorDeclStmt,TCustomDb2Stmt,TCustomDropStatement,TCustomMySQLStmt,TCustomOracleSqlStmt,TDaxStmt,TDb2StmtStub,TDeclareCursorStmt,TDeleteSqlStatement,TDenyStmt,TDescribeStmt,TDisableEnableTriggerStmt,TDisconnectStmt,TDropAccessPolicy,TDropAggregateFunction,TDropAuthentication,TDropConstraintStmt,TDropDatabaseLinkStmt,TDropDatabaseStmt,TDropFaultGroup,TDropFunctionStmt,TDropGroup,TDropLibraryStmt,TDropMacro,TDropMaterializedViewLogStmt,TDropMaterializedViewStmt,TDropNetworkInterface,TDropPartitionSchemeStmt,TDropProcedureStmt,TDropProfileStmt,TDropProjectionStmt,TDropResourcePool,TDropRoleSqlStatement,TDropRoleStmt,TDropSchemaSqlStatement,TDropSequenceStmt,TDropStmt,TDropStreamStmt,TDropSubnet,TDropSynonymStmt,TDropTableSqlStatement,TDropTextIndex,TDropTransformFunction,TDropTriggerSqlStatement,TDropUserStmt,TDropViewSqlStatement,TElsifStmt,TEndTran,TExecutePreparedStatement,TExecuteSqlStatement,TExitStmt,TExplainPlan,TExportDataStmt,TExportStmt,TExportToVertica,TFetchFromStmt,TFetchStmt,TGetDiagnosticsStmt,TGetDiagStmt,TGetStmt,TGrantSqlStatement,TGrantStmt,THelpProcedure,THiveCreateFunction,THiveCreateRole,THiveDescribe,THiveDropDatabase,THiveDropFunction,THiveDropRole,THiveExplain,THiveExportTable,THiveGrant,THiveGrantRole,THiveImportTable,THiveLoad,THiveRevoke,THiveRevokeRole,THiveSet,THiveShow,THiveShowGrant,THiveShowRoleGrant,THiveSwitchDatabase,THiveUnlockTable,TIfStmt,TImportStmt,TInferKeyspaceStmt,TInformixAllocateCollectionStmt,TInformixAllocateDescriptorStmt,TInformixAllocateRow,TInformixAlterAccess_MethodStmt,TInformixAlterFragment,TInformixCreateRowTypeStmt,TInformixCreateTrigger,TInformixDropRowTypeStmt,TInformixExecuteFunction,TInformixExecuteImmediate,TInformixExecuteProcedure,TInformixExecuteStmt,TInsertBulk,TInsertSqlStatement,TIterateStmt,TLeaveStmt,TListStmt,TLoadStmt,TLockSqlStatement,TLockTableStmt,TMdxAlterCube,TMdxCalculate,TMdxCall,TMdxCase,TMdxClearCalculations,TMdxCreateAction,TMdxCreateCellCalculation,TMdxCreateGlobalCube,TMdxCreateMeasure,TMdxCreateMember,TMdxCreateSessionCube,TMdxCreateSet,TMdxCreateSubCube,TMdxDrillthrough,TMdxDropAction,TMdxDropCellCalculation,TMdxDropMember,TMdxDropSet,TMdxDropSubcube,TMdxExpression,TMdxFreeze,TMdxIf,TMdxRefreshCube,TMdxScope,TMdxSelect,TMdxUpdate,TMergeDeltaStmt,TMergeSqlStatement,TMoveStmt,TMSCKStmt,TMssqlAlterSecurityPolicy,TMssqlBeginConversationTimer,TMssqlBeginDialog,TMssqlBulkInsert,TMssqlClose,TMssqlCommit,TMssqlContinue,TMssqlCopyIntoStmt,TMssqlCreateSecurityPolicy,TMssqlCreateType,TMssqlCreateXmlSchemaCollectionStmt,TMssqlDeallocate,TMssqlDeclare,TMssqlDropDbObject,TMssqlDropSecurityPolicy,TMssqlDropTable,TMssqlDropView,TMssqlDummyStmt,TMssqlEndConversation,TMssqlErrorStmt,TMssqlExecute,TMssqlExecuteAs,TMssqlFetch,TMssqlGo,TMssqlGoTo,TMssqlGrant,TMssqlIfElse,TMssqlLabel,TMssqlOpen,TMssqlPrint,TMssqlRaiserror,TMssqlReturn,TMssqlRevert,TMssqlRollback,TMssqlSaveTran,TMssqlSendOnConversation,TMssqlSet,TMssqlSetRowCount,TMssqlStmtStub,TMssqlThrow,TMssqlTryCatch,TMssqlUpdateStatistics,TMssqlUpdateText,TMssqlWaitFor,TMssqlWithas,TMySQLOptimizeTableStmt,TMySQLStmtStub,TNetezzaGenerateStatistics,TNetezzaGroomTable,TNullStmt,TOpenforStmt,TOpenStmt,TOptimizeStmt,TOracleCreateLibraryStmt,TOracleExecuteProcedure,TParseErrorSqlStatement,TPerformanceStmt,TPgImport,TPlsqlContinue,TPlsqlCreateTriggerSqlStatement,TPlsqlCreateType,TPlsqlCreateType_Placeholder,TPlsqlDummyStmt,TPlsqlForallStmt,TPlsqlGotoStmt,TPlsqlNullStmt,TPlsqlPipeRowStmt,TPlsqlPragmaDeclStmt,TPlsqlProcedureSpecStmt,TPlsqlRecordTypeDefStmt,TPlsqlSqlStmt,TPlsqlStatement,TPlsqlSubProgram,TPlsqlTableTypeDefStmt,TPlsqlVarrayTypeDefStmt,TPostgresqlTableStmt,TPrepareStmt,TProfileStmt,TPseudoExprStmt,TPutStmt,TRaiseStmt,TReconfigure,TRecoverDatabaseStmt,TRecoverDataStmt,TRedshiftAbort,TRedshiftAlterSchema,TRedshiftAlterUser,TRedshiftAnalyze,TRedshiftAnalyzeCompression,TRedshiftBegin,TRedshiftCancel,TRedshiftClose,TRedshiftComment,TRedshiftCommit,TRedshiftCopy,TRedshiftCreateSchema,TRedshiftCreateUser,TRedshiftDeallocate,TRedshiftDeclare,TRedshiftDropSchema,TRedshiftDropUser,TRedshiftEnd,TRedshiftExplain,TRedshiftLock,TRedshiftPrepare,TRedshiftReset,TRedshiftRollback,TRedshiftSessionAuthorization,TRedshiftUnload,TRedshiftVacuum,TRefresh,TRefreshMaterializedViewStmt,TRefreshStatisticsStmt,TReindexStmt,TReleaseSavepointStmt,TRemoveStmt,TRenameStmt,TReorgTableStmt,TResetSessionStmt,TResetStmt,TResourceManagement,TRestoreTableStmt,TReturnStmt,TRevokeStmt,TRollbackStmt,TSavepointStmt,TSelectSqlStatement,TSetCatalogStmt,TSetDatabaseObjectStmt,TSetSchemaStmt,TSetSearchPathStmt,TSetStmt,TShowProcedure,TShowSearchPathStmt,TShowStmt,TSignalStmt,TSlashCommand,TSnowflakeCopyIntoStmt,TSqlplusCmdStatement,TStartTransactionStmt,TSybaseDeleteStatistics,TSybaseDumpTran,TSybaseUpdateIndexStatistics,TSybaseWritetext,TTBuildIndexesStmt,TTeradataAbort,TTeradataBeginLogging,TTeradataBeginTransaction,TTeradataBTEQCmd,TTeradataCollectStatistics,TTeradataCommit,TTeradataCreateTrigger,TTeradataDropDbObject,TTeradataEndLogging,TTeradataExecute,TTeradataFastExportCmd,TTeradataFastLoadCmd,TTeradataGive,TTeradataGrant,TTeradataLock,TTeradataMultiLoadCmd,TTeradataMultiLoadExport,TTeradataMultiLoadImport,TTeradataMultiLoadLayout,TTeradataNotImplement,TTeradataReleaseLockStmt,TTeradataRollback,TTeradataSetRole,TTeradataSetSession,TTeradataSetTimezone,TTeradataStmtStub,TTeradataUsing,TTruncateCollectionStmt,TTruncateStatement,TUndropStmt,TUnknownSqlStatement,TUnloadStmt,TUnsetStmt,TUpdateSqlStatement,TUpsertStmt,TUseDatabase,TUseRole,TUseSchema,TUseSecondaryRolesStmt,TUseStmt,TUseWarehouse,TVacuumStmt,TValidateLDAPProviderStmt,TValidateUserStmt,TVarDeclStmt,TVerticaSetStmt,TVerticaShow
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumNormalization profiles for SQL hashing. -
Field Summary
FieldsModifier and TypeFieldDescriptionintTag used by parser internally.protected TFromClauseprotected TJoinExprprotected TTablebooleanprotected booleanjoins represents table sources in the from clause.Parser used to parse this statement.PLSQL parser used to parse this statement.protected ArrayList<TAttributeNode>Original Parse tree node from parserSource tokens included in this statement.Type of this statement.protected gudusoft.gsqlparser.compiler.TStmtScopeOriginal SQL fragment of this statement.Provides a quick way to access all tables involved in this SQL statement.Fields inherited from class gudusoft.gsqlparser.nodes.TParseTreeNode
dbvendor, doubleLinkedTokenListToString, nodeActionAppend, nodeActionInsert, nodeActionRemove, nodeActionUnknown, nodeActionUpdate, nodeActionUpdateText, nodeChangeEndToken, nodeChangeStartToken -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddToTables(TTable pTable) addWhereClause(String condition) Deprecated.analyzeFromTable(TFromTable pfromTable, Boolean addToTableList) analyzeFromTable(TFromTable pfromTable, Boolean addToTableList, ESqlClause pLocation) analyzeJoin(TJoinExpr pJoinExpr, TJoin pJoin, Boolean isSub) analyzeTablename(TObjectName tableName) analyzeTableOrJoin(TFromTable pfromTable) this method return a canonical form of a SQL statement in plan text.booleancheckNonQualifiedColumnReferenceInSubQueryOfUplevelStmt(TObjectName crf, boolean sameLevelOnly) Found out is a non qualified column is a column in uplevel subquery table like this: take ma_parkey for example: ma_parkey is not a physical column SELECT c_mandant , CASE WHEN EXISTS (SELECT 1 FROM CDS_H_GRUPPE GRP1 WHERE GRP1.c_mandant = c_mandant AND GRP1.parkey1 = ma_parkey) THEN 1 ELSE NULL END MA_ME FROM (SELECT c_mandant , CASE WHEN funktionscode = 'U' THEN parkey1 ELSE parkey2 END MA_PARKEY FROM CDS_H_GRUPPE )voidcomputeSqlHash(TCustomSqlStatement.SqlNormalizationProfile profile, String normVersion) Compute a SQL hash using the given normalization profile and version.protected intintfindTable(ETableEffectType[] tableEffectTypes) booleanfireOnMetaDatabaseTableColumn(String pServer, String pDatabase, String pSchema, String pTable, String pColumn) 每个 relation 包含的 attributes 当它为 base table 时,这些 attributes 的来源有三种可能 1.getColumnsInTable(TTable lcTable) Deprecated.since 2.3.8.2, useTTable.getExpandedStarColumns()instead.getColumnsInTable(String pServer, String pDatabase, String pSchema, String pTable) Deprecated.since 2.3.8.2, useTTable.getExpandedStarColumns()instead.Multiple common table expressionsTCTEcan be specified following the single WITH keyword.intNumber of syntax errors for this statement.Stack<gudusoft.gsqlparser.compiler.TFrame>This is a join in from clause, including left and right relation.This is table in from clause if only one table is listed in the from clause, If more than one table is listed in from clause, please checkgetFromSourceJoin()instead.gudusoft.gsqlparser.compiler.TGlobalScopegetJoins()Retrieves the unique and stable identifier for this SQL statement.Relations that used in from clause of select statement.In select statement, this method returns Items in select_list.Backward compatible overload equivalent togetSqlHash(false).getSqlHash(boolean forceReCalculate) Returns a stable, vendor-aware hash of this statement's SQL text for lineage grouping and statement identity.Saves all first level sub statements.gudusoft.gsqlparser.compiler.TStmtScopeDeprecated.since ver 2.5.3.5, please useTStmtScopeinsteadtarget table in the delete/insert/update/create table statement.restrict the rows selected to those that satisfy one or more conditions.booleanbooleanbooleanbooleanbooleanbooleanbooleanbooleanbooleanbooleanprotected booleanisTableACTE(TTable pTable) booleanvoidlinkColumnReferenceToTable(TObjectName cr, ESqlClause plocation) Deprecated.As of v1.6.0.1, uselinkColumnToTable(gudusoft.gsqlparser.nodes.TObjectName, gudusoft.gsqlparser.ESqlClause)insteadbooleanlinkColumnToTable(TObjectName pColumn, ESqlClause pLocation) 将列引用解析并绑定到其来源(表、子查询、CTE、表函数、OPENQUERY/UNNEST 等)。 功能概述: 1) 针对 DAX 语法直接走 DAX 分支。 2) 已绑定或标记“延迟到列解析器”的列直接返回。 3) 设定列所在语法位置,并校验列名/保留字(含 MySQL true/false/default、内置函数等)。 4) 处理厂商伪表/特殊前缀(Oracle :new/:old;SQL Server INSERTED/DELETED)。 5) Insert All/VALUES 场景:优先在子查询结果集中/变量或过程参数中匹配。 6) 在当前语句的 FROM 表集合中查找并建立绑定: - 限定列 table.col:按别名/表名匹配;对子查询/CTE/OPENQUERY 进一步在结果集中定位源列; 命中后写入 linkedColumns,必要时将 TableToken 标记为 subquery_alias。 - 非限定列 col: a.protected booleanlinkToFirstTable(TObjectName pColumn, int pCandidateTableCnt) booleanbooleanlocateVariableOrParameter(TObjectName cr, boolean checkVariableDeclaredInProcedure) booleanLog error messages if syntax errors found while parsing this statement.intparsestatement(TCustomSqlStatement pparentsql, boolean isparsetreeavailable) intparsestatement(TCustomSqlStatement pparentsql, boolean isparsetreeavailable, boolean onlyNeedRawParseTree) Parse this statement.protected TCTEListsearchCTEList(Boolean stopAtFirstFinding) booleansearchFunctionInSQLEnv(String functionName) voidsetAlreadyAddToParent(boolean alreadyAddToParent) voidsetCteIncludeThisStmt(TCTE cteIncludeThisStmt) voidsetCteList(TCTEList cteList) voidsetEndlabelName(TObjectName endlabelName) voidsetFrameStack(Stack<gudusoft.gsqlparser.compiler.TFrame> frameStack) voidsetFromClause(TFromClause fromClause) voidsetLabelName(TObjectName lName) voidsetOutputClause(TOutputClause outputClause) voidsetParentStmt(TCustomSqlStatement parentStmt) voidvoidsetQueryId(String queryId) voidsetResultColumnList(TResultColumnList resultColumnList) voidsetReturningClause(TReturningClause returningClause) voidsetSqlHash(String sqlHash) voidsetStmtScope(gudusoft.gsqlparser.compiler.TStmtScope stmtScope) voidsetTargetTable(TTable targetTable) voidsetTopClause(TTopClause topClause) voidsetUsingVariableList(TColumnDefinitionList usingVariableList) voidsetVariableStack(Stack<TObjectName> variableStack) voidsetWhereClause(TWhereClause newWhereClause) intsize()Produce a normalized textual representation of this statement according to the supplied profile.toScript()Return the text string of this node, the return value is the same asTParseTreeNode.toString()if this node is not modified manually after created by parser.booleanMethods inherited from class gudusoft.gsqlparser.nodes.TParseTreeNode
accept, acceptChildren, addAllMyTokensToTokenList, addToTokenChain, appendNewNode, calculateTokenCount, doAppendNewNode, doParse, fastSetString, getAnchorNode, getColumnNo, getCommentAfterNode, getCommentBeforeNode, getCompactString, getDummyTag, getEndToken, getEvaluateDatatype, getEvalValue, getGsqlparser, getLineNo, getLocation, getMd5, getNodeStatus, getNodeType, getPlainText, getStartToken, getTokenCount, hasNext, init, init, init, init, init, init, insertAfterAToken, insertNewNodeBeforeMe, isChanged, isTokensInChain, next, refreshAllNodesTokenCount, remove, removeAllMyTokensFromTokenList, removeTokens, removeTokensBetweenNodes, removeTokensBetweenToken, replaceWithNewNode, resetIterator, setAnchorNode, setChanged, setDummyTag, setEndToken, setEndToken, setEndToken, setEndToken, setEndToken, setEndTokenDirectly, setEvaluateDatatype, setEvalValue, setGsqlparser, setIncludingComment, setLocation, setNewSubNode, setNodeStatus, setNodeType, setParent, setPlainText, setStartToken, setStartToken, setStartToken, setStartToken, setStartTokenDirectly, setString, setString2, subNodeInNode, toString, toString2Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.Iterator
forEachRemaining
-
Field Details
-
relationAttributes
-
fromClause
-
fromSourceTable
-
fromSourceJoin
-
sqlstatementtype
Type of this statement. -
sourcetokenlist
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. Please checkTParseTreeNode.getStartToken(), andTParseTreeNode.getEndToken()of this statement. -
parser
Parser used to parse this statement. -
plsqlparser
PLSQL parser used to parse this statement. -
dummytag
Tag used by parser internally. -
joins
joins represents table sources in the from clause. All structure information was reserved.SQL 1:
select f from t1
size of joins will be 1, t1 can be fetch via joins.getJoin(0).getTable()
SQL 2:
select f from t1,t2
size of joins will be 2,
t1 can be fetch via joins.getJoin(0).getTable()
t2 can be fetch via joins.getJoin(1).getTable()
SQL 3:
select f from t1 join t2 on t1.f1 = t2.f1
size of joins will be 1,
t1 information can be fetch via joins.getJoin(0).getTable()
In order to access t2, we need to introduce a new class
TJoinItemwhich includes all information about t2 and join condition.There is a property named joinItems of
TJoinwhich is type ofTJoinItemListthat includes a list ofTJoinItem.this property can be access via
TJoin.getJoinItems().Now, t2 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(0).getTable()
SQL 4:
select f from t1 join t2 on t1.f1 = t2.f1 join t3 on t1.f1 = t3.f1
size of joins will be 1,
t1 can be fetch via joins.getJoin(0).getTable()
t2 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(0).getTable()
t3 can be fetch via joins.getJoin(0).getJoinItems().getJoinItem(1).getTable()
- See Also:
-
tables
Provides a quick way to access all tables involved in this SQL statement.It stores all tables in a flat way while
joinsstores all tables in a hierarchical structure.joins only represents tables in from clause of select/delete statement, and tables in update/insert statement.
tablesincludes all tables in all types of SQL statements such as tables involved in a create table or create trigger statements. -
rootNode
Original Parse tree node from parser -
semicolonended
-
isctequery
-
isparsed
-
stmtScope
Original SQL fragment of this statement.
-
-
Constructor Details
-
TCustomSqlStatement
-
-
Method Details
-
setSqlHash
-
getSqlHash
Returns a stable, vendor-aware hash of this statement's SQL text for lineage grouping and statement identity.Purpose:
- Provide a deterministic identifier for a statement that is insensitive to formatting (whitespace, comments, keyword case).
- Act as the first component of a recommended
statementKeyfor lineage grouping:statementKey = sqlHash + "#" + queryId.
- Builds a normalized textual representation of the statement by
iterating the token chain between
getStartToken()andgetEndToken(). - Normalization rules (Profile A by default): remove comments;
collapse spacing deterministically; uppercase keywords; handle
identifiers by the current vendor's case-sensitivity
(
TSQLEnv.columnCollationCaseSensitive). For delimited identifiers (quoted identifiers), the quotes are removed viaTBaseType.removeQuoteChar(String)before case normalization. String literals are kept as-is. - The hash input is prefixed by a normalization version and the
current vendor, so future evolution of the normalizer will not break
previously computed values:
normVersion + "\n" + vendor + "\n" + normalizedSql. - Hash function: SHA-256 (lowercase hex).
- Call
getSqlHash(false)for cached result or lazy calculation with Profile A (identity-safe) normalization. - Call
getSqlHash(true)to force recalculation (e.g., after mutating the underlying token chain). - If you need a grouping-friendly variant (masking certain literal
classes), use
computeSqlHash(SqlNormalizationProfile, String)withTCustomSqlStatement.SqlNormalizationProfile.GROUPING_FRIENDLY.
- Parameters:
forceReCalculate- if true, recompute the hash even if a cached value exists- Returns:
- lowercase hex SHA-256 hash of the normalized SQL text
-
getSqlHash
Backward compatible overload equivalent togetSqlHash(false). -
computeSqlHash
public String computeSqlHash(TCustomSqlStatement.SqlNormalizationProfile profile, String normVersion) Compute a SQL hash using the given normalization profile and version. SeegetSqlHash(boolean)for details.- Parameters:
profile- normalization profilenormVersion- version tag embedded in the hash input- Returns:
- lowercase hex SHA-256 hash
-
toNormalizedSql
Produce a normalized textual representation of this statement according to the supplied profile. The method is non-mutating: it does not alter token texts or statuses permanently. Rules applied: - Remove comments. - Remove trailing semicolon. - Deterministic spacing around punctuation/operators. - Uppercase keywords, keep string literals as-is. - Identifiers: if the vendor's column collation is case sensitive, keep identifier case; otherwise uppercase. For quoted identifiers, remove quoting viaTBaseType.removeQuoteChar(String)prior to case handling. - Minimal operator unification:"!="becomes"<>". - Profile B adds date/time string masking:'1970-01-01'.- Parameters:
profile- normalization profile- Returns:
- normalized SQL string
-
setQueryId
-
getQueryId
Retrieves the unique and stable identifier for this SQL statement.The queryId provides a reliable way to reference any statement, including subqueries, within a parsed SQL script. It is generated hierarchically based on the statement's position within the Abstract Syntax Tree (AST), ensuring that the ID is reproducible across identical SQL inputs.
ID Format:
- A top-level statement has an ID like
"stmt_0_select", where0is the index of the statement in the script andselectis the statement type. - A nested statement will have a path-like ID that includes its parent's ID. For example,
an
INSERTstatement containing aSELECTsubquery might have an ID for the subquery like"stmt_0_insert#stmt_1_select".
- Returns:
- The unique query identifier string for this statement, or
nullif it has not been set.
- A top-level statement has an ID like
-
setUsingVariableList
-
getUsingVariableList
-
getAttributes
Description copied from interface:IRelation每个 relation 包含的 attributes 当它为 base table 时,这些 attributes 的来源有三种可能 1. 来自数据库的 metadata,第一次 resolve 时就可以获取,来自 sqlenv 2. 来自 create table ddl,第一次 resolve 时就可以获取,来自 sqlenv 3. 来自 sql script,第二次 resolve 时,来自relation的 referenceAttribute 属性。 第一、二中来源是可靠的来源,attributes应该是完整的,第三种推断自 sql script,attributes很可能是不完整的。- Specified by:
getAttributesin interfaceIRelation- Returns:
-
getRelationName
- Specified by:
getRelationNamein interfaceIRelation
-
size
-
toScript
Description copied from class:TParseTreeNodeReturn the text string of this node, the return value is the same asTParseTreeNode.toString()if this node is not modified manually after created by parser.
If this node is modified, then use this method to get string representation instead of theTParseTreeNode.toString()method.- Overrides:
toScriptin classTParseTreeNode- Returns:
- text string of this node
-
setFromClause
-
getFromClause
-
getRelations
Relations that used in from clause of select statement. Or tables of other statements such as insert, update, delete and etc Please use this property to get the relations instead ofgetTables()andgetJoins()after version 2.7.4.0 when a join is used in from clause, then the table in getRelations() is type of ETableSource.join, and you can use TTable.getJoinExpr() to get this join.- Returns:
-
getFromSourceTable
This is table in from clause if only one table is listed in the from clause, If more than one table is listed in from clause, please checkgetFromSourceJoin()instead.- Returns:
- table in from clause
-
getFromSourceJoin
This is a join in from clause, including left and right relation. If only a single table is listed in from clause, please usegetFromSourceTable()instead- Returns:
-
asCanonical
this method return a canonical form of a SQL statement in plan text.
1. remove all comment inside SQL query.
2. remove redundant parenthesis at the begin/end of a select statement.
3. replace all number in where clause with 999 constant
4. replace all string constant in where clause with 'placeholder_str'
5. all number elements in a list such as (1,2,3,4) will be change to a single element (999)
6. all string elements in a list such as ('a','b','c','d') will be change to a single element ('placeholder_str')- Returns:
- a canonical form of a SQL statement in plan text.
-
setCteIncludeThisStmt
-
getCteIncludeThisStmt
-
getExpandedResultColumns
-
searchFunctionInSQLEnv
-
getSqlEnv
-
getGlobalScope
-
setFrameStack
-
getFrameStack
-
getIndexColumns
-
setVariableStack
-
getVariableStack
-
getDaxFunctionStack
-
setLabelName
-
getLabelName
- Returns:
- label name used in plsql statement.
-
setEndlabelName
-
getEndlabelName
-
getTokenList
-
getTargetTable
target table in the delete/insert/update/create table statement. -
setTargetTable
-
getJoins
-
getTables
-
getStatements
Saves all first level sub statements.By iterating statements recursively, you can fetch all included statements in an easy way.
select f1+(select f2 from t2) from t1 where f2 > all (select f3 from t3 where f4 = (select f5 from t4))
Statements included in above SQL was save in a hierarchical way like this:
- (select f2 from t2)
- (select f3 from t3 where f4 = (select f5 from t4))
- (select f5 from t4)
If this statement is a create procedure/function statement, then all declaration statements and statements in procedure body can also be fetched quickly by iterating this property recursively.
-
setCteList
-
getCteList
Multiple common table expressionsTCTEcan be specified following the single WITH keyword.Each common table expression specified can also be referenced by name in the FROM clause of subsequent common table expressions.
Used in select, delete, update statement.
- Returns:
- List of common table expression.
-
setResultColumnList
-
getResultColumnList
In select statement, this method returns Items in select_list. Can be *, expr, and name.*
In update statement, this method returns assignments in set clause.- Returns:
- select list of select statement or assignments of update statement.
-
setReturningClause
-
getReturningClause
- Returns:
returning clause.
-
setOutputClause
-
getOutputClause
- Returns:
- output clause.
-
setTopClause
-
getTopClause
- Returns:
top clause.
-
setWhereClause
-
addWhereClause
Deprecated.As of 2.0.9.0, usesetWhereClause(TWhereClause)instead Or, useTWhereClause.setText(String)- Parameters:
condition-- Returns:
-
getWhereClause
restrict the rows selected to those that satisfy one or more conditions. used in select, delete, update statement.- Returns:
where clause.
-
setAlreadyAddToParent
-
searchCTEList
-
getParentStmt
-
getParentObjectName
- Overrides:
getParentObjectNamein classTParseTreeNode
-
setParentStmt
-
setParentStmtToNull
-
getAncestorStmt
-
getSymbolTable
Deprecated.since ver 2.5.3.5, please useTStmtScopeinstead -
getSyntaxErrors
-
getErrormessage
-
getSyntaxHints
-
getErrorCount
Number of syntax errors for this statement.- Returns:
- 0 means no syntax error.
-
parseerrormessagehandle
Log error messages if syntax errors found while parsing this statement.- Parameters:
se- syntax error structure.- Returns:
- type of error
-
parsestatement
-
parsestatement
public int parsestatement(TCustomSqlStatement pparentsql, boolean isparsetreeavailable, boolean onlyNeedRawParseTree) Parse this statement.- Parameters:
pparentsql-isparsetreeavailable-- Returns:
- parse result, zero means no syntax error found.
-
OracleStatementCanBeSeparatedByBeginEndPair
-
VerticaStatementCanBeSeparatedByBeginEndPair
-
isnzplsql
-
ispgplsql
-
isGaussDBStoredProcedure
-
isdatabricksplsql
-
isgreeplumplsql
-
isathenaplsql
-
isprestoplsql
-
issnowflakeplsql
-
isBigQueryplsql
-
isverticaplsql
-
isoracleplsql
-
dochecksyntax
-
clearError
-
setStmtScope
-
getStmtScope
-
doParseStatement
-
analyzeTablename
-
isTableACTE
-
findTable
-
addToTables
-
analyzeTableOrJoin
-
analyzeFromTable
-
analyzeFromTable
-
analyzeJoin
-
locateVariableOrParameter
-
locateVariableOrParameter
-
getColumnsInTable
Deprecated.since 2.3.8.2, useTTable.getExpandedStarColumns()instead.- Parameters:
lcTable-- Returns:
-
getColumnsInTable
public ArrayList<String> getColumnsInTable(String pServer, String pDatabase, String pSchema, String pTable) Deprecated.since 2.3.8.2, useTTable.getExpandedStarColumns()instead.- Parameters:
pServer-pDatabase-pSchema-pTable-- Returns:
-
fireOnMetaDatabaseTableColumn
-
getFirstPhysicalTable
-
getOrphanColumns
-
linkToFirstTable
-
searchDaxVariableInStack
-
linkColumnToTable
将列引用解析并绑定到其来源(表、子查询、CTE、表函数、OPENQUERY/UNNEST 等)。 功能概述: 1) 针对 DAX 语法直接走 DAX 分支。 2) 已绑定或标记“延迟到列解析器”的列直接返回。 3) 设定列所在语法位置,并校验列名/保留字(含 MySQL true/false/default、内置函数等)。 4) 处理厂商伪表/特殊前缀(Oracle :new/:old;SQL Server INSERTED/DELETED)。 5) Insert All/VALUES 场景:优先在子查询结果集中/变量或过程参数中匹配。 6) 在当前语句的 FROM 表集合中查找并建立绑定: - 限定列 table.col:按别名/表名匹配;对子查询/CTE/OPENQUERY 进一步在结果集中定位源列; 命中后写入 linkedColumns,必要时将 TableToken 标记为 subquery_alias。 - 非限定列 col: a. 先尝试同层 SELECT 列别名(支持 LATERAL 语义且位置在别名之后); b. 处理通配符“*”:收集所有来源表; c. 基础表通过元数据回调 fireOnMetaDatabaseTableColumn 校验;未命中则记录候选; d. 子查询/CTE/函数/UNNEST/PIVOT 分别按各自规则匹配。 7) 命中后将列加入表的 linkedColumns 并设置 sourceTable/sourceColumn,必要时维持 isContinue 以继续匹配“*”。 8) 若未命中:尝试变量/参数;再按条件(语句类型/位置/是否限定等)向上一层语句递归查找(维护 searchLevel)。 9) 仍未命中:在顶层(searchLevel==0)按“候选唯一/或首表”兜底策略linkToFirstTable(TObjectName, int)。 参数:- Parameters:
pColumn- 需要绑定的列名对象(方法会更新其 location、sourceTable、sourceColumn 等)pLocation- 列出现的语法位置(如 selectList、where、insertValues 等) 返回值:- Returns:
- 成功绑定到某个来源返回 true;未能绑定或被识别为变量/保留字等返回 false
厂商兼容:
- Oracle: 处理 :new/:old,Insert All 的 values 子句源自子查询的匹配
- SQL Server: 处理 INSERTED/DELETED 伪表
- MySQL: 对保留字/布尔字面量/内置函数名的特殊判断
- DAX: 委托
linkColumnToTableDax(TObjectName, ESqlClause)副作用: - 更新 pColumn 的 location/searchLevel/sourceTable/sourceColumn/validate 状态 - 向命中的表写入 linkedColumns 或向别名列写入 targetColumns - 对“*”列填充 sourceTableList;对子查询命中时可能将 TableToken 标为 subquery_alias - 记录候选表数量并填充 pColumn.candidateTables,用于后续兜底 复杂度与顺序: - 优先使用同层信息(别名/元数据/子查询结果),再逐层向外查找;避免无谓的上层搜索 注意: - 本方法完成“旧算法”的快速联接,新的解析/消歧逻辑在解析器(如 TStmtScope/TAttributeResolver)中继续处理
-
linkColumnReferenceToTable
Deprecated.As of v1.6.0.1, uselinkColumnToTable(gudusoft.gsqlparser.nodes.TObjectName, gudusoft.gsqlparser.ESqlClause)instead -
checkNonQualifiedColumnReferenceInSubQueryOfUplevelStmt
public boolean checkNonQualifiedColumnReferenceInSubQueryOfUplevelStmt(TObjectName crf, boolean sameLevelOnly) Found out is a non qualified column is a column in uplevel subquery table like this: take ma_parkey for example: ma_parkey is not a physical column SELECT c_mandant , CASE WHEN EXISTS (SELECT 1 FROM CDS_H_GRUPPE GRP1 WHERE GRP1.c_mandant = c_mandant AND GRP1.parkey1 = ma_parkey) THEN 1 ELSE NULL END MA_ME FROM (SELECT c_mandant , CASE WHEN funktionscode = 'U' THEN parkey1 ELSE parkey2 END MA_PARKEY FROM CDS_H_GRUPPE ) -
getTopStatement
-
setWhereClause(TWhereClause)instead Or, useTWhereClause.setText(String)