Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix null ref in persistence service #65646

Merged
merged 3 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServices.UnitTests;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
Expand Down Expand Up @@ -870,6 +873,46 @@ public async Task PersistentService_ReadByteTwice(Size size, bool withChecksum,
}
}

[Theory, CombinatorialData]
public async Task TestPersistSyntaxTreeIndex([CombinatorialRange(0, Iterations)] int iteration)
{
_ = iteration;
var solution = CreateOrOpenSolution();
var id = DocumentId.CreateNewId(solution.Projects.Single().Id);
solution = solution.AddDocument(id, "file.cs", "class C { void M() }", filePath: @"c:\temp\file.cs");

var document = solution.GetRequiredDocument(id);

await using (var storage = await GetStorageAsync(solution))
{
var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, default);
await index.SaveAsync(_storageService!, document, default);

var index2 = await SyntaxTreeIndex.LoadAsync(_storageService!, DocumentKey.ToDocumentKey(document), checksum: null, new StringTable(), default);
Assert.NotNull(index2);
}
}

[Theory, CombinatorialData]
public async Task TestPersistTopLevelSyntaxTreeIndex([CombinatorialRange(0, Iterations)] int iteration)
{
_ = iteration;
var solution = CreateOrOpenSolution();
var id = DocumentId.CreateNewId(solution.Projects.Single().Id);
solution = solution.AddDocument(id, "file.cs", "class C { void M() }", filePath: @"c:\temp\file.cs");

var document = solution.GetRequiredDocument(id);

await using (var storage = await GetStorageAsync(solution))
{
var index = await TopLevelSyntaxTreeIndex.GetRequiredIndexAsync(document, default);
await index.SaveAsync(_storageService!, document, default);

var index2 = await TopLevelSyntaxTreeIndex.LoadAsync(_storageService!, DocumentKey.ToDocumentKey(document), checksum: null, new StringTable(), default);
Assert.NotNull(index2);
}
}

private static void DoSimultaneousReads(Func<Task<string>> read, string expectedValue)
{
var barrier = new Barrier(NumThreads);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,13 @@ internal partial class AbstractSyntaxIndex<TIndex> : IObjectWritable

// attempt to load from persisted state
using var stream = await storage.ReadStreamAsync(documentKey, s_persistenceName, checksum, cancellationToken).ConfigureAwait(false);
using var gzipStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true);
using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken);
if (reader != null)
return read(stringTable, reader, checksum);
if (stream != null)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stream can be null when no data is stored. didn't test the 'load first then save' scenario.

{
using var gzipStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true);
using var reader = ObjectReader.TryGetReader(gzipStream, cancellationToken: cancellationToken);
if (reader != null)
return read(stringTable, reader, checksum);
}
}
catch (Exception e) when (IOUtilities.IsNormalIOException(e))
{
Expand Down Expand Up @@ -119,11 +122,18 @@ internal partial class AbstractSyntaxIndex<TIndex> : IObjectWritable
return (textChecksum, textAndDirectivesChecksum);
}

private async Task<bool> SaveAsync(
private Task<bool> SaveAsync(
Document document, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;
var persistentStorageService = solution.Services.GetPersistentStorageService();
return SaveAsync(persistentStorageService, document, cancellationToken);
}

public async Task<bool> SaveAsync(
IChecksummedPersistentStorageService persistentStorageService, Document document, CancellationToken cancellationToken)
{
var solution = document.Project.Solution;

try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ internal sealed partial class SQLitePersistentStorage : AbstractPersistentStorag

private readonly string _insert_into_string_table_values_0 = $"insert into {StringInfoTableName}({DataColumnName}) values (?)";
private readonly string _select_star_from_string_table_where_0_limit_one = $"select * from {StringInfoTableName} where ({DataColumnName} = ?) limit 1";
private readonly string _select_star_from_string_table = $"select * from {StringInfoTableName}";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not, remove as well

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will do!


private SQLitePersistentStorage(
SQLiteConnectionPoolService connectionPoolService,
Expand Down Expand Up @@ -189,6 +190,8 @@ private void Initialize(SqlConnection connection, CancellationToken cancellation
EnsureTables(connection, Database.Main);
EnsureTables(connection, Database.WriteCache);

LoadExistingStringIds(connection);
CyrusNajmabadi marked this conversation as resolved.
Show resolved Hide resolved

return;

void EnsureTables(SqlConnection connection, Database database)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,5 +170,29 @@ private int InsertStringIntoDatabase_MustRunInTransaction(SqlConnection connecti
// So how could we then not find the string in the table?
throw new InvalidOperationException();
}

private void LoadExistingStringIds(SqlConnection connection)
{
try
{
using var resettableStatement = connection.GetResettableStatement(_select_star_from_string_table);
var statement = resettableStatement.Statement;

Result stepResult;
while ((stepResult = statement.Step()) == Result.ROW)
{
var id = statement.GetInt32At(columnIndex: 0);
var value = statement.GetStringAt(columnIndex: 1);
_stringToIdMap.TryAdd(value, id);
}
}
catch (Exception ex)
{
// If we simply failed to even talk to the DB then we have to bail out. There's
// nothing we can accomplish at this point.
StorageDatabaseLogger.LogException(ex);
return;
}
}
}
}