mirror of
https://github.com/ckaczor/sqltoolsservice.git
synced 2026-01-14 01:25:40 -05:00
This is a very large change. I'll try to outline what's going on.
1. This adds the **EditDataService** which manages editing **Sessions**.
1. Each session has a **ResultSet** (from the QueryExecutionService) which has the rows of the table and basic metadata about the columns
2. Each session also has an **IEditTableMetadata** implementation which is derived from SMO metadata which provides more in-depth and trustworthy data about the table than SqlClient alone can.
3. Each session holds a list of **RowEditBase** abstract class implementations
1. **RowUpdate** - Update cells in a row (generates `UPDATE` statement)
2. **RowDelete** - Delete an entire row (generates `DELETE` statement)
3. **RowCreate** - Add a new row (generates `INSERT INTO` statement)
4. Row edits have a collection of **CellUpdates** that hold updates for individual cells (except for RowDelete)
1. Cell updates are generated from text
5. RowEditBase offers some baseline functionality
1. Generation of `WHERE` clauses (which can be parameterized)
2. Validation of whether a column can be updated
2. New API Actions
1. edit/initialize - Queries for the contents of a table/view, builds SMO metadata, sets up a session
2. edit/createRow - Adds a new RowCreate to the Session
3. edit/deleteRow - Adds a new RowDelete to the Session
4. edit/updateCell - Adds a CellUpdate to a RowCreate or RowUpdate in the Session
5. edit/revertRow - Removes a RowCreate, RowDelete, or RowUpdate from the Session
6. edit/script - Generates a script for the changes in the Session and stores to disk
7. edit/dispose - Removes a Session and releases the query
3. Smaller updates (unit test mock improvements, tweaks to query execution service)
**There are more updates planned -- this is just to get eyeballs on the main body of code**
* Initial stubs for edit data service
* Stubbing out update management code
* Adding rudimentary dispose request
* More stubbing out of update row code
* Adding complete edit command contracts, stubbing out request handlers
* Adding basic implementation of get script
* More in progress work to implement base of row edits
* More in progress work to implement base of row edits
* Adding string => object conversion logic and various cleanup
* Adding a formatter for using values in scripts
* Splitting IMessageSender into IEventSender and IRequestSender
* Adding inter-service method for executing queries
* Adding inter-service method for disposing of a query
* Changing edit contract to include the object to edit
* Fully fleshing out edit session initialization
* Generation of delete scripts is working
* Adding scripter for update statements
* Adding scripting functionality for INSERT statements
* Insert, Update, and Delete all working with SMO metadata
* Polishing for SqlScriptFormatter
* Unit tests and reworked byte[] conversion
* Replacing the awful and inflexible Dictionary<string, string>[][] with a much better test data set class
* Fixing syntax error in generated UPDATE statements
* Adding unit tests for RowCreate
* Adding tests for the row edit base class
* Adding row delete tests
* Adding RowUpdate tests, validation for number of key columns
* Adding tests for the unit class
* Adding get script tests for the session
* Service integration tests, except initialization tests
* Service integration tests, except initialization tests
* Adding messages to sr.strings
* Adding messages to sr.strings
* Fixing broken unit tests
* Adding factory pattern for SMO metadata provider
* Copyright and other comments
* Addressing first round of comments
* Refactoring EditDataService to have a single method for handling
session-dependent operations
* Refactoring Edit Data contracts to inherit from a Session and Row
operation params base class
* Copyright additions
* Small tweak to strings
* Updated unit tests to test the refactors
* More revisions as per pull request comments
382 lines
14 KiB
C#
382 lines
14 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.Data.Common;
|
|
using System.IO;
|
|
using Microsoft.SqlTools.ServiceLayer.Connection;
|
|
using Microsoft.SqlTools.ServiceLayer.EditData;
|
|
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
|
|
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
|
|
using Microsoft.SqlTools.ServiceLayer.SqlContext;
|
|
using Microsoft.SqlTools.ServiceLayer.Test.Common;
|
|
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
|
|
using Moq;
|
|
using Xunit;
|
|
|
|
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
|
|
{
|
|
public class SessionTests
|
|
{
|
|
#region Construction Tests
|
|
|
|
[Fact]
|
|
public void SessionConstructionNullQuery()
|
|
{
|
|
// If: I create a session object without a null query
|
|
// Then: It should throw an exception
|
|
Assert.Throws<ArgumentNullException>(() => new Session(null, Common.GetMetadata(new DbColumn[] {})));
|
|
}
|
|
|
|
[Fact]
|
|
public void SessionConstructionNullMetadataProvider()
|
|
{
|
|
// If: I create a session object without a null metadata provider
|
|
// Then: It should throw an exception
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
Assert.Throws<ArgumentNullException>(() => new Session(rs, null));
|
|
}
|
|
|
|
[Fact]
|
|
public void SessionConstructionValid()
|
|
{
|
|
// If: I create a session object with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// Then:
|
|
// ... The edit cache should exist and be empty
|
|
Assert.NotNull(s.EditCache);
|
|
Assert.Empty(s.EditCache);
|
|
|
|
// ... The next row ID should be equivalent to the number of rows in the result set
|
|
Assert.Equal(q.Batches[0].ResultSets[0].RowCount, s.NextRowId);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Validate Tests
|
|
|
|
[Fact]
|
|
public void SessionValidateUnfinishedQuery()
|
|
{
|
|
// If: I create a session object with a query that hasn't finished execution
|
|
// Then: It should throw an exception
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
q.HasExecuted = false;
|
|
Assert.Throws<InvalidOperationException>(() => Session.ValidateQueryForSession(q));
|
|
}
|
|
|
|
[Fact]
|
|
public void SessionValidateIncorrectResultSet()
|
|
{
|
|
// Setup: Create a query that yields >1 result sets
|
|
TestResultSet[] results =
|
|
{
|
|
QueryExecution.Common.StandardTestResultSet,
|
|
QueryExecution.Common.StandardTestResultSet
|
|
};
|
|
|
|
// @TODO: Fix when the connection service is fixed
|
|
ConnectionInfo ci = QueryExecution.Common.CreateConnectedConnectionInfo(results, false);
|
|
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
|
|
|
|
var fsf = QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
|
|
Query query = new Query(QueryExecution.Common.StandardQuery, ci, new QueryExecutionSettings(), fsf);
|
|
query.Execute();
|
|
query.ExecutionTask.Wait();
|
|
|
|
// If: I create a session object with a query that has !=1 result sets
|
|
// Then: It should throw an exception
|
|
Assert.Throws<InvalidOperationException>(() => Session.ValidateQueryForSession(query));
|
|
}
|
|
|
|
[Fact]
|
|
public void SessionValidateValidResultSet()
|
|
{
|
|
// If: I validate a query for a session with a valid query
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = Session.ValidateQueryForSession(q);
|
|
|
|
// Then: I should get the only result set back
|
|
Assert.NotNull(rs);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Create Row Tests
|
|
|
|
[Fact]
|
|
public void CreateRowAddFailure()
|
|
{
|
|
// NOTE: This scenario should theoretically never occur, but is tested for completeness
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
|
|
var mockEdit = new Mock<RowEditBase>().Object;
|
|
s.EditCache[rs.RowCount] = mockEdit;
|
|
|
|
// If: I create a row in the session
|
|
// Then:
|
|
// ... An exception should be thrown
|
|
Assert.Throws<InvalidOperationException>(() => s.CreateRow());
|
|
|
|
// ... The mock edit should still exist
|
|
Assert.Equal(mockEdit, s.EditCache[rs.RowCount]);
|
|
|
|
// ... The next row ID should not have changes
|
|
Assert.Equal(rs.RowCount, s.NextRowId);
|
|
}
|
|
|
|
[Fact]
|
|
public void CreateRowSuccess()
|
|
{
|
|
// Setup: Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I add a row to the session
|
|
long newId = s.CreateRow();
|
|
|
|
// Then:
|
|
// ... The new ID should be equal to the row count
|
|
Assert.Equal(rs.RowCount, newId);
|
|
|
|
// ... The next row ID should have been incremented
|
|
Assert.Equal(rs.RowCount + 1, s.NextRowId);
|
|
|
|
// ... There should be a new row create object in the cache
|
|
Assert.Contains(newId, s.EditCache.Keys);
|
|
Assert.IsType<RowCreate>(s.EditCache[newId]);
|
|
}
|
|
|
|
#endregion
|
|
|
|
[Theory]
|
|
[MemberData(nameof(RowIdOutOfRangeData))]
|
|
public void RowIdOutOfRange(long rowId, Action<Session, long> testAction)
|
|
{
|
|
// Setup: Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I delete a row that is out of range for the result set
|
|
// Then: I should get an exception
|
|
Assert.Throws<ArgumentOutOfRangeException>(() => testAction(s, rowId));
|
|
}
|
|
|
|
public static IEnumerable<object> RowIdOutOfRangeData
|
|
{
|
|
get
|
|
{
|
|
// Delete Row
|
|
Action<Session, long> delAction = (s, l) => s.DeleteRow(l);
|
|
yield return new object[] { -1L, delAction };
|
|
yield return new object[] { 100L, delAction };
|
|
|
|
// Update Cell
|
|
Action<Session, long> upAction = (s, l) => s.UpdateCell(l, 0, null);
|
|
yield return new object[] { -1L, upAction };
|
|
yield return new object[] { 100L, upAction };
|
|
}
|
|
}
|
|
|
|
#region Delete Row Tests
|
|
|
|
[Fact]
|
|
public void DeleteRowAddFailure()
|
|
{
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
|
|
var mockEdit = new Mock<RowEditBase>().Object;
|
|
s.EditCache[0] = mockEdit;
|
|
|
|
// If: I delete a row in the session
|
|
// Then:
|
|
// ... An exception should be thrown
|
|
Assert.Throws<InvalidOperationException>(() => s.DeleteRow(0));
|
|
|
|
// ... The mock edit should still exist
|
|
Assert.Equal(mockEdit, s.EditCache[0]);
|
|
}
|
|
|
|
[Fact]
|
|
public void DeleteRowSuccess()
|
|
{
|
|
// Setup: Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I add a row to the session
|
|
s.DeleteRow(0);
|
|
|
|
// Then: There should be a new row delete object in the cache
|
|
Assert.Contains(0, s.EditCache.Keys);
|
|
Assert.IsType<RowDelete>(s.EditCache[0]);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Revert Row Tests
|
|
|
|
[Fact]
|
|
public void RevertRowOutOfRange()
|
|
{
|
|
// Setup: Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I revert a row that doesn't have any pending changes
|
|
// Then: I should get an exception
|
|
Assert.Throws<ArgumentOutOfRangeException>(() => s.RevertRow(0));
|
|
}
|
|
|
|
[Fact]
|
|
public void RevertRowSuccess()
|
|
{
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
|
|
var mockEdit = new Mock<RowEditBase>().Object;
|
|
s.EditCache[0] = mockEdit;
|
|
|
|
// If: I revert the row that has a pending update
|
|
s.RevertRow(0);
|
|
|
|
// Then:
|
|
// ... The edit cache should not contain a pending edit for the row
|
|
Assert.DoesNotContain(0, s.EditCache.Keys);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Update Cell Tests
|
|
|
|
[Fact]
|
|
public void UpdateCellExisting()
|
|
{
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
|
|
var mockEdit = new Mock<RowEditBase>();
|
|
mockEdit.Setup(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>()));
|
|
s.EditCache[0] = mockEdit.Object;
|
|
|
|
// If: I update a cell on a row that already has a pending edit
|
|
s.UpdateCell(0, 0, null);
|
|
|
|
// Then:
|
|
// ... The mock update should still be in the cache
|
|
// ... And it should have had set cell called on it
|
|
Assert.Contains(mockEdit.Object, s.EditCache.Values);
|
|
}
|
|
|
|
[Fact]
|
|
public void UpdateCellNew()
|
|
{
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I update a cell on a row that does not have a pending edit
|
|
s.UpdateCell(0, 0, "");
|
|
|
|
// Then:
|
|
// ... A new update row edit should have been added to the cache
|
|
Assert.Contains(0, s.EditCache.Keys);
|
|
Assert.IsType<RowUpdate>(s.EditCache[0]);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Script Edits Tests
|
|
|
|
[Theory]
|
|
[InlineData(null)]
|
|
[InlineData("")]
|
|
[InlineData(" \t\r\n")]
|
|
public void ScriptNullOrEmptyOutput(string outputPath)
|
|
{
|
|
// Setup: Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// If: I try to script the edit cache with a null or whitespace output path
|
|
// Then: It should throw an exception
|
|
Assert.Throws<ArgumentNullException>(() => s.ScriptEdits(outputPath));
|
|
}
|
|
|
|
[Fact]
|
|
public void ScriptProvidedOutputPath()
|
|
{
|
|
// Setup:
|
|
// ... Create a session with a proper query and metadata
|
|
Query q = QueryExecution.Common.GetBasicExecutedQuery();
|
|
ResultSet rs = q.Batches[0].ResultSets[0];
|
|
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
|
|
Session s = new Session(rs, etm);
|
|
|
|
// ... Add two mock edits that will generate a script
|
|
Mock<RowEditBase> edit = new Mock<RowEditBase>();
|
|
edit.Setup(e => e.GetScript()).Returns("test");
|
|
s.EditCache[0] = edit.Object;
|
|
s.EditCache[1] = edit.Object;
|
|
|
|
using (SelfCleaningTempFile file = new SelfCleaningTempFile())
|
|
{
|
|
// If: I script the edit cache to a local output path
|
|
string outputPath = s.ScriptEdits(file.FilePath);
|
|
|
|
// Then:
|
|
// ... The output path used should be the same as the one we provided
|
|
Assert.Equal(file.FilePath, outputPath);
|
|
|
|
// ... The written file should have two lines, one for each edit
|
|
Assert.Equal(2, File.ReadAllLines(outputPath).Length);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|