78 lines
2.9 KiB
FSharp
78 lines
2.9 KiB
FSharp
namespace MyWebLog.Data.Postgres
|
|
|
|
open BitBadger.Documents
|
|
open BitBadger.Documents.Postgres
|
|
open Microsoft.Extensions.Logging
|
|
open MyWebLog
|
|
open MyWebLog.Data
|
|
open Npgsql.FSharp
|
|
|
|
/// PostgreSQL myWebLog person data implementation
|
|
type PostgresPersonData(log: ILogger) =
|
|
|
|
/// Add a person
|
|
let add (person : Person) =
|
|
log.LogTrace "Person.add"
|
|
insert Table.Person person
|
|
|
|
/// Find persons for the given assignments
|
|
let findByAssignment (assignments: PersonAssignment list) =
|
|
log.LogTrace "Person.findByAssignment"
|
|
Find.byFieldsOrdered<Person>
|
|
Table.Person
|
|
All
|
|
[ Field.In (nameof Person.Empty.Id) (assignments |> List.map (fun it -> string it.PersonId)) ]
|
|
[ Field.Named (nameof Person.Empty.Name) ]
|
|
|
|
/// Find a person by their ID for the given web log
|
|
let findById (personId: PersonId) (webLogId: WebLogId) =
|
|
log.LogTrace "Person.findById"
|
|
Find.firstByContains<Person> Table.Person {| Id = personId; WebLogId = webLogId |}
|
|
|
|
/// Delete a person by their ID for the given web log
|
|
let delete personId webLogId = backgroundTask {
|
|
log.LogTrace "Person.delete"
|
|
match! findById personId webLogId with
|
|
| Some _ ->
|
|
// TODO: also remove this person from assignments in episodes and podcasts
|
|
do! Custom.nonQuery
|
|
$"""{Query.delete Table.Person} WHERE {Query.whereById "@id"}"""
|
|
[ idParam personId ]
|
|
return true
|
|
| None -> return false
|
|
}
|
|
|
|
/// Find all persons for the given web log
|
|
let findByWebLog webLogId =
|
|
log.LogTrace "Person.findByWebLog"
|
|
Find.byContainsOrdered<Person> Table.Person (webLogDoc webLogId) [ Field.Named (nameof Person.Empty.Name) ]
|
|
|
|
|
|
/// Restore persons from a backup
|
|
let restore persons = backgroundTask {
|
|
log.LogTrace "Person.restore"
|
|
let! _ =
|
|
Configuration.dataSource ()
|
|
|> Sql.fromDataSource
|
|
|> Sql.executeTransactionAsync
|
|
[ Query.insert Table.Person, persons |> List.map (fun person -> [ jsonParam "@data" person ]) ]
|
|
()
|
|
}
|
|
|
|
/// Update a person
|
|
let update (person: Person) = backgroundTask {
|
|
log.LogTrace "Person.update"
|
|
match! findById person.Id person.WebLogId with
|
|
| Some _ -> do! Update.byId Table.Person person.Id person
|
|
| None -> ()
|
|
}
|
|
|
|
interface IPersonData with
|
|
member _.Add person = add person
|
|
member _.Delete personId webLogId = delete personId webLogId
|
|
member _.FindByAssignment assignments = findByAssignment assignments
|
|
member _.FindById personId webLogId = findById personId webLogId
|
|
member _.FindByWebLog webLogId = findByWebLog webLogId
|
|
member _.Restore persons = restore persons
|
|
member _.Update person = update person
|