A Text2SQL training and reasoning method based on structured database graph enhancement, an electronic device, a computer readable storage medium and a computer program product

By constructing a structured database graph and combining it with graph neural networks and large language models, the problem of insufficient database schema information in existing Text2SQL technology is solved. This enables a deep understanding of complex database structures and accurate generation of cross-table queries, and provides continuous self-optimization capabilities.

CN121501818BActive Publication Date: 2026-06-12JIANGSU DAMENG DATABASE CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
JIANGSU DAMENG DATABASE CO LTD
Filing Date
2025-10-31
Publication Date
2026-06-12

AI Technical Summary

Technical Problem

Existing Text2SQL technology lacks database schema information modeling during training and inference, resulting in poor performance in complex or unseen database structures, difficulty in accurately capturing cross-table query relationships, and lack of dynamic feedback optimization mechanisms, making continuous improvement difficult.

Method used

By constructing a structured database graph, combining graph neural networks and large language models, training and inference are integrated and enhanced. Graph retrieval is used to generate contextual hints, and dynamic optimization is performed by combining execution feedback, thereby achieving a deep understanding of the database pattern and continuous self-optimization of the model.

Benefits of technology

It significantly improves the model's ability to understand complex table structures and cross-table queries, enhances the accuracy and executability of SQL generation, and enables the system to continuously self-optimize and adapt.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121501818B_ABST
    Figure CN121501818B_ABST
Patent Text Reader

Abstract

The application discloses a Text2SQL training and reasoning method based on structured database graph enhancement, an electronic device, a computer readable storage medium and a computer program product. The method comprises the following steps: receiving a natural language query request input by a user; splicing the natural language query request input by the user and a graph enhanced representation corresponding to a target database into an input sequence; inputting the input sequence into a large language model after training to generate a group of candidate SQL query statements; performing semantic consistency verification and syntax legality verification on the candidate SQL query statements to obtain a final SQL query statement that passes the verification; and submitting the final SQL query statement to the target database for execution to obtain an execution result.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of natural language processing and database technology, specifically relating to a Text2SQL training and inference method based on structured database graph enhancement, electronic devices, computer-readable storage media, and computer program products. Background Technology

[0002] Existing Text2SQL technologies primarily rely on large language models or deep learning models to directly generate SQL query statements from natural language problems. However, existing methods have the following shortcomings:

[0003] (1) Separation of training and inference information: During the training phase, only natural language and SQL are paired, and there is a lack of modeling of database schema information, which leads to poor performance of the model when faced with complex or unseen database structures.

[0004] (2) Insufficient performance of cross-table queries: There are often complex inter-table relationships in the database (such as primary and foreign keys, nested queries), which are difficult to accurately capture with existing methods, and the generated SQL is prone to semantic errors or missing relationships.

[0005] (3) Lack of dynamic feedback optimization: If the existing model generates SQL but fails to execute or produces an incorrect result, it is usually impossible to use execution feedback to correct or improve the model, making it difficult to continuously optimize the system.

[0006] Therefore, there is an urgent need for a method that can combine database structure information (schema graph) and integrate training, inference and feedback to enhance the accuracy and generalization ability of Text2SQL models. Summary of the Invention

[0007] Purpose of the invention: To address the problems existing in the prior art, this invention proposes a Text2SQL training and inference method, system, computer device, and storage medium based on structured database graph enhancement.

[0008] Technical Solution: In a first aspect, this invention proposes a Text2SQL training and inference method based on structured database graph enhancement, comprising:

[0009] Receive natural language query requests from users and perform entity word recognition on the natural language query requests input by users;

[0010] Based on the identified entity words, retrieve the table / field subgraphs related to the entity words from the graph corresponding to the target database;

[0011] The user's input natural language query request is concatenated with the graph augmentation representation corresponding to the retrieved table / field subgraph to form an input sequence. The input sequence is then input into the trained large language model to generate a set of candidate SQL query statements.

[0012] Perform semantic consistency verification and syntax validity verification on the candidate SQL query statements to obtain the final SQL query statement that passes the verification;

[0013] The final SQL query statement is submitted to the target database for execution, and the execution result is obtained.

[0014] Furthermore, the map corresponding to the target database is obtained according to the following steps:

[0015] The schema information of the target database is extracted, including tables, fields, primary and foreign key relationships, and comments.

[0016] Extract the containment relationship between tables and fields, extract the dependency relationship formed by primary key and foreign key constraints, and extract the join relationship between tables;

[0017] These three relationships are transformed into triples (entity, relation, entity) and stored as a graph structure to construct a database graph, which contains entity, relation, and attribute triples.

[0018] Furthermore, the graph augmentation representation corresponding to the retrieved table / field subgraph is obtained according to the following steps:

[0019] Graph neural networks are used to perform embedding calculations on the retrieved table / field subgraphs to obtain vectorized embeddings; at the same time, a large language model is used in combination with triples to generate contextual prompts.

[0020] Vectorized embeddings and contextual hints together constitute the graph-enhanced representation of the table / field subgraph.

[0021] Furthermore, the trained large language model is obtained according to the following steps:

[0022] The natural language query request, the database graph augmentation representation, and the corresponding standard SQL query statement are input into the large language model.

[0023] During the training phase, supervised learning, contrastive learning, and LoRA fine-tuning were employed to enable the large language model to learn the alignment relationship between natural language and database graphs. Reinforcement learning was combined to optimize the difference between the generated SQL query statement and the standard SQL query statement, ultimately resulting in the trained large language model.

[0024] During the training phase, a hybrid loss function is used: L_total = L_token + λ·L_schema + μ·L_exec_proxy; where L_schema is the component matching loss for the table / column / predicate, L_exec_proxy is the execution agent loss or executability predictor loss for the differentiable approximation, and λ and μ represent the corresponding weights.

[0025] Furthermore, the semantic consistency verification refers to the semantic consistency between the candidate SQL query statement and the natural language query request;

[0026] The syntax validity verification refers to whether the candidate SQL query statement is executable under the target database syntax.

[0027] Furthermore, it also includes:

[0028] Collect user feedback on execution results and actual execution status, and record the correctness, performance indicators and error patterns of the execution results;

[0029] Based on the correctness, performance metrics, and error patterns of the recorded execution results, the database graph and training samples are dynamically updated.

[0030] Furthermore, it also includes:

[0031] Based on the correctness, performance metrics, and error patterns of the recorded execution results, reinforcement learning is used to adjust the inference and decoding strategies of the large language model, update the search space generated by candidate SQL, and adaptively adjust the graph encoding weights.

[0032] Secondly, the present invention provides an electronic device, the electronic device comprising:

[0033] At least one processor;

[0034] and a memory communicatively connected to the at least one processor;

[0035] The memory stores a computer program that can be executed by the at least one processor, which enables the at least one processor to execute a Text2SQL training and inference method based on structured database graph enhancement.

[0036] Thirdly, the present invention proposes a computer-readable storage medium storing computer instructions for causing a processor to execute a Text2SQL training and inference method based on structured database graph enhancement.

[0037] Fourthly, the present invention proposes a computer program product, which includes a computer program that, when executed by a processor, implements a Text2SQL training and inference method based on structured database graph enhancement.

[0038] Beneficial Effects: This invention constructs a unified schema graph by parsing database tables, fields, primary and foreign key relationships, and annotation information. This graph is used for enhancement in both the training and inference phases. During training, enhanced corpora are generated based on the schema graph to fine-tune the large language model, thereby improving its understanding of complex table structures and cross-table queries. During inference, contextual enhancement hints are generated through graph retrieval to assist SQL generation, and combined with execution feedback to form a dynamic optimization loop. This invention's method realizes the integration of database schema information throughout the entire training-inference-feedback process, significantly improving the accuracy and executability of SQL generation. Compared with existing technologies, this invention has the following advantages:

[0039] (1) By introducing a database graph, this invention significantly enhances the model’s ability to understand database patterns and solves the problem of ambiguous field semantics in complex patterns;

[0040] (2) The present invention adopts graph coding and natural language joint modeling, which can improve the accuracy and robustness of SQL generation.

[0041] (3) The present invention combines semantic and syntactic dual verification mechanisms to ensure the executability and correctness of the generated SQL.

[0042] (4) The present invention provides a feedback-driven incremental optimization mechanism, which enables the system to continuously evolve and adapt to changes in database structure and user needs.

[0043] (5) The method of the present invention achieves continuous self-optimization of the system through closed-loop feedback. Attached Figure Description

[0044] Figure 1 This is a flowchart of a Text2SQL training and inference method based on structured database graph enhancement proposed in this invention;

[0045] Figure 2 Schema diagram for map extraction and representation;

[0046] Figure 3 This is a schematic diagram of the training process;

[0047] Figure 4 This is a diagram illustrating the reasoning process;

[0048] Figure 5 A schematic diagram illustrating the feedback and incremental optimization closed loop;

[0049] Figure 6 This is a block diagram of a system for generating SQL query statements based on structured database graph enhancement proposed in this invention. Detailed Implementation

[0050] The technical solution of the present invention will now be further described in conjunction with the accompanying drawings and embodiments.

[0051] Example 1:

[0052] This invention provides a Text2SQL training and inference method based on structured database graph enhancement, which mainly includes the following steps:

[0053] Step 1: Receive the natural language query request input by the user, and perform word segmentation, part-of-speech tagging and intent recognition on the natural language query request to obtain a preliminary semantic representation of the query;

[0054] Step 2: Extract schema information from the target database. Schema information includes, but is not limited to, tables, fields, primary and foreign key relationships, and comments. Extract the containment relationships between tables and fields, the dependency relationships formed by primary and foreign key constraints, and the join relationships between tables. Transform these relationships into triples (entity, relation, entity) and store them as a graph structure to construct a database graph. This database graph contains entity, relation, and attribute triples and can be dynamically updated to reflect changes in the database structure.

[0055] Step 3: Encode the database graph using a Graph Neural Network (GNN), Graph Transformer, or a pre-trained language model to generate corresponding vectorized and textual representations, thereby enhancing the model's understanding of the database structure. Specifically, this includes: using a GNN to perform embedding computation on the database graph structure to obtain vectorized embeddings; using a large language model combined with graph triples to generate contextual clues; and then feeding the vectorized embeddings and contextual clues in parallel and complementary ways into the training model.

[0056] Step 4: Input the natural language query request, the vectorized and textual representations of the database graph, and the corresponding standard SQL query statement into the training model. During training, supervised learning, contrastive learning, and LoRA (freezing the weights of the pre-trained model and training a low-rank matrix) fine-tuning methods are used successively to enable the model to learn the alignment relationship between the natural language and the database graph. Reinforcement learning is also combined to optimize the reward for the difference between the generated SQL and the standard SQL.

[0057] Step 5: During the inference phase, the natural language query request and its corresponding vectorized or textual representation in the database graph are concatenated into an input sequence, and the model generates a set of candidate SQL query statements. Database graph constraints are used for filtering, eliminating candidate SQL statements that do not conform to the pattern constraints.

[0058] In this step, database graph constraints are a candidate SQL validity screening mechanism based on database structure and semantic information. It ensures that the SQL generated by the model is consistent with the structure, field types, and logical relationships of the real database, thereby significantly improving the executability and correctness of the generated results. For example, graph matching verification: candidate SQL is parsed into an abstract syntax tree (AST); tables, columns, and operators are extracted from the AST; corresponding nodes are matched in the database graph; if none exist, it is judged as an illegal candidate. Primary and foreign key consistency checks: the validity of joins is determined based on the "inter-table edges" in the graph; if no valid join path exists, the SQL is discarded or rewritten.

[0059] Step 6: Use a semantic consistency discriminant model to match and verify the candidate SQL with the original natural language query, including:

[0060] Semantic consistency verification: Ensures that the candidate SQL query statement is semantically consistent with the natural language query request;

[0061] Syntax validity verification: Ensures that candidate SQL query statements are executable under the target database syntax.

[0062] Step 7: Submit the validated final SQL query to the database for execution and return the result to the user.

[0063] Step 8: Collect user feedback on query results and actual execution status, and use it to incrementally update the database graph and training samples. At the same time, adjust the model's decoding strategy and graph weight distribution through reinforcement learning to achieve continuous self-optimization of the system.

[0064] Example 2:

[0065] This invention provides a SQL query statement generation system based on structured database graph enhancement, comprising:

[0066] Query receiving module: Used to receive natural language queries input by users and convert the queries into an internal unified format for subsequent processing;

[0067] The graph construction module is used to extract tables, fields, primary and foreign key relationships, and annotation information from the target database, and convert them into triples to construct a database graph that reflects the structured semantics of the database.

[0068] Graph encoding module: used to vectorize and textualize the database graph, including using graph neural networks to compute vectorized embeddings and converting triples into text prompt sequences to obtain graph-enhanced representations;

[0069] Training module: Used to train the model by jointly inputting natural language, graph representations, and SQL statements; it optimizes the parameters of the large language model through supervised learning and reinforcement learning, enabling the model to understand database structure and semantics;

[0070] Inference module: Used to receive user natural language queries during the inference phase and generate a set of candidate SQL query statements by combining graph augmented representations;

[0071] Validation module: Used to perform semantic consistency and syntax validity validation on candidate SQL query statements to filter SQL query statements that match the user's query intent and comply with database schema constraints;

[0072] Execution module: Used to submit the filtered SQL query statements to the database for execution, obtain the execution results and return them to the user.

[0073] Furthermore, the system also includes:

[0074] Feedback Update Module: Used to collect database execution results and user feedback information, and record the correctness, performance indicators and error patterns of SQL execution;

[0075] Incremental optimization module: used to dynamically update the database graph and training sample library based on the feedback data, thereby expanding the training corpus and improving the model's adaptability to specific databases;

[0076] Model Adaptive Module: This module is used to adjust the inference and decoding strategies of the large language model based on feedback data, update the search space generated by candidate SQL, and adaptively adjust the graph encoding weights to achieve continuous optimization and performance improvement.

[0077] Figure 1 The entire process of this invention is demonstrated: the left side shows the training path (extracting structural information from the database, including tables, columns, data types, primary / foreign keys, indexes, annotations, etc., to fine-tune and validate the model); the right side shows the inference path (user query → subgraph retrieval → pattern-aware prompts → SQL generation → validation → execution → return). The middle section is the execution feedback loop, where feedback data is used for both immediate context injection and periodic incremental training (adaptor / low-rank adaptation).

[0078] Figure 2This demonstrates how to automatically extract metadata (tables / columns / data types / primary and foreign keys / comments) from a database, perform naming standardization and sample value sampling, and convert it into triples and store it as a graph. After the graph is built, a retrieval interface needs to be constructed to support retrieving related subgraphs by keywords, column comments, or sample values, so as to enable rapid candidate filtering and suggestion construction during inference.

[0079] Figure 3 The training process details are as follows: Raw natural language-SQL data is combined with pattern subgraphs to generate augmented samples, which are then subjected to executability filtering (validated on a sandbox database). During training, a hybrid loss is used: L_total = L_token + λ·L_schema + μ·L_exec_proxy (where L_schema is the component matching loss for tables / columns / predicates, and L_exec_proxy is the differentiable approximation execution proxy loss or executability predictor loss). Every few steps, a test execution evaluation is triggered, and EM (exact match rate) and EX (exact execution rate) are recorded in real time to select the optimal weight model.

[0080] Figure 4 The inference process first extracts the pattern subgraph most relevant to the problem through subgraph retrieval; prompt words are concatenated according to templates (including one-hop or two-hop neighbors directly connected to the target table, example values, and error correction suggestions), and the model generates several candidate SQL statements; the validator performs AST (Abstract Syntax Tree) / column existence / type matching and semantic similarity judgment; qualified candidates can first be EXPLAIN / ANALYZE (execution plan / actual execution statistics) in a sandbox environment, and the optimal one is selected based on the evaluation or enters the automatic repairer (minimum edit / constraint-satisfied bundle search) to generate again; finally, it is executed on the target database and the results are returned.

[0081] Figure 5 This section explains how feedback is used both for immediate context enhancement and for offline incremental training (generating incremental samples and performing local fine-tuning of the adapter / low-rank adaptation). Collected metrics include execution time, failure type, and row count changes. Error patterns are indexed for future retrieval and prompt word injection, and adapter versioning is used for rollback and A / B testing.

[0082] Figure 6 It is a system engineering module diagram, including query reception, caching, pattern graph retrieval, prompt word generation, model generation (including the Adapter layer), validator, sandbox / real execution, execution monitoring and feedback flow.

[0083] Example 3:

[0084] In an airline's flight_2 database, a user enters the query: "Query all flight numbers and departure times from Beijing to Shanghai".

[0085] Step S1, Query Receive: Receive the user's NL query and perform basic preprocessing (removing empty strings, sentence segmentation, and entity recognition). For example, given nl_text = "Query all flight numbers and departure times from Beijing to Shanghai.", through word segmentation / entity recognition (using simple regular expressions / named entity recognition to identify "Beijing", "Shanghai", and "flights"), the output is: { "nl":nl_text, "entities": ["Beijing","Shanghai"]}.

[0086] Step S2: Construct / query fingerprints (Fingerprint / Cache Check) to quickly find historical optimization results and avoid redundant calculations. Normalize NL or intermediate SQL (if provided by the user): lowercase keywords, remove spaces, standardize table column names (remove aliases), remove constant values, and optionally perform template-based processing (depending on whether exact matching is required).

[0087] Decision: If the fingerprint is in the cache → directly return the best cached SQL and execution data and end.

[0088] This example was not hit; proceed to the next step.

[0089] Step S3: Schema Graph Retrieval. Retrieve the most relevant table / field subgraph to the query within the schema graph of flight_2. The schema graph is stored as triples, for example:

[0090] ("flights","has_column","flight_id")

[0091] ("flights","has_column","departure_airport")

[0092] ("flights","has_column","arrival_airport")

[0093] ("flights","has_column","departure_time")

[0094] ("airports","has_column","city")

[0095] ("flights","fk->","airports.code")

[0096] Retrieve potentially relevant nodes based on entity terms (Beijing / Shanghai / flights / departure): match field names / comments / example values ​​(e.g., the departure_airport comment contains "departure city / airport"). Return a subgraph: subgraph = {tables: ["flights","airports"], columns: [...], fk_edges: [...]}, the final output: the subgraph contains the flights and airports tables and their fields, and the FK relationship.

[0097] Step S4: Graph Encoding & Prompt Construction, converting the subgraph into model input (textualized prompt and vectorized embedding).

[0098] Example of a schema-aware prompt:

[0099] Schema:

[0100] TABLE flights(id, flight_id, departure_airport, arrival_airport,departure_time, ...)

[0101] TABLE airports(code, city, name)

[0102] JOIN: flights.departure_airport = airports.code

[0103] Hint: departure_airport / arrival_airport store airport codes;airports.city stores city name.

[0104] User Query: Retrieve all flight numbers and departure times from Beijing to Shanghai.

[0105] Please output a single SQL query for Postgres.

[0106] Vectorized embedding means directly storing the data in a vector database for retrieval during subsequent question-and-answer sessions.

[0107] Step S5: Generate candidate SQL (Model Generate), using LLM to generate multiple candidate SQL statements. Example candidates (5 statements):

[0108] SELECT flight_id, departure_time FROM flights WHERE departure_airport= 'Beijing' AND arrival_airport = 'Shanghai';

[0109] SELECT f.flight_id, f.departure_time FROM flights f JOIN airports a1ON f.departure_airport=a1.code JOIN airports a2 ON f.arrival_airport=a2.codeWHERE a1.city='Beijing' AND a2.city='Shanghai';

[0110] SELECT flight_id, departure_time FROM flights WHERE departure_airportIN (SELECT code FROM airports WHERE city='Beijing') AND arrival_airport IN(SELECT code FROM airports WHERE city='Shanghai');

[0111] SELECT flight_id, departure_time FROM flights WHERE departure_airport='PEK' AND arrival_airport='PVG';

[0112] SELECT flight_no, depart_time FROM flight_table WHERE from_city='Beijing' AND to_city='Shanghai';

[0113] Note: The candidates may contain different levels of precision and may also have different names (flight_no vsflight_id).

[0114] Step S6: Semantic & Syntax Validation, including:

[0115] Sub-step 6.1: Syntax Legality. Check whether the syntax can be parsed using sqlparse or the parser of the DB. If the parsing fails, mark it as invalid.

[0116] Sub-step 6.2: Semantic Equivalence / Consistency Screening. Determine whether the candidate meets the natural language semantics. Adopt the following combined rules: If the candidate uses the join table of airports.city, the semantics are highly credible. If the candidate directly uses airports.code or the literal 'Beijing', it is necessary to determine whether 'Beijing' exists in the data by code or by its Chinese name. After normalizing using AST (field alias and case normalization), match it with the intent template. Set a threshold, for example, semantic_score >= 0.8 (based on the cosine of the embedding similarity: Embed(NL) and Embed(SQL intent)).

[0117] Examples of screening results: Candidates 2 and 3 are determined to be more strictly consistent in semantics; Candidate 1 may not work (Is 'Beijing' a code? It is necessary to check the data); For Candidate 4, if the database uses a code such as 'PEK', mapping is required; Candidate 5 is directly excluded because the table name does not match (flight_table does not exist in the schema).

[0118] Step S7: Execution Plan and Cost Evaluation (Explain & Analyze). Submit the screened candidates to the database optimizer: Use EXPLAIN (FORMAT JSON) <candidate_sql> to obtain the estimated plan and cost. Use EXPLAIN ANALYZE <candidate_sql> (on sandbox / sample data) to obtain the actual execution time and running statistics (rows, time, buffers). Collect example fields of cost information: estimated_cost, execution_time_ms, cpu_percent, memory_use_kb, io_reads. Comparison of multiple candidates: Use a predefined scoring function:

[0119] Score = - (w1 * estimated_cost) - (w2 * execution_time) - (w3 * cpu)- (w4 * memory) + bonus_if_direct_matching

[0120] Here, `estimated_cost` is the estimated cost, i.e., the cost estimated by the database optimizer; `execution_time` is the actual execution time, the real execution time measured under sandbox conditions; `cpu` refers to CPU usage / percentage, the CPU resources consumed during execution; `memory` is the memory consumption, the peak memory used during execution; `bonus_if_direct_matching` is the direct matching reward, a positive reward is given when a candidate SQL statement directly uses the column / function / filter condition explicitly requested in the user's question. `w1..w4` are weight coefficients, representing the relative attention to different cost types; the larger the coefficient, the more sensitive the user is to that resource, and the weights can be dynamically adjusted.

[0121] Step S8: Result selection, caching and return, select the candidate with the highest score (e.g., candidate 2 has the highest score).

[0122] Write the SQL, execution plan, cost information, and score to the cache (fingerprint → record). Return the final SQL and execution result / sample rows to the user.

[0123] Step S9: Execute feedback and incremental optimization, monitoring phase: Record long-term metrics for actual online execution (response time distribution, error rate, user adoption). If actual performance differs significantly from expectations: adjust the scoring function weights w1...w4.

[0124] Successful NL↔SQL pairs are added to the training pool and periodically fine-tuned using LoRA (or stored in the Agent-Lighting context memory). If common errors occur in the candidates (such as using city names instead of airport codes), the error pattern is written to the "error correction library" and a hint is injected in a subsequent prompt.

[0125] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium, and when executed, it can include the processes of the embodiments of the methods described above. Any references to memory, storage, databases, or other media used in the embodiments provided in this application can include at least one of non-volatile and volatile memory. Non-volatile memory can include read-only memory (ROM), magnetic tape, floppy disk, flash memory, or optical storage, etc. Volatile memory can include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM can be in various forms, such as static random access memory (SRAM) or dynamic random access memory (DRAM), etc.

[0126] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.

[0127] The embodiments described above are merely illustrative of several implementation methods of this application, and while the descriptions are relatively specific and detailed, they should not be construed as limiting the scope of the invention patent. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this patent application should be determined by the appended claims.

Claims

1. A Text2SQL training and inference method based on structured database graph enhancement, characterized in that: include: Receive natural language query requests from users and perform entity word recognition on the natural language query requests input by users; Based on the identified entity words, retrieve the table / field subgraphs related to the entity words from the graph corresponding to the target database; The user's input natural language query request is concatenated with the graph augmentation representation corresponding to the retrieved table / field subgraph to form an input sequence. The input sequence is then input into the trained large language model to generate a set of candidate SQL query statements. Perform semantic consistency verification and syntax validity verification on the candidate SQL query statements to obtain the final SQL query statement that passes the verification; The final SQL query statement is submitted to the target database for execution, and the execution result is obtained.

2. The Text2SQL training and inference method based on structured database graph enhancement according to claim 1, characterized in that: The map corresponding to the target database is obtained according to the following steps: The schema information of the target database is extracted, including tables, fields, primary and foreign key relationships, and comments. Extract the containment relationship between tables and fields, extract the dependency relationship formed by primary key and foreign key constraints, and extract the join relationship between tables; These three relationships are transformed into triples (entity, relation, entity) and stored as a graph structure to construct a database graph, which contains entity, relation, and attribute triples.

3. The Text2SQL training and inference method based on structured database graph enhancement according to claim 2, characterized in that: The graph augmentation representation corresponding to the retrieved table / field subgraph is obtained according to the following steps: Graph neural networks are used to perform embedding calculations on the retrieved table / field subgraphs to obtain vectorized embeddings; at the same time, a large language model is used in combination with triples to generate contextual prompts. Vectorized embeddings and contextual hints together constitute the graph-enhanced representation of the table / field subgraph.

4. The Text2SQL training and inference method based on structured database graph enhancement according to claim 3, characterized in that: The trained large language model is obtained through the following steps: The natural language query request, the database graph augmentation representation, and the corresponding standard SQL query statement are input into the large language model. During the training phase, supervised learning, contrastive learning, and LoRA fine-tuning were used successively to enable the large language model to learn the alignment relationship between natural language and database graphs. By combining reinforcement learning, the difference between the generated SQL query statement and the standard SQL query statement is used to optimize the reward, and finally the trained large language model is obtained. During the training phase, a hybrid loss function is used: L_total = L_token + λ·L_schema + μ·L_exec_proxy; where L_schema is the component matching loss for the table / column / predicate, L_exec_proxy is the execution agent loss or executability predictor loss for the differentiable approximation, and λ and μ represent the corresponding weights.

5. The Text2SQL training and inference method based on structured database graph enhancement according to claim 1, characterized in that: The semantic consistency verification refers to the semantic consistency between the candidate SQL query statement and the natural language query request. The syntax validity verification refers to whether the candidate SQL query statement is executable under the target database syntax.

6. The Text2SQL training and inference method based on structured database graph enhancement according to claim 1, characterized in that: Also includes: Collect user feedback on execution results and actual execution status, and record the correctness, performance indicators and error patterns of the execution results; Based on the correctness, performance metrics, and error patterns of the recorded execution results, the database graph and training samples are dynamically updated.

7. The Text2SQL training and inference method based on structured database graph enhancement according to claim 6, characterized in that: Also includes: Based on the correctness, performance metrics, and error patterns of the recorded execution results, reinforcement learning is used to adjust the inference and decoding strategies of the large language model, update the search space generated by candidate SQL, and adaptively adjust the graph encoding weights.

8. An electronic device, characterized in that, The electronic device includes: At least one processor; and a memory communicatively connected to the at least one processor; The memory stores a computer program that can be executed by the at least one processor, which is then executed by the at least one processor to enable the at least one processor to execute the Text2SQL training and inference method based on structured database graph enhancement as described in any one of claims 1-7.

9. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer instructions that cause a processor to execute and implement the Text2SQL training and inference method based on structured database graph enhancement as described in any one of claims 1-7.

10. A computer program product, characterized in that, The computer program product includes a computer program that, when executed by a processor, implements the Text2SQL training and inference method based on structured database graph enhancement as described in any one of claims 1-7.