Method and system for compiling natural language of Chinese into parameterized SQL based on OWL-RDF ontology

By using an OWL-RDF ontology-based approach, entities and relationships in the manufacturing sector are projected into structured configurations, generating standardized query text and performing semantic validation. This solves the instability problem of natural language queries being converted into SQL in manufacturing information systems, and improves the stability and security of queries.

CN123157759APending Publication Date: 2026-11-24YIZHIWEISI (BEIJING) INTELLIGENT TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611324286.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-28
Publication Date
2026-11-24

AI Technical Summary

Technical Problem

In manufacturing information systems, existing natural language to SQL solutions lack a stable domain semantic foundation, which leads to instability in the selection of table fields and JOIN relationships when querying SQL from Chinese natural language. This can easily result in problems such as incorrect selection of table fields, missing joins, incorrect joins, and record bloat after joining.

Method used

Using an OWL-RDF ontology-based approach, entities, relationships, dimensions, metrics, and filters in the manufacturing sector are projected into a structured ontology configuration. Standardized query text is generated through synonym normalization, relative time parsing, and text cleaning. Combined with semantic and permission verification, the join path is derived and parameterized SQL is generated.

Benefits of technology

It improves the stability and executability of SQL structures in multi-table queries in the manufacturing industry, reduces misselection, omission, and incorrect connection of table fields, and ensures the security and traceability of query results.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123157759A_ABST
    Figure CN123157759A_ABST
Patent Text Reader

Abstract

This invention provides a method and system for compiling Chinese natural language into parameterized SQL based on the OWL-RDF ontology, relating to the field of artificial intelligence technology. The method includes: upon passing all validations, determining the target entity based on the main entity and grouping dimensions, and deriving the connection path from the main entity to the target entity based on the entity relationships in the structured ontology configuration, thus obtaining a join clause; generating parameterized SQL based on the structured query plan and join clause, converting business filter values ​​into named parameters, and injecting row-level security conditions for non-privileged roles, thus obtaining a named parameter dictionary; outputting the parameterized SQL, named parameter dictionary, SQL hash value, and query form, and submitting for execution. This invention can reduce errors such as incorrect selection of table fields, missing joins, incorrect joins, and inappropriate join paths caused by temporary guessing, improving the stability and executability of SQL structures in multi-table queries in the manufacturing industry.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence technology, and in particular to a method and system for compiling Chinese natural language into parameterized SQL based on the OWL-RDF ontology. Background Technology

[0002] In manufacturing information systems, production, quality, equipment, processes, and master data are typically distributed across fact tables and multiple dimension tables. Business users can submit query requests for indicators using Chinese natural language. Existing natural language to SQL solutions usually entrust database schema information and user queries to a large language model for processing, and then the model directly generates SQL statements, or uses a few examples to prompt the model to construct SQL statements.

[0003] In query scenarios involving multiple fact tables and multiple dimension tables in the manufacturing industry, the aforementioned solutions lack a unified domain semantic foundation for stabilizing business terms, database table fields, and entity join relationships. The model needs to temporarily guess the fact table, dimension fields, and JOIN paths to which the indicators belong. When the same business concept has multiple Chinese expressions, or the same dimension has different physical bindings in different fact tables, it is prone to errors such as selecting the wrong table, selecting the wrong field, missing table joins, incorrect table joins, or record bloat after the join. Therefore, the existing solutions have the specific defect of unstable selection of table fields and JOIN relationships in Chinese natural language queries. Summary of the Invention

[0004] This invention provides a method and system for compiling Chinese natural language into parameterized SQL based on the OWL-RDF ontology. It can reduce the errors caused by temporary guessing in table field selection, omission, incorrect connection, and inappropriate connection paths, and improve the stability and executability of SQL structure in multi-table queries in the manufacturing industry.

[0005] To solve the above-mentioned technical problems, the technical solution of the present invention is as follows: The first aspect is the compilation method for converting Chinese natural language into parameterized SQL based on the OWL-RDF ontology, including: Load OWL or RDF ontology from the manufacturing domain and project entities, relations, dimensions, metrics, filters, and row-level security rules from the ontology into a structured ontology configuration. It receives Chinese natural language queries, user context information, and request time. Based on the structured ontology configuration and request time, it performs synonym normalization, relative time parsing, and text cleaning on the Chinese natural language queries to obtain normalized query text. Based on the normalized query text and structured ontology configuration, entities, indicators, dimensions and filtering conditions are identified, resulting in a structured query plan that records the main entity, indicator list, filtering conditions and grouping dimensions; Based on the structured ontology configuration and user context information, semantic verification, permission verification, and anti-injection verification are performed on the structured query plan. If any verification fails, the compilation is terminated and an error message is output. When all checks pass, the target entity is determined based on the main entity and grouping dimension, and the connection path from the main entity to the target entity is derived based on the entity relationships in the structured ontology configuration, thus obtaining the connection clause; Parameterized SQL is generated based on the structured query plan and join clauses, business filter values ​​are converted into named parameters, and row-level security conditions are injected for non-privileged roles to obtain a named parameter dictionary; Output parameterized SQL, named parameter dictionary, SQL hash value and query form, and submit for execution.

[0006] Secondly, a compilation system for converting Chinese natural language to parameterized SQL based on the OWL-RDF ontology, the system comprising: The OWL or RDF ontology loading and projection module is used to load OWL or RDF ontology in the manufacturing field and project entities, relationships, dimensions, metrics, filters, row-level security rules and global configurations into structured ontology configurations. The index and cache compilation module is used to compile the synonym index, query constraint whitelist and indicator dimension compatibility matrix according to the structured ontology configuration, and write the compilation results to the system cache. The query compilation pipeline module includes a preprocessing unit, a query plan parsing unit, a validation unit, a join derivation unit, and an SQL generation unit. The preprocessing unit is used to obtain normalized query text based on Chinese natural language queries, thesaurus indexes, and request times. The query plan parsing unit is used to obtain a structured query plan based on the normalized query text. The validation unit is used to perform semantic validation, permission validation, and anti-injection validation on the structured query plan before SQL generation. The join derivation unit is used to obtain join clauses based on the ontology relation graph when the validation passes. The SQL generation unit is used to generate parameterized SQL based on the structured query plan and join clauses. The security control and SQL output module is used to convert business filter values ​​into named parameters, inject row-level security conditions for non-privileged roles, and output parameterized SQL, named parameter dictionary, SQL hash value and query form.

[0007] The above-described solution of the present invention has at least the following beneficial effects: This application projects the OWL or RDF ontology of the manufacturing domain into a structured ontology configuration, and generates a synonym index, query constraint whitelist, and indicator dimension compatibility matrix accordingly. This ensures that business terms, indicators, dimensions, fact tables, and entity relationships have unified and reusable semantic constraints before query compilation. Chinese natural language queries are preprocessed and converted into structured query plans. Before generating SQL, the system checks the plan's integrity, ontology consistency, indicator dimension compatibility, and entity reachability. Only after successful verification is the connection path from the main entity to the target entity deduced based on the ontology relationship graph. This reduces errors caused by temporary guessing in table field selection, missing connections, incorrect connections, and inappropriate connection paths, improving the stability and executability of SQL structures in multi-table queries in the manufacturing industry. Furthermore, it restricts named parameter conversion, non-privileged role row-level security condition injection, short-circuiting of verification failures, and the output of SQL hash values ​​and query formats, ensuring that the resulting query results possess both checkable security constraints and traceable compilation basis. Attached Figure Description

[0008] Figure 1 A flowchart illustrating the compilation method of Chinese natural language to parameterized SQL based on the OWL-RDF ontology is shown.

[0009] Figure 2 A flowchart of a compilation system for converting Chinese natural language to parameterized SQL based on the OWL-RDF ontology is shown. Detailed Implementation

[0010] To make the technical solution of this application clearer, the embodiments of this application will be described in detail below with reference to the illustrated process. OWL is the Web Ontology Language, and RDF is the Resource Description Framework; the OWL / RDF ontology is used to express the business objects, object relationships, and query constraints involved in manufacturing data queries. SQL is the Structured Query Language; parameterized SQL is a query expression that separates SQL text from business filter values ​​and permission values. The SQL text reserves placeholder positions for named parameters, and the database execution engine obtains the corresponding parameter values ​​from the named parameter dictionary during execution. The terms "first" and "second" in this document are only used to distinguish similar objects and do not indicate any order or importance.

[0011] like Figure 1 and Figure 2 As shown, this embodiment is applied to a data query scenario in a manufacturing execution system. Production, quality, equipment, process, work orders, and master data are distributed across multiple database tables. The fact table stores capacity, quality, or other measurable facts, while the dimension table stores descriptive information such as production lines, processes, workstations, and dates. Business personnel input Chinese questions such as the yield rate of each process over the past few days, the capacity of a certain production line yesterday, or the number of abnormalities in each production line this week. The compilation system converts these Chinese questions into parameterized SQL that can be executed by the database execution engine.

[0012] In this embodiment, the structured ontology configuration is called OntologyConfig, which includes at least entity definitions, relationship definitions, dimension definitions, metric definitions, filter definitions, row-level security rule definitions, and global configuration definitions. The structured query plan is called QueryPlan, which includes at least the main entity, metric list, filter conditions, grouping dimensions, aggregation method, and query limit. Dimension binding is called DimBinding, used to record the physical field position of the same dimension under the current main entity. The SQL hash value is used to identify the generated SQL text, and the query shape QueryShape is used to describe the query type composed of metrics and grouping dimensions.

[0013] In this embodiment, an entity is a structured representation of a manufacturing business object on the query compilation side, and the entity definition specifies the database table corresponding to the business object; a relation is a foreign key connection between two entities that can be used to join tables, and the relation definition specifies the entities at both ends of the relation and the fields on which the connection is based; a dimension is a business observation direction used for grouping or filtering, and the dimension definition specifies the canonical dimension identifier and its physical field binding; a metric is a query object obtained after performing aggregation calculations on fact data, and the metric definition specifies the canonical metric identifier, the fact table to which it belongs, and the aggregation calculation expression; a filter is a structured definition that converts canonical filter objects into WHERE conditions; and a row-level security rule is a filter definition that restricts access to the production line or factory scope according to user roles. All of the above objects come from the OWL / RDF ontology, and the compilation system does not temporarily create new entities, relations, dimensions, metrics, filters, or row-level security rules from user input.

[0014] The term "establishment" in this paper refers to the process of creating configuration objects, index objects, relationship graph objects, or SQL clauses that can be read by subsequent steps based on the ontology definition or structured results obtained in the previous step. The term "mapping" or "projection" refers to the process of transforming semantic objects in the ontology to their corresponding definition locations in OntologyConfig according to the query responsibilities of the ontology objects, while preserving the correspondence between business objects and database table fields. The term "identification" refers to the process of determining candidate objects corresponding to the standardized identifiers from the standardized query text within the candidate range limited by the synonym index and query constraint whitelist. The term "verification" refers to the process of comparing the objects and object relationships in QueryPlan with OntologyConfig, user context information, or security naming constraints item by item, and giving a pass or fail status based on the comparison results.

[0015] The term "search" as used in this article refers to accessing relation edges from the primary entity and obtaining a path that leads to the target entity within an entity relationship graph composed of ontology entities and ontology relations. The term "path scoring" refers to determining the path length cost, relation cardinality cost, JOIN type cost, and data inflation risk cost of candidate paths, multiplying each cost by its corresponding weight, and then summing the results. The term "ranking" refers to determining the order of candidate paths according to their path scores, and comparing them sequentially based on path length, relation cardinality risk, and predefined primary join relationships when the score differences meet the configured threshold conditions. The term "parameterization" refers to separating the SQL structure from business filter values ​​and permission values, preserving the positions of named parameters in the SQL text, and storing the corresponding actual values ​​in the named parameter dictionary.

[0016] OntologyConfig, synonym index, query constraint whitelist, indicator dimension compatibility matrix, and entity relationship graph belong to ontology configuration-side data; Chinese natural language query, normalized query text, QueryPlan, join clauses, parameterized SQL, and named parameter dictionary belong to request compilation-side data. Configuration-side data can be read by multiple query requests. After a single query request obtains a specific cached version, M1 to M5 all read that version. Request compilation-side data is passed in the order of M1 to M5, without using the results of later steps to rewrite the ontology definition already confirmed in the previous step. By distinguishing between these two types of data, configuration updates and single request compilations can be kept separate.

[0017] Existing solutions centrally provide database schema, examples, permission rules, user questions, and SQL generation requirements to a large language model, which then selects tables, fields, and join relationships in one go and generates SQL. In manufacturing databases, indicators may reside in either a capacity fact table or a quality fact table, and the same dimension may be directly located in a fact table or in a separate dimension table. Without stable domain semantic constraints, the model needs to temporarily infer the fact table and JOIN path to which the indicator belongs based on the current input. Business synonyms further increase the identification differences, leading to unstable selection of table fields and JOIN relationships.

[0018] To address this issue, this embodiment does not directly convert Chinese queries into SQL all at once. Instead, it first projects the OWL / RDF ontology into a unified configuration usable during the compilation process. Then, it forms a progressively chained processing step by step through M1 preprocessing, M2 query plan parsing, M3 validation, M4 JOIN deduction, and M5 SQL generation. Each level of processing uses the structured output of the previous level. If M3 validation fails, subsequent compilation stops; only after validation passes is the join path determined based on the ontology relationship graph. Since table field selection and JOIN deduction are constrained by the ontology definition and structured plan, it can reduce fluctuations in join results between different query requests.

[0019] See Figure 1 The compilation method in this embodiment includes steps S1 to S11. Step S1 loads the OWL / RDF ontology; Step S2 projects the ontology to OntologyConfig; Step S3 compiles the index according to OntologyConfig and writes it to SystemCache; Step S4 receives Chinese natural language queries, user context information, and request time; Step S5 performs M1 preprocessing; Step S6 performs M2 query plan parsing; Step S7 performs M3 verification, executing a failure short-circuit if verification fails, and proceeding to Step S8 if verification passes; Step S8 performs M4 JOIN derivation; Step S9 performs M5 SQL generation; Step S10 outputs parameterized SQL, named parameter dictionary, SQL hash value, and QueryShape; Step S11 submits the parameterized SQL and named parameter dictionary to the database execution engine.

[0020] This process progressively transforms natural language text into normalized query text, QueryPlan, join clauses, and parameterized SQL, ensuring that the input and output at each stage are inspectable. OWL / RDF ontology is integrated throughout terminology normalization, candidate constraints, compatibility checks, and relational graph derivation, while user context information is integrated throughout permission verification and row-level security condition generation. Therefore, the main table, metrics, dimensions, join relationships, and permission conditions in the final SQL can all be traced back to their corresponding ontology definitions or user context.

[0021] From a data lineage perspective, step S1 takes an OWL / RDF ontology file from the manufacturing sector as input and outputs a loaded ontology object. Step S2 takes the aforementioned ontology object as input and outputs OntologyConfig. Step S3 takes OntologyConfig as input and outputs a thesaurus index, a query constraint whitelist, an indicator dimension compatibility matrix, and a SystemCache version containing these contents. Step S4 obtains the query request input. Step S5 takes the query request and thesaurus index as input and outputs the normalized query text and the parsed time range. Step S6 takes the aforementioned normalized query text and OntologyConfig as input and outputs QueryPlan. Step S7 takes QueryPlan, OntologyConfig, and user context information as input and outputs a validation pass status or corresponding error. Step S8 outputs the join clause only when validation passes. Step S9 outputs the parameterized SQL to be executed and a named parameter dictionary based on QueryPlan, join clause, and user context information. Step S10 supplements the SQL hash value and QueryShape. Step S11 executes the query and generates a structured response.

[0022] M1 through M5 form a sequentially executed query compilation pipeline. If M1 fails to obtain a supported time range, it does not generate normalized query text for M2; if M2 detects multiple metrics belonging to different fact tables, it does not generate a QueryPlan for M3 to proceed; if any validation fails in M3, it does not generate the validation pass status required by M4; if M4 cannot determine a unique join path, it returns a candidate path instead of directly entering M5; M5 only generates SQL for the determined QueryPlan and join clauses. Each stopping point is located at the stage where an uncertain result first appears, thus subsequent stages will not continue compilation with missing or conflicting intermediate results.

[0023] In this embodiment, the structured output in the processing chain is also used to interpret the compilation results. The normalized query text describes the normalized identifier and time range corresponding to the original Chinese business expression; the QueryPlan describes the selected metrics, main entity, filtering conditions, and grouping dimensions; the M3 result describes whether the corresponding object satisfies ontology and permission constraints; the connection path describes the ontology relationship between the main entity and the target entity; and the named parameter dictionary describes the binding positions of business filter values ​​and permission values. All of the above outputs are generated by the recorded compilation stage and do not infer user intent.

[0024] OWL / RDF ontology loading, projection, and index cache compilation specifically include: Step S1: The compilation system loads a pre-built OWL / RDF ontology file for the manufacturing domain. The ontology file defines entities, relationships, dimensions, metrics, filters, row-level security rules, and global configurations in the MES scenario. Entities can correspond to capacity fact tables, quality fact tables, process dimension tables, or production line dimension tables. Relationships record foreign key connections between entities. Metrics record aggregate calculation expressions corresponding to output, yield, or OEE. Dimensions record grouping or filtering fields corresponding to production lines, processes, workstations, or dates. By loading the above ontology, the compilation system obtains the domain semantic source used for subsequent parsing and SQL generation.

[0025] In step S2, the compilation system parses the semantic nodes and relationships in the loaded ontology and writes them into the OntologyConfig according to the query responsibilities represented by the nodes or relationships. For the mapping between business objects and database tables, the compilation system writes entity definitions; for foreign key joins between tables, the compilation system writes relationship definitions; for groupable or filterable fields, the compilation system writes dimension definitions; for aggregate calculation expressions, the compilation system writes metric definitions; for content that can generate WHERE conditions, the compilation system writes filter definitions; and for the data ranges that different roles can access, the compilation system writes row-level security rule definitions. These definitions together constitute the OntologyConfig, which can be directly read by subsequent compilation stages, transforming the semantic information in the OWL / RDF graph structure into a unified structured configuration.

[0026] Step S3: The compilation system traverses OntologyConfig and generates a synonym index, a query constraint whitelist, and a metric dimension compatibility matrix. The index entries in the synonym index point multiple Chinese expressions to the same specification identifier; for example, "production line" and "line body" point to "line," and "yield rate" and "pass rate" point to "yield_rate." The query constraint whitelist includes entities, metrics, dimensions, and filters that the system allows to recognize, used to prevent arbitrary user text from becoming SQL identifiers. The metric dimension compatibility matrix indicates whether a metric supports grouping by a certain dimension, such as whether yield rate supports grouping by process, production line, or date.

[0027] The compilation system writes the OntologyConfig and each auxiliary index into the SystemCache. When the SystemCache uses a double-buffering mechanism, one cache is used for currently executing query requests, while the other cache receives the updated ontology configuration and indexes. After the update is complete, the system uses atomic pointer switching to ensure that subsequent queries read the updated cache, while queries that have already obtained a reference from the original cache continue to use the original cache to complete compilation. This approach avoids interrupting currently executing requests by updating the ontology configuration and ensures that the semantic configuration remains consistent within a single query.

[0028] During ontology loading, the OWL / RDF ontology loading and projection module reads the entities, relations, dimensions, metrics, filters, row-level security rules, and global configurations contained in the ontology file, and creates a set to be projected for each type of content. The module first checks whether the ontology content can be parsed into semantic objects and object relations. If it can be parsed, it is sent to the corresponding set to be projected according to the object category. If it cannot be parsed, it does not enter the index and cache compilation. The output of this step is still ontology semantic objects, and SQL table names, SQL clauses, or user query results are not directly generated yet.

[0029] When performing entity projection, the module reads the business objects in the ontology and their corresponding database table mappings, using the canonical identifiers of the business objects as the identification items for the entity definition and the database table mappings as the physical location items for the entity definition. When performing relation projection, the module reads the entities and foreign key connections at both ends of the relation, writes both ends of the relation into the relation definition, and saves the connection relationships required to generate a JOIN from one entity to the other. When performing dimension projection, the module reads the canonical identifiers of the dimensions, the fields that can be used for grouping or filtering, and their respective entities, and writes this content into the dimension definition. When performing metric projection, the module reads the canonical identifiers of the metrics, the fact tables to which they belong, and the aggregation calculation expressions, and writes this content into the metric definition. Through the above corresponding writes, M2 can subsequently obtain the main entity from the metric definition, M4 can obtain the connection path and DimBinding from the relation definition and dimension definition, and M5 can obtain the content required for the SQL clause from the metric definition and filter definition.

[0030] During filter projection, the module writes the ontology content that generates filter conditions into the filter definition and maintains a reference relationship between the filter definition and the corresponding dimension or entity. During row-level security rule projection, the module writes user roles and the applicable data range restrictions for those roles into the row-level security rule definition, enabling M3 to check the explicit filtering range of users and M5 to obtain the permission conditions that require unconditional injection. During global configuration projection, the module saves the configuration content that is read by all stages of query compilation. After projection is completed, the module forms OntologyConfig according to the fixed composition of entity definition, relationship definition, dimension definition, indicator definition, filter definition, row-level security rule definition, and global configuration definition. Any subsequent module reads the corresponding definition with the same name.

[0031] The input for constructing the synonym index is the canonical identifiers and their Chinese synonyms for entities, metrics, dimensions, and filters in OntologyConfig. During construction, the index and cache compilation modules read each Chinese expression corresponding to the same canonical object item by item, using the Chinese expression as the search entry point and the canonical identifier as the search result to form index terms. When the same canonical object has multiple Chinese expressions, multiple index terms pointing to the same canonical identifier are formed. The index terms also retain the length order of the Chinese expressions, allowing M1 to match longer expressions first and then shorter expressions. If the Chinese query does not hit an index term, M1 does not generate a canonical identifier on its own, and the unmatched objects are handled by M2 and M3 according to the whitelist and ontology consistency constraints.

[0032] The input for constructing the query constraint whitelist is the entity definition, metric definition, dimension definition, and filter definition in OntologyConfig. The index and cache compilation modules read the canonical identifiers of each definition and write them into the allowed identification set. After M2 obtains the candidate identifiers, it compares each candidate identifier with the allowed identification set. Only candidate identifiers that exist in the set can be written into QueryPlan. The whitelist is used to restrict the source of SQL structure objects. Its comparison object is the canonical identifier. It does not replace the canonical identifier with the user's original text, nor does it write business filter values ​​into the whitelist.

[0033] The input for constructing the metric-dimension compatibility matrix is ​​the metric and dimension combination relationship recorded in OntologyConfig. During construction, the indexing and caching compilation module determines the metric position in the matrix using the metric specification identifier and the dimension position using the dimension specification identifier. Then, it writes the ontology's allowed aggregation relationship for the metric according to that dimension into the corresponding position. Combinations not recorded as compatible are not allowed by M3 as available combinations. When M3 uses the matrix, it locates the corresponding position and reads the compatibility status based on the metric specification identifier and grouping dimension specification identifier in QueryPlan. This status directly determines the pass / fail result of the metric-dimension compatibility check. The matrix only expresses the combination relationship already recorded in the ontology and does not change automatically based on the current query frequency or execution result.

[0034] The entity relationship graph is built based on the entity and relationship definitions in OntologyConfig. The module creates a graph node for each entity definition and an edge connecting the corresponding entity node for each foreign key connection, associating the connection field, JOIN type, and cardinality information of the relationship in the edge. The entity relationship graph does not add edges not defined in the ontology. When a relationship definition is updated, the indexing and caching compilation module reconstructs the entity relationship graph, indexes, and matrices corresponding to the updated OntologyConfig in the inactive cache. Only after all content forms a complete cached version is the atomic pointer switch performed.

[0035] SystemCache's double-buffering process includes preparing the active cache and updating the cache. When a query request begins compilation, it obtains a reference to the current active cache and continues to use this reference throughout the M1 to M5 stages of the request. When the ontology configuration is refreshed, the index and cache compilation modules write new OntologyConfig, synonym indexes, query constraint whitelists, metric dimension compatibility matrices, and entity relationship graphs into the update cache. After confirming that these contents belong to the same update result, the active pointer is switched from the original active cache to the update cache. Requests that have already obtained a reference to the original active cache before the switch continue to use the original version, while requests starting after the switch obtain the updated version. This avoids a situation where a QueryPlan is built based on one version while the connection path is deduced based on another version.

[0036] After the OntologyConfig is generated, the loading and projection module checks the reference relationships between various definitions according to the subsequent query responsibilities. For indicator definitions, it checks whether the fact table to which it belongs can be found in the entity definition; for dimension definitions, it checks whether the entity pointed to by its physical field binding can be found in the entity definition; for relationship definitions, it checks whether the entities at both ends of the relationship exist and whether the relationship has the foreign key join content required to form a table join; for filter definitions, it checks whether its filter objects can correspond to entities or dimensions; for row-level security rule definitions, it checks whether the user roles and permission scope objects corresponding to the rules can be read by subsequent permission verification and filter condition generation. OntologyConfig that passes the check enters the indexing and caching compilation. Configurations with missing references are not switched to the active version as a complete cache version. This check only confirms that objects within the ontology can reference each other and does not replace the consistency check performed by M3 for a single QueryPlan.

[0037] When constructing the metric-dimensional compatibility matrix, each matrix position represents only a specific combination state of metric dimensions. The indexing and caching compilation module reads the metric definitions sequentially, using the current metric as the metric to be processed, and then reads the dimension definitions sequentially, using the current dimension as the dimension to be processed. The module checks whether the OntologyConfig records whether the metric to be processed is allowed to be aggregated according to the dimension to be processed. If the allowed relationship is recorded, the corresponding position is written as compatible; if the allowed relationship is not recorded, the corresponding position is kept as incompatible. After all metrics and dimensions are processed, a compatibility matrix covering the metrics and dimensions contained in the current OntologyConfig is obtained. When a new metric or dimension is added, the updated cached matrix is ​​reconstructed with the updated OntologyConfig, without appending an isolated position that cannot be matched with other objects to the old matrix.

[0038] The synonym index, whitelist, compatibility matrix, and entity relationship graph are connected by the same specification identifier. After the synonym index outputs the specification identifier, the whitelist uses this identifier to confirm the object category and allowed status. M2 writes the same specification identifier into QueryPlan, and M3 then uses this identifier to query the compatibility matrix or OntologyConfig. M4 locates the entity relationship graph node based on the main entity identifier in QueryPlan and locates the DimBinding based on the dimension identifier. M5 reads the corresponding physical mapping based on the metric, dimension, and entity identifier. Since different internal names are not repeatedly generated for the same object at each stage, changes in Chinese expression only affect the index hit entry of M1 and do not change the subsequent mapping of ontology objects and database table fields.

[0039] The query request reception and M1 preprocessing specifically include: In step S4, the compilation system receives a Chinese natural language query and simultaneously obtains user context information and the request time. The user context information includes at least the user identifier, user role, permitted production line range, and permitted factory range; the request time is used to determine the actual time range corresponding to relative time expressions such as today, yesterday, and this week. The Chinese natural language query, user context information, and request time serve as input to the same compilation request, and subsequent validation and SQL generation are all linked to this user context.

[0040] In step S5, the M1 preprocessing unit first performs synonym normalization. The preprocessing unit searches for synonym index items in the Chinese natural language query and converts the matched business expressions into corresponding standard identifiers. When long words and short words may be matched at the same time, the preprocessing unit processes the longer expressions first according to the long word priority strategy to avoid short words matching substrings within long words and causing erroneous replacements. After synonym normalization, the expressions of production lines or production lines used by different business personnel have the same standard identifier when entering the subsequent stages.

[0041] The M1 preprocessing unit continues to parse relative time. It identifies expressions such as today, yesterday, this week, last week, this month, last month, and recent days, and generates standard start and end dates and time granularity based on the requested time obtained in step S4. For the yield of each process in the recent days, the preprocessing unit obtains the number of days information from the user's expression and gets the corresponding start date, end date, and time granularity used in the query. The preprocessing unit then cleans up text that does not participate in the query semantics, obtaining normalized query text.

[0042] If the preprocessing unit identifies a time expression that the system does not yet support, such as tomorrow, next week, or last year, the abnormal path will prevent subsequent QueryPlans from including undefined time conditions, thus avoiding the continued entry of incorrect time ranges into SQL generation.

[0043] The specific process of synonym normalization is as follows: The M1 preprocessing unit obtains the synonym index of the Chinese natural language query and the current cached version, and checks the query text in descending order of the Chinese expressions corresponding to the index entries; when a longer expression is matched at the current position, the complete expression is replaced with the corresponding standard identifier, and the position is marked as processed, and subsequent shorter expressions will not be replaced at the processed position again; when no index entry is matched at the current position, the original text at that position is retained for subsequent cleaning or candidate recognition. The input of this process is the original Chinese natural language query, and the output is the query text after term normalization. The standard identifiers in the output can all be traced back to the synonym index.

[0044] The input for relative time parsing is the query text after terminology normalization and the request time. M1 first identifies supported expressions in the query text that belong to today, yesterday, this week, last week, this month, last month, or several recent days. Then, it determines the time interval boundary corresponding to the expression based on the request time, and simultaneously determines the time granularity required for subsequent grouping and validation. The start boundary, end boundary, and time granularity together constitute the time parsing result. M1 only writes the boundary results into the intermediate structure required by the subsequent filtering conditions, and does not directly concatenate the actual dates into SQL text during the preprocessing stage.

[0045] For the expression "recent days", the number of days comes from the time expression in the user query. M1 uses the request time as the end reference, determines the starting boundary forward according to this number, and retains the time granularity corresponding to this time range. For today, yesterday, this week, last week, this month, and last month, M1 determines the corresponding boundary based on the day, week, or month in which the request time is located. The boundary expression of the time interval is provided by the global configuration and is consistent with the boundary expression used by the database time field.

[0046] Text cleaning follows synonym normalization and relative time parsing. M1 retains the normalized entities, metrics, dimensions, filtered objects, and time parsing results, and cleans the text that does not participate in query semantic recognition to obtain normalized query text for M2 to read. Cleaning must not delete the already identified normalized identifiers, nor change the start boundary, end boundary, or granularity of the time interval. If the cleaned text cannot retain the candidate objects required to form the query, M2 will return the corresponding error through QueryPlan integrity processing, while M1 will not create new metrics or dimensions.

[0047] When the query text contains time expressions such as "tomorrow," "next week," or "last year," which are not currently supported, M1 writes the matched time segment and the unsupported status into the preprocessing result, terminates the current preprocessing output, and returns a preprocessing error. When the query text does not contain relative time expressions, M1 does not generate a relative time range, and M2 subsequently forms a QueryPlan based only on other specification objects. Thus, relative time parsing has supported paths, unsupported paths, and paths without relative time, and all three types of paths have explicit outputs.

[0048] M2 query plan parsing specifically includes: In step S6, the M2 query plan parsing unit receives the normalized query text obtained in step S5 and reads the OntologyConfig, the thesaurus index, and the query constraint whitelist. The parsing unit identifies candidate semantic identifiers of entities, metrics, dimensions, and filtering conditions from the normalized query text. After applying whitelist constraints to the candidate identifiers, the candidate items that pass the constraints are written into the QueryPlan. The QueryPlan also records the aggregation method and the number of query limits, so that subsequent stages no longer directly interpret the original Chinese text.

[0049] The M2 query plan parsing unit determines the primary entity based on the indicator definition. The indicator definition records the fact table to which the indicator belongs. When the normalized query text contains indicators such as yield, the parsing unit reads the indicator definition and determines the corresponding production capacity fact table or quality fact table as the primary entity. The filtering conditions and grouping dimensions retain their normalized semantic identifiers, which are used by M3 to check compatibility and by M4 to parse DimBinding. The primary entity is routed by the indicator definition, so that the selection of the primary table has an ontological basis.

[0050] When a single request contains multiple metrics, the M2 query plan parsing unit reads the fact table to which each metric belongs. If multiple metrics belong to different fact tables, the parsing unit returns a parsing error to indicate a split query and does not generate a QueryPlan containing multiple semantically ambiguous main entities. This process avoids forcibly establishing connections for metrics in different fact tables in subsequent stages.

[0051] M2 query plan parsing can be implemented by a rule parser, a constrained large language model parser, or a combination of both. When any implementation is used, the output is a QueryPlan with the aforementioned fixed structure, and this QueryPlan must undergo M3 validation. Therefore, the parser is only responsible for generating candidate structures and cannot bypass ontology constraints, permission checks, and security checks before SQL generation.

[0052] During candidate identification, M2 first reads the normative identifiers already written by M1 from the normalized query text, and then classifies the normative identifiers into entity candidate sets, indicator candidate sets, dimension candidate sets, and filter condition candidate sets according to the query constraint whitelist. The category of the candidate is determined by the corresponding definition in OntologyConfig, and the category of the same normative identifier does not change due to changes in user expression. For time parsing results, M2 writes the start boundary, end boundary, and time granularity into the filter conditions; for dimension candidates used for expression by a certain dimension, M2 writes them into the grouping dimension; for business object values, M2 saves them as filter values ​​and does not use them as SQL field names.

[0053] The input to the main entity routing is the set of candidate metrics and the metric definitions in OntologyConfig. M2 reads the fact table to which each candidate metric belongs. If a candidate metric belongs to only one fact table, the entity corresponding to that fact table is written into the main entity of QueryPlan. If multiple candidate metric ...

[0054] The aggregation method comes from the aggregation calculation expression recorded in the indicator definition. M2 writes the indicator specification identifier and its aggregation method into the indicator list, enabling M5 to form a SELECT field. The number of query limits is written into the query limit position in QueryPlan, so that M5 can form a LIMIT clause. M2 saves the query limit information provided by the query request or global configuration. If the query limit information is not obtained, the query limit position is marked as empty, and M5 does not generate a LIMIT clause.

[0055] In the rule-based parser implementation, M2 identifies candidates and fills in fixed fields according to the synonym index, whitelist, and OntologyConfig definition. In the constrained large language model parser implementation, the parser receives normalized query text and output requirements restricted by the ontology candidate set, and can only output QueryPlan candidates with fixed structures. In the combined implementation, one parser generates candidates, and another parser supplements the structure within the same candidate constraints. Regardless of the method used, M2's output does not have the authority to directly generate SQL; each object in the QueryPlan still needs to be verified item by item by M3.

[0056] Each field in the QueryPlan has a definite source. The main entity field originates from the fact table to which the metric belongs in the metric definition; the standardized metric identifier in the metric list originates from the M1 normalization result and whitelist confirmation result, and the aggregation method originates from the corresponding metric definition; the filter object in the filter conditions originates from the standardized query text recognition result, the filter value originates from the user query, and the time start and end boundaries and time granularity originate from the M1 time parsing result; the grouping dimension originates from the dimension candidate and whitelist confirmation result in the standardized query text; and the query restriction information originates from the query request or global configuration. When M2 forms the QueryPlan, it also saves the correspondence between the above objects to avoid M3 or M5 re-extracting metrics, dimensions, or filter values ​​from the original Chinese query.

[0057] When multiple candidates of the same type exist in a normalized query text, M2 retains the normalized identifier of each candidate and writes them according to the structure of the corresponding fields in QueryPlan. For multiple indicator candidates, the corresponding fact table is read item by item and a main entity consistency comparison is performed. Multiple filter values ​​are grouped according to the same filter object, and multiple grouping dimensions are formed into dimensions to be verified. M2 does not delete candidates based on unrecorded probability scores, nor does it write candidates that have not passed the whitelist into QueryPlan. When there are semantic conflicts in the candidate structure, M2 outputs a parsing error and only passes it to M3 when a fixed structure can be formed.

[0058] When M2 uses a constrained large language model parser, the ontology candidate set constitutes the boundary of the objects that the parser can output. The parsing result still needs to be converted into a fixed structure containing the main entity, indicator list, filtering conditions, grouping dimensions, aggregation methods, and query restriction information. During the conversion, the object names output by the parser are first compared with the candidate set and whitelist. Content that cannot be mapped to the specification identifier is not considered a valid QueryPlan object. When M2 uses a rule parser, the synonym index hit results and time parsing results are directly entered into the corresponding fields. When the two are combined, any candidate supplemented by either side also accepts the same object boundary. Therefore, the large language model only serves as the recorded candidate parsing implementation and does not gain the ability to modify OntologyConfig or skip M3.

[0059] M3 check and failure short circuit specifically include: In step S7, the M3 verification unit receives the QueryPlan and sequentially performs basic integrity verification, ontology consistency verification, indicator dimension compatibility verification, entity reachability verification, time granularity legality verification, role and permission verification, and anti-injection verification. M3 is located after query plan parsing and before JOIN derivation and SQL generation. Only QueryPlans that pass all verifications are passed to M4.

[0060] The basic integrity check verifies whether the QueryPlan contains the main entity, metrics, dimensions, or other necessary content required for this query; the ontology consistency check compares the entities, metrics, dimensions, and filters in the QueryPlan with the OntologyConfig, and objects not defined in the OntologyConfig are not included in the subsequent compilation; the metric and dimension compatibility check uses a metric and dimension compatibility matrix to check whether the selected metrics can be aggregated according to the specified grouping dimensions; through these three checks, structural missing items, unknown semantic objects, and metric and dimension combinations not allowed by the ontology can be excluded before generating SQL.

[0061] Entity reachability checks the entity relationships in OntologyConfig to see if a connection path exists between the main entity and the target entity required for the query. Time granularity validity checks whether the grouping dimension supports the time granularity obtained from M1 parsing. Role-based access control compares the explicitly specified production line or factory filter conditions with the allowed access range in the user's context information; if the explicit filter conditions exceed the allowed access range, the access control fails. These checks respectively constrain table join probability, time grouping relationships, and the range of data accessible to the user.

[0062] The injection prevention check verifies whether SQL identifiers such as entity names, metric names, and dimension names conform to secure naming rules and excludes SQL keywords. Business filter values ​​are not concatenated as SQL identifiers but are converted into named parameters in the M5 stage; therefore, M3 performs whitelist and naming rule checks on the source of identifiers, and M5 performs parameter binding on values. The two-level processing constrains the SQL structure part and the SQL value part respectively.

[0063] In step S7-1, if any verification fails, the M3 verification unit immediately terminates the current request, stops executing the M4 JOIN derivation and M5 SQL generation, and outputs error messages such as unknown metrics, unknown dimensions, incompatible metrics and dimensions, unreachable entities, insufficient permissions, or illegal identifiers based on the reason for failure. The failure short-circuit retains the specific failure type, enabling business or maintenance personnel to locate the check items that failed the QueryPlan, while preventing queries that have already been determined to be non-compliant from continuing to generate SQL text.

[0064] The input for basic integrity verification is QueryPlan. M3 reads the main entity, indicator list, filter conditions, and grouping dimensions, and checks for any missing information according to the current query requirements. Integrity verification fails when the query requires indicators but the indicator list is empty, or when indicators have been identified but the main entity cannot be determined by the indicator definition. Integrity verification only determines whether the structure has the content required for subsequent compilation, without modifying QueryPlan or replacing missing indicators with default indicators.

[0065] The input for ontology consistency verification is the QueryPlan and OntologyConfig that have passed the integrity check. M3 retrieves the entity identifier, indicator identifier, dimension identifier, and filter identifier from the QueryPlan and performs a member lookup in the corresponding definition set of OntologyConfig. The ontology consistency verification passes when all identifiers can be found in the definition set of the same type; otherwise, an unknown object error corresponding to the object category is returned. By using type-based lookup, it can prevent a dimension identifier existing in the ontology from being mistakenly used as an indicator identifier.

[0066] The indicator dimension compatibility check forms a combination to be checked for each indicator and each group dimension in the QueryPlan. M3 uses indicator specification identifiers to determine the indicator positions in the compatibility matrix and dimension specification identifiers to determine the dimension positions, and reads the compatibility status of the intersection positions. If all combinations to be checked are in a compatible state, the check is allowed; if there are incompatible combinations, an indicator dimension incompatibility error is returned. If the QueryPlan has no group dimensions, no combination of indicators and group dimensions is generated, and this check does not fabricate a group dimension based on this.

[0067] The entity reachability check first determines the target entities that the query may involve based on the DimBinding of the grouping and filtering dimensions. Then, taking the main entity of QueryPlan as the starting point, it checks whether there are paths to each target entity in the entity relationship graph. If any required target entity is unreachable, an entity unreachable error is returned. This stage only determines whether a path exists and does not make a final selection among multiple paths. The search, scoring and sorting of candidate paths are performed by M4, thereby avoiding the confusion between reachability judgment and optimal path selection.

[0068] The time granularity validity check reads the time granularity written into the filter conditions in M1 and the grouping dimension in the QueryPlan, and checks whether the grouping dimension supports the current time granularity. If it supports it, the check passes; otherwise, a time granularity error is returned. If the user does not specify a time group and the QueryPlan does not contain the time grouping dimension that needs to be checked, M3 does not add an additional time dimension. The role permission check reads the allowed access production line range and allowed access factory range from the user's context information, and then reads the corresponding range from the explicit filter conditions in the QueryPlan. If all explicit ranges are within the allowed range, the check passes; if any explicit value exceeds the allowed range, an insufficient permission error is returned.

[0069] The injection prevention check treats entity names, metric names, and dimension names in the QueryPlan as structure identifiers. It first confirms that each identifier comes from the whitelist and OntologyConfig, then checks whether it conforms to secure naming rules and excludes SQL keywords. Business filter values ​​are not included in the structure identifier concatenation; their security processing is handled by M5's naming parameter conversion. If an identifier contains content that does not conform to the naming rules or hits an SQL keyword, M3 returns an illegal identifier error and does not pass that content to the SELECT, FROM, JOIN, or GROUP BY clauses.

[0070] Each validation result is represented as either a pass status or a failure status. M3 retrieves the current check result in the validation order. If the current result is pass, it proceeds to the next item. If the current result is fail, it immediately stops the remaining validations and processing by M4 and M5, and outputs error messages that indicate the failed object or failure category. The error messages explain why the request did not enter the SQL generation process and do not contain a substitute SQL. The failure short route QueryPlan status is controlled and cannot be ignored by the upper layer and M5 is not allowed to continue to be called.

[0071] M3 uses the same QueryPlan and SystemCache version when performing various checks. After the basic integrity check passes, the ontology consistency check confirms the existence of the object; the metric dimension compatibility check confirms the combination relationship between the metric and the grouping dimension; the entity reachability check confirms the existence of an ontology relationship path between the main entity and the target entity; the time granularity check confirms the compatibility of the time expression with the grouping dimension; the role and permission check confirms that the explicit scope of the user does not exceed the scope contained in the user context; and the anti-injection check confirms the source and naming security of the structure identifier. The passing result of the previous check only serves as a condition for entering the next check, and does not rewrite the result of the previous check as the conclusion of the next check. Only after all checks pass does M3 generate a verification passed status that can be read by M4.

[0072] In role-based access control, the scope comparison is performed separately for each filtered object. When explicit production line filtering conditions exist, M3 retrieves the requested production line value item by item and searches within the allowed production line range in the user's context. When explicit factory filtering conditions exist, M3 retrieves the requested factory value item by item and searches within the allowed factory range. If all explicit values ​​can be found within their corresponding allowed ranges, the scope check passes; otherwise, an insufficient permission error is returned. If the user does not explicitly specify a range, M3 does not relinquish security control, and M5 still generates the necessary filtering conditions according to the row-level security rules corresponding to the non-privileged role.

[0073] Interpretable error messages are formed by the failed validation type and the corresponding object. When an indicator is missing in the ontology, the error message is associated with an unknown indicator type and its candidate identifiers; when a dimension is missing in the ontology, the error message is associated with an unknown dimension type; when the compatibility matrix does not allow the selected combination, the error message is associated with an incompatible indicator / dimension type, as well as the corresponding indicator and dimension; when there is no reachable path in the relationship graph, the error message is associated with an unreachable entity type, as well as the main entity and the target entity; when the user scope is out of bounds, the error message is associated with insufficient permissions; when a structure identifier fails a security check, the error message is associated with an illegal identifier type. Error messages describe the location of the failure and do not contain business data returned by the database.

[0074] In step S8, after all M3 checks pass, the M4 JOIN derivation unit reads the main entity, grouping dimension, and filtering dimension from the QueryPlan, and determines the target entities required for the query accordingly. The derivation unit constructs an entity relationship graph using entities in OntologyConfig as nodes and foreign key connections between entities as edges, and then searches for candidate connection paths for each target entity starting from the main entity.

[0075] In one implementation, M4 uses a breadth-first search to obtain candidate join paths; in a documented alternative, M4 may also use Dijkstra's path search or pre-compute the shortest path. Regardless of the search method used, candidate paths consist of defined relations in the ontology graph and cannot use table join relations not documented in the ontology.

[0076] M4 parses DimBindings for grouping and filtering dimensions. If the fact table corresponding to the current main entity already directly stores the dimension field, the DimBinding points to the fact table field, and M4 does not generate an additional JOIN for that dimension. If the dimension field is located in another dimension table, the DimBinding points to the corresponding dimension table and field, and M4 generates corresponding candidate JOIN clauses based on the foreign key join relationships in the ontology relation. This process ensures that the same semantic dimension can select the correct physical binding according to the current fact table.

[0077] When multiple candidate join paths exist, M4 determines the path score based on path length cost, relation cardinality cost, JOIN type cost, and data inflation risk cost. Specifically, it obtains the path length cost corresponding to the number of relations included in the candidate path, the relation cardinality cost corresponding to each relation cardinality, the JOIN type cost corresponding to the JOIN type used in the candidate path, and the data inflation risk cost. The data inflation risk is represented by the ratio between the expected number of records after the join and the original number of records in the fact table. Then, the four types of costs are multiplied by their corresponding weight parameters, and the results are summed to obtain the score for the candidate path.

[0078] M4 sorts candidate paths according to their scores, prioritizing shorter paths with lower row bloat risk. When the score difference among multiple candidate paths is less than a configured threshold, M4 performs a secondary sort: first comparing path lengths and prioritizing shorter paths; then comparing relation cardinality risk and prioritizing lower-risk paths; subsequently comparing whether they belong to a predefined primary join relation and prioritizing predefined primary join relations. If a path still cannot be determined after the above steps, M4 returns multiple candidate paths to the upper layer. This fallback approach avoids unjustifiably selecting a JOIN result when candidate conditions are similar.

[0079] When using breadth-first search, M4 establishes a sequence of entities to be visited and a set of visited entities. The main entity is written into the sequence of entities to be visited as the starting entity, and the starting path without relational edges is recorded. Each time, an entity is taken from the sequence of entities to be visited, and all relational edges connected to that entity in the entity relation graph are read. For unvisited adjacent entities, a new path is created by continuing the relational edge from the current path. If the adjacent entity is the target entity, the new path is written into the candidate path set; if the adjacent entity is not the target entity, the adjacent entity and the new path are written into the sequence of entities to be visited. The search ends when the sequence of entities to be visited is empty or when a candidate path satisfying the subsequent selection requirements has been obtained. During the search process, only the graph edges corresponding to the OntologyConfig relation definitions are expanded.

[0080] When using Dijkstra's path search, M4 establishes the initial cumulative cost for the main entity and selects the entity with the smaller current cumulative cost from the undetermined entities. It then reads the path cost of the connecting edges of that entity and adds the current cumulative cost to the edge cost to obtain the candidate cumulative cost to reach the adjacent entity. If the candidate cumulative cost is less than the existing cumulative cost of the adjacent entity, the cumulative cost of the adjacent entity and its predecessor relationship are updated until the path to the target entity is determined or no further accessible entity exists. When using pre-computed shortest paths, the system forms a correspondence between entity pairs and candidate shortest paths based on the entity relationship graph during the ontology configuration and compilation phase. M4 searches for this result based on the main entity and the target entity; if the result is not found, it returns an entity unreachable status. The input and output of the above alternative search methods are consistent with breadth-first search.

[0081] DimBinding parsing takes the current main entity and the target dimension as input. M4 first reads the field bindings in the target dimension definition that correspond to the current main entity. If there is a direct binding in the fact table, the fact table field is used as the dimension's physical field and marked as not requiring a join. M5 then directly uses this field to generate SELECT, WHERE, or GROUP BY statements. If there is no direct binding in the fact table but there is a binding in the dimension table, the dimension table is identified as the target entity, and the dimension table field is used as the physical field. Subsequently, candidate paths from the main entity to that dimension table are searched. If the same semantic dimension corresponds to different fields in different fact tables, M4 always uses the current main entity in the QueryPlan as the condition for selecting DimBinding.

[0082] The path length cost characterizes the number of relation edges contained in the candidate path. M4 determines this cost based on the relation edges traversed sequentially in the candidate path. The relation cardinality cost characterizes the cardinality risk of entity relations in the path. M4 reads the cardinality information recorded in each relation definition and forms this cost. The JOIN type cost distinguishes the connection type used by the candidate path. M4 reads the JOIN type recorded in each relation definition and forms this cost. The data inflation risk cost characterizes the degree of increase in the number of records after the connection relative to the original number of records in the fact table. M4 obtains the expected number of records after the connection corresponding to the candidate path to be evaluated and the original number of records in the current fact table, and forms the data inflation risk by the ratio of the former to the latter.

[0083] The path scoring is calculated as follows: first, obtain the path length cost, relation cardinality cost, JOIN type cost, and data inflation risk cost; then, obtain the weight parameters corresponding to each of the four cost types; multiply each cost type by its corresponding weight to obtain its weighted cost; finally, sum the weighted costs to obtain the total score for the candidate path. The weight parameters are derived from the ontology configuration or global configuration, and all candidate paths use the same set of weights in the same selection process.

[0084] In the data inflation risk calculation, the original number of fact table records is the expected number of records in the fact table corresponding to the current QueryPlan main entity before the join, and the expected number of records after the join is the expected number of records after the join is completed according to the candidate path. The ratio representing the relative inflation degree is obtained by dividing the aforementioned expected number of records after the join by the aforementioned original number of fact table records. When the original number of fact table records cannot be used as a valid divisor, the system does not independently determine the path based on this ratio, but processes it according to the available path length, relation cardinality, JOIN type, and secondary sorting rules, or returns candidate paths for the upper layer to choose from; this boundary handling avoids unexplainable risk results when there is no valid divisor.

[0085] When ranking candidate paths, M4 compares the total scores of each candidate path and determines their order. If the score difference is not less than a configured threshold, the priority path is determined according to the total score order. If the score difference is less than the configured threshold, M4 first compares the number of relation edges contained in the candidate paths, prioritizing paths with fewer relation edges. Then, it compares the relation cardinality risk, prioritizing paths with lower risk. Subsequently, it checks whether the candidate paths contain predefined primary join relationships in the ontology, prioritizing those that meet the primary join relationship criteria. If the comparisons are still identical or the path cannot be determined, M4 outputs multiple candidate paths and their corresponding relationships, selecting one of them without a clear basis.

[0086] Candidate paths are represented as ordered sequences of relations, starting with the QueryPlan main entity. Each relation in the sequence uses the entity reached by the previous relation as the starting entity for the next relation, and ends at the target entity. When generating JOIN clauses, M4 reads the relation definitions in this order, ensuring that each entity to be joined can be accessed through previously encountered entities and foreign key fields. If adjacent relations in a candidate path cannot be connected end-to-end, the relation sequence cannot form a valid JOIN path. If a path contains relations outside the ontology relation graph, M4 does not add it to the candidate path set. When a query requires multiple target entities, M4 obtains the candidate relation sequences from the main entity to each target entity separately, avoiding unnecessary duplicate joins due to the same used relations.

[0087] Relation cardinality cost and data inflation risk cost serve different purposes. The relation cardinality cost is read from the ontology relation definition and reflects the cardinality risk of the entity relations traversed by the candidate path. The data inflation risk cost is formed based on the ratio of the expected number of records after the join to the original number of records in the fact table and reflects the potential record growth that may occur after the candidate path is applied to the current fact table. M4 first obtains the two types of costs separately, and then multiplies them by their respective weights, without directly replacing one cost with the other. The path length cost and JOIN type cost are also retained separately, so that the total score can simultaneously correspond to the four inputs: the number of path relations, relation cardinality, join type, and record inflation.

[0088] After path scoring is completed, M4 retains the path identifier, relation sequence, four types of costs, total score, and information required for secondary ranking for each candidate path. If the total score can determine the order, the candidate path with the highest priority in the scoring ranking is selected. If the difference between multiple total scores is less than a configured threshold, the relation sequence length, relation cardinality risk, and predefined primary join relation status are read sequentially for comparison. If a unique result still cannot be obtained, multiple candidate paths retaining the above information are output to the upper layer. After the upper layer completes the selection, the selected path is passed to M5 as the output of M4. No final JOIN clause is generated if no selection is completed.

[0089] M5 parameterized SQL generation and row-level secure injection specifically include: In step S9, the M5 SQL generation unit receives the JOIN clauses output by QueryPlan and M4. The generation unit generates SELECT fields based on the indicator list and grouping dimensions, generates a FROM main table based on the main entity, appends the JOIN clauses output by M4 to the FROM main table, generates WHERE conditions based on filtering conditions, generates GROUP BY clauses based on grouping dimensions, and generates LIMIT limits based on the number of rows to be bound. All clauses are combined according to the SQL query structure to form the SQL text containing the parameters to be bound.

[0090] For time-based filtering conditions, M5 writes the start and end dates into the named parameter dictionary separately, and retains the corresponding start and end date named parameters in the WHERE clause. For conditions with multiple filter values, such as production lines, M5 generates distinguishable named parameters for each filter value, for example, forming production line filter parameters in sequence, and writes the actual production line values ​​into the named parameter dictionary. After the database execution engine obtains the SQL text, it binds the values ​​through the named parameter dictionary; the user-inputted business filter values ​​are not directly concatenated into the SQL text.

[0091] M5 simultaneously reads user roles and row-level security rules from the user context information. For non-privileged roles, M5 unconditionally adds the corresponding row-level security rule to the WHERE clause. When a row-level security rule contains placeholders for a list of permissions allowing access to the production line or factory, M5 expands the permission list into a named parameter IN condition and writes each permission value to a named parameter dictionary. This permission condition, along with the user's explicit filtering conditions, resides in the filtering section of the final SQL, avoiding the need to append permission conditions via an outer string after the SQL is generated.

[0092] If the permission list corresponding to a non-privileged role is empty, M5 generates a constant false condition in the WHERE clause, does not generate an empty permission IN list, and does not omit row-level security conditions; the database will not return business data when executing this SQL. This boundary handling, together with the parameter expansion of the non-empty permission list, covers the permission status of the non-privileged role, ensuring that empty permissions are not misinterpreted as unrestricted access.

[0093] In step S10, the compilation system outputs parameterized SQL, a named parameter dictionary, an SQL hash value, and a QueryShape. The parameterized SQL and named parameter dictionary are used for database execution; the SQL hash value is used for audit tracing, query cache hits, and problem localization; the QueryShape records the query pattern for a specific metric grouped by a specific dimension. The compilation system can also retain the JOIN paths selected by QueryPlan and M4, thereby enabling the tracking of the metrics, main entities, dimensions, join paths, and permission conditions used in the final SQL.

[0094] The SELECT field generation takes the indicator list and grouping dimensions from the QueryPlan as input. M5 reads the aggregation calculation expression from the indicator definition and writes the corresponding selection content into the SELECT clause. When the QueryPlan includes grouping dimensions, M5 reads the DimBinding determined by M4 and writes the corresponding physical fields into the SELECT clause. The FROM main table generation takes the QueryPlan main entity as input. M5 reads the database table mapping from the entity definition and writes it into the FROM clause. The JOIN clause is not re-searched by M5, but is directly generated according to the path order using the relationship path and join fields already determined by M4.

[0095] The WHERE condition generation takes the filter conditions in QueryPlan, the time range generated by M1, and user context information as input. For each business filter condition, M5 reads the filter definition to determine the corresponding physical fields and comparison relationships, then creates named parameter names for the filter values, writes the physical fields, comparison relationships, and named parameter placeholders into the SQL text, and writes the corresponding entries of the named parameter names and actual filter values ​​into the named parameter dictionary. When a filter object has multiple values, M5 creates mutually distinguishable named parameters according to the order of the values ​​in the filter object, and combines the named parameters into the conditions of the filter object. This process only changes the way the filter values ​​are carried, and does not change the filter fields and comparison relationships.

[0096] During time parameter conversion, M5 retrieves the start and end boundaries from the time parsing results of M1, establishes distinguishable named parameters for both, and writes the start and end boundaries into the named parameter dictionary respectively; the time filtering part in the SQL text only retains the corresponding named parameter positions. When generating the GROUP BY clause, M5 reads the QueryPlan grouping dimensions and their DimBinding, and writes the physical fields corresponding to the grouping fields in the SELECT into the GROUP BY clause; when generating the LIMIT clause, M5 reads the query restriction information in the QueryPlan and forms a restriction clause, and does not fabricate specific restriction values ​​if restriction information is not obtained.

[0097] The input for row-level security injection is the user role, the row-level security rule corresponding to the user role, the allowed access to the production line range, and the allowed access to the factory range. M5 first looks up the corresponding rule based on the user role. If the user role is a non-privileged role, the rule is determined as a necessary filter condition. If the rule contains a placeholder for the permission list, M5 reads the corresponding allowed access range, establishes mutually distinguishable named parameters for each permission value within the range, assembles the named parameters into an IN condition, and writes each permission value into a named parameter dictionary. If the allowed access range is empty, M5 writes a constant false condition, does not generate an empty IN condition without parameters, and does not delete the permission filter.

[0098] When both explicit user filtering conditions and row-level security conditions exist, M5 generates two types of conditions separately, and then writes them into the WHERE clause with a logical relationship of simultaneous satisfaction. This ensures that the final result satisfies both the user's requested business scope and the user's role's allowed access range. If the user does not explicitly specify the production line or factory scope, row-level security conditions for non-privileged roles are still generated. M3 has already performed pre-validation to check whether the explicit scope exceeds privileges, while M5 continues to execute unconditional injection. The two handle request validity checks and final SQL permission constraints respectively, and do not replace each other.

[0099] When combining SQL clauses, M5 retrieves the SELECT, FROM, JOIN, WHERE, GROUPBY, and LIMIT clauses sequentially, writing only the clauses actually needed for the current QueryPlan into the SQL text. All business filter values ​​and permission values ​​are stored in the named parameter dictionary. After combination, M5 checks that the SQL structure objects all originate from the OntologyConfig definition, the join clauses all originate from the M4 output, and that the named parameter placeholders all have corresponding values ​​available in the named parameter dictionary; if any named parameter lacks a corresponding value, the database execution is not committed.

[0100] The input to the SQL hash value is the SQL text generated by M5. The compilation system performs hash processing on this SQL text and outputs a hash result to identify the SQL text. The input to the QueryShape is the metrics and grouping dimensions in the QueryPlan. The system forms a query pattern identifier according to the combination of metrics and grouping dimensions; when there are no grouping dimensions, the QueryShape records the ungrouped query pattern of the corresponding metrics. The SQL hash value is used for audit trails, cache hits, and problem localization, while the QueryShape is used to distinguish the structural types of metrics grouped by different dimensions.

[0101] The named parameter dictionary is a set of correspondences between named parameter names and their actual values. When M5 generates distinguishable names for multiple values ​​of the same filter object, it ensures that each SQL placeholder corresponds to only one value in the dictionary, and that each current query parameter name in the dictionary can be found in the SQL text for its use. Start time, end time, business filter value, allowed access to production line value, and allowed access to factory value use distinguishable parameter names to prevent permission values ​​from overriding business filter values ​​or the value of one filter object from overriding the value of another. Parameter names are used for binding location identification; the actual parameter values ​​retain their business meaning.

[0102] When M5 generates multiple WHERE conditions, it first forms time conditions, explicit filtering conditions for business objects, and row-level security conditions separately, and then combines them according to the logical relationship of simultaneous satisfaction. If there is no time filter, no time condition is generated; if there is no explicit business filter, no corresponding explicit condition is generated. However, row-level security conditions for non-privileged roles are not omitted due to the absence of other conditions. When the permission list is not empty, the number of named parameters in the IN condition corresponds to the number of permission values ​​written to the dictionary; when the permission list is empty, the constant false condition directly occupies the permission condition position, and an IN structure without members is not generated.

[0103] After the parameterized SQL is generated, M5 checks each category to verify that the SELECT and GROUP BY fields originate from the indicator definition and DimBinding, the FROM main table from the main entity definition, the JOIN relationship from the path determined by M4, the WHERE field from the filter definition or row-level security rules, and that named parameters have corresponding dictionary entries. Upon successful verification, the SQL text and named parameter dictionary are output. This verification does not reselect indicators, main entities, or join paths; it only confirms that the preceding structured results have been fully implemented in each clause of the SQL, allowing the SQL structure to be traced step-by-step along QueryPlan, DimBinding, join paths, and OntologyConfig.

[0104] Both the SQL hash and QueryShape are generated after the SQL is generated, but their inputs differ. The SQL hash takes the generated SQL text as input, and after hashing, it yields a result that identifies the SQL structure. The QueryShape takes the metrics and grouping dimensions in the QueryPlan as input, and combines them to form the query pattern. The same query pattern can correspond to a named parameter dictionary containing different business filter values. The actual values ​​of the named parameters are not used to change the combination of metrics and dimensions in the QueryShape. The audit log simultaneously saves the SQL hash, QueryShape, execution time, and user context, enabling the establishment of a correspondence between the query structure, query pattern, and execution entity.

[0105] SQL execution and response specifically include: In step S11, the compilation system submits the parameterized SQL and named parameter dictionary output in step S10 to the database execution engine. The database execution engine builds a query structure according to the SQL text and binds the business filter values ​​and permission values ​​from the named parameter dictionary to each named parameter position. Then, it executes the query on the MES database. Since the business filter values ​​and permission values ​​are passed in as parameters, the input values ​​do not change the already formed SQL structure.

[0106] After the database execution engine returns the query results, the compilation system can encapsulate the results into a structured response such as a table, scalar, or empty result, and retain the SQL hash value, QueryShape, execution time, and user context information as audit information. For requests that have returned errors in stages M1, M2, or M3, the system does not submit SQL execution; for requests that return multiple candidate paths in stage M4, the upper layer obtains the candidate paths and makes a selection, and does not proceed to stage M5 to generate the final SQL before the path is determined.

[0107] Before execution, the compilation system holds both the parameterized SQL and the named parameter dictionary. The database execution engine reads the SQL text, looks up the actual values ​​in the dictionary according to the named parameter names, and binds each value to its corresponding placeholder. After binding, the SQL is executed; the character content of business filter values ​​or permission values ​​is not parsed again as part of the SQL structure. If a named parameter in the parameterized SQL does not have a corresponding entry in the dictionary, or if the necessary permission parameters for the current SQL are missing from the dictionary, the system does not replace permission restrictions with null values, nor does it continue executing the SQL.

[0108] When the query result has multiple rows and columns, the system encapsulates it as a table response; when the query result is a single aggregate result, it can be encapsulated as a scalar response; when the row-level safety condition is a constant false condition or there are no records in the database that meet the filtering conditions, it is encapsulated as an empty result response. All three types of responses can be associated with SQL hash value, QueryShape, execution time, and user context information, so that the execution result can correspond to the query form, user role, and SQL structure that produced the result.

[0109] Taking the user inputting the yield rate of each process in the most recent few days as an example, step S4 obtains the Chinese natural language query, user context information and request time; step S5 normalizes the yield rate into a standardized indicator identifier and the process into a standardized dimension identifier based on the synonym index, and determines the standard start and end dates and corresponding time granularity based on the number of days information carried in the query, thus obtaining the standardized query text.

[0110] Step S6 determines the fact table to which the yield indicator belongs based on the yield indicator definition, writes the fact table into the main entity of QueryPlan, writes the yield into the indicator list, writes the time range corresponding to the aforementioned number of days information into the filter conditions, and writes the process into the grouping dimension; Step S7 checks that the yield, process, and main entity all exist in OntologyConfig, checks that the indicator dimension compatibility matrix allows the yield to be grouped by process, checks that the main entity and the corresponding entity of the process dimension are reachable, and completes the time granularity, role permissions, and identifier checks.

[0111] After successful verification, step S8 parses the DimBinding of the process dimension relative to the current master entity. If the process field is directly located in the fact table, no JOIN is generated for the process. If the process field is located in the process dimension table, candidate paths from the master entity to the process dimension table are searched in the ontology graph, and the JOIN clause is determined according to path scoring and secondary sorting rules. Step S9 generates parameterized SQL containing yield selection fields, master table, necessary JOINs, time range filtering conditions, process grouping conditions, and query restrictions. The time range is written into the start date naming parameters and end date naming parameters, and row-level security conditions are injected according to user roles.

[0112] Step S10 outputs parameterized SQL, a named parameter dictionary, SQL hash values, and a QueryShape representing yield grouped by process. Step S11 executes the query after binding date and permission parameters by the database execution engine and encapsulates the results into a structured response. If the allowed access range in the user context is empty, step S9 changes to writing a constant false condition in the filter conditions, ultimately returning an empty result; if the process dimension and yield index are incompatible in the index dimension compatibility matrix, step S7 directly returns an index dimension incompatibility error, without executing steps S8 to S11.

[0113] The following uses the yield rates of each process over the past few days to illustrate how the intermediate structures are connected, without substituting specific dates or specific indicator values. M1 obtains the standard indicator identifiers corresponding to the yield rates and the standard dimension identifiers corresponding to the processes from the synonym index, and then uses the request time and the expression of the past few days to determine the start boundary, end boundary, and time granularity; M1 retains the above standard identifiers and time parsing results to form a standardized query text.

[0114] M2 retrieves candidate yield metrics and process dimensions from the normalized query text. After confirming the candidate categories in the whitelist, it reads the fact table and aggregation calculation expression from the yield metric definition. M2 writes this fact table into the main entity, writes the yield metric and its aggregation method into the metric list, writes the start and end time boundaries into the filter conditions, and writes the process into the grouping dimension, thus forming the QueryPlan. The main entity in this QueryPlan comes from the metric definition and is not determined by the table containing the process dimension.

[0115] M3 first confirms that the QueryPlan contains the main entity and metrics, then confirms that the yield metric, process dimension, and related filters all exist in the OntologyConfig. Next, it reads the compatibility status of yield and process in the metric dimension compatibility matrix, confirms in the entity relationship graph that the main entity can reach the corresponding entity in the process dimension, and checks the time granularity, user-defined filtering range, and structural identifiers. If all results pass, it outputs a validation pass status; if any result fails, it outputs the corresponding error and stops.

[0116] M4 parses DimBindings using the main entity and process dimension as input. If the process field is directly bound to the fact table corresponding to the main entity, M4 outputs results without needing to create a JOIN for the process. If the process field is bound to the process dimension table, M4 searches for candidate paths from the main entity to the process dimension table in the entity relationship graph, determines the path length cost, relationship cardinality cost, JOIN type cost, and data bloat risk cost for each path, and outputs the connection path after weighted summation and necessary secondary sorting.

[0117] M5 generates SELECT metric content based on the aggregated calculation expression of yield metrics, generates SELECT grouping fields and GROUP BY fields based on process DimBinding, generates FROM content based on the main entity, and generates necessary JOINs based on the M4 results. It then converts the start and end time boundaries into named parameters, converts the user role's corresponding permission range into row-level secure named parameters, and combines the WHERE conditions. M5 outputs parameterized SQL and a named parameter dictionary, and the compilation system then generates SQL hash values ​​and QueryShapes representing yield grouping by process.

[0118] When the user's allowed access range is empty, M5 does not create an empty permission list, but adds a constant false condition to the WHERE condition, and the database returns an empty result after execution; when the indicator dimension compatibility matrix indicates that the yield cannot be grouped according to the process, M3 returns an indicator dimension incompatibility error; when M4 has multiple paths with similar scores that cannot be determined after secondary sorting, M4 returns multiple candidate paths for the upper layer to choose from. These branches respectively cover permission boundaries, semantic incompatibility and multiple path solutions.

[0119] This application also provides a compilation system for converting Chinese natural language to parameterized SQL based on the OWL-RDF ontology. The system includes an OWL / RDF ontology loading and projection module, an indexing and caching compilation module, a query compilation pipeline module, and a security control and SQL output module. Each module can be deployed on a computing device used to access the MES database and transmits OntologyConfig, normalized query text, QueryPlan, JOIN clauses, parameterized SQL, and named parameter dictionaries according to the aforementioned method.

[0120] The OWL / RDF ontology loading and projection module loads the manufacturing domain ontology and converts entities, relations, dimensions, metrics, filters, row-level security rules, and global configurations into OntologyConfig. The indexing and caching compilation module constructs a synonym index, a query constraint whitelist, and a metric / dimension compatibility matrix based on the OntologyConfig, and provides a consistent configuration version to the query compilation pipeline through SystemCache. These two modules correspond to steps S1 to S3.

[0121] The query compilation pipeline module includes an M1 preprocessing unit, an M2 query plan parsing unit, an M3 verification unit, an M4 JOIN derivation unit, and an M5 SQL generation unit. The M1 preprocessing unit corresponds to step S5 and outputs the normalized query text; the M2 query plan parsing unit corresponds to step S6 and outputs the QueryPlan; the M3 verification unit corresponds to step S7 and controls failure short-circuiting or allowing the query to proceed; the M4 JOIN derivation unit corresponds to step S8 and outputs the JOIN clause; and the M5 SQL generation unit corresponds to step S9 and forms the SQL clauses. The modules are connected through intermediate results with a fixed structure, ensuring consistency between the aforementioned method steps and the system modules.

[0122] The security control and SQL output module writes the business filter value and permission value into the named parameter dictionary, injects row-level security conditions into non-privileged roles, generates a constant false condition when the permission list is empty, and outputs parameterized SQL, named parameter dictionary, SQL hash value, and QueryShape. The database execution engine receives the parameterized SQL and named parameter dictionary and returns the query results. The security control and SQL output module corresponds to steps S9 to S11, and its specific processing can be referred to the aforementioned method embodiment.

[0123] The OWL / RDF ontology loading and projection module has an ontology input end, a classification projection processing part, and an OntologyConfig output end. The ontology input end receives OWL / RDF ontology from the manufacturing domain. The classification projection processing part forms corresponding definitions according to entities, relations, dimensions, indicators, filters, row-level security rules, and query responsibilities configured globally. The OntologyConfig output end passes the structured ontology configuration to the index and cache compilation module. This module does not receive user query values, nor does it directly generate SQL.

[0124] The indexing and caching compilation module comprises a synonym index construction section, a whitelist construction section, a compatibility matrix construction section, an entity relationship graph construction section, and a SystemCache update section. Each construction section takes the same OntologyConfig version as input and outputs the corresponding items of synonym expressions and specification identifiers, the allowed recognition set, the combination status of indicator dimensions, and the entity relationship graph, respectively. The SystemCache update section writes the complete results to the inactive cache and performs an atomic switch. After obtaining a cache version reference from the query compilation pipeline, the configuration objects within it are distributed to M1 through M5.

[0125] The inputs to the M1 preprocessing unit include Chinese natural language queries, request times, and thesaurus indexes, and the outputs include normalized query text and time parsing results; the inputs to the M2 query plan parsing unit include normalized query text, OntologyConfig, and a whitelist, and the output is QueryPlan; the inputs to the M3 verification unit include QueryPlan, OntologyConfig, compatibility matrix, entity relationship graph, and user context information, and the output is a verification pass status or an error status; the M4 JOIN derivation unit only receives the main entity, target dimension, and entity relationship graph after obtaining the verification pass status, and outputs DimBinding and join clauses; the M5 SQL generation unit receives QueryPlan, DimBinding, join clauses, and user context information, and outputs parameterized SQL and a named parameter dictionary.

[0126] The security control and SQL output module checks whether row-level security rules for non-privileged roles have been written into the final WHERE condition. If the permission list is empty, it controls M5 to use a constant false condition. This module also receives SQL text and QueryPlan, performs hashing on the SQL text to generate an SQL hash value, generates a QueryShape based on metrics and grouping dimensions, and outputs the parameterized SQL, named parameter dictionary, SQL hash value, and QueryShape together. The database execution engine binds the parameters and returns a table, scalar, or empty result. Audit information is associated with and saved in relation to this output.

[0127] The serialization format of an OWL / RDF ontology can be RDF / XML, Turtle, or JSON-LD, or a format that can equivalently express the recorded entities, relations, and constraints. The format change does not change the composition of the OntologyConfig obtained by ontology projection, nor does it change the use of entities, relations, dimensions, metrics, filters, and row-level security rules in the subsequent compilation stage.

[0128] M2 can employ a rule parser, a constrained large language model parser, or a combination of both, but all three methods output a QueryPlan with a specified structure and are subject to M3 validation. M4 can employ breadth-first search, Dijkstra's path search, or pre-computed shortest path, but candidate paths are constrained by ontology relations and deterministic ordering. These alternative methods can be combined with double-buffered SystemCache, named parameter binding, and row-level secure injection, respectively. When there are no logical conflicts, the technical features of each implementation can be combined with each other.

[0129] RDF / XML, Turtle, and JSON-LD are simply different serialization formats for OWL / RDF ontology. After the loading module parses the corresponding format into ontology semantic objects, it performs projection according to the same entity, relation, dimension, metric, filter, row-level security rules, and global configuration classification. When other formats that can equivalently express the recorded content are used, a consistent OntologyConfig must also be obtained. Relationship definitions or security rule definitions cannot be omitted due to format replacement.

[0130] The differences between the rule parser, the constrained large language model parser, and their combination lie in the M2 candidate structure generation method, while their candidate range, QueryPlan field, and M3 entry point remain consistent. The differences between breadth-first search, Dijkstra's path search, and pre-computed shortest path lie in the M4 candidate path acquisition process, while their entity relationship graph source, DimBinding, path scoring, and deterministic ranking constraints remain consistent. Alternative methods only replace the corresponding recorded stages and do not change M3 failure short-circuiting, M5 named parameter conversion, or non-privileged role row-level secure injection.

[0131] The above description represents a preferred embodiment of the present invention. It should be noted that, for those with general knowledge in this field, the preferred embodiments are not necessarily those described above. For those skilled in the art, several improvements and modifications can be made without departing from the principles described in this invention, and these improvements and modifications should also be considered within the scope of protection of this invention.

Claims

1. A method for compiling Chinese natural language to parameterized SQL based on OWL-RDF ontology, characterized in that, include: Load OWL or RDF ontology from the manufacturing domain and project entities, relations, dimensions, metrics, filters, and row-level security rules from the ontology into a structured ontology configuration. It receives Chinese natural language queries, user context information, and request time. Based on the structured ontology configuration and request time, it performs synonym normalization, relative time parsing, and text cleaning on the Chinese natural language queries to obtain normalized query text. Based on the normalized query text and structured ontology configuration, entities, indicators, dimensions and filtering conditions are identified, resulting in a structured query plan that records the main entity, indicator list, filtering conditions and grouping dimensions; Based on the structured ontology configuration and user context information, semantic verification, permission verification, and anti-injection verification are performed on the structured query plan. If any verification fails, the compilation is terminated and an error message is output. When all checks pass, the target entity is determined based on the main entity and grouping dimension, and the connection path from the main entity to the target entity is derived based on the entity relationships in the structured ontology configuration, thus obtaining the connection clause; Parameterized SQL is generated based on the structured query plan and join clauses, business filter values ​​are converted into named parameters, and row-level security conditions are injected for non-privileged roles to obtain a named parameter dictionary; Output parameterized SQL, named parameter dictionary, SQL hash value and query form, and submit for execution.

2. The compiling method of claim 1, wherein, Based on the entities, relations, dimensions, metrics, filters, row-level security rules, and global configurations recorded in the OWL or RDF ontology, a structured ontology configuration is obtained, including: Write the mapping relationship between business objects and database tables into the entity definition; write the foreign key connection relationship between entities into the relationship definition; Write the fields used for grouping or filtering into the dimension definition; write the aggregation calculation expression into the metric definition; write the content used to generate the filtering conditions into the filter definition; Write the data range that different roles can access into the row-level security rule definition; The structured ontology configuration is composed of entity definitions, relationship definitions, dimension definitions, indicator definitions, filter definitions, row-level security rule definitions, and global configuration definitions; The system generates a synonym index, a query constraint whitelist, and an indicator dimension compatibility matrix based on the structured ontology configuration. The generated results are written to the system cache using a double-buffering method, and the updated cache is switched via atomic pointers when the ontology configuration is updated.

3. The compiling method of claim 1, wherein, The Chinese natural language query is processed sequentially using synonym normalization, relative time parsing, and text cleaning to obtain a normalized query text, including: Based on the thesaurus index, multiple Chinese expressions in the Chinese natural language query are mapped to corresponding standardized identifiers, and replacements are performed according to the order of longer words. Recognize relative time expressions such as today, yesterday, this week, last week, this month, last month, or recent days in Chinese natural language queries, and convert the recognized relative time expressions into standard start and end dates and time granularity according to the requested time; Clean up non-query text in Chinese natural language queries to obtain normalized query text; When a relative time expression not supported by the system is detected, query plan parsing is terminated and a preprocessing error is output.

4. The compiling method of claim 1, wherein, The resulting structured query plan includes the main entity, a list of metrics, filtering conditions, grouping dimensions, aggregation methods, and a query limit on the number of rows. Based on the query constraint whitelist and the thesaurus, entity candidates, indicator candidates, dimension candidates and filtering condition candidates are identified in the normalized query text. Based on the indicator definitions corresponding to the identified indicator candidates, determine the fact table to which the indicator candidates belong, and identify the fact table as the main entity; Generate a structured query plan based on entity candidates, indicator candidates, dimension candidates, and filter condition candidates; When multiple metrics in the metric list belong to different fact tables, terminate semantic validation and output a parsing error to indicate a split query.

5. The compiling method of claim 1, wherein, The system performs checks on the integrity of structured query plan execution, ontology consistency, metric dimension compatibility, entity reachability, time granularity, role permissions, and injection prevention, including: Check if the structured query plan contains the required metrics, dimensions, or main entity for the query; check if the entities, metrics, dimensions, and filters in the structured query plan exist in the structured ontology configuration; Check whether the metrics support aggregation by grouping dimension based on the metric dimension compatibility matrix; Check whether the entities required for the query can be connected based on the entity relationship diagram; check whether the grouping dimension supports the time granularity obtained from the parsing. Check whether the explicit filtering conditions fall within the allowed access range based on the user context information; check whether the entity name, metric name, and dimension name conform to the security naming rules and are not SQL keywords.

6. The compiling method of claim 5, wherein, If any check fails, the subsequent compilation will terminate and the corresponding error message will be output, including: If any of the following checks fails: integrity check, ontology consistency check, metric dimension compatibility check, entity reachability check, time granularity legality check, role and permission check, or anti-injection check, connection path deduction and parameterized SQL generation will not be executed. Based on the failed validation items, determine the corresponding error type from unknown metrics, unknown dimensions, incompatible metrics and dimensions, unreachable entities, insufficient permissions, and illegal identifiers, and output an interpretable error message carrying the error type.

7. The method of claim 1, wherein, Based on the entity relationships in the structured ontology configuration, the connection path from the main entity to the target entity is derived, resulting in the connection clause, including: Construct an entity relationship graph with entities as nodes and foreign key connections between entities as edges; obtain candidate connection paths from the main entity to the target entity using breadth-first search, Dijkstra's path search, or pre-computed shortest path methods; Based on the dimension binding corresponding to the grouping or filtering dimension of the current main entity, no join clause is generated when the dimension field is located in the fact table corresponding to the main entity; when the dimension field is located in the dimension table, candidate join clauses are generated based on the corresponding foreign key join relationship. The candidate connection paths are ranked based on a weighted average of path length cost, relation cardinality cost, connection type cost, and data inflation risk cost. When the difference between multiple weighted results is less than the configured threshold, a secondary sort is performed according to path length, relation cardinality risk, and predefined primary connection relationship. If the result cannot be determined, multiple candidate connection paths are output.

8. The method of claim 1, wherein, Generate selection clauses, main table clauses, filter clauses, grouping clauses, and query restriction clauses based on the structured query plan and join clauses, and convert business filter values ​​into named parameters, including: Generate selection clauses based on the indicator list and grouping dimensions; generate main table clauses based on the main entity; Connect the join clause to the main table clause; generate filter clauses based on the filter conditions, and convert the time range into start date named parameters and end date named parameters respectively, and convert multiple filter values ​​of the business object into mutually distinguishable named parameters; Generate grouping clauses based on grouping dimensions, and generate query restriction clauses based on the number of rows to be restricted in the query; Parameterized SQL is obtained by combining the SELECT clause, TABLE clause, JOIN clause, SELECT clause, GROUP BY clause, and SELECT LIMIT clause in that order.

9. The compiling method of claim 1, wherein, For non-privileged roles, the corresponding row-level security conditions are injected into the filter clause, resulting in parameterized SQL and a named parameter dictionary, including: The corresponding row-level security rules are determined based on the user role in the user context information; when the user role is a non-privileged role, the row-level security rules are written as necessary filtering conditions into the filtering clause; When a row-level security rule contains a permission list placeholder, the allowed production line range or factory range is expanded into a named parameter list, and each permission value is written into the named parameter dictionary. When the corresponding permission list is empty, write the constant false condition into the filter clause; The SQL hash value is determined based on the generated parameterized SQL, and the query form is determined based on the metrics and grouping dimensions. The SQL hash value, query form, execution time, and user context information are retained as audit information.

10. A system for compiling Chinese natural language to parameterized SQL based on OWL-RDF ontology, which implements the method as claimed in any one of claims 1 to 9, characterized in that, The system includes: The OWL or RDF ontology loading and projection module is used to load OWL or RDF ontology in the manufacturing field and project entities, relationships, dimensions, metrics, filters, row-level security rules and global configurations into structured ontology configurations. The index and cache compilation module is used to compile the synonym index, query constraint whitelist and indicator dimension compatibility matrix according to the structured ontology configuration, and write the compilation results to the system cache. The query compilation pipeline module includes a preprocessing unit, a query plan parsing unit, a validation unit, a join derivation unit, and an SQL generation unit. The preprocessing unit is used to obtain normalized query text based on Chinese natural language queries, thesaurus indexes, and request times. The query plan parsing unit is used to obtain a structured query plan based on the normalized query text. The validation unit is used to perform semantic validation, permission validation, and anti-injection validation on the structured query plan before SQL generation. The join derivation unit is used to obtain join clauses based on the ontology relation graph when the validation passes. The SQL generation unit is used to generate parameterized SQL based on the structured query plan and join clauses. The security control and SQL output module is used to convert business filter values ​​into named parameters, inject row-level security conditions for non-privileged roles, and output parameterized SQL, named parameter dictionary, SQL hash value and query form.