Engineering Metadata Delivery for LLMs on Large Databases

    This article presents an engineering approach for organizing and delivering metadata from large databases to LLMs for natural-language query and SQL generation. It covers layered metadata modeling, offline indexing, online candidate schema retrieval, prompt assembly, SQL validation and feedback, caching, cost evaluation, and security controls. The goal is to supply the right schema information at the right time rather than sending an entire database schema with every request.

    Engineering Metadata Delivery for LLMs on Large Databases

    When a database is small, providing table names, columns, types, comments, and relationships to an LLM in a single request is often enough to produce usable SQL. But when a database contains thousands of tables and metadata reaches tens of MB, this approach quickly hits two hard constraints: limited context length and unacceptable token cost from sending massive amounts of information with every request. The core problem is therefore not “dumping the entire database into the model,” but “supplying the right schema information to the model on demand at the right time.”

    1. Define What to Feed: Metadata First, Sample Data with Caution

    In natural-language query scenarios, the main thing to feed an LLM is not full business data, but metadata that helps the model understand query semantics. This includes table names, column names, data types, comments, primary and foreign keys, indexes, partitions, table relationships, business term mappings, and a small amount of masked sample values and statistics. Providing full business data is both unnecessary and a security risk.

    Metadata should also be layered. Database-level information is suitable for subject-domain summaries; table-level information is suitable for “table cards”; column-level information is suitable after candidate tables are identified; sample values should be used only when a column has a small enumeration and the data has been masked. This controls context size and prevents irrelevant tables from interfering with the model’s judgment.

    2. Build a Layered Metadata Knowledge Base Offline

    A practical design organizes metadata into four layers:

    1. Database summary layer: Summaries by business domain, table count, naming conventions, and common table families, used for question routing.
    2. Table card layer: A structured card for each table, including table name, display name, purpose, domain, primary key, foreign keys, commonly used columns, update frequency, data volume level, and permission tags.
    3. Column detail layer: Column name, type, comment, enumeration description, sensitivity flag, and whether the column is commonly used for filtering or aggregation.
    4. Relationship and terminology layer: Primary and foreign key relationships, fact-table and dimension-table relationships, business metric definitions, and synonym mappings, such as the correspondence between “client” and “customer.”

    The offline stage should also build retrieval indexes. Table names and comments can use keyword indexes; table cards and column descriptions can use vector indexes; the relationship graph is used to expand candidate tables. Permission tags must participate in filtering during retrieval so that tables the user is not authorized to access are not provided to the model.

    Example pseudocode:

    1. function build_metadata_knowledge_base(db):
    2. tables = collect_tables(db)
    3. for table in tables:
    4. card = {
    5. "name": table.name,
    6. "comment": table.comment,
    7. "domain": infer_domain(table),
    8. "columns": collect_columns(table),
    9. "primary_key": table.primary_key,
    10. "foreign_keys": table.foreign_keys,
    11. "sensitive_tags": detect_sensitive(table),
    12. "sample_stats": safe_stats(table)
    13. }
    14. store_table_card(card)
    15. index_keywords(card.name, card.comment)
    16. index_vector(card.summary)
    17. build_relation_graph(tables)
    18. build_business_term_mapping()

    3. Retrieve Candidate Schemas On Demand Online

    After a user asks a natural-language question, do not insert the entire database metadata into the prompt. Instead, run a retrieve, filter, rerank, and expand process. First, use keywords from the question to retrieve candidate tables; then use vector search to retrieve semantically similar table cards; next, filter by user permissions, business domain, and freshness; finally, expand one or two hops through the relationship graph to ensure that tables required for JOINs are included.

    Set a token budget for candidate tables, for example, keeping only the most relevant top tables and necessary columns. For ambiguous columns, inject column comments and a small number of masked enumeration values. If the question involves metric definitions, inject business term mappings first rather than letting the model guess.

    1. function retrieve_schema(question, user):
    2. keyword_tables = keyword_search(question)
    3. vector_tables = vector_search(question)
    4. candidates = merge(keyword_tables, vector_tables)
    5. candidates = filter_by_permission(candidates, user)
    6. candidates = rerank(question, candidates)
    7. expanded = expand_by_relations(candidates, max_hops=1)
    8. return select_within_token_budget(expanded)

    4. Assemble Prompts with Constraints, Relationships, and Output Format

    The prompt should include system constraints, candidate schemas, table relationships, business definitions, examples, and output requirements. System constraints should clearly specify read-only queries, prohibit full table scans, require explicit returned columns, and require standard SQL. Candidate schemas should be expressed in a compact structure to avoid repetitive comments. Table relationships should include only the parts relevant to candidate tables. The output format can ask the model to outline its query logic first and then provide the SQL, which makes validation easier.

    1. You are a SQL generation assistant. Generate read-only queries only based on the following schema.
    2. Candidate tables:
    3. - order_main(order_id, customer_id, amount, status, create_time)
    4. - customer(customer_id, name, region)
    5. Relationships:
    6. order_main.customer_id -> customer.customer_id
    7. Business definition:
    8. "valid order" means status in ('PAID','SHIPPED')
    9. Requirements:
    10. 1. Output only one SQL statement;
    11. 2. Do not use SELECT *;
    12. 3. Time ranges must use parameter placeholders;
    13. 4. If information is insufficient, state the missing information first.

    5. SQL Validation, Execution Feedback, and Caching

    SQL generated by the model must not be executed directly. First perform static validation: syntax, whether tables and columns exist, whether the query is read-only, whether it contains dangerous operations, and whether it hits permission tags. Then evaluate cost through an execution plan or a rate-limited trial run. Execution results can be summarized and returned to the model for self-repair, but retries should be limited. Frequently asked questions can cache the “question, candidate schema, SQL template” combination to reduce token consumption and response latency.

    6. Cost, Evaluation, and Security Governance

    Production deployment should track three types of metrics: retrieval hit rate, SQL executability rate, and result correctness rate. It should also monitor average token count, number of candidate tables, retry count, and cache hit rate. For security, enforce least privilege, column masking, audit logs, read-only accounts, timeouts, and row limits. Only by connecting metadata governance, retrieval, prompting, and validation into a closed loop can an LLM reliably assist with queries on large databases instead of being overwhelmed by massive schemas.