-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHiveTypeProvider.fs
2158 lines (1848 loc) · 120 KB
/
HiveTypeProvider.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
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
module Hive.HiveRuntime
open System.Reflection
open System.Linq.Expressions
open System.Collections.Generic
open System
open System.Text
open System.Linq
open System.Collections.Concurrent
open System.Net
open System.Net.Sockets
open System.IO
open Microsoft.FSharp.Control.WebExtensions
open Microsoft.FSharp.Collections
open Microsoft.FSharp.Data.UnitSystems.SI.UnitSymbols
open System.Threading
open System.Collections.Generic
open System.Diagnostics
open System.ComponentModel
open System.IO.Pipes
open System.Text.RegularExpressions
open System.Reflection
open System.Data.Odbc
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Reflection
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns
open Microsoft.FSharp.Data.UnitSystems.SI.UnitSymbols
open FSharp.ProvidedTypes
[<AutoOpen>]
module (*internal*) HiveSchema =
let inline (|Value|Null|) (x:System.Nullable<_>) = if x.HasValue then Value x.Value else Null
let inline Value x = System.Nullable x
let inline Null<'T when 'T : (new : unit -> 'T) and 'T : struct and 'T :> System.ValueType> = System.Nullable<'T>()
/// Represents a type of a column in a hive table
type DBasic =
| DInt8
| DInt16
| DInt32
| DInt64
| DSingle
| DDouble
| DDecimal
| DBoolean
| DAtom
| DMap of DBasic * DBasic
| DArray of DBasic // note, accessing these columns NYI
| DStruct of (string * DBasic) [] // note, accessing these columns NYI
| DTable of HiveColumnSchema[] // result of 'select *'
| DString
and HiveColumnSchema =
{ HiveName: string
Description: string
HiveType: DBasic
IsRequired: bool }
and internal HiveTableSortKey =
{ Column: string; Order: string }
and HiveTableSchema =
{ Description: string
Columns: HiveColumnSchema[]
PartitionKeys: string[]
//BucketKeys: string[]
//SortKeys: HiveTableSortKey[]
}
let rec formatHiveType ty =
match ty with
| DSingle _ -> "float"
| DDouble _ -> "double"
| DDecimal _ -> "decimal"
| DString -> "string"
| DInt32 -> "int"
| DInt8 -> "tinyint"
| DInt16 -> "smallint"
| DInt64 -> "bigint"
| DBoolean -> "bool"
| DMap(ty1,ty2) -> "map<" + formatHiveType ty1 + "," + formatHiveType ty2 + ">"
| DArray(ty1) -> "array<" + formatHiveType ty1 + ">"
| DStruct _cols -> failwith "struct types: nyi"
| _ -> failwith (sprintf "unexpected type '%A'" ty)
let rec formatHiveComment (req) =
match req with
| true -> "(required)"
| false -> ""
/// Represents a value in one column of one row in a hive table
type TVal =
| VInt8 of System.Nullable<sbyte>
| VInt16 of System.Nullable<int16>
| VInt32 of System.Nullable<int32>
| VInt64 of System.Nullable<int64>
| VSingle of System.Nullable<single>
| VDecimal of System.Nullable<decimal>
| VDouble of System.Nullable<double>
| VBoolean of System.Nullable<bool>
| VString of string // may be null
| VMap of (TVal * TVal) [] // may be null
| VArray of TVal[] // may be null
| VStruct of (string * TVal)[] // may be null
/// Represents an expression in a hive 'where' expression
type TExpr =
| EVal of TVal * DBasic
| ETable of string * HiveColumnSchema[]
| EColumn of string * DBasic
| EQuery of HiveQueryData // e.g. 'AVG(height)'
| EBinOp of TExpr * string * TExpr * DBasic
| EFunc of string * TExpr list * DBasic
/// Represents a hive query
and HiveQueryData =
| Table of string * HiveColumnSchema[]
| GroupBy of HiveQueryData * TExpr // Not fully implemented - see comments for #if GROUP_BY below
| Distinct of HiveQueryData
| Where of HiveQueryData * TExpr
| Limit of HiveQueryData * int
| Count of HiveQueryData
/// A 'sumBy' or other aggregation operation.
/// The 'bool' indicates whether the result would get labelled as 'required' if we write the table.
| AggregateOpBy of string * HiveQueryData * TExpr * bool
| TableSample of HiveQueryData * int * int
/// A 'select' operation.
/// The 'bool' indicates whether the field would get labelled as 'required' if we write the table.
| Select of HiveQueryData * (string * TExpr * bool)[]
let rec typeOfExpr e =
match e with
| EVal (_,ty) -> ty
| ETable (_,ty) -> DTable ty
| EColumn (_,ty) -> ty
| EQuery q ->
match q with
| AggregateOpBy(_,_,e,_) -> typeOfExpr e
| Count(_) -> DInt64
| q -> failwith (sprintf "unsupported query embedded in expression: %A" q)
| EBinOp (_,_,_,ty) -> ty
| EFunc (_,_,ty) -> ty
type HiveRequest =
| GetTableNames
| GetTablePartitionNames of string
| GetTableDescription of string
| GetTableSchema of string
| GetDataFrame of HiveQueryData * HiveColumnSchema[]
| ExecuteCommand of string
type HiveResult =
| TableNames of string[]
// tableDescription, first 10 rows
| TableDescription of string*string
| TablePartitionNames of string[]
| TableSchema of HiveTableSchema
// data[][]
| DataFrame of TVal[][]
| Exception of string
| CommandResult of int
let rec internal formatExpr expr =
match expr with
| ETable (_v,_ty) -> "*"
| EVal (v,ty) ->
match v with
| VInt8 (Value n) -> string n
| VInt16 (Value n) -> string n
| VInt32 (Value n) -> string n
| VInt64 (Value n) -> string n
| VSingle (Value n) -> string n
| VDouble (Value n) -> string n
| VDecimal (Value n) -> string n
| VBoolean (Value b) -> string b
| VString null -> "null"
| VString s ->
// "String literals can be expressed with either single quotes (') or double quotes ("). Hive uses C-style escaping within the strings."
// (from https://cwiki.apache.org/confluence/display/Hive/Literals)
sprintf "'%s'" (s.Replace("'", @"\'"))
| VInt8 Null -> "null"
| VInt16 Null -> "null"
| VInt32 Null -> "null"
| VInt64 Null -> "null"
| VSingle Null -> "null"
| VDouble Null -> "null"
| VDecimal Null -> "null"
| VBoolean Null -> "null"
| VMap _ | VArray _ | VStruct _ -> "<nyi: map/array/struct>"
| EColumn (nm,ty) -> nm
| EBinOp(arg1,op,arg2,_) -> "(" + formatExpr arg1 + ")" + " " + op + " " + "(" + formatExpr arg2 + ")"
| EQuery(q) ->
if formatQueryAux q <> "" then failwith (sprintf "unsupported nested query: %A" q)
formatQuerySelect q
| EFunc("$id",[e],_) -> formatExpr e // used for changing types
| EFunc(op,[],_) -> op
| EFunc(op,args,_) -> op + "(" + (List.map formatExpr args |> String.concat ",") + ")"
and getTableName q =
match q with
| Table(tableName,_) -> tableName
| Distinct q2 | GroupBy(q2,_) | AggregateOpBy(_,q2,_,_) | Select(q2,_) | Count(q2) | Limit(q2, _) | Where(q2,_) | TableSample(q2,_,_) -> getTableName q2
// https://cwiki.apache.org/Hive/languagemanual.html
and internal formatQuerySelect q =
match q with
| Table(_tableName, _) -> "*"
| Select (_q2,colExprs) -> colExprs |> Array.map (fun (_,e,_) -> formatExpr e) |> String.concat ", "
| AggregateOpBy (op, _q2,selector,_) -> op + "(" + formatExpr selector + ")"
| TableSample (q2,_n1,_n2) -> formatQuerySelect q2
| GroupBy (q2,_) -> formatQuerySelect q2
| Limit (q2,_rowCount) -> formatQuerySelect q2
| Count (q2) -> "COUNT(" + formatQuerySelect q2 + ")"
| Distinct (q2) -> "DISTINCT " + formatQuerySelect q2
| Where (q2,_pred) -> formatQuerySelect q2
and internal formatQueryAux q =
match q with
| Table(_tableName,_) -> ""
| Select (q2,_colExprs) -> formatQueryAux q2
| GroupBy (q2,keyExpr) -> formatQueryAux q2 + " GROUP BY " + formatExpr keyExpr
| AggregateOpBy (_op, q2,_selector,_) -> formatQueryAux q2
| TableSample (q2,n1,n2) -> formatQueryAux q2 + sprintf " TABLESAMPLE(BUCKET %d OUT OF %d)" n1 n2
| Limit (q2,rowCount) -> formatQueryAux q2 + sprintf " LIMIT %i" rowCount
| Count (q2) -> formatQueryAux q2
| Distinct (q2) -> formatQueryAux q2
| Where (q2,pred) -> formatQueryAux q2 + " WHERE " + formatExpr pred
let internal formatQuery q =
"SELECT " + formatQuerySelect q + " FROM " + getTableName q + formatQueryAux q
type internal IHiveDataServer =
inherit System.IDisposable
abstract GetTableNames : unit -> string[]
abstract GetTablePartitionNames : tableName: string -> string[]
abstract GetTableSchema : tableName: string -> HiveTableSchema
abstract ExecuteCommand : string -> int
abstract GetDataFrame : HiveQueryData * HiveColumnSchema[] -> TVal[][]
#nowarn "40" // recursive objects
[<AutoOpen>]
module internal DetailedTableDescriptionParser =
open System
open System.Collections.Generic
type Parser<'T> = P of (list<char> -> ('T * list<char>) option)
let result v = P(fun c -> Some (v, c) )
let zero () = P(fun _c -> None)
let bind (P p) f = P(fun inp ->
match p inp with
| Some (pr, inp') ->
let (P pars) = f pr
pars inp'
| None -> None)
let plus (P p) (P q) = P (fun inp -> match p inp with Some x -> Some x | None -> q inp )
let (<|>) p1 p2 = plus p1 p2
type ParserBuilder() =
member x.Bind(v, f) = bind v f
member x.Zero() = zero()
member x.Return(v) = result(v)
member x.ReturnFrom(p) = p
member x.Combine(a, b) = plus a b
member x.Delay(f) = f()
let parser = new ParserBuilder()
/// Accept any character
let anyChar = P(function | [] -> None | c :: r -> Some (c,r))
/// Accept any character satisfyin the predicate
let sat p = parser { let! v = anyChar in if (p v) then return v }
/// Accept precisely the given character
let char x = sat ((=) x)
/// Accept any whitespace character
let whitespace = sat (Char.IsWhiteSpace)
/// Accept zero or more repetitions of the given parser
let rec many p =
parser { let! it = p in let! res = many p in return it::res }
<|>
parser { return [] }
/// Accept zero or one repetitions of the given parser
let optional p =
parser { let! v = p in return Some v }
<|>
parser { return None }
/// Run the given parser
let apply (P p) (str:seq<char>) =
let res = str |> List.ofSeq |> p
match res with
| Some (x,[]) -> Some x
| _ -> None
/// Accept one or more repetitions of the given parser with the given character separator followed by whitespace
let oneOrMoreSep f sep =
parser { let! first = f
let! rest = many (parser { let! _ = char sep in let! _ = many whitespace in let! w = f in return w })
return (first :: rest) }
/// Accept zero or more repetitions of the given parser with the given character separator followed by whitespace
let zeroOrMoreSep f sep =
oneOrMoreSep f sep <|> parser { return [] }
/// Results of parsing the detailed table description
[<RequireQualifiedAccess>]
type Data =
| DataNode of string * IDictionary<string,Data>
| List of Data list
| Value of string
let anyNonDelim lhs =
if lhs then sat (fun c -> c <> '=' && c <> '{' && c <> '(' && c <> ')' && c <> ',' && c <> ':' && c <> '[' && c <> ']' && c <> '}' && not (Char.IsWhiteSpace c))
else sat (fun c -> c <> '(' && c <> '{' && c <> '[' && c <> ')' && c <> ']' && c <> '}' && c <> ',' && not (Char.IsWhiteSpace c))
let word lhs =
parser { let! ch = anyNonDelim lhs
let! chs = many (anyNonDelim lhs)
return String(Array.ofSeq (ch::chs)) }
/// Parse either
// 1023
// Foo
// Foo(a1:b1,...,an:bn)
// [a1,...,an]
let rec data lhs =
parser { let! w = word lhs
let! rest = optional (parser { let! _ = char '('
let! rest = oneOrMoreSep dataField ','
let! _ = char ')'
return rest })
return (match rest with None -> Data.Value w | Some xs -> Data.DataNode(w,dict xs)) }
<|>
parser { let! xs = dataList
return Data.List(xs) }
<|>
record
/// Parse left of 'a:int' or 'a=3' labelled data
and lhsData = data true
/// Parse right of 'a:int' or 'a=3' labelled data
and rhsData = data false
/// Parse a a1:b1 data field, e.g. in FieldSchema(a:int)
and dataField =
parser { let! w = word(true)
let! _ = char ':'
let! d = if w = "comment" then commentData elif w = "type" then typeData else rhsData
return (w,d) }
/// Parse a {a1=b1,...,an=bn} record
and record =
parser { let! _ = char '{'
let! rest = zeroOrMoreSep recordField ','
let! _ = char '}'
return Data.DataNode("Record",dict rest) }
/// Parse a {...a=b...} field
and recordField =
parser { let! w = word(true)
let! _ = char '='
let! d = if w = "comment" then commentData elif w = "type" then typeData else rhsData
return (w,d) }
/// Parse a comment, which can include balanced parens
and commentData = delimData ('(', ')', '{', '}', (fun c -> c <> ')' && c <> '}'))
/// Parse a type, e.g. 'map<string,string>'
and typeData = delimData ('<','>', '<', '>', (fun c -> c <> ')' && c <> '}' && c <> ','))
/// Parse free text where 'startParen' and 'endParen' are balanced and we terminate when 'delim' is false
and delimData (startParen1,endParen1,startParen2,endParen2,delim) =
parser { let! chs = delimText (startParen1,endParen1,startParen2,endParen2,delim) 0
return Data.Value(String(Array.ofSeq chs)) }
/// Parse free text where 'startParen' and 'endParen' are balanced and we terminate when 'delim' is false
and delimText (startParen1,endParen1,startParen2,endParen2,endText) parenCount =
parser { let! w = (char startParen1 <|> char startParen2)
let! d = delimText (startParen1,endParen1,startParen2,endParen2,endText) (parenCount+1)
return (w::d) }
<|>
parser { let! c = sat (fun c -> parenCount > 0 && (c = endParen1 || c = endParen2))
let! d = delimText (startParen1,endParen1,startParen2,endParen2,endText) (parenCount-1)
return (c::d) }
<|>
parser { let! c = sat (fun c -> parenCount > 0 || (endText c))
let! d = delimText (startParen1,endParen1,startParen2,endParen2,endText) parenCount
return (c::d) }
<|>
parser { return [] }
/// Parse [FieldSchema(...),...,FieldSchema(...)]
and dataList =
parser { let! _ = char '['
let! rest = zeroOrMoreSep lhsData ','
let! _ = char ']'
return rest }
type IDictionary<'Key,'Value> with
member x.TryGet(key) = if x.ContainsKey key then Some x.[key] else None
let (|ConstructedType|_|) (s:string) =
match s.Split('<') with
| [| nm; rest |] ->
match rest.Split('>') with
| [| args; "" |] ->
match args.Split( [| ',' |], System.StringSplitOptions.RemoveEmptyEntries) with
| [| |] -> None
| args -> Some (nm,List.ofArray args)
| _ -> None
| [| nm |] -> Some(nm,[ ])
| _ -> None
//(|ConstructedType|_|) "map<int,int>" = Some ("map", [ "int"; "int" ])
//(|ConstructedType|_|) "array<int>"= Some ("array", [ "int" ])
//(|ConstructedType|_|) "array<>"= None
//(|ConstructedType|_|) "array"= Some("array", [])
let rec parseHiveType (s:string) =
match s.Trim() with
| "float" -> DSingle
| "double" -> DDouble
| x when Regex.Match(x, @"decimal\s?(\([^\)]+\)\s?)?").Success -> DDecimal
| "string" -> DString
| "int" -> DInt32
| "tinyint" -> DInt8
| "smallint" -> DInt16
| "bigint" -> DInt64
| "bool" -> DBoolean
| ConstructedType("map", [arg1; arg2]) -> DMap(parseHiveType arg1, parseHiveType arg2)
| ConstructedType("array", [arg1]) -> DArray(parseHiveType arg1)
| _ -> failwith (sprintf "unknown type '%s'" s)
// Extract if the field is required (not nullable)
let parseHiveColumnAnnotation (desc:string) = (desc.Trim() = "(required)")
type FieldSchema = { Name: string; Type:DBasic; Comment: string }
type DetailedTableInfo =
{ PartitionKeys: FieldSchema[]
//BucketKeys: string[]
//SortKeys: HiveTableSortKey[]
Columns: FieldSchema[]
Comment: string }
(*
/// Get the names of the bucket columns out of the parsed detailed table description
//bucketCols:[userid]
let getBucketColumns r =
[| match r with
| Data.Node("Table",d) ->
d.ToList |> printfn "%A"
match d.TryGet "bucketCols" with
| Some (Data.List d2) ->
for v in d2 do
match v with
| Data.Value(colName) -> yield colName
| _ -> ()
| _ -> ()
| _ -> () |]
/// Get the names of the sort columns out of the parsed detailed table description
//sortCols:[Order(col:viewtime, order:1)]
let getSortColumns r =
[| match r with
| Data.Node("Table",d) ->
match d.TryGet "sortCols" with
| Some (Data.List d2) ->
for v in d2 do
match v with
| Data.Node("Order",d4) ->
match (d4.TryGet "col", defaultArg (d4.TryGet "order") (Data.Value "1")) with
| Some (Data.Value col), Data.Value order ->
yield {Column=col; Order=order}
| _ -> ()
| _ -> ()
| _ -> ()
| _ -> () |]
*)
/// Get the partition keys out of the parsed detailed table description
let getPartitionKeys r =
[| match r with
| Data.DataNode("Table",d) ->
match d.TryGet "partitionKeys" with
| Some (Data.List d2) ->
for v in d2 do
match v with
| Data.DataNode("FieldSchema",d4) ->
match (d4.TryGet "name", d4.TryGet "type", defaultArg (d4.TryGet "comment") (Data.Value "")) with
| Some (Data.Value nm), Some (Data.Value typ), Data.Value comment ->
yield {Name=nm; Type=parseHiveType typ; Comment=comment}
| _ -> ()
| _ -> ()
| _ -> ()
| _ -> () |]
/// Get the getFields out of the parsed detailed table description
let getFields r =
[| match r with
| Data.DataNode("Table",d) ->
match d.["sd"] with
| Data.DataNode("StorageDescriptor",d2) ->
match d2.TryGet "cols" with
| Some (Data.List cols) ->
for col in cols do
match col with
| Data.DataNode("FieldSchema",d4) ->
match (d4.TryGet "name", d4.TryGet "type", defaultArg (d4.TryGet "comment") (Data.Value "")) with
| Some (Data.Value nm), Some (Data.Value typ), Data.Value comment ->
yield {Name=nm; Type=parseHiveType typ; Comment=comment}
| _ -> ()
| _ -> ()
| _ -> ()
| _ -> ()
| _ -> () |]
/// Get the 'comment' field out of the parsed detailed table description
let getComment r =
match r with
| Data.DataNode("Table",d) ->
match d.TryGet "parameters" with
| Some (Data.DataNode(_,d2)) ->
match d2.TryGet "comment" with
| Some (Data.Value comment) -> comment
| _ -> ""
| _ -> ""
| _ -> ""
let getDetailedTableInfo (text:string) =
apply lhsData text
|> Option.map (fun r ->
{ PartitionKeys=getPartitionKeys r;
Columns = getFields r
//SortKeys = getSortColumns r
//BucketKeys = getBucketColumns r
Comment=getComment r})
type internal OdbcDataServer(dsn:string,timeout:int<s>) =
let conn =
let conn = new OdbcConnection (sprintf "DSN=%s" dsn,ConnectionTimeout=int timeout*1000)
conn.Open()
conn
let runReaderComand (cmd:string) =
System.Diagnostics.Debug.WriteLine(sprintf "executing query command \"%s\"" cmd)
let command = conn.CreateCommand(CommandTimeout=int timeout*1000, CommandText=cmd)
command.ExecuteReader()
let runNonQueryComand (cmd:string) =
System.Diagnostics.Debug.WriteLine(sprintf "executing non-query command \"%s\"" cmd)
let command = conn.CreateCommand(CommandTimeout=int timeout*1000, CommandText=cmd)
command.ExecuteNonQuery()
let GetTableSchema tableName =
let xs =
[| use reader = runReaderComand (sprintf "DESCRIBE extended %s" tableName)
while reader.Read() && not (String.IsNullOrWhiteSpace (reader.GetString(0))) do
let colName = reader.GetString(0).Trim()
// These are the 'simple' description of the table columns. If anything goes wrong
// with parsing the detailed description then we assume there are no partition
// keys and use the information extracted from the simple description instead.
let datatype = parseHiveType (reader.GetString(1).Trim().ToLower())
let desc = (if reader.IsDBNull(2) then "" else reader.GetString(2).Trim())
yield (None,Some((colName, desc, datatype)),None)
while reader.Read() && (reader.GetString(0) <> "Detailed Table Information") do
()
let detailedInfoText = reader.GetString(1)
match getDetailedTableInfo detailedInfoText with
| Some detailedInfo ->
yield (None, None, Some detailedInfo)
| None ->
// This case is if we failed to parse the detailed table information
let comment = System.Text.RegularExpressions.Regex.Match(detailedInfoText,"parameters:{[^}]*comment=([^}]*)}").Groups.[1].Value
yield (Some(comment),None,None)
|]
let tableDetailsOpt = xs |> Array.map (fun (_,_,c) -> c) |> Array.tryPick id
let tableDetails =
match tableDetailsOpt with
| Some tableDetails -> tableDetails
| None ->
let tableCommentBackup = xs |> Array.map (fun (a,_,_) -> a) |> Array.tryPick id
let tableColumnsBackup = xs |> Array.map (fun (_,b,_) -> b) |> Array.choose id
{ Columns = tableColumnsBackup |> Array.map (fun (a,b,c) -> { Name=a; Type=c; Comment=b })
//SortKeys=[| |]
//BucketKeys=[| |]
PartitionKeys=[| |]
Comment=defaultArg tableCommentBackup ""}
let columns =
tableDetails.Columns |> Array.map (fun column ->
let colRequired = parseHiveColumnAnnotation column.Comment
{ HiveName=column.Name
Description=column.Comment
HiveType=column.Type
IsRequired=colRequired })
let partitionKeys = tableDetails.PartitionKeys |> Array.map (fun x -> x.Name)
{ Columns=columns
Description=tableDetails.Comment
PartitionKeys=partitionKeys
//BucketKeys=tableDetails.BucketKeys
//SortKeys=tableDetails.SortKeys
}
interface IDisposable with
member x.Dispose() =
// TODO: we are getting long pauses on exit of fsc.exe and devenv.exe because the ODBC connection pool is
// being finalized. This is really annoying. I don't know what to do about this. Explicitly
// closing doesn't help.
//printfn "closing..."
//System.Data.Odbc.OdbcConnection.ReleaseObjectPool()
conn.Dispose()
//printfn "%A" [ for f in conn.GetType().GetFields(System.Reflection.BindingFlags.Public ||| System.Reflection.BindingFlags.Instance ||| System.Reflection.BindingFlags.NonPublic) -> f.Name, f.GetValue(conn) ]
//System.AppDomain.CurrentDomain.DomainUnload.Add(fun _ ->
// printfn "exiting..."
// System.Environment.Exit(0))
//printfn "closed!"
interface IHiveDataServer with
member x.GetTablePartitionNames(tableName) =
[| use reader = runReaderComand ("SHOW PARTITIONS " + tableName ) ;
while reader.Read() do yield reader.GetString(0) |]
member x.GetTableNames() =
[| use reader = runReaderComand "SHOW TABLES" ;
while reader.Read() do yield reader.GetString(0) |]
member x.GetTableSchema tableName = GetTableSchema tableName
member x.ExecuteCommand (commandText) = runNonQueryComand commandText
member x.GetDataFrame (query, colData) =
let queryText = formatQuery query
let table =
[| use reader = runReaderComand queryText
while reader.Read() do
let row = [|for i in 0..colData.Length-1 -> reader.GetValue(i)|]
yield [|
for i in 0..colData.Length-1 do
let colData =
match colData.[i].HiveType with
| DInt8 -> VInt8(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToSByte o))
| DInt16 -> VInt16(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToInt16 o))
| DInt32 -> VInt32(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToInt32 o))
| DInt64 -> VInt64(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToInt64 o))
| DSingle _ -> VSingle(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToSingle o))
| DDouble _ -> VDouble(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToDouble o))
| DDecimal _ -> VDecimal(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToDecimal o))
| DBoolean -> VBoolean(match row.[i] with | :? DBNull -> Null | o -> Value(Convert.ToBoolean o))
| DString -> VString(match row.[i] with | :? DBNull -> null | o -> (o :?> string))
| DArray _ -> failwith "nyi map/array/struct"
| DMap _ -> failwith "nyi map/array/struct"
| DStruct _ -> failwith "nyi map/array/struct"
| DAtom -> failwith "unreachable: atom"
| DTable(_args) -> failwith "evaluating whole table as part of client-side expression"
yield colData
|]
|]
table
type internal Adjustment =
| Center
| Right
| Left
let internal hiveHandler (dsn:string) (timeout:int<s>) (msg:HiveRequest) : HiveResult =
try
async {
try
use dataServer = new OdbcDataServer(dsn,timeout) :> IHiveDataServer
let result =
match msg with
| ExecuteCommand(commandText) -> dataServer.ExecuteCommand(commandText) |> CommandResult
| GetTableNames -> dataServer.GetTableNames()|> TableNames
| GetTablePartitionNames(tableName) -> dataServer.GetTablePartitionNames(tableName)|> TablePartitionNames
| GetTableDescription tableName ->
let table = dataServer.GetTableSchema tableName
let rows = dataServer.GetDataFrame (Limit(Table(tableName,table.Columns),10), table.Columns)
let maxWidth = 30
let tableHead =
let inline nullToString x = match x with | null -> "NA" | x -> string x
let inline nullableToString (x:Nullable<'T>) = if x.HasValue then string x.Value else "NA"
let flip (xs:'a[][]) = [|for i in 0..xs.[0].Length - 1 -> [| for j in 0..xs.Length - 1 -> xs.[j].[i]|]|]
let resize (adjust:Adjustment) (length:int) (str:string) =
if str.Length < length
then
match adjust with
| Center ->
let diff = length - str.Length
let leftPad = (String.replicate ((diff / 2) + (diff % 2)) " ")
let rightPad = (String.replicate (diff / 2) " ")
leftPad + str + rightPad
| Right -> str.PadLeft(length)
| Left -> str.PadRight(length)
elif str.Length = length then str
else str.Substring(0,Math.Max(0,length - 2)) + ".."
let tValToString =
function
| VInt8 x -> x |> nullableToString
| VInt16 x -> x |> nullableToString
| VInt32 x -> x |> nullableToString
| VInt64 x -> x |> nullableToString
| VSingle x -> x |> nullableToString
| VDouble x -> x |> nullableToString
| VDecimal x -> x |> nullableToString
| VBoolean x -> x |> nullableToString
| VString x -> x |> nullToString
| VArray x -> x |> nullToString
| VStruct x -> x |> nullToString
| VMap x -> x |> nullToString
// TODO - change adjustment based on hive type
let dataFrame = [| for (col,column) in (table.Columns,rows |> flip) ||> Array.zip -> [| yield col.HiveName; yield! column |> Array.map tValToString |]|]
[|
let lengths = dataFrame |> Array.map (fun xs -> min maxWidth ((xs |> Array.maxBy (fun x -> x.Length)).Length))
let hr = "+" + (lengths |> Array.map (fun length -> String.replicate length "-") |> String.concat "+") + "+"
yield hr
// Header
for i in 0..dataFrame.[0].Length - 1 do
yield "|" + ([|for (column,length) in (dataFrame,lengths) ||> Array.zip -> resize (if i = 0 then Center else Left) length column.[i]|] |> String.concat "|") + "|"
if i = 0 then yield hr
yield hr
|] |> String.concat "\n"
TableDescription(table.Description,tableHead)
| GetTableSchema tableName ->
TableSchema (dataServer.GetTableSchema tableName)
| GetDataFrame (query, colData) ->
DataFrame (dataServer.GetDataFrame (query, colData))
return result
with
| ex -> return Exception("Error: " + ex.Message + "\n" (* + sprintf "Connection='%s'\n" cns *) + sprintf "Timeout='%d'\n" (int timeout) + sprintf "Message='%A'\n" msg + ex.ToString())
} |> fun x -> Async.RunSynchronously(x,int timeout*1000)
with
| ex -> Exception("Error: " + ex.Message + "\n" (* + sprintf "Connection='%s'\n" cns *) + sprintf "Message='%A'\n" msg + ex.ToString())
let internal HiveRequestInProcess (dsn:string, timeout:int<s>) (req:HiveRequest) =
hiveHandler dsn timeout req
[<AutoOpen>]
module internal StaticHelpers =
let memoize f =
let tab = System.Collections.Generic.Dictionary()
fun x ->
if tab.ContainsKey x then tab.[x]
else let a = f x in tab.[x] <- a; a
let rec computeFSharpTypeWithoutNullable(colHiveType) =
match colHiveType with
| DInt8 -> typeof<sbyte>
| DInt16 -> typeof<int16>
| DInt32 -> typeof<int32>
| DInt64 -> typeof<int64>
| DSingle _ -> typeof<single>
| DDouble _ -> typeof<double>
| DDecimal _ -> typeof<decimal>
| DBoolean -> typeof<bool>
| DString -> typeof<string>
| DAtom -> failwith "should not need to convert atoms"
| DArray(et) -> computeFSharpTypeWithoutNullable(et).MakeArrayType()
| DMap(dt,rt) -> typedefof<IDictionary<_,_>>.MakeGenericType(computeFSharpTypeWithoutNullable dt, computeFSharpTypeWithoutNullable rt)
| DStruct(_cols) -> failwith "nyi: struct"
| DTable(_args) -> failwith "evaluating whole table as part of client-side expression"
let rec colDataOfQuery q =
let mkColumn (colName:string, typ, isRequired) =
{HiveName=colName
HiveType= typ
Description="The column '" + colName + "' in a selected table"
IsRequired=isRequired}
match q with
| Table(tableName, tableColumns) -> tableName, tableColumns
| Distinct q2 | Where (q2,_) | Limit (q2,_) | TableSample(q2,_,_) -> colDataOfQuery q2
| Select (_q2,colExprs) ->
// Compute the types of the selected expressions
let colData = colExprs |> Array.map (fun (colName,colExpr,isRequired) -> mkColumn (colName, HiveSchema.typeOfExpr colExpr, isRequired))
"$select", colData
| Count _ ->
"$count", [| mkColumn ("count", DInt64, true) |]
| GroupBy(q2,e) ->
let _,groupColData = colDataOfQuery q2
"$grouping", [| mkColumn ("$key", typeOfExpr e, true); mkColumn ("$group", DTable groupColData, true) |]
| AggregateOpBy(_,_,e,isRequired) ->
"$result", [| mkColumn ("$value", typeOfExpr e, isRequired) |]
module internal RuntimeHelpers =
let unexpected exp msg =
match msg with
| Exception(ex) -> failwith ex
| _ -> failwithf "unexpected message, expected %s, got %+A" exp msg
/// Represents one row retrieved from the Hive data store
type HiveDataRow internal (dict : IDictionary<string,obj>) =
member __.GetValue<'T> (colName:string) =
dict.[colName] :?> 'T
member __.Item with get (colName : string) = dict.[colName]
new (_tableName, values : (string * obj * bool) []) = new HiveDataRow (dict [| for (key,obj,_) in values -> (key,obj) |])
static member internal GetValueMethodInfo =
match <@@ fun x -> (Unchecked.defaultof<HiveDataRow>).GetValue(x) @@> with
| Lambdas(_,Call(_,mi,_)) -> mi.GetGenericMethodDefinition()
| _ -> failwith "unexpected"
static member internal HiveDataRowCtor =
match <@@ fun (x: (string * obj * bool)[]) -> HiveDataRow("",x) @@> with
| Lambdas(_,NewObject(ci,_)) -> ci
| _ -> failwith "unexpected"
override x.ToString() = "{" + ([ for KeyValue(k,v) in dict -> k+"="+string v ] |> String.concat "; ") + "}"
/// The base type for a connection to the Hive data store.
type HiveDataContext (dsn,defaultQueryTimeout,defaultMetadataTimeout) =
let event = Event<_>()
let executeRequest (requestData : HiveRequest, timeout) =
let evData =
match requestData with
| HiveRequest.GetDataFrame(queryData,_) -> sprintf "query '%s'" (formatQuery queryData)
| HiveRequest.ExecuteCommand (cmd) -> sprintf "command %A" cmd
| HiveRequest.GetTableDescription tableName -> sprintf "get table description %s" tableName
| HiveRequest.GetTableNames -> sprintf "get table names"
| HiveRequest.GetTablePartitionNames table -> sprintf "get table partition names for %s" table
| HiveRequest.GetTableSchema table -> sprintf "get table schema for %s" table
event.Trigger evData
HiveRequestInProcess(dsn,timeout) requestData
let executeQueryRequest (requestData, queryTimeout) = executeRequest (requestData, defaultArg queryTimeout defaultQueryTimeout)
let executeMetadataRequest (requestData, metadataTimeout) = executeRequest (requestData, defaultArg metadataTimeout defaultMetadataTimeout)
let rec getValue v =
match v with
| VInt8 x -> box x
| VInt16 x -> box x
| VInt32 x -> box x
| VInt64 x -> box x
| VSingle x -> box x
| VDouble x -> box x
| VDecimal x -> box x
| VBoolean x -> box x
| VString x -> box x
| VArray x -> box (Array.map getValue x)
| VStruct _x -> failwith "nyi: struct"
| VMap x -> dict (x |> Array.map (fun (x,y) -> getValue x, getValue y)) |> box
member __.RequestSent = event.Publish
/// Dynamically read the table names from the Hive data store
member __.GetTableNames () =
match executeMetadataRequest (GetTableNames, None) with
| TableNames(tableNames) -> tableNames
| data -> RuntimeHelpers.unexpected "GetTableNames" data
/// Dynamically read the table names from the Hive data store
member __.GetTablePartitionNames (tableName) =
match executeMetadataRequest (GetTablePartitionNames(tableName), None) with
| TablePartitionNames(partitionNames) -> partitionNames
| data -> RuntimeHelpers.unexpected "GetPartitionNames" data
/// Dynamically read the table names from the Hive data store
member __.GetTableSchema (tableName) =
match executeMetadataRequest (GetTableSchema(tableName), None) with
| TableSchema(schema) -> schema
| data -> RuntimeHelpers.unexpected "GetTableSchema" data
/// Dynamically read the table description from the Hive data store.
member __.GetTableDescription (tableName) =
match executeMetadataRequest (GetTableDescription(tableName),None) with
| TableDescription(tableDesc,_tableHead) -> tableDesc
| data -> RuntimeHelpers.unexpected "TableDescription" data
member x.GetTable<'T> (tableName) = HiveTable<'T>(x, tableName)
member x.GetTableUntyped (tableName) = HiveTable<HiveDataRow>(x, tableName)
member x.ExecuteCommand (command, ?timeout) =
executeQueryRequest (ExecuteCommand(command), timeout) |> function
| CommandResult(text) -> text
| data -> RuntimeHelpers.unexpected "Commmand" data
/// Execute a single query value
member internal x.ExecuteQueryValue (queryData, ?timeout) =
let _tableName, colData = colDataOfQuery queryData
let rows =
executeQueryRequest (GetDataFrame(queryData, colData), timeout) |> function
| DataFrame(rows) -> rows
| data -> RuntimeHelpers.unexpected "GetDataFrame" data
getValue rows.[0].[0]
/// Dynamically read the rows of a table from the Hive data store.
member internal __.ExecuteQuery (queryData, rowType, ?timeout) : seq<obj> =
seq {
let _tableName, colData = colDataOfQuery queryData
let rows =
executeQueryRequest (GetDataFrame(queryData, colData), timeout) |> function
| DataFrame(rows) -> rows
| data -> RuntimeHelpers.unexpected "GetDataFrame" data
// If making F# record values, precompute a record constructor
let maker =
if rowType = typeof<HiveDataRow> then
None
elif FSharpType.IsRecord rowType then
// We don't need to permute the record fields here because F# quotations are already permuted.
Some (FSharpValue.PreComputeRecordConstructor(rowType,BindingFlags.NonPublic ||| BindingFlags.Public))
elif FSharpType.IsUnion rowType && FSharpType.GetUnionCases(rowType).Length=1 then
Some (FSharpValue.PreComputeUnionConstructor(FSharpType.GetUnionCases(rowType).[0],BindingFlags.NonPublic ||| BindingFlags.Public))
elif FSharpType.IsTuple rowType then
Some (FSharpValue.PreComputeTupleConstructor(rowType))
else
None //failwith (sprintf "unrecognized row type '%A'" rowType)
for row in rows do
let values = (colData, row) ||> Array.map2 (fun colData v -> (colData.HiveName,getValue v) )
match maker with
| None -> yield HiveDataRow (dict values) |> box
| Some f -> yield f (Array.map snd values)
}
/// Represents a query of the Hive data store
and internal IHiveQueryable =
abstract DataContext : HiveDataContext
abstract QueryData : HiveQueryData
abstract TailOps : Expr list
abstract Timeout : int<s> option
and internal IHiveTable =
abstract TableName : string
and HiveTable<'T> internal (dataCtxt: HiveDataContext, tableName: string, colData: HiveColumnSchema[]) =
inherit HiveQueryable<'T>(dataCtxt, Table(tableName, colData), [], None)
new (dataCtxt: HiveDataContext, tableName: string) =
// Performance: it would be nice not to have to make this metadata request when creating the table
let colData = dataCtxt.GetTableSchema(tableName).Columns
new HiveTable<'T>(dataCtxt, tableName, colData)
/// Get the table name of the Hive table
member x.TableName = tableName
/// Get the partition names for the Hive table
member x.GetPartitionNames() = dataCtxt.GetTablePartitionNames(tableName)
/// Get the schema for the Hive table
member x.GetSchema() = dataCtxt.GetTableSchema(tableName)
interface IHiveTable with
member x.TableName = tableName
#if GROUP_BY
and HiveGrouping<'Key,'T> internal (key: 'Key, dataCtxt: HiveDataContext, queryData: HiveQueryData, tailOps: Expr list, timeout: int<s> option) =
inherit HiveQueryable<'T>(dataCtxt, queryData, tailOps, timeout)
member x.Key = key
#endif
and HiveQueryable<'T> internal (dataCtxt: HiveDataContext, queryData: HiveQueryData, tailOps: Expr list, timeout: int<s> option) =
member x.Run(?timeout) =
let rowType =
match tailOps with
| [] -> typeof<'T>
| tailOp::_ ->
assert (tailOp.Type.IsGenericType) // assert the tailOp is a function
assert (tailOp.Type.GetGenericTypeDefinition() = typedefof<int -> int>) // assert the tailOp is a function