refactor(sql-engine): rebuild parsing, behavior, lineage, and execution - #206
Draft
zycgit wants to merge 70 commits into
Draft
refactor(sql-engine): rebuild parsing, behavior, lineage, and execution#206zycgit wants to merge 70 commits into
zycgit wants to merge 70 commits into
Conversation
- Register the MySQL, PostgreSQL, Oracle, SQL Server, DB2, Doris, MongoDB, Redis, and AnalyticDB SQL engines as independent hidden plugins - Bind SQL engines by name from datasource plugins instead of constructing and registering SqlEngineSpi instances locally - Add dedicated names and localized resources for each SQL engine plugin - Update SqlEngineSpi implementations to accept SqlParserParameters and cache parser, split, security, column-analysis, and rewrite capabilities by parameter set - Build MySQL parser configurations from server, exact, grammar version, and sql_mode parameters, and create PostgreSQL capabilities for the selected version - Replace the legacy ResAnalysisSpi entry point with BehaviorAnalysisSpi - Remove duplicated SQL engine labels and editor localization entries from datasource modules - Remove obsolete duplicate tests and the bundled Druid SNAPSHOT dependency
- Add independent parser modules for SQL-92, SQL-99, and SQL-2003 - Add complete ANTLR lexer and parser grammars for all three SQL standards - Implement DSL providers, statement parsers, SQL splitting, and SecQueryType classification - Recognize DDL for schemas, tables, views, routines, triggers, sequences, and related objects - Classify SELECT, INSERT, UPDATE, DELETE, MERGE, CALL, transaction, and privilege statements - Implement behavior analysis for statement subjects, actions, and source-object relations - Add security-domain resolution, resource-domain collection, and select-column analysis - Register the three standard engines as independent hidden plugins with localized resources - Expose parsing, splitting, behavior, security, and column analysis through SqlEngineSpi
- Move database security resolvers, builders, and domain models into the unified analysis/security package - Standardize the security-analysis structure for MySQL, PostgreSQL, Oracle, Doris, Redis, MongoDB, ClickHouse, MaxCompute, StarRocks, TiDB, OceanBase, PolarDB, GaussDB, and AnalyticDB - Rebuild DB2 and SQL Server security analysis around parser visitors, builder factories, and domain builders instead of legacy resolve-helper chains - Add a complete security-domain collector and SecDomainResolveSpi implementation for Dameng - Extend MySQL security analysis for DDL, DML, privileges, SHOW, FLUSH, REPLACE, and related statements - Add security-rule capability definitions for Greenplum and Hologres - Realign datasource SecRulesSupportSpi implementations with the unified security-analysis package structure - Expand security-rule resource scoring for tablespaces, policies, program objects, logs, jobs, libraries, resource groups, and other object types - Update sensitive-data processing, constraint checks, and rule matching for the new analysis model - Remove legacy security resolve helpers, duplicate implementations, and obsolete global DSL registration
… resource type, normalized name, and exact version-range lookup - Introduce ResourceRegistryDialect and RegisteredResourceType for dialect-specific identifier and resource rules - Implement MySQL identifier normalization with backtick and double-quote recognition - Add a strictly validated JSON resource loader for versions, types, name paths, and duplicate definitions - Maintain built-in functions, system loadable functions, and system objects for MySQL 5.6, 5.7, 8.0, 8.4, and 9.7 - Add MySqlResourceRegistry to classify built-in, user-defined, aggregate, system, and metadata resources - Register statement types and behavior actions for administrative functions involving locks, replication, logs, policies, configuration, imports, and performance - Support version-aware system-resource detection and object-permission bypass rules - Add the neutral MySqlObjectReference model with statement type, object type, existence semantics, resource path, and source position - Implement MySqlObjectReferenceVisitor for DDL, DML, DCL, session, replication, administration, import/export, and program-object references - Distinguish system functions from user-defined functions by target MySQL version and provide normalized facts for behavior-relation assembly
…s dialects - Introduce a shared lightweight SQL splitting framework across database dialects - Emit top-level statements incrementally and release completed parse trees to reduce memory usage for large scripts - Consolidate dialect-specific split implementations into parser packages and remove duplicated adapters - Preserve comments, source locations, statement type sets, and recursive child statements - Complete splitting support for MySQL, PostgreSQL, GaussDB, DB2, Dameng, MongoDB, SQL Server, and other dialects - Improve recursive splitting for MySQL stored programs, triggers, events, control statements, cursors, and view query bodies - Add MySQL version and sql_mode awareness to keep splitting accurate across syntax environments - Add DB2 case-insensitive handling and Redis SWAPDB statement splitting support
…s SPI - Migrate database plugins from ResAnalysisSpi to BehaviorAnalysisSpi - Use StatementBehavior to represent statement types, behavior actions, and resource relationships - Model resource access, creation, deletion, renaming, privileges, and dependencies through subject, action, and target - Add RdbBehaviorObjectFactory to build resource paths, object types, and source locations consistently - Implement behavior analysis visitors for MySQL, PostgreSQL, Oracle, DB2, SQL Server, Redis, MongoDB, and other parsers - Improve MySQL object reference collection, statement type resolution, and behavior relation assembly - Support compound relationships for rename, grant and revoke, import and export, indexes, triggers, and data dependencies - Adapt ClickHouse, Dameng, GaussDB, HANA, MaxCompute, StarRocks, TiDB, OceanBase, PolarDB-X, and AnalyticDB plugins - Remove legacy dialect-specific ResAnalysisSpi implementations and the shared RdbResAnalysisSpi implementation to support centralized resource-action conversion on the console side
- Move query column analysis implementations to analysis.column - Move SQL rewrite implementations to editor.rewrite - Add query column analysis support for Dameng - Remove inapplicable column analyzers and update related dependencies
- Replace the legacy ResAnalysisSpi resource analysis API with BehaviorAnalysisSpi - Introduce statement behavior, resource object, action, and relationship models - Pass SqlParserParameters consistently to parser, analysis, and rewrite capabilities - Complete SqlEngineSpi and SqlPlugin adapters across database plugins - Align SDK packages for SQL splitting, column analysis, security analysis, and rewriting - Remove the legacy resource analysis entry point and wire behavior analysis into plugins
- Cover MySQL 5.6, 5.7, 8.0, 8.4, and 9.7 grammar families - Support executable comments controlled by exact server versions - Add sql_mode-aware lexer rules for ANSI_QUOTES, PIPES_AS_CONCAT, and related features - Complete version-specific DDL, DML, transaction, replication, account, and administration syntax - Expand newer keywords, data types, query expressions, JSON, and external data syntax - Update related dialect grammars and parser base references
- Remove legacy resource fields and propagation from query and result models - Remove the supportMultiStatement capability from RdbSupportSpi - Update package references for SQL splitting, column analysis, and security analysis - Parse security rule scripts through the DetectRuleDslProvider instance - Clean up obsolete resource result handling across console and sidecar
… and StarRocks - Add dedicated CREATE TABLE ANTLR grammars for Doris and StarRocks - Parse table DDL into the unified RdbTable metadata model - Extract columns, data types, defaults, comments, indexes, key models, engines, and distribution settings - Move the StarRocks table parser from the UI layer to the execution metadata layer - Remove obsolete multi-statement capability implementations
- Add SQL parser parameter discovery to DsMetaService and MetaRService - Carry parser environments through sqlParameters in SessionContextDTO and StatusDTO - Centralize SqlEngineSpi and SqlParserParameters resolution in DmDsConfigService - Read VERSION() and @@SESSION.sql_mode from the active MySQL connection - Preserve the distinction between an empty sql_mode and unknown parameters - Synchronize parser parameters when updating session status - Remove the legacy datasource language configuration model and static capability metadata
- Detect completion, validation, and splitting capabilities through SqlEngineSpi - Pass session-level SqlParserParameters to language services and parsers - Use a consistent datasource parsing environment for completion, validation, and splitting - Simplify completion analysis and remove duplicated statement type inference - Expose datasource language capabilities and keyword resources dynamically in the query editor - Improve table permission validation and completion context handling
- Stop reading MY_SQL_MODE in MySQL and MariaDB connection factories - Do not execute SET sql_mode when creating connections - Remove sql_mode injection through MariaDB sessionVariables - Remove the EMPTY special value and related helper logic - Use the actual Session @@SESSION.sql_mode as the authoritative parser parameter
- merge resource analysis into QueryAnalysisService - convert statement behaviors into authorization resource actions
- Create auto-execution tasks using the primary SplitScript type - Keep transaction rejection and remove duplicate context-switch checks - Simplify split-script iteration and task type assignment
- Move ConsoleSqlNotifyService logic into SqlAuditRServiceProvider - Extract execution backfill into ExecutionBackfillHandler under analysis
- Centralize SQL splitting, rewriting, resource analysis, lineage analysis, and desensitization in QueryAnalysisService - Build complete QueryRequest objects per statement before validation, session creation, and execution - Remove duplicated and incorrectly ordered analysis logic from ConsoleQueryService and consolidate ResourceAction conversion
- Replace scalar SplitQueryType fields in QueryRequest and RuleDomain with ordered deduplicated collections - Update datasource parsers, rule evaluation, execution backfill, and query flows to preserve all classifications of composite statements - Remove primary-type selection and migrate security-domain fixtures to sqlTypes and sqlTargets arrays
- replace the single primary QueryType with query type collections - derive read/write semantics and permission requirements from resource actions - match security rules against analyzed target collections - replace legacy type metadata with typed level context and parser parameters 15:33
- introduce RuleQueryType as the internal type for security rule analysis - keep the single sqlType behavior of RuleDomain aligned with the main branch - migrate database visitors and builders away from direct SplitQueryType dependencies - preserve existing rule analysis behavior and defer further rule domain improvements 15:35
- initialize audit context from the latest SQL analysis results and behavior relations - create PENDING audit records before query execution or auto-execution dispatch - correlate prepared audit records by queryId and prevent duplicate initialization - reduce Sidecar reporting to status updates identified by queryId and sessionId - dispatch auto-execution jobs only after the transaction commits and audit preparation completes
…e isolation - adapt the rule engine and rule execution flow to the single-target RuleDomain model - use the isolated RuleQueryType model in sensitive data processing - provide a dedicated command type mapping for Redis rule analysis - add explicit type mappings required by MongoDB and PostgreSQL behavior analysis - align related auto-execution and audit APIs with the surrounding refactor
- introduce QueryAnalysisOptions for user, datasource, and resource-level context - control optional analysis features with REWRITE, PROVENANCE, and MASKING - skip unnecessary analysis stages for approval and auto-execution flows
Classify option_tracker_usage_set as SYSTEM_SETTING_WRITE and update its unit test.
- Remove unused primaryUid and puid parameters from query analysis and column lineage contexts - Clean up unused authorization APIs and helper methods - Centralize resource path handling and audit object conversion
- Add ObjectName to the behavior analysis model to represent catalog, schema, and object names - Introduce SysObjectRegistrySpi for SQL engines to register and identify built-in database objects - Register built-in object rules for MySQL, Oracle, OceanBase Oracle, SQL Server, MongoDB, and Redis - Integrate built-in object detection with authorization and data masking, exempting allowlisted objects while retaining standard permission checks for others
- Properly extract resource names enclosed in single quotes, double quotes, or backticks - Remove enclosing delimiters and unescape doubled quote characters - Correct behavior-analysis paths generated for configuration keys, functions, and other resources - Consolidate the behavior-analysis test framework and update related fixtures
- add 347 positive and 85 rejection fixtures covering DM8 DDL, DML, DQL, DCL, procedural blocks, data types, functions, packages, backup and recovery, and distributed features - expand lexer and parser support for huge and external tables, partitions, materialized views, types, classes, operators, system packages, and administrative statements - improve nested program splitting and secondary query-type collection, and correct rename, comment, session lock, and session setting classifications - align behavior extraction, security-domain collection, and column lineage analysis with the expanded DM8 grammar - discover positive and rejected fixtures separately and remove the legacy aggregate coverage files
- Remove the security rule requiring specific columns in query results - Remove the related SDK service, DTO, and plugin registration - Clean up the constraint-checking function and persistence layer - Eliminate an experimental feature that lacked a complete configuration workflow
- carry source lineage into ColumnConfig for each result column - exclude lineage sources authorized for sensitive-data access - enable masking independently for each output column - match masking rules against every non-exempt lineage source - remove duplicated column resolution from security domain builders - clean up obsolete query constraint storage
- unify lineage contracts with LineageAnalysisSpi, ColumnLineage, and SourceName - migrate SQL engines and data source implementations to the new lineage API - rebuild common lineage resolution for aliases, wildcards, joins, subqueries, CTEs, and set operations - fix source-column resolution for Dameng, MySQL, PostgreSQL, Oracle, and other engines - improve MySQL lineage handling across versions, functions, expressions, and query structures - migrate legacy column-analysis fixtures to lineage tests and expand cross-database coverage
- manage DM8 built-in functions and system procedures through VersionedResourceRegistry - move built-in functions and permission-exempt system resources to external JSON catalogs - validate resource versions, types, names, and duplicate entries - use the registry in DmSplitAnalysisSpi to distinguish built-in functions from user program objects - align lineage context usage and remove the unused MetaColConvert
- Add comprehensive DM8 behavior, column, and security-domain test fixtures - Cover database object lifecycles, DDL, DML, DQL, DCL, PL/SQL, system packages, and built-in functions - Improve behavior relations, object types, resource paths, and source-range analysis - Add versioned registries and permission exemptions for built-in functions, system procedures, types, and views - Enhance the DM8 grammar, parser base, and behavior visitor for nested statements and complex object relationships - Update downstream consumers for newly introduced TargetType values - Establish a comprehensive DM8 SQL compatibility regression baseline
…derivation - Rebuild the MySQL lineage pipeline with a CST visitor, unified lineage model, and scope-based resolver - Support complex lineage scenarios including CTEs, derived tables, joins, unions, wildcards, subqueries, and table functions - Unify the LineageColumn and SourceName APIs and adapt lineage implementations across database dialects - Add BehaviorRelations to flatten behavior relations into deduplicated resource permission requests - Derive READ, WRITE, DDL, PROGRAM, AUTH, ADMIN, and other authorization kinds from actions and resource types - Handle permission exemptions for system objects, virtual resources, and special statements with normalized resource paths - Integrate permission derivation into query authorization, approval tasks, automatic execution, and SQL editor workflows - Expand MySQL multi-version lineage and permission tests, update fixtures, and enable concurrent execution
…ing config - expand data-source permissions for program, authorization, and unsafe operations - centralize permission exemptions in database-specific resource registries - improve behavior resource derivation and Dameng function classification - add dm_ds_meta_config migration, DAO, and masking configuration mapping - add behavior permission tests and refresh MySQL and Dameng fixtures
- split behavior, lineage, permission, and split dynamic tests into separate test classes - divide each MySQL version into two shards to utilize the test framework's class-level concurrency - work around the inability to further parallelize dynamic test tasks - cover MySQL 5.6, 5.7, 8.0, 8.4, and 9.7 variants - adapt split tests to Reader-based APIs with caller-managed resource lifecycles
Refactor the ds-test framework to better fit JUnit discovery and parallel execution: - implement stable three-way sharding using relative resource path hashes - migrate split, lineage, behavior, and permission suites to three shards - use the Basic prefix consistently for shard base classes - enable adaptive JUnit parallel execution within a single Gradle test worker - lazily stream dynamic tests to reduce discovery and execution memory usage - derive parallelism and test heap size from the available processors - add test progress reporting, heartbeat output, and runtime tuning options - add missing datasource test entries and third-shard classes - verify that shards are disjoint and cover all fixture resources - fix test compilation issues caused by the Reader API migration - correct Oracle and OB-Oracle DUAL system-object path expectations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Rebuild the SQL processing stack from parser entry points through execution-time authorization.
This branch replaces the legacy coupling between statement splitting, query types, resource analysis, security domains, and Console-specific execution logic with a shared pipeline built around:
Most of the diff is the regenerated and expanded cross-dialect SQL fixture corpus required to validate the new contracts. The production changes span the plugin SDK, SQL engines, datasource plugins, Console services, audit persistence, security rules, and database migration.
Related Issues
None.
Type of Change
Commit Evolution
1. Establish the new engine foundation (
d3b0e00ab–489e14206)2. Make parsing session-aware and dialect-complete (
ffa941c72–d79f39b1b)CREATE TABLEmetadata parsers.sql_modebranching.supportMultiStatementpath in favor of the shared splitter.SplitQueryType.3. Move Console execution onto the shared analysis pipeline (
bc5820c7c–f2fb1147e)QueryTypevalues.4. Rebuild security, approval, and audit integration (
bfbe4dec4–76a236e1f)query_id, then transition them throughPENDING,RUNNING, and terminal states.QueryAnalysisOptionsand remove redundant analysis parameters from callers.5. Harden dialect behavior, lineage, and masking (
2505b9bd4–5bd73592d)dm_ds_meta_configpersistence model, DAO, mapper, and migration foundation for datasource object metadata such as masking configuration.6. Reconcile
mainand stabilize the merged result (1c2c60108,c133b8a96)mainbranch into the feature branch.username→account→bindAccount→ UID).execDalfield.s-testprogress and heartbeat output for the large dynamic fixture suite.Key Changes
SDK and plugin contracts
SplitQueryTyperesults.SQL engines and dialect support
Console analysis and execution
QueryAnalysisOptionsandQueryAnalysisFeature.Audit and persistence
query_id.query_id, indexes, nullable execution fields, and behavior storage;dm_exec_query_constraintstodm_ds_meta_config;maskingmetadata column.Compatibility and Scope Notes
dm_ds_meta_configestablishes the datasource-object metadata persistence contract. This PR does not add a management UI or write API for that table.Review Guide
Recommended review order:
cgdm-plugin-sdkanalysis, behavior, lineage, parser, and security contracts.sqlc-commonplus the SQL-engine implementations and versioned resource registries.QueryAnalysisServiceImpland its authorization, approval, CI/CD, auto-execution, and query callers.V202607270001__sql_audit_ack.Test Plan
Details:
Current GitHub Actions status:
b9053c915; the stale field injection is fixed ands-testnow emits progress heartbeats.The full local unit and integration test suites were not rerun during the final merge-conflict repair. The branch itself adds and updates extensive parser, split, behavior, security-domain, lineage, and compatibility coverage.
git diff --check origin/main...HEADreports whitespace in tracked SQL grammar and SQL fixture content. Those findings are in the large fixture corpus rather than uncommitted local files; the working tree is clean and the branch head matchesorigin/feat/sql_engine_optimization.Checklist