mirror of
https://github.com/ckaczor/sqltoolsservice.git
synced 2026-01-14 17:23:27 -05:00
It's an overhaul of the Save As mechanism to utilize the file reader/writer classes to better align with the patterns laid out by the rest of the query execution. Why make this change? This change makes our code base more uniform and adherent to the patterns/paradigms we've set up. This change also helps with the encapsulation of the classes to "separate the concerns" of each component of the save as function.
* Replumbing the save as execution to pass the call down the query stack as QueryExecutionService->Query->Batch->ResultSet
* Each layer performs it's own parameter checking
* QueryExecutionService checks if the query exists
* Query checks if the batch exists
* Batch checks if the result set exists
* ResultSet checks if the row counts are valid and if the result set has been executed
* Success/Failure delegates are passed down the chain as well
* Determination of whether a save request is a "selection" moved to the SaveResultsRequest class to eliminate duplication of code and creation of utility classes
* Making the IFileStream* classes more generic
* Removing the requirements of max characters to store from the GetWriter method, and moving it into the constructor for the temporary buffer writer - the values have been moved to the settings and given defaults
* Removing the individual type writers from IFileStreamWriter
* Removing the individual type writers from IFIleStreamReader
* Adding a new overload for WriteRow to IFileStreamWriter that will write out data, given a row's worth of data and the list of columns
* Creating a new IFileStreamFactory that creates a reader/writer pair for reading from the temporary files and writing to CSV files
* Creating a new IFileStreamFactory that creates a reader/writer pair for reading from the temporary files and writing to JSON files
* Dramatically simplified the CSV encoding functionality
* Removed duplicated logic for saving in different types and condensed down to a single chain that only differs based on what type of factory is provided
* Removing the logic for managing the list of save as tasks, since the ResultSet now performs the actual saving work, there's no real need to expose the internals of the ResultSet
* Adding new strings to the sr.strings file for save as error messages
* Completely rewriting the unit tests for the save as mechanism. Very fine grained unit tests now that should cover majority of cases (aside from race conditions)
* Refactoring maxchars params into settings and out of file stream factory
* Removing write*/read* methods from file stream readers/writers
* Migrating the CSV save as to the resultset
* Tweaks to unit testing to eliminate writing files to disk
* WIP, moving to a base class for save results writers
* Everything is wired up and compiles
* Adding unit tests for CSV encoding
* Adding unit tests for CSV and Json writers
* Adding tests to the result set for saving
* Refactor to throw exceptions on errors instead of calling failure handler
* Unit tests for batch/query argument in range
* Unit tests
* Adding service integration unit tests
* Final polish, copyright notices, etc
* Adding NULL logic
* Fixing issue of unicode to utf8
* Fixing issues as per @kburtram code review comments
* Adding files that got broken?
217 lines
8.4 KiB
C#
217 lines
8.4 KiB
C#
//
|
|
// Copyright (c) Microsoft. All rights reserved.
|
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
//
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
|
|
using Microsoft.SqlTools.ServiceLayer.QueryExecution.DataStorage;
|
|
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
|
|
using Xunit;
|
|
|
|
namespace Microsoft.SqlTools.ServiceLayer.Test.QueryExecution.DataStorage
|
|
{
|
|
public class SaveAsCsvFileStreamWriterTests
|
|
{
|
|
[Theory]
|
|
[InlineData("Something\rElse")]
|
|
[InlineData("Something\nElse")]
|
|
[InlineData("Something\"Else")]
|
|
[InlineData("Something,Else")]
|
|
[InlineData("\tSomething")]
|
|
[InlineData("Something\t")]
|
|
[InlineData(" Something")]
|
|
[InlineData("Something ")]
|
|
[InlineData(" \t\r\n\",\r\n\"\r ")]
|
|
public void EncodeCsvFieldShouldWrap(string field)
|
|
{
|
|
// If: I CSV encode a field that has forbidden characters in it
|
|
string output = SaveAsCsvFileStreamWriter.EncodeCsvField(field);
|
|
|
|
// Then: It should wrap it in quotes
|
|
Assert.True(Regex.IsMatch(output, "^\".*")
|
|
&& Regex.IsMatch(output, ".*\"$"));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("Something")]
|
|
[InlineData("Something valid.")]
|
|
[InlineData("Something\tvalid")]
|
|
public void EncodeCsvFieldShouldNotWrap(string field)
|
|
{
|
|
// If: I CSV encode a field that does not have forbidden characters in it
|
|
string output = SaveAsCsvFileStreamWriter.EncodeCsvField(field);
|
|
|
|
// Then: It should not wrap it in quotes
|
|
Assert.False(Regex.IsMatch(output, "^\".*\"$"));
|
|
}
|
|
|
|
[Fact]
|
|
public void EncodeCsvFieldReplace()
|
|
{
|
|
// If: I CSV encode a field that has a double quote in it,
|
|
string output = SaveAsCsvFileStreamWriter.EncodeCsvField("Some\"thing");
|
|
|
|
// Then: It should be replaced with double double quotes
|
|
Assert.Equal("\"Some\"\"thing\"", output);
|
|
}
|
|
|
|
[Fact]
|
|
public void EncodeCsvFieldNull()
|
|
{
|
|
// If: I CSV encode a null
|
|
string output = SaveAsCsvFileStreamWriter.EncodeCsvField(null);
|
|
|
|
// Then: there should be a string version of null returned
|
|
Assert.Equal("NULL", output);
|
|
}
|
|
|
|
[Fact]
|
|
public void WriteRowWithoutColumnSelectionOrHeader()
|
|
{
|
|
// Setup:
|
|
// ... Create a request params that has no selection made
|
|
// ... Create a set of data to write
|
|
// ... Create a memory location to store the data
|
|
var requestParams = new SaveResultsAsCsvRequestParams();
|
|
List<DbCellValue> data = new List<DbCellValue>
|
|
{
|
|
new DbCellValue { DisplayValue = "item1" },
|
|
new DbCellValue { DisplayValue = "item2" }
|
|
};
|
|
List<DbColumnWrapper> columns = new List<DbColumnWrapper>
|
|
{
|
|
new DbColumnWrapper(new TestDbColumn("column1")),
|
|
new DbColumnWrapper(new TestDbColumn("column2"))
|
|
};
|
|
byte[] output = new byte[8192];
|
|
|
|
// If: I write a row
|
|
SaveAsCsvFileStreamWriter writer = new SaveAsCsvFileStreamWriter(new MemoryStream(output), requestParams);
|
|
using (writer)
|
|
{
|
|
writer.WriteRow(data, columns);
|
|
}
|
|
|
|
// Then: It should write one line with 2 items, comma delimited
|
|
string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n');
|
|
string[] lines = outputString.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
|
|
Assert.Equal(1, lines.Length);
|
|
string[] values = lines[0].Split(',');
|
|
Assert.Equal(2, values.Length);
|
|
}
|
|
|
|
[Fact]
|
|
public void WriteRowWithHeader()
|
|
{
|
|
// Setup:
|
|
// ... Create a request params that has no selection made, headers should be printed
|
|
// ... Create a set of data to write
|
|
// ... Create a memory location to store the data
|
|
var requestParams = new SaveResultsAsCsvRequestParams
|
|
{
|
|
IncludeHeaders = true
|
|
};
|
|
List<DbCellValue> data = new List<DbCellValue>
|
|
{
|
|
new DbCellValue { DisplayValue = "item1" },
|
|
new DbCellValue { DisplayValue = "item2" }
|
|
};
|
|
List<DbColumnWrapper> columns = new List<DbColumnWrapper>
|
|
{
|
|
new DbColumnWrapper(new TestDbColumn("column1")),
|
|
new DbColumnWrapper(new TestDbColumn("column2"))
|
|
};
|
|
byte[] output = new byte[8192];
|
|
|
|
// If: I write a row
|
|
SaveAsCsvFileStreamWriter writer = new SaveAsCsvFileStreamWriter(new MemoryStream(output), requestParams);
|
|
using (writer)
|
|
{
|
|
writer.WriteRow(data, columns);
|
|
}
|
|
|
|
// Then:
|
|
// ... It should have written two lines
|
|
string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n');
|
|
string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
|
|
Assert.Equal(2, lines.Length);
|
|
|
|
// ... It should have written a header line with two, comma separated names
|
|
string[] headerValues = lines[0].Split(',');
|
|
Assert.Equal(2, headerValues.Length);
|
|
for (int i = 0; i < columns.Count; i++)
|
|
{
|
|
Assert.Equal(columns[i].ColumnName, headerValues[i]);
|
|
}
|
|
|
|
// Note: No need to check values, it is done as part of the previous test
|
|
}
|
|
|
|
[Fact]
|
|
public void WriteRowWithColumnSelection()
|
|
{
|
|
// Setup:
|
|
// ... Create a request params that selects n-1 columns from the front and back
|
|
// ... Create a set of data to write
|
|
// ... Create a memory location to store the data
|
|
var requestParams = new SaveResultsAsCsvRequestParams
|
|
{
|
|
ColumnStartIndex = 1,
|
|
ColumnEndIndex = 2,
|
|
RowStartIndex = 0, // Including b/c it is required to be a "save selection"
|
|
RowEndIndex = 10,
|
|
IncludeHeaders = true // Including headers to test both column selection logic
|
|
};
|
|
List<DbCellValue> data = new List<DbCellValue>
|
|
{
|
|
new DbCellValue { DisplayValue = "item1" },
|
|
new DbCellValue { DisplayValue = "item2" },
|
|
new DbCellValue { DisplayValue = "item3" },
|
|
new DbCellValue { DisplayValue = "item4" }
|
|
};
|
|
List<DbColumnWrapper> columns = new List<DbColumnWrapper>
|
|
{
|
|
new DbColumnWrapper(new TestDbColumn("column1")),
|
|
new DbColumnWrapper(new TestDbColumn("column2")),
|
|
new DbColumnWrapper(new TestDbColumn("column3")),
|
|
new DbColumnWrapper(new TestDbColumn("column4"))
|
|
};
|
|
byte[] output = new byte[8192];
|
|
|
|
// If: I write a row
|
|
SaveAsCsvFileStreamWriter writer = new SaveAsCsvFileStreamWriter(new MemoryStream(output), requestParams);
|
|
using (writer)
|
|
{
|
|
writer.WriteRow(data, columns);
|
|
}
|
|
|
|
// Then:
|
|
// ... It should have written two lines
|
|
string outputString = Encoding.UTF8.GetString(output).TrimEnd('\0', '\r', '\n');
|
|
string[] lines = outputString.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
|
|
Assert.Equal(2, lines.Length);
|
|
|
|
// ... It should have written a header line with two, comma separated names
|
|
string[] headerValues = lines[0].Split(',');
|
|
Assert.Equal(2, headerValues.Length);
|
|
for (int i = 1; i <= 2; i++)
|
|
{
|
|
Assert.Equal(columns[i].ColumnName, headerValues[i-1]);
|
|
}
|
|
|
|
// ... The second line should have two, comma separated values
|
|
string[] dataValues = lines[1].Split(',');
|
|
Assert.Equal(2, dataValues.Length);
|
|
for (int i = 1; i <= 2; i++)
|
|
{
|
|
Assert.Equal(data[i].DisplayValue, dataValues[i-1]);
|
|
}
|
|
}
|
|
}
|
|
}
|