All files / commands save-sparql-query-results.ts

100% Statements 20/20
87.5% Branches 7/8
100% Functions 3/3
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54      1x     4x     4x 3x     3x     3x     3x 3x 6x   6x 1x     5x 2x       2x       2x   3x         3x     3x     4x   4x    
import * as vscode from 'vscode';
import { SparqlQueryExecutionState, BindingsResult } from '@src/languages/sparql/services/sparql-query-state';
 
export const saveSparqlQueryResults = {
    id: 'mentor.command.saveSparqlQueryResults',
    handler: async (context: SparqlQueryExecutionState): Promise<void> => {
        let content = '';
 
        // TODO: Read the query results from the service instead of serializing them.
        if (context.result?.type === 'bindings') {
            const result = context.result as BindingsResult;
 
            // Use array join instead of string concatenation
            const lines: string[] = [];
 
            // Add header row
            lines.push(result.columns.join(', '));
 
            // Process all data rows at once
            const dataRows = result.rows.map(row =>
                result.columns.map(column => {
                    const term = row[column];
 
                    if (!term) {
                        return '';
                    }
 
                    if (term.termType === 'Literal') {
                        const value = term.value || '';
 
                        // Escape single quotes in the value and wrap in quotes.
                        // Note: This is to have valid CSV and not break lines in the output.
                        const escapedValue = value
                            .replace(/'/g, "''")
                            .replace(/\n/g, '');
 
                        return `"${escapedValue}"`;
                    } else {
                        return term.value;
                    }
                }).join(', ')
            );
 
            lines.push(...dataRows);
 
            // Single join operation at the end
            content = lines.join('\n');
        }
 
        const document = await vscode.workspace.openTextDocument({ content, language: 'csv' });
 
        await vscode.window.showTextDocument(document, { preview: false });
    }
};