Skip to content

Instantly share code, notes, and snippets.

@jhewlett
Created February 23, 2020 12:13
Show Gist options
  • Save jhewlett/ece738f59a3a8249727e9449916a2a7b to your computer and use it in GitHub Desktop.
Save jhewlett/ece738f59a3a8249727e9449916a2a7b to your computer and use it in GitHub Desktop.
F# Data Access Example
//db.fs - helpers
module Db =
open System.Data.SQLite
open System.Data
open Dapper
let createConnectionFactory (connectionString : string) =
let createConnection () =
new SQLiteConnection(connectionString) :> IDbConnection
createConnection
let writeData (createConnection : unit -> IDbConnection) statement parameters =
async {
use conn = createConnection ()
do! conn.ExecuteAsync(statement, parameters) |> Async.AwaitTask |> Async.Ignore
}
let readData<'a> (createConnection : unit -> IDbConnection) query parameters =
async {
use conn = createConnection ()
let! results = conn.QueryAsync<'a>(query, parameters) |> Async.AwaitTask
return results |> List.ofSeq
}
//Planet.fs - domain type
type Planet = {
Id : string
Name : string
}
//PlanetDb.fs
[<CLIMutable>]
type PlanetDto = {
Id : string
Name : string
}
module PlanetDto =
let toDomain (planetDto : PlanetDto) : Planet =
{ Id = planetDto.Id; Name = planetDto.Name }
module PlanetDb =
let savePlanet writeData (planet : Planet) : Async<unit> =
let statement = """
insert into planets (id, name)
values (:id, :name);
"""
writeData statement {| id = planet.Id; name = planet.Name |}
let findPlanet readData id : Async<Planet option> =
let query = """
select id, name from planets
where id = :id;
"""
async {
let! results = readData query {| id = id |}
return
results
|> List.tryHead
|> Option.map PlanetDto.toDomain
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment