-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathSqlDesignTime.fs
More file actions
1586 lines (1421 loc) · 97.1 KB
/
SqlDesignTime.fs
File metadata and controls
1586 lines (1421 loc) · 97.1 KB
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace FSharp.Data.Sql
open System
open System.Data
open System.Reflection
open System.Threading.Tasks
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Quotations
open FSharp.Data.Sql.Transactions
open FSharp.Data.Sql.Schema
open FSharp.Data.Sql.Runtime
open FSharp.Data.Sql.Common
open FSharp.Data.Sql
open ProviderImplementation.ProvidedTypes
type DesignCacheKey =
(struct ( string * // ConnectionString URL
string * // ConnectionString Name
DatabaseProviderTypes * // db vendor
string * // Assembly resolution path for db connectors and custom types
int * // Individuals Amount
NullableColumnType * // Use option types?
string * // Schema owner currently only used for oracle
CaseSensitivityChange * // Should we do ToUpper or ToLower when generating table names?
string * // Table names list (Oracle and MSSQL Only)
string * // Context schema path
OdbcQuoteCharacter * // Quote characters (Odbc only)
SQLiteLibrary * // Use System.Data.SQLite or Mono.Data.SQLite or select automatically (SQLite only)
string * // SSDT Path
string)) //typeName
module DesignTimeCacheSchema =
let schemaMap = System.Collections.Concurrent.ConcurrentDictionary<DesignCacheKey*string, ProvidedTypeDefinition>()
type internal ParameterValue =
| UserProvided of string * string * Type
| Default of Expr
module DesignTimeUtils =
#if COMMON
let [<Literal>] design1 = "FSharp.Data.SqlProvider.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider"
let [<Literal>] design2 = "SQLProvider.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql"
#endif
#if MSSQL
let [<Literal>] design1 = "FSharp.Data.SqlProvider.MsSql.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.MsSql"
let [<Literal>] design2 = "SQLProvider.MsSql.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.MsSql.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.MsSql"
#endif
#if POSTGRESQL
let [<Literal>] design1 = "FSharp.Data.SqlProvider.PostgreSql.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.PostgreSql"
let [<Literal>] design2 = "SQLProvider.PostgreSql.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.PostgreSql.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.PostgreSql"
#endif
#if MYSQL
let [<Literal>] design1 = "FSharp.Data.SqlProvider.MySql.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.MySql"
let [<Literal>] design2 = "SQLProvider.MySql.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.MySql.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.MySql"
#endif
#if MYSQLCONNECTOR
let [<Literal>] design1 = "FSharp.Data.SqlProvider.MySqlConnector.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.MySqlConnector"
let [<Literal>] design2 = "SQLProvider.MySqlConnector.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.MySqlConnector.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.MySqlConnector"
#endif
#if SQLITE
let [<Literal>] design1 = "FSharp.Data.SqlProvider.SQLite.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.SQLite"
let [<Literal>] design2 = "SQLProvider.SQLite.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.SQLite.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.SQLite"
#endif
#if FIREBIRD
let [<Literal>] design1 = "FSharp.Data.SqlProvider.Firebird.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.Firebird"
let [<Literal>] design2 = "SQLProvider.Firebird.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.Firebird.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.Firebird"
#endif
#if ODBC
let [<Literal>] design1 = "FSharp.Data.SqlProvider.Odbc.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.Odbc"
let [<Literal>] design2 = "SQLProvider.Odbc.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.Odbc.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.Odbc"
#endif
#if ORACLE
let [<Literal>] design1 = "FSharp.Data.SqlProvider.Oracle.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.Oracle"
let [<Literal>] design2 = "SQLProvider.Oracle.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.Oracle.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.Oracle"
#endif
#if MSACCESS
let [<Literal>] design1 = "FSharp.Data.SqlProvider.MsAccess.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.MsAccess"
let [<Literal>] design2 = "SQLProvider.MsAccess.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.MsAccess.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.MsAccess"
#endif
#if DUCKDB
let [<Literal>] design1 = "FSharp.Data.SqlProvider.DuckDb.DesignTime"
let [<Literal>] runtime1 = "FSharp.Data.SqlProvider.DuckDb"
let [<Literal>] design2 = "SQLProvider.DuckDb.DesignTime"
let [<Literal>] runtime2 = "SQLProvider.DuckDb.Runtime"
let [<Literal>] FSHARP_DATA_SQL = "FSharp.Data.Sql.DuckDb"
#endif
let mySaveLock = new Object();
let mutable saveInProcess = false
let empty = fun (_:Expr list) -> <@@ () @@>
let getSprocReturnColumns con (prov:ISqlProvider) sprocname (sprocDefinition: CompileTimeSprocDefinition) param =
match con with
| Some con ->
let returnParams = sprocDefinition.ReturnColumns con param
prov.GetSchemaCache().SprocsParams.AddOrUpdate(sprocname, returnParams, fun _ inputParams -> inputParams @ returnParams) |> ignore
returnParams
| None ->
let ok, pars = prov.GetSchemaCache().SprocsParams.TryGetValue sprocname
if ok then
pars |> List.filter (fun p ->
not (p.Name |> String.IsNullOrWhiteSpace)
&& (p.Direction = ParameterDirection.Output
|| p.Direction = ParameterDirection.InputOutput
|| p.Direction = ParameterDirection.ReturnValue))
else []
let transactionOptions = TransactionOptions.Default
let createIndividualsType (con:IDbConnection option) (prov:ISqlProvider) (table:Table) (designTimeDc:Lazy<_>) dbVendor individualsAmount tableTypeDef =
let t = ProvidedTypeDefinition(table.Schema + "." + table.Name + "." + "Individuals", Some typeof<obj>, isErased=true)
let individualsTypes = ResizeArray<_>()
individualsTypes.Add t
t.AddXmlDocDelayed(fun _ -> sprintf "<summary>A sample of %s individuals from the SQL object as supplied in the static parameters</summary>" table.Name)
t.AddMember(ProvidedConstructor([ProvidedParameter("dataContext", typeof<ISqlDataContext>)], empty))
t.AddMembersDelayed( fun _ ->
let columns =
match con with
| Some con -> prov.GetColumns(con,table)
| None -> prov.GetSchemaCache().Columns.TryGetValue(table.FullName) |> function | true,cols -> cols | false, _ -> Map.empty
match prov.GetPrimaryKey table with
| Some pkName ->
let rec (|FixedType|_|) (o:obj) =
match o, o.GetType().IsValueType with
// watch out for normal strings
| :? string, _ -> Some o
// special case for guids as they are not a supported quotable constant in the TP mechanics,
// but we can deal with them as strings.
| :? Guid, _ -> Some (box (o.ToString()))
// Postgres also supports arrays
| :? Array as arr, _ when dbVendor = DatabaseProviderTypes.POSTGRESQL -> Some (box arr)
// value types in general work
| _, true -> Some o
// can't support any other types
| _, _ -> None
let dcDone = designTimeDc.Force()
let entities =
prov.GetSchemaCache().Individuals.GetOrAdd((table.FullName+"_"+pkName), fun k ->
match con with
| Some con ->
use com = prov.CreateCommand(con,prov.GetIndividualsQueryText(table,individualsAmount))
if con.State <> ConnectionState.Open then con.Open()
use reader = com.ExecuteReader()
let ret = (dcDone :> ISqlDataContext).ReadEntities(table.FullName+"_"+pkName, columns, reader)
reader.Close()
if (dbVendor <> DatabaseProviderTypes.MSACCESS) then con.Close()
let mapped = ret |> Array.choose(fun e ->
match (e :> IColumnHolder).GetColumn pkName with
| FixedType pkValue -> Some (pkValue, e.ColumnValues |> dict)
| _ -> None)
mapped
| None -> [||]
)
if Array.isEmpty entities then [] else
// for each column in the entity except the primary key, create a new type that will read ``As Column 1`` etc
// inside that type the individuals will be listed again but with the text for the relevant column as the name
// of the property and the primary key e.g. ``1, Dennis The Squirrel``
let buildFieldName = SchemaProjections.buildFieldName
let propertyMap =
match con with
| Some con -> prov.GetColumns(con,table)
| None -> prov.GetSchemaCache().Columns.TryGetValue(table.FullName) |> function | true,cols -> cols | false, _ -> Map.empty
|> Seq.choose(fun col ->
if col.Key = pkName then None else
let name = table.Schema + "." + table.Name + "." + col.Key + "Individuals"
let ty = ProvidedTypeDefinition(name, Some typeof<obj>, isErased=true)
ty.AddMember(ProvidedConstructor([ProvidedParameter("sqlService", typeof<ISqlDataContext>)], empty))
individualsTypes.Add ty
Some(col.Key,(ty,ProvidedProperty(sprintf "As %s" (buildFieldName col.Key),ty, getterCode = fun args ->
let a0 = args.[0]
<@@ ((%%a0 : obj) :?> ISqlDataContext)@@> ))))
|> Map.ofSeq
let prettyPrint (value : obj) =
let dirtyName =
match value with
| null -> "<null>"
| :? Array as a -> (sprintf "%A" a)
| x -> x.ToString()
dirtyName.Replace("\r", "").Replace("\n", "").Replace("\t", "")
// on the main object create a property for each entity simply using the primary key
let props =
entities
|> Array.choose(fun (pkValue, columnValues) ->
let tableName = table.FullName
let getterCode (args : Expr list) =
let a0 = args.[0]
<@@ ((%%a0 : obj) :?> ISqlDataContext).GetIndividual(tableName, pkValue) @@>
// this next bit is just side effect to populate the "As Column" types for the supported columns
for colName, colValue in columnValues |> Seq.map(fun kvp -> kvp.Key, kvp.Value) do
if colName <> pkName then
let colDefinition, _ = propertyMap.[colName]
colDefinition.AddMemberDelayed(fun() ->
ProvidedProperty( sprintf "%s, %s" (prettyPrint pkValue) (prettyPrint colValue)
, tableTypeDef
, getterCode = getterCode
)
)
// return the primary key property
Some <| ProvidedProperty(prettyPrint pkValue
, tableTypeDef
, getterCode = getterCode
)
)
// Add async method to fetch individual by primary key
let tableName = table.FullName
let pkColumn = columns.[pkName]
let pkType = Utilities.getType pkColumn.TypeMapping.ClrType
let returnType = typedefof<System.Threading.Tasks.Task<_>>.MakeGenericType(tableTypeDef)
let getAsyncMethod =
ProvidedMethod("GetAsync", [ProvidedParameter("id", pkType)], returnType, invokeCode = fun args ->
let a0 = args.[0]
let pkValue = args.[1]
<@@ ((%%a0 : obj) :?> ISqlDataContext).GetIndividualAsync(tableName, %%pkValue) @@>
)
getAsyncMethod.AddXmlDoc(sprintf "<summary>Asynchronously get an individual %s by primary key value</summary>" table.Name)
seq {
yield getAsyncMethod :> MemberInfo
yield! props |> Seq.cast<MemberInfo>
yield! propertyMap |> Map.toSeq |> Seq.map (snd >> snd) |> Seq.cast<MemberInfo>
} |> Seq.toList
propertyMap
|> Map.toSeq
|> Seq.map (snd >> fst)
|> Seq.cast<MemberInfo>
|> Seq.append (props |> Seq.cast<MemberInfo>)
|> Seq.toList
| None -> [])
individualsTypes :> seq<_>
let createColumnProperty (con:IDbConnection option) (prov:ISqlProvider) useOptionTypes key (c:Column) =
let nullable = if c.IsNullable then useOptionTypes else NullableColumnType.NO_OPTION
let ty = Utilities.getType c.TypeMapping.ClrType
let propTy = match nullable with
| NullableColumnType.OPTION -> typedefof<option<_>>.MakeGenericType(ty)
| NullableColumnType.VALUE_OPTION -> typedefof<ValueOption<_>>.MakeGenericType(ty)
| _ -> ty
let name = c.Name
let prop =
ProvidedProperty(
SchemaProjections.buildFieldName(name),propTy,
getterCode =
match nullable with
| NullableColumnType.OPTION ->
(fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("GetColumnOption").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name]))
| NullableColumnType.VALUE_OPTION ->
(fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("GetColumnValueOption").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name]))
| _ ->
(fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("GetColumn").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name]))
,
setterCode =
match nullable with
| NullableColumnType.OPTION ->
(fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("SetColumnOption").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name;args.[1]]))
| NullableColumnType.VALUE_OPTION ->
(fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("SetColumnValueOption").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name;args.[1]]))
| _ ->
(fun (args:Expr list) ->
let meth = typeof<SqlEntity>.GetMethod("SetColumn").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name;args.[1]])))
let nfo = c.TypeInfo
let typeInfo = match nfo with ValueNone -> "" | ValueSome x -> x.ToString()
match con with
| Some con ->
prop.AddXmlDocDelayed(fun () ->
let details = prov.GetColumnDescription(con, key, name).Replace("<","<").Replace(">",">")
let separator = if (String.IsNullOrWhiteSpace typeInfo) || (String.IsNullOrWhiteSpace details) then "" else "/"
sprintf "<summary>%s %s %s</summary>" (String.concat ": " [|name; details|]) separator typeInfo)
| None ->
prop.AddXmlDocDelayed(fun () -> sprintf "<summary>Offline mode. %s</summary>" typeInfo)
()
prop
let generateSprocMethod (container:ProvidedTypeDefinition) (con:IDbConnection option) (prov:ISqlProvider) (sproc:CompileTimeSprocDefinition) =
let sprocname = SchemaProjections.buildSprocName(sproc.Name.DbName)
|> SchemaProjections.avoidNameClashBy (container.GetMember >> Array.isEmpty >> not)
let rt = ProvidedTypeDefinition(sprocname, Some typeof<obj>, isErased=true)
let resultType = ProvidedTypeDefinition("Result", Some typeof<obj>, isErased=true)
resultType.AddMember(ProvidedConstructor([ProvidedParameter("sqlDataContext", typeof<ISqlDataContext>)], empty))
rt.AddMember resultType
container.AddMember(rt)
resultType.AddMembersDelayed(fun () ->
let sprocParameters =
match con with
| None ->
match prov.GetSchemaCache().SprocsParams.TryGetValue sprocname with
| true, x -> x
| false, _ -> []
| Some con ->
(lazy
Sql.ensureOpen con
let ps = sproc.Params con
prov.GetSchemaCache().SprocsParams.AddOrUpdate(sprocname, ps, fun _ _ -> ps) |> ignore
ps).Value
let parameters =
sprocParameters
|> List.filter (fun p -> p.Direction = ParameterDirection.Input || p.Direction = ParameterDirection.InputOutput)
|> List.map(fun p -> ProvidedParameter(p.Name,Utilities.getType p.TypeMapping.ClrType))
let retCols = getSprocReturnColumns con prov sprocname sproc sprocParameters |> List.toArray
let runtimeSproc = {Name = sproc.Name; Params = sprocParameters} : RunTimeSprocDefinition
let returnType =
match retCols.Length with
| 0 -> typeof<Unit>
| _ ->
let rt = ProvidedTypeDefinition("SprocResult",Some typeof<SqlEntity>, isErased=true)
rt.AddMember(ProvidedConstructor([], empty))
retCols
|> Array.iter(fun col ->
let name = col.Name
let ty = Utilities.getType col.TypeMapping.ClrType
let ty =
if isNull ty then
Utilities.getType (col.TypeMapping.ClrType+",FSharp.Data.SqlProvider.Common")
else ty
let prop =
ProvidedProperty(
name, ty,
getterCode = (fun (args:Expr list) ->
let meth = typeof<IColumnHolder>.GetMethod("GetColumn").MakeGenericMethod([|ty|])
Expr.Call(args.[0],meth,[Expr.Value name])),
setterCode = (fun (args:Expr list) ->
let meth = typeof<SqlEntity>.GetMethod("SetColumn").MakeGenericMethod([|typeof<obj>|])
Expr.Call(args.[0],meth,[Expr.Value name;Expr.Coerce(args.[1], typeof<obj>)])))
rt.AddMember prop)
resultType.AddMember(rt)
rt :> Type
let retColsExpr =
QuotationHelpers.arrayExpr retCols |> snd
let isUnit, asyncRet =
if Type.(=)(returnType, typeof<unit>) then
true, typeof<Task>
else
false, typedefof<Task<_>>.MakeGenericType([| returnType |])
[ProvidedMethod("Invoke", parameters, returnType, invokeCode = QuotationHelpers.quoteRecord runtimeSproc (fun args var ->
let a0 = args.[0]
let tail = args.Tail
<@@ (((%%a0 : obj):?>ISqlDataContext)).CallSproc(%%var, %%retColsExpr, %%Expr.NewArray(typeof<obj>,List.map(fun e -> Expr.Coerce(e,typeof<obj>)) tail)) @@>));
ProvidedMethod("InvokeAsync", parameters, asyncRet, invokeCode =
if isUnit then
QuotationHelpers.quoteRecord runtimeSproc (fun args var ->
let a0 = args.[0]
let tail = args.Tail
<@@ task {
let! r =
(((%%a0 : obj):?>ISqlDataContext)).CallSprocAsync(%%var, %%retColsExpr, %%Expr.NewArray(typeof<obj>,List.map(fun e -> Expr.Coerce(e,typeof<obj>)) tail))
return ()
} :> Task @@>
)
else
QuotationHelpers.quoteRecord runtimeSproc (fun args var ->
let a0 = args.[0]
let tail = args.Tail
<@@ (((%%a0 : obj):?>ISqlDataContext)).CallSprocAsync(%%var, %%retColsExpr, %%Expr.NewArray(typeof<obj>,List.map(fun e -> Expr.Coerce(e,typeof<obj>)) tail)) @@>
)
)]
)
let niceUniqueSprocName =
SchemaProjections.buildSprocName(sproc.Name.ProcName)
|> SchemaProjections.avoidNameClashBy (container.GetProperty >> (<>) null)
let p = ProvidedProperty(niceUniqueSprocName, resultType, getterCode = (fun args ->
let a0 = args.[0]
<@@ ((%%a0 : obj) :?>ISqlDataContext) @@>) )
let dbName = sproc.Name.DbName
p.AddXmlDocDelayed(fun _ -> sprintf "<summary>%s</summary>" dbName)
p
let rec walkSproc con (prov:ISqlProvider) (path:string list) (parent:ProvidedTypeDefinition option) (createdTypes:Map<string list,ProvidedTypeDefinition>) (sproc:Sproc) =
match sproc with
| Root(typeName, next) ->
let path = (path @ [typeName])
match createdTypes.TryFind path with
| Some(typ) ->
walkSproc con prov path (Some typ) createdTypes next
| None ->
let typ = ProvidedTypeDefinition(typeName, Some typeof<obj>, isErased=true)
typ.AddMember(ProvidedConstructor([ProvidedParameter("sqlDataContext", typeof<ISqlDataContext>)], empty))
walkSproc con prov path (Some typ) (createdTypes.Add(path, typ)) next
| Package(typeName, packageDefn) ->
match parent with
| Some(parent) ->
let path = (path @ [typeName])
let typ = ProvidedTypeDefinition(typeName, Some typeof<obj>, isErased=true)
parent.AddMember(typ)
parent.AddMember(ProvidedProperty(SchemaProjections.nicePascalName typeName, typ, getterCode = fun args ->
let a0 = args.[0]
<@@ ((%%a0 : obj) :?> ISqlDataContext) @@>))
typ.AddMember(ProvidedConstructor([ProvidedParameter("sqlDataContext", typeof<ISqlDataContext>)], empty))
match con with
| Some co ->
typ.AddMembersDelayed(fun () ->
(lazy
Sql.ensureOpen co
let p = (packageDefn.Sprocs co)
prov.GetSchemaCache().Packages.AddRange p
p |> List.map (generateSprocMethod typ con prov)).Value)
| None ->
typ.AddMembersDelayed(fun () ->
prov.GetSchemaCache().Packages |> Seq.toList |> List.map (generateSprocMethod typ con prov))
createdTypes.Add(path, typ)
| _ -> failwithf "Could not generate package path type undefined root or previous type"
| Sproc(sproc) ->
match parent with
| Some(parent) ->
match con with
| Some co ->
parent.AddMemberDelayed(fun () ->
(lazy
Sql.ensureOpen co
generateSprocMethod parent con prov sproc
).Value)
createdTypes
| None ->
parent.AddMemberDelayed(fun () -> generateSprocMethod parent con prov sproc); createdTypes
| _ -> failwithf "Could not generate sproc undefined root or previous type"
| Empty -> createdTypes
let rec generateTypeTree con (prov:ISqlProvider) (createdTypes:Map<string list, ProvidedTypeDefinition>) (sprocs:Sproc list) =
match sprocs with
| [] ->
Map.filter (fun (k:string list) _ -> match k with [_] -> true | _ -> false) createdTypes
|> Map.toSeq
|> Seq.map snd
| sproc::rest -> generateTypeTree con prov (walkSproc con prov [] None createdTypes sproc) rest
let getOrAddSchema (args:DesignCacheKey) (name:string) =
DesignTimeCacheSchema.schemaMap.GetOrAdd((args,name), fun (a,nme) ->
let pt = ProvidedTypeDefinition(nme + "Schema", Some typeof<obj>, isErased=true)
pt)
let createDesignTimeCommands (prov:ISqlProvider) contextSchemaPath recreate (invalidate: _ -> Unit)=
let designTimeCommandsContainer = ProvidedTypeDefinition("DesignTimeCommands", Some typeof<obj>, isErased=true)
let designTime = ProvidedProperty("Design Time Commands", designTimeCommandsContainer, getterCode = empty)
designTime.AddXmlDocDelayed(fun () -> "Developer's design time commands to TypeProvider.")
let saveResponse = ProvidedTypeDefinition("SaveContextResponse", Some typeof<obj>, isErased=true)
saveResponse.AddMember(ProvidedConstructor([], empty))
saveResponse.AddMembersDelayed(fun () ->
if not saveInProcess then
let result =
if not(String.IsNullOrEmpty contextSchemaPath) then
try
lock mySaveLock (fun() ->
saveInProcess <- true
prov.GetSchemaCache().Save contextSchemaPath
saveInProcess <- false
"Saved " + contextSchemaPath + " at " + DateTime.Now.ToString("hh:mm:ss")
)
with
| e -> "Save failed: " + e.Message
else "ContextSchemaPath is not defined"
[ ProvidedProperty(result,typeof<unit>, getterCode = empty) :> MemberInfo ]
else []
)
let m = ProvidedProperty("SaveContextSchema", (saveResponse :> Type), getterCode = empty)
let mOld = ProvidedMethod("SaveContextSchema", [], (saveResponse :> Type), invokeCode = empty)
m.AddXmlDocComputed(fun () ->
if String.IsNullOrEmpty contextSchemaPath then "ContextSchemaPath static parameter has to be defined to use this function."
else "Schema location: " + contextSchemaPath + ". Write dot after SaveContextSchema to save the schema at design time."
)
let expirationMessage = "Expired, moved under: .``Design Time Commands``"
mOld.AddXmlDocComputed(fun () -> expirationMessage)
mOld.AddObsoleteAttribute expirationMessage
// ClearDatabaseSchemaCache only in online-mode
if String.IsNullOrEmpty contextSchemaPath then
let invalidateActionResponse = ProvidedTypeDefinition("InvalidateResponse", Some typeof<obj>, isErased=true)
invalidateActionResponse.AddMember(ProvidedConstructor([], empty))
invalidateActionResponse.AddMembersDelayed(fun () ->
if not saveInProcess then
let result =
lock mySaveLock (fun() ->
saveInProcess <- true
let schemacache = prov.GetSchemaCache()
schemacache.PrimaryKeys.Clear()
schemacache.Tables.Clear()
schemacache.Columns.Clear()
schemacache.Relationships.Clear()
schemacache.Sprocs.Clear()
schemacache.SprocsParams.Clear()
schemacache.Packages.Clear()
schemacache.Individuals.Clear()
DesignTimeCacheSchema.schemaMap.Clear()
invalidate()
let pf = recreate()
saveInProcess <- false
"Database schema cache cleared.")
[ProvidedProperty(result,typeof<unit>, getterCode = empty) :> MemberInfo]
else []
)
let m2 = ProvidedProperty("ClearDatabaseSchemaCache", (invalidateActionResponse :> Type), getterCode = empty)
m2.AddXmlDocComputed(fun () ->
"This method can be used to refresh and detect recent database schema changes. " +
"Write dot after ClearDatabaseSchemaCache to invalidate and clear the schema cache. May take a while."
)
designTimeCommandsContainer.AddMember m2
designTimeCommandsContainer.AddMember m
designTimeCommandsContainer, saveResponse, mOld, designTime, Some invalidateActionResponse
else
designTimeCommandsContainer.AddMember m
designTimeCommandsContainer, saveResponse, mOld, designTime, None
let rec createTypes (rootType:ProvidedTypeDefinition) (serviceType:ProvidedTypeDefinition) (readServiceType:ProvidedTypeDefinition) (config:TypeProviderConfig) (sqlRuntimeInfo:_) invalidate registerDispose (args) =
let struct(connectionString, conStringName,dbVendor,resolutionPath,individualsAmount,useOptionTypes,owner,caseSensitivity, tableNames, contextSchemaPath, odbcquote, sqliteLibrary, ssdtPath, rootTypeName) = args
let resolutionPath =
if String.IsNullOrWhiteSpace resolutionPath
then config.ResolutionFolder
else resolutionPath
let caseInsensitivityCheck =
match caseSensitivity with
| CaseSensitivityChange.TOLOWER -> (fun (x:string) -> x.ToLower())
| CaseSensitivityChange.TOUPPER -> (fun (x:string) -> x.ToUpperInvariant())
| _ -> id
let conString = ConfigHelpers.tryGetConnectionString false config.ResolutionFolder conStringName connectionString
let rootType, prov, con =
let referencedAssemblies = Array.append [|config.RuntimeAssembly|] config.ReferencedAssemblies
let prov : ISqlProvider = SqlDataContext.ProviderFactory dbVendor resolutionPath referencedAssemblies config.RuntimeAssembly owner tableNames contextSchemaPath odbcquote sqliteLibrary ssdtPath
let con =
match dbVendor with
| DatabaseProviderTypes.MSSQLSERVER_SSDT ->
if ssdtPath = "" then failwith "No SsdtPath was specified."
elif not (ssdtPath.EndsWith(".dacpac")) then failwith "SsdtPath must point to a .dacpac file."
elif not (System.IO.File.Exists ssdtPath) then failwith ("File not exists: " + ssdtPath)
else Some Stubs.connection
| _ ->
match conString, conStringName with
| "", "" -> failwith "No connection string or connection string name was specified."
| "", _ -> failwithf "Could not find a connection string with name '%s'." conStringName
| _ ->
match prov.GetSchemaCache().IsOffline with
| false ->
let con = prov.CreateConnection conString
registerDispose (con, dbVendor)
try
con.Open()
with
| exn ->
let baseError = exn.GetBaseException()
failwithf $"Error opening compile-time connection. Connection string: {conString}. Error: {exn.GetType()}, {exn.Message}, inner {baseError.GetType()} {baseError.Message}"
prov.CreateTypeMappings con
Some con
| true ->
None
rootType, prov, con
let tables =
lazy
match con with
| Some con -> prov.GetTables(con,caseSensitivity)
| None -> prov.GetSchemaCache().Tables |> Seq.map (fun kv -> kv.Value) |> Seq.toArray
let tableColumns =
lazy
dict
[for t in tables.Force() do
yield( t.FullName,
lazy
match con with
| Some con ->
let cols = prov.GetColumns(con,t)
let rel = prov.GetRelationships(con,t)
(cols,rel)
| None ->
let cols =
match prov.GetSchemaCache().Columns.TryGetValue(t.FullName) with
| true,cols -> cols
| false,_ -> Map.empty
let rel =
match prov.GetSchemaCache().Relationships.TryGetValue(t.FullName) with
| true,rel -> rel
| false,_ -> ([||],[||])
(cols,rel))]
let sprocData =
lazy
match con with
| Some con -> prov.GetSprocs con
| None -> prov.GetSchemaCache().Sprocs |> Seq.toList
let getTableData name = tableColumns.Force().[name].Force()
let designTimeDc = lazy SqlDataContext(rootTypeName, conString, dbVendor, resolutionPath, config.ReferencedAssemblies, config.RuntimeAssembly, owner, caseSensitivity, tableNames, contextSchemaPath, odbcquote, sqliteLibrary, transactionOptions, None, SelectOperations.DotNetSide, ssdtPath, true)
// first create all the types so we are able to recursively reference them in each other's definitions
let baseTypes =
lazy
dict [ let tablesforced = tables.Force()
if Array.isEmpty tablesforced then
let hint =
match con with
| Some con ->
match caseSensitivity with
| CaseSensitivityChange.ORIGINAL | CaseSensitivityChange.TOLOWER
when prov.GetTables(con,CaseSensitivityChange.TOUPPER).Length > 0 ->
". Try adding parameter SqlDataProvider<CaseSensitivityChange=Common.CaseSensitivityChange.TOUPPER, ...> \r\nConnection: " + connectionString
| CaseSensitivityChange.ORIGINAL | CaseSensitivityChange.TOUPPER
when prov.GetTables(con,CaseSensitivityChange.TOLOWER).Length > 0 ->
". Try adding parameter SqlDataProvider<CaseSensitivityChange=Common.CaseSensitivityChange.TOLOWER, ...> \r\nConnection: " + connectionString
| _ when owner = "" -> ". Try adding parameter SqlDataProvider<Owner=...> where Owner value is database name or schema. \r\nConnection: " + connectionString
| _ -> " for schema or database " + owner + ". Connection: " + connectionString
| None -> ""
let possibleError = "Tables not found" + hint
let errInfo =
ProvidedProperty("PossibleError", typeof<String>, getterCode = fun _ -> <@@ possibleError @@>)
errInfo.AddXmlDocDelayed(fun () ->
invalidate()
"You have possible configuration error. \r\n " + possibleError)
serviceType.AddMember errInfo
else
for table in tablesforced do
let t = ProvidedTypeDefinition(table.FullName + "Entity", Some typeof<SqlEntity>, isErased=true)
let fullname = table.FullName
t.AddMemberDelayed(fun () -> ProvidedConstructor([ProvidedParameter("dataContext",typeof<ISqlDataContext>)],
fun args ->
let a0 = args.[0]
try
<@@ ((%%a0 : obj) :?> ISqlDataContext).CreateEntity(fullname) @@>
with
| :? ArgumentException ->
<@@ (%%a0 : ISqlDataContext).CreateEntity(fullname) @@>
))
let desc = (sprintf "An instance of the %s %s belonging to schema %s" table.Type table.Name table.Schema)
t.AddXmlDoc desc
yield table.FullName,(t,sprintf "The %s %s belonging to schema %s" table.Type table.Name table.Schema,"", table.Schema) ]
let baseCollectionTypes =
lazy
dict [ for table in tables.Force() do
let name = table.FullName
match baseTypes.Force().TryGetValue name with
| true, (et,_,_,_) ->
let ct = ProvidedTypeDefinition(name, Some typeof<obj>,isErased=true)
ct.AddInterfaceImplementationsDelayed( fun () -> [ProvidedTypeBuilder.MakeGenericType(typedefof<System.Linq.IQueryable<_>>,[et :> Type]); typeof<ISqlDataContext>])
let tableTypeDef,_,_,_ = baseTypes.Force().[table.FullName]
let it = createIndividualsType con prov table designTimeDc dbVendor individualsAmount tableTypeDef
yield name,(ct,it)
| false, _ -> ()]
// add the attributes and relationships
for KeyValue(key,(t,_,_,_)) in baseTypes.Force() do
t.AddMembersDelayed(fun () ->
let (columns,(children,parents)) = getTableData key
let attProps =
let createCols = createColumnProperty con prov useOptionTypes key
List.map createCols (columns |> Seq.map (fun kvp -> kvp.Value) |> Seq.toList)
let relProps =
let getRelationshipName = Utilities.uniqueName()
let bts = baseTypes.Force()
let ty = typedefof<System.Linq.IQueryable<_>>
[ for r in children do
match bts.TryGetValue r.ForeignTable with
| true, (tt,_,_,_) ->
let ty = ty.MakeGenericType tt
let constraintName = r.Name
let niceName = getRelationshipName (sprintf "%s by %s" r.ForeignTable r.PrimaryKey)
let pt = r.PrimaryTable
let pk = r.PrimaryKey
let ft = r.ForeignTable
let fk = r.ForeignKey
let prop = ProvidedProperty(niceName,ty, getterCode = fun args ->
let a0 = args.[0]
<@@ (%%a0 : SqlEntity).DataContext.CreateRelated((%%a0 : SqlEntity),constraintName,pt,pk,ft,fk,RelationshipDirection.Children) @@> )
prop.AddXmlDoc(sprintf "Related %s entities from the foreign side of the relationship, where the primary key is %s and the foreign key is %s. Constraint: %s" r.ForeignTable r.PrimaryKey r.ForeignKey constraintName)
yield prop
| false, _ -> ()
] @
[ for r in parents do
match bts.TryGetValue r.PrimaryTable with
| true, (tt,_,_,_) ->
let ty = ty.MakeGenericType tt
let constraintName = r.Name
let niceName = getRelationshipName (sprintf "%s by %s" r.PrimaryTable r.PrimaryKey)
let pt = r.PrimaryTable
let pk = r.PrimaryKey
let ft = r.ForeignTable
let fk = r.ForeignKey
let prop = ProvidedProperty(niceName,ty, getterCode = fun args ->
let a0 = args.[0]
<@@ (%%a0 : SqlEntity).DataContext.CreateRelated((%%a0 : SqlEntity),constraintName,pt, pk,ft, fk,RelationshipDirection.Parents) @@> )
prop.AddXmlDoc(sprintf "Related %s entities from the primary side of the relationship, where the primary key is %s and the foreign key is %s. Constraint: %s" r.PrimaryTable r.PrimaryKey r.ForeignKey constraintName)
yield prop
| false, _ -> ()
]
attProps @ relProps)
let tableTypes = baseTypes.Force()
let containers =
let sprocs =
match con with
| None -> prov.GetSchemaCache().Sprocs |> Seq.toList
| Some _ ->
let sprocList = sprocData.Force()
prov.GetSchemaCache().Sprocs.AddRange sprocList
sprocList
generateTypeTree con prov Map.empty sprocs
let addServiceTypeMembers (isReadonly:bool) =
[
if not isReadonly then
yield! containers |> Seq.cast<MemberInfo>
let tableTypes =
if not isReadonly then tableTypes
else [] |> dict // Readonly shares the same schema and table types.
let templateContainer = ProvidedTypeDefinition("TemplateAsRecord", Some typeof<obj>, isErased=true)
templateContainer.AddXmlDocDelayed(fun () -> "As this is erasing TypeProvider, you can use the generated types. However, if you need manual access to corresponding type, e.g. to use it in reflection, this will generate you a template of the runtime type. Copy and paste this to use however you will (e.g. with MapTo).")
for (KeyValue(key,(entityType,desc,_,schema))) in tableTypes do
// collection type, individuals type
let (ct,it) = baseCollectionTypes.Force().[key]
let schemaType = getOrAddSchema args schema
let templateTable = ProvidedTypeDefinition(ct.Name+"Template", Some typeof<obj>, isErased=true)
templateTable.AddMemberDelayed(fun () ->
let columns, _ = getTableData key
let optType =
match useOptionTypes with
| NullableColumnType.OPTION -> " option"
| NullableColumnType.VALUE_OPTION -> " voption"
| NullableColumnType.NO_OPTION
| _ -> ""
let template=
let items =
columns
|> Map.toArray
|> Array.map(fun (s,v) -> (SchemaProjections.nicePascalName v.Name) + " : " + (Utilities.getType v.TypeMapping.ClrType).Name + (if v.IsNullable then optType else ""))
"type " + (SchemaProjections.nicePascalName key) + " = { " + (String.concat "; " items) + " }"
let p = ProvidedProperty(template, typeof<obj>, isStatic = true, getterCode = empty)
p.AddXmlDoc("Remove quotes and copy paste this to your code.")
p :> MemberInfo
)
templateContainer.AddMember templateTable
ct.AddMembersDelayed( fun () ->
// creation methods.
// we are forced to load the columns here, but this is ok as the user has already
// pressed . on an IQueryable type so they are obviously interested in using this entity..
let columns, _ = getTableData key
let requiredColumns =
columns
|> Map.toArray
|> Array.map (fun (s,c) -> c)
|> Array.filter (fun c -> (not c.IsNullable) && (not c.IsAutonumber) && (not c.IsComputed))
let backwardCompatibilityOnly =
requiredColumns
|> Array.filter (fun c-> not c.IsPrimaryKey)
|> Array.map(fun c -> ProvidedParameter(c.Name,Utilities.getType c.TypeMapping.ClrType))
|> Array.sortBy(fun p -> p.Name)
|> Array.toList
let normalParameters =
requiredColumns
|> Array.map(fun c -> ProvidedParameter(c.Name,Utilities.getType c.TypeMapping.ClrType))
|> Array.sortBy(fun p -> p.Name)
|> Array.toList
if isReadonly then
seq {
if not (ct.DeclaredProperties |> Seq.exists(fun m -> m.Name = "Individuals")) then
let individuals = ProvidedProperty("Individuals",Seq.head it, getterCode = fun args ->
let a0 = args.[0]
<@@ ((%%a0 : obj ):?> IWithDataContext ).DataContext @@> )
individuals.AddXmlDoc("<summary>Get individual items from the table. Requires single primary key.</summary>")
yield individuals :> MemberInfo
} |> Seq.toList
else
// Create: unit -> SqlEntity
let create1 = ProvidedMethod("Create", [], entityType, invokeCode = fun args ->
let a0 = args.[0]
<@@
let e = ((%%a0 : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
((%%a0 : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@> )
// Create: ('a * 'b * 'c * ...) -> SqlEntity
let create2 =
if List.isEmpty normalParameters then Unchecked.defaultof<ProvidedMethod> else
ProvidedMethod("Create", normalParameters, entityType, invokeCode = fun args ->
let dc = args.Head
let args = args.Tail
let columns =
Expr.NewArray(
typeof<string*obj>,
args
|> List.mapi(fun i v -> Expr.NewTuple [ Expr.Value normalParameters.[i].Name
Expr.Coerce(v, typeof<obj>) ] ))
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%columns : (string *obj) array)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
// Create: ('a * 'b * 'c * ...) -> SqlEntity
let create2old =
if List.isEmpty backwardCompatibilityOnly || normalParameters.Length = backwardCompatibilityOnly.Length then Unchecked.defaultof<ProvidedMethod> else
ProvidedMethod("Create", backwardCompatibilityOnly, entityType, invokeCode = fun args ->
let dc = args.Head
let args = args.Tail
let columns =
Expr.NewArray(
typeof<string*obj>,
args
|> List.mapi(fun i v -> Expr.NewTuple [ Expr.Value backwardCompatibilityOnly.[i].Name
Expr.Coerce(v, typeof<obj>) ] ))
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%columns : (string *obj) array)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
// Create: (data : seq<string*obj>) -> SqlEntity
let create3 = ProvidedMethod("Create", [ProvidedParameter("data",typeof< (string*obj) seq >)] , entityType, invokeCode = fun args ->
let dc = args.[0]
let data = args.[1]
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%data : (string * obj) seq)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
let desc3 =
let cols = requiredColumns |> Seq.map(fun c -> c.Name)
"Item array of database columns: \r\n" + (String.concat "," cols)
create3.AddXmlDoc (sprintf "<summary>%s</summary>" desc3)
// ``Create(...)``: ('a * 'b * 'c * ...) -> SqlEntity
let create4 =
if List.isEmpty normalParameters then Unchecked.defaultof<ProvidedMethod> else
let template=
let cols = normalParameters |> Seq.map(fun c -> c.Name )
"Create(" + (String.concat ", " cols) + ")"
ProvidedMethod(template, normalParameters, entityType, invokeCode = fun args ->
let dc = args.Head
let args = args.Tail
let columns =
Expr.NewArray(
typeof<string*obj>,
args
|> List.mapi(fun i v -> Expr.NewTuple [ Expr.Value normalParameters.[i].Name
Expr.Coerce(v, typeof<obj>) ] ))
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%columns : (string *obj) array)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
let minimalParameters =
requiredColumns
|> Array.filter (fun c-> (not c.HasDefault))
|> Array.map(fun c -> ProvidedParameter(c.Name,Utilities.getType c.TypeMapping.ClrType))
|> Array.sortBy(fun p -> p.Name)
|> Array.toList
// ``Create(...)``: ('a * 'b * 'c * ...) -> SqlEntity
let create4old =
if List.isEmpty backwardCompatibilityOnly || backwardCompatibilityOnly.Length = normalParameters.Length ||
backwardCompatibilityOnly.Length = minimalParameters.Length then Unchecked.defaultof<ProvidedMethod> else
let template=
let cols = backwardCompatibilityOnly |> Seq.map(fun c -> c.Name )
"Create(" + (String.concat ", " cols) + ")"
ProvidedMethod(template, backwardCompatibilityOnly, entityType, invokeCode = fun args ->
let dc = args.Head
let args = args.Tail
let columns =
Expr.NewArray(
typeof<string*obj>,
args
|> List.mapi(fun i v -> Expr.NewTuple [ Expr.Value backwardCompatibilityOnly.[i].Name
Expr.Coerce(v, typeof<obj>) ] ))
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%columns : (string *obj) array)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
// ``Create(...)``: ('a * 'b * 'c * ...) -> SqlEntity
let create5 =
if List.isEmpty minimalParameters || normalParameters.Length = minimalParameters.Length then Unchecked.defaultof<ProvidedMethod> else
let template=
let cols = minimalParameters |> Seq.map(fun c -> c.Name )
"Create(" + (String.concat ", " cols) + ")"
ProvidedMethod(template, minimalParameters, entityType, invokeCode = fun args ->
let dc = args.Head
let args = args.Tail
let columns =
Expr.NewArray(
typeof<string*obj>,
args
|> List.mapi(fun i v -> Expr.NewTuple [ Expr.Value minimalParameters.[i].Name
Expr.Coerce(v, typeof<obj>) ] ))
<@@
let e = ((%%dc : obj ):?> IWithDataContext).DataContext.CreateEntity(key)
e._State <- Created
e.SetData(%%columns : (string *obj) array)
((%%dc : obj ):?> IWithDataContext ).DataContext.SubmitChangedEntity e
e
@@>)
seq {
if not (ct.DeclaredProperties |> Seq.exists(fun m -> m.Name = "Individuals")) then
let individuals = ProvidedProperty("Individuals",Seq.head it, getterCode = fun args ->
let a0 = args.[0]
<@@ ((%%a0 : obj ):?> IWithDataContext ).DataContext @@> )
individuals.AddXmlDoc("<summary>Get individual items from the table. Requires single primary key.</summary>")
yield individuals :> MemberInfo
if normalParameters.Length > 0 then yield create2 :> MemberInfo
if backwardCompatibilityOnly.Length > 0 && normalParameters.Length <> backwardCompatibilityOnly.Length then
create2old.AddXmlDoc("This will be obsolete soon. Migrate away from this!")
yield create2old :> MemberInfo
yield create3 :> MemberInfo
yield create1 :> MemberInfo
if normalParameters.Length > 0 then