Skip to content
This repository has been archived by the owner on Aug 2, 2024. It is now read-only.

Commit

Permalink
(#616) Provided logging capability within the SQLite Store. (#618)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianhall authored Feb 17, 2023
1 parent 8c4ce4a commit 474b0ad
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 5 deletions.
6 changes: 3 additions & 3 deletions sdk/dotnet/Datasync.Framework.sln
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Datasy
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Datasync.Swashbuckle.Test", "test\Microsoft.AspNetCore.Datasync.Swashbuckle.Test\Microsoft.AspNetCore.Datasync.Swashbuckle.Test.csproj", "{3ECDBFF9-B5DF-4D39-81C1-FBD1D471CC03}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Datasync.NSwag", "src\Microsoft.AspNetCore.Datasync.NSwag\Microsoft.AspNetCore.Datasync.NSwag.csproj", "{1D1F6B46-CE89-4277-81F5-4D4B614B7060}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Datasync.NSwag", "src\Microsoft.AspNetCore.Datasync.NSwag\Microsoft.AspNetCore.Datasync.NSwag.csproj", "{1D1F6B46-CE89-4277-81F5-4D4B614B7060}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNetCore.Datasync.NSwag.Test", "test\Microsoft.AspNetCore.Datasync.NSwag.Test\Microsoft.AspNetCore.Datasync.NSwag.Test.csproj", "{CCA3A587-0060-4D71-BCFE-30477F408EE6}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Datasync.NSwag.Test", "test\Microsoft.AspNetCore.Datasync.NSwag.Test\Microsoft.AspNetCore.Datasync.NSwag.Test.csproj", "{CCA3A587-0060-4D71-BCFE-30477F408EE6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -175,7 +175,7 @@ Global
{05FD004E-D69F-4E38-A561-B87B27815BF6} = {897BFB53-D437-4D6F-A581-DF708C560545}
{94F09CBD-6B48-48CE-8B32-E3A80E13962A} = {1675CF58-54FE-474F-80AD-8E494662F2A4}
{3ECDBFF9-B5DF-4D39-81C1-FBD1D471CC03} = {897BFB53-D437-4D6F-A581-DF708C560545}
{1D1F6B46-CE89-4277-81F5-4D4B614B7060} = {4AD0B95F-AAF4-4E0A-95F1-111D71A92533}
{1D1F6B46-CE89-4277-81F5-4D4B614B7060} = {1675CF58-54FE-474F-80AD-8E494662F2A4}
{CCA3A587-0060-4D71-BCFE-30477F408EE6} = {897BFB53-D437-4D6F-A581-DF708C560545}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.4" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
using Microsoft.Datasync.Client.SQLiteStore.Utils;
using Microsoft.Datasync.Client.Table;
using Microsoft.Datasync.Client.Utils;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -55,11 +57,34 @@ public OfflineSQLiteStore(string connectionString)
DbConnection = new SqliteConnection(connectionString);
}

/// <summary>
/// Creates a new instance of <see cref="OfflineSQLiteStore"/> using the provided connection string.
/// </summary>
/// <remarks>
/// <para>If the connection string starts with <c>file:</c>, then it is considered to be a URI filename and
/// should be structured as such. This allows the setting of any options (such as mode, cache, etc.)
/// if needed.</para>
/// <para>If the connection string does not start with file:, then it should be an absolute path (which starts
/// with a <c>/</c>).</para>
/// </remarks>
/// <see href="https://sqlite.org/c3ref/open.html"/>
/// <param name="connectionString">The connection string to use for persistent storage.</param>
/// <param name="logger">The logger to use for logging SQL requests.</param>
public OfflineSQLiteStore(string connectionString, ILogger logger) : this(connectionString)
{
Logger = logger;
}

/// <summary>
/// The database connection.
/// </summary>
internal SqliteConnection DbConnection { get; }

/// <summary>
/// The logging service
/// </summary>
public ILogger Logger { get; set; }

#region AbstractOfflineStore
/// <summary>
/// Defines the local table in the persistent store.
Expand All @@ -73,6 +98,7 @@ public override void DefineTable(string tableName, JObject tableDefinition)

if (!tableMap.ContainsKey(tableName))
{
Logger?.LogDebug("Created table definition for table {tableName}", tableName);
tableMap.Add(tableName, new TableDefinition(tableName, tableDefinition));
}
}
Expand Down Expand Up @@ -395,11 +421,12 @@ protected void CreateTableFromDefinition(TableDefinition tableDefinition)
/// </summary>
/// <param name="sqlStatement">The SQL statement to execute.</param>
/// <param name="parameters">The parameters that are referenced in the SQL statement.</param>
protected void ExecuteNonQueryInternal(string sqlStatement, Dictionary<string, object> parameters = null)
protected void ExecuteNonQueryInternal(string sqlStatement, IDictionary<string, object> parameters = null)
{
Arguments.IsNotNullOrWhitespace(sqlStatement, nameof(sqlStatement));
parameters ??= new();
parameters ??= new Dictionary<string, object>();

LogSqlStatement(sqlStatement, parameters);
using SqliteStatement stmt = DbConnection.PrepareStatement(sqlStatement);
stmt.BindParameters(parameters);
stmt.ExecuteNonQuery();
Expand Down Expand Up @@ -437,6 +464,7 @@ protected IList<JObject> ExecuteQueryInternal(TableDefinition tableDefinition, s
Arguments.IsNotNullOrWhitespace(sqlStatement, nameof(sqlStatement));
parameters ??= new Dictionary<string, object>();

LogSqlStatement(sqlStatement, parameters);
var rows = new List<JObject>();
using var statement = DbConnection.PrepareStatement(sqlStatement);
statement.BindParameters(parameters);
Expand Down Expand Up @@ -474,6 +502,23 @@ private TableDefinition GetTableOrThrow(string tableName)
throw new InvalidOperationException($"Table '{tableName}' is not defined.");
}

/// <summary>
/// Logs a SQL execution to the logging service.
/// </summary>
/// <param name="sqlStatement">The SQL Statement</param>
/// <param name="parameters">The List of parameters</param>
private void LogSqlStatement(string sqlStatement, IDictionary<string, object> parameters)
{
// Early return.
if (Logger == null) return;

Logger?.LogDebug("SQL STMT: {sqlStatement}", sqlStatement);
if (parameters.Count > 0)
{
Logger?.LogDebug("SQL PARAMS: {params}", string.Join(";", parameters.ToList().Select(x => $"{x.Key}={x.Value}")));
}
}

/// <summary>
/// Dispose of the database connection.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.Datasync.Client.Offline;
using Microsoft.Datasync.Client.SQLiteStore;
using Microsoft.Datasync.Integration.Test.Helpers;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
Expand Down Expand Up @@ -118,5 +120,32 @@ public async Task KS4_WriteDeltaTokenInterval()
var entities = await offlineTable.Where(x => x.IntValue > 0).ToListAsync();
Assert.Equal(50, entities.Count);
}

[Fact]
public async Task KS5_CanLogSqlStatements()
{
// Set up logger
var logger = new Mock<ILogger<OfflineSQLiteStore>>();
logger.Setup(x => x.Log(It.IsAny<LogLevel>(), It.IsAny<EventId>(), It.IsAny<object>(), It.IsAny<Exception>(), It.IsAny<Func<object, Exception?, string>>()));
store.Logger = logger.Object;

// On client 1
KitchenSinkDto client1dto = new() { StringValue = "This is a string" };
await remoteTable.InsertItemAsync(client1dto);
var remoteId = client1dto.Id;
Assert.NotEmpty(remoteId);

// On client 2
await InitializeAsync();
var pullQuery = offlineTable!.CreateQuery();
await offlineTable!.PullItemsAsync(pullQuery, new PullOptions());
var client2dto = await offlineTable.GetItemAsync(remoteId);
Assert.NotNull(client2dto);
Assert.Equal("This is a string", client2dto.StringValue);

// Check log statements here
Assert.True(logger.Invocations.Count > 0);

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.13" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Xunit.Combinatorial" Version="1.5.25" />
Expand Down

0 comments on commit 474b0ad

Please sign in to comment.