-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathParser.hs
2324 lines (1897 loc) · 70.4 KB
/
Parser.hs
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
-- Copyright (c) 2017 Uber Technologies, Inc.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Database.Sql.Hive.Parser where
import Database.Sql.Type
import Database.Sql.Info
import Database.Sql.Helpers
import Database.Sql.Hive.Type as HT
import Database.Sql.Hive.Scanner
import Database.Sql.Hive.Parser.Internal
import Database.Sql.Position
import qualified Database.Sql.Hive.Parser.Token as Tok
import Control.Monad (void)
import Control.Monad.Reader (runReader, local, asks)
import Data.Char (isDigit)
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.List as L
import Data.Maybe (fromMaybe)
import Data.Monoid (Endo (..))
import qualified Text.Parsec as P
import Text.Parsec ( chainl1, choice, many
, option, optional, optionMaybe
, sepBy, sepBy1, try, (<|>), (<?>))
import Data.Semigroup (Semigroup (..), sconcat)
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.Foldable (fold)
statementParser :: Parser (HiveStatement RawNames Range)
statementParser = do
maybeStmt <- optionMaybe $ choice
[ HiveUseStmt <$> useP
, HiveAnalyzeStmt <$> analyzeP
, do
let options =
-- this list is hive-specific statement types that may be
-- preceded by an optional `WITH` and an optional inverted
-- `FROM`
[ (void insertDirectoryPrefixP, fmap HiveInsertDirectoryStmt . insertDirectoryP)
]
prefixes = map fst options
baseParsers = map snd options
_ <- try $ P.lookAhead $ optional withP >> invertedFromP >> choice prefixes
with <- option id withP
invertedFrom <- invertedFromP
let parsers = map ($ (with, invertedFrom)) baseParsers
choice $ parsers
, try $ HiveTruncatePartitionStmt <$> truncatePartitionStatementP
, HiveUnhandledStatement <$> describeP
, HiveUnhandledStatement <$> showP
, do
_ <- try $ P.lookAhead createFunctionPrefixP
HiveUnhandledStatement <$> createFunctionP
, do
_ <- try $ P.lookAhead dropFunctionPrefixP
HiveUnhandledStatement <$> dropFunctionP
, HiveStandardSqlStatement <$> statementP
, try $ HiveAlterTableSetLocationStmt <$> alterTableSetLocationP
, try $ HiveUnhandledStatement <$> alterTableSetTblPropertiesP
, alterPartitionP
, HiveSetPropertyStmt <$> setP
, HiveUnhandledStatement <$> reloadFunctionP
]
case maybeStmt of
Just stmt -> terminator >> return stmt
Nothing -> HiveStandardSqlStatement <$> emptyStatementP
where
terminator = (Tok.semicolonP <|> eof) -- normal statements may be terminated by `;` or eof
emptyStatementP = EmptyStmt <$> Tok.semicolonP -- but we don't allow eof here. `;` is the
-- only way to write the empty statement, i.e. `` (empty string) is not allowed.
emptyParserScope :: ParserScope
emptyParserScope = ParserScope
{ selectTableAliases = Nothing }
-- | parse consumes a statement, or fails
parse :: Text -> Either P.ParseError (HiveStatement RawNames Range)
parse text = runReader (P.runParserT statementParser 0 "-" . tokenize $ text) emptyParserScope
-- | parseAll consumes all input as a single statement, or fails
parseAll :: Text -> Either P.ParseError (HiveStatement RawNames Range)
parseAll text = runReader (P.runParserT (statementParser <* P.eof) 0 "-" . tokenize $ text) emptyParserScope
-- | parseMany consumes multiple statements, or fails
parseMany :: Text -> Either P.ParseError [HiveStatement RawNames Range]
parseMany text = runReader (P.runParserT (P.many1 statementParser) 0 "-" . tokenize $ text) emptyParserScope
-- | parseManyAll consumes all input multiple statements, or fails
parseManyAll :: Text -> Either P.ParseError [HiveStatement RawNames Range]
parseManyAll text = runReader (P.runParserT (P.many1 statementParser <* P.eof) 0 "-" . tokenize $ text) emptyParserScope
-- | parseManyEithers consumes all input as multiple (statements or failures)
-- it should never fail
parseManyEithers :: Text -> Either P.ParseError [Either (Unparsed Range) (HiveStatement RawNames Range)]
parseManyEithers text = runReader (P.runParserT parser 0 "-" . tokenize $ text) emptyParserScope
where
parser = do
statements <- P.many1 $ P.setState 0 >> choice
[ try $ Right <$> statementParser
, try $ Left <$> do
ss <- many Tok.notSemicolonP
e <- Tok.semicolonP
pure $ case ss of
[] -> Unparsed e
s:_ -> Unparsed (s <> e)
]
locs <- many Tok.notSemicolonP
P.eof
pure $ case locs of
[] -> statements
s:es -> statements ++ [Left $ Unparsed $ sconcat (s:|es)]
optionBool :: Parser a -> Parser Bool
optionBool p = option False $ p >> pure True
statementP :: Parser (Statement Hive RawNames Range)
statementP = choice
[ do
let options =
-- this list is universal statement types that may be preceded
-- by an optional `WITH` and an optional inverted `FROM`
[ (void Tok.insertP, fmap InsertStmt . insertP)
, (void Tok.selectP, fmap QueryStmt . queryP )
]
prefixes = map fst options
baseParsers = map snd options
_ <- try $ P.lookAhead $ optional withP >> invertedFromP >> choice prefixes
with <- option id withP
invertedFrom <- invertedFromP
let parsers = map ($ (with, invertedFrom)) baseParsers
choice $ parsers
, InsertStmt <$> loadDataInPathP
, DeleteStmt <$> deleteP
, explainP
, TruncateStmt <$> truncateP
, do
_ <- try $ P.lookAhead createSchemaPrefixP
CreateSchemaStmt <$> createSchemaP
, do
_ <- try $ P.lookAhead createViewPrefixP
CreateViewStmt <$> createViewP
, CreateTableStmt <$> createTableP
, DropTableStmt <$> dropTableP
, do
_ <- try $ P.lookAhead alterTableRenameTablePrefixP
AlterTableStmt <$> alterTableRenameTableP
, do
_ <- try $ P.lookAhead alterTableRenameColumnPrefixP
AlterTableStmt <$> alterTableRenameColumnP
, do
_ <- try $ P.lookAhead alterTableAddColumnsPrefixP
AlterTableStmt <$> alterTableAddColumnsP
, GrantStmt <$> grantP
, RevokeStmt <$> revokeP
, CommitStmt <$> Tok.commitP
, RollbackStmt <$> Tok.rollbackP
]
useP :: Parser (Use Range)
useP = do
r <- Tok.useP
use <- choice
[ UseDefault <$> Tok.defaultP
, UseDatabase . uncurry mkNormalSchema <$> Tok.schemaNameP
]
return $ (r<>) <$> use
analyzeP :: Parser (Analyze RawNames Range)
analyzeP = do
r <- Tok.analyzeP
_ <- Tok.tableP
tn <- tableNameP
optional $ do
_ <- Tok.partitionP
partitionSpecP
_ <- Tok.computeP
e <- Tok.statisticsP
e' <- consumeOrderedOptions e $
[ do
_ <- Tok.forP
Tok.columnsP
, do
_ <- Tok.cacheP
Tok.metadataP
, Tok.noScanP
]
return $ Analyze (r<>e') tn
insertDirectoryPrefixP :: Parser (Range, InsertDirectoryLocale Range, Location Range)
insertDirectoryPrefixP = do
s <- Tok.insertP
_ <- Tok.overwriteP
insertDirectoryLocale <- insertDirectoryLocaleP
insertDirectoryPath <- insertDirectoryPathP
return (s, insertDirectoryLocale, insertDirectoryPath)
insertDirectoryP :: (QueryPrefix, InvertedFrom) -> Parser (InsertDirectory RawNames Range)
insertDirectoryP (with, farInvertedFrom) = do
r <- Tok.insertP
_ <- Tok.overwriteP
insertDirectoryLocale <- insertDirectoryLocaleP
insertDirectoryPath <- insertDirectoryPathP
case farInvertedFrom of
Just _ -> pure ()
Nothing -> optional rowFormatP >> optional storedAsP
insertDirectoryQuery <- case farInvertedFrom of
Just _ -> querySelectP (with, farInvertedFrom)
Nothing -> do
nearInvertedFrom <- invertedFromP
queryP (with, nearInvertedFrom)
let insertDirectoryInfo = r <> (getInfo insertDirectoryQuery)
return InsertDirectory{..}
where
rowFormatP :: Parser Range
rowFormatP = do
s <- Tok.rowP
_ <- Tok.formatP
e <- delimitedP
return $ s <> e
insertDirectoryLocaleP :: Parser (InsertDirectoryLocale Range)
insertDirectoryLocaleP = do
localToken <- optionMaybe Tok.localP
let locale = case localToken of
Just a -> InsertDirectoryLocal a
Nothing -> InsertDirectoryHDFS
return locale
insertDirectoryPathP :: Parser (Location Range)
insertDirectoryPathP = do
r <- Tok.directoryP
(path, r') <- Tok.stringP
return $ HDFSPath (r <> r') path
staticPartitionSpecItemP :: Parser (StaticPartitionSpecItem RawNames Range)
staticPartitionSpecItemP = do
col <- columnNameP
_ <- Tok.equalP
val <- constantP
return $ StaticPartitionSpecItem (getInfo col <> getInfo val) col val
staticPartitionSpecP :: Parser ([StaticPartitionSpecItem RawNames Range], Range)
staticPartitionSpecP = do
s <- Tok.openP
items <- staticPartitionSpecItemP `sepBy1` Tok.commaP
e <- Tok.closeP
return (items, s <> e)
type PartitionDecider = (Either
(StaticPartitionSpecItem RawNames Range)
(DynamicPartitionSpecItem RawNames Range))
dynamicPartitionSpecItemP :: Parser (DynamicPartitionSpecItem RawNames Range)
dynamicPartitionSpecItemP = do
col <- columnNameP
return $ DynamicPartitionSpecItem (getInfo col) col
partitionSpecDeciderP :: Parser PartitionDecider
partitionSpecDeciderP = do
item <- choice
[ do
sp <- try $ staticPartitionSpecItemP
return $ Left sp
, do
dp <- dynamicPartitionSpecItemP
return $ Right dp
]
return item
partitionSpecP :: Parser ()
partitionSpecP = do
-- partitionSpecP currently does not tie down to any specific datatype.
-- The datatype implementation is being deferred.
_ <- Tok.openP
items <- partitionSpecDeciderP `sepBy1` Tok.commaP
_ <- Tok.closeP
let dpSpec = L.foldl' specHelper dpSpecBase $ L.reverse items
case dpSpec of
Right _ -> return ()
Left err -> fail err
where
specHelper :: (Either String ([StaticPartitionSpecItem RawNames Range],
[DynamicPartitionSpecItem RawNames Range])) ->
PartitionDecider ->
(Either String ([StaticPartitionSpecItem RawNames Range],
[DynamicPartitionSpecItem RawNames Range]))
-- Note that specHelper reads partition cols from right to left
-- This allows for list insertions to output a non-reversed list
specHelper (Right (spItems, dpItems)) (Left spItem) =
Right (spItem:spItems, dpItems)
specHelper (Right (spItems, dpItems)) (Right dpItem) =
case spItems of
[] -> Right $ (spItems, dpItem:dpItems)
_ -> Left $ "Failed to parse partition \"" ++ show dpItem ++ "\": dynamic partition found preceding static partition"
specHelper (Left s) _ = Left s
dpSpecBase :: (Either String ([StaticPartitionSpecItem RawNames Range],
[DynamicPartitionSpecItem RawNames Range]))
dpSpecBase = Right ([], [])
truncatePartitionStatementP :: Parser (TruncatePartition RawNames Range)
truncatePartitionStatementP = do
s <- Tok.truncateP
_ <- Tok.tableP
table <- tableNameP
_ <- Tok.partitionP
(_, e) <- staticPartitionSpecP
let truncate' = Truncate (s <> getInfo table) table
return $ TruncatePartition (s <> e) truncate'
describeP :: Parser Range
describeP = do
s <- Tok.describeP
e <- P.many1 Tok.notSemicolonP
return $ s <> last e
showP :: Parser Range
showP = do
s <- Tok.showP
e <- P.many1 Tok.notSemicolonP
return $ s <> last e
createFunctionPrefixP :: Parser Range
createFunctionPrefixP = do
s <- Tok.createP
optional Tok.temporaryP
e <- Tok.functionP
return $ s <> e
createFunctionP :: Parser Range
createFunctionP = do
s <- createFunctionPrefixP
e <- P.many1 Tok.notSemicolonP
return $ s <> last e
dropFunctionPrefixP :: Parser Range
dropFunctionPrefixP = do
s <- Tok.dropP
optional Tok.temporaryP
e <- Tok.functionP
return $ s <> e
dropFunctionP :: Parser Range
dropFunctionP = do
s <- dropFunctionPrefixP
e <- P.many1 Tok.notSemicolonP
return $ s <> last e
alterTableSetLocationP :: Parser (AlterTableSetLocation RawNames Range)
alterTableSetLocationP = do
s <- Tok.alterP
_ <- Tok.tableP
table <- tableNameP
_ <- Tok.setP
loc <- locationP
let alterTableSetLocationInfo = s <> getInfo loc
alterTableSetLocationTable = table
alterTableSetLocationLocation = loc
return AlterTableSetLocation{..}
alterTableSetTblPropertiesP :: Parser Range
alterTableSetTblPropertiesP = do
s <- Tok.alterP
_ <- Tok.tableP
_ <- tableNameP
_ <- Tok.setP
_ <- Tok.tblPropertiesP
_ <- Tok.openP
_ <- (Tok.stringP >> Tok.equalP >> Tok.stringP) `sepBy1` Tok.commaP
e <- Tok.closeP
return $ s <> e
alterPartitionP :: Parser (HiveStatement RawNames Range)
alterPartitionP = do
s <- Tok.alterP
_ <- Tok.tableP
tableName <- tableNameP
choice $
[ do
_ <- Tok.partitionP
(items, _) <- staticPartitionSpecP
_ <- Tok.setP
location <- locationP
pure $ HiveAlterPartitionSetLocationStmt $ AlterPartitionSetLocation (s <> getInfo location) tableName items location
, HiveUnhandledStatement . (s <>) <$> (addP <|> dropP)
]
where
addP :: Parser Range
addP = do
_ <- Tok.addP
_ <- ifNotExistsP
let partitionLocationP = do
_ <- Tok.partitionP
(_, e) <- staticPartitionSpecP
option e (getInfo <$> locationP)
last <$> P.many1 partitionLocationP
dropP :: Parser Range
dropP = do
_ <- Tok.dropP
optional $ ifExistsP
(_, e) <- last <$> P.many1 (Tok.partitionP >> staticPartitionSpecP)
consumeOrderedOptions e $
[ Tok.ignoreP >> Tok.protectionP
, Tok.purgeP
]
setP :: Parser (SetProperty Range)
setP = do
s <- Tok.setP
option (PrintProperties s "") $ choice $
[ Tok.minusP >> Tok.keywordP "v" >> pure (PrintProperties s "-v")
, do
(name, pe) <- Tok.propertyNameP
choice $
[ do
_ <- Tok.equalP
(setConfigValue, e) <- Tok.propertyValuePartP
let details = SetPropertyDetails (s <> e) name setConfigValue
pure (SetProperty details)
, pure (PrintProperties (s <> pe) name)
]
]
reloadFunctionP :: Parser Range
reloadFunctionP = do
s <- Tok.reloadP
e <- Tok.functionP
return $ s <> e
insertBehaviorHelper :: InsertBehavior Range ->
Maybe (TablePartition) ->
InsertBehavior Range
insertBehaviorHelper (InsertOverwrite a) (Just partition) = InsertOverwritePartition a partition
insertBehaviorHelper (InsertAppend a) (Just partition) = InsertAppendPartition a partition
insertBehaviorHelper ib _ = ib
insertP :: (QueryPrefix, InvertedFrom) -> Parser (Insert RawNames Range)
insertP (with, farInvertedFrom) = do
r <- Tok.insertP
insertBehaviorTok <- choice
-- T407432 Overhaul Overwrite with Partition support
[ do
overwrite <- Tok.overwriteP
return $ InsertOverwrite overwrite
, do
into <- Tok.intoP
return $ InsertAppend into
]
optional Tok.tableP
insertTable <- tableNameP
tablePartition <- optionMaybe $ do
_ <- Tok.partitionP
partitionSpecP
let insertBehavior = insertBehaviorHelper insertBehaviorTok tablePartition
insertColumns <- optionMaybe $ try $ do
_ <- Tok.openP
let oqColumnNameP = (\ (c, r') -> QColumnName r' Nothing c) <$> Tok.columnNameP
c:cs <- oqColumnNameP `sepBy1` Tok.commaP
_ <- Tok.closeP
pure (c :| cs)
insertValues <- choice
[ do
s <- Tok.valuesP
(e, rows) <- rowsOfValuesP
pure $ InsertExprValues (s <> e) rows
, do
isv <- case farInvertedFrom of
Just _ -> InsertSelectValues <$> querySelectP (with, farInvertedFrom)
Nothing -> InsertSelectValues <$> queryP (with, noInversion) -- INSERT .. FROM .. SELECT is not permitted
pure $ isv
]
let insertInfo = r <> (getInfo insertValues)
pure Insert{..}
where
valueP :: Parser (DefaultExpr RawNames Range)
valueP = do
value <- constantP
let r = getInfo value
pure $ ExprValue $ ConstantExpr r value
rowOfValuesP = do
s <- Tok.openP
x:xs <- valueP `sepBy1` Tok.commaP
e <- Tok.closeP
pure $ (s <> e, x :| xs)
rowsOfValuesP = do
rows <- rowOfValuesP `sepBy1` Tok.commaP
let infos = map fst rows
r:rs = map snd rows
pure $ (head infos <> last infos, r :| rs)
loadDataInPathP :: Parser (Insert RawNames Range)
loadDataInPathP = do
s <- Tok.loadP
_ <- Tok.dataP
optional Tok.localP
_ <- Tok.inPathP
(path, r) <- Tok.stringP
maybeOverwrite <- optionMaybe Tok.overwriteP
into <- Tok.intoP
_ <- Tok.tableP
table <- tableNameP
partitions <- optionMaybe $ do
_ <- Tok.partitionP
snd <$> staticPartitionSpecP
let e = maybe (getInfo table) id partitions
insertInfo = s <> e
behaviorTok = case maybeOverwrite of
Nothing -> InsertAppend into
Just overwrite -> InsertOverwrite overwrite
insertBehavior = insertBehaviorHelper behaviorTok (void partitions)
insertTable = table
insertColumns = Nothing
insertValues = InsertDataFromFile r path
pure Insert{..}
deleteP :: Parser (Delete RawNames Range)
deleteP = do
r <- Tok.deleteP
_ <- Tok.fromP
table <- tableNameP
maybeExpr <- optionMaybe $ do
_ <- Tok.whereP
local (introduceAliases $ tableNameToTableAlias table) exprP
let r' = case maybeExpr of
Nothing -> getInfo table
Just expr -> getInfo expr
info = r <> r'
pure $ Delete info table maybeExpr
truncateP :: Parser (Truncate RawNames Range)
truncateP = do
s <- Tok.truncateP
_ <- Tok.tableP
table <- tableNameP
pure $ Truncate (s <> getInfo table) table
type QueryPrefix = Query RawNames Range -> Query RawNames Range
emptyPrefix :: QueryPrefix
emptyPrefix = id
withP :: Parser QueryPrefix
withP = do
r <- Tok.withP
withs <- cteP `sepBy1` Tok.commaP
return $ \ query ->
let r' = sconcat $ r :| getInfo query : map cteInfo withs
in QueryWith r' withs query
where
cteP = do
alias <- tableAliasP
columns <- option []
$ P.between Tok.openP Tok.closeP $ columnAliasP `sepBy1` Tok.commaP
_ <- Tok.asP
(query, r') <- do
_ <- Tok.openP
invertedFrom <- invertedFromP
q <- queryP (emptyPrefix, invertedFrom) -- a query may not have more than 1 WITH clause.
r' <- Tok.closeP
return (q, r')
return $ CTE (getInfo alias <> r') alias columns query
-- parses just a SELECT, consuming no UNIONs
-- i.e. it returns only QuerySelects
querySelectP :: (QueryPrefix, InvertedFrom) -> Parser (Query RawNames Range)
querySelectP (with, invertedFrom) = queryPHelper with invertedFrom False
-- parses SELECTs and UNIONs
-- i.e. it returns QuerySelects and QueryUnions
queryP :: (QueryPrefix, InvertedFrom) -> Parser (Query RawNames Range)
queryP (with, invertedFrom) = queryPHelper with invertedFrom True
queryPHelper :: QueryPrefix -> InvertedFrom -> Bool -> Parser (Query RawNames Range)
queryPHelper with invertedFrom unionsPermitted = do
-- The invertedFrom, if supplied, will only be applied to the first SELECT.
-- If invertedFrom is Nothing, then it is assumed the first SELECT has no inversion.
firstSelect <- onlySelectP invertedFrom
query <- if unionsPermitted
then do
maybeUnion <- optionMaybe unionP
case maybeUnion of
Nothing -> return firstSelect
Just union -> do
let subsequentSelectP = do
nextInvertedFrom <- invertedFromP
onlySelectP nextInvertedFrom
subsequentSelects <- subsequentSelectP `chainl1` unionP
return $ union firstSelect subsequentSelects
else return firstSelect
order <- option id orderP
optional selectClusterP
limit <- option id limitP
return $ with $ limit $ order query
where
onlySelectP invertedFrom' = do
select <- selectP invertedFrom'
return $ QuerySelect (selectInfo select) select
unionP = do
r <- Tok.unionP
distinct <- option (Distinct True) distinctP
return $ QueryUnion r distinct Unused
orderP = do
(r, orders) <- orderTopLevelP
return $ \ query -> QueryOrder (getInfo query <> r) orders query
limitP = do
r <- Tok.limitP
Tok.numberP >>= \ (v, r') ->
let limit = Limit (r <> r') v
in return $ \ query -> QueryLimit (getInfo query <> r') limit query
distinctP :: Parser Distinct
distinctP = choice $
[ Tok.allP >> return (Distinct False)
, Tok.distinctP >> return (Distinct True)
]
explainP :: Parser (Statement Hive RawNames Range)
explainP = do
s <- Tok.explainP
stmt <- choice
[ InsertStmt <$> insertP (emptyPrefix, noInversion)
, DeleteStmt <$> deleteP
, QueryStmt <$> queryP (emptyPrefix, noInversion)
]
pure $ ExplainStmt (s <> getInfo stmt) stmt
tableAliasP :: Parser (TableAlias Range)
tableAliasP = do
(name, r) <- Tok.tableNameP
makeTableAlias r name
columnAliasP :: Parser (ColumnAlias Range)
columnAliasP = do
(name, r) <- Tok.columnNameP
makeColumnAlias r name
createSchemaPrefixP :: Parser Range
createSchemaPrefixP = do
s <- Tok.createP
e <- Tok.schemaP <|> Tok.databaseP
return $ s <> e
ifNotExistsP :: Parser (Maybe Range)
ifNotExistsP = optionMaybe $ do
s' <- Tok.ifP
_ <- Tok.notP
e' <- Tok.existsP
pure $ s' <> e'
commentP :: Parser Range
commentP = do
s <- Tok.commentP
(_, e) <- Tok.stringP
return $ s <> e
locationP :: Parser (Location Range)
locationP = do
s <- Tok.locationP
(loc, e) <- Tok.stringP
return $ HDFSPath (s <> e) loc
createSchemaP :: Parser (CreateSchema RawNames Range)
createSchemaP = do
s <- createSchemaPrefixP
createSchemaIfNotExists <- ifNotExistsP
(name, r) <- Tok.schemaNameP
let createSchemaName = mkNormalSchema name r
e <- consumeOrderedOptions r $
[ commentP
, getInfo <$> locationP
, dbPropertiesP
]
let createSchemaInfo = s <> e
return $ CreateSchema{..}
where
dbPropertiesP = do
s <- Tok.withP
_ <-Tok.dbPropertiesP
_ <- Tok.openP
_ <- propertyP `sepBy1` Tok.commaP
e <- Tok.closeP
return $ s <> e
createViewPrefixP :: Parser Range
createViewPrefixP = do
s <- Tok.createP
e <- Tok.viewP
return $ s <> e
createViewP :: Parser (CreateView RawNames Range)
createViewP = do
s <- createViewPrefixP
let createViewPersistence = Persistent
createViewIfNotExists <- ifNotExistsP
createViewName <- tableNameP
createViewColumns <- optionMaybe $ do
_ <- Tok.openP
c:cs <- flip sepBy1 Tok.commaP $ do
col <- unqualifiedColumnNameP
_ <- commentP
return col
_ <- Tok.closeP
return (c:|cs)
optional commentP
optional $ do
_ <- Tok.tblPropertiesP
_ <- Tok.openP
_ <- (Tok.stringP >> Tok.equalP >> Tok.stringP) `sepBy1` Tok.commaP
Tok.closeP
_ <- Tok.asP
createViewQuery <- querySelectP (emptyPrefix, noInversion)
let createViewInfo = s <> getInfo createViewQuery
pure CreateView{..}
data CreateTablePrefix r a = CreateTablePrefix
{ createTablePrefixInfo :: a
, createTablePrefixPersistence :: Persistence a
, createTablePrefixExternality :: Externality a
, createTablePrefixIfNotExists :: Maybe a
, createTablePrefixName :: CreateTableName r a
}
deriving instance ConstrainSNames Eq r a => Eq (CreateTablePrefix r a)
deriving instance ConstrainSNames Show r a => Show (CreateTablePrefix r a)
deriving instance ConstrainSASNames Functor r => Functor (CreateTablePrefix r)
deriving instance ConstrainSASNames Foldable r => Foldable (CreateTablePrefix r)
deriving instance ConstrainSASNames Traversable r => Traversable (CreateTablePrefix r)
createTablePrefixP :: Parser (CreateTablePrefix RawNames Range)
createTablePrefixP = do
s <- Tok.createP
createTablePrefixPersistence <- option Persistent $ Temporary <$> Tok.temporaryP
createTablePrefixExternality <- option Internal (External <$> Tok.externalP)
_ <- Tok.tableP
createTablePrefixIfNotExists <- ifNotExistsP
createTablePrefixName <- tableNameP
let createTablePrefixInfo = s <> getInfo createTablePrefixName
return CreateTablePrefix{..}
createTableP :: Parser (CreateTable Hive RawNames Range)
createTableP = choice
[ do
_ <- try $ P.lookAhead $ createTablePrefixP >> Tok.likeP
createTableLikeP
, createTableStandardP
]
createTableLikeP :: Parser (CreateTable Hive RawNames Range)
createTableLikeP = do
CreateTablePrefix{..} <- createTablePrefixP
let s = createTablePrefixInfo
createTablePersistence = createTablePrefixPersistence
createTableExternality = createTablePrefixExternality
createTableIfNotExists = createTablePrefixIfNotExists
createTableName = createTablePrefixName
_ <- Tok.likeP
table <- tableNameP
let e = getInfo table
e' <- option e $ choice $
[ getInfo <$> locationP
, storedAsP
]
let createTableInfo = s <> e'
createTableDefinition = TableLike (s <> e) table
createTableExtra = Nothing
return CreateTable{..}
propertyP :: Parser (HiveMetadataProperty Range)
propertyP = do
(k, s) <- Tok.stringP
_ <- Tok.equalP
(v, e) <- Tok.stringP
return $ HiveMetadataProperty (s <> e) k v
storedAsP :: Parser Range
storedAsP = do
s <- Tok.storedP
_ <- Tok.asP
e <- choice
[ Tok.orcP
, Tok.sequenceFileP
, Tok.textFileP
, Tok.rcFileP
, Tok.parquetP
, Tok.avroP
, do
s' <- Tok.inputFormatP
_ <- Tok.stringP
_ <- Tok.outputFormatP
(_, e') <- Tok.stringP
return (s' <> e')
]
return $ s <> e
createTableStandardP :: Parser (CreateTable Hive RawNames Range)
createTableStandardP = do
CreateTablePrefix{..} <- createTablePrefixP
let s = createTablePrefixInfo
createTablePersistence = createTablePrefixPersistence
createTableExternality = createTablePrefixExternality
createTableIfNotExists = createTablePrefixIfNotExists
createTableName = createTablePrefixName
tableDefColumns <- optionMaybe createTableColumnsP
let e1 = maybe s getInfo tableDefColumns
e2 <- consumeOrderedOptions e1 $
[ commentP
, partitionedByP
, clusteredByP
, rowFormatP
, storedAsP
, getInfo <$> locationP
]
tblProperties <- option Nothing (Just <$> tblPropertiesP)
createTableDefinition <- case tableDefColumns of
Just definition -> return definition
Nothing -> choice
[ createTableAsP
, createTableNoColumnInfoP e2
]
let e3 = getInfo createTableDefinition
e4 = fromMaybe e2 (hiveMetadataPropertiesInfo <$> tblProperties)
createTableExtra =
Just HiveCreateTableExtra
{ hiveCreateTableExtraInfo = e3 <> e4
, hiveCreateTableExtraTableProperties = tblProperties
}
createTableInfo = s <> e1 <> e2 <> e3 <> e4
pure CreateTable{..}
where
columnDefinitionP = do
(name, s) <- Tok.columnNameP
columnDefinitionType <- dataTypeP
optional commentP
let columnDefinitionInfo = s <> getInfo columnDefinitionType
columnDefinitionExtra = Nothing -- TODO
columnDefinitionNull = Nothing
columnDefinitionDefault = Nothing
columnDefinitionName = QColumnName s None name
pure ColumnDefinition{..}
partitionedByP = do
_ <- Tok.partitionedP
_ <- Tok.byP
_ <- Tok.openP
_ <- columnDefinitionP `sepBy1` Tok.commaP
Tok.closeP
clusteredByP = do
_ <- Tok.clusteredP
_ <- Tok.byP
_ <- Tok.openP
_ <- Tok.columnNameP `sepBy1` Tok.commaP
_ <- Tok.closeP
optional $ do
_ <- Tok.sortedP
_ <- Tok.byP
_ <- Tok.openP
_ <- (Tok.columnNameP >> optional directionP) `sepBy1` Tok.commaP
Tok.closeP
_ <- Tok.intoP
_ <- Tok.numberP
Tok.bucketsP
serdeP = do
_ <- Tok.serdeP
e <- snd <$> Tok.stringP
option e $ do
_ <- Tok.withP