pure sql baybeee

This commit is contained in:
ntr committed 2023-08-30 20:21:08 +10:00
1 parent b7ad479ead
commit 5a7e493d92
12 files changed
+173 -39

No files matched your search

+33 -6
View File
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
using Server.Services;
using SpaceRace.Shared;
namespace Server.Controllers;
@@ -10,10 +12,16 @@ namespace Server.Controllers;
public class LapController : ControllerBase {
private readonly ILogger<LapController> _logger;
private SpaceRaceDbContext _db;
private LapTimesService _lapTimes;
public LapController(ILogger<LapController> logger, SpaceRaceDbContext db) {
public LapController(
ILogger<LapController> logger,
SpaceRaceDbContext db,
LapTimesService lapTimes
){
_logger = logger;
_db = db;
_lapTimes = lapTimes;
}
[HttpGet()]
@@ -28,11 +36,25 @@ public class LapController : ControllerBase {
}
[HttpPost()]
public async Task<Lap> Post(LapDTO dto) {
public async Task<LapTimesDTO> Post(LapDTO dto) {
Lap existing = _db.Laps
.SingleOrDefault(l => l.UserId == dto.UserId && l.Map == dto.Map);
Lap v = new Lap {
Lap NotFaster(Lap e) {
_logger.LogInformation($"Lap was not a PB.");
return e;
}
Lap UpdateValues(Lap e) => new Lap {
Id = e.Id,
UserId = e.UserId,
Map = e.Map,
Time = dto.Time,
Sectors = dto.Sectors,
Created = DateTimeOffset.Now,
};
Lap Create() => new Lap {
Id = Guid.NewGuid(),
UserId = dto.UserId,
Map = dto.Map,
@@ -41,8 +63,13 @@ public class LapController : ControllerBase {
Created = DateTimeOffset.UtcNow,
};
_db.Laps.Add(v);
await _db.SaveChangesAsync();
return v;
Lap v = existing switch {
null => Create(),
Lap e when dto.Time < e.Time => UpdateValues(e),
_ => NotFaster(existing),
};
await _db.Laps.Upsert(v).RunAsync();
return _lapTimes.LapTimes(v.UserId, v.Map);
}
}
+10 -16
View File
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
using Server.Services;
using SpaceRace.Shared;
namespace Server.Controllers;
@@ -10,29 +12,21 @@ namespace Server.Controllers;
public class LapTimesController : ControllerBase {
private readonly ILogger<LapTimesController> _logger;
private SpaceRaceDbContext _db;
private LapTimesService _lapTimes;
public LapTimesController(ILogger<LapTimesController> logger, SpaceRaceDbContext db) {
public LapTimesController(
ILogger<LapTimesController> logger,
SpaceRaceDbContext db,
LapTimesService lapTimes
){
_logger = logger;
_db = db;
_lapTimes = lapTimes;
}
[HttpGet()]
public LapTimesDTO LapTimes(Guid userId, string mapName) {
_logger.LogInformation($"{userId} {mapName}");
PbDTO pb = _db.PbDTO
.Where(pb => pb.UserId == userId)
.Where(pb => pb.Map == mapName)
.SingleOrDefault();
PbDTO lapRecord = _db.PbDTO
.Where(pb => pb.Map == mapName)
.OrderBy(pb => pb.Position)
.FirstOrDefault();
return new LapTimesDTO {
Pb = pb,
LapRecord = lapRecord,
};
return _lapTimes.LapTimes(userId, mapName);
}
}
@@ -113,7 +113,7 @@ namespace Server.Migrations
b.ToTable((string)null);
b.ToSqlQuery("WITH ranked AS (\n SELECT *, rank() OVER (ORDER BY \"Time\" ASC) AS \"Position\", COUNT(\"Id\") OVER () AS \"Completions\"\n FROM \"Laps\"\n)\n\nSELECT * FROM ranked");
b.ToSqlQuery("SELECT *, rank() OVER (ORDER BY \"Time\" ASC) AS \"Position\", COUNT(\"Id\") OVER () AS \"Completions\"\n FROM \"Laps\"\n)\n\n");
});
#pragma warning restore 612, 618
}
+2
View File
@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Server;
using Server.Services;
var builder = WebApplication.CreateBuilder(args);
@@ -11,6 +12,7 @@ builder.Services.AddDbContextPool<SpaceRaceDbContext>(options => {
assembly => assembly.MigrationsAssembly(typeof(SpaceRaceDbContext).Assembly.FullName)
);
});
builder.Services.AddScoped<LapTimesService>();
var app = builder.Build();
+3 -11
View File
@@ -1,5 +1,7 @@
using System;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SpaceRace.Shared;
@@ -14,19 +16,8 @@ public class SpaceRaceDbContext : DbContext {
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
new SpaceRaceInitialiser(modelBuilder).Seed();
var pbQuery = $$"""
WITH ranked AS (
SELECT *, rank() OVER (ORDER BY "Time" ASC) AS "Position", COUNT("Id") OVER () AS "Completions"
FROM "Laps"
)
SELECT * FROM ranked
""";
modelBuilder.Entity<PbDTO>()
.HasNoKey()
.ToSqlQuery(pbQuery)
.ToTable(null as string);
}
}
@@ -34,6 +25,7 @@ public class SpaceRaceDbContext : DbContext {
[Index(nameof(UserId), nameof(Map), IsUnique = true)]
[Index(nameof(Map))]
public class Lap {
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public Guid UserId { get; set; }
[Required] public DateTimeOffset Created { get; set; }
+1
View File
@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+43
View File
@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore;
using SpaceRace.Shared;
namespace Server.Services;
public class LapTimesService {
private readonly ILogger<LapTimesService> _logger;
private SpaceRaceDbContext _db;
public LapTimesService(ILogger<LapTimesService> logger, SpaceRaceDbContext db) {
_logger = logger;
_db = db;
}
public LapTimesDTO LapTimes(Guid userId, string mapName) {
PbDTO pb = _db.PbDTO
.FromSql($$"""
WITH ranked AS (
SELECT *, rank() OVER (ORDER BY "Time" ASC) AS "Position", COUNT("Id") OVER () AS "Completions"
FROM "Laps"
WHERE "Map" = {{mapName}}
ORDER BY "Position" ASC
)
SELECT * FROM ranked
WHERE "UserId" = {{userId}}
""").FirstOrDefault();
PbDTO lapRecord = _db.PbDTO
.FromSql($$"""
SELECT *, rank() OVER (ORDER BY "Time" ASC) AS "Position", COUNT("Id") OVER () AS "Completions"
FROM "Laps"
WHERE "Map" = {{mapName}}
ORDER BY "Position" ASC
""").FirstOrDefault();
return new LapTimesDTO {
Pb = pb,
LapRecord = lapRecord,
};
}
}