Skip to content

Commit

Permalink
Hacky solution to get tests working
Browse files Browse the repository at this point in the history
  • Loading branch information
mnbuhl committed Aug 15, 2024
1 parent b26272d commit a3176c9
Show file tree
Hide file tree
Showing 21 changed files with 158 additions and 63 deletions.
15 changes: 14 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,18 @@ services:
volumes:
- mysql:/var/lib/mysql

postgres:
image: postgres
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: secret
POSTGRES_DB: persistedcachedb
ports:
- "5432:5432"
volumes:
- postgres:/var/lib/postgresql/data

volumes:
mysql:
mysql:
postgres:
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\PersistedCache.MySql\PersistedCache.MySql.csproj" />
<ProjectReference Include="..\..\src\PersistedCache.PostgreSql\PersistedCache.PostgreSql.csproj" />
</ItemGroup>

</Project>
11 changes: 8 additions & 3 deletions examples/PersistedCache.Example/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
using PersistedCache;
using PersistedCache.MySql;
using PersistedCache.PostgreSql;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMySqlPersistedCache(builder.Configuration.GetConnectionString("MySql")!, options =>
// builder.Services.AddMySqlPersistedCache(builder.Configuration.GetConnectionString("MySql")!, options =>
// {
// options.TableName = "persisted_cache";
// });

builder.Services.AddPostgreSqlPersistedCache(builder.Configuration.GetConnectionString("PostgreSql")!, options =>
{
options.TableName = "persisted_cache";
});
Expand All @@ -28,7 +33,7 @@
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", (IPersistedCache cache) => cache.Get<int>("weather_forecast"))
app.MapGet("/weatherforecast", (IPersistedCache cache) => cache.Get<WeatherForecast[]>("weather_forecast"))
.WithName("GetWeatherForecast")
.WithOpenApi();

Expand Down
3 changes: 2 additions & 1 deletion examples/PersistedCache.Example/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
}
},
"ConnectionStrings": {
"MySql": "Server=localhost;Port=3306;Database=persistedcachedb;Uid=root;Pwd=root;"
"MySql": "Server=localhost;Port=3306;Database=persistedcachedb;Uid=root;Pwd=root;",
"PostgreSql": "Host=localhost;Port=5432;Database=persistedcachedb;User ID=postgres;Password=secret;"
}
}
12 changes: 6 additions & 6 deletions src/PersistedCache.MySql/MySqlCacheDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public MySqlCacheDriver(SqlPersistedCacheOptions options)
public string SetupStorageScript =>
/*lang=MySQL*/
$"""
CREATE TABLE IF NOT EXISTS {_options.TableName} (
CREATE TABLE IF NOT EXISTS `{_options.TableName}` (
`key` VARCHAR(255) NOT NULL PRIMARY KEY,
`value` JSON NOT NULL,
`expiry` DATETIME(6) NOT NULL,
Expand All @@ -31,23 +31,23 @@ public MySqlCacheDriver(SqlPersistedCacheOptions options)
/*lang=MySQL*/
$"""
SELECT `value`
FROM {_options.TableName}
FROM `{_options.TableName}`
WHERE `key` = @Key
AND `expiry` > @Expiry;
""";

public string SetScript =>
/*lang=MySQL*/
$"""
INSERT INTO {_options.TableName} (`key`, `value`, `expiry`)
INSERT INTO `{_options.TableName}` (`key`, `value`, `expiry`)
VALUES (@Key, @Value, @Expiry)
ON DUPLICATE KEY UPDATE `value` = @value, `expiry` = @expiry;
""";

public string ForgetScript =>
/*lang=MySQL*/
$"""
DELETE FROM {_options.TableName}
DELETE FROM `{_options.TableName}`
WHERE `key` = @Key;
""";

Expand All @@ -58,14 +58,14 @@ DELETE FROM {_options.TableName}
public string FlushPatternScript =>
/*lang=MySQL*/
$"""
DELETE FROM {_options.TableName}
DELETE FROM `{_options.TableName}`
WHERE `key` LIKE @Pattern;
""";

public string PurgeScript =>
/*lang=MySQL*/
$"""
DELETE FROM {_options.TableName}
DELETE FROM `{_options.TableName}`
WHERE `expiry` <= @Expiry;
""";

Expand Down
6 changes: 5 additions & 1 deletion src/PersistedCache.MySql/PersistedCache.MySql.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,14 @@
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<Optimize>true</Optimize>
</PropertyGroup>

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<ProjectReference Include="..\PersistedCache\PersistedCache.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="PersistedCache" Version="0.0.2" />
<PackageReference Include="MySql.Data" Version="9.0.0" />
<PackageReference Include="PersistedCache" Version="0.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
19 changes: 8 additions & 11 deletions src/PersistedCache.MySql/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,6 @@
"Microsoft.NETCore.Platforms": "1.1.0"
}
},
"PersistedCache": {
"type": "Direct",
"requested": "[0.0.1, )",
"resolved": "0.0.1",
"contentHash": "rzdPkRiuasUHk4Ft9Bw9Q0uGBuJgNt3gq52qn+P8k4Mx3CDbnnE5MZY7FQzKyNh4nsXEUlTX+ZJd42ncQGMw2A==",
"dependencies": {
"Dapper": "2.1.35",
"Microsoft.Extensions.Hosting.Abstractions": "6.0.0",
"System.Text.Json": "6.0.9"
}
},
"BouncyCastle.Cryptography": {
"type": "Transitive",
"resolved": "2.3.1",
Expand Down Expand Up @@ -373,6 +362,14 @@
"Microsoft.Bcl.AsyncInterfaces": "5.0.0",
"System.Memory": "4.5.5"
}
},
"persistedcache": {
"type": "Project",
"dependencies": {
"Dapper": "[2.1.35, )",
"Microsoft.Extensions.Hosting.Abstractions": "[6.0.0, )",
"System.Text.Json": "[6.0.9, )"
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,13 @@
<Optimize>true</Optimize>
</PropertyGroup>

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<ProjectReference Include="..\PersistedCache\PersistedCache.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Npgsql" Version="6.0.11" />
<PackageReference Include="PersistedCache" Version="0.0.1" />
<PackageReference Include="PersistedCache" Version="0.0.2" />
</ItemGroup>

<ItemGroup>
Expand Down
28 changes: 14 additions & 14 deletions src/PersistedCache.PostgreSql/PostgreSqlCacheDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ namespace PersistedCache.PostgreSql;

public class PostgreSqlCacheDriver : ISqlCacheDriver
{
private readonly SqlPersistedCacheOptions _options;
private readonly PostgreSqlPersistedCacheOptions _options;

public PostgreSqlCacheDriver(SqlPersistedCacheOptions options)
public PostgreSqlCacheDriver(ISqlPersistedCacheOptions options)
{
_options = options;
_options = (PostgreSqlPersistedCacheOptions)options;
}

public string SetupStorageScript =>
Expand All @@ -19,13 +19,13 @@ public PostgreSqlCacheDriver(SqlPersistedCacheOptions options)
DO
$$
BEGIN
CREATE TABLE IF NOT EXISTS "{_options.TableName}" (
CREATE TABLE IF NOT EXISTS "{_options.Schema}"."{_options.TableName}" (
"key" VARCHAR(255) NOT NULL PRIMARY KEY,
"value" JSONB NOT NULL,
"expiry" TIMESTAMP(6) WITH TIME ZONE NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_key_expiry ON "{_options.TableName}" ("key", "expiry");
CREATE INDEX IF NOT EXISTS idx_expiry ON "{_options.TableName}" ("expiry");
CREATE INDEX IF NOT EXISTS idx_key_expiry ON "{_options.Schema}"."{_options.TableName}" ("key", "expiry");
CREATE INDEX IF NOT EXISTS idx_expiry ON "{_options.Schema}"."{_options.TableName}" ("expiry");
END;
$$
""";
Expand All @@ -34,42 +34,42 @@ public PostgreSqlCacheDriver(SqlPersistedCacheOptions options)
/*lang=PostgreSQL*/
$"""
SELECT "value"
FROM "{_options.TableName}"
FROM "{_options.Schema}"."{_options.TableName}"
WHERE "key" = @Key
AND "expiry" > @Expiry;
""";

public string SetScript =>
/*lang=PostgreSQL*/
$"""
INSERT INTO "{_options.TableName}" ("key", "value", "expiry")
VALUES (@Key, to_json(@Value), @Expiry)
INSERT INTO "{_options.Schema}"."{_options.TableName}" ("key", "value", "expiry")
VALUES (@Key, cast(@Value as jsonb), @Expiry)
ON CONFLICT ("key") DO UPDATE
SET "value" = to_json(@Value), "expiry" = @Expiry;
SET "value" = cast(@Value as jsonb), "expiry" = @Expiry;
""";

public string ForgetScript =>
/*lang=PostgreSQL*/
$"""
DELETE FROM "{_options.TableName}"
DELETE FROM "{_options.Schema}"."{_options.TableName}"
WHERE "key" = @Key;
""";

public string FlushScript =>
/*lang=PostgreSQL*/
$"""DELETE FROM "{_options.TableName}";""";
$"""DELETE FROM "{_options.Schema}"."{_options.TableName}";""";

public string FlushPatternScript =>
/*lang=PostgreSQL*/
$"""
DELETE FROM "{_options.TableName}"
DELETE FROM "{_options.Schema}"."{_options.TableName}"
WHERE "key" ILIKE @Pattern;
""";

public string PurgeScript =>
/*lang=PostgreSQL*/
$"""
DELETE FROM "{_options.TableName}"
DELETE FROM "{_options.Schema}"."{_options.TableName}"
WHERE "expiry" <= @Expiry;
""";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static class PostgreSqlPersistedCacheExtensions
public static IServiceCollection AddPostgreSqlPersistedCache(this IServiceCollection services,
string connectionString)
{
return services.AddPostgreSqlPersistedCache(new SqlPersistedCacheOptions(connectionString));
return services.AddPostgreSqlPersistedCache(new PostgreSqlPersistedCacheOptions(connectionString));
}

/// <summary>
Expand All @@ -23,9 +23,9 @@ public static IServiceCollection AddPostgreSqlPersistedCache(this IServiceCollec
/// <param name="connectionString">Connection string to the PostgreSQL database.</param>
/// <param name="configure">Action to configure the cache options.</param>
public static IServiceCollection AddPostgreSqlPersistedCache(this IServiceCollection services,
string connectionString, Action<SqlPersistedCacheOptions> configure)
string connectionString, Action<PostgreSqlPersistedCacheOptions> configure)
{
var options = new SqlPersistedCacheOptions(connectionString);
var options = new PostgreSqlPersistedCacheOptions(connectionString);
configure(options);

return services.AddPostgreSqlPersistedCache(options);
Expand All @@ -37,9 +37,9 @@ public static IServiceCollection AddPostgreSqlPersistedCache(this IServiceCollec
/// <param name="services">Service collection.</param>
/// <param name="options">Options for the cache.</param>
public static IServiceCollection AddPostgreSqlPersistedCache(this IServiceCollection services,
SqlPersistedCacheOptions options)
PostgreSqlPersistedCacheOptions options)
{
services.AddSingleton(options);
services.AddSingleton<ISqlPersistedCacheOptions>(options);
services.AddSingleton<ISqlCacheDriver, PostgreSqlCacheDriver>();
services.AddSingleton<IPersistedCache, SqlPersistedCache>();

Expand Down
15 changes: 15 additions & 0 deletions src/PersistedCache.PostgreSql/PostgreSqlPersistedCacheOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using PersistedCache.Sql;

namespace PersistedCache.PostgreSql;

public class PostgreSqlPersistedCacheOptions : SqlPersistedCacheOptions
{
public PostgreSqlPersistedCacheOptions(string connectionString) : base(connectionString)
{
}

/// <summary>
/// The search path/schema to use for the cache (default: public).
/// </summary>
public string Schema { get; set; } = "public";
}
19 changes: 8 additions & 11 deletions src/PersistedCache.PostgreSql/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,6 @@
"System.Threading.Channels": "6.0.0"
}
},
"PersistedCache": {
"type": "Direct",
"requested": "[0.0.1, )",
"resolved": "0.0.1",
"contentHash": "rzdPkRiuasUHk4Ft9Bw9Q0uGBuJgNt3gq52qn+P8k4Mx3CDbnnE5MZY7FQzKyNh4nsXEUlTX+ZJd42ncQGMw2A==",
"dependencies": {
"Dapper": "2.1.35",
"Microsoft.Extensions.Hosting.Abstractions": "6.0.0",
"System.Text.Json": "6.0.9"
}
},
"Dapper": {
"type": "Transitive",
"resolved": "2.1.35",
Expand Down Expand Up @@ -204,6 +193,14 @@
"dependencies": {
"System.Runtime.CompilerServices.Unsafe": "4.5.3"
}
},
"persistedcache": {
"type": "Project",
"dependencies": {
"Dapper": "[2.1.35, )",
"Microsoft.Extensions.Hosting.Abstractions": "[6.0.0, )",
"System.Text.Json": "[6.0.9, )"
}
}
}
}
Expand Down
37 changes: 37 additions & 0 deletions src/PersistedCache/Sql/ISqlPersistedCacheOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Text.Json;

namespace PersistedCache.Sql;

public interface ISqlPersistedCacheOptions
{
/// <summary>
/// The name of the table to use for the cache.
/// </summary>
/// <exception cref="ArgumentException">Thrown when the table name is null or empty.</exception>
string TableName { get; set; }

/// <summary>
/// Whether to create the table if it does not exist.
/// </summary>
bool CreateTableIfNotExists { get; set; }

/// <summary>
/// The connection string to use for the cache.
/// </summary>
string ConnectionString { get; }

/// <summary>
/// Whether to purge expired entries.
/// </summary>
bool PurgeExpiredEntries { get; set; }

/// <summary>
/// The interval at which to purge expired entries.
/// </summary>
TimeSpan PurgeInterval { get; set; }

/// <summary>
/// The options to use for JSON serialization.
/// </summary>
JsonSerializerOptions JsonOptions { get; set; }
}
Loading

0 comments on commit a3176c9

Please sign in to comment.