From 427faf8a36075381824a898e211cce1748fd34cc Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Tue, 17 Nov 2026 16:42:48 +0000 Subject: [PATCH 1/4] Evaluate captured values without compiling; cache row readers by shape - Patterns.evaluateExpression reads a query's one-off values (constants, members, method calls on captured values, conversions, quotes) by reflection and interprets the rest, in place of Expression.Lambda(e).Compile(). - QueryExpression.CompiledLambdas compiles a row reader once per shape and binds each run's constants into it. Not used where the runtime interprets lambdas (IsDynamicCodeSupported false). - Exceptions from a captured value are raised unwrapped. --- docs/RELEASE_NOTES.md | 5 + src/SQLProvider.Common/SqlRuntime.Patterns.fs | 244 ++++++++------- .../SqlRuntime.QueryExpression.fs | 158 +++++++++- .../ExpressionEvaluationTests.fs | 292 ++++++++++++++++++ .../SqlProvider.Tests.fsproj | 1 + 5 files changed, 586 insertions(+), 114 deletions(-) create mode 100644 tests/SqlProvider.Tests/ExpressionEvaluationTests.fs diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 2572051b3..2b81aa54b 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,3 +1,8 @@ +### 1.5.33 - 17.11.2026 +- A query's row reader is compiled once per shape and reused when the query runs again, with any captured values: a run no longer compiles and JITs a new delegate. Unchanged where the runtime interprets lambdas (IsDynamicCodeSupported false) +- Values a query reads once (a captured variable's member, a sub-query's source, a method call on captured values) are read by reflection, and other one-off expressions are interpreted where the runtime can (not on .NET Framework), instead of compiled +- An exception thrown while evaluating a query's captured value is raised as it is, not wrapped in TargetInvocationException + ### 1.5.32 - 14.11.2026 - Fix: PostgreSQL functions are called inside a SELECT. With Npgsql 7 and newer they failed with "procedure ... does not exist", as a stored-procedure command is a CALL there - PostgreSQL procedures (11 and newer) are under ctx.Procedures and called with CALL, with any Npgsql version; they weren't listed before. INOUT and OUT parameters are the result's properties diff --git a/src/SQLProvider.Common/SqlRuntime.Patterns.fs b/src/SQLProvider.Common/SqlRuntime.Patterns.fs index 4ea3e84b5..259289ee3 100644 --- a/src/SQLProvider.Common/SqlRuntime.Patterns.fs +++ b/src/SQLProvider.Common/SqlRuntime.Patterns.fs @@ -9,6 +9,114 @@ open FSharp.Data.Sql.Schema /// Marker interface type ISqlQueryable = interface end +/// Reflection raises a member's exception wrapped in TargetInvocationException; compiled code raises it as it is. +let private unwrapInvocation (read: unit -> obj) = + try read () + with :? TargetInvocationException as ex when not (isNull ex.InnerException) -> + Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw() + null + +/// A Convert that keeps the value as it is: a reference cast, boxing, unboxing to the same type or wrapping in +/// Nullable. A numeric, enum or user-defined conversion computes a new value, so it isn't one. +let private convertsAsIs (u:UnaryExpression) (value:obj) = + isNull u.Method + && (if isNull value then not u.Type.IsValueType || not (isNull (Nullable.GetUnderlyingType u.Type)) + else u.Type.IsInstanceOfType value) + +/// Value types whose methods don't change the value. Reflection calls a method on a boxed copy, which compiled code +/// doesn't, so a method of any other value type is left to the interpreter. +let private unchangedByMethods = + Collections.Generic.HashSet([ typeof; typeof; typeof; typeof; typeof ]) + +let private callableByReflection (mc:MethodCallExpression) = + (mc.Method.IsStatic + || not mc.Object.Type.IsValueType || mc.Object.Type.IsPrimitive || mc.Object.Type.IsEnum + || unchangedByMethods.Contains mc.Object.Type) + && mc.Method.GetParameters() |> Array.forall (fun p -> not p.ParameterType.IsByRef) + +/// Finds a parameter that none of the expression's own lambdas, blocks or catch blocks declares. +type private OuterParameterFinder() = + inherit ExpressionVisitor() + let declared = Collections.Generic.HashSet() + let used = Collections.Generic.HashSet() + member _.Found = not (used.IsSubsetOf declared) + override _.Visit (e:Expression) = + match e with + | :? LambdaExpression as l -> declared.UnionWith l.Parameters + | :? BlockExpression as b -> declared.UnionWith b.Variables + | :? TryExpression as t -> for h in t.Handlers do if not (isNull h.Variable) then declared.Add h.Variable |> ignore + | :? ParameterExpression as p -> used.Add p |> ignore + | _ -> () + base.Visit e + +/// Whether readValue reads the expression: a constant, a field or property of a readable value or a static one, a +/// method call on readable values, a Convert or TypeAs of one, and a Quote that uses no outer lambda's parameter. +/// The answer comes from the expression's shape, so nothing has been evaluated when it is false. +let rec private isReadable (e:Expression) = + match e.NodeType, e with + | ExpressionType.Constant, _ -> true + | ExpressionType.MemberAccess, (:? MemberExpression as me) -> isNull me.Expression || isReadable me.Expression + | ExpressionType.Call, (:? MethodCallExpression as mc) -> + callableByReflection mc && (isNull mc.Object || isReadable mc.Object) && Seq.forall isReadable mc.Arguments + | (ExpressionType.Convert | ExpressionType.ConvertChecked | ExpressionType.TypeAs), (:? UnaryExpression as ue) -> + isReadable ue.Operand + | ExpressionType.Quote, (:? UnaryExpression as ue) -> + let finder = OuterParameterFinder() + finder.Visit ue.Operand |> ignore + not finder.Found + | _ -> false + +/// Runs a parameterless expression interpreted, as compiling it would JIT code that runs once. +let private interpret (e:Expression) : obj = + let body = + if Type.(=)(e.Type, typeof) then Expression.Block(e, Expression.Constant(null)) :> Expression + else Expression.Convert(e, typeof) :> Expression + let lambda = Expression.Lambda> body +#if NET461 || NET462 + lambda.Compile().Invoke() +#else + lambda.Compile(preferInterpretation = true).Invoke() +#endif + +/// The value of an expression isReadable accepts, each part of it evaluated once. Where reflection doesn't answer as +/// compiled code does (a member of null or of a Nullable, a conversion that computes a new value), the node is +/// interpreted over its operand's value. +let rec private readValue (e:Expression) : obj = + match e.NodeType, e with + | ExpressionType.MemberAccess, (:? MemberExpression as me) -> + let owner = if isNull me.Expression then null else readValue me.Expression + if not (isNull me.Expression) && (isNull owner || not (isNull (Nullable.GetUnderlyingType me.Expression.Type))) then + interpret (me.Update(Expression.Constant(owner, me.Expression.Type))) + else + match me.Member with + | :? FieldInfo as f -> f.GetValue owner + | m -> unwrapInvocation (fun () -> (m :?> PropertyInfo).GetValue(owner, null)) + | ExpressionType.Call, (:? MethodCallExpression as mc) -> + let owner = if isNull mc.Object then null else readValue mc.Object + let args = Array.zeroCreate mc.Arguments.Count + for i in 0 .. args.Length - 1 do + args.[i] <- readValue mc.Arguments.[i] + if isNull owner && not mc.Method.IsStatic then raise (NullReferenceException()) + unwrapInvocation (fun () -> mc.Method.Invoke(owner, args)) + | (ExpressionType.Convert | ExpressionType.ConvertChecked), (:? UnaryExpression as ue) -> + let value = readValue ue.Operand + if convertsAsIs ue value then value + else interpret (ue.Update(Expression.Constant(value, ue.Operand.Type))) + | ExpressionType.TypeAs, (:? UnaryExpression as ue) -> + let value = readValue ue.Operand + if isNull value || ue.Type.IsInstanceOfType value then value else null + | ExpressionType.Quote, (:? UnaryExpression as ue) -> box ue.Operand + | _ -> (e :?> ConstantExpression).Value + +/// The value of a parameterless expression when isReadable accepts it. +let private tryReadValue (e:Expression) : obj voption = + if isReadable e then ValueSome (readValue e) else ValueNone + +/// The value of a parameterless expression, evaluated once: read by reflection where isReadable accepts it, +/// interpreted otherwise. +let internal evaluateExpression (e:Expression) : obj = + if isReadable e then readValue e else interpret e + [] let inline (|MethodWithName|_|) (s:string) (m:MethodInfo) = if String.Equals(m.Name, s, StringComparison.Ordinal) then ValueSome () else ValueNone [] @@ -67,14 +175,11 @@ let (|SeqValuesQueryable|_|) (e:Expression) = match e.NodeType, e with | ExpressionType.Constant, (:? ConstantExpression as ce) -> match ce.Value with - | :? ISqlQueryable -> - let values = (Expression.Lambda(e).Compile() :?> Func).Invoke() - ValueSome values + | :? ISqlQueryable -> ValueSome (ce.Value :?> System.Linq.IQueryable) | _ -> ValueNone | _ -> - let values = (Expression.Lambda(e).Compile() :?> Func).Invoke() - match values with - | :? ISqlQueryable -> ValueSome values + match evaluateExpression e with + | :? ISqlQueryable as values -> ValueSome (values :?> System.Linq.IQueryable) | _ -> ValueNone [] @@ -92,22 +197,7 @@ let (|SeqValues|_|) (e:Expression) = // select x from xs where x in (select y from ys) // ...but instead we just execute the sub-query. Works when sub-query results are small. - let values = - match e.NodeType, e with - | ExpressionType.Constant, (:? ConstantExpression as ce) when not(isNull ce.Value) -> - ce.Value :?> System.Collections.IEnumerable - | ExpressionType.MemberAccess, (:? MemberExpression as me) when (me.Expression :? ConstantExpression) -> - let ceVal = (me.Expression :?> ConstantExpression).Value - let myVal = - match me.Member with - | :? FieldInfo as fieldInfo when not(isNull fieldInfo) -> - fieldInfo.GetValue ceVal - | :? PropertyInfo as propInfo when not(isNull propInfo) -> - propInfo.GetValue(ceVal, null) - | _ -> ceVal - myVal :?> System.Collections.IEnumerable - | _ -> - (Expression.Lambda(e).Compile() :?> Func).Invoke() + let values = evaluateExpression e :?> System.Collections.IEnumerable // Working with untyped IEnumerable so need to do a lot manually instead of using Seq // Work out the size the sequence @@ -174,11 +264,7 @@ let (|ConstantOrNullableConstant|_|) (e:Expression) = match ue.Operand.NodeType, ue.Operand with | ExpressionType.Constant, (:? ConstantExpression as ce) -> if isNull ce.Value then Some None else Some(Some ce.Value) | ExpressionType.New, (:? NewExpression as ne) -> - try - if ne.Type.IsClass then - Some(Some((Expression.Lambda(ne).Compile() :?> Func<_>).Invoke())) - else - Some(Some(Expression.Lambda(ne).Compile().DynamicInvoke())) + try Some(Some(evaluateExpression ne)) with err -> failwith ("unsupported nullable new expression " + ne.ToString() + " err: " + err.Message) | _ -> failwith ("unsupported nullable expression " + e.ToString()) | _ -> None @@ -392,82 +478,26 @@ let intType (typ:Type) = elif (not (isNull typ)) && Common.Utilities.isVOpt typ then typeof> else typeof -/// Fast type-safe evaluation without boxing for common types +/// Return types whose evaluation errors propagate; for other types evaluateMethodCall gives None on an error. +let private propagatingReturnTypes = + System.Collections.Generic.HashSet( + [ typeof; typeof; typeof; typeof; typeof; typeof; typeof + typeof; typeof; typeof; typeof; typeof; typeof; typeof + typeof; typeof + typeof>; typeof>; typeof>; typeof> + typeof>; typeof>; typeof>; typeof> + typeof>; typeof>; typeof>; typeof> + typeof>; typeof>; typeof>; typeof> ]) + +/// Evaluates a parameterless method call once let internal evaluateMethodCall (meth: MethodCallExpression) : obj option = let returnType = meth.Method.ReturnType - - if returnType.IsClass then - try - Some((Expression.Lambda(meth).Compile() :?> Func<_>).Invoke() |> box) - with - _ -> None - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then - // Should we handle case where isNull e.Object and e.Method.Name in (get_Now, get_UtcNow, get_Today) ? - Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then - // Should we handle case where isNull e.Object and e.Method.Name in (get_Now, get_UtcNow) ? - Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - elif Type.(=)(returnType, typeof) then Some((Expression.Lambda(meth).Compile() :?> Func).Invoke() |> box) - - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) - elif Type.(=)(returnType, typeof>) then Some((Expression.Lambda(meth).Compile() :?> Func>).Invoke() |> box) + if not returnType.IsClass && propagatingReturnTypes.Contains returnType then Some(evaluateExpression meth) else - try - Some(Expression.Lambda(meth).Compile().DynamicInvoke()) - with err -> None - -let internal getRightFromOp (right:Expression) = - match right.NodeType, right with - | ExpressionType.Constant, (:? ConstantExpression as ce) -> ce.Value - | ExpressionType.MemberAccess, (:? MemberExpression as me) when (me.Expression :? ConstantExpression) -> - let ceVal = (me.Expression :?> ConstantExpression).Value - let myVal = - match me.Member with - | :? FieldInfo as fieldInfo when not(isNull fieldInfo) -> - fieldInfo.GetValue ceVal - | :? PropertyInfo as propInfo when not(isNull propInfo) -> - propInfo.GetValue(ceVal, null) - | _ -> ceVal - myVal - | ExpressionType.Call, (:? MethodCallExpression as e) -> - match evaluateMethodCall e with - | Some x -> x - | None -> Expression.Lambda(right).Compile().DynamicInvoke() - | _ -> - if right.Type.IsClass then - try - (Expression.Lambda(right).Compile() :?> Func<_>).Invoke() |> box - with - | _ -> Expression.Lambda(right).Compile().DynamicInvoke() - else Expression.Lambda(right).Compile().DynamicInvoke() + try Some(evaluateExpression meth) + with _ -> None +let internal getRightFromOp (right:Expression) = evaluateExpression right let (|SqlExistsClause|_|) = function | MethodCall(None, (MethodWithName "Any" as meth), [ SeqValuesQueryable src; OptionalQuote qual ]) -> @@ -783,15 +813,7 @@ and (|SimpleCondition|_|) exp = match meth.NodeType, meth with | ExpressionType.Constant, (:? ConstantExpression as ce) -> Some ce.Value | ExpressionType.MemberAccess, (:? MemberExpression as me) when (me.Expression :? ConstantExpression) -> - let ceVal = (me.Expression :?> ConstantExpression).Value - let myVal = - match me.Member with - | :? FieldInfo as fieldInfo when not(isNull fieldInfo) -> - fieldInfo.GetValue ceVal - | :? PropertyInfo as propInfo when not(isNull propInfo) -> - propInfo.GetValue(ceVal, null) - | _ -> ceVal - Some myVal + Some(evaluateExpression me) | ExpressionType.Call, (:? MethodCallExpression as e) -> evaluateMethodCall e @@ -803,10 +825,8 @@ and (|SimpleCondition|_|) exp = | ExpressionType.MemberAccess, (:? MemberExpression as me) when Type.(=)(me.Type, typeof) && me.Member.Name = "UtcNow" -> Some(DateTimeOffset.UtcNow |> box) | _ -> // In case user feeds us incomplete lambda, we will not execute: the user might have a context needed for the compilation. - try - if meth.Type.IsClass then (Expression.Lambda(meth).Compile() :?> Func<_>).Invoke() |> box |> Some - else Some(Expression.Lambda(meth).Compile().DynamicInvoke()) - with err -> None + try Some(evaluateExpression meth) + with _ -> None match invokation with | None -> None | Some invokedResult -> diff --git a/src/SQLProvider.Common/SqlRuntime.QueryExpression.fs b/src/SQLProvider.Common/SqlRuntime.QueryExpression.fs index 2eaf1f211..0ce8c1af5 100644 --- a/src/SQLProvider.Common/SqlRuntime.QueryExpression.fs +++ b/src/SQLProvider.Common/SqlRuntime.QueryExpression.fs @@ -9,6 +9,160 @@ open FSharp.Data.Sql.Common open FSharp.Data.Sql.Patterns open FSharp.Data.Sql.Schema +/// Compiled lambdas cached by shape. A lambda's constants become reads of an array argument, so lambdas that differ +/// only in their constants' values share one compiled factory, which binds the values into a new delegate. +module internal CompiledLambdas = + + /// A lambda's shape as a sequence of tokens: node types, types, members, methods, counts and parameter + /// positions, with each constant's type but not its value. + [] + type ShapeKey = + { Tokens: obj[]; Hash: int } + override this.GetHashCode() = this.Hash + override this.Equals other = + match other with + | :? ShapeKey as o -> + this.Hash = o.Hash && this.Tokens.Length = o.Tokens.Length + && Array.forall2 (fun (a: obj) b -> obj.Equals(a, b)) this.Tokens o.Tokens + | _ -> false + + /// Assignments: a constant they write to can't become an array read. + let private assignments = + HashSet( + [ ExpressionType.Assign; ExpressionType.AddAssign; ExpressionType.AddAssignChecked; ExpressionType.AndAssign + ExpressionType.DivideAssign; ExpressionType.ExclusiveOrAssign; ExpressionType.LeftShiftAssign + ExpressionType.ModuloAssign; ExpressionType.MultiplyAssign; ExpressionType.MultiplyAssignChecked + ExpressionType.OrAssign; ExpressionType.PowerAssign; ExpressionType.RightShiftAssign + ExpressionType.SubtractAssign; ExpressionType.SubtractAssignChecked; ExpressionType.PreIncrementAssign + ExpressionType.PreDecrementAssign; ExpressionType.PostIncrementAssign; ExpressionType.PostDecrementAssign ]) + + /// Reads a lambda's shape and its constants' values, both in the order ExpressionVisitor visits the nodes. + /// Supported is false when the lambda holds a node kind the shape doesn't describe, a Quote (its expression is a + /// value, whose constants must stay constants) or an assignment to anything but a variable. + type private ShapeReader() = + inherit ExpressionVisitor() + let tokens = ResizeArray 64 + let values = ResizeArray() + let parameters = Dictionary(HashIdentity.Reference) + let positionOf (p: ParameterExpression) = + match parameters.TryGetValue p with + | true, i -> i + | false, _ -> + parameters.Add(p, parameters.Count) + parameters.Count - 1 + let add (token: obj) = tokens.Add token + member val Supported = true with get, set + member _.Tokens = tokens.ToArray() + member _.Values = values.ToArray() + override this.Visit (e: Expression) = + if not this.Supported then e + elif isNull e then + add null + e + else + add (box e.NodeType) + add e.Type + let supported = + match e with + | :? ConstantExpression -> true + | :? ParameterExpression as p -> + add (box (positionOf p)) + add (box p.IsByRef) + true + | :? LambdaExpression as l -> + add (box l.Parameters.Count) + true + | :? MemberExpression as m -> + add m.Member + true + | :? MethodCallExpression as c -> + add c.Method + add (box c.Arguments.Count) + true + | :? UnaryExpression as u -> + add u.Method + add (box u.IsLiftedToNull) + e.NodeType <> ExpressionType.Quote + && not (assignments.Contains e.NodeType && not (u.Operand :? ParameterExpression)) + | :? BinaryExpression as b -> + add b.Method + add (box b.IsLiftedToNull) + not (assignments.Contains e.NodeType && not (b.Left :? ParameterExpression)) + | :? ConditionalExpression | :? DefaultExpression -> true + | :? NewExpression as n -> + add n.Constructor + add (box n.Arguments.Count) + true + | :? NewArrayExpression as n -> + add (box n.Expressions.Count) + true + | :? InvocationExpression as i -> + add (box i.Arguments.Count) + true + | :? TypeBinaryExpression as t -> + add t.TypeOperand + true + | :? BlockExpression as b -> + add (box b.Variables.Count) + add (box b.Expressions.Count) + true + | :? MemberInitExpression as mi -> + add (box mi.Bindings.Count) + mi.Bindings |> Seq.forall (fun b -> add b.Member; b :? MemberAssignment) + | :? ListInitExpression as li -> + add (box li.Initializers.Count) + li.Initializers |> Seq.iter (fun i -> add i.AddMethod; add (box i.Arguments.Count)) + true + | _ -> false + if supported then base.Visit e + else + this.Supported <- false + e + override _.VisitConstant c = + values.Add c.Value + upcast c + + /// Replaces each constant with a read of the array parameter, numbered in the order ShapeReader reads them. + type private ConstantLifter(constants: ParameterExpression) = + inherit ExpressionVisitor() + let mutable count = 0 + override _.VisitConstant c = + let read = Expression.ArrayIndex(constants, Expression.Constant count) + count <- count + 1 + if Type.(=)(c.Type, typeof) then upcast read else upcast Expression.Convert(read, c.Type) + + let private factories = System.Collections.Concurrent.ConcurrentDictionary>() + + /// The number of shapes compiled. + let internal cachedShapes () = factories.Count + + /// Whether the runtime compiles lambdas to IL. Where it interprets them (RuntimeFeature.IsDynamicCodeSupported is + /// false), a lambda costs little to compile and a factory's array reads slow every row, so the cache isn't used. + let private compilesToIL = + match Type.GetType "System.Runtime.CompilerServices.RuntimeFeature" with + | null -> true + | feature -> + match feature.GetProperty "IsDynamicCodeSupported" with + | null -> true + | supported -> supported.GetValue null :?> bool + + /// The lambda's delegate, from the factory compiled for its shape; a lambda the shape doesn't describe is compiled alone. + let internal compile (lambda: LambdaExpression) : Delegate = + if not compilesToIL then lambda.Compile() + else + let reader = ShapeReader() + reader.Visit lambda |> ignore + if not reader.Supported then lambda.Compile() + else + let tokens = reader.Tokens + let key = { Tokens = tokens; Hash = tokens |> Array.fold (fun h t -> h * 31 + (if isNull t then 0 else t.GetHashCode())) 17 } + let factory = + factories.GetOrAdd(key, fun _ -> + let constants = Expression.Parameter(typeof, "constants") + let lifted = ConstantLifter(constants).Visit lambda + Expression.Lambda>(Expression.Convert(lifted, typeof), constants).Compile()) + factory.Invoke reader.Values + module internal QueryExpressionTransformer = /// One lock for each table of each provider. The first query of a table reads its columns from the database inside @@ -742,7 +896,7 @@ module internal QueryExpressionTransformer = | _ -> Expression.Parameter(typeof,"result") let pmap = Dictionary() pmap.Add(baseAlias, ResizeArray<_>()) - (Expression.Lambda(initDbParam,initDbParam).Compile(),pmap) + (CompiledLambdas.compile (Expression.Lambda(initDbParam,initDbParam)),pmap) | projs -> let replaceParams = Dictionary() @@ -978,7 +1132,7 @@ module internal QueryExpressionTransformer = QueryEvents.PublishExpression generatedMegaLambda if membershipSubquery && not (isNull generatedMegaLambda) && not (isColumnRead generatedMegaLambda.Body) then failwithf "IN / NOT IN needs a sub-query that selects one column as the database computes it, but this projection is computed in .NET after the rows are read: %O. Select the column or aggregate itself, or read the values first with Seq.toArray." generatedMegaLambda - (generatedMegaLambda.Compile(),finalParams) + (CompiledLambdas.compile generatedMegaLambda,finalParams) let sqlQuery = if groupgin.Count > 0 then diff --git a/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs b/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs new file mode 100644 index 000000000..21d0b9d8f --- /dev/null +++ b/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs @@ -0,0 +1,292 @@ +module ExpressionEvaluationTests + +// Values of parameterless expressions read without compiling (Patterns.evaluateExpression), and compiled lambdas +// cached by shape (CompiledLambdas.compile). Both are internal, so they are called by reflection. + +open System +open System.Linq +open System.Linq.Expressions +open NUnit.Framework + +let private flags = Reflection.BindingFlags.Static ||| Reflection.BindingFlags.Public ||| Reflection.BindingFlags.NonPublic +let private commonAssembly = typeof.Assembly + +let private invokeStatic (typeName: string) (name: string) (arguments: obj array) = + let methodInfo = commonAssembly.GetType(typeName, true).GetMethod(name, flags) + try methodInfo.Invoke(null, arguments) + with :? Reflection.TargetInvocationException as ex -> + Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw() + null + +/// The expression's value, read by reflection or interpreted. +let private evaluate (e: Expression) = invokeStatic "FSharp.Data.Sql.Patterns" "evaluateExpression" [| box e |] + +/// The expression's value when it is read by reflection alone; ValueNone when it would be interpreted. +let private readByReflection (e: Expression) = + invokeStatic "FSharp.Data.Sql.Patterns" "tryReadValue" [| box e |] :?> obj voption + +let private compile (lambda: LambdaExpression) = + invokeStatic "FSharp.Data.Sql.QueryExpression.CompiledLambdas" "compile" [| box lambda |] :?> Delegate + +let private cachedShapes () = + invokeStatic "FSharp.Data.Sql.QueryExpression.CompiledLambdas" "cachedShapes" [||] :?> int + +[] +type Point = { X: int; Y: int } + +type Holder(name: string, count: int, point: Point) = + member _.Name = name + member _.Count = count + member _.Point = point + member _.Failing: string = invalidOp "getter failed" + +/// Closure classes as C# generates them: a nested lambda's class holds the outer one in a field. +type OuterClosure() = + [] val mutable Ids: int list + +type InnerClosure() = + [] val mutable Outer: OuterClosure + [] val mutable Name: string + +type Statics = + static member Greeting = "hello" + static member Fail() : string = invalidOp "method failed" + +type ToExpression = + static member Of(e: Expression>) = e + +let private field (owner: Expression) (name: string) = Expression.Field(owner, name) :> Expression +let private property (owner: Expression) (name: string) = Expression.Property(owner, name) :> Expression +let private constant (value: obj) = Expression.Constant value :> Expression + +[] +let ``constants are read as they are``() = + Assert.AreEqual(ValueSome(box 42), readByReflection (constant 42)) + Assert.AreEqual(ValueSome(box "text"), readByReflection (constant "text")) + Assert.AreEqual(ValueSome(null: obj), readByReflection (Expression.Constant(null, typeof))) + +[] +let ``properties and fields of a constant are read by reflection``() = + let holder = Holder("name", 3, { X = 1; Y = 2 }) + Assert.AreEqual(ValueSome(box "name"), readByReflection (property (constant holder) "Name")) + Assert.AreEqual(ValueSome(box 3), readByReflection (property (constant holder) "Count")) + let closure = InnerClosure(Name = "closure") + Assert.AreEqual(ValueSome(box "closure"), readByReflection (field (constant closure) "Name")) + +[] +let ``a member whose value is null reads null``() = + let holder = Holder(null, 0, { X = 0; Y = 0 }) + Assert.AreEqual(ValueSome(null: obj), readByReflection (property (constant holder) "Name")) + Assert.AreEqual(ValueSome(null: obj), readByReflection (field (constant (InnerClosure())) "Outer")) + +[] +let ``a member of null throws as compiled code does``() = + let read = property (Expression.Constant(null, typeof)) "Name" + Assert.Throws(fun () -> evaluate read |> ignore) |> ignore + +[] +let ``members of a Nullable give what compiled code gives``() = + let none = Expression.Constant(null, typeof>) + Assert.AreEqual(ValueSome(box false), readByReflection (property none "HasValue")) + Assert.Throws(fun () -> evaluate (property none "Value") |> ignore) |> ignore + let some = Expression.Constant(Nullable 5, typeof>) + Assert.AreEqual(ValueSome(box true), readByReflection (property some "HasValue")) + Assert.AreEqual(ValueSome(box 5), readByReflection (property some "Value")) + +[] +let ``members of value types are read``() = + let point = { X = 5; Y = 7 } + Assert.AreEqual(ValueSome(box 5), readByReflection (property (constant point) "X")) + let holder = Holder("h", 1, point) + Assert.AreEqual(ValueSome(box 7), readByReflection (property (property (constant holder) "Point") "Y")) + +[] +let ``static members are read``() = + let staticProperty = Expression.Property(null, typeof.GetProperty "Greeting") + Assert.AreEqual(ValueSome(box "hello"), readByReflection staticProperty) + let staticField = Expression.Field(null, typeof.GetField "Empty") + Assert.AreEqual(ValueSome(box ""), readByReflection staticField) + let literalField = Expression.Field(null, typeof.GetField "MaxValue") + Assert.AreEqual(ValueSome(box Int32.MaxValue), readByReflection literalField) + +[] +let ``nested closures are read through their member chain``() = + let inner = InnerClosure(Outer = OuterClosure(Ids = [ 1; 2; 3 ])) + let ids = field (field (constant inner) "Outer") "Ids" + Assert.AreEqual(ValueSome(box [ 1; 2; 3 ]), readByReflection ids) + +[] +let ``values captured by F# lambdas are evaluated``() = + let outer (x: int) = + let y = x + 1 + ToExpression.Of(fun () -> (x, y)) + let lambda = outer 41 + Assert.AreEqual(box (41, 42), evaluate lambda.Body) + let ids = [ "a"; "b" ] + Assert.AreEqual(box ids, evaluate (ToExpression.Of(fun () -> ids)).Body) + +[] +let ``conversions are read, and ones that compute a value give what compiled code gives``() = + Assert.AreEqual(ValueSome(box 5), readByReflection (Expression.Convert(constant 5, typeof))) + Assert.AreEqual(ValueSome(box 5), readByReflection (Expression.Convert(constant 5, typeof>))) + Assert.AreEqual(ValueSome(box 5), readByReflection (Expression.Convert(Expression.Constant(box 5, typeof), typeof))) + Assert.AreEqual(ValueSome(null: obj), readByReflection (Expression.Convert(Expression.Constant(null, typeof), typeof))) + Assert.AreEqual(ValueSome(box 5L), readByReflection (Expression.Convert(constant 5, typeof))) + Assert.AreEqual(ValueSome(box 2), readByReflection (Expression.Convert(constant 2.7, typeof))) + Assert.AreEqual(ValueSome(box DayOfWeek.Friday), readByReflection (Expression.Convert(constant 5, typeof))) + Assert.Throws(fun () -> evaluate (Expression.ConvertChecked(constant 300, typeof)) |> ignore) |> ignore + Assert.Throws(fun () -> evaluate (Expression.Convert(Expression.Constant(box 5, typeof), typeof)) |> ignore) |> ignore + Assert.Throws(fun () -> evaluate (Expression.Convert(Expression.Constant(null, typeof), typeof)) |> ignore) |> ignore + Assert.AreEqual(ValueSome(box "s"), readByReflection (Expression.TypeAs(Expression.Constant(box "s", typeof), typeof))) + Assert.AreEqual(ValueSome(null: obj), readByReflection (Expression.TypeAs(Expression.Constant(box 5, typeof), typeof))) + +[] +let ``a quote evaluates to its expression``() = + let lambda = Expression.Lambda>(constant 1) + match readByReflection (Expression.Quote lambda) with + | ValueSome value -> Assert.AreSame(lambda, value) + | ValueNone -> Assert.Fail "a quote is read without evaluating" + +[] +let ``a getter's exception is raised as it is``() = + let holder = Holder("h", 1, { X = 0; Y = 0 }) + Assert.Throws(fun () -> evaluate (property (constant holder) "Failing") |> ignore) |> ignore + +[] +let ``other expressions are interpreted``() = + let sum = Expression.Add(constant 1, constant 2) + Assert.AreEqual(ValueNone, readByReflection sum) + Assert.AreEqual(box 3, evaluate sum) + let created = Expression.New(typeof.GetConstructor [| typeof; typeof; typeof |], constant 2000, constant 1, constant 2) + Assert.AreEqual(ValueNone, readByReflection created) + Assert.AreEqual(box (DateTime(2000, 1, 2)), evaluate created) + +[] +let ``static and instance method calls on readable values are read by reflection``() = + let concat = Expression.Call(typeof.GetMethod("Concat", [| typeof; typeof |]), constant "a", constant "b") + Assert.AreEqual(ValueSome(box "ab"), readByReflection concat) + let holder = Holder("name", 1, { X = 0; Y = 0 }) + let upper = Expression.Call(property (constant holder) "Name", typeof.GetMethod("ToUpperInvariant")) + Assert.AreEqual(ValueSome(box "NAME"), readByReflection upper) + let addDays = Expression.Call(constant (DateTime(2026, 1, 1)), typeof.GetMethod("AddDays"), constant 1.0) + Assert.AreEqual(ValueSome(box (DateTime(2026, 1, 2))), readByReflection addDays) + let voidCall = Expression.Call(typeof.GetMethod("KeepAlive"), Expression.Constant(null, typeof)) + Assert.AreEqual(ValueSome(null: obj), readByReflection voidCall) + +/// Queryable.Where over ints with a quoted predicate comparing the item to the given expression. +let private whereGreaterThan (limit: Expression) = + let x = Expression.Parameter(typeof, "x") + let predicate = Expression.Lambda>(Expression.GreaterThan(x, limit), x) + let where = typeof.GetMethods() |> Array.find (fun m -> m.Name = "Where" && m.GetParameters().[1].ParameterType.GetGenericArguments().[0].GetGenericArguments().Length = 2) + Expression.Call(where.MakeGenericMethod typeof, constant ([ 1; 2; 3 ].AsQueryable()), Expression.Quote predicate) + +[] +let ``a call with a quoted argument passes the expression``() = + match readByReflection (whereGreaterThan (constant 1)) with + | ValueSome (:? IQueryable as filtered) -> Assert.AreEqual([ 2; 3 ], filtered |> Seq.toList) + | other -> Assert.Fail(sprintf "a quoted argument is read without evaluating, got %A" other) + +[] +let ``a quote that uses an outer lambda's parameter is not evaluated``() = + let call = whereGreaterThan (Expression.Parameter(typeof, "outer")) + Assert.AreEqual(ValueNone, readByReflection call) + Assert.Throws(fun () -> evaluate call |> ignore) |> ignore + +type Counter() = + let mutable calls = 0 + member _.Calls = calls + member _.Next() = + calls <- calls + 1 + calls + member _.Missing() : string = + calls <- calls + 1 + null + +[] +let ``a captured method is called once``() = + let call (counter: Counter) (name: string) = Expression.Call(constant counter, typeof.GetMethod name) :> Expression + let max = typeof.GetMethod("Max", [| typeof; typeof |]) + let cases: (string * (Counter -> Expression)) list = + [ "under a conversion that computes a value", fun c -> Expression.Convert(call c "Next", typeof) + "beside an argument that is interpreted", fun c -> Expression.Call(max, call c "Next", Expression.Negate(constant 4)) + "before a member of its null result", fun c -> Expression.Property(call c "Missing", "Length") ] + for name, build in cases do + let counter = Counter() + try evaluate (build counter) |> ignore + with :? NullReferenceException -> () + Assert.AreEqual(1, counter.Calls, name) + +[] +let ``calls left to the interpreter``() = + let point = { X = 1; Y = 2 } + let structCall = Expression.Call(constant point, typeof.GetMethod("ToString", Type.EmptyTypes)) + Assert.AreEqual(ValueNone, readByReflection structCall) + Assert.AreEqual(box (point.ToString()), evaluate structCall) + let unreadableArgument = Expression.Call(typeof.GetMethod("Abs", [| typeof |]), Expression.Negate(constant 4)) + Assert.AreEqual(ValueNone, readByReflection unreadableArgument) + Assert.AreEqual(box 4, evaluate unreadableArgument) + +[] +let ``a method of null throws as compiled code does``() = + let call = Expression.Call(Expression.Constant(null, typeof), typeof.GetMethod("ToUpperInvariant")) + Assert.Throws(fun () -> evaluate call |> ignore) |> ignore + +[] +let ``a method's exception is raised as it is``() = + let call = Expression.Call(typeof.GetMethod("Fail")) + Assert.Throws(fun () -> evaluate call |> ignore) |> ignore + +let private addConstant (value: int) = + let x = Expression.Parameter(typeof, "x") + Expression.Lambda>(Expression.Add(x, Expression.Constant value), x) + +[] +let ``lambdas that differ only in constants share one compiled shape``() = + let first = compile (addConstant 1000001) :?> Func + let before = cachedShapes () + let second = compile (addConstant 1000002) :?> Func + Assert.AreEqual(before, cachedShapes ()) + Assert.AreEqual(1000011, first.Invoke 10) + Assert.AreEqual(1000012, second.Invoke 10) + +[] +let ``lambdas of other shapes are not mixed up``() = + let x = Expression.Parameter(typeof, "x") + let multiply = Expression.Lambda>(Expression.Multiply(x, Expression.Constant 3), x) + Assert.AreEqual(30, (compile multiply :?> Func).Invoke 10) + Assert.AreEqual(13, (compile (addConstant 3) :?> Func).Invoke 10) + let a, b = Expression.Parameter(typeof, "a"), Expression.Parameter(typeof, "b") + let aMinusB = Expression.Lambda>(Expression.Subtract(a, b), a, b) + let bMinusA = Expression.Lambda>(Expression.Subtract(b, a), a, b) + Assert.AreEqual(7, (compile aMinusB :?> Func).Invoke(10, 3)) + Assert.AreEqual(-7, (compile bMinusA :?> Func).Invoke(10, 3)) + +[] +let ``a constant used twice and two constants of one value are each bound``() = + let x = Expression.Parameter(typeof, "x") + let shared = Expression.Constant 2000001 + let twice = Expression.Lambda>(Expression.Add(x, Expression.Add(shared, shared)), x) + let distinct = Expression.Lambda>(Expression.Add(x, Expression.Add(Expression.Constant 2000001, Expression.Constant 5)), x) + Assert.AreEqual(4000002, (compile twice :?> Func).Invoke 0) + Assert.AreEqual(2000006, (compile distinct :?> Func).Invoke 0) + +[] +let ``compiled lambdas keep reference, null and nullable constants``() = + let s = Expression.Parameter(typeof, "s") + let concat = typeof.GetMethod("Concat", [| typeof; typeof |]) + let prefixed (prefix: string) = Expression.Lambda>(Expression.Call(concat, Expression.Constant(prefix, typeof), s), s) + Assert.AreEqual("ab", (compile (prefixed "a") :?> Func).Invoke "b") + Assert.AreEqual("b", (compile (prefixed null) :?> Func).Invoke "b") + let n = Expression.Parameter(typeof>, "n") + let orDefault (value: Nullable) = Expression.Lambda, Nullable>>(Expression.Coalesce(n, Expression.Constant(value, typeof>)), n) + Assert.AreEqual(Nullable 4, (compile (orDefault (Nullable 4)) :?> Func, Nullable>).Invoke(Nullable())) + Assert.AreEqual(Nullable(), (compile (orDefault (Nullable())) :?> Func, Nullable>).Invoke(Nullable())) + +[] +let ``a lambda holding a quote is compiled without the cache``() = + let inner = Expression.Lambda>(Expression.Constant 3000001) + let quoting = Expression.Lambda>(Expression.Convert(Expression.Quote inner, typeof)) + let before = cachedShapes () + let quoted = (compile quoting :?> Func).Invoke() :?> Expression> + Assert.AreEqual(before, cachedShapes ()) + Assert.AreEqual(3000001, quoted.Compile().Invoke()) diff --git a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj index 14951dfca..c1c02e714 100644 --- a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj +++ b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj @@ -36,6 +36,7 @@ + From 457c709d1b060216c6f4815c2b2862d0e566791f Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sun, 22 Nov 2026 10:15:04 +0000 Subject: [PATCH 2/4] net8 design-time fix --- src/Directory.Build.targets | 18 ++++++++++++++++++ src/SQLProvider.Common/AssemblyInfo.fs | 8 ++++---- src/SQLProvider.DesignTime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.DuckDb.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.MsSql.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.MySql.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.Odbc.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.Oracle.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.Runtime/AssemblyInfo.fs | 8 ++++---- .../AssemblyInfo.fs | 8 ++++---- src/SQLProvider.SQLite.Runtime/AssemblyInfo.fs | 8 ++++---- .../CapturedValueQueryTests.fs | 3 ++- 27 files changed, 120 insertions(+), 101 deletions(-) create mode 100644 src/Directory.Build.targets diff --git a/src/Directory.Build.targets b/src/Directory.Build.targets new file mode 100644 index 000000000..5e893fcfb --- /dev/null +++ b/src/Directory.Build.targets @@ -0,0 +1,18 @@ + + + + 8.0.403 + true + + + + + + + + + diff --git a/src/SQLProvider.Common/AssemblyInfo.fs b/src/SQLProvider.Common/AssemblyInfo.fs index 1b5c50110..5fef6cc71 100644 --- a/src/SQLProvider.Common/AssemblyInfo.fs +++ b/src/SQLProvider.Common/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Common" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type provider for SQL database access, common library" - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.DesignTime/AssemblyInfo.fs b/src/SQLProvider.DesignTime/AssemblyInfo.fs index 290192077..559fbac7b 100644 --- a/src/SQLProvider.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for any SQL database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.DuckDb.DesignTime/AssemblyInfo.fs b/src/SQLProvider.DuckDb.DesignTime/AssemblyInfo.fs index ac6266b28..8863395d2 100644 --- a/src/SQLProvider.DuckDb.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.DuckDb.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.DuckDb.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for DuckDb database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.DuckDb.Runtime/AssemblyInfo.fs b/src/SQLProvider.DuckDb.Runtime/AssemblyInfo.fs index c810ccbc6..b9b49e185 100644 --- a/src/SQLProvider.DuckDb.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.DuckDb.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.DuckDb.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for DuckDb database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Firebird.DesignTime/AssemblyInfo.fs b/src/SQLProvider.Firebird.DesignTime/AssemblyInfo.fs index e89f9fc76..84ea0145e 100644 --- a/src/SQLProvider.Firebird.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.Firebird.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Firebird.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Firebird database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Firebird.Runtime/AssemblyInfo.fs b/src/SQLProvider.Firebird.Runtime/AssemblyInfo.fs index c764a4721..625465a7b 100644 --- a/src/SQLProvider.Firebird.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.Firebird.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Firebird.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Firebird database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MsAccess.DesignTime/AssemblyInfo.fs b/src/SQLProvider.MsAccess.DesignTime/AssemblyInfo.fs index 2c0a51f5c..cc74b092a 100644 --- a/src/SQLProvider.MsAccess.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.MsAccess.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MsAccess.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Microsoft Access database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MsAccess.Runtime/AssemblyInfo.fs b/src/SQLProvider.MsAccess.Runtime/AssemblyInfo.fs index 456f20163..e11e11e84 100644 --- a/src/SQLProvider.MsAccess.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.MsAccess.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MsAccess.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Microsoft Access database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MsSql.DesignTime/AssemblyInfo.fs b/src/SQLProvider.MsSql.DesignTime/AssemblyInfo.fs index b636c6326..2c11c8a01 100644 --- a/src/SQLProvider.MsSql.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.MsSql.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MsSql.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Microsoft SQL Server database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MsSql.Runtime/AssemblyInfo.fs b/src/SQLProvider.MsSql.Runtime/AssemblyInfo.fs index 9c8cb42a7..86c93dd63 100644 --- a/src/SQLProvider.MsSql.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.MsSql.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MsSql.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Microsoft SQL Server database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MySql.DesignTime/AssemblyInfo.fs b/src/SQLProvider.MySql.DesignTime/AssemblyInfo.fs index c9aff7df9..dafd4b277 100644 --- a/src/SQLProvider.MySql.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.MySql.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MySql.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for MySQL database and MariaDB database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MySql.Runtime/AssemblyInfo.fs b/src/SQLProvider.MySql.Runtime/AssemblyInfo.fs index 7499c298c..716dbaf68 100644 --- a/src/SQLProvider.MySql.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.MySql.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MySql.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for MySQL database and MariaDB database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MySqlConnector.DesignTime/AssemblyInfo.fs b/src/SQLProvider.MySqlConnector.DesignTime/AssemblyInfo.fs index 196ed0fdc..aa15faeb9 100644 --- a/src/SQLProvider.MySqlConnector.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.MySqlConnector.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MySqlConnector.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for MySQL database and MariaDB database access via MySqlConnector." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.MySqlConnector.Runtime/AssemblyInfo.fs b/src/SQLProvider.MySqlConnector.Runtime/AssemblyInfo.fs index 2baf38433..ca4889c6f 100644 --- a/src/SQLProvider.MySqlConnector.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.MySqlConnector.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.MySqlConnector.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for MySQL database and MariaDB database access via MySqlConnector." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Odbc.DesignTime/AssemblyInfo.fs b/src/SQLProvider.Odbc.DesignTime/AssemblyInfo.fs index 071e15c17..52a24f83c 100644 --- a/src/SQLProvider.Odbc.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.Odbc.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Odbc.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for any ODBC connection database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Odbc.Runtime/AssemblyInfo.fs b/src/SQLProvider.Odbc.Runtime/AssemblyInfo.fs index a4342bcdf..0e6a9e19e 100644 --- a/src/SQLProvider.Odbc.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.Odbc.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Odbc.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for any ODBC connection database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Oracle.DesignTime/AssemblyInfo.fs b/src/SQLProvider.Oracle.DesignTime/AssemblyInfo.fs index 9d36a0de0..75abdc840 100644 --- a/src/SQLProvider.Oracle.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.Oracle.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Oracle.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Oracle database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Oracle.Runtime/AssemblyInfo.fs b/src/SQLProvider.Oracle.Runtime/AssemblyInfo.fs index 15c9c13d2..3dc680aba 100644 --- a/src/SQLProvider.Oracle.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.Oracle.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Oracle.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for Oracle database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.PostgreSql.DesignTime/AssemblyInfo.fs b/src/SQLProvider.PostgreSql.DesignTime/AssemblyInfo.fs index 66ba846d9..1f9be2269 100644 --- a/src/SQLProvider.PostgreSql.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.PostgreSql.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.PostgreSql.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for PostgreSql database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.PostgreSql.Runtime/AssemblyInfo.fs b/src/SQLProvider.PostgreSql.Runtime/AssemblyInfo.fs index f132b4212..a164fadce 100644 --- a/src/SQLProvider.PostgreSql.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.PostgreSql.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.PostgreSql.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for PostgreSql database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Postgresql.DesignTime/AssemblyInfo.fs b/src/SQLProvider.Postgresql.DesignTime/AssemblyInfo.fs index 66ba846d9..1f9be2269 100644 --- a/src/SQLProvider.Postgresql.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.Postgresql.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.PostgreSql.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for PostgreSql database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Postgresql.Runtime/AssemblyInfo.fs b/src/SQLProvider.Postgresql.Runtime/AssemblyInfo.fs index f132b4212..a164fadce 100644 --- a/src/SQLProvider.Postgresql.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.Postgresql.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.PostgreSql.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for PostgreSql database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.Runtime/AssemblyInfo.fs b/src/SQLProvider.Runtime/AssemblyInfo.fs index 298f7abe8..b354b1db7 100644 --- a/src/SQLProvider.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for any SQL database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.SQLite.DesignTime/AssemblyInfo.fs b/src/SQLProvider.SQLite.DesignTime/AssemblyInfo.fs index cdd7f0150..e34d50bb6 100644 --- a/src/SQLProvider.SQLite.DesignTime/AssemblyInfo.fs +++ b/src/SQLProvider.SQLite.DesignTime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.SQLite.DesignTime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for SQLite database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/src/SQLProvider.SQLite.Runtime/AssemblyInfo.fs b/src/SQLProvider.SQLite.Runtime/AssemblyInfo.fs index 80abbe71f..14ddebb54 100644 --- a/src/SQLProvider.SQLite.Runtime/AssemblyInfo.fs +++ b/src/SQLProvider.SQLite.Runtime/AssemblyInfo.fs @@ -5,13 +5,13 @@ open System.Reflection [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = let [] AssemblyTitle = "SQLProvider.SQLite.Runtime" let [] AssemblyProduct = "SQLProvider" let [] AssemblyDescription = "Type providers for SQLite database access." - let [] AssemblyVersion = "1.5.34" - let [] AssemblyFileVersion = "1.5.34" + let [] AssemblyVersion = "1.5.35" + let [] AssemblyFileVersion = "1.5.35" diff --git a/tests/SqlProvider.Tests/CapturedValueQueryTests.fs b/tests/SqlProvider.Tests/CapturedValueQueryTests.fs index 6652fdbd5..a5318545a 100644 --- a/tests/SqlProvider.Tests/CapturedValueQueryTests.fs +++ b/tests/SqlProvider.Tests/CapturedValueQueryTests.fs @@ -106,7 +106,8 @@ let ``a member of a null owner is not supported``() = let ``a getter that throws raises its error``() = let dc = sql.GetDataContext() let throwing = Throwing() - Assert.Throws(fun () -> + // The getter's own exception, not reflection's TargetInvocationException around it + Assert.Throws(fun () -> query { for c in dc.Main.Customers do where (c.CustomerId = throwing.Value); select c.CustomerId } |> Seq.length |> ignore) |> ignore From 48e9d7d116576b20fd294c3080fdf01425fc447e Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sun, 22 Nov 2026 11:06:13 +0000 Subject: [PATCH 3/4] net48 fix --- src/SQLProvider.Common/SqlRuntime.Patterns.fs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/SQLProvider.Common/SqlRuntime.Patterns.fs b/src/SQLProvider.Common/SqlRuntime.Patterns.fs index 259289ee3..3c8306ea6 100644 --- a/src/SQLProvider.Common/SqlRuntime.Patterns.fs +++ b/src/SQLProvider.Common/SqlRuntime.Patterns.fs @@ -66,6 +66,15 @@ let rec private isReadable (e:Expression) = not finder.Found | _ -> false +#if NETSTANDARD2_0 +/// LambdaExpression.Compile(preferInterpretation), or null where the runtime doesn't have it: the netstandard2.0 +/// build also runs on .NET Framework, which has the method only from 4.7.1. +let private compilePreferringInterpretation : Func = + match typeof.GetMethod("Compile", [| typeof |]) with + | null -> null + | compile -> Delegate.CreateDelegate(typeof>, compile) :?> Func +#endif + /// Runs a parameterless expression interpreted, as compiling it would JIT code that runs once. let private interpret (e:Expression) : obj = let body = @@ -74,9 +83,14 @@ let private interpret (e:Expression) : obj = let lambda = Expression.Lambda> body #if NET461 || NET462 lambda.Compile().Invoke() +#else +#if NETSTANDARD2_0 + if isNull compilePreferringInterpretation then lambda.Compile().Invoke() + else (compilePreferringInterpretation.Invoke(lambda, true) :?> Func).Invoke() #else lambda.Compile(preferInterpretation = true).Invoke() #endif +#endif /// The value of an expression isReadable accepts, each part of it evaluated once. Where reflection doesn't answer as /// compiled code does (a member of null or of a Nullable, a conversion that computes a new value), the node is From 451b30449a9277b78b03b2f47ff1550e7ad72a43 Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sun, 22 Nov 2026 12:46:40 +0000 Subject: [PATCH 4/4] code cleanup with fsharp-refactor tool --- docs/content/core/composable.fsx | 4 ++-- docs/content/core/crud.fsx | 4 ++-- docs/content/core/locking.fsx | 2 +- docs/content/core/querying.fsx | 2 ++ src/SQLProvider.Common/SqlRuntime.Common.fs | 14 +++++++++----- src/SQLProvider.Common/SqlRuntime.Patterns.fs | 6 +++++- src/SQLProvider.Common/Utils.fs | 10 +++++++--- src/SQLProvider.DesignTime/SqlDesignTime.fs | 15 ++++++++------- src/SQLProvider.Runtime/Providers.DuckDb.fs | 4 ++-- src/SQLProvider.Runtime/Providers.Firebird.fs | 4 ++-- src/SQLProvider.Runtime/Providers.MySql.fs | 6 +++++- src/SQLProvider.Runtime/Providers.Postgresql.fs | 10 +++++----- src/SQLProvider.Runtime/Providers.SQLite.fs | 2 +- src/SQLProvider.Runtime/SqlRuntime.DataContext.fs | 2 +- .../ExpressionEvaluationTests.fs | 4 ++-- tests/SqlProvider.Tests/LockingTests.fs | 2 +- tests/SqlProvider.Tests/QueryTests.fs | 8 ++++---- tests/SqlProvider.Tests/SchemaCacheFileTests.fs | 8 ++++---- tests/SqlProvider.Tests/SchemaTypeNameTests.fs | 12 +++++++----- tests/SqlProvider.Tests/SqlCheck.fs | 6 ++++-- .../more/SubqueryCompositionTests.fs | 10 +++++----- 21 files changed, 79 insertions(+), 56 deletions(-) diff --git a/docs/content/core/composable.fsx b/docs/content/core/composable.fsx index 11943b3ed..fd7d91abd 100644 --- a/docs/content/core/composable.fsx +++ b/docs/content/core/composable.fsx @@ -181,12 +181,12 @@ open System.Linq let nestedQueryTest = let qry1 = query { for emp in ctx.Main.Employees do - where (emp.FirstName.StartsWith("S")) + where (emp.FirstName.StartsWith "S") select emp.FirstName } query { for emp in ctx.Main.Employees do - where (qry1.Contains(emp.FirstName)) + where (qry1.Contains emp.FirstName) select (emp.FirstName, emp.LastName) } |> Seq.toArray diff --git a/docs/content/core/crud.fsx b/docs/content/core/crud.fsx index e3e1b1370..92641d438 100644 --- a/docs/content/core/crud.fsx +++ b/docs/content/core/crud.fsx @@ -59,7 +59,7 @@ row.CustomerId <- customer.CustomerId row.EmployeeId <- employee.EmployeeId row.Freight <- 10M row.OrderDate <- now.AddDays(-1.0) -row.RequiredDate <- now.AddDays(1.0) +row.RequiredDate <- now.AddDays 1.0 row.ShipAddress <- "10 Downing St" row.ShipCity <- "London" row.ShipName <- "Dragons den" @@ -188,7 +188,7 @@ output of .ColumnValues: employees |> Seq.map (fun x -> - ctx.Main.Employees.Create(x.ColumnValues)) // create twins + ctx.Main.Employees.Create x.ColumnValues) // create twins |> Seq.toList /// Retrieve the FSharp.Data.Sql.Common.SqlEntity objects diff --git a/docs/content/core/locking.fsx b/docs/content/core/locking.fsx index 325dde055..e19dd2908 100644 --- a/docs/content/core/locking.fsx +++ b/docs/content/core/locking.fsx @@ -173,7 +173,7 @@ let saveFreight (orderId: int64) (freightSeen: decimal) (newFreight: decimal) = use scope = new TransactionScope( TransactionScopeOption.Required, - TransactionOptions(IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted), + TransactionOptions(IsolationLevel = IsolationLevel.ReadCommitted), TransactionScopeAsyncFlowOption.Enabled) let ctx = sql.GetDataContext() diff --git a/docs/content/core/querying.fsx b/docs/content/core/querying.fsx index 05428987d..37783c8e8 100644 --- a/docs/content/core/querying.fsx +++ b/docs/content/core/querying.fsx @@ -114,7 +114,9 @@ let xs2 = *) // query parameters: +[] let allCountries = false // or true +[] let onlyCountry = "Finland" // or "" query { for c in ctx.Main.Customers do diff --git a/src/SQLProvider.Common/SqlRuntime.Common.fs b/src/SQLProvider.Common/SqlRuntime.Common.fs index d1053df41..e62b40ff0 100644 --- a/src/SQLProvider.Common/SqlRuntime.Common.fs +++ b/src/SQLProvider.Common/SqlRuntime.Common.fs @@ -966,7 +966,7 @@ and SchemaCache = use ms = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText(filePath))) let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof) // Schema files saved before 1.5.34 may carry individuals in the schema file itself: they're kept. - let loaded = ser.ReadObject(ms) :?> SchemaCache + let loaded = ser.ReadObject ms :?> SchemaCache let cache = { loaded with IsOffline = true @@ -995,7 +995,7 @@ and SchemaCache = File.WriteAllText(filePath, Encoding.UTF8.GetString(json, 0, json.Length)) static member private ReadJson<'T>(filePath) = use ms = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText filePath)) - System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof<'T>).ReadObject(ms) :?> 'T + System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof<'T>).ReadObject ms :?> 'T /// Saves the schema, and the descriptions and the individuals read so far to their own files. Individuals are /// not in the schema file, and each table is in the individuals file once: see SaveIndividuals. member this.Save(filePath) = @@ -1056,7 +1056,11 @@ and SchemaCache = // The offset is that of the machine that saved the file. With it the date is as the database gave it, // whatever the time zone of the machine that reads the file. let offset = m.Groups.[2].Value +#if NETSTANDARD21 + let minutes = Int32.Parse(offset.AsSpan(1, 2)) * 60 + Int32.Parse(offset.AsSpan(3, 2)) +#else let minutes = Int32.Parse(offset.Substring(1, 2)) * 60 + Int32.Parse(offset.Substring(3, 2)) +#endif let saved = utc.AddMinutes(float (if offset.[0] = '-' then -minutes else minutes)) Some (DateTime.SpecifyKind(saved, DateTimeKind.Unspecified)) /// A primary key value read from a file, as the design time has it online: in the type of its column. The file @@ -1103,7 +1107,7 @@ and SchemaCache = let keys = [ table.FullName; tableKey; table.Name ] match SchemaCache.TryFindKeyed(this.PrimaryKeys, keys), SchemaCache.TryFindKeyed(this.Columns, keys) with | Some [ pk ], Some columns -> - let key = table.FullName + "_" + pk + let key = $"{table.FullName}_{pk}" match this.Individuals.TryGetValue key, columns.TryFind pk with | (true, entities), Some column when not (isNull entities) -> let clrType = try Utilities.getType column.TypeMapping.ClrType with _ -> null @@ -1350,12 +1354,12 @@ module CommonTasks = |> List.choose (fun (_, key) -> match key with | KeyColumn name -> Some(name.ToUpperInvariant()) - | _ -> None) + | CanonicalOperation _ | GroupColumn _ -> None) |> Set.ofList let alias = Seq.initInfinite (fun extra -> sprintf "sqlp_key%i%s" index (String.replicate extra "_")) |> Seq.find (fun name -> not (taken.Contains(name.ToUpperInvariant()))) - sprintf "%s as %s" notation alias + $"%s{notation} as %s{alias}" | _ -> plain /// The select list of a grouped query: the key columns (`keys`, in the order of the groupings' Keys) of each diff --git a/src/SQLProvider.Common/SqlRuntime.Patterns.fs b/src/SQLProvider.Common/SqlRuntime.Patterns.fs index 3c8306ea6..4ca9ae363 100644 --- a/src/SQLProvider.Common/SqlRuntime.Patterns.fs +++ b/src/SQLProvider.Common/SqlRuntime.Patterns.fs @@ -20,7 +20,7 @@ let private unwrapInvocation (read: unit -> obj) = /// Nullable. A numeric, enum or user-defined conversion computes a new value, so it isn't one. let private convertsAsIs (u:UnaryExpression) (value:obj) = isNull u.Method - && (if isNull value then not u.Type.IsValueType || not (isNull (Nullable.GetUnderlyingType u.Type)) + && (if isNull value then not (u.Type.IsValueType && isNull (Nullable.GetUnderlyingType u.Type)) else u.Type.IsInstanceOfType value) /// Value types whose methods don't change the value. Reflection calls a method on a boxed copy, which compiled code @@ -430,7 +430,11 @@ let (|SqlNegativeCondOp|_|) (e:Expression) = let (|MethodCallOrFSharpWrap|_|) (e:Expression) = match e.NodeType, e with | ExpressionType.Call, (:? MethodCallExpression as e) -> +#if NETSTANDARD21 + if isNull e.Object && e.Method.Name.Contains('$') && e.Arguments.Count = 2 && e.Method.DeclaringType.FullName = "Microsoft.FSharp.Core.Operators" then +#else if isNull e.Object && e.Method.Name.Contains("$") && e.Arguments.Count = 2 && e.Method.DeclaringType.FullName = "Microsoft.FSharp.Core.Operators" then +#endif match e.Arguments.[0].NodeType, e.Arguments.[0] with | ExpressionType.Call, (:? MethodCallExpression as ec) when ec.Method.Name = "ToFSharpFunc" && ec.Arguments.Count = 1 -> match ec.Arguments.[0] with diff --git a/src/SQLProvider.Common/Utils.fs b/src/SQLProvider.Common/Utils.fs index ea15e6c79..95d4129b2 100644 --- a/src/SQLProvider.Common/Utils.fs +++ b/src/SQLProvider.Common/Utils.fs @@ -885,14 +885,14 @@ module Sql = /// Reads rows of a name and its description to a dictionary. Rows without a description are left out, /// and of rows with the same name the first one counts. let readDescriptions (reader:IDataReader) = - let descriptions = System.Collections.Generic.Dictionary() + let descriptions = Dictionary() while reader.Read() do - if not (reader.IsDBNull 0) && not (reader.IsDBNull 1) then + if not (reader.IsDBNull 0 || reader.IsDBNull 1) then let name = reader.GetValue(0).ToString() let description = reader.GetValue(1).ToString() if description <> "" && not (descriptions.ContainsKey name) then descriptions.[name] <- description - descriptions :> System.Collections.Generic.IDictionary + descriptions :> IDictionary /// The Guid of a text that is one; any other value as it is. The key of an individual with a Guid key is text, /// because a Guid can't be a constant in a provided quotation, and not every database takes text for a Guid parameter. @@ -908,7 +908,11 @@ module Sql = /// it is in quotes in FullName (quoteWhiteSpace): those quotes are left out, so the name is as the database has it. let tableSchemaAndName (fullName:string) = let unquote (name:string) = +#if NETSTANDARD21 + if name.Length > 1 && name.StartsWith "\"" && name.EndsWith "\"" && name.Contains ' ' then name.Substring(1, name.Length - 2) +#else if name.Length > 1 && name.StartsWith "\"" && name.EndsWith "\"" && name.Contains " " then name.Substring(1, name.Length - 2) +#endif else name if fullName.Length > 1 && fullName.StartsWith "\"" && fullName.EndsWith "\"" then "", unquote fullName else // A quoted name may have a dot in it: it starts after the schema's ." diff --git a/src/SQLProvider.DesignTime/SqlDesignTime.fs b/src/SQLProvider.DesignTime/SqlDesignTime.fs index 3f981475d..acbba030c 100644 --- a/src/SQLProvider.DesignTime/SqlDesignTime.fs +++ b/src/SQLProvider.DesignTime/SqlDesignTime.fs @@ -1,6 +1,7 @@ namespace FSharp.Data.Sql open System +open System.Collections.Concurrent open System.Data open System.IO open System.Reflection @@ -160,7 +161,7 @@ module DesignTimeUtils = match con with | Some con -> let description = match prov.GetColumnDescription(con, tableName, columnName) with null -> "" | d -> d - descriptions.GetOrAdd(tableName, fun _ -> System.Collections.Concurrent.ConcurrentDictionary()).[columnName] <- description + descriptions.GetOrAdd(tableName, fun _ -> ConcurrentDictionary()).[columnName] <- description Some description | None -> offlineDescriptions.Force() @@ -821,7 +822,7 @@ module DesignTimeUtils = // Schema container types are per-build on purpose: sharing them across rebuilds would // mutate types that another (VS) thread may concurrently enumerate, and would // accumulate duplicate members on every rebuild. - let schemaTypes = System.Collections.Concurrent.ConcurrentDictionary() + let schemaTypes = ConcurrentDictionary() let getOrAddSchema (name:string) = schemaTypes.GetOrAdd(name, fun nme -> ProvidedTypeDefinition(nme + "Schema", Some typeof, isErased=true)) @@ -839,7 +840,7 @@ module DesignTimeUtils = let mutable count = 0 for table in tables.Force() do try if read table then count <- count + 1 - with e -> failed.Add(table.FullName + ": " + e.Message) + with e -> failed.Add $"{table.FullName}: {e.Message}" count // A stored procedure's parameters and return columns are read when IntelliSense opens its type, and @@ -853,8 +854,8 @@ module DesignTimeUtils = let nested = try nestedTypes [||] with e -> - let name = if isNull t.DeclaringType then t.Name else t.DeclaringType.Name + "." + t.Name - failed.Add(name + ": " + e.Message) + let name = if isNull t.DeclaringType then t.Name else $"{t.DeclaringType.Name}.{t.Name}" + failed.Add $"{name}: {e.Message}" [||] for n in nested do openTypes failed n @@ -875,7 +876,7 @@ module DesignTimeUtils = | :? IColumnDescriptionsProvider as allColumns -> // One query for the table, instead of one for each column let described = allColumns.GetColumnDescriptions(connection, table.FullName) - let known = schemaCache().ColumnDescriptions.GetOrAdd(table.FullName, fun _ -> System.Collections.Concurrent.ConcurrentDictionary()) + let known = schemaCache().ColumnDescriptions.GetOrAdd(table.FullName, fun _ -> ConcurrentDictionary()) for KeyValue(_, column) in columns do known.[column.Name] <- match described.TryGetValue column.Name with @@ -1501,7 +1502,7 @@ type DesignCacheEntry = mutable LastAccess : int64 } module DesignTimeCache = - let cache = System.Collections.Concurrent.ConcurrentDictionary() + let cache = ConcurrentDictionary() /// The idea of this is trying to avoid case where compile-time has loaded non-runtime assembly. (Happens in .NET 8.0, not in .NET Framework.) /// So let's load compile-time (and design-time) manually the required runtime assembly. diff --git a/src/SQLProvider.Runtime/Providers.DuckDb.fs b/src/SQLProvider.Runtime/Providers.DuckDb.fs index 3282842dd..e8d448bad 100644 --- a/src/SQLProvider.Runtime/Providers.DuckDb.fs +++ b/src/SQLProvider.Runtime/Providers.DuckDb.fs @@ -137,7 +137,7 @@ module DuckDb = let mapping = if not (isNull value || sprocCommand) then (findClrType (value.GetType().ToString())) else None let value = if isNull value then (box DBNull.Value) else value // DuckDB names a parameter without a prefix: the name of $id is id, and the key of an individual comes as @id - let name = param.Name.TrimStart('@') + let name = param.Name.TrimStart '@' #if REFLECTIONLOAD let parameterType = parameterType.Value @@ -620,7 +620,7 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re [ while reader.Read() do let table ={ Schema = reader.GetString 0; Name = reader.GetString 1; Type=reader.GetString 2 } yield schemaCache.Tables.GetOrAdd(table |> quotedTableName,table) ] |> List.toArray - executeSql DuckDb.createCommand (sprintf "select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE from INFORMATION_SCHEMA.TABLES where %s in (%s)" caseChane dbName) con) + executeSql DuckDb.createCommand $"select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE from INFORMATION_SCHEMA.TABLES where %s{caseChane} in (%s{dbName})" con) member __.GetPrimaryKey(table) = match schemaCache.PrimaryKeys.TryGetValue (table |> quotedTableName) with diff --git a/src/SQLProvider.Runtime/Providers.Firebird.fs b/src/SQLProvider.Runtime/Providers.Firebird.fs index 308341ede..73d01ad7d 100644 --- a/src/SQLProvider.Runtime/Providers.Firebird.fs +++ b/src/SQLProvider.Runtime/Providers.Firebird.fs @@ -425,9 +425,9 @@ module Firebird = /// Whether each procedure is executable: it has no SUSPEND, so it gives its output parameters once and can't be /// selected from. By connection and procedure name. - let private executables = System.Collections.Concurrent.ConcurrentDictionary() + let private executables = ConcurrentDictionary() - let private procedureKey (com: IDbCommand) = com.Connection.ConnectionString + "\n" + com.CommandText + let private procedureKey (com: IDbCommand) = $"{com.Connection.ConnectionString}\n{com.CommandText}" /// Asks whether the procedure a command names is executable (RDB$PROCEDURE_TYPE 2; 1 is selectable). let private executableLookup (com: IDbCommand) = diff --git a/src/SQLProvider.Runtime/Providers.MySql.fs b/src/SQLProvider.Runtime/Providers.MySql.fs index 01040ab80..253a08f33 100644 --- a/src/SQLProvider.Runtime/Providers.MySql.fs +++ b/src/SQLProvider.Runtime/Providers.MySql.fs @@ -271,6 +271,10 @@ module MySql = let procName = (Sql.dbUnboxWithDefault (Guid.NewGuid().ToString()) row.["specific_name"]) { ProcName = procName; Owner = sprocSchema; PackageName = String.Empty; } + [] + let inline private (|IsDBNull|_|) (input: obj) = + if Convert.IsDBNull input then ValueSome input else ValueNone + let getSprocParameters (con:IDbConnection) (name:SprocName) = let createSprocParameters (row:DataRow) = let dataType = Sql.dbUnbox row.["data_type"] @@ -278,7 +282,7 @@ module MySql = // MySQL 8 gives the length as bigint and the position as bigint unsigned; before it both were int let maxLength = match row.["character_maximum_length"] with - | length when Convert.IsDBNull length -> ValueNone + | IsDBNull _ -> ValueNone | length -> ValueSome(int (min (Convert.ToInt64 length) (int64 Int32.MaxValue))) findDbType dataType diff --git a/src/SQLProvider.Runtime/Providers.Postgresql.fs b/src/SQLProvider.Runtime/Providers.Postgresql.fs index f1cba3f2e..9136978ef 100644 --- a/src/SQLProvider.Runtime/Providers.Postgresql.fs +++ b/src/SQLProvider.Runtime/Providers.Postgresql.fs @@ -402,9 +402,9 @@ module PostgreSQL = null /// Whether each routine is a procedure (PostgreSQL 11 and newer), by connection and the command text of its call. - let private procedures = System.Collections.Concurrent.ConcurrentDictionary() + let private procedures = ConcurrentDictionary() - let private routineKey (com: IDbCommand) = com.Connection.ConnectionString + "\n" + com.CommandText + let private routineKey (com: IDbCommand) = $"{com.Connection.ConnectionString}\n{com.CommandText}" /// Asks whether the routine a command names is a procedure. The command text is the routine's name, or its quoted /// schema and name. @@ -434,8 +434,8 @@ module PostgreSQL = else None) |> String.concat ", " com.CommandText <- - if isProcedure then sprintf "CALL %s(%s)" com.CommandText arguments - else sprintf "SELECT * FROM %s(%s)" com.CommandText arguments + if isProcedure then $"CALL %s{com.CommandText}(%s{arguments})" + else $"SELECT * FROM %s{com.CommandText}(%s{arguments})" com.CommandType <- CommandType.Text /// A command that names a routine as a stored procedure becomes the text of its call, by what the routine is. @@ -985,7 +985,7 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer PostgreSQL.createCommandParameter (QueryParameter.Create("@schema", 0)) table.Schema |> command.Parameters.Add |> ignore PostgreSQL.createCommandParameter (QueryParameter.Create("@table", 1)) table.Name |> command.Parameters.Add |> ignore Sql.connect con (fun _ -> - command.CommandText <- columnsQuery (con :?> System.Data.Common.DbConnection).ServerVersion baseQuery + command.CommandText <- columnsQuery (con :?> DbConnection).ServerVersion baseQuery use reader = command.ExecuteReader() let columns = [ while reader.Read() do diff --git a/src/SQLProvider.Runtime/Providers.SQLite.fs b/src/SQLProvider.Runtime/Providers.SQLite.fs index ea725c776..ae3ab41d0 100644 --- a/src/SQLProvider.Runtime/Providers.SQLite.fs +++ b/src/SQLProvider.Runtime/Providers.SQLite.fs @@ -1186,7 +1186,7 @@ type internal SQLiteProvider(resolutionPath, contextSchemaPath, referencedAssemb task { // close the connection first otherwise it won't get enlisted into the transaction if con.State = ConnectionState.Open then con.Close() - con.Open() + do! con.OpenAsync() use trans = con.BeginTransaction(TransactionUtils.toSystemDataIsolationLevel transactionOptions.IsolationLevel) //System.Data.IsolationLevel. transactionOptions.IsolationLevel) try do! processFunc (Some trans) diff --git a/src/SQLProvider.Runtime/SqlRuntime.DataContext.fs b/src/SQLProvider.Runtime/SqlRuntime.DataContext.fs index b8e31fa01..f06fc9516 100644 --- a/src/SQLProvider.Runtime/SqlRuntime.DataContext.fs +++ b/src/SQLProvider.Runtime/SqlRuntime.DataContext.fs @@ -108,7 +108,7 @@ type public SqlDataContext (typeName, connectionString:string, providerType:Data && not (String.Equals(name.Owner, con.Database, StringComparison.OrdinalIgnoreCase)) -> let quoted (identifier: string) = "`" + identifier.Replace("`", "``") + "`" quoted name.Owner + "." + quoted name.ProcName - | DatabaseProviderTypes.ORACLE when not (String.IsNullOrEmpty name.Owner) -> name.Owner + "." + name.DbName + | DatabaseProviderTypes.ORACLE when not (String.IsNullOrEmpty name.Owner) -> $"{name.Owner}.{name.DbName}" | _ -> name.DbName /// IoC: A factory that can be used to extend custom SQLProvider implementations from separate Nuget packages diff --git a/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs b/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs index 21d0b9d8f..035a1b525 100644 --- a/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs +++ b/tests/SqlProvider.Tests/ExpressionEvaluationTests.fs @@ -184,7 +184,7 @@ let private whereGreaterThan (limit: Expression) = let ``a call with a quoted argument passes the expression``() = match readByReflection (whereGreaterThan (constant 1)) with | ValueSome (:? IQueryable as filtered) -> Assert.AreEqual([ 2; 3 ], filtered |> Seq.toList) - | other -> Assert.Fail(sprintf "a quoted argument is read without evaluating, got %A" other) + | other -> Assert.Fail($"a quoted argument is read without evaluating, got %A{other}") [] let ``a quote that uses an outer lambda's parameter is not evaluated``() = @@ -233,7 +233,7 @@ let ``a method of null throws as compiled code does``() = [] let ``a method's exception is raised as it is``() = - let call = Expression.Call(typeof.GetMethod("Fail")) + let call = Expression.Call(typeof.GetMethod "Fail") Assert.Throws(fun () -> evaluate call |> ignore) |> ignore let private addConstant (value: int) = diff --git a/tests/SqlProvider.Tests/LockingTests.fs b/tests/SqlProvider.Tests/LockingTests.fs index d6a880b9c..e5e3bde7e 100644 --- a/tests/SqlProvider.Tests/LockingTests.fs +++ b/tests/SqlProvider.Tests/LockingTests.fs @@ -45,7 +45,7 @@ let private textWith (connection: Data.IDbConnection) (provider: ISqlProvider) ( let projection = Collections.Generic.Dictionary>() projection.["m"] <- ResizeArray [ EntityColumn "id" ] let sql, _ = provider.GenerateQueryText(query, "m", mark, projection, false, connection) - (SqlCheck.normalise sql).Trim().TrimEnd(';') + (SqlCheck.normalise sql).Trim().TrimEnd ';' let private text (provider: ISqlProvider) (query: SqlQuery) = textWith null provider query diff --git a/tests/SqlProvider.Tests/QueryTests.fs b/tests/SqlProvider.Tests/QueryTests.fs index 14a5b12a1..f45b0ffb3 100644 --- a/tests/SqlProvider.Tests/QueryTests.fs +++ b/tests/SqlProvider.Tests/QueryTests.fs @@ -2071,7 +2071,7 @@ let ``simple select with bool outside query``() = query { for cust in dc.Main.Customers do // Simple booleans outside queries are supported: - where (((myCond1 && myCond1=true) && cust.City="Helsinki" || myCond1) || cust.City="London") + where (((myCond1) && cust.City="Helsinki" || myCond1) || cust.City="London") // Boolean in select fetches just either country or address, not both: select (if not myCond3 then cust.Country else cust.Address) } |> Seq.toArray @@ -3372,7 +3372,7 @@ let ``groupBy with value-option columns in the key keeps their types``() = select (cust.Country, cust.CustomerId, cust.Region, cust.Fax, order.ShippedDate, order.OrderId) } |> Seq.toArray |> Array.filter (fun (country, _, _, _, _, _) -> country = ValueSome "Germany" || country = ValueSome "Venezuela") - |> Array.groupBy (fun (_, id, region, fax, shipped, _) -> (id, region, fax, shipped)) + |> Array.groupBy (fun (_, pid, region, fax, shipped, _) -> (pid, region, fax, shipped)) |> Array.map (fun (key, rows) -> key, rows |> Array.map (fun (_, _, _, _, _, oid) -> oid) |> Array.min) |> Array.sort Assert.IsTrue(expected |> Array.exists (fun ((_, region, _, _), _) -> region.IsNone)) @@ -3398,7 +3398,7 @@ let ``groupBy with option columns in the key keeps their types``() = select (cust.Country, cust.CustomerId, cust.Region, order.ShippedDate) } |> Seq.toArray |> Array.filter (fun (country, _, _, _) -> country = Some "Germany" || country = Some "Venezuela") - |> Array.countBy (fun (_, id, region, shipped) -> (id, region, shipped)) + |> Array.countBy (fun (_, pid, region, shipped) -> (pid, region, shipped)) |> Array.sort Assert.IsTrue(expected |> Array.exists (fun ((_, _, shipped), _) -> shipped.IsNone)) Assert.AreEqual(expected, actual) @@ -3421,7 +3421,7 @@ let ``groupBy with a computed IsSome in the key``() = select (cust.Country, cust.CustomerId, order.ShipCountry, order.ShippedDate) } |> Seq.toArray |> Array.filter (fun (country, _, _, _) -> country = ValueSome "Germany" || country = ValueSome "Venezuela") - |> Array.countBy (fun (_, id, shipCountry, shipped) -> (id, shipCountry, shipped.IsSome)) + |> Array.countBy (fun (_, pid, shipCountry, shipped) -> (pid, shipCountry, shipped.IsSome)) |> Array.sort Assert.IsTrue(expected |> Array.exists (fun ((_, _, shipped), _) -> not shipped)) Assert.AreEqual(expected, actual) diff --git a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs index 56f88e4b0..c3adc7524 100644 --- a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs +++ b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs @@ -17,7 +17,7 @@ let private tempSchemaPath () = Path.Combine(dir, "schema.json") let private customers () : (obj * IDictionary) array = - [| for i in 1 .. 3 -> box i, (dict [ "Id", box i; "Name", box (sprintf "Customer %d" i) ]) |] + [| for i in 1 .. 3 -> box i, (dict [ "Id", box i; "Name", box $"Customer %d{i}" ]) |] let private withCustomers (cache:SchemaCache) = cache.Tables.["main.Customers"] <- { Schema = "main"; Name = "Customers"; Type = "TABLE" } @@ -363,7 +363,7 @@ let private providerKeys () = "Firebird", "Longs", "Longs", "Longs" "Oracle", "main.Longs", "Longs", "main.Longs" ] -let private keyedAs (tableKey, primaryKeyKey, columnKey) = +let private keyedAs tableKey primaryKeyKey columnKey = let cache = keyed "main.Longs" typeof [ box 7L ] rekeyed cache.Tables tableKey rekeyed cache.PrimaryKeys primaryKeyKey @@ -374,7 +374,7 @@ let private keyedAs (tableKey, primaryKeyKey, columnKey) = let ``a table's columns and primary key are found however the provider keys them`` () = let table = { Schema = "main"; Name = "Longs"; Type = "TABLE" } for provider, tableKey, primaryKeyKey, columnKey in providerKeys () do - let cache = keyedAs (tableKey, primaryKeyKey, columnKey) + let cache = keyedAs tableKey primaryKeyKey columnKey Assert.AreEqual(Some [ "Id" ], cache.TryFindByTable(cache.PrimaryKeys, table), provider) Assert.IsTrue((cache.TryFindByTable(cache.Columns, table) |> Option.exists (fun columns -> columns.ContainsKey "Id")), provider) Assert.AreEqual(None, cache.TryFindByTable(cache.Columns, { table with Name = "Others" }), provider) @@ -383,7 +383,7 @@ let ``a table's columns and primary key are found however the provider keys them let ``primary keys of individuals are read back as they are online however the provider keys the schema`` () = for provider, tableKey, primaryKeyKey, columnKey in providerKeys () do let path = tempSchemaPath () - let cache = keyedAs (tableKey, primaryKeyKey, columnKey) + let cache = keyedAs tableKey primaryKeyKey columnKey cache.Save path cache.SaveIndividuals path |> ignore let loaded = SchemaCache.Load path diff --git a/tests/SqlProvider.Tests/SchemaTypeNameTests.fs b/tests/SqlProvider.Tests/SchemaTypeNameTests.fs index 358d14d34..730f4b7ad 100644 --- a/tests/SqlProvider.Tests/SchemaTypeNameTests.fs +++ b/tests/SqlProvider.Tests/SchemaTypeNameTests.fs @@ -7,9 +7,11 @@ open System.Net open FSharp.Data.Sql.Common open NUnit.Framework -let private savedOnNet10 name assembly token = sprintf "%s, %s, Version=10.0.0.0, Culture=neutral, PublicKeyToken=%s" name assembly token -let private savedOnNetFramework name assembly token = sprintf "%s, %s, Version=4.0.0.0, Culture=neutral, PublicKeyToken=%s" name assembly token +let private savedOnNet10 name assembly token = $"%s{name}, %s{assembly}, Version=10.0.0.0, Culture=neutral, PublicKeyToken=%s{token}" +let private savedOnNetFramework name assembly token = $"%s{name}, %s{assembly}, Version=4.0.0.0, Culture=neutral, PublicKeyToken=%s{token}" +[] let private coreLib = "7cec85d7bea7798e" +[] let private mscorlib = "b77a5c561934e089" [] @@ -41,15 +43,15 @@ let ``a type in another assembly on the other runtime resolves`` () = [] let ``the arguments of a generic type resolve as well`` () = let stringOnNet10 = savedOnNet10 "System.String" "System.Private.CoreLib" coreLib - let hstore = sprintf "System.Collections.Generic.IDictionary`2[[%s],[%s]]" stringOnNet10 stringOnNet10 + let hstore = $"System.Collections.Generic.IDictionary`2[[%s{stringOnNet10}],[%s{stringOnNet10}]]" Assert.AreEqual(typeof>, Utilities.getType (savedOnNet10 hstore "System.Private.CoreLib" coreLib)) let stringOnNetFramework = savedOnNetFramework "System.String" "mscorlib" mscorlib - let hstore = sprintf "System.Collections.Generic.IDictionary`2[[%s],[%s]]" stringOnNetFramework stringOnNetFramework + let hstore = $"System.Collections.Generic.IDictionary`2[[%s{stringOnNetFramework}],[%s{stringOnNetFramework}]]" Assert.AreEqual(typeof>, Utilities.getType (savedOnNetFramework hstore "mscorlib" mscorlib)) let nullableInts = sprintf "System.Nullable`1[[%s]][]" (savedOnNet10 "System.Int32" "System.Private.CoreLib" coreLib) Assert.AreEqual(typeof[]>, Utilities.getType (savedOnNet10 nullableInts "System.Private.CoreLib" coreLib)) let ipAddress = savedOnNet10 "System.Net.IPAddress" "System.Net.Primitives" "b03f5f7f11d50a3a" - Assert.AreEqual(typeof>, Utilities.getType (savedOnNet10 (sprintf "System.Lazy`1[[%s]]" ipAddress) "System.Private.CoreLib" coreLib)) + Assert.AreEqual(typeof>, Utilities.getType (savedOnNet10 $"System.Lazy`1[[%s{ipAddress}]]" "System.Private.CoreLib" coreLib)) [] let ``a name without an assembly is not searched in the loaded assemblies`` () = diff --git a/tests/SqlProvider.Tests/SqlCheck.fs b/tests/SqlProvider.Tests/SqlCheck.fs index 05df8d07a..0f63f64e7 100644 --- a/tests/SqlProvider.Tests/SqlCheck.fs +++ b/tests/SqlProvider.Tests/SqlCheck.fs @@ -44,10 +44,12 @@ let private subscribed = | [ only ] -> only.Enqueue e.Command | _ -> ())) +let private normaliseRegex = Regex @"\s+" +let private normaliseRegex2 = Regex @"\s*([(),])\s*" /// Upper case, single spaces, no spaces around parentheses or commas. let normalise (sql: string) = - let spaced = Regex.Replace(sql.ToUpperInvariant(), @"\s+", " ") - Regex.Replace(spaced, @"\s*([(),])\s*", "$1") + let spaced = normaliseRegex.Replace(sql.ToUpperInvariant(), " ") + normaliseRegex2.Replace(spaced, "$1") /// The expectations no command meets. let unmet (expectations: string seq) (commands: string list) = diff --git a/tests/SqlProvider.Tests/more/SubqueryCompositionTests.fs b/tests/SqlProvider.Tests/more/SubqueryCompositionTests.fs index b6933a8bc..f02759ca5 100644 --- a/tests/SqlProvider.Tests/more/SubqueryCompositionTests.fs +++ b/tests/SqlProvider.Tests/more/SubqueryCompositionTests.fs @@ -376,7 +376,7 @@ let ``parameters of a subquery nested in another subquery are bound``() = let chosen = query { for order in dc.Main.Orders do - where ((allCases || order.CustomerId.Value = onlyCase) && (not openOnly || not (bigOrders.Contains order.OrderId))) + where ((allCases || order.CustomerId.Value = onlyCase) && (not (openOnly && bigOrders.Contains order.OrderId))) select order.OrderId } let runQuery () = @@ -389,7 +389,7 @@ let ``parameters of a subquery nested in another subquery are bound``() = let bigIds = query { for d in dc.Main.OrderDetails do select (d.OrderId, d.Quantity) } |> Seq.filter (fun (_, q) -> q > minQty) |> Seq.map fst |> Set.ofSeq let expected = query { for o in dc.Main.Orders do select (o.OrderId, o.CustomerId) } - |> Seq.filter (fun (id, c) -> c = ValueSome onlyCase && not (bigIds.Contains id)) + |> Seq.filter (fun (pid, c) -> c = ValueSome onlyCase && not (bigIds.Contains pid)) |> Seq.map fst |> Seq.toArray |> Array.sort Assert.IsNotEmpty expected @@ -428,7 +428,7 @@ let ``parameters of three nested subquery levels are bound``() = let bigIds = query { for d in dc.Main.OrderDetails do select (d.OrderId, d.Quantity) } |> Seq.filter (fun (_, q) -> q > minQty) |> Seq.map fst |> Set.ofSeq let expected = query { for o in dc.Main.Orders do select (o.OrderId, o.ShipCountry, o.CustomerId) } - |> Seq.filter (fun (id, c, _) -> c = ValueSome country && bigIds.Contains id) + |> Seq.filter (fun (pid, c, _) -> c = ValueSome country && bigIds.Contains pid) |> Seq.map (fun (_, _, cust) -> cust.Value) |> Seq.distinct |> Seq.toArray |> Array.sort Assert.IsNotEmpty expected @@ -521,7 +521,7 @@ let ``a union of grouped sub-queries gives one column to IN on both sides``() = let latestBy key = query { for o in dc.Main.Orders do select (o.CustomerId, o.EmployeeId, o.OrderId) } - |> Seq.groupBy key |> Seq.map (fun (_, rows) -> rows |> Seq.map (fun (_, _, id) -> id) |> Seq.max) + |> Seq.groupBy key |> Seq.map (fun (_, rows) -> rows |> Seq.map (fun (_, _, pid) -> pid) |> Seq.max) let expected = Seq.append (latestBy (fun (customer, _, _) -> box customer)) (latestBy (fun (_, employee, _) -> box employee)) @@ -694,7 +694,7 @@ let ``an IN sub-query with arithmetic the database computes still runs``() = } |> Seq.toArray |> Array.sort let ids = query { for o in dc.Main.Orders do select o.OrderId } |> Seq.toArray - let next = ids |> Array.map (fun id -> id + 1L) |> Set.ofArray + let next = ids |> Array.map (fun pid -> pid + 1L) |> Set.ofArray let expected = ids |> Array.filter next.Contains |> Array.sort Assert.IsNotEmpty expected