예제 #1
0
        public async void SaveResultsAsCsvExceptionTest()
        {
            // Execute a query
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await Common.AwaitExecution(queryService, executeParams, executeRequest.Object);

            // Request to save the results as csv with incorrect filepath
            var saveParams = new SaveResultsAsCsvRequestParams
            {
                OwnerUri       = Common.OwnerUri,
                ResultSetIndex = 0,
                BatchIndex     = 0,
                FilePath       = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "G:\\test.csv" : "/test.csv"
            };

            SaveResultRequestError errMessage = null;
            var saveRequest = GetSaveResultsContextMock(null, err => errMessage = (SaveResultRequestError)err);

            // Call save results and wait on the save task
            await queryService.HandleSaveResultsAsCsvRequest(saveParams, saveRequest.Object);

            ResultSet selectedResultSet = queryService.ActiveQueries[saveParams.OwnerUri].Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex];
            await selectedResultSet.GetSaveTask(saveParams.FilePath);

            // Expect to see error message
            VerifySaveResultsCallCount(saveRequest, Times.Never(), Times.Once());
            Assert.NotNull(errMessage);
            Assert.False(File.Exists(saveParams.FilePath));
        }
예제 #2
0
 void HQuery_QueryExecute(QueryExecuteParams obj)
 {
     if (m_visible)
     {
         MainWindow.Instance.RunInMainWindow(ReloadData);
     }
 }
예제 #3
0
        public async void QueryExecuteInProgressTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a query
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            // Note, we don't care about the results of the first request
            var firstRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null);
            await Common.AwaitExecution(queryService, queryParams, firstRequestContext.Object);

            // ... And then I request another query without waiting for the first to complete
            queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false;   // Simulate query hasn't finished
            object error = null;
            var    secondRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                          .AddErrorHandling(e => error = e);
            await Common.AwaitExecution(queryService, queryParams, secondRequestContext.Object);

            // Then:
            // ... An error should have been sent
            // ... A result should have not have been sent
            // ... No completion event should have been fired
            // ... A batch completion event should have fired, but not a resultset event
            // ... There should only be one active query
            VerifyQueryExecuteCallCount(secondRequestContext, Times.Never(), Times.AtMostOnce(), Times.AtMostOnce(), Times.AtMostOnce(), Times.Never(), Times.Once());
            Assert.IsType <string>(error);
            Assert.NotEmpty((string)error);
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
예제 #4
0
        private static async Task AwaitExecution(QueryExecutionService service, QueryExecuteParams qeParams,
                                                 RequestContext <QueryExecuteResult> requestContext)
        {
            await service.HandleExecuteRequest(qeParams, requestContext);

            await service.ActiveQueries[qeParams.OwnerUri].ExecutionTask;
        }
예제 #5
0
        public async void SubsetServiceOutOfRangeSubsetTest()
        {
            // If:
            // ... I have a query that doesn't have any result sets
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And I then ask for a set of results from it
            var subsetParams = new QueryExecuteSubsetParams {
                OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            QueryExecuteSubsetResult result = null;
            var subsetRequest = GetQuerySubsetResultContextMock(qesr => result = qesr, null);

            queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object).Wait();

            // Then:
            // ... I should get an error result
            // ... There should not be rows
            // ... There should not be any error calls
            VerifyQuerySubsetCallCount(subsetRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Message);
            Assert.Null(result.ResultSubset);
        }
예제 #6
0
        public async Task QueryExecuteMissingSelectionTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(string.Empty);

            // If:
            // ... I request to execute a query with a missing query string
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = null
            };

            object errorResult    = null;
            var    requestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                    .AddErrorHandling(error => errorResult = error);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);


            // Then:
            // ... Am error should have been sent
            // ... No result should have been sent
            // ... No completion events should have been fired
            // ... An active query should not have been added
            VerifyQueryExecuteCallCount(requestContext, Times.Never(), Times.Never(), Times.Never(), Times.Never(), Times.Never(), Times.Once());
            Assert.NotNull(errorResult);
            Assert.IsType <string>(errorResult);
            Assert.DoesNotContain(Common.OwnerUri, queryService.ActiveQueries.Keys);

            // ... There should not be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
예제 #7
0
        public async void QueryExecuteUnconnectedUriTest()
        {
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();
            // If:
            // ... I request to execute a query using a file URI that isn't connected
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), false, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                OwnerUri = "notConnected", QuerySelection = Common.WholeDocument
            };

            object error          = null;
            var    requestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                    .AddErrorHandling(e => error = e);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            // Then:
            // ... An error should have been returned
            // ... No result should have been returned
            // ... No completion event should have been fired
            // ... There should be no active queries
            VerifyQueryExecuteCallCount(requestContext, Times.Never(), Times.Never(), Times.Once());
            Assert.IsType <string>(error);
            Assert.NotEmpty((string)error);
            Assert.Empty(queryService.ActiveQueries);
        }
예제 #8
0
 public void OnQueryExecute(QueryExecuteParams ep)
 {
     lock (this)
     {
         try
         {
             if (!m_cleared && QueryHistorySettings.Page.DeleteAfterDays > 0)
             {
                 int tm = (DateTime.Now - TimeSpan.FromDays(QueryHistorySettings.Page.DeleteAfterDays)).GetUnixTimestamp();
                 Connection.ExecuteNonQuery("delete from QueryExecute where ExecutedAtTimestamp < @p1", tm);
                 Connection.ExecuteNonQuery("delete from QueryText where not exists (select * from QueryExecute where QueryExecute.QueryText_ID = QueryText.ID)");
                 m_cleared = true;
             }
             if (QueryHistorySettings.Page.UseQueryHistory)
             {
                 int    hash   = ep.Sql.GetHashCode();
                 string codeid = Connection.ExecuteScalar("select ID from QueryText where HashCode=@p1", hash).SafeToString();
                 if (String.IsNullOrEmpty(codeid))
                 {
                     Connection.ExecuteScalar("insert into QueryText (QueryText, HashCode) values (@p1, @p2)", ep.Sql, hash);
                     codeid = Connection.GetInsertId().ToString();
                 }
                 Connection.ExecuteNonQuery(
                     "insert into QueryExecute (ExecutedAt, ExecutedAtTimestamp, Dialect, QueryText_ID, DbServer, DbName, QueryContext, FileName, DurationInMilisecs) values "
                     + "(@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9)", ep.ExecutedAt.ToString("s"), ep.ExecutedAt.GetUnixTimestamp(), ep.Dialect.DialectName, codeid, ep.DbServer, ep.DbName, ep.QueryContext, ep.FileName, ep.DurationInMilisecs);
             }
         }
         catch (Exception err)
         {
             Logging.Warning("Error saving query to history:" + err.Message);
         }
     }
 }
예제 #9
0
        public async Task SubsetServiceUnexecutedQueryTest()
        {
            // If:
            // ... I have a query that hasn't finished executing (doesn't matter what)
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            queryService.ActiveQueries[Common.OwnerUri].Batches[0].ResultSets[0].hasBeenRead = false;

            // ... And I then ask for a valid set of results from it
            var subsetParams = new QueryExecuteSubsetParams {
                OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            QueryExecuteSubsetResult result = null;
            var subsetRequest = GetQuerySubsetResultContextMock(qesr => result = qesr, null);
            await queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object);

            // Then:
            // ... I should get an error result
            // ... There should not be rows
            // ... There should not be any error calls
            VerifyQuerySubsetCallCount(subsetRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Message);
            Assert.Null(result.ResultSubset);
        }
예제 #10
0
        public async Task ServiceDispose()
        {
            // Setup:
            // ... We need a workspace service that returns a file
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // ... We need a query service
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true,
                                                                      workspaceService.Object);

            // If:
            // ... I execute some bogus query
            var queryParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And it sticks around as an active query
            Assert.Equal(1, queryService.ActiveQueries.Count);

            // ... The query execution service is disposed, like when the service is shutdown
            queryService.Dispose();

            // Then:
            // ... There should no longer be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
예제 #11
0
        public async void QueryExecuteSingleBatchSingleResultTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a valid query with results
            var queryService = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            QueryExecuteResult                  result               = null;
            QueryExecuteCompleteParams          completeParams       = null;
            QueryExecuteBatchNotificationParams batchStartParams     = null;
            QueryExecuteBatchNotificationParams batchCompleteParams  = null;
            QueryExecuteResultSetCompleteParams resultCompleteParams = null;
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                 .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, p) => completeParams                = p)
                                 .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStartParams            = p)
                                 .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchCompleteParams      = p)
                                 .AddEventHandling(QueryExecuteResultSetCompleteEvent.Type, (et, p) => resultCompleteParams = p);
            await Common.AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No errors should have been sent
            // ... A successful result should have been sent without messages
            // ... A completion event should have been fired with one result
            // ... A batch completion event should have been fired
            // ... A resultset completion event should have been fired
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never());
            Assert.Null(result.Messages);

            Assert.Equal(1, completeParams.BatchSummaries.Length);
            Assert.NotEmpty(completeParams.BatchSummaries[0].ResultSetSummaries);
            Assert.NotEmpty(completeParams.BatchSummaries[0].Messages);
            Assert.False(completeParams.BatchSummaries[0].HasError);

            // ... Batch start summary should not contain result sets, messages, but should contain owner URI
            Assert.NotNull(batchStartParams);
            Assert.NotNull(batchStartParams.BatchSummary);
            Assert.Null(batchStartParams.BatchSummary.Messages);
            Assert.Null(batchStartParams.BatchSummary.ResultSetSummaries);
            Assert.Equal(Common.OwnerUri, batchStartParams.OwnerUri);

            Assert.NotNull(batchCompleteParams);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.ResultSetSummaries);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.Messages);
            Assert.Equal(Common.OwnerUri, batchCompleteParams.OwnerUri);

            Assert.NotNull(resultCompleteParams);
            Assert.Equal(Common.StandardColumns, resultCompleteParams.ResultSetSummary.ColumnInfo.Length);
            Assert.Equal(Common.StandardRows, resultCompleteParams.ResultSetSummary.RowCount);
            Assert.Equal(Common.OwnerUri, resultCompleteParams.OwnerUri);

            // ... There should be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
        public async Task HandleExecuteRequest(QueryExecuteParams executeParams,
                                               RequestContext <QueryExecuteResult> requestContext)
        {
            // Get a query new active query
            Query newQuery = await CreateAndActivateNewQuery(executeParams, requestContext);

            // Execute the query -- asynchronously
            await ExecuteAndCompleteQuery(executeParams, requestContext, newQuery);
        }
예제 #13
0
        public async void QueryExecuteSingleBatchNoResultsTest()
        {
            // Given:
            // ... Default settings are stored in the workspace service
            // ... A workspace with a standard query is configured
            WorkspaceService <SqlToolsSettings> .Instance.CurrentSettings = new SqlToolsSettings();
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a valid query with no results
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };

            QueryExecuteResult                  result              = null;
            QueryExecuteCompleteParams          completeParams      = null;
            QueryExecuteBatchNotificationParams batchStartParams    = null;
            QueryExecuteBatchNotificationParams batchCompleteParams = null;
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                 .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, p) => completeParams           = p)
                                 .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStartParams       = p)
                                 .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchCompleteParams = p)
                                 .AddEventHandling(QueryExecuteResultSetCompleteEvent.Type, null);
            await Common.AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No Errors should have been sent
            // ... A successful result should have been sent with messages on the first batch
            // ... A completion event should have been fired with empty results
            // ... A batch completion event should have been fired with empty results
            // ... A result set completion event should not have been fired
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never(), Times.Never());
            Assert.Null(result.Messages);

            Assert.Equal(1, completeParams.BatchSummaries.Length);
            Assert.Empty(completeParams.BatchSummaries[0].ResultSetSummaries);
            Assert.NotEmpty(completeParams.BatchSummaries[0].Messages);

            // ... Batch start summary should not contain result sets, messages, but should contain owner URI
            Assert.NotNull(batchStartParams);
            Assert.NotNull(batchStartParams.BatchSummary);
            Assert.Null(batchStartParams.BatchSummary.Messages);
            Assert.Null(batchStartParams.BatchSummary.ResultSetSummaries);
            Assert.Equal(Common.OwnerUri, batchStartParams.OwnerUri);

            // ... Batch completion summary should contain result sets, messages, and the owner URI
            Assert.NotNull(batchCompleteParams);
            Assert.NotNull(batchCompleteParams.BatchSummary);
            Assert.Empty(batchCompleteParams.BatchSummary.ResultSetSummaries);
            Assert.NotEmpty(batchCompleteParams.BatchSummary.Messages);
            Assert.Equal(Common.OwnerUri, batchCompleteParams.OwnerUri);

            // ... There should be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
예제 #14
0
        public static async Task AwaitExecution(QueryExecutionService service, QueryExecuteParams qeParams,
                                                RequestContext <QueryExecuteResult> requestContext)
        {
            await service.HandleExecuteRequest(qeParams, requestContext);

            if (service.ActiveQueries.ContainsKey(qeParams.OwnerUri) && service.ActiveQueries[qeParams.OwnerUri].ExecutionTask != null)
            {
                await service.ActiveQueries[qeParams.OwnerUri].ExecutionTask;
            }
        }
예제 #15
0
        /// <summary>
        /// Run a query using a given connection bound to a URI. This method only waits for the initial response from query
        /// execution (QueryExecuteResult). It is up to the caller to wait for the QueryExecuteCompleteEvent if they are interested.
        /// </summary>
        public async Task <QueryExecuteResult> RunQueryAsync(string ownerUri, string query, int timeoutMilliseconds = 5000)
        {
            WriteToFile(ownerUri, query);

            var queryParams = new QueryExecuteParams
            {
                OwnerUri       = ownerUri,
                QuerySelection = null
            };

            return(await Driver.SendRequest(QueryExecuteRequest.Type, queryParams));
        }
예제 #16
0
        public async void SaveResultsAsCsvWithSelectionSuccessTest()
        {
            // Execute a query
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, Common.GetPrimedWorkspaceService());

            var executeParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // Request to save the results as csv with correct parameters
            var saveParams = new SaveResultsAsCsvRequestParams
            {
                OwnerUri         = Common.OwnerUri,
                ResultSetIndex   = 0,
                BatchIndex       = 0,
                FilePath         = "testwrite_2.csv",
                IncludeHeaders   = true,
                RowStartIndex    = 0,
                RowEndIndex      = 0,
                ColumnStartIndex = 0,
                ColumnEndIndex   = 0
            };
            SaveResultRequestResult result = null;
            var saveRequest = GetSaveResultsContextMock(qcr => result = qcr, null);

            queryService.ActiveQueries[Common.OwnerUri].Batches[0] = Common.GetBasicExecutedBatch();

            // Call save results and wait on the save task
            await queryService.HandleSaveResultsAsCsvRequest(saveParams, saveRequest.Object);

            ResultSet selectedResultSet = queryService.ActiveQueries[saveParams.OwnerUri].Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex];
            Task      saveTask          = selectedResultSet.GetSaveTask(saveParams.FilePath);
            await     saveTask;

            // Expect to see a file successfully created in filepath and a success message
            Assert.Null(result.Messages);
            Assert.True(File.Exists(saveParams.FilePath));
            VerifySaveResultsCallCount(saveRequest, Times.Once(), Times.Never());

            // Delete temp file after test
            if (File.Exists(saveParams.FilePath))
            {
                File.Delete(saveParams.FilePath);
            }
        }
예제 #17
0
        public async void QueryExecuteValidNoResultsTest()
        {
            // Given:
            // ... Default settings are stored in the workspace service
            WorkspaceService <SqlToolsSettings> .Instance.CurrentSettings = new SqlToolsSettings();

            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // If:
            // ... I request to execute a valid query with no results
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };

            QueryExecuteResult         result         = null;
            QueryExecuteCompleteParams completeParams = null;
            var requestContext =
                RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(
                    resultCallback: qer => result = qer,
                    expectedEvent: QueryExecuteCompleteEvent.Type,
                    eventCallback: (et, cp) => completeParams = cp,
                    errorCallback: null);

            await AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No Errors should have been sent
            // ... A successful result should have been sent with messages on the first batch
            // ... A completion event should have been fired with empty results
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Never());
            Assert.Null(result.Messages);
            Assert.Equal(1, completeParams.BatchSummaries.Length);
            Assert.Empty(completeParams.BatchSummaries[0].ResultSetSummaries);
            Assert.NotEmpty(completeParams.BatchSummaries[0].Messages);

            // ... There should be one active query
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
예제 #18
0
        public async void QueryExecuteInvalidQueryTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a query that is invalid
            var queryService = Common.GetPrimedExecutionService(null, true, true, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            QueryExecuteResult                  result        = null;
            QueryExecuteCompleteParams          complete      = null;
            QueryExecuteBatchNotificationParams batchStart    = null;
            QueryExecuteBatchNotificationParams batchComplete = null;
            var requestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                 .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, qecp) => complete        = qecp)
                                 .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStart       = p)
                                 .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchComplete = p);
            await Common.AwaitExecution(queryService, queryParams, requestContext.Object);

            // Then:
            // ... No errors should have been sent
            // ... A result should have been sent with success (we successfully started the query)
            // ... A completion event (query, batch, not resultset) should have been sent with error
            VerifyQueryExecuteCallCount(requestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never(), Times.Never());
            Assert.Null(result.Messages);

            Assert.Equal(1, complete.BatchSummaries.Length);
            Assert.True(complete.BatchSummaries[0].HasError);
            Assert.NotEmpty(complete.BatchSummaries[0].Messages);

            Assert.NotNull(batchStart);
            Assert.False(batchStart.BatchSummary.HasError);
            Assert.Null(batchStart.BatchSummary.Messages);
            Assert.Null(batchStart.BatchSummary.ResultSetSummaries);
            Assert.Equal(Common.OwnerUri, batchStart.OwnerUri);

            Assert.NotNull(batchComplete);
            Assert.True(batchComplete.BatchSummary.HasError);
            Assert.NotEmpty(batchComplete.BatchSummary.Messages);
            Assert.Equal(Common.OwnerUri, batchComplete.OwnerUri);
        }
예제 #19
0
        public async void CancelInProgressQueryTest()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.Setup(file => file.GetLinesInRange(It.IsAny <BufferRange>()))
            .Returns(new[] { Common.StandardQuery });
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);

            // If:
            // ... I request a query (doesn't matter what kind) and execute it
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var executeParams = new QueryExecuteParams {
                QuerySelection = Common.GetSubSectionDocument(), OwnerUri = Common.OwnerUri
            };
            var executeRequest =
                RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(null, QueryExecuteCompleteEvent.Type, null, null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false;    // Fake that it hasn't completed execution

            // ... And then I request to cancel the query
            var cancelParams = new QueryCancelParams {
                OwnerUri = Common.OwnerUri
            };
            QueryCancelResult result = null;
            var cancelRequest        = GetQueryCancelResultContextMock(qcr => result = qcr, null);

            queryService.HandleCancelRequest(cancelParams, cancelRequest.Object).Wait();

            // Then:
            // ... I should have seen a successful event (no messages)
            VerifyQueryCancelCallCount(cancelRequest, Times.Once(), Times.Never());
            Assert.Null(result.Messages);

            // ... The query should not have been disposed
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
        private static async Task ExecuteAndCompleteQuery(QueryExecuteParams executeParams, RequestContext <QueryExecuteResult> requestContext, Query query)
        {
            // Skip processing if the query is null
            if (query == null)
            {
                return;
            }

            // Setup the query completion/failure callbacks
            Query.QueryAsyncEventHandler callback = async q =>
            {
                // Send back the results
                QueryExecuteCompleteParams eventParams = new QueryExecuteCompleteParams
                {
                    OwnerUri       = executeParams.OwnerUri,
                    BatchSummaries = q.BatchSummaries
                };
                await requestContext.SendEvent(QueryExecuteCompleteEvent.Type, eventParams);
            };

            Query.QueryAsyncErrorEventHandler errorCallback = async errorMessage =>
            {
                // Send back the error message
                QueryExecuteCompleteParams eventParams = new QueryExecuteCompleteParams
                {
                    OwnerUri = executeParams.OwnerUri,
                    Message  = errorMessage
                };
                await requestContext.SendEvent(QueryExecuteCompleteEvent.Type, eventParams);
            };

            query.QueryCompleted           += callback;
            query.QueryFailed              += callback;
            query.QueryConnectionException += errorCallback;

            // Launch this as an asynchronous task
            query.Execute();

            // Send back a result showing we were successful
            await requestContext.SendResult(new QueryExecuteResult
            {
                Messages = null
            });
        }
예제 #21
0
        public async void SubsetServiceUnexecutedQueryTest()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // If:
            // ... I have a query that hasn't finished executing (doesn't matter what)
            var queryService = await Common.GetPrimedExecutionService(
                Common.CreateMockFactory(new[] { Common.StandardTestData }, false), true,
                workspaceService.Object);

            var executeParams = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false;

            // ... And I then ask for a valid set of results from it
            var subsetParams = new QueryExecuteSubsetParams {
                OwnerUri = Common.OwnerUri, RowsCount = 1, ResultSetIndex = 0, RowsStartIndex = 0
            };
            QueryExecuteSubsetResult result = null;
            var subsetRequest = GetQuerySubsetResultContextMock(qesr => result = qesr, null);

            queryService.HandleResultSubsetRequest(subsetParams, subsetRequest.Object).Wait();

            // Then:
            // ... I should get an error result
            // ... There should not be rows
            // ... There should not be any error calls
            VerifyQuerySubsetCallCount(subsetRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Message);
            Assert.Null(result.ResultSubset);
        }
예제 #22
0
        public async void QueryExecuteCompletedTest()
        {
            // Given:
            // ... A workspace with a standard query is configured
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);

            // If:
            // ... I request to execute a query
            var queryService = Common.GetPrimedExecutionService(null, true, false, workspaceService);
            var queryParams  = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            // Note, we don't care about the results of the first request
            var firstRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null);
            await Common.AwaitExecution(queryService, queryParams, firstRequestContext.Object);

            // ... And then I request another query after waiting for the first to complete
            QueryExecuteResult                  result        = null;
            QueryExecuteCompleteParams          complete      = null;
            QueryExecuteBatchNotificationParams batchStart    = null;
            QueryExecuteBatchNotificationParams batchComplete = null;
            var secondRequestContext = RequestContextMocks.Create <QueryExecuteResult>(qer => result = qer)
                                       .AddEventHandling(QueryExecuteCompleteEvent.Type, (et, qecp) => complete        = qecp)
                                       .AddEventHandling(QueryExecuteBatchStartEvent.Type, (et, p) => batchStart       = p)
                                       .AddEventHandling(QueryExecuteBatchCompleteEvent.Type, (et, p) => batchComplete = p);
            await Common.AwaitExecution(queryService, queryParams, secondRequestContext.Object);

            // Then:
            // ... No errors should have been sent
            // ... A result should have been sent with no errors
            // ... There should only be one active query
            // ... A batch completion event should have fired, but not a result set completion event
            VerifyQueryExecuteCallCount(secondRequestContext, Times.Once(), Times.Once(), Times.Once(), Times.Once(), Times.Never(), Times.Never());
            Assert.Null(result.Messages);

            Assert.False(complete.BatchSummaries.Any(b => b.HasError));
            Assert.Equal(1, queryService.ActiveQueries.Count);

            Assert.NotNull(batchStart);
            Assert.NotNull(batchComplete);
            Assert.False(batchComplete.BatchSummary.HasError);
            Assert.Equal(complete.OwnerUri, batchComplete.OwnerUri);
        }
예제 #23
0
        public async void SaveResultsAsJsonWithSelectionSuccessTest()
        {
            // Execute a query
            var workspaceService = Common.GetPrimedWorkspaceService(Common.StandardQuery);
            var queryService     = Common.GetPrimedExecutionService(new[] { Common.StandardTestData }, true, false, workspaceService);
            var executeParams    = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await Common.AwaitExecution(queryService, executeParams, executeRequest.Object);

            // Request to save the results as json with correct parameters
            var saveParams = new SaveResultsAsJsonRequestParams
            {
                OwnerUri         = Common.OwnerUri,
                ResultSetIndex   = 0,
                BatchIndex       = 0,
                FilePath         = "testwrite_5.json",
                RowStartIndex    = 0,
                RowEndIndex      = 1,
                ColumnStartIndex = 0,
                ColumnEndIndex   = 1
            };
            SaveResultRequestResult result = null;
            var saveRequest = GetSaveResultsContextMock(qcr => result = qcr, null);

            // Call save results and wait on the save task
            await queryService.HandleSaveResultsAsJsonRequest(saveParams, saveRequest.Object);

            ResultSet selectedResultSet = queryService.ActiveQueries[saveParams.OwnerUri].Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex];
            await selectedResultSet.GetSaveTask(saveParams.FilePath);

            // Expect to see a file successfully created in filepath and a success message
            VerifySaveResultsCallCount(saveRequest, Times.Once(), Times.Never());
            Assert.Null(result.Messages);
            Assert.True(File.Exists(saveParams.FilePath));

            // Delete temp file after test
            if (File.Exists(saveParams.FilePath))
            {
                File.Delete(saveParams.FilePath);
            }
        }
예제 #24
0
        public async void QueryExecuteInProgressTest()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);

            // If:
            // ... I request to execute a query
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            // Note, we don't care about the results of the first request
            var firstRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null);

            await AwaitExecution(queryService, queryParams, firstRequestContext.Object);

            // ... And then I request another query without waiting for the first to complete
            queryService.ActiveQueries[Common.OwnerUri].HasExecuted = false;   // Simulate query hasn't finished
            object error = null;
            var    secondRequestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                          .AddErrorHandling(e => error = e);

            await AwaitExecution(queryService, queryParams, secondRequestContext.Object);

            // Then:
            // ... An error should have been sent
            // ... A result should have not have been sent
            // ... No completion event should have been fired
            // ... The original query should exist
            VerifyQueryExecuteCallCount(secondRequestContext, Times.Never(), Times.Never(), Times.Once());
            Assert.IsType <string>(error);
            Assert.NotEmpty((string)error);
            Assert.Contains(Common.OwnerUri, queryService.ActiveQueries.Keys);
        }
예제 #25
0
        public async void QueryExecuteCompletedTest()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);

            // If:
            // ... I request to execute a query
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = Common.WholeDocument
            };

            // Note, we don't care about the results of the first request
            var firstRequestContext = RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(null, QueryExecuteCompleteEvent.Type, null, null);

            await AwaitExecution(queryService, queryParams, firstRequestContext.Object);

            // ... And then I request another query after waiting for the first to complete
            QueryExecuteResult         result   = null;
            QueryExecuteCompleteParams complete = null;
            var secondRequestContext            =
                RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(qer => result = qer, QueryExecuteCompleteEvent.Type, (et, qecp) => complete = qecp, null);

            await AwaitExecution(queryService, queryParams, secondRequestContext.Object);

            // Then:
            // ... No errors should have been sent
            // ... A result should have been sent with no errors
            // ... There should only be one active query
            VerifyQueryExecuteCallCount(secondRequestContext, Times.Once(), Times.Once(), Times.Never());
            Assert.Null(result.Messages);
            Assert.False(complete.BatchSummaries.Any(b => b.HasError));
            Assert.Equal(1, queryService.ActiveQueries.Count);
        }
예제 #26
0
        public async void DisposeExecutedQuery()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns("doesn't matter");
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // If:
            // ... I request a query (doesn't matter what kind)
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var executeParams = new QueryExecuteParams {
                QuerySelection = null, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(null, QueryExecuteCompleteEvent.Type, null, null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And then I dispose of the query
            var disposeParams = new QueryDisposeParams {
                OwnerUri = Common.OwnerUri
            };
            QueryDisposeResult result = null;
            var disposeRequest        = GetQueryDisposeResultContextMock(qdr => {
                result = qdr;
            }, null);

            queryService.HandleDisposeRequest(disposeParams, disposeRequest.Object).Wait();

            // Then:
            // ... I should have seen a successful result
            // ... And the active queries should be empty
            VerifyQueryDisposeCallCount(disposeRequest, Times.Once(), Times.Never());
            Assert.Null(result.Messages);
            Assert.Empty(queryService.ActiveQueries);
        }
예제 #27
0
        public async void SaveResultsAsJsonExceptionTest()
        {
            // Execute a query
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, Common.GetPrimedWorkspaceService());

            var executeParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest = RequestContextMocks.Create <QueryExecuteResult>(null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // Request to save the results as json with incorrect filepath
            var saveParams = new SaveResultsAsJsonRequestParams
            {
                OwnerUri       = Common.OwnerUri,
                ResultSetIndex = 0,
                BatchIndex     = 0,
                FilePath       = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "G:\\test.json" : "/test.json"
            };


            SaveResultRequestError errMessage = null;
            var saveRequest = GetSaveResultsContextMock(null, err => errMessage = (SaveResultRequestError)err);

            queryService.ActiveQueries[Common.OwnerUri].Batches[0] = Common.GetBasicExecutedBatch();

            // Call save results and wait on the save task
            await queryService.HandleSaveResultsAsJsonRequest(saveParams, saveRequest.Object);

            ResultSet selectedResultSet = queryService.ActiveQueries[saveParams.OwnerUri].Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex];
            Task      saveTask          = selectedResultSet.GetSaveTask(saveParams.FilePath);
            await     saveTask;

            // Expect to see error message
            Assert.NotNull(errMessage);
            VerifySaveResultsCallCount(saveRequest, Times.Never(), Times.Once());
            Assert.False(File.Exists(saveParams.FilePath));
        }
예제 #28
0
        public async void CancelExecutedQueryTest()
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns(Common.StandardQuery);
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // If:
            // ... I request a query (doesn't matter what kind) and wait for execution
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var executeParams = new QueryExecuteParams {
                QuerySelection = Common.WholeDocument, OwnerUri = Common.OwnerUri
            };
            var executeRequest =
                RequestContextMocks.SetupRequestContextMock <QueryExecuteResult, QueryExecuteCompleteParams>(null, QueryExecuteCompleteEvent.Type, null, null);
            await queryService.HandleExecuteRequest(executeParams, executeRequest.Object);

            await queryService.ActiveQueries[Common.OwnerUri].ExecutionTask;

            // ... And then I request to cancel the query
            var cancelParams = new QueryCancelParams {
                OwnerUri = Common.OwnerUri
            };
            QueryCancelResult result = null;
            var cancelRequest        = GetQueryCancelResultContextMock(qcr => result = qcr, null);
            await queryService.HandleCancelRequest(cancelParams, cancelRequest.Object);

            // Then:
            // ... I should have seen a result event with an error message
            VerifyQueryCancelCallCount(cancelRequest, Times.Once(), Times.Never());
            Assert.NotNull(result.Messages);

            // ... The query should not have been disposed
            Assert.NotEmpty(queryService.ActiveQueries);
        }
예제 #29
0
        public async Task QueryExecuteMissingSelectionTest(SelectionData selection)
        {
            // Set up file for returning the query
            var fileMock = new Mock <ScriptFile>();

            fileMock.SetupGet(file => file.Contents).Returns("");
            // Set up workspace mock
            var workspaceService = new Mock <WorkspaceService <SqlToolsSettings> >();

            workspaceService.Setup(service => service.Workspace.GetFile(It.IsAny <string>()))
            .Returns(fileMock.Object);
            // If:
            // ... I request to execute a query with a missing query string
            var queryService = await Common.GetPrimedExecutionService(Common.CreateMockFactory(null, false), true, workspaceService.Object);

            var queryParams = new QueryExecuteParams {
                OwnerUri = Common.OwnerUri, QuerySelection = selection
            };

            object errorResult    = null;
            var    requestContext = RequestContextMocks.Create <QueryExecuteResult>(null)
                                    .AddErrorHandling(error => errorResult = error);
            await queryService.HandleExecuteRequest(queryParams, requestContext.Object);

            // Then:
            // ... Am error should have been sent
            // ... No result should have been sent
            // ... No completion event should have been fired
            // ... An active query should not have been added
            VerifyQueryExecuteCallCount(requestContext, Times.Never(), Times.Never(), Times.Once());
            Assert.NotNull(errorResult);
            Assert.IsType <string>(errorResult);
            Assert.DoesNotContain(Common.OwnerUri, queryService.ActiveQueries.Keys);

            // ... There should not be an active query
            Assert.Empty(queryService.ActiveQueries);
        }
        public async Task CancelQueryOnPremTest()
        {
            TestServerType serverType = TestServerType.OnPrem;

            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
                using (TestHelper testHelper = new TestHelper())
                {
                    await Common.ConnectAsync(testHelper, serverType, Scripts.DelayQuery, queryTempFile.FilePath, Common.PerfTestDatabaseName);

                    var queryParams = new QueryExecuteParams
                    {
                        OwnerUri       = queryTempFile.FilePath,
                        QuerySelection = null
                    };

                    var result = await testHelper.Driver.SendRequest(QueryExecuteRequest.Type, queryParams);

                    if (result != null && string.IsNullOrEmpty(result.Messages))
                    {
                        TestTimer timer = new TestTimer()
                        {
                            PrintResult = true
                        };
                        await Common.ExecuteWithTimeout(timer, 100000, async() =>
                        {
                            var cancelQueryResult = await testHelper.CancelQuery(queryTempFile.FilePath);
                            return(true);
                        }, TimeSpan.FromMilliseconds(10));
                    }
                    else
                    {
                        Assert.True(false, "Failed to run the query");
                    }

                    await testHelper.Disconnect(queryTempFile.FilePath);
                }
        }