pure sql baybeee

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

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Server/bin/Debug/net7.0/Server.dll",
"args": [],
"cwd": "${workspaceFolder}/Server",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"dotnet.defaultSolution": "Server/Server.sln"
}
+41
View File
@@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Server/Server.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Server/Server.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/Server/Server.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
+1 -1
View File
@@ -75,7 +75,7 @@ public class LapService {
Created = DateTimeOffset.UtcNow, Created = DateTimeOffset.UtcNow,
}; };
Debug.Log(JsonConvert.SerializeObject(dto)); Debug.Log($"Posting lap: {JsonConvert.SerializeObject(dto)}");
using (UnityWebRequest req = UnityWebRequest.Post("localhost:40080/Lap", JsonConvert.SerializeObject(dto), "application/json")) { using (UnityWebRequest req = UnityWebRequest.Post("localhost:40080/Lap", JsonConvert.SerializeObject(dto), "application/json")) {
yield return req.SendWebRequest(); yield return req.SendWebRequest();
+33 -6
View File
@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient; using System.Data.SqlClient;
using Server.Services;
using SpaceRace.Shared; using SpaceRace.Shared;
namespace Server.Controllers; namespace Server.Controllers;
@@ -10,10 +12,16 @@ namespace Server.Controllers;
public class LapController : ControllerBase { public class LapController : ControllerBase {
private readonly ILogger<LapController> _logger; private readonly ILogger<LapController> _logger;
private SpaceRaceDbContext _db; private SpaceRaceDbContext _db;
private LapTimesService _lapTimes;
public LapController(ILogger<LapController> logger, SpaceRaceDbContext db) { public LapController(
ILogger<LapController> logger,
SpaceRaceDbContext db,
LapTimesService lapTimes
){
_logger = logger; _logger = logger;
_db = db; _db = db;
_lapTimes = lapTimes;
} }
[HttpGet()] [HttpGet()]
@@ -28,11 +36,25 @@ public class LapController : ControllerBase {
} }
[HttpPost()] [HttpPost()]
public async Task<Lap> Post(LapDTO dto) { public async Task<LapTimesDTO> Post(LapDTO dto) {
Lap existing = _db.Laps Lap existing = _db.Laps
.SingleOrDefault(l => l.UserId == dto.UserId && l.Map == dto.Map); .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(), Id = Guid.NewGuid(),
UserId = dto.UserId, UserId = dto.UserId,
Map = dto.Map, Map = dto.Map,
@@ -41,8 +63,13 @@ public class LapController : ControllerBase {
Created = DateTimeOffset.UtcNow, Created = DateTimeOffset.UtcNow,
}; };
_db.Laps.Add(v); Lap v = existing switch {
await _db.SaveChangesAsync(); null => Create(),
return v; 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.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient; using System.Data.SqlClient;
using Server.Services;
using SpaceRace.Shared; using SpaceRace.Shared;
namespace Server.Controllers; namespace Server.Controllers;
@@ -10,29 +12,21 @@ namespace Server.Controllers;
public class LapTimesController : ControllerBase { public class LapTimesController : ControllerBase {
private readonly ILogger<LapTimesController> _logger; private readonly ILogger<LapTimesController> _logger;
private SpaceRaceDbContext _db; private SpaceRaceDbContext _db;
private LapTimesService _lapTimes;
public LapTimesController(ILogger<LapTimesController> logger, SpaceRaceDbContext db) { public LapTimesController(
ILogger<LapTimesController> logger,
SpaceRaceDbContext db,
LapTimesService lapTimes
){
_logger = logger; _logger = logger;
_db = db; _db = db;
_lapTimes = lapTimes;
} }
[HttpGet()] [HttpGet()]
public LapTimesDTO LapTimes(Guid userId, string mapName) { public LapTimesDTO LapTimes(Guid userId, string mapName) {
_logger.LogInformation($"{userId} {mapName}"); _logger.LogInformation($"{userId} {mapName}");
return _lapTimes.LapTimes(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,
};
} }
} }
@@ -113,7 +113,7 @@ namespace Server.Migrations
b.ToTable((string)null); 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 #pragma warning restore 612, 618
} }
+2
View File
@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Server; using Server;
using Server.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -11,6 +12,7 @@ builder.Services.AddDbContextPool<SpaceRaceDbContext>(options => {
assembly => assembly.MigrationsAssembly(typeof(SpaceRaceDbContext).Assembly.FullName) assembly => assembly.MigrationsAssembly(typeof(SpaceRaceDbContext).Assembly.FullName)
); );
}); });
builder.Services.AddScoped<LapTimesService>();
var app = builder.Build(); var app = builder.Build();
+3 -11
View File
@@ -1,5 +1,7 @@
using System;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SpaceRace.Shared; using SpaceRace.Shared;
@@ -14,19 +16,8 @@ public class SpaceRaceDbContext : DbContext {
protected override void OnModelCreating(ModelBuilder modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
new SpaceRaceInitialiser(modelBuilder).Seed(); 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>() modelBuilder.Entity<PbDTO>()
.HasNoKey() .HasNoKey()
.ToSqlQuery(pbQuery)
.ToTable(null as string); .ToTable(null as string);
} }
} }
@@ -34,6 +25,7 @@ public class SpaceRaceDbContext : DbContext {
[Index(nameof(UserId), nameof(Map), IsUnique = true)] [Index(nameof(UserId), nameof(Map), IsUnique = true)]
[Index(nameof(Map))] [Index(nameof(Map))]
public class Lap { public class Lap {
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; } public Guid Id { get; set; }
public Guid UserId { get; set; } public Guid UserId { get; set; }
[Required] public DateTimeOffset Created { get; set; } [Required] public DateTimeOffset Created { get; set; }
+1
View File
@@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.10"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <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,
};
}
}
-4
View File
@@ -2,10 +2,6 @@
- post times to server - post times to server
- update on scene change - update on scene change
- check time is lower when posting
- return pb and lap record
- convert laps to lapDTO?
- include sectors
- controls - controls
- mouse / controller sens - mouse / controller sens