diff --git a/.editorconfig b/.editorconfig index 3bd8453..3398f13 100644 --- a/.editorconfig +++ b/.editorconfig @@ -43,7 +43,7 @@ fsharp_space_before_lowercase_invocation=true # false: x.ToString() # true: x.ToString () # default false -fsharp_space_before_uppercase_invocation=true +fsharp_space_before_uppercase_invocation=false # false: new Ship(withBeans) # true: new Ship (withBeans) diff --git a/src/FSharp.AWS.DynamoDB/Expression/ConditionalExpr.fs b/src/FSharp.AWS.DynamoDB/Expression/ConditionalExpr.fs index 92cce56..2deb8bf 100644 --- a/src/FSharp.AWS.DynamoDB/Expression/ConditionalExpr.fs +++ b/src/FSharp.AWS.DynamoDB/Expression/ConditionalExpr.fs @@ -76,7 +76,7 @@ type QueryExpr with match r with | False -> False | True -> l - | _ -> And (l, r) + | _ -> And(l, r) static member EOr l r = match l with @@ -86,7 +86,7 @@ type QueryExpr with match r with | True -> True | False -> l - | _ -> Or (l, r) + | _ -> Or(l, r) static member ENot q = match q with @@ -121,15 +121,15 @@ let extractKeyCondition (qExpr: QueryExpr) = | In _ | Not _ | Or _ -> false - | And (l, r) -> isKeyCond l && isKeyCond r - | BeginsWith (attr, _) when attr.IsRangeKey -> trySet rangeKeyRef attr - | BeginsWith (attr, _) when attr.IsHashKey -> false - | BeginsWith (attr, _) when attr.IsRangeKey -> trySet rangeKeyRef attr + | And(l, r) -> isKeyCond l && isKeyCond r + | BeginsWith(attr, _) when attr.IsRangeKey -> trySet rangeKeyRef attr + | BeginsWith(attr, _) when attr.IsHashKey -> false + | BeginsWith(attr, _) when attr.IsRangeKey -> trySet rangeKeyRef attr | BeginsWith _ -> false - | Between (Attribute attr, (Value _ | Param _), (Value _ | Param _)) when attr.IsRangeKey -> trySet rangeKeyRef attr + | Between(Attribute attr, (Value _ | Param _), (Value _ | Param _)) when attr.IsRangeKey -> trySet rangeKeyRef attr | Between _ -> false - | Compare (cmp, Attribute attr, (Value _ | Param _)) - | Compare (cmp, (Value _ | Param _), Attribute attr) -> + | Compare(cmp, Attribute attr, (Value _ | Param _)) + | Compare(cmp, (Value _ | Param _), Attribute attr) -> if attr.IsHashKey && cmp = EQ then trySet hashKeyRef attr elif attr.IsRangeKey then trySet rangeKeyRef attr else false @@ -171,7 +171,7 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp let nParams, (|PVar|_|), expr' = extractExprParams recordInfo expr match expr' with - | Lambda (r, body) when r.Type = recordInfo.Type -> + | Lambda(r, body) when r.Type = recordInfo.Type -> let getAttrValue (pickler: Pickler) (expr: Expr) = expr |> evalRaw |> pickler.PickleCoerced @@ -179,7 +179,7 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp match QuotedAttribute.TryExtract (|PVar|_|) r recordInfo e with | None -> None | Some qa as aopt -> - qa.Iter (fun pickler -> + qa.Iter(fun pickler -> if pickler.PicklerType = PicklerType.Serialized then invalidArg "expr" "cannot perform queries on serialized attributes.") @@ -195,8 +195,8 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp match getAttrValue pickler expr with | None -> Undefined - | Some av -> Value (wrap av) - | Coerce (e, _) + | Some av -> Value(wrap av) + | Coerce(e, _) | PipeLeft e | PipeRight e -> extractOperand pickler e | AttributeGet attr -> Attribute attr.Id @@ -206,14 +206,14 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp | Some p -> p | None -> Pickler.resolveUntyped expr.Type - Param (i, pickler) - | SpecificProperty <@ fun (s: string) -> s.Length @> (Some (AttributeGet attr), _, []) -> SizeOf attr.Id - | SpecificProperty <@ fun (l: _ list) -> l.Length @> (Some (AttributeGet attr), _, []) -> SizeOf attr.Id + Param(i, pickler) + | SpecificProperty <@ fun (s: string) -> s.Length @> (Some(AttributeGet attr), _, []) -> SizeOf attr.Id + | SpecificProperty <@ fun (l: _ list) -> l.Length @> (Some(AttributeGet attr), _, []) -> SizeOf attr.Id | SpecificCall2 <@ List.length @> (None, _, _, [ AttributeGet attr ]) -> SizeOf attr.Id - | SpecificProperty <@ fun (s: Set<_>) -> s.Count @> (Some (AttributeGet attr), _, []) -> SizeOf attr.Id + | SpecificProperty <@ fun (s: Set<_>) -> s.Count @> (Some(AttributeGet attr), _, []) -> SizeOf attr.Id | SpecificCall2 <@ Set.count @> (None, _, _, [ AttributeGet attr ]) -> SizeOf attr.Id - | SpecificProperty <@ fun (m: Map<_, _>) -> m.Count @> (Some (AttributeGet attr), _, []) -> SizeOf attr.Id - | SpecificProperty <@ fun (a: _[]) -> a.Length @> (Some (AttributeGet attr), _, []) -> SizeOf attr.Id + | SpecificProperty <@ fun (m: Map<_, _>) -> m.Count @> (Some(AttributeGet attr), _, []) -> SizeOf attr.Id + | SpecificProperty <@ fun (a: _[]) -> a.Length @> (Some(AttributeGet attr), _, []) -> SizeOf attr.Id | SpecificCall2 <@ Array.length @> (None, _, _, [ AttributeGet attr ]) -> SizeOf attr.Id | _ -> invalidQuery () @@ -234,8 +234,8 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp match op with | Value av when av.AttributeValue.S <> null -> FField av.AttributeValue.S - | Value av when av.AttributeValue.N <> null -> FIndex (int av.AttributeValue.N) - | Param (i, _) -> FParam i + | Value av when av.AttributeValue.N <> null -> FIndex(int av.AttributeValue.N) + | Param(i, _) -> FParam i | _ -> invalidQuery () let (|Comparison|_|) (pat: Expr) (expr: Expr) = @@ -253,7 +253,7 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp | Some p -> p | None -> Pickler.resolveUntyped args.[0].Type - Some (pickler, operands) + Some(pickler, operands) | _ -> None @@ -283,47 +283,47 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp if left = Undefined then assignUndefined right elif right = Undefined then assignUndefined left - else Compare (cmp, left, right) + else Compare(cmp, left, right) let rec extractQuery (expr: Expr) = match expr with | e when e.IsClosed -> if evalRaw e then True else False - | SpecificCall <@ not @> (None, _, [ body ]) -> QueryExpr.ENot (extractQuery body) - | AndAlso (left, right) -> QueryExpr.EAnd (extractQuery left) (extractQuery right) - | OrElse (left, right) -> QueryExpr.EOr (extractQuery left) (extractQuery right) + | SpecificCall <@ not @> (None, _, [ body ]) -> QueryExpr.ENot(extractQuery body) + | AndAlso(left, right) -> QueryExpr.EAnd (extractQuery left) (extractQuery right) + | OrElse(left, right) -> QueryExpr.EOr (extractQuery left) (extractQuery right) | PipeLeft e | PipeRight e -> extractQuery e - | AttributeGet attr -> Compare (EQ, Attribute attr.Id, Value (wrap (AttributeValue (BOOL = true)))) + | AttributeGet attr -> Compare(EQ, Attribute attr.Id, Value(wrap (AttributeValue(BOOL = true)))) | Comparison <@ (=) @> (p, [ left; right ]) -> extractComparison p EQ left right | Comparison <@ (<>) @> (p, [ left; right ]) -> extractComparison p NE left right | Comparison <@ (<) @> (p, [ left; right ]) -> extractComparison p LT left right | Comparison <@ (>) @> (p, [ left; right ]) -> extractComparison p GT left right | Comparison <@ (<=) @> (p, [ left; right ]) -> extractComparison p LE left right | Comparison <@ (>=) @> (p, [ left; right ]) -> extractComparison p GE left right - | SpecificCall2 <@ fun (x: string) y -> x.StartsWith y @> (Some (AttributeGet attr), _, _, [ value ]) -> + | SpecificCall2 <@ fun (x: string) y -> x.StartsWith y @> (Some(AttributeGet attr), _, _, [ value ]) -> let op = extractOperand None value - BeginsWith (attr.Id, op) - | SpecificCall2 <@ fun (x: string) y -> x.Contains y @> (Some (AttributeGet attr), _, _, [ value ]) -> + BeginsWith(attr.Id, op) + | SpecificCall2 <@ fun (x: string) y -> x.Contains y @> (Some(AttributeGet attr), _, _, [ value ]) -> let op = extractOperand None value - Contains (attr.Id, op) + Contains(attr.Id, op) | SpecificCall2 <@ Set.contains @> (None, _, _, [ elem; AttributeGet attr ]) | SpecificCall2 <@ Array.contains @> (None, _, _, [ elem; AttributeGet attr ]) | SpecificCall2 <@ List.contains @> (None, _, _, [ elem; AttributeGet attr ]) -> let ep = getElemPickler attr.Pickler let op = extractOperand (Some ep) elem - Contains (attr.Id, op) - | SpecificCall2 <@ Array.contains @> (None, _, _, [ AttributeGet attr; SequenceGet items ]) -> In (Attribute attr.Id, items) - | SpecificCall2 <@ List.contains @> (None, _, _, [ AttributeGet attr; SequenceGet items ]) -> In (Attribute attr.Id, items) - | SpecificCall2 <@ fun (x: Set<_>) e -> x.Contains e @> (Some (AttributeGet attr), _, _, [ elem ]) -> + Contains(attr.Id, op) + | SpecificCall2 <@ Array.contains @> (None, _, _, [ AttributeGet attr; SequenceGet items ]) -> In(Attribute attr.Id, items) + | SpecificCall2 <@ List.contains @> (None, _, _, [ AttributeGet attr; SequenceGet items ]) -> In(Attribute attr.Id, items) + | SpecificCall2 <@ fun (x: Set<_>) e -> x.Contains e @> (Some(AttributeGet attr), _, _, [ elem ]) -> let ep = getElemPickler attr.Pickler let op = extractOperand (Some ep) elem - Contains (attr.Id, op) + Contains(attr.Id, op) | SpecificCall2 <@ Map.containsKey @> (None, _, _, [ key; AttributeGet attr ]) -> let nf = extractNestedField key - Attribute_Exists (attr.Id.Append nf) - | SpecificCall2 <@ fun (x: Map<_, _>) y -> x.ContainsKey y @> (Some (AttributeGet attr), _, _, [ key ]) when key.IsClosed -> + Attribute_Exists(attr.Id.Append nf) + | SpecificCall2 <@ fun (x: Map<_, _>) y -> x.ContainsKey y @> (Some(AttributeGet attr), _, _, [ key ]) when key.IsClosed -> let nf = extractNestedField key - Attribute_Exists (attr.Id.Append nf) + Attribute_Exists(attr.Id.Append nf) | SpecificCall2 <@ BETWEEN @> (None, _, _, [ value; lower; upper ]) -> let pickler = Pickler.resolveUntyped value.Type @@ -332,7 +332,7 @@ let extractQueryExpr (recordInfo: RecordTableInfo) (expr: Expr) : ConditionalExp let vOp = extractOperand sc value let lOp = extractOperand sc lower let uOp = extractOperand sc upper - Between (vOp, lOp, uOp) + Between(vOp, lOp, uOp) else invalidArg "expr" "BETWEEN predicate only applies to scalar attributes." | SpecificCall2 <@ EXISTS @> (None, _, _, [ AttributeGet attr ]) -> Attribute_Exists attr.Id @@ -358,27 +358,27 @@ let applyParams (cond: ConditionalExpression) (inputValues: obj[]) = let applyOperand (op: Operand) = match op with - | Param (i, pickler) -> + | Param(i, pickler) -> match pickler.PickleCoerced inputValues.[i] with - | Some av -> Value (wrap av) + | Some av -> Value(wrap av) | None -> Undefined - | Attribute attr -> Attribute (applyAttr attr) + | Attribute attr -> Attribute(applyAttr attr) | _ -> op let rec applyQuery q = match q with | False | True -> q - | Attribute_Exists attr -> Attribute_Exists (applyAttr attr) - | Attribute_Not_Exists attr -> Attribute_Not_Exists (applyAttr attr) - | Not q -> QueryExpr.ENot (applyQuery q) - | And (q, q') -> QueryExpr.EAnd (applyQuery q) (applyQuery q') - | Or (q, q') -> QueryExpr.EOr (applyQuery q) (applyQuery q') - | In (o, os) -> In (applyOperand o, Array.map applyOperand os) - | Between (x, l, u) -> Between (applyOperand x, applyOperand l, applyOperand u) - | BeginsWith (attr, o) -> BeginsWith (applyAttr attr, applyOperand o) - | Contains (attr, o) -> Contains (applyAttr attr, applyOperand o) - | Compare (cmp, l, r) -> + | Attribute_Exists attr -> Attribute_Exists(applyAttr attr) + | Attribute_Not_Exists attr -> Attribute_Not_Exists(applyAttr attr) + | Not q -> QueryExpr.ENot(applyQuery q) + | And(q, q') -> QueryExpr.EAnd (applyQuery q) (applyQuery q') + | Or(q, q') -> QueryExpr.EOr (applyQuery q) (applyQuery q') + | In(o, os) -> In(applyOperand o, Array.map applyOperand os) + | Between(x, l, u) -> Between(applyOperand x, applyOperand l, applyOperand u) + | BeginsWith(attr, o) -> BeginsWith(applyAttr attr, applyOperand o) + | Contains(attr, o) -> Contains(applyAttr attr, applyOperand o) + | Compare(cmp, l, r) -> let l' = applyOperand l let r' = applyOperand r @@ -386,14 +386,14 @@ let applyParams (cond: ConditionalExpression) (inputValues: obj[]) = match op with | Attribute attr -> match cmp with - | NE -> Attribute_Exists (applyAttr attr) - | EQ -> Attribute_Not_Exists (applyAttr attr) + | NE -> Attribute_Exists(applyAttr attr) + | EQ -> Attribute_Not_Exists(applyAttr attr) | _ -> True | _ -> invalidOp "internal error; assigning undefined value to non attribute path." if l' = Undefined then assignUndefined r' elif r' = Undefined then assignUndefined l' - else Compare (cmp, l', r') + else Compare(cmp, l', r') let reduced = applyQuery cond.QueryExpr do ensureNotTautological reduced @@ -401,14 +401,14 @@ let applyParams (cond: ConditionalExpression) (inputValues: obj[]) = /// prints a query expression to string recognizable by the DynamoDB APIs let writeConditionExpression (writer: AttributeWriter) (cond: ConditionalExpression) = - let sb = new System.Text.StringBuilder () + let sb = new System.Text.StringBuilder() let inline (!) (p: string) = sb.Append p |> ignore let inline writeOp o = match o with | Undefined -> invalidOp "internal error: attempting to reference undefined value in query expression." | Param _ -> invalidOp "internal error: attempting to reference parameter value in query expression." - | Value v -> !(writer.WriteValue (unwrap v)) + | Value v -> !(writer.WriteValue(unwrap v)) | Attribute a -> !(writer.WriteAttibute a) | SizeOf a -> ! "( size ( " @@ -443,25 +443,25 @@ let writeConditionExpression (writer: AttributeWriter) (cond: ConditionalExpress ! "( NOT " writeQuery q ! " )" - | And (l, r) -> + | And(l, r) -> ! "( " writeQuery l ! " AND " writeQuery r ! " )" - | Or (l, r) -> + | Or(l, r) -> ! "( " writeQuery l ! " OR " writeQuery r ! " )" - | Compare (cmp, l, r) -> + | Compare(cmp, l, r) -> ! "( " writeOp l writeCmp cmp writeOp r ! " )" - | Between (v, l, u) -> + | Between(v, l, u) -> ! "( " writeOp v ! " BETWEEN " @@ -469,13 +469,13 @@ let writeConditionExpression (writer: AttributeWriter) (cond: ConditionalExpress ! " AND " writeOp u ! " )" - | BeginsWith (attr, op) -> + | BeginsWith(attr, op) -> ! "( begins_with ( " !(writer.WriteAttibute attr) ! ", " writeOp op ! " ))" - | Contains (attr, op) -> + | Contains(attr, op) -> ! "( contains ( " !(writer.WriteAttibute attr) ! ", " @@ -489,7 +489,7 @@ let writeConditionExpression (writer: AttributeWriter) (cond: ConditionalExpress ! "( attribute_not_exists ( " !(writer.WriteAttibute attr) ! "))" - | In (op, ops) -> + | In(op, ops) -> ! "(" writeOp op ! " IN (" @@ -497,7 +497,7 @@ let writeConditionExpression (writer: AttributeWriter) (cond: ConditionalExpress ! "))" writeQuery cond.QueryExpr - sb.ToString () + sb.ToString() /// Generates a conditional that verifies whether a given item exists let mkItemExistsCondition (schema: TableKeySchema) = @@ -515,7 +515,7 @@ let mkItemNotExistsCondition (schema: TableKeySchema) = let mkHashKeyEqualityCondition (schema: TableKeySchema) (av: AttributeValue) = let hkAttrId = AttributeId.FromKeySchema schema - { QueryExpr = Compare (EQ, Attribute hkAttrId, Value (wrap av)) + { QueryExpr = Compare(EQ, Attribute hkAttrId, Value(wrap av)) KeyCondition = Some schema NParams = 0 } @@ -533,7 +533,7 @@ type ConditionalExpression with | None -> None member cond.GetDebugData() = - let aw = new AttributeWriter () + let aw = new AttributeWriter() let expr = writeConditionExpression aw cond let names = @@ -543,7 +543,7 @@ type ConditionalExpression with let values = aw.Values - |> Seq.map (fun kv -> kv.Key, kv.Value.Print ()) + |> Seq.map (fun kv -> kv.Key, kv.Value.Print()) |> Seq.toList expr, names, values @@ -553,7 +553,7 @@ type ConditionalExpression with /// Extract a KeyCondition for records that specify a default hashkey static member TryExtractHashKeyCondition(recordInfo: RecordTableInfo) = match recordInfo.PrimaryKeyStructure with - | DefaultHashKey (_, value, pickler, _) -> + | DefaultHashKey(_, value, pickler, _) -> let av = pickler.PickleUntyped value |> Option.get let cond = mkHashKeyEqualityCondition recordInfo.PrimaryKeySchema av Some cond diff --git a/src/FSharp.AWS.DynamoDB/Expression/ExprCommon.fs b/src/FSharp.AWS.DynamoDB/Expression/ExprCommon.fs index 53a05bf..3692d6e 100644 --- a/src/FSharp.AWS.DynamoDB/Expression/ExprCommon.fs +++ b/src/FSharp.AWS.DynamoDB/Expression/ExprCommon.fs @@ -50,19 +50,19 @@ type AttributeId = append id.RootId for nf in id.NestedAttributes do - append <| nf.Print ()) + append <| nf.Print()) member id.Name = mkString (fun append -> append id.RootId for nf in id.NestedAttributes do - append <| nf.Print ()) + append <| nf.Print()) member id.Tokens = seq { yield id.RootName - yield! id.NestedAttributes |> Seq.map (fun nf -> nf.Print ()) + yield! id.NestedAttributes |> Seq.map (fun nf -> nf.Print()) } member id.IsHashKey = @@ -96,10 +96,10 @@ type AttributeId = | :? string as f -> FField f | :? int as i -> if i < 0 then - raise <| ArgumentOutOfRangeException () + raise <| ArgumentOutOfRangeException() else FIndex i - | _ -> raise <| new InvalidCastException () + | _ -> raise <| new InvalidCastException() | _ -> nf { id with NestedAttributes = id.NestedAttributes |> List.map applyField } @@ -129,19 +129,19 @@ type QuotedAttribute = /// Gets the pickler corresponding to the type pointed to by the attribute path member ap.Pickler = match ap with - | Root (rp, _) -> rp.Pickler - | Nested (rp, _) -> rp.Pickler - | Item (_, pickler, _) -> pickler - | Optional (p, _) -> p + | Root(rp, _) -> rp.Pickler + | Nested(rp, _) -> rp.Pickler + | Item(_, pickler, _) -> pickler + | Optional(p, _) -> p /// Gets the root record property of given attribute path member ap.RootProperty = let rec aux ap = match ap with - | Root (rp, _) -> rp - | Nested (_, p) -> aux p - | Item (_, _, p) -> aux p - | Optional (_, p) -> aux p + | Root(rp, _) -> rp + | Nested(_, p) -> aux p + | Item(_, _, p) -> aux p + | Optional(_, p) -> aux p aux ap @@ -149,10 +149,10 @@ type QuotedAttribute = member ap.Id = let rec getTokens acc ap = match ap with - | Nested (rp, p) -> getTokens (FField rp.Name :: acc) p - | Item (nf, _, p) -> getTokens (nf :: acc) p - | Optional (_, p) -> getTokens acc p - | Root (rp, schema) -> + | Nested(rp, p) -> getTokens (FField rp.Name :: acc) p + | Item(nf, _, p) -> getTokens (nf :: acc) p + | Optional(_, p) -> getTokens acc p + | Root(rp, schema) -> { RootId = rp.AttrId RootName = rp.Name NestedAttributes = acc @@ -164,14 +164,14 @@ type QuotedAttribute = member ap.Iter(f: Pickler -> unit) = let rec aux ap = match ap with - | Root (rp, _) -> f rp.Pickler - | Nested (rp, p) -> + | Root(rp, _) -> f rp.Pickler + | Nested(rp, p) -> f rp.Pickler aux p - | Item (_, pickler, p) -> + | Item(_, pickler, p) -> f pickler aux p - | Optional (pickler, p) -> + | Optional(pickler, p) -> f pickler aux p @@ -196,32 +196,32 @@ type QuotedAttribute = let rec extractProps props e = match e with - | PropertyGet (Some (Var r'), p, []) when record = r' -> + | PropertyGet(Some(Var r'), p, []) when record = r' -> match tryGetPropInfo info.Properties (List.isEmpty props) p with | None -> None | Some rp -> - let root = Root (rp, info.GetPropertySchemata rp.Name) + let root = Root(rp, info.GetPropertySchemata rp.Name) mkAttrPath root rp.NestedRecord props | SpecificProperty <@ fun (t: _ option) -> t.Value @> (Some e, [ et ], _) -> extractProps (Choice2Of3 et :: props) e | SpecificProperty <@ fun (r: _ ref) -> r.Value @> (Some e, _, _) -> - let p = e.Type.GetProperty ("contents") + let p = e.Type.GetProperty("contents") extractProps (Choice1Of3 p :: props) e - | PropertyGet (Some e, p, []) -> extractProps (Choice1Of3 p :: props) e + | PropertyGet(Some e, p, []) -> extractProps (Choice1Of3 p :: props) e | SpecificCall2 <@ fst @> (None, _, _, [ e ]) -> - let p = e.Type.GetProperty ("Item1") + let p = e.Type.GetProperty("Item1") extractProps (Choice1Of3 p :: props) e | SpecificCall2 <@ snd @> (None, _, _, [ e ]) -> - let p = e.Type.GetProperty ("Item2") + let p = e.Type.GetProperty("Item2") extractProps (Choice1Of3 p :: props) e | SpecificCall2 <@ Option.get @> (None, _, [ et ], [ e ]) -> extractProps (Choice2Of3 et :: props) e - | IndexGet (e, et, i) -> extractProps (Choice3Of3 (et, i) :: props) e + | IndexGet(e, et, i) -> extractProps (Choice3Of3(et, i) :: props) e | _ -> None @@ -231,13 +231,13 @@ type QuotedAttribute = | Choice1Of3 p :: tail, Some rI -> match tryGetPropInfo rI (List.isEmpty tail) p with | None -> None - | Some rp -> mkAttrPath (Nested (rp, acc)) rp.NestedRecord tail + | Some rp -> mkAttrPath (Nested(rp, acc)) rp.NestedRecord tail | Choice2Of3 opt :: tail, None -> let pickler = Pickler.resolveUntyped opt - mkAttrPath (Optional (pickler, acc)) ctx tail + mkAttrPath (Optional(pickler, acc)) ctx tail - | Choice3Of3 (et, ie) :: tail, None -> + | Choice3Of3(et, ie) :: tail, None -> let pickler = Pickler.resolveUntyped et let ctx = @@ -245,14 +245,14 @@ type QuotedAttribute = | :? IRecordPickler as rc -> Some rc.Properties | _ -> None - let inline mkAttrPath indexV = mkAttrPath (Item (indexV, pickler, acc)) ctx tail + let inline mkAttrPath indexV = mkAttrPath (Item(indexV, pickler, acc)) ctx tail match ie with | _ when ie.IsClosed -> match evalRaw ie: obj with | :? int as i -> if i < 0 then - raise <| ArgumentOutOfRangeException () + raise <| ArgumentOutOfRangeException() else mkAttrPath (FIndex i) | :? string as f -> mkAttrPath (FField f) @@ -266,10 +266,10 @@ type QuotedAttribute = /// Wrapper API for writing attribute names and values for Dynamo query expressions type AttributeWriter(names: Dictionary, values: Dictionary) = - static let cmp = new AttributeValueComparer () - let vcontents = new Dictionary (cmp) + static let cmp = new AttributeValueComparer() + let vcontents = new Dictionary(cmp) - new() = new AttributeWriter (new Dictionary<_, _> (), new Dictionary<_, _> ()) + new() = new AttributeWriter(new Dictionary<_, _>(), new Dictionary<_, _>()) member __.Names = names member __.Values = values @@ -281,8 +281,8 @@ type AttributeWriter(names: Dictionary, values: Dictionary, values: Dictionary body @> let extractExprParams (recordInfo: RecordTableInfo) (expr: Expr) = - let vars = new Dictionary () + let vars = new Dictionary() let rec aux i expr = match expr with - | Lambda (v, body) when v.Type <> recordInfo.Type -> - vars.Add (v, i) + | Lambda(v, body) when v.Type <> recordInfo.Type -> + vars.Add(v, i) aux (i + 1) body | _ -> expr @@ -318,24 +318,24 @@ type private AttributeNode = { Value: string; Children: ResizeArray) = - let root = new ResizeArray () + let root = new ResizeArray() let tryAppendPath (attr: AttributeId) = let tokens = attr.Tokens - let enum = tokens.GetEnumerator () + let enum = tokens.GetEnumerator() let mutable ctx = root let mutable isNodeAdded = false let mutable isLeafFound = false - let acc = new ResizeArray<_> () + let acc = new ResizeArray<_>() - while not isLeafFound && enum.MoveNext () do + while not isLeafFound && enum.MoveNext() do let t = enum.Current let child = - match ctx.FindIndex (fun n -> n.Value = t) with + match ctx.FindIndex(fun n -> n.Value = t) with | -1 -> isNodeAdded <- true - let ch = { Value = t; Children = new ResizeArray<_> () } + let ch = { Value = t; Children = new ResizeArray<_>() } ctx.Add ch ch @@ -353,14 +353,14 @@ let tryFindConflictingPaths (attrs: seq) = let concat xs = String.concat "" xs if isLeafFound then - Some (concat tokens, concat acc) + Some(concat tokens, concat acc) elif not isNodeAdded then while ctx.Count > 0 do let ch = ctx.[0] acc.Add ch.Value ctx <- ch.Children - Some (concat tokens, concat acc) + Some(concat tokens, concat acc) else None diff --git a/src/FSharp.AWS.DynamoDB/Expression/ExpressionContainers.fs b/src/FSharp.AWS.DynamoDB/Expression/ExpressionContainers.fs index d8988d2..2b33281 100644 --- a/src/FSharp.AWS.DynamoDB/Expression/ExpressionContainers.fs +++ b/src/FSharp.AWS.DynamoDB/Expression/ExpressionContainers.fs @@ -14,7 +14,7 @@ open FSharp.AWS.DynamoDB.ProjectionExpr /// Represents a condition expression for a given record type [] type ConditionExpression<'TRecord> internal (cond: ConditionalExpression) = - let data = lazy (cond.GetDebugData ()) + let data = lazy (cond.GetDebugData()) /// Gets whether given conditional is a valid key condition member __.IsKeyConditionCompatible = cond.IsKeyConditionCompatible /// Gets the infered local secondary index for the query, if applicable @@ -46,7 +46,7 @@ type ConditionExpression = static member And(left: ConditionExpression<'TRecord>, right: ConditionExpression<'TRecord>) = let qExpr = QueryExpr.EAnd left.Conditional.QueryExpr right.Conditional.QueryExpr ensureNotTautological qExpr - new ConditionExpression<'TRecord> ({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) + new ConditionExpression<'TRecord>({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) /// /// Applies the OR operation on two conditionals @@ -54,7 +54,7 @@ type ConditionExpression = static member Or(left: ConditionExpression<'TRecord>, right: ConditionExpression<'TRecord>) = let qExpr = QueryExpr.EOr left.Conditional.QueryExpr right.Conditional.QueryExpr ensureNotTautological qExpr - new ConditionExpression<'TRecord> ({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) + new ConditionExpression<'TRecord>({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) /// /// Applies the NOT operation on a conditional @@ -62,12 +62,12 @@ type ConditionExpression = static member Not(conditional: ConditionExpression<'TRecord>) = let qExpr = QueryExpr.ENot conditional.Conditional.QueryExpr ensureNotTautological qExpr - new ConditionExpression<'TRecord> ({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) + new ConditionExpression<'TRecord>({ QueryExpr = qExpr; KeyCondition = extractKeyCondition qExpr; NParams = 0 }) /// Represents an update expression for a given record type [] type UpdateExpression<'TRecord> internal (updateOps: UpdateOperations) = - let data = lazy (updateOps.GetDebugData ()) + let data = lazy (updateOps.GetDebugData()) /// Internal update expression object member internal __.UpdateOps = updateOps /// DynamoDB update expression string @@ -84,7 +84,7 @@ type UpdateExpression<'TRecord> internal (updateOps: UpdateOperations) = override __.GetHashCode() = hash updateOps.UpdateOps - static member (&&&)(this: UpdateExpression<'TRecord>, that: UpdateExpression<'TRecord>) = UpdateExpression.Combine (this, that) + static member (&&&)(this: UpdateExpression<'TRecord>, that: UpdateExpression<'TRecord>) = UpdateExpression.Combine(this, that) and UpdateExpression = /// Combines a collection of compatible update expressions into a single expression. @@ -102,16 +102,16 @@ and UpdateExpression = |> tryFindConflictingPaths with | None -> () - | Some (p1, p2) -> + | Some(p1, p2) -> let msg = sprintf "found conflicting paths '%s' and '%s' being accessed in update expression." p1 p2 invalidArg "expr" msg - new UpdateExpression<'TRecord> ({ UpdateOps = uops; NParams = 0 }) + new UpdateExpression<'TRecord>({ UpdateOps = uops; NParams = 0 }) /// Represents a projection expression for a given record type [] type ProjectionExpression<'TRecord, 'TProjection> internal (expr: ProjectionExpr) = - let data = lazy (expr.GetDebugData ()) + let data = lazy (expr.GetDebugData()) /// Internal projection expression object member internal __.ProjectionExpr = expr /// DynamoDB projection expression string diff --git a/src/FSharp.AWS.DynamoDB/Expression/ProjectionExpr.fs b/src/FSharp.AWS.DynamoDB/Expression/ProjectionExpr.fs index 529bf06..700095d 100644 --- a/src/FSharp.AWS.DynamoDB/Expression/ProjectionExpr.fs +++ b/src/FSharp.AWS.DynamoDB/Expression/ProjectionExpr.fs @@ -42,7 +42,7 @@ type AttributeId with let ok, nested = av.M.TryGetValue f if not ok then notFound tl else aux result tl nested else - av.Print () + av.Print() |> sprintf "Expected map, but was '%s'." |> InvalidCastException |> raise @@ -56,7 +56,7 @@ type AttributeId with else aux result tl av.L.[i] else - av.Print () + av.Print() |> sprintf "Expected list, but was '%s'." |> InvalidCastException |> raise @@ -87,13 +87,13 @@ type ProjectionExpr = let invalidExpr () = invalidArg "expr" "supplied expression is not a valid projection." match expr with - | Lambda (r, body) when r.Type = recordInfo.Type -> + | Lambda(r, body) when r.Type = recordInfo.Type -> let (|AttributeGet|_|) expr = QuotedAttribute.TryExtract (fun _ -> None) r recordInfo expr let (|Ignore|_|) e = match e with - | Value (null, t) when t = typeof -> Some () - | SpecificCall2 <@ ignore @> _ -> Some () + | Value(null, t) when t = typeof -> Some() + | SpecificCall2 <@ ignore @> _ -> Some() | _ -> None match body with @@ -107,7 +107,7 @@ type ProjectionExpr = let ctor (ro: RestObject) = let mutable av = null - let ok = attr.View (ro, &av) + let ok = attr.View(ro, &av) if ok then pickler.UnPickleUntyped av @@ -129,7 +129,7 @@ type ProjectionExpr = // check for conflicting projection attributes match tryFindConflictingPaths attrs with - | Some (p1, p2) -> + | Some(p1, p2) -> let msg = sprintf "found conflicting paths '%s' and '%s' being accessed in projection expression." p1 p2 invalidArg "expr" msg | None -> () @@ -141,7 +141,7 @@ type ProjectionExpr = for i = 0 to attrs.Length - 1 do let mutable av = null - let ok = attrs.[i].View (ro, &av) + let ok = attrs.[i].View(ro, &av) if ok then values.[i] <- picklers.[i].UnPickleUntyped av @@ -156,7 +156,7 @@ type ProjectionExpr = | _ -> invalidExpr () member __.Write(writer: AttributeWriter) = - let sb = new System.Text.StringBuilder () + let sb = new System.Text.StringBuilder() let inline (!) (x: string) = sb.Append x |> ignore let mutable isFirst = true @@ -165,11 +165,11 @@ type ProjectionExpr = !(writer.WriteAttibute attr) - sb.ToString () + sb.ToString() member __.GetDebugData() = - let aw = new AttributeWriter () - let expr = __.Write (aw) + let aw = new AttributeWriter() + let expr = __.Write(aw) let names = aw.Names diff --git a/src/FSharp.AWS.DynamoDB/Expression/UpdateExpr.fs b/src/FSharp.AWS.DynamoDB/Expression/UpdateExpr.fs index d450093..2cc6308 100644 --- a/src/FSharp.AWS.DynamoDB/Expression/UpdateExpr.fs +++ b/src/FSharp.AWS.DynamoDB/Expression/UpdateExpr.fs @@ -37,10 +37,10 @@ type UpdateOperation = member uo.Attribute = match uo with | Skip -> invalidOp "no attribute contained in skip op" - | Set (attr, _) -> attr + | Set(attr, _) -> attr | Remove attr -> attr - | Add (attr, _) -> attr - | Delete (attr, _) -> attr + | Add(attr, _) -> attr + | Delete(attr, _) -> attr member uo.Id = match uo with @@ -102,7 +102,7 @@ type UpdateValue with | _ -> match right with | Undefined -> Operand left - | _ -> Op_Addition (left, right) + | _ -> Op_Addition(left, right) static member EOp_Subtraction (left: Operand) (right: Operand) = match left with @@ -110,7 +110,7 @@ type UpdateValue with | _ -> match right with | Undefined -> Operand left - | _ -> Op_Subtraction (left, right) + | _ -> Op_Subtraction(left, right) static member EList_Append (left: Operand) (right: Operand) = match left with @@ -118,24 +118,24 @@ type UpdateValue with | _ -> match right with | Undefined -> Operand left - | _ -> List_Append (left, right) + | _ -> List_Append(left, right) type UpdateOperation with static member EAdd attrId op = match op with | Undefined -> Skip - | _ -> Add (attrId, op) + | _ -> Add(attrId, op) static member EDelete attrId op = match op with | Undefined -> Skip - | _ -> Delete (attrId, op) + | _ -> Delete(attrId, op) static member ESet attrId uv = match uv with | Operand Undefined -> Remove attrId - | _ -> Set (attrId, uv) + | _ -> Set(attrId, uv) /// Extracts update expressions from a quoted record update predicate let extractRecordExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : IntermediateUpdateExprs = @@ -149,11 +149,11 @@ let extractRecordExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : Inter let nParams, pRecognizer, expr' = extractExprParams recordInfo expr match expr' with - | Lambda (r, body) when r.Type = recordInfo.Type -> + | Lambda(r, body) when r.Type = recordInfo.Type -> let rec stripBindings (bindings: Map) (expr: Expr) = match expr with - | Let (v, body, cont) -> stripBindings (Map.add v body bindings) cont - | NewRecord (_, assignments) -> bindings, assignments + | Let(v, body, cont) -> stripBindings (Map.add v body bindings) cont + | NewRecord(_, assignments) -> bindings, assignments | _ -> invalidExpr () let bindings, assignments = stripBindings Map.empty body @@ -162,9 +162,9 @@ let extractRecordExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : Inter let rp = recordInfo.Properties.[i] match assignment with - | PropertyGet (Some (Var y), prop, []) when r = y && rp.PropertyInfo = prop -> None - | Var v when bindings.ContainsKey v -> Some (Root (rp, recordInfo.GetPropertySchemata rp.Name), bindings.[v]) - | e -> Some (Root (rp, recordInfo.GetPropertySchemata rp.Name), e) + | PropertyGet(Some(Var y), prop, []) when r = y && rp.PropertyInfo = prop -> None + | Var v when bindings.ContainsKey v -> Some(Root(rp, recordInfo.GetPropertySchemata rp.Name), bindings.[v]) + | e -> Some(Root(rp, recordInfo.GetPropertySchemata rp.Name), e) let assignmentExprs = assignments @@ -195,21 +195,21 @@ let extractOpExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : Intermedi let rec getOperand (pickler: Pickler) (expr: Expr) = match expr with - | Coerce (e, _) -> getOperand pickler e - | PVar i -> Param (i, pickler) + | Coerce(e, _) -> getOperand pickler e + | PVar i -> Param(i, pickler) | _ when expr.IsClosed -> match expr |> evalRaw |> pickler.PickleCoerced with | None -> Undefined - | Some av -> Value (wrap av) + | Some av -> Value(wrap av) | _ -> invalidExpr () match expr' with - | Lambda (r, body) when r.Type = recordInfo.Type -> + | Lambda(r, body) when r.Type = recordInfo.Type -> let (|AttributeGet|_|) (e: Expr) = QuotedAttribute.TryExtract (|PVar|_|) r recordInfo e - let attrs = new ResizeArray () - let assignments = new ResizeArray () - let updateOps = new ResizeArray () + let attrs = new ResizeArray() + let assignments = new ResizeArray() + let updateOps = new ResizeArray() let rec extract e = match e with @@ -219,21 +219,21 @@ let extractOpExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : Intermedi | SpecificCall2 <@ SET @> (None, _, _, [ AttributeGet attr; value ]) -> attrs.Add attr - assignments.Add (attr, value) + assignments.Add(attr, value) | SpecificCall2 <@ REMOVE @> (None, _, _, [ AttributeGet attr ]) -> attrs.Add attr - updateOps.Add (Remove attr.Id) + updateOps.Add(Remove attr.Id) | SpecificCall2 <@ ADD @> (None, _, _, [ AttributeGet attr; value ]) -> let op = getOperand attr.Pickler value attrs.Add attr - updateOps.Add (Add (attr.Id, op)) + updateOps.Add(Add(attr.Id, op)) | SpecificCall2 <@ DELETE @> (None, _, _, [ AttributeGet attr; value ]) -> let op = getOperand attr.Pickler value attrs.Add attr - updateOps.Add (Delete (attr.Id, op)) + updateOps.Add(Delete(attr.Id, op)) | _ -> invalidExpr () @@ -244,14 +244,14 @@ let extractOpExprUpdaters (recordInfo: RecordTableInfo) (expr: Expr) : Intermedi |> Seq.map (fun attr -> attr.Id) |> tryFindConflictingPaths with - | Some (p1, p2) -> + | Some(p1, p2) -> let msg = sprintf "found conflicting paths '%s' and '%s' being accessed in update expression." p1 p2 invalidArg "expr" msg | None -> () - let assignments = assignments.ToArray () - let updateOps = updateOps.ToArray () + let assignments = assignments.ToArray() + let updateOps = updateOps.ToArray() { RVar = r NParams = nParams @@ -274,7 +274,7 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = let getValue (pickler: Pickler) (expr: Expr) = match expr |> evalRaw |> pickler.PickleCoerced with | None -> Undefined - | Some av -> Value (wrap av) + | Some av -> Value(wrap av) let rec extractOperand (pickler: Pickler) (expr: Expr) = @@ -283,16 +283,16 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = | PipeRight e | PipeLeft e -> extractOperand pickler e | AttributeGet attr -> Attribute attr.Id - | PVar i -> Param (i, pickler) + | PVar i -> Param(i, pickler) | _ -> invalidExpr () let extractNestedField (expr: Expr) = let op = extractOperand (Pickler.resolveUntyped expr.Type) expr match op with - | Param (i, _) -> FParam i + | Param(i, _) -> FParam i | Value av when av.AttributeValue.S <> null -> FField av.AttributeValue.S - | Value av when av.AttributeValue.N <> null -> FIndex (int av.AttributeValue.N) + | Value av when av.AttributeValue.N <> null -> FIndex(int av.AttributeValue.N) | _ -> invalidExpr () let rec extractUpdateValue (pickler: Pickler) (expr: Expr) = @@ -311,7 +311,7 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = | SpecificCall2 <@ (@) @> (None, _, _, [ left; right ]) -> UpdateValue.EList_Append (extractOperand pickler left) (extractOperand pickler right) - | ConsList (head, tail) -> UpdateValue.EList_Append (extractOperand pickler head) (extractOperand pickler tail) + | ConsList(head, tail) -> UpdateValue.EList_Append (extractOperand pickler head) (extractOperand pickler tail) | SpecificCall2 <@ List.append @> (None, _, _, [ left; right ]) -> UpdateValue.EList_Append (extractOperand pickler left) (extractOperand pickler right) @@ -319,7 +319,7 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = | SpecificCall2 <@ defaultArg @> (None, _, _, [ AttributeGet attr; operand ]) -> match extractOperand attr.Pickler operand with | Undefined -> invalidExpr () - | op -> If_Not_Exists (attr.Id, op) + | op -> If_Not_Exists(attr.Id, op) | _ -> extractOperand pickler expr |> Operand @@ -330,13 +330,13 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = | SpecificCall2 <@ Set.add @> (None, _, _, [ elem; AttributeGet attr ]) when parent = attr -> UpdateOperation.EAdd attr.Id (extractOperand parent.Pickler elem) - | SpecificCall2 <@ fun (s: Set<_>) e -> s.Add e @> (Some (AttributeGet attr), _, _, [ elem ]) when attr = parent -> + | SpecificCall2 <@ fun (s: Set<_>) e -> s.Add e @> (Some(AttributeGet attr), _, _, [ elem ]) when attr = parent -> UpdateOperation.EAdd attr.Id (extractOperand parent.Pickler elem) | SpecificCall2 <@ Set.remove @> (None, _, _, [ elem; AttributeGet attr ]) when attr = parent -> UpdateOperation.EDelete attr.Id (extractOperand parent.Pickler elem) - | SpecificCall2 <@ fun (s: Set<_>) e -> s.Remove e @> (Some (AttributeGet attr), _, _, [ elem ]) when attr = parent -> + | SpecificCall2 <@ fun (s: Set<_>) e -> s.Remove e @> (Some(AttributeGet attr), _, _, [ elem ]) when attr = parent -> UpdateOperation.EDelete attr.Id (extractOperand parent.Pickler elem) | SpecificCall2 <@ (+) @> (None, _, _, ([ AttributeGet attr; other ] | [ other; AttributeGet attr ])) when @@ -349,13 +349,13 @@ let extractUpdateOps (exprs: IntermediateUpdateExprs) = | SpecificCall2 <@ Map.add @> (None, _, _, [ keyE; value; AttributeGet attr ]) when attr = parent -> let nf = extractNestedField keyE - let attr = attr.Id.Append (nf) + let attr = attr.Id.Append(nf) let ep = getElemPickler parent.Pickler UpdateOperation.ESet attr (extractUpdateValue ep value) | SpecificCall2 <@ Map.remove @> (None, _, _, [ keyE; AttributeGet attr ]) when attr = parent -> let nf = extractNestedField keyE - let attr = attr.Id.Append (nf) + let attr = attr.Id.Append(nf) Remove attr | e -> UpdateOperation.ESet parent.Id (extractUpdateValue parent.Pickler e) @@ -389,29 +389,29 @@ let applyParams (uops: UpdateOperations) (inputValues: obj[]) = let applyOperand (op: Operand) = match op with - | Param (i, pickler) -> + | Param(i, pickler) -> match pickler.PickleCoerced inputValues.[i] with - | Some av -> Value (wrap av) + | Some av -> Value(wrap av) | None -> Undefined - | Attribute attr -> Attribute (applyAttr attr) + | Attribute attr -> Attribute(applyAttr attr) | _ -> op let applyUpdateValue (uv: UpdateValue) = match uv with - | Operand op -> Operand (applyOperand op) - | Op_Addition (l, r) -> UpdateValue.EOp_Addition (applyOperand l) (applyOperand r) - | Op_Subtraction (l, r) -> UpdateValue.EOp_Subtraction (applyOperand l) (applyOperand r) - | List_Append (l, r) -> UpdateValue.EList_Append (applyOperand l) (applyOperand r) - | If_Not_Exists (attr, op) -> If_Not_Exists (applyAttr attr, applyOperand op) + | Operand op -> Operand(applyOperand op) + | Op_Addition(l, r) -> UpdateValue.EOp_Addition (applyOperand l) (applyOperand r) + | Op_Subtraction(l, r) -> UpdateValue.EOp_Subtraction (applyOperand l) (applyOperand r) + | List_Append(l, r) -> UpdateValue.EList_Append (applyOperand l) (applyOperand r) + | If_Not_Exists(attr, op) -> If_Not_Exists(applyAttr attr, applyOperand op) let applyUpdateOp uop = match uop with | Skip -> uop - | Remove (attr) -> Remove (applyAttr attr) - | Set (attr, uv) -> UpdateOperation.ESet (applyAttr attr) (applyUpdateValue uv) - | Add (attr, op) -> UpdateOperation.EAdd (applyAttr attr) (applyOperand op) - | Delete (attr, op) -> UpdateOperation.EDelete (applyAttr attr) (applyOperand op) + | Remove(attr) -> Remove(applyAttr attr) + | Set(attr, uv) -> UpdateOperation.ESet (applyAttr attr) (applyUpdateValue uv) + | Add(attr, op) -> UpdateOperation.EAdd (applyAttr attr) (applyOperand op) + | Delete(attr, op) -> UpdateOperation.EDelete (applyAttr attr) (applyOperand op) let updateOps' = uops.UpdateOps @@ -427,11 +427,11 @@ let applyParams (uops: UpdateOperations) (inputValues: obj[]) = /// prints a set of update operations to string recognizable by the DynamoDB APIs let writeUpdateExpression (writer: AttributeWriter) (uops: UpdateOperations) = - let sb = new System.Text.StringBuilder () + let sb = new System.Text.StringBuilder() let inline (!) (s: string) = sb.Append s |> ignore let inline writeAttr attr = !(writer.WriteAttibute attr) - let inline writeVal v = !(writer.WriteValue (unwrap v)) + let inline writeVal v = !(writer.WriteValue(unwrap v)) let writeOp op = match op with @@ -443,25 +443,25 @@ let writeUpdateExpression (writer: AttributeWriter) (uops: UpdateOperations) = let writeUV value = match value with | Operand op -> writeOp op - | Op_Addition (l, r) -> + | Op_Addition(l, r) -> writeOp l ! " + " writeOp r - | Op_Subtraction (l, r) -> + | Op_Subtraction(l, r) -> writeOp l ! " - " writeOp r - | List_Append (l, r) -> + | List_Append(l, r) -> ! "(list_append(" writeOp l ! ", " writeOp r ! "))" - | If_Not_Exists (attr, Undefined) -> + | If_Not_Exists(attr, Undefined) -> sprintf "attempting to populate If_Not_Exists(%s) clause with value of undefined representation." attr.Id |> invalidOp - | If_Not_Exists (attr, op) -> + | If_Not_Exists(attr, op) -> ! "(if_not_exists(" writeAttr attr ! ", " @@ -485,7 +485,7 @@ let writeUpdateExpression (writer: AttributeWriter) (uops: UpdateOperations) = for uop in uops.UpdateOps do match uop with | Skip -> () - | Set (attr, uv) -> + | Set(attr, uv) -> if isFirstGp uop then ! "SET " else ! ", " writeAttr attr ! " = " @@ -495,19 +495,19 @@ let writeUpdateExpression (writer: AttributeWriter) (uops: UpdateOperations) = if isFirstGp uop then ! "REMOVE " else ! ", " writeAttr attr - | Add (attr, op) -> + | Add(attr, op) -> if isFirstGp uop then ! "ADD " else ! ", " writeAttr attr ! " " writeOp op - | Delete (attr, op) -> + | Delete(attr, op) -> if isFirstGp uop then ! "DELETE " else ! ", " writeAttr attr ! " " writeOp op - sb.ToString () + sb.ToString() type UpdateOperations with @@ -517,7 +517,7 @@ type UpdateOperations with member uops.Write(writer: AttributeWriter) = writeUpdateExpression writer uops member uops.GetDebugData() = - let aw = new AttributeWriter () + let aw = new AttributeWriter() let expr = writeUpdateExpression aw uops let names = @@ -527,7 +527,7 @@ type UpdateOperations with let values = aw.Values - |> Seq.map (fun kv -> kv.Key, kv.Value.Print ()) + |> Seq.map (fun kv -> kv.Key, kv.Value.Print()) |> Seq.toList expr, names, values diff --git a/src/FSharp.AWS.DynamoDB/Extensions.fs b/src/FSharp.AWS.DynamoDB/Extensions.fs index e846822..9316627 100644 --- a/src/FSharp.AWS.DynamoDB/Extensions.fs +++ b/src/FSharp.AWS.DynamoDB/Extensions.fs @@ -14,7 +14,7 @@ open Amazon.Runtime.CredentialManagement module Extensions = /// Precomputes a template expression - let inline template<'TRecord> = RecordTemplate.Define<'TRecord> () + let inline template<'TRecord> = RecordTemplate.Define<'TRecord>() /// A conditional which verifies that given item exists let inline itemExists<'TRecord> = template<'TRecord>.ItemExists @@ -37,8 +37,7 @@ module Extensions = // simple recognizer for aws credentials file syntax // c.f. http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html - let private profileRegex = - Regex ("\[(\S+)\]\s+aws_access_key_id\s*=\s*(\S+)\s+aws_secret_access_key\s*=\s*(\S+)", RegexOptions.Compiled) + let private profileRegex = Regex("\[(\S+)\]\s+aws_access_key_id\s*=\s*(\S+)\s+aws_secret_access_key\s*=\s*(\S+)", RegexOptions.Compiled) type AWSCredentials with @@ -61,21 +60,21 @@ module Extensions = | _, null -> sprintf "Undefined environment variable '%s'" secretKeyName |> invalidOp - | aK, sK -> new BasicAWSCredentials (aK, sK) :> _ + | aK, sK -> new BasicAWSCredentials(aK, sK) :> _ /// /// Recover a set of credentials using the local credentials store. /// /// Credential store profile name. Defaults to 'default' profile. static member FromCredentialsStore(?profileName: string) : Amazon.Runtime.AWSCredentials = - let credentialProfileStoreChain = new CredentialProfileStoreChain () + let credentialProfileStoreChain = new CredentialProfileStoreChain() let profileName = defaultArg profileName "default" - let ok, creds = credentialProfileStoreChain.TryGetAWSCredentials (profileName) + let ok, creds = credentialProfileStoreChain.TryGetAWSCredentials(profileName) if ok then creds else - let credsFile = Path.Combine (getHomePath (), ".aws", "credentials") + let credsFile = Path.Combine(getHomePath (), ".aws", "credentials") if not <| File.Exists credsFile then sprintf "Could not locate stored credentials profile '%s'." profileName @@ -93,4 +92,4 @@ module Extensions = | None -> sprintf "Could not locate stored credentials profile '%s'." profileName |> invalidOp - | Some (_, aK, sK) -> new BasicAWSCredentials (aK, sK) :> _ + | Some(_, aK, sK) -> new BasicAWSCredentials(aK, sK) :> _ diff --git a/src/FSharp.AWS.DynamoDB/Picklers/CollectionPicklers.fs b/src/FSharp.AWS.DynamoDB/Picklers/CollectionPicklers.fs index 34b4f75..efb6629 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/CollectionPicklers.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/CollectionPicklers.fs @@ -19,18 +19,18 @@ type ListPickler<'List, 'T when 'List :> seq<'T>>(ctor: seq<'T> -> 'List, nullV: override __.PickleCoerced obj = match obj with - | null -> Some <| AttributeValue (NULL = true) + | null -> Some <| AttributeValue(NULL = true) | :? 'T as t -> match tp.Pickle t with | None -> None - | Some av -> Some <| AttributeValue (L = rlist [| av |]) + | Some av -> Some <| AttributeValue(L = rlist [| av |]) | _ -> let rl = unbox> obj |> Seq.choose tp.Pickle |> rlist if rl.Count = 0 then None else - Some <| AttributeValue (L = rl) + Some <| AttributeValue(L = rl) override __.Pickle list = __.PickleCoerced list @@ -52,24 +52,24 @@ type BytesSetPickler() = override __.PickleCoerced obj = match obj with - | null -> Some <| AttributeValue (NULL = true) + | null -> Some <| AttributeValue(NULL = true) | :? (byte[]) as bs -> if bs.Length = 0 then None else Some - <| AttributeValue (BS = rlist [| new MemoryStream (bs) |]) + <| AttributeValue(BS = rlist [| new MemoryStream(bs) |]) | _ -> let rl = unbox> obj - |> Seq.choose (fun bs -> if bs.Length = 0 then None else Some (new MemoryStream (bs))) + |> Seq.choose (fun bs -> if bs.Length = 0 then None else Some(new MemoryStream(bs))) |> rlist if rl.Count = 0 then None else - Some <| AttributeValue (BS = rl) + Some <| AttributeValue(BS = rl) override __.Pickle bss = __.PickleCoerced bss @@ -77,12 +77,12 @@ type BytesSetPickler() = if a.NULL then Set.empty elif a.IsBSSet then - a.BS |> Seq.map (fun ms -> ms.ToArray ()) |> set + a.BS |> Seq.map (fun ms -> ms.ToArray()) |> set else invalidCast a interface ICollectionPickler with - member __.ElementPickler = new ByteArrayPickler () :> _ + member __.ElementPickler = new ByteArrayPickler() :> _ @@ -94,15 +94,15 @@ type NumSetPickler<'T when 'T: comparison>(tp: NumRepresentablePickler<'T>) = override __.PickleCoerced obj = match obj with - | null -> Some <| AttributeValue (NULL = true) - | :? 'T as t -> Some <| AttributeValue (NS = rlist [| tp.UnParse t |]) + | null -> Some <| AttributeValue(NULL = true) + | :? 'T as t -> Some <| AttributeValue(NS = rlist [| tp.UnParse t |]) | _ -> let rl = obj |> unbox> |> Seq.map tp.UnParse |> rlist if rl.Count = 0 then None else - Some <| AttributeValue (NS = rl) + Some <| AttributeValue(NS = rl) override __.Pickle set = __.PickleCoerced set @@ -124,15 +124,15 @@ type StringSetPickler<'T when 'T: comparison>(tp: StringRepresentablePickler<'T> override __.PickleCoerced obj = match obj with - | null -> AttributeValue (NULL = true) |> Some - | :? 'T as t -> AttributeValue (SS = rlist [| tp.UnParse t |]) |> Some + | null -> AttributeValue(NULL = true) |> Some + | :? 'T as t -> AttributeValue(SS = rlist [| tp.UnParse t |]) |> Some | _ -> let rl = obj |> unbox> |> Seq.map tp.UnParse |> rlist if rl.Count = 0 then None else - AttributeValue (SS = rl) |> Some + AttributeValue(SS = rl) |> Some override __.Pickle set = __.PickleCoerced set @@ -146,11 +146,11 @@ type StringSetPickler<'T when 'T: comparison>(tp: StringRepresentablePickler<'T> let mkSetPickler<'T when 'T: comparison> (tp: Pickler<'T>) : Pickler> = if typeof<'T> = typeof then - BytesSetPickler () |> unbox + BytesSetPickler() |> unbox else match tp with - | :? NumRepresentablePickler<'T> as tc -> NumSetPickler<'T> (tc) :> _ - | :? StringRepresentablePickler<'T> as tc -> StringSetPickler<'T> (tc) :> _ + | :? NumRepresentablePickler<'T> as tc -> NumSetPickler<'T>(tc) :> _ + | :? StringRepresentablePickler<'T> as tc -> StringSetPickler<'T>(tc) :> _ | _ -> UnSupportedType.Raise typeof> @@ -163,7 +163,7 @@ type MapPickler<'Value>(vp: Pickler<'Value>) = override __.Pickle map = if isNull map then - AttributeValue (NULL = true) |> Some + AttributeValue(NULL = true) |> Some elif map.Count = 0 then None else @@ -176,14 +176,14 @@ type MapPickler<'Value>(vp: Pickler<'Value>) = match vp.Pickle kv.Value with | None -> None - | Some av -> Some (keyVal kv.Key av)) + | Some av -> Some(keyVal kv.Key av)) |> cdict if m.Count = 0 then None else - AttributeValue (M = m) |> Some + AttributeValue(M = m) |> Some override __.UnPickle a = diff --git a/src/FSharp.AWS.DynamoDB/Picklers/Pickler.fs b/src/FSharp.AWS.DynamoDB/Picklers/Pickler.fs index 092b0d6..018df0e 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/Pickler.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/Pickler.fs @@ -87,7 +87,7 @@ type Pickler<'T>() = override __.Type = typeof<'T> override __.DefaultValueUntyped = __.DefaultValue :> obj - override __.PickleUntyped o = __.Pickle (o :?> 'T) + override __.PickleUntyped o = __.Pickle(o :?> 'T) override __.UnPickleUntyped av = __.UnPickle av :> obj /// Represent a pickler instance that can naturally represent @@ -119,8 +119,8 @@ type IPicklerResolver = // let inline invalidCast (av: AttributeValue) : 'T = - let msg = sprintf "could not convert value %A to type '%O'" (av.Print ()) typeof<'T> - raise <| new InvalidCastException (msg) + let msg = sprintf "could not convert value %A to type '%O'" (av.Print()) typeof<'T> + raise <| new InvalidCastException(msg) let getElemPickler (pickler: Pickler) = (unbox pickler).ElementPickler @@ -131,4 +131,4 @@ type UnSupportedType = | None -> sprintf "unsupported record field type '%O'" fieldType | Some r -> sprintf "unsupported record field type '%O': %s" fieldType r - raise <| new ArgumentException (message) + raise <| new ArgumentException(message) diff --git a/src/FSharp.AWS.DynamoDB/Picklers/PicklerResolver.fs b/src/FSharp.AWS.DynamoDB/Picklers/PicklerResolver.fs index ef1c60c..505b7a5 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/PicklerResolver.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/PicklerResolver.fs @@ -15,7 +15,7 @@ module private ResolverImpl = let resolvePickler (resolver: IPicklerResolver) (t: Type) : Pickler = match TypeShape.Create t with - | Shape.Bool -> BoolPickler () :> _ + | Shape.Bool -> BoolPickler() :> _ | Shape.Byte -> mkNumericalPickler () :> _ | Shape.SByte -> mkNumericalPickler () :> _ | Shape.Int16 -> mkNumericalPickler () :> _ @@ -26,15 +26,15 @@ module private ResolverImpl = | Shape.UInt64 -> mkNumericalPickler () :> _ | Shape.Single -> mkNumericalPickler () :> _ | Shape.Decimal -> mkNumericalPickler () :> _ - | Shape.Double -> DoublePickler () :> _ - | Shape.Char -> CharPickler () :> _ - | Shape.String -> StringPickler () :> _ - | Shape.Guid -> GuidPickler () :> _ - | Shape.ByteArray -> ByteArrayPickler () :> _ - | Shape.TimeSpan -> TimeSpanPickler () :> _ - | Shape.DateTime -> UnSupportedType.Raise (t, "please use DateTimeOffset instead.") - | Shape.DateTimeOffset -> DateTimeOffsetPickler () :> _ - | :? TypeShape -> MemoryStreamPickler () :> _ + | Shape.Double -> DoublePickler() :> _ + | Shape.Char -> CharPickler() :> _ + | Shape.String -> StringPickler() :> _ + | Shape.Guid -> GuidPickler() :> _ + | Shape.ByteArray -> ByteArrayPickler() :> _ + | Shape.TimeSpan -> TimeSpanPickler() :> _ + | Shape.DateTime -> UnSupportedType.Raise(t, "please use DateTimeOffset instead.") + | Shape.DateTimeOffset -> DateTimeOffsetPickler() :> _ + | :? TypeShape -> MemoryStreamPickler() :> _ | Shape.Enum s -> s.Accept { new IEnumVisitor with @@ -42,55 +42,55 @@ module private ResolverImpl = when 'Enum: enum<'Underlying> and 'Enum: struct and 'Enum :> ValueType and 'Enum: (new: unit -> 'Enum)> () = - new EnumerationPickler<'Enum, 'Underlying> () :> _ } + new EnumerationPickler<'Enum, 'Underlying>() :> _ } | Shape.Nullable s -> s.Accept { new INullableVisitor with member _.Visit<'T when 'T: (new: unit -> 'T) and 'T :> ValueType and 'T: struct>() = - new NullablePickler<'T> (resolver.Resolve ()) :> _ } + new NullablePickler<'T>(resolver.Resolve()) :> _ } | Shape.FSharpOption s -> s.Element.Accept { new ITypeVisitor with member _.Visit<'T>() = - let tp = resolver.Resolve<'T> () - new OptionPickler<'T> (tp) :> _ } + let tp = resolver.Resolve<'T>() + new OptionPickler<'T>(tp) :> _ } | Shape.Array s when s.Rank = 1 -> s.Element.Accept { new ITypeVisitor with member _.Visit<'T>() = - let tp = resolver.Resolve<'T> () - new ListPickler<'T[], 'T> (Seq.toArray, null, tp) :> _ } + let tp = resolver.Resolve<'T>() + new ListPickler<'T[], 'T>(Seq.toArray, null, tp) :> _ } | Shape.FSharpList s -> s.Element.Accept { new ITypeVisitor with member _.Visit<'T>() = - let tp = resolver.Resolve<'T> () - new ListPickler<'T list, 'T> (List.ofSeq, [], tp) :> _ } + let tp = resolver.Resolve<'T>() + new ListPickler<'T list, 'T>(List.ofSeq, [], tp) :> _ } | Shape.ResizeArray s -> s.Element.Accept { new ITypeVisitor with member _.Visit<'T>() = - let tp = resolver.Resolve<'T> () - new ListPickler, 'T> (rlist, null, tp) :> _ } + let tp = resolver.Resolve<'T>() + new ListPickler, 'T>(rlist, null, tp) :> _ } | Shape.FSharpSet s -> s.Accept { new IFSharpSetVisitor with - member _.Visit<'T when 'T: comparison>() = mkSetPickler<'T> (resolver.Resolve ()) :> _ } + member _.Visit<'T when 'T: comparison>() = mkSetPickler<'T> (resolver.Resolve()) :> _ } | Shape.FSharpMap s -> s.Accept { new IFSharpMapVisitor with member _.Visit<'K, 'V when 'K: comparison>() = if typeof<'K> <> typeof then - UnSupportedType.Raise (t, "Map types must have key of type string.") + UnSupportedType.Raise(t, "Map types must have key of type string.") - new MapPickler<'V> (resolver.Resolve ()) :> _ } + new MapPickler<'V>(resolver.Resolve()) :> _ } | Shape.Tuple _ as s -> s.Accept @@ -105,22 +105,22 @@ module private ResolverImpl = | Shape.FSharpUnion _ as s -> s.Accept { new ITypeVisitor with - member _.Visit<'T>() = new UnionPickler<'T> (resolver) :> _ } + member _.Visit<'T>() = new UnionPickler<'T>(resolver) :> _ } | _ -> UnSupportedType.Raise t type CachedResolver private () as self = - static let globalCache = ConcurrentDictionary> () - let stack = Stack () + static let globalCache = ConcurrentDictionary>() + let stack = Stack() let resolve t = try if stack.Contains t then - UnSupportedType.Raise (t, "recursive types not supported.") + UnSupportedType.Raise(t, "recursive types not supported.") stack.Push t - let pf = globalCache.GetOrAdd (t, (fun t -> lazy (resolvePickler self t))) - let _ = stack.Pop () + let pf = globalCache.GetOrAdd(t, (fun t -> lazy (resolvePickler self t))) + let _ = stack.Pop() pf.Value with UnsupportedShape t -> @@ -136,7 +136,7 @@ module private ResolverImpl = if ok then found.Value else - (CachedResolver () :> IPicklerResolver).Resolve t + (CachedResolver() :> IPicklerResolver).Resolve t [] module internal Pickler = diff --git a/src/FSharp.AWS.DynamoDB/Picklers/PrimitivePicklers.fs b/src/FSharp.AWS.DynamoDB/Picklers/PrimitivePicklers.fs index ae7e913..3bc2190 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/PrimitivePicklers.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/PrimitivePicklers.fs @@ -20,7 +20,7 @@ type BoolPickler() = override _.IsComparable = true override _.DefaultValue = false - override _.Pickle b = AttributeValue (BOOL = b) |> Some + override _.Pickle b = AttributeValue(BOOL = b) |> Some override _.UnPickle a = if a.IsBOOLSet then a.BOOL else invalidCast a override _.Parse s = Boolean.Parse s @@ -36,11 +36,11 @@ type StringPickler() = override _.Pickle s = if isNull s then - AttributeValue (NULL = true) + AttributeValue(NULL = true) elif s = "" then invalidOp "empty strings not supported by DynamoDB." else - AttributeValue (s) + AttributeValue(s) |> Some override _.UnPickle a = @@ -58,13 +58,9 @@ type CharPickler() = override _.IsComparable = true override _.DefaultValue = char 0 - override _.Pickle c = AttributeValue (string c) |> Some + override _.Pickle c = AttributeValue(string c) |> Some - override _.UnPickle a = - if not <| isNull a.S then - Char.Parse (a.S) - else - invalidCast a + override _.UnPickle a = if not <| isNull a.S then Char.Parse(a.S) else invalidCast a override _.Parse s = Char.Parse s override _.UnParse c = string c @@ -88,7 +84,7 @@ let inline mkNumericalPickler< ^N member _.UnParse e = toString e member _.DefaultValue = Unchecked.defaultof< ^N> - member _.Pickle num = AttributeValue (N = toString num) |> Some + member _.Pickle num = AttributeValue(N = toString num) |> Some member _.UnPickle a = if not <| isNull a.N then parseNum a.N else invalidCast a member x.PickleCoerced o = @@ -101,8 +97,8 @@ let inline mkNumericalPickler< ^N type DoublePickler() = inherit NumRepresentablePickler() - let parse s = Double.Parse (s, CultureInfo.InvariantCulture) - let unparse (d: double) = d.ToString ("G17", CultureInfo.InvariantCulture) + let parse s = Double.Parse(s, CultureInfo.InvariantCulture) + let unparse (d: double) = d.ToString("G17", CultureInfo.InvariantCulture) override _.PickleType = PickleType.Number override _.PicklerType = PicklerType.Value @@ -112,7 +108,7 @@ type DoublePickler() = override _.UnParse e = unparse e override _.DefaultValue = Unchecked.defaultof - override _.Pickle num = AttributeValue (N = unparse num) |> Some + override _.Pickle num = AttributeValue(N = unparse num) |> Some override _.UnPickle a = if not <| isNull a.N then parse a.N else invalidCast a override x.PickleCoerced o = @@ -135,13 +131,13 @@ type ByteArrayPickler() = override _.DefaultValue = [||] override _.Pickle bs = - if isNull bs then Some <| AttributeValue (NULL = true) + if isNull bs then Some <| AttributeValue(NULL = true) elif bs.Length = 0 then None - else Some <| AttributeValue (B = new MemoryStream (bs)) + else Some <| AttributeValue(B = new MemoryStream(bs)) override _.UnPickle a = if a.NULL then null - elif not <| isNull a.B then a.B.ToArray () + elif not <| isNull a.B then a.B.ToArray() else invalidCast a @@ -153,9 +149,9 @@ type MemoryStreamPickler() = override _.DefaultValue = null override _.Pickle m = - if isNull m then Some <| AttributeValue (NULL = true) + if isNull m then Some <| AttributeValue(NULL = true) elif m.Length = 0L then None - else Some <| AttributeValue (B = m) + else Some <| AttributeValue(B = m) override _.UnPickle a = if a.NULL then null @@ -169,7 +165,7 @@ type GuidPickler() = override _.IsComparable = true override _.DefaultValue = Guid.Empty - override _.Pickle g = AttributeValue (string g) |> Some + override _.Pickle g = AttributeValue(string g) |> Some override _.UnPickle a = if not <| isNull a.S then Guid.Parse a.S else invalidCast a override _.Parse s = Guid.Parse s @@ -178,18 +174,18 @@ type GuidPickler() = type DateTimeOffsetPickler() = inherit StringRepresentablePickler() static let isoFormat = "yyyy-MM-dd\THH:mm:ss.fffffffzzz" - static let parse s = DateTimeOffset.Parse (s) - static let unparse (d: DateTimeOffset) = d.ToString (isoFormat) + static let parse s = DateTimeOffset.Parse(s) + static let unparse (d: DateTimeOffset) = d.ToString(isoFormat) override _.PickleType = PickleType.String override _.PicklerType = PicklerType.Value override _.IsComparable = true - override _.DefaultValue = DateTimeOffset () + override _.DefaultValue = DateTimeOffset() override _.Parse s = parse s override _.UnParse d = unparse d - override _.Pickle d = AttributeValue (unparse d) |> Some + override _.Pickle d = AttributeValue(unparse d) |> Some override _.UnPickle a = if not <| isNull a.S then parse a.S else invalidCast a @@ -199,14 +195,14 @@ type TimeSpanPickler() = override _.PicklerType = PicklerType.Value override _.IsComparable = true - override _.Parse s = TimeSpan.FromTicks (int64 s) + override _.Parse s = TimeSpan.FromTicks(int64 s) override _.UnParse t = string t.Ticks override _.DefaultValue = TimeSpan.Zero - override _.Pickle t = AttributeValue (N = string t.Ticks) |> Some + override _.Pickle t = AttributeValue(N = string t.Ticks) |> Some override _.UnPickle a = if not <| isNull a.N then - TimeSpan.FromTicks (int64 a.N) + TimeSpan.FromTicks(int64 a.N) else invalidCast a @@ -217,35 +213,35 @@ type EnumerationPickler<'E, 'U when 'E: enum<'U> and 'E: struct and 'E :> ValueT override _.PicklerType = PicklerType.Enum override _.DefaultValue = Unchecked.defaultof<'E> - override _.Pickle e = AttributeValue (S = e.ToString ()) |> Some + override _.Pickle e = AttributeValue(S = e.ToString()) |> Some override _.UnPickle a = if notNull a.S then - Enum.Parse (typeof<'E>, a.S) :?> 'E + Enum.Parse(typeof<'E>, a.S) :?> 'E else invalidCast a - override _.Parse s = Enum.Parse (typeof<'E>, s) :?> 'E - override _.UnParse e = e.ToString () + override _.Parse s = Enum.Parse(typeof<'E>, s) :?> 'E + override _.UnParse e = e.ToString() type NullablePickler<'T when 'T: (new: unit -> 'T) and 'T :> ValueType and 'T: struct>(tp: Pickler<'T>) = inherit Pickler>() override _.PickleType = tp.PickleType override _.PicklerType = PicklerType.Wrapper override _.IsComparable = tp.IsComparable - override _.DefaultValue = Nullable<'T> () + override _.DefaultValue = Nullable<'T>() override _.Pickle n = if n.HasValue then tp.Pickle n.Value else - AttributeValue (NULL = true) |> Some + AttributeValue(NULL = true) |> Some override _.UnPickle a = if a.NULL then - Nullable<'T> () + Nullable<'T>() else - new Nullable<'T> (tp.UnPickle a) + new Nullable<'T>(tp.UnPickle a) type OptionPickler<'T>(tp: Pickler<'T>) = inherit Pickler<'T option>() @@ -259,32 +255,32 @@ type OptionPickler<'T>(tp: Pickler<'T>) = | None -> None | Some t -> tp.Pickle t - override _.UnPickle a = if a.NULL then None else Some (tp.UnPickle a) + override _.UnPickle a = if a.NULL then None else Some(tp.UnPickle a) override x.PickleCoerced obj = match obj with | :? 'T as t -> tp.Pickle t | :? ('T option) as topt -> x.Pickle topt - | _ -> raise <| InvalidCastException () + | _ -> raise <| InvalidCastException() type StringRepresentationPickler<'T>(ep: StringRepresentablePickler<'T>) = inherit Pickler<'T>() override _.PickleType = PickleType.String override _.PicklerType = ep.PicklerType override _.DefaultValue = ep.DefaultValue - override _.Pickle t = AttributeValue (S = ep.UnParse t) |> Some + override _.Pickle t = AttributeValue(S = ep.UnParse t) |> Some override _.UnPickle a = if notNull a.S then ep.Parse a.S else invalidCast a let mkStringRepresentationPickler (resolver: IPicklerResolver) (prop: PropertyInfo) = TypeShape.Create(prop.PropertyType).Accept { new ITypeVisitor with member _.Visit<'T>() = - match resolver.Resolve<'T> () with + match resolver.Resolve<'T>() with | :? StringRepresentablePickler<'T> as tp -> if tp.PickleType = PickleType.String then tp :> Pickler else - new StringRepresentationPickler<'T> (tp) :> Pickler + new StringRepresentationPickler<'T>(tp) :> Pickler | _ -> invalidArg prop.Name "property type cannot be represented as string." } type SerializerAttributePickler<'T>(serializer: IPropertySerializer, resolver: IPicklerResolver) = @@ -297,7 +293,7 @@ type SerializerAttributePickler<'T>(serializer: IPropertySerializer, resolver: I override _.DefaultValue = raise - <| NotSupportedException ("Default values not supported in serialized types.") + <| NotSupportedException("Default values not supported in serialized types.") override _.Pickle value = let pickle = serializer.Serialize value @@ -310,4 +306,4 @@ type SerializerAttributePickler<'T>(serializer: IPropertySerializer, resolver: I let mkSerializerAttributePickler (resolver: IPicklerResolver) (serializer: IPropertySerializer) (t: Type) = TypeShape.Create(t).Accept { new ITypeVisitor with - member _.Visit<'T>() = new SerializerAttributePickler<'T> (serializer, resolver) :> _ } + member _.Visit<'T>() = new SerializerAttributePickler<'T>(serializer, resolver) :> _ } diff --git a/src/FSharp.AWS.DynamoDB/Picklers/PropertyMetadata.fs b/src/FSharp.AWS.DynamoDB/Picklers/PropertyMetadata.fs index 09865ab..4e3680d 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/PropertyMetadata.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/PropertyMetadata.fs @@ -29,7 +29,7 @@ type PropertyMetadata = override r.GetHashCode() = hash r.PropertyInfo static member FromPropertyInfo (resolver: IPicklerResolver) (attrId: int) (prop: PropertyInfo) = - let attributes = prop.GetAttributes () + let attributes = prop.GetAttributes() let pickler = match diff --git a/src/FSharp.AWS.DynamoDB/Picklers/RecordPickler.fs b/src/FSharp.AWS.DynamoDB/Picklers/RecordPickler.fs index 124116a..82cc009 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/RecordPickler.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/RecordPickler.fs @@ -22,14 +22,14 @@ type RecordPickler<'T>(ctor: obj[] -> obj, properties: PropertyMetadata[]) = member __.Properties = properties member __.OfRecord(value: 'T) : RestObject = - let values = new RestObject () + let values = new RestObject() for prop in properties do let field = prop.PropertyInfo.GetValue value match prop.Pickler.PickleUntyped field with | None -> () - | Some av -> values.Add (prop.Name, av) + | Some av -> values.Add(prop.Name, av) values @@ -41,7 +41,7 @@ type RecordPickler<'T>(ctor: obj[] -> obj, properties: PropertyMetadata[]) = let notFound () = raise - <| new KeyNotFoundException (sprintf "attribute %A not found." prop.Name) + <| new KeyNotFoundException(sprintf "attribute %A not found." prop.Name) let ok, av = ro.TryGetValue prop.Name @@ -70,7 +70,7 @@ type RecordPickler<'T>(ctor: obj[] -> obj, properties: PropertyMetadata[]) = if ro.Count = 0 then None else - Some <| AttributeValue (M = ro) + Some <| AttributeValue(M = ro) override __.UnPickle a = if a.IsMSet then __.ToRecord a.M else invalidCast a @@ -86,16 +86,16 @@ let mkTuplePickler<'T> (resolver: IPicklerResolver) = let ctor = FSharpValue.PreComputeTupleConstructor typeof<'T> let properties = - typeof<'T>.GetProperties () + typeof<'T>.GetProperties() |> Array.mapi (PropertyMetadata.FromPropertyInfo resolver) - new RecordPickler<'T> (ctor, properties) + new RecordPickler<'T>(ctor, properties) let mkFSharpRecordPickler<'T> (resolver: IPicklerResolver) = - let ctor = FSharpValue.PreComputeRecordConstructor (typeof<'T>, true) + let ctor = FSharpValue.PreComputeRecordConstructor(typeof<'T>, true) let properties = - FSharpType.GetRecordFields (typeof<'T>, true) + FSharpType.GetRecordFields(typeof<'T>, true) |> Array.mapi (PropertyMetadata.FromPropertyInfo resolver) - new RecordPickler<'T> (ctor, properties) + new RecordPickler<'T>(ctor, properties) diff --git a/src/FSharp.AWS.DynamoDB/Picklers/UnionPickler.fs b/src/FSharp.AWS.DynamoDB/Picklers/UnionPickler.fs index 9435e1a..00e327a 100644 --- a/src/FSharp.AWS.DynamoDB/Picklers/UnionPickler.fs +++ b/src/FSharp.AWS.DynamoDB/Picklers/UnionPickler.fs @@ -21,14 +21,14 @@ type UnionPickler<'U>(resolver: IPicklerResolver) = inherit Pickler<'U>() let caseAttr = "Union_Case" - let ucis = FSharpType.GetUnionCases (typeof<'U>, true) - let tagReader = FSharpValue.PreComputeUnionTagReader (typeof<'U>, true) + let ucis = FSharpType.GetUnionCases(typeof<'U>, true) + let tagReader = FSharpValue.PreComputeUnionTagReader(typeof<'U>, true) let mkUCD uci = - let ctor = FSharpValue.PreComputeUnionConstructorInfo (uci, true) + let ctor = FSharpValue.PreComputeUnionConstructorInfo(uci, true) let props = - uci.GetFields () + uci.GetFields() |> Array.mapi (PropertyMetadata.FromPropertyInfo resolver) { UCI = uci; CaseCtor = ctor; Properties = props } @@ -36,24 +36,24 @@ type UnionPickler<'U>(resolver: IPicklerResolver) = let cases = ucis |> Array.map mkUCD member __.OfUnion(union: 'U) : RestObject = - let values = new RestObject () + let values = new RestObject() let tag = tagReader union let case = cases.[tag] - values.Add (caseAttr, AttributeValue (case.UCI.Name)) + values.Add(caseAttr, AttributeValue(case.UCI.Name)) for prop in case.Properties do let field = prop.PropertyInfo.GetValue union match prop.Pickler.PickleUntyped field with | None -> () - | Some av -> values.Add (prop.Name, av) + | Some av -> values.Add(prop.Name, av) values member __.ToUnion(ro: RestObject) : 'U = let notFound name = raise - <| new KeyNotFoundException (sprintf "attribute %A not found." name) + <| new KeyNotFoundException(sprintf "attribute %A not found." name) let tag = let ok, av = ro.TryGetValue caseAttr @@ -68,7 +68,7 @@ type UnionPickler<'U>(resolver: IPicklerResolver) = match cases |> Array.tryFind (fun c -> c.UCI.Name = tag) with | None -> let msg = sprintf "union case name %A does not correspond to type '%O'." tag typeof<'U> - raise <| new InvalidDataException (msg) + raise <| new InvalidDataException(msg) | Some case -> let values = Array.zeroCreate case.Properties.Length @@ -81,7 +81,7 @@ type UnionPickler<'U>(resolver: IPicklerResolver) = elif prop.NoDefaultValue then notFound prop.Name else values.[i] <- prop.Pickler.DefaultValueUntyped - case.CaseCtor.Invoke (null, values) :?> 'U + case.CaseCtor.Invoke(null, values) :?> 'U override __.PicklerType = PicklerType.Union override __.PickleType = PickleType.Map @@ -92,6 +92,6 @@ type UnionPickler<'U>(resolver: IPicklerResolver) = override __.Pickle(union: 'U) = let ro = __.OfUnion union - Some <| AttributeValue (M = ro) + Some <| AttributeValue(M = ro) override __.UnPickle a = if a.IsMSet then __.ToUnion a.M else invalidCast a diff --git a/src/FSharp.AWS.DynamoDB/RecordKeySchema.fs b/src/FSharp.AWS.DynamoDB/RecordKeySchema.fs index b689312..d0e7eb5 100644 --- a/src/FSharp.AWS.DynamoDB/RecordKeySchema.fs +++ b/src/FSharp.AWS.DynamoDB/RecordKeySchema.fs @@ -61,79 +61,79 @@ type PrimaryKeyStructure with /// Converts given TableKey to AttributeValue form static member ToAttributeValues(keyStructure: PrimaryKeyStructure, key: TableKey) = - let dict = new Dictionary () + let dict = new Dictionary() let extractKey name (pickler: Pickler) (value: obj) = if isNull value then invalidArg name "Key value was not specified." let av = pickler.PickleUntyped value |> Option.get - dict.Add (name, av) + dict.Add(name, av) match keyStructure with | HashKeyOnly hkp -> extractKey hkp.Name hkp.Pickler key.HashKey - | Combined (hkp, rkp) -> + | Combined(hkp, rkp) -> extractKey hkp.Name hkp.Pickler key.HashKey extractKey rkp.Name rkp.Pickler key.RangeKey - | DefaultHashKey (name, value, pickler, rkp) -> + | DefaultHashKey(name, value, pickler, rkp) -> if key.IsHashKeySpecified then extractKey name pickler key.HashKey else let av = value |> pickler.PickleUntyped |> Option.get - dict.Add (name, av) + dict.Add(name, av) extractKey rkp.Name rkp.Pickler key.RangeKey - | DefaultRangeKey (name, value, pickler, hkp) -> + | DefaultRangeKey(name, value, pickler, hkp) -> extractKey hkp.Name hkp.Pickler key.HashKey if key.IsRangeKeySpecified then extractKey name pickler key.RangeKey else let av = value |> pickler.PickleUntyped |> Option.get - dict.Add (name, av) + dict.Add(name, av) dict /// Extracts key from given record instance static member ExtractKey(keyStructure: PrimaryKeyStructure, record: 'Record) = - let inline getValue (rp: PropertyMetadata) = rp.PropertyInfo.GetValue (record) + let inline getValue (rp: PropertyMetadata) = rp.PropertyInfo.GetValue(record) match keyStructure with | HashKeyOnly hkp -> let hashKey = getValue hkp in TableKey.Hash hashKey - | DefaultHashKey (_, hashKey, _, rkp) -> + | DefaultHashKey(_, hashKey, _, rkp) -> let rangeKey = getValue rkp - TableKey.Combined (hashKey, rangeKey) - | DefaultRangeKey (_, rangeKey, _, hkp) -> + TableKey.Combined(hashKey, rangeKey) + | DefaultRangeKey(_, rangeKey, _, hkp) -> let hashKey = getValue hkp - TableKey.Combined (hashKey, rangeKey) - | Combined (hkp, rkp) -> + TableKey.Combined(hashKey, rangeKey) + | Combined(hkp, rkp) -> let hashKey = getValue hkp let rangeKey = getValue rkp - TableKey.Combined (hashKey, rangeKey) + TableKey.Combined(hashKey, rangeKey) /// Extracts key from attribute values static member ExtractKey(keyStructure: PrimaryKeyStructure, attributeValues: Dictionary) = let inline getValue (rp: PropertyMetadata) = let notFound () = raise - <| KeyNotFoundException (sprintf "attribute %A not found." rp.Name) + <| KeyNotFoundException(sprintf "attribute %A not found." rp.Name) let ok, av = attributeValues.TryGetValue rp.Name if ok then rp.Pickler.UnPickleUntyped av else notFound () match keyStructure with | HashKeyOnly hkp -> let hashKey = getValue hkp in TableKey.Hash hashKey - | DefaultHashKey (_, hashKey, _, rkp) -> + | DefaultHashKey(_, hashKey, _, rkp) -> let rangeKey = getValue rkp - TableKey.Combined (hashKey, rangeKey) - | DefaultRangeKey (_, rangeKey, _, hkp) -> + TableKey.Combined(hashKey, rangeKey) + | DefaultRangeKey(_, rangeKey, _, hkp) -> let hashKey = getValue hkp - TableKey.Combined (hashKey, rangeKey) - | Combined (hkp, rkp) -> + TableKey.Combined(hashKey, rangeKey) + | Combined(hkp, rkp) -> let hashKey = getValue hkp let rangeKey = getValue rkp - TableKey.Combined (hashKey, rangeKey) + TableKey.Combined(hashKey, rangeKey) type KeyAttributeSchema with @@ -160,39 +160,39 @@ type KeyAttributeSchema with { AttributeName = name; KeyType = keyType } - static member Create(prop: PropertyMetadata, allowNull: bool) = KeyAttributeSchema.Create (prop.Name, prop.Pickler, allowNull) + static member Create(prop: PropertyMetadata, allowNull: bool) = KeyAttributeSchema.Create(prop.Name, prop.Pickler, allowNull) type TableKeySchema with static member OfKeyStructure(ks: PrimaryKeyStructure) : TableKeySchema = - let inline mkKeySchema (name: string) (pickler: Pickler) = KeyAttributeSchema.Create (name, pickler, false) - let inline mkPropSchema (rp: PropertyMetadata) = KeyAttributeSchema.Create (rp, false) + let inline mkKeySchema (name: string) (pickler: Pickler) = KeyAttributeSchema.Create(name, pickler, false) + let inline mkPropSchema (rp: PropertyMetadata) = KeyAttributeSchema.Create(rp, false) let inline mkTableKeySchema h r = { HashKey = h; RangeKey = r; Type = PrimaryKey } match ks with | HashKeyOnly rp -> mkTableKeySchema (mkPropSchema rp) None - | Combined (hk, rk) -> mkTableKeySchema (mkPropSchema hk) (Some (mkPropSchema rk)) - | DefaultHashKey (name, _, pickler, rk) -> mkTableKeySchema (mkKeySchema name pickler) (Some (mkPropSchema rk)) - | DefaultRangeKey (name, _, pickler, hk) -> mkTableKeySchema (mkPropSchema hk) (Some (mkKeySchema name pickler)) + | Combined(hk, rk) -> mkTableKeySchema (mkPropSchema hk) (Some(mkPropSchema rk)) + | DefaultHashKey(name, _, pickler, rk) -> mkTableKeySchema (mkKeySchema name pickler) (Some(mkPropSchema rk)) + | DefaultRangeKey(name, _, pickler, hk) -> mkTableKeySchema (mkPropSchema hk) (Some(mkKeySchema name pickler)) type RecordTableInfo with /// Builds key structure from supplied F# record info static member FromRecordPickler<'T>(pickler: RecordPickler<'T>) = - let hkcaOpt = typeof<'T>.TryGetAttribute () - let rkcaOpt = typeof<'T>.TryGetAttribute () - let mkKAS rp = KeyAttributeSchema.Create (rp, true) + let hkcaOpt = typeof<'T>.TryGetAttribute() + let rkcaOpt = typeof<'T>.TryGetAttribute() + let mkKAS rp = KeyAttributeSchema.Create(rp, true) let extractKeyType (rp: PropertyMetadata) (attr: Attribute) = match attr with - | :? HashKeyAttribute -> Some (rp, KeyType.Hash, PrimaryKey) - | :? RangeKeyAttribute -> Some (rp, KeyType.Range, PrimaryKey) - | :? GlobalSecondaryHashKeyAttribute as hk -> Some (rp, KeyType.Hash, GlobalSecondaryIndex hk.IndexName) - | :? GlobalSecondaryRangeKeyAttribute as rk -> Some (rp, KeyType.Range, GlobalSecondaryIndex rk.IndexName) + | :? HashKeyAttribute -> Some(rp, KeyType.Hash, PrimaryKey) + | :? RangeKeyAttribute -> Some(rp, KeyType.Range, PrimaryKey) + | :? GlobalSecondaryHashKeyAttribute as hk -> Some(rp, KeyType.Hash, GlobalSecondaryIndex hk.IndexName) + | :? GlobalSecondaryRangeKeyAttribute as rk -> Some(rp, KeyType.Range, GlobalSecondaryIndex rk.IndexName) | :? LocalSecondaryIndexAttribute as lsi -> let name = defaultArg lsi.IndexName (rp.Name + "Index") - Some (rp, KeyType.Range, LocalSecondaryIndex name) + Some(rp, KeyType.Range, LocalSecondaryIndex name) | _ -> None @@ -210,7 +210,7 @@ type RecordTableInfo with | PrimaryKey, _ -> let setResult (pks: PrimaryKeyStructure) = let ks = TableKeySchema.OfKeyStructure pks - primaryKey := Some (pks, ks) + primaryKey := Some(pks, ks) ks match hkcaOpt, rkcaOpt, groupedAttrs with @@ -230,7 +230,7 @@ type RecordTableInfo with let pickler = Pickler.resolveUntyped hkca.HashKeyType - DefaultHashKey (hkca.Name, hkca.HashKey, pickler, rk) + DefaultHashKey(hkca.Name, hkca.HashKey, pickler, rk) |> setResult | None, Some rkca, [| (KeyType.Hash, hk) |] -> @@ -245,11 +245,11 @@ type RecordTableInfo with let pickler = Pickler.resolveUntyped rkca.HashKeyType - DefaultRangeKey (rkca.Name, rkca.RangeKey, pickler, hk) + DefaultRangeKey(rkca.Name, rkca.RangeKey, pickler, hk) |> setResult - | None, None, [| (KeyType.Hash, hk) |] -> HashKeyOnly (hk) |> setResult - | None, None, [| (KeyType.Hash, hk); (KeyType.Range, rk) |] -> Combined (hk, rk) |> setResult + | None, None, [| (KeyType.Hash, hk) |] -> HashKeyOnly(hk) |> setResult + | None, None, [| (KeyType.Hash, hk); (KeyType.Range, rk) |] -> Combined(hk, rk) |> setResult | _ -> invalidArg (string typeof<'T>) "Invalid combination of HashKey and RangeKey attributes." | LocalSecondaryIndex _, [| (KeyType.Range, rk) |] -> @@ -257,11 +257,11 @@ type RecordTableInfo with | None -> "Does not specify a HashKey attribute." |> invalidArg (string typeof<'T>) - | Some (_, ks) when Option.isNone ks.RangeKey -> + | Some(_, ks) when Option.isNone ks.RangeKey -> "LocalSecondaryIndex tables must specify a primary RangeKey" |> invalidArg (string typeof<'T>) - | Some (_, ks) -> { ks with RangeKey = Some (mkKAS rk); Type = kst } + | Some(_, ks) -> { ks with RangeKey = Some(mkKAS rk); Type = kst } | LocalSecondaryIndex _, ([||] | [| _ |]) -> invalidOp "internal error when infering LocalSecondaryIndex." | LocalSecondaryIndex id, _ -> @@ -270,7 +270,7 @@ type RecordTableInfo with | GlobalSecondaryIndex _, [| (KeyType.Hash, hk) |] -> { HashKey = mkKAS hk; RangeKey = None; Type = kst } | GlobalSecondaryIndex _, [| (KeyType.Hash, hk); (KeyType.Range, rk) |] -> - { HashKey = mkKAS hk; RangeKey = Some (mkKAS rk); Type = kst } + { HashKey = mkKAS hk; RangeKey = Some(mkKAS rk); Type = kst } | GlobalSecondaryIndex id, [| (KeyType.Range, _) |] -> sprintf "Global secondary index '%s' is missing a HashKey declaration." id |> invalidArg (string typeof<'T>) @@ -294,7 +294,7 @@ type RecordTableInfo with | None -> "Does not specify a HashKey attribute." |> invalidArg (string typeof<'T>) - | Some (pkStruct, pkSchema) -> + | Some(pkStruct, pkSchema) -> let propSchema = schemata @@ -323,7 +323,7 @@ type RecordTableInfo with PrimaryKeyStructure = pkStruct PrimaryKeySchema = pkSchema PropertySchemata = propSchema - Schemata = new TableKeySchemata (schemata) } + Schemata = new TableKeySchemata(schemata) } member info.GetPropertySchemata(propName: string) = defaultArg (info.PropertySchemata.TryFind propName) [||] @@ -337,7 +337,7 @@ type RecordTableInfo with let inline getValue (ks: KeyAttributeSchema) = let notFound () = raise - <| KeyNotFoundException (sprintf "attribute %A not found." ks.AttributeName) + <| KeyNotFoundException(sprintf "attribute %A not found." ks.AttributeName) let meta = recordInfo.Properties @@ -350,23 +350,23 @@ type RecordTableInfo with | { HashKey = hk; RangeKey = Some rk; Type = PrimaryKey } -> let hash = getValue hk let range = getValue rk - IndexKey.Primary (TableKey.Combined (hash, range)) + IndexKey.Primary(TableKey.Combined(hash, range)) | { HashKey = hk; RangeKey = None; Type = PrimaryKey } -> let hash = getValue hk - IndexKey.Primary (TableKey.Hash (hash)) + IndexKey.Primary(TableKey.Hash(hash)) | { HashKey = hk; RangeKey = Some rk; Type = LocalSecondaryIndex _ } | { HashKey = hk; RangeKey = Some rk; Type = GlobalSecondaryIndex _ } -> let hash = getValue hk let range = getValue rk - IndexKey.Combined (hash, range, PrimaryKeyStructure.ExtractKey (recordInfo.PrimaryKeyStructure, attributeValues)) + IndexKey.Combined(hash, range, PrimaryKeyStructure.ExtractKey(recordInfo.PrimaryKeyStructure, attributeValues)) | { HashKey = hk; RangeKey = None; Type = LocalSecondaryIndex _ } | { HashKey = hk; RangeKey = None; Type = GlobalSecondaryIndex _ } -> let hash = getValue hk - IndexKey.Hash (hash, PrimaryKeyStructure.ExtractKey (recordInfo.PrimaryKeyStructure, attributeValues)) + IndexKey.Hash(hash, PrimaryKeyStructure.ExtractKey(recordInfo.PrimaryKeyStructure, attributeValues)) /// Converts given IndexKey to AttributeValue form static member IndexKeyToAttributeValues(indexKeySchema: TableKeySchema, recordInfo: RecordTableInfo, key: IndexKey) = - let dict = PrimaryKeyStructure.ToAttributeValues (recordInfo.PrimaryKeyStructure, key.PrimaryKey) + let dict = PrimaryKeyStructure.ToAttributeValues(recordInfo.PrimaryKeyStructure, key.PrimaryKey) let extractKey (ks: KeyAttributeSchema) (value: obj) = if isNull value then @@ -409,7 +409,7 @@ type TableKeySchemata with td.KeySchema |> Seq.tryPick (fun ks -> if ks.KeyType = KeyType.RANGE then - Some (mkKeySchema ks) + Some(mkKeySchema ks) else None) Type = PrimaryKey } @@ -448,7 +448,7 @@ type TableKeySchemata with |> Some Type = LocalSecondaryIndex lsid.IndexName } - TableKeySchemata ( + TableKeySchemata( [| yield primaryKey yield! td.GlobalSecondaryIndexes |> Seq.map mkGlobalSecondaryIndex yield! td.LocalSecondaryIndexes |> Seq.map mkLocalSecondaryIndex |] @@ -456,9 +456,9 @@ type TableKeySchemata with /// Applies the settings implied by the schema to the supplied CreateTableRequest member schema.ApplyToCreateTableRequest(ctr: CreateTableRequest) = - let inline mkKSE n t = KeySchemaElement (n, t) + let inline mkKSE n t = KeySchemaElement(n, t) - let keyAttrs = new Dictionary () + let keyAttrs = new Dictionary() for tks in schema.Schemata do keyAttrs.[tks.HashKey.AttributeName] <- tks.HashKey @@ -475,7 +475,7 @@ type TableKeySchemata with |> Option.iter (fun rk -> ctr.KeySchema.Add <| mkKSE rk.AttributeName KeyType.RANGE) | GlobalSecondaryIndex name -> - let gsi = new GlobalSecondaryIndex () + let gsi = new GlobalSecondaryIndex() gsi.IndexName <- name gsi.KeySchema.Add @@ -484,11 +484,11 @@ type TableKeySchemata with tks.RangeKey |> Option.iter (fun rk -> gsi.KeySchema.Add <| mkKSE rk.AttributeName KeyType.RANGE) - gsi.Projection <- Projection (ProjectionType = ProjectionType.ALL) + gsi.Projection <- Projection(ProjectionType = ProjectionType.ALL) ctr.GlobalSecondaryIndexes.Add gsi | LocalSecondaryIndex name -> - let lsi = new LocalSecondaryIndex () + let lsi = new LocalSecondaryIndex() lsi.IndexName <- name lsi.KeySchema.Add @@ -497,9 +497,9 @@ type TableKeySchemata with tks.RangeKey |> Option.iter (fun rk -> lsi.KeySchema.Add <| mkKSE rk.AttributeName KeyType.RANGE) - lsi.Projection <- Projection (ProjectionType = ProjectionType.ALL) + lsi.Projection <- Projection(ProjectionType = ProjectionType.ALL) ctr.LocalSecondaryIndexes.Add lsi for attr in keyAttrs.Values do - let ad = AttributeDefinition (attr.AttributeName, attr.KeyType) + let ad = AttributeDefinition(attr.AttributeName, attr.KeyType) ctr.AttributeDefinitions.Add ad diff --git a/src/FSharp.AWS.DynamoDB/RecordTemplate.fs b/src/FSharp.AWS.DynamoDB/RecordTemplate.fs index d9cee2f..188fe7f 100644 --- a/src/FSharp.AWS.DynamoDB/RecordTemplate.fs +++ b/src/FSharp.AWS.DynamoDB/RecordTemplate.fs @@ -18,7 +18,7 @@ open FSharp.AWS.DynamoDB.ProjectionExpr [] type RecordTemplate<'TRecord> internal () = do - if not <| FSharpType.IsRecord (typeof<'TRecord>, true) then + if not <| FSharpType.IsRecord(typeof<'TRecord>, true) then invalidArg (string typeof<'TRecord>) "not a valid F# record type." let pickler = Pickler.resolve<'TRecord> () :?> RecordPickler<'TRecord> @@ -26,7 +26,7 @@ type RecordTemplate<'TRecord> internal () = let hkeyCond = ConditionalExpression.TryExtractHashKeyCondition recordInfo - |> Option.map (fun cond -> new ConditionExpression<'TRecord> (cond)) + |> Option.map (fun cond -> new ConditionExpression<'TRecord>(cond)) /// Key schema used by the current record member _.PrimaryKey = recordInfo.PrimaryKeySchema @@ -50,13 +50,13 @@ type RecordTemplate<'TRecord> internal () = /// Gets the constant HashKey if specified by the record implementation member _.ConstantHashKey: obj option = match recordInfo.PrimaryKeyStructure with - | DefaultHashKey (_, value, _, _) -> Some value + | DefaultHashKey(_, value, _, _) -> Some value | _ -> None /// Gets the constant RangeKey if specified by the record implementation member _.ConstantRangeKey: obj option = match recordInfo.PrimaryKeyStructure with - | DefaultRangeKey (_, value, _, _) -> Some value + | DefaultRangeKey(_, value, _, _) -> Some value | _ -> None /// Gets a condition expression that matches the constant HashKey, @@ -70,14 +70,14 @@ type RecordTemplate<'TRecord> internal () = /// Extracts the key that corresponds to supplied record instance. /// /// Input record instance. - member _.ExtractKey(record: 'TRecord) = PrimaryKeyStructure.ExtractKey (recordInfo.PrimaryKeyStructure, record) + member _.ExtractKey(record: 'TRecord) = PrimaryKeyStructure.ExtractKey(recordInfo.PrimaryKeyStructure, record) /// /// Extracts the key that corresponds to supplied record instance. /// /// Key attribute values member _.ExtractKey(attributeValues: Dictionary) = - PrimaryKeyStructure.ExtractKey (recordInfo.PrimaryKeyStructure, attributeValues) + PrimaryKeyStructure.ExtractKey(recordInfo.PrimaryKeyStructure, attributeValues) /// /// Extracts the last evaluated key from the supplied attributes @@ -85,17 +85,17 @@ type RecordTemplate<'TRecord> internal () = /// Key schema for the index used for the Scan/Query /// Key attribute values member _.ExtractIndexKey(keySchema: TableKeySchema, attributeValues: Dictionary) = - RecordTableInfo.ExtractIndexKey (keySchema, recordInfo, attributeValues) + RecordTableInfo.ExtractIndexKey(keySchema, recordInfo, attributeValues) /// Generates a conditional which verifies whether an item already exists. member _.ItemExists = let cond = mkItemExistsCondition recordInfo.PrimaryKeySchema - new ConditionExpression<'TRecord> (cond) + new ConditionExpression<'TRecord>(cond) /// Generates a conditional which verifies whether an item does not already exist. member _.ItemDoesNotExist = let cond = mkItemNotExistsCondition recordInfo.PrimaryKeySchema - new ConditionExpression<'TRecord> (cond) + new ConditionExpression<'TRecord>(cond) /// /// Precomputes a DynamoDB conditional expression using @@ -104,7 +104,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record predicate. member _.PrecomputeConditionalExpr(expr: Expr<'TRecord -> bool>) : ConditionExpression<'TRecord> = let cexpr = ConditionalExpression.Extract recordInfo expr - new ConditionExpression<'TRecord> (cexpr) + new ConditionExpression<'TRecord>(cexpr) /// /// Precomputes a DynamoDB conditional expression using @@ -113,7 +113,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record predicate. member _.PrecomputeConditionalExpr(expr: Expr<'I1 -> 'TRecord -> bool>) : 'I1 -> ConditionExpression<'TRecord> = let f = ConditionalExpression.Extract recordInfo expr - fun i1 -> new ConditionExpression<'TRecord> (f.Apply (i1)) + fun i1 -> new ConditionExpression<'TRecord>(f.Apply(i1)) /// /// Precomputes a DynamoDB conditional expression using @@ -122,7 +122,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record predicate. member _.PrecomputeConditionalExpr(expr: Expr<'I1 -> 'I2 -> 'TRecord -> bool>) : 'I1 -> 'I2 -> ConditionExpression<'TRecord> = let f = ConditionalExpression.Extract recordInfo expr - fun i1 i2 -> new ConditionExpression<'TRecord> (f.Apply (i1, i2)) + fun i1 i2 -> new ConditionExpression<'TRecord>(f.Apply(i1, i2)) /// /// Precomputes a DynamoDB conditional expression using @@ -133,7 +133,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'TRecord -> bool>) : 'I1 -> 'I2 -> 'I3 -> ConditionExpression<'TRecord> = let f = ConditionalExpression.Extract recordInfo expr - fun i1 i2 i3 -> new ConditionExpression<'TRecord> (f.Apply (i1, i2, i3)) + fun i1 i2 i3 -> new ConditionExpression<'TRecord>(f.Apply(i1, i2, i3)) /// /// Precomputes a DynamoDB conditional expression using @@ -144,7 +144,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'TRecord -> bool>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> ConditionExpression<'TRecord> = let f = ConditionalExpression.Extract recordInfo expr - fun i1 i2 i3 i4 -> new ConditionExpression<'TRecord> (f.Apply (i1, i2, i3, i4)) + fun i1 i2 i3 i4 -> new ConditionExpression<'TRecord>(f.Apply(i1, i2, i3, i4)) /// /// Precomputes a DynamoDB conditional expression using @@ -155,7 +155,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> 'TRecord -> bool>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> ConditionExpression<'TRecord> = let f = ConditionalExpression.Extract recordInfo expr - fun i1 i2 i3 i4 i5 -> new ConditionExpression<'TRecord> (f.Apply (i1, i2, i3, i4, i5)) + fun i1 i2 i3 i4 i5 -> new ConditionExpression<'TRecord>(f.Apply(i1, i2, i3, i4, i5)) /// /// Precomputes a DynamoDB update expression using @@ -164,7 +164,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update expression. member _.PrecomputeUpdateExpr(expr: Expr<'TRecord -> 'TRecord>) : UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - new UpdateExpression<'TRecord> (uops) + new UpdateExpression<'TRecord>(uops) /// /// Precomputes a DynamoDB update expression using @@ -173,7 +173,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update expression. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'TRecord -> 'TRecord>) : 'I1 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - fun i1 -> new UpdateExpression<'TRecord> (uops.Apply (i1)) + fun i1 -> new UpdateExpression<'TRecord>(uops.Apply(i1)) /// /// Precomputes a DynamoDB update expression using @@ -182,7 +182,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update expression. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'I2 -> 'TRecord -> 'TRecord>) : 'I1 -> 'I2 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - fun i1 i2 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2)) + fun i1 i2 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2)) /// /// Precomputes a DynamoDB update expression using @@ -191,7 +191,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update expression. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'I2 -> 'I3 -> 'TRecord -> 'TRecord>) : 'I1 -> 'I2 -> 'I3 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - fun i1 i2 i3 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3)) + fun i1 i2 i3 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3)) /// /// Precomputes a DynamoDB update expression using @@ -202,7 +202,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'TRecord -> 'TRecord>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - fun i1 i2 i3 i4 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3, i4)) + fun i1 i2 i3 i4 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3, i4)) /// /// Precomputes a DynamoDB update expression using @@ -213,7 +213,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> 'TRecord -> 'TRecord>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractUpdateExpr recordInfo expr - fun i1 i2 i3 i4 i5 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3, i4, i5)) + fun i1 i2 i3 i4 i5 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3, i4, i5)) /// /// Precomputes a DynamoDB update expression using @@ -222,7 +222,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update operations. member _.PrecomputeUpdateExpr(expr: Expr<'TRecord -> UpdateOp>) : UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - new UpdateExpression<'TRecord> (uops) + new UpdateExpression<'TRecord>(uops) /// /// Precomputes a DynamoDB update expression using @@ -231,7 +231,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update operations. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'TRecord -> UpdateOp>) : 'I1 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - fun i1 -> new UpdateExpression<'TRecord> (uops.Apply i1) + fun i1 -> new UpdateExpression<'TRecord>(uops.Apply i1) /// /// Precomputes a DynamoDB update expression using @@ -240,7 +240,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update operations. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'I2 -> 'TRecord -> UpdateOp>) : 'I1 -> 'I2 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - fun i1 i2 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2)) + fun i1 i2 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2)) /// /// Precomputes a DynamoDB update expression using @@ -249,7 +249,7 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record update operations. member _.PrecomputeUpdateExpr(expr: Expr<'I1 -> 'I2 -> 'I3 -> 'TRecord -> UpdateOp>) : 'I1 -> 'I2 -> 'I3 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - fun i1 i2 i3 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3)) + fun i1 i2 i3 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3)) /// /// Precomputes a DynamoDB update expression using @@ -260,7 +260,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'TRecord -> UpdateOp>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - fun i1 i2 i3 i4 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3, i4)) + fun i1 i2 i3 i4 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3, i4)) /// /// Precomputes a DynamoDB update expression using @@ -271,7 +271,7 @@ type RecordTemplate<'TRecord> internal () = (expr: Expr<'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> 'TRecord -> UpdateOp>) : 'I1 -> 'I2 -> 'I3 -> 'I4 -> 'I5 -> UpdateExpression<'TRecord> = let uops = UpdateOperations.ExtractOpExpr recordInfo expr - fun i1 i2 i3 i4 i5 -> new UpdateExpression<'TRecord> (uops.Apply (i1, i2, i3, i4, i5)) + fun i1 i2 i3 i4 i5 -> new UpdateExpression<'TRecord>(uops.Apply(i1, i2, i3, i4, i5)) /// /// Precomputes a DynamoDB projection expression using @@ -280,27 +280,27 @@ type RecordTemplate<'TRecord> internal () = /// Quoted record projection expression. member _.PrecomputeProjectionExpr(expr: Expr<'TRecord -> 'TProjection>) : ProjectionExpression<'TRecord, 'TProjection> = let pexpr = ProjectionExpr.Extract recordInfo expr - new ProjectionExpression<'TRecord, 'TProjection> (pexpr) + new ProjectionExpression<'TRecord, 'TProjection>(pexpr) /// Convert primary table key to attribute values - member internal _.ToAttributeValues(key: TableKey) = PrimaryKeyStructure.ToAttributeValues (recordInfo.PrimaryKeyStructure, key) + member internal _.ToAttributeValues(key: TableKey) = PrimaryKeyStructure.ToAttributeValues(recordInfo.PrimaryKeyStructure, key) /// Convert query (index) key to attribute values member internal _.ToAttributeValues(key: IndexKey, schema: TableKeySchema) = - RecordTableInfo.IndexKeyToAttributeValues (schema, recordInfo, key) + RecordTableInfo.IndexKeyToAttributeValues(schema, recordInfo, key) /// Converts a record instance to attribute values member internal _.ToAttributeValues(record: 'TRecord) = let kv = pickler.OfRecord record match recordInfo.PrimaryKeyStructure with - | DefaultHashKey (name, hashKey, pickler, _) -> + | DefaultHashKey(name, hashKey, pickler, _) -> let av = hashKey |> pickler.PickleUntyped |> Option.get - kv.Add (name, av) + kv.Add(name, av) - | DefaultRangeKey (name, rangeKey, pickler, _) -> + | DefaultRangeKey(name, rangeKey, pickler, _) -> let av = rangeKey |> pickler.PickleUntyped |> Option.get - kv.Add (name, av) + kv.Add(name, av) | _ -> () @@ -313,10 +313,10 @@ type RecordTemplate<'TRecord> internal () = [] type RecordTemplate private () = - static let descriptors = ConcurrentDictionary> () + static let descriptors = ConcurrentDictionary>() /// Defines a DynamoDB template instance using given F# record type static member Define<'TRecord>() : RecordTemplate<'TRecord> = - let mkRd _ = lazy (new RecordTemplate<'TRecord> () :> obj) - let v = descriptors.GetOrAdd (typeof<'TRecord>, mkRd) + let mkRd _ = lazy (new RecordTemplate<'TRecord>() :> obj) + let v = descriptors.GetOrAdd(typeof<'TRecord>, mkRd) v.Value :?> RecordTemplate<'TRecord> diff --git a/src/FSharp.AWS.DynamoDB/Script.fsx b/src/FSharp.AWS.DynamoDB/Script.fsx index de5fffa..711958a 100644 --- a/src/FSharp.AWS.DynamoDB/Script.fsx +++ b/src/FSharp.AWS.DynamoDB/Script.fsx @@ -20,23 +20,23 @@ open Amazon.DynamoDBv2 let ok, creds = Amazon.Runtime.CredentialManagement .CredentialProfileStoreChain() - .TryGetAWSCredentials ("default") + .TryGetAWSCredentials("default") let ddb = if ok then - new AmazonDynamoDBClient (creds) :> IAmazonDynamoDB + new AmazonDynamoDBClient(creds) :> IAmazonDynamoDB else failwith "Unable to load default credentials" #else // Use Docker-hosted dynamodb-local instance // See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.DownloadingAndRunning.html#docker for details of how to deploy a simulator instance #if USE_CREDS_FROM_ENV_VARS // 'AWS_ACCESS_KEY_ID' and 'AWS_SECRET_ACCESS_KEY' must be set for this to work -let credentials = AWSCredentials.FromEnvironmentVariables () +let credentials = AWSCredentials.FromEnvironmentVariables() #else // Credentials are not validated if connecting to local instance so anything will do (this avoids it looking for profiles to be configured) -let credentials = Amazon.Runtime.BasicAWSCredentials ("A", "A") +let credentials = Amazon.Runtime.BasicAWSCredentials("A", "A") #endif -let clientConfig = AmazonDynamoDBConfig (ServiceURL = "http://localhost:8000") -let ddb = new AmazonDynamoDBClient (credentials, clientConfig) :> IAmazonDynamoDB +let clientConfig = AmazonDynamoDBConfig(ServiceURL = "http://localhost:8000") +let ddb = new AmazonDynamoDBClient(credentials, clientConfig) :> IAmazonDynamoDB #endif type Nested = { A: string; B: System.Reflection.BindingFlags } @@ -62,11 +62,11 @@ type Test = Set: Set list Bytes: byte[] } -let throughput = ProvisionedThroughput (readCapacityUnits = 10L, writeCapacityUnits = 10L) -let table = TableContext.Initialize (ddb, "test", Throughput.Provisioned throughput) +let throughput = ProvisionedThroughput(readCapacityUnits = 10L, writeCapacityUnits = 10L) +let table = TableContext.Initialize(ddb, "test", Throughput.Provisioned throughput) let value = - { HashKey = Guid.NewGuid () + { HashKey = Guid.NewGuid() List = [] RangeKey = "2" Value = 3.1415926 @@ -77,7 +77,7 @@ let value = Set = [ set [ 1L ]; set [ 2L ] ] Bytes = [| 1uy .. 10uy |] String = ref "1a" - Unions = [ A 42; B ("42", 3) ] } + Unions = [ A 42; B("42", 3) ] } let key = table.PutItem value table.GetItem key @@ -100,21 +100,21 @@ for i = 1 to 1000 do // Real: 00:01:57.405, CPU: 00:00:19.750, GC gen0: 241, gen1: 13, gen2: 1 for i = 1 to 1000 do - let _ = table.UpdateItem (key, <@ fun r -> { r with Value2 = Some 42 } @>) + let _ = table.UpdateItem(key, <@ fun r -> { r with Value2 = Some 42 } @>) () // Real: 00:01:35.912, CPU: 00:00:01.921, GC gen0: 27, gen1: 3, gen2: 1 let uexpr = table.Template.PrecomputeUpdateExpr <@ fun r -> { r with Value2 = Some 42 } @> for i = 1 to 1000 do - let _ = table.UpdateItem (key, uexpr) + let _ = table.UpdateItem(key, uexpr) () // Real: 00:01:35.107, CPU: 00:00:02.078, GC gen0: 26, gen1: 2, gen2: 0 let uexpr2 = table.Template.PrecomputeUpdateExpr <@ fun v r -> { r with Value2 = v } @> for i = 1 to 1000 do - let _ = table.UpdateItem (key, uexpr2 (Some 42)) + let _ = table.UpdateItem(key, uexpr2 (Some 42)) () (* Expanded version of README sample that illustrates how one can better split Table initialization from application logic *) @@ -129,20 +129,20 @@ type Counter internal (table: TableContext, key: TableKey) = static member internal Start(table: TableContext) = async { - let initialEntry = { Id = Guid.NewGuid (); Value = 0L } - let! key = table.PutItemAsync (initialEntry) - return Counter (table, key) + let initialEntry = { Id = Guid.NewGuid(); Value = 0L } + let! key = table.PutItemAsync(initialEntry) + return Counter(table, key) } member _.Value = async { - let! current = table.GetItemAsync (key) + let! current = table.GetItemAsync(key) return current.Value } member _.Incr() = async { - let! updated = table.UpdateItemAsync (key, <@ fun (e: CounterEntry) -> { e with Value = e.Value + 1L } @>) + let! updated = table.UpdateItemAsync(key, <@ fun (e: CounterEntry) -> { e with Value = e.Value + 1L } @>) return updated.Value } @@ -153,12 +153,12 @@ type EasyCounters private (table: TableContext) = // We only want to do the initialization bit once per instance of our application static member Create(client: IAmazonDynamoDB, tableName: string) : Async = async { - let table = TableContext (client, tableName) + let table = TableContext(client, tableName) // Create the table if necessary. Verifies schema is correct if it has already been created // NOTE the hard coded initial throughput provisioning - arguably this belongs outside of your application logic - let throughput = ProvisionedThroughput (readCapacityUnits = 10L, writeCapacityUnits = 10L) - let! _desc = table.VerifyOrCreateTableAsync (Throughput.Provisioned throughput) - return EasyCounters (table) + let throughput = ProvisionedThroughput(readCapacityUnits = 10L, writeCapacityUnits = 10L) + let! _desc = table.VerifyOrCreateTableAsync(Throughput.Provisioned throughput) + return EasyCounters(table) } member _.StartCounter() : Async = Counter.Start table @@ -168,22 +168,22 @@ type SimpleCounters private (table: TableContext) = static member Provision(client: IAmazonDynamoDB, tableName: string, readCapacityUnits, writeCapacityUnits) = async { - let table = TableContext (client, tableName) - let provisionedThroughput = ProvisionedThroughput (readCapacityUnits, writeCapacityUnits) + let table = TableContext(client, tableName) + let provisionedThroughput = ProvisionedThroughput(readCapacityUnits, writeCapacityUnits) let throughput = Throughput.Provisioned provisionedThroughput // normally, RCU/WCU provisioning only happens first time the Table is created and is then considered an external concern // here we use `UpdateTableIfRequiredAsync` to reset it each time we deploy the app - let! desc = table.VerifyOrCreateTableAsync (throughput) - return! table.UpdateTableIfRequiredAsync (throughput, currentTableDescription = desc) + let! desc = table.VerifyOrCreateTableAsync(throughput) + return! table.UpdateTableIfRequiredAsync(throughput, currentTableDescription = desc) } static member ProvisionOnDemand(client: IAmazonDynamoDB, tableName: string) = async { - let table = TableContext (client, tableName) + let table = TableContext(client, tableName) let throughput = Throughput.OnDemand - let! desc = table.VerifyOrCreateTableAsync (throughput) + let! desc = table.VerifyOrCreateTableAsync(throughput) // as per the Provision, above, we reset to OnDemand, if it got reconfigured since it was originally created - return! table.UpdateTableIfRequiredAsync (throughput, currentTableDescription = desc) + return! table.UpdateTableIfRequiredAsync(throughput, currentTableDescription = desc) } /// We only want to do the initialization bit once per instance of our application @@ -191,47 +191,47 @@ type SimpleCounters private (table: TableContext) = /// However it will never actually create the table static member CreateWithVerify(client: IAmazonDynamoDB, tableName: string) : Async = async { - let table = TableContext (client, tableName) + let table = TableContext(client, tableName) // This validates the Table has been created correctly // (in general this is a good idea, but it is an optional step so it can be skipped, i.e. see Create() below) - do! table.VerifyTableAsync () - return SimpleCounters (table) + do! table.VerifyTableAsync() + return SimpleCounters(table) } /// Assumes the table has been provisioned externally via Provision() static member Create(client: IAmazonDynamoDB, tableName: string) : SimpleCounters = // NOTE we are skipping - SimpleCounters (TableContext (client, tableName)) + SimpleCounters(TableContext(client, tableName)) member _.StartCounter() : Async = Counter.Start table let e = - EasyCounters.Create (ddb, "testing") + EasyCounters.Create(ddb, "testing") |> Async.RunSynchronously -let e1 = e.StartCounter () |> Async.RunSynchronously -let e2 = e.StartCounter () |> Async.RunSynchronously -e1.Incr () |> Async.RunSynchronously -e2.Incr () |> Async.RunSynchronously +let e1 = e.StartCounter() |> Async.RunSynchronously +let e2 = e.StartCounter() |> Async.RunSynchronously +e1.Incr() |> Async.RunSynchronously +e2.Incr() |> Async.RunSynchronously // First, we create it in On-Demand mode -SimpleCounters.ProvisionOnDemand (ddb, "testing-pre-provisioned") +SimpleCounters.ProvisionOnDemand(ddb, "testing-pre-provisioned") |> Async.RunSynchronously // Then we flip it to Provisioned mode -SimpleCounters.Provision (ddb, "testing-pre-provisioned", readCapacityUnits = 10L, writeCapacityUnits = 10L) +SimpleCounters.Provision(ddb, "testing-pre-provisioned", readCapacityUnits = 10L, writeCapacityUnits = 10L) |> Async.RunSynchronously // The consuming code can assume the provisioning has been carried out as part of the deploy // that allows the creation to be synchronous (and not impede application startup) -let s = SimpleCounters.Create (ddb, "testing-pre-provisioned") -let s1 = s.StartCounter () |> Async.RunSynchronously // Throws if Provision step has not been executed -s1.Incr () |> Async.RunSynchronously +let s = SimpleCounters.Create(ddb, "testing-pre-provisioned") +let s1 = s.StartCounter() |> Async.RunSynchronously // Throws if Provision step has not been executed +s1.Incr() |> Async.RunSynchronously // Alternately, we can have the app do an extra call (and have some asynchronous initialization work) to check the table is ready let v = - SimpleCounters.CreateWithVerify (ddb, "testing-not-present") + SimpleCounters.CreateWithVerify(ddb, "testing-not-present") |> Async.RunSynchronously // Throws, as table not present -let v2 = v.StartCounter () |> Async.RunSynchronously -v2.Incr () |> Async.RunSynchronously +let v2 = v.StartCounter() |> Async.RunSynchronously +v2.Incr() |> Async.RunSynchronously // (TOCONSIDER: Illustrate how to use AsyncCacheCell from https://github.com/jet/equinox/blob/master/src/Equinox.Core/AsyncCacheCell.fs to make Verify call lazy) diff --git a/src/FSharp.AWS.DynamoDB/TableContext.fs b/src/FSharp.AWS.DynamoDB/TableContext.fs index 883cbb3..9a04692 100644 --- a/src/FSharp.AWS.DynamoDB/TableContext.fs +++ b/src/FSharp.AWS.DynamoDB/TableContext.fs @@ -67,8 +67,8 @@ type Streaming = module internal Streaming = let private (|Spec|) = function - | Streaming.Enabled svt -> StreamSpecification (StreamEnabled = true, StreamViewType = svt) - | Streaming.Disabled -> StreamSpecification (StreamEnabled = false) + | Streaming.Enabled svt -> StreamSpecification(StreamEnabled = true, StreamViewType = svt) + | Streaming.Disabled -> StreamSpecification(StreamEnabled = false) let applyToCreateRequest (req: CreateTableRequest) (Spec spec) = req.StreamSpecification <- spec @@ -88,7 +88,7 @@ module internal Streaming = module internal CreateTableRequest = let create (tableName, template: RecordTemplate<'TRecord>) throughput streaming customize = - let req = CreateTableRequest (TableName = tableName) + let req = CreateTableRequest(TableName = tableName) template.Info.Schemata.ApplyToCreateTableRequest req // NOTE needs to precede the throughput application as that walks the GSIs list throughput @@ -105,13 +105,13 @@ module internal CreateTableRequest = let! ct = Async.CancellationToken return! - client.CreateTableAsync (request, ct) + client.CreateTableAsync(request, ct) |> Async.AwaitTaskCorrect } module internal UpdateTableRequest = - let create tableName = UpdateTableRequest (TableName = tableName) + let create tableName = UpdateTableRequest(TableName = tableName) let apply throughput streaming request = throughput @@ -147,7 +147,7 @@ module internal UpdateTableRequest = let! ct = Async.CancellationToken let! response = - client.UpdateTableAsync (request, ct) + client.UpdateTableAsync(request, ct) |> Async.AwaitTaskCorrect return response.TableDescription @@ -160,7 +160,7 @@ module internal Provisioning = let! ct = Async.CancellationToken let! td = - client.DescribeTableAsync (tableName, ct) + client.DescribeTableAsync(tableName, ct) |> Async.AwaitTaskCorrect return @@ -184,8 +184,8 @@ module internal Provisioning = let (|Conflict|_|) (e: exn) = match e with - | :? AmazonDynamoDBException as e when e.StatusCode = HttpStatusCode.Conflict -> Some () - | :? ResourceInUseException -> Some () + | :? AmazonDynamoDBException as e when e.StatusCode = HttpStatusCode.Conflict -> Some() + | :? ResourceInUseException -> Some() | _ -> None let private checkOrCreate (client, tableName) validateDescription maybeMakeCreateTableRequest : Async = @@ -196,8 +196,8 @@ module internal Provisioning = validateDescription desc return desc - | Choice2Of2 (:? ResourceNotFoundException) when Option.isSome maybeMakeCreateTableRequest -> - let req = maybeMakeCreateTableRequest.Value () + | Choice2Of2(:? ResourceNotFoundException) when Option.isSome maybeMakeCreateTableRequest -> + let req = maybeMakeCreateTableRequest.Value() match! CreateTableRequest.execute client req |> Async.Catch with | Choice1Of2 _ -> return! aux retries @@ -300,38 +300,38 @@ module TransactWriteItemsRequest = (template: RecordTemplate<'TRecord>) : TransactWrite<'TRecord> -> TransactWriteItem = function - | TransactWrite.Check (key, cond) -> - let req = ConditionCheck (TableName = tableName, Key = template.ToAttributeValues key) - let writer = AttributeWriter (req.ExpressionAttributeNames, req.ExpressionAttributeValues) + | TransactWrite.Check(key, cond) -> + let req = ConditionCheck(TableName = tableName, Key = template.ToAttributeValues key) + let writer = AttributeWriter(req.ExpressionAttributeNames, req.ExpressionAttributeValues) req.ConditionExpression <- cond.Conditional.Write writer - TransactWriteItem (ConditionCheck = req) - | TransactWrite.Put (item, maybeCond) -> - let req = Put (TableName = tableName, Item = template.ToAttributeValues item) + TransactWriteItem(ConditionCheck = req) + | TransactWrite.Put(item, maybeCond) -> + let req = Put(TableName = tableName, Item = template.ToAttributeValues item) maybeCond |> Option.iter (fun cond -> - let writer = AttributeWriter (req.ExpressionAttributeNames, req.ExpressionAttributeValues) + let writer = AttributeWriter(req.ExpressionAttributeNames, req.ExpressionAttributeValues) req.ConditionExpression <- cond.Conditional.Write writer) - TransactWriteItem (Put = req) - | TransactWrite.Update (key, maybeCond, updater) -> - let req = Update (TableName = tableName, Key = template.ToAttributeValues key) - let writer = AttributeWriter (req.ExpressionAttributeNames, req.ExpressionAttributeValues) - req.UpdateExpression <- updater.UpdateOps.Write (writer) + TransactWriteItem(Put = req) + | TransactWrite.Update(key, maybeCond, updater) -> + let req = Update(TableName = tableName, Key = template.ToAttributeValues key) + let writer = AttributeWriter(req.ExpressionAttributeNames, req.ExpressionAttributeValues) + req.UpdateExpression <- updater.UpdateOps.Write(writer) maybeCond |> Option.iter (fun cond -> req.ConditionExpression <- cond.Conditional.Write writer) - TransactWriteItem (Update = req) - | TransactWrite.Delete (key, maybeCond) -> - let req = Delete (TableName = tableName, Key = template.ToAttributeValues key) + TransactWriteItem(Update = req) + | TransactWrite.Delete(key, maybeCond) -> + let req = Delete(TableName = tableName, Key = template.ToAttributeValues key) maybeCond |> Option.iter (fun cond -> - let writer = AttributeWriter (req.ExpressionAttributeNames, req.ExpressionAttributeValues) + let writer = AttributeWriter(req.ExpressionAttributeNames, req.ExpressionAttributeValues) req.ConditionExpression <- cond.Conditional.Write writer) - TransactWriteItem (Delete = req) + TransactWriteItem(Delete = req) let internal toTransactItems<'TRecord> tableName template items = Seq.map (toTransactWriteItem<'TRecord> tableName template) items @@ -341,7 +341,7 @@ module TransactWriteItemsRequest = /// one or more of the supplied precondition checks failing. let (|TransactionCanceledConditionalCheckFailed|_|): exn -> unit option = function - | :? TransactionCanceledException as e when e.CancellationReasons.Exists (fun x -> x.Code = "ConditionalCheckFailed") -> Some () + | :? TransactionCanceledException as e when e.CancellationReasons.Exists(fun x -> x.Code = "ConditionalCheckFailed") -> Some() | _ -> None /// Helpers for identifying Failed Precondition check outcomes emanating from PutItem, UpdateItem or DeleteItem @@ -349,7 +349,7 @@ module Precondition = /// Exception filter to identify whether an individual (non-transactional) PutItem, UpdateItem or DeleteItem call's precondition check failing. let (|CheckFailed|_|): exn -> unit option = function - | :? ConditionalCheckFailedException -> Some () + | :? ConditionalCheckFailedException -> Some() | _ -> None /// DynamoDB client object for performing table operations in the context of given F# record representations @@ -367,18 +367,18 @@ type TableContext<'TRecord> let returnConsumedCapacity, maybeReport = match metricsCollector with - | Some sink -> ReturnConsumedCapacity.INDEXES, Some (reportMetrics sink) + | Some sink -> ReturnConsumedCapacity.INDEXES, Some(reportMetrics sink) | None -> ReturnConsumedCapacity.NONE, None let tryGetItemAsync (key: TableKey) (consistentRead: bool option) (proj: ProjectionExpr.ProjectionExpr option) = async { - let kav = template.ToAttributeValues (key) - let request = GetItemRequest (tableName, kav, ReturnConsumedCapacity = returnConsumedCapacity) + let kav = template.ToAttributeValues(key) + let request = GetItemRequest(tableName, kav, ReturnConsumedCapacity = returnConsumedCapacity) match proj with | None -> () | Some proj -> - let aw = AttributeWriter (request.ExpressionAttributeNames, null) + let aw = AttributeWriter(request.ExpressionAttributeNames, null) request.ProjectionExpression <- proj.Write aw match consistentRead with @@ -386,7 +386,7 @@ type TableContext<'TRecord> | Some c -> request.ConsistentRead <- c let! ct = Async.CancellationToken - let! response = client.GetItemAsync (request, ct) |> Async.AwaitTaskCorrect + let! response = client.GetItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport |> Option.iter (fun r -> r GetItem [ response.ConsumedCapacity ] (if response.IsItemSet then 1 else 0)) @@ -407,31 +407,31 @@ type TableContext<'TRecord> | None -> return raise - <| ResourceNotFoundException (sprintf "could not find item %O" key) + <| ResourceNotFoundException(sprintf "could not find item %O" key) } let batchGetItemsAsync (keys: seq) (consistentRead: bool option) (projExpr: ProjectionExpr.ProjectionExpr option) = async { let consistentRead = defaultArg consistentRead false - let kna = KeysAndAttributes () - kna.AttributesToGet.AddRange (template.Info.Properties |> Seq.map (fun p -> p.Name)) - kna.Keys.AddRange (keys |> Seq.map template.ToAttributeValues) + let kna = KeysAndAttributes() + kna.AttributesToGet.AddRange(template.Info.Properties |> Seq.map (fun p -> p.Name)) + kna.Keys.AddRange(keys |> Seq.map template.ToAttributeValues) kna.ConsistentRead <- consistentRead match projExpr with | None -> () | Some projExpr -> - let aw = AttributeWriter (kna.ExpressionAttributeNames, null) + let aw = AttributeWriter(kna.ExpressionAttributeNames, null) kna.ProjectionExpression <- projExpr.Write aw - let request = BatchGetItemRequest (ReturnConsumedCapacity = returnConsumedCapacity) + let request = BatchGetItemRequest(ReturnConsumedCapacity = returnConsumedCapacity) request.RequestItems[tableName] <- kna let! ct = Async.CancellationToken let! response = - client.BatchGetItemAsync (request, ct) + client.BatchGetItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport @@ -466,8 +466,8 @@ type TableContext<'TRecord> * Must not contain nested operands. """ - let downloaded = ResizeArray<_> () - let consumedCapacity = ResizeArray () + let downloaded = ResizeArray<_>() + let consumedCapacity = ResizeArray() let emitMetrics () = maybeReport @@ -477,12 +477,12 @@ type TableContext<'TRecord> let rec aux last = async { - let request = QueryRequest (tableName, ReturnConsumedCapacity = returnConsumedCapacity) + let request = QueryRequest(tableName, ReturnConsumedCapacity = returnConsumedCapacity) keyCondition.IndexName |> Option.iter (fun name -> request.IndexName <- name) - let writer = AttributeWriter (request.ExpressionAttributeNames, request.ExpressionAttributeValues) + let writer = AttributeWriter(request.ExpressionAttributeNames, request.ExpressionAttributeValues) request.KeyConditionExpression <- keyCondition.Write writer match filterCondition with @@ -493,7 +493,7 @@ type TableContext<'TRecord> | None -> () | Some pe -> request.ProjectionExpression <- pe.Write writer - limit.GetCount () + limit.GetCount() |> Option.iter (fun l -> request.Limit <- l - downloaded.Count) consistentRead @@ -506,7 +506,7 @@ type TableContext<'TRecord> |> Option.iter (fun l -> request.ExclusiveStartKey <- l) let! ct = Async.CancellationToken - let! response = client.QueryAsync (request, ct) |> Async.AwaitTaskCorrect + let! response = client.QueryAsync(request, ct) |> Async.AwaitTaskCorrect consumedCapacity.Add response.ConsumedCapacity if response.HttpStatusCode <> HttpStatusCode.OK then @@ -527,7 +527,7 @@ type TableContext<'TRecord> do! aux ( exclusiveStartKey - |> Option.map (fun k -> template.ToAttributeValues (k, keyCondition.KeyCondition.Value)) + |> Option.map (fun k -> template.ToAttributeValues(k, keyCondition.KeyCondition.Value)) ) emitMetrics () @@ -535,7 +535,7 @@ type TableContext<'TRecord> return (downloaded, lastEvaluatedKey - |> Option.map (fun av -> template.ExtractIndexKey (keyCondition.KeyCondition.Value, av))) + |> Option.map (fun av -> template.ExtractIndexKey(keyCondition.KeyCondition.Value, av))) } let queryAsync @@ -570,8 +570,8 @@ type TableContext<'TRecord> = async { - let downloaded = ResizeArray<_> () - let consumedCapacity = ResizeArray () + let downloaded = ResizeArray<_>() + let consumedCapacity = ResizeArray() let emitMetrics () = maybeReport @@ -581,8 +581,8 @@ type TableContext<'TRecord> let rec aux last = async { - let request = ScanRequest (tableName, ReturnConsumedCapacity = returnConsumedCapacity) - let writer = AttributeWriter (request.ExpressionAttributeNames, request.ExpressionAttributeValues) + let request = ScanRequest(tableName, ReturnConsumedCapacity = returnConsumedCapacity) + let writer = AttributeWriter(request.ExpressionAttributeNames, request.ExpressionAttributeValues) match filterCondition with | None -> () @@ -592,7 +592,7 @@ type TableContext<'TRecord> | None -> () | Some pe -> request.ProjectionExpression <- pe.Write writer - limit.GetCount () + limit.GetCount() |> Option.iter (fun l -> request.Limit <- l - downloaded.Count) consistentRead @@ -602,7 +602,7 @@ type TableContext<'TRecord> |> Option.iter (fun l -> request.ExclusiveStartKey <- l) let! ct = Async.CancellationToken - let! response = client.ScanAsync (request, ct) |> Async.AwaitTaskCorrect + let! response = client.ScanAsync(request, ct) |> Async.AwaitTaskCorrect if response.HttpStatusCode <> HttpStatusCode.OK then emitMetrics () @@ -665,43 +665,43 @@ type TableContext<'TRecord> if not <| isValidTableName tableName then invalidArg "tableName" "unsupported DynamoDB table name." - TableContext<'TRecord> (client, tableName, RecordTemplate.Define<'TRecord> (), metricsCollector) + TableContext<'TRecord>(client, tableName, RecordTemplate.Define<'TRecord>(), metricsCollector) /// Creates a new table context instance that uses /// a new F# record type. The new F# record type /// must define a compatible key schema. member _.WithRecordType<'TRecord2>() : TableContext<'TRecord2> = - let rd = RecordTemplate.Define<'TRecord2> () + let rd = RecordTemplate.Define<'TRecord2>() if template.PrimaryKey <> rd.PrimaryKey then invalidArg (string typeof<'TRecord2>) "incompatible key schema." - new TableContext<'TRecord2> (client, tableName, rd, metricsCollector) + new TableContext<'TRecord2>(client, tableName, rd, metricsCollector) /// Creates an identical table context with the specified metricsCollector callback replacing any previously specified one member _.WithMetricsCollector(collector: RequestMetrics -> unit) : TableContext<'TRecord> = - new TableContext<'TRecord> (client, tableName, template, Some collector) + new TableContext<'TRecord>(client, tableName, template, Some collector) /// Asynchronously puts a record item in the table. /// Item to be written. /// Precondition to satisfy where item already exists. Use Precondition.CheckFailed to identify Precondition Check failures. member _.PutItemAsync(item: 'TRecord, ?precondition: ConditionExpression<'TRecord>) : Async = async { - let attrValues = template.ToAttributeValues (item) + let attrValues = template.ToAttributeValues(item) let request = - PutItemRequest (tableName, attrValues, ReturnValues = ReturnValue.NONE, ReturnConsumedCapacity = returnConsumedCapacity) + PutItemRequest(tableName, attrValues, ReturnValues = ReturnValue.NONE, ReturnConsumedCapacity = returnConsumedCapacity) match precondition with | Some pc -> - let writer = AttributeWriter (request.ExpressionAttributeNames, request.ExpressionAttributeValues) + let writer = AttributeWriter(request.ExpressionAttributeNames, request.ExpressionAttributeValues) request.ConditionExpression <- pc.Conditional.Write writer request.ReturnValuesOnConditionCheckFailure <- ReturnValuesOnConditionCheckFailure.ALL_OLD | _ -> () let! ct = Async.CancellationToken - let! response = client.PutItemAsync (request, ct) |> Async.AwaitTaskCorrect + let! response = client.PutItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport |> Option.iter (fun r -> r PutItem [ response.ConsumedCapacity ] 1) @@ -716,7 +716,7 @@ type TableContext<'TRecord> /// Item to be written. /// Precondition to satisfy where item already exists. Use Precondition.CheckFailed to identify Precondition Check failures. member t.PutItemAsync(item: 'TRecord, precondition: Expr<'TRecord -> bool>) = - t.PutItemAsync (item, template.PrecomputeConditionalExpr precondition) + t.PutItemAsync(item, template.PrecomputeConditionalExpr precondition) /// /// Asynchronously puts a collection of items to the table as a batch write operation. @@ -727,9 +727,9 @@ type TableContext<'TRecord> member _.BatchPutItemsAsync(items: seq<'TRecord>) : Async<'TRecord[]> = async { let mkWriteRequest (item: 'TRecord) = - let attrValues = template.ToAttributeValues (item) - let pr = PutRequest (attrValues) - WriteRequest (pr) + let attrValues = template.ToAttributeValues(item) + let pr = PutRequest(attrValues) + WriteRequest(pr) let items = Seq.toArray items @@ -737,12 +737,12 @@ type TableContext<'TRecord> invalidArg "items" "item length must be less than or equal to 25." let writeRequests = items |> Seq.map mkWriteRequest |> rlist - let pbr = BatchWriteItemRequest (ReturnConsumedCapacity = returnConsumedCapacity) + let pbr = BatchWriteItemRequest(ReturnConsumedCapacity = returnConsumedCapacity) pbr.RequestItems[tableName] <- writeRequests let! ct = Async.CancellationToken let! response = - client.BatchWriteItemAsync (pbr, ct) + client.BatchWriteItemAsync(pbr, ct) |> Async.AwaitTaskCorrect let unprocessed = @@ -778,8 +778,8 @@ type TableContext<'TRecord> ) : Async<'TRecord> = async { - let kav = template.ToAttributeValues (key) - let request = UpdateItemRequest (Key = kav, TableName = tableName, ReturnConsumedCapacity = returnConsumedCapacity) + let kav = template.ToAttributeValues(key) + let request = UpdateItemRequest(Key = kav, TableName = tableName, ReturnConsumedCapacity = returnConsumedCapacity) request.ReturnValues <- if defaultArg returnLatest true then @@ -787,8 +787,8 @@ type TableContext<'TRecord> else ReturnValue.ALL_OLD - let writer = AttributeWriter (request.ExpressionAttributeNames, request.ExpressionAttributeValues) - request.UpdateExpression <- updater.UpdateOps.Write (writer) + let writer = AttributeWriter(request.ExpressionAttributeNames, request.ExpressionAttributeValues) + request.UpdateExpression <- updater.UpdateOps.Write(writer) match precondition with | Some pc -> @@ -799,7 +799,7 @@ type TableContext<'TRecord> let! ct = Async.CancellationToken let! response = - client.UpdateItemAsync (request, ct) + client.UpdateItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport @@ -829,7 +829,7 @@ type TableContext<'TRecord> precondition |> Option.map template.PrecomputeConditionalExpr - t.UpdateItemAsync (key, updater, ?returnLatest = returnLatest, ?precondition = precondition) + t.UpdateItemAsync(key, updater, ?returnLatest = returnLatest, ?precondition = precondition) /// Asynchronously updates item with supplied key using provided update operation expression. /// Key of item to be updated. @@ -849,7 +849,7 @@ type TableContext<'TRecord> precondition |> Option.map template.PrecomputeConditionalExpr - t.UpdateItemAsync (key, updater, ?returnLatest = returnLatest, ?precondition = precondition) + t.UpdateItemAsync(key, updater, ?returnLatest = returnLatest, ?precondition = precondition) /// @@ -870,12 +870,12 @@ type TableContext<'TRecord> /// Key to be checked. member _.ContainsKeyAsync(key: TableKey) : Async = async { - let kav = template.ToAttributeValues (key) - let request = GetItemRequest (tableName, kav, ReturnConsumedCapacity = returnConsumedCapacity) - request.ExpressionAttributeNames.Add ("#HKEY", template.PrimaryKey.HashKey.AttributeName) + let kav = template.ToAttributeValues(key) + let request = GetItemRequest(tableName, kav, ReturnConsumedCapacity = returnConsumedCapacity) + request.ExpressionAttributeNames.Add("#HKEY", template.PrimaryKey.HashKey.AttributeName) request.ProjectionExpression <- "#HKEY" let! ct = Async.CancellationToken - let! response = client.GetItemAsync (request, ct) |> Async.AwaitTaskCorrect + let! response = client.GetItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport |> Option.iter (fun r -> r GetItem [ response.ConsumedCapacity ] 1) @@ -926,7 +926,7 @@ type TableContext<'TRecord> /// Projection expression to be applied to item. /// Specify whether to perform consistent read operation. member t.GetItemProjectedAsync(key: TableKey, projection: Expr<'TRecord -> 'TProjection>, ?consistentRead: bool) : Async<'TProjection> = - t.GetItemProjectedAsync (key, (template.PrecomputeProjectionExpr projection), ?consistentRead = consistentRead) + t.GetItemProjectedAsync(key, (template.PrecomputeProjectionExpr projection), ?consistentRead = consistentRead) /// /// Asynchronously performs a batch fetch of items with supplied keys. @@ -974,7 +974,7 @@ type TableContext<'TRecord> projection: Expr<'TRecord -> 'TProjection>, ?consistentRead: bool ) : Async<'TProjection[]> = - t.BatchGetItemsProjectedAsync (keys, template.PrecomputeProjectionExpr projection, ?consistentRead = consistentRead) + t.BatchGetItemsProjectedAsync(keys, template.PrecomputeProjectionExpr projection, ?consistentRead = consistentRead) /// Asynchronously deletes item of given key from table. @@ -986,11 +986,11 @@ type TableContext<'TRecord> let kav = template.ToAttributeValues key let request = - DeleteItemRequest (tableName, kav, ReturnValues = ReturnValue.ALL_OLD, ReturnConsumedCapacity = returnConsumedCapacity) + DeleteItemRequest(tableName, kav, ReturnValues = ReturnValue.ALL_OLD, ReturnConsumedCapacity = returnConsumedCapacity) match precondition with | Some pc -> - let writer = AttributeWriter (request.ExpressionAttributeNames, request.ExpressionAttributeValues) + let writer = AttributeWriter(request.ExpressionAttributeNames, request.ExpressionAttributeValues) request.ConditionExpression <- pc.Conditional.Write writer request.ReturnValuesOnConditionCheckFailure <- ReturnValuesOnConditionCheckFailure.ALL_OLD | None -> () @@ -998,7 +998,7 @@ type TableContext<'TRecord> let! ct = Async.CancellationToken let! response = - client.DeleteItemAsync (request, ct) + client.DeleteItemAsync(request, ct) |> Async.AwaitTaskCorrect maybeReport @@ -1018,7 +1018,7 @@ type TableContext<'TRecord> /// Key of item to be deleted. /// Specifies a precondition expression that existing item should satisfy. Use Precondition.CheckFailed to identify Precondition Check failures. member t.DeleteItemAsync(key: TableKey, precondition: Expr<'TRecord -> bool>) : Async<'TRecord option> = - t.DeleteItemAsync (key, template.PrecomputeConditionalExpr precondition) + t.DeleteItemAsync(key, template.PrecomputeConditionalExpr precondition) /// @@ -1029,23 +1029,23 @@ type TableContext<'TRecord> member _.BatchDeleteItemsAsync(keys: seq) = async { let mkDeleteRequest (key: TableKey) = - let kav = template.ToAttributeValues (key) - let pr = DeleteRequest (kav) - WriteRequest (pr) + let kav = template.ToAttributeValues(key) + let pr = DeleteRequest(kav) + WriteRequest(pr) let keys = Seq.toArray keys if keys.Length > 25 then invalidArg "items" "key length must be less than or equal to 25." - let request = BatchWriteItemRequest (ReturnConsumedCapacity = returnConsumedCapacity) + let request = BatchWriteItemRequest(ReturnConsumedCapacity = returnConsumedCapacity) let deleteRequests = keys |> Seq.map mkDeleteRequest |> rlist request.RequestItems[tableName] <- deleteRequests let! ct = Async.CancellationToken let! response = - client.BatchWriteItemAsync (request, ct) + client.BatchWriteItemAsync(request, ct) |> Async.AwaitTaskCorrect let unprocessed = @@ -1082,9 +1082,9 @@ type TableContext<'TRecord> if reqs.Count = 0 || reqs.Count > 100 then raise - <| System.ArgumentOutOfRangeException (nameof items, "must be between 1 and 100 items.") + <| System.ArgumentOutOfRangeException(nameof items, "must be between 1 and 100 items.") - let req = TransactWriteItemsRequest (ReturnConsumedCapacity = returnConsumedCapacity, TransactItems = reqs) + let req = TransactWriteItemsRequest(ReturnConsumedCapacity = returnConsumedCapacity, TransactItems = reqs) clientRequestToken |> Option.iter (fun x -> req.ClientRequestToken <- x) @@ -1092,7 +1092,7 @@ type TableContext<'TRecord> let! ct = Async.CancellationToken let! response = - client.TransactWriteItemsAsync (req, ct) + client.TransactWriteItemsAsync(req, ct) |> Async.AwaitTaskCorrect maybeReport @@ -1153,7 +1153,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.QueryAsync (kc, ?filterCondition = fc, ?limit = limit, ?consistentRead = consistentRead, ?scanIndexForward = scanIndexForward) + t.QueryAsync(kc, ?filterCondition = fc, ?limit = limit, ?consistentRead = consistentRead, ?scanIndexForward = scanIndexForward) /// @@ -1208,7 +1208,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.QueryProjectedAsync ( + t.QueryProjectedAsync( template.PrecomputeConditionalExpr keyCondition, template.PrecomputeProjectionExpr projection, ?filterCondition = filterCondition, @@ -1282,7 +1282,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.QueryPaginatedAsync ( + t.QueryPaginatedAsync( kc, ?filterCondition = fc, ?limit = limit, @@ -1359,7 +1359,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.QueryProjectedPaginatedAsync ( + t.QueryProjectedPaginatedAsync( template.PrecomputeConditionalExpr keyCondition, template.PrecomputeProjectionExpr projection, ?filterCondition = filterCondition, @@ -1395,7 +1395,7 @@ type TableContext<'TRecord> /// Specify whether to perform consistent read operation. member t.ScanAsync(filterCondition: Expr<'TRecord -> bool>, ?limit: int, ?consistentRead: bool) : Async<'TRecord[]> = let cond = template.PrecomputeConditionalExpr filterCondition - t.ScanAsync (cond, ?limit = limit, ?consistentRead = consistentRead) + t.ScanAsync(cond, ?limit = limit, ?consistentRead = consistentRead) /// @@ -1440,7 +1440,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.ScanProjectedAsync ( + t.ScanProjectedAsync( template.PrecomputeProjectionExpr projection, ?filterCondition = filterCondition, ?limit = limit, @@ -1491,7 +1491,7 @@ type TableContext<'TRecord> ?consistentRead: bool ) : Async> = let cond = template.PrecomputeConditionalExpr filterCondition - t.ScanPaginatedAsync (cond, ?limit = limit, ?exclusiveStartKey = exclusiveStartKey, ?consistentRead = consistentRead) + t.ScanPaginatedAsync(cond, ?limit = limit, ?exclusiveStartKey = exclusiveStartKey, ?consistentRead = consistentRead) /// @@ -1550,7 +1550,7 @@ type TableContext<'TRecord> filterCondition |> Option.map template.PrecomputeConditionalExpr - t.ScanProjectedPaginatedAsync ( + t.ScanProjectedPaginatedAsync( template.PrecomputeProjectionExpr projection, ?filterCondition = filterCondition, ?limit = limit, @@ -1610,7 +1610,7 @@ type TableContext<'TRecord> /// Provisioned throughput to use on table. [] member t.UpdateProvisionedThroughputAsync(provisionedThroughput: ProvisionedThroughput) : Async = - t.UpdateTableIfRequiredAsync (Throughput.Provisioned provisionedThroughput) + t.UpdateTableIfRequiredAsync(Throughput.Provisioned provisionedThroughput) |> Async.Ignore /// Asynchronously verify that the table exists and is compatible with record key schema. @@ -1622,12 +1622,12 @@ type TableContext<'TRecord> let throughput = match provisionedThroughput with | Some p -> p - | None -> ProvisionedThroughput (10L, 10L) + | None -> ProvisionedThroughput(10L, 10L) - t.VerifyOrCreateTableAsync (Throughput.Provisioned throughput) + t.VerifyOrCreateTableAsync(Throughput.Provisioned throughput) |> Async.Ignore else - t.VerifyTableAsync () + t.VerifyTableAsync() // Deprecated factory method, to be removed. Replaced with // 1. TableContext<'T> ctor (synchronous) @@ -1644,19 +1644,19 @@ type TableContext internal () = ?metricsCollector: RequestMetrics -> unit ) = async { - let context = TableContext<'TRecord> (client, tableName, ?metricsCollector = metricsCollector) + let context = TableContext<'TRecord>(client, tableName, ?metricsCollector = metricsCollector) if createIfNotExists = Some true then let throughput = match provisionedThroughput with | Some p -> p - | None -> ProvisionedThroughput (10L, 10L) + | None -> ProvisionedThroughput(10L, 10L) do! - context.VerifyOrCreateTableAsync (Throughput.Provisioned throughput) + context.VerifyOrCreateTableAsync(Throughput.Provisioned throughput) |> Async.Ignore elif verifyTable <> Some false then - do! context.VerifyTableAsync () + do! context.VerifyTableAsync() return context } @@ -1681,7 +1681,7 @@ type TableContext internal () = ?provisionedThroughput: ProvisionedThroughput, ?metricsCollector: RequestMetrics -> unit ) = - TableContext.CreateAsyncImpl<'TRecord> ( + TableContext.CreateAsyncImpl<'TRecord>( client, tableName, ?verifyTable = verifyTable, @@ -1711,7 +1711,7 @@ type TableContext internal () = ?provisionedThroughput: ProvisionedThroughput, ?metricsCollector: RequestMetrics -> unit ) = - TableContext.CreateAsyncImpl<'TRecord> ( + TableContext.CreateAsyncImpl<'TRecord>( client, tableName, ?verifyTable = verifyTable, @@ -1739,8 +1739,8 @@ module Scripting = /// DynamoDB client instance. /// Table name to target. static member Initialize<'TRecord>(client: IAmazonDynamoDB, tableName: string) : TableContext<'TRecord> = - let context = TableContext<'TRecord> (client, tableName) - context.VerifyTableAsync () |> Async.RunSynchronously + let context = TableContext<'TRecord>(client, tableName) + context.VerifyTableAsync() |> Async.RunSynchronously context /// Creates a DynamoDB client instance for the specified F# record type, client and table name.
@@ -1750,10 +1750,10 @@ module Scripting = /// Table name to target. /// Throughput to configure if the Table does not yet exist. static member Initialize<'TRecord>(client: IAmazonDynamoDB, tableName: string, throughput) : TableContext<'TRecord> = - let context = TableContext<'TRecord> (client, tableName) + let context = TableContext<'TRecord>(client, tableName) let _desc = - context.VerifyOrCreateTableAsync (throughput) + context.VerifyOrCreateTableAsync(throughput) |> Async.RunSynchronously context @@ -1766,7 +1766,7 @@ module Scripting = /// Item to be written. /// Precondition to satisfy where item already exists. Use Precondition.CheckFailed to identify Precondition Check failures. member t.PutItem(item: 'TRecord, ?precondition: ConditionExpression<'TRecord>) = - t.PutItemAsync (item, ?precondition = precondition) + t.PutItemAsync(item, ?precondition = precondition) |> Async.RunSynchronously /// @@ -1775,8 +1775,7 @@ module Scripting = /// Item to be written. /// Precondition to satisfy where item already exists. Use Precondition.CheckFailed to identify Precondition Check failures. member t.PutItem(item: 'TRecord, precondition: Expr<'TRecord -> bool>) = - t.PutItemAsync (item, precondition) - |> Async.RunSynchronously + t.PutItemAsync(item, precondition) |> Async.RunSynchronously /// @@ -1785,7 +1784,7 @@ module Scripting = /// /// Any unprocessed items due to throttling. /// Items to be written. - member t.BatchPutItems(items: seq<'TRecord>) = t.BatchPutItemsAsync (items) |> Async.RunSynchronously + member t.BatchPutItems(items: seq<'TRecord>) = t.BatchPutItemsAsync(items) |> Async.RunSynchronously /// @@ -1802,7 +1801,7 @@ module Scripting = ?precondition: ConditionExpression<'TRecord>, ?returnLatest: bool ) = - t.UpdateItemAsync (key, updater, ?precondition = precondition, ?returnLatest = returnLatest) + t.UpdateItemAsync(key, updater, ?precondition = precondition, ?returnLatest = returnLatest) |> Async.RunSynchronously /// @@ -1819,7 +1818,7 @@ module Scripting = ?precondition: Expr<'TRecord -> bool>, ?returnLatest: bool ) = - t.UpdateItemAsync (key, updater, ?precondition = precondition, ?returnLatest = returnLatest) + t.UpdateItemAsync(key, updater, ?precondition = precondition, ?returnLatest = returnLatest) |> Async.RunSynchronously /// @@ -1836,7 +1835,7 @@ module Scripting = ?precondition: Expr<'TRecord -> bool>, ?returnLatest: bool ) = - t.UpdateItemAsync (key, updater, ?precondition = precondition, ?returnLatest = returnLatest) + t.UpdateItemAsync(key, updater, ?precondition = precondition, ?returnLatest = returnLatest) |> Async.RunSynchronously @@ -1844,13 +1843,13 @@ module Scripting = /// Checks whether item of supplied key exists in table. /// /// Key to be checked. - member t.ContainsKey(key: TableKey) = t.ContainsKeyAsync (key) |> Async.RunSynchronously + member t.ContainsKey(key: TableKey) = t.ContainsKeyAsync(key) |> Async.RunSynchronously /// /// Fetches item of given key from table. /// /// Key of item to be fetched. - member r.GetItem(key: TableKey) = r.GetItemAsync (key) |> Async.RunSynchronously + member r.GetItem(key: TableKey) = r.GetItemAsync(key) |> Async.RunSynchronously /// @@ -1861,7 +1860,7 @@ module Scripting = /// Key of item to be fetched. /// Projection expression to be applied to item. member t.GetItemProjected(key: TableKey, projection: ProjectionExpression<'TRecord, 'TProjection>) : 'TProjection = - t.GetItemProjectedAsync (key, projection) + t.GetItemProjectedAsync(key, projection) |> Async.RunSynchronously /// @@ -1873,7 +1872,7 @@ module Scripting = /// Projection expression to be applied to item. member t.GetItemProjected(key: TableKey, projection: Expr<'TRecord -> 'TProjection>) : 'TProjection = // TOCONSIDER implement in terms of Async equivalent as per the rest - t.GetItemProjected (key, t.Template.PrecomputeProjectionExpr projection) + t.GetItemProjected(key, t.Template.PrecomputeProjectionExpr projection) /// @@ -1882,7 +1881,7 @@ module Scripting = /// Keys of items to be fetched. /// Perform consistent read. Defaults to false. member t.BatchGetItems(keys: seq, ?consistentRead: bool) = - t.BatchGetItemsAsync (keys, ?consistentRead = consistentRead) + t.BatchGetItemsAsync(keys, ?consistentRead = consistentRead) |> Async.RunSynchronously @@ -1898,7 +1897,7 @@ module Scripting = projection: ProjectionExpression<'TRecord, 'TProjection>, ?consistentRead: bool ) : 'TProjection[] = - t.BatchGetItemsProjectedAsync (keys, projection, ?consistentRead = consistentRead) + t.BatchGetItemsProjectedAsync(keys, projection, ?consistentRead = consistentRead) |> Async.RunSynchronously @@ -1914,14 +1913,14 @@ module Scripting = projection: Expr<'TRecord -> 'TProjection>, ?consistentRead: bool ) : 'TProjection[] = - t.BatchGetItemsProjectedAsync (keys, projection, ?consistentRead = consistentRead) + t.BatchGetItemsProjectedAsync(keys, projection, ?consistentRead = consistentRead) |> Async.RunSynchronously /// Deletes item of given key from table. /// Key of item to be deleted. /// Precondition to satisfy where item exists. Use Precondition.CheckFailed to identify Precondition Check failures. member t.DeleteItem(key: TableKey, ?precondition: ConditionExpression<'TRecord>) = - t.DeleteItemAsync (key, ?precondition = precondition) + t.DeleteItemAsync(key, ?precondition = precondition) |> Async.RunSynchronously /// @@ -1930,7 +1929,7 @@ module Scripting = /// Key of item to be deleted. /// Precondition to satisfy where item exists. Use Precondition.CheckFailed to identify Precondition Check failures. member t.DeleteItem(key: TableKey, precondition: Expr<'TRecord -> bool>) = - t.DeleteItemAsync (key, precondition) + t.DeleteItemAsync(key, precondition) |> Async.RunSynchronously @@ -1939,7 +1938,7 @@ module Scripting = /// /// Any unprocessed keys due to throttling. /// Keys of items to be deleted. - member t.BatchDeleteItems(keys: seq) = t.BatchDeleteItemsAsync (keys) |> Async.RunSynchronously + member t.BatchDeleteItems(keys: seq) = t.BatchDeleteItemsAsync(keys) |> Async.RunSynchronously /// @@ -1958,7 +1957,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : 'TRecord[] = - t.QueryAsync ( + t.QueryAsync( keyCondition, ?filterCondition = filterCondition, ?limit = limit, @@ -1983,7 +1982,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : 'TRecord[] = - t.QueryAsync ( + t.QueryAsync( keyCondition, ?filterCondition = filterCondition, ?limit = limit, @@ -2013,7 +2012,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : 'TProjection[] = - t.QueryProjectedAsync ( + t.QueryProjectedAsync( keyCondition, projection, ?filterCondition = filterCondition, @@ -2043,7 +2042,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : 'TProjection[] = - t.QueryProjectedAsync ( + t.QueryProjectedAsync( keyCondition, projection, ?filterCondition = filterCondition, @@ -2072,7 +2071,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : PaginatedResult<'TRecord, IndexKey> = - t.QueryPaginatedAsync ( + t.QueryPaginatedAsync( keyCondition, ?filterCondition = filterCondition, ?limit = limit, @@ -2100,7 +2099,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : PaginatedResult<'TRecord, IndexKey> = - t.QueryPaginatedAsync ( + t.QueryPaginatedAsync( keyCondition, ?filterCondition = filterCondition, ?limit = limit, @@ -2133,7 +2132,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : PaginatedResult<'TProjection, IndexKey> = - t.QueryProjectedPaginatedAsync ( + t.QueryProjectedPaginatedAsync( keyCondition, projection, ?filterCondition = filterCondition, @@ -2166,7 +2165,7 @@ module Scripting = ?consistentRead: bool, ?scanIndexForward: bool ) : PaginatedResult<'TProjection, IndexKey> = - t.QueryProjectedPaginatedAsync ( + t.QueryProjectedPaginatedAsync( keyCondition, projection, ?filterCondition = filterCondition, @@ -2185,7 +2184,7 @@ module Scripting = /// Maximum number of items to evaluate. /// Specify whether to perform consistent read operation. member t.Scan(?filterCondition: ConditionExpression<'TRecord>, ?limit: int, ?consistentRead: bool) : 'TRecord[] = - t.ScanAsync (?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) + t.ScanAsync(?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) |> Async.RunSynchronously /// @@ -2195,7 +2194,7 @@ module Scripting = /// Maximum number of items to evaluate. /// Specify whether to perform consistent read operation. member t.Scan(filterCondition: Expr<'TRecord -> bool>, ?limit: int, ?consistentRead: bool) : 'TRecord[] = - t.ScanAsync (filterCondition, ?limit = limit, ?consistentRead = consistentRead) + t.ScanAsync(filterCondition, ?limit = limit, ?consistentRead = consistentRead) |> Async.RunSynchronously @@ -2215,7 +2214,7 @@ module Scripting = ?limit: int, ?consistentRead: bool ) : 'TProjection[] = - t.ScanProjectedAsync (projection, ?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) + t.ScanProjectedAsync(projection, ?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) |> Async.RunSynchronously /// @@ -2234,7 +2233,7 @@ module Scripting = ?limit: int, ?consistentRead: bool ) : 'TProjection[] = - t.ScanProjectedAsync (projection, ?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) + t.ScanProjectedAsync(projection, ?filterCondition = filterCondition, ?limit = limit, ?consistentRead = consistentRead) |> Async.RunSynchronously /// @@ -2251,7 +2250,7 @@ module Scripting = ?exclusiveStartKey: TableKey, ?consistentRead: bool ) : PaginatedResult<'TRecord, TableKey> = - t.ScanPaginatedAsync ( + t.ScanPaginatedAsync( ?filterCondition = filterCondition, ?limit = limit, ?exclusiveStartKey = exclusiveStartKey, @@ -2274,7 +2273,7 @@ module Scripting = ?exclusiveStartKey: TableKey, ?consistentRead: bool ) : PaginatedResult<'TRecord, TableKey> = - t.ScanPaginatedAsync (filterCondition, ?limit = limit, ?exclusiveStartKey = exclusiveStartKey, ?consistentRead = consistentRead) + t.ScanPaginatedAsync(filterCondition, ?limit = limit, ?exclusiveStartKey = exclusiveStartKey, ?consistentRead = consistentRead) |> Async.RunSynchronously @@ -2296,7 +2295,7 @@ module Scripting = ?exclusiveStartKey: TableKey, ?consistentRead: bool ) : PaginatedResult<'TProjection, TableKey> = - t.ScanProjectedPaginatedAsync ( + t.ScanProjectedPaginatedAsync( projection, ?filterCondition = filterCondition, ?limit = limit, @@ -2323,7 +2322,7 @@ module Scripting = ?exclusiveStartKey: TableKey, ?consistentRead: bool ) : PaginatedResult<'TProjection, TableKey> = - t.ScanProjectedPaginatedAsync ( + t.ScanProjectedPaginatedAsync( projection, ?filterCondition = filterCondition, ?limit = limit, @@ -2338,6 +2337,6 @@ module Scripting = member t.UpdateProvisionedThroughput(provisionedThroughput: ProvisionedThroughput) : unit = let spec = Throughput.Provisioned provisionedThroughput - t.UpdateTableIfRequiredAsync (spec) + t.UpdateTableIfRequiredAsync(spec) |> Async.Ignore |> Async.RunSynchronously diff --git a/src/FSharp.AWS.DynamoDB/Types.fs b/src/FSharp.AWS.DynamoDB/Types.fs index 0f88294..05d761d 100644 --- a/src/FSharp.AWS.DynamoDB/Types.fs +++ b/src/FSharp.AWS.DynamoDB/Types.fs @@ -37,8 +37,8 @@ type GlobalSecondaryRangeKeyAttribute(indexName: string) = [] type LocalSecondaryIndexAttribute private (indexName: string option) = inherit Attribute() - new() = LocalSecondaryIndexAttribute (None) - new(indexName: string) = LocalSecondaryIndexAttribute (Some indexName) + new() = LocalSecondaryIndexAttribute(None) + new(indexName: string) = LocalSecondaryIndexAttribute(Some indexName) member internal _.IndexName = indexName /// Declares a constant HashKey attribute for the given record. @@ -49,14 +49,14 @@ type ConstantHashKeyAttribute(name: string, hashkey: obj) = do if isNull name then - raise <| ArgumentNullException ("name") + raise <| ArgumentNullException("name") if isNull hashkey then - raise <| ArgumentNullException ("hashkey") + raise <| ArgumentNullException("hashkey") member _.Name = name member _.HashKey = hashkey - member _.HashKeyType = hashkey.GetType () + member _.HashKeyType = hashkey.GetType() /// Declares a constant RangeKey attribute for the given record. /// Records carrying this attribute should specify a HashKey field. @@ -66,14 +66,14 @@ type ConstantRangeKeyAttribute(name: string, rangeKey: obj) = do if isNull name then - raise <| ArgumentNullException ("name") + raise <| ArgumentNullException("name") if isNull rangeKey then - raise <| ArgumentNullException ("rangeKey") + raise <| ArgumentNullException("rangeKey") member _.Name = name member _.RangeKey = rangeKey - member _.HashKeyType = rangeKey.GetType () + member _.HashKeyType = rangeKey.GetType() /// Declares that annotated property should be represented /// as string in the DynamoDB table. Only applies to @@ -88,7 +88,7 @@ type CustomNameAttribute(name: string) = do if isNull name then - raise <| ArgumentNullException ("name") + raise <| ArgumentNullException("name") member _.Name = name @@ -118,7 +118,7 @@ type PropertySerializerAttribute<'PickleType>() = interface IPropertySerializer with member _.PickleType = typeof<'PickleType> member x.Serialize value = x.Serialize value :> obj - member x.Deserialize pickle = x.Deserialize (pickle :?> 'PickleType) + member x.Deserialize pickle = x.Deserialize(pickle :?> 'PickleType) /// Metadata on a table key attribute type KeyAttributeSchema = { AttributeName: string; KeyType: ScalarAttributeType } @@ -169,23 +169,23 @@ type TableKey private (hashKey: obj, rangeKey: obj) = /// Defines a table key using provided HashKey static member Hash<'HashKey>(hashKey: 'HashKey) = if isNull hashKey then - raise <| ArgumentNullException ("hashKey") + raise <| ArgumentNullException("hashKey") - TableKey (hashKey, null) + TableKey(hashKey, null) /// Defines a table key using provided RangeKey static member Range<'RangeKey>(rangeKey: 'RangeKey) = if isNull rangeKey then - raise <| ArgumentNullException ("rangeKey") + raise <| ArgumentNullException("rangeKey") - TableKey (null, rangeKey) + TableKey(null, rangeKey) /// Defines a table key using combined HashKey and RangeKey static member Combined<'HashKey, 'RangeKey>(hashKey: 'HashKey, rangeKey: 'RangeKey) = if isNull hashKey then - raise <| ArgumentNullException ("hashKey") + raise <| ArgumentNullException("hashKey") - TableKey (hashKey, rangeKey) + TableKey(hashKey, rangeKey) /// Query (start/last evaluated) key identifier [] @@ -216,19 +216,19 @@ type IndexKey private (hashKey: obj, rangeKey: obj, primaryKey: TableKey) = /// Defines an index key using provided HashKey and primary TableKey static member Hash<'HashKey>(hashKey: 'HashKey, primaryKey: TableKey) = if isNull hashKey then - raise <| ArgumentNullException ("hashKey") + raise <| ArgumentNullException("hashKey") - IndexKey (hashKey, null, primaryKey) + IndexKey(hashKey, null, primaryKey) /// Defines an index key using combined HashKey, RangeKey and primary TableKey static member Combined<'HashKey, 'RangeKey>(hashKey: 'HashKey, rangeKey: 'RangeKey, primaryKey: TableKey) = if isNull hashKey then - raise <| ArgumentNullException ("hashKey") + raise <| ArgumentNullException("hashKey") - IndexKey (hashKey, rangeKey, primaryKey) + IndexKey(hashKey, rangeKey, primaryKey) // Defines an index key using just the primary TableKey - static member Primary(primaryKey: TableKey) = IndexKey (null, null, primaryKey) + static member Primary(primaryKey: TableKey) = IndexKey(null, null, primaryKey) /// Pagination result type type PaginatedResult<'TRecord, 'Key> = @@ -236,11 +236,10 @@ type PaginatedResult<'TRecord, 'Key> = LastEvaluatedKey: 'Key option } interface System.Collections.IEnumerable with - member x.GetEnumerator() = x.Records.GetEnumerator () + member x.GetEnumerator() = x.Records.GetEnumerator() interface System.Collections.Generic.IEnumerable<'TRecord> with - member x.GetEnumerator() = - (x.Records :> System.Collections.Generic.IEnumerable<'TRecord>).GetEnumerator () + member x.GetEnumerator() = (x.Records :> System.Collections.Generic.IEnumerable<'TRecord>).GetEnumerator() #nowarn "1182" diff --git a/src/FSharp.AWS.DynamoDB/Utils/DynamoUtils.fs b/src/FSharp.AWS.DynamoDB/Utils/DynamoUtils.fs index 542df10..db261a9 100644 --- a/src/FSharp.AWS.DynamoDB/Utils/DynamoUtils.fs +++ b/src/FSharp.AWS.DynamoDB/Utils/DynamoUtils.fs @@ -12,7 +12,7 @@ type AttributeValueComparer() = if m.Length <> m'.Length then false else - m.ToArray () = m'.ToArray () + m.ToArray() = m'.ToArray() static let areEqualResizeArrays (ra: ResizeArray<'T>) (ra': ResizeArray<'T>) = if ra.Count <> ra'.Count then @@ -108,12 +108,12 @@ type AttributeValueEqWrapper(av: AttributeValue) = override __.Equals(o) = match o with - | :? AttributeValueEqWrapper as av' -> AttributeValueComparer.Equals (av, av') + | :? AttributeValueEqWrapper as av' -> AttributeValueComparer.Equals(av, av') | _ -> false override __.GetHashCode() = AttributeValueComparer.GetHashCode av -let inline wrap av = new AttributeValueEqWrapper (av) +let inline wrap av = new AttributeValueEqWrapper(av) let inline unwrap (avw: AttributeValueEqWrapper) = avw.AttributeValue type AttributeValue with @@ -132,26 +132,26 @@ type AttributeValue with elif av.N <> null then sprintf "{ N = %s }" av.N elif av.B <> null then - sprintf "{ N = %A }" (av.B.ToArray ()) + sprintf "{ N = %A }" (av.B.ToArray()) elif av.SS.Count > 0 then sprintf "{ SS = %A }" (Seq.toArray av.SS) elif av.NS.Count > 0 then sprintf "{ SN = %A }" (Seq.toArray av.NS) elif av.BS.Count > 0 then av.BS - |> Seq.map (fun bs -> bs.ToArray ()) + |> Seq.map (fun bs -> bs.ToArray()) |> Seq.toArray |> sprintf "{ BS = %A }" elif av.IsLSet then av.L - |> Seq.map (fun av -> av.Print ()) + |> Seq.map (fun av -> av.Print()) |> Seq.toArray |> sprintf "{ L = %A }" elif av.IsMSet then av.M - |> Seq.map (fun kv -> (kv.Key, kv.Value.Print ())) + |> Seq.map (fun kv -> (kv.Key, kv.Value.Print())) |> Seq.toArray |> sprintf "{ M = %A }" @@ -160,7 +160,7 @@ type AttributeValue with // DynamoDB Name limitations, see: // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html -let private tableNameRegex = Regex ("^[\w\-_\.]*$", RegexOptions.Compiled) +let private tableNameRegex = Regex("^[\w\-_\.]*$", RegexOptions.Compiled) let isValidTableName (tableName: string) = if tableName.Length < 3 || tableName.Length > 255 then false diff --git a/src/FSharp.AWS.DynamoDB/Utils/Utils.fs b/src/FSharp.AWS.DynamoDB/Utils/Utils.fs index 1fe031b..5c21de9 100644 --- a/src/FSharp.AWS.DynamoDB/Utils/Utils.fs +++ b/src/FSharp.AWS.DynamoDB/Utils/Utils.fs @@ -13,20 +13,20 @@ open Microsoft.FSharp.Quotations.DerivedPatterns [] module internal Utils = - let inline rlist (ts: seq<'T>) = ResizeArray<_> (ts) + let inline rlist (ts: seq<'T>) = ResizeArray<_>(ts) - let inline keyVal k v = KeyValuePair<_, _> (k, v) + let inline keyVal k v = KeyValuePair<_, _>(k, v) let inline cdict (kvs: seq>) = - let d = new Dictionary<'K, 'V> () + let d = new Dictionary<'K, 'V>() for kv in kvs do - d.Add (kv.Key, kv.Value) + d.Add(kv.Key, kv.Value) d - let inline isNull o = obj.ReferenceEquals (o, null) - let inline notNull o = not <| obj.ReferenceEquals (o, null) + let inline isNull o = obj.ReferenceEquals(o, null) + let inline notNull o = not <| obj.ReferenceEquals(o, null) /// taken from mscorlib's Tuple.GetHashCode() implementation let inline combineHash (h1: int) (h2: int) = ((h1 <<< 5) + h1) ^^^ h2 @@ -41,9 +41,9 @@ module internal Utils = let inline hash4 (t: 'T) (s: 'S) (u: 'U) (v: 'V) = combineHash (combineHash (combineHash (hash t) (hash s)) (hash u)) (hash v) let inline mkString (builder: (string -> unit) -> unit) : string = - let sb = StringBuilder () + let sb = StringBuilder() builder (fun s -> sb.Append s |> ignore) - sb.ToString () + sb.ToString() let tryGetAttribute<'Attribute when 'Attribute :> Attribute> (attrs: seq) : 'Attribute option = attrs @@ -72,17 +72,17 @@ module internal Utils = type MemberInfo with member m.TryGetAttribute<'Attribute when 'Attribute :> Attribute>() : 'Attribute option = - m.GetCustomAttributes (true) + m.GetCustomAttributes(true) |> Seq.map unbox |> tryGetAttribute member m.GetAttributes<'Attribute when 'Attribute :> Attribute>() : 'Attribute[] = - m.GetCustomAttributes (true) + m.GetCustomAttributes(true) |> Seq.map unbox |> getAttributes member m.ContainsAttribute<'Attribute when 'Attribute :> Attribute>() : bool = - m.GetCustomAttributes (true) + m.GetCustomAttributes(true) |> Seq.map unbox |> containsAttribute @@ -94,9 +94,9 @@ module internal Utils = let dt = m.DeclaringType if dt.IsGenericType then - let gt = dt.GetGenericTypeDefinition () - let gas = dt.GetGenericArguments () - let mas = m.GetGenericArguments () + let gt = dt.GetGenericTypeDefinition() + let gas = dt.GetGenericArguments() + let mas = m.GetGenericArguments() let bindingFlags = BindingFlags.Public @@ -106,14 +106,14 @@ module internal Utils = ||| BindingFlags.FlattenHierarchy let m = - gt.GetMethods (bindingFlags) + gt.GetMethods(bindingFlags) |> Array.find (fun m' -> m.Name = m'.Name && m.MetadataToken = m'.MetadataToken) m, gas, mas elif m.IsGenericMethod then - let mas = m.GetGenericArguments () - m.GetGenericMethodDefinition (), [||], mas + let mas = m.GetGenericArguments() + m.GetGenericMethodDefinition(), [||], mas else m, [||], [||] @@ -124,8 +124,8 @@ module internal Utils = let dt = p.DeclaringType if dt.IsGenericType then - let gt = dt.GetGenericTypeDefinition () - let gas = dt.GetGenericArguments () + let gt = dt.GetGenericTypeDefinition() + let gas = dt.GetGenericArguments() let bindingFlags = BindingFlags.Public @@ -134,7 +134,7 @@ module internal Utils = ||| BindingFlags.Instance ||| BindingFlags.FlattenHierarchy - let gp = gt.GetProperty (p.Name, bindingFlags) + let gp = gt.GetProperty(p.Name, bindingFlags) gp, gas else @@ -142,8 +142,8 @@ module internal Utils = type Expr with - member e.IsClosed = e.GetFreeVars () |> Seq.isEmpty - member e.Substitute(v: Var, sub: Expr) = e.Substitute (fun w -> if v = w then Some sub else None) + member e.IsClosed = e.GetFreeVars() |> Seq.isEmpty + member e.Substitute(v: Var, sub: Expr) = e.Substitute(fun w -> if v = w then Some sub else None) type Environment with @@ -156,7 +156,7 @@ module internal Utils = static member ResolveEnvironmentVariable(variableName: string) = let aux found target = if String.IsNullOrWhiteSpace found then - Environment.GetEnvironmentVariable (variableName, target) + Environment.GetEnvironmentVariable(variableName, target) else found @@ -172,17 +172,17 @@ module internal Utils = /// See also https://github.com/fsharp/fsharp/issues/546 let (|SpecificCall2|_|) (pattern: Expr) = match pattern with - | Lambdas (_, Call (_, mI, _)) - | Call (_, mI, _) -> - let gm, _, _ = mI.GetUnderlyingMethodDefinition () + | Lambdas(_, Call(_, mI, _)) + | Call(_, mI, _) -> + let gm, _, _ = mI.GetUnderlyingMethodDefinition() fun (input: Expr) -> match input with - | Call (obj, mI', args) -> - let gm', ta, ma = mI'.GetUnderlyingMethodDefinition () + | Call(obj, mI', args) -> + let gm', ta, ma = mI'.GetUnderlyingMethodDefinition() if gm = gm' then - Some (obj, Array.toList ta, Array.toList ma, args) + Some(obj, Array.toList ta, Array.toList ma, args) else None | _ -> None @@ -191,23 +191,23 @@ module internal Utils = let (|SpecificProperty|_|) (pattern: Expr) = match pattern with - | Lambdas (_, PropertyGet (_, pI, _)) - | PropertyGet (_, pI, _) -> - let gp, _ = pI.GetUnderlyingProperty () + | Lambdas(_, PropertyGet(_, pI, _)) + | PropertyGet(_, pI, _) -> + let gp, _ = pI.GetUnderlyingProperty() fun (input: Expr) -> match input with - | PropertyGet (obj, pI', args) -> - let gp', ta = pI'.GetUnderlyingProperty () - if gp' = gp then Some (obj, Array.toList ta, args) else None + | PropertyGet(obj, pI', args) -> + let gp', ta = pI'.GetUnderlyingProperty() + if gp' = gp then Some(obj, Array.toList ta, args) else None | _ -> None | _ -> invalidArg "pattern" "supplied pattern is not a property getter" let (|IndexGet|_|) (e: Expr) = match e with - | SpecificCall2 <@ LanguagePrimitives.IntrinsicFunctions.GetArray @> (None, _, [ t ], [ obj; index ]) -> Some (obj, t, index) - | PropertyGet (Some obj, prop, [ index ]) when prop.Name = "Item" -> Some (obj, prop.PropertyType, index) + | SpecificCall2 <@ LanguagePrimitives.IntrinsicFunctions.GetArray @> (None, _, [ t ], [ obj; index ]) -> Some(obj, t, index) + | PropertyGet(Some obj, prop, [ index ]) when prop.Name = "Item" -> Some(obj, prop.PropertyType, index) | _ -> None let (|PipeLeft|_|) (e: Expr) = @@ -215,8 +215,8 @@ module internal Utils = | SpecificCall2 <@ (<|) @> (None, _, _, [ func; arg ]) -> let rec unwind (body: Expr) = match body with - | Let (x, value, body) -> unwind (body.Substitute (x, value)) - | Lambda (v, body) -> Some <| body.Substitute (v, arg) + | Let(x, value, body) -> unwind (body.Substitute(x, value)) + | Lambda(v, body) -> Some <| body.Substitute(v, arg) | _ -> None unwind func @@ -227,8 +227,8 @@ module internal Utils = | SpecificCall2 <@ (|>) @> (None, _, _, [ left; right ]) -> let rec unwind (body: Expr) = match body with - | Let (x, value, body) -> unwind (body.Substitute (x, value)) - | Lambda (x, body) -> Some <| body.Substitute (x, left) + | Let(x, value, body) -> unwind (body.Substitute(x, value)) + | Lambda(x, body) -> Some <| body.Substitute(x, left) | _ -> None unwind right @@ -236,14 +236,14 @@ module internal Utils = let (|ConsList|_|) (e: Expr) = match e with - | NewUnionCase (uci, [ h; t ]) -> + | NewUnionCase(uci, [ h; t ]) -> let dt = uci.DeclaringType if dt.IsGenericType - && dt.GetGenericTypeDefinition () = typedefof<_ list> + && dt.GetGenericTypeDefinition() = typedefof<_ list> then - Some (h, t) + Some(h, t) else None | _ -> None @@ -251,7 +251,7 @@ module internal Utils = type Async with /// Raise an exception - static member Raise e = Async.FromContinuations (fun (_, ec, _) -> ec e) + static member Raise e = Async.FromContinuations(fun (_, ec, _) -> ec e) (* Direct copies of canonical implementation at http://www.fssnip.net/7Rc/title/AsyncAwaitTaskCorrect pending that being officially packaged somewhere or integrated into FSharp.Core https://github.com/fsharp/fslang-suggestions/issues/840 *) @@ -264,8 +264,8 @@ module internal Utils = /// Task to be awaited. [] static member AwaitTaskCorrect(task: Task<'T>) : Async<'T> = - Async.FromContinuations (fun (sc, ec, _cc) -> - task.ContinueWith (fun (t: Task<'T>) -> + Async.FromContinuations(fun (sc, ec, _cc) -> + task.ContinueWith(fun (t: Task<'T>) -> if t.IsFaulted then let e = t.Exception @@ -274,7 +274,7 @@ module internal Utils = else ec e elif t.IsCanceled then - ec (TaskCanceledException ()) + ec (TaskCanceledException()) else sc t.Result) |> ignore) @@ -287,8 +287,8 @@ module internal Utils = /// Task to be awaited. [] static member AwaitTaskCorrect(task: Task) : Async = - Async.FromContinuations (fun (sc, ec, _cc) -> - task.ContinueWith (fun (task: Task) -> + Async.FromContinuations(fun (sc, ec, _cc) -> + task.ContinueWith(fun (task: Task) -> if task.IsFaulted then let e = task.Exception @@ -297,7 +297,7 @@ module internal Utils = else ec e elif task.IsCanceled then - ec (TaskCanceledException ()) + ec (TaskCanceledException()) else sc ()) |> ignore) diff --git a/tests/FSharp.AWS.DynamoDB.Tests/ConditionalExpressionTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/ConditionalExpressionTests.fs index c487ff6..b73ea24 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/ConditionalExpressionTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/ConditionalExpressionTests.fs @@ -69,20 +69,20 @@ module CondExprTypes = type ``Conditional Expression Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = { HashKey = guid () RangeKey = rand () Value = rand () Tuple = rand (), rand () - TimeSpan = TimeSpan.FromTicks (rand ()) + TimeSpan = TimeSpan.FromTicks(rand ()) DateTimeOffset = DateTimeOffset.Now - Guid = Guid.NewGuid () + Guid = Guid.NewGuid() Bool = false - Optional = Some (guid ()) + Optional = Some(guid ()) Ref = ref (guid ()) - Bytes = Guid.NewGuid().ToByteArray () + Bytes = Guid.NewGuid().ToByteArray() Nested = { NV = guid (); NE = enum (int (rand ()) % 3) } NestedList = [ { NV = guid (); NE = enum (int (rand ()) % 3) } ] LSI = rand () @@ -94,36 +94,36 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = Set = seq { for _ in 0L .. rand () % 5L -> rand () } |> Set.ofSeq List = [ for _ in 0L .. rand () % 5L -> rand () ] Array = [| for _ in 0L .. rand () % 5L -> rand () |] - Union = if rand () % 2L = 0L then UA (rand ()) else UB (guid ()) } + Union = if rand () % 2L = 0L then UA(rand ()) else UB(guid ()) } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Item exists precondition`` () = let item = mkItem () - fun () -> table.PutItem (item, precondition = itemExists) + fun () -> table.PutItem(item, precondition = itemExists) |> shouldFailwith<_, ConditionalCheckFailedException> let _key = table.PutItem item - table.PutItem (item, precondition = itemExists) =! _key + table.PutItem(item, precondition = itemExists) =! _key [] let ``Item not exists precondition`` () = let item = mkItem () - let _key = table.PutItem (item, precondition = itemDoesNotExist) + let _key = table.PutItem(item, precondition = itemDoesNotExist) - fun () -> table.PutItem (item, precondition = itemDoesNotExist) + fun () -> table.PutItem(item, precondition = itemDoesNotExist) |> shouldFailwith<_, ConditionalCheckFailedException> [] let ``Item not exists failure should add conflicting item data to the exception`` () = let item = mkItem () - let _key = table.PutItem (item, precondition = itemDoesNotExist) + let _key = table.PutItem(item, precondition = itemDoesNotExist) raisesWith <@ - table.PutItemAsync (item, precondition = itemDoesNotExist) + table.PutItemAsync(item, precondition = itemDoesNotExist) |> Async.RunSynchronously @> (fun e -> <@ e.Item.Count > 0 @>) @@ -133,24 +133,23 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.HashKey = guid () @>) + fun () -> table.PutItem(item, <@ fun r -> r.HashKey = guid () @>) |> shouldFailwith<_, ConditionalCheckFailedException> let hkey = item.HashKey - table.PutItem (item, <@ fun r -> r.HashKey = hkey @>) - =! _key + table.PutItem(item, <@ fun r -> r.HashKey = hkey @>) =! _key [] let ``Number precondition`` () = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Value = rand () @>) + fun () -> table.PutItem(item, <@ fun r -> r.Value = rand () @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Value - table.PutItem (item, <@ fun r -> r.Value = value @>) =! _key + table.PutItem(item, <@ fun r -> r.Value = value @>) =! _key [] let ``Bool precondition`` () = @@ -158,10 +157,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let value = item.Bool - fun () -> table.PutItem (item, <@ fun r -> r.Bool = not value @>) + fun () -> table.PutItem(item, <@ fun r -> r.Bool = not value @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Bool = value @>) =! _key + table.PutItem(item, <@ fun r -> r.Bool = value @>) =! _key [] let ``Bytes precondition`` () = @@ -169,28 +168,28 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let _value = item.Bool - fun () -> table.PutItem (item, <@ fun r -> r.Bytes = Guid.NewGuid().ToByteArray () @>) + fun () -> table.PutItem(item, <@ fun r -> r.Bytes = Guid.NewGuid().ToByteArray() @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Bytes - table.PutItem (item, <@ fun r -> r.Bytes = value @>) =! _key + table.PutItem(item, <@ fun r -> r.Bytes = value @>) =! _key [] let ``DateTimeOffset precondition`` () = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.DateTimeOffset > DateTimeOffset.Now + TimeSpan.FromDays (3.) @>) + fun () -> table.PutItem(item, <@ fun r -> r.DateTimeOffset > DateTimeOffset.Now + TimeSpan.FromDays(3.) @>) |> shouldFailwith<_, ConditionalCheckFailedException> let _value = item.DateTimeOffset - table.PutItem ( + table.PutItem( item, <@ fun r -> r.DateTimeOffset - <= DateTimeOffset.Now + TimeSpan.FromDays (3.) + <= DateTimeOffset.Now + TimeSpan.FromDays(3.) @> ) =! _key @@ -201,22 +200,22 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let UB = item.TimeSpan + item.TimeSpan - fun () -> table.PutItem (item, <@ fun r -> r.TimeSpan >= UB @>) + fun () -> table.PutItem(item, <@ fun r -> r.TimeSpan >= UB @>) |> shouldFailwith<_, ConditionalCheckFailedException> let _value = item.DateTimeOffset - table.PutItem (item, <@ fun r -> r.TimeSpan < UB @>) =! _key + table.PutItem(item, <@ fun r -> r.TimeSpan < UB @>) =! _key [] let ``Guid precondition`` () = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Guid = Guid.NewGuid () @>) + fun () -> table.PutItem(item, <@ fun r -> r.Guid = Guid.NewGuid() @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Guid - table.PutItem (item, <@ fun r -> r.Guid = value @>) =! _key + table.PutItem(item, <@ fun r -> r.Guid = value @>) =! _key [] let ``Guid not equal precondition`` () = @@ -224,11 +223,11 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let value = item.Guid - fun () -> table.PutItem (item, <@ fun r -> r.Guid <> value @>) + fun () -> table.PutItem(item, <@ fun r -> r.Guid <> value @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Guid <> Guid.NewGuid () @>) + table.PutItem(item, <@ fun r -> r.Guid <> Guid.NewGuid() @>) =! _key [] @@ -236,15 +235,15 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Optional = None @>) + fun () -> table.PutItem(item, <@ fun r -> r.Optional = None @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Optional - table.PutItem ({ item with Optional = None }, <@ fun r -> r.Optional = value @>) + table.PutItem({ item with Optional = None }, <@ fun r -> r.Optional = value @>) =! _key - fun () -> table.PutItem (item, <@ fun r -> r.Optional = (guid () |> Some) @>) + fun () -> table.PutItem(item, <@ fun r -> r.Optional = (guid () |> Some) @>) |> shouldFailwith<_, ConditionalCheckFailedException> [] @@ -252,13 +251,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Optional = Some "foo" } let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Optional.Value = "bar" @>) + fun () -> table.PutItem(item, <@ fun r -> r.Optional.Value = "bar" @>) |> shouldFailwith<_, ConditionalCheckFailedException> let _value = item.Optional - let _ = table.PutItem ({ item with Optional = None }, <@ fun r -> r.Optional.Value = "foo" @>) + let _ = table.PutItem({ item with Optional = None }, <@ fun r -> r.Optional.Value = "foo" @>) - fun () -> table.PutItem (item, <@ fun r -> r.Optional.Value = "foo" @>) + fun () -> table.PutItem(item, <@ fun r -> r.Optional.Value = "foo" @>) |> shouldFailwith<_, ConditionalCheckFailedException> [] @@ -266,12 +265,12 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Ref = (guid () |> ref) @>) + fun () -> table.PutItem(item, <@ fun r -> r.Ref = (guid () |> ref) @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Ref.Value - table.PutItem (item, <@ fun r -> r.Ref = ref value @>) + table.PutItem(item, <@ fun r -> r.Ref = ref value @>) =! _key [] @@ -279,12 +278,12 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> fst r.Tuple = rand () @>) + fun () -> table.PutItem(item, <@ fun r -> fst r.Tuple = rand () @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = fst item.Tuple - table.PutItem (item, <@ fun r -> fst r.Tuple = value @>) + table.PutItem(item, <@ fun r -> fst r.Tuple = value @>) =! _key [] @@ -292,13 +291,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Nested = { NV = guid (); NE = Enum.C } @>) + fun () -> table.PutItem(item, <@ fun r -> r.Nested = { NV = guid (); NE = Enum.C } @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Nested.NV let enum = item.Nested.NE - table.PutItem (item, <@ fun r -> r.Nested = { NV = value; NE = enum } @>) + table.PutItem(item, <@ fun r -> r.Nested = { NV = value; NE = enum } @>) =! _key [] @@ -306,12 +305,12 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Nested.NV = guid () @>) + fun () -> table.PutItem(item, <@ fun r -> r.Nested.NV = guid () @>) |> shouldFailwith<_, ConditionalCheckFailedException> let value = item.Nested.NE - table.PutItem (item, <@ fun r -> r.Nested.NE = value @>) + table.PutItem(item, <@ fun r -> r.Nested.NE = value @>) =! _key [] @@ -319,10 +318,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Union = UA (rand ()) @>) + fun () -> table.PutItem(item, <@ fun r -> r.Union = UA(rand ()) @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Union = item.Union @>) + table.PutItem(item, <@ fun r -> r.Union = item.Union @>) =! _key [] @@ -330,10 +329,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Ref = ref "12-42-12" } let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Ref.Value.Contains "41" @>) + fun () -> table.PutItem(item, <@ fun r -> r.Ref.Value.Contains "41" @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Ref.Value.Contains "42" @>) + table.PutItem(item, <@ fun r -> r.Ref.Value.Contains "42" @>) =! _key [] @@ -341,10 +340,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Ref = ref "12-42-12" } let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Ref.Value.StartsWith "41" @>) + fun () -> table.PutItem(item, <@ fun r -> r.Ref.Value.StartsWith "41" @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Ref.Value.StartsWith "12" @>) + table.PutItem(item, <@ fun r -> r.Ref.Value.StartsWith "12" @>) =! _key [] @@ -353,10 +352,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let elem = item.HashKey - fun () -> table.PutItem (item, <@ fun r -> r.HashKey.Length <> elem.Length @>) + fun () -> table.PutItem(item, <@ fun r -> r.HashKey.Length <> elem.Length @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.HashKey.Length >= elem.Length @>) + table.PutItem(item, <@ fun r -> r.HashKey.Length >= elem.Length @>) =! _key @@ -366,13 +365,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let bytes = item.Bytes - fun () -> table.PutItem (item, <@ fun r -> r.Bytes.Length <> bytes.Length @>) + fun () -> table.PutItem(item, <@ fun r -> r.Bytes.Length <> bytes.Length @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Bytes.Length >= bytes.Length @>) + table.PutItem(item, <@ fun r -> r.Bytes.Length >= bytes.Length @>) =! _key - table.PutItem (item, <@ fun r -> r.Bytes |> Array.length >= bytes.Length @>) + table.PutItem(item, <@ fun r -> r.Bytes |> Array.length >= bytes.Length @>) =! _key [] @@ -381,10 +380,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let nested = item.NestedList[0] - fun () -> table.PutItem (item, <@ fun r -> r.NestedList[0].NV = guid () @>) + fun () -> table.PutItem(item, <@ fun r -> r.NestedList[0].NV = guid () @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.NestedList[0] = nested @>) + table.PutItem(item, <@ fun r -> r.NestedList[0] = nested @>) =! _key [] @@ -393,13 +392,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let list = item.List - fun () -> table.PutItem (item, <@ fun r -> r.List.Length <> list.Length @>) + fun () -> table.PutItem(item, <@ fun r -> r.List.Length <> list.Length @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.List.Length >= list.Length @>) + table.PutItem(item, <@ fun r -> r.List.Length >= list.Length @>) =! _key - table.PutItem (item, <@ fun r -> List.length r.List >= list.Length @>) + table.PutItem(item, <@ fun r -> List.length r.List >= list.Length @>) =! _key [] @@ -407,10 +406,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = { mkItem () with List = [] } let _key = table.PutItem item - table.PutItem ({ item with List = [ 42L ] }, <@ fun r -> List.isEmpty r.List @>) + table.PutItem({ item with List = [ 42L ] }, <@ fun r -> List.isEmpty r.List @>) =! _key - fun () -> table.PutItem (item, <@ fun r -> List.isEmpty r.List @>) + fun () -> table.PutItem(item, <@ fun r -> List.isEmpty r.List @>) |> shouldFailwith<_, ConditionalCheckFailedException> @@ -420,13 +419,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let set = item.Set - fun () -> table.PutItem (item, <@ fun r -> r.Set.Count <> set.Count @>) + fun () -> table.PutItem(item, <@ fun r -> r.Set.Count <> set.Count @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Set.Count <= set.Count @>) + table.PutItem(item, <@ fun r -> r.Set.Count <= set.Count @>) =! _key - table.PutItem (item, <@ fun r -> r.Set |> Set.count >= Set.count set @>) + table.PutItem(item, <@ fun r -> r.Set |> Set.count >= Set.count set @>) =! _key [] @@ -435,13 +434,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let elem = item.Set |> Seq.max - fun () -> table.PutItem (item, <@ fun r -> r.Set.Contains (elem + 1L) @>) + fun () -> table.PutItem(item, <@ fun r -> r.Set.Contains(elem + 1L) @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Set.Contains elem @>) + table.PutItem(item, <@ fun r -> r.Set.Contains elem @>) =! _key - table.PutItem (item, <@ fun r -> r.Set |> Set.contains elem @>) + table.PutItem(item, <@ fun r -> r.Set |> Set.contains elem @>) =! _key [] @@ -450,10 +449,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let map = item.Map - fun () -> table.PutItem (item, <@ fun r -> r.Map.Count <> map.Count @>) + fun () -> table.PutItem(item, <@ fun r -> r.Map.Count <> map.Count @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Map.Count >= map.Count @>) + table.PutItem(item, <@ fun r -> r.Map.Count >= map.Count @>) =! _key [] @@ -462,13 +461,13 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let elem = item.Map |> Map.toSeq |> Seq.head |> fst - fun () -> table.PutItem (item, <@ fun r -> r.Map.ContainsKey (elem + "foo") @>) + fun () -> table.PutItem(item, <@ fun r -> r.Map.ContainsKey(elem + "foo") @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Map.ContainsKey elem @>) + table.PutItem(item, <@ fun r -> r.Map.ContainsKey elem @>) =! _key - table.PutItem (item, <@ fun r -> r.Map |> Map.containsKey elem @>) + table.PutItem(item, <@ fun r -> r.Map |> Map.containsKey elem @>) =! _key [] @@ -476,10 +475,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 42L) ] } let _key = table.PutItem item - fun () -> table.PutItem (item, <@ fun r -> r.Map["A"] = 41L @>) + fun () -> table.PutItem(item, <@ fun r -> r.Map["A"] = 41L @>) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, <@ fun r -> r.Map["A"] = 42L @>) + table.PutItem(item, <@ fun r -> r.Map["A"] = 42L @>) |> ignore [] @@ -488,10 +487,10 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let cond = table.Template.PrecomputeConditionalExpr <@ fun k v r -> r.Map[k] = v @> - fun () -> table.PutItem (item, cond "A" 41L) + fun () -> table.PutItem(item, cond "A" 41L) |> shouldFailwith<_, ConditionalCheckFailedException> - table.PutItem (item, cond "A" 42L) =! _key + table.PutItem(item, cond "A" 42L) =! _key [] @@ -506,18 +505,18 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let ``EXISTS precondition`` () = let item = { mkItem () with List = [ 1L ] } let _key = table.PutItem item - let _ = table.PutItem (item, precondition = <@ fun r -> EXISTS r.List[0] @>) + let _ = table.PutItem(item, precondition = <@ fun r -> EXISTS r.List[0] @>) - fun () -> table.PutItem (item, precondition = <@ fun r -> EXISTS r.List[1] @>) + fun () -> table.PutItem(item, precondition = <@ fun r -> EXISTS r.List[1] @>) |> shouldFailwith<_, ConditionalCheckFailedException> [] let ``NOT_EXISTS precondition`` () = let item = { mkItem () with List = [ 1L ] } let _key = table.PutItem item - let _ = table.PutItem (item, precondition = <@ fun r -> NOT_EXISTS r.List[1] @>) + let _ = table.PutItem(item, precondition = <@ fun r -> NOT_EXISTS r.List[1] @>) - fun () -> table.PutItem (item, precondition = <@ fun r -> NOT_EXISTS r.List[0] @>) + fun () -> table.PutItem(item, precondition = <@ fun r -> NOT_EXISTS r.List[0] @>) |> shouldFailwith<_, ConditionalCheckFailedException> [] @@ -525,7 +524,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let item = mkItem () let _key = table.PutItem item - table.PutItem ( + table.PutItem( item, <@ fun r -> @@ -536,7 +535,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = ) =! _key - table.PutItem ( + table.PutItem( item, <@ fun r -> @@ -558,7 +557,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = |> Async.RunSynchronously - let results = table.Query (<@ fun r -> r.HashKey = hKey && BETWEEN r.RangeKey 50L 149L @>) + let results = table.Query(<@ fun r -> r.HashKey = hKey && BETWEEN r.RangeKey 50L 149L @>) test <@ 100 = results.Length @> [] @@ -573,7 +572,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = |> Async.RunSynchronously let results = - table.Query (<@ fun r -> r.HashKey = hKey && BETWEEN r.RangeKey 50L 149L @>, filterCondition = <@ fun r -> r.Bool = true @>) + table.Query(<@ fun r -> r.HashKey = hKey && BETWEEN r.RangeKey 50L 149L @>, filterCondition = <@ fun r -> r.Bool = true @>) test <@ 50 = results.Length @> @@ -603,7 +602,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = [] let ``Detect incompatible comparisons`` () = let test outcome q = - let f () = table.Template.PrecomputeConditionalExpr (q) + let f () = table.Template.PrecomputeConditionalExpr(q) if outcome then f () |> ignore @@ -630,7 +629,7 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = |> Async.Ignore |> Async.RunSynchronously - let results = table.Scan (<@ fun r -> r.HashKey = hKey && r.RangeKey <= 100L && r.Bool = true @>) + let results = table.Scan(<@ fun r -> r.HashKey = hKey && r.RangeKey <= 100L && r.Bool = true @>) test <@ 50 = results.Length @> [] @@ -639,15 +638,14 @@ type ``Conditional Expression Tests``(fixture: TableFixture) = let _key = table.PutItem item let cond = table.Template.PrecomputeConditionalExpr <@ fun hk rk r -> r.HashKey = hk && r.RangeKey = rk @> - table.PutItem (item, cond item.HashKey item.RangeKey) - =! _key + table.PutItem(item, cond item.HashKey item.RangeKey) =! _key [] let ``Parametric Conditional with optional argument`` () = let item = { mkItem () with Optional = None } let _key = table.PutItem item let cond = table.Template.PrecomputeConditionalExpr <@ fun opt r -> r.Optional = opt @> - table.PutItem (item, cond None) =! _key + table.PutItem(item, cond None) =! _key [] let ``Parametric Conditional with invalid param usage`` () = diff --git a/tests/FSharp.AWS.DynamoDB.Tests/MetricsCollectorTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/MetricsCollectorTests.fs index b18851b..a8f7427 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/MetricsCollectorTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/MetricsCollectorTests.fs @@ -26,7 +26,7 @@ type MetricsRecord = LocalAttribute: int } -let rand = let r = Random.Shared in fun () -> r.Next () |> int64 +let rand = let r = Random.Shared in fun () -> r.Next() |> int64 let mkItem (hk: string) (gshk: string) (i: int) : MetricsRecord = { HashKey = hk @@ -38,32 +38,32 @@ let mkItem (hk: string) (gshk: string) (i: int) : MetricsRecord = type TestCollector() = - let metrics = ResizeArray () + let metrics = ResizeArray() member _.Collect(m: RequestMetrics) = metrics.Add m member _.Metrics = metrics |> Seq.toList - member _.Clear() = metrics.Clear () + member _.Clear() = metrics.Clear() let (|TotalCu|): ConsumedCapacity list -> float = Seq.sumBy (fun c -> c.CapacityUnits) /// Tests without common setup type Tests(fixture: TableFixture) = - let rawTable = fixture.CreateEmpty () + let rawTable = fixture.CreateEmpty() - let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some () else None + let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some() else None - let collector = TestCollector () - let sut = rawTable.WithMetricsCollector (collector.Collect) + let collector = TestCollector() + let sut = rawTable.WithMetricsCollector(collector.Collect) [] let ``Collect Metrics on TryGetItem`` () = async { let! result = let nonExistentHk = guid () - sut.TryGetItemAsync (key = TableKey.Combined (nonExistentHk, 0)) + sut.TryGetItemAsync(key = TableKey.Combined(nonExistentHk, 0)) None =! result @@ -109,10 +109,10 @@ type Tests(fixture: TableFixture) = | x -> failwithf "Unexpected %A" x @> - collector.Clear () + collector.Clear() let item = mkItem (guid ()) (guid ()) 0 - let requests = [ TransactWrite.Put (item, Some (compile <@ fun t -> NOT_EXISTS t.RangeKey @>)) ] + let requests = [ TransactWrite.Put(item, Some(compile <@ fun t -> NOT_EXISTS t.RangeKey @>)) ] do! sut.TransactWriteItems requests @@ -126,20 +126,20 @@ type Tests(fixture: TableFixture) = | _ -> false @> - let! itemFound = sut.ContainsKeyAsync (sut.Template.ExtractKey item) + let! itemFound = sut.ContainsKeyAsync(sut.Template.ExtractKey item) test <@ itemFound @> } [] let ``No Metrics on Canceled PutItem`` () = async { - let collector = TestCollector () - let sut = rawTable.WithMetricsCollector (collector.Collect) + let collector = TestCollector() + let sut = rawTable.WithMetricsCollector(collector.Collect) let item = mkItem (guid ()) (guid ()) 0 // The check will fail, which triggers a throw from the underlying AWS SDK; there's no way to extract the consumption info in that case - let requests = [ TransactWrite.Put (item, Some (compile <@ fun t -> EXISTS t.RangeKey @>)) ] + let requests = [ TransactWrite.Put(item, Some(compile <@ fun t -> EXISTS t.RangeKey @>)) ] let mutable failed = false @@ -157,18 +157,18 @@ type Tests(fixture: TableFixture) = /// Tests that look up a specific item. Each test run gets a fresh individual item type ItemTests(fixture: TableFixture) = - let rawTable = fixture.CreateEmpty () - let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some () else None + let rawTable = fixture.CreateEmpty() + let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some() else None let item = mkItem (guid ()) (guid ()) 0 do rawTable.PutItem item |> ignore - let collector = TestCollector () - let sut = rawTable.WithMetricsCollector (collector.Collect) + let collector = TestCollector() + let sut = rawTable.WithMetricsCollector(collector.Collect) [] let ``Collect Metrics on GetItem`` () = - let _ = sut.GetItem (key = TableKey.Combined (item.HashKey, 0)) + let _ = sut.GetItem(key = TableKey.Combined(item.HashKey, 0)) test <@ @@ -182,7 +182,7 @@ type ItemTests(fixture: TableFixture) = [] let ``Collect Metrics on ContainsKey`` () = - let _ = sut.ContainsKey (key = TableKey.Combined (item.HashKey, 0)) + let _ = sut.ContainsKey(key = TableKey.Combined(item.HashKey, 0)) test <@ @@ -197,10 +197,7 @@ type ItemTests(fixture: TableFixture) = [] let ``Collect Metrics on UpdateItem`` () = let _ = - sut.UpdateItem ( - TableKey.Combined (item.HashKey, item.RangeKey), - <@ fun (i: MetricsRecord) -> { i with LocalAttribute = 1000 } @> - ) + sut.UpdateItem(TableKey.Combined(item.HashKey, item.RangeKey), <@ fun (i: MetricsRecord) -> { i with LocalAttribute = 1000 } @>) test <@ @@ -214,7 +211,7 @@ type ItemTests(fixture: TableFixture) = [] let ``Collect Metrics on DeleteItem`` () = - let _ = sut.DeleteItem (TableKey.Combined (item.HashKey, item.RangeKey)) + let _ = sut.DeleteItem(TableKey.Combined(item.HashKey, item.RangeKey)) test <@ @@ -231,8 +228,8 @@ type ItemTests(fixture: TableFixture) = /// Heavy tests reliant on establishing (and mutating) multiple items. Separate Test Class so Xunit will run them in parallel with others type BulkMutationTests(fixture: TableFixture) = - let rawTable = fixture.CreateEmpty () - let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some () else None + let rawTable = fixture.CreateEmpty() + let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some() else None // NOTE we mutate the items so they need to be established each time let items = @@ -243,12 +240,12 @@ type BulkMutationTests(fixture: TableFixture) = for item in items do rawTable.PutItem item |> ignore - let collector = TestCollector () - let sut = rawTable.WithMetricsCollector (collector.Collect) + let collector = TestCollector() + let sut = rawTable.WithMetricsCollector(collector.Collect) [] let ``Collect Metrics on BatchPutItem`` () = - let _results = sut.BatchPutItems (items |> Seq.map (fun i -> { i with LocalAttribute = 1000 })) + let _results = sut.BatchPutItems(items |> Seq.map (fun i -> { i with LocalAttribute = 1000 })) test <@ @@ -263,9 +260,9 @@ type BulkMutationTests(fixture: TableFixture) = [] let ``Collect Metrics on BatchDeleteItem`` () = let _keys = - sut.BatchDeleteItems ( + sut.BatchDeleteItems( items - |> Seq.map (fun i -> TableKey.Combined (i.HashKey, i.RangeKey)) + |> Seq.map (fun i -> TableKey.Combined(i.HashKey, i.RangeKey)) ) test @@ -285,7 +282,7 @@ type ManyReadOnlyItemsFixture() = inherit TableFixture() // TOCONSIDER shift this into IAsyncLifetime.InitializeAsync - let table = base.CreateEmpty () + let table = base.CreateEmpty() let hk = guid () @@ -303,14 +300,14 @@ type ManyReadOnlyItemsFixture() = // DO NOT add tests that will delete or mutate those items type ``Bulk Read Operations``(fixture: ManyReadOnlyItemsFixture) = - let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some () else None + let (|ExpectedTableName|_|) name = if name = fixture.TableName then Some() else None - let collector = TestCollector () - let sut = fixture.Table.WithMetricsCollector (collector.Collect) + let collector = TestCollector() + let sut = fixture.Table.WithMetricsCollector(collector.Collect) [] let ``Collect Metrics on Scan`` () = - let items = sut.Scan () + let items = sut.Scan() test <@ @@ -324,7 +321,7 @@ type ``Bulk Read Operations``(fixture: ManyReadOnlyItemsFixture) = [] let ``Collect Metrics on Query`` () = - let items = sut.Query (<@ fun (r: MetricsRecord) -> r.HashKey = fixture.HashKey @>) + let items = sut.Query(<@ fun (r: MetricsRecord) -> r.HashKey = fixture.HashKey @>) test <@ @@ -338,7 +335,7 @@ type ``Bulk Read Operations``(fixture: ManyReadOnlyItemsFixture) = [] let ``Collect Metrics on BatchGetItem`` () = - let items = sut.BatchGetItems (seq { for i in 0..99 -> TableKey.Combined (fixture.HashKey, i) }) + let items = sut.BatchGetItems(seq { for i in 0..99 -> TableKey.Combined(fixture.HashKey, i) }) test <@ diff --git a/tests/FSharp.AWS.DynamoDB.Tests/MultipleKeyAttributeTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/MultipleKeyAttributeTests.fs index 3c7f88c..9525fdf 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/MultipleKeyAttributeTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/MultipleKeyAttributeTests.fs @@ -32,13 +32,13 @@ module MultiKeyTypes = type ``Inverse GSI Table Operation Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = - { PrimaryKey = ((int (rand ())) % 50).ToString () - SortKey = ((int (rand ())) % 50).ToString () } + { PrimaryKey = ((int (rand ())) % 50).ToString() + SortKey = ((int (rand ())) % 50).ToString() } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Query by Table Key and GSI`` () = @@ -71,15 +71,15 @@ type ``Inverse GSI Table Operation Tests``(fixture: TableFixture) = type ``Shared Range Key Table Operation Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = { HashKey = guid () - GSI1 = ((int (rand ())) % 5).ToString () - GSI2 = ((int (rand ())) % 5 + 20).ToString () - SortKey = ((int (rand ())) % 50).ToString () } + GSI1 = ((int (rand ())) % 5).ToString() + GSI2 = ((int (rand ())) % 5 + 20).ToString() + SortKey = ((int (rand ())) % 50).ToString() } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Query by GSIs with shared range key`` () = diff --git a/tests/FSharp.AWS.DynamoDB.Tests/PaginationTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/PaginationTests.fs index 14cb576..33d5090 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/PaginationTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/PaginationTests.fs @@ -30,7 +30,7 @@ module PaginationTests = type ``Pagination Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem (hk: string) (gshk: string) : PaginationRecord = { HashKey = hk @@ -40,7 +40,7 @@ type ``Pagination Tests``(fixture: TableFixture) = SecondaryRangeKey = guid () LocalAttribute = int (rand () % 2L) } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Paginated Query on Primary Key`` () = @@ -54,11 +54,11 @@ type ``Pagination Tests``(fixture: TableFixture) = for item in items do table.PutItem item - =! TableKey.Combined (item.HashKey, item.RangeKey) + =! TableKey.Combined(item.HashKey, item.RangeKey) - let res1 = table.QueryPaginated (<@ fun r -> r.HashKey = hk @>, limit = 5) - let res2 = table.QueryPaginated (<@ fun r -> r.HashKey = hk @>, limit = 5, ?exclusiveStartKey = res1.LastEvaluatedKey) - let res3 = table.QueryPaginated (<@ fun r -> r.HashKey = hk @>, limit = 5, ?exclusiveStartKey = res2.LastEvaluatedKey) + let res1 = table.QueryPaginated(<@ fun r -> r.HashKey = hk @>, limit = 5) + let res2 = table.QueryPaginated(<@ fun r -> r.HashKey = hk @>, limit = 5, ?exclusiveStartKey = res1.LastEvaluatedKey) + let res3 = table.QueryPaginated(<@ fun r -> r.HashKey = hk @>, limit = 5, ?exclusiveStartKey = res2.LastEvaluatedKey) test <@ @@ -85,19 +85,19 @@ type ``Pagination Tests``(fixture: TableFixture) = for item in items do table.PutItem item - =! TableKey.Combined (item.HashKey, item.RangeKey) + =! TableKey.Combined(item.HashKey, item.RangeKey) - let res1 = table.QueryPaginated (<@ fun r -> r.HashKey = hk && r.LocalSecondaryRangeKey > "0" @>, limit = 5) + let res1 = table.QueryPaginated(<@ fun r -> r.HashKey = hk && r.LocalSecondaryRangeKey > "0" @>, limit = 5) let res2 = - table.QueryPaginated ( + table.QueryPaginated( <@ fun r -> r.HashKey = hk && r.LocalSecondaryRangeKey > "0" @>, limit = 5, ?exclusiveStartKey = res1.LastEvaluatedKey ) let res3 = - table.QueryPaginated ( + table.QueryPaginated( <@ fun r -> r.HashKey = hk && r.LocalSecondaryRangeKey > "0" @>, limit = 5, ?exclusiveStartKey = res2.LastEvaluatedKey @@ -128,11 +128,11 @@ type ``Pagination Tests``(fixture: TableFixture) = for item in items do table.PutItem item - =! TableKey.Combined (item.HashKey, item.RangeKey) + =! TableKey.Combined(item.HashKey, item.RangeKey) - let res1 = table.QueryPaginated (<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5) - let res2 = table.QueryPaginated (<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5, ?exclusiveStartKey = res1.LastEvaluatedKey) - let res3 = table.QueryPaginated (<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5, ?exclusiveStartKey = res2.LastEvaluatedKey) + let res1 = table.QueryPaginated(<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5) + let res2 = table.QueryPaginated(<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5, ?exclusiveStartKey = res1.LastEvaluatedKey) + let res3 = table.QueryPaginated(<@ fun r -> r.SecondaryHashKey = gsk @>, limit = 5, ?exclusiveStartKey = res2.LastEvaluatedKey) test <@ @@ -159,9 +159,9 @@ type ``Pagination Tests``(fixture: TableFixture) = for item in items do table.PutItem item - =! TableKey.Combined (item.HashKey, item.RangeKey) + =! TableKey.Combined(item.HashKey, item.RangeKey) - let res = table.QueryPaginated (<@ fun r -> r.HashKey = hk @>, filterCondition = <@ fun r -> r.LocalAttribute = 0 @>, limit = 5) + let res = table.QueryPaginated(<@ fun r -> r.HashKey = hk @>, filterCondition = <@ fun r -> r.LocalAttribute = 0 @>, limit = 5) test <@ diff --git a/tests/FSharp.AWS.DynamoDB.Tests/ProjectionExpressionTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/ProjectionExpressionTests.fs index e2b2cbd..9f6cf0d 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/ProjectionExpressionTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/ProjectionExpressionTests.fs @@ -73,9 +73,9 @@ module ProjectionExprTypes = type ``Projection Expression Tests``(fixture: TableFixture) = - static let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + static let rand = let r = Random.Shared in fun () -> int64 <| r.Next() - let bytes () = Guid.NewGuid().ToByteArray () + let bytes () = Guid.NewGuid().ToByteArray() let mkItem () = { HashKey = guid () @@ -83,13 +83,13 @@ type ``Projection Expression Tests``(fixture: TableFixture) = String = guid () Value = rand () Tuple = rand (), rand () - TimeSpan = TimeSpan.FromTicks (rand ()) + TimeSpan = TimeSpan.FromTicks(rand ()) DateTimeOffset = DateTimeOffset.Now - Guid = Guid.NewGuid () + Guid = Guid.NewGuid() Bool = false - Optional = Some (guid ()) + Optional = Some(guid ()) Ref = ref (guid ()) - Bytes = Guid.NewGuid().ToByteArray () + Bytes = Guid.NewGuid().ToByteArray() Nested = { NV = guid (); NE = enum (int (rand ()) % 3) } NestedList = [ { NV = guid (); NE = enum (int (rand ()) % 3) } ] Map = @@ -99,10 +99,10 @@ type ``Projection Expression Tests``(fixture: TableFixture) = StringSet = seq { for _ in 0L .. rand () % 5L -> guid () } |> Set.ofSeq ByteSet = seq { for _ in 0L .. rand () % 5L -> bytes () } |> Set.ofSeq List = [ for _ in 0L .. rand () % 5L -> rand () ] - Union = if rand () % 2L = 0L then UA (rand ()) else UB (guid ()) - Unions = [ for _ in 0L .. rand () % 5L -> if rand () % 2L = 0L then UA (rand ()) else UB (guid ()) ] } + Union = if rand () % 2L = 0L then UA(rand ()) else UB(guid ()) + Unions = [ for _ in 0L .. rand () % 5L -> if rand () % 2L = 0L then UA(rand ()) else UB(guid ()) ] } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Should fail on invalid projections`` () = @@ -127,57 +127,57 @@ type ``Projection Expression Tests``(fixture: TableFixture) = [] let ``Null value projection`` () = let item = mkItem () - let key = table.PutItem (item) - table.GetItemProjected (key, <@ fun _ -> () @>) - table.GetItemProjected (key, <@ ignore @>) + let key = table.PutItem(item) + table.GetItemProjected(key, <@ fun _ -> () @>) + table.GetItemProjected(key, <@ ignore @>) [] let ``Single value projection`` () = let item = mkItem () - let key = table.PutItem (item) - let guid = table.GetItemProjected (key, <@ fun r -> r.Guid @>) + let key = table.PutItem(item) + let guid = table.GetItemProjected(key, <@ fun r -> r.Guid @>) test <@ item.Guid = guid @> [] let ``Map projection`` () = let item = mkItem () - let key = table.PutItem (item) - let map = table.GetItemProjected (key, <@ fun r -> r.Map @>) + let key = table.PutItem(item) + let map = table.GetItemProjected(key, <@ fun r -> r.Map @>) test <@ item.Map = map @> [] let ``Option-None projection`` () = let item = { mkItem () with Optional = None } - let key = table.PutItem (item) - let opt = table.GetItemProjected (key, <@ fun r -> r.Optional @>) + let key = table.PutItem(item) + let opt = table.GetItemProjected(key, <@ fun r -> r.Optional @>) test <@ None = opt @> [] let ``Option-Some projection`` () = let item = { mkItem () with Optional = Some "test" } - let key = table.PutItem (item) - let opt = table.GetItemProjected (key, <@ fun r -> r.Optional @>) + let key = table.PutItem(item) + let opt = table.GetItemProjected(key, <@ fun r -> r.Optional @>) test <@ item.Optional = opt @> [] let ``Multi-value projection`` () = let item = mkItem () - let key = table.PutItem (item) - let result = table.GetItemProjected (key, <@ fun r -> r.Bool, r.ByteSet, r.Bytes @>) + let key = table.PutItem(item) + let result = table.GetItemProjected(key, <@ fun r -> r.Bool, r.ByteSet, r.Bytes @>) test <@ (item.Bool, item.ByteSet, item.Bytes) = result @> [] let ``Nested value projection 1`` () = let item = { mkItem () with Map = Map.ofList [ "Nested", 42L ] } - let key = table.PutItem (item) - let result = table.GetItemProjected (key, <@ fun r -> r.Nested.NV, r.NestedList[0].NV, r.Map["Nested"] @>) + let key = table.PutItem(item) + let result = table.GetItemProjected(key, <@ fun r -> r.Nested.NV, r.NestedList[0].NV, r.Map["Nested"] @>) test <@ (item.Nested.NV, item.NestedList[0].NV, item.Map["Nested"]) = result @> [] let ``Nested value projection 2`` () = let item = { mkItem () with List = [ 1L; 2L; 3L ] } - let key = table.PutItem (item) - let result = table.GetItemProjected (key, <@ fun r -> r.List[0], r.List[1] @>) + let key = table.PutItem(item) + let result = table.GetItemProjected(key, <@ fun r -> r.List[0], r.List[1] @>) test <@ (item.List[0], item.List[1]) = result @> [] @@ -191,7 +191,7 @@ type ``Projection Expression Tests``(fixture: TableFixture) = |> Async.Ignore |> Async.RunSynchronously - let results = table.QueryProjected (<@ fun r -> r.HashKey = hKey @>, <@ fun r -> r.RangeKey @>) + let results = table.QueryProjected(<@ fun r -> r.HashKey = hKey @>, <@ fun r -> r.RangeKey @>) test <@ set [ 1..200 ] = (results |> Seq.map int |> set) @> [] @@ -205,7 +205,7 @@ type ``Projection Expression Tests``(fixture: TableFixture) = |> Async.Ignore |> Async.RunSynchronously - let results = table.ScanProjected (<@ fun r -> r.RangeKey @>, filterCondition = <@ fun r -> r.HashKey = hKey @>) + let results = table.ScanProjected(<@ fun r -> r.RangeKey @>, filterCondition = <@ fun r -> r.HashKey = hKey @>) test <@ set [ 1..200 ] = (results |> Seq.map int |> set) @> interface IClassFixture diff --git a/tests/FSharp.AWS.DynamoDB.Tests/RecordGenerationTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/RecordGenerationTests.fs index ba6e711..62b853c 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/RecordGenerationTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/RecordGenerationTests.fs @@ -17,7 +17,7 @@ module ``Record Generation Tests`` = static member RoundTrip<'Record when 'Record: equality>(?tolerateInequality) = let tolerateInequality = defaultArg tolerateInequality false let mutable isFoundInequality = false - let rt = RecordTemplate.Define<'Record> () + let rt = RecordTemplate.Define<'Record>() let roundTrip (r: 'Record) = try @@ -40,7 +40,7 @@ module ``Record Generation Tests`` = -> () - Check.One (config, roundTrip) + Check.One(config, roundTrip) // Section A. Simple Record schemata @@ -107,76 +107,76 @@ module ``Record Generation Tests`` = [] let ``Generate correct schema for S Record`` () = - let rt = RecordTemplate.Define<``S Record``> () + let rt = RecordTemplate.Define<``S Record``>() checkRecord rt "A1" ScalarAttributeType.S None [] let ``Generate correct schema for N Record`` () = - let rt = RecordTemplate.Define<``N Record``> () + let rt = RecordTemplate.Define<``N Record``>() checkRecord rt "A1" ScalarAttributeType.N None [] let ``Generate correct schema for B Record`` () = - let rt = RecordTemplate.Define<``B Record``> () + let rt = RecordTemplate.Define<``B Record``>() checkRecord rt "A1" ScalarAttributeType.B None [] let ``Generate correct schema for SN Record`` () = - let rt = RecordTemplate.Define<``SN Record``> () + let rt = RecordTemplate.Define<``SN Record``>() checkRecord rt "A1" ScalarAttributeType.S (Some { AttributeName = "B1"; KeyType = ScalarAttributeType.N }) [] let ``Generate correct schema for NB Record`` () = - let rt = RecordTemplate.Define<``NB Record``> () + let rt = RecordTemplate.Define<``NB Record``>() checkRecord rt "A1" ScalarAttributeType.N (Some { AttributeName = "B1"; KeyType = ScalarAttributeType.B }) [] let ``Generate correct schema for BS Record`` () = - let rt = RecordTemplate.Define<``BS Record``> () + let rt = RecordTemplate.Define<``BS Record``>() checkRecord rt "A1" ScalarAttributeType.B (Some { AttributeName = "B1"; KeyType = ScalarAttributeType.S }) [] let ``Generate correct schema for NS Constant HashKey Record`` () = - let rt = RecordTemplate.Define<``NS Constant HashKey Record``> () + let rt = RecordTemplate.Define<``NS Constant HashKey Record``>() checkRecord rt "HashKey" ScalarAttributeType.N (Some { AttributeName = "B1"; KeyType = ScalarAttributeType.S }) [] let ``Generate correct schema for BS Constant RangeKey Record`` () = - let rt = RecordTemplate.Define<``BS Constant RangeKey Record``> () + let rt = RecordTemplate.Define<``BS Constant RangeKey Record``>() checkRecord rt "A1" ScalarAttributeType.B (Some { AttributeName = "RangeKey"; KeyType = ScalarAttributeType.S }) [] let ``Generate correct schema for SS String representation Record`` () = - let rt = RecordTemplate.Define<``SS Record``> () - let rt' = RecordTemplate.Define<``SS String Representation Record``> () + let rt = RecordTemplate.Define<``SS Record``>() + let rt' = RecordTemplate.Define<``SS String Representation Record``>() test <@ rt.PrimaryKey = rt'.PrimaryKey @> [] let ``Generate correct schema for Custom HashKey Name Record`` () = - let rt = RecordTemplate.Define<``Custom HashKey Name Record``> () + let rt = RecordTemplate.Define<``Custom HashKey Name Record``>() checkRecord rt "CustomHashKeyName" ScalarAttributeType.S None [] - let ``Attribute value roundtrip for S Record`` () = Test.RoundTrip<``S Record``> () + let ``Attribute value roundtrip for S Record`` () = Test.RoundTrip<``S Record``>() [] - let ``Attribute value roundtrip for N Record`` () = Test.RoundTrip<``N Record``> () + let ``Attribute value roundtrip for N Record`` () = Test.RoundTrip<``N Record``>() [] - let ``Attribute value roundtrip for B Record`` () = Test.RoundTrip<``B Record``> () + let ``Attribute value roundtrip for B Record`` () = Test.RoundTrip<``B Record``>() [] - let ``Attribute value roundtrip for SN Record`` () = Test.RoundTrip<``SN Record``> () + let ``Attribute value roundtrip for SN Record`` () = Test.RoundTrip<``SN Record``>() [] - let ``Attribute value roundtrip for NB Record`` () = Test.RoundTrip<``NB Record``> () + let ``Attribute value roundtrip for NB Record`` () = Test.RoundTrip<``NB Record``>() [] - let ``Attribute value roundtrip for BS Record`` () = Test.RoundTrip<``BS Record``> () + let ``Attribute value roundtrip for BS Record`` () = Test.RoundTrip<``BS Record``>() [] - let ``Attribute value roundtrip for NS constant HashKey Record`` () = Test.RoundTrip<``NS Constant HashKey Record``> () + let ``Attribute value roundtrip for NS constant HashKey Record`` () = Test.RoundTrip<``NS Constant HashKey Record``>() // Section B. Complex Record schemata @@ -263,16 +263,16 @@ module ``Record Generation Tests`` = [] - let ``Roundtrip complex record A`` () = Test.RoundTrip<``Complex Record A``> () + let ``Roundtrip complex record A`` () = Test.RoundTrip<``Complex Record A``>() [] - let ``Roundtrip complex record B`` () = Test.RoundTrip<``Complex Record B``> () + let ``Roundtrip complex record B`` () = Test.RoundTrip<``Complex Record B``>() [] - let ``Roundtrip complex record C`` () = Test.RoundTrip<``Complex Record C``> (tolerateInequality = true) + let ``Roundtrip complex record C`` () = Test.RoundTrip<``Complex Record C``>(tolerateInequality = true) [] - let ``Roundtrip complex record D`` () = Test.RoundTrip<``Complex Record D``> (tolerateInequality = true) + let ``Roundtrip complex record D`` () = Test.RoundTrip<``Complex Record D``>(tolerateInequality = true) // Section C: test errors @@ -281,7 +281,7 @@ module ``Record Generation Tests`` = [] let ``Record lacking key attributes should fail`` () = - fun () -> RecordTemplate.Define<``Record lacking key attributes``> () + fun () -> RecordTemplate.Define<``Record lacking key attributes``>() |> shouldFailwith<_, ArgumentException> @@ -292,7 +292,7 @@ module ``Record Generation Tests`` = [] let ``Record lacking hashkey attribute should fail`` () = - fun () -> RecordTemplate.Define<``Record lacking hashkey attribute``> () + fun () -> RecordTemplate.Define<``Record lacking hashkey attribute``>() |> shouldFailwith<_, ArgumentException> @@ -305,7 +305,7 @@ module ``Record Generation Tests`` = [] let ``Record containing unsupported attribute type should fail`` () = - fun () -> RecordTemplate.Define<``Record lacking hashkey attribute``> () + fun () -> RecordTemplate.Define<``Record lacking hashkey attribute``>() |> shouldFailwith<_, ArgumentException> type ``Record containing key field of unsupported type`` = @@ -314,7 +314,7 @@ module ``Record Generation Tests`` = [] let ``Record containing key field of unsupported type should fail`` () = - fun () -> RecordTemplate.Define<``Record containing key field of unsupported type``> () + fun () -> RecordTemplate.Define<``Record containing key field of unsupported type``>() |> shouldFailwith<_, ArgumentException> @@ -326,7 +326,7 @@ module ``Record Generation Tests`` = [] let ``Record containing multiple HashKey attributes should fail`` () = - fun () -> RecordTemplate.Define<``Record containing multiple HashKey attributes``> () + fun () -> RecordTemplate.Define<``Record containing multiple HashKey attributes``>() |> shouldFailwith<_, ArgumentException> [] @@ -334,7 +334,7 @@ module ``Record Generation Tests`` = [] let ``Record containing costant HashKey attribute lacking RangeKey attribute should fail`` () = - fun () -> RecordTemplate.Define<``Record containing costant HashKey attribute lacking RangeKey attribute``> () + fun () -> RecordTemplate.Define<``Record containing costant HashKey attribute lacking RangeKey attribute``>() |> shouldFailwith<_, ArgumentException> [] @@ -346,7 +346,7 @@ module ``Record Generation Tests`` = [] let ``Record containing costant HashKey attribute with HashKey attribute should fail`` () = - fun () -> RecordTemplate.Define<``Record containing costant HashKey attribute with HashKey attribute``> () + fun () -> RecordTemplate.Define<``Record containing costant HashKey attribute with HashKey attribute``>() |> shouldFailwith<_, ArgumentException> @@ -423,7 +423,7 @@ module ``Record Generation Tests`` = [] let ``GSI Simple HashKey`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ 1 = template.GlobalSecondaryIndices.Length @> let gsi = template.GlobalSecondaryIndices[0] test <@ None = gsi.RangeKey @> @@ -438,7 +438,7 @@ module ``Record Generation Tests`` = [] let ``GSI Simple Combined key`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ 1 = template.GlobalSecondaryIndices.Length @> let gsi = template.GlobalSecondaryIndices[0] @@ -458,17 +458,17 @@ module ``Record Generation Tests`` = [] let ``GSI should fail if supplying RangeKey only`` () = - fun () -> RecordTemplate.Define () + fun () -> RecordTemplate.Define() |> shouldFailwith<_, ArgumentException> [] let ``GSI should fail if invalid key type`` () = - fun () -> RecordTemplate.Define () + fun () -> RecordTemplate.Define() |> shouldFailwith<_, ArgumentException> [] let ``Sparse GSI`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ 1 = template.GlobalSecondaryIndices.Length @> let gsi = template.GlobalSecondaryIndices[0] test <@ None = gsi.RangeKey @> @@ -482,12 +482,12 @@ module ``Record Generation Tests`` = [] let ``GSI should fail with option primary hash key`` () = - fun () -> RecordTemplate.Define () + fun () -> RecordTemplate.Define() |> shouldFailwith<_, ArgumentException> [] let ``Inverse GSI should be permitted`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ @@ -505,7 +505,7 @@ module ``Record Generation Tests`` = [] let ``Shared GSI Range Keys should be permitted`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ @@ -547,7 +547,7 @@ module ``Record Generation Tests`` = [] let ``LSI Simple`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ 1 = template.LocalSecondaryIndices.Length @> let lsi = template.LocalSecondaryIndices[0] test <@ template.PrimaryKey.HashKey = lsi.HashKey @> @@ -561,12 +561,12 @@ module ``Record Generation Tests`` = [] let ``LSI should fail if no RangeKey is specified`` () = - fun () -> RecordTemplate.Define () + fun () -> RecordTemplate.Define() |> shouldFailwith<_, ArgumentException> [] let ``Sparse LSI`` () = - let template = RecordTemplate.Define () + let template = RecordTemplate.Define() test <@ 1 = template.LocalSecondaryIndices.Length @> let lsi = template.LocalSecondaryIndices[0] test <@ template.PrimaryKey.HashKey = lsi.HashKey @> @@ -581,16 +581,16 @@ module ``Record Generation Tests`` = [] let ``DateTimeOffset pickler encoding should preserve ordering`` () = let config = { Config.QuickThrowOnFailure with MaxTest = 1000 } - let pickler = DateTimeOffsetPickler () + let pickler = DateTimeOffsetPickler() let inline cmp x y = sign (compare x y) - Check.One (config, (fun (d1: DateTimeOffset, d2: DateTimeOffset) -> cmp d1 d2 = cmp (pickler.UnParse d1) (pickler.UnParse d2))) + Check.One(config, (fun (d1: DateTimeOffset, d2: DateTimeOffset) -> cmp d1 d2 = cmp (pickler.UnParse d1) (pickler.UnParse d2))) [] let ``DateTimeOffset pickler encoding should preserve offsets`` () = let config = { Config.QuickThrowOnFailure with MaxTest = 1000 } - let pickler = DateTimeOffsetPickler () + let pickler = DateTimeOffsetPickler() - Check.One ( + Check.One( config, fun (d: DateTimeOffset) -> let d' = pickler.UnParse d |> pickler.Parse diff --git a/tests/FSharp.AWS.DynamoDB.Tests/SimpleTableOperationTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/SimpleTableOperationTests.fs index f941546..9dc1d8e 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/SimpleTableOperationTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/SimpleTableOperationTests.fs @@ -42,7 +42,7 @@ module SimpleTableTypes = type ``Simple Table Operation Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = { HashKey = guid () @@ -52,18 +52,18 @@ type ``Simple Table Operation Tests``(fixture: TableFixture) = Map = seq { for _ in 0L .. rand () % 5L -> "K" + guid (), rand () } |> Map.ofSeq - Unions = [ Choice1Of3 (guid ()); Choice2Of3 (rand ()); Choice3Of3 (Guid.NewGuid().ToByteArray ()) ] } + Unions = [ Choice1Of3(guid ()); Choice2Of3(rand ()); Choice3Of3(Guid.NewGuid().ToByteArray()) ] } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Convert to compatible table`` () = - let table' = table.WithRecordType () + let table' = table.WithRecordType() test <@ table.PrimaryKey = table'.PrimaryKey @> [] let ``Convert to compatible table 2`` () = - let table' = table.WithRecordType () + let table' = table.WithRecordType() test <@ table.PrimaryKey = table'.PrimaryKey @> [] @@ -101,9 +101,9 @@ type ``Simple Table Operation Tests``(fixture: TableFixture) = let unprocessed = table.BatchPutItems values let values' = - table.BatchGetItems ( + table.BatchGetItems( values - |> Seq.map (fun r -> TableKey.Combined (r.HashKey, r.RangeKey)) + |> Seq.map (fun r -> TableKey.Combined(r.HashKey, r.RangeKey)) ) |> Set.ofArray @@ -116,17 +116,17 @@ type ``Simple Table Operation Tests``(fixture: TableFixture) = table.BatchPutItems values |> ignore let unprocessed = - table.BatchDeleteItems ( + table.BatchDeleteItems( values - |> Seq.map (fun r -> TableKey.Combined (r.HashKey, r.RangeKey)) + |> Seq.map (fun r -> TableKey.Combined(r.HashKey, r.RangeKey)) ) test <@ Array.isEmpty unprocessed @> let values' = - table.BatchGetItems ( + table.BatchGetItems( values - |> Seq.map (fun r -> TableKey.Combined (r.HashKey, r.RangeKey)) + |> Seq.map (fun r -> TableKey.Combined(r.HashKey, r.RangeKey)) ) test <@ Array.isEmpty values' @> @@ -155,7 +155,7 @@ type ``Simple Table Operation Tests``(fixture: TableFixture) = type ``TransactWriteItems tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = { HashKey = guid () @@ -165,9 +165,9 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = Map = seq { for _ in 0L .. rand () % 5L -> "K" + guid (), rand () } |> Map.ofSeq - Unions = [ Choice1Of3 (guid ()); Choice2Of3 (rand ()); Choice3Of3 (Guid.NewGuid().ToByteArray ()) ] } + Unions = [ Choice1Of3(guid ()); Choice2Of3(rand ()); Choice3Of3(Guid.NewGuid().ToByteArray()) ] } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() let compile = table.Template.PrecomputeConditionalExpr let compileUpdate (e: Quotations.Expr SimpleRecord>) = table.Template.PrecomputeUpdateExpr e let doesntExistCondition = compile <@ fun t -> NOT_EXISTS t.Value @> @@ -178,11 +178,11 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = async { let item = mkItem () - let requests = [ TransactWrite.Put (item, Some doesntExistCondition) ] + let requests = [ TransactWrite.Put(item, Some doesntExistCondition) ] do! table.TransactWriteItems requests - let! itemFound = table.ContainsKeyAsync (table.Template.ExtractKey item) + let! itemFound = table.ContainsKeyAsync(table.Template.ExtractKey item) true =! itemFound } @@ -191,7 +191,7 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = async { let item = mkItem () - let requests = [ TransactWrite.Put (item, Some existsCondition) ] + let requests = [ TransactWrite.Put(item, Some existsCondition) ] let mutable failed = false @@ -202,7 +202,7 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = true =! failed - let! itemFound = table.ContainsKeyAsync (table.Template.ExtractKey item) + let! itemFound = table.ContainsKeyAsync(table.Template.ExtractKey item) false =! itemFound } @@ -214,10 +214,10 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = let requests = [ if shouldFail then - TransactWrite.Check (key, doesntExistCondition) + TransactWrite.Check(key, doesntExistCondition) else - TransactWrite.Check (key, existsCondition) - TransactWrite.Put (item2, None) ] + TransactWrite.Check(key, existsCondition) + TransactWrite.Put(item2, None) ] let mutable failed = false @@ -228,7 +228,7 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = failed =! shouldFail - let! item2Found = table.ContainsKeyAsync (table.Template.ExtractKey item2) + let! item2Found = table.ContainsKeyAsync(table.Template.ExtractKey item2) failed =! not item2Found } @@ -239,14 +239,14 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = let! key = table.PutItemAsync item let requests = - [ TransactWrite.Update (key, Some existsCondition, compileUpdate <@ fun t -> { t with Value = 42 } @>) - TransactWrite.Put (item2, None) - TransactWrite.Put (item3, Some doesntExistCondition) - TransactWrite.Delete (table.Template.ExtractKey item4, Some doesntExistCondition) - TransactWrite.Delete (table.Template.ExtractKey item5, None) - TransactWrite.Check (table.Template.ExtractKey item6, (if shouldFail then existsCondition else doesntExistCondition)) - TransactWrite.Update ( - TableKey.Combined (item7.HashKey, item7.RangeKey), + [ TransactWrite.Update(key, Some existsCondition, compileUpdate <@ fun t -> { t with Value = 42 } @>) + TransactWrite.Put(item2, None) + TransactWrite.Put(item3, Some doesntExistCondition) + TransactWrite.Delete(table.Template.ExtractKey item4, Some doesntExistCondition) + TransactWrite.Delete(table.Template.ExtractKey item5, None) + TransactWrite.Check(table.Template.ExtractKey item6, (if shouldFail then existsCondition else doesntExistCondition)) + TransactWrite.Update( + TableKey.Combined(item7.HashKey, item7.RangeKey), None, compileUpdate <@ fun t -> { t with Tuple = (42, 42) } @> ) ] @@ -268,13 +268,13 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = <> (maybeItem |> Option.contains { item with Value = 42 }) @> - let! maybeItem2 = table.TryGetItemAsync (table.Template.ExtractKey item2) + let! maybeItem2 = table.TryGetItemAsync(table.Template.ExtractKey item2) test <@ shouldFail <> (maybeItem2 |> Option.contains item2) @> - let! maybeItem3 = table.TryGetItemAsync (table.Template.ExtractKey item3) + let! maybeItem3 = table.TryGetItemAsync(table.Template.ExtractKey item3) test <@ shouldFail <> (maybeItem3 |> Option.contains item3) @> - let! maybeItem7 = table.TryGetItemAsync (table.Template.ExtractKey item7) + let! maybeItem7 = table.TryGetItemAsync(table.Template.ExtractKey item7) test <@ @@ -287,12 +287,12 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = let shouldBeRejectedWithArgumentOutOfRangeException requests = async { - let! e = Async.Catch (table.TransactWriteItems requests) + let! e = Async.Catch(table.TransactWriteItems requests) test <@ match e with - | Choice1Of2 () -> false + | Choice1Of2() -> false | Choice2Of2 e -> e :? ArgumentOutOfRangeException @> } @@ -302,6 +302,6 @@ type ``TransactWriteItems tests``(fixture: TableFixture) = [] let ``Over 100 writes are rejected with AORE`` () = - shouldBeRejectedWithArgumentOutOfRangeException [ for _x in 1..101 -> TransactWrite.Put (mkItem (), None) ] + shouldBeRejectedWithArgumentOutOfRangeException [ for _x in 1..101 -> TransactWrite.Put(mkItem (), None) ] interface IClassFixture diff --git a/tests/FSharp.AWS.DynamoDB.Tests/SparseGSITests.fs b/tests/FSharp.AWS.DynamoDB.Tests/SparseGSITests.fs index 3a81625..f87df5e 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/SparseGSITests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/SparseGSITests.fs @@ -22,14 +22,14 @@ module SparseGSITests = type ``Sparse GSI Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() let mkItem () = { HashKey = guid () RangeKey = guid () - SecondaryHashKey = if rand () % 2L = 0L then Some (guid ()) else None } + SecondaryHashKey = if rand () % 2L = 0L then Some(guid ()) else None } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``GSI Put Operation`` () = @@ -40,20 +40,20 @@ type ``Sparse GSI Tests``(fixture: TableFixture) = [] let ``GSI Query Operation (match)`` () = - let value = { mkItem () with SecondaryHashKey = Some (guid ()) } + let value = { mkItem () with SecondaryHashKey = Some(guid ()) } let _key = table.PutItem value - let res = table.Query (keyCondition = <@ fun (r: GsiRecord) -> r.SecondaryHashKey = value.SecondaryHashKey @>) + let res = table.Query(keyCondition = <@ fun (r: GsiRecord) -> r.SecondaryHashKey = value.SecondaryHashKey @>) test <@ 1 = Array.length res @> [] let ``GSI Query Operation (missing)`` () = - let value = { mkItem () with SecondaryHashKey = Some (guid ()) } + let value = { mkItem () with SecondaryHashKey = Some(guid ()) } let key = table.PutItem value - table.UpdateItem (key, <@ fun r -> { r with SecondaryHashKey = None } @>) + table.UpdateItem(key, <@ fun r -> { r with SecondaryHashKey = None } @>) |> ignore - let res = table.Query (keyCondition = <@ fun (r: GsiRecord) -> r.SecondaryHashKey = value.SecondaryHashKey @>) + let res = table.Query(keyCondition = <@ fun (r: GsiRecord) -> r.SecondaryHashKey = value.SecondaryHashKey @>) test <@ Array.isEmpty res @> interface IClassFixture diff --git a/tests/FSharp.AWS.DynamoDB.Tests/UpdateExpressionTests.fs b/tests/FSharp.AWS.DynamoDB.Tests/UpdateExpressionTests.fs index aa1ebba..35ee781 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/UpdateExpressionTests.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/UpdateExpressionTests.fs @@ -71,8 +71,8 @@ module UpdateExprTypes = type ``Update Expression Tests``(fixture: TableFixture) = - let rand = let r = Random.Shared in fun () -> int64 <| r.Next () - let bytes () = Guid.NewGuid().ToByteArray () + let rand = let r = Random.Shared in fun () -> int64 <| r.Next() + let bytes () = Guid.NewGuid().ToByteArray() let mkItem () = { HashKey = guid () @@ -80,13 +80,13 @@ type ``Update Expression Tests``(fixture: TableFixture) = String = guid () Value = rand () Tuple = rand (), rand () - TimeSpan = TimeSpan.FromTicks (rand ()) + TimeSpan = TimeSpan.FromTicks(rand ()) DateTimeOffset = DateTimeOffset.Now - Guid = Guid.NewGuid () + Guid = Guid.NewGuid() Bool = false - Optional = Some (guid ()) + Optional = Some(guid ()) Ref = ref (guid ()) - Bytes = Guid.NewGuid().ToByteArray () + Bytes = Guid.NewGuid().ToByteArray() Nested = { NV = guid (); NE = enum (int (rand ()) % 3) } NestedList = [ { NV = guid (); NE = enum (int (rand ()) % 3) } ] Map = @@ -96,17 +96,17 @@ type ``Update Expression Tests``(fixture: TableFixture) = StringSet = seq { for _ in 0L .. rand () % 5L -> guid () } |> Set.ofSeq ByteSet = seq { for _ in 0L .. rand () % 5L -> bytes () } |> Set.ofSeq List = [ for _ in 0L .. rand () % 5L -> rand () ] - Union = if rand () % 2L = 0L then UA (rand ()) else UB (guid ()) - Unions = [ for _ in 0L .. rand () % 5L -> if rand () % 2L = 0L then UA (rand ()) else UB (guid ()) ] } + Union = if rand () % 2L = 0L then UA(rand ()) else UB(guid ()) + Unions = [ for _ in 0L .. rand () % 5L -> if rand () % 2L = 0L then UA(rand ()) else UB(guid ()) ] } - let table = fixture.CreateEmpty () + let table = fixture.CreateEmpty() [] let ``Attempt to update HashKey`` () = let item = mkItem () let key = table.PutItem item - fun () -> table.UpdateItem (key, <@ fun (r: R) -> { r with HashKey = guid () } @>) + fun () -> table.UpdateItem(key, <@ fun (r: R) -> { r with HashKey = guid () } @>) |> shouldFailwith<_, ArgumentException> [] @@ -114,14 +114,14 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = mkItem () let key = table.PutItem item - fun () -> table.UpdateItem (key, <@ fun (r: R) -> { r with RangeKey = guid () } @>) + fun () -> table.UpdateItem(key, <@ fun (r: R) -> { r with RangeKey = guid () } @>) |> shouldFailwith<_, ArgumentException> [] let ``Returning old value`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>, returnLatest = false) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>, returnLatest = false) test <@ item = item' @> [] @@ -129,80 +129,80 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = mkItem () let key = table.PutItem item let nv = DateTimeOffset.Now + TimeSpan.FromDays 366. - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with DateTimeOffset = nv } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with DateTimeOffset = nv } @>) test <@ nv = item'.DateTimeOffset @> [] let ``Simple update TimeSpan`` () = let item = mkItem () let key = table.PutItem item - let ts = TimeSpan.FromTicks (rand ()) - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with TimeSpan = ts } @>) + let ts = TimeSpan.FromTicks(rand ()) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with TimeSpan = ts } @>) test <@ ts = item'.TimeSpan @> [] let ``Simple update Guid`` () = let item = mkItem () let key = table.PutItem item - let g = Guid.NewGuid () - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Guid = g } @>) + let g = Guid.NewGuid() + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Guid = g } @>) test <@ g = item'.Guid @> [] let ``Simple increment update`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>) test <@ item.Value + 1L = item'.Value @> [] let ``Simple decrement update`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Value = r.Value - 10L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Value = r.Value - 10L } @>) test <@ item.Value - 10L = item'.Value @> [] let ``Update using nested record values`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with String = r.Nested.NV } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with String = r.Nested.NV } @>) test <@ item.Nested.NV = item'.String @> [] let ``Update using nested union values`` () = let item = mkItem () let key = table.PutItem item - let u = UB (guid ()) - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Union = u } @>) + let u = UB(guid ()) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Union = u } @>) test <@ u = item'.Union @> [] let ``Update using nested list`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Nested = r.NestedList[0] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Nested = r.NestedList[0] } @>) test <@ item.NestedList[0] = item'.Nested @> [] let ``Update using tuple values`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Value = fst r.Tuple + 1L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Value = fst r.Tuple + 1L } @>) test <@ fst item.Tuple + 1L = item'.Value @> [] let ``Update optional field to None`` () = - let item = { mkItem () with Optional = Some (guid ()) } + let item = { mkItem () with Optional = Some(guid ()) } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Optional = None } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Optional = None } @>) test <@ None = item'.Optional @> [] let ``Update optional field to Some`` () = let item = { mkItem () with Optional = None } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Optional = Some (guid ()) } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Optional = Some(guid ()) } @>) test <@ None <> item'.Optional @> [] @@ -210,133 +210,133 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with List = [ 1L ] } let key = table.PutItem item let nv = [ for _ in 1..10 -> rand () ] - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with List = nv } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with List = nv } @>) test <@ nv = item'.List @> [] let ``Update list field to empty`` () = let item = { mkItem () with List = [ 1L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with List = [] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with List = [] } @>) test <@ 0 = item'.List.Length @> [] let ``Update list with concatenation`` () = let item = { mkItem () with List = [ 1L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with List = r.List @ r.List } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with List = r.List @ r.List } @>) test <@ item.List @ item.List = item'.List @> [] let ``Update list with consing`` () = let item = { mkItem () with List = [ 2L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with List = 1L :: r.List } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with List = 1L :: r.List } @>) test <@ [ 1L; 2L ] = item'.List @> [] let ``Update using defaultArg combinator (Some)`` () = - let item = { mkItem () with Optional = Some (guid ()) } + let item = { mkItem () with Optional = Some(guid ()) } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with String = defaultArg r.Optional "" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with String = defaultArg r.Optional "" } @>) test <@ item.Optional = Some item'.String @> [] let ``Update using defaultArg combinator (None)`` () = let item = { mkItem () with Optional = None } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with String = defaultArg r.Optional "" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with String = defaultArg r.Optional "" } @>) test <@ "" = item'.String @> [] let ``Update int set with add element`` () = let item = { mkItem () with IntSet = set [ 1L; 2L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with IntSet = r.IntSet |> Set.add 3L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with IntSet = r.IntSet |> Set.add 3L } @>) test <@ item'.IntSet.Contains 3L @> [] let ``Update int set with remove element`` () = let item = { mkItem () with IntSet = set [ 1L; 2L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with IntSet = r.IntSet |> Set.remove 2L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with IntSet = r.IntSet |> Set.remove 2L } @>) test <@ not (item'.IntSet.Contains 2L) @> [] let ``Update int set with append set`` () = let item = { mkItem () with IntSet = Set.empty } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with IntSet = r.IntSet + set [ 3L ] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with IntSet = r.IntSet + set [ 3L ] } @>) test <@ item'.IntSet.Contains 3L @> [] let ``Update int set with remove set`` () = let item = { mkItem () with IntSet = set [ 1L; 2L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with IntSet = r.IntSet - set [ 1L; 2L; 3L ] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with IntSet = r.IntSet - set [ 1L; 2L; 3L ] } @>) test <@ 0 = item'.IntSet.Count @> [] let ``Update string set with add element`` () = let item = { mkItem () with StringSet = set [ "1"; "2" ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with StringSet = r.StringSet |> Set.add "3" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with StringSet = r.StringSet |> Set.add "3" } @>) test <@ item'.StringSet.Contains "3" @> [] let ``Update string set with remove element`` () = let item = { mkItem () with StringSet = set [ "1"; "2" ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with StringSet = r.StringSet |> Set.remove "2" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with StringSet = r.StringSet |> Set.remove "2" } @>) test <@ not (item'.StringSet.Contains "2") @> [] let ``Update string set with append set`` () = let item = { mkItem () with StringSet = Set.empty } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with StringSet = r.StringSet + set [ "3" ] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with StringSet = r.StringSet + set [ "3" ] } @>) test <@ item'.StringSet.Contains "3" @> [] let ``Update byte set with append set`` () = let item = { mkItem () with ByteSet = Set.empty } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with ByteSet = r.ByteSet + set [ [| 42uy |] ] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with ByteSet = r.ByteSet + set [ [| 42uy |] ] } @>) test <@ item'.ByteSet.Contains [| 42uy |] @> [] let ``Update string set with remove set`` () = let item = { mkItem () with StringSet = set [ "1"; "2" ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with StringSet = r.StringSet - set [ "1"; "2"; "3" ] } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with StringSet = r.StringSet - set [ "1"; "2"; "3" ] } @>) test <@ 0 = item'.StringSet.Count @> [] let ``Update map with add element`` () = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Map = r.Map |> Map.add "C" 3L } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Map = r.Map |> Map.add "C" 3L } @>) test <@ Some 3L = item'.Map.TryFind "C" @> [] let ``Update map with remove element`` () = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Map = r.Map |> Map.remove "B" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Map = r.Map |> Map.remove "B" } @>) test <@ not (item'.Map.ContainsKey "B") @> [] let ``Update map with remove element on existing`` () = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> { r with Map = r.Map |> Map.remove "C" } @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> { r with Map = r.Map |> Map.remove "C" } @>) test <@ 2 = item'.Map.Count @> [] let ``Update map entry with Item access`` () = let item = { mkItem () with Map = Map.ofList [ ("A", 1L) ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun (r: R) -> SET r.Map["A"] 2L @>) + let item' = table.UpdateItem(key, <@ fun (r: R) -> SET r.Map["A"] 2L @>) test <@ 2L = item'.Map["A"] @> [] @@ -344,7 +344,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 1L) ] } let key = table.PutItem item let uop = table.Template.PrecomputeUpdateExpr <@ fun i v (r: R) -> SET r.Map[i] v @> - let item' = table.UpdateItem (key, uop "A" 2L) + let item' = table.UpdateItem(key, uop "A" 2L) test <@ 2L = item'.Map["A"] @> [] @@ -352,7 +352,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 1L) ] } let _key = table.PutItem item let cond = table.Template.PrecomputeConditionalExpr <@ fun i r -> r.Map |> Map.containsKey i @> - let _item' = table.PutItem (item, cond "A") + let _item' = table.PutItem(item, cond "A") () [] @@ -361,7 +361,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let key = table.PutItem item let item' = - table.UpdateItem (key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>, precondition = <@ fun r -> r.Value = item.Value @>) + table.UpdateItem(key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>, precondition = <@ fun r -> r.Value = item.Value @>) test <@ item.Value + 1L = item'.Value @> @@ -371,7 +371,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let key = table.PutItem item fun () -> - table.UpdateItem ( + table.UpdateItem( key, <@ fun (r: R) -> { r with Value = r.Value + 1L } @>, precondition = <@ fun r -> r.Value = item.Value + 1L @> @@ -388,7 +388,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let key = table.PutItem item let item' = - table.UpdateItem ( + table.UpdateItem( key, <@ fun r -> @@ -402,10 +402,10 @@ type ``Update Expression Tests``(fixture: TableFixture) = [] let ``SET a union attribute`` () = - let item = { mkItem () with Unions = [ UB (guid ()) ] } + let item = { mkItem () with Unions = [ UB(guid ()) ] } let key = table.PutItem item - let u = UA (rand ()) - let item' = table.UpdateItem (key, <@ fun r -> SET r.Unions[0] u @>) + let u = UA(rand ()) + let item' = table.UpdateItem(key, <@ fun r -> SET r.Unions[0] u @>) test <@ 1 = item'.Unions.Length @> test <@ u = item'.Unions[0] @> @@ -414,7 +414,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let ``REMOVE an attribute`` () = let item = { mkItem () with NestedList = [ { NV = "foo"; NE = Enum.A } ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun r -> REMOVE r.NestedList[0] @>) + let item' = table.UpdateItem(key, <@ fun r -> REMOVE r.NestedList[0] @>) test <@ 0 = item'.NestedList.Length @> @@ -422,7 +422,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let ``ADD to set`` () = let item = mkItem () let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun r -> ADD r.IntSet [ 42L ] @>) + let item' = table.UpdateItem(key, <@ fun r -> ADD r.IntSet [ 42L ] @>) test <@ item'.IntSet.Contains 42L @> @@ -430,7 +430,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let ``DELETE from set`` () = let item = { mkItem () with IntSet = set [ 1L; 42L ] } let key = table.PutItem item - let item' = table.UpdateItem (key, <@ fun r -> DELETE r.IntSet [ 42L ] @>) + let item' = table.UpdateItem(key, <@ fun r -> DELETE r.IntSet [ 42L ] @>) test <@ not (item'.IntSet.Contains 42L) @> test <@ 1 = item'.IntSet.Count @> @@ -440,7 +440,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = mkItem () let key = table.PutItem item - fun () -> table.UpdateItem (key, <@ fun r -> SET r.NestedList[0].NV "foo" &&& REMOVE r.NestedList @>) + fun () -> table.UpdateItem(key, <@ fun r -> SET r.NestedList[0].NV "foo" &&& REMOVE r.NestedList @>) |> shouldFailwith<_, ArgumentException> @@ -454,7 +454,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let cond = table.Template.PrecomputeUpdateExpr <@ fun v1 v2 r -> { r with Value = v1; String = v2 } @> let v1 = rand () let v2 = guid () - let result = table.UpdateItem (key, cond v1 v2) + let result = table.UpdateItem(key, cond v1 v2) test <@ v1 = result.Value @> test <@ v2 = result.String @> @@ -465,7 +465,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let cond = table.Template.PrecomputeUpdateExpr <@ fun v1 v2 r -> SET r.Value v1 &&& ADD r.IntSet v2 @> let v1 = rand () let v2 = [ for _ in 1..10 -> rand () ] - let result = table.UpdateItem (key, cond v1 v2) + let result = table.UpdateItem(key, cond v1 v2) test <@ v1 = result.Value @> for v in v2 do @@ -473,10 +473,10 @@ type ``Update Expression Tests``(fixture: TableFixture) = [] let ``Parametric Updater with optional argument`` () = - let item = { mkItem () with Optional = Some (guid ()) } + let item = { mkItem () with Optional = Some(guid ()) } let key = table.PutItem item let cond = table.Template.PrecomputeUpdateExpr <@ fun opt (r: R) -> { r with Optional = opt } @> - let result = table.UpdateItem (key, cond None) + let result = table.UpdateItem(key, cond None) test <@ None = result.Optional @> [] @@ -485,7 +485,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let key = table.PutItem item let values = [ for _ in 1..10 -> rand () ] let cond = table.Template.PrecomputeUpdateExpr <@ fun vs r -> SET r.List vs &&& ADD r.IntSet vs @> - let result = table.UpdateItem (key, cond values) + let result = table.UpdateItem(key, cond values) test <@ values = result.List @> for v in values do @@ -506,7 +506,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item let cond = table.Template.PrecomputeUpdateExpr <@ fun v (r: UpdateExprRecord) -> { r with Map = r.Map |> Map.add "C" v } @> - let result = table.UpdateItem (key, cond 3L) + let result = table.UpdateItem(key, cond 3L) test <@ 3 = result.Map.Count @> [] @@ -514,7 +514,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item let cond = table.Template.PrecomputeUpdateExpr <@ fun k v (r: UpdateExprRecord) -> { r with Map = r.Map |> Map.add k v } @> - let result = table.UpdateItem (key, cond "C" 3L) + let result = table.UpdateItem(key, cond "C" 3L) test <@ 3 = result.Map.Count @> [] @@ -522,7 +522,7 @@ type ``Update Expression Tests``(fixture: TableFixture) = let item = { mkItem () with Map = Map.ofList [ ("A", 1L); ("B", 2L) ] } let key = table.PutItem item let cond = table.Template.PrecomputeUpdateExpr <@ fun k (r: UpdateExprRecord) -> { r with Map = r.Map |> Map.remove k } @> - let result = table.UpdateItem (key, cond "A") + let result = table.UpdateItem(key, cond "A") test <@ 1 = result.Map.Count @> interface IClassFixture diff --git a/tests/FSharp.AWS.DynamoDB.Tests/Utils.fs b/tests/FSharp.AWS.DynamoDB.Tests/Utils.fs index 64a27fa..a10d59a 100644 --- a/tests/FSharp.AWS.DynamoDB.Tests/Utils.fs +++ b/tests/FSharp.AWS.DynamoDB.Tests/Utils.fs @@ -15,17 +15,17 @@ open Amazon.Runtime [] module Utils = - let guid () = Guid.NewGuid().ToString ("N") + let guid () = Guid.NewGuid().ToString("N") let getRandomTableName () = sprintf "fsdynamodb-%s" <| guid () let shouldFailwith<'T, 'Exn when 'Exn :> exn> (f: unit -> 'T) = <@ f () |> ignore @> |> raises<'Exn> let getDynamoDBAccount () = - let credentials = BasicAWSCredentials ("Fake", "Fake") - let config = AmazonDynamoDBConfig (ServiceURL = "http://localhost:8000") + let credentials = BasicAWSCredentials("Fake", "Fake") + let config = AmazonDynamoDBConfig(ServiceURL = "http://localhost:8000") - new AmazonDynamoDBClient (credentials, config) :> IAmazonDynamoDB + new AmazonDynamoDBClient(credentials, config) :> IAmazonDynamoDB type FsCheckGenerators = @@ -33,7 +33,7 @@ module Utils = Arb.generate |> Gen.map (function | None -> null - | Some bs -> new MemoryStream (bs)) + | Some bs -> new MemoryStream(bs)) |> Arb.fromGen @@ -46,9 +46,9 @@ module Utils = member _.TableName = tableName member _.CreateEmpty<'TRecord>() = - let throughput = ProvisionedThroughput (readCapacityUnits = 10L, writeCapacityUnits = 10L) - Scripting.TableContext.Initialize<'TRecord> (client, tableName, Throughput.Provisioned throughput) + let throughput = ProvisionedThroughput(readCapacityUnits = 10L, writeCapacityUnits = 10L) + Scripting.TableContext.Initialize<'TRecord>(client, tableName, Throughput.Provisioned throughput) interface IAsyncLifetime with member _.InitializeAsync() = System.Threading.Tasks.Task.CompletedTask - member _.DisposeAsync() = client.DeleteTableAsync (tableName) + member _.DisposeAsync() = client.DeleteTableAsync(tableName)