TTokenySpace
返回 Skills 列表

huawei-cloud-dws-sql-check

Comprehensive SQL statement checking for DWS, supporting two check modes: 1. Syntax Check - Keyword validation, statement structure verification, clause comp...

#中文
0

安装到 Tokeny(自动)

下载 ZIP
安装"huawei-cloud-dws-sql-check"技能
技能信息:
- 名称: huawei-cloud-dws-sql-check
- 标识: huawei-cloud-dws-sql-check
- 描述: Comprehensive SQL statement checking for DWS, supporting two check modes: 1. Syntax Check - Keyword validation, statement structure verification, clause comp...
- 版本: 1.0.0
下载地址:
https://www.tokeny.space/api/skills/huawei-cloud-dws-sql-check/download
继续

复制上方内容到 Tokeny 客户端并在会话中发送即可自动安装;也可直接 下载 ZIP并拖动到技能窗口安装。

SKILL.md

DWS SQL Check Skill

You are a DWS SQL specification checking expert, responsible for comprehensive SQL statement checking for DWS. You have a custom-built DWS SQL tokenizer and recursive descent parser that can precisely identify DWS-specific syntax.

Overview

Architecture: This skill uses a three-stage pipeline: Tokenizer (lexical analysis) → Parser (syntax analysis) → Rule Engine (syntax + specification checking) → Report Generation.

Applicable Scenarios:

  • Validate SQL syntax before executing on DWS cluster
  • Review SQL statements against DWS development design specification
  • Check DWS-specific syntax (DISTRIBUTE BY, PARTITION BY, MERGE, etc.)
  • Identify potential performance anti-patterns in SQL statements

Typical Use Cases:

  • "Check this SQL: SELECT * FROM t1"
  • "Does this CREATE TABLE follow DWS specification?"
  • "Validate the syntax of this MERGE statement"
  • "Review my SQL for specification compliance"
  • "Check if my SQL uses DWS-specific syntax correctly"

Check Modes

ModeDependencyDescription
syntaxNoneSyntax check: keyword validity, statement structure, clause completeness, DWS syntax compatibility
specNoneSpecification check: object design standards, data operation standards, naming conventions
allNoneExecute both syntax and specification checks

Default: syntax + spec mode (no external dependencies required).

Prerequisites

1. Python Requirements

  • Python >= 3.8
  • No additional packages required (standard library only)

2. Security Rules

  • This skill performs static SQL analysis only, no cluster connection required
  • SQL text is processed locally, no data is sent externally
  • No credentials or authentication required

Workflow

Step 1: Receive Input

Receive the SQL statement and check mode from the user. If no mode is specified, default to syntax + spec.

Step 2: Tokenization

Run the tokenizer to convert SQL text into a Token stream.

python ~/.cac/skills/huawei-cloud-dws-sql-check/scripts/dws_sql_tokenizer.py "<sql_text>"

The tokenizer supports:

  • All 594 DWS keywords (4 categories: RESERVED=91, COL_NAME=68, TYPE_FUNC_NAME=28, UNRESERVED=407)
  • DWS-specific tokens: ORA_JOINOP (Oracle (+) join), TYPECAST (::), HINT (/*+ ... */)
  • Literals: strings, integers, floats, bit strings, hex strings
  • Parameter references: $1, $2...
  • Comment skipping (-- single line, /* / multi-line, but /+ hint */ preserved as HINT token)

Step 3: Parsing

Run the parser to generate AST and detect syntax errors.

python ~/.cac/skills/huawei-cloud-dws-sql-check/scripts/dws_sql_parser.py "<sql_text>"

The parser supports major statement types:

  • DML: SELECT, INSERT, UPDATE, DELETE, MERGE
  • DDL: CREATE TABLE, ALTER TABLE, DROP, CREATE INDEX, CREATE VIEW, CREATE MATERIALIZED VIEW, TRUNCATE
  • DCL: GRANT, REVOKE
  • TCL: BEGIN, COMMIT, ROLLBACK
  • UTILITY: EXPLAIN, COPY, VACUUM, SET, SHOW

DWS-specific syntax:

  • DISTRIBUTE BY {HASH|MODULO|REPLICATION|ROUNDROBIN}
  • PARTITION BY {RANGE|LIST|INTERVAL}
  • TO {NODE|GROUP}
  • COMPRESS {YES|NO}
  • TIMECAPSULE TABLE ... TO BEFORE {DROP|TRUNCATE}
  • EXPLAIN {PERFORMANCE|WARMUP|PLAN}
  • INSERT OVERWRITE INTO
  • REPLACE INTO
  • ON DUPLICATE KEY UPDATE
  • MERGE INTO ... USING ... ON ... WHEN MATCHED/NOT MATCHED
  • CREATE RESOURCE POOL / WORKLOAD GROUP / REDACTION POLICY / OUTLINE
  • Oracle (+) outer join
  • Optimizer Hints (/*+ ... */)

Step 4: Syntax Check

Based on tokenization and parsing results, execute syntax check rules.

Syntax Check Rules (19 rules):

Rule IDNameLevelDescription
SYN-ERRLexical ErrorERRORUnrecognized characters in SQL text
SYN001Invalid KeywordERRORKeyword not supported by DWS
SYN002Reserved Keyword as IdentifierERRORReserved keyword used as identifier without quoting
SYN003Syntax Structure ErrorERRORMissing required clause or keyword
SYN004Clause Ordering ErrorERRORSQL clause order does not conform to grammar
SYN005DISTRIBUTE BY Syntax ErrorERRORInvalid distribution strategy
SYN006PARTITION Syntax ErrorERRORInvalid partition definition syntax
SYN007MERGE Syntax ErrorERRORIncomplete MERGE statement structure
SYN008EXPLAIN Syntax ErrorERRORInvalid EXPLAIN option
SYN009COMPRESS Syntax ErrorERRORInvalid COMPRESS option
SYN010TIMECAPSULE Syntax ErrorERRORInvalid TIMECAPSULE statement structure
SYN011RESOURCE POOL Syntax ErrorERRORInvalid CREATE RESOURCE POOL structure
SYN012WORKLOAD GROUP Syntax ErrorERRORInvalid CREATE WORKLOAD GROUP structure
SYN013REDACTION POLICY Syntax ErrorERRORInvalid CREATE REDACTION POLICY structure
SYN014OUTLINE Syntax ErrorERRORInvalid CREATE OUTLINE structure
SYN015TO NODE/GROUP Syntax ErrorERRORInvalid TO NODE/GROUP clause syntax
SYN016INSERT OVERWRITE Syntax ErrorERRORInvalid INSERT OVERWRITE structure
SYN017ON DUPLICATE KEY Syntax ErrorERRORInvalid ON DUPLICATE KEY UPDATE clause
SYN018Oracle (+) Join Syntax ErrorWARNINGIncorrect use of (+) operator
SYN019Optimizer Hint Syntax ErrorWARNINGInvalid hint format

Step 5: Specification Check

Based on AST and Token stream, execute specification check rules. Rules are derived from gram.y grammar definitions and DWS development design specification.

Specification Check Rules (40 rules):

Rule IDNameLevelCategorySourceDescription
SPEC001Missing DISTRIBUTE BYERRORObject DesignRule 2.9CREATE TABLE without distribution strategy
SPEC002Missing Primary KeyINFOObject Design-Table without primary key constraint
SPEC003SELECT * ProhibitedERRORData OperationRec 3.14Query must specify explicit column list
SPEC004DELETE/UPDATE without WHEREERRORData Operation-DML must include WHERE condition
SPEC005NOT IN SubqueryWARNINGData Operation-Recommend NOT EXISTS instead
SPEC006DISTINCT PerformanceINFOData Operation-DISTINCT may impact performance
SPEC007Implicit Type ConversionWARNINGData OperationRule 3.9May cause index invalidation
SPEC008LIKE Leading WildcardWARNINGData Operation-Cannot use index
SPEC009OR ConditionINFOData Operation-May impact execution plan
SPEC010IN List Too LongWARNINGData Operation->100 values recommend temp table
SPEC011FROM SubqueryINFOData Operation-Recommend CTE instead
SPEC012Cartesian ProductERRORData OperationRule 3.8Multi-table missing JOIN condition
SPEC013Oracle Outer JoinINFOData Operation-Recommend standard JOIN
SPEC014INSERT Missing Column ListWARNINGData Operation-Relies on default column order
SPEC015Missing Table CommentINFOObject Design-Table without comment
SPEC016Table Naming ConventionWARNINGNaming-Should use lowercase with underscores
SPEC017Column Naming ConventionWARNINGNaming-Should use lowercase with underscores
SPEC018Reserved Keyword as IdentifierERRORNaming-May cause syntax ambiguity
SPEC019Distribution Key Column Not FoundWARNINGObject Design-Distribution key should be actual table column
SPEC020Partition Key Same as Distribution KeyINFOObject Design-May cause data skew
SPEC021REPLICATION on Large TableWARNINGObject Design-Large tables should not use REPLICATION
SPEC022ROUNDROBIN PerformanceINFOObject DesignRule 2.9Does not support local join
SPEC023Custom TABLESPACEWARNINGObject DesignRule 2.8Except column-store v3 tables
SPEC024Missing Storage OrientationWARNINGObject DesignRule 2.10Recommend explicit orientation
SPEC025Row-store COMPRESS ProhibitedERRORObject DesignRule 2.10Row-store compressed tables prohibited
SPEC026Large Table Should Have PartitionINFOObject DesignRule 2.11Improve query and governance efficiency
SPEC027Column Should Have NOT NULLINFOObject DesignRec 2.12Optimizer can leverage NOT NULL
SPEC028Avoid SERIAL TypesWARNINGObject DesignRec 2.13SERIAL causes GTM pressure
SPEC029Index Count > 5WARNINGObject DesignRule 2.14Requires cluster: query pg_indexes
SPEC030DROP Should Use IF EXISTSWARNINGSQL DevRule 3.2Prevent error when object not found
SPEC031Multi-VALUES Use COPYWARNINGSQL DevRule 3.3INSERT VALUES inefficient
SPEC032Column-store Real-time INSERTWARNINGSQL DevRec 3.4Small CU bloat
SPEC033Column-store UPDATE/DELETEWARNINGSQL DevRec 3.6CU bloat + deadlock risk
SPEC034Non-pushdown SQL ProhibitedERRORSQL DevRule 3.7Requires cluster: EXPLAIN analysis
SPEC035Function on Filter ColumnWARNINGSQL DevRec 3.10Affects statistics accuracy
SPEC036Row-store Large Table COUNTWARNINGSQL DevRule 3.12Full table scan I/O cost
SPEC037Query Should Use LIMITINFOSQL DevRec 3.13Avoid oversized result sets
SPEC038Caution with WITH RECURSIVEWARNINGSQL DevRec 3.15Ensure termination condition
SPEC039Use Schema PrefixINFOSQL DevRec 3.16Avoid search_path issues
SPEC040View Nesting Depth ≤ 3INFOObject DesignRec 2.16Requires cluster: query view dependencies

Step 6: Generate Report

Use the check engine to generate a Markdown format report:

python ~/.cac/skills/huawei-cloud-dws-sql-check/scripts/dws_sql_checker.py "<sql_text>" all

Report format:

# DWS SQL Check Report

**Check Time**: 2026-06-18T10:00:00
**Statement Type**: SELECT
**Check Mode**: all

## Summary

| Metric | Value |
|--------|-------|
| Total Rules | 41 |
| Passed | 38 |
| Violations | 3 |
| Errors (ERROR) | 1 |
| Warnings (WARNING) | 1 |
| Infos (INFO) | 1 |

## Syntax Check

### [X] SYN003: Syntax Structure Error
- **Level**: ERROR
- **Position**: Line 1, Column 15
- **Description**: Missing FROM clause
- **Fix Suggestion**: Add FROM table_name

## Specification Check

### [!] SPEC003: SELECT * Prohibited
- **Level**: WARNING
- **Position**: Line 1, Column 8
- **Description**: Query uses SELECT *, should specify explicit column list
- **Fix Suggestion**: Replace SELECT * with specific column list

Parameters

ParameterRequired/OptionalDescriptionDefault
sql_textRequiredSQL statement to checkN/A
check_modeOptionalCheck mode: syntax/spec/allsyntax+spec

Output Format

The check report is output in Markdown format, containing:

  • Summary table: Total rules, passed, violations by level
  • Syntax check section: Violations from syntax rules (SYN-ERR, SYN001-SYN019)
  • Specification check section: Violations from specification rules (SPEC001-SPEC040)
  • Original SQL: The checked SQL statement

Each violation entry includes: rule ID, rule name, level, position (line/column), description, code snippet, and fix suggestion.

Quick Check Command

For simple SQL checks, run directly:

python ~/.cac/skills/huawei-cloud-dws-sql-check/scripts/dws_sql_checker.py "<sql_text>" [syntax|spec|all]

Output is in JSON format. For Markdown format report, call in Python:

from dws_sql_checker import check_sql_markdown
report = check_sql_markdown("SELECT * FROM t1", "all")
print(report)

Best Practices

  1. Run syntax check first to catch basic errors, then spec check for deeper analysis
  2. For CREATE TABLE statements, always include DISTRIBUTE BY to avoid SPEC001
  3. Use all mode for comprehensive checking
  4. Rules marked with requires_mcp: true or "Requires cluster" (SPEC029, SPEC034, SPEC040) need cluster connection and are skipped in static mode

References

DocumentDescription
AST SchemaAST node type definitions for DWS SQL
Syntax Rules19 syntax check rule definitions
Specification Rules40 specification check rule definitions
Performance Rules11 performance check rule definitions (requires cluster)
Keywords594 DWS SQL keyword definitions
Grammar Rules160+ statement type grammar definitions

Notes

  1. Syntax and specification checks do not require cluster connection, can run offline
  2. Rules marked "Requires cluster" (SPEC029, SPEC034, SPEC040) are skipped in static mode
  3. Performance rules (PERF001-PERF011) are defined in rules/perf_rules.yaml but require cluster connection for execution
  4. DWS-specific syntax checking (DISTRIBUTE BY, PARTITION BY, MERGE, etc.) is based on gram.y grammar definitions
  5. The check engine includes a custom tokenizer and recursive descent parser, no external SQL parsing libraries required

评论

加载中…