-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathUtils.fs
814 lines (725 loc) · 37.3 KB
/
Utils.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
namespace FSharp.Data.Sql.Common
open System
open System.Collections.Generic
#if NETSTANDARD
module StandardExtensions =
type System.Data.DataTable with
member x.AsEnumerable() =
seq {
for r in x.Rows do
yield r
}
#endif
module Utilities =
open System.IO
open System.Collections.Concurrent
open FSharp.Data.Sql
#if !NETSTANDARD
type TempFile(path:string) =
member val Path = path with get
interface IDisposable with
member this.Dispose() = File.Delete(path)
let tempFile(extension : string) =
let filename =
let tempF = Path.GetTempFileName()
let tempF' = Path.ChangeExtension(tempF, extension)
if tempF <> tempF' then
File.Delete tempF
tempF'
new TempFile(filename)
#endif
let inline internal resolveTuplePropertyName (name:string) (tupleIndex:string ResizeArray) =
// eg "Item1" -> tupleIndex.[0]
let itemid =
if name.Length > 4 then
#if NETSTANDARD21
match Int32.TryParse (name.AsSpan 4) with
#else
match Int32.TryParse (name.Substring 4) with
#endif
| (true, n) when name.StartsWith("Item", StringComparison.InvariantCultureIgnoreCase) -> n
| _ -> Int32.MaxValue
else Int32.MaxValue
if itemid = Int32.MaxValue && tupleIndex.Contains(name) && name <> "" then name //already resolved
elif tupleIndex.Count < itemid then name
else tupleIndex.[itemid - 1]
let inline quoteWhiteSpace (str:String) =
(if str.Contains(" ") then sprintf "\"%s\"" str else str)
let uniqueName()=
let dict = ConcurrentDictionary<string, int>()
(fun name ->
match dict.AddOrUpdate(name,(fun n -> 0),(fun n v -> v + 1)) with
| 0 -> name
| count -> name + "_" + (string count)
)
let parseAggregates fieldNotat fieldNotationAlias query =
let rec parseAggregates' fieldNotation fieldNotationAlias query (selectColumns:string list) =
match query with
| [] -> selectColumns |> Seq.distinct |> Seq.toList
| (opAlias, (aggCol:SqlColumnType))::tail ->
let parsed =
((fieldNotation opAlias aggCol) + " as " + fieldNotationAlias(opAlias, aggCol)) :: selectColumns
parseAggregates' fieldNotation fieldNotationAlias tail parsed
parseAggregates' fieldNotat fieldNotationAlias query []
// https://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null
let getType typename =
Type.GetType typename
let rec internal convertTypes (itm:obj) (returnType:Type) =
if (returnType.Name.StartsWith("Option") || returnType.Name.StartsWith("FSharpOption")) && returnType.GenericTypeArguments.Length = 1 then
if isNull itm then None |> box
else
match convertTypes itm (returnType.GenericTypeArguments.[0]) with
| :? String as t -> Option.Some t |> box
| :? Int32 as t -> Option.Some t |> box
| :? Decimal as t -> Option.Some t |> box
| :? Int64 as t -> Option.Some t |> box
| :? Single as t -> Option.Some t |> box
| :? UInt32 as t -> Option.Some t |> box
| :? Double as t -> Option.Some t |> box
| :? UInt64 as t -> Option.Some t |> box
| :? Int16 as t -> Option.Some t |> box
| :? UInt16 as t -> Option.Some t |> box
| :? DateTime as t -> Option.Some t |> box
| :? Boolean as t -> Option.Some t |> box
| :? Byte as t -> Option.Some t |> box
| :? SByte as t -> Option.Some t |> box
| :? Char as t -> Option.Some t |> box
| :? DateTimeOffset as t -> Option.Some t |> box
| :? TimeSpan as t -> Option.Some t |> box
| t -> Option.Some t |> box
elif (returnType.Name.StartsWith("ValueOption") || returnType.Name.StartsWith("FSharpValueOption")) && returnType.GenericTypeArguments.Length = 1 then
if isNull itm then ValueNone |> box
else
match convertTypes itm (returnType.GenericTypeArguments.[0]) with
| :? String as t -> ValueOption.Some t |> box
| :? Int32 as t -> ValueOption.Some t |> box
| :? Decimal as t -> ValueOption.Some t |> box
| :? Int64 as t -> ValueOption.Some t |> box
| :? Single as t -> ValueOption.Some t |> box
| :? UInt32 as t -> ValueOption.Some t |> box
| :? Double as t -> ValueOption.Some t |> box
| :? UInt64 as t -> ValueOption.Some t |> box
| :? Int16 as t -> ValueOption.Some t |> box
| :? UInt16 as t -> ValueOption.Some t |> box
| :? DateTime as t -> ValueOption.Some t |> box
| :? Boolean as t -> ValueOption.Some t |> box
| :? Byte as t -> ValueOption.Some t |> box
| :? SByte as t -> ValueOption.Some t |> box
| :? Char as t -> ValueOption.Some t |> box
| :? DateTimeOffset as t -> ValueOption.Some t |> box
| :? TimeSpan as t -> ValueOption.Some t |> box
| t -> ValueOption.Some t |> box
elif returnType.Name.StartsWith("Nullable") && returnType.GenericTypeArguments.Length = 1 then
if isNull itm then null |> box
else convertTypes itm (returnType.GenericTypeArguments.[0])
else
match itm, returnType with
| :? string as s, t when Type.(=) (t, typeof<String>) -> s |> box
| :? string as s, t when Type.(=) (t, typeof<Int32>) && Int32.TryParse s |> fst -> Int32.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Decimal>) && Decimal.TryParse s |> fst -> Decimal.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Int64>) && Int64.TryParse s |> fst -> Int64.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Single>) && Single.TryParse s |> fst -> Single.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<UInt32>) && UInt32.TryParse s |> fst -> UInt32.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Double>) && Double.TryParse s |> fst -> Double.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<UInt64>) && UInt64.TryParse s |> fst -> UInt64.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Int16>) && Int16.TryParse s |> fst -> Int16.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<UInt16>) && UInt16.TryParse s |> fst -> UInt16.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<DateTime>) && DateTime.TryParse s |> fst -> DateTime.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Boolean>) && Boolean.TryParse s |> fst -> Boolean.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Byte>) && Byte.TryParse s |> fst -> Byte.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<SByte>) && SByte.TryParse s |> fst -> SByte.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<Char>) && Char.TryParse s |> fst -> Char.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<DateTimeOffset>) && DateTimeOffset.TryParse s |> fst -> DateTimeOffset.Parse s |> box
| :? string as s, t when Type.(=) (t, typeof<TimeSpan>) && TimeSpan.TryParse s |> fst -> TimeSpan.Parse s |> box
| _ ->
if Type.(=) (returnType, typeof<String>) then Convert.ToString itm |> box
elif Type.(=) (returnType, typeof<Int32>) then Convert.ToInt32 itm |> box
elif Type.(=) (returnType, typeof<Decimal>) then Convert.ToDecimal itm |> box
elif Type.(=) (returnType, typeof<Int64>) then Convert.ToInt64 itm |> box
elif Type.(=) (returnType, typeof<Single>) then Convert.ToSingle itm |> box
elif Type.(=) (returnType, typeof<UInt32>) then Convert.ToUInt32 itm |> box
elif Type.(=) (returnType, typeof<Double>) then Convert.ToDouble itm |> box
elif Type.(=) (returnType, typeof<UInt64>) then Convert.ToUInt64 itm |> box
elif Type.(=) (returnType, typeof<Int16>) then Convert.ToInt16 itm |> box
elif Type.(=) (returnType, typeof<UInt16>) then Convert.ToUInt16 itm |> box
elif Type.(=) (returnType, typeof<DateTime>) then Convert.ToDateTime itm |> box
elif Type.(=) (returnType, typeof<Boolean>) then Convert.ToBoolean itm |> box
elif Type.(=) (returnType, typeof<Byte>) then Convert.ToByte itm |> box
elif Type.(=) (returnType, typeof<SByte>) then Convert.ToSByte itm |> box
elif Type.(=) (returnType, typeof<Char>) then Convert.ToChar itm |> box
else itm |> box
/// Standard SQL. Provider spesific overloads can be done before this.
let genericFieldNotation (recursionBase:SqlColumnType->string) (colSprint:string->string) = function
| SqlColumnType.KeyColumn col -> colSprint col
| SqlColumnType.CanonicalOperation(op,key) ->
let column = recursionBase key
match op with // These are very standard:
| ToUpper -> sprintf "UPPER(%s)" column
| ToLower -> sprintf "LOWER(%s)" column
| Abs -> sprintf "ABS(%s)" column
| Ceil -> sprintf "CEILING(%s)" column
| Floor -> sprintf "FLOOR(%s)" column
| Round -> sprintf "ROUND(%s)" column
| RoundDecimals x -> sprintf "ROUND(%s,%d)" column x
| BasicMath(o, c) when o = "/" -> sprintf "(%s %s (1.0*%O))" column o c
| BasicMathLeft(o, c) when o = "/" -> sprintf "(%O %s (1.0*%s))" c o column
| BasicMath(o, c) -> sprintf "(%s %s %O)" column o c
| BasicMathLeft(o, c) -> sprintf "(%O %s %s)" c o column
| Sqrt -> sprintf "SQRT(%s)" column
| Sin -> sprintf "SIN(%s)" column
| Cos -> sprintf "COS(%s)" column
| Tan -> sprintf "TAN(%s)" column
| ASin -> sprintf "ASIN(%s)" column
| ACos -> sprintf "ACOS(%s)" column
| ATan -> sprintf "ATAN(%s)" column
| _ -> failwithf "Not yet supported: %O %s" op (key.ToString())
| GroupColumn (AvgOp key, KeyColumn _) -> sprintf "AVG(%s)" (colSprint key)
| GroupColumn (MinOp key, KeyColumn _) -> sprintf "MIN(%s)" (colSprint key)
| GroupColumn (MaxOp key, KeyColumn _) -> sprintf "MAX(%s)" (colSprint key)
| GroupColumn (SumOp key, KeyColumn _) -> sprintf "SUM(%s)" (colSprint key)
| GroupColumn (CountDistOp key, KeyColumn _) -> sprintf "COUNT(DISTINCT %s)" (colSprint key)
| GroupColumn (StdDevOp key, KeyColumn _) -> sprintf "STDDEV(%s)" (colSprint key)
| GroupColumn (VarianceOp key, KeyColumn _) -> sprintf "VAR(%s)" (colSprint key)
| GroupColumn (KeyOp key,_) -> colSprint key
| GroupColumn (CountOp _,_) -> sprintf "COUNT(1)"
// Nested aggregate operators, e.g. select(x*y) |> Seq.sum
| GroupColumn (CountDistOp _,x) -> sprintf "COUNT(DISTINCT %s)" (recursionBase x)
| GroupColumn (AvgOp _,x) -> sprintf "AVG(%s)" (recursionBase x)
| GroupColumn (MinOp _,x) -> sprintf "MIN(%s)" (recursionBase x)
| GroupColumn (MaxOp _,x) -> sprintf "MAX(%s)" (recursionBase x)
| GroupColumn (SumOp _,x) -> sprintf "SUM(%s)" (recursionBase x)
| GroupColumn (StdDevOp _,x) -> sprintf "STDDEV(%s)" (recursionBase x)
| GroupColumn (VarianceOp _,x) -> sprintf "VARIANCE(%s)" (recursionBase x)
let rec genericAliasNotation aliasSprint = function
| SqlColumnType.KeyColumn col -> aliasSprint col
| SqlColumnType.CanonicalOperation(op,col) ->
let subItm = genericAliasNotation aliasSprint col
aliasSprint (sprintf "%s_%O" (op.ToString().Replace(" ", "_")) subItm)
| GroupColumn (KeyOp key,_) -> aliasSprint key
| GroupColumn (CountOp key,_) -> aliasSprint (sprintf "COUNT_%s" key)
| GroupColumn (CountDistOp key,_) -> aliasSprint (sprintf "COUNTD_%s" key)
| GroupColumn (AvgOp key,_) -> aliasSprint (sprintf "AVG_%s" key)
| GroupColumn (MinOp key,_) -> aliasSprint (sprintf "MIN_%s" key)
| GroupColumn (MaxOp key,_) -> aliasSprint (sprintf "MAX_%s" key)
| GroupColumn (SumOp key,_) -> aliasSprint (sprintf "SUM_%s" key)
| GroupColumn (StdDevOp key,_) -> aliasSprint (sprintf "STDDEV_%s" key)
| GroupColumn (VarianceOp key,_) -> aliasSprint (sprintf "VAR_%s" key)
let rec getBaseColumnName x =
match x with
| KeyColumn k -> k
| CanonicalOperation(op, c) -> $"c{abs(op.GetHashCode())}c{getBaseColumnName c}"
| GroupColumn(op, c) -> $"g{abs(op.GetHashCode())}g{getBaseColumnName c}"
let fieldConstant (value:obj) =
//Can we create named parameters in ODBC, and how?
match value with
| :? Guid
| :? DateTime
| :? String -> sprintf "'%s'" (value.ToString().Replace("'", ""))
| _ -> value.ToString()
let inline internal replaceFirst (text:string) (oldValue:string) (newValue:string) =
let position = text.IndexOf oldValue
if position < 0 then
text
else
//String.Concat(text.AsSpan(0, position), newValue.AsSpan(), text.AsSpan(position + oldValue.Length))
// ...would throw error FS0412: A type instantiation involves a byref type. This is not permitted by the rules of Common IL.
text.AsSpan(0, position).ToString() + newValue + text.AsSpan(position + oldValue.Length).ToString()
let internal checkPred alias =
let prefix = "[" + alias + "]."
let prefix2 = alias + "."
let prefix3 = "`" + alias + "`."
let prefix4 = alias + "_"
let prefix5 = alias.ToUpper() + "_"
let prefix6 = "\"" + alias + "\"."
(fun (k:string,v) ->
if k.StartsWith prefix then
let temp = replaceFirst k prefix ""
let temp = temp.AsSpan(1,temp.Length-2)
Some(temp.ToString(),v)
// this case is for PostgreSQL and other vendors that use " as whitespace qualifiers
elif k.StartsWith prefix2 then
let temp = replaceFirst k prefix2 ""
Some(temp,v)
// this case is for MySQL and other vendors that use ` as whitespace qualifiers
elif k.StartsWith prefix3 then
let temp = replaceFirst k prefix3 ""
let temp = temp.AsSpan(1,temp.Length-2)
Some(temp.ToString(),v)
//this case for MSAccess, uses _ as whitespace qualifier
elif k.StartsWith prefix4 then
let temp = replaceFirst k prefix4 ""
Some(temp,v)
//this case for Firebird version<=2.1, all uppercase
elif k.StartsWith prefix5 then
let temp = replaceFirst k prefix5 ""
Some(temp,v)
//this case is for DuckDb
elif k.StartsWith prefix6 then
let temp = replaceFirst k prefix6 ""
let temp = temp.AsSpan(1,temp.Length-2)
Some(temp.ToString(),v)
elif not(String.IsNullOrEmpty(k)) then // this is for dynamic alias columns: [a].[City] as City
Some(k,v)
else None)
module ConfigHelpers =
open System
open System.IO
#if !NETSTANDARD
open System.Configuration
let internal getConStringFromConfig isRuntime root (connectionStringName : string) =
let entryAssembly =
match Reflection.Assembly.GetEntryAssembly() with null -> None | x -> Some x
let root, paths =
if isRuntime && entryAssembly.IsSome
then entryAssembly.Value.Location, [
entryAssembly.Value.GetName().Name + ".exe.config";
Path.Combine(root, entryAssembly.Value.GetName().Name + ".exe.config")
]
else root, []
let configFilePath =
paths @ [
Path.Combine(root, "app.config")
Path.Combine(root, "web.config")
"app.config"
"web.config"
]|> List.tryFind File.Exists
match configFilePath with
| Some(configFilePath) ->
use tempFile = Utilities.tempFile "config"
File.Copy(configFilePath, tempFile.Path)
let fileMap = new ExeConfigurationFileMap(ExeConfigFilename = tempFile.Path)
let config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
match config.ConnectionStrings.ConnectionStrings.[connectionStringName] with
| null -> ""
| a -> a.ConnectionString
| None -> ""
#endif
let cachedConStrings = System.Collections.Concurrent.ConcurrentDictionary<string, string>()
let tryGetConnectionString isRuntime root (connectionStringName:string) (connectionString:string) =
#if !NETSTANDARD
if String.IsNullOrWhiteSpace(connectionString)
then
match isRuntime with
| false -> getConStringFromConfig isRuntime root connectionStringName
| _ -> cachedConStrings.GetOrAdd(connectionStringName, fun name ->
let fromFile = getConStringFromConfig isRuntime root connectionStringName
fromFile)
else
#endif
connectionString
module SchemaProjections =
let inline internal forall predicate (source : ReadOnlySpan<_>) =
let mutable state = true
let mutable e = source.GetEnumerator()
while state && e.MoveNext() do
state <- predicate e.Current
state
//Creatviely taken from FSharp.Data (https://github.com/fsharp/FSharp.Data/blob/master/src/CommonRuntime/NameUtils.fs)
[<return: Struct>]
let private (|LetterDigit|_|) = fun c -> if Char.IsLetterOrDigit c then ValueSome c else ValueNone
[<return: Struct>]
let private (|UpperC|_|) = fun c -> if Char.IsUpper c || Char.IsDigit c then ValueSome c else ValueNone
[<return: Struct>]
let private (|Upper|_|) = function ValueSome c when Char.IsUpper c || Char.IsDigit c -> ValueSome c | _ -> ValueNone
[<return: Struct>]
let private (|Lower|_|) = function ValueSome c when Char.IsLower c || Char.IsDigit c -> ValueSome c | _ -> ValueNone
// --------------------------------------------------------------------------------------
/// Turns a given non-empty string into a nice 'PascalCase' identifier
let nicePascalName (s:string) =
let le = s.Length
if le = 1 then string (Char.ToUpperInvariant(s.[0])) else
// Starting to parse a new segment
let rec restart i =
if i >= le then Seq.empty
else
match s.[i] with
| LetterDigit _ & UpperC _ -> upperStart i (i + 1)
| LetterDigit _ -> consume i false (i + 1)
| _ -> restart (i + 1)
// Parsed first upper case letter, continue either all lower or all upper
and upperStart from i =
match if i >= le then ValueNone else ValueSome s.[i] with
| Upper _ -> consume from true (i + 1)
| Lower _ -> consume from false (i + 1)
| _ ->
seq {
yield struct(from, i)
yield! restart (i + 1)
}
// Consume are letters of the same kind (either all lower or all upper)
and consume from takeUpper i =
match takeUpper, if i >= le then ValueNone else ValueSome s.[i] with
| false, Lower _ -> consume from takeUpper (i + 1)
| true, Upper _ -> consume from takeUpper (i + 1)
| true, Lower _ ->
seq {
yield struct(from, (i - 1))
yield! restart (i - 1)
}
| _ ->
seq {
yield struct(from, i)
yield! restart i
}
// Split string into segments and turn them to PascalCase
let results = restart 0
seq { for i1, i2 in results do
let sub = s.AsSpan(i1, i2 - i1)
if forall Char.IsLetterOrDigit sub then
(string (Char.ToUpperInvariant sub.[0])) + sub.Slice(1).ToString().ToLowerInvariant() }
|> String.Concat
/// Turns a given non-empty string into a nice 'camelCase' identifier
let niceCamelName (s:string) =
let name = nicePascalName s
if name.Length > 0 then
(string name.[0]).ToLowerInvariant() + name.Substring(1)
else name
/// Add ' until the name is unique
let rec avoidNameClashBy nameExists name =
if nameExists name then avoidNameClashBy nameExists (name + "'")
else name
let buildTableName (tableName:string) =
//Current Name = [SCHEMA].[TABLE_NAME]
if(tableName.Contains("."))
then
let tableName = tableName.Replace("[", "").Replace("]", "")
let startIndex = tableName.IndexOf('.')
nicePascalName (tableName.Substring(startIndex))
else nicePascalName tableName
let buildFieldName (fieldName:string) = nicePascalName fieldName
let buildSprocName (sprocName:string) = nicePascalName sprocName
let buildTableNameWhereFilter columnName (tableNames : string) =
let trim (s:string) = s.Trim()
let names = tableNames.Split([|','|], StringSplitOptions.RemoveEmptyEntries)
|> Seq.map trim
|> Seq.toArray
match names with
| [||] -> ""
| [|name|] -> sprintf "and %s like '%s'" columnName name
| _ -> names |> Array.map (sprintf "%s like '%s'" columnName)
|> String.concat " or "
|> sprintf "and (%s)"
module Reflection =
open System.Reflection
open System.IO
let execAssembly = lazy System.Reflection.Assembly.GetExecutingAssembly()
//let mutable resourceLinkedFiles = Set.empty
let getPlatform (a:Assembly) =
match a with
| null -> ""
| x ->
match x.GetCustomAttributes(typeof<System.Runtime.Versioning.TargetFrameworkAttribute>, false) with
| null -> ""
| itms when itms.Length > 0 -> (itms |> Seq.head :?> System.Runtime.Versioning.TargetFrameworkAttribute).FrameworkName
| _ -> ""
let listResolutionFullPaths (resolutionPathSemicoloned:string) =
if resolutionPathSemicoloned.Contains ";" then
String.concat ";"
(resolutionPathSemicoloned.Split ';'
|> Array.map (fun p -> p.Trim() |> System.IO.Path.GetFullPath))
else
System.IO.Path.GetFullPath (resolutionPathSemicoloned.Trim())
let tryLoadAssembly path =
try
if not (File.Exists path) || path.StartsWith "System.Runtime.WindowsRuntime" then None
else
let loadedAsm = Assembly.LoadFrom(path)
if isNull loadedAsm
then None
else Some(Choice1Of2 loadedAsm)
with e ->
Some(Choice2Of2 e)
let tryLoadAssemblyFrom (resolutionPathSemicoloned:string) (referencedAssemblies:string[]) assemblyNames =
let resolutionPaths =
if resolutionPathSemicoloned.Contains ";" then
resolutionPathSemicoloned.Split ';' |> Array.toList |> List.map(fun p -> p.Trim())
else [ resolutionPathSemicoloned.Trim() ]
let resolutionPaths =
resolutionPaths
|> List.map(fun resolutionPath ->
let p = resolutionPath.Replace('/', System.IO.Path.DirectorySeparatorChar)
if not(File.Exists p) then p else p |> Path.GetDirectoryName
)
let referencedPaths =
referencedAssemblies
|> Array.filter (fun ra -> assemblyNames |> List.exists(fun (a:string) -> ra.Contains(a)))
|> Array.toList
let resolutionPathsFiles =
assemblyNames
|> List.collect (fun asm ->
if List.isEmpty resolutionPaths then
[ asm ]
else
resolutionPaths
|> List.map(fun resolutionPath ->
if String.IsNullOrEmpty resolutionPath
then asm
else Path.Combine(resolutionPath,asm))
)
let ifNotNull (x:Assembly) =
if isNull x then ""
elif String.IsNullOrWhiteSpace x.Location then ""
else x.Location |> Path.GetDirectoryName
//#if NETSTANDARD
// // This would be nice to add myPaths, but Microsoft.Extensions.DependencyModel conflicts in System.Runtime:
// if Microsoft.Extensions.DependencyModel.DependencyContext.Default = null then [] else
// Microsoft.Extensions.DependencyModel.DependencyContext.Default.CompileLibraries
// |> Seq.map(fun lib -> Path.GetDirectoryName(lib.Name)) |> Seq.distinct |> Seq.toList
//#endif
let myPaths =
let dirs =
[__SOURCE_DIRECTORY__;
#if !INTERACITVE
execAssembly.Force() |> ifNotNull;
#endif
Environment.CurrentDirectory;
System.Reflection.Assembly.GetEntryAssembly() |> ifNotNull;]
let dirs =
if List.isEmpty resolutionPaths then
dirs
else
resolutionPaths
|> List.collect(fun resolutionPath ->
if not(System.IO.Path.IsPathRooted resolutionPath) then
dirs @ (dirs |> List.map(fun d -> Path.Combine(d, resolutionPath)))
else
dirs)
dirs |> Seq.distinct |> Seq.filter(fun x -> not(String.IsNullOrEmpty x) && Directory.Exists x) |> Seq.toList
let currentPaths =
myPaths |> List.map(fun myPath ->
assemblyNames |> List.map (fun asm -> System.IO.Path.Combine(myPath,asm)))
|> Seq.concat |> Seq.toList
let allPaths =
(assemblyNames @ resolutionPathsFiles @ referencedPaths @ currentPaths)
|> Seq.distinct |> Seq.toList
let tryLoadFromMemory () =
let assemblies =
let loadedAssemblies =
AppDomain.CurrentDomain.GetAssemblies()
dict [
for assembly in loadedAssemblies ->
assembly.ManifestModule.ScopeName, assembly
]
assemblyNames
|> List.tryPick (fun name ->
match assemblies.TryGetValue name with
| true, aname -> Some aname
| false, _ -> None
)
let result =
allPaths
|> List.tryPick (fun p ->
match tryLoadAssembly p with
| Some(Choice1Of2 ass) -> Some ass
| _ -> None
)
|> function
| Some assembly -> Some assembly
| None -> tryLoadFromMemory ()
// Some providers have additional references to other libraries.
// https://stackoverflow.com/questions/18942832/how-can-i-dynamically-reference-an-assembly-that-looks-for-another-assembly
// and runtime binding-redirect: http://blog.slaks.net/2013-12-25/redirecting-assembly-loads-at-runtime/
let loadHandler (args:ResolveEventArgs) (loadFunc:string->bool->Assembly) =
let fileName = args.Name.Split(',').[0] + ".dll"
try
let tryLoad = loadFunc fileName false
tryLoad
with
| _ ->
let extraPathDirs = (resolutionPaths @ myPaths)
let loaded =
extraPathDirs |> List.tryPick(fun dllPath ->
let assemblyPath = Path.Combine(dllPath,fileName)
if File.Exists assemblyPath then
let tryLoad = loadFunc assemblyPath true
if isNull tryLoad then None else
Some(tryLoad)
else None)
match loaded with
| Some x ->
x
| None when not (isNull (Environment.GetEnvironmentVariable "USERPROFILE")) ->
// Final try: nuget cache
try
let currentPlatform = getPlatform(execAssembly.Force()).Split(',').[0]
let c = System.IO.Path.Combine [| Environment.GetEnvironmentVariable("USERPROFILE"); ".nuget"; "packages" |]
if System.IO.Directory.Exists c then
let picked =
System.IO.Directory.GetFiles(c, fileName, SearchOption.AllDirectories)
|> Array.sortByDescending(fun f -> f) // "runtime over lib"
|> Array.tryPick(fun assemblyPath ->
try
let tmpAssembly = Assembly.Load(assemblyPath |> File.ReadAllBytes)
if tmpAssembly.FullName = args.Name then
let loadedPlatform = getPlatform(tmpAssembly)
match currentPlatform, loadedPlatform with
| x, y when (x = "" || y = "" || x = y.Split(',').[0]) ->
// Ok...good to go. (Although, we could match better the target frameworks.)
//let tryLoad = loadFunc assemblyPath true
Some(tmpAssembly)
| _ -> None
else
None
with _ -> None
)
match picked with Some x -> x | None -> null
else null
with
| _ -> null
| None ->
null
let mutable handler = Unchecked.defaultof<ResolveEventHandler>
handler <- // try to avoid StackOverflowException of Assembly.LoadFrom calling handler again
System.ResolveEventHandler (fun _ args ->
let loadfunc (x:string) shouldCatch =
if not (isNull handler) then AppDomain.CurrentDomain.remove_AssemblyResolve handler
let res =
try
if x.StartsWith "System.Runtime.WindowsRuntime" then
// Issue: https://github.com/dotnet/fsharp/pull/9644
null
else
//File.AppendAllText(@"c:\Temp\build.txt", "Binding trial " + args.Name + " to " + x + " " + DateTime.UtcNow.ToString() + "\r\n")
let r = Assembly.LoadFrom x
//if not (isNull r) then
// File.AppendAllText(@"c:\Temp\build.txt", "Binding success " + args.Name + " to " + r.FullName + "\r\n")
r
with e ->
if shouldCatch then
null
else
//if x.EndsWith ".dll" && not (resourceLinkedFiles.Contains x) then
// resourceLinkedFiles <- resourceLinkedFiles.Add(x)
reraise()
if not (isNull handler) then AppDomain.CurrentDomain.add_AssemblyResolve handler
res
loadHandler args loadfunc)
System.AppDomain.CurrentDomain.add_AssemblyResolve handler
match result with
| Some asm -> Choice1Of2 asm
| None ->
let folders =
allPaths
|> Seq.map (Path.GetDirectoryName)
|> Seq.distinct
let errors =
allPaths
|> List.map (fun p ->
match tryLoadAssembly p with
| Some(Choice2Of2 err) when (err :? System.IO.FileNotFoundException) -> None //trivial
| Some(Choice2Of2 err) -> Some err
| _ -> None
) |> List.filter Option.isSome
|> List.map(fun o -> o.Value.GetBaseException().Message)
|> Seq.distinct |> Seq.toList
let paths =
resolutionPaths
|> List.filter(fun resolutionPath -> not(String.IsNullOrEmpty resolutionPath) && not(System.IO.Directory.Exists resolutionPath))
if List.isEmpty paths then
Choice2Of2(folders, errors)
else
let x = "" :: errors
let resPaths = String.concat ";" paths
Choice2Of2(folders, ("resolutionPath directory doesn't exist:" + resPaths::errors))
module Sql =
open System
open System.Data
let private collectfunc(reader:IDataReader) =
[|
for i = 0 to reader.FieldCount - 1 do
let v = reader.GetValue i // if we would like to swallow unknown types errors: try reader.GetValue(i) with | :? System.IO.FileNotFoundException as ex -> box ex
match v with
| null | :? DBNull -> yield (reader.GetName(i),null)
| value -> yield (reader.GetName(i),value)
|]
let dataReaderToArray (reader:IDataReader) =
[|
while reader.Read() do
yield collectfunc reader
|]
let dataReaderToArrayAsync (reader:System.Data.Common.DbDataReader) =
task {
let res = ResizeArray<_>()
while! reader.ReadAsync() do
let e = collectfunc reader
res.Add e
return res |> Seq.toArray
}
let dbUnbox<'a> (v:obj) : 'a =
if Convert.IsDBNull(v) then Unchecked.defaultof<'a> else unbox v
let dbUnboxWithDefault<'a> def (v:obj) : 'a =
if Convert.IsDBNull(v) then def else unbox v
let connect (con:IDbConnection) f =
if con.State <> ConnectionState.Open then con.Open()
let result = f con
con.Close(); result
let connectAsync (con:System.Data.Common.DbConnection) f =
task {
if con.State <> ConnectionState.Open then
do! con.OpenAsync()
let result = f con
con.Close(); result
}
let executeSql createCommand sql (con:IDbConnection) =
use com : IDbCommand = createCommand sql con
com.ExecuteReader()
let executeSqlAsync createCommand sql (con:IDbConnection) =
use com : System.Data.Common.DbCommand = createCommand sql con
com.ExecuteReaderAsync()
let executeSqlAsDataTable createCommand sql con =
use r = executeSql createCommand sql con
let dt = new DataTable()
dt.Load r
dt
let executeSqlAsDataTableAsync createCommand sql con =
task{
use! r = executeSqlAsync createCommand sql con
let dt = new DataTable()
dt.Load r
return dt
}
let ensureOpen (con:IDbConnection) =
if con.State <> ConnectionState.Open
then con.Open()
/// Helper function to run async computation non-parallel style for list of objects.
/// This is needed if async database opreation is executed for a list of entities.
/// DB-connections are not usually supporting parallel SQL-query execution, so even when
/// async thread is available, it can't be used to execute another SQL at the same time.
let evaluateOneByOne asyncFunc entityList =
async {
let! arr =
entityList
|> Seq.map (fun x ->
async { // task { } would start as parallel, async { } is not.
return! asyncFunc x |> Async.AwaitTask
})
|> Async.Sequential
return arr |> Seq.toList
} |> Async.StartImmediateAsTask
module Stubs =
open System.Data
let connection =
{ new IDbConnection with
member __.BeginTransaction() = null
member __.BeginTransaction(il) = null
member __.ChangeDatabase(str) = ()
member __.Close() = ()
member __.ConnectionString with get() = "" and set value = ()
member __.ConnectionTimeout = 0
member __.CreateCommand () = null
member __.Database = ""
member __.Open() = ()
member __.State = ConnectionState.Closed
member __.Dispose() = () }
// Taken from https://github.com/haf/yolo
module Bytes =
open System.IO
open System.Security.Cryptography
let hash (algo : unit -> #HashAlgorithm) (bs : byte[]) =
use ms = new MemoryStream()
ms.Write(bs, 0, bs.Length)
ms.Seek(0L, SeekOrigin.Begin) |> ignore
use sha = algo ()
sha.ComputeHash ms
let sha1 = hash (fun () -> SHA1.Create())
let sha256 = hash (fun () -> SHA256.Create())