Using query expression vs Seq modules?

269 Views Asked by At

Are there any advantages in using the query expression over Sequence modules when manipulating data retrieved via FSharp.Data.SqlClient?

For example:

query{
    for row in SelectAllCategories.Execute() do
    where row.Id = 1
    select {
        Id = row.Id;
        Category = row.CategoryName
    }
}

versus

SelectAllCategories.Execute()
|> Seq.filter (fun x -> x.Id = 1)
|> Seq.map (fun x ->
                {
                   Id = x.Id;
                   Category = x.CategoryName
                }

For that matter you can even consider LINQ as well. So what are the advantages if any, specifically in regards to FSharp.Data.SqlClient?

2

There are 2 best solutions below

0
On BEST ANSWER

In this particular case FSharp.Data.SqlClient provides the default IEnumerable<ProvidedType>.Record result type, not IQueryable<ProvidedType> of any sort. All communications with SQL engine are opaque to query expression, being encapsulated into provided SqlCommandProvider.Execute() method. So any potential benefits of query {...} using Linq-to-Sql are not in play here.

Hence, I'd not be surprised that the case with functions from Seq module would yield better performance having less overhead, than underlying desugared machinery associated with query expressions. No advantages of using the query expression here.

2
On

Query builder provides a way to construct IQueryables in F#, Seq module functions work on IEnumerables (that seq type is an alias for). Those are general .NET interfaces rather than an F# thing, and the differences between them are well outlined for example here.

Also, apart from Seq module functions you also have the seq builder:

seq {
   for row in SelectAllCategories.Execute() do 
       if row.Id = 1 then 
           yield { Id = row.Id; Category = row.CategoryName }
}

It's roughly equivalent to using Seq module functions, so the choice of one over the other is mostly a style or convenience decision.