Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-editor): one query plan visualizer for PostgreSQL, SQL Server and Spanner (#21448)

Danny Xuc41e89c42c4b
diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.go
index 935f9832c6..06129c76c5 100644
--- a/backend/plugin/db/spanner/spanner.go
+++ b/backend/plugin/db/spanner/spanner.go
@@ -597,7 +597,7 @@ func (d *Driver) explainStatement(ctx context.Context, statement string) ([]*v1p
for _, stmt := range stmts {
startTime := time.Now()
queryResult, err := func() (*v1pb.QueryResult, error) {
- plan, err := d.client.Single().AnalyzeQuery(ctx, spanner.NewStatement(stmt))
+ plan, err := d.analyzeStatement(ctx, stmt)
if err != nil {
return nil, err
}
@@ -634,6 +634,22 @@ func (d *Driver) explainStatement(ctx context.Context, statement string) ([]*v1p
return results, nil
}
+// analyzeStatement returns the plan Spanner chooses for statement without
+// running it. Spanner rejects DML in a single-use transaction, so anything
+// QueryConn would not read in one is analyzed in a read-write transaction that
+// is rolled back.
+func (d *Driver) analyzeStatement(ctx context.Context, statement string) (*sppb.QueryPlan, error) {
+ if util.IsSelect(statement) {
+ return d.client.Single().AnalyzeQuery(ctx, spanner.NewStatement(statement))
+ }
+ txn, err := spanner.NewReadWriteStmtBasedTransaction(ctx, d.client)
+ if err != nil {
+ return nil, err
+ }
+ defer txn.Rollback(ctx)
+ return txn.AnalyzeQuery(ctx, spanner.NewStatement(statement))
+}
+
// PlanNode represents a node in the Spanner query plan for JSON serialization.
type PlanNode struct {
Index int32 `json:"index"`
diff --git a/backend/plugin/db/spanner/spanner_test.go b/backend/plugin/db/spanner/spanner_test.go
index 5c64e0c6ec..b44750fb8c 100644
--- a/backend/plugin/db/spanner/spanner_test.go
+++ b/backend/plugin/db/spanner/spanner_test.go
@@ -1,10 +1,16 @@
package spanner
import (
+ "context"
+ "fmt"
"math"
+ "os"
"testing"
"time"
+ "cloud.google.com/go/spanner"
+ spannerdb "cloud.google.com/go/spanner/admin/database/apiv1"
+ "cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/structpb"
@@ -14,6 +20,60 @@ import (
"github.com/bytebase/bytebase/backend/plugin/db/util"
)
+// TestExplainDMLWithoutRunningIt needs a Spanner that plans queries, which CI
+// cannot provide and the emulator does not do. Spanner Omni works: the client
+// reaches it without TLS or credentials through SPANNER_EMULATOR_HOST, and
+// SPANNER_TEST_DATABASE names a database in it as
+// projects/default/instances/default/databases/d.
+func TestExplainDMLWithoutRunningIt(t *testing.T) {
+ database := os.Getenv("SPANNER_TEST_DATABASE")
+ if os.Getenv("SPANNER_EMULATOR_HOST") == "" || database == "" {
+ t.Skip("set SPANNER_EMULATOR_HOST and SPANNER_TEST_DATABASE to run against Spanner Omni")
+ }
+ a := require.New(t)
+ ctx := context.Background()
+
+ admin, err := spannerdb.NewDatabaseAdminClient(ctx)
+ a.NoError(err)
+ defer admin.Close()
+ table := fmt.Sprintf("ExplainDML%d", time.Now().UnixNano())
+ updateDDL := func(statement string) {
+ op, err := admin.UpdateDatabaseDdl(ctx, &databasepb.UpdateDatabaseDdlRequest{
+ Database: database,
+ Statements: []string{statement},
+ })
+ a.NoError(err)
+ a.NoError(op.Wait(ctx))
+ }
+ updateDDL(fmt.Sprintf("CREATE TABLE %s (Id INT64 NOT NULL, Total INT64) PRIMARY KEY (Id)", table))
+ defer updateDDL(fmt.Sprintf("DROP TABLE %s", table))
+
+ client, err := spanner.NewClient(ctx, database)
+ a.NoError(err)
+ defer client.Close()
+ _, err = client.Apply(ctx, []*spanner.Mutation{
+ spanner.Insert(table, []string{"Id", "Total"}, []any{int64(1), int64(10)}),
+ })
+ a.NoError(err)
+
+ driver := &Driver{client: client}
+ results, err := driver.explainStatement(ctx, fmt.Sprintf(
+ "UPDATE %[1]s SET Total = Total + 1 WHERE Id = 1; SELECT Total FROM %[1]s", table,
+ ))
+ a.NoError(err)
+ a.Len(results, 2)
+ for _, result := range results {
+ a.Empty(result.Error, result.Statement)
+ a.Contains(result.Rows[0].Values[0].GetStringValue(), `"planNodes"`)
+ }
+
+ row, err := client.Single().ReadRow(ctx, table, spanner.Key{int64(1)}, []string{"Total"})
+ a.NoError(err)
+ var total int64
+ a.NoError(row.Column(0, &total))
+ a.Equal(int64(10), total)
+}
+
func TestGetDatabaseFromDSN(t *testing.T) {
tests := []struct {
dsn string
diff --git a/frontend/explain-visualizer.html b/frontend/explain-visualizer.html
index 9d5920f437..4a1c5c7ea0 100644
--- a/frontend/explain-visualizer.html
+++ b/frontend/explain-visualizer.html
@@ -5,7 +5,7 @@
<link rel="icon" type="image/*" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light only" />
- <title>Bytebase - PostgreSQL Explain Visualizer</title>
+ <title>Bytebase - Query Plan</title>
</head>
<body class="text-base">
diff --git a/frontend/package.json b/frontend/package.json
index 199bac86f4..180edaeb64 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -46,7 +46,6 @@
"events": "^3.3.0",
"file-saver": "^2.0.5",
"highlight.js": "11.11.1",
- "html-query-plan": "^2.6.1",
"html-to-image": "^1.11.13",
"i18next": "^26.0.10",
"immer": "^11.1.8",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index c3d860cc75..593040b8e6 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -104,9 +104,6 @@ importers:
highlight.js:
specifier: 11.11.1
version: 11.11.1
- html-query-plan:
- specifier: ^2.6.1
- version: 2.6.1
html-to-image:
specifier: ^1.11.13
version: 1.11.13
@@ -2557,9 +2554,6 @@ packages:
resolution: {integrity: sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==}
- resolution: {integrity: sha512-8LoHDSOFGu4RKXit8we3ydE5W5qJFYg/hKtCfrV+hUnqhOssVDAgaxoJ2NNyF+eDkeXaicbJ/FBhz2/NmI4KuQ==}
-
resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}
@@ -5909,8 +5903,6 @@ snapshots:
-
diff --git a/frontend/public/libs/qp.min.js b/frontend/public/libs/qp.min.js
deleted file mode 100755
index 5837b2077f..0000000000
--- a/frontend/public/libs/qp.min.js
+++ /dev/null
@@ -1,11 +0,0 @@
-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.QP=e():t.QP=e()}(window,function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=2)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1);function i(t,e){for(var n=[],r=0;r<t.length;r++)t[r].nodeName===e&&n.push(t[r]);return n}function s(t,e,n){var r=t.querySelector('[StatementId="'+e+'"]');if(!n)return r;for(var i=r.getElementsByTagName("RelOp"),s=0;s<i.length;s++){var a=i[s];if(a.attributes.NodeId&&a.attributes.NodeId.value==n)return a}return null}var a=function(){function t(t){if(this.element=t,!this.element)throw new Error("element cannot be null");if("RelOp"!=this.element.tagName)throw new Error("element must be a RelOp element")}return Object.defineProperty(t.prototype,"estimatedRows",{get:function(){return parseFloat(this.element.attributes.EstimateRows.value)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"estimatedRowSize",{get:function(){return parseInt(this.element.attributes.AvgRowSize.value)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"estimatedDataSize",{get:function(){return Math.round(this.estimatedRowSize*this.estimatedRows)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"runtimeCountersPerThread",{get:function(){var t=i(this.element.childNodes,"RunTimeInformation");return 0==t.length?[]:i(t[0].childNodes,"RunTimeCountersPerThread")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"actualRows",{get:function(){return 0==this.runtimeCountersPerThread.length?null:this.runtimeCountersPerThread.reduce(function(t,e){return t+parseFloat(e.attributes.ActualRows.value)},0)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"actualRowsRead",{get:function(){return 0!=this.runtimeCountersPerThread.length&&this.runtimeCountersPerThread[0].attributes.ActualRowsRead?this.runtimeCountersPerThread.reduce(function(t,e){return t+parseFloat(e.attributes.ActualRowsRead.value)},0):null},enumerable:!0,configurable:!0}),t}();e.RelOp=a;var l=function(){function t(t){if(this.element=t,!this.element)throw new Error("element cannot be null");if("qp-node"!=this.element.className)throw new Error("element must have class qp-node")}return Object.defineProperty(t.prototype,"children",{get:function(){return[].slice.call(r.findAncestor(this.element,"qp-tr").children[1].children).map(function(e){return new t(e.children[0].children[0].children[0])})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeId",{get:function(){var t=this.element.attributes["data-node-id"];return t&&t.value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"statementId",{get:function(){return r.findAncestorP(this.element,function(t){return t.hasAttribute("data-statement-id")}).attributes["data-statement-id"].value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"queryPlanXml",{get:function(){var t=r.findAncestor(this.element,"qp-root");return null==t?null:t.parentElement.xml},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeXml",{get:function(){return null==this.queryPlanXml?null:s(this.queryPlanXml,this.statementId,this.nodeId)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relOp",{get:function(){var t=this.nodeXml;return t&&"RelOp"==t.tagName?new a(this.nodeXml):null},enumerable:!0,configurable:!0}),t}();e.Node=l;var o=function(){function t(t){if(this.element=t,!this.element)throw new Error("element cannot be null");if("polyline"!=this.element.nodeName)throw new Error("element must be a polyline")}return Object.defineProperty(t.prototype,"nodeId",{get:function(){var t=this.element.attributes["data-node-id"];return t&&t.value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"statementId",{get:function(){return this.element.attributes["data-statement-id"].value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"queryPlanXml",{get:function(){return r.findAncestor(this.element,"qp-root").parentElement.xml},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeXml",{get:function(){return s(this.queryPlanXml,this.statementId,this.nodeId)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"relOp",{get:function(){var t=this.nodeXml;return t&&"RelOp"==t.tagName?new a(this.nodeXml):null},enumerable:!0,configurable:!0}),t}();e.Line=o},function(t,e,n){"use strict";function r(t,e){if(null===t)return null;for(;(t=t.parentElement)&&t&&!e(t););return t}function i(t,e){return(" "+t.className+" ").indexOf(" "+e+" ")>-1}Object.defineProperty(e,"__esModule",{value:!0}),e.findAncestor=function(t,e){return r(t,function(t){return i(t,e)})},e.findAncestorP=r,e.hasClass=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(3),i=n(4);e.drawLines=i.drawLines;var s=n(6),a=n(0);e.Node=a.Node;var l=n(7);e.showPlan=function(t,e,n){n=function(t,e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}(n,{jsTooltips:!0}),r.setContentsUsingXslt(t,e,l),t.xml=(new DOMParser).parseFromString(e,"text/xml"),i.drawLines(t),n.jsTooltips&&s.initTooltip(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setContentsUsingXslt=function(t,e,n){if(window.ActiveXObject||"ActiveXObject"in window){var r=new ActiveXObject("Microsoft.xmlDOM");r.async=!1,r.loadXML(n);var i=new ActiveXObject("Microsoft.xmlDOM");i.async=!1,i.loadXML(e);var s=i.transformNode(r);t.innerHTML=s}else if(document.implementation&&document.implementation.createDocument){var a=new DOMParser,l=new XSLTProcessor;l.importStylesheet(a.parseFromString(n,"text/xml")),s=l.transformToFragment(a.parseFromString(e,"text/xml"),document),t.innerHTML="",t.appendChild(s)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(5),i=n(0),s=5;function a(t,e){for(var n=[],r=-(t.reduce(function(t,e){return t+e},0)+(t.length-1)*e)/2,i=0;i<t.length;i++){var s=r+t[i];n.push((s+r)/2),r=s+e}return n}function l(t){var e=0;return null!=t.relOp&&(e=null==t.relOp.actualRows?t.relOp.estimatedRows:t.relOp.actualRows),Math.max(2,Math.min(Math.floor(Math.log(e>0?e:1)),12))}function o(t,e,n){var r=n.children,i=r.map(l);!function(t,e){t.element.parentElement.parentElement.style.paddingRight=e+"px"}(n,i.reduce(function(t,e){return t+e},0)+s*(r.length-1));for(var o=a(i,s),u=0;u<r.length;u++)h(t,e,n,r[u],i[u],o[u])}function h(t,e,n,r,i,s){var a=n.element.getBoundingClientRect(),l=r.element.getBoundingClientRect(),o=a.right,h=(a.top+a.bottom)/2,c=l.left,m=(l.top+l.bottom)/2;Math.abs(m-h)<5&&(m=h);var p=o/2+c/2;!function(t,e,n,r,i,s,a){var l=u(e,n,r,i),o=t.polyline(l).fill("#E3E3E3").stroke({color:"#505050",width:.5}).data("statement-id",a);s&&o.data("node-id",s)}(t,{x:o-e.left+1,y:h-e.top+s},{x:l.left-e.left-1,y:m-e.top},p-e.left-s,i,r.nodeId,r.statementId)}function u(t,e,n,r){var i=r/2;return[[t.x,t.y],[t.x+i+2,t.y-(i+2)],[t.x+i+2,t.y-i],[n+(t.y<=e.y?i:-i),t.y-i],[n+(t.y<=e.y?i:-i),e.y-i],[e.x,e.y-i],[e.x,e.y+i],[n+(t.y<=e.y?-i:i),e.y+i],[n+(t.y<=e.y?-i:i),t.y+i],[t.x+i+2,t.y+i],[t.x+i+2,t.y+i+2],[t.x,t.y]]}e.drawLines=function(t){for(var e=t.querySelector(".qp-root"),n=r(e),s=e.getBoundingClientRect(),a=e.querySelectorAll(".qp-node"),l=0;l<a.length;l++)o(n,s,new i.Node(a[l]))},e.thicknessesToOffsets=a,e.nodeToThickness=l,e.arrowPath=u},function(t,e,n){var r;
-/*!
-* svg.js - A lightweight library for manipulating and animating SVG.
-* @version 2.6.2
-* https://svgdotjs.github.io/
-*
-* @copyright Wout Fierens <[email protected]>
-* @license MIT
-*
-* BUILT: Mon Jun 05 2017 11:33:23 GMT+0200 (Mitteleuropäische Sommerzeit)
-*/!function(i,s){void 0===(r=function(){return function(t,e){var n=this.SVG=function(t){if(n.supported)return t=new n.Doc(t),n.parser.draw||n.prepare(),t};if(n.ns="http://www.w3.org/2000/svg",n.xmlns="http://www.w3.org/2000/xmlns/",n.xlink="http://www.w3.org/1999/xlink",n.svgjs="http://svgjs.com/svgjs",n.supported=!!e.createElementNS&&!!e.createElementNS(n.ns,"svg").createSVGRect,!n.supported)return!1;n.did=1e3,n.eid=function(t){return"Svgjs"+u(t)+n.did++},n.create=function(t){var n=e.createElementNS(this.ns,t);return n.setAttribute("id",this.eid(t)),n},n.extend=function(){var t,e,r,i;for(t=[].slice.call(arguments),e=t.pop(),i=t.length-1;i>=0;i--)if(t[i])for(r in e)t[i].prototype[r]=e[r];n.Set&&n.Set.inherit&&n.Set.inherit()},n.invent=function(t){var e="function"==typeof t.create?t.create:function(){this.constructor.call(this,n.create(t.create))};return t.inherit&&(e.prototype=new t.inherit),t.extend&&n.extend(e,t.extend),t.construct&&n.extend(t.parent||n.Container,t.construct),e},n.adopt=function(e){return e?e.instance?e.instance:((r="svg"==e.nodeName?e.parentNode instanceof t.SVGElement?new n.Nested:new n.Doc:"linearGradient"==e.nodeName?new n.Gradient("linear"):"radialGradient"==e.nodeName?new n.Gradient("radial"):n[u(e.nodeName)]?new(n[u(e.nodeName)]):new n.Element(e)).type=e.nodeName,r.node=e,e.instance=r,r instanceof n.Doc&&r.namespace().defs(),r.setData(JSON.parse(e.getAttribute("svgjs:data"))||{}),r):null;var r},n.prepare=function(){var t=e.getElementsByTagName("body")[0],r=(t?new n.Doc(t):n.adopt(e.documentElement).nested()).size(2,0);n.parser={body:t||e.documentElement,draw:r.style("opacity:0;position:absolute;left:-100%;top:-100%;overflow:hidden").node,poly:r.polyline().node,path:r.path().node,native:n.create("svg")}},n.parser={native:n.create("svg")},e.addEventListener("DOMContentLoaded",function(){n.parser.draw||n.prepare()},!1),n.regex={numberAndUnit:/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,hex:/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,rgb:/rgb\((\d+),(\d+),(\d+)\)/,reference:/#([a-z0-9\-_]+)/i,transforms:/\)\s*,?\s*/,whitespace:/\s/g,isHex:/^#[a-f0-9]{3,6}$/i,isRgb:/^rgb\(/,isCss:/[^:]+:[^;]+;?/,isBlank:/^(\s+)?$/,isNumber:/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,isPercent:/^-?[\d\.]+%$/,isImage:/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,delimiter:/[\s,]+/,hyphen:/([^e])\-/gi,pathLetters:/[MLHVCSQTAZ]/gi,isPathLetter:/[MLHVCSQTAZ]/i,numbersWithDots:/((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi,dots:/\./g},n.utils={map:function(t,e){var n,r=t.length,i=[];for(n=0;n<r;n++)i.push(e(t[n]));return i},filter:function(t,e){var n,r=t.length,i=[];for(n=0;n<r;n++)e(t[n])&&i.push(t[n]);return i},radians:function(t){return t%360*Math.PI/180},degrees:function(t){return 180*t/Math.PI%360},filterSVGElements:function(e){return this.filter(e,function(e){return e instanceof t.SVGElement})}},n.defaults={attrs:{"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","font-size":16,"font-family":"Helvetica, Arial, sans-serif","text-anchor":"start"}},n.Color=function(t){var e;this.r=0,this.g=0,this.b=0,t&&("string"==typeof t?n.regex.isRgb.test(t)?(e=n.regex.rgb.exec(t.replace(n.regex.whitespace,"")),this.r=parseInt(e[1]),this.g=parseInt(e[2]),this.b=parseInt(e[3])):n.regex.isHex.test(t)&&(e=n.regex.hex.exec(function(t){return 4==t.length?["#",t.substring(1,2),t.substring(1,2),t.substring(2,3),t.substring(2,3),t.substring(3,4),t.substring(3,4)].join(""):t}(t)),this.r=parseInt(e[1],16),this.g=parseInt(e[2],16),this.b=parseInt(e[3],16)):"object"==typeof t&&(this.r=t.r,this.g=t.g,this.b=t.b))},n.extend(n.Color,{toString:function(){return this.toHex()},toHex:function(){return"#"+c(this.r)+c(this.g)+c(this.b)},toRgb:function(){return"rgb("+[this.r,this.g,this.b].join()+")"},brightness:function(){return this.r/255*.3+this.g/255*.59+this.b/255*.11},morph:function(t){return this.destination=new n.Color(t),this},at:function(t){return this.destination?(t=t<0?0:t>1?1:t,new n.Color({r:~~(this.r+(this.destination.r-this.r)*t),g:~~(this.g+(this.destination.g-this.g)*t),b:~~(this.b+(this.destination.b-this.b)*t)})):this}}),n.Color.test=function(t){return t+="",n.regex.isHex.test(t)||n.regex.isRgb.test(t)},n.Color.isRgb=function(t){return t&&"number"==typeof t.r&&"number"==typeof t.g&&"number"==typeof t.b},n.Color.isColor=function(t){return n.Color.isRgb(t)||n.Color.test(t)},n.Array=function(t,e){0==(t=(t||[]).valueOf()).length&&e&&(t=e.valueOf()),this.value=this.parse(t)},n.extend(n.Array,{morph:function(t){if(this.destination=this.parse(t),this.value.length!=this.destination.length){for(var e=this.value[this.value.length-1],n=this.destination[this.destination.length-1];this.value.length>this.destination.length;)this.destination.push(n);for(;this.value.length<this.destination.length;)this.value.push(e)}return this},settle:function(){for(var t=0,e=this.value.length,n=[];t<e;t++)-1==n.indexOf(this.value[t])&&n.push(this.value[t]);return this.value=n},at:function(t){if(!this.destination)return this;for(var e=0,r=this.value.length,i=[];e<r;e++)i.push(this.value[e]+(this.destination[e]-this.value[e])*t);return new n.Array(i)},toString:function(){return this.value.join(" ")},valueOf:function(){return this.value},parse:function(t){return t=t.valueOf(),Array.isArray(t)?t:this.split(t)},split:function(t){return t.trim().split(n.regex.delimiter).map(parseFloat)},reverse:function(){return this.value.reverse(),this},clone:function(){var t=new this.constructor;return t.value=function t(e){var n=e.slice(0);for(var r=n.length;r--;)Array.isArray(n[r])&&(n[r]=t(n[r]));return n}(this.value),t}}),n.PointArray=function(t,e){n.Array.call(this,t,e||[[0,0]])},n.PointArray.prototype=new n.Array,n.PointArray.prototype.constructor=n.PointArray,n.extend(n.PointArray,{toString:function(){for(var t=0,e=this.value.length,n=[];t<e;t++)n.push(this.value[t].join(","));return n.join(" ")},toLine:function(){return{x1:this.value[0][0],y1:this.value[0][1],x2:this.value[1][0],y2:this.value[1][1]}},at:function(t){if(!this.destination)return this;for(var e=0,r=this.value.length,i=[];e<r;e++)i.push([this.value[e][0]+(this.destination[e][0]-this.value[e][0])*t,this.value[e][1]+(this.destination[e][1]-this.value[e][1])*t]);return new n.PointArray(i)},parse:function(t){var e=[];if(t=t.valueOf(),Array.isArray(t)){if(Array.isArray(t[0]))return t}else t=t.trim().split(n.regex.delimiter).map(parseFloat);t.length%2!=0&&t.pop();for(var r=0,i=t.length;r<i;r+=2)e.push([t[r],t[r+1]]);return e},move:function(t,e){var n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(var r=this.value.length-1;r>=0;r--)this.value[r]=[this.value[r][0]+t,this.value[r][1]+e];return this},size:function(t,e){var n,r=this.bbox();for(n=this.value.length-1;n>=0;n--)r.width&&(this.value[n][0]=(this.value[n][0]-r.x)*t/r.width+r.x),r.height&&(this.value[n][1]=(this.value[n][1]-r.y)*e/r.height+r.y);return this},bbox:function(){return n.parser.poly.setAttribute("points",this.toString()),n.parser.poly.getBBox()}});for(var r={M:function(t,e,n){return e.x=n.x=t[0],e.y=n.y=t[1],["M",e.x,e.y]},L:function(t,e){return e.x=t[0],e.y=t[1],["L",t[0],t[1]]},H:function(t,e){return e.x=t[0],["H",t[0]]},V:function(t,e){return e.y=t[0],["V",t[0]]},C:function(t,e){return e.x=t[4],e.y=t[5],["C",t[0],t[1],t[2],t[3],t[4],t[5]]},S:function(t,e){return e.x=t[2],e.y=t[3],["S",t[0],t[1],t[2],t[3]]},Q:function(t,e){return e.x=t[2],e.y=t[3],["Q",t[0],t[1],t[2],t[3]]},T:function(t,e){return e.x=t[0],e.y=t[1],["T",t[0],t[1]]},Z:function(t,e,n){return e.x=n.x,e.y=n.y,["Z"]},A:function(t,e){return e.x=t[5],e.y=t[6],["A",t[0],t[1],t[2],t[3],t[4],t[5],t[6]]}},i="mlhvqtcsaz".split(""),s=0,a=i.length;s<a;++s)r[i[s]]=function(t){return function(e,n,i){if("H"==t)e[0]=e[0]+n.x;else if("V"==t)e[0]=e[0]+n.y;else if("A"==t)e[5]=e[5]+n.x,e[6]=e[6]+n.y;else for(var s=0,a=e.length;s<a;++s)e[s]=e[s]+(s%2?n.y:n.x);return r[t](e,n,i)}}(i[s].toUpperCase());n.PathArray=function(t,e){n.Array.call(this,t,e||[["M",0,0]])},n.PathArray.prototype=new n.Array,n.PathArray.prototype.constructor=n.PathArray,n.extend(n.PathArray,{toString:function(){return function(t){for(var e=0,n=t.length,r="";e<n;e++)r+=t[e][0],null!=t[e][1]&&(r+=t[e][1],null!=t[e][2]&&(r+=" ",r+=t[e][2],null!=t[e][3]&&(r+=" ",r+=t[e][3],r+=" ",r+=t[e][4],null!=t[e][5]&&(r+=" ",r+=t[e][5],r+=" ",r+=t[e][6],null!=t[e][7]&&(r+=" ",r+=t[e][7])))));return r+" "}(this.value)},move:function(t,e){var n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(var r,i=this.value.length-1;i>=0;i--)"M"==(r=this.value[i][0])||"L"==r||"T"==r?(this.value[i][1]+=t,this.value[i][2]+=e):"H"==r?this.value[i][1]+=t:"V"==r?this.value[i][1]+=e:"C"==r||"S"==r||"Q"==r?(this.value[i][1]+=t,this.value[i][2]+=e,this.value[i][3]+=t,this.value[i][4]+=e,"C"==r&&(this.value[i][5]+=t,this.value[i][6]+=e)):"A"==r&&(this.value[i][6]+=t,this.value[i][7]+=e);return this},size:function(t,e){var n,r,i=this.bbox();for(n=this.value.length-1;n>=0;n--)"M"==(r=this.value[n][0])||"L"==r||"T"==r?(this.value[n][1]=(this.value[n][1]-i.x)*t/i.width+i.x,this.value[n][2]=(this.value[n][2]-i.y)*e/i.height+i.y):"H"==r?this.value[n][1]=(this.value[n][1]-i.x)*t/i.width+i.x:"V"==r?this.value[n][1]=(this.value[n][1]-i.y)*e/i.height+i.y:"C"==r||"S"==r||"Q"==r?(this.value[n][1]=(this.value[n][1]-i.x)*t/i.width+i.x,this.value[n][2]=(this.value[n][2]-i.y)*e/i.height+i.y,this.value[n][3]=(this.value[n][3]-i.x)*t/i.width+i.x,this.value[n][4]=(this.value[n][4]-i.y)*e/i.height+i.y,"C"==r&&(this.value[n][5]=(this.value[n][5]-i.x)*t/i.width+i.x,this.value[n][6]=(this.value[n][6]-i.y)*e/i.height+i.y)):"A"==r&&(this.value[n][1]=this.value[n][1]*t/i.width,this.value[n][2]=this.value[n][2]*e/i.height,this.value[n][6]=(this.value[n][6]-i.x)*t/i.width+i.x,this.value[n][7]=(this.value[n][7]-i.y)*e/i.height+i.y);return this},equalCommands:function(t){var e,r,i;for(t=new n.PathArray(t),i=this.value.length===t.value.length,e=0,r=this.value.length;i&&e<r;e++)i=this.value[e][0]===t.value[e][0];return i},morph:function(t){return t=new n.PathArray(t),this.equalCommands(t)?this.destination=t:this.destination=null,this},at:function(t){if(!this.destination)return this;var e,r,i,s,a=this.value,l=this.destination.value,o=[],h=new n.PathArray;for(e=0,r=a.length;e<r;e++){for(o[e]=[a[e][0]],i=1,s=a[e].length;i<s;i++)o[e][i]=a[e][i]+(l[e][i]-a[e][i])*t;"A"===o[e][0]&&(o[e][4]=+(0!=o[e][4]),o[e][5]=+(0!=o[e][5]))}return h.value=o,h},parse:function(t){if(t instanceof n.PathArray)return t.valueOf();var e,i={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};t="string"==typeof t?t.replace(n.regex.numbersWithDots,o).replace(n.regex.pathLetters," $& ").replace(n.regex.hyphen,"$1 -").trim().split(n.regex.delimiter):t.reduce(function(t,e){return[].concat.call(t,e)},[]);var s=[],a=new n.Point,l=new n.Point,h=0,u=t.length;do{n.regex.isPathLetter.test(t[h])?(e=t[h],++h):"M"==e?e="L":"m"==e&&(e="l"),s.push(r[e].call(null,t.slice(h,h+=i[e.toUpperCase()]).map(parseFloat),a,l))}while(u>h);return s},bbox:function(){return n.parser.path.setAttribute("d",this.toString()),n.parser.path.getBBox()}}),n.Number=n.invent({create:function(t,e){this.value=0,this.unit=e||"","number"==typeof t?this.value=isNaN(t)?0:isFinite(t)?t:t<0?-3.4e38:3.4e38:"string"==typeof t?(e=t.match(n.regex.numberAndUnit))&&(this.value=parseFloat(e[1]),"%"==e[5]?this.value/=100:"s"==e[5]&&(this.value*=1e3),this.unit=e[5]):t instanceof n.Number&&(this.value=t.valueOf(),this.unit=t.unit)},extend:{toString:function(){return("%"==this.unit?~~(1e8*this.value)/1e6:"s"==this.unit?this.value/1e3:this.value)+this.unit},toJSON:function(){return this.toString()},valueOf:function(){return this.value},plus:function(t){return t=new n.Number(t),new n.Number(this+t,this.unit||t.unit)},minus:function(t){return t=new n.Number(t),new n.Number(this-t,this.unit||t.unit)},times:function(t){return t=new n.Number(t),new n.Number(this*t,this.unit||t.unit)},divide:function(t){return t=new n.Number(t),new n.Number(this/t,this.unit||t.unit)},to:function(t){var e=new n.Number(this);return"string"==typeof t&&(e.unit=t),e},morph:function(t){return this.destination=new n.Number(t),t.relative&&(this.destination.value+=this.value),this},at:function(t){return this.destination?new n.Number(this.destination).minus(this).times(t).plus(this):this}}}),n.Element=n.invent({create:function(t){this._stroke=n.defaults.attrs.stroke,this._event=null,this.dom={},(this.node=t)&&(this.type=t.nodeName,this.node.instance=this,this._stroke=t.getAttribute("stroke")||this._stroke)},extend:{x:function(t){return this.attr("x",t)},y:function(t){return this.attr("y",t)},cx:function(t){return null==t?this.x()+this.width()/2:this.x(t-this.width()/2)},cy:function(t){return null==t?this.y()+this.height()/2:this.y(t-this.height()/2)},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},width:function(t){return this.attr("width",t)},height:function(t){return this.attr("height",t)},size:function(t,e){var r=m(this,t,e);return this.width(new n.Number(r.width)).height(new n.Number(r.height))},clone:function(e,r){this.writeDataToDom();var i=function e(r){for(var i=r.childNodes.length-1;i>=0;i--)r.childNodes[i]instanceof t.SVGElement&&e(r.childNodes[i]);return n.adopt(r).id(n.eid(r.nodeName))}(this.node.cloneNode(!0));return e?e.add(i):this.after(i),i},remove:function(){return this.parent()&&this.parent().removeElement(this),this},replace:function(t){return this.after(t).remove(),t},addTo:function(t){return t.put(this)},putIn:function(t){return t.add(this)},id:function(t){return this.attr("id",t)},inside:function(t,e){var n=this.bbox();return t>n.x&&e>n.y&&t<n.x+n.width&&e<n.y+n.height},show:function(){return this.style("display","")},hide:function(){return this.style("display","none")},visible:function(){return"none"!=this.style("display")},toString:function(){return this.attr("id")},classes:function(){var t=this.attr("class");return null==t?[]:t.trim().split(n.regex.delimiter)},hasClass:function(t){return-1!=this.classes().indexOf(t)},addClass:function(t){if(!this.hasClass(t)){var e=this.classes();e.push(t),this.attr("class",e.join(" "))}return this},removeClass:function(t){return this.hasClass(t)&&this.attr("class",this.classes().filter(function(e){return e!=t}).join(" ")),this},toggleClass:function(t){return this.hasClass(t)?this.removeClass(t):this.addClass(t)},reference:function(t){return n.get(this.attr(t))},parent:function(e){var r=this;if(!r.node.parentNode)return null;if(r=n.adopt(r.node.parentNode),!e)return r;for(;r&&r.node instanceof t.SVGElement;){if("string"==typeof e?r.matches(e):r instanceof e)return r;r=n.adopt(r.node.parentNode)}},doc:function(){return this instanceof n.Doc?this:this.parent(n.Doc)},parents:function(t){var e=[],n=this;do{if(!(n=n.parent(t))||!n.node)break;e.push(n)}while(n.parent);return e},matches:function(t){return function(t,e){return(t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector).call(t,e)}(this.node,t)},native:function(){return this.node},svg:function(t){var r=e.createElement("svg");if(!(t&&this instanceof n.Parent))return r.appendChild(t=e.createElement("svg")),this.writeDataToDom(),t.appendChild(this.node.cloneNode(!0)),r.innerHTML.replace(/^<svg>/,"").replace(/<\/svg>$/,"");r.innerHTML="<svg>"+t.replace(/\n/,"").replace(/<(\w+)([^<]+?)\/>/g,"<$1$2></$1>")+"</svg>";for(var i=0,s=r.firstChild.childNodes.length;i<s;i++)this.node.appendChild(r.firstChild.firstChild);return this},writeDataToDom:function(){if(this.each||this.lines){var t=this.each?this:this.lines();t.each(function(){this.writeDataToDom()})}return this.node.removeAttribute("svgjs:data"),Object.keys(this.dom).length&&this.node.setAttribute("svgjs:data",JSON.stringify(this.dom)),this},setData:function(t){return this.dom=t,this},is:function(t){return function(t,e){return t instanceof e}(this,t)}}}),n.easing={"-":function(t){return t},"<>":function(t){return-Math.cos(t*Math.PI)/2+.5},">":function(t){return Math.sin(t*Math.PI/2)},"<":function(t){return 1-Math.cos(t*Math.PI/2)}},n.morph=function(t){return function(e,r){return new n.MorphObj(e,r).at(t)}},n.Situation=n.invent({create:function(t){this.init=!1,this.reversed=!1,this.reversing=!1,this.duration=new n.Number(t.duration).valueOf(),this.delay=new n.Number(t.delay).valueOf(),this.start=+new Date+this.delay,this.finish=this.start+this.duration,this.ease=t.ease,this.loop=0,this.loops=!1,this.animations={},this.attrs={},this.styles={},this.transforms=[],this.once={}}}),n.FX=n.invent({create:function(t){this._target=t,this.situations=[],this.active=!1,this.situation=null,this.paused=!1,this.lastPos=0,this.pos=0,this.absPos=0,this._speed=1},extend:{animate:function(t,e,r){"object"==typeof t&&(e=t.ease,r=t.delay,t=t.duration);var i=new n.Situation({duration:t||1e3,delay:r||0,ease:n.easing[e||"-"]||e});return this.queue(i),this},delay:function(t){var e=new n.Situation({duration:t,delay:0,ease:n.easing["-"]});return this.queue(e)},target:function(t){return t&&t instanceof n.Element?(this._target=t,this):this._target},timeToAbsPos:function(t){return(t-this.situation.start)/(this.situation.duration/this._speed)},absPosToTime:function(t){return this.situation.duration/this._speed*t+this.situation.start},startAnimFrame:function(){this.stopAnimFrame(),this.animationFrame=t.requestAnimationFrame(function(){this.step()}.bind(this))},stopAnimFrame:function(){t.cancelAnimationFrame(this.animationFrame)},start:function(){return!this.active&&this.situation&&(this.active=!0,this.startCurrent()),this},startCurrent:function(){return this.situation.start=+new Date+this.situation.delay/this._speed,this.situation.finish=this.situation.start+this.situation.duration/this._speed,this.initAnimations().step()},queue:function(t){return("function"==typeof t||t instanceof n.Situation)&&this.situations.push(t),this.situation||(this.situation=this.situations.shift()),this},dequeue:function(){return this.stop(),this.situation=this.situations.shift(),this.situation&&(this.situation instanceof n.Situation?this.start():this.situation.call(this)),this},initAnimations:function(){var t,e,r,i=this.situation;if(i.init)return this;for(t in i.animations)for(r=this.target()[t](),Array.isArray(r)||(r=[r]),Array.isArray(i.animations[t])||(i.animations[t]=[i.animations[t]]),e=r.length;e--;)i.animations[t][e]instanceof n.Number&&(r[e]=new n.Number(r[e])),i.animations[t][e]=r[e].morph(i.animations[t][e]);for(t in i.attrs)i.attrs[t]=new n.MorphObj(this.target().attr(t),i.attrs[t]);for(t in i.styles)i.styles[t]=new n.MorphObj(this.target().style(t),i.styles[t]);return i.initialTransformation=this.target().matrixify(),i.init=!0,this},clearQueue:function(){return this.situations=[],this},clearCurrent:function(){return this.situation=null,this},stop:function(t,e){var n=this.active;return this.active=!1,e&&this.clearQueue(),t&&this.situation&&(!n&&this.startCurrent(),this.atEnd()),this.stopAnimFrame(),this.clearCurrent()},reset:function(){if(this.situation){var t=this.situation;this.stop(),this.situation=t,this.atStart()}return this},finish:function(){for(this.stop(!0,!1);this.dequeue().situation&&this.stop(!0,!1););return this.clearQueue().clearCurrent(),this},atStart:function(){return this.at(0,!0)},atEnd:function(){return!0===this.situation.loops&&(this.situation.loops=this.situation.loop+1),"number"==typeof this.situation.loops?this.at(this.situation.loops,!0):this.at(1,!0)},at:function(t,e){var n=this.situation.duration/this._speed;return this.absPos=t,e||(this.situation.reversed&&(this.absPos=1-this.absPos),this.absPos+=this.situation.loop),this.situation.start=+new Date-this.absPos*n,this.situation.finish=this.situation.start+n,this.step(!0)},speed:function(t){return 0===t?this.pause():t?(this._speed=t,this.at(this.absPos,!0)):this._speed},loop:function(t,e){var n=this.last();return n.loops=null==t||t,n.loop=0,e&&(n.reversing=!0),this},pause:function(){return this.paused=!0,this.stopAnimFrame(),this},play:function(){return this.paused?(this.paused=!1,this.at(this.absPos,!0)):this},reverse:function(t){var e=this.last();return e.reversed=void 0===t?!e.reversed:t,this},progress:function(t){return t?this.situation.ease(this.pos):this.pos},after:function(t){var e=this.last();return this.target().on("finished.fx",function n(r){r.detail.situation==e&&(t.call(this,e),this.off("finished.fx",n))}),this._callStart()},during:function(t){var e=this.last(),r=function(r){r.detail.situation==e&&t.call(this,r.detail.pos,n.morph(r.detail.pos),r.detail.eased,e)};return this.target().off("during.fx",r).on("during.fx",r),this.after(function(){this.off("during.fx",r)}),this._callStart()},afterAll:function(t){var e=function e(n){t.call(this),this.off("allfinished.fx",e)};return this.target().off("allfinished.fx",e).on("allfinished.fx",e),this._callStart()},duringAll:function(t){var e=function(e){t.call(this,e.detail.pos,n.morph(e.detail.pos),e.detail.eased,e.detail.situation)};return this.target().off("during.fx",e).on("during.fx",e),this.afterAll(function(){this.off("during.fx",e)}),this._callStart()},last:function(){return this.situations.length?this.situations[this.situations.length-1]:this.situation},add:function(t,e,n){return this.last()[n||"animations"][t]=e,this._callStart()},step:function(t){var e,n,r;(t||(this.absPos=this.timeToAbsPos(+new Date)),!1!==this.situation.loops)?(e=Math.max(this.absPos,0),n=Math.floor(e),!0===this.situation.loops||n<this.situation.loops?(this.pos=e-n,r=this.situation.loop,this.situation.loop=n):(this.absPos=this.situation.loops,this.pos=1,r=this.situation.loop-1,this.situation.loop=this.situation.loops),this.situation.reversing&&(this.situation.reversed=this.situation.reversed!=Boolean((this.situation.loop-r)%2))):(this.absPos=Math.min(this.absPos,1),this.pos=this.absPos);this.pos<0&&(this.pos=0),this.situation.reversed&&(this.pos=1-this.pos);var i=this.situation.ease(this.pos);for(var s in this.situation.once)s>this.lastPos&&s<=i&&(this.situation.once[s].call(this.target(),this.pos,i),delete this.situation.once[s]);return this.active&&this.target().fire("during",{pos:this.pos,eased:i,fx:this,situation:this.situation}),this.situation?(this.eachAt(),1==this.pos&&!this.situation.reversed||this.situation.reversed&&0==this.pos?(this.stopAnimFrame(),this.target().fire("finished",{fx:this,situation:this.situation}),this.situations.length||(this.target().fire("allfinished"),this.situations.length||(this.target().off(".fx"),this.active=!1)),this.active?this.dequeue():this.clearCurrent()):!this.paused&&this.active&&this.startAnimFrame(),this.lastPos=i,this):this},eachAt:function(){var t,e,r,i=this,s=this.target(),a=this.situation;for(t in a.animations)r=[].concat(a.animations[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(a.ease(i.pos),i.pos):t}),s[t].apply(s,r);for(t in a.attrs)r=[t].concat(a.attrs[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(a.ease(i.pos),i.pos):t}),s.attr.apply(s,r);for(t in a.styles)r=[t].concat(a.styles[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(a.ease(i.pos),i.pos):t}),s.style.apply(s,r);if(a.transforms.length){for(r=a.initialTransformation,t=0,e=a.transforms.length;t<e;t++){var l=a.transforms[t];l instanceof n.Matrix?r=l.relative?r.multiply((new n.Matrix).morph(l).at(a.ease(this.pos))):r.morph(l).at(a.ease(this.pos)):(l.relative||l.undo(r.extract()),r=r.multiply(l.at(a.ease(this.pos))))}s.matrix(r)}return this},once:function(t,e,n){var r=this.last();return n||(t=r.ease(t)),r.once[t]=e,this},_callStart:function(){return setTimeout(function(){this.start()}.bind(this),0),this}},parent:n.Element,construct:{animate:function(t,e,r){return(this.fx||(this.fx=new n.FX(this))).animate(t,e,r)},delay:function(t){return(this.fx||(this.fx=new n.FX(this))).delay(t)},stop:function(t,e){return this.fx&&this.fx.stop(t,e),this},finish:function(){return this.fx&&this.fx.finish(),this},pause:function(){return this.fx&&this.fx.pause(),this},play:function(){return this.fx&&this.fx.play(),this},speed:function(t){if(this.fx){if(null==t)return this.fx.speed();this.fx.speed(t)}return this}}}),n.MorphObj=n.invent({create:function(t,e){return n.Color.isColor(e)?new n.Color(t).morph(e):n.regex.numberAndUnit.test(e)?new n.Number(t).morph(e):(this.value=t,void(this.destination=e))},extend:{at:function(t,e){return e<1?this.value:this.destination},valueOf:function(){return this.value}}}),n.extend(n.FX,{attr:function(t,e,n){if("object"==typeof t)for(var r in t)this.attr(r,t[r]);else this.add(t,e,"attrs");return this},style:function(t,e){if("object"==typeof t)for(var n in t)this.style(n,t[n]);else this.add(t,e,"styles");return this},x:function(t,e){if(this.target()instanceof n.G)return this.transform({x:t},e),this;var r=new n.Number(t);return r.relative=e,this.add("x",r)},y:function(t,e){if(this.target()instanceof n.G)return this.transform({y:t},e),this;var r=new n.Number(t);return r.relative=e,this.add("y",r)},cx:function(t){return this.add("cx",new n.Number(t))},cy:function(t){return this.add("cy",new n.Number(t))},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},size:function(t,e){var r;this.target()instanceof n.Text?this.attr("font-size",t):(t&&e||(r=this.target().bbox()),t||(t=r.width/r.height*e),e||(e=r.height/r.width*t),this.add("width",new n.Number(t)).add("height",new n.Number(e)));return this},width:function(t){return this.add("width",new n.Number(t))},height:function(t){return this.add("height",new n.Number(t))},plot:function(t,e,n,r){return 4==arguments.length?this.plot([t,e,n,r]):this.add("plot",new(this.target().morphArray)(t))},leading:function(t){return this.target().leading?this.add("leading",new n.Number(t)):this},viewbox:function(t,e,r,i){return this.target()instanceof n.Container&&this.add("viewbox",new n.ViewBox(t,e,r,i)),this},update:function(t){if(this.target()instanceof n.Stop){if("number"==typeof t||t instanceof n.Number)return this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]});null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",t.offset)}return this}}),n.Box=n.invent({create:function(t,e,r,i){if(!("object"!=typeof t||t instanceof n.Element))return n.Box.call(this,null!=t.left?t.left:t.x,null!=t.top?t.top:t.y,t.width,t.height);4==arguments.length&&(this.x=t,this.y=e,this.width=r,this.height=i),x(this)},extend:{merge:function(t){var e=new this.constructor;return e.x=Math.min(this.x,t.x),e.y=Math.min(this.y,t.y),e.width=Math.max(this.x+this.width,t.x+t.width)-e.x,e.height=Math.max(this.y+this.height,t.y+t.height)-e.y,x(e)},transform:function(t){var e,r=1/0,i=-1/0,s=1/0,a=-1/0,l=[new n.Point(this.x,this.y),new n.Point(this.x2,this.y),new n.Point(this.x,this.y2),new n.Point(this.x2,this.y2)];return l.forEach(function(e){e=e.transform(t),r=Math.min(r,e.x),i=Math.max(i,e.x),s=Math.min(s,e.y),a=Math.max(a,e.y)}),(e=new this.constructor).x=r,e.width=i-r,e.y=s,e.height=a-s,x(e),e}}}),n.BBox=n.invent({create:function(t){if(n.Box.apply(this,[].slice.call(arguments)),t instanceof n.Element){var r;try{if(e.documentElement.contains){if(!e.documentElement.contains(t.node))throw new Exception("Element not in the dom")}else{for(var i=t.node;i.parentNode;)i=i.parentNode;if(i!=e)throw new Exception("Element not in the dom")}r=t.node.getBBox()}catch(e){if(t instanceof n.Shape){var s=t.clone(n.parser.draw.instance).show();r=s.node.getBBox(),s.remove()}else r={x:t.node.clientLeft,y:t.node.clientTop,width:t.node.clientWidth,height:t.node.clientHeight}}n.Box.call(this,r)}},inherit:n.Box,parent:n.Element,construct:{bbox:function(){return new n.BBox(this)}}}),n.BBox.prototype.constructor=n.BBox,n.extend(n.Element,{tbox:function(){return console.warn("Use of TBox is deprecated and mapped to RBox. Use .rbox() instead."),this.rbox(this.doc())}}),n.RBox=n.invent({create:function(t){n.Box.apply(this,[].slice.call(arguments)),t instanceof n.Element&&n.Box.call(this,t.node.getBoundingClientRect())},inherit:n.Box,parent:n.Element,extend:{addOffset:function(){return this.x+=t.pageXOffset,this.y+=t.pageYOffset,this}},construct:{rbox:function(t){return t?new n.RBox(this).transform(t.screenCTM().inverse()):new n.RBox(this).addOffset()}}}),n.RBox.prototype.constructor=n.RBox,n.Matrix=n.invent({create:function(t){var e,r=d([1,0,0,1,0,0]);for(t=t instanceof n.Element?t.matrixify():"string"==typeof t?d(t.split(n.regex.delimiter).map(parseFloat)):6==arguments.length?d([].slice.call(arguments)):Array.isArray(t)?d(t):"object"==typeof t?t:r,e=v.length-1;e>=0;--e)this[v[e]]=null!=t[v[e]]?t[v[e]]:r[v[e]]},extend:{extract:function(){var t=p(this,0,1),e=p(this,1,0),r=180/Math.PI*Math.atan2(t.y,t.x)-90;return{x:this.e,y:this.f,transformedX:(this.e*Math.cos(r*Math.PI/180)+this.f*Math.sin(r*Math.PI/180))/Math.sqrt(this.a*this.a+this.b*this.b),transformedY:(this.f*Math.cos(r*Math.PI/180)+this.e*Math.sin(-r*Math.PI/180))/Math.sqrt(this.c*this.c+this.d*this.d),skewX:-r,skewY:180/Math.PI*Math.atan2(e.y,e.x),scaleX:Math.sqrt(this.a*this.a+this.b*this.b),scaleY:Math.sqrt(this.c*this.c+this.d*this.d),rotation:r,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f,matrix:new n.Matrix(this)}},clone:function(){return new n.Matrix(this)},morph:function(t){return this.destination=new n.Matrix(t),this},at:function(t){if(!this.destination)return this;var e=new n.Matrix({a:this.a+(this.destination.a-this.a)*t,b:this.b+(this.destination.b-this.b)*t,c:this.c+(this.destination.c-this.c)*t,d:this.d+(this.destination.d-this.d)*t,e:this.e+(this.destination.e-this.e)*t,f:this.f+(this.destination.f-this.f)*t});return e},multiply:function(t){return new n.Matrix(this.native().multiply(function(t){t instanceof n.Matrix||(t=new n.Matrix(t));return t}(t).native()))},inverse:function(){return new n.Matrix(this.native().inverse())},translate:function(t,e){return new n.Matrix(this.native().translate(t||0,e||0))},scale:function(t,e,r,i){return 1==arguments.length?e=t:3==arguments.length&&(i=r,r=e,e=t),this.around(r,i,new n.Matrix(t,0,0,e,0,0))},rotate:function(t,e,r){return t=n.utils.radians(t),this.around(e,r,new n.Matrix(Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),0,0))},flip:function(t,e){return"x"==t?this.scale(-1,1,e,0):"y"==t?this.scale(1,-1,0,e):this.scale(-1,-1,t,null!=e?e:t)},skew:function(t,e,r,i){return 1==arguments.length?e=t:3==arguments.length&&(i=r,r=e,e=t),t=n.utils.radians(t),e=n.utils.radians(e),this.around(r,i,new n.Matrix(1,Math.tan(e),Math.tan(t),1,0,0))},skewX:function(t,e,n){return this.skew(t,0,e,n)},skewY:function(t,e,n){return this.skew(0,t,e,n)},around:function(t,e,r){return this.multiply(new n.Matrix(1,0,0,1,t||0,e||0)).multiply(r).multiply(new n.Matrix(1,0,0,1,-t||0,-e||0))},native:function(){for(var t=n.parser.native.createSVGMatrix(),e=v.length-1;e>=0;e--)t[v[e]]=this[v[e]];return t},toString:function(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}},parent:n.Element,construct:{ctm:function(){return new n.Matrix(this.node.getCTM())},screenCTM:function(){if(this instanceof n.Nested){var t=this.rect(1,1),e=t.node.getScreenCTM();return t.remove(),new n.Matrix(e)}return new n.Matrix(this.node.getScreenCTM())}}}),n.Point=n.invent({create:function(t,e){var n;n=Array.isArray(t)?{x:t[0],y:t[1]}:"object"==typeof t?{x:t.x,y:t.y}:null!=t?{x:t,y:null!=e?e:t}:{x:0,y:0},this.x=n.x,this.y=n.y},extend:{clone:function(){return new n.Point(this)},morph:function(t,e){return this.destination=new n.Point(t,e),this},at:function(t){if(!this.destination)return this;var e=new n.Point({x:this.x+(this.destination.x-this.x)*t,y:this.y+(this.destination.y-this.y)*t});return e},native:function(){var t=n.parser.native.createSVGPoint();return t.x=this.x,t.y=this.y,t},transform:function(t){return new n.Point(this.native().matrixTransform(t.native()))}}}),n.extend(n.Element,{point:function(t,e){return new n.Point(t,e).transform(this.screenCTM().inverse())}}),n.extend(n.Element,{attr:function(t,e,r){if(null==t){for(t={},e=this.node.attributes,r=e.length-1;r>=0;r--)t[e[r].nodeName]=n.regex.isNumber.test(e[r].nodeValue)?parseFloat(e[r].nodeValue):e[r].nodeValue;return t}if("object"==typeof t)for(e in t)this.attr(e,t[e]);else if(null===e)this.node.removeAttribute(t);else{if(null==e)return null==(e=this.node.getAttribute(t))?n.defaults.attrs[t]:n.regex.isNumber.test(e)?parseFloat(e):e;"stroke-width"==t?this.attr("stroke",parseFloat(e)>0?this._stroke:null):"stroke"==t&&(this._stroke=e),"fill"!=t&&"stroke"!=t||(n.regex.isImage.test(e)&&(e=this.doc().defs().image(e,0,0)),e instanceof n.Image&&(e=this.doc().defs().pattern(0,0,function(){this.add(e)}))),"number"==typeof e?e=new n.Number(e):n.Color.isColor(e)?e=new n.Color(e):Array.isArray(e)&&(e=new n.Array(e)),"leading"==t?this.leading&&this.leading(e):"string"==typeof r?this.node.setAttributeNS(r,t,e.toString()):this.node.setAttribute(t,e.toString()),!this.rebuild||"font-size"!=t&&"x"!=t||this.rebuild(t,e)}return this}}),n.extend(n.Element,{transform:function(t,e){var r,i;if("object"!=typeof t)return r=new n.Matrix(this).extract(),"string"==typeof t?r[t]:r;if(r=new n.Matrix(this),e=!!e||!!t.relative,null!=t.a)r=e?r.multiply(new n.Matrix(t)):new n.Matrix(t);else if(null!=t.rotation)f(t,this),r=e?r.rotate(t.rotation,t.cx,t.cy):r.rotate(t.rotation-r.extract().rotation,t.cx,t.cy);else if(null!=t.scale||null!=t.scaleX||null!=t.scaleY){if(f(t,this),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1,!e){var s=r.extract();t.scaleX=1*t.scaleX/s.scaleX,t.scaleY=1*t.scaleY/s.scaleY}r=r.scale(t.scaleX,t.scaleY,t.cx,t.cy)}else if(null!=t.skew||null!=t.skewX||null!=t.skewY){if(f(t,this),t.skewX=null!=t.skew?t.skew:null!=t.skewX?t.skewX:0,t.skewY=null!=t.skew?t.skew:null!=t.skewY?t.skewY:0,!e){var s=r.extract();r=r.multiply((new n.Matrix).skew(s.skewX,s.skewY,t.cx,t.cy).inverse())}r=r.skew(t.skewX,t.skewY,t.cx,t.cy)}else t.flip?("x"==t.flip||"y"==t.flip?t.offset=null==t.offset?this.bbox()["c"+t.flip]:t.offset:null==t.offset?(i=this.bbox(),t.flip=i.cx,t.offset=i.cy):t.flip=t.offset,r=(new n.Matrix).flip(t.flip,t.offset)):null==t.x&&null==t.y||(e?r=r.translate(t.x,t.y):(null!=t.x&&(r.e=t.x),null!=t.y&&(r.f=t.y)));return this.attr("transform",r)}}),n.extend(n.FX,{transform:function(t,e){var r,i,s=this.target();return"object"!=typeof t?(r=new n.Matrix(s).extract(),"string"==typeof t?r[t]:r):(e=!!e||!!t.relative,null!=t.a?r=new n.Matrix(t):null!=t.rotation?(f(t,s),r=new n.Rotate(t.rotation,t.cx,t.cy)):null!=t.scale||null!=t.scaleX||null!=t.scaleY?(f(t,s),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1,r=new n.Scale(t.scaleX,t.scaleY,t.cx,t.cy)):null!=t.skewX||null!=t.skewY?(f(t,s),t.skewX=null!=t.skewX?t.skewX:0,t.skewY=null!=t.skewY?t.skewY:0,r=new n.Skew(t.skewX,t.skewY,t.cx,t.cy)):t.flip?("x"==t.flip||"y"==t.flip?t.offset=null==t.offset?s.bbox()["c"+t.flip]:t.offset:null==t.offset?(i=s.bbox(),t.flip=i.cx,t.offset=i.cy):t.flip=t.offset,r=(new n.Matrix).flip(t.flip,t.offset)):null==t.x&&null==t.y||(r=new n.Translate(t.x,t.y)),r?(r.relative=e,this.last().transforms.push(r),this._callStart()):this)}}),n.extend(n.Element,{untransform:function(){return this.attr("transform",null)},matrixify:function(){var t=(this.attr("transform")||"").split(n.regex.transforms).slice(0,-1).map(function(t){var e=t.trim().split("(");return[e[0],e[1].split(n.regex.delimiter).map(function(t){return parseFloat(t)})]}).reduce(function(t,e){return"matrix"==e[0]?t.multiply(d(e[1])):t[e[0]].apply(t,e[1])},new n.Matrix);return t},toParent:function(t){if(this==t)return this;var e=this.screenCTM(),n=t.screenCTM().inverse();return this.addTo(t).untransform().transform(n.multiply(e)),this},toDoc:function(){return this.toParent(this.doc())}}),n.Transformation=n.invent({create:function(t,e){if(arguments.length>1&&"boolean"!=typeof e)return this.constructor.call(this,[].slice.call(arguments));if(Array.isArray(t))for(var n=0,r=this.arguments.length;n<r;++n)this[this.arguments[n]]=t[n];else if("object"==typeof t)for(var n=0,r=this.arguments.length;n<r;++n)this[this.arguments[n]]=t[this.arguments[n]];this.inversed=!1,!0===e&&(this.inversed=!0)},extend:{arguments:[],method:"",at:function(t){for(var e=[],r=0,i=this.arguments.length;r<i;++r)e.push(this[this.arguments[r]]);var s=this._undo||new n.Matrix;return s=(new n.Matrix).morph(n.Matrix.prototype[this.method].apply(s,e)).at(t),this.inversed?s.inverse():s},undo:function(t){for(var e=0,r=this.arguments.length;e<r;++e)t[this.arguments[e]]=void 0===this[this.arguments[e]]?0:t[this.arguments[e]];return t.cx=this.cx,t.cy=this.cy,this._undo=new(n[u(this.method)])(t,!0).at(1),this}}}),n.Translate=n.invent({parent:n.Matrix,inherit:n.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["transformedX","transformedY"],method:"translate"}}),n.Rotate=n.invent({parent:n.Matrix,inherit:n.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["rotation","cx","cy"],method:"rotate",at:function(t){var e=(new n.Matrix).rotate((new n.Number).morph(this.rotation-(this._undo?this._undo.rotation:0)).at(t),this.cx,this.cy);return this.inversed?e.inverse():e},undo:function(t){return this._undo=t,this}}}),n.Scale=n.invent({parent:n.Matrix,inherit:n.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["scaleX","scaleY","cx","cy"],method:"scale"}}),n.Skew=n.invent({parent:n.Matrix,inherit:n.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["skewX","skewY","cx","cy"],method:"skew"}}),n.extend(n.Element,{style:function(t,e){if(0==arguments.length)return this.node.style.cssText||"";if(arguments.length<2)if("object"==typeof t)for(e in t)this.style(e,t[e]);else{if(!n.regex.isCss.test(t))return this.node.style[h(t)];for(t=t.split(/\s*;\s*/).filter(function(t){return!!t}).map(function(t){return t.split(/\s*:\s*/)});e=t.pop();)this.style(e[0],e[1])}else this.node.style[h(t)]=null===e||n.regex.isBlank.test(e)?"":e;return this}}),n.Parent=n.invent({create:function(t){this.constructor.call(this,t)},inherit:n.Element,extend:{children:function(){return n.utils.map(n.utils.filterSVGElements(this.node.childNodes),function(t){return n.adopt(t)})},add:function(t,e){return null==e?this.node.appendChild(t.node):t.node!=this.node.childNodes[e]&&this.node.insertBefore(t.node,this.node.childNodes[e]),this},put:function(t,e){return this.add(t,e),t},has:function(t){return this.index(t)>=0},index:function(t){return[].slice.call(this.node.childNodes).indexOf(t.node)},get:function(t){return n.adopt(this.node.childNodes[t])},first:function(){return this.get(0)},last:function(){return this.get(this.node.childNodes.length-1)},each:function(t,e){var r,i,s=this.children();for(r=0,i=s.length;r<i;r++)s[r]instanceof n.Element&&t.apply(s[r],[r,s]),e&&s[r]instanceof n.Container&&s[r].each(t,e);return this},removeElement:function(t){return this.node.removeChild(t.node),this},clear:function(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return delete this._defs,this},defs:function(){return this.doc().defs()}}}),n.extend(n.Parent,{ungroup:function(t,e){return 0===e||this instanceof n.Defs||this.node==n.parser.draw?this:(t=t||(this instanceof n.Doc?this:this.parent(n.Parent)),e=e||1/0,this.each(function(){return this instanceof n.Defs?this:this instanceof n.Parent?this.ungroup(t,e-1):this.toParent(t)}),this.node.firstChild||this.remove(),this)},flatten:function(t,e){return this.ungroup(t,e)}}),n.Container=n.invent({create:function(t){this.constructor.call(this,t)},inherit:n.Parent}),n.ViewBox=n.invent({create:function(t){var e,r,i,s,a,l,o,h=1,u=1,c=/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/gi;if(t instanceof n.Element){for(l=t,o=t,a=(t.attr("viewBox")||"").match(c),t.bbox,i=new n.Number(t.width()),s=new n.Number(t.height());"%"==i.unit;)h*=i.value,i=new n.Number(l instanceof n.Doc?l.parent().offsetWidth:l.parent().width()),l=l.parent();for(;"%"==s.unit;)u*=s.value,s=new n.Number(o instanceof n.Doc?o.parent().offsetHeight:o.parent().height()),o=o.parent();this.x=0,this.y=0,this.width=i*h,this.height=s*u,this.zoom=1,a&&(e=parseFloat(a[0]),r=parseFloat(a[1]),i=parseFloat(a[2]),s=parseFloat(a[3]),this.zoom=this.width/this.height>i/s?this.height/s:this.width/i,this.x=e,this.y=r,this.width=i,this.height=s)}else t="string"==typeof t?t.match(c).map(function(t){return parseFloat(t)}):Array.isArray(t)?t:"object"==typeof t?[t.x,t.y,t.width,t.height]:4==arguments.length?[].slice.call(arguments):[0,0,0,0],this.x=t[0],this.y=t[1],this.width=t[2],this.height=t[3]},extend:{toString:function(){return this.x+" "+this.y+" "+this.width+" "+this.height},morph:function(t,e,r,i){return this.destination=new n.ViewBox(t,e,r,i),this},at:function(t){return this.destination?new n.ViewBox([this.x+(this.destination.x-this.x)*t,this.y+(this.destination.y-this.y)*t,this.width+(this.destination.width-this.width)*t,this.height+(this.destination.height-this.height)*t]):this}},parent:n.Container,construct:{viewbox:function(t,e,r,i){return 0==arguments.length?new n.ViewBox(this):this.attr("viewBox",new n.ViewBox(t,e,r,i))}}}),["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","touchstart","touchmove","touchleave","touchend","touchcancel"].forEach(function(t){n.Element.prototype[t]=function(e){return n.on(this.node,t,e),this}}),n.listeners=[],n.handlerMap=[],n.listenerId=0,n.on=function(t,e,r,i,s){var a=r.bind(i||t.instance||t),l=(n.handlerMap.indexOf(t)+1||n.handlerMap.push(t))-1,o=e.split(".")[0],h=e.split(".")[1]||"*";n.listeners[l]=n.listeners[l]||{},n.listeners[l][o]=n.listeners[l][o]||{},n.listeners[l][o][h]=n.listeners[l][o][h]||{},r._svgjsListenerId||(r._svgjsListenerId=++n.listenerId),n.listeners[l][o][h][r._svgjsListenerId]=a,t.addEventListener(o,a,s||!1)},n.off=function(t,e,r){var i=n.handlerMap.indexOf(t),s=e&&e.split(".")[0],a=e&&e.split(".")[1],l="";if(-1!=i)if(r){if("function"==typeof r&&(r=r._svgjsListenerId),!r)return;n.listeners[i][s]&&n.listeners[i][s][a||"*"]&&(t.removeEventListener(s,n.listeners[i][s][a||"*"][r],!1),delete n.listeners[i][s][a||"*"][r])}else if(a&&s){if(n.listeners[i][s]&&n.listeners[i][s][a]){for(r in n.listeners[i][s][a])n.off(t,[s,a].join("."),r);delete n.listeners[i][s][a]}}else if(a)for(e in n.listeners[i])for(l in n.listeners[i][e])a===l&&n.off(t,[e,a].join("."));else if(s){if(n.listeners[i][s]){for(l in n.listeners[i][s])n.off(t,[s,l].join("."));delete n.listeners[i][s]}}else{for(e in n.listeners[i])n.off(t,e);delete n.listeners[i],delete n.handlerMap[i]}},n.extend(n.Element,{on:function(t,e,r,i){return n.on(this.node,t,e,r,i),this},off:function(t,e){return n.off(this.node,t,e),this},fire:function(e,n){return e instanceof t.Event?this.node.dispatchEvent(e):this.node.dispatchEvent(e=new t.CustomEvent(e,{detail:n,cancelable:!0})),this._event=e,this},event:function(){return this._event}}),n.Defs=n.invent({create:"defs",inherit:n.Container}),n.G=n.invent({create:"g",inherit:n.Container,extend:{x:function(t){return null==t?this.transform("x"):this.transform({x:t-this.x()},!0)},y:function(t){return null==t?this.transform("y"):this.transform({y:t-this.y()},!0)},cx:function(t){return null==t?this.gbox().cx:this.x(t-this.gbox().width/2)},cy:function(t){return null==t?this.gbox().cy:this.y(t-this.gbox().height/2)},gbox:function(){var t=this.bbox(),e=this.transform();return t.x+=e.x,t.x2+=e.x,t.cx+=e.x,t.y+=e.y,t.y2+=e.y,t.cy+=e.y,t}},construct:{group:function(){return this.put(new n.G)}}}),n.extend(n.Element,{siblings:function(){return this.parent().children()},position:function(){return this.parent().index(this)},next:function(){return this.siblings()[this.position()+1]},previous:function(){return this.siblings()[this.position()-1]},forward:function(){var t=this.position()+1,e=this.parent();return e.removeElement(this).add(this,t),e instanceof n.Doc&&e.node.appendChild(e.defs().node),this},backward:function(){var t=this.position();return t>0&&this.parent().removeElement(this).add(this,t-1),this},front:function(){var t=this.parent();return t.node.appendChild(this.node),t instanceof n.Doc&&t.node.appendChild(t.defs().node),this},back:function(){return this.position()>0&&this.parent().removeElement(this).add(this,0),this},before:function(t){t.remove();var e=this.position();return this.parent().add(t,e),this},after:function(t){t.remove();var e=this.position();return this.parent().add(t,e+1),this}}),n.Mask=n.invent({create:function(){this.constructor.call(this,n.create("mask")),this.targets=[]},inherit:n.Container,extend:{remove:function(){for(var t=this.targets.length-1;t>=0;t--)this.targets[t]&&this.targets[t].unmask();return this.targets=[],this.parent().removeElement(this),this}},construct:{mask:function(){return this.defs().put(new n.Mask)}}}),n.extend(n.Element,{maskWith:function(t){return this.masker=t instanceof n.Mask?t:this.parent().mask().add(t),this.masker.targets.push(this),this.attr("mask",'url("#'+this.masker.attr("id")+'")')},unmask:function(){return delete this.masker,this.attr("mask",null)}}),n.ClipPath=n.invent({create:function(){this.constructor.call(this,n.create("clipPath")),this.targets=[]},inherit:n.Container,extend:{remove:function(){for(var t=this.targets.length-1;t>=0;t--)this.targets[t]&&this.targets[t].unclip();return this.targets=[],this.parent().removeElement(this),this}},construct:{clip:function(){return this.defs().put(new n.ClipPath)}}}),n.extend(n.Element,{clipWith:function(t){return this.clipper=t instanceof n.ClipPath?t:this.parent().clip().add(t),this.clipper.targets.push(this),this.attr("clip-path",'url("#'+this.clipper.attr("id")+'")')},unclip:function(){return delete this.clipper,this.attr("clip-path",null)}}),n.Gradient=n.invent({create:function(t){this.constructor.call(this,n.create(t+"Gradient")),this.type=t},inherit:n.Container,extend:{at:function(t,e,r){return this.put(new n.Stop).update(t,e,r)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},fill:function(){return"url(#"+this.id()+")"},toString:function(){return this.fill()},attr:function(t,e,r){return"transform"==t&&(t="gradientTransform"),n.Container.prototype.attr.call(this,t,e,r)}},construct:{gradient:function(t,e){return this.defs().gradient(t,e)}}}),n.extend(n.Gradient,n.FX,{from:function(t,e){return"radial"==(this._target||this).type?this.attr({fx:new n.Number(t),fy:new n.Number(e)}):this.attr({x1:new n.Number(t),y1:new n.Number(e)})},to:function(t,e){return"radial"==(this._target||this).type?this.attr({cx:new n.Number(t),cy:new n.Number(e)}):this.attr({x2:new n.Number(t),y2:new n.Number(e)})}}),n.extend(n.Defs,{gradient:function(t,e){return this.put(new n.Gradient(t)).update(e)}}),n.Stop=n.invent({create:"stop",inherit:n.Element,extend:{update:function(t){return("number"==typeof t||t instanceof n.Number)&&(t={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",new n.Number(t.offset)),this}}}),n.Pattern=n.invent({create:"pattern",inherit:n.Container,extend:{fill:function(){return"url(#"+this.id()+")"},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return this.fill()},attr:function(t,e,r){return"transform"==t&&(t="patternTransform"),n.Container.prototype.attr.call(this,t,e,r)}},construct:{pattern:function(t,e,n){return this.defs().pattern(t,e,n)}}}),n.extend(n.Defs,{pattern:function(t,e,r){return this.put(new n.Pattern).update(r).attr({x:0,y:0,width:t,height:e,patternUnits:"userSpaceOnUse"})}}),n.Doc=n.invent({create:function(t){t&&("svg"==(t="string"==typeof t?e.getElementById(t):t).nodeName?this.constructor.call(this,t):(this.constructor.call(this,n.create("svg")),t.appendChild(this.node),this.size("100%","100%")),this.namespace().defs())},inherit:n.Container,extend:{namespace:function(){return this.attr({xmlns:n.ns,version:"1.1"}).attr("xmlns:xlink",n.xlink,n.xmlns).attr("xmlns:svgjs",n.svgjs,n.xmlns)},defs:function(){var t;this._defs||((t=this.node.getElementsByTagName("defs")[0])?this._defs=n.adopt(t):this._defs=new n.Defs,this.node.appendChild(this._defs.node));return this._defs},parent:function(){return"#document"==this.node.parentNode.nodeName?null:this.node.parentNode},spof:function(t){var e=this.node.getScreenCTM();return e&&this.style("left",-e.e%1+"px").style("top",-e.f%1+"px"),this},remove:function(){return this.parent()&&this.parent().removeChild(this.node),this},clear:function(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return delete this._defs,n.parser.draw.parentNode||this.node.appendChild(n.parser.draw),this}}}),n.Shape=n.invent({create:function(t){this.constructor.call(this,t)},inherit:n.Element}),n.Bare=n.invent({create:function(t,e){if(this.constructor.call(this,n.create(t)),e)for(var r in e.prototype)"function"==typeof e.prototype[r]&&(this[r]=e.prototype[r])},inherit:n.Element,extend:{words:function(t){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this.node.appendChild(e.createTextNode(t)),this}}}),n.extend(n.Parent,{element:function(t,e){return this.put(new n.Bare(t,e))}}),n.Symbol=n.invent({create:"symbol",inherit:n.Container,construct:{symbol:function(){return this.put(new n.Symbol)}}}),n.Use=n.invent({create:"use",inherit:n.Shape,extend:{element:function(t,e){return this.attr("href",(e||"")+"#"+t,n.xlink)}},construct:{use:function(t,e){return this.put(new n.Use).element(t,e)}}}),n.Rect=n.invent({create:"rect",inherit:n.Shape,construct:{rect:function(t,e){return this.put(new n.Rect).size(t,e)}}}),n.Circle=n.invent({create:"circle",inherit:n.Shape,construct:{circle:function(t){return this.put(new n.Circle).rx(new n.Number(t).divide(2)).move(0,0)}}}),n.extend(n.Circle,n.FX,{rx:function(t){return this.attr("r",t)},ry:function(t){return this.rx(t)}}),n.Ellipse=n.invent({create:"ellipse",inherit:n.Shape,construct:{ellipse:function(t,e){return this.put(new n.Ellipse).size(t,e).move(0,0)}}}),n.extend(n.Ellipse,n.Rect,n.FX,{rx:function(t){return this.attr("rx",t)},ry:function(t){return this.attr("ry",t)}}),n.extend(n.Circle,n.Ellipse,{x:function(t){return null==t?this.cx()-this.rx():this.cx(t+this.rx())},y:function(t){return null==t?this.cy()-this.ry():this.cy(t+this.ry())},cx:function(t){return null==t?this.attr("cx"):this.attr("cx",t)},cy:function(t){return null==t?this.attr("cy"):this.attr("cy",t)},width:function(t){return null==t?2*this.rx():this.rx(new n.Number(t).divide(2))},height:function(t){return null==t?2*this.ry():this.ry(new n.Number(t).divide(2))},size:function(t,e){var r=m(this,t,e);return this.rx(new n.Number(r.width).divide(2)).ry(new n.Number(r.height).divide(2))}}),n.Line=n.invent({create:"line",inherit:n.Shape,extend:{array:function(){return new n.PointArray([[this.attr("x1"),this.attr("y1")],[this.attr("x2"),this.attr("y2")]])},plot:function(t,e,r,i){return null==t?this.array():(t=void 0!==e?{x1:t,y1:e,x2:r,y2:i}:new n.PointArray(t).toLine(),this.attr(t))},move:function(t,e){return this.attr(this.array().move(t,e).toLine())},size:function(t,e){var n=m(this,t,e);return this.attr(this.array().size(n.width,n.height).toLine())}},construct:{line:function(t,e,r,i){return n.Line.prototype.plot.apply(this.put(new n.Line),null!=t?[t,e,r,i]:[0,0,0,0])}}}),n.Polyline=n.invent({create:"polyline",inherit:n.Shape,construct:{polyline:function(t){return this.put(new n.Polyline).plot(t||new n.PointArray)}}}),n.Polygon=n.invent({create:"polygon",inherit:n.Shape,construct:{polygon:function(t){return this.put(new n.Polygon).plot(t||new n.PointArray)}}}),n.extend(n.Polyline,n.Polygon,{array:function(){return this._array||(this._array=new n.PointArray(this.attr("points")))},plot:function(t){return null==t?this.array():this.clear().attr("points","string"==typeof t?t:this._array=new n.PointArray(t))},clear:function(){return delete this._array,this},move:function(t,e){return this.attr("points",this.array().move(t,e))},size:function(t,e){var n=m(this,t,e);return this.attr("points",this.array().size(n.width,n.height))}}),n.extend(n.Line,n.Polyline,n.Polygon,{morphArray:n.PointArray,x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},width:function(t){var e=this.bbox();return null==t?e.width:this.size(t,e.height)},height:function(t){var e=this.bbox();return null==t?e.height:this.size(e.width,t)}}),n.Path=n.invent({create:"path",inherit:n.Shape,extend:{morphArray:n.PathArray,array:function(){return this._array||(this._array=new n.PathArray(this.attr("d")))},plot:function(t){return null==t?this.array():this.clear().attr("d","string"==typeof t?t:this._array=new n.PathArray(t))},clear:function(){return delete this._array,this},move:function(t,e){return this.attr("d",this.array().move(t,e))},x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},size:function(t,e){var n=m(this,t,e);return this.attr("d",this.array().size(n.width,n.height))},width:function(t){return null==t?this.bbox().width:this.size(t,this.bbox().height)},height:function(t){return null==t?this.bbox().height:this.size(this.bbox().width,t)}},construct:{path:function(t){return this.put(new n.Path).plot(t||new n.PathArray)}}}),n.Image=n.invent({create:"image",inherit:n.Shape,extend:{load:function(e){if(!e)return this;var r=this,i=new t.Image;return n.on(i,"load",function(){var t=r.parent(n.Pattern);null!==t&&(0==r.width()&&0==r.height()&&r.size(i.width,i.height),t&&0==t.width()&&0==t.height()&&t.size(r.width(),r.height()),"function"==typeof r._loaded&&r._loaded.call(r,{width:i.width,height:i.height,ratio:i.width/i.height,url:e}))}),n.on(i,"error",function(t){"function"==typeof r._error&&r._error.call(r,t)}),this.attr("href",i.src=this.src=e,n.xlink)},loaded:function(t){return this._loaded=t,this},error:function(t){return this._error=t,this}},construct:{image:function(t,e,r){return this.put(new n.Image).load(t).size(e||0,r||e||0)}}}),n.Text=n.invent({create:function(){this.constructor.call(this,n.create("text")),this.dom.leading=new n.Number(1.3),this._rebuild=!0,this._build=!1,this.attr("font-family",n.defaults.attrs["font-family"])},inherit:n.Shape,extend:{x:function(t){return null==t?this.attr("x"):this.attr("x",t)},y:function(t){var e=this.attr("y"),n="number"==typeof e?e-this.bbox().y:0;return null==t?"number"==typeof e?e-n:e:this.attr("y","number"==typeof t?t+n:t)},cx:function(t){return null==t?this.bbox().cx:this.x(t-this.bbox().width/2)},cy:function(t){return null==t?this.bbox().cy:this.y(t-this.bbox().height/2)},text:function(t){if(void 0===t){for(var t="",e=this.node.childNodes,r=0,i=e.length;r<i;++r)0!=r&&3!=e[r].nodeType&&1==n.adopt(e[r]).dom.newLined&&(t+="\n"),t+=e[r].textContent;return t}if(this.clear().build(!0),"function"==typeof t)t.call(this,this);else for(var r=0,s=(t=t.split("\n")).length;r<s;r++)this.tspan(t[r]).newLine();return this.build(!1).rebuild()},size:function(t){return this.attr("font-size",t).rebuild()},leading:function(t){return null==t?this.dom.leading:(this.dom.leading=new n.Number(t),this.rebuild())},lines:function(){var t=(this.textPath&&this.textPath()||this).node,e=n.utils.map(n.utils.filterSVGElements(t.childNodes),function(t){return n.adopt(t)});return new n.Set(e)},rebuild:function(t){if("boolean"==typeof t&&(this._rebuild=t),this._rebuild){var e=this,r=0,i=this.dom.leading*new n.Number(this.attr("font-size"));this.lines().each(function(){this.dom.newLined&&(e.textPath()||this.attr("x",e.attr("x")),"\n"==this.text()?r+=i:(this.attr("dy",i+r),r=0))}),this.fire("rebuild")}return this},build:function(t){return this._build=!!t,this},setData:function(t){return this.dom=t,this.dom.leading=new n.Number(t.leading||1.3),this}},construct:{text:function(t){return this.put(new n.Text).text(t)},plain:function(t){return this.put(new n.Text).plain(t)}}}),n.Tspan=n.invent({create:"tspan",inherit:n.Shape,extend:{text:function(t){return null==t?this.node.textContent+(this.dom.newLined?"\n":""):("function"==typeof t?t.call(this,this):this.plain(t),this)},dx:function(t){return this.attr("dx",t)},dy:function(t){return this.attr("dy",t)},newLine:function(){var t=this.parent(n.Text);return this.dom.newLined=!0,this.dy(t.dom.leading*t.attr("font-size")).attr("x",t.x())}}}),n.extend(n.Text,n.Tspan,{plain:function(t){return!1===this._build&&this.clear(),this.node.appendChild(e.createTextNode(t)),this},tspan:function(t){var e=(this.textPath&&this.textPath()||this).node,r=new n.Tspan;return!1===this._build&&this.clear(),e.appendChild(r.node),r.text(t)},clear:function(){for(var t=(this.textPath&&this.textPath()||this).node;t.hasChildNodes();)t.removeChild(t.lastChild);return this},length:function(){return this.node.getComputedTextLength()}}),n.TextPath=n.invent({create:"textPath",inherit:n.Parent,parent:n.Text,construct:{morphArray:n.PathArray,path:function(t){for(var e=new n.TextPath,r=this.doc().defs().path(t);this.node.hasChildNodes();)e.node.appendChild(this.node.firstChild);return this.node.appendChild(e.node),e.attr("href","#"+r,n.xlink),this},array:function(){var t=this.track();return t?t.array():null},plot:function(t){var e=this.track(),n=null;return e&&(n=e.plot(t)),null==t?n:this},track:function(){var t=this.textPath();if(t)return t.reference("href")},textPath:function(){if(this.node.firstChild&&"textPath"==this.node.firstChild.nodeName)return n.adopt(this.node.firstChild)}}}),n.Nested=n.invent({create:function(){this.constructor.call(this,n.create("svg")),this.style("overflow","visible")},inherit:n.Container,construct:{nested:function(){return this.put(new n.Nested)}}}),n.A=n.invent({create:"a",inherit:n.Container,extend:{to:function(t){return this.attr("href",t,n.xlink)},show:function(t){return this.attr("show",t,n.xlink)},target:function(t){return this.attr("target",t)}},construct:{link:function(t){return this.put(new n.A).to(t)}}}),n.extend(n.Element,{linkTo:function(t){var e=new n.A;return"function"==typeof t?t.call(e,e):e.to(t),this.parent().put(e).put(this)}}),n.Marker=n.invent({create:"marker",inherit:n.Container,extend:{width:function(t){return this.attr("markerWidth",t)},height:function(t){return this.attr("markerHeight",t)},ref:function(t,e){return this.attr("refX",t).attr("refY",e)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return"url(#"+this.id()+")"}},construct:{marker:function(t,e,n){return this.defs().marker(t,e,n)}}}),n.extend(n.Defs,{marker:function(t,e,r){return this.put(new n.Marker).size(t,e).ref(t/2,e/2).viewbox(0,0,t,e).attr("orient","auto").update(r)}}),n.extend(n.Line,n.Polyline,n.Polygon,n.Path,{marker:function(t,e,r,i){var s=["marker"];return"all"!=t&&s.push(t),s=s.join("-"),t=arguments[1]instanceof n.Marker?arguments[1]:this.doc().marker(e,r,i),this.attr(s,t)}});var l={stroke:["color","width","opacity","linecap","linejoin","miterlimit","dasharray","dashoffset"],fill:["color","opacity","rule"],prefix:function(t,e){return"color"==e?t:t+"-"+e}};function o(t,e,r,i){return r+i.replace(n.regex.dots," .")}function h(t){return t.toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()})}function u(t){return t.charAt(0).toUpperCase()+t.slice(1)}function c(t){var e=t.toString(16);return 1==e.length?"0"+e:e}function m(t,e,n){if(null==e||null==n){var r=t.bbox();null==e?e=r.width/r.height*n:null==n&&(n=r.height/r.width*e)}return{width:e,height:n}}function p(t,e,n){return{x:e*t.a+n*t.c+0,y:e*t.b+n*t.d+0}}function d(t){return{a:t[0],b:t[1],c:t[2],d:t[3],e:t[4],f:t[5]}}function f(t,e){t.cx=null==t.cx?e.bbox().cx:t.cx,t.cy=null==t.cy?e.bbox().cy:t.cy}function x(t){return null==t.x&&(t.x=0,t.y=0,t.width=0,t.height=0),t.w=t.width,t.h=t.height,t.x2=t.x+t.width,t.y2=t.y+t.height,t.cx=t.x+t.width/2,t.cy=t.y+t.height/2,t}["fill","stroke"].forEach(function(t){var e,r={};r[t]=function(r){if(void 0===r)return this;if("string"==typeof r||n.Color.isRgb(r)||r&&"function"==typeof r.fill)this.attr(t,r);else for(e=l[t].length-1;e>=0;e--)null!=r[l[t][e]]&&this.attr(l.prefix(t,l[t][e]),r[l[t][e]]);return this},n.extend(n.Element,n.FX,r)}),n.extend(n.Element,n.FX,{rotate:function(t,e,n){return this.transform({rotation:t,cx:e,cy:n})},skew:function(t,e,n,r){return 1==arguments.length||3==arguments.length?this.transform({skew:t,cx:e,cy:n}):this.transform({skewX:t,skewY:e,cx:n,cy:r})},scale:function(t,e,n,r){return 1==arguments.length||3==arguments.length?this.transform({scale:t,cx:e,cy:n}):this.transform({scaleX:t,scaleY:e,cx:n,cy:r})},translate:function(t,e){return this.transform({x:t,y:e})},flip:function(t,e){return e="number"==typeof t?t:e,this.transform({flip:t||"both",offset:e})},matrix:function(t){return this.attr("transform",new n.Matrix(6==arguments.length?[].slice.call(arguments):t))},opacity:function(t){return this.attr("opacity",t)},dx:function(t){return this.x(new n.Number(t).plus(this instanceof n.FX?0:this.x()),!0)},dy:function(t){return this.y(new n.Number(t).plus(this instanceof n.FX?0:this.y()),!0)},dmove:function(t,e){return this.dx(t).dy(e)}}),n.extend(n.Rect,n.Ellipse,n.Circle,n.Gradient,n.FX,{radius:function(t,e){var r=(this._target||this).type;return"radial"==r||"circle"==r?this.attr("r",new n.Number(t)):this.rx(t).ry(null==e?t:e)}}),n.extend(n.Path,{length:function(){return this.node.getTotalLength()},pointAt:function(t){return this.node.getPointAtLength(t)}}),n.extend(n.Parent,n.Text,n.Tspan,n.FX,{font:function(t,e){if("object"==typeof t)for(e in t)this.font(e,t[e]);return"leading"==t?this.leading(e):"anchor"==t?this.attr("text-anchor",e):"size"==t||"family"==t||"weight"==t||"stretch"==t||"variant"==t||"style"==t?this.attr("font-"+t,e):this.attr(t,e)}}),n.Set=n.invent({create:function(t){Array.isArray(t)?this.members=t:this.clear()},extend:{add:function(){var t,e,n=[].slice.call(arguments);for(t=0,e=n.length;t<e;t++)this.members.push(n[t]);return this},remove:function(t){var e=this.index(t);return e>-1&&this.members.splice(e,1),this},each:function(t){for(var e=0,n=this.members.length;e<n;e++)t.apply(this.members[e],[e,this.members]);return this},clear:function(){return this.members=[],this},length:function(){return this.members.length},has:function(t){return this.index(t)>=0},index:function(t){return this.members.indexOf(t)},get:function(t){return this.members[t]},first:function(){return this.get(0)},last:function(){return this.get(this.members.length-1)},valueOf:function(){return this.members},bbox:function(){if(0==this.members.length)return new n.RBox;var t=this.members[0].rbox(this.members[0].doc());return this.each(function(){t=t.merge(this.rbox(this.doc()))}),t}},construct:{set:function(t){return new n.Set(t)}}}),n.FX.Set=n.invent({create:function(t){this.set=t}}),n.Set.inherit=function(){var t=[];for(var e in n.Shape.prototype)"function"==typeof n.Shape.prototype[e]&&"function"!=typeof n.Set.prototype[e]&&t.push(e);for(var e in t.forEach(function(t){n.Set.prototype[t]=function(){for(var e=0,r=this.members.length;e<r;e++)this.members[e]&&"function"==typeof this.members[e][t]&&this.members[e][t].apply(this.members[e],arguments);return"animate"==t?this.fx||(this.fx=new n.FX.Set(this)):this}}),t=[],n.FX.prototype)"function"==typeof n.FX.prototype[e]&&"function"!=typeof n.FX.Set.prototype[e]&&t.push(e);t.forEach(function(t){n.FX.Set.prototype[t]=function(){for(var e=0,n=this.set.members.length;e<n;e++)this.set.members[e].fx[t].apply(this.set.members[e].fx,arguments);return this}})},n.extend(n.Element,{data:function(t,e,n){if("object"==typeof t)for(e in t)this.data(e,t[e]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+t))}catch(e){return this.attr("data-"+t)}else this.attr("data-"+t,null===e?null:!0===n||"string"==typeof e||"number"==typeof e?e:JSON.stringify(e));return this}}),n.extend(n.Element,{remember:function(t,e){if("object"==typeof arguments[0])for(var e in t)this.remember(e,t[e]);else{if(1==arguments.length)return this.memory()[t];this.memory()[t]=e}return this},forget:function(){if(0==arguments.length)this._memory={};else for(var t=arguments.length-1;t>=0;t--)delete this.memory()[arguments[t]];return this},memory:function(){return this._memory||(this._memory={})}}),n.get=function(t){var r=e.getElementById(function(t){var e=t.toString().match(n.regex.reference);if(e)return e[1]}(t)||t);return n.adopt(r)},n.select=function(t,r){return new n.Set(n.utils.map((r||e).querySelectorAll(t),function(t){return n.adopt(t)}))},n.extend(n.Parent,{select:function(t){return n.select(t,this.node)}});var v="abcdef".split("");if("function"!=typeof t.CustomEvent){var y=function(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var r=e.createEvent("CustomEvent");return r.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),r};y.prototype=t.Event.prototype,t.CustomEvent=y}return function(e){for(var n=0,r=["moz","webkit"],i=0;i<r.length&&!t.requestAnimationFrame;++i)e.requestAnimationFrame=e[r[i]+"RequestAnimationFrame"],e.cancelAnimationFrame=e[r[i]+"CancelAnimationFrame"]||e[r[i]+"CancelRequestAnimationFrame"];e.requestAnimationFrame=e.requestAnimationFrame||function(t){var r=(new Date).getTime(),i=Math.max(0,16-(r-n)),s=e.setTimeout(function(){t(r+i)},i);return n=r+i,s},e.cancelAnimationFrame=e.cancelAnimationFrame||e.clearTimeout}(t),n}(i,i.document)}.call(e,n,e,t))||(t.exports=r)}("undefined"!=typeof window?window:this)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n(0),s=500,a=null,l=null,o=0,h=0;function u(t,e){t.addEventListener("mouseover",function(){return function(t,e){if(null!=a)return;a=window.setTimeout(function(){var n=e(t);null!=n&&function(t,e){m();var n=h,r=function(){var t=document.body,e=document.documentElement;return Math.max(t.scrollHeight,t.offsetHeight,e.clientHeight,e.scrollHeight,e.offsetHeight)}();r-(n+e.offsetHeight)<10&&(n=r-(e.offsetHeight+10));n<10&&(n=10);l=e,document.body.appendChild(l),l.style.left=o+"px",l.style.top=n+"px",l.addEventListener("mouseout",function(e){c(t,e)})}(t,n)},s)}(t,e)}),t.addEventListener("mouseout",function(e){return c(t,e)})}function c(t,e){var n=e.toElement||e.relatedTarget;n!=t&&n!=l&&(r.findAncestorP(n,function(e){return e==t})||r.findAncestorP(n,function(t){return t==l})||(window.clearTimeout(a),a=null,m()))}function m(){null!=l&&(document.body.removeChild(l),l=null)}function p(t){if(null==t.relOp)return null;var e=new DOMParser,n=null!=t.relOp.actualRows?"<tr>\n <th>Actual Number of Rows</th>\n <td>"+t.relOp.actualRows+"</td>\n </tr>":"",r=null!=t.relOp.actualRowsRead?"<tr>\n <th>Number of Rows Read</th>\n <td>"+t.relOp.actualRowsRead+"</td>\n </tr>":"";return e.parseFromString('\n <div class="qp-tt"><table><tbody>\n '+n+"\n "+r+"\n <tr>\n <th>Estimated Number of Rows</th>\n <td>"+t.relOp.estimatedRows+"</td>\n </tr>\n <tr>\n <th>Estimated Row Size</th>\n <td>"+d(t.relOp.estimatedRowSize)+"</td>\n </tr>\n <tr>\n <th>Estimated Data Size</th>\n <td>"+d(t.relOp.estimatedDataSize)+"</td>\n </tr>\n </tbody></tabke></div>\n ","text/html").getElementsByClassName("qp-tt")[0]}function d(t){if(t>=1e4){var e=t/1024;if(e>=1e4){var n=e/1024;return Math.round(n)+" MB"}return Math.round(e)+" KB"}return t+" B"}e.initTooltip=function(t){!function(t){t.querySelector(".qp-root").className+=" qp-noCssTooltip"}(t),document.onmousemove=function(t){o=t.pageX,h=t.pageY};for(var e=t.querySelectorAll(".qp-node"),n=0;n<e.length;n++)u(e[n],function(t){return t.querySelector(".qp-tt").cloneNode(!0)});var r=t.getElementsByTagName("polyline"),s=function(t){var e=new i.Line(r[t]);u(e.element,function(t){return p(e)})};for(n=0;n<r.length;n++)s(n)},e.buildLineTooltip=p,e.convertSize=d},function(t,e){t.exports='<?xml version="1.0" encoding="utf-8"?>\r\n<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"\r\n xmlns:msxsl="urn:schemas-microsoft-com:xslt"\r\n xmlns:exslt="http://exslt.org/common"\r\n xmlns:s="http://schemas.microsoft.com/sqlserver/2004/07/showplan"\r\n exclude-result-prefixes="msxsl s xsl">\r\n <xsl:output method="html" indent="no" omit-xml-declaration="yes" />\r\n\r\n \x3c!-- Disable built-in recursive processing templates --\x3e\r\n <xsl:template match="*|/|text()|@*" mode="NodeLabel" />\r\n <xsl:template match="*|/|text()|@*" mode="NodeLabel2" />\r\n <xsl:template match="*|/|text()|@*" mode="ToolTipDescription" />\r\n <xsl:template match="*|/|text()|@*" mode="ToolTipDetails" />\r\n\r\n \x3c!-- Default template --\x3e\r\n <xsl:template match="/">\r\n <xsl:apply-templates select="s:ShowPlanXML" />\r\n </xsl:template>\r\n\r\n \x3c!-- Outermost div that contains all statement plans. --\x3e\r\n <xsl:template match="s:ShowPlanXML">\r\n <div class="qp-root">\r\n <xsl:apply-templates select="s:BatchSequence/s:Batch/s:Statements/*" mode="Statement" /> \r\n </div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:BatchSequence/s:Batch/s:Statements/*" mode="Statement">\r\n <div class="qp-statement-header">\r\n <div class="qp-statement-header-row">\r\n <div><xsl:value-of select="@StatementText" /></div>\r\n </div>\r\n <xsl:apply-templates select="s:QueryPlan/s:MissingIndexes/s:MissingIndexGroup" mode="MissingIndex" />\r\n </div>\r\n <xsl:apply-templates select="." mode="QpTr" />\r\n </xsl:template>\r\n\r\n <xsl:template match="s:MissingIndexGroup" mode="MissingIndex">\r\n <div class="qp-statement-header-row missing-index">\r\n <div>Missing Index (Impact <xsl:value-of select="@Impact" />): <xsl:apply-templates select="s:MissingIndex" mode="CreateIndex" /></div>\r\n </div>\r\n </xsl:template>\r\n\r\n \x3c!-- This template produces the "CREATE INDEX ..." text --\x3e\r\n <xsl:template match="s:MissingIndex" mode="CreateIndex">CREATE NONCLUSTERED INDEX [&lt;Name of Missing Index, sysname,>] ON <xsl:value-of select="@Schema" />.<xsl:value-of select="@Table" /> (<xsl:for-each select="s:ColumnGroup[@Usage!=\'INCLUDE\']/s:Column">\r\n <xsl:value-of select="@Name" />\r\n <xsl:if test="position() != last()">,</xsl:if>\r\n</xsl:for-each>)\r\n<xsl:if test="s:ColumnGroup[@Usage=\'INCLUDE\']"> INCLUDE (<xsl:for-each select="s:ColumnGroup[@Usage=\'INCLUDE\']/s:Column">\r\n <xsl:value-of select="@Name" />\r\n <xsl:if test="position() != last()">,</xsl:if>\r\n</xsl:for-each>)</xsl:if>\r\n </xsl:template>\r\n \r\n \x3c!-- Each node has a parent qp-tr element which contains / positions the node and its children --\x3e\r\n <xsl:template match="s:RelOp|s:StmtSimple|s:StmtUseDb|s:StmtCond|s:StmtCursor|s:Operation" mode="QpTr">\r\n <div class="qp-tr">\r\n <xsl:if test="@StatementId">\r\n <xsl:attribute name="data-statement-id"><xsl:value-of select="@StatementId" /></xsl:attribute>\r\n </xsl:if>\r\n <div>\r\n <div class="qp-node-outer">\r\n <div class="qp-node">\r\n <xsl:if test="@NodeId">\r\n <xsl:attribute name="data-node-id"><xsl:value-of select="@NodeId" /></xsl:attribute>\r\n </xsl:if>\r\n <xsl:call-template name="NodeIcon" />\r\n <div><xsl:apply-templates select="." mode="NodeLabel" /></div>\r\n <xsl:apply-templates select="." mode="NodeLabel2" />\r\n <xsl:apply-templates select="." mode="NodeCostLabel" />\r\n <xsl:call-template name="ToolTip" />\r\n </div>\r\n </div>\r\n </div>\r\n <div><xsl:apply-templates select="*/*" mode="QpTr" /></div>\r\n </div>\r\n </xsl:template>\r\n\r\n \x3c!-- Writes the tool tip --\x3e\r\n <xsl:template name="ToolTip">\r\n <div class="qp-tt">\r\n <div class="qp-tt-header"><xsl:apply-templates select="." mode="NodeLabel" /></div>\r\n <div><xsl:apply-templates select="." mode="ToolTipDescription" /></div>\r\n <xsl:call-template name="ToolTipGrid" />\r\n <xsl:apply-templates select="* | @* | */* | */@*" mode="ToolTipDetails" />\r\n <xsl:choose>\r\n <xsl:when test="s:QueryPlan">\r\n <xsl:apply-templates select="s:QueryPlan" mode="QueryPlanToolTipDetails" />\r\n </xsl:when>\r\n <xsl:otherwise>\r\n <xsl:call-template name="ToolTipDetails" />\r\n </xsl:otherwise>\r\n </xsl:choose>\r\n </div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:QueryPlan" mode="QueryPlanToolTipDetails">\r\n <xsl:call-template name="ToolTipDetails" />\r\n </xsl:template>\r\n\r\n \x3c!-- Writes the grid of node properties to the tool tip --\x3e\r\n <xsl:template name="ToolTipGrid">\r\n <table>\r\n \r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:QueryPlan/@CachedPlanSize" />\r\n <xsl:with-param name="Label">Cached plan size</xsl:with-param>\r\n <xsl:with-param name="Value" select="concat(s:QueryPlan/@CachedPlanSize, \' KB\')" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@PhysicalOp" />\r\n <xsl:with-param name="Label">Physical Operation</xsl:with-param>\r\n <xsl:with-param name="Value"> \r\n <xsl:apply-templates select="." mode="PhysicalOperation" />\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@LogicalOp" />\r\n <xsl:with-param name="Label">Logical Operation</xsl:with-param>\r\n <xsl:with-param name="Value"> \r\n <xsl:apply-templates select="." mode="LogicalOperation" />\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualJoinType" />\r\n <xsl:with-param name="Label">Actual Join Type</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:value-of select="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualJoinType" />\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation" />\r\n <xsl:with-param name="Label">Actual Execution Mode</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:choose>\r\n <xsl:when test="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualExecutionMode">\r\n <xsl:value-of select="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualExecutionMode" />\r\n </xsl:when>\r\n <xsl:otherwise>Row</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Join Type</xsl:with-param>\r\n <xsl:with-param name="Value" select="@EstimatedJoinType" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@IsAdaptive" />\r\n <xsl:with-param name="Label">Is Adaptive</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:choose>\r\n <xsl:when test="@IsAdaptive = \'true\'">True</xsl:when>\r\n <xsl:otherwise>False</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Execution Mode</xsl:with-param>\r\n <xsl:with-param name="Value" select="@EstimatedExecutionMode" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Storage</xsl:with-param>\r\n <xsl:with-param name="Value" select="s:IndexScan/@Storage|s:TableScan/@Storage" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Number of Rows Read</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualRowsRead)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@AdaptiveThresholdRows" />\r\n <xsl:with-param name="Label">Adaptive Threshold Rows</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:value-of select="@AdaptiveThresholdRows" />\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n \r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation" />\r\n <xsl:with-param name="Label">Actual Number of Rows</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualRows)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation" />\r\n <xsl:with-param name="Label">Actual Number of Batches</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@Batches)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Operator Cost</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:variable name="EstimatedOperatorCost">\r\n <xsl:call-template name="EstimatedOperatorCost" />\r\n </xsl:variable>\r\n <xsl:variable name="TotalCost">\r\n <xsl:value-of select="ancestor::s:QueryPlan/s:RelOp/@EstimatedTotalSubtreeCost" />\r\n </xsl:variable>\r\n <xsl:variable name="Percentage">\r\n <xsl:choose>\r\n <xsl:when test="$TotalCost > 0"><xsl:value-of select="number($EstimatedOperatorCost) div number($TotalCost)" /></xsl:when>\r\n <xsl:otherwise>0</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:variable>\r\n <xsl:call-template name="round">\r\n <xsl:with-param name="value" select="$EstimatedOperatorCost" />\r\n </xsl:call-template> (<xsl:value-of select="format-number($Percentage, \'0%\')" />)</xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@EstimateIO" />\r\n <xsl:with-param name="Label">Estimated I/O Cost</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:call-template name="round">\r\n <xsl:with-param name="value" select="@EstimateIO" />\r\n </xsl:call-template>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@EstimateCPU" />\r\n <xsl:with-param name="Label">Estimated CPU Cost</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:call-template name="round">\r\n <xsl:with-param name="value" select="@EstimateCPU" />\r\n </xsl:call-template>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@StatementSubTreeCost | @EstimatedTotalSubtreeCost" />\r\n <xsl:with-param name="Label">Estimated Subtree Cost</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:call-template name="round">\r\n <xsl:with-param name="value" select="@StatementSubTreeCost | @EstimatedTotalSubtreeCost" />\r\n </xsl:call-template>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Number of Executions</xsl:with-param>\r\n <xsl:with-param name="Value" select="@EstimateRebinds + 1" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Number of Executions</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualExecutions)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Degree of Parallelism</xsl:with-param>\r\n <xsl:with-param name="Value" select="s:QueryPlan/@DegreeOfParallelism" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Memory Grant</xsl:with-param>\r\n <xsl:with-param name="Value" select="s:QueryPlan/@MemoryGrant" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Number of Rows to be Read</xsl:with-param>\r\n <xsl:with-param name="Value" select="@EstimatedRowsRead" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Estimated Number of Rows</xsl:with-param>\r\n <xsl:with-param name="Value" select="@StatementEstRows | @EstimateRows" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="@AvgRowSize" />\r\n <xsl:with-param name="Label">Estimated Row Size</xsl:with-param>\r\n <xsl:with-param name="Value" select="concat(@AvgRowSize, \' B\')" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation" />\r\n <xsl:with-param name="Label">Actual Rebinds</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualRebinds)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:RunTimeInformation" />\r\n <xsl:with-param name="Label">Actual Rewinds</xsl:with-param>\r\n <xsl:with-param name="Value" select="sum(s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualRewinds)" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Condition" select="s:IndexScan/@Ordered" />\r\n <xsl:with-param name="Label">Ordered</xsl:with-param>\r\n <xsl:with-param name="Value">\r\n <xsl:choose>\r\n <xsl:when test="s:IndexScan/@Ordered = \'true\'">True</xsl:when>\r\n <xsl:when test="s:IndexScan/@Ordered = 1">True</xsl:when>\r\n <xsl:otherwise>False</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Partitioning Type</xsl:with-param>\r\n <xsl:with-param name="Value" select="s:Parallelism/@PartitioningType" />\r\n </xsl:call-template>\r\n\r\n <xsl:call-template name="ToolTipRow">\r\n <xsl:with-param name="Label">Node ID</xsl:with-param>\r\n <xsl:with-param name="Value" select="@NodeId" />\r\n </xsl:call-template>\r\n\r\n </table>\r\n </xsl:template>\r\n\r\n \x3c!-- Gets the Physical Operation --\x3e\r\n <xsl:template match="s:RelOp" mode="PhysicalOperation">\r\n <xsl:value-of select="@PhysicalOp" />\r\n </xsl:template>\r\n <xsl:template match="s:RelOp[s:IndexScan/@Lookup]" mode="PhysicalOperation">Key Lookup</xsl:template>\r\n \r\n \x3c!-- Gets the Logical Operation --\x3e\r\n <xsl:template match="s:RelOp" mode="LogicalOperation">\r\n <xsl:value-of select="@LogicalOp" />\r\n </xsl:template>\r\n <xsl:template match="s:RelOp[s:IndexScan/@Lookup]" mode="LogicalOperation">Key Lookup</xsl:template>\r\n \r\n \x3c!-- Calculates the estimated operator cost. --\x3e\r\n <xsl:template name="EstimatedOperatorCost">\r\n <xsl:variable name="EstimatedTotalSubtreeCost">\r\n <xsl:call-template name="convertSciToNumString">\r\n <xsl:with-param name="inputVal">\r\n <xsl:choose>\r\n <xsl:when test="@EstimatedTotalSubtreeCost"><xsl:value-of select="@EstimatedTotalSubtreeCost" /></xsl:when>\r\n <xsl:otherwise>0</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:with-param>\r\n </xsl:call-template>\r\n </xsl:variable>\r\n <xsl:variable name="ChildEstimatedSubtreeCost">\r\n <xsl:for-each select="*/s:RelOp">\r\n <value>\r\n <xsl:call-template name="convertSciToNumString">\r\n <xsl:with-param name="inputVal" select="@EstimatedTotalSubtreeCost" />\r\n </xsl:call-template>\r\n </value>\r\n </xsl:for-each>\r\n </xsl:variable>\r\n <xsl:variable name="TotalChildEstimatedSubtreeCost">\r\n <xsl:choose>\r\n <xsl:when test="function-available(\'exslt:node-set\')">\r\n <xsl:value-of select=\'sum(exslt:node-set($ChildEstimatedSubtreeCost)/value)\' />\r\n </xsl:when>\r\n <xsl:when test="function-available(\'msxsl:node-set\')">\r\n <xsl:value-of select=\'sum(msxsl:node-set($ChildEstimatedSubtreeCost)/value)\' />\r\n </xsl:when>\r\n </xsl:choose>\r\n </xsl:variable>\r\n <xsl:choose>\r\n <xsl:when test="number($EstimatedTotalSubtreeCost) - number($TotalChildEstimatedSubtreeCost) &lt; 0">0</xsl:when>\r\n <xsl:otherwise>\r\n <xsl:value-of select="number($EstimatedTotalSubtreeCost) - number($TotalChildEstimatedSubtreeCost)" />\r\n </xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:template>\r\n\r\n \x3c!-- Renders a row in the tool tip details table. --\x3e\r\n <xsl:template name="ToolTipRow">\r\n <xsl:param name="Label" />\r\n <xsl:param name="Value" />\r\n <xsl:param name="Condition" select="$Value" />\r\n <xsl:if test="$Condition">\r\n <tr>\r\n <th><xsl:value-of select="$Label" /></th>\r\n <td><xsl:value-of select="$Value" /></td>\r\n </tr>\r\n </xsl:if>\r\n </xsl:template>\r\n\r\n \x3c!-- Prints the name of an object. --\x3e\r\n <xsl:template match="s:Object | s:ColumnReference" mode="ObjectName">\r\n <xsl:param name="ExcludeDatabaseName" select="false()" />\r\n <xsl:choose>\r\n <xsl:when test="$ExcludeDatabaseName">\r\n <xsl:for-each select="@Table | @Index | @Column | @Alias">\r\n <xsl:value-of select="." />\r\n <xsl:if test="position() != last()">.</xsl:if>\r\n </xsl:for-each>\r\n </xsl:when>\r\n <xsl:otherwise>\r\n <xsl:for-each select="@Database | @Schema | @Table | @Index | @Column | @Alias">\r\n <xsl:value-of select="." />\r\n <xsl:if test="position() != last()">.</xsl:if>\r\n </xsl:for-each>\r\n </xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:template>\r\n \r\n <xsl:template match="s:Object | s:ColumnReference" mode="ObjectNameNoAlias">\r\n <xsl:for-each select="@Database | @Schema | @Table | @Index | @Column">\r\n <xsl:value-of select="." />\r\n <xsl:if test="position() != last()">.</xsl:if>\r\n </xsl:for-each>\r\n </xsl:template>\r\n\r\n \x3c!-- Displays the node cost label. --\x3e \r\n <xsl:template match="s:RelOp" mode="NodeCostLabel">\r\n <xsl:variable name="EstimatedOperatorCost"><xsl:call-template name="EstimatedOperatorCost" /></xsl:variable>\r\n <xsl:variable name="TotalCost"><xsl:value-of select="ancestor::s:QueryPlan/s:RelOp/@EstimatedTotalSubtreeCost" /></xsl:variable>\r\n <div>Cost: <xsl:value-of select="format-number(number($EstimatedOperatorCost) div number($TotalCost), \'0%\')" /></div>\r\n </xsl:template>\r\n\r\n \x3c!-- Dont show the node cost for statements. --\x3e\r\n <xsl:template match="s:StmtSimple|s:StmtUseDb" mode="NodeCostLabel" />\r\n\r\n <xsl:template match="s:StmtCursor|s:Operation|s:StmtCond" mode="NodeCostLabel">\r\n <div>Cost: 0%</div>\r\n </xsl:template>\r\n\r\n \x3c!-- \r\n ================================\r\n Tool tip detail sections\r\n ================================\r\n The following section contains templates used for writing the detail sections at the bottom of the tool tip,\r\n for example listing outputs, or information about the object to which an operator applies.\r\n --\x3e\r\n\r\n <xsl:template match="*/s:Object" mode="ToolTipDetails">\r\n \x3c!-- TODO: Make sure this works all the time --\x3e\r\n <div class="qp-bold">Object</div>\r\n <div><xsl:apply-templates select="." mode="ObjectName" /></div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:SetPredicate[s:ScalarOperator/@ScalarString]" mode="ToolTipDetails">\r\n <div class="qp-bold">Predicate</div>\r\n <div><xsl:value-of select="s:ScalarOperator/@ScalarString" /></div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:Predicate[s:ScalarOperator/@ScalarString]" mode="ToolTipDetails">\r\n <div class="qp-bold">Predicate</div>\r\n <div><xsl:value-of select="s:ScalarOperator/@ScalarString" /></div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:TopExpression[s:ScalarOperator/@ScalarString]" mode="ToolTipDetails">\r\n <div class="qp-bold">Top Expression</div>\r\n <div><xsl:value-of select="s:ScalarOperator/@ScalarString" /></div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:OutputList[count(s:ColumnReference) > 0]" mode="ToolTipDetails">\r\n <div class="qp-bold">Output List</div>\r\n <xsl:for-each select="s:ColumnReference">\r\n <div><xsl:apply-templates select="." mode="ObjectName" /></div>\r\n </xsl:for-each>\r\n </xsl:template>\r\n \r\n <xsl:template match="s:AdaptiveJoin/s:HashKeysProbe" mode="ToolTipDetails">\r\n <div class="qp-bold">Hash Keys Probe</div>\r\n <xsl:for-each select="s:ColumnReference">\r\n <div><xsl:apply-templates select="." mode="ObjectNameNoAlias" /></div>\r\n </xsl:for-each>\r\n </xsl:template>\r\n \r\n <xsl:template match="s:AdaptiveJoin/s:OuterReferences" mode="ToolTipDetails">\r\n <div class="qp-bold">Outer References</div>\r\n <xsl:for-each select="s:ColumnReference">\r\n <div><xsl:apply-templates select="." mode="ObjectNameNoAlias" /></div>\r\n </xsl:for-each>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:NestedLoops/s:OuterReferences[count(s:ColumnReference) > 0]" mode="ToolTipDetails">\r\n <div class="qp-bold">Outer References</div>\r\n <xsl:for-each select="s:ColumnReference">\r\n <div><xsl:apply-templates select="." mode="ObjectName" /></div>\r\n </xsl:for-each>\r\n </xsl:template>\r\n\r\n <xsl:template match="@StatementText" mode="ToolTipDetails">\r\n <div class="qp-bold">Statement</div>\r\n <div><xsl:value-of select="." /></div>\r\n </xsl:template>\r\n \r\n <xsl:template match="s:StmtSimple/s:StoredProc" mode="ToolTipDetails">\r\n <div class="qp-bold">Procedure Name</div>\r\n <div><xsl:value-of select="@ProcName" /></div>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:Sort/s:OrderBy[count(s:OrderByColumn/s:ColumnReference) > 0]" mode="ToolTipDetails">\r\n <div class="qp-bold">Order By</div>\r\n <xsl:for-each select="s:OrderByColumn">\r\n <div>\r\n <xsl:apply-templates select="s:ColumnReference" mode="ObjectName" />\r\n <xsl:choose>\r\n <xsl:when test="@Ascending = \'true\'"> Ascending</xsl:when>\r\n <xsl:when test="@Ascending = 1"> Ascending</xsl:when>\r\n <xsl:otherwise> Descending</xsl:otherwise>\r\n </xsl:choose>\r\n </div>\r\n </xsl:for-each>\r\n </xsl:template>\r\n\r\n \x3c!-- \r\n Seek Predicates Tooltip\r\n --\x3e\r\n\r\n <xsl:template match="s:SeekPredicates" mode="ToolTipDetails">\r\n <div class="qp-bold">Seek Predicates</div>\r\n <div>\r\n <xsl:for-each select="s:SeekPredicateNew/s:SeekKeys">\r\n <xsl:call-template name="SeekKeyDetail">\r\n <xsl:with-param name="position" select="position()" />\r\n </xsl:call-template>\r\n <xsl:if test="position() != last()">, </xsl:if>\r\n </xsl:for-each>\r\n </div>\r\n </xsl:template>\r\n\r\n \x3c!-- Turns out using apply-templates for this was a bad idea, but its too big a change to fix it all right now. This is probably\r\n the template that should contain tooltip details, I\'ll try to refactor more stuff into here over time, maybe. --\x3e\r\n <xsl:template name="ToolTipDetails">\r\n <xsl:variable name="relop" select="." />\r\n <xsl:if test="s:Warnings">\r\n <div class="qp-bold">Warnings</div>\r\n <div>\r\n <xsl:if test="s:Warnings/@NoJoinPredicate=1 or s:Warnings/@NoJoinPredicate=true"><div>No Join Predicate</div></xsl:if>\r\n <xsl:for-each select="s:UnmatchedIndexes/s:Parameterization/s:Object">\r\n <div>Unmatched index: <xsl:apply-templates select="." mode="ObjectNameNoAlias" /></div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:SpillToTempDb">\r\n <div>Operator used tempdb to spill data during execution with spill level <xsl:value-of select="@SpillLevel" /> and <xsl:value-of select="@SpilledThreadCount" /> spilled thread(s)</div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:ColumnsWithNoStatistics/s:ColumnReference">\r\n <div>Columns With No Statistics: <xsl:apply-templates select="." mode="ObjectNameNoAlias" /></div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:Wait">\r\n <div>The query had to wait <xsl:value-of select="@WaitTime" /> seconds for <xsl:value-of select="@WaitType" /> during execution.</div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:PlanAffectingConvert">\r\n <div>Type conversion in expression (<xsl:value-of select="@Expression" />) may affect "<xsl:value-of select="@ConvertIssue" />" in query plan choice.</div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:SortSpillDetails">\r\n <div><xsl:value-of select="$relop/@LogicalOp" /> wrote <xsl:value-of select="@WritesToTempDb" /> pages to and read <xsl:value-of select="@ReadsFromTempDb" /> pages from tempdb with granted memory <xsl:value-of select="@GrantedMemoryKb" />KB and used memory <xsl:value-of select="@UsedMemoryKb" />KB.</div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:MemoryGrantWarning">\r\n <div>The query memory grant detected "<xsl:value-of select="@GrantWarningKind" />", which may impact the reliability. Grant size: Initial <xsl:value-of select="@RequestedMemory" /> KB, Final <xsl:value-of select="@GrantedMemory" /> KB, Used <xsl:value-of select="@MaxUsedMemory" /> KB.</div>\r\n </xsl:for-each>\r\n <xsl:for-each select="s:Warnings/s:HashSpillDetails">\r\n <div>Hash wrote <xsl:value-of select="@WritesToTempDb" /> pages to and read <xsl:value-of select="@ReadsFromTempDb" /> pages from tempdb with granted memory <xsl:value-of select="@GrantedMemoryKb" />KB and used memory <xsl:value-of select="@UsedMemoryKb" />KB.</div>\r\n </xsl:for-each>\r\n </div>\r\n </xsl:if>\r\n </xsl:template>\r\n\r\n <xsl:template name="SeekKeyDetail">\r\n <xsl:param name="position" />Seek Keys[<xsl:value-of select="$position" />]: <xsl:for-each select="s:Prefix|s:StartRange|s:EndRange">\r\n <xsl:choose>\r\n <xsl:when test="self::s:Prefix">Prefix: </xsl:when>\r\n <xsl:when test="self::s:StartRange">Start: </xsl:when>\r\n <xsl:when test="self::s:EndRange">End: </xsl:when>\r\n </xsl:choose>\r\n <xsl:for-each select="s:RangeColumns/s:ColumnReference">\r\n <xsl:apply-templates select="." mode="ObjectNameNoAlias" />\r\n <xsl:if test="position() != last()">, </xsl:if>\r\n </xsl:for-each>\r\n <xsl:choose>\r\n <xsl:when test="@ScanType = \'EQ\'"> = </xsl:when>\r\n <xsl:when test="@ScanType = \'LT\'"> &lt; </xsl:when>\r\n <xsl:when test="@ScanType = \'GT\'"> > </xsl:when>\r\n <xsl:when test="@ScanType = \'LE\'"> &lt;= </xsl:when>\r\n <xsl:when test="@ScanType = \'GE\'"> >= </xsl:when>\r\n </xsl:choose>\r\n <xsl:for-each select="s:RangeExpressions/s:ScalarOperator">Scalar Operator(<xsl:value-of select="@ScalarString" />)<xsl:if test="position() != last()">, </xsl:if>\r\n </xsl:for-each>\r\n <xsl:if test="position() != last()">, </xsl:if>\r\n </xsl:for-each>\r\n </xsl:template>\r\n\r\n <xsl:template name="NodeIcon">\r\n <xsl:variable name="iconName">\r\n <xsl:choose>\r\n \x3c!-- Use the logical operation to determine the icon for the "Parallelism" operators. --\x3e\r\n <xsl:when test="@PhysicalOp = \'Parallelism\'"><xsl:value-of select="translate(@LogicalOp, \' \', \'\')" /></xsl:when>\r\n <xsl:when test="s:CursorPlan/@CursorActualType"><xsl:value-of select="s:CursorPlan/@CursorActualType" /></xsl:when>\r\n <xsl:when test="@OperationType"><xsl:value-of select="@OperationType" /></xsl:when>\r\n <xsl:when test="s:IndexScan/@Lookup">KeyLookup</xsl:when>\r\n <xsl:when test="s:IndexScan/@Storage = \'ColumnStore\'">ColumnStoreIndexScan</xsl:when>\r\n <xsl:when test="s:ScalarInsert/s:Object/@Storage = \'ColumnStore\'">ColumnStoreIndexInsert</xsl:when>\r\n <xsl:when test="s:Update/s:Object/@Storage = \'ColumnStore\'">ColumnStoreIndex<xsl:value-of select="@LogicalOp" /></xsl:when>\r\n <xsl:when test="s:TableValuedFunction">TableValuedFunction</xsl:when>\r\n \x3c!-- Use the physical operation to determine icon if it is present. --\x3e\r\n <xsl:when test="@PhysicalOp"><xsl:value-of select="translate(@PhysicalOp, \' \', \'\')" /></xsl:when>\r\n \x3c!-- Matches all statements. --\x3e\r\n <xsl:when test="local-name() = \'StmtSimple\'">Statement</xsl:when>\r\n <xsl:when test="local-name() = \'StmtCursor\'">StmtCursor</xsl:when>\r\n <xsl:when test="local-name() = \'StmtCond\'">StmtCond</xsl:when>\r\n \x3c!-- Fallback - show the Bitmap icon. --\x3e\r\n <xsl:otherwise>Catchall</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:variable>\r\n <xsl:variable name="executionMode">\r\n <xsl:choose>\r\n <xsl:when test="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualExecutionMode">\r\n <xsl:value-of select="s:RunTimeInformation/s:RunTimeCountersPerThread/@ActualExecutionMode" />\r\n </xsl:when>\r\n <xsl:otherwise><xsl:value-of select="@EstimatedExecutionMode" /></xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:variable>\r\n <xsl:element name="div">\r\n <xsl:attribute name="class">qp-icon-<xsl:value-of select="$iconName" /></xsl:attribute>\r\n <xsl:if test="s:Warnings or s:QueryPlan/s:Warnings"><div class="qp-iconwarn" /></xsl:if>\r\n <xsl:if test="@Parallel=\'1\' or @Parallel=\'true\'"><div class="qp-iconpar" /></xsl:if>\r\n <xsl:if test="$executionMode=\'Batch\'"><div class="qp-iconbatch" /></xsl:if>\r\n </xsl:element>\r\n </xsl:template>\r\n\r\n \x3c!-- \r\n ================================\r\n Node labels\r\n ================================\r\n The following section contains templates used to determine the first (main) label for a node.\r\n --\x3e\r\n\r\n <xsl:template match="s:RelOp[s:ScalarInsert/s:Object/@Storage=\'ColumnStore\']" mode="NodeLabel">Columnstore Index Insert</xsl:template>\r\n <xsl:template match="s:RelOp[s:Update/s:Object/@Storage=\'ColumnStore\']" mode="NodeLabel">Columnstore Index <xsl:value-of select="@LogicalOp"/></xsl:template>\r\n <xsl:template match="s:RelOp[s:IndexScan]" mode="NodeLabel">\r\n <xsl:choose>\r\n <xsl:when test="s:IndexScan/@Storage=\'ColumnStore\'">Columnstore Index Scan</xsl:when>\r\n <xsl:when test="s:IndexScan/@Lookup and s:IndexScan/s:Object/@IndexKind=\'Clustered\'">Key Lookup</xsl:when>\r\n <xsl:when test="s:IndexScan/@Lookup">RID Lookup</xsl:when>\r\n <xsl:otherwise><xsl:value-of select="@PhysicalOp" /></xsl:otherwise>\r\n </xsl:choose>\r\n <xsl:if test="s:IndexScan/s:Object/@IndexKind"> (<xsl:value-of select="s:IndexScan/s:Object/@IndexKind" />)</xsl:if>\r\n </xsl:template>\r\n\r\n <xsl:template match="s:RelOp" mode="NodeLabel">\r\n <xsl:value-of select="@PhysicalOp" />\r\n </xsl:template>\r\n\r\n <xsl:template match="*[@StatementType]" mode="NodeLabel">\r\n <xsl:value-of select="@StatementType" />\r\n </xsl:template>\r\n \r\n <xsl:template match="*[s:StoredProc]" mode="NodeLabel">Stored Procedure</xsl:template>\r\n\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType = \'Dynamic\']" mode="NodeLabel">Dynamic</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType = \'FastForward\']" mode="NodeLabel">Fast Forward</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType = \'Keyset\']" mode="NodeLabel">Keyset</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType = \'SnapShot\']" mode="NodeLabel">Snapshot</xsl:template> \r\n\r\n <xsl:template match="*[@OperationType = \'FetchQuery\']" mode="NodeLabel">Fetch Query</xsl:template>\r\n <xsl:template match="*[@OperationType = \'PopulateQuery\']" mode="NodeLabel">Population Query</xsl:template>\r\n <xsl:template match="*[@OperationType = \'RefreshQuery\']" mode="NodeLabel">Refresh Query</xsl:template>\r\n\r\n \x3c!--\r\n ================================\r\n Node alternate labels\r\n ================================\r\n The following section contains templates used to determine the second label to be displayed for a node.\r\n --\x3e\r\n\r\n \x3c!-- Display the object for any node that has one --\x3e\r\n <xsl:template match="*[*/s:Object]" mode="NodeLabel2">\r\n <xsl:variable name="ObjectName">\r\n <xsl:apply-templates select="*/s:Object" mode="ObjectName">\r\n <xsl:with-param name="ExcludeDatabaseName" select="true()" />\r\n </xsl:apply-templates>\r\n </xsl:variable>\r\n <div>\r\n <xsl:value-of select="substring($ObjectName, 0, 36)" />\r\n <xsl:if test="string-length($ObjectName) >= 36">…</xsl:if>\r\n </div>\r\n </xsl:template>\r\n\r\n \x3c!-- Display the logical operation for any node where it is not the same as the physical operation. --\x3e\r\n <xsl:template match="s:RelOp[@LogicalOp != @PhysicalOp]" mode="NodeLabel2">\r\n <div>(<xsl:value-of select="@LogicalOp" />)</div>\r\n </xsl:template>\r\n\r\n \x3c!-- Disable the default template --\x3e\r\n <xsl:template match="*" mode="NodeLabel2" />\r\n\r\n \x3c!-- \r\n ================================\r\n Tool tip descriptions\r\n ================================\r\n The following section contains templates used for writing the description shown in the tool tip.\r\n --\x3e\r\n\r\n <xsl:template match="*[@PhysicalOp = \'Table Insert\']" mode="ToolTipDescription">Insert input rows into the table specified in Argument field.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Compute Scalar\']" mode="ToolTipDescription">Compute new values from existing values in a row.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Sort\']" mode="ToolTipDescription">Sort the input.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Clustered Index Scan\']" mode="ToolTipDescription">Scanning a clustered index, entirely or only a range.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Stream Aggregate\']" mode="ToolTipDescription">Compute summary values for groups of rows in a suitably sorted stream.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Hash Match\']" mode="ToolTipDescription">Use each row from the top input to build a hash table, and each row from the bottom input to probe into the hash table, outputting all matching rows.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Bitmap\']" mode="ToolTipDescription">Bitmap.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Clustered Index Seek\']" mode="ToolTipDescription">Scanning a particular range of rows from a clustered index.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Index Seek\']" mode="ToolTipDescription">Scan a particular range of rows from a nonclustered index.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Adaptive Join\']" mode="ToolTipDescription">Chooses dynamically between hash join and nested loops.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Index Spool\']" mode="ToolTipDescription">Reformats the data from the input into a temporary index, which is then used for seeking with the supplied seek predicate.</xsl:template>\r\n <xsl:template match="*[s:IndexScan/@Lookup]" mode="ToolTipDescription">Uses a supplied clustering key to lookup on a table that has a clustered index.</xsl:template>\r\n\r\n <xsl:template match="*[@PhysicalOp = \'Parallelism\' and @LogicalOp=\'Repartition Streams\']" mode="ToolTipDescription">Repartition Streams.</xsl:template>\r\n <xsl:template match="*[@PhysicalOp = \'Parallelism\']" mode="ToolTipDescription">An operation involving parallelism.</xsl:template>\r\n \r\n <xsl:template match="*[s:TableScan]" mode="ToolTipDescription">Scan rows from a table.</xsl:template>\r\n <xsl:template match="*[s:NestedLoops]" mode="ToolTipDescription">For each row in the top (outer) input, scan the bottom (inner) input, and output matching rows.</xsl:template>\r\n <xsl:template match="*[s:Top]" mode="ToolTipDescription">Select the first few rows based on a sort order.</xsl:template>\r\n \r\n <xsl:template match="*[@OperationType=\'FetchQuery\']" mode="ToolTipDescription">The query used to retrieve rows when a fetch is issued against a cursor.</xsl:template>\r\n <xsl:template match="*[@OperationType=\'PopulateQuery\']" mode="ToolTipDescription">The query used to populate a cursor\'s work table when the cursor is opened.</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType=\'FastForward\']" mode="ToolTipDescription">Fast Forward.</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType=\'Dynamic\']" mode="ToolTipDescription">Cursor that can see all changes made by others.</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType=\'Keyset\']" mode="ToolTipDescription">Cursor that can see updates made by others, but not inserts.</xsl:template>\r\n <xsl:template match="*[s:CursorPlan/@CursorActualType=\'SnapShot\']" mode="ToolTipDescription">A cursor that does not see changes made by others.</xsl:template>\r\n\r\n \x3c!-- \r\n ================================\r\n Number handling\r\n ================================\r\n The following section contains templates used for handling numbers (scientific notation, rounding etc...)\r\n --\x3e\r\n\r\n \x3c!-- Outputs a number rounded to 7 decimal places - to be used for displaying all numbers.\r\n This template accepts numbers in scientific notation. --\x3e\r\n <xsl:template name="round">\r\n <xsl:param name="value" select="0" />\r\n <xsl:variable name="number">\r\n <xsl:call-template name="convertSciToNumString">\r\n <xsl:with-param name="inputVal" select="$value" />\r\n </xsl:call-template>\r\n </xsl:variable>\r\n <xsl:value-of select="format-number(round(number($number) * 10000000) div 10000000, \'0.#######\')" />\r\n </xsl:template>\r\n \r\n \x3c!-- Template for handling of scientific numbers\r\n See: http://www.orm-designer.com/article/xslt-convert-scientific-notation-to-decimal-number --\x3e\r\n <xsl:variable name="max-exp">\r\n <xsl:value-of select="\'0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\'" />\r\n </xsl:variable>\r\n\r\n <xsl:template name="convertSciToNumString">\r\n <xsl:param name="inputVal" select="0" />\r\n\r\n <xsl:variable name="numInput">\r\n <xsl:value-of select="translate(string($inputVal),\'e\',\'E\')" />\r\n </xsl:variable>\r\n\r\n <xsl:choose>\r\n <xsl:when test="number($numInput) = $numInput">\r\n <xsl:value-of select="$numInput" />\r\n </xsl:when> \r\n <xsl:otherwise>\r\n \x3c!-- ==== Mantisa ==== --\x3e\r\n <xsl:variable name="numMantisa">\r\n <xsl:value-of select="number(substring-before($numInput,\'E\'))" />\r\n </xsl:variable>\r\n\r\n \x3c!-- ==== Exponent ==== --\x3e\r\n <xsl:variable name="numExponent">\r\n <xsl:choose>\r\n <xsl:when test="contains($numInput,\'E+\')">\r\n <xsl:value-of select="substring-after($numInput,\'E+\')" />\r\n </xsl:when>\r\n <xsl:otherwise>\r\n <xsl:value-of select="substring-after($numInput,\'E\')" />\r\n </xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:variable>\r\n\r\n \x3c!-- ==== Coefficient ==== --\x3e\r\n <xsl:variable name="numCoefficient">\r\n <xsl:choose>\r\n <xsl:when test="$numExponent > 0">\r\n <xsl:text>1</xsl:text>\r\n <xsl:value-of select="substring($max-exp, 1, number($numExponent))" />\r\n </xsl:when>\r\n <xsl:when test="$numExponent &lt; 0">\r\n <xsl:text>0.</xsl:text>\r\n <xsl:value-of select="substring($max-exp, 1, -number($numExponent)-1)" />\r\n <xsl:text>1</xsl:text>\r\n </xsl:when>\r\n <xsl:otherwise>1</xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:variable>\r\n <xsl:value-of select="number($numCoefficient) * number($numMantisa)" />\r\n </xsl:otherwise>\r\n </xsl:choose>\r\n </xsl:template>\r\n</xsl:stylesheet>\r\n'}])});
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx
new file mode 100644
index 0000000000..95f2b01ee2
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx
@@ -0,0 +1,120 @@
+import { render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { createExplainToken } from "@/utils/explainToken";
+import { ExplainVisualizerApp } from "./ExplainVisualizerApp";
+import { MSSQL_PLAN_INVALID_XML_MESSAGE } from "./mssql-plan";
+import {
+ POSTGRES_PLAN_EMPTY_MESSAGE,
+ POSTGRES_PLAN_INVALID_JSON_MESSAGE,
+} from "./postgres-plan";
+import indexSeekKeyLookup from "./test-data/mssql/index-seek-key-lookup.xml?raw";
+import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
+import spannerHashJoin from "./test-data/spanner/hash-join.json";
+
+vi.mock("react-resizable-panels", () => ({
+ Group: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Separator: () => <div />,
+}));
+
+/** Opens the page the way the SQL editor does: a stored plan and its token. */
+const openPlan = (engine: Engine, explain: string, statement = "SELECT 1") => {
+ const token = createExplainToken({ engine, explain, statement });
+ history.replaceState(null, "", `/explain-visualizer.html?token=${token}`);
+ return render(<ExplainVisualizerApp />);
+};
+
+const card = (name: RegExp) =>
+ screen
+ .getAllByTestId("plan-node-card")
+ .find((entry) => name.test(entry.getAttribute("aria-label") ?? ""));
+
+describe("ExplainVisualizerApp", () => {
+ beforeEach(() => {
+ sessionStorage.clear();
+ // jsdom's window exposes no matchMedia under vitest; the viewer queries it
+ // to decide whether to stack the detail pane.
+ window.matchMedia = ((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => true,
+ })) as unknown as typeof window.matchMedia;
+ });
+
+ test("draws a PostgreSQL plan", () => {
+ openPlan(Engine.POSTGRES, JSON.stringify(cteNestedLoopInitplan));
+
+ for (const nodeType of [/^Limit/, /^Nested Loop/, /^Index Scan/]) {
+ expect(card(nodeType)).toBeDefined();
+ }
+ expect(screen.getByText("InitPlan 1")).toBeInTheDocument();
+ });
+
+ test("draws a SQL Server plan in the same viewer", () => {
+ openPlan(Engine.MSSQL, indexSeekKeyLookup);
+
+ for (const nodeType of [/^SELECT/, /^Index Seek/, /^Key Lookup/]) {
+ expect(card(nodeType)).toBeDefined();
+ }
+ expect(screen.getByRole("tab", { name: "Summary" })).toBeInTheDocument();
+ });
+
+ test("draws a Spanner plan in the same viewer", () => {
+ openPlan(Engine.SPANNER, JSON.stringify(spannerHashJoin));
+
+ for (const nodeType of [/^Hash Join/, /^Table Scan/, /^Index Scan/]) {
+ expect(card(nodeType)).toBeDefined();
+ }
+ expect(screen.getByRole("tab", { name: "Diagram" })).toBeInTheDocument();
+ });
+
+ test("explains a plan it cannot read and still shows what the server returned", () => {
+ openPlan(Engine.POSTGRES, "Seq Scan on customers");
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ POSTGRES_PLAN_INVALID_JSON_MESSAGE
+ );
+ expect(screen.getByText("Seq Scan on customers")).toBeInTheDocument();
+ expect(screen.queryByTestId("plan-diagram-viewport")).toBeNull();
+ });
+
+ test("reads each engine's plan with that engine's parser", () => {
+ // Valid JSON, but SQL Server's plan is XML.
+ openPlan(Engine.MSSQL, JSON.stringify(cteNestedLoopInitplan));
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ MSSQL_PLAN_INVALID_XML_MESSAGE
+ );
+ });
+
+ test("explains an empty plan without echoing an empty block", () => {
+ const { container } = openPlan(Engine.POSTGRES, "");
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ POSTGRES_PLAN_EMPTY_MESSAGE
+ );
+ expect(container.querySelector("pre")).toBeNull();
+ });
+
+ test("says the session expired when the plan is no longer stored", () => {
+ history.replaceState(null, "", "/explain-visualizer.html?token=explain-gone");
+ render(<ExplainVisualizerApp />);
+
+ expect(screen.getByRole("alert")).toHaveTextContent("Session expired");
+ });
+
+ test("turns away an engine the visualizer cannot draw", () => {
+ openPlan(Engine.MYSQL, "-> Table scan on t");
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Unsupported database engine"
+ );
+ });
+});
diff --git a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx
index 4eefcca13b..b62734d0e2 100644
--- a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx
+++ b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx
@@ -1,10 +1,63 @@
import { parse } from "qs";
-import { type ReactNode, useMemo } from "react";
+import { useMemo } from "react";
+import { Alert } from "@/components/ui/alert";
import { Engine } from "@/types/proto-es/v1/common_pb";
-import { readExplainFromToken } from "@/utils/explainToken";
-import { MSSQLPlanView } from "./MSSQLPlanView";
-import { PostgresPlanView } from "./PostgresPlanView";
-import { SpannerQueryPlan } from "./SpannerQueryPlan";
+import {
+ isVisualizerEngine,
+ readExplainFromToken,
+ type VisualizerEngine,
+} from "@/utils/explainToken";
+import { parseMssqlPlan } from "./mssql-plan";
+import type { PlanParseResult } from "./plan-model";
+import { parsePostgresPlan } from "./postgres-plan";
+import { QueryPlanViewer } from "./QueryPlanViewer";
+import { parseSpannerPlan } from "./spanner-plan";
+
+const PARSERS: Record<VisualizerEngine, (source: string) => PlanParseResult> = {
+ [Engine.POSTGRES]: parsePostgresPlan,
+ [Engine.MSSQL]: parseMssqlPlan,
+ [Engine.SPANNER]: parseSpannerPlan,
+};
+
+const STATUS_CLASS =
+ "flex h-full min-h-0 w-full flex-col gap-4 overflow-auto bg-background p-4";
+
+function PlanView({
+ parsePlan,
+ planSource,
+ planQuery,
+}: {
+ parsePlan: (source: string) => PlanParseResult;
+ planSource: string;
+ planQuery?: string;
+}) {
+ const result = useMemo(() => parsePlan(planSource), [parsePlan, planSource]);
+
+ if (!result.ok) {
+ return (
+ <div className={STATUS_CLASS}>
+ <Alert
+ variant="error"
+ title="This query plan could not be read"
+ description={result.message}
+ />
+ {planSource.trim() ? (
+ <pre className="font-mono text-xs leading-4 break-words whitespace-pre-wrap text-control">
+ {planSource}
+ </pre>
+ ) : null}
+ </div>
+ );
+ }
+
+ return (
+ <QueryPlanViewer
+ tree={result.tree}
+ rawPlan={planSource}
+ query={planQuery}
+ />
+ );
+}
export function ExplainVisualizerApp() {
const storedQuery = useMemo(() => {
@@ -15,46 +68,33 @@ export function ExplainVisualizerApp() {
if (!storedQuery) {
return (
- <div className="ev-app">
- <div className="ev-unsupported">
- <h2>Session expired</h2>
- <p>Run the statement again to open a fresh query plan.</p>
- </div>
+ <div className={STATUS_CLASS}>
+ <Alert
+ variant="warning"
+ title="Session expired"
+ description="Run the statement again to open a fresh query plan."
+ />
</div>
);
}
- let body: ReactNode;
- switch (storedQuery.engine) {
- case Engine.POSTGRES:
- body = (
- <PostgresPlanView
- planSource={storedQuery.explain}
- planQuery={storedQuery.statement}
- />
- );
- break;
- case Engine.MSSQL:
- body = <MSSQLPlanView planXml={storedQuery.explain} />;
- break;
- case Engine.SPANNER:
- body = (
- <SpannerQueryPlan
- planSource={storedQuery.explain}
- planQuery={storedQuery.statement}
+ if (!isVisualizerEngine(storedQuery.engine)) {
+ return (
+ <div className={STATUS_CLASS}>
+ <Alert
+ variant="warning"
+ title="Unsupported database engine"
+ description="Query plan visualization is not available for this database engine."
/>
- );
- break;
- default:
- body = (
- <div className="ev-unsupported">
- <h2>Unsupported Database Engine</h2>
- <p>
- Query plan visualization is not available for this database engine.
- </p>
- </div>
- );
+ </div>
+ );
}
- return <div className="ev-app">{body}</div>;
+ return (
+ <PlanView
+ parsePlan={PARSERS[storedQuery.engine]}
+ planSource={storedQuery.explain}
+ planQuery={storedQuery.statement}
+ />
+ );
}
diff --git a/frontend/src/apps/explain-visualizer/MSSQLPlanView.tsx b/frontend/src/apps/explain-visualizer/MSSQLPlanView.tsx
deleted file mode 100644
index 72833c5a18..0000000000
--- a/frontend/src/apps/explain-visualizer/MSSQLPlanView.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useEffect, useRef } from "react";
-import { loadQueryPlanScript } from "./loadQueryPlanScript";
-
-interface Props {
- planXml: string;
-}
-
-export function MSSQLPlanView({ planXml }: Props) {
- const containerRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- let cancelled = false;
- const container = containerRef.current;
- if (!container) return;
- void (async () => {
- try {
- await loadQueryPlanScript();
- if (cancelled) return;
- if (window.QP && containerRef.current) {
- window.QP.showPlan(containerRef.current, planXml);
- }
- } catch (error) {
- console.error("Failed to load query plan visualizer:", error);
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [planXml]);
-
- return <div ref={containerRef} className="ev-mssql-container" />;
-}
diff --git a/frontend/src/apps/explain-visualizer/PlanMiniMap.test.tsx b/frontend/src/apps/explain-visualizer/PlanMiniMap.test.tsx
index 1fa46d47a2..29da09a960 100644
--- a/frontend/src/apps/explain-visualizer/PlanMiniMap.test.tsx
+++ b/frontend/src/apps/explain-visualizer/PlanMiniMap.test.tsx
@@ -7,12 +7,8 @@ import type { PlanNode } from "./plan-model";
const node = (id: string): PlanNode => ({
id,
nodeType: "Seq Scan",
- startupCost: 0,
- totalCost: 0,
- selfCost: 0,
- rows: 0,
- width: 0,
properties: [],
+ warnings: [],
children: [],
});
diff --git a/frontend/src/apps/explain-visualizer/PostgresPlanView.test.tsx b/frontend/src/apps/explain-visualizer/PostgresPlanView.test.tsx
deleted file mode 100644
index db1a342407..0000000000
--- a/frontend/src/apps/explain-visualizer/PostgresPlanView.test.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import type { ReactNode } from "react";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import cteNestedLoopInitplan from "./test-data/cte-nested-loop-initplan.json";
-import { PostgresPlanView } from "./PostgresPlanView";
-import {
- POSTGRES_PLAN_EMPTY_MESSAGE,
- POSTGRES_PLAN_INVALID_JSON_MESSAGE,
- POSTGRES_PLAN_NO_PLAN_MESSAGE,
-} from "./postgres-plan";
-
-vi.mock("react-resizable-panels", () => ({
- Group: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Separator: () => <div />,
-}));
-
-describe("PostgresPlanView", () => {
- beforeEach(() => {
- // jsdom's window exposes no matchMedia under vitest; the viewer queries it
- // to decide whether to stack the detail pane.
- window.matchMedia = ((query: string) => ({
- matches: false,
- media: query,
- onchange: null,
- addEventListener: () => {},
- removeEventListener: () => {},
- addListener: () => {},
- removeListener: () => {},
- dispatchEvent: () => true,
- })) as unknown as typeof window.matchMedia;
- });
-
- test("renders every node of a real EXPLAIN (FORMAT JSON) plan", () => {
- render(
- <PostgresPlanView
- planSource={JSON.stringify(cteNestedLoopInitplan)}
- planQuery="SELECT c.region FROM orders JOIN customers c ON c.id = orders.customer_id LIMIT 10;"
- />
- );
-
- for (const nodeType of [
- "Limit",
- "Aggregate",
- "Nested Loop",
- "Seq Scan",
- "Index Scan",
- ]) {
- expect(
- screen.getAllByRole("button", { name: new RegExp(nodeType) }).length
- ).toBeGreaterThan(0);
- }
- expect(screen.getByText("InitPlan 1")).toBeInTheDocument();
- });
-
- test("explains malformed JSON and still shows what the server returned", () => {
- render(<PostgresPlanView planSource="Seq Scan on customers" />);
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- POSTGRES_PLAN_INVALID_JSON_MESSAGE
- );
- expect(screen.getByText("Seq Scan on customers")).toBeInTheDocument();
- expect(screen.queryByTestId("plan-diagram-viewport")).toBeNull();
- });
-
- test("explains JSON that carries no plan", () => {
- render(<PostgresPlanView planSource='[{"Planning Time": 0.1}]' />);
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- POSTGRES_PLAN_NO_PLAN_MESSAGE
- );
- });
-
- test("explains an empty plan without echoing an empty block", () => {
- const { container } = render(<PostgresPlanView planSource="" />);
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- POSTGRES_PLAN_EMPTY_MESSAGE
- );
- expect(container.querySelector("pre")).toBeNull();
- });
-});
diff --git a/frontend/src/apps/explain-visualizer/PostgresPlanView.tsx b/frontend/src/apps/explain-visualizer/PostgresPlanView.tsx
deleted file mode 100644
index 781c4c1251..0000000000
--- a/frontend/src/apps/explain-visualizer/PostgresPlanView.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useMemo } from "react";
-import { Alert } from "@/components/ui/alert";
-import { parsePostgresPlan } from "./postgres-plan";
-import { QueryPlanViewer } from "./QueryPlanViewer";
-
-interface Props {
- /** `EXPLAIN (FORMAT JSON)` output as PostgreSQL returned it. */
- planSource: string;
- planQuery?: string;
-}
-
-export function PostgresPlanView({ planSource, planQuery }: Props) {
- const result = useMemo(() => parsePostgresPlan(planSource), [planSource]);
-
- if (!result.ok) {
- return (
- <div className="flex h-full min-h-0 w-full flex-col gap-4 overflow-auto bg-background p-4">
- <Alert
- variant="error"
- title="This query plan could not be read"
- description={result.message}
- />
- {planSource.trim() ? (
- <pre className="font-mono text-xs leading-4 break-words whitespace-pre-wrap text-control">
- {planSource}
- </pre>
- ) : null}
- </div>
- );
- }
-
- return (
- <QueryPlanViewer
- tree={result.tree}
- rawPlan={planSource}
- query={planQuery}
- />
- );
-}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
index 93e5478622..fb4a55c2d8 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
@@ -1,21 +1,29 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
-import hashJoinAggregateSort from "./test-data/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/seq-scan-filter.json";
+import noJoinPredicate from "./test-data/mssql/no-join-predicate.xml?raw";
+import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
+import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
+import spannerHashJoin from "./test-data/spanner/hash-join.json";
+import { parseMssqlPlan } from "./mssql-plan";
+import { PLAN_READABLE_SCALE } from "./plan-layout";
import {
PLAN_EDGE_MAX_WIDTH,
PLAN_EDGE_MIN_WIDTH,
+ type PlanParseResult,
type PlanTree,
} from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
import { QueryPlanDiagram } from "./QueryPlanDiagram";
+import { parseSpannerPlan } from "./spanner-plan";
-const treeFrom = (fixture: unknown): PlanTree => {
- const result = parsePostgresPlan(JSON.stringify(fixture));
+const treeOf = (result: PlanParseResult): PlanTree => {
if (!result.ok) throw new Error(result.message);
return result.tree;
};
+const treeFrom = (fixture: unknown): PlanTree =>
+ treeOf(parsePostgresPlan(JSON.stringify(fixture)));
+
const tree = (): PlanTree => treeFrom(hashJoinAggregateSort);
/**
@@ -43,6 +51,9 @@ const toggleFor = (label: string) => {
const canvasTransform = () =>
screen.getByTestId("plan-diagram-canvas").style.transform;
+const scaleNow = () =>
+ Number(/scale\(([\d.]+)\)/.exec(canvasTransform())?.[1] ?? "0");
+
const renderDiagram = (
overrides: Partial<Parameters<typeof QueryPlanDiagram>[0]> = {}
) => {
@@ -157,35 +168,74 @@ describe("QueryPlanDiagram", () => {
expect(barOf("^Hash, Inner")?.style.width).toBe("0%");
});
- test("warns on a sequential scan of a relation worth flagging", () => {
+ test("marks a node the parser warns about", () => {
renderDiagram();
- expect(screen.getAllByTestId("plan-node-full-scan")).toHaveLength(1);
+ expect(screen.getAllByTestId("plan-node-warning")).toHaveLength(1);
expect(
cardFor("^Seq Scan, orders").querySelector(
- "[data-testid='plan-node-full-scan']"
+ "[data-testid='plan-node-warning']"
)
).not.toBeNull();
expect(cardFor("^Seq Scan, orders")).toHaveAccessibleName(
- /full table scan/
+ /Full table scan/
);
// `customers` is small enough that reading all of it costs nothing worth
// acting on.
expect(
cardFor("^Seq Scan, customers").querySelector(
- "[data-testid='plan-node-full-scan']"
+ "[data-testid='plan-node-warning']"
)
).toBeNull();
});
+ test("names each of a node's warnings on its icon and its label", () => {
+ renderDiagram({ tree: treeOf(parseMssqlPlan(noJoinPredicate)) });
+ const join = cardFor("^Nested Loops \\(Inner Join\\)");
+
+ expect(join).toHaveAccessibleName(/No join predicate/);
+ expect(
+ join.querySelector("[data-testid='plan-node-warning'] title")
+ ).toHaveTextContent("No join predicate");
+ });
+
test("gives a lone node the whole plan and no warning", () => {
renderDiagram({ tree: treeFrom(seqScanFilter) });
expect(cardFor("^Seq Scan, customers")).toHaveTextContent("100%");
- expect(screen.queryAllByTestId("plan-node-full-scan")).toHaveLength(0);
+ expect(screen.queryAllByTestId("plan-node-warning")).toHaveLength(0);
expect(screen.queryAllByTestId("plan-diagram-edge")).toHaveLength(0);
});
+ test("draws a plan without estimates as its operators alone", () => {
+ renderDiagram({ tree: treeOf(parseSpannerPlan(JSON.stringify(spannerHashJoin))) });
+
+ expect(screen.getAllByTestId("plan-node-card")).toHaveLength(7);
+ // No cost or row line, no cost bar, and no share in the label.
+ expect(cardFor("^Hash Join")).not.toHaveTextContent(/cost|rows/);
+ expect(cardFor("^Hash Join")).not.toHaveAccessibleName(/of plan cost/);
+ expect(screen.queryAllByTestId("plan-cost-share-bar")).toHaveLength(0);
+ // Without row estimates every edge is the same hairline, with no count.
+ for (const edge of screen.getAllByTestId("plan-diagram-edge")) {
+ expect(Number(edge.getAttribute("stroke-width"))).toBe(
+ PLAN_EDGE_MIN_WIDTH
+ );
+ expect(edge.querySelector("title")).toBeNull();
+ }
+ expect(cardFor("^Table Scan")).toHaveAccessibleName(/Full table scan/);
+ expect(cardFor("^Index Scan")).toHaveAccessibleName(/Full index scan/);
+ });
+
+ test("gives the subject the lines a plan without estimates leaves free", () => {
+ renderDiagram({ tree: treeOf(parseSpannerPlan(JSON.stringify(spannerHashJoin))) });
+
+ expect(
+ screen.getByText("(($SingerId = $SingerId_1) AND ($AlbumId = $AlbumId_1))")
+ ).toHaveClass("line-clamp-3");
+ renderDiagram();
+ expect(screen.getByText("(o.customer_id = c.id)")).toHaveClass("truncate");
+ });
+
test("marks the selected card and reports clicks on the others", () => {
const { onSelect } = renderDiagram();
@@ -236,8 +286,7 @@ describe("QueryPlanDiagram", () => {
sizeViewport(600, 400);
renderDiagram();
const viewport = screen.getByTestId("plan-diagram-viewport");
- const scaleNow = () =>
- Number(/scale\(([\d.]+)\)/.exec(canvasTransform())?.[1] ?? "0");
+ fireEvent.click(screen.getByRole("button", { name: "Fit to view" }));
const fitted = scaleNow();
// Chrome sends one notch as pixels; Firefox sends the same notch as lines.
@@ -273,11 +322,11 @@ describe("QueryPlanDiagram", () => {
expect(canvasTransform()).toBe(placed);
});
- test("still fits a plan the reader has not moved when it re-lays out", () => {
+ test("places the view again for a plan the reader has not moved when it re-lays out", () => {
sizeViewport(600, 400);
const plan = tree();
const { rerender } = renderDiagram({ tree: plan });
- const fitted = canvasTransform();
+ const opened = canvasTransform();
rerender(
<QueryPlanDiagram
@@ -290,11 +339,52 @@ describe("QueryPlanDiagram", () => {
/>
);
- // A narrower plan fits at a larger scale, so the fit has to be redone.
- expect(canvasTransform()).not.toBe(fitted);
+ // What is left is small enough to read whole, so the view changes to show it.
+ expect(canvasTransform()).not.toBe(opened);
+ expect(scaleNow()).toBeGreaterThan(PLAN_READABLE_SCALE);
expect(screen.getAllByTestId("plan-node-card")).toHaveLength(3);
});
+ test("opens a plan too deep to read whole at a readable scale, from its root down", () => {
+ sizeViewport(600, 400);
+ renderDiagram();
+
+ // Shown whole, this plan would open at about half size.
+ expect(scaleNow()).toBe(PLAN_READABLE_SCALE);
+ expect(canvasTransform()).toMatch(/translate\([\d.]+px, 0px\)/);
+ expect(screen.getByTestId("plan-mini-map")).toBeInTheDocument();
+ });
+
+ test("opens a plan small enough to read whole by showing all of it", () => {
+ sizeViewport(1200, 900);
+ renderDiagram();
+
+ expect(scaleNow()).toBe(1);
+ expect(screen.queryByTestId("plan-mini-map")).toBeNull();
+ });
+
+ test("keeps showing the whole plan after Fit to view when it re-lays out", () => {
+ sizeViewport(600, 400);
+ const plan = tree();
+ const { rerender } = renderDiagram({ tree: plan });
+ fireEvent.click(screen.getByRole("button", { name: "Fit to view" }));
+
+ // Folding the hash's scan away leaves a plan still too deep to read whole.
+ rerender(
+ <QueryPlanDiagram
+ tree={plan}
+ selectedId="0"
+ onSelect={() => undefined}
+ highlight="off"
+ collapsedIds={new Set(["0.0.0.1"])}
+ onToggleCollapse={() => undefined}
+ />
+ );
+
+ expect(scaleNow()).toBeLessThan(PLAN_READABLE_SCALE);
+ expect(screen.queryByTestId("plan-mini-map")).toBeNull();
+ });
+
test("tints cards only while a highlight mode is on", () => {
const { rerender } = renderDiagram();
expect(screen.queryAllByTestId("plan-node-tint")).toHaveLength(0);
@@ -433,9 +523,10 @@ describe("QueryPlanDiagram", () => {
expect(onRevealed).toHaveBeenCalled();
});
- test("shows a mini-map only while the plan is too big to fit", () => {
- sizeViewport(400, 300);
+ test("shows a mini-map only while part of the plan is off screen", () => {
+ sizeViewport(600, 400);
renderDiagram();
+ fireEvent.click(screen.getByRole("button", { name: "Fit to view" }));
expect(screen.queryByTestId("plan-mini-map")).toBeNull();
// Zooming in pushes the plan past the edges of the viewport.
@@ -448,7 +539,7 @@ describe("QueryPlanDiagram", () => {
});
test("moves the view when the mini-map is clicked", () => {
- sizeViewport(400, 300);
+ sizeViewport(600, 400);
renderDiagram();
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
@@ -468,6 +559,16 @@ describe("QueryPlanDiagram", () => {
expect(screen.queryByTestId("plan-mini-map")).toBeNull();
});
+ test("leaves the mini-map out of a viewport too small to spare room for it", () => {
+ sizeViewport(400, 300);
+ renderDiagram();
+
+ // The plan opens partly off screen, which in a roomier viewport would
+ // bring the mini-map up over it.
+ expect(scaleNow()).toBe(PLAN_READABLE_SCALE);
+ expect(screen.queryByTestId("plan-mini-map")).toBeNull();
+ });
+
test("still selects a node from the keyboard after a drag", () => {
const onSelect = vi.fn();
renderDiagram({ onSelect });
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
index 207ddf7f7e..3f4dda02a6 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
@@ -20,24 +20,27 @@ import { cn } from "@/lib/utils";
// Deep import: `@/utils` (the barrel) transitively pulls in Monaco, which this
// standalone entry never loads. `minmax` itself is a leaf math helper.
import { minmax } from "@/utils/math";
-import { PlanMiniMap } from "./PlanMiniMap";
+import { PLAN_MINI_MAP_BOX, PlanMiniMap } from "./PlanMiniMap";
import {
layoutPlan,
+ PLAN_IDENTITY_VIEWPORT,
+ PLAN_MAX_SCALE,
+ PLAN_MIN_SCALE,
PLAN_NODE_HEIGHT,
PLAN_NODE_WIDTH,
type PlanViewport,
type PlanViewportSize,
- planFitsViewport,
+ planFitViewport,
planNodeCenter,
planNodeOnScreen,
+ planOpeningViewport,
+ planShowsMiniMap,
planViewportCenteredOn,
} from "./plan-layout";
import {
formatPlanCost,
formatPlanCount,
formatPlanShare,
- isFlaggedFullScan,
- PLAN_FULL_SCAN_HINT,
type PlanHighlightMode,
type PlanNode,
type PlanTree,
@@ -62,14 +65,14 @@ interface Props {
readonly onRevealed?: () => void;
}
-const MIN_SCALE = 0.2;
-const MAX_SCALE = 2;
const ZOOM_STEP = 1.25;
/** Pointer travel, in CSS pixels, that turns a click into a pan. */
const PAN_THRESHOLD = 4;
-const IDENTITY_VIEWPORT: PlanViewport = { scale: 1, x: 0, y: 0 };
const UNMEASURED: PlanViewportSize = { width: 0, height: 0 };
+/** A view the diagram places itself: the one it opens on, or the whole plan. */
+type PlacedView = "opening" | "whole";
+
/**
* What one wheel notch means in CSS pixels when the event reports something
* else. Firefox reports the wheel in lines and some devices in pages; read as
@@ -94,6 +97,16 @@ const HIGHLIGHT_CLASS: Record<Exclude<PlanHighlightMode, "off">, string> = {
rows: "bg-info",
};
+/** The estimates a card prints, leaving out any the plan does not carry. */
+function planCardMetrics(node: PlanNode, tree: PlanTree): string {
+ return [
+ tree.estimates.cost ? `cost ${formatPlanCost(node.totalCost)}` : undefined,
+ tree.estimates.rows ? `rows ${formatPlanCount(node.rows)}` : undefined,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+}
+
/** Opacity of the tint on the plan's worst node; the rest scale below it. */
const MAX_TINT_OPACITY = 0.45;
@@ -190,7 +203,7 @@ export function QueryPlanDiagram({
[tree, collapsedIds]
);
const viewportRef = useRef<HTMLDivElement>(null);
- const [view, setView] = useState<PlanViewport>(IDENTITY_VIEWPORT);
+ const [view, setView] = useState<PlanViewport>(PLAN_IDENTITY_VIEWPORT);
const [size, setSize] = useState<PlanViewportSize>(UNMEASURED);
// Pan reads the live viewport without re-binding its window listeners.
@@ -201,10 +214,11 @@ export function QueryPlanDiagram({
// A drag that moved must not also select the card it started on.
const draggedRef = useRef(false);
const stopPanRef = useRef<(() => void) | undefined>(undefined);
- // Until the user zooms or pans, the diagram keeps refitting itself as the
- // container resizes. Once they place the view themselves, a resize must not
- // throw it away.
- const viewIsUsersRef = useRef(false);
+ // Until the reader zooms or pans, the diagram keeps placing the view itself
+ // as the container resizes: the opening view, or the whole plan once Fit to
+ // view has asked for it. Once the reader places the view, a resize must not
+ // throw it away, and this is undefined.
+ const placedViewRef = useRef<PlacedView | undefined>("opening");
const measure = useCallback(() => {
const rect = viewportRef.current?.getBoundingClientRect();
@@ -219,9 +233,9 @@ export function QueryPlanDiagram({
}, []);
const zoomAt = useCallback((factor: number, cx: number, cy: number) => {
- viewIsUsersRef.current = true;
+ placedViewRef.current = undefined;
setView((prev) => {
- const scale = minmax(prev.scale * factor, MIN_SCALE, MAX_SCALE);
+ const scale = minmax(prev.scale * factor, PLAN_MIN_SCALE, PLAN_MAX_SCALE);
const ratio = scale / prev.scale;
return {
scale,
@@ -239,51 +253,45 @@ export function QueryPlanDiagram({
[zoomAt]
);
- const fitToView = useCallback(() => {
- viewIsUsersRef.current = false;
- const measured = measure();
- // jsdom and a not-yet-laid-out container both report a zero-size box.
- if (measured.width === 0 || measured.height === 0) {
- setView(IDENTITY_VIEWPORT);
- return;
- }
- const scale = minmax(
- Math.min(measured.width / layout.width, measured.height / layout.height),
- MIN_SCALE,
- 1
- );
- setView({
- scale,
- x: (measured.width - layout.width * scale) / 2,
- y: (measured.height - layout.height * scale) / 2,
- });
- }, [layout, measure]);
+ const placeView = useCallback(
+ (placed: PlacedView) => {
+ placedViewRef.current = placed;
+ const measured = measure();
+ setView(
+ placed === "whole"
+ ? planFitViewport(layout, measured)
+ : planOpeningViewport(layout, measured)
+ );
+ },
+ [layout, measure]
+ );
const panTo = useCallback((point: { x: number; y: number }) => {
- viewIsUsersRef.current = true;
+ placedViewRef.current = undefined;
setView((prev) => planViewportCenteredOn(point, sizeRef.current, prev));
}, []);
useLayoutEffect(() => {
- // `fitToView` is rebuilt whenever the layout is, so this also runs when a
+ // `placeView` is rebuilt whenever the layout is, so this also runs when a
// collapse re-lays out the plan. Folding a subtree away must not throw out
- // a view the reader placed, so only an untouched view refits.
- if (viewIsUsersRef.current) return;
- fitToView();
- }, [fitToView]);
+ // a view the reader placed, so only a view the diagram placed is redone.
+ const placed = placedViewRef.current;
+ if (placed) placeView(placed);
+ }, [placeView]);
useEffect(() => {
const element = viewportRef.current;
if (!element) return;
// The first measurement can land before the surrounding split pane has
- // sized itself, so refit until the user takes the view over.
+ // sized itself, so the view is placed again until the reader takes it over.
const observer = new ResizeObserver(() => {
- if (viewIsUsersRef.current) measure();
- else fitToView();
+ const placed = placedViewRef.current;
+ if (placed) placeView(placed);
+ else measure();
});
observer.observe(element);
return () => observer.disconnect();
- }, [fitToView, measure]);
+ }, [placeView, measure]);
useEffect(() => {
const element = viewportRef.current;
@@ -306,8 +314,8 @@ export function QueryPlanDiagram({
// Release a drag still in flight when the diagram unmounts.
useEffect(() => () => stopPanRef.current?.(), []);
- // Fitting runs in a layout effect above, so this plain effect always lands
- // after it and the centering survives. Keep the two in that order.
+ // The view is placed in a layout effect above, so this plain effect always
+ // lands after it and the centering survives. Keep the two in that order.
useEffect(() => {
if (revealId === undefined) return;
const placed = layout.nodes.find((entry) => entry.node.id === revealId);
@@ -327,7 +335,7 @@ export function QueryPlanDiagram({
const dy = moveEvent.clientY - startY;
if (Math.abs(dx) + Math.abs(dy) > PAN_THRESHOLD) {
draggedRef.current = true;
- viewIsUsersRef.current = true;
+ placedViewRef.current = undefined;
}
if (!draggedRef.current) return;
setView((prev) => ({ ...prev, x: origin.x + dx, y: origin.y + dy }));
@@ -373,7 +381,9 @@ export function QueryPlanDiagram({
strokeWidth={planEdgeWidth(edge.target.rows, tree)}
strokeLinecap="round"
>
- <title>{`${formatPlanCount(edge.target.rows)} estimated rows`}</title>
+ {edge.target.rows === undefined ? null : (
+ <title>{`${formatPlanCount(edge.target.rows)} estimated rows`}</title>
+ )}
</path>
)),
[layout, tree]
@@ -384,14 +394,12 @@ export function QueryPlanDiagram({
layout.nodes.map((placed) => {
const { node, x, y } = placed;
const selected = node.id === selectedId;
- const metrics = `cost ${formatPlanCost(node.totalCost)} · rows ${formatPlanCount(node.rows)}`;
+ const metrics = planCardMetrics(node, tree);
const share = planSelfCostShare(node, tree);
- const fullScan = isFlaggedFullScan(node);
+ const warnings = node.warnings.map((warning) => warning.title);
const collapsed = collapsedIds.has(node.id);
const subtreeCount = planDescendantCount(node);
- // "Outer" is the default relationship and carries no information.
- const relationship =
- node.relationship === "Outer" ? undefined : node.relationship;
+ const { relationship } = node;
return (
<div
key={node.id}
@@ -408,15 +416,17 @@ export function QueryPlanDiagram({
data-testid="plan-node-card"
aria-pressed={selected}
// The card's stacked lines concatenate into an unreadable name,
- // so it states its own. The full-scan warning is an icon with a
- // hover-only explanation, so the label has to carry it too.
+ // so it states its own. A warning is an icon with a hover-only
+ // explanation, so the label has to carry it too.
aria-label={[
node.nodeType,
relationship,
node.subject,
metrics,
- `${formatPlanShare(share)} of plan cost`,
- fullScan ? "full table scan" : undefined,
+ tree.estimates.cost
+ ? `${formatPlanShare(share)} of plan cost`
+ : undefined,
+ ...warnings,
collapsed
? `${formatPlanCount(subtreeCount)} nodes hidden`
: undefined,
@@ -447,17 +457,17 @@ export function QueryPlanDiagram({
<span className="min-w-0 flex-1 truncate text-sm leading-5 font-medium text-main">
{node.nodeType}
</span>
- {fullScan ? (
+ {warnings.length > 0 ? (
// A native SVG title rather than a `Tooltip`: a large plan
// would otherwise mount one tooltip provider per flagged
- // scan, and the detail pane states the same warning in the
+ // node, and the detail pane states the same warnings in the
// accessibility tree.
<TriangleAlert
aria-hidden="true"
- data-testid="plan-node-full-scan"
+ data-testid="plan-node-warning"
className="size-3.5 shrink-0 text-warning"
>
- <title>{PLAN_FULL_SCAN_HINT}</title>
+ <title>{warnings.join("\n")}</title>
</TriangleAlert>
) : null}
{relationship ? (
@@ -466,18 +476,32 @@ export function QueryPlanDiagram({
</span>
) : null}
</span>
- <span className="w-full truncate text-xs leading-4 text-control-light">
+ <span
+ className={cn(
+ "w-full text-xs leading-4 break-words text-control-light",
+ // A plan without estimates leaves the card's lower lines
+ // empty, so the subject gets them.
+ metrics ? "truncate" : "line-clamp-3"
+ )}
+ >
{node.subject ?? "—"}
</span>
- <span className="w-full truncate text-xs leading-4 text-control">
- {metrics}
- </span>
- <span className="flex w-full items-center gap-2">
- <PlanCostShareBar share={share} className="min-w-0 flex-1" />
- <span className="shrink-0 text-xs leading-4 text-control-light tabular-nums">
- {formatPlanShare(share)}
+ {metrics ? (
+ <span className="w-full truncate text-xs leading-4 text-control">
+ {metrics}
</span>
- </span>
+ ) : null}
+ {tree.estimates.cost ? (
+ <span className="flex w-full items-center gap-2">
+ <PlanCostShareBar
+ share={share}
+ className="min-w-0 flex-1"
+ />
+ <span className="shrink-0 text-xs leading-4 text-control-light tabular-nums">
+ {formatPlanShare(share)}
+ </span>
+ </span>
+ ) : null}
</span>
</Button>
@@ -533,7 +557,7 @@ export function QueryPlanDiagram({
{cards}
</div>
- {planFitsViewport(layout, size, view) ? null : (
+ {planShowsMiniMap(layout, size, view, PLAN_MINI_MAP_BOX) ? (
<PlanMiniMap
layout={layout}
size={size}
@@ -541,7 +565,7 @@ export function QueryPlanDiagram({
selectedId={selectedId}
onPanTo={panTo}
/>
- )}
+ ) : null}
<div className="absolute right-2 bottom-2 flex items-center gap-1">
<Tooltip content="Zoom out">
@@ -572,7 +596,7 @@ export function QueryPlanDiagram({
size="xs"
aria-label="Fit to view"
className="bg-background"
- onClick={fitToView}
+ onClick={() => placeView("whole")}
>
<Maximize2 className="size-3.5" />
</Button>
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
index 836821bf9e..83a36e97d7 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
@@ -1,16 +1,25 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, test, vi } from "vitest";
-import cteNestedLoopInitplan from "./test-data/cte-nested-loop-initplan.json";
-import type { PlanTree } from "./plan-model";
+import indexSeekKeyLookup from "./test-data/mssql/index-seek-key-lookup.xml?raw";
+import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
+import spannerHashJoin from "./test-data/spanner/hash-join.json";
+import { parseMssqlPlan } from "./mssql-plan";
+import type { PlanParseResult, PlanTree } from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
import { QueryPlanGrid } from "./QueryPlanGrid";
+import { parseSpannerPlan } from "./spanner-plan";
-const treeFrom = (plan: unknown): PlanTree => {
- const result = parsePostgresPlan(JSON.stringify(plan));
+const treeOf = (result: PlanParseResult): PlanTree => {
if (!result.ok) throw new Error(result.message);
return result.tree;
};
+const treeFrom = (plan: unknown): PlanTree =>
+ treeOf(parsePostgresPlan(JSON.stringify(plan)));
+
+const headers = () =>
+ screen.getAllByRole("columnheader").map((cell) => cell.textContent);
+
const tree = () => treeFrom(cteNestedLoopInitplan);
const renderGrid = (
@@ -55,6 +64,43 @@ describe("QueryPlanGrid", () => {
]);
});
+ test("has a column for every estimate PostgreSQL reports", () => {
+ renderGrid();
+ expect(headers()).toEqual([
+ "#",
+ "Node",
+ "Added cost",
+ "Total cost",
+ "Rows",
+ "Width",
+ ]);
+ });
+
+ test("marks an estimate one node lacks and the rest of the plan has", () => {
+ renderGrid({ tree: treeOf(parseMssqlPlan(indexSeekKeyLookup)) });
+
+ expect(headers()).toEqual([
+ "#",
+ "Node",
+ "Added cost",
+ "Total cost",
+ "Rows",
+ "Width",
+ ]);
+ // A SQL Server statement has a cost and rows but no row width.
+ expect(cellsOf(rows()[0]).slice(2)).toEqual(["0", "0.0325", "10", "—"]);
+ });
+
+ test("leaves out the estimate columns of a plan without estimates", () => {
+ renderGrid({
+ tree: treeOf(parseSpannerPlan(JSON.stringify(spannerHashJoin))),
+ });
+
+ expect(headers()).toEqual(["#", "Node"]);
+ expect(cellsOf(rows()[4])).toEqual(["5", "Table ScanAlbums"]);
+ expect(screen.queryAllByTestId("plan-cost-share-bar")).toHaveLength(0);
+ });
+
test("numbers rows from one and reports each node's estimates", () => {
renderGrid();
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
index 341807c94e..ab4e3e8736 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
@@ -169,27 +169,34 @@ const PlanGridRow = memo(function PlanGridRow({
</div>
</TableCell>
- <TableCell className="py-2 pr-4 pl-2">
- <div className="flex items-center justify-end gap-2">
- <PlanCostShareBar
- share={planSelfCostShare(node, tree)}
- className="w-10 shrink-0 sm:w-16"
- />
- <span className="text-xs leading-4 text-main tabular-nums">
- {formatPlanCost(node.selfCost)}
- </span>
- </div>
- </TableCell>
-
- <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
- {formatPlanCost(node.totalCost)}
- </TableCell>
- <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
- {formatPlanCount(node.rows)}
- </TableCell>
- <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
- {formatPlanCount(node.width)}
- </TableCell>
+ {tree.estimates.cost ? (
+ <>
+ <TableCell className="py-2 pr-4 pl-2">
+ <div className="flex items-center justify-end gap-2">
+ <PlanCostShareBar
+ share={planSelfCostShare(node, tree)}
+ className="w-10 shrink-0 sm:w-16"
+ />
+ <span className="text-xs leading-4 text-main tabular-nums">
+ {formatPlanCost(node.selfCost)}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
+ {formatPlanCost(node.totalCost)}
+ </TableCell>
+ </>
+ ) : null}
+ {tree.estimates.rows ? (
+ <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
+ {formatPlanCount(node.rows)}
+ </TableCell>
+ ) : null}
+ {tree.estimates.width ? (
+ <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>
+ {formatPlanCount(node.width)}
+ </TableCell>
+ ) : null}
</TableRow>
);
});
@@ -257,41 +264,49 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {
#
</TableHead>
<TableHead className={HEAD_CLASS}>Node</TableHead>
- <TableHead
- className={cn(HEAD_CLASS, "w-32 pl-2 text-right sm:w-48")}
- title="Cost this node adds on top of its children; a node that rescans an input carries the repeats. The bar is that cost as a share of the plan."
- >
- Added cost
- </TableHead>
- <TableHead
- className={cn(
- HEAD_CLASS,
- SECONDARY_COLUMN_CLASS,
- "text-right sm:w-28"
- )}
- >
- Total cost
- </TableHead>
- <TableHead
- className={cn(
- HEAD_CLASS,
- SECONDARY_COLUMN_CLASS,
- "text-right sm:w-24"
- )}
- title="Estimated rows"
- >
- Rows
- </TableHead>
- <TableHead
- className={cn(
- HEAD_CLASS,
- SECONDARY_COLUMN_CLASS,
- "text-right sm:w-24"
- )}
- title="Estimated row width in bytes"
- >
- Width
- </TableHead>
+ {tree.estimates.cost ? (
+ <>
+ <TableHead
+ className={cn(HEAD_CLASS, "w-32 pl-2 text-right sm:w-48")}
+ title="Cost this node adds on top of its children; some engines also count an input's repeats here, as under a nested loop. The bar is that cost as a share of the plan."
+ >
+ Added cost
+ </TableHead>
+ <TableHead
+ className={cn(
+ HEAD_CLASS,
+ SECONDARY_COLUMN_CLASS,
+ "text-right sm:w-28"
+ )}
+ >
+ Total cost
+ </TableHead>
+ </>
+ ) : null}
+ {tree.estimates.rows ? (
+ <TableHead
+ className={cn(
+ HEAD_CLASS,
+ SECONDARY_COLUMN_CLASS,
+ "text-right sm:w-24"
+ )}
+ title="Estimated rows"
+ >
+ Rows
+ </TableHead>
+ ) : null}
+ {tree.estimates.width ? (
+ <TableHead
+ className={cn(
+ HEAD_CLASS,
+ SECONDARY_COLUMN_CLASS,
+ "text-right sm:w-24"
+ )}
+ title="Estimated row width in bytes"
+ >
+ Width
+ </TableHead>
+ ) : null}
</TableRow>
</TableHeader>
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx
index aeb4e65402..5ef36818b1 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx
@@ -1,6 +1,6 @@
import { render, screen } from "@testing-library/react";
-import { describe, expect, test } from "vitest";
-import type { PlanNode } from "./plan-model";
+import { describe, expect, test, vi } from "vitest";
+import { PLAN_FULL_TABLE_SCAN, type PlanNode } from "./plan-model";
import { QueryPlanNodeDetails } from "./QueryPlanNodeDetails";
const node = (overrides: Partial<PlanNode> = {}): PlanNode => ({
@@ -17,6 +17,7 @@ const node = (overrides: Partial<PlanNode> = {}): PlanNode => ({
{ label: "Hash Cond", value: "(o.customer_id = c.id)" },
{ label: "Join Type", value: "Inner" },
],
+ warnings: [],
children: [],
...overrides,
});
@@ -25,7 +26,7 @@ describe("QueryPlanNodeDetails", () => {
test("prompts for a selection when no node is chosen", () => {
render(<QueryPlanNodeDetails node={undefined} />);
expect(
- screen.getByText("Select a node to see its estimates.")
+ screen.getByText("Select a node to see its details.")
).toBeInTheDocument();
});
@@ -76,28 +77,84 @@ describe("QueryPlanNodeDetails", () => {
expect(screen.getByText("Total cost")).toBeInTheDocument();
});
- test("explains a full table scan without needing a hover to do it", () => {
+ test("explains every warning without needing a hover to do it", () => {
render(
<QueryPlanNodeDetails
- node={node({ nodeType: "Seq Scan", subject: "orders", totalCost: 819 })}
+ node={node({
+ warnings: [
+ PLAN_FULL_TABLE_SCAN,
+ { title: "No join predicate", detail: "Every row pairs up." },
+ ],
+ })}
/>
);
- const warning = screen.getByTestId("plan-details-full-scan");
- expect(warning).toHaveTextContent("Full table scan");
- expect(warning).toHaveTextContent(/an index on the filtered columns/);
- expect(screen.getByRole("alert")).toBe(warning);
+ const warnings = screen.getAllByTestId("plan-details-warning");
+ expect(warnings).toHaveLength(2);
+ expect(warnings[0]).toHaveTextContent("Full table scan");
+ expect(warnings[0]).toHaveTextContent(/an index on the filtered columns/);
+ expect(warnings[1]).toHaveTextContent("No join predicate");
+ expect(screen.getAllByRole("alert")).toEqual(warnings);
});
- test("says nothing about scans that are not worth flagging", () => {
+ test("shows a warning the engine repeats as often as it reports it", () => {
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
render(
<QueryPlanNodeDetails
- node={node({ nodeType: "Seq Scan", subject: "regions", totalCost: 12 })}
+ node={node({ warnings: [PLAN_FULL_TABLE_SCAN, PLAN_FULL_TABLE_SCAN] })}
/>
);
- expect(screen.queryByTestId("plan-details-full-scan")).toBeNull();
- render(<QueryPlanNodeDetails node={node({ totalCost: 5000 })} />);
- expect(screen.queryByTestId("plan-details-full-scan")).toBeNull();
+ expect(screen.getAllByTestId("plan-details-warning")).toHaveLength(2);
+ // React reports colliding keys through console.error.
+ expect(consoleError).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ test("says nothing when the node has no warnings", () => {
+ render(<QueryPlanNodeDetails node={node()} />);
+ expect(screen.queryByTestId("plan-details-warning")).toBeNull();
+ });
+
+ test("lists only the estimates the node has", () => {
+ render(
+ <QueryPlanNodeDetails
+ node={node({
+ startupCost: undefined,
+ width: undefined,
+ totalCost: 0.2138,
+ selfCost: 0.2138,
+ rows: 50,
+ })}
+ />
+ );
+
+ expect(screen.getByText("Total cost").nextSibling).toHaveTextContent(
+ "0.21"
+ );
+ expect(screen.getByText("Estimated rows")).toBeInTheDocument();
+ expect(screen.queryByText("Startup cost")).toBeNull();
+ expect(screen.queryByText("Row width")).toBeNull();
+ });
+
+ test("leaves out the estimates section of a node without any", () => {
+ const { container } = render(
+ <QueryPlanNodeDetails
+ node={{
+ id: "0",
+ nodeType: "Distributed Union",
+ properties: [{ label: "Split Range", value: "true" }],
+ warnings: [],
+ children: [],
+ }}
+ />
+ );
+
+ expect(screen.queryByText("Total cost")).toBeNull();
+ // The property list is the only list left.
+ expect(container.querySelectorAll("dl")).toHaveLength(1);
+ expect(screen.getByText("Split Range").nextSibling).toHaveTextContent(
+ "true"
+ );
});
});
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
index 1882f5db70..dd1225fcba 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
@@ -1,29 +1,42 @@
import { Alert } from "@/components/ui/alert";
import { Separator } from "@/components/ui/separator";
-import {
- formatPlanCost,
- formatPlanCount,
- isFlaggedFullScan,
- PLAN_FULL_SCAN_HINT,
- type PlanNode,
-} from "./plan-model";
+import { formatPlanCost, formatPlanCount, type PlanNode } from "./plan-model";
import { PlanMetric } from "./plan-shared";
interface Props {
readonly node: PlanNode | undefined;
}
+/** The node's estimates as labelled values, leaving out any it does not have. */
+function nodeMetrics(node: PlanNode): { label: string; value: string }[] {
+ return [
+ { label: "Startup cost", value: node.startupCost, format: formatPlanCost },
+ { label: "Total cost", value: node.totalCost, format: formatPlanCost },
+ { label: "Added cost", value: node.selfCost, format: formatPlanCost },
+ { label: "Estimated rows", value: node.rows, format: formatPlanCount },
+ {
+ label: "Row width",
+ value: node.width,
+ format: (width: number) => `${formatPlanCount(width)} bytes`,
+ },
+ ].flatMap(({ label, value, format }) =>
+ value === undefined ? [] : [{ label, value: format(value) }]
+ );
+}
+
export function QueryPlanNodeDetails({ node }: Props) {
if (!node) {
return (
<div className="flex h-full items-center justify-center p-4">
<p className="text-sm leading-5 text-control-light">
- Select a node to see its estimates.
+ Select a node to see its details.
</p>
</div>
);
}
+ const metrics = nodeMetrics(node);
+
return (
<div className="flex h-full min-h-0 flex-col overflow-auto p-4 gap-4">
<div className="flex flex-col gap-1">
@@ -42,33 +55,35 @@ export function QueryPlanNodeDetails({ node }: Props) {
) : null}
</div>
- {/* The diagram flags this with a hover-only icon, which a touch reader
+ {/* The diagram flags these with a hover-only icon, which a touch reader
never reaches. The pane is where the selected node is explained, so
- it carries the warning too. */}
- {isFlaggedFullScan(node) ? (
+ it carries the warnings too. */}
+ {node.warnings.map((warning, index) => (
<Alert
+ // An engine can report the same warning twice, so its text is not a
+ // key; a node's warnings never reorder.
+ key={index}
variant="warning"
- data-testid="plan-details-full-scan"
- title="Full table scan"
- description={PLAN_FULL_SCAN_HINT}
+ data-testid="plan-details-warning"
+ title={warning.title}
+ description={warning.detail}
/>
- ) : null}
-
- <Separator />
+ ))}
- <dl className="flex flex-wrap gap-4">
- <PlanMetric
- label="Startup cost"
- value={formatPlanCost(node.startupCost)}
- />
- <PlanMetric label="Total cost" value={formatPlanCost(node.totalCost)} />
- <PlanMetric label="Added cost" value={formatPlanCost(node.selfCost)} />
- <PlanMetric label="Estimated rows" value={formatPlanCount(node.rows)} />
- <PlanMetric
- label="Row width"
- value={`${formatPlanCount(node.width)} bytes`}
- />
- </dl>
+ {metrics.length > 0 ? (
+ <>
+ <Separator />
+ <dl className="flex flex-wrap gap-4">
+ {metrics.map((metric) => (
+ <PlanMetric
+ key={metric.label}
+ label={metric.label}
+ value={metric.value}
+ />
+ ))}
+ </dl>
+ </>
+ ) : null}
{node.properties.length > 0 ? (
<>
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
index 4e10f49396..dbc3c5c231 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
@@ -1,18 +1,23 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, test, vi } from "vitest";
-import cteNestedLoopInitplan from "./test-data/cte-nested-loop-initplan.json";
-import hashJoinAggregateSort from "./test-data/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/seq-scan-filter.json";
-import type { PlanTree } from "./plan-model";
+import mssqlHashJoinAggregateSort from "./test-data/mssql/hash-join-aggregate-sort.xml?raw";
+import twoStatementBatch from "./test-data/mssql/two-statement-batch.xml?raw";
+import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
+import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
+import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
+import { parseMssqlPlan } from "./mssql-plan";
+import type { PlanParseResult, PlanTree } from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
import { QueryPlanSummary } from "./QueryPlanSummary";
-const treeFrom = (plan: unknown): PlanTree => {
- const result = parsePostgresPlan(JSON.stringify(plan));
+const treeOf = (result: PlanParseResult): PlanTree => {
if (!result.ok) throw new Error(result.message);
return result.tree;
};
+const treeFrom = (plan: unknown): PlanTree =>
+ treeOf(parsePostgresPlan(JSON.stringify(plan)));
+
/** A plan the planner costs at nothing, as a `VALUES`-only statement is. */
const zeroCostPlan = [
{
@@ -64,7 +69,7 @@ describe("QueryPlanSummary", () => {
expect(
screen.getByText("Estimated rows returned").nextSibling
).toHaveTextContent("3");
- expect(screen.getByText(/planner estimate rather than a measurement/))
+ expect(screen.getByText(/optimizer estimate rather than a measurement/))
.toBeVisible();
expect(
screen.getByText(/comparable only within this plan/)
@@ -263,6 +268,30 @@ describe("QueryPlanSummary", () => {
).toEqual(["Limit100%", "Result100%"]);
});
+ test("leaves the cost ranges out of a plan without startup costs", () => {
+ renderSummary({ tree: treeOf(parseMssqlPlan(mssqlHashJoinAggregateSort)) });
+
+ expect(screen.queryByText("Cost ranges")).toBeNull();
+ expect(screen.queryByTestId("plan-timeline")).toBeNull();
+ // The rest of the summary reads SQL Server's costs like any other.
+ expect(
+ screen.getByText("Total estimated cost").nextSibling
+ ).toHaveTextContent("0.277");
+ expect(screen.getAllByTestId("plan-costliest-row")[0]).toHaveTextContent(
+ "Index Scan"
+ );
+ expect(screen.getAllByTestId("plan-operation-row").length).toBeGreaterThan(
+ 0
+ );
+ });
+
+ test("leaves out the rows returned when the root estimates none", () => {
+ renderSummary({ tree: treeOf(parseMssqlPlan(twoStatementBatch)) });
+
+ expect(screen.getByText("Nodes").nextSibling).toHaveTextContent("9");
+ expect(screen.queryByText("Estimated rows returned")).toBeNull();
+ });
+
test("renders a subject containing markup as text, not as markup", () => {
const injected = "<img src=x onerror=alert(1)>";
const { container } = renderSummary({
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
index d35cc2cea7..27d7a5734e 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
@@ -97,17 +97,19 @@ function PlanTotals({ tree }: { tree: PlanTree }) {
label="Total estimated cost"
value={formatPlanCost(tree.root.totalCost)}
/>
- <PlanMetric
- label="Estimated rows returned"
- value={formatPlanCount(tree.root.rows)}
- />
+ {tree.root.rows === undefined ? null : (
+ <PlanMetric
+ label="Estimated rows returned"
+ value={formatPlanCount(tree.root.rows)}
+ />
+ )}
</dl>
<p className="flex items-start gap-2 text-xs leading-4 text-control-light">
<Info aria-hidden="true" className="mt-px size-3.5 shrink-0" />
<span>
- EXPLAIN ran without ANALYZE, so every figure here is a planner
- estimate rather than a measurement. Cost units are arbitrary and
- comparable only within this plan.
+ The statement was planned but not run, so every figure here is an
+ optimizer estimate rather than a measurement. Cost units are arbitrary
+ and comparable only within this plan.
</span>
</p>
</div>
@@ -362,8 +364,8 @@ function CostByOperation({ tree }: { tree: PlanTree }) {
}
/**
- * Where the plan's estimated cost goes, read three ways: when each node's work
- * happens, which nodes own the most of it, and which kinds of operation do.
+ * Where the plan's estimated cost goes, read three ways: how much of it each
+ * node spans, which nodes own the most of it, and which kinds of operation do.
*/
export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {
return (
@@ -374,20 +376,23 @@ export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {
<div className="flex flex-col gap-6 p-4">
<PlanTotals tree={tree} />
- <Section
- title="Cost ranges"
- description="Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other."
- >
- <CostTimeline
- tree={tree}
- selectedId={selectedId}
- onSelect={onSelect}
- />
- </Section>
+ {/* A span starts at a startup cost, which not every engine reports. */}
+ {tree.estimates.startupCost ? (
+ <Section
+ title="Cost ranges"
+ description="Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other."
+ >
+ <CostTimeline
+ tree={tree}
+ selectedId={selectedId}
+ onSelect={onSelect}
+ />
+ </Section>
+ ) : null}
<Section
title="Costliest operators"
- description="Ranked by the cost a node adds on top of its children. A node that rescans an input, such as a nested loop, carries the repeats of that input rather than the input itself."
+ description="Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself."
>
<CostliestOperators
tree={tree}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
index e8b7e44a1a..bbdfc89ed7 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
@@ -1,10 +1,14 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import bitmapIndexScan from "./test-data/bitmap-index-scan.json";
+import procedureTwoStatements from "./test-data/mssql/procedure-two-statements.xml?raw";
+import bitmapIndexScan from "./test-data/postgres/bitmap-index-scan.json";
+import spannerHashJoin from "./test-data/spanner/hash-join.json";
+import { parseMssqlPlan } from "./mssql-plan";
import type { PlanTree } from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
import { QueryPlanViewer } from "./QueryPlanViewer";
+import { parseSpannerPlan } from "./spanner-plan";
vi.mock("react-resizable-panels", () => ({
Group: ({
@@ -48,9 +52,22 @@ const tree = (): PlanTree => {
const renderViewer = (query?: string) =>
render(<QueryPlanViewer tree={tree()} rawPlan={rawPlan} query={query} />);
+/** Renders a plan the way the entry does: parsed, beside its source. */
+const renderParsed = (
+ parse: (source: string) => ReturnType<typeof parsePostgresPlan>,
+ source: string
+) => {
+ const result = parse(source);
+ if (!result.ok) throw new Error(result.message);
+ return render(<QueryPlanViewer tree={result.tree} rawPlan={source} />);
+};
+
const openTab = (name: string) =>
fireEvent.click(screen.getByRole("tab", { name }));
+const tabNames = () =>
+ screen.getAllByRole("tab").map((entry) => entry.textContent);
+
/** Loads the page at a fragment, the way following a shared link would. */
const startAtFragment = (fragment: string) =>
history.replaceState(null, "", `${location.pathname}${fragment}`);
@@ -236,6 +253,59 @@ describe("QueryPlanViewer", () => {
expect(screen.getAllByTestId("plan-node-tint").length).toBeGreaterThan(0);
});
+ test("offers every tab and highlight for a plan with cost and row estimates", () => {
+ renderParsed(parseMssqlPlan, procedureTwoStatements);
+
+ expect(tabNames()).toEqual([
+ "Diagram",
+ "Grid",
+ "Summary",
+ "Raw plan",
+ "Query",
+ ]);
+ expect(
+ within(screen.getByRole("group", { name: "Highlight nodes by" }))
+ .getAllByRole("button")
+ .map((option) => option.textContent)
+ ).toEqual(["Off", "Cost", "Rows"]);
+ expect(screen.getByText("10 nodes · estimated cost 1.64")).toBeVisible();
+ });
+
+ test("keeps to what a plan without estimates can show", () => {
+ renderParsed(parseSpannerPlan, JSON.stringify(spannerHashJoin));
+
+ // The summary is where the cost goes, and nothing can be shaded.
+ expect(tabNames()).toEqual(["Diagram", "Grid", "Raw plan", "Query"]);
+ expect(screen.queryByRole("group", { name: "Highlight nodes by" })).toBeNull();
+ expect(screen.getByText("7 nodes")).toBeVisible();
+ expect(screen.queryByText(/card's bar/)).toBeNull();
+ expect(screen.getAllByTestId("plan-node-card")).toHaveLength(7);
+ });
+
+ test("indents an XML plan one element per line on the raw tab", () => {
+ renderParsed(parseMssqlPlan, procedureTwoStatements);
+
+ openTab("Raw plan");
+ const raw = within(screen.getByRole("tabpanel")).getByText(
+ /^<ShowPlanXML/
+ ).textContent;
+ const lines = raw?.split("\n") ?? [];
+
+ expect(lines[0]).toBe(
+ '<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2">'
+ );
+ expect(lines[1]).toBe(" <BatchSequence>");
+ expect(lines.at(-1)).toBe("</ShowPlanXML>");
+ // A line break inside an attribute stays escaped, so a copy keeps it.
+ expect(raw).toContain(
+ 'StatementText="&#10;CREATE PROCEDURE dbo.region_report @region VARCHAR(16) AS&#10;BEGIN&#10;'
+ );
+ // The indented plan is still the same plan.
+ const reparsed = parseMssqlPlan(raw ?? "");
+ const original = parseMssqlPlan(procedureTwoStatements);
+ expect(reparsed.ok && reparsed.tree).toEqual(original.ok && original.tree);
+ });
+
test("splits side by side on a wide screen", () => {
renderViewer();
expect(screen.getByTestId("plan-split")).toHaveAttribute(
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
index ef84b3aca0..824a738961 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
@@ -15,6 +15,7 @@ import {
findPlanNode,
formatPlanCost,
formatPlanCount,
+ type PlanEstimates,
type PlanHighlightMode,
type PlanNode,
type PlanTree,
@@ -30,27 +31,42 @@ import { QueryPlanSummary } from "./QueryPlanSummary";
interface Props {
readonly tree: PlanTree;
- /** The engine's plan output, shown verbatim on the raw tab. */
+ /** The engine's plan output, shown on the raw tab. */
readonly rawPlan: string;
readonly query?: string;
}
type TabValue = "diagram" | "grid" | "summary" | "raw" | "query";
-const HIGHLIGHT_OPTIONS: {
- value: PlanHighlightMode;
- label: string;
- hint: string;
-}[] = [
- { value: "off", label: "Off", hint: "Leave every node card unshaded" },
+interface HighlightOption {
+ readonly value: PlanHighlightMode;
+ readonly label: string;
+ readonly hint: string;
+ /** Whether a plan carries the estimate the option shades by. */
+ readonly available: (estimates: PlanEstimates) => boolean;
+}
+
+const HIGHLIGHT_OPTIONS: readonly HighlightOption[] = [
+ {
+ value: "off",
+ label: "Off",
+ hint: "Leave every node card unshaded",
+ available: () => true,
+ },
{
value: "cost",
label: "Cost",
// Total cost is cumulative, so shading by it would always make the root
// darkest. Self cost is what the node adds on top of its children.
hint: "Shade by the cost a node adds on top of its children",
+ available: (estimates) => estimates.cost,
+ },
+ {
+ value: "rows",
+ label: "Rows",
+ hint: "Shade by the estimated row count",
+ available: (estimates) => estimates.rows,
},
- { value: "rows", label: "Rows", hint: "Shade by the estimated row count" },
];
const RESIZE_HANDLE_BASE_CLASS =
@@ -65,9 +81,11 @@ const STACK_QUERY = "(max-width: 767px)";
* StyleX-sized control would render unstyled here.
*/
function HighlightControl({
+ options,
value,
onChange,
}: {
+ options: readonly HighlightOption[];
value: PlanHighlightMode;
onChange: (next: PlanHighlightMode) => void;
}) {
@@ -77,7 +95,7 @@ function HighlightControl({
aria-label="Highlight nodes by"
className="inline-flex items-center gap-px overflow-hidden rounded-xs border border-control-border bg-control-border"
>
- {HIGHLIGHT_OPTIONS.map((option) => {
+ {options.map((option) => {
const selected = option.value === value;
return (
<Tooltip key={option.value} content={option.hint}>
@@ -100,11 +118,33 @@ function HighlightControl({
function PlanTotalsLine({ tree }: { tree: PlanTree }) {
return (
<p className="text-xs leading-4 text-control-light">
- {`${formatPlanCount(tree.nodes.length)} nodes · estimated cost ${formatPlanCost(tree.root.totalCost)}`}
+ {[
+ `${formatPlanCount(tree.nodes.length)} nodes`,
+ tree.estimates.cost
+ ? `estimated cost ${formatPlanCost(tree.root.totalCost)}`
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
</p>
);
}
+/** What the diagram's bars and edge widths encode, for the estimates it has. */
+function diagramLegend(estimates: PlanEstimates): string | undefined {
+ const parts = [
+ estimates.cost
+ ? "each card's bar is that node's share of the plan's estimated cost"
+ : undefined,
+ estimates.rows
+ ? "an edge thickens with the rows its child is estimated to return"
+ : undefined,
+ ].filter(Boolean);
+ if (parts.length === 0) return undefined;
+ const sentence = `${parts.join("; ")}.`;
+ return sentence.charAt(0).toUpperCase() + sentence.slice(1);
+}
+
/**
* Puts one plan representation beside the detail pane. The diagram and the grid
* are two readings of the same selection, so they share this frame instead of
@@ -140,7 +180,62 @@ function PlanWithDetails({
);
}
-function prettyPrintJson(source: string): string {
+const XML_INDENT = " ";
+
+function escapeXmlText(value: string): string {
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;");
+}
+
+function escapeXmlAttribute(value: string): string {
+ // A literal line break inside a value is read back as a space, so breaks
+ // stay escaped and a copied plan keeps the engine's values.
+ return escapeXmlText(value)
+ .replaceAll('"', "&quot;")
+ .replaceAll("\n", "&#10;")
+ .replaceAll("\r", "&#13;")
+ .replaceAll("\t", "&#9;");
+}
+
+/**
+ * An XML document with one element per line, or undefined when it does not
+ * parse. Plans are elements and attributes only, so text is kept solely in
+ * elements that have no children.
+ */
+function indentXml(source: string): string | undefined {
+ const document = new DOMParser().parseFromString(source, "application/xml");
+ if (document.getElementsByTagName("parsererror").length > 0) return undefined;
+ const lines: string[] = [];
+ const visit = (element: Element, depth: number) => {
+ const indent = XML_INDENT.repeat(depth);
+ const attributes = Array.from(element.attributes)
+ .map(
+ (attribute) =>
+ ` ${attribute.name}="${escapeXmlAttribute(attribute.value)}"`
+ )
+ .join("");
+ const tag = element.tagName;
+ if (element.children.length === 0) {
+ const text = element.textContent ?? "";
+ lines.push(
+ text
+ ? `${indent}<${tag}${attributes}>${escapeXmlText(text)}</${tag}>`
+ : `${indent}<${tag}${attributes}/>`
+ );
+ return;
+ }
+ lines.push(`${indent}<${tag}${attributes}>`);
+ for (const child of Array.from(element.children)) visit(child, depth + 1);
+ lines.push(`${indent}</${tag}>`);
+ };
+ visit(document.documentElement, 0);
+ return lines.join("\n");
+}
+
+/** The plan indented for reading when it is JSON or XML, else as it came. */
+function formatPlanSource(source: string): string {
+ if (source.trimStart().startsWith("<")) {
+ return indentXml(source.trim()) ?? source;
+ }
try {
return JSON.stringify(JSON.parse(source), null, 2);
} catch {
@@ -171,6 +266,19 @@ function CopyablePanel({
const MONOSPACE_BLOCK_CLASS =
"font-mono text-xs leading-4 break-words whitespace-pre-wrap text-main";
+/**
+ * The raw plan tab's content. The tab mounts it only while open, so a large
+ * plan is formatted when someone reads it rather than on every page load.
+ */
+function RawPlan({ source }: { source: string }) {
+ const formatted = useMemo(() => formatPlanSource(source), [source]);
+ return (
+ <CopyablePanel content={formatted} label="Copy plan">
+ <pre className={MONOSPACE_BLOCK_CLASS}>{formatted}</pre>
+ </CopyablePanel>
+ );
+}
+
/**
* The node a fragment names, ignoring one that names a node this plan does not
* have: a stale or hand-edited link should open the plan, not break it.
@@ -197,8 +305,11 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {
);
const selectedNode = findPlanNode(tree, selectedId);
- const formattedPlan = useMemo(() => prettyPrintJson(rawPlan), [rawPlan]);
const stacked = useMediaQuery(STACK_QUERY);
+ const highlightOptions = HIGHLIGHT_OPTIONS.filter((option) =>
+ option.available(tree.estimates)
+ );
+ const legend = diagramLegend(tree.estimates);
const selectNode = useCallback(
(id: string) => {
@@ -265,7 +376,11 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {
<TabsList className="shrink-0 flex-wrap px-4 pt-3">
<TabsTrigger value="diagram">Diagram</TabsTrigger>
<TabsTrigger value="grid">Grid</TabsTrigger>
- <TabsTrigger value="summary">Summary</TabsTrigger>
+ {/* The summary is where the plan's cost goes, which a plan without
+ cost estimates cannot say. */}
+ {tree.estimates.cost ? (
+ <TabsTrigger value="summary">Summary</TabsTrigger>
+ ) : null}
<TabsTrigger value="raw">Raw plan</TabsTrigger>
<TabsTrigger value="query">Query</TabsTrigger>
</TabsList>
@@ -278,19 +393,31 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {
className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
>
<PlanWithDetails stacked={stacked} node={selectedNode}>
- <div className="flex shrink-0 flex-wrap items-center justify-between gap-4 px-4 py-2">
- <div className="flex items-center gap-2">
- <span className="text-xs leading-4 text-control-light">
- Highlight
- </span>
- <HighlightControl value={highlight} onChange={setHighlight} />
- </div>
+ <div
+ className={cn(
+ "flex shrink-0 flex-wrap items-center gap-4 px-4 py-2",
+ highlightOptions.length > 1 ? "justify-between" : "justify-end"
+ )}
+ >
+ {highlightOptions.length > 1 ? (
+ <div className="flex items-center gap-2">
+ <span className="text-xs leading-4 text-control-light">
+ Highlight
+ </span>
+ <HighlightControl
+ options={highlightOptions}
+ value={highlight}
+ onChange={setHighlight}
+ />
+ </div>
+ ) : null}
<PlanTotalsLine tree={tree} />
</div>
- <p className="shrink-0 px-4 pb-2 text-xs leading-4 text-control-light">
- Each card's bar is that node's share of the plan's estimated cost;
- an edge thickens with the rows its child is estimated to return.
- </p>
+ {legend ? (
+ <p className="shrink-0 px-4 pb-2 text-xs leading-4 text-control-light">
+ {legend}
+ </p>
+ ) : null}
<QueryPlanDiagram
tree={tree}
selectedId={selectedId}
@@ -320,26 +447,26 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {
</PlanWithDetails>
</TabsPanel>
- <TabsPanel
- value="summary"
- className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
- >
- <PlanWithDetails stacked={stacked} node={selectedNode}>
- <QueryPlanSummary
- tree={tree}
- selectedId={selectedId}
- onSelect={selectNode}
- />
- </PlanWithDetails>
- </TabsPanel>
+ {tree.estimates.cost ? (
+ <TabsPanel
+ value="summary"
+ className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
+ >
+ <PlanWithDetails stacked={stacked} node={selectedNode}>
+ <QueryPlanSummary
+ tree={tree}
+ selectedId={selectedId}
+ onSelect={selectNode}
+ />
+ </PlanWithDetails>
+ </TabsPanel>
+ ) : null}
<TabsPanel
value="raw"
className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
>
- <CopyablePanel content={formattedPlan} label="Copy plan">
- <pre className={MONOSPACE_BLOCK_CLASS}>{formattedPlan}</pre>
- </CopyablePanel>
+ <RawPlan source={rawPlan} />
</TabsPanel>
<TabsPanel
diff --git a/frontend/src/apps/explain-visualizer/SpannerPlanNode.test.tsx b/frontend/src/apps/explain-visualizer/SpannerPlanNode.test.tsx
deleted file mode 100644
index a9752fa9e3..0000000000
--- a/frontend/src/apps/explain-visualizer/SpannerPlanNode.test.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, test } from "vitest";
-import { SpannerPlanNode } from "./SpannerPlanNode";
-import type { SpannerPlanNodeData } from "./spanner-types";
-
-const node = (
- index: number,
- kind: string,
- displayName: string,
- extra: Partial<SpannerPlanNodeData> = {}
-): SpannerPlanNodeData => ({
- index,
- kind,
- displayName,
- ...extra,
-});
-
-describe("SpannerPlanNode", () => {
- test("renders a leaf node with its kind and displayName", () => {
- const root = node(0, "RELATIONAL", "Distributed Union");
- render(<SpannerPlanNode node={root} allNodes={[root]} depth={0} />);
- expect(screen.getByText("RELATIONAL")).toBeInTheDocument();
- expect(screen.getByText("Distributed Union")).toBeInTheDocument();
- });
-
- test("renders only RELATIONAL child links, skipping scalar links", () => {
- const root = node(0, "RELATIONAL", "Distributed Union", {
- childLinks: [{ childIndex: 1 }, { childIndex: 2, type: "Reference" }],
- });
- const relChild = node(1, "RELATIONAL", "Hash Join");
- const scalarChild = node(2, "SCALAR", "Param");
- render(
- <SpannerPlanNode
- node={root}
- allNodes={[root, relChild, scalarChild]}
- depth={0}
- />
- );
- expect(screen.getByText("Hash Join")).toBeInTheDocument();
- expect(screen.queryByText("Param")).not.toBeInTheDocument();
- });
-
- test("collapses children when the node row is clicked", () => {
- const root = node(0, "RELATIONAL", "Distributed Union", {
- childLinks: [{ childIndex: 1 }],
- });
- const child = node(1, "RELATIONAL", "Hash Join");
- render(<SpannerPlanNode node={root} allNodes={[root, child]} depth={0} />);
- expect(screen.getByText("Hash Join")).toBeInTheDocument();
- // The root's row is the first element with class `ev-spanner-row`.
- const row = document.querySelector(".ev-spanner-row");
- expect(row).not.toBeNull();
- fireEvent.click(row as Element);
- expect(screen.queryByText("Hash Join")).not.toBeInTheDocument();
- });
-
- test("filters out metadata keys that start with `_`", () => {
- const root = node(0, "RELATIONAL", "Scan", {
- metadata: {
- table: "users",
- _internal_id: "skip-me",
- },
- });
- render(<SpannerPlanNode node={root} allNodes={[root]} depth={0} />);
- expect(screen.getByText("table:")).toBeInTheDocument();
- expect(screen.getByText("users")).toBeInTheDocument();
- expect(screen.queryByText("_internal_id:")).not.toBeInTheDocument();
- expect(screen.queryByText("skip-me")).not.toBeInTheDocument();
- });
-
- test("renders shortRepresentation.description when present", () => {
- const root = node(0, "RELATIONAL", "Filter", {
- shortRepresentation: { description: "age > 18" },
- });
- render(<SpannerPlanNode node={root} allNodes={[root]} depth={0} />);
- expect(screen.getByText("age > 18")).toBeInTheDocument();
- });
-
- test("renders unknown placeholder for missing child indexes", () => {
- const root = node(0, "RELATIONAL", "Union", {
- childLinks: [{ childIndex: 42 }],
- });
- // Child 42 is missing from allNodes — but the parent only renders
- // children whose RELATIONAL kind matches. With a missing child the
- // filter drops the link, so nothing renders for it.
- render(<SpannerPlanNode node={root} allNodes={[root]} depth={0} />);
- expect(screen.queryByText(/Unknown Node/)).not.toBeInTheDocument();
- });
-});
diff --git a/frontend/src/apps/explain-visualizer/SpannerPlanNode.tsx b/frontend/src/apps/explain-visualizer/SpannerPlanNode.tsx
deleted file mode 100644
index c1ba98cfe9..0000000000
--- a/frontend/src/apps/explain-visualizer/SpannerPlanNode.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
-import { useMemo, useState } from "react";
-import type { SpannerChildLink, SpannerPlanNodeData } from "./spanner-types";
-
-interface Props {
- node: SpannerPlanNodeData;
- allNodes: SpannerPlanNodeData[];
- depth: number;
-}
-
-const formatValue = (value: unknown): string => {
- if (value === null || value === undefined) return "null";
- if (typeof value === "object") return JSON.stringify(value);
- return String(value);
-};
-
-const kindClassName = (kind: string): string => {
- switch (kind) {
- case "RELATIONAL":
- return "ev-spanner-kind-relational";
- case "SCALAR":
- return "ev-spanner-kind-scalar";
- default:
- return "ev-spanner-kind-unknown";
- }
-};
-
-export function SpannerPlanNode({ node, allNodes, depth }: Props) {
- const [expanded, setExpanded] = useState(true);
-
- const relationalChildLinks = useMemo<SpannerChildLink[]>(() => {
- if (!node.childLinks) return [];
- return node.childLinks.filter((link) => {
- const childNode = allNodes.find((n) => n.index === link.childIndex);
- return childNode && childNode.kind === "RELATIONAL";
- });
- }, [node.childLinks, allNodes]);
-
- const hasChildren = relationalChildLinks.length > 0;
- const isScalar = node.kind === "SCALAR";
- const shortDescription = node.shortRepresentation?.description;
-
- const displayMetadata = useMemo<Record<string, unknown>>(() => {
- if (!node.metadata) return {};
- // Filter out internal metadata keys (prefixed with `_`).
- const filtered: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(node.metadata)) {
- if (!key.startsWith("_")) filtered[key] = value;
- }
- return filtered;
- }, [node.metadata]);
-
- const hasMetadata = Object.keys(displayMetadata).length > 0;
-
- const handleToggle = () => {
- if (hasChildren) setExpanded((v) => !v);
- };
-
- const getChildNode = (index: number): SpannerPlanNodeData => {
- const child = allNodes.find((n) => n.index === index);
- return (
- child ?? {
- index,
- kind: "UNKNOWN",
- displayName: `Unknown Node (${index})`,
- }
- );
- };
-
- return (
- <div
- className={`ev-spanner-node${isScalar ? " is-scalar" : ""}`}
- data-depth={depth}
- >
- <div className="ev-spanner-row" onClick={handleToggle}>
- {hasChildren ? (
- <span className="ev-spanner-toggle">
- {expanded ? (
- <ChevronDownIcon className="w-4" />
- ) : (
- <ChevronUpIcon className="w-4" />
- )}
- </span>
- ) : (
- <span className="ev-spanner-toggle-placeholder" />
- )}
-
- <span className={`ev-spanner-kind ${kindClassName(node.kind)}`}>
- {node.kind}
- </span>
- <span className="ev-spanner-name">{node.displayName}</span>
-
- {shortDescription ? (
- <span className="ev-spanner-desc">{shortDescription}</span>
- ) : null}
- </div>
-
- {hasMetadata ? (
- <div className="ev-spanner-metadata">
- {Object.entries(displayMetadata).map(([key, value]) => (
- <div key={key} className="ev-spanner-metadata-item">
- <span className="ev-spanner-metadata-key">{key}:</span>
- <span className="ev-spanner-metadata-value">
- {formatValue(value)}
- </span>
- </div>
- ))}
- </div>
- ) : null}
-
- {expanded && hasChildren ? (
- <div className="ev-spanner-children">
- {relationalChildLinks.map((childLink) => (
- <div key={childLink.childIndex} className="ev-spanner-child">
- {childLink.type ? (
- <div className="ev-spanner-child-type">{childLink.type}</div>
- ) : null}
- <SpannerPlanNode
- node={getChildNode(childLink.childIndex)}
- allNodes={allNodes}
- depth={depth + 1}
- />
- </div>
- ))}
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/frontend/src/apps/explain-visualizer/SpannerQueryPlan.tsx b/frontend/src/apps/explain-visualizer/SpannerQueryPlan.tsx
deleted file mode 100644
index 4ebf618636..0000000000
--- a/frontend/src/apps/explain-visualizer/SpannerQueryPlan.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useMemo } from "react";
-import { SpannerPlanNode } from "./SpannerPlanNode";
-import type { SpannerPlanNodeData } from "./spanner-types";
-
-interface Props {
- planSource: string;
- planQuery?: string;
-}
-
-export function SpannerQueryPlan({ planSource, planQuery }: Props) {
- const planNodes = useMemo<SpannerPlanNodeData[]>(() => {
- try {
- const parsed = JSON.parse(planSource);
- return parsed.planNodes || [];
- } catch {
- return [];
- }
- }, [planSource]);
-
- // The first node (index 0) is the root node in Spanner query plans.
- const rootNode = useMemo<SpannerPlanNodeData | undefined>(() => {
- if (planNodes.length === 0) return undefined;
- return planNodes.find((node) => node.index === 0);
- }, [planNodes]);
-
- return (
- <div className="ev-spanner">
- <div className="ev-spanner-header">
- <h3>Query Plan</h3>
- {planQuery ? <div className="ev-spanner-query">{planQuery}</div> : null}
- </div>
- <div className="ev-spanner-tree">
- {rootNode ? (
- <SpannerPlanNode node={rootNode} allNodes={planNodes} depth={0} />
- ) : (
- <div className="ev-spanner-empty">No query plan available</div>
- )}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/apps/explain-visualizer/explain-visualizer.css b/frontend/src/apps/explain-visualizer/explain-visualizer.css
index 228320b2fb..3d44a769a1 100644
--- a/frontend/src/apps/explain-visualizer/explain-visualizer.css
+++ b/frontend/src/apps/explain-visualizer/explain-visualizer.css
@@ -1,18 +1,9 @@
-/* Standalone styles for the Explain Visualizer entry.
- The page loads the product's Tailwind entry, so the PostgreSQL view uses the
- shared semantic tokens. The `ev-` prefixed rules below belong to the SQL
- Server and Spanner views, which predate that and also share the page with
- `html-query-plan`'s stylesheet. */
-
-:root {
- --radius-xs: 2px;
- --radius-sm: 4px;
-}
+/* The Explain Visualizer entry loads the product's Tailwind entry and nothing
+ else of the app, so the page itself has to fill the tab. */
html,
body,
-#app,
-.ev-app {
+#app {
height: 100%;
}
@@ -21,207 +12,3 @@ body {
background-color: rgb(var(--color-background));
color: rgb(var(--color-main));
}
-
-.ev-app {
- display: flex;
-}
-
-.ev-unsupported {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- width: 100%;
- height: 100%;
- padding: 24px;
- text-align: center;
-}
-
-/* Tailwind's preflight strips heading sizing, so these state screens restate
- it rather than relying on browser defaults. */
-.ev-unsupported h2 {
- margin-bottom: 8px;
- font-size: 18px;
- font-weight: 600;
- color: rgb(var(--color-main));
-}
-
-.ev-unsupported p {
- color: rgb(var(--color-control-light));
-}
-
-.ev-mssql-container {
- width: 100%;
- height: 100%;
- overflow: auto;
- padding: 16px;
-}
-
-/* Spanner query plan tree */
-.ev-spanner {
- width: 100%;
- height: 100%;
- overflow: auto;
- padding: 16px;
- font-family:
- -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
- Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
-}
-
-.ev-spanner-header {
- margin-bottom: 16px;
- padding-bottom: 12px;
- border-bottom: 1px solid #e0e0e0;
-}
-
-.ev-spanner-header h3 {
- margin: 0 0 8px 0;
- font-size: 18px;
- font-weight: 600;
- color: #333;
-}
-
-.ev-spanner-query {
- font-family:
- "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
- font-size: 13px;
- color: #666;
- background-color: #f5f5f5;
- padding: 8px 12px;
- border-radius: var(--radius-sm);
- white-space: pre-wrap;
- word-break: break-word;
-}
-
-.ev-spanner-tree {
- padding: 8px 0;
-}
-
-.ev-spanner-empty {
- color: #999;
- font-style: italic;
- padding: 16px;
- text-align: center;
-}
-
-.ev-spanner-node {
- margin-left: 0;
- font-size: 14px;
-}
-
-.ev-spanner-node.is-scalar {
- display: inline;
-}
-
-.ev-spanner-row {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 6px 8px;
- border-radius: var(--radius-sm);
- cursor: pointer;
- transition: background-color 0.15s ease;
-}
-
-.ev-spanner-row:hover {
- background-color: #f0f4f8;
-}
-
-.ev-spanner-toggle {
- width: 16px;
- font-size: 10px;
- color: #666;
- user-select: none;
-}
-
-.ev-spanner-toggle-placeholder {
- width: 16px;
-}
-
-.ev-spanner-kind {
- font-size: 11px;
- font-weight: 600;
- padding: 2px 6px;
- border-radius: var(--radius-xs);
- text-transform: uppercase;
-}
-
-.ev-spanner-kind-relational {
- background-color: #e3f2fd;
- color: #1565c0;
-}
-
-.ev-spanner-kind-scalar {
- background-color: #f3e5f5;
- color: #7b1fa2;
-}
-
-.ev-spanner-kind-unknown {
- background-color: #f5f5f5;
- color: #666;
-}
-
-.ev-spanner-name {
- font-weight: 500;
- color: #333;
-}
-
-.ev-spanner-desc {
- font-family:
- "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
- font-size: 12px;
- color: #666;
- background-color: #f5f5f5;
- padding: 2px 6px;
- border-radius: var(--radius-xs);
- max-width: 400px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.ev-spanner-metadata {
- margin-left: 40px;
- margin-top: 4px;
- padding: 8px 12px;
- background-color: #fafafa;
- border-radius: var(--radius-sm);
- border-left: 3px solid #e0e0e0;
-}
-
-.ev-spanner-metadata-item {
- display: flex;
- gap: 8px;
- font-size: 12px;
- line-height: 1.6;
-}
-
-.ev-spanner-metadata-key {
- font-weight: 500;
- color: #666;
-}
-
-.ev-spanner-metadata-value {
- font-family:
- "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
- color: #333;
- word-break: break-all;
-}
-
-.ev-spanner-children {
- margin-left: 24px;
- padding-left: 16px;
- border-left: 2px solid #e0e0e0;
-}
-
-.ev-spanner-child {
- margin-top: 4px;
-}
-
-.ev-spanner-child-type {
- font-size: 11px;
- color: #999;
- margin-left: 8px;
- margin-bottom: 2px;
- font-style: italic;
-}
diff --git a/frontend/src/apps/explain-visualizer/loadQueryPlanScript.ts b/frontend/src/apps/explain-visualizer/loadQueryPlanScript.ts
deleted file mode 100644
index 5872f74c57..0000000000
--- a/frontend/src/apps/explain-visualizer/loadQueryPlanScript.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-// Dynamically load `html-query-plan` from `/libs/qp.min.js` and resolve
-// when `window.QP.showPlan` is callable. The script attaches `QP` as a
-// global the first time it loads; subsequent calls short-circuit.
-
-declare global {
- interface Window {
- QP: {
- showPlan: (
- container: Element,
- planXml: string,
- options?: Record<string, unknown>
- ) => void;
- };
- }
-}
-
-const SCRIPT_ID = "html-query-plan-script";
-
-export const loadQueryPlanScript = (): Promise<void> => {
- return new Promise((resolve, reject) => {
- if (window.QP) {
- resolve();
- return;
- }
- if (document.getElementById(SCRIPT_ID)) {
- resolve();
- return;
- }
- const script = document.createElement("script");
- script.id = SCRIPT_ID;
- script.src = "/libs/qp.min.js";
- script.onload = () => resolve();
- script.onerror = () =>
- reject(new Error("Failed to load html-query-plan script"));
- document.head.appendChild(script);
- });
-};
diff --git a/frontend/src/apps/explain-visualizer/main.tsx b/frontend/src/apps/explain-visualizer/main.tsx
index 51d9efa672..e1a44a1c3d 100644
--- a/frontend/src/apps/explain-visualizer/main.tsx
+++ b/frontend/src/apps/explain-visualizer/main.tsx
@@ -1,5 +1,4 @@
import "@/assets/css/tailwind.css";
-import "html-query-plan/css/qp.css";
import "./explain-visualizer.css";
import { createRoot } from "react-dom/client";
import { ExplainVisualizerApp } from "./ExplainVisualizerApp";
diff --git a/frontend/src/apps/explain-visualizer/mssql-plan.test.ts b/frontend/src/apps/explain-visualizer/mssql-plan.test.ts
new file mode 100644
index 0000000000..aac33392b9
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/mssql-plan.test.ts
@@ -0,0 +1,481 @@
+import { describe, expect, test } from "vitest";
+import {
+ MSSQL_PLAN_EMPTY_MESSAGE,
+ MSSQL_PLAN_INVALID_XML_MESSAGE,
+ MSSQL_PLAN_NO_PLAN_MESSAGE,
+ parseMssqlPlan,
+} from "./mssql-plan";
+import {
+ PLAN_FULL_TABLE_SCAN,
+ PLAN_TOO_DEEP_MESSAGE,
+ type PlanNode,
+ type PlanTree,
+} from "./plan-model";
+import hashJoinAggregateSort from "./test-data/mssql/hash-join-aggregate-sort.xml?raw";
+import ifElse from "./test-data/mssql/if-else.xml?raw";
+import implicitConversionWarning from "./test-data/mssql/implicit-conversion-warning.xml?raw";
+import indexSeekKeyLookup from "./test-data/mssql/index-seek-key-lookup.xml?raw";
+import missingIndex from "./test-data/mssql/missing-index.xml?raw";
+import noJoinPredicate from "./test-data/mssql/no-join-predicate.xml?raw";
+import procedureTwoStatements from "./test-data/mssql/procedure-two-statements.xml?raw";
+import scalarUdf from "./test-data/mssql/scalar-udf.xml?raw";
+import splitStatementsBatch from "./test-data/mssql/split-statements-batch.xml?raw";
+import staticCursor from "./test-data/mssql/static-cursor.xml?raw";
+import twoStatementBatch from "./test-data/mssql/two-statement-batch.xml?raw";
+import unmatchedFilteredIndex from "./test-data/mssql/unmatched-filtered-index.xml?raw";
+
+const SHOWPLAN_NS = "http://schemas.microsoft.com/sqlserver/2004/07/showplan";
+
+const showplan = (statements: string) =>
+ `<ShowPlanXML xmlns="${SHOWPLAN_NS}" Version="1.564"><BatchSequence><Batch><Statements>${statements}</Statements></Batch></BatchSequence></ShowPlanXML>`;
+
+/** A statement whose plan is a chain of `depth` operators. */
+const nestedPlan = (depth: number): string => {
+ let relop =
+ '<RelOp NodeId="0" PhysicalOp="Table Scan" LogicalOp="Table Scan"><TableScan/></RelOp>';
+ for (let level = 1; level < depth; level += 1) {
+ relop = `<RelOp NodeId="${level}" PhysicalOp="Filter" LogicalOp="Filter"><Filter>${relop}</Filter></RelOp>`;
+ }
+ return showplan(
+ `<StmtSimple StatementType="SELECT"><QueryPlan>${relop}</QueryPlan></StmtSimple>`
+ );
+};
+
+const parseFixture = (source: string): PlanTree => {
+ const result = parseMssqlPlan(source);
+ if (!result.ok)
+ throw new Error(`expected a parsable plan: ${result.message}`);
+ return result.tree;
+};
+
+const nodeTypes = (tree: PlanTree) =>
+ tree.nodes.map((node) => `${node.id} ${node.nodeType}`);
+
+const byType = (tree: PlanTree, nodeType: string): PlanNode => {
+ const node = tree.nodes.find((entry) => entry.nodeType === nodeType);
+ if (!node) throw new Error(`no ${nodeType} node`);
+ return node;
+};
+
+const propertyValue = (node: PlanNode, label: string): string | undefined =>
+ node.properties.find((property) => property.label === label)?.value;
+
+describe("parseMssqlPlan", () => {
+ test("puts the statement above its operators, depth-first", () => {
+ const tree = parseFixture(hashJoinAggregateSort);
+
+ expect(nodeTypes(tree)).toEqual([
+ "0 SELECT",
+ "0.0 Sort",
+ "0.0.0 Compute Scalar",
+ "0.0.0.0 Hash Match (Aggregate)",
+ "0.0.0.0.0 Merge Join (Inner Join)",
+ "0.0.0.0.0.0 Stream Aggregate",
+ "0.0.0.0.0.0.0 Index Scan",
+ "0.0.0.0.0.1 Clustered Index Scan",
+ ]);
+ expect(tree.root).toMatchObject({
+ subject:
+ "SELECT c.region, COUNT(*) AS orders FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.region ORDER BY COUNT(*) DESC",
+ totalCost: 0.276656,
+ selfCost: 0,
+ rows: 3,
+ });
+ expect(tree.root.width).toBeUndefined();
+ });
+
+ test("names operators the way SQL Server Management Studio does", () => {
+ // The logical operator only joins the name when it says something new.
+ expect(nodeTypes(parseFixture(indexSeekKeyLookup))).toEqual([
+ "0 SELECT",
+ "0.0 Nested Loops (Inner Join)",
+ "0.0.0 Index Seek",
+ // SQL Server reports the lookup as a clustered index seek.
+ "0.0.1 Key Lookup",
+ ]);
+ const procedure = parseFixture(procedureTwoStatements);
+ expect(byType(procedure, "TopN Sort").subject).toBe("o.total DESC");
+ expect(byType(procedure, "Hash Match (Inner Join)").subject).toBe(
+ "c.id = o.customer_id"
+ );
+ });
+
+ test("reports SQL Server's estimates, with no startup cost to report", () => {
+ const tree = parseFixture(hashJoinAggregateSort);
+ const scan = byType(tree, "Index Scan");
+
+ expect(tree.estimates).toEqual({
+ cost: true,
+ startupCost: false,
+ rows: true,
+ width: true,
+ });
+ expect(scan).toMatchObject({ totalCost: 0.121986, rows: 50000, width: 11 });
+ expect(scan.startupCost).toBeUndefined();
+ });
+
+ test("charges each operator only the cost its children do not explain", () => {
+ const tree = parseFixture(hashJoinAggregateSort);
+ const selfTotal = tree.nodes.reduce(
+ (sum, node) => sum + (node.selfCost ?? 0),
+ 0
+ );
+
+ expect(byType(tree, "Sort").selfCost).toBeCloseTo(0.276656 - 0.265287, 9);
+ expect(byType(tree, "Compute Scalar").selfCost).toBe(0);
+ expect(selfTotal).toBeCloseTo(0.276656, 9);
+ expect(tree.costBasis).toBeCloseTo(0.276656, 9);
+ });
+
+ test("says what each operator works on", () => {
+ const tree = parseFixture(hashJoinAggregateSort);
+
+ expect(byType(tree, "Index Scan").subject).toBe(
+ "orders.orders_customer_id_idx"
+ );
+ expect(byType(tree, "Merge Join (Inner Join)").subject).toBe(
+ "o.customer_id = c.id"
+ );
+ expect(byType(tree, "Hash Match (Aggregate)").subject).toBe("c.region");
+ expect(byType(tree, "Stream Aggregate").subject).toBe("o.customer_id");
+ expect(byType(tree, "Sort").subject).toBe("Expr1002 DESC");
+ expect(byType(tree, "Compute Scalar").subject).toBeUndefined();
+ });
+
+ test("carries the operator's expressions and attributes as properties", () => {
+ const tree = parseFixture(indexSeekKeyLookup);
+ const seek = byType(tree, "Index Seek");
+ const lookup = byType(tree, "Key Lookup");
+
+ expect(seek.properties.slice(0, 3)).toEqual([
+ {
+ label: "Object",
+ value: "[plandb].[dbo].[orders].[orders_customer_id_idx]",
+ },
+ { label: "Index Kind", value: "NonClustered" },
+ { label: "Seek Predicates", value: "orders.customer_id = (42)" },
+ ]);
+ expect(propertyValue(seek, "Output List")).toBe(
+ "orders.id, orders.customer_id"
+ );
+ expect(propertyValue(seek, "Estimated Rows Read")).toBe("10");
+ expect(propertyValue(seek, "Scan Direction")).toBe("FORWARD");
+ // Only an operator that reruns says how many times it runs.
+ expect(propertyValue(seek, "Estimated Executions")).toBeUndefined();
+ expect(propertyValue(lookup, "Estimated Executions")).toBe("10");
+ expect(propertyValue(tree.root, "Parameter List")).toBe("@1 = (42)");
+ expect(propertyValue(tree.root, "Statement Optm Level")).toBe("FULL");
+ });
+
+ test("writes flags, sizes, times and tiny numbers out the way SSMS shows them", () => {
+ const tree = parseFixture(indexSeekKeyLookup);
+ const seek = byType(tree, "Index Seek");
+
+ expect(propertyValue(seek, "Ordered")).toBe("True");
+ expect(propertyValue(seek, "Forced Index")).toBe("False");
+ expect(propertyValue(byType(tree, "Key Lookup"), "Lookup")).toBe("True");
+ expect(propertyValue(tree.root, "Retrieved From Cache")).toBe("False");
+ expect(propertyValue(tree.root, "Cached Plan Size")).toBe("32 KB");
+ expect(propertyValue(tree.root, "Compile Time")).toBe("1 ms");
+ expect(
+ propertyValue(byType(tree, "Nested Loops (Inner Join)"), "Estimate CPU")
+ ).toBe("0.0000418");
+ });
+
+ test("keeps fields the model already has out of the property list", () => {
+ const tree = parseFixture(indexSeekKeyLookup);
+ const labels = tree.nodes.flatMap((node) =>
+ node.properties.map((property) => property.label)
+ );
+
+ for (const promoted of [
+ "Physical Op",
+ "Logical Op",
+ "Estimate Rows",
+ "Avg Row Size",
+ "Estimated Total Subtree Cost",
+ "Statement Type",
+ "Statement Sub Tree Cost",
+ "Statement Est Rows",
+ ]) {
+ expect(labels).not.toContain(promoted);
+ }
+ });
+
+ test("labels the condition and branches of an IF", () => {
+ const { root } = parseFixture(ifElse);
+
+ expect(root.nodeType).toBe("COND WITH QUERY");
+ expect(
+ root.children.map((child) => [child.relationship, child.nodeType])
+ ).toEqual([
+ ["Condition", "Compute Scalar"],
+ ["Then", "SELECT"],
+ ["Else", "SELECT WITHOUT QUERY"],
+ ]);
+ // The ELSE branch returns a constant and has nothing to estimate.
+ expect(root.children[2].totalCost).toBeUndefined();
+ expect(root.totalCost).toBeCloseTo(0.00330167 + 0.151986, 9);
+ expect(root.selfCost).toBe(0);
+ });
+
+ test("puts a procedure's statements under the call", () => {
+ const { root } = parseFixture(procedureTwoStatements);
+
+ expect(root.nodeType).toBe("EXECUTE PROC");
+ expect(propertyValue(root, "Procedure Name")).toBe("dbo.region_report");
+ expect(root.children.map((child) => child.nodeType)).toEqual([
+ "SELECT",
+ "SELECT",
+ ]);
+ expect(root.totalCost).toBeCloseTo(0.0343858 + 1.60801, 9);
+ });
+
+ test("labels a called function's statements with the function's name", () => {
+ const { root } = parseFixture(scalarUdf);
+
+ expect(
+ root.children.map((child) => [child.relationship, child.nodeType])
+ ).toEqual([
+ [undefined, "Compute Scalar"],
+ ["dbo.order_count", "SELECT"],
+ ["dbo.order_count", "RETURN"],
+ ]);
+ // SQL Server's own estimate for the statement, 0.00345998, leaves the
+ // function out.
+ expect(root.totalCost).toBeCloseTo(0.00345998 + 0.0032842, 9);
+ });
+
+ test("roots a batch of statements in one tree", () => {
+ const { root } = parseFixture(twoStatementBatch);
+
+ expect(root).toMatchObject({ nodeType: "Batch", subject: "2 statements" });
+ expect(root.children.map((child) => child.subject)).toEqual([
+ "SELECT COUNT(*) FROM customers",
+ "; SELECT COUNT(*) FROM orders",
+ ]);
+ expect(root.totalCost).toBeCloseTo(0.0354862 + 0.151986, 9);
+ });
+
+ test("reads every statement of a batch that gives each its own block", () => {
+ const { root } = parseFixture(splitStatementsBatch);
+
+ expect(root.children.map((child) => child.nodeType)).toEqual([
+ "CREATE TABLE",
+ "ASSIGN",
+ "EXECUTE STRING",
+ "DECLARE CURSOR",
+ "OPEN CURSOR",
+ "FETCH CURSOR",
+ "COND",
+ "CLOSE CURSOR",
+ "DEALLOCATE CURSOR",
+ "DROP OBJECT",
+ ]);
+ });
+
+ test("turns an operator warning SQL Server reports into a node warning", () => {
+ const tree = parseFixture(noJoinPredicate);
+
+ expect(byType(tree, "Nested Loops (Inner Join)").warnings).toEqual([
+ {
+ title: "No join predicate",
+ detail:
+ "The join has no condition, so every row of one input is paired with every row of the other.",
+ },
+ ]);
+ });
+
+ test("puts a statement's warnings on the statement", () => {
+ const { root } = parseFixture(implicitConversionWarning);
+
+ expect(root.warnings.map((warning) => warning.detail)).toEqual([
+ 'Type conversion in expression (CONVERT_IMPLICIT(int,[plandb].[dbo].[customers].[code],0)) may affect "Cardinality Estimate" in query plan choice.',
+ 'Type conversion in expression (CONVERT_IMPLICIT(int,[plandb].[dbo].[customers].[code],0)=CONVERT_IMPLICIT(int,[@1],0)) may affect "Seek Plan" in query plan choice.',
+ ]);
+ });
+
+ test("writes a missing index out as the statement that creates it", () => {
+ const { root } = parseFixture(missingIndex);
+
+ expect(root.warnings).toEqual([
+ {
+ title: "Missing index",
+ detail:
+ "SQL Server estimates this index would lower the statement's cost by 78.4%: CREATE NONCLUSTERED INDEX [idx_orders_total] ON [dbo].[orders] ([total]) INCLUDE ([customer_id]);",
+ },
+ ]);
+ });
+
+ test("warns on a full scan of a table large enough to matter", () => {
+ const tree = parseFixture(missingIndex);
+ const scans = tree.nodes.filter(
+ (node) => node.nodeType === "Clustered Index Scan"
+ );
+
+ // `orders` reads 50,000 rows; `customers` reads 5,000, too few to matter.
+ expect(scans.map((scan) => [scan.subject, scan.warnings])).toEqual([
+ ["customers.PK__customer__3213E83FBDBA5577", []],
+ ["orders.PK__orders__3213E83F52C28C59", [PLAN_FULL_TABLE_SCAN]],
+ ]);
+ // A nonclustered index is narrower than the table, so reading all of it
+ // is not flagged.
+ expect(
+ byType(parseFixture(hashJoinAggregateSort), "Index Scan").warnings
+ ).toEqual([]);
+ });
+
+ test("reads separate seeks as alternatives and one seek's ranges as all holding", () => {
+ const range = (
+ element: string,
+ scanType: string,
+ column: string,
+ value: string
+ ) =>
+ `<${element} ScanType="${scanType}"><RangeColumns><ColumnReference Table="[orders]" Column="${column}"/></RangeColumns><RangeExpressions><ScalarOperator ScalarString="${value}"/></RangeExpressions></${element}>`;
+ const seek = (...ranges: string[]) =>
+ `<SeekPredicateNew><SeekKeys>${ranges.join("")}</SeekKeys></SeekPredicateNew>`;
+ const tree = parseFixture(
+ showplan(
+ `<StmtSimple StatementType="SELECT"><QueryPlan><RelOp NodeId="0" PhysicalOp="Index Seek" LogicalOp="Index Seek"><IndexScan><Object Table="[orders]" Index="[orders_customer_id_idx]"/><SeekPredicates>${seek(range("Prefix", "EQ", "customer_id", "(1)"))}${seek(range("Prefix", "EQ", "customer_id", "(2)"))}${seek(range("StartRange", "GT", "total", "(10)"), range("EndRange", "LT", "total", "(20)"))}</SeekPredicates></IndexScan></RelOp></QueryPlan></StmtSimple>`
+ )
+ );
+
+ // An IN list seeks once per value; a range seek bounds both ends at once.
+ expect(propertyValue(byType(tree, "Index Seek"), "Seek Predicates")).toBe(
+ "orders.customer_id = (1) OR orders.customer_id = (2) OR orders.total > (10) AND orders.total < (20)"
+ );
+ });
+
+ test("explains a flag SQL Server raises on a statement without naming an operator", () => {
+ const { root } = parseFixture(
+ showplan(
+ '<StmtSimple StatementType="SELECT"><QueryPlan><Warnings UnmatchedIndexes="true" SpatialGuess="1"/></QueryPlan></StmtSimple>'
+ )
+ );
+
+ expect(root.warnings).toEqual([
+ {
+ title: "Unmatched indexes",
+ detail:
+ "A filtered index could not be used because the statement is parameterized.",
+ },
+ {
+ title: "Spatial Guess",
+ detail: "SQL Server flagged this while compiling the plan.",
+ },
+ ]);
+ });
+
+ test("names the filtered indexes a parameterized statement could not use", () => {
+ const statement = byType(parseFixture(unmatchedFilteredIndex), "SELECT");
+
+ expect(statement.warnings).toContainEqual({
+ title: "Unmatched indexes",
+ detail:
+ "The statement is parameterized, so SQL Server could not use the filtered index [plandb].[dbo].[orders].[orders_big_total_idx].",
+ });
+ });
+
+ test("says what an unfamiliar warning names, and still says something when it names nothing", () => {
+ const { root } = parseFixture(
+ showplan(
+ '<StmtSimple StatementType="SELECT"><QueryPlan><Warnings><ColumnsWithStaleStatistics><ColumnReference Table="[customers]" Column="region"/></ColumnsWithStaleStatistics><SpillOccurred/></Warnings></QueryPlan></StmtSimple>'
+ )
+ );
+
+ expect(root.warnings).toEqual([
+ { title: "Columns With Stale Statistics", detail: "customers.region" },
+ {
+ title: "Spill Occurred",
+ detail: "SQL Server flagged this while compiling the plan.",
+ },
+ ]);
+ });
+
+ test("keeps a suggested index's name within SQL Server's identifier limit", () => {
+ const columns = [1, 2, 3, 4]
+ .map(
+ (n) =>
+ `<Column Name="[a_column_name_long_enough_to_matter_here_${n}]"/>`
+ )
+ .join("");
+ const { root } = parseFixture(
+ showplan(
+ `<StmtSimple StatementType="SELECT"><QueryPlan><MissingIndexes><MissingIndexGroup Impact="50"><MissingIndex Schema="[dbo]" Table="[customer_order_history]"><ColumnGroup Usage="EQUALITY">${columns}</ColumnGroup></MissingIndex></MissingIndexGroup></MissingIndexes></QueryPlan></StmtSimple>`
+ )
+ );
+ const name = /INDEX \[([^\]]+)\]/.exec(root.warnings[0].detail)?.[1] ?? "";
+
+ expect(name).toHaveLength(128);
+ expect(name.startsWith("idx_customer_order_history_")).toBe(true);
+ });
+
+ test("escapes a closing bracket in a suggested index's name", () => {
+ const { root } = parseFixture(
+ showplan(
+ '<StmtSimple StatementType="SELECT"><QueryPlan><MissingIndexes><MissingIndexGroup><MissingIndex Schema="[dbo]" Table="[sales]]2026]"><ColumnGroup Usage="EQUALITY"><Column Name="[total]"/></ColumnGroup></MissingIndex></MissingIndexGroup></MissingIndexes></QueryPlan></StmtSimple>'
+ )
+ );
+
+ expect(root.warnings[0].detail).toBe(
+ "SQL Server suggests this index: CREATE NONCLUSTERED INDEX [idx_sales]]2026_total] ON [dbo].[sales]]2026] ([total]);"
+ );
+ });
+
+ test("reads a cursor's query plans as the cursor statement's own", () => {
+ const { root } = parseFixture(
+ showplan(
+ '<StmtCursor StatementType="DECLARE CURSOR" StatementText="DECLARE c CURSOR FOR SELECT id FROM orders WHERE total = 500.99"><CursorPlan CursorName="c"><Operation OperationType="FetchQuery"><QueryPlan CachedPlanSize="16"><MissingIndexes><MissingIndexGroup Impact="90"><MissingIndex Schema="[dbo]" Table="[orders]"><ColumnGroup Usage="EQUALITY"><Column Name="[total]"/></ColumnGroup></MissingIndex></MissingIndexGroup></MissingIndexes><RelOp NodeId="0" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan"><IndexScan/></RelOp></QueryPlan></Operation></CursorPlan></StmtCursor>'
+ )
+ );
+
+ expect(root.nodeType).toBe("DECLARE CURSOR");
+ expect(root.children.map((child) => child.nodeType)).toEqual([
+ "Clustered Index Scan",
+ ]);
+ expect(root.warnings.map((warning) => warning.title)).toEqual([
+ "Missing index",
+ ]);
+ expect(propertyValue(root, "Cached Plan Size")).toBe("16 KB");
+ });
+
+ test("labels a cursor's population and fetch queries and says what kind of cursor it is", () => {
+ const { root } = parseFixture(staticCursor);
+
+ expect(root.nodeType).toBe("DECLARE CURSOR");
+ expect(
+ root.children.map((child) => [child.relationship, child.nodeType])
+ ).toEqual([
+ ["Populate Query", "Clustered Index Insert"],
+ ["Fetch Query", "Clustered Index Seek"],
+ ]);
+ expect(propertyValue(root, "Cursor Actual Type")).toBe("SnapShot");
+ expect(propertyValue(root, "Cursor Concurrency")).toBe("Read Only");
+ expect(propertyValue(root, "Forward Only")).toBe("False");
+ });
+
+ test("reads a plan nested deeper than anything the optimizer produces", () => {
+ const result = parseMssqlPlan(nestedPlan(100));
+ // The statement, then its hundred operators.
+ expect(result.ok && result.tree.nodes).toHaveLength(101);
+ });
+
+ test("rejects a plan nested deeper than the walks over it can go", () => {
+ expect(parseMssqlPlan(nestedPlan(2000))).toEqual({
+ ok: false,
+ message: PLAN_TOO_DEEP_MESSAGE,
+ });
+ });
+
+ test.each([
+ ["", MSSQL_PLAN_EMPTY_MESSAGE],
+ [" ", MSSQL_PLAN_EMPTY_MESSAGE],
+ ["Clustered Index Scan", MSSQL_PLAN_INVALID_XML_MESSAGE],
+ ["<ShowPlanXML>", MSSQL_PLAN_INVALID_XML_MESSAGE],
+ ["<plan/>", MSSQL_PLAN_NO_PLAN_MESSAGE],
+ [showplan(""), MSSQL_PLAN_NO_PLAN_MESSAGE],
+ ])("rejects %j with a specific message", (source, message) => {
+ expect(parseMssqlPlan(source)).toEqual({ ok: false, message });
+ });
+});
diff --git a/frontend/src/apps/explain-visualizer/mssql-plan.ts b/frontend/src/apps/explain-visualizer/mssql-plan.ts
new file mode 100644
index 0000000000..cf06845cea
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/mssql-plan.ts
@@ -0,0 +1,822 @@
+import {
+ addPlanProperty,
+ checkPlanDepth,
+ formatPlanCost,
+ formatPlanShare,
+ PLAN_FULL_TABLE_SCAN,
+ type PlanNode,
+ type PlanParseResult,
+ type PlanProperty,
+ type PlanWarning,
+ parseWithDepthLimit,
+ planSelfCost,
+} from "./plan-model";
+
+/**
+ * Maps SQL Server's `SHOWPLAN_XML` output onto the engine-neutral plan model.
+ *
+ * A showplan holds statements, and a statement with a query plan holds a tree
+ * of `RelOp` operators. Both become nodes: a statement is the parent of its
+ * plan's root operator, and a statement that contains others — an IF, a
+ * procedure call — is the parent of those. A batch of several statements gets
+ * a "Batch" root so the plan stays one tree.
+ *
+ * Names follow SQL Server Management Studio, and attributes the model has no
+ * field for are carried through under SQL Server's own names.
+ */
+
+export const MSSQL_PLAN_EMPTY_MESSAGE =
+ "SQL Server returned no query plan for this statement.";
+export const MSSQL_PLAN_INVALID_XML_MESSAGE =
+ "The query plan is not valid XML. SHOWPLAN_XML output is expected.";
+export const MSSQL_PLAN_NO_PLAN_MESSAGE =
+ "The query plan XML is not a SQL Server showplan with at least one statement.";
+
+const STATEMENT_ELEMENTS = new Set([
+ "StmtSimple",
+ "StmtCond",
+ "StmtCursor",
+ "StmtReceive",
+ "StmtUseDb",
+]);
+
+/** The branches of an IF, which label the statements and plans under them. */
+const BRANCH_ELEMENTS = new Set(["Condition", "Then", "Else"]);
+
+/** Children of a `RelOp` that describe it rather than being its operator. */
+const RELOP_DETAIL_ELEMENTS = new Set([
+ "OutputList",
+ "Warnings",
+ "MemoryFractions",
+ "RunTimeInformation",
+ "RunTimePartitionSummary",
+ "InternalInfo",
+]);
+
+/** Attributes promoted to typed fields, so the property list omits them. */
+const PROMOTED_STATEMENT_ATTRIBUTES = new Set([
+ "StatementText",
+ "StatementType",
+ "StatementSubTreeCost",
+ "StatementEstRows",
+]);
+const PROMOTED_RELOP_ATTRIBUTES = new Set([
+ "PhysicalOp",
+ "LogicalOp",
+ "EstimateRows",
+ "AvgRowSize",
+ "EstimatedTotalSubtreeCost",
+]);
+
+/** Operator children the property list puts first, in this order. */
+const LEADING_OPERATOR_ELEMENTS = ["Object", "SeekPredicates", "Predicate"];
+
+/** Operators that read a whole table: a heap, or the clustered index that is one. */
+const FULL_TABLE_SCAN_OPERATORS = new Set([
+ "Table Scan",
+ "Clustered Index Scan",
+]);
+
+/**
+ * Rows read at or below which a full table scan is not worth flagging, the
+ * same size of table the PostgreSQL parser leaves alone.
+ */
+const FULL_SCAN_ROWS_THRESHOLD = 5000;
+
+/** Longest name SQL Server accepts for an index, as for any identifier. */
+const MAX_IDENTIFIER_LENGTH = 128;
+
+const SEEK_OPERATORS: Record<string, string> = {
+ EQ: "=",
+ NE: "<>",
+ GT: ">",
+ GE: ">=",
+ LT: "<",
+ LE: "<=",
+};
+
+function childElements(element: Element | undefined, name?: string): Element[] {
+ if (!element) return [];
+ return Array.from(element.children).filter(
+ (child) => name === undefined || child.localName === name
+ );
+}
+
+function firstChild(
+ element: Element | undefined,
+ name: string
+): Element | undefined {
+ return childElements(element, name)[0];
+}
+
+function numberAttribute(element: Element, name: string): number | undefined {
+ const value = element.getAttribute(name);
+ if (value === null || value.trim() === "") return undefined;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+}
+
+function isTrue(value: string | null): boolean {
+ return value === "1" || value === "true";
+}
+
+/** "EstimatedRowsRead" as "Estimated Rows Read": SQL Server's name, spaced. */
+function humanize(name: string): string {
+ return name
+ .replace(/([a-z\d])([A-Z])/g, "$1 $2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
+}
+
+function unbracket(identifier: string): string {
+ const match = /^\[(.*)\]$/.exec(identifier);
+ return match ? match[1].replaceAll("]]", "]") : identifier;
+}
+
+function bracket(identifier: string): string {
+ return `[${identifier.replaceAll("]", "]]")}]`;
+}
+
+/** `o.customer_id`: the alias or table a column comes from, and the column. */
+function columnName(reference: Element): string {
+ const column = unbracket(reference.getAttribute("Column") ?? "");
+ const owner =
+ reference.getAttribute("Alias") ?? reference.getAttribute("Table");
+ return owner ? `${unbracket(owner)}.${column}` : column;
+}
+
+function columnList(element: Element | undefined): string[] {
+ return childElements(element, "ColumnReference").map(columnName);
+}
+
+function scalarStrings(element: Element | undefined): string[] {
+ return childElements(element, "ScalarOperator")
+ .map((scalar) => scalar.getAttribute("ScalarString") ?? "")
+ .filter(Boolean);
+}
+
+/**
+ * Attributes the showplan schema types as booleans, among those on the
+ * elements read here. SQL Server writes most of them as 1 or 0.
+ */
+const BOOLEAN_ATTRIBUTES = new Set([
+ "BatchModeOnRowStoreUsed",
+ "BitmapCreator",
+ "ComputeSequence",
+ "ContainsInlineScalarTsqlUdfs",
+ "ContainsInterleavedExecutionCandidates",
+ "ContainsLedgerTables",
+ "DMLRequestSort",
+ "Distinct",
+ "DynamicSeek",
+ "ExclusiveProfileTimeActive",
+ "ForceScan",
+ "ForceSeek",
+ "ForcedIndex",
+ "ForwardOnly",
+ "GroupExecuted",
+ "InRow",
+ "IsAdaptive",
+ "IsDistributed",
+ "IsExternal",
+ "IsExternallyComputed",
+ "IsFull",
+ "IsGraphDBTransitiveClosure",
+ "IsHashDistributed",
+ "IsNoOp",
+ "IsPercent",
+ "IsReplicated",
+ "IsRoundRobin",
+ "IsScalar",
+ "LocalParallelism",
+ "Lookup",
+ "ManyToMany",
+ "NoExpandHint",
+ "Optimized",
+ "Ordered",
+ "Parallel",
+ "Partitioned",
+ "RemoteDataAccess",
+ "Remoting",
+ "RowCount",
+ "SecurityPolicyApplied",
+ "Stack",
+ "StartupExpression",
+ "UsePlan",
+ "WithOrderedPrefetch",
+ "WithTies",
+ "WithUnorderedPrefetch",
+]);
+
+/** Units of the attributes that measure memory or time, per the showplan schema. */
+const ATTRIBUTE_UNITS: Record<string, string> = {
+ CachedPlanSize: "KB",
+ CompileTime: "ms",
+ CompileCPU: "ms",
+ CompileMemory: "KB",
+ MemoryGrant: "KB",
+ SerialRequiredMemory: "KB",
+ SerialDesiredMemory: "KB",
+ RequiredMemory: "KB",
+ DesiredMemory: "KB",
+ RequestedMemory: "KB",
+ GrantWaitTime: "s",
+ GrantedMemory: "KB",
+ MaxUsedMemory: "KB",
+ MaxQueryMemory: "KB",
+ LastRequestedMemory: "KB",
+};
+
+/** SQL Server writes numbers far from one in exponent form, as in `1.157e-06`. */
+const EXPONENT_NUMBER = /^[-+]?\d+(\.\d+)?e[-+]?\d+$/i;
+const plainNumberFormat = new Intl.NumberFormat("en-US", {
+ maximumSignificantDigits: 15,
+ useGrouping: false,
+});
+
+function formatAttribute(name: string, value: string): string {
+ if (BOOLEAN_ATTRIBUTES.has(name) || value === "true" || value === "false") {
+ return isTrue(value) ? "True" : "False";
+ }
+ const number = EXPONENT_NUMBER.test(value)
+ ? plainNumberFormat.format(Number(value))
+ : value;
+ const unit = ATTRIBUTE_UNITS[name];
+ return unit ? `${number} ${unit}` : number;
+}
+
+function addAttributes(
+ properties: PlanProperty[],
+ element: Element | undefined,
+ skip: ReadonlySet<string> = new Set()
+) {
+ for (const attribute of Array.from(element?.attributes ?? [])) {
+ if (skip.has(attribute.name)) continue;
+ addPlanProperty(
+ properties,
+ humanize(attribute.name),
+ formatAttribute(attribute.name, attribute.value)
+ );
+ }
+}
+
+/** `[plandb].[dbo].[orders].[orders_customer_id_idx] [o]`, as SSMS prints it. */
+function objectFullName(object: Element): string {
+ const name = ["Database", "Schema", "Table", "Index"]
+ .map((part) => object.getAttribute(part))
+ .filter(Boolean)
+ .join(".");
+ const alias = object.getAttribute("Alias");
+ return alias ? `${name} ${alias}` : name;
+}
+
+function descendantsNamed(
+ element: Element,
+ names: ReadonlySet<string>
+): Element[] {
+ return Array.from(element.getElementsByTagName("*")).filter((descendant) =>
+ names.has(descendant.localName)
+ );
+}
+
+const SEEK_ELEMENTS = new Set(["SeekPredicate", "SeekPredicateNew"]);
+const SEEK_RANGE_ELEMENTS = new Set(["Prefix", "StartRange", "EndRange"]);
+
+/**
+ * The ranges within one seek all hold, but each seek is a range of its own —
+ * one per value of an IN list — so separate seeks are alternatives.
+ */
+function formatSeekPredicates(seekPredicates: Element): string {
+ return descendantsNamed(seekPredicates, SEEK_ELEMENTS)
+ .map((seek) =>
+ descendantsNamed(seek, SEEK_RANGE_ELEMENTS)
+ .flatMap((range) => {
+ const scanType = range.getAttribute("ScanType") ?? "";
+ const operator = SEEK_OPERATORS[scanType] ?? scanType;
+ const columns = columnList(firstChild(range, "RangeColumns"));
+ const values = scalarStrings(firstChild(range, "RangeExpressions"));
+ return columns.map((column, index) =>
+ [column, operator, values[index]].filter(Boolean).join(" ")
+ );
+ })
+ .join(" AND ")
+ )
+ .filter(Boolean)
+ .join(" OR ");
+}
+
+function formatDefinedValues(definedValues: Element): string {
+ const entries = childElements(definedValues, "DefinedValue").map((entry) => {
+ const columns = columnList(entry).join(", ");
+ const [expression] = scalarStrings(entry);
+ return expression ? `${columns} = ${expression}` : columns;
+ });
+ const separator = entries.some((entry) => entry.includes(" = "))
+ ? "\n"
+ : ", ";
+ return entries.join(separator);
+}
+
+function formatOrderBy(orderBy: Element): string {
+ return childElements(orderBy, "OrderByColumn")
+ .map((entry) => {
+ const [column] = columnList(entry);
+ const direction = isTrue(entry.getAttribute("Ascending"))
+ ? "ASC"
+ : "DESC";
+ return `${column} ${direction}`;
+ })
+ .join(", ");
+}
+
+/** An operator's child element as text, or empty when it holds no expression. */
+function formatOperatorElement(element: Element): string {
+ switch (element.localName) {
+ case "Object":
+ return objectFullName(element);
+ case "SeekPredicates":
+ return formatSeekPredicates(element);
+ case "DefinedValues":
+ return formatDefinedValues(element);
+ case "OrderBy":
+ return formatOrderBy(element);
+ }
+ const expressions = scalarStrings(element);
+ if (expressions.length > 0) return expressions.join("\n");
+ return columnList(element).join(", ");
+}
+
+function pairColumns(left: string[], right: string[]): string {
+ return left
+ .map((column, index) => `${column} = ${right[index] ?? "?"}`)
+ .join(", ");
+}
+
+/** Warnings SQL Server raises as a flag on `<Warnings>`, by attribute name. */
+const FLAG_WARNINGS: Record<string, PlanWarning> = {
+ NoJoinPredicate: {
+ title: "No join predicate",
+ detail:
+ "The join has no condition, so every row of one input is paired with every row of the other.",
+ },
+ UnmatchedIndexes: {
+ title: "Unmatched indexes",
+ detail:
+ "A filtered index could not be used because the statement is parameterized.",
+ },
+};
+
+/**
+ * `unmatchedIndexes` names the filtered indexes the flag is about, which SQL
+ * Server lists beside `<Warnings>` in the query plan rather than inside it.
+ */
+function toServerWarnings(
+ warnings: Element | undefined,
+ unmatchedIndexes: readonly string[] = []
+): PlanWarning[] {
+ if (!warnings) return [];
+ const result: PlanWarning[] = [];
+ for (const attribute of Array.from(warnings.attributes)) {
+ if (!isTrue(attribute.value)) continue;
+ if (attribute.name === "UnmatchedIndexes" && unmatchedIndexes.length > 0) {
+ result.push({
+ title: FLAG_WARNINGS.UnmatchedIndexes.title,
+ detail: `The statement is parameterized, so SQL Server could not use the filtered ${unmatchedIndexes.length === 1 ? "index" : "indexes"} ${unmatchedIndexes.join(", ")}.`,
+ });
+ continue;
+ }
+ result.push(
+ FLAG_WARNINGS[attribute.name] ?? {
+ title: humanize(attribute.name),
+ detail: "SQL Server flagged this while compiling the plan.",
+ }
+ );
+ }
+ for (const child of childElements(warnings)) {
+ switch (child.localName) {
+ case "PlanAffectingConvert":
+ result.push({
+ title: "Type conversion affects the plan",
+ detail: `Type conversion in expression (${child.getAttribute("Expression") ?? ""}) may affect "${child.getAttribute("ConvertIssue") ?? ""}" in query plan choice.`,
+ });
+ break;
+ case "ColumnsWithNoStatistics":
+ result.push({
+ title: "Columns with no statistics",
+ detail: `Estimates over ${columnList(child).join(", ")} were made without statistics, so they may be far off.`,
+ });
+ break;
+ default: {
+ const details = [
+ ...Array.from(child.attributes).map(
+ (attribute) =>
+ `${humanize(attribute.name)}: ${formatAttribute(attribute.name, attribute.value)}`
+ ),
+ ...columnList(child),
+ ];
+ result.push({
+ title: humanize(child.localName),
+ detail:
+ details.length > 0
+ ? details.join(", ")
+ : "SQL Server flagged this while compiling the plan.",
+ });
+ }
+ }
+ }
+ return result;
+}
+
+/**
+ * An index SQL Server suggests for the statement, written out as the statement
+ * that creates it, and named in Bytebase's default index naming convention,
+ * `idx_<table>_<columns>`.
+ */
+function toMissingIndexWarnings(queryPlan: Element): PlanWarning[] {
+ const groups = childElements(
+ firstChild(queryPlan, "MissingIndexes"),
+ "MissingIndexGroup"
+ );
+ return groups.flatMap((group) =>
+ childElements(group, "MissingIndex").map((index) => {
+ const columns = (usages: string[]) =>
+ childElements(index, "ColumnGroup")
+ .filter((columnGroup) =>
+ usages.includes(columnGroup.getAttribute("Usage") ?? "")
+ )
+ .flatMap((columnGroup) => childElements(columnGroup, "Column"))
+ .map((column) => column.getAttribute("Name") ?? "");
+ const keys = columns(["EQUALITY", "INEQUALITY"]);
+ const includes = columns(["INCLUDE"]);
+ const table = index.getAttribute("Table") ?? "";
+ const name = ["idx", unbracket(table), ...keys.map(unbracket)]
+ .join("_")
+ .slice(0, MAX_IDENTIFIER_LENGTH);
+ const target = [index.getAttribute("Schema"), table]
+ .filter(Boolean)
+ .join(".");
+ const include =
+ includes.length > 0 ? ` INCLUDE (${includes.join(", ")})` : "";
+ const statement = `CREATE NONCLUSTERED INDEX ${bracket(name)} ON ${target} (${keys.join(", ")})${include};`;
+ const impact = numberAttribute(group, "Impact");
+ return {
+ title: "Missing index",
+ detail:
+ impact === undefined
+ ? `SQL Server suggests this index: ${statement}`
+ : `SQL Server estimates this index would lower the statement's cost by ${formatPlanShare(impact / 100)}: ${statement}`,
+ };
+ })
+ );
+}
+
+interface PlanChild {
+ readonly element: Element;
+ readonly relationship?: string;
+}
+
+/**
+ * The label an IF's branch, a cursor's operation or a called function puts on
+ * the plans under it. A function goes by the name a query calls it with,
+ * `dbo.order_count` for `[plandb].[dbo].[order_count]`.
+ */
+function branchLabel(element: Element): string | undefined {
+ if (BRANCH_ELEMENTS.has(element.localName)) return element.localName;
+ if (element.localName === "Operation") {
+ return humanize(element.getAttribute("OperationType") ?? "") || undefined;
+ }
+ if (element.localName === "UDF") {
+ const name = element.getAttribute("ProcName") ?? "";
+ const parts = Array.from(name.matchAll(/\[((?:[^\]]|\]\])*)\]/g), (match) =>
+ match[1].replaceAll("]]", "]")
+ );
+ return (parts.length > 0 ? parts.slice(-2).join(".") : name) || undefined;
+ }
+ return undefined;
+}
+
+/**
+ * The statements and operators directly below `element`: the nearest ones at
+ * any depth, since SQL Server nests them inside elements that are neither.
+ */
+function planChildren(element: Element): PlanChild[] {
+ const found: PlanChild[] = [];
+ const visit = (parent: Element, relationship: string | undefined) => {
+ for (const child of childElements(parent)) {
+ if (
+ child.localName === "RelOp" ||
+ STATEMENT_ELEMENTS.has(child.localName)
+ ) {
+ found.push({ element: child, relationship });
+ } else {
+ visit(child, branchLabel(child) ?? relationship);
+ }
+ }
+ };
+ visit(element, undefined);
+ return found;
+}
+
+function toChildren(element: Element, id: string, depth: number): PlanNode[] {
+ return planChildren(element).map((child, index) =>
+ toNode(child, `${id}.${index}`, depth + 1)
+ );
+}
+
+function toNode(child: PlanChild, id: string, depth: number): PlanNode {
+ checkPlanDepth(depth);
+ return child.element.localName === "RelOp"
+ ? toOperatorNode(child, id, depth)
+ : toStatementNode(child, id, depth);
+}
+
+/**
+ * The query plans a statement owns, as opposed to ones nested statements do:
+ * its own, an IF's condition, and each operation of a cursor.
+ */
+function ownQueryPlans(statement: Element): Element[] {
+ return [
+ ...childElements(statement, "QueryPlan"),
+ ...childElements(firstChild(statement, "Condition"), "QueryPlan"),
+ ...childElements(firstChild(statement, "CursorPlan"), "Operation").flatMap(
+ (operation) => childElements(operation, "QueryPlan")
+ ),
+ ];
+}
+
+function toStatementNode(
+ { element, relationship }: PlanChild,
+ id: string,
+ depth: number
+): PlanNode {
+ const children = toChildren(element, id, depth);
+ const queryPlans = ownQueryPlans(element);
+
+ // A statement costs what the operators and statements under it do, a
+ // called function's body included once, though SQL Server leaves that out
+ // of its own estimate; only a statement with neither keeps the cost SQL
+ // Server gave it.
+ const totalCost = children.some((child) => child.totalCost !== undefined)
+ ? children.reduce((sum, child) => sum + (child.totalCost ?? 0), 0)
+ : numberAttribute(element, "StatementSubTreeCost");
+
+ const text = element.getAttribute("StatementText") ?? "";
+ const properties: PlanProperty[] = [];
+ addPlanProperty(properties, "Statement", text.trim());
+ addPlanProperty(
+ properties,
+ "Procedure Name",
+ firstChild(element, "StoredProc")?.getAttribute("ProcName") ?? ""
+ );
+ addAttributes(properties, element, PROMOTED_STATEMENT_ATTRIBUTES);
+ addAttributes(properties, firstChild(element, "CursorPlan"));
+ for (const queryPlan of queryPlans) {
+ addAttributes(properties, queryPlan);
+ addAttributes(properties, firstChild(queryPlan, "MemoryGrantInfo"));
+ const parameters = childElements(
+ firstChild(queryPlan, "ParameterList"),
+ "ColumnReference"
+ ).map((parameter) =>
+ [
+ parameter.getAttribute("Column"),
+ parameter.getAttribute("ParameterCompiledValue"),
+ ]
+ .filter(Boolean)
+ .join(" = ")
+ );
+ addPlanProperty(properties, "Parameter List", parameters.join(", "));
+ }
+
+ return {
+ id,
+ nodeType: element.getAttribute("StatementType") ?? "Statement",
+ subject: text.replace(/\s+/g, " ").trim() || undefined,
+ relationship,
+ totalCost,
+ selfCost: planSelfCost(totalCost, children),
+ rows: numberAttribute(element, "StatementEstRows"),
+ properties,
+ warnings: queryPlans.flatMap((queryPlan) => [
+ ...toServerWarnings(
+ firstChild(queryPlan, "Warnings"),
+ childElements(
+ firstChild(
+ firstChild(queryPlan, "UnmatchedIndexes"),
+ "Parameterization"
+ ),
+ "Object"
+ ).map(objectFullName)
+ ),
+ ...toMissingIndexWarnings(queryPlan),
+ ]),
+ children,
+ };
+}
+
+function operatorElement(relop: Element): Element | undefined {
+ return childElements(relop).find(
+ (child) => !RELOP_DETAIL_ELEMENTS.has(child.localName)
+ );
+}
+
+/**
+ * The operator's name as SSMS prints it: the physical operator, with the
+ * logical one it implements when that says something the first does not.
+ */
+function toOperatorName(relop: Element, operator: Element | undefined): string {
+ const physical = relop.getAttribute("PhysicalOp") ?? "Unknown";
+ const logical = relop.getAttribute("LogicalOp");
+ if (operator?.localName === "IndexScan") {
+ if (operator.getAttribute("Storage") === "ColumnStore") {
+ return "Columnstore Index Scan";
+ }
+ // SQL Server reports a lookup into the clustered index as a seek.
+ if (isTrue(operator.getAttribute("Lookup"))) {
+ return physical === "Clustered Index Seek" ? "Key Lookup" : physical;
+ }
+ }
+ if (!logical || physical.includes(logical) || logical.includes(physical)) {
+ return logical && logical.length > physical.length ? logical : physical;
+ }
+ return `${physical} (${logical})`;
+}
+
+/** What the operator works on, for the one line a card has room for. */
+function toOperatorSubject(operator: Element | undefined): string | undefined {
+ const object = firstChild(operator, "Object");
+ if (object) {
+ return ["Table", "Index"]
+ .map((part) => object.getAttribute(part))
+ .filter((part): part is string => Boolean(part))
+ .map(unbracket)
+ .join(".");
+ }
+ const hashBuild = columnList(firstChild(operator, "HashKeysBuild"));
+ const hashProbe = columnList(firstChild(operator, "HashKeysProbe"));
+ if (hashBuild.length > 0 && hashProbe.length > 0) {
+ return pairColumns(hashBuild, hashProbe);
+ }
+ const mergeOuter = columnList(firstChild(operator, "OuterSideJoinColumns"));
+ const mergeInner = columnList(firstChild(operator, "InnerSideJoinColumns"));
+ if (mergeOuter.length > 0 && mergeInner.length > 0) {
+ return pairColumns(mergeOuter, mergeInner);
+ }
+ const groupBy = [
+ ...hashBuild,
+ ...columnList(firstChild(operator, "GroupBy")),
+ ];
+ if (groupBy.length > 0) return groupBy.join(", ");
+ const orderBy = firstChild(operator, "OrderBy");
+ if (orderBy) return formatOrderBy(orderBy);
+ const [predicate] = scalarStrings(firstChild(operator, "Predicate"));
+ return predicate;
+}
+
+function toOperatorProperties(
+ relop: Element,
+ operator: Element | undefined
+): PlanProperty[] {
+ const properties: PlanProperty[] = [];
+ const operatorChildren = childElements(operator).filter(
+ (child) => child.localName !== "RelOp"
+ );
+ const leading = LEADING_OPERATOR_ELEMENTS.flatMap((name) =>
+ operatorChildren.filter((child) => child.localName === name)
+ );
+ const rest = operatorChildren.filter((child) => !leading.includes(child));
+ for (const child of [...leading, ...rest]) {
+ addPlanProperty(
+ properties,
+ humanize(child.localName),
+ formatOperatorElement(child)
+ );
+ if (child.localName === "Object") {
+ addPlanProperty(
+ properties,
+ "Index Kind",
+ child.getAttribute("IndexKind") ?? ""
+ );
+ }
+ }
+ addPlanProperty(
+ properties,
+ "Output List",
+ columnList(firstChild(relop, "OutputList")).join(", ")
+ );
+
+ // The first run plus every rerun. Row estimates are per run, so an operator
+ // that reruns — the inner side of a nested loop — returns this many times
+ // its estimate.
+ const reruns =
+ (numberAttribute(relop, "EstimateRebinds") ?? 0) +
+ (numberAttribute(relop, "EstimateRewinds") ?? 0);
+ if (reruns > 0) {
+ addPlanProperty(
+ properties,
+ "Estimated Executions",
+ formatPlanCost(1 + reruns)
+ );
+ }
+ addAttributes(properties, relop, PROMOTED_RELOP_ATTRIBUTES);
+ addAttributes(properties, operator);
+ return properties;
+}
+
+function toOperatorWarnings(
+ relop: Element,
+ operator: Element | undefined,
+ physical: string
+): PlanWarning[] {
+ const warnings = toServerWarnings(firstChild(relop, "Warnings"));
+ const rowsRead =
+ numberAttribute(relop, "EstimatedRowsRead") ??
+ numberAttribute(relop, "TableCardinality") ??
+ 0;
+ if (
+ FULL_TABLE_SCAN_OPERATORS.has(physical) &&
+ operator?.getAttribute("Storage") !== "ColumnStore" &&
+ rowsRead > FULL_SCAN_ROWS_THRESHOLD
+ ) {
+ warnings.push(PLAN_FULL_TABLE_SCAN);
+ }
+ return warnings;
+}
+
+function toOperatorNode(
+ { element: relop, relationship }: PlanChild,
+ id: string,
+ depth: number
+): PlanNode {
+ const operator = operatorElement(relop);
+ const children = operator ? toChildren(operator, id, depth) : [];
+ const totalCost = numberAttribute(relop, "EstimatedTotalSubtreeCost");
+ return {
+ id,
+ nodeType: toOperatorName(relop, operator),
+ subject: toOperatorSubject(operator),
+ relationship,
+ totalCost,
+ selfCost: planSelfCost(totalCost, children),
+ rows: numberAttribute(relop, "EstimateRows"),
+ width: numberAttribute(relop, "AvgRowSize"),
+ properties: toOperatorProperties(relop, operator),
+ warnings: toOperatorWarnings(
+ relop,
+ operator,
+ relop.getAttribute("PhysicalOp") ?? ""
+ ),
+ children,
+ };
+}
+
+function toRoot(statements: Element[]): PlanNode {
+ if (statements.length === 1) {
+ return toNode({ element: statements[0] }, "0", 0);
+ }
+ const children = statements.map((element, index) =>
+ toNode({ element }, `0.${index}`, 1)
+ );
+ const totalCost = children.some((child) => child.totalCost !== undefined)
+ ? children.reduce((sum, child) => sum + (child.totalCost ?? 0), 0)
+ : undefined;
+ return {
+ id: "0",
+ nodeType: "Batch",
+ subject: `${children.length} statements`,
+ totalCost,
+ selfCost: planSelfCost(totalCost, children),
+ properties: [],
+ warnings: [],
+ children,
+ };
+}
+
+export function parseMssqlPlan(source: string): PlanParseResult {
+ const trimmed = source.trim();
+ if (!trimmed) {
+ return { ok: false, message: MSSQL_PLAN_EMPTY_MESSAGE };
+ }
+
+ const document = new DOMParser().parseFromString(trimmed, "application/xml");
+ if (document.getElementsByTagName("parsererror").length > 0) {
+ return { ok: false, message: MSSQL_PLAN_INVALID_XML_MESSAGE };
+ }
+
+ const root = document.documentElement;
+ // A batch can split its statements across several `<Statements>`, one
+ // each, as SQL Server 2016 writes them.
+ const statements =
+ root.localName === "ShowPlanXML"
+ ? childElements(firstChild(root, "BatchSequence"), "Batch")
+ .flatMap((batch) => childElements(batch, "Statements"))
+ .flatMap((block) =>
+ childElements(block).filter((element) =>
+ STATEMENT_ELEMENTS.has(element.localName)
+ )
+ )
+ : [];
+ if (statements.length === 0) {
+ return { ok: false, message: MSSQL_PLAN_NO_PLAN_MESSAGE };
+ }
+
+ return parseWithDepthLimit(() => toRoot(statements));
+}
diff --git a/frontend/src/apps/explain-visualizer/plan-layout.test.ts b/frontend/src/apps/explain-visualizer/plan-layout.test.ts
index a21737dcaf..970a35c468 100644
--- a/frontend/src/apps/explain-visualizer/plan-layout.test.ts
+++ b/frontend/src/apps/explain-visualizer/plan-layout.test.ts
@@ -1,20 +1,26 @@
import { describe, expect, test } from "vitest";
import {
layoutPlan,
+ PLAN_IDENTITY_VIEWPORT,
+ PLAN_MIN_SCALE,
PLAN_NODE_HEIGHT,
PLAN_NODE_WIDTH,
+ PLAN_READABLE_SCALE,
planFitsViewport,
+ planFitViewport,
planGuideLevels,
planIndentPixels,
planMiniMap,
planNodeCenter,
planNodeOnScreen,
+ planOpeningViewport,
+ planShowsMiniMap,
planViewportCenteredOn,
} from "./plan-layout";
import type { PlanNode, PlanTree } from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
-import hashJoinAggregateSort from "./test-data/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/seq-scan-filter.json";
+import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
+import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
const parseFixture = (fixture: unknown): PlanTree => {
const result = parsePostgresPlan(JSON.stringify(fixture));
@@ -254,6 +260,141 @@ describe("planFitsViewport", () => {
});
});
+/** A node with nothing but its place in the tree, which is all a layout reads. */
+const bare = (id: string, children: PlanNode[] = []): PlanNode => ({
+ id,
+ nodeType: "Scan",
+ properties: [],
+ warnings: [],
+ children,
+});
+
+const leaves = (parent: string, count: number) =>
+ Array.from({ length: count }, (_, index) => bare(`${parent}.${index}`));
+
+describe("planFitViewport", () => {
+ test("centers the whole plan at the largest scale that shows it", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ const size = { width: layout.width, height: layout.height / 2 };
+ const view = planFitViewport(layout, size);
+
+ expect(view.scale).toBeCloseTo(0.5, 6);
+ expect(view.x).toBeCloseTo(layout.width / 4, 6);
+ expect(view.y).toBeCloseTo(0, 6);
+ expect(planFitsViewport(layout, size, view)).toBe(true);
+ });
+
+ test("never blows a small plan up past its own size", () => {
+ const layout = layoutPlan(parseFixture(seqScanFilter).root);
+ expect(planFitViewport(layout, { width: 4000, height: 4000 }).scale).toBe(
+ 1
+ );
+ });
+
+ test("stops shrinking at the diagram's furthest zoom", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ expect(planFitViewport(layout, { width: 10, height: 10 }).scale).toBe(
+ PLAN_MIN_SCALE
+ );
+ });
+
+ test("leaves an unmeasured viewport alone", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ expect(planFitViewport(layout, { width: 0, height: 0 })).toBe(
+ PLAN_IDENTITY_VIEWPORT
+ );
+ });
+});
+
+describe("planOpeningViewport", () => {
+ test("shows a plan whole when its cards are readable that way", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ const size = { width: layout.width * 0.9, height: layout.height * 0.9 };
+
+ expect(planOpeningViewport(layout, size)).toEqual(
+ planFitViewport(layout, size)
+ );
+ });
+
+ test("opens a plan too deep to read whole at a readable scale, from the root down", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ const size = { width: 800, height: 300 };
+ const view = planOpeningViewport(layout, size);
+
+ expect(planFitViewport(layout, size).scale).toBeLessThan(
+ PLAN_READABLE_SCALE
+ );
+ expect(view.scale).toBe(PLAN_READABLE_SCALE);
+ // The top of the plan at the top of the screen, and the plan, narrow
+ // enough at this scale, centered across it.
+ expect(view.y).toBe(0);
+ expect(view.x).toBeCloseTo(
+ (size.width - layout.width * PLAN_READABLE_SCALE) / 2,
+ 6
+ );
+ expect(planFitsViewport(layout, size, view)).toBe(false);
+ });
+
+ test("centers the root across a plan wider than the screen", () => {
+ const layout = layoutPlan(bare("0", leaves("0", 12)));
+ const size = { width: 600, height: 400 };
+ const view = planOpeningViewport(layout, size);
+ const [root] = layout.nodes;
+
+ expect(view.scale).toBe(PLAN_READABLE_SCALE);
+ expect(view.x + planNodeCenter(root).x * view.scale).toBeCloseTo(300, 6);
+ });
+
+ test("keeps the plan's edge at the screen's edge rather than centering past it", () => {
+ // The wide first child pulls the root right of the plan's middle.
+ const layout = layoutPlan(
+ bare("0", [bare("0.0", leaves("0.0", 10)), bare("0.1")])
+ );
+ const [root] = layout.nodes;
+ const width = layout.width * PLAN_READABLE_SCALE;
+ const size = { width: width - 100, height: 400 };
+ const view = planOpeningViewport(layout, size);
+
+ expect(planNodeCenter(root).x).toBeGreaterThan(layout.width / 2);
+ expect(view.scale).toBe(PLAN_READABLE_SCALE);
+ expect(view.x + width).toBeCloseTo(size.width, 6);
+ });
+
+ test("leaves an unmeasured viewport alone", () => {
+ const layout = layoutPlan(parseFixture(hashJoinAggregateSort).root);
+ expect(planOpeningViewport(layout, { width: 0, height: 0 })).toBe(
+ PLAN_IDENTITY_VIEWPORT
+ );
+ });
+});
+
+describe("planShowsMiniMap", () => {
+ const BOX = { width: 160, height: 112 };
+ const layout = () => layoutPlan(parseFixture(hashJoinAggregateSort).root);
+
+ test("offers one only while part of the plan is off screen", () => {
+ const plan = layout();
+ const roomy = { width: 1200, height: 900 };
+
+ expect(planShowsMiniMap(plan, roomy, VIEW, BOX)).toBe(false);
+ expect(planShowsMiniMap(plan, roomy, { ...VIEW, scale: 2 }, BOX)).toBe(
+ true
+ );
+ });
+
+ test("leaves it out of a viewport it would cover too much of", () => {
+ const plan = layout();
+ const zoomed = { ...VIEW, scale: 2 };
+
+ expect(
+ planShowsMiniMap(plan, { width: 400, height: 900 }, zoomed, BOX)
+ ).toBe(false);
+ expect(
+ planShowsMiniMap(plan, { width: 1200, height: 300 }, zoomed, BOX)
+ ).toBe(false);
+ });
+});
+
describe("planNodeOnScreen", () => {
const placed = { node: {} as PlanNode, x: 300, y: 200 };
const size = { width: 400, height: 300 };
diff --git a/frontend/src/apps/explain-visualizer/plan-layout.ts b/frontend/src/apps/explain-visualizer/plan-layout.ts
index 440c33da3b..ae2a232d77 100644
--- a/frontend/src/apps/explain-visualizer/plan-layout.ts
+++ b/frontend/src/apps/explain-visualizer/plan-layout.ts
@@ -66,6 +66,7 @@ export interface PlanLayoutEdge {
}
export interface PlanLayout {
+ /** Every card on the canvas, root first. */
readonly nodes: readonly PlanLayoutNode[];
readonly edges: readonly PlanLayoutEdge[];
readonly width: number;
@@ -149,6 +150,70 @@ export interface PlanViewportSize {
readonly height: number;
}
+export const PLAN_IDENTITY_VIEWPORT: PlanViewport = { scale: 1, x: 0, y: 0 };
+
+/** The furthest out and in the diagram zooms. */
+export const PLAN_MIN_SCALE = 0.2;
+export const PLAN_MAX_SCALE = 2;
+
+/**
+ * Smallest scale the diagram opens a plan at, where a card's 12px secondary
+ * text still renders at about ten pixels. Further out, the diagram shows the
+ * plan's shape with nothing in it to read.
+ */
+export const PLAN_READABLE_SCALE = 0.8;
+
+/**
+ * The whole plan, centered, at the largest scale that shows all of it. A plan
+ * is never enlarged past its own size nor shrunk past the diagram's furthest
+ * zoom, and an unmeasured viewport — jsdom's, or one not laid out yet — gets
+ * the identity, since there is nothing to fit to.
+ */
+export function planFitViewport(
+ layout: PlanLayout,
+ size: PlanViewportSize
+): PlanViewport {
+ if (size.width <= 0 || size.height <= 0) return PLAN_IDENTITY_VIEWPORT;
+ const scale = minmax(
+ Math.min(size.width / layout.width, size.height / layout.height),
+ PLAN_MIN_SCALE,
+ 1
+ );
+ return {
+ scale,
+ x: (size.width - layout.width * scale) / 2,
+ y: (size.height - layout.height * scale) / 2,
+ };
+}
+
+/**
+ * The view the diagram opens on: the whole plan when its cards are readable at
+ * the scale that shows all of it, and otherwise the readable scale from the
+ * root down, centered on the root as far as the plan's edges allow. The
+ * mini-map then offers the rest.
+ */
+export function planOpeningViewport(
+ layout: PlanLayout,
+ size: PlanViewportSize
+): PlanViewport {
+ const fit = planFitViewport(layout, size);
+ if (size.width <= 0 || size.height <= 0) return fit;
+ if (fit.scale >= PLAN_READABLE_SCALE) return fit;
+ const scale = PLAN_READABLE_SCALE;
+ const width = layout.width * scale;
+ const height = layout.height * scale;
+ const [root] = layout.nodes;
+ const rootX = root ? planNodeCenter(root).x * scale : width / 2;
+ return {
+ scale,
+ x:
+ width <= size.width
+ ? (size.width - width) / 2
+ : minmax(size.width / 2 - rootX, size.width - width, 0),
+ y: height <= size.height ? (size.height - height) / 2 : 0,
+ };
+}
+
export interface PlanRect {
readonly x: number;
readonly y: number;
@@ -204,6 +269,30 @@ export function planFitsViewport(
);
}
+/**
+ * How many times the mini-map's box the viewport has to be, across and down,
+ * before the diagram offers it. In anything smaller — a phone's stacked pane —
+ * the overview would cover the plan it is an overview of.
+ */
+const MINI_MAP_ROOM = 3;
+
+/**
+ * Whether the diagram offers a mini-map: only while part of the plan is off
+ * screen, and only in a viewport with room for one.
+ */
+export function planShowsMiniMap(
+ layout: PlanLayout,
+ size: PlanViewportSize,
+ view: PlanViewport,
+ box: PlanViewportSize
+): boolean {
+ return (
+ !planFitsViewport(layout, size, view) &&
+ size.width >= box.width * MINI_MAP_ROOM &&
+ size.height >= box.height * MINI_MAP_ROOM
+ );
+}
+
/**
* Whether a card is fully on screen at the current pan and zoom. An unmeasured
* viewport counts as showing everything, so nothing moves before the first
diff --git a/frontend/src/apps/explain-visualizer/plan-model.test.ts b/frontend/src/apps/explain-visualizer/plan-model.test.ts
index 31f988c0d0..0e9c19a63e 100644
--- a/frontend/src/apps/explain-visualizer/plan-model.test.ts
+++ b/frontend/src/apps/explain-visualizer/plan-model.test.ts
@@ -1,16 +1,21 @@
import { describe, expect, test } from "vitest";
import {
+ addPlanProperty,
buildPlanTree,
+ checkPlanDepth,
findPlanNode,
flattenPlan,
formatPlanCost,
formatPlanCount,
formatPlanShare,
- isFlaggedFullScan,
+ isJsonRecord,
PLAN_EDGE_MAX_WIDTH,
PLAN_EDGE_MIN_WIDTH,
+ PLAN_TOO_DEEP_MESSAGE,
type PlanNode,
+ type PlanProperty,
type PlanTree,
+ parseWithDepthLimit,
planCollapsedAncestor,
planCostByOperation,
planCostliestNodes,
@@ -21,13 +26,14 @@ import {
planNodeIdFromFragment,
planRevealNode,
planRows,
+ planSelfCost,
planSelfCostShare,
planTimeline,
} from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
-import cteNestedLoopInitplan from "./test-data/cte-nested-loop-initplan.json";
-import hashJoinAggregateSort from "./test-data/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/seq-scan-filter.json";
+import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
+import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
+import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
const parseFixture = (fixture: unknown): PlanTree => {
const result = parsePostgresPlan(JSON.stringify(fixture));
@@ -48,10 +54,20 @@ const node = (
rows: 0,
width: 0,
properties: [],
+ warnings: [],
children,
...overrides,
});
+/** A node the way an engine that reports no estimates describes one. */
+const bareNode = (id: string, children: PlanNode[] = []): PlanNode => ({
+ id,
+ nodeType: "Scan",
+ properties: [],
+ warnings: [],
+ children,
+});
+
const sampleTree = () =>
buildPlanTree(
node("0", { selfCost: 10, rows: 100 }, [
@@ -81,6 +97,132 @@ describe("buildPlanTree", () => {
expect(tree.maxSelfCost).toBe(40);
expect(tree.maxRows).toBe(900);
});
+
+ test("says which estimates the plan carries", () => {
+ expect(sampleTree().estimates).toEqual({
+ cost: true,
+ startupCost: true,
+ rows: true,
+ width: true,
+ });
+ expect(buildPlanTree(bareNode("0", [bareNode("0.0")])).estimates).toEqual({
+ cost: false,
+ startupCost: false,
+ rows: false,
+ width: false,
+ });
+ // One node reporting an estimate is enough for the plan to carry it.
+ const mixed = buildPlanTree(
+ bareNode("0", [{ ...bareNode("0.0"), rows: 5 }])
+ );
+ expect(mixed.estimates).toEqual({
+ cost: false,
+ startupCost: false,
+ rows: true,
+ width: false,
+ });
+ expect(mixed.maxRows).toBe(5);
+ });
+
+ test("ranks and bases nothing on a plan without estimates", () => {
+ const tree = buildPlanTree(bareNode("0", [bareNode("0.0")]));
+
+ expect(tree.maxSelfCost).toBe(0);
+ expect(tree.maxRows).toBe(0);
+ expect(tree.costBasis).toBe(0);
+ for (const entry of tree.nodes) {
+ expect(planSelfCostShare(entry, tree)).toBe(0);
+ expect(planHighlightIntensity(entry, tree, "cost")).toBe(0);
+ expect(planHighlightIntensity(entry, tree, "rows")).toBe(0);
+ }
+ expect(planCostliestNodes(tree)).toEqual([]);
+ });
+});
+
+describe("parseWithDepthLimit", () => {
+ test("builds the tree a parser returns", () => {
+ const result = parseWithDepthLimit(() => bareNode("0", [bareNode("0.0")]));
+ expect(result.ok && result.tree.nodes.map((entry) => entry.id)).toEqual([
+ "0",
+ "0.0",
+ ]);
+ });
+
+ test("turns a build that went too deep into the depth message", () => {
+ const chain = (depth: number): PlanNode => {
+ checkPlanDepth(depth);
+ return bareNode(String(depth), [chain(depth + 1)]);
+ };
+ expect(parseWithDepthLimit(() => chain(0))).toEqual({
+ ok: false,
+ message: PLAN_TOO_DEEP_MESSAGE,
+ });
+ });
+
+ test("lets any other error through", () => {
+ expect(() =>
+ parseWithDepthLimit(() => {
+ throw new Error("boom");
+ })
+ ).toThrow("boom");
+ });
+});
+
+describe("isJsonRecord", () => {
+ test("is true only for a plain object", () => {
+ expect(isJsonRecord({ Plan: {} })).toBe(true);
+ expect(isJsonRecord([])).toBe(false);
+ expect(isJsonRecord(null)).toBe(false);
+ expect(isJsonRecord("Plan")).toBe(false);
+ });
+});
+
+describe("addPlanProperty", () => {
+ test("appends a new label and folds a repeated one onto its own line", () => {
+ const properties: PlanProperty[] = [];
+ addPlanProperty(properties, "Agg", "COUNT() AS $v1");
+ addPlanProperty(properties, "Condition", "($a = $b)");
+ addPlanProperty(properties, "Agg", "ANY() AS $v2");
+
+ expect(properties).toEqual([
+ { label: "Agg", value: "COUNT() AS $v1\nANY() AS $v2" },
+ { label: "Condition", value: "($a = $b)" },
+ ]);
+ });
+
+ test("skips an empty value and a value the label already holds", () => {
+ const properties: PlanProperty[] = [];
+ addPlanProperty(properties, "Storage", "RowStore");
+ addPlanProperty(properties, "Storage", "RowStore");
+ addPlanProperty(properties, "Predicate", "");
+
+ expect(properties).toEqual([{ label: "Storage", value: "RowStore" }]);
+ });
+});
+
+describe("planSelfCost", () => {
+ test("subtracts the children's total cost from the node's", () => {
+ expect(
+ planSelfCost(100, [
+ node("0.0", { totalCost: 30 }),
+ node("0.1", { totalCost: 45 }),
+ ])
+ ).toBe(25);
+ });
+
+ test("clamps at zero when the children report more than the node", () => {
+ expect(planSelfCost(10, [node("0.0", { totalCost: 40 })])).toBe(0);
+ });
+
+ test("counts a child without a cost as costing nothing", () => {
+ expect(planSelfCost(10, [bareNode("0.0")])).toBe(10);
+ });
+
+ test("has no self cost for a node without a total cost", () => {
+ expect(planSelfCost(undefined, [node("0.0", { totalCost: 5 })])).toBe(
+ undefined
+ );
+ });
});
describe("findPlanNode", () => {
@@ -140,6 +282,23 @@ describe("number formatting", () => {
expect(formatPlanCount(50000)).toBe("50,000");
});
+ test("keeps a fractional row estimate from rounding to a whole row", () => {
+ expect(formatPlanCount(1.56767)).toBe("1.57");
+ expect(formatPlanCount(16660.5)).toBe("16,660.5");
+ });
+
+ test("keeps a fractional cost's leading digits rather than rounding it away", () => {
+ expect(formatPlanCost(0.68)).toBe("0.68");
+ expect(formatPlanCost(0.0325135)).toBe("0.0325");
+ expect(formatPlanCost(0.0000418)).toBe("0.0000418");
+ expect(formatPlanCost(1.60801)).toBe("1.61");
+ });
+
+ test("prints a dash for an estimate the engine did not report", () => {
+ expect(formatPlanCost(undefined)).toBe("—");
+ expect(formatPlanCount(undefined)).toBe("—");
+ });
+
test("keeps a share that rounds to nothing from reading as nothing", () => {
expect(formatPlanShare(0)).toBe("0%");
expect(formatPlanShare(1)).toBe("100%");
@@ -282,10 +441,13 @@ describe("plan node fragments", () => {
describe("costBasis", () => {
test("is the root's total cost, which the self costs add back up to", () => {
const tree = parseFixture(hashJoinAggregateSort);
- const selfTotal = tree.nodes.reduce((sum, node) => sum + node.selfCost, 0);
+ const selfTotal = tree.nodes.reduce(
+ (sum, node) => sum + (node.selfCost ?? 0),
+ 0
+ );
expect(tree.costBasis).toBeCloseTo(1465.93, 5);
- expect(selfTotal).toBeCloseTo(tree.root.totalCost, 5);
+ expect(selfTotal).toBeCloseTo(tree.root.totalCost ?? Number.NaN, 5);
});
test("covers the self costs a Limit truncates out of the root's total", () => {
@@ -347,6 +509,7 @@ describe("planEdgeWidth", () => {
const rowless = buildPlanTree(node("0"));
expect(planEdgeWidth(0, tree)).toBe(PLAN_EDGE_MIN_WIDTH);
+ expect(planEdgeWidth(undefined, tree)).toBe(PLAN_EDGE_MIN_WIDTH);
expect(planEdgeWidth(10, rowless)).toBe(PLAN_EDGE_MIN_WIDTH);
});
@@ -356,31 +519,6 @@ describe("planEdgeWidth", () => {
});
});
-describe("isFlaggedFullScan", () => {
- test("flags a sequential scan of a relation large enough to matter", () => {
- const tree = parseFixture(hashJoinAggregateSort);
- const flagged = tree.nodes.filter(isFlaggedFullScan);
-
- // `orders` at 819 is flagged; `customers` at 78 is a tiny relation.
- expect(flagged.map((entry) => entry.subject)).toEqual(["orders"]);
- });
-
- test("leaves a scan of a tiny relation alone", () => {
- const tree = parseFixture(seqScanFilter);
- expect(tree.root.totalCost).toBe(90.5);
- expect(isFlaggedFullScan(tree.root)).toBe(false);
- });
-
- test("flags the parallel variant and no other scan type", () => {
- const scan = (nodeType: string) => node("0", { nodeType, totalCost: 5000 });
-
- expect(isFlaggedFullScan(scan("Seq Scan"))).toBe(true);
- expect(isFlaggedFullScan(scan("Parallel Seq Scan"))).toBe(true);
- expect(isFlaggedFullScan(scan("Index Scan"))).toBe(false);
- expect(isFlaggedFullScan(scan("Bitmap Heap Scan"))).toBe(false);
- });
-});
-
describe("planTimeline", () => {
test("spans each node from its startup cost to its total cost", () => {
const tree = parseFixture(hashJoinAggregateSort);
diff --git a/frontend/src/apps/explain-visualizer/plan-model.ts b/frontend/src/apps/explain-visualizer/plan-model.ts
index 531bb354c8..7986b3dcd9 100644
--- a/frontend/src/apps/explain-visualizer/plan-model.ts
+++ b/frontend/src/apps/explain-visualizer/plan-model.ts
@@ -4,8 +4,10 @@
* Engine adapters map their own EXPLAIN output onto this model and the viewer
* components read nothing else, so adding an engine means adding a parser.
*
- * Bytebase runs EXPLAIN without ANALYZE, so every number here is a planner
+ * Bytebase plans without executing, so every number here is an optimizer
* estimate: there is no actual timing, loop, buffer, or worker data to model.
+ * Engines differ in which estimates they report at all, so each one is
+ * optional and a surface shows only what the plan carries.
*/
/** One free-form attribute the engine reported for a node. */
@@ -14,6 +16,12 @@ export interface PlanProperty {
readonly value: string;
}
+/** Something about a node worth a reader's attention, and what it means. */
+export interface PlanWarning {
+ readonly title: string;
+ readonly detail: string;
+}
+
export interface PlanNode {
/** Unique within one tree; derived from the node's path from the root. */
readonly id: string;
@@ -23,20 +31,34 @@ export interface PlanNode {
readonly subject?: string;
/** How the parent consumes this node, such as "Inner" or "InitPlan 1". */
readonly relationship?: string;
- readonly startupCost: number;
- readonly totalCost: number;
- /** Total cost minus the children's total cost, clamped at zero. */
- readonly selfCost: number;
- readonly rows: number;
- readonly width: number;
+ /** Cost before the node returns its first row, including its subtree. */
+ readonly startupCost?: number;
+ /** Cost of returning every row, including the node's subtree. */
+ readonly totalCost?: number;
+ /** What the node adds on top of its children; see `planSelfCost`. */
+ readonly selfCost?: number;
+ /** Rows the node is estimated to return each time it runs. */
+ readonly rows?: number;
+ /** Estimated size of one returned row, in bytes. */
+ readonly width?: number;
readonly properties: readonly PlanProperty[];
+ readonly warnings: readonly PlanWarning[];
readonly children: readonly PlanNode[];
}
+/** Which estimates appear anywhere in a plan. */
+export interface PlanEstimates {
+ readonly cost: boolean;
+ readonly startupCost: boolean;
+ readonly rows: boolean;
+ readonly width: boolean;
+}
+
export interface PlanTree {
readonly root: PlanNode;
/** Every node in depth-first order, root first. */
readonly nodes: readonly PlanNode[];
+ readonly estimates: PlanEstimates;
readonly maxSelfCost: number;
readonly maxRows: number;
/**
@@ -57,6 +79,95 @@ export type PlanParseResult =
| { readonly ok: true; readonly tree: PlanTree }
| { readonly ok: false; readonly message: string };
+/**
+ * Deepest plan a parser will build.
+ *
+ * The parsers and the walks over their result (`flattenPlan`, `planRows`,
+ * `planPath`) recurse once per level, so a pathological nesting depth
+ * overflows the stack. Without a cap that happens during render, where there
+ * is no error boundary to catch it and React unmounts the page instead of
+ * showing the parse error. The cap is an order of magnitude below the depth
+ * any of those walks fails at, and far above any plan an optimizer produces.
+ */
+const PLAN_MAX_DEPTH = 500;
+
+export const PLAN_TOO_DEEP_MESSAGE = `The query plan nests more than ${PLAN_MAX_DEPTH} levels deep, which is deeper than this visualizer can draw.`;
+
+/** Raised by `checkPlanDepth` and caught by `parseWithDepthLimit` alone. */
+const PLAN_TOO_DEEP = new Error(PLAN_TOO_DEEP_MESSAGE);
+
+/** Called by a parser for each level it builds; past the cap it stops the build. */
+export function checkPlanDepth(depth: number) {
+ if (depth > PLAN_MAX_DEPTH) throw PLAN_TOO_DEEP;
+}
+
+/** A parser's tree from `build`, or the depth message when it went too deep. */
+export function parseWithDepthLimit(build: () => PlanNode): PlanParseResult {
+ try {
+ return { ok: true, tree: buildPlanTree(build()) };
+ } catch (error) {
+ if (error !== PLAN_TOO_DEEP) throw error;
+ return { ok: false, message: PLAN_TOO_DEEP_MESSAGE };
+ }
+}
+
+export type JsonRecord = Record<string, unknown>;
+
+export function isJsonRecord(value: unknown): value is JsonRecord {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * Appends a property, folding a value under a label already present into that
+ * property on a line of its own, since an engine can report one label twice.
+ */
+export function addPlanProperty(
+ properties: PlanProperty[],
+ label: string,
+ value: string
+) {
+ if (!value) return;
+ const index = properties.findIndex((property) => property.label === label);
+ if (index < 0) {
+ properties.push({ label, value });
+ } else if (!properties[index].value.split("\n").includes(value)) {
+ properties[index] = {
+ label,
+ value: `${properties[index].value}\n${value}`,
+ };
+ }
+}
+
+/**
+ * A node's total cost minus its children's, clamped at zero, or undefined when
+ * the node has no total cost. `PlanTree.costBasis` says when the clamp bites.
+ */
+export function planSelfCost(
+ totalCost: number | undefined,
+ children: readonly PlanNode[]
+): number | undefined {
+ if (totalCost === undefined) return undefined;
+ const childCost = children.reduce(
+ (sum, child) => sum + (child.totalCost ?? 0),
+ 0
+ );
+ return Math.max(0, totalCost - childCost);
+}
+
+/** Warning for a read of a whole table, attached by each engine's parser. */
+export const PLAN_FULL_TABLE_SCAN: PlanWarning = {
+ title: "Full table scan",
+ detail:
+ "Reads every row of this table. If the query needs only a few of them, an index on the filtered columns could avoid the full read.",
+};
+
+/** Warning for a read of a whole index, attached by each engine's parser. */
+export const PLAN_FULL_INDEX_SCAN: PlanWarning = {
+ title: "Full index scan",
+ detail:
+ "Reads every entry of this index. If the query needs only a few of them, a condition on the index's leading columns could avoid the full read.",
+};
+
/** Which estimate, if any, shades the diagram's node cards. */
export type PlanHighlightMode = "off" | "cost" | "rows";
@@ -75,17 +186,30 @@ export function buildPlanTree(root: PlanNode): PlanTree {
let maxSelfCost = 0;
let maxRows = 0;
let selfCostTotal = 0;
+ const estimates = {
+ cost: false,
+ startupCost: false,
+ rows: false,
+ width: false,
+ };
for (const node of nodes) {
- if (node.selfCost > maxSelfCost) maxSelfCost = node.selfCost;
- if (node.rows > maxRows) maxRows = node.rows;
- selfCostTotal += node.selfCost;
+ const selfCost = node.selfCost ?? 0;
+ const rows = node.rows ?? 0;
+ if (selfCost > maxSelfCost) maxSelfCost = selfCost;
+ if (rows > maxRows) maxRows = rows;
+ selfCostTotal += selfCost;
+ estimates.cost ||= node.totalCost !== undefined;
+ estimates.startupCost ||= node.startupCost !== undefined;
+ estimates.rows ||= node.rows !== undefined;
+ estimates.width ||= node.width !== undefined;
}
return {
root,
nodes,
+ estimates,
maxSelfCost,
maxRows,
- costBasis: Math.max(root.totalCost, selfCostTotal),
+ costBasis: Math.max(root.totalCost ?? 0, selfCostTotal),
};
}
@@ -224,16 +348,28 @@ export function planNodeIdFromFragment(
const costFormat = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 2,
});
+// SQL Server's cost units are small enough that a whole plan often costs less
+// than one, where two decimal places would print most operators as zero.
+const fractionalCostFormat = new Intl.NumberFormat("en-US", {
+ maximumSignificantDigits: 3,
+});
+// SQL Server estimates rows as fractions, and 1.57 rows is not 2.
const countFormat = new Intl.NumberFormat("en-US", {
- maximumFractionDigits: 0,
+ maximumFractionDigits: 2,
});
-export function formatPlanCost(value: number): string {
- return costFormat.format(value);
+/** What a surface prints for an estimate the engine did not report. */
+const PLAN_NO_ESTIMATE = "—";
+
+export function formatPlanCost(value: number | undefined): string {
+ if (value === undefined) return PLAN_NO_ESTIMATE;
+ return Math.abs(value) < 1
+ ? fractionalCostFormat.format(value)
+ : costFormat.format(value);
}
-export function formatPlanCount(value: number): string {
- return countFormat.format(value);
+export function formatPlanCount(value: number | undefined): string {
+ return value === undefined ? PLAN_NO_ESTIMATE : countFormat.format(value);
}
const shareFormat = new Intl.NumberFormat("en-US", {
@@ -256,7 +392,7 @@ export function formatPlanShare(value: number): string {
*/
export function planSelfCostShare(node: PlanNode, tree: PlanTree): number {
if (tree.costBasis <= 0) return 0;
- return Math.min(1, Math.max(0, node.selfCost / tree.costBasis));
+ return Math.min(1, Math.max(0, (node.selfCost ?? 0) / tree.costBasis));
}
/** Narrowest and widest stroke a diagram edge is drawn with, in pixels. */
@@ -270,8 +406,13 @@ export const PLAN_EDGE_MAX_WIDTH = 6;
* scale is logarithmic; a linear one would draw everything but the largest
* edge as the same hairline.
*/
-export function planEdgeWidth(rows: number, tree: PlanTree): number {
- if (tree.maxRows <= 0 || rows <= 0) return PLAN_EDGE_MIN_WIDTH;
+export function planEdgeWidth(
+ rows: number | undefined,
+ tree: PlanTree
+): number {
+ if (tree.maxRows <= 0 || rows === undefined || rows <= 0) {
+ return PLAN_EDGE_MIN_WIDTH;
+ }
const ratio =
Math.log1p(Math.min(rows, tree.maxRows)) / Math.log1p(tree.maxRows);
const width =
@@ -279,34 +420,6 @@ export function planEdgeWidth(rows: number, tree: PlanTree): number {
return Math.round(width * 100) / 100;
}
-/**
- * Node types that read a whole relation, spelled as `toNodeType` names them.
- */
-const FULL_RELATION_SCAN_TYPES = new Set(["Seq Scan", "Parallel Seq Scan"]);
-
-/**
- * Total cost below which reading a whole relation is not worth flagging.
- *
- * Under PostgreSQL's default settings a sequential scan costs `seq_page_cost`
- * (1.0) per page plus `cpu_tuple_cost` (0.01) per row, so 100 cost units is
- * roughly a 50-page, 5,000-row relation — about 400 KB. Reading all of that is
- * a handful of page fetches that no index lookup would beat, and flagging it
- * would bury the scans a reader can act on.
- */
-export const PLAN_FULL_SCAN_COST_THRESHOLD = 100;
-
-/** What a flagged full scan means, shared by every surface that reports one. */
-export const PLAN_FULL_SCAN_HINT =
- "Reads every row of this relation. If the query needs only a few of them, an index on the filtered columns could avoid the full read.";
-
-/** Whether the node reads a whole relation large enough to be worth saying so. */
-export function isFlaggedFullScan(node: PlanNode): boolean {
- return (
- FULL_RELATION_SCAN_TYPES.has(node.nodeType) &&
- node.totalCost >= PLAN_FULL_SCAN_COST_THRESHOLD
- );
-}
-
export interface PlanTimelineRow extends PlanRow {
/** Where the node's first row is ready, as a fraction of the plan's cost. */
readonly start: number;
@@ -326,7 +439,7 @@ export interface PlanTimelineRow extends PlanRow {
* the other.
*/
export function planTimeline(tree: PlanTree): PlanTimelineRow[] {
- const fraction = (value: number) =>
+ const fraction = (value = 0) =>
tree.costBasis <= 0 ? 0 : Math.min(1, Math.max(0, value / tree.costBasis));
return planRows(tree.root).map((row) => {
const start = fraction(row.node.startupCost);
@@ -351,8 +464,8 @@ export function planCostliestNodes(
limit: number = PLAN_COSTLIEST_LIMIT
): PlanNode[] {
return tree.nodes
- .filter((node) => node.selfCost > 0)
- .sort((a, b) => b.selfCost - a.selfCost)
+ .filter((node) => (node.selfCost ?? 0) > 0)
+ .sort((a, b) => (b.selfCost ?? 0) - (a.selfCost ?? 0))
.slice(0, limit);
}
@@ -369,7 +482,7 @@ export function planCostByOperation(tree: PlanTree): PlanOperationCost[] {
for (const node of tree.nodes) {
const entry = totals.get(node.nodeType) ?? { count: 0, selfCost: 0 };
entry.count += 1;
- entry.selfCost += node.selfCost;
+ entry.selfCost += node.selfCost ?? 0;
totals.set(node.nodeType, entry);
}
return [...totals]
@@ -398,7 +511,7 @@ export function planHighlightIntensity(
mode: PlanHighlightMode
): number {
if (mode === "off") return 0;
- const value = mode === "cost" ? node.selfCost : node.rows;
+ const value = (mode === "cost" ? node.selfCost : node.rows) ?? 0;
const max = mode === "cost" ? tree.maxSelfCost : tree.maxRows;
if (max <= 0 || value <= 0) return 0;
return Math.sqrt(Math.min(value, max) / max);
diff --git a/frontend/src/apps/explain-visualizer/postgres-plan.test.ts b/frontend/src/apps/explain-visualizer/postgres-plan.test.ts
index 6cfc6c79c6..55a00e264d 100644
--- a/frontend/src/apps/explain-visualizer/postgres-plan.test.ts
+++ b/frontend/src/apps/explain-visualizer/postgres-plan.test.ts
@@ -1,16 +1,20 @@
import { describe, expect, test } from "vitest";
-import type { PlanNode, PlanTree } from "./plan-model";
+import {
+ PLAN_FULL_TABLE_SCAN,
+ PLAN_TOO_DEEP_MESSAGE,
+ type PlanNode,
+ type PlanTree,
+} from "./plan-model";
import {
POSTGRES_PLAN_EMPTY_MESSAGE,
POSTGRES_PLAN_INVALID_JSON_MESSAGE,
POSTGRES_PLAN_NO_PLAN_MESSAGE,
- POSTGRES_PLAN_TOO_DEEP_MESSAGE,
parsePostgresPlan,
} from "./postgres-plan";
-import bitmapIndexScan from "./test-data/bitmap-index-scan.json";
-import cteNestedLoopInitplan from "./test-data/cte-nested-loop-initplan.json";
-import hashJoinAggregateSort from "./test-data/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/seq-scan-filter.json";
+import bitmapIndexScan from "./test-data/postgres/bitmap-index-scan.json";
+import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
+import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
+import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
/** A chain of `depth` nodes, the shape that drives every recursive walk. */
const nestedPlan = (depth: number): string => {
@@ -75,12 +79,20 @@ describe("parsePostgresPlan", () => {
id: "0.0",
nodeType: "Bitmap Index Scan",
subject: "orders_customer_id_idx",
- relationship: "Outer",
selfCost: 4.37,
});
expect(propertyValue(indexScan, "Index Cond")).toBe("(customer_id = 42)");
});
+ test("leaves out the Outer relationship every child has unless it says otherwise", () => {
+ const { nodes } = parseFixture(hashJoinAggregateSort);
+ const byId = new Map(nodes.map((node) => [node.id, node]));
+
+ // The join's probe side is PostgreSQL's default "Outer"; its hash is "Inner".
+ expect(byId.get("0.0.0.0")?.relationship).toBeUndefined();
+ expect(byId.get("0.0.0.1")?.relationship).toBe("Inner");
+ });
+
test("walks a hash join plan depth-first and joins list-valued properties", () => {
const { nodes } = parseFixture(hashJoinAggregateSort);
@@ -239,7 +251,42 @@ describe("parsePostgresPlan", () => {
// later, in a render with no error boundary over it.
expect(parsePostgresPlan(nestedPlan(2000))).toEqual({
ok: false,
- message: POSTGRES_PLAN_TOO_DEEP_MESSAGE,
+ message: PLAN_TOO_DEEP_MESSAGE,
});
});
+
+ test("warns on a sequential scan of a table large enough to matter", () => {
+ const { nodes } = parseFixture(hashJoinAggregateSort);
+ const flagged = nodes.filter((node) => node.warnings.length > 0);
+
+ // `orders` at 819 is flagged; `customers` at 78 is a tiny table.
+ expect(flagged.map((node) => node.subject)).toEqual(["orders"]);
+ expect(flagged[0].warnings).toEqual([PLAN_FULL_TABLE_SCAN]);
+ });
+
+ test("leaves a scan of a tiny table alone", () => {
+ const { root } = parseFixture(seqScanFilter);
+
+ expect(root.totalCost).toBe(90.5);
+ expect(root.warnings).toEqual([]);
+ });
+
+ test("flags the parallel sequential scan and no other scan type", () => {
+ const warningsOf = (raw: Record<string, unknown>) => {
+ const result = parsePostgresPlan(
+ JSON.stringify([{ Plan: { "Total Cost": 5000, ...raw } }])
+ );
+ if (!result.ok) throw new Error(result.message);
+ return result.tree.root.warnings;
+ };
+
+ expect(warningsOf({ "Node Type": "Seq Scan" })).toEqual([
+ PLAN_FULL_TABLE_SCAN,
+ ]);
+ expect(
+ warningsOf({ "Node Type": "Seq Scan", "Parallel Aware": true })
+ ).toEqual([PLAN_FULL_TABLE_SCAN]);
+ expect(warningsOf({ "Node Type": "Index Scan" })).toEqual([]);
+ expect(warningsOf({ "Node Type": "Bitmap Heap Scan" })).toEqual([]);
+ });
});
diff --git a/frontend/src/apps/explain-visualizer/postgres-plan.ts b/frontend/src/apps/explain-visualizer/postgres-plan.ts
index 24fb3d43e8..8a44532e5b 100644
--- a/frontend/src/apps/explain-visualizer/postgres-plan.ts
+++ b/frontend/src/apps/explain-visualizer/postgres-plan.ts
@@ -1,8 +1,14 @@
import {
- buildPlanTree,
+ checkPlanDepth,
+ isJsonRecord,
+ type JsonRecord,
+ PLAN_FULL_TABLE_SCAN,
type PlanNode,
type PlanParseResult,
type PlanProperty,
+ type PlanWarning,
+ parseWithDepthLimit,
+ planSelfCost,
} from "./plan-model";
/**
@@ -32,33 +38,32 @@ const PROMOTED_KEYS = new Set([
"Subplan Name",
]);
-/**
- * Deepest plan this file will build.
- *
- * Both this parser and the model's walks (`flattenPlan`, `planRows`,
- * `planPath`) recurse once per level, so a pathological nesting depth
- * overflows the stack. Without a cap that happens during render, where there
- * is no error boundary to catch it and React unmounts the page instead of
- * showing the parse error. The cap is an order of magnitude below the depth
- * any of those walks fails at, and far above any plan PostgreSQL produces.
- */
-const MAX_PLAN_DEPTH = 500;
-
export const POSTGRES_PLAN_EMPTY_MESSAGE =
"PostgreSQL returned no query plan for this statement.";
export const POSTGRES_PLAN_INVALID_JSON_MESSAGE =
"The query plan is not valid JSON. EXPLAIN (FORMAT JSON) output is expected.";
export const POSTGRES_PLAN_NO_PLAN_MESSAGE =
'The query plan JSON does not contain a "Plan" object.';
-export const POSTGRES_PLAN_TOO_DEEP_MESSAGE = `The query plan nests more than ${MAX_PLAN_DEPTH} levels deep, which is deeper than this visualizer can draw.`;
-/** Raised by `toPlanNode` and caught by `parsePostgresPlan` alone. */
-const PLAN_TOO_DEEP = new Error(POSTGRES_PLAN_TOO_DEEP_MESSAGE);
+/** Node types that read a whole table, spelled as `toNodeType` names them. */
+const FULL_TABLE_SCAN_TYPES = new Set(["Seq Scan", "Parallel Seq Scan"]);
-type JsonRecord = Record<string, unknown>;
+/**
+ * Total cost below which reading a whole table is not worth flagging.
+ *
+ * Under PostgreSQL's default settings a sequential scan costs `seq_page_cost`
+ * (1.0) per page plus `cpu_tuple_cost` (0.01) per row, so 100 cost units is
+ * roughly a 50-page, 5,000-row table — about 400 KB. Reading all of that is a
+ * handful of page fetches that no index lookup would beat, and flagging it
+ * would bury the scans a reader can act on.
+ */
+const FULL_SCAN_COST_THRESHOLD = 100;
-function isRecord(value: unknown): value is JsonRecord {
- return typeof value === "object" && value !== null && !Array.isArray(value);
+function toWarnings(nodeType: string, totalCost: number): PlanWarning[] {
+ return FULL_TABLE_SCAN_TYPES.has(nodeType) &&
+ totalCost >= FULL_SCAN_COST_THRESHOLD
+ ? [PLAN_FULL_TABLE_SCAN]
+ : [];
}
function toNumber(value: unknown): number {
@@ -181,7 +186,8 @@ function toRelationship(raw: JsonRecord): string | undefined {
const subplan = raw["Subplan Name"];
if (typeof subplan === "string" && subplan) return subplan;
const parent = raw["Parent Relationship"];
- if (typeof parent === "string" && parent) return parent;
+ // "Outer" is the default relationship and carries no information.
+ if (typeof parent === "string" && parent && parent !== "Outer") return parent;
return undefined;
}
@@ -189,26 +195,27 @@ function toChildren(raw: JsonRecord, id: string, depth: number): PlanNode[] {
const rawChildren = raw[CHILDREN_KEY];
if (!Array.isArray(rawChildren)) return [];
return rawChildren
- .filter(isRecord)
+ .filter(isJsonRecord)
.map((child, index) => toPlanNode(child, `${id}.${index}`, depth + 1));
}
function toPlanNode(raw: JsonRecord, id: string, depth: number): PlanNode {
- if (depth > MAX_PLAN_DEPTH) throw PLAN_TOO_DEEP;
+ checkPlanDepth(depth);
const children = toChildren(raw, id, depth);
+ const nodeType = toNodeType(raw);
const totalCost = toNumber(raw["Total Cost"]);
- const childCost = children.reduce((sum, child) => sum + child.totalCost, 0);
return {
id,
- nodeType: toNodeType(raw),
+ nodeType,
subject: toSubject(raw),
relationship: toRelationship(raw),
startupCost: toNumber(raw["Startup Cost"]),
totalCost,
- selfCost: Math.max(0, totalCost - childCost),
+ selfCost: planSelfCost(totalCost, children),
rows: toNumber(raw["Plan Rows"]),
width: toNumber(raw["Plan Width"]),
properties: toProperties(raw),
+ warnings: toWarnings(nodeType, totalCost),
children,
};
}
@@ -251,14 +258,10 @@ export function parsePostgresPlan(source: string): PlanParseResult {
}
const entry = Array.isArray(parsed) ? parsed[0] : parsed;
- if (!isRecord(entry) || !isRecord(entry["Plan"])) {
+ const plan = isJsonRecord(entry) ? entry["Plan"] : undefined;
+ if (!isJsonRecord(plan)) {
return { ok: false, message: POSTGRES_PLAN_NO_PLAN_MESSAGE };
}
- try {
- return { ok: true, tree: buildPlanTree(toPlanNode(entry["Plan"], "0", 0)) };
- } catch (error) {
- if (error !== PLAN_TOO_DEEP) throw error;
- return { ok: false, message: POSTGRES_PLAN_TOO_DEEP_MESSAGE };
- }
+ return parseWithDepthLimit(() => toPlanNode(plan, "0", 0));
}
diff --git a/frontend/src/apps/explain-visualizer/spanner-plan.test.ts b/frontend/src/apps/explain-visualizer/spanner-plan.test.ts
new file mode 100644
index 0000000000..365e79c1d7
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/spanner-plan.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, test } from "vitest";
+import {
+ PLAN_FULL_INDEX_SCAN,
+ PLAN_FULL_TABLE_SCAN,
+ PLAN_TOO_DEEP_MESSAGE,
+ type PlanNode,
+ type PlanTree,
+} from "./plan-model";
+import {
+ parseSpannerPlan,
+ SPANNER_PLAN_EMPTY_MESSAGE,
+ SPANNER_PLAN_EMULATOR_MESSAGE,
+ SPANNER_PLAN_INVALID_JSON_MESSAGE,
+ SPANNER_PLAN_NO_PLAN_MESSAGE,
+} from "./spanner-plan";
+import filterLimit from "./test-data/spanner/filter-limit.json";
+import hashJoin from "./test-data/spanner/hash-join.json";
+import nestedArraySubqueries from "./test-data/spanner/nested-array-subqueries.json";
+import scalarSubquery from "./test-data/spanner/scalar-subquery.json";
+
+/** A plan whose operators form a chain `depth` long. */
+const nestedPlan = (depth: number): string =>
+ JSON.stringify({
+ planNodes: Array.from({ length: depth }, (_, index) => ({
+ index,
+ kind: "RELATIONAL",
+ displayName: "Filter",
+ childLinks: index + 1 < depth ? [{ childIndex: index + 1 }] : undefined,
+ })),
+ });
+
+const parseFixture = (fixture: unknown): PlanTree => {
+ const result = parseSpannerPlan(JSON.stringify(fixture));
+ if (!result.ok)
+ throw new Error(`expected a parsable plan: ${result.message}`);
+ return result.tree;
+};
+
+const nodeTypes = (tree: PlanTree) =>
+ tree.nodes.map((node) => `${node.id} ${node.nodeType}`);
+
+const byType = (tree: PlanTree, nodeType: string): PlanNode => {
+ const node = tree.nodes.find((entry) => entry.nodeType === nodeType);
+ if (!node) throw new Error(`no ${nodeType} node`);
+ return node;
+};
+
+describe("parseSpannerPlan", () => {
+ test("keeps the operators and leaves the expressions out of the tree", () => {
+ const tree = parseFixture(hashJoin);
+
+ expect(nodeTypes(tree)).toEqual([
+ "0 Distributed Union",
+ "0.0 Serialize Result",
+ "0.0.0 Hash Join",
+ "0.0.0.0 Local Distributed Union",
+ "0.0.0.0.0 Table Scan",
+ "0.0.0.1 Local Distributed Union",
+ "0.0.0.1.0 Index Scan",
+ ]);
+ });
+
+ test("names nodes with the call, iterator and scan types Spanner reports", () => {
+ expect(nodeTypes(parseFixture(filterLimit))).toEqual([
+ "0 Serialize Result",
+ "0.0 Filter",
+ "0.0.0 Global Limit",
+ "0.0.0.0 Distributed Union",
+ "0.0.0.0.0 Local Limit",
+ "0.0.0.0.0.0 Local Distributed Union",
+ "0.0.0.0.0.0.0 FilterScan",
+ "0.0.0.0.0.0.0.0 Index Scan",
+ ]);
+ const subquery = parseFixture(scalarSubquery);
+ expect(byType(subquery, "Global Stream Aggregate")).toBeDefined();
+ expect(byType(subquery, "Local Stream Aggregate")).toBeDefined();
+ });
+
+ test("labels an operator's inputs with the role their link names", () => {
+ const join = byType(parseFixture(hashJoin), "Hash Join");
+
+ expect(join.children.map((child) => child.relationship)).toEqual([
+ "Build",
+ "Probe",
+ ]);
+ });
+
+ test("folds the expressions an operator names into its properties", () => {
+ const tree = parseFixture(hashJoin);
+
+ expect(byType(tree, "Hash Join").properties).toEqual([
+ {
+ label: "Condition",
+ value: "(($SingerId = $SingerId_1) AND ($AlbumId = $AlbumId_1))",
+ },
+ { label: "Build", value: "$AlbumTitle AS $AlbumTitle'" },
+ { label: "join_type", value: "INNER" },
+ ]);
+ expect(
+ byType(parseFixture(filterLimit), "Global Limit").properties
+ ).toEqual([{ label: "Limit", value: "3" }]);
+ });
+
+ test("leaves metadata already in the name, or meaningless, out of the properties", () => {
+ const tree = parseFixture(scalarSubquery);
+ const labels = tree.nodes.flatMap((node) =>
+ node.properties.map((property) => property.label)
+ );
+
+ for (const folded of [
+ "call_type",
+ "iterator_type",
+ "scan_type",
+ "scan_target",
+ "subquery_cluster_node",
+ ]) {
+ expect(labels).not.toContain(folded);
+ }
+ expect(labels).toContain("scalar_aggregate");
+ });
+
+ test("leaves Spanner's internal metadata out of the properties", () => {
+ const result = parseSpannerPlan(
+ JSON.stringify({
+ planNodes: [
+ {
+ index: 0,
+ kind: "RELATIONAL",
+ displayName: "Scan",
+ metadata: {
+ scan_type: "TableScan",
+ scan_target: "Singers",
+ "Full scan": "true",
+ _internal_id: "7",
+ },
+ },
+ ],
+ })
+ );
+
+ expect(result.ok && result.tree.root.properties).toEqual([
+ { label: "Full scan", value: "true" },
+ ]);
+ });
+
+ test("names what a scan reads and what a filter keeps", () => {
+ const tree = parseFixture(scalarSubquery);
+
+ expect(byType(tree, "Table Scan").subject).toBe("Songs");
+ expect(byType(tree, "Index Scan").subject).toBe("ConcertsBySingerId");
+ expect(
+ tree.nodes
+ .filter((node) => node.nodeType === "FilterScan")
+ .map((node) => node.subject)
+ ).toEqual([
+ "IF(($SongGenre = 'ROCKS'), true, $sv_1)",
+ "($SingerId_1 = $SingerId)",
+ ]);
+ });
+
+ test("hangs a subquery's operators under the subquery", () => {
+ const tree = parseFixture(scalarSubquery);
+ const filter = tree.nodes.find((node) => node.nodeType === "FilterScan");
+ const subquery = byType(tree, "Scalar Subquery");
+
+ expect(filter?.children.map((child) => child.nodeType)).toEqual([
+ "Table Scan",
+ "Scalar Subquery",
+ ]);
+ expect(subquery).toMatchObject({ subject: "$sv_1" });
+ expect(subquery.relationship).toBeUndefined();
+ expect(subquery.children.map((child) => child.nodeType)).toEqual([
+ "Global Stream Aggregate",
+ ]);
+ });
+
+ test("nests a subquery inside another one", () => {
+ const tree = parseFixture(nestedArraySubqueries);
+ const subqueries = tree.nodes.filter(
+ (node) => node.nodeType === "Array Subquery"
+ );
+
+ expect(subqueries.map((node) => [node.id, node.subject])).toEqual([
+ ["0.0.0.1", "$sv_2"],
+ ["0.0.0.1.0.0.1", "$sv_1"],
+ ]);
+ });
+
+ test("warns on the full scans Spanner reports, table or index", () => {
+ const tree = parseFixture(hashJoin);
+
+ expect(byType(tree, "Table Scan").warnings).toEqual([PLAN_FULL_TABLE_SCAN]);
+ expect(byType(tree, "Index Scan").warnings).toEqual([PLAN_FULL_INDEX_SCAN]);
+ // This one seeks with a condition, so Spanner does not call it full.
+ expect(byType(parseFixture(filterLimit), "Index Scan").warnings).toEqual(
+ []
+ );
+ });
+
+ test("carries no estimates, because Spanner plans without any", () => {
+ const tree = parseFixture(hashJoin);
+
+ expect(tree.estimates).toEqual({
+ cost: false,
+ startupCost: false,
+ rows: false,
+ width: false,
+ });
+ expect(tree.costBasis).toBe(0);
+ });
+
+ test("reads a root that leaves its zero index out", () => {
+ const result = parseSpannerPlan(
+ JSON.stringify({
+ planNodes: [
+ {
+ kind: "RELATIONAL",
+ displayName: "Serialize Result",
+ childLinks: [{ childIndex: 1 }],
+ },
+ {
+ index: 1,
+ kind: "RELATIONAL",
+ displayName: "Scan",
+ metadata: { scan_type: "TableScan", scan_target: "Singers" },
+ },
+ ],
+ })
+ );
+
+ expect(result.ok && nodeTypes(result.tree)).toEqual([
+ "0 Serialize Result",
+ "0.0 Table Scan",
+ ]);
+ });
+
+ test("skips a link back up the tree instead of following it forever", () => {
+ const result = parseSpannerPlan(
+ JSON.stringify({
+ planNodes: [
+ {
+ index: 0,
+ kind: "RELATIONAL",
+ displayName: "Distributed Union",
+ childLinks: [{ childIndex: 1 }],
+ },
+ {
+ index: 1,
+ kind: "RELATIONAL",
+ displayName: "Filter",
+ childLinks: [{ childIndex: 0 }],
+ },
+ ],
+ })
+ );
+
+ expect(result.ok && nodeTypes(result.tree)).toEqual([
+ "0 Distributed Union",
+ "0.0 Filter",
+ ]);
+ });
+
+ test("reads a plan nested deeper than anything the optimizer produces", () => {
+ const result = parseSpannerPlan(nestedPlan(100));
+ expect(result.ok && result.tree.nodes).toHaveLength(100);
+ });
+
+ test("rejects a plan nested deeper than the walks over it can go", () => {
+ expect(parseSpannerPlan(nestedPlan(2000))).toEqual({
+ ok: false,
+ message: PLAN_TOO_DEEP_MESSAGE,
+ });
+ });
+
+ test.each([
+ ["", SPANNER_PLAN_EMPTY_MESSAGE],
+ [" ", SPANNER_PLAN_EMPTY_MESSAGE],
+ ["Distributed Union", SPANNER_PLAN_INVALID_JSON_MESSAGE],
+ ["{}", SPANNER_PLAN_NO_PLAN_MESSAGE],
+ ['{"planNodes": []}', SPANNER_PLAN_NO_PLAN_MESSAGE],
+ // What Bytebase returns for the Spanner emulator, which does not plan queries.
+ [
+ '{"planNodes":[{"index":0,"kind":"KIND_UNSPECIFIED","displayName":"No query plan"}]}',
+ SPANNER_PLAN_EMULATOR_MESSAGE,
+ ],
+ ])("rejects %j with a specific message", (source, message) => {
+ expect(parseSpannerPlan(source)).toEqual({ ok: false, message });
+ });
+});
diff --git a/frontend/src/apps/explain-visualizer/spanner-plan.ts b/frontend/src/apps/explain-visualizer/spanner-plan.ts
new file mode 100644
index 0000000000..9cd656b95d
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/spanner-plan.ts
@@ -0,0 +1,214 @@
+import {
+ addPlanProperty,
+ checkPlanDepth,
+ isJsonRecord,
+ type JsonRecord,
+ PLAN_FULL_INDEX_SCAN,
+ PLAN_FULL_TABLE_SCAN,
+ type PlanNode,
+ type PlanParseResult,
+ type PlanProperty,
+ type PlanWarning,
+ parseWithDepthLimit,
+} from "./plan-model";
+
+/**
+ * Maps a Spanner query plan onto the engine-neutral plan model.
+ *
+ * Spanner returns a flat `planNodes` list whose entries link to their children
+ * by position. Relational nodes are operators; scalar nodes are the expressions
+ * those operators evaluate. The tree keeps every operator, folds a named
+ * expression — a condition, a limit — into its operator's properties, and
+ * keeps a scalar node only when it is a subquery, since that is where a
+ * subquery's own operators hang.
+ *
+ * Bytebase asks Spanner for the plan without running the query, and a plan
+ * from that mode carries no estimates.
+ */
+
+export const SPANNER_PLAN_EMPTY_MESSAGE =
+ "Spanner returned no query plan for this statement.";
+export const SPANNER_PLAN_INVALID_JSON_MESSAGE =
+ "The query plan is not valid JSON. A Spanner query plan is expected.";
+export const SPANNER_PLAN_NO_PLAN_MESSAGE =
+ 'The query plan JSON does not contain a "planNodes" list with an operator at its root.';
+export const SPANNER_PLAN_EMULATOR_MESSAGE =
+ "Spanner returned no query plan for this statement. The Spanner emulator returns none for any statement, so explain it on a Spanner instance to see one.";
+
+/** The link type that attaches a subquery to the expression using it. */
+const SUBQUERY_LINK = "Scalar";
+
+/**
+ * Metadata folded into the node's name and subject, or of no use to a reader:
+ * `subquery_cluster_node` is a position in the node list.
+ */
+const FOLDED_METADATA = new Set([
+ "call_type",
+ "iterator_type",
+ "scan_type",
+ "scan_target",
+ "subquery_cluster_node",
+]);
+
+function stringField(record: JsonRecord | undefined, key: string): string {
+ const value = record?.[key];
+ if (typeof value === "string") return value;
+ if (typeof value === "number" || typeof value === "boolean") {
+ return String(value);
+ }
+ return value === undefined || value === null ? "" : JSON.stringify(value);
+}
+
+function metadataOf(raw: JsonRecord): JsonRecord | undefined {
+ return isJsonRecord(raw.metadata) ? raw.metadata : undefined;
+}
+
+/**
+ * The node's name as Spanner's tooling prints it: "Local Distributed Union",
+ * "Global Stream Aggregate", "Table Scan".
+ */
+function toNodeType(raw: JsonRecord): string {
+ const metadata = metadataOf(raw);
+ const name = [
+ stringField(metadata, "call_type"),
+ stringField(metadata, "iterator_type"),
+ stringField(metadata, "scan_type").replace(/Scan$/, ""),
+ stringField(raw, "displayName") || "Unknown",
+ ].filter(Boolean);
+ return name.join(" ");
+}
+
+function toWarnings(raw: JsonRecord): PlanWarning[] {
+ const metadata = metadataOf(raw);
+ if (stringField(metadata, "Full scan") !== "true") return [];
+ return stringField(metadata, "scan_type") === "IndexScan"
+ ? [PLAN_FULL_INDEX_SCAN]
+ : [PLAN_FULL_TABLE_SCAN];
+}
+
+/**
+ * @param path - The positions of this node's ancestors. It is shared across the
+ * walk: a node adds itself while its children are built and removes itself
+ * after.
+ */
+function toPlanNode(
+ planNodes: readonly unknown[],
+ index: number,
+ id: string,
+ relationship: string | undefined,
+ path: Set<number>,
+ depth: number
+): PlanNode {
+ checkPlanDepth(depth);
+ const raw = planNodes[index] as JsonRecord;
+ path.add(index);
+ const children: PlanNode[] = [];
+ const properties: PlanProperty[] = [];
+
+ const links = Array.isArray(raw.childLinks) ? raw.childLinks : [];
+ for (const link of links.filter(isJsonRecord)) {
+ const childIndex = link.childIndex;
+ if (typeof childIndex !== "number") continue;
+ const child = planNodes[childIndex];
+ // A link back up the path would never end; a plan that has one is
+ // malformed, and the rest of it is still worth drawing.
+ if (!isJsonRecord(child) || path.has(childIndex)) continue;
+ const type = stringField(link, "type") || undefined;
+ if (child.kind === "RELATIONAL" || type === SUBQUERY_LINK) {
+ children.push(
+ toPlanNode(
+ planNodes,
+ childIndex,
+ `${id}.${children.length}`,
+ // A subquery's node type already says how it is used.
+ type === SUBQUERY_LINK ? undefined : type,
+ path,
+ depth + 1
+ )
+ );
+ } else if (type) {
+ // An expression the operator names by its role, such as "Seek
+ // Condition". Unnamed ones are the columns it reads or returns.
+ const description = stringField(
+ isJsonRecord(child.shortRepresentation)
+ ? child.shortRepresentation
+ : {},
+ "description"
+ );
+ const variable = stringField(link, "variable");
+ addPlanProperty(
+ properties,
+ type,
+ variable ? `${description} AS $${variable}` : description
+ );
+ }
+ }
+
+ const metadata = metadataOf(raw);
+ for (const key of Object.keys(metadata ?? {})) {
+ // Keys starting with `_` are Spanner's internal ones.
+ if (FOLDED_METADATA.has(key) || key.startsWith("_")) continue;
+ addPlanProperty(properties, key, stringField(metadata, key));
+ }
+
+ const scanTarget = stringField(metadata, "scan_target");
+ const condition = properties.find((property) =>
+ property.label.endsWith("Condition")
+ );
+ const description =
+ raw.kind === "RELATIONAL"
+ ? ""
+ : stringField(
+ isJsonRecord(raw.shortRepresentation) ? raw.shortRepresentation : {},
+ "description"
+ );
+
+ path.delete(index);
+ return {
+ id,
+ nodeType: toNodeType(raw),
+ subject: scanTarget || condition?.value || description || undefined,
+ relationship,
+ properties,
+ warnings: toWarnings(raw),
+ children,
+ };
+}
+
+export function parseSpannerPlan(source: string): PlanParseResult {
+ const trimmed = source.trim();
+ if (!trimmed) {
+ return { ok: false, message: SPANNER_PLAN_EMPTY_MESSAGE };
+ }
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return { ok: false, message: SPANNER_PLAN_INVALID_JSON_MESSAGE };
+ }
+
+ const planNodes =
+ isJsonRecord(parsed) && Array.isArray(parsed.planNodes)
+ ? parsed.planNodes
+ : [];
+ // Nodes link to each other by position, and the root is the first.
+ const root = planNodes[0];
+ if (!isJsonRecord(root) || root.kind !== "RELATIONAL") {
+ // The emulator answers every explain with this one placeholder node.
+ const emulator =
+ planNodes.length === 1 &&
+ isJsonRecord(root) &&
+ root.displayName === "No query plan";
+ return {
+ ok: false,
+ message: emulator
+ ? SPANNER_PLAN_EMULATOR_MESSAGE
+ : SPANNER_PLAN_NO_PLAN_MESSAGE,
+ };
+ }
+
+ return parseWithDepthLimit(() =>
+ toPlanNode(planNodes, 0, "0", undefined, new Set(), 0)
+ );
+}
diff --git a/frontend/src/apps/explain-visualizer/spanner-types.ts b/frontend/src/apps/explain-visualizer/spanner-types.ts
deleted file mode 100644
index fc9d587212..0000000000
--- a/frontend/src/apps/explain-visualizer/spanner-types.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-export interface SpannerChildLink {
- childIndex: number;
- type?: string;
- variable?: string;
-}
-
-export interface SpannerShortRepresentation {
- description: string;
- subqueries?: Record<string, number>;
-}
-
-export interface SpannerPlanNodeData {
- index: number;
- kind: string;
- displayName: string;
- childLinks?: SpannerChildLink[];
- shortRepresentation?: SpannerShortRepresentation;
- metadata?: Record<string, unknown>;
- executionStats?: Record<string, unknown>;
-}
-
-export interface SpannerQueryPlanData {
- planNodes: SpannerPlanNodeData[];
-}
diff --git a/frontend/src/apps/explain-visualizer/test-data/README.md b/frontend/src/apps/explain-visualizer/test-data/README.md
index e2cf1f3ff2..f3e0fe0852 100644
--- a/frontend/src/apps/explain-visualizer/test-data/README.md
+++ b/frontend/src/apps/explain-visualizer/test-data/README.md
@@ -1,10 +1,17 @@
# Plan test data
-Real `EXPLAIN (FORMAT JSON)` output, captured from PostgreSQL 17 against a seeded
-schema, one file per plan shape. The tests in this directory parse these instead
-of hand-written JSON so the parser is pinned to what the server actually emits —
-including the fields nobody thinks to invent, such as `Parent Relationship`,
-`Subplan Name`, `Strategy` and `Partial Mode`.
+Real query plans, one file per plan shape, in the exact form Bytebase hands the
+visualizer. The parser tests read these instead of hand-written plans so each
+parser is pinned to what the engine actually emits — including the fields
+nobody thinks to invent.
+
+Keep them verbatim. Editing one to make a test pass defeats the point of
+capturing it.
+
+## `postgres/`
+
+`EXPLAIN (FORMAT JSON)` output captured from PostgreSQL 17 against a seeded
+schema: `customers` (5,000 rows) and `orders` (50,000 rows).
| File | Shape it covers |
| --- | --- |
@@ -13,11 +20,57 @@ including the fields nobody thinks to invent, such as `Parent Relationship`,
| `hash-join-aggregate-sort.json` | Hash join under a hashed aggregate under a sort |
| `cte-nested-loop-initplan.json` | A CTE, a nested loop, an InitPlan subquery and a limit |
-To add one, run the query against PostgreSQL and save the output verbatim:
+To add one:
```bash
-psql -At -c "EXPLAIN (FORMAT JSON) <query>" > <shape>.json
+psql -At -c "EXPLAIN (FORMAT JSON) <query>" > postgres/<shape>.json
```
-Keep them verbatim. Editing one to make a test pass defeats the point of
-capturing it.
+## `mssql/`
+
+`SHOWPLAN_XML` output captured from SQL Server 2022 against the same schema,
+with `orders_customer_id_idx` on `orders(customer_id)`. Each file is one
+statement run with `SET SHOWPLAN_XML ON`, which is how the driver runs them.
+
+The exception is `split-statements-batch.xml`, a SQL Server 2016 plan kept as
+published: `Cursors/cursor2.sqlplan` from
+[html-query-plan's test plans](https://github.com/JustinPealing/html-query-plan/tree/master/test_plans)
+(MIT License). SQL Server 2016 gives each statement of a batch its own
+`<Statements>` block, which SQL Server 2022 no longer does.
+
+| File | Shape it covers |
+| --- | --- |
+| `index-seek-key-lookup.xml` | Nested loops over an index seek and a key lookup |
+| `hash-join-aggregate-sort.xml` | Merge join, stream and hash aggregates, and a sort |
+| `missing-index.xml` | A missing-index suggestion and a full scan of `orders` |
+| `implicit-conversion-warning.xml` | Statement-level type conversion warnings |
+| `no-join-predicate.xml` | An operator warning on a join without a condition |
+| `if-else.xml` | An `IF` with its condition, `THEN` and `ELSE` |
+| `procedure-two-statements.xml` | A procedure call holding two statements |
+| `two-statement-batch.xml` | Two statements in one plan, under a batch |
+| `static-cursor.xml` | A cursor's population and fetch queries |
+| `scalar-udf.xml` | A call to a scalar function SQL Server doesn't inline, with the function's own statements |
+| `unmatched-filtered-index.xml` | A procedure whose parameter keeps SQL Server from using a filtered index |
+| `split-statements-batch.xml` | A batch of cursor statements, each in its own `<Statements>` block |
+
+To add one, run the statement in `sqlcmd` and keep the `<ShowPlanXML>` document
+from its output:
+
+```bash
+printf 'SET SHOWPLAN_XML ON;\nGO\n<statement>\nGO\n' | sqlcmd -S localhost -U sa -C -d plandb -y 0
+```
+
+## `spanner/`
+
+The Spanner emulator does not plan queries, so these are production Spanner
+plans from [spanner-cli's test data](https://github.com/cloudspannerecosystem/spanner-cli/tree/master/testdata/plans)
+(Apache License 2.0), passed through the driver's `convertQueryPlanToJSON` so
+each file holds the JSON Bytebase returns for that plan. Biome re-indents it,
+as it does every JSON file here.
+
+| File | Source | Shape it covers |
+| --- | --- | --- |
+| `hash-join.json` | `hash_join.input.json` | Build and probe inputs, full table and index scans |
+| `filter-limit.json` | `filter.input.json` | Global and local limits, a seek condition |
+| `scalar-subquery.json` | `scalar_subquery_with_filter_scan.input.json` | A scalar subquery with its own aggregates |
+| `nested-array-subqueries.json` | `array_subqueries_with_compute_struct.input.json` | An array subquery inside another |
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/hash-join-aggregate-sort.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/hash-join-aggregate-sort.xml
new file mode 100644
index 0000000000..f23140048a
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/hash-join-aggregate-sort.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT c.region, COUNT(*) AS orders FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.region ORDER BY COUNT(*) DESC" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.276656" StatementEstRows="3" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0x2FFFF267429A278E" QueryPlanHash="0xE9FB2911342785EF" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="40" CompileTime="2" CompileCPU="2" CompileMemory="288"><MemoryGrantInfo SerialRequiredMemory="1536" SerialDesiredMemory="1584" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213464"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:21:57.03" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:21:57" ModificationCount="0" SamplingPercent="100" Statistics="[PK__customer__3213E83FBDBA5577]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:22:56.15" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Sort" LogicalOp="Sort" EstimateRows="3" EstimateIO="0.0112613" EstimateCPU="0.000107435" AvgRowSize="17" EstimatedTotalSubtreeCost="0.276656" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference><ColumnReference Column="Expr1002"></ColumnReference></OutputList><MemoryFractions Input="0.666667" Output="1"></MemoryFractions><Sort Distinct="0"><OrderBy><OrderByColumn Ascending="0"><ColumnReference Column="Expr1002"></ColumnReference></OrderByColumn></OrderBy><RelOp NodeId="2" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="3" EstimateIO="0" EstimateCPU="3e-07" AvgRowSize="17" EstimatedTotalSubtreeCost="0.265287" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[globalagg1004],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="globalagg1004"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="3" PhysicalOp="Hash Match" LogicalOp="Aggregate" EstimateRows="3" EstimateIO="0" EstimateCPU="0.0512121" AvgRowSize="21" EstimatedTotalSubtreeCost="0.265287" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference><ColumnReference Column="globalagg1004"></ColumnReference></OutputList><MemoryFractions Input="1" Output="0.333333"></MemoryFractions><Hash><DefinedValues><DefinedValue><ColumnReference Column="globalagg1004"></ColumnReference><ScalarOperator ScalarString="SUM([partialagg1003])"><Aggregate Distinct="0" AggType="SUM"><ScalarOperator><Identifier><ColumnReference Column="partialagg1003"></ColumnReference></Identifier></ScalarOperator></Aggregate></ScalarOperator></DefinedValue></DefinedValues><HashKeysBuild><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></HashKeysBuild><BuildResidual><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region] as [c].[region] = [plandb].[dbo].[customers].[region] as [c].[region]"><Compare CompareOp="IS"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></BuildResidual><RelOp NodeId="4" PhysicalOp="Merge Join" LogicalOp="Inner Join" EstimateRows="5000" EstimateIO="0" EstimateCPU="0.0271" AvgRowSize="21" EstimatedTotalSubtreeCost="0.214074" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference><ColumnReference Column="partialagg1003"></ColumnReference></OutputList><Merge ManyToMany="0"><InnerSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></InnerSideJoinColumns><OuterSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OuterSideJoinColumns><Residual><ScalarOperator ScalarString="[plandb].[dbo].[orders].[customer_id] as [o].[customer_id]=[plandb].[dbo].[customers].[id] as [c].[id]"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Residual><RelOp NodeId="5" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="5000" EstimateIO="0" EstimateCPU="0.0325" AvgRowSize="19" EstimatedTotalSubtreeCost="0.154486" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference><ColumnReference Column="partialagg1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="partialagg1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><GroupBy><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></GroupBy><RelOp NodeId="6" PhysicalOp="Index Scan" LogicalOp="Index Scan" EstimateRows="50000" EstimatedRowsRead="50000" EstimateIO="0.0668287" EstimateCPU="0.055157" AvgRowSize="11" EstimatedTotalSubtreeCost="0.121986" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" Alias="[o]" IndexKind="NonClustered" Storage="RowStore"></Object></IndexScan></RelOp></StreamAggregate></RelOp><RelOp NodeId="7" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="5000" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="17" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" Alias="[c]" IndexKind="Clustered" Storage="RowStore"></Object></IndexScan></RelOp></Merge></RelOp></Hash></RelOp></ComputeScalar></RelOp></Sort></RelOp></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/if-else.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/if-else.xml
new file mode 100644
index 0000000000..cbc6124a97
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/if-else.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtCond StatementText="IF EXISTS (SELECT 1 FROM customers WHERE region = &apos;eu&apos;)" StatementId="1" StatementCompId="1" StatementType="COND WITH QUERY" RetrievedFromCache="false" StatementSubTreeCost="0.00330167" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0x64AAF9A2F70D52CB" QueryPlanHash="0x074E1CDEA81A7C7A" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><Condition><QueryPlan CachedPlanSize="16" CompileTime="1" CompileCPU="1" CompileMemory="208"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:22:56.15" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="1e-07" AvgRowSize="11" EstimatedTotalSubtreeCost="0.00330167" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="CASE WHEN [Expr1004] THEN (1) ELSE (0) END"><IF><Condition><ScalarOperator><Identifier><ColumnReference Column="Expr1004"></ColumnReference></Identifier></ScalarOperator></Condition><Then><ScalarOperator><Const ConstValue="(1)"></Const></ScalarOperator></Then><Else><ScalarOperator><Const ConstValue="(0)"></Const></ScalarOperator></Else></IF></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Nested Loops" LogicalOp="Left Semi Join" EstimateRows="1" EstimateIO="0" EstimateCPU="4.18e-06" AvgRowSize="9" EstimatedTotalSubtreeCost="0.00330157" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1004"></ColumnReference></OutputList><NestedLoops Optimized="0"><DefinedValues><DefinedValue><ColumnReference Column="Expr1004"></ColumnReference></DefinedValue></DefinedValues><ProbeColumn><ColumnReference Column="Expr1004"></ColumnReference></ProbeColumn><RelOp NodeId="2" PhysicalOp="Constant Scan" LogicalOp="Constant Scan" EstimateRows="1" EstimateIO="0" EstimateCPU="1.157e-06" AvgRowSize="9" EstimatedTotalSubtreeCost="1.157e-06" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><ConstantScan></ConstantScan></RelOp><RelOp NodeId="3" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="1" EstimateRowsWithoutRowGoal="1666" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="13" EstimatedTotalSubtreeCost="0.00329479" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region]=&apos;eu&apos;"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Const ConstValue="&apos;eu&apos;"></Const></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp></NestedLoops></RelOp></ComputeScalar></RelOp></QueryPlan></Condition><Then><Statements><StmtSimple StatementText=" SELECT COUNT(*) FROM orders" StatementId="2" StatementCompId="2" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.151986" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x99D3EC46E287D3C6" QueryPlanHash="0x400BBAF6B0F6CC3F" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="16" CompileTime="0" CompileCPU="0" CompileMemory="136"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="0" AvgRowSize="11" EstimatedTotalSubtreeCost="0.151986" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[Expr1003],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="Expr1003"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="0.0300005" AvgRowSize="11" EstimatedTotalSubtreeCost="0.151986" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Index Scan" LogicalOp="Index Scan" EstimateRows="50000" EstimatedRowsRead="50000" EstimateIO="0.0668287" EstimateCPU="0.055157" AvgRowSize="9" EstimatedTotalSubtreeCost="0.121986" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" IndexKind="NonClustered" Storage="RowStore"></Object></IndexScan></RelOp></StreamAggregate></RelOp></ComputeScalar></RelOp></QueryPlan></StmtSimple></Statements></Then><Else><Statements><StmtSimple StatementText=" ELSE SELECT 0" StatementId="3" StatementCompId="5" StatementType="SELECT WITHOUT QUERY" RetrievedFromCache="false"></StmtSimple></Statements></Else></StmtCond></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/implicit-conversion-warning.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/implicit-conversion-warning.xml
new file mode 100644
index 0000000000..9a46d19501
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/implicit-conversion-warning.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT id FROM customers WHERE code = 42" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.0324857" StatementEstRows="500" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x5B536730E5E35CB0" QueryPlanHash="0xFB7EB0E1AD91228F" CardinalityEstimationModelVersion="160" ParameterizedText="(@1 tinyint)SELECT [id] FROM [customers] WHERE [code]=@1"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="24" CompileTime="0" CompileCPU="0" CompileMemory="176"><Warnings><PlanAffectingConvert ConvertIssue="Cardinality Estimate" Expression="CONVERT_IMPLICIT(int,[plandb].[dbo].[customers].[code],0)"></PlanAffectingConvert><PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT(int,[plandb].[dbo].[customers].[code],0)=CONVERT_IMPLICIT(int,[@1],0)"></PlanAffectingConvert></Warnings><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:22:56.58" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000004_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="500" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="18" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[plandb].[dbo].[customers].[code],0)=CONVERT_IMPLICIT(int,[@1],0)"><Compare CompareOp="EQ"><ScalarOperator><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="code"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator><ScalarOperator><Identifier><ColumnReference Column="ConstExpr1002"><ScalarOperator><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="@1"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp><ParameterList><ColumnReference Column="@1" ParameterDataType="tinyint" ParameterCompiledValue="(42)"></ColumnReference></ParameterList></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/index-seek-key-lookup.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/index-seek-key-lookup.xml
new file mode 100644
index 0000000000..01c180f830
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/index-seek-key-lookup.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT * FROM orders WHERE customer_id = 42" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.0325135" StatementEstRows="10" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0xB5596D401F8A54C4" QueryPlanHash="0xFB127B1774DF4AE0" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160" ParameterizedText="(@1 tinyint)SELECT * FROM [orders] WHERE [customer_id]=@1"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="32" CompileTime="1" CompileCPU="1" CompileMemory="176"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213464"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:21:57.03" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Nested Loops" LogicalOp="Inner Join" EstimateRows="10" EstimateIO="0" EstimateCPU="4.18e-05" AvgRowSize="32" EstimatedTotalSubtreeCost="0.0325135" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="customer_id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="total"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="created_at"></ColumnReference></OutputList><NestedLoops Optimized="0"><OuterReferences><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></OuterReferences><RelOp NodeId="1" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="10" EstimatedRowsRead="10" EstimateIO="0.003125" EstimateCPU="0.000168" AvgRowSize="15" EstimatedTotalSubtreeCost="0.003293" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="customer_id"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="customer_id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" IndexKind="NonClustered" Storage="RowStore"></Object><SeekPredicates><SeekPredicateNew><SeekKeys><Prefix ScanType="EQ"><RangeColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="customer_id"></ColumnReference></RangeColumns><RangeExpressions><ScalarOperator ScalarString="(42)"><Const ConstValue="(42)"></Const></ScalarOperator></RangeExpressions></Prefix></SeekKeys></SeekPredicateNew></SeekPredicates></IndexScan></RelOp><RelOp NodeId="3" PhysicalOp="Clustered Index Seek" LogicalOp="Clustered Index Seek" EstimateRows="1" EstimateIO="0.003125" EstimateCPU="0.0001581" AvgRowSize="24" EstimatedTotalSubtreeCost="0.0291787" TableCardinality="50000" Parallel="0" EstimateRebinds="9" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="total"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="created_at"></ColumnReference></OutputList><IndexScan Lookup="1" Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="total"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="created_at"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[PK__orders__3213E83F52C28C59]" TableReferenceId="-1" IndexKind="Clustered" Storage="RowStore"></Object><SeekPredicates><SeekPredicateNew><SeekKeys><Prefix ScanType="EQ"><RangeColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></RangeColumns><RangeExpressions><ScalarOperator ScalarString="[plandb].[dbo].[orders].[id]"><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></Identifier></ScalarOperator></RangeExpressions></Prefix></SeekKeys></SeekPredicateNew></SeekPredicates></IndexScan></RelOp></NestedLoops></RelOp><ParameterList><ColumnReference Column="@1" ParameterDataType="tinyint" ParameterCompiledValue="(42)"></ColumnReference></ParameterList></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/missing-index.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/missing-index.xml
new file mode 100644
index 0000000000..f40893409d
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/missing-index.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT o.id, c.region FROM orders o JOIN customers c ON c.id = o.customer_id WHERE o.total = 500.99" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.298338" StatementEstRows="50" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0x36D40E85789358C4" QueryPlanHash="0x0773AFE8BDDF1009" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="24" CompileTime="2" CompileCPU="2" CompileMemory="280"><MissingIndexes><MissingIndexGroup Impact="78.4251"><MissingIndex Database="[plandb]" Schema="[dbo]" Table="[orders]"><ColumnGroup Usage="EQUALITY"><Column Name="[total]" ColumnId="3"></Column></ColumnGroup><ColumnGroup Usage="INCLUDE"><Column Name="[customer_id]" ColumnId="2"></Column></ColumnGroup></MissingIndex></MissingIndexGroup></MissingIndexes><MemoryGrantInfo SerialRequiredMemory="512" SerialDesiredMemory="544" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:21:57.03" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:22:56.49" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_37A5467C]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:21:57" ModificationCount="0" SamplingPercent="100" Statistics="[PK__customer__3213E83FBDBA5577]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Merge Join" LogicalOp="Inner Join" EstimateRows="50" EstimateIO="0" EstimateCPU="0.01621" AvgRowSize="23" EstimatedTotalSubtreeCost="0.298338" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></OutputList><Merge ManyToMany="0"><InnerSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></InnerSideJoinColumns><OuterSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></OuterSideJoinColumns><Residual><ScalarOperator ScalarString="[plandb].[dbo].[orders].[customer_id] as [o].[customer_id]=[plandb].[dbo].[customers].[id] as [c].[id]"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Residual><RelOp NodeId="1" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="5000" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="23" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" Alias="[c]" IndexKind="Clustered" Storage="RowStore"></Object></IndexScan></RelOp><RelOp NodeId="2" PhysicalOp="Sort" LogicalOp="Sort" EstimateRows="50" EstimateIO="0.0112613" EstimateCPU="0.000540236" AvgRowSize="15" EstimatedTotalSubtreeCost="0.249639" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OutputList><MemoryFractions Input="1" Output="1"></MemoryFractions><Sort Distinct="0"><OrderBy><OrderByColumn Ascending="1"><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OrderByColumn></OrderBy><RelOp NodeId="3" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="50" EstimatedRowsRead="50000" EstimateIO="0.158681" EstimateCPU="0.055157" AvgRowSize="24" EstimatedTotalSubtreeCost="0.213838" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[PK__orders__3213E83F52C28C59]" Alias="[o]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[orders].[total] as [o].[total]=(500.99)"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Const ConstValue="(500.99)"></Const></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp></Sort></RelOp></Merge></RelOp></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/no-join-predicate.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/no-join-predicate.xml
new file mode 100644
index 0000000000..3d3510551e
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/no-join-predicate.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT TOP 5 c.id, o.id FROM customers c, orders o" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.00659201" StatementEstRows="5" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0xC3A47BC51AC935E0" QueryPlanHash="0x325FA86BB6606DB9" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="24" CompileTime="1" CompileCPU="1" CompileMemory="152"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><RelOp NodeId="0" PhysicalOp="Top" LogicalOp="Top" EstimateRows="5" EstimateIO="0" EstimateCPU="5e-07" AvgRowSize="15" EstimatedTotalSubtreeCost="0.00659201" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></OutputList><Top RowCount="0" IsPercent="0" WithTies="0"><TopExpression><ScalarOperator ScalarString="(5)"><Const ConstValue="(5)"></Const></ScalarOperator></TopExpression><RelOp NodeId="1" PhysicalOp="Nested Loops" LogicalOp="Inner Join" EstimateRows="5" EstimateRowsWithoutRowGoal="2.5e+08" EstimateIO="0" EstimateCPU="1045" AvgRowSize="15" EstimatedTotalSubtreeCost="0.00659151" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></OutputList><Warnings NoJoinPredicate="1"></Warnings><NestedLoops Optimized="0"><RelOp NodeId="2" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="1" EstimateRowsWithoutRowGoal="5000" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0032831" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" Alias="[c]" IndexKind="Clustered" Storage="RowStore"></Object></IndexScan></RelOp><RelOp NodeId="3" PhysicalOp="Index Scan" LogicalOp="Index Scan" EstimateRows="5" EstimateRowsWithoutRowGoal="50000" EstimatedRowsRead="50000" EstimateIO="0.0668287" EstimateCPU="0.055157" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0032926" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" Alias="[o]" IndexKind="NonClustered" Storage="RowStore"></Object></IndexScan></RelOp></NestedLoops></RelOp></Top></RelOp></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/procedure-two-statements.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/procedure-two-statements.xml
new file mode 100644
index 0000000000..b23a508d8d
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/procedure-two-statements.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="EXEC dbo.region_report &apos;eu&apos;" StatementId="1" StatementCompId="1" StatementType="EXECUTE PROC" RetrievedFromCache="false"><StoredProc ProcName="dbo.region_report"><Statements><StmtSimple StatementText="&#xa;CREATE PROCEDURE dbo.region_report @region VARCHAR(16) AS&#xa;BEGIN&#xa; SELECT COUNT(*) FROM customers WHERE region = @region" StatementId="2" StatementCompId="3" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.0343858" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x66806B67F09C1A8D" QueryPlanHash="0x405336BC121105C7" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="16" CompileTime="0" CompileCPU="0" CompileMemory="144"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:22:56.15" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="0" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0343858" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[Expr1003],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="Expr1003"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="0.0010001" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0343858" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="1666" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="13" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region]=[@region]"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Column="@region"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp></StreamAggregate></RelOp></ComputeScalar></RelOp><ParameterList><ColumnReference Column="@region" ParameterDataType="varchar(16)" ParameterCompiledValue="&apos;eu&apos;"></ColumnReference></ParameterList></QueryPlan></StmtSimple><StmtSimple StatementText=";&#xa; SELECT TOP 5 o.id, o.total FROM orders o JOIN customers c ON c.id = o.customer_id&#xa; WHERE c.region = @region ORDER BY o.total DESC" StatementId="3" StatementCompId="4" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="1.60801" StatementEstRows="5" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0xD997F3ADFD295EC5" QueryPlanHash="0x40605A0D3D4DE942" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="40" CompileTime="2" CompileCPU="2" CompileMemory="296"><MemoryGrantInfo SerialRequiredMemory="1040" SerialDesiredMemory="1080" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T10:21:57.03" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:21:57" ModificationCount="0" SamplingPercent="100" Statistics="[PK__customer__3213E83FBDBA5577]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T10:22:56.15" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Sort" LogicalOp="TopN Sort" EstimateRows="5" EstimateRowsWithoutRowGoal="16660" EstimateIO="0.0112613" EstimateCPU="1.07251" AvgRowSize="20" EstimatedTotalSubtreeCost="1.60801" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><MemoryFractions Input="0.2" Output="1"></MemoryFractions><TopSort Distinct="0" Rows="5"><OrderBy><OrderByColumn Ascending="0"><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OrderByColumn></OrderBy><RelOp NodeId="1" PhysicalOp="Hash Match" LogicalOp="Inner Join" EstimateRows="16660" EstimateRowsWithoutRowGoal="16660" EstimateIO="0" EstimateCPU="0.275505" AvgRowSize="20" EstimatedTotalSubtreeCost="0.524231" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><MemoryFractions Input="1" Output="0.8"></MemoryFractions><Hash><DefinedValues></DefinedValues><HashKeysBuild><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></HashKeysBuild><HashKeysProbe><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></HashKeysProbe><RelOp NodeId="2" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="1666" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="17" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" Alias="[c]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region] as [c].[region]=[@region]"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Column="@region"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp><RelOp NodeId="3" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="50000" EstimatedRowsRead="50000" EstimateIO="0.158681" EstimateCPU="0.055157" AvgRowSize="24" EstimatedTotalSubtreeCost="0.213838" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[PK__orders__3213E83F52C28C59]" Alias="[o]" IndexKind="Clustered" Storage="RowStore"></Object></IndexScan></RelOp></Hash></RelOp></TopSort></RelOp><ParameterList><ColumnReference Column="@region" ParameterDataType="varchar(16)" ParameterCompiledValue="&apos;eu&apos;"></ColumnReference></ParameterList></QueryPlan></StmtSimple></Statements></StoredProc></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/scalar-udf.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/scalar-udf.xml
new file mode 100644
index 0000000000..e5fb969e9b
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/scalar-udf.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT TOP 10 id, dbo.order_count(id) AS orders FROM customers WHERE region = &apos;eu&apos;" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.00345998" StatementEstRows="10" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x5E4083483B16FD57" QueryPlanHash="0x5E25589B79E39BFD" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="true" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan NonParallelPlanReason="TSQLUserDefinedFunctionsNotParallelizable" CachedPlanSize="24" CompileTime="7" CompileCPU="7" CompileMemory="144"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="19660" EstimatedPagesCached="19660" EstimatedAvailableDegreeOfParallelism="8" MaxCompileMemory="1538568"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-15T00:31:30.76" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="10" EstimateIO="0" EstimateCPU="1e-06" AvgRowSize="15" EstimatedTotalSubtreeCost="0.00345998" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="[plandb].[dbo].[order_count]([plandb].[dbo].[customers].[id])"><UserDefinedFunction FunctionName="[plandb].[dbo].[order_count]"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></Identifier></ScalarOperator></UserDefinedFunction></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Top" LogicalOp="Top" EstimateRows="10" EstimateIO="0" EstimateCPU="1e-06" AvgRowSize="11" EstimatedTotalSubtreeCost="0.00345898" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></OutputList><Top RowCount="0" IsPercent="0" WithTies="0"><TopExpression><ScalarOperator ScalarString="(10)"><Const ConstValue="(10)"></Const></ScalarOperator></TopExpression><RelOp NodeId="2" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="10" EstimateRowsWithoutRowGoal="5000" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="17" EstimatedTotalSubtreeCost="0.00345258" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FE1F4FE76]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region]=&apos;eu&apos;"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Const ConstValue="&apos;eu&apos;"></Const></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp></Top></RelOp></ComputeScalar></RelOp></QueryPlan><UDF ProcName="[plandb].[dbo].[order_count]"><Statements><StmtSimple StatementText="CREATE FUNCTION dbo.order_count(@customer_id INT) RETURNS INT WITH INLINE = OFF AS&#xa;BEGIN&#xa; DECLARE @n INT;&#xa; SELECT @n = COUNT(*) FROM orders WHERE customer_id = @customer_id" StatementId="2" StatementCompId="3" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.0032842" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x3F38F1937C59C040" QueryPlanHash="0x88F19E50966C24DB" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="true" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="16" CompileTime="0" CompileCPU="0" CompileMemory="160"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="19660" EstimatedPagesCached="19660" EstimatedAvailableDegreeOfParallelism="8" MaxCompileMemory="1538568"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-15T00:31:12.50" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="0" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0032842" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[Expr1003],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="Expr1003"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="1.1e-06" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0032842" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="1" EstimatedRowsRead="1" EstimateIO="0.003125" EstimateCPU="0.0001581" AvgRowSize="9" EstimatedTotalSubtreeCost="0.0032831" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" IndexKind="NonClustered" Storage="RowStore"></Object><SeekPredicates><SeekPredicateNew><SeekKeys><Prefix ScanType="EQ"><RangeColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="customer_id"></ColumnReference></RangeColumns><RangeExpressions><ScalarOperator ScalarString="[@customer_id]"><Identifier><ColumnReference Column="@customer_id"></ColumnReference></Identifier></ScalarOperator></RangeExpressions></Prefix></SeekKeys></SeekPredicateNew></SeekPredicates></IndexScan></RelOp></StreamAggregate></RelOp></ComputeScalar></RelOp><ParameterList><ColumnReference Column="@customer_id" ParameterDataType="int" ParameterCompiledValue="NULL"></ColumnReference></ParameterList></QueryPlan></StmtSimple><StmtSimple StatementText=";&#xa; RETURN @n" StatementId="3" StatementCompId="4" StatementType="RETURN" RetrievedFromCache="false"></StmtSimple></Statements></UDF></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/split-statements-batch.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/split-statements-batch.xml
new file mode 100755
index 0000000000..df41ceaaaf
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/split-statements-batch.xml
@@ -0,0 +1,144 @@
+<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.5" Build="13.0.1601.5" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">
+ <BatchSequence>
+ <Batch>
+ <Statements>
+ <StmtSimple StatementCompId="1" StatementId="1" StatementText="Declare @UserID varchar(100)&#xD;&#xA;create table #users (UserID varchar(100))" StatementType="CREATE TABLE" RetrievedFromCache="false" />
+ </Statements>
+ <Statements>
+ <StmtSimple StatementCompId="2" StatementId="2" StatementText="&#xD;&#xA;&#xD;&#xA;declare @sqlstatement nvarchar(4000)&#xD;&#xA;set @sqlstatement = 'Insert into #users (userID) SELECT userId FROM users'&#xD;&#xA;" StatementType="ASSIGN" RetrievedFromCache="false" />
+ </Statements>
+ <Statements>
+ <StmtSimple StatementCompId="3" StatementId="3" StatementText="exec(@sqlstatement)" StatementType="EXECUTE STRING" RetrievedFromCache="false" />
+ </Statements>
+ <Statements>
+ <StmtCursor StatementCompId="4" StatementId="4" StatementText="&#xD;&#xA;&#xD;&#xA;declare users_cursor cursor for Select UserId from #Users" StatementType="DECLARE CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" CursorActualType="Dynamic" CursorRequestedType="Dynamic" CursorConcurrency="Optimistic" ForwardOnly="true">
+ <Operation OperationType="FetchQuery">
+ <QueryPlan NonParallelPlanReason="CouldNotGenerateValidParallelPlan" CachedPlanSize="24" CompileTime="0" CompileCPU="0" CompileMemory="160">
+ <MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" />
+ <OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="206734" EstimatedPagesCached="51683" EstimatedAvailableDegreeOfParallelism="2" />
+ <RelOp AvgRowSize="65" EstimateCPU="1E-06" EstimateIO="0.01" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1" LogicalOp="Insert" NodeId="0" Parallel="false" PhysicalOp="Clustered Index Insert" EstimatedTotalSubtreeCost="0.0132842">
+ <OutputList>
+ <ColumnReference Database="[tempdb]" Schema="[dbo]" Table="[#Users]" Column="UserID" />
+ <ColumnReference Column="Expr1006" />
+ </OutputList>
+ <Update DMLRequestSort="false">
+ <Object Database="[tempdb]" Index="[CWT_PrimaryKey]" Storage="RowStore" />
+ <SetPredicate>
+ <ScalarOperator ScalarString="[CWT].[BMK0] = [Bmk1002],[CWT].[CHECKSUM1] = [Chk1003],[CWT].[ROWID] = [Expr1006]">
+ <ScalarExpressionList>
+ <ScalarOperator>
+ <MultipleAssign>
+ <Assign>
+ <ColumnReference Table="[CWT]" Column="BMK0" />
+ <ScalarOperator>
+ <Identifier>
+ <ColumnReference Column="Bmk1002" />
+ </Identifier>
+ </ScalarOperator>
+ </Assign>
+ <Assign>
+ <ColumnReference Table="[CWT]" Column="CHECKSUM1" />
+ <ScalarOperator>
+ <Identifier>
+ <ColumnReference Column="Chk1003" />
+ </Identifier>
+ </ScalarOperator>
+ </Assign>
+ <Assign>
+ <ColumnReference Table="[CWT]" Column="ROWID" />
+ <ScalarOperator>
+ <Identifier>
+ <ColumnReference Column="Expr1006" />
+ </Identifier>
+ </ScalarOperator>
+ </Assign>
+ </MultipleAssign>
+ </ScalarOperator>
+ </ScalarExpressionList>
+ </ScalarOperator>
+ </SetPredicate>
+ <RelOp AvgRowSize="77" EstimateCPU="1E-07" EstimateIO="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1" LogicalOp="Compute Scalar" NodeId="1" Parallel="false" PhysicalOp="Compute Scalar" EstimatedTotalSubtreeCost="0.0032832">
+ <OutputList>
+ <ColumnReference Column="Bmk1002" />
+ <ColumnReference Column="Chk1003" />
+ <ColumnReference Database="[tempdb]" Schema="[dbo]" Table="[#Users]" Column="UserID" />
+ <ColumnReference Column="Expr1006" />
+ </OutputList>
+ <ComputeScalar>
+ <DefinedValues>
+ <DefinedValue>
+ <ColumnReference Column="Expr1006" />
+ <ScalarOperator ScalarString="CWT_ROWID()">
+ <Intrinsic FunctionName="CWT_ROWID" />
+ </ScalarOperator>
+ </DefinedValue>
+ </DefinedValues>
+ <RelOp AvgRowSize="73" EstimateCPU="7.96E-05" EstimateIO="0.0032035" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1" LogicalOp="Table Scan" NodeId="2" Parallel="false" PhysicalOp="Table Scan" EstimatedTotalSubtreeCost="0.0032831" TableCardinality="0">
+ <OutputList>
+ <ColumnReference Column="Bmk1002" />
+ <ColumnReference Column="Chk1003" />
+ <ColumnReference Database="[tempdb]" Schema="[dbo]" Table="[#Users]" Column="UserID" />
+ </OutputList>
+ <TableScan Ordered="false" ForcedIndex="false" ForceScan="false" NoExpandHint="false" Storage="RowStore">
+ <DefinedValues>
+ <DefinedValue>
+ <ColumnReference Column="Bmk1002" />
+ </DefinedValue>
+ <DefinedValue>
+ <ColumnReference Column="Chk1003" />
+ </DefinedValue>
+ <DefinedValue>
+ <ColumnReference Database="[tempdb]" Schema="[dbo]" Table="[#Users]" Column="UserID" />
+ </DefinedValue>
+ </DefinedValues>
+ <Object Database="[tempdb]" Schema="[dbo]" Table="[#Users]" IndexKind="Heap" Storage="RowStore" />
+ </TableScan>
+ </RelOp>
+ </ComputeScalar>
+ </RelOp>
+ </Update>
+ </RelOp>
+ </QueryPlan>
+ </Operation>
+ </CursorPlan>
+ </StmtCursor>
+ </Statements>
+ <Statements>
+ <StmtCursor StatementCompId="5" StatementId="5" StatementText="&#xD;&#xA;OPEN users_cursor&#xD;&#xA;" StatementType="OPEN CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" />
+ </StmtCursor>
+ </Statements>
+ <Statements>
+ <StmtCursor StatementCompId="6" StatementId="6" StatementText="FETCH NEXT FROM users_cursor&#xD;&#xA;INTO @UserId&#xD;&#xA;&#xD;&#xA;" StatementType="FETCH CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" />
+ </StmtCursor>
+ </Statements>
+ <Statements>
+ <StmtCond StatementCompId="7" StatementId="7" StatementText="WHILE @@FETCH_STATUS = 0" StatementType="COND" RetrievedFromCache="false">
+ <Condition />
+ <Then>
+ <Statements>
+ <StmtCursor StatementCompId="8" StatementId="8" StatementText="&#xD;&#xA;BEGIN&#xD;&#xA;&#xD;&#xA;--EXEC asp_DoSomethingStoredProc @UserId&#xD;&#xA;&#xD;&#xA;FETCH NEXT FROM users_cursor&#xD;&#xA;INTO @UserId&#xD;&#xA;&#xD;&#xA;" StatementType="FETCH CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" />
+ </StmtCursor>
+ </Statements>
+ </Then>
+ </StmtCond>
+ </Statements>
+ <Statements>
+ <StmtCursor StatementCompId="11" StatementId="9" StatementText="END&#xD;&#xA;CLOSE users_cursor&#xD;&#xA;" StatementType="CLOSE CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" />
+ </StmtCursor>
+ </Statements>
+ <Statements>
+ <StmtCursor StatementCompId="12" StatementId="10" StatementText="DEALLOCATE users_cursor&#xD;&#xA;&#xD;&#xA;" StatementType="DEALLOCATE CURSOR" RetrievedFromCache="false">
+ <CursorPlan CursorName="users_cursor" />
+ </StmtCursor>
+ </Statements>
+ <Statements>
+ <StmtSimple StatementCompId="13" StatementId="11" StatementText="drop table #users" StatementType="DROP OBJECT" RetrievedFromCache="false" />
+ </Statements>
+ </Batch>
+ </BatchSequence>
+</ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/static-cursor.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/static-cursor.xml
new file mode 100644
index 0000000000..146663ffa5
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/static-cursor.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtCursor StatementText="DECLARE eu_orders CURSOR STATIC FOR SELECT o.id, o.total FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.region = &apos;eu&apos; AND o.total &gt; 990" StatementId="1" StatementCompId="1" StatementType="DECLARE CURSOR" RetrievedFromCache="false"><CursorPlan CursorName="eu_orders" CursorActualType="SnapShot" CursorRequestedType="SnapShot" CursorConcurrency="Read Only" ForwardOnly="false"><Operation OperationType="PopulateQuery"><QueryPlan CachedPlanSize="64" CompileTime="10" CompileCPU="10" CompileMemory="384"><MissingIndexes><MissingIndexGroup Impact="61.2726"><MissingIndex Database="[plandb]" Schema="[dbo]" Table="[orders]"><ColumnGroup Usage="INEQUALITY"><Column Name="[total]" ColumnId="3"></Column></ColumnGroup><ColumnGroup Usage="INCLUDE"><Column Name="[customer_id]" ColumnId="2"></Column></ColumnGroup></MissingIndex></MissingIndexGroup><MissingIndexGroup Impact="9.00024"><MissingIndex Database="[plandb]" Schema="[dbo]" Table="[customers]"><ColumnGroup Usage="EQUALITY"><Column Name="[region]" ColumnId="3"></Column></ColumnGroup></MissingIndex></MissingIndexGroup></MissingIndexes><MemoryGrantInfo SerialRequiredMemory="512" SerialDesiredMemory="592" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="13107" EstimatedPagesCached="13107" EstimatedAvailableDegreeOfParallelism="8" MaxCompileMemory="913168"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-14T23:37:05.43" ModificationCount="0" SamplingPercent="100" Statistics="[orders_customer_id_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T23:37:05.40" ModificationCount="0" SamplingPercent="100" Statistics="[PK__customer__3213E83FEB6EE552]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T23:37:47.48" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_35BCFE0A]" Table="[customers]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo><StatisticsInfo LastUpdate="2026-09-14T23:37:05.99" ModificationCount="0" SamplingPercent="100" Statistics="[_WA_Sys_00000003_37A5467C]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Clustered Index Insert" LogicalOp="Insert" EstimateRows="172.042" EstimateIO="0.01" EstimateCPU="0.000172042" AvgRowSize="24" EstimatedTotalSubtreeCost="0.311736" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference><ColumnReference Column="Expr1004"></ColumnReference></OutputList><Update DMLRequestSort="0"><Object Database="[tempdb]" Index="[CWT_PrimaryKey]" Storage="RowStore"></Object><SetPredicate><ScalarOperator ScalarString="[CWT].[COLUMN0] = [plandb].[dbo].[orders].[id] as [o].[id],[CWT].[COLUMN1] = [plandb].[dbo].[orders].[total] as [o].[total],[CWT].[ROWID] = [Expr1004]"><ScalarExpressionList><ScalarOperator><MultipleAssign><Assign><ColumnReference Table="[CWT]" Column="COLUMN0"></ColumnReference><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></Identifier></ScalarOperator></Assign><Assign><ColumnReference Table="[CWT]" Column="COLUMN1"></ColumnReference><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></Identifier></ScalarOperator></Assign><Assign><ColumnReference Table="[CWT]" Column="ROWID"></ColumnReference><ScalarOperator><Identifier><ColumnReference Column="Expr1004"></ColumnReference></Identifier></ScalarOperator></Assign></MultipleAssign></ScalarOperator></ScalarExpressionList></ScalarOperator></SetPredicate><RelOp NodeId="1" PhysicalOp="Sequence Project" LogicalOp="Compute Scalar" EstimateRows="172.042" EstimateIO="0" EstimateCPU="1.37634e-05" AvgRowSize="24" EstimatedTotalSubtreeCost="0.301564" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference><ColumnReference Column="Expr1004"></ColumnReference></OutputList><SequenceProject><DefinedValues><DefinedValue><ColumnReference Column="Expr1004"></ColumnReference><ScalarOperator ScalarString="i4_row_number"><Sequence FunctionName="i4_row_number"></Sequence></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Segment" LogicalOp="Segment" EstimateRows="172.042" EstimateIO="0" EstimateCPU="3.44085e-06" AvgRowSize="24" EstimatedTotalSubtreeCost="0.30155" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference><ColumnReference Column="Segment1005"></ColumnReference></OutputList><Segment><GroupBy></GroupBy><SegmentColumn><ColumnReference Column="Segment1005"></ColumnReference></SegmentColumn><RelOp NodeId="3" PhysicalOp="Merge Join" LogicalOp="Inner Join" EstimateRows="172.042" EstimateIO="0" EstimateCPU="0.0102001" AvgRowSize="20" EstimatedTotalSubtreeCost="0.301547" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><Merge ManyToMany="0"><InnerSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></InnerSideJoinColumns><OuterSideJoinColumns><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></OuterSideJoinColumns><Residual><ScalarOperator ScalarString="[plandb].[dbo].[orders].[customer_id] as [o].[customer_id]=[plandb].[dbo].[customers].[id] as [c].[id]"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Residual><RelOp NodeId="4" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="1666" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="17" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FEB6EE552]" Alias="[c]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[customers].[region] as [c].[region]=&apos;eu&apos;"><Compare CompareOp="EQ"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[customers]" Alias="[c]" Column="region"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Const ConstValue="&apos;eu&apos;"></Const></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp><RelOp NodeId="5" PhysicalOp="Sort" LogicalOp="Sort" EstimateRows="516.333" EstimateIO="0.0112613" EstimateCPU="0.00735914" AvgRowSize="24" EstimatedTotalSubtreeCost="0.256458" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><MemoryFractions Input="1" Output="1"></MemoryFractions><Sort Distinct="0"><OrderBy><OrderByColumn Ascending="1"><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></OrderByColumn></OrderBy><RelOp NodeId="6" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="516.333" EstimatedRowsRead="50000" EstimateIO="0.158681" EstimateCPU="0.055157" AvgRowSize="24" EstimatedTotalSubtreeCost="0.213838" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="customer_id"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[PK__orders__3213E83FFF45F63E]" Alias="[o]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[orders].[total] as [o].[total]&gt;(990.00)"><Compare CompareOp="GT"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Alias="[o]" Column="total"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Const ConstValue="(990.00)"></Const></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp></Sort></RelOp></Merge></RelOp></Segment></RelOp></SequenceProject></RelOp></Update></RelOp></QueryPlan></Operation><Operation OperationType="FetchQuery"><QueryPlan NonParallelPlanReason="NonParallelizableIntrinsicFunction" CachedPlanSize="64" CompileTime="0" CompileCPU="0" CompileMemory="152"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="13107" EstimatedPagesCached="13107" EstimatedAvailableDegreeOfParallelism="8" MaxCompileMemory="913168"></OptimizerHardwareDependentProperties><RelOp NodeId="0" PhysicalOp="Clustered Index Seek" LogicalOp="Clustered Index Seek" EstimateRows="1" EstimatedRowsRead="1" EstimateIO="0.003125" EstimateCPU="0.0001581" AvgRowSize="24" EstimatedTotalSubtreeCost="0.0032831" TableCardinality="0" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Table="[CWT]" Column="COLUMN0"></ColumnReference><ColumnReference Table="[CWT]" Column="COLUMN1"></ColumnReference><ColumnReference Table="[CWT]" Column="ROWID"></ColumnReference></OutputList><IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Table="[CWT]" Column="COLUMN0"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Table="[CWT]" Column="COLUMN1"></ColumnReference></DefinedValue><DefinedValue><ColumnReference Table="[CWT]" Column="ROWID"></ColumnReference></DefinedValue></DefinedValues><Object Database="[tempdb]" Index="[CWT_PrimaryKey]" Storage="RowStore"></Object><SeekPredicates><SeekPredicateNew><SeekKeys><Prefix ScanType="EQ"><RangeColumns><ColumnReference Table="[CWT]" Column="ROWID"></ColumnReference></RangeColumns><RangeExpressions><ScalarOperator ScalarString="FETCH_RANGE((0))"><Intrinsic FunctionName="FETCH_RANGE"><ScalarOperator><Const ConstValue="(0)"></Const></ScalarOperator></Intrinsic></ScalarOperator></RangeExpressions></Prefix></SeekKeys></SeekPredicateNew></SeekPredicates></IndexScan></RelOp></QueryPlan></Operation></CursorPlan></StmtCursor></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/two-statement-batch.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/two-statement-batch.xml
new file mode 100644
index 0000000000..678a8b0e2e
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/two-statement-batch.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT COUNT(*) FROM customers" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.0354862" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0xCF50D4D5BDCC49BE" QueryPlanHash="0x405336BC121105C7" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="16" CompileTime="0" CompileCPU="0" CompileMemory="112"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="0" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0354862" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[Expr1003],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="Expr1003"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="0.0030005" AvgRowSize="11" EstimatedTotalSubtreeCost="0.0354862" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="5000" EstimatedRowsRead="5000" EstimateIO="0.0268287" EstimateCPU="0.005657" AvgRowSize="9" EstimatedTotalSubtreeCost="0.0324857" TableCardinality="5000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[customers]" Index="[PK__customer__3213E83FBDBA5577]" IndexKind="Clustered" Storage="RowStore"></Object></IndexScan></RelOp></StreamAggregate></RelOp></ComputeScalar></RelOp></QueryPlan></StmtSimple><StmtSimple StatementText="; SELECT COUNT(*) FROM orders" StatementId="2" StatementCompId="2" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.151986" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="TRIVIAL" QueryHash="0x99D3EC46E287D3C6" QueryPlanHash="0x400BBAF6B0F6CC3F" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="false" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="16" CompileTime="0" CompileCPU="0" CompileMemory="112"><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="131420" EstimatedPagesCached="164275" EstimatedAvailableDegreeOfParallelism="10" MaxCompileMemory="18213448"></OptimizerHardwareDependentProperties><RelOp NodeId="0" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="0" AvgRowSize="11" EstimatedTotalSubtreeCost="0.151986" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1002"></ColumnReference></OutputList><ComputeScalar><DefinedValues><DefinedValue><ColumnReference Column="Expr1002"></ColumnReference><ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[Expr1003],0)"><Convert DataType="int" Style="0" Implicit="1"><ScalarOperator><Identifier><ColumnReference Column="Expr1003"></ColumnReference></Identifier></ScalarOperator></Convert></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="1" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="0.0300005" AvgRowSize="11" EstimatedTotalSubtreeCost="0.151986" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Column="Expr1003"></ColumnReference></OutputList><StreamAggregate><DefinedValues><DefinedValue><ColumnReference Column="Expr1003"></ColumnReference><ScalarOperator ScalarString="Count(*)"><Aggregate AggType="countstar" Distinct="0"></Aggregate></ScalarOperator></DefinedValue></DefinedValues><RelOp NodeId="2" PhysicalOp="Index Scan" LogicalOp="Index Scan" EstimateRows="50000" EstimatedRowsRead="50000" EstimateIO="0.0668287" EstimateCPU="0.055157" AvgRowSize="9" EstimatedTotalSubtreeCost="0.121986" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_customer_id_idx]" IndexKind="NonClustered" Storage="RowStore"></Object></IndexScan></RelOp></StreamAggregate></RelOp></ComputeScalar></RelOp></QueryPlan></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/mssql/unmatched-filtered-index.xml b/frontend/src/apps/explain-visualizer/test-data/mssql/unmatched-filtered-index.xml
new file mode 100644
index 0000000000..d9b0b43a32
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/mssql/unmatched-filtered-index.xml
@@ -0,0 +1 @@
+<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" Version="1.564" Build="16.0.4275.2"><BatchSequence><Batch><Statements><StmtSimple StatementText="EXEC dbo.orders_above 950" StatementId="1" StatementCompId="1" StatementType="EXECUTE PROC" RetrievedFromCache="false"><StoredProc ProcName="dbo.orders_above"><Statements><StmtSimple StatementText="CREATE PROCEDURE dbo.orders_above @t DECIMAL(12, 2) AS&#xa; SELECT id FROM orders WHERE total &gt; @t" StatementId="2" StatementCompId="3" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="0.213838" StatementEstRows="2500" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0xC05CFC50F863D3C2" QueryPlanHash="0x04CD43D38297F896" StatementOptmEarlyAbortReason="GoodEnoughPlanFound" CardinalityEstimationModelVersion="160"><StatementSetOptions QUOTED_IDENTIFIER="true" ARITHABORT="false" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false"></StatementSetOptions><QueryPlan CachedPlanSize="24" CompileTime="1" CompileCPU="1" CompileMemory="176"><UnmatchedIndexes><Parameterization><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[orders_big_total_idx]"></Object></Parameterization></UnmatchedIndexes><Warnings UnmatchedIndexes="1"></Warnings><MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" GrantedMemory="0" MaxUsedMemory="0"></MemoryGrantInfo><OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="19660" EstimatedPagesCached="19660" EstimatedAvailableDegreeOfParallelism="8" MaxCompileMemory="1452512"></OptimizerHardwareDependentProperties><OptimizerStatsUsage><StatisticsInfo LastUpdate="2026-09-15T00:31:30.59" ModificationCount="0" SamplingPercent="100" Statistics="[orders_big_total_idx]" Table="[orders]" Schema="[dbo]" Database="[plandb]"></StatisticsInfo></OptimizerStatsUsage><RelOp NodeId="0" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="2500" EstimatedRowsRead="50000" EstimateIO="0.158681" EstimateCPU="0.055157" AvgRowSize="20" EstimatedTotalSubtreeCost="0.213838" TableCardinality="50000" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row"><OutputList><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></OutputList><IndexScan Ordered="0" ForcedIndex="0" ForceScan="0" NoExpandHint="0" Storage="RowStore"><DefinedValues><DefinedValue><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="id"></ColumnReference></DefinedValue></DefinedValues><Object Database="[plandb]" Schema="[dbo]" Table="[orders]" Index="[PK__orders__3213E83FD393A6E8]" IndexKind="Clustered" Storage="RowStore"></Object><Predicate><ScalarOperator ScalarString="[plandb].[dbo].[orders].[total]&gt;[@t]"><Compare CompareOp="GT"><ScalarOperator><Identifier><ColumnReference Database="[plandb]" Schema="[dbo]" Table="[orders]" Column="total"></ColumnReference></Identifier></ScalarOperator><ScalarOperator><Identifier><ColumnReference Column="@t"></ColumnReference></Identifier></ScalarOperator></Compare></ScalarOperator></Predicate></IndexScan></RelOp><ParameterList><ColumnReference Column="@t" ParameterDataType="decimal(12,2)" ParameterCompiledValue="(950.00)"></ColumnReference></ParameterList></QueryPlan></StmtSimple></Statements></StoredProc></StmtSimple></Statements></Batch></BatchSequence></ShowPlanXML>
\ No newline at end of file
diff --git a/frontend/src/apps/explain-visualizer/test-data/bitmap-index-scan.json b/frontend/src/apps/explain-visualizer/test-data/postgres/bitmap-index-scan.json
similarity index 100%
rename from frontend/src/apps/explain-visualizer/test-data/bitmap-index-scan.json
rename to frontend/src/apps/explain-visualizer/test-data/postgres/bitmap-index-scan.json
diff --git a/frontend/src/apps/explain-visualizer/test-data/cte-nested-loop-initplan.json b/frontend/src/apps/explain-visualizer/test-data/postgres/cte-nested-loop-initplan.json
similarity index 100%
rename from frontend/src/apps/explain-visualizer/test-data/cte-nested-loop-initplan.json
rename to frontend/src/apps/explain-visualizer/test-data/postgres/cte-nested-loop-initplan.json
diff --git a/frontend/src/apps/explain-visualizer/test-data/hash-join-aggregate-sort.json b/frontend/src/apps/explain-visualizer/test-data/postgres/hash-join-aggregate-sort.json
similarity index 100%
rename from frontend/src/apps/explain-visualizer/test-data/hash-join-aggregate-sort.json
rename to frontend/src/apps/explain-visualizer/test-data/postgres/hash-join-aggregate-sort.json
diff --git a/frontend/src/apps/explain-visualizer/test-data/seq-scan-filter.json b/frontend/src/apps/explain-visualizer/test-data/postgres/seq-scan-filter.json
similarity index 100%
rename from frontend/src/apps/explain-visualizer/test-data/seq-scan-filter.json
rename to frontend/src/apps/explain-visualizer/test-data/postgres/seq-scan-filter.json
diff --git a/frontend/src/apps/explain-visualizer/test-data/spanner/filter-limit.json b/frontend/src/apps/explain-visualizer/test-data/spanner/filter-limit.json
new file mode 100644
index 0000000000..6c6e00761a
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/spanner/filter-limit.json
@@ -0,0 +1,172 @@
+{
+ "planNodes": [
+ {
+ "index": 0,
+ "kind": "RELATIONAL",
+ "displayName": "Serialize Result",
+ "childLinks": [{ "childIndex": 1 }, { "childIndex": 22 }]
+ },
+ {
+ "index": 1,
+ "kind": "RELATIONAL",
+ "displayName": "Filter",
+ "childLinks": [
+ { "childIndex": 2 },
+ { "childIndex": 19, "type": "Condition" }
+ ]
+ },
+ {
+ "index": 2,
+ "kind": "RELATIONAL",
+ "displayName": "Limit",
+ "childLinks": [
+ { "childIndex": 3 },
+ { "childIndex": 18, "type": "Limit" }
+ ],
+ "metadata": { "call_type": "Global" }
+ },
+ {
+ "index": 3,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [
+ { "childIndex": 4 },
+ { "childIndex": 15, "type": "Split Range" }
+ ],
+ "metadata": { "subquery_cluster_node": "4" }
+ },
+ {
+ "index": 4,
+ "kind": "RELATIONAL",
+ "displayName": "Limit",
+ "childLinks": [
+ { "childIndex": 5 },
+ { "childIndex": 14, "type": "Limit" }
+ ],
+ "metadata": { "call_type": "Local" }
+ },
+ {
+ "index": 5,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 6 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "6" }
+ },
+ {
+ "index": 6,
+ "kind": "RELATIONAL",
+ "displayName": "FilterScan",
+ "childLinks": [
+ { "childIndex": 7 },
+ { "childIndex": 13, "type": "Seek Condition" }
+ ]
+ },
+ {
+ "index": 7,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 8, "variable": "FirstName" },
+ { "childIndex": 9, "variable": "LastName" }
+ ],
+ "metadata": {
+ "scan_target": "SingersByFirstLastName",
+ "scan_type": "IndexScan"
+ }
+ },
+ {
+ "index": 8,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "FirstName" }
+ },
+ {
+ "index": 9,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "LastName" }
+ },
+ {
+ "index": 10,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 11 }, { "childIndex": 12 }],
+ "shortRepresentation": { "description": "STARTS_WITH($FirstName, 'A')" }
+ },
+ {
+ "index": 11,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$FirstName" }
+ },
+ {
+ "index": 12,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "'A'" }
+ },
+ {
+ "index": 13,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 10 }],
+ "shortRepresentation": { "description": "STARTS_WITH($FirstName, 'A')" }
+ },
+ {
+ "index": 14,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "3" }
+ },
+ {
+ "index": 15,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 16 }, { "childIndex": 17 }],
+ "shortRepresentation": { "description": "STARTS_WITH($FirstName, 'A')" }
+ },
+ {
+ "index": 16,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$FirstName" }
+ },
+ {
+ "index": 17,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "'A'" }
+ },
+ {
+ "index": 18,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "3" }
+ },
+ {
+ "index": 19,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 20 }, { "childIndex": 21 }],
+ "shortRepresentation": { "description": "STARTS_WITH($LastName, 'Rich')" }
+ },
+ {
+ "index": 20,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$LastName" }
+ },
+ {
+ "index": 21,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "'Rich'" }
+ },
+ {
+ "index": 22,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$LastName" }
+ }
+ ]
+}
diff --git a/frontend/src/apps/explain-visualizer/test-data/spanner/hash-join.json b/frontend/src/apps/explain-visualizer/test-data/spanner/hash-join.json
new file mode 100644
index 0000000000..df0521dad8
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/spanner/hash-join.json
@@ -0,0 +1,187 @@
+{
+ "planNodes": [
+ {
+ "index": 0,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [
+ { "childIndex": 1 },
+ { "childIndex": 23, "type": "Split Range" }
+ ],
+ "metadata": { "subquery_cluster_node": "1" }
+ },
+ {
+ "index": 1,
+ "kind": "RELATIONAL",
+ "displayName": "Serialize Result",
+ "childLinks": [
+ { "childIndex": 2 },
+ { "childIndex": 21 },
+ { "childIndex": 22 }
+ ]
+ },
+ {
+ "index": 2,
+ "kind": "RELATIONAL",
+ "displayName": "Hash Join",
+ "childLinks": [
+ { "childIndex": 3, "type": "Build" },
+ { "childIndex": 8, "type": "Probe" },
+ { "childIndex": 13, "type": "Condition" },
+ { "childIndex": 20, "type": "Build", "variable": "AlbumTitle'" }
+ ],
+ "metadata": { "join_type": "INNER" }
+ },
+ {
+ "index": 3,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 4 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "4" }
+ },
+ {
+ "index": 4,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 5, "variable": "SingerId" },
+ { "childIndex": 6, "variable": "AlbumId" },
+ { "childIndex": 7, "variable": "AlbumTitle" }
+ ],
+ "metadata": {
+ "Full scan": "true",
+ "scan_target": "Albums",
+ "scan_type": "TableScan"
+ }
+ },
+ {
+ "index": 5,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 6,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumId" }
+ },
+ {
+ "index": 7,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumTitle" }
+ },
+ {
+ "index": 8,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 9 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "9" }
+ },
+ {
+ "index": 9,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 10, "variable": "AlbumId_1" },
+ { "childIndex": 11, "variable": "SingerId_1" },
+ { "childIndex": 12, "variable": "SongName" }
+ ],
+ "metadata": {
+ "Full scan": "true",
+ "scan_target": "SongsBySingerAlbumSongNameDesc",
+ "scan_type": "IndexScan"
+ }
+ },
+ {
+ "index": 10,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumId" }
+ },
+ {
+ "index": 11,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 12,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SongName" }
+ },
+ {
+ "index": 13,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 14 }, { "childIndex": 17 }],
+ "shortRepresentation": {
+ "description": "(($SingerId = $SingerId_1) AND ($AlbumId = $AlbumId_1))"
+ }
+ },
+ {
+ "index": 14,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 15 }, { "childIndex": 16 }],
+ "shortRepresentation": { "description": "($SingerId = $SingerId_1)" }
+ },
+ {
+ "index": 15,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 16,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 17,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 18 }, { "childIndex": 19 }],
+ "shortRepresentation": { "description": "($AlbumId = $AlbumId_1)" }
+ },
+ {
+ "index": 18,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId" }
+ },
+ {
+ "index": 19,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId_1" }
+ },
+ {
+ "index": 20,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumTitle" }
+ },
+ {
+ "index": 21,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumTitle'" }
+ },
+ {
+ "index": 22,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongName" }
+ },
+ {
+ "index": 23,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "true" }
+ }
+ ]
+}
diff --git a/frontend/src/apps/explain-visualizer/test-data/spanner/nested-array-subqueries.json b/frontend/src/apps/explain-visualizer/test-data/spanner/nested-array-subqueries.json
new file mode 100644
index 0000000000..ac0dd52ae4
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/spanner/nested-array-subqueries.json
@@ -0,0 +1,433 @@
+{
+ "planNodes": [
+ {
+ "index": 0,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [
+ { "childIndex": 1 },
+ { "childIndex": 58, "type": "Split Range" }
+ ],
+ "metadata": { "subquery_cluster_node": "1" }
+ },
+ {
+ "index": 1,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 2 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "2" }
+ },
+ {
+ "index": 2,
+ "kind": "RELATIONAL",
+ "displayName": "Serialize Result",
+ "childLinks": [
+ { "childIndex": 3 },
+ { "childIndex": 9 },
+ { "childIndex": 10 },
+ { "childIndex": 11 },
+ { "childIndex": 12 },
+ { "childIndex": 13 },
+ { "childIndex": 14 },
+ { "childIndex": 14, "type": "Scalar" }
+ ]
+ },
+ {
+ "index": 3,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 4, "variable": "SingerId" },
+ { "childIndex": 5, "variable": "FirstName" },
+ { "childIndex": 6, "variable": "LastName" },
+ { "childIndex": 7, "variable": "SingerInfo" },
+ { "childIndex": 8, "variable": "BirthDate" }
+ ],
+ "metadata": {
+ "Full scan": "true",
+ "scan_target": "Singers",
+ "scan_type": "TableScan"
+ }
+ },
+ {
+ "index": 4,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 5,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "FirstName" }
+ },
+ {
+ "index": 6,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "LastName" }
+ },
+ {
+ "index": 7,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerInfo" }
+ },
+ {
+ "index": 8,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "BirthDate" }
+ },
+ {
+ "index": 9,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 10,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$FirstName" }
+ },
+ {
+ "index": 11,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$LastName" }
+ },
+ {
+ "index": 12,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerInfo" }
+ },
+ {
+ "index": 13,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$BirthDate" }
+ },
+ {
+ "index": 14,
+ "kind": "SCALAR",
+ "displayName": "Array Subquery",
+ "childLinks": [{ "childIndex": 15 }, { "childIndex": 57 }],
+ "shortRepresentation": { "description": "$sv_2" }
+ },
+ {
+ "index": 15,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 16 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "16" }
+ },
+ {
+ "index": 16,
+ "kind": "RELATIONAL",
+ "displayName": "Compute Struct",
+ "childLinks": [
+ { "childIndex": 17 },
+ { "childIndex": 27, "variable": "struct_1.SingerId" },
+ { "childIndex": 28, "variable": "struct_1.AlbumId" },
+ { "childIndex": 29, "variable": "struct_1.AlbumTitle" },
+ { "childIndex": 30, "variable": "struct_1.MarketingBudget" },
+ { "childIndex": 31, "variable": "struct_1.no_name\u003c4\u003e" },
+ { "childIndex": 31, "type": "Scalar" }
+ ]
+ },
+ {
+ "index": 17,
+ "kind": "RELATIONAL",
+ "displayName": "FilterScan",
+ "childLinks": [
+ { "childIndex": 18 },
+ { "childIndex": 26, "type": "Seek Condition" }
+ ]
+ },
+ {
+ "index": 18,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 19, "variable": "SingerId_1" },
+ { "childIndex": 20, "variable": "AlbumId" },
+ { "childIndex": 21, "variable": "AlbumTitle" },
+ { "childIndex": 22, "variable": "MarketingBudget" }
+ ],
+ "metadata": { "scan_target": "Albums", "scan_type": "TableScan" }
+ },
+ {
+ "index": 19,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 20,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumId" }
+ },
+ {
+ "index": 21,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumTitle" }
+ },
+ {
+ "index": 22,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "MarketingBudget" }
+ },
+ {
+ "index": 23,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 24 }, { "childIndex": 25 }],
+ "shortRepresentation": { "description": "($SingerId_1 = $SingerId)" }
+ },
+ {
+ "index": 24,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 25,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 26,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 23 }],
+ "shortRepresentation": { "description": "($SingerId_1 = $SingerId)" }
+ },
+ {
+ "index": 27,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 28,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId" }
+ },
+ {
+ "index": 29,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumTitle" }
+ },
+ {
+ "index": 30,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$MarketingBudget" }
+ },
+ {
+ "index": 31,
+ "kind": "SCALAR",
+ "displayName": "Array Subquery",
+ "childLinks": [{ "childIndex": 32 }, { "childIndex": 56 }],
+ "shortRepresentation": { "description": "$sv_1" }
+ },
+ {
+ "index": 32,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 33 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "33" }
+ },
+ {
+ "index": 33,
+ "kind": "RELATIONAL",
+ "displayName": "Compute Struct",
+ "childLinks": [
+ { "childIndex": 34 },
+ { "childIndex": 50, "variable": "struct.SingerId" },
+ { "childIndex": 51, "variable": "struct.AlbumId" },
+ { "childIndex": 52, "variable": "struct.TrackId" },
+ { "childIndex": 53, "variable": "struct.SongName" },
+ { "childIndex": 54, "variable": "struct.Duration" },
+ { "childIndex": 55, "variable": "struct.SongGenre" }
+ ]
+ },
+ {
+ "index": 34,
+ "kind": "RELATIONAL",
+ "displayName": "FilterScan",
+ "childLinks": [
+ { "childIndex": 35 },
+ { "childIndex": 49, "type": "Seek Condition" }
+ ]
+ },
+ {
+ "index": 35,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 36, "variable": "SingerId_2" },
+ { "childIndex": 37, "variable": "AlbumId_1" },
+ { "childIndex": 38, "variable": "TrackId" },
+ { "childIndex": 39, "variable": "SongName" },
+ { "childIndex": 40, "variable": "Duration" },
+ { "childIndex": 41, "variable": "SongGenre" }
+ ],
+ "metadata": { "scan_target": "Songs", "scan_type": "TableScan" }
+ },
+ {
+ "index": 36,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 37,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumId" }
+ },
+ {
+ "index": 38,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "TrackId" }
+ },
+ {
+ "index": 39,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SongName" }
+ },
+ {
+ "index": 40,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "Duration" }
+ },
+ {
+ "index": 41,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SongGenre" }
+ },
+ {
+ "index": 42,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 43 }, { "childIndex": 46 }],
+ "shortRepresentation": {
+ "description": "(($SingerId_2 = $SingerId_1) AND ($AlbumId_1 = $AlbumId))"
+ }
+ },
+ {
+ "index": 43,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 44 }, { "childIndex": 45 }],
+ "shortRepresentation": { "description": "($SingerId_2 = $SingerId_1)" }
+ },
+ {
+ "index": 44,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_2" }
+ },
+ {
+ "index": 45,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 46,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 47 }, { "childIndex": 48 }],
+ "shortRepresentation": { "description": "($AlbumId_1 = $AlbumId)" }
+ },
+ {
+ "index": 47,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId_1" }
+ },
+ {
+ "index": 48,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId" }
+ },
+ {
+ "index": 49,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 42 }],
+ "shortRepresentation": {
+ "description": "(($SingerId_2 = $SingerId_1) AND ($AlbumId_1 = $AlbumId))"
+ }
+ },
+ {
+ "index": 50,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_2" }
+ },
+ {
+ "index": 51,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId_1" }
+ },
+ {
+ "index": 52,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$TrackId" }
+ },
+ {
+ "index": 53,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongName" }
+ },
+ {
+ "index": 54,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$Duration" }
+ },
+ {
+ "index": 55,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongGenre" }
+ },
+ {
+ "index": 56,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$struct" }
+ },
+ {
+ "index": 57,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$struct_1" }
+ },
+ {
+ "index": 58,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "true" }
+ }
+ ]
+}
diff --git a/frontend/src/apps/explain-visualizer/test-data/spanner/scalar-subquery.json b/frontend/src/apps/explain-visualizer/test-data/spanner/scalar-subquery.json
new file mode 100644
index 0000000000..ea01b47fe1
--- /dev/null
+++ b/frontend/src/apps/explain-visualizer/test-data/spanner/scalar-subquery.json
@@ -0,0 +1,329 @@
+{
+ "planNodes": [
+ {
+ "index": 0,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [
+ { "childIndex": 1 },
+ { "childIndex": 41, "type": "Split Range" }
+ ],
+ "metadata": { "subquery_cluster_node": "1" }
+ },
+ {
+ "index": 1,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 2 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "2" }
+ },
+ {
+ "index": 2,
+ "kind": "RELATIONAL",
+ "displayName": "Serialize Result",
+ "childLinks": [
+ { "childIndex": 3 },
+ { "childIndex": 35 },
+ { "childIndex": 36 },
+ { "childIndex": 37 },
+ { "childIndex": 38 },
+ { "childIndex": 39 },
+ { "childIndex": 40 }
+ ]
+ },
+ {
+ "index": 3,
+ "kind": "RELATIONAL",
+ "displayName": "FilterScan",
+ "childLinks": [
+ { "childIndex": 4 },
+ { "childIndex": 34, "type": "Residual Condition" },
+ { "childIndex": 16, "type": "Scalar" }
+ ]
+ },
+ {
+ "index": 4,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [
+ { "childIndex": 5, "variable": "SingerId" },
+ { "childIndex": 6, "variable": "AlbumId" },
+ { "childIndex": 7, "variable": "TrackId" },
+ { "childIndex": 8, "variable": "SongName" },
+ { "childIndex": 9, "variable": "Duration" },
+ { "childIndex": 10, "variable": "SongGenre" }
+ ],
+ "metadata": {
+ "Full scan": "true",
+ "scan_target": "Songs",
+ "scan_type": "TableScan"
+ }
+ },
+ {
+ "index": 5,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 6,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "AlbumId" }
+ },
+ {
+ "index": 7,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "TrackId" }
+ },
+ {
+ "index": 8,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SongName" }
+ },
+ {
+ "index": 9,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "Duration" }
+ },
+ {
+ "index": 10,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SongGenre" }
+ },
+ {
+ "index": 11,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [
+ { "childIndex": 12 },
+ { "childIndex": 15 },
+ { "childIndex": 16 }
+ ],
+ "shortRepresentation": {
+ "description": "IF(($SongGenre = 'ROCKS'), true, $sv_1)",
+ "subqueries": { "$sv_1": 16 }
+ }
+ },
+ {
+ "index": 12,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 13 }, { "childIndex": 14 }],
+ "shortRepresentation": { "description": "($SongGenre = 'ROCKS')" }
+ },
+ {
+ "index": 13,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongGenre" }
+ },
+ {
+ "index": 14,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "'ROCKS'" }
+ },
+ {
+ "index": 15,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "true" }
+ },
+ {
+ "index": 16,
+ "kind": "SCALAR",
+ "displayName": "Scalar Subquery",
+ "childLinks": [{ "childIndex": 17 }, { "childIndex": 33 }],
+ "shortRepresentation": { "description": "$sv_1" }
+ },
+ {
+ "index": 17,
+ "kind": "RELATIONAL",
+ "displayName": "Aggregate",
+ "childLinks": [
+ { "childIndex": 18 },
+ { "childIndex": 32, "type": "Agg", "variable": "v1" }
+ ],
+ "metadata": {
+ "call_type": "Global",
+ "iterator_type": "Stream",
+ "scalar_aggregate": "true"
+ }
+ },
+ {
+ "index": 18,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [
+ { "childIndex": 19 },
+ { "childIndex": 29, "type": "Split Range" }
+ ],
+ "metadata": { "subquery_cluster_node": "19" }
+ },
+ {
+ "index": 19,
+ "kind": "RELATIONAL",
+ "displayName": "Aggregate",
+ "childLinks": [
+ { "childIndex": 20 },
+ { "childIndex": 28, "type": "Agg", "variable": "v2" }
+ ],
+ "metadata": {
+ "call_type": "Local",
+ "iterator_type": "Stream",
+ "scalar_aggregate": "true"
+ }
+ },
+ {
+ "index": 20,
+ "kind": "RELATIONAL",
+ "displayName": "Distributed Union",
+ "childLinks": [{ "childIndex": 21 }],
+ "metadata": { "call_type": "Local", "subquery_cluster_node": "21" }
+ },
+ {
+ "index": 21,
+ "kind": "RELATIONAL",
+ "displayName": "FilterScan",
+ "childLinks": [
+ { "childIndex": 22 },
+ { "childIndex": 27, "type": "Seek Condition" }
+ ]
+ },
+ {
+ "index": 22,
+ "kind": "RELATIONAL",
+ "displayName": "Scan",
+ "childLinks": [{ "childIndex": 23, "variable": "SingerId_1" }],
+ "metadata": {
+ "scan_target": "ConcertsBySingerId",
+ "scan_type": "IndexScan"
+ }
+ },
+ {
+ "index": 23,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "SingerId" }
+ },
+ {
+ "index": 24,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 25 }, { "childIndex": 26 }],
+ "shortRepresentation": { "description": "($SingerId_1 = $SingerId)" }
+ },
+ {
+ "index": 25,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 26,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 27,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 24 }],
+ "shortRepresentation": { "description": "($SingerId_1 = $SingerId)" }
+ },
+ {
+ "index": 28,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "shortRepresentation": { "description": "ANY()" }
+ },
+ {
+ "index": 29,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 30 }, { "childIndex": 31 }],
+ "shortRepresentation": { "description": "($SingerId_1 = $SingerId)" }
+ },
+ {
+ "index": 30,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId_1" }
+ },
+ {
+ "index": 31,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 32,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "shortRepresentation": { "description": "ANY()" }
+ },
+ {
+ "index": 33,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$v1" }
+ },
+ {
+ "index": 34,
+ "kind": "SCALAR",
+ "displayName": "Function",
+ "childLinks": [{ "childIndex": 11 }],
+ "shortRepresentation": {
+ "description": "IF(($SongGenre = 'ROCKS'), true, $sv_1)"
+ }
+ },
+ {
+ "index": 35,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SingerId" }
+ },
+ {
+ "index": 36,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$AlbumId" }
+ },
+ {
+ "index": 37,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$TrackId" }
+ },
+ {
+ "index": 38,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongName" }
+ },
+ {
+ "index": 39,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$Duration" }
+ },
+ {
+ "index": 40,
+ "kind": "SCALAR",
+ "displayName": "Reference",
+ "shortRepresentation": { "description": "$SongGenre" }
+ },
+ {
+ "index": 41,
+ "kind": "SCALAR",
+ "displayName": "Constant",
+ "shortRepresentation": { "description": "true" }
+ }
+ ]
+}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
index 027472f78e..1640986bb0 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
@@ -208,7 +208,8 @@ vi.mock("@/stores/app", () => ({
},
}));
-vi.mock("@/utils/explainToken", () => ({
+vi.mock("@/utils/explainToken", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils/explainToken")>()),
createExplainToken,
}));
@@ -787,8 +788,77 @@ describe("SingleResultView explain visualizer", () => {
openSpy.mockRestore();
});
- test("Spanner reuses the plan already in the result", async () => {
- const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
+ test.each([[Engine.MSSQL, QueryOption_ExplainFormat.XML, "<ShowPlanXML/>"]])(
+ "asks engine %s for the plan in the format its visualizer reads",
+ async (engine, explainFormat, plan) => {
+ const openSpy = vi
+ .spyOn(window, "open")
+ .mockReturnValue({} as Window);
+ runQuery.mockImplementation(
+ async (
+ _database: unknown,
+ context: { resultSet?: { results: unknown[] } }
+ ) => {
+ context.resultSet = {
+ results: [
+ create(QueryResultSchema, {
+ statement: "SELECT 1",
+ rows: [
+ create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: plan },
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ };
+ }
+ );
+
+ render(
+ <SingleResultView
+ disallowCopyingData={false}
+ params={{ ...params, engine, explain: true }}
+ database={databaseForEngine(engine)}
+ result={create(QueryResultSchema, {
+ columnNames: ["QUERY PLAN"],
+ statement: "SELECT 1",
+ rows: [
+ create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: "a readable plan" },
+ }),
+ ],
+ }),
+ ],
+ })}
+ showExport={false}
+ />
+ );
+
+ fireEvent.click(screen.getByText("visualize-explain"));
+
+ await waitFor(() => expect(openSpy).toHaveBeenCalled());
+ expect(
+ runQuery.mock.calls[0][1].params.queryOption?.explainFormat
+ ).toBe(explainFormat);
+ expect(createExplainToken).toHaveBeenCalledWith({
+ statement: "SELECT 1",
+ explain: plan,
+ engine,
+ });
+ expect(notify).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ }
+ );
+
+ test("Spanner hands over the plan already in the result", async () => {
+ const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);
+ const plan = '{"planNodes":[]}';
render(
<SingleResultView
@@ -803,7 +873,7 @@ describe("SingleResultView explain visualizer", () => {
create(QueryRowSchema, {
values: [
create(RowValueSchema, {
- kind: { case: "stringValue", value: '{"planNodes":[]}' },
+ kind: { case: "stringValue", value: plan },
}),
],
}),
@@ -817,6 +887,37 @@ describe("SingleResultView explain visualizer", () => {
await waitFor(() => expect(openSpy).toHaveBeenCalled());
expect(runQuery).not.toHaveBeenCalled();
+ expect(createExplainToken).toHaveBeenCalledWith({
+ statement: "SELECT 1",
+ explain: plan,
+ engine: Engine.SPANNER,
+ });
openSpy.mockRestore();
});
+
+ test("offers no visualizer for an engine it cannot draw", () => {
+ render(
+ <SingleResultView
+ disallowCopyingData={false}
+ params={{ ...params, engine: Engine.MYSQL, explain: true }}
+ database={databaseForEngine(Engine.MYSQL)}
+ result={create(QueryResultSchema, {
+ columnNames: ["EXPLAIN"],
+ statement: "SELECT 1",
+ rows: [
+ create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: "-> Table scan on t" },
+ }),
+ ],
+ }),
+ ],
+ })}
+ showExport={false}
+ />
+ );
+
+ expect(screen.queryByText("visualize-explain")).toBeNull();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
index 014bb1e48f..c2a9a8dcc5 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
@@ -48,7 +48,12 @@ import {
QueryOptionSchema,
type QueryResult,
} from "@/types/proto-es/v1/sql_service_pb";
-import { createExplainToken } from "@/utils/explainToken";
+import {
+ createExplainToken,
+ isVisualizerEngine,
+ VISUALIZER_EXPLAIN_FORMATS,
+ type VisualizerEngine,
+} from "@/utils/explainToken";
import {
flattenElasticsearchSearchResult,
flattenNoSQLQueryResult,
@@ -392,32 +397,23 @@ function SingleResultViewInner({
[flattenedTableView, result.masked]
);
- const showVisualizeButton =
- (engine === Engine.POSTGRES ||
- engine === Engine.MSSQL ||
- engine === Engine.SPANNER) &&
- !!params.explain;
+ const showVisualizeButton = isVisualizerEngine(engine) && !!params.explain;
const visualizeExplain = async () => {
- let token: string | undefined;
+ if (!isVisualizerEngine(engine)) return;
try {
- // Spanner explains as JSON already. PostgreSQL and SQL Server return the
- // readable plan in the grid, so the visualizer re-runs the explain asking
- // for the format it can render.
- if (engine === Engine.SPANNER) {
- token = getExplainTokenFromResult(result, engine);
- } else {
- token = await getExplainTokenForFormat(
- database,
- params,
- runQuery,
- engine,
- engine === Engine.POSTGRES
- ? QueryOption_ExplainFormat.JSON
- : QueryOption_ExplainFormat.XML,
- resultIndex
- );
- }
+ // Spanner explains only as JSON, so the result on screen already is the
+ // plan the visualizer reads; the other engines show a readable plan.
+ const token =
+ engine === Engine.SPANNER
+ ? getExplainTokenFromResult(result, engine)
+ : await getExplainToken(
+ database,
+ params,
+ runQuery,
+ engine,
+ resultIndex
+ );
if (!token) {
// The plan is fetched by a second query, so a failure here is invisible
// unless we say so — the button would otherwise do nothing.
@@ -834,17 +830,18 @@ function getExplainTokenFromResult(
return createExplainToken({ statement, explain, engine });
}
-// getExplainTokenForFormat re-runs the explain in a format the visualizer can
-// render. The grid keeps the readable plan the user already sees, so the
-// renderable one is only fetched when they ask for it.
-async function getExplainTokenForFormat(
+// getExplainToken re-runs the explain in the format the visualizer reads for
+// the engine, whatever format the grid is showing, so the plan is only fetched
+// when the user asks for it.
+async function getExplainToken(
database: Database,
params: SQLEditorQueryParams,
runQuery: ReturnType<typeof useExecuteSQL>["runQuery"],
- engine: Engine,
- explainFormat: QueryOption_ExplainFormat,
+ engine: VisualizerEngine,
resultIndex: number
): Promise<string | undefined> {
+ const explainFormat =
+ QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];
const context: SQLEditorDatabaseQueryContext = {
id: uuidv4(),
params: {
diff --git a/frontend/src/utils/explainToken.ts b/frontend/src/utils/explainToken.ts
index ef8fc6fc07..dfd753e4d3 100644
--- a/frontend/src/utils/explainToken.ts
+++ b/frontend/src/utils/explainToken.ts
@@ -1,5 +1,23 @@
import { Engine } from "@/types/proto-es/v1/common_pb";
+/**
+ * The engines the query-plan visualizer draws, each with the explain output it
+ * reads, named as `QueryOption.ExplainFormat` names it. The SQL editor offers
+ * Visualize for exactly these engines and hands over the plan in this format;
+ * the visualizer keys its parsers on the same table, so the two cannot drift.
+ */
+export const VISUALIZER_EXPLAIN_FORMATS = {
+ [Engine.POSTGRES]: "JSON",
+ [Engine.MSSQL]: "XML",
+ [Engine.SPANNER]: "JSON",
+} as const;
+
+export type VisualizerEngine = keyof typeof VISUALIZER_EXPLAIN_FORMATS;
+
+export const isVisualizerEngine = (
+ engine: Engine
+): engine is VisualizerEngine => engine in VISUALIZER_EXPLAIN_FORMATS;
+
export type StoredExplain = {
statement: string;
explain: string;