clean up the code

This commit is contained in:
Archie Agarwal 2025-06-16 15:16:47 +05:30
parent dc8bb69359
commit a96d679087
3 changed files with 272 additions and 277 deletions

View File

@ -24,5 +24,8 @@
"source.organizeImports": "explicit" "source.organizeImports": "explicit"
}, },
"typescript.preferences.importModuleSpecifier": "non-relative", "typescript.preferences.importModuleSpecifier": "non-relative",
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
} }

View File

@ -265,16 +265,10 @@ class QueryTabComponentImpl extends React.Component<QueryTabComponentImplProps,
} }
public onExecuteQueryClick = async (): Promise<void> => { public onExecuteQueryClick = async (): Promise<void> => {
// console.log("i am ",this.props.collection.databaseId);
// console.log("I am query",this.state.sqlQueryEditorContent );
// console.log("i am",this.props.collection.id());
const query1=this.state.sqlQueryEditorContent; const query1=this.state.sqlQueryEditorContent;
const db = this.props.collection.databaseId; const db = this.props.collection.databaseId;
const container = this.props.collection.id(); const container = this.props.collection.id();
useQueryMetadataStore.getState().setMetadata(query1, db, container); useQueryMetadataStore.getState().setMetadata(query1, db, container);
console.log("i am ",query1);
console.log("I am db",db);
console.log("i am cnt",container);
this._iterator = undefined; this._iterator = undefined;
setTimeout(async () => { setTimeout(async () => {

View File

@ -39,7 +39,7 @@ import { ResultsViewProps } from "./QueryResultSection";
enum ResultsTabs { enum ResultsTabs {
Results = "results", Results = "results",
QueryStats = "queryStats", QueryStats = "queryStats",
IndexAdvisor="indexadv", IndexAdvisor = "indexadv",
} }
const ResultsTab: React.FC<ResultsViewProps> = ({ queryResults, isMongoDB, executeQueryDocumentsPage }) => { const ResultsTab: React.FC<ResultsViewProps> = ({ queryResults, isMongoDB, executeQueryDocumentsPage }) => {
@ -392,9 +392,8 @@ const QueryStatsTab: React.FC<Pick<ResultsViewProps, "queryResults">> = ({ query
}, },
{ {
metric: "User defined function execution time", metric: "User defined function execution time",
value: `${ value: `${aggregatedQueryMetrics.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.toString() || 0
aggregatedQueryMetrics.runtimeExecutionTimes?.userDefinedFunctionExecutionTime?.toString() || 0 } ms`,
} ms`,
toolTip: "Total time spent executing user-defined functions", toolTip: "Total time spent executing user-defined functions",
}, },
{ {
@ -536,12 +535,12 @@ const QueryStatsTab: React.FC<Pick<ResultsViewProps, "queryResults">> = ({ query
}; };
interface IIndexMetric { interface IIndexMetric {
index: string; index: string;
impact: string; impact: string;
section: "Included" | "Not Included" | "Header"; section: "Included" | "Not Included" | "Header";
} }
const IndexAdvisorTab: React.FC = () => { const IndexAdvisorTab: React.FC = () => {
const {userQuery, databaseId, containerId}=useQueryMetadataStore(); const { userQuery, databaseId, containerId } = useQueryMetadataStore();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [indexMetrics, setIndexMetrics] = useState<any>(null); const [indexMetrics, setIndexMetrics] = useState<any>(null);
const [showIncluded, setShowIncluded] = useState(true); const [showIncluded, setShowIncluded] = useState(true);
@ -574,251 +573,249 @@ const IndexAdvisorTab: React.FC = () => {
setLoading(false); setLoading(false);
} }
} }
if(userQuery && databaseId && containerId){ if (userQuery && databaseId && containerId) {
fetchIndexMetrics(); fetchIndexMetrics();
} }
}, [userQuery, databaseId, containerId]); }, [userQuery, databaseId, containerId]);
useEffect(() => { useEffect(() => {
if (!indexMetrics) return ; if (!indexMetrics) return;
const included: any[] = []; const included: any[] = [];
const notIncluded: any[] = []; const notIncluded: any[] = [];
const lines = indexMetrics.split("\n").map((line: string) => line.trim()).filter(Boolean); const lines = indexMetrics.split("\n").map((line: string) => line.trim()).filter(Boolean);
let currentSection = ""; let currentSection = "";
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
const line = lines[i]; const line = lines[i];
if (line.startsWith("Utilized Single Indexes") || line.startsWith("Utilized Composite Indexes")) { if (line.startsWith("Utilized Single Indexes") || line.startsWith("Utilized Composite Indexes")) {
currentSection = "included"; currentSection = "included";
} else if (line.startsWith("Potential Single Indexes") || line.startsWith("Potential Composite Indexes")) { } else if (line.startsWith("Potential Single Indexes") || line.startsWith("Potential Composite Indexes")) {
currentSection = "notIncluded"; currentSection = "notIncluded";
} else if (line.startsWith("Index Spec:")) { } else if (line.startsWith("Index Spec:")) {
const index = line.replace("Index Spec:", "").trim(); const index = line.replace("Index Spec:", "").trim();
const impactLine = lines[i + 1]; const impactLine = lines[i + 1];
const impact = impactLine?.includes("Index Impact Score:") ? impactLine.split(":")[1].trim() : "Unknown"; const impact = impactLine?.includes("Index Impact Score:") ? impactLine.split(":")[1].trim() : "Unknown";
const isComposite = index.includes(","); const isComposite = index.includes(",");
const indexObj: any = { index, impact }; const indexObj: any = { index, impact };
if (isComposite) { if (isComposite) {
indexObj.composite = index.split(",").map((part:string) => { indexObj.composite = index.split(",").map((part: string) => {
const [path, order] = part.trim().split(/\s+/); const [path, order] = part.trim().split(/\s+/);
return { return {
path: path.trim(), path: path.trim(),
order: order?.toLowerCase() === "desc" ? "descending" : "ascending", order: order?.toLowerCase() === "desc" ? "descending" : "ascending",
}; };
}); });
} else {
let path = "/unknown/*";
const pathRegex = /\/[^\/\s*?]+(?:\/[^\/\s*?]+)*(\/\*|\?)/;
const match = index.match(pathRegex);
if (match) {
path = match[0];
} else { } else {
const simplePathRegex = /\/[^\/\s]+/; let path = "/unknown/*";
const simpleMatch = index.match(simplePathRegex); const pathRegex = /\/[^\/\s*?]+(?:\/[^\/\s*?]+)*(\/\*|\?)/;
if (simpleMatch) { const match = index.match(pathRegex);
path = simpleMatch[0] + "/*"; if (match) {
path = match[0];
} else {
const simplePathRegex = /\/[^\/\s]+/;
const simpleMatch = index.match(simplePathRegex);
if (simpleMatch) {
path = simpleMatch[0] + "/*";
}
} }
indexObj.path = path;
} }
indexObj.path = path;
}
if (currentSection === "included") { if (currentSection === "included") {
included.push(indexObj); included.push(indexObj);
} else if (currentSection === "notIncluded") { } else if (currentSection === "notIncluded") {
notIncluded.push(indexObj); notIncluded.push(indexObj);
}
} }
} }
} setIncludedIndexes(included);
setIncludedIndexes(included); setNotIncludedIndexes(notIncluded);
setNotIncludedIndexes(notIncluded); }, [indexMetrics]);
},[indexMetrics]);
useEffect(() => { useEffect(() => {
const allSelected = notIncluded.length > 0 && notIncluded.every((item) => selectedIndexes.some((s) => s.index === item.index)); const allSelected = notIncluded.length > 0 && notIncluded.every((item) => selectedIndexes.some((s) => s.index === item.index));
setSelectAll(allSelected); setSelectAll(allSelected);
}, [selectedIndexes, notIncluded]); }, [selectedIndexes, notIncluded]);
const handleCheckboxChange = (indexObj: any, checked: boolean) => { const handleCheckboxChange = (indexObj: any, checked: boolean) => {
if (checked) { if (checked) {
setSelectedIndexes((prev) => [...prev, indexObj]); setSelectedIndexes((prev) => [...prev, indexObj]);
} else { } else {
setSelectedIndexes((prev) => setSelectedIndexes((prev) =>
prev.filter((item) => item.index !== indexObj.index) prev.filter((item) => item.index !== indexObj.index)
); );
} }
}; };
const handleSelectAll = (checked: boolean) => { const handleSelectAll = (checked: boolean) => {
setSelectAll(checked); setSelectAll(checked);
setSelectedIndexes(checked ? notIncluded : []); setSelectedIndexes(checked ? notIncluded : []);
}; };
const handleUpdatePolicy = async () => { const handleUpdatePolicy = async () => {
if (selectedIndexes.length === 0) { if (selectedIndexes.length === 0) {
console.log("No indexes selected for update"); console.log("No indexes selected for update");
return; return;
} }
try { try {
const { resource: containerDef } = await client() const { resource: containerDef } = await client()
.database(databaseId) .database(databaseId)
.container(containerId) .container(containerId)
.read(); .read();
const newIncludedPaths = selectedIndexes const newIncludedPaths = selectedIndexes
.filter(index => !index.composite) .filter(index => !index.composite)
.map(index => { .map(index => {
return { return {
path: index.path, path: index.path,
}; };
}); });
const newCompositeIndexes = selectedIndexes const newCompositeIndexes = selectedIndexes
.filter(index => index.composite) .filter(index => index.composite)
.map(index => index.composite); .map(index => index.composite);
const updatedPolicy = { const updatedPolicy = {
...containerDef.indexingPolicy, ...containerDef.indexingPolicy,
includedPaths: [ includedPaths: [
...(containerDef.indexingPolicy?.includedPaths || []), ...(containerDef.indexingPolicy?.includedPaths || []),
...newIncludedPaths, ...newIncludedPaths,
], ],
compositeIndexes: [ compositeIndexes: [
...(containerDef.indexingPolicy?.compositeIndexes || []), ...(containerDef.indexingPolicy?.compositeIndexes || []),
...newCompositeIndexes, ...newCompositeIndexes,
], ],
}; };
await client() await client()
.database(databaseId) .database(databaseId)
.container(containerId) .container(containerId)
.replace({ .replace({
id: containerId, id: containerId,
partitionKey: containerDef.partitionKey, partitionKey: containerDef.partitionKey,
indexingPolicy: updatedPolicy, indexingPolicy: updatedPolicy,
}); });
console.log("Indexing policy successfully updated:", updatedPolicy); const newIncluded = [...included, ...notIncluded.filter(item =>
selectedIndexes.find(s => s.index === item.index)
)];
const newNotIncluded = notIncluded.filter(item =>
!selectedIndexes.find(s => s.index === item.index)
);
const newIncluded = [...included, ...notIncluded.filter(item => setSelectedIndexes([]);
selectedIndexes.find(s => s.index === item.index) setSelectAll(false);
)]; setIndexMetricsFromParsed(newIncluded, newNotIncluded);
const newNotIncluded = notIncluded.filter(item => setUpdateMessageShown(true);
!selectedIndexes.find(s => s.index === item.index) } catch (err) {
); console.error("Failed to update indexing policy:", err);
}
};
setSelectedIndexes([]); const setIndexMetricsFromParsed = (included: { index: string; impact: string }[], notIncluded: { index: string; impact: string }[]) => {
setSelectAll(false);
setIndexMetricsFromParsed(newIncluded, newNotIncluded);
setUpdateMessageShown(true);
} catch (err) {
console.error("Failed to update indexing policy:", err);
}
};
const setIndexMetricsFromParsed = (included: { index: string; impact: string }[], notIncluded: { index: string; impact: string }[]) => {
const serialize = (sectionTitle: string, items: { index: string; impact: string }[], isUtilized: boolean) => const serialize = (sectionTitle: string, items: { index: string; impact: string }[], isUtilized: boolean) =>
items.length items.length
? `${sectionTitle}\n` + ? `${sectionTitle}\n` +
items items
.map((item) => `Index Spec: ${item.index}\nIndex Impact Score: ${item.impact}`) .map((item) => `Index Spec: ${item.index}\nIndex Impact Score: ${item.impact}`)
.join("\n") + "\n" .join("\n") + "\n"
: ""; : "";
const composedMetrics = const composedMetrics =
serialize("Utilized Single Indexes", included, true) + serialize("Utilized Single Indexes", included, true) +
serialize("Potential Single Indexes", notIncluded, false); serialize("Potential Single Indexes", notIncluded, false);
setIndexMetrics(composedMetrics.trim()); setIndexMetrics(composedMetrics.trim());
}; };
const renderImpactDots = (impact: string) => { const renderImpactDots = (impact: string) => {
let count = 0; let count = 0;
if (impact === "High") count = 3; if (impact === "High") count = 3;
else if (impact === "Medium") count = 2; else if (impact === "Medium") count = 2;
else if (impact === "Low") count = 1; else if (impact === "Low") count = 1;
return( return (
<div style={{ display: "flex", alignItems: "center", gap: "4px" }}> <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
{Array.from({ length: count }).map((_, i) => ( {Array.from({ length: count }).map((_, i) => (
<CircleFilled <CircleFilled
key={i} key={i}
style={{ style={{
color: "#0078D4", color: "#0078D4",
fontSize: "12px", fontSize: "12px",
display: "inline-flex", display: "inline-flex",
}} }}
/> />
))} ))}
</div> </div>
); );
}; };
const renderRow = (item: IIndexMetric, index: number) => { const renderRow = (item: IIndexMetric, index: number) => {
const isHeader = item.section === "Header"; const isHeader = item.section === "Header";
const isNotIncluded = item.section === "Not Included"; const isNotIncluded = item.section === "Not Included";
const isIncluded = item.section === "Included"; const isIncluded = item.section === "Included";
return ( return (
<TableRow key={index}> <TableRow key={index}>
<TableCell colSpan={2}> <TableCell colSpan={2}>
<div <div
style={{ style={{
display: "grid", display: "grid",
gridTemplateColumns: "30px 30px 1fr 50px 120px", gridTemplateColumns: "30px 30px 1fr 50px 120px",
alignItems: "center", alignItems: "center",
gap: "8px", gap: "8px",
}}> }}>
{isNotIncluded ? ( {isNotIncluded ? (
<Checkbox <Checkbox
checked={selectedIndexes.some((selected)=>selected.index===item.index)} checked={selectedIndexes.some((selected) => selected.index === item.index)}
onChange={(_, data) => handleCheckboxChange(item, data.checked === true)} onChange={(_, data) => handleCheckboxChange(item, data.checked === true)}
/> />
) : isHeader && item.index === "Not Included in Current Policy" && notIncluded.length > 0 ? ( ) : isHeader && item.index === "Not Included in Current Policy" && notIncluded.length > 0 ? (
<Checkbox <Checkbox
checked={selectAll} checked={selectAll}
onChange={(_, data) => handleSelectAll(data.checked === true)} onChange={(_, data) => handleSelectAll(data.checked === true)}
/> />
) : ( ) : (
<div style={{ width: "18px", height: "18px" }}></div> <div style={{ width: "18px", height: "18px" }}></div>
)} )}
{isHeader ? ( {isHeader ? (
<span <span
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={() => { onClick={() => {
if (item.index === "Included in Current Policy") { if (item.index === "Included in Current Policy") {
setShowIncluded(!showIncluded); setShowIncluded(!showIncluded);
} else if (item.index === "Not Included in Current Policy") { } else if (item.index === "Not Included in Current Policy") {
setShowNotIncluded(!showNotIncluded); setShowNotIncluded(!showNotIncluded);
}
}}
>
{item.index === "Included in Current Policy"
? showIncluded
? <ChevronDown20Regular />
: <ChevronRight20Regular />
: showNotIncluded
? <ChevronDown20Regular />
: <ChevronRight20Regular />
} }
}} </span>
> ) : (
{item.index === "Included in Current Policy" <div style={{ width: "24px" }}></div>
? showIncluded )}
? <ChevronDown20Regular /> <div style={{ fontWeight: isHeader ? "bold" : "normal" }}>
: <ChevronRight20Regular /> {item.index}
: showNotIncluded </div>
? <ChevronDown20Regular /> <div style={{ fontSize: isHeader ? 0 : undefined }}>
: <ChevronRight20Regular /> {isHeader ? null : item.impact}
} </div>
</span> <div>
) : ( {isHeader ? null : renderImpactDots(item.impact)}
<div style={{ width: "24px" }}></div> </div>
)}
<div style={{ fontWeight: isHeader ? "bold" : "normal" }}>
{item.index}
</div> </div>
<div style={{ fontSize: isHeader ? 0 : undefined }}> </TableCell>
{isHeader ? null : item.impact} </TableRow>
</div> );
<div> };
{isHeader ? null : renderImpactDots(item.impact)}
</div>
</div>
</TableCell>
</TableRow>
);
};
const generateIndexMetricItems = ( const generateIndexMetricItems = (
included: { index: string; impact: string }[], included: { index: string; impact: string }[],
@ -844,55 +841,56 @@ const renderRow = (item: IIndexMetric, index: number) => {
if (loading) { if (loading) {
return <div> return <div>
<Spinner <Spinner
size="small" size="small"
style={{ style={{
'--spinner-size': '16px', '--spinner-size': '16px',
'--spinner-thickness': '2px', '--spinner-thickness': '2px',
'--spinner-color': '#0078D4', '--spinner-color': '#0078D4',
} as React.CSSProperties}/> } as React.CSSProperties} />
</div>;} </div>;
}
return ( return (
<div> <div>
<div style={{ padding: "1rem", fontSize: "1.2rem", display: "flex", alignItems: "center", gap: "0.5rem" }}> <div style={{ padding: "1rem", fontSize: "1.2rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
{updateMessageShown ? ( {updateMessageShown ? (
<> <>
<span <span
style={{ style={{
width: 18, width: 18,
height: 18, height: 18,
borderRadius: "50%", borderRadius: "50%",
backgroundColor: "#107C10", backgroundColor: "#107C10",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
}}> }}>
<FontIcon iconName="CheckMark" style={{ color: "white", fontSize: 12 }} /> <FontIcon iconName="CheckMark" style={{ color: "white", fontSize: 12 }} />
</span> </span>
<span> <span>
Your indexing policy has been updated with the new included paths. You may review the changes in Scale & Settings. Your indexing policy has been updated with the new included paths. You may review the changes in Scale & Settings.
</span> </span>
</> </>
) : ( ) : (
"Here is an analysis on the indexes utilized for executing the query. Based on the analysis, Cosmos DB recommends adding the selected indexes to your indexing policy to optimize the performance of this particular query." "Here is an analysis on the indexes utilized for executing the query. Based on the analysis, Cosmos DB recommends adding the selected indexes to your indexing policy to optimize the performance of this particular query."
)} )}
</div> </div>
<div style={{ padding: "1rem", fontSize: "1.3rem", fontWeight: "bold" }}>Indexes analysis</div> <div style={{ padding: "1rem", fontSize: "1.3rem", fontWeight: "bold" }}>Indexes analysis</div>
<Table style={{ display: "block", alignItems: "center",marginBottom:"7rem" }}> <Table style={{ display: "block", alignItems: "center", marginBottom: "7rem" }}>
<TableHeader> <TableHeader>
<TableRow > <TableRow >
<TableCell colSpan={2}> <TableCell colSpan={2}>
<div <div
style={{ style={{
display: "grid", display: "grid",
gridTemplateColumns: "30px 30px 1fr 50px 120px", gridTemplateColumns: "30px 30px 1fr 50px 120px",
alignItems: "center", alignItems: "center",
gap: "8px", gap: "8px",
fontWeight: "bold", fontWeight: "bold",
}} }}
> >
<div style={{ width: "18px", height: "18px" }}></div> {/* Checkbox column */} <div style={{ width: "18px", height: "18px" }}></div>
<div style={{ width: "24px" }}></div> {/* Chevron column */} <div style={{ width: "24px" }}></div>
<div>Index</div> <div>Index</div>
<div><span style={{ whiteSpace: "nowrap" }}>Estimated Impact</span></div> <div><span style={{ whiteSpace: "nowrap" }}>Estimated Impact</span></div>
</div> </div>
@ -904,23 +902,23 @@ return (
</TableBody> </TableBody>
</Table> </Table>
{selectedIndexes.length > 0 && ( {selectedIndexes.length > 0 && (
<div style={{ padding: "1rem", marginTop: "-7rem",flexWrap:"wrap"}}> <div style={{ padding: "1rem", marginTop: "-7rem", flexWrap: "wrap" }}>
<button <button
onClick={handleUpdatePolicy} onClick={handleUpdatePolicy}
style={{ style={{
backgroundColor: "#0078D4", backgroundColor: "#0078D4",
color: "white", color: "white",
padding: "8px 16px", padding: "8px 16px",
border: "none", border: "none",
borderRadius: "4px", borderRadius: "4px",
cursor: "pointer", cursor: "pointer",
marginTop: "1rem", marginTop: "1rem",
}} }}
> >
Update Indexing Policy with selected index(es) Update Indexing Policy with selected index(es)
</button> </button>
</div> </div>
)} )}
</div> </div>
); );
}; };
@ -928,7 +926,7 @@ export const ResultsView: React.FC<ResultsViewProps> = ({ isMongoDB, queryResult
const styles = useQueryTabStyles(); const styles = useQueryTabStyles();
const [activeTab, setActiveTab] = useState<ResultsTabs>(ResultsTabs.Results); const [activeTab, setActiveTab] = useState<ResultsTabs>(ResultsTabs.Results);
const onTabSelect = useCallback((event: SelectTabEvent, data: SelectTabData) =>{ const onTabSelect = useCallback((event: SelectTabEvent, data: SelectTabData) => {
setActiveTab(data.value as ResultsTabs); setActiveTab(data.value as ResultsTabs);
}, []); }, []);