Virtual Answersets¶
Virtual answersets bring in-memory descriptive statistics, summary footers, computed columns, server-side SQL pushdown, and volatile-table materialization directly into vim-teradata result buffers without unnecessary database round trips.
Overview¶
Working with query results often requires quick aggregations, ad-hoc calculations, or "what-if" modeling:
- What is the total revenue and average margin of this filtered view?
- How many distinct customers or NULL values appear in this column?
- Can I add a computed (price - cost) * qty column without re-writing the SQL query?
- Can I verify totals against the entire database table when the result grid is truncated by retlimit?
- Can I safely edit data in a sandboxed copy to test business logic without touching production tables?
vim-teradata delivers these capabilities through a tiered approach:
1. In-Memory Lua Engine: Instant client-side aggregations, selection stats popups, and Tree-sitter parsed computed columns running directly on loaded cells.
2. SQL Pushdown (gD & :TDColPush): Automatic SQL rewriting into derived queries executed against Teradata for exact full-table calculations and turning virtual columns into database columns.
3. Volatile Table Materialization (:TDMaterialize): Caching the full answerset into a session volatile table for fast, isolated "what-if" edits and queries inside a persistent session (:TDSession).
┌────────────────────────────────────────────────────────┐
│ Result Grid Buffer (nofile) │
├────────────────────────────────────────────────────────┤
│ CustomerId │ Amount │ Qty │ ƒ Margin (Computed Column) │
│ 1001 │ 45.00 │ 2 │ 12.50 │
│ 1002 │ 80.00 │ 1 │ 24.00 │
├────────────────────────────────────────────────────────┤
│ ── virt_lines summary footer (gS / gs) ─────────────── │
│ Σ: 2 rows │ 125.00 │ 3 │ 36.50 │
└────────────────────────────────────────────────────────┘
│ │
▼ (gD / :TDColPush) ▼ (:TDMaterialize)
┌──────────────────────┐ ┌──────────────────────┐
│ Teradata SQL │ │ Persistent Session │
│ Pushdown Engine │ │ Volatile Table │
│ (Derived Query) │ │ (VAS_<id> Sandboxed) │
└──────────────────────┘ └──────────────────────┘
Summary Footers (gS / gs)¶
Press gS (forward) or gs (backward) in any result buffer to cycle a virtual two-line summary footer anchored below the last data row:
$$\text{off} \longrightarrow \Sigma\text{ (sum)} \longrightarrow \bar{x}\text{ (avg)} \longrightarrow \downarrow\text{ (min)} \longrightarrow \uparrow\text{ (max)} \longrightarrow \text{# (count)} \longrightarrow \emptyset\text{ (nulls)} \longrightarrow \ne\text{ (distinct)}$$
Virtual Line Non-Intrusiveness¶
The footer is rendered using Neovim's virt_lines API in the TeradataVirtual highlight group. It does not insert actual text lines into the buffer:
- Line numbers and row counts remain accurate.
- Row filtering (<CR>), filter reset (u), and column removal (- / <BS>) operate smoothly.
- In-grid editing (<E>) and cell navigation work completely unaffected.
Filtering & Scope (footer_scope)¶
By default (virtual.footer_scope = "displayed"), footer statistics dynamically reflect only the currently visible rows matching active <CR> cell filters. If you remove filters with u, the footer immediately updates to encompass all loaded rows.
To always aggregate across all loaded rows regardless of in-grid filters, configure:
require('vim-teradata').setup({
virtual = {
footer_scope = "all",
},
})
Visual Quick-Calc (<leader>= / :TDCalc)¶
To inspect descriptive statistics for a subset of cells:
- Select cells in visual mode (
vfor characterwise,Vfor linewise, or<C-v>for blockwise). - Press
<leader>=(or execute:[range]TDCalc).
A floating popup appears at the cursor showing comprehensive statistics:
- count: Total number of selected cells.
- nulls: Count of NULL cells.
- sum: Sum of numeric values.
- avg: Arithmetic mean.
- min: Minimum value.
- max: Maximum value.
- distinct: Count of distinct non-null values.
When your selection spans multiple columns, the popup displays both pooled statistics across all selected cells and an itemized column-by-column breakdown.
Dismiss the popup by moving the cursor or pressing q or <Esc>.
Yank Statistics to Clipboard
Setting virtual.yank_quick_calc = true automatically copies a tab-separated line (sum\tavg\tmin\tmax) into the unnamed register "" whenever you trigger quick-calc, making it effortless to paste summaries into spreadsheets or notes.
Computed Virtual Columns (= / :TDCol)¶
You can append new calculated columns to the result grid on the fly without re-running or modifying your SQL query.
Press = in a result buffer, or run:
:TDCol margin = (price - cost) * qty
If the {name} = prefix is omitted, columns are named automatically (EXPR1, EXPR2, etc.). Virtual column headers are marked with ƒ (configurable via header_prefix).
Supported Scalar Syntax¶
Expressions are parsed using the Teradata Tree-sitter grammar and evaluated in Lua using Teradata SQL scalar semantics:
| Expression Category | Supported Syntax / Functions |
|---|---|
| Arithmetic | +, -, *, / (floating-point division), MOD, %, unary + / - |
| String Concatenation | \|\| (e.g. col_a \|\| ' - ' \|\| col_b) |
| Conditional & Branching | CASE [expr] WHEN ... THEN ... ELSE ... END |
| Comparison & Logic | =, <>, !=, <, <=, >, >=, AND, OR, NOT, IS [NOT] NULL, [NOT] BETWEEN, [NOT] IN (...), [NOT] LIKE |
| Math & Numeric | ABS, ROUND, TRUNC, CEILING, FLOOR, SQRT, LN, EXP, POWER, LEAST, GREATEST |
| Null Handling | COALESCE, NULLIF, ZEROIFNULL, NULLIFZERO |
| String Manipulation | UPPER, LOWER, TRIM, LENGTH / CHARACTER_LENGTH, SUBSTR / SUBSTRING, INDEX, POSITION, OREPLACE |
| Date & Time | EXTRACT(YEAR\|MONTH\|DAY FROM date_col), date1 - date2 (days between), date + n, date - n (YYYY-MM-DD or YY/MM/DD formats) |
| Type Conversions | CAST(x AS INTEGER\|DECIMAL(p,s)\|VARCHAR(n)\|DATE\|FLOAT) |
NULL and Division-by-Zero Handling¶
- Any arithmetic operation or concatenation with a
NULLoperand evaluates toNULL(rendered usingnull_token). - Division or modulo by zero safely evaluates to
NULLwithout crashing, and reports the number of affected rows in a warning message. - Floating-point calculations adhere to 64-bit IEEE-754 precision (~15 significant decimal digits).
Live "What-If" Recalculation¶
In edit mode (<E>), virtual columns are displayed with dimmed formatting and remain strictly read-only (they are never included in generated database UPDATE statements).
When you edit a source cell in the grid, all dependent virtual columns instantly recalculate live on screen. Pressing <C> cancels edits and restores original source and computed values.
Persistence across Sessions¶
When virtual.persist_columns = true (enabled by default), virtual column definitions are saved in <data_dir>/virtual_columns.json keyed by a normalized SHA-256 hash of the query. Re-running the query with :TDRerun (.) or opening it from history (:TDH) automatically restores your computed columns.
Managing Virtual Columns¶
:TDCol [{name} =] {expr}: Add or overwrite a computed column.:TDCol! {name}: Remove a computed column by name.:TDColEdit [{name}]: Open an interactive prompt pre-filled with the expression for{name}(or the virtual column under cursor).:TDCols: Open a scratch split listing all active virtual columns and their definitions (name = expr).
Server-Side SQL Pushdown (gD & :TDColPush)¶
Client-side Lua calculation is fast, but has two natural boundaries:
1. Truncated Result Sets: If a query returns more rows than retlimit (e.g. 100 rows), Lua only computes aggregates over the fetched sample.
2. High-Precision Decimal Arithmetic: Numbers requiring more than 15 significant digits may experience floating-point rounding in Lua.
When either condition occurs, the footer indicates the limitation: Σ (partial) or Σ (≈).
Exact Database Totals (gD)¶
Press gD in the result buffer to compute the exact aggregate in Teradata:
vim-teradatawraps your original base query in a derived table:SELECT SUM(vt."Amount"), AVG(vt."Qty") FROM ( <original query> ) AS vt ("CustomerId", "Amount", "Qty");- Any top-level
WITH ...(Common Table Expressions) orLOCKING ... FOR ACCESSclauses are hoisted outside the derived table. - Top-level
ORDER BYclauses are stripped to maximize database execution speed. - While Teradata executes, the footer displays
… computing in Teradata, updating toΣ dbupon completion.
[!NOTE] Client-side
<CR>row filters are not pushed down to the server. When viewing a filtered grid, the database total is labeledΣ db (unfiltered).
Pushing Computed Columns to Teradata (:TDColPush)¶
If you created computed virtual columns with :TDCol and want to materialize them as genuine database columns, run:
:TDColPush
vim-teradata translates your virtual expressions into Teradata SQL syntax against the derived table (vt."<COL>"), submits SELECT vt.*, <expr> AS "<NAME>" FROM ( ... ) AS vt, and displays the result in a brand-new grid split where the virtual columns are now regular database columns.
Volatile-Table Materialization (:TDMaterialize)¶
When working inside an open persistent session (:TDSession), you can materialize the entire result set into a private session volatile table.
In any result buffer belonging to a persistent session, run:
:TDMaterialize [table_name]
(If table_name is omitted, vim-teradata generates a unique name such as VAS_<id>.)
The plugin creates the table on the server:
CREATE VOLATILE TABLE <table_name> AS (
<original query>
) WITH DATA NO PRIMARY INDEX ON COMMIT PRESERVE ROWS;
Benefits of Materialization¶
- Instant SQL Pushdown: Once materialized, running
gDor:TDColPushqueries the volatile table directly (FROM <table_name>) rather than re-running the heavy base query. - UI Status Indicator: The grid hint line displays
[VT: <table_name>]. - Querying the Table: Run
:TDVQueryto switch to the session's SQL buffer withSELECT * FROM <table_name>;already inserted at the end of the buffer. - Teardown: Drop the table at any time with
:TDMaterialize!. Closing the persistent session (:TDSession!) automatically drops all session volatile tables.
Safe "What-If" In-Grid Editing¶
When experimenting with data transformations or forecasting scenarios, modifying live database tables can be dangerous. Materialized virtual answersets provide a sandboxed environment for safe in-grid edits.
Workflow: Editing the Volatile Copy¶
- Open a persistent session: Run
:TDSessionin your SQL buffer. - Execute your base query: Run
:TDOto produce a result grid. - Materialize into volatile table: In the result grid, run
:TDMaterialize. - Switch edit target: Run:
(or configure
:TDEditTarget volatilevirtual.edit_target = "volatile"). - Enter edit mode: Press
<E>. The status line indicates:-- EDIT MODE (VT VAS_1042) -- - Modify cells: In this mode, every column is editable (unlike production tables where primary keys or computed fields might be restricted).
- Stage & Save: Press
<S>. When prompted, confirm saving.vim-teradataissuesUPDATE <table_name> ...statements strictly against the volatile table. The underlying production table is never touched. - Inspect Results: Press
gDto see the updated database aggregates on your modified volatile data!
To switch back to targeting the real database table, run :TDEditTarget table.
Keymaps & Commands Reference¶
Buffer Keymaps (Result Grids)¶
| Keymap | Mode | Action | Description |
|---|---|---|---|
gS |
Normal | footer_next |
Cycle virtual summary footer forward (off → sum → avg → min → max → count → nulls → distinct). |
gs |
Normal | footer_prev |
Cycle virtual summary footer backward. |
gD |
Normal | footer_db |
Compute exact database totals via Teradata SQL pushdown (Σ db). |
<leader>= |
Visual | quick_calc |
Open floating quick-calc popup for the selected cells. |
= |
Normal | add_column |
Prompt to add a computed virtual column (:TDCol). |
Commands¶
| Command | Buffer Scope | Description |
|---|---|---|
:[range]TDCalc |
Result buffer | Open floating quick-calc popup for selected cells or line range. |
:TDCol [{name} =] {expr} |
Result buffer | Add or update a computed virtual column. |
:TDCol! {name} |
Result buffer | Remove a computed virtual column. |
:TDColEdit [{name}] |
Result buffer | Interactively edit the expression for virtual column {name}. |
:TDCols |
Result buffer | Display all active virtual columns in a scratch split. |
:TDColPush |
Result buffer | Push virtual columns to Teradata as a derived table query in a new split. |
:TDMaterialize [name] |
Result buffer | Materialize answerset into a session volatile table (VAS_<id>). |
:TDMaterialize! |
Result buffer | Drop the materialized volatile table. |
:TDVQuery |
Result buffer | Append SELECT * FROM <name>; into the session's SQL buffer. |
:TDEditTarget [volatile\|table] |
Result buffer | Toggle or set in-grid edit destination (volatile or table). |
Configuration¶
Configure virtual answersets via the virtual table in setup():
require('vim-teradata').setup({
virtual = {
footer_default = 'off', -- initial footer mode on grid open
footer_scope = 'displayed', -- 'displayed' (filtered rows) or 'all'
yank_quick_calc = false, -- yank 'sum\tavg\tmin\tmax' on quick-calc
persist_columns = true, -- persist virtual columns per query hash
header_prefix = 'ƒ ', -- prefix for virtual column headers
engine = 'auto', -- 'auto', 'lua', or 'db'
edit_target = 'table', -- default edit target ('table' or 'volatile')
keymaps = {
footer_next = 'gS',
footer_prev = 'gs',
footer_db = 'gD',
quick_calc = '<leader>=',
add_column = '=',
},
},
})
See Configuration Reference: virtual for full option specifications.