Skip to content

Commit

Permalink
Convert OrmLite APIs to use sync (for SQLite)
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Aug 19, 2024
1 parent 383d295 commit 44cc15f
Show file tree
Hide file tree
Showing 47 changed files with 353 additions and 360 deletions.
8 changes: 4 additions & 4 deletions MyApp.ServiceInterface/AdminServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ public async Task<object> Any(AdminResetCommonPassword request)
throw HttpError.NotFound("Post not found");

var refId = $"{request.Id}";
await Db.SaveAsync(post);
var statTotal = await Db.SingleAsync(Db.From<StatTotals>().Where(x => x.Id == refId));
Db.Save(post);
var statTotal = Db.Single(Db.From<StatTotals>().Where(x => x.Id == refId));
if (statTotal != null)
{
await Db.InsertAsync(new StatTotals
Db.Insert(new StatTotals
{
Id = refId,
PostId = post.Id,
Expand All @@ -121,7 +121,7 @@ public async Task<object> Any(RankAnswer request)
throw HttpError.NotFound("Answer not found");

var answerCreator = !string.IsNullOrEmpty(answer.CreatedBy)
? await Db.ScalarAsync<string>(Db.From<ApplicationUser>().Where(x => x.UserName == answer.CreatedBy).Select(x => x.Id))
? Db.Scalar<string>(Db.From<ApplicationUser>().Where(x => x.UserName == answer.CreatedBy).Select(x => x.Id))
: null;

if (answerCreator == null)
Expand Down
10 changes: 5 additions & 5 deletions MyApp.ServiceInterface/AiServerServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public async Task Any(CreateAnswerCallback request)
LastUpdated = DateTime.UtcNow,
});

await Db.NotifyQuestionAuthorIfRequiredAsync(jobs, answer);
Db.NotifyQuestionAuthorIfRequired(jobs, answer);

jobs.RunCommand<CreateRankAnswerTaskCommand>(new CreateRankAnswerTask {
AnswerId = answer.RefId!,
Expand All @@ -120,7 +120,7 @@ public async Task Any(CreateAnswerCallback request)

public async Task Any(RankAnswerCallback request)
{
var answerCreator = await AssertUserNameById(request.UserId);
var answerCreator = AssertUserNameById(request.UserId);

var graderUser = appConfig.GetModelUser(request.Grader);
if (graderUser?.UserName == null)
Expand Down Expand Up @@ -182,7 +182,7 @@ public async Task Any(RankAnswerCallback request)

public async Task Any(AnswerCommentCallback request)
{
var commentCreator = await AssertUserNameById(request.UserId);
var commentCreator = AssertUserNameById(request.UserId);
var postId = request.AnswerId.LeftPart('-').ToInt();
var modelUserName = request.AnswerId.RightPart('-');

Expand Down Expand Up @@ -226,10 +226,10 @@ public async Task Any(AnswerCommentCallback request)
await questions.SaveMetaAsync(postId, meta);
}

private async Task<string> AssertUserNameById(string userId)
private string AssertUserNameById(string userId)
{
var userName = appConfig.GetModelUserById(userId)?.UserName
?? await Db.ScalarAsync<string?>(Db.From<ApplicationUser>().Where(x => x.Id == userId).Select(x => x.UserName));
?? Db.Scalar<string?>(Db.From<ApplicationUser>().Where(x => x.Id == userId).Select(x => x.UserName));
if (userName == null)
throw HttpError.BadRequest("Invalid User Id: " + userId);
return userName;
Expand Down
14 changes: 7 additions & 7 deletions MyApp.ServiceInterface/AnalyticsTasksCommand.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
using MyApp.Data;
using MyApp.ServiceModel;
using ServiceStack;
using ServiceStack.IO;
using ServiceStack.Data;
using ServiceStack.OrmLite;

namespace MyApp.ServiceInterface;

[Worker(Databases.Analytics)]
public class AnalyticsTasksCommand(R2VirtualFiles r2, QuestionsProvider questions) : AsyncCommand<AnalyticsTasks>
public class AnalyticsTasksCommand(IDbConnectionFactory dbFactory) : SyncCommand<AnalyticsTasks>
{
protected override async Task RunAsync(AnalyticsTasks request, CancellationToken token)
protected override void Run(AnalyticsTasks request)
{
if (request.CreatePostStat == null && request.CreateSearchStat == null && request.DeletePost == null)
return;

using var analyticsDb = HostContext.AppHost.GetDbConnection(Databases.Analytics);
using var analyticsDb = dbFactory.Open(Databases.Analytics);

if (request.CreatePostStat != null)// && !Stats.IsAdminOrModerator(request.RecordPostView.UserName))
{
await analyticsDb.InsertAsync(request.CreatePostStat, token: token);
analyticsDb.Insert(request.CreatePostStat);
}

if (request.CreateSearchStat != null)// && !Stats.IsAdminOrModerator(request.RecordSearchView.UserName))
{
await analyticsDb.InsertAsync(request.CreateSearchStat, token: token);
analyticsDb.Insert(request.CreateSearchStat);
}

if (request.DeletePost != null)
{
await analyticsDb.DeleteAsync<PostStat>(x => x.PostId == request.DeletePost, token: token);
analyticsDb.Delete<PostStat>(x => x.PostId == request.DeletePost);
}
}
}
14 changes: 7 additions & 7 deletions MyApp.ServiceInterface/ApiServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ namespace MyApp.ServiceInterface;

public class ApiServices(IDbConnectionFactory dbFactory) : Service
{
public async Task<object> Any(SearchPosts request)
public object Any(SearchPosts request)
{
using var dbSearch = await dbFactory.OpenAsync(Databases.Search);
using var dbSearch = dbFactory.Open(Databases.Search);

var skip = request.Skip;
var take = Math.Min(request.Take ?? 25, 200);
Expand All @@ -31,14 +31,14 @@ public async Task<object> Any(SearchPosts request)

q.OrderByView(request.View);

List<PostFts> postsFts = await dbSearch.SelectAsync(q
List<PostFts> postsFts = dbSearch.Select(q
.Select("RefId, substring(Body,0,400) as Body, ModifiedDate")
.Skip(request.Skip)
.Take(take));
var total = dbSearch.Count(q);

using var db = await dbFactory.OpenAsync();
var posts = await db.PopulatePostsAsync(postsFts);
using var db = dbFactory.Open();
var posts = db.PopulatePosts(postsFts);

return new SearchPostsResponse
{
Expand All @@ -48,10 +48,10 @@ public async Task<object> Any(SearchPosts request)
}
else
{
using var db = await dbFactory.OpenAsync();
using var db = dbFactory.Open();
var q = db.From<Post>();

var posts = await db.SelectAsync(q
var posts = db.Select(q
.OrderByView(request.View)
.Skip(skip)
.Take(take));
Expand Down
18 changes: 9 additions & 9 deletions MyApp.ServiceInterface/App/CreateAnswerCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ namespace MyApp.ServiceInterface.App;

[Tag(Tags.Answers)]
[Worker(Databases.App)]
public class CreateAnswerCommand(AppConfig appConfig, IDbConnection db) : IAsyncCommand<Post>
public class CreateAnswerCommand(AppConfig appConfig, IDbConnection db) : SyncCommand<Post>
{
public async Task ExecuteAsync(Post answer)
protected override void Run(Post answer)
{
if (answer.ParentId == null)
throw new ArgumentNullException(nameof(answer.ParentId));
Expand All @@ -19,9 +19,9 @@ public async Task ExecuteAsync(Post answer)

var postId = answer.ParentId!.Value;
var refId = $"{postId}-{answer.CreatedBy}";
if (!await db.ExistsAsync(db.From<StatTotals>().Where(x => x.Id == refId)))
if (!db.Exists(db.From<StatTotals>().Where(x => x.Id == refId)))
{
await db.InsertAsync(new StatTotals
db.Insert(new StatTotals
{
Id = refId,
PostId = postId,
Expand All @@ -34,13 +34,13 @@ await db.InsertAsync(new StatTotals
});
}

var post = await db.SingleByIdAsync<Post>(postId);
var post = db.SingleById<Post>(postId);
if (post?.CreatedBy != null)
{
// Notify Post Author of new Answer
if (post.CreatedBy != answer.CreatedBy && appConfig.IsHuman(post.CreatedBy))
{
await db.InsertAsync(new Notification
db.Insert(new Notification
{
UserName = post.CreatedBy,
Type = NotificationType.NewAnswer,
Expand All @@ -61,7 +61,7 @@ await db.InsertAsync(new Notification
.Where(x => x != post.CreatedBy && x != answer.CreatedBy && appConfig.IsHuman(x)).ToList();
if (userNameMentions.Count > 0)
{
var existingUsers = await db.SelectAsync(db.From<ApplicationUser>()
var existingUsers = db.Select(db.From<ApplicationUser>()
.Where(x => userNameMentions.Contains(x.UserName!)));

foreach (var existingUser in existingUsers)
Expand All @@ -72,7 +72,7 @@ await db.InsertAsync(new Notification
var startPos = Math.Max(0, firstMentionPos - 50);
if (appConfig.IsHuman(existingUser.UserName))
{
await db.InsertAsync(new Notification
db.Insert(new Notification
{
UserName = existingUser.UserName!,
Type = NotificationType.AnswerMention,
Expand All @@ -91,7 +91,7 @@ await db.InsertAsync(new Notification

if (appConfig.IsHuman(answer.CreatedBy))
{
await db.InsertAsync(new Achievement
db.Insert(new Achievement
{
UserName = answer.CreatedBy,
Type = AchievementType.NewAnswer,
Expand Down
7 changes: 4 additions & 3 deletions MyApp.ServiceInterface/App/CreateCommentVoteCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
namespace MyApp.ServiceInterface.App;

[Tag(Tags.Database)]
[Worker(Databases.App)]
public class CreateCommentVoteCommand(IDbConnection db, QuestionsProvider questions) : IAsyncCommand<Vote>
{
public async Task ExecuteAsync(Vote vote)
Expand All @@ -16,7 +17,7 @@ public async Task ExecuteAsync(Vote vote)
if (string.IsNullOrEmpty(vote.UserName))
throw new ArgumentNullException(nameof(vote.UserName));

var rowsDeleted = await db.DeleteAsync<Vote>(new { vote.RefId, vote.UserName });
var rowsDeleted = db.Delete<Vote>(new { vote.RefId, vote.UserName });

var meta = await questions.GetMetaAsync(vote.PostId);
var created = vote.RefId.LastRightPart('-').ToLong();
Expand All @@ -30,9 +31,9 @@ public async Task ExecuteAsync(Vote vote)
throw new ArgumentException("Can't vote on your own comment", nameof(vote.RefId));

vote.RefUserName = comment.CreatedBy;
await db.InsertAsync(vote);
db.Insert(vote);

comment.UpVotes = (int) await db.CountAsync<Vote>(x => x.RefId == vote.RefId && x.Score > 0);
comment.UpVotes = (int) db.Count<Vote>(x => x.RefId == vote.RefId && x.Score > 0);
await questions.SaveMetaAsync(vote.PostId, meta);
}
}
Expand Down
7 changes: 2 additions & 5 deletions MyApp.ServiceInterface/App/CreateFlagCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ namespace MyApp.ServiceInterface.App;

[Tag(Tags.Database)]
[Worker(Databases.App)]
public class CreateFlagCommand(IDbConnection db) : AsyncCommand<Flag>
public class CreateFlagCommand(IDbConnection db) : SyncCommand<Flag>
{
protected override async Task RunAsync(Flag request, CancellationToken token)
{
await db.InsertAsync(request, token: token);
}
protected override void Run(Flag request) => db.Insert(request);
}
6 changes: 3 additions & 3 deletions MyApp.ServiceInterface/App/CreateNotificationCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ namespace MyApp.ServiceInterface.App;

[Tag(Tags.Notifications)]
[Worker(Databases.App)]
public class CreateNotificationCommand(AppConfig appConfig, IDbConnection db) : AsyncCommand<Notification>
public class CreateNotificationCommand(AppConfig appConfig, IDbConnection db) : SyncCommand<Notification>
{
protected override async Task RunAsync(Notification request, CancellationToken token)
protected override void Run(Notification request)
{
await db.InsertAsync(request, token: token);
db.Insert(request);
appConfig.IncrUnreadNotificationsFor(request.UserName);
}
}
30 changes: 15 additions & 15 deletions MyApp.ServiceInterface/App/CreatePostCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,40 +20,40 @@ protected override async Task RunAsync(Post post, CancellationToken token)

if (post.Id > 0)
{
await db.InsertAsync(post, token: token);
db.Insert(post);
}
else
{
post.Id = (int)await db.InsertAsync(post, selectIdentity: true, token: token);
post.Id = (int)db.Insert(post, selectIdentity: true);
}

var createdBy = post.CreatedBy;
if (createdBy != null && post.PostTypeId == 1)
{
await appConfig.ResetUserQuestionsAsync(db, createdBy);
appConfig.ResetUserQuestions(db, createdBy);
}

try
{
await db.InsertAsync(new StatTotals
db.Insert(new StatTotals
{
Id = $"{post.Id}",
PostId = post.Id,
UpVotes = 0,
DownVotes = 0,
StartingUpVotes = 0,
CreatedBy = post.CreatedBy,
}, token: token);
});
}
catch (Exception e)
{
log.LogWarning("Couldn't insert StatTotals for Post {PostId}: '{Message}', updating instead...", post.Id,
e.Message);
await db.UpdateOnlyAsync(() => new StatTotals
db.UpdateOnly(() => new StatTotals
{
PostId = post.Id,
CreatedBy = post.CreatedBy,
}, x => x.Id == $"{post.Id}", token: token);
}, x => x.Id == $"{post.Id}");
}

if (!string.IsNullOrEmpty(body))
Expand All @@ -63,8 +63,8 @@ await db.InsertAsync(new StatTotals
.Where(x => x != createdBy && appConfig.IsHuman(x)).ToList();
if (userNameMentions.Count > 0)
{
var existingUsers = await db.SelectAsync(db.From<ApplicationUser>()
.Where(x => userNameMentions.Contains(x.UserName!)), token: token);
var existingUsers = db.Select(db.From<ApplicationUser>()
.Where(x => userNameMentions.Contains(x.UserName!)));

foreach (var existingUser in existingUsers)
{
Expand All @@ -74,7 +74,7 @@ await db.InsertAsync(new StatTotals
var startPos = Math.Max(0, firstMentionPos - 50);
if (appConfig.IsHuman(existingUser.UserName))
{
await db.InsertAsync(new Notification
db.Insert(new Notification
{
UserName = existingUser.UserName!,
Type = NotificationType.QuestionMention,
Expand All @@ -83,7 +83,7 @@ await db.InsertAsync(new Notification
CreatedDate = post.CreationDate,
Summary = cleanBody.GenerateNotificationSummary(startPos),
RefUserName = createdBy,
}, token: token);
});
appConfig.IncrUnreadNotificationsFor(existingUser.UserName!);
}
}
Expand All @@ -92,26 +92,26 @@ await db.InsertAsync(new Notification

if (appConfig.IsHuman(post.CreatedBy))
{
await db.InsertAsync(new Achievement
db.Insert(new Achievement
{
UserName = post.CreatedBy!,
Type = AchievementType.NewQuestion,
RefId = $"{post.Id}",
PostId = post.Id,
Score = 1,
CreatedDate = DateTime.UtcNow,
}, token: token);
});
appConfig.IncrUnreadAchievementsFor(post.CreatedBy!);

// Setup auto-watch for new questions (Sending Emails for new Answers)
await db.InsertAsync(new WatchPost
db.Insert(new WatchPost
{
UserName = post.CreatedBy!,
PostId = post.Id,
CreatedDate = post.CreationDate,
// Email new answers 1hr after asking question
AfterDate = DateTime.UtcNow.Add(TimeSpan.FromHours(1)),
}, token: token);
});
}
}
}
Loading

0 comments on commit 44cc15f

Please sign in to comment.