Three Technical Approaches to Automatic SQL Generation: A Practical Guide
This article examines three technical paths for automatic SQL generation: static generation from schemas or entity classes, reconstructing executed statements from runtime logs, and static preview based on code semantics. It explains how each path works, where each one falls short, and how to choose among them, then offers practical guidance on using AI-generated SQL responsibly and building a verifiable generation workflow.
1. Why Hand-Written SQL Is Becoming a Bottleneck
In data-driven application development, SQL is the bridge between business logic and the storage layer. As the number of tables grows, query conditions become more complex, and cross-cutting requirements such as multi-tenancy, logical deletion, and pagination are introduced, the cost of writing SQL by hand rises quickly. The pain points fall into three categories:
- Repetitive work: Single-table CRUD is highly templated, and the more fields there are, the easier it is to omit or miswrite one.
- Hard-to-maintain dynamic conditions: Optional query conditions produce combinatorial explosion, and string concatenation is both error-prone and vulnerable to injection.
- Long verification loop: After changing a condition, you often have to start the service, construct test data, and set breakpoints just to see what the final statement looks like.
So “automatic SQL generation” is not simply about typing less. It is about engineering the production, reconstruction, and verification of SQL. The three paths are described below.
2. Path 1: Static Generation from Schema or Entity Classes
This is the most mature category. The core idea is metadata in, templates out.
- Input: Database table definitions (fields, types, primary keys, indexes) or entity class definitions.
- Output: Mapper interfaces, XML mapping files, or single-table SELECT / INSERT / UPDATE / DELETE statements.
- Typical forms: Code generators can produce data-access-layer skeletons in batches per table; some IDE plugins infer query semantics from method naming conventions; database clients usually offer a right-click option to generate single-table statements.
The use case is clear: scaffolding a new project, or adding a standard CRUD layer to a legacy database. The advantages are high determinism and versionable artifacts. The limitation is that it only covers cases where the structure is known and the semantics are simple; complex dynamic queries are out of reach.
Example (generated output typically looks like):
<select id="selectByPrimaryKey" resultType="User">SELECT id, name, status, created_atFROM t_userWHERE id = #{id}</select>
3. Path 2: Reconstructing the Real Executed Statement from Runtime Logs
The second idea is after-the-fact reconstruction: once the application is actually running, the persistence framework usually emits two log lines, one for the prepared statement and one for the parameters. Merging them yields an executable SQL statement.
- Advantage: What you get is a statement that actually ran in production, with accurate parameters and ordering, which makes troubleshooting production issues very direct.
- Cost: You must enable the relevant log level and perform a real invocation; if the log format, driver version, or parameter-printing strategy changes, the parsing rules may no longer match.
- Caution: Keeping fine-grained logging on in production for long periods creates performance and disk pressure, so it is usually enabled only temporarily during a troubleshooting window.
The essence of this path is trading observability for accuracy. It is suited to confirming what actually ran in a given environment.
4. Path 3: Static Preview Based on Code Semantics
The third direction has drawn more attention in recent years: previewing the SQL that will be generated, directly in the code editor, without starting the service.
Key implementation points:
- Parse the call chain: Provide an entry icon next to chained condition builders, mapping files, and annotation-based SQL, and statically derive the final statement.
- Visualize dynamic conditions: Render optional conditions as selectable items and fill in parameters by type, making it easy to enumerate combinations.
- Reconstruct cross-cutting semantics: Pre-compute runtime-injected behaviors such as logical deletion, multi-tenant isolation, and pagination according to the framework’s semantics.
- Runtime channel (optional enhancement): After the application starts, a JDBC-layer proxy collects real parameters, elapsed time, and affected row counts, highlights slow queries, and lets you jump back to the call site; this approach does not depend on log text format and is more robust.
One boundary must be stated honestly: static preview is not the runtime result. Static constants may be inlined, pagination literals are computed directly, and dynamic SQL may still differ from runtime behavior in extreme branches. It is therefore better suited to “change a condition and immediately see its shape” than to replacing production verification.
5. How to Choose Among the Three Paths
| Goal | Recommended path |
|---|---|
| Scaffold CRUD for a new project or a legacy table | Path 1: structure-driven generation |
| Confirm what actually ran in production | Path 2: log reconstruction |
| Preview statement shape immediately after changing conditions | Path 3: static preview |
| Need real parameters and performance data | Path 3’s runtime collection capability |
The three are not mutually exclusive: generation answers “does it exist”, preview answers “is it correct”, and logs plus runtime collection answer “what actually ran in production”.
6. A Rational View of “AI-Generated SQL”
Pasting a table schema into a general-purpose AI coding tool and describing the requirement to get SQL is a common practice, but it has structural flaws: the model’s output is based on guesses about a “typical schema” rather than your real schema and constraints, which leads to repeated rework. A more sound engineering approach is:
- Give the tool real metadata as context (fields, types, indexes, constraints);
- After generation, always run syntax validation and execution plan analysis;
- Use parameterized binding for dynamic conditions and eliminate string concatenation.
In general practice on cloud platforms such as Baidu AI Cloud, this capability is usually decomposed into a combination of metadata management, logging services, monitoring and alerting, and database tooling, rather than relying on a single “one-click generate” feature.
7. Recommendations for Engineering Adoption
- Layered governance: Leave templated CRUD to generators, and keep human review for complex queries.
- Verifiability first: Any generated result should be executable with one click or expose its execution plan.
- Mandatory parameterization: All external input goes through bound variables.
- Observability as the fallback: Slow-query collection and call-stack tracing serve as the final source of truth.
- Commit the artifacts: Generated mapping files belong in version control, so they do not “exist only in someone’s IDE”.
8. Conclusion
The point of automatic SQL generation is not typing less, but closing the loop on the production, preview, reconstruction, and verification of SQL. Structure-driven generation handles volume, static preview handles immediate confirmation, and runtime collection plus log reconstruction handle factual verification. Making the capability boundaries of each path explicit is what keeps efficiency gains from coming at the cost of correctness.
