forked from hpcc-systems/HPCC-Platform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_sqlService.cpp
2066 lines (1716 loc) · 75.3 KB
/
ws_sqlService.cpp
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
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2014 HPCC Systems.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#include "ws_sqlService.hpp"
#include "exception_util.hpp"
#include "jconfig.hpp"
void CwssqlEx::init(IPropertyTree *_cfg, const char *_process, const char *_service)
{
cfg = _cfg;
try
{
ECLFunctions::init();
}
catch (...)
{
throw MakeStringException(-1, "ws_sqlEx: Problem initiating ECLFunctions structure");
}
setWsSqlBuildVersion(hpccBuildInfo.buildTag);
}
bool CwssqlEx::onEcho(IEspContext &context, IEspEchoRequest &req, IEspEchoResponse &resp)
{
resp.setResponse(req.getRequest());
return true;
}
bool CwssqlEx::onGetDBMetaData(IEspContext &context, IEspGetDBMetaDataRequest &req, IEspGetDBMetaDataResponse &resp)
{
context.ensureFeatureAccess(WSSQLACCESS, SecAccess_Read, -1, "WsSQL::GetDBMetaData: Permission denied.");
bool success = false;
StringBuffer username;
context.getUserID(username);
const char* passwd = context.queryPassword();
bool includetables = req.getIncludeTables();
if (includetables)
{
Owned<HPCCFileCache> tmpHPCCFileCache = HPCCFileCache::createFileCache(username.str(), passwd);
tmpHPCCFileCache->populateTablesResponse(resp, req.getTableFilter(), context.getClientVersion() >= 3.06);
resp.setTableCount(resp.getTables().length());
}
bool includeStoredProcs = req.getIncludeStoredProcedures();
if (includeStoredProcs)
{
const char * querysetfilter = req.getQuerySet();
#ifdef _CONTAINERIZED
ESPLOG(LogNormal, "WsSQL: getting containerTargetClusters...");
Owned<IStringIterator> targets = config::getContainerTargets(nullptr, nullptr);
#else
ESPLOG(LogNormal, "WsSQL-legacy: getting targetClusters...");
Owned<IStringIterator> targets = getTargetClusters(nullptr, nullptr);
#endif
IArrayOf<IEspHPCCQuerySet> pquerysets;
SCMStringBuffer target;
ForEach(*targets)
{
const char *setname = targets->str(target).str();
if ( querysetfilter && *querysetfilter && stricmp(setname, querysetfilter)!=0)
continue;
Owned<IEspHPCCQuerySet> pqset = createHPCCQuerySet();
pqset->setName(setname);
pquerysets.append(*pqset.getLink());
Owned<IPropertyTree> settree = getQueryRegistry(setname, true);
if (settree == NULL)
continue;
IArrayOf<IEspPublishedQuery> queries;
Owned<IPropertyTreeIterator> iter = settree->getElements("Query");
ForEach(*iter)
{
const char * id = iter->query().queryProp("@id");
const char * qname = iter->query().queryProp("@name");
const char * wuid = iter->query().queryProp("@wuid");
if (qname && *qname && wuid && *wuid)
{
StringBuffer resp;
Owned<IEspPublishedQuery> pubQuery = createPublishedQuery();
pubQuery->setName(qname);
pubQuery->setId(id);
pubQuery->setWuid(wuid);
pubQuery->setSuspended(iter->query().getPropBool("@suspended"));
Owned<IEspQuerySignature> querysignature = createQuerySignature();
IArrayOf<IEspHPCCColumn> inparams;
IArrayOf<IEspOutputDataset> resultsets;
WsEclWuInfo wsinfo(wuid, setname, qname, username, passwd);
Owned<IResultSetFactory> resultSetFactory(getResultSetFactory(username, passwd));
//Each published query can have multiple results (datasets)
IConstWUResultIterator &results = wsinfo.ensureWorkUnit()->getResults();
ForEach(results)
{
Owned<IEspOutputDataset> outputdataset = createOutputDataset();
IArrayOf<IEspHPCCColumn> outparams;
IConstWUResult &result = results.query();
SCMStringBuffer resultName;
result.getResultName(resultName);
outputdataset->setName(resultName.s.str());
Owned<IResultSetMetaData> meta = resultSetFactory->createResultSetMeta(&result);
//Each result dataset can have multiple result columns
int columncount = meta->getColumnCount();
for (int i = 0; i < columncount; i++)
{
Owned<IEspHPCCColumn> col = createHPCCColumn();
SCMStringBuffer columnLabel;
meta->getColumnLabel(columnLabel,i);
col->setName(columnLabel.str());
SCMStringBuffer eclType;
meta->getColumnEclType(eclType, i);
col->setType(eclType.str());
outparams.append(*col.getLink());
}
outputdataset->setOutParams(outparams);
resultsets.append(*outputdataset.getLink());
}
//Each query can have multiple input parameters
IConstWUResultIterator &vars = wsinfo.ensureWorkUnit()->getVariables();
ForEach(vars)
{
Owned<IEspHPCCColumn> col = createHPCCColumn();
IConstWUResult &var = vars.query();
SCMStringBuffer varname;
var.getResultName(varname);
col->setName(varname.str());
Owned<IResultSetMetaData> meta = resultSetFactory->createResultSetMeta(&var);
SCMStringBuffer eclType;
meta->getColumnEclType(eclType, 0);
col->setType(eclType.str());
inparams.append(*col.getLink());
}
querysignature->setInParams(inparams);
querysignature->setResultSets(resultsets);
pubQuery->setSignature(*querysignature.getLink());
queries.append(*pubQuery.getLink());
}
}
pqset->setQuerySetQueries(queries);
IArrayOf<IEspQuerySetAliasMap> aliases;
Owned<IPropertyTreeIterator> aliasiter = settree->getElements("Alias");
ForEach(*aliasiter)
{
Owned<IEspQuerySetAliasMap> alias = createQuerySetAliasMap();
const char * qname;
const char * id;
id = aliasiter->query().queryProp("@id");
qname = aliasiter->query().queryProp("@name");
alias->setId(id);
alias->setName(qname);
aliases.append(*alias.getLink());
}
pqset->setQuerySetAliases(aliases);
}
resp.setQuerySets(pquerysets);
}
bool includeTargetClusters = req.getIncludeTargetClusters();
if (includeTargetClusters)
{
try
{
StringArray dfuclusters;
#ifdef _CONTAINERIZED
ESPLOG(LogNormal, "WsSQL: getting containerTargetClusters...");
Owned<IStringIterator> targets = config::getContainerTargets(nullptr, nullptr);
SCMStringBuffer target;
ForEach(*targets)
{
const char *setname = targets->str(target).str();
ESPLOG(LogNormal, "WsSQL: found containerTargetClusters: %s", setname);
dfuclusters.append(setname);
}
#else
ESPLOG(LogNormal, "WsSQL-legacy: getting getTargetClusterList...");
CTpWrapper topologyWrapper;
IArrayOf<IEspTpLogicalCluster> clusters;
topologyWrapper.getTargetClusterList(clusters, req.getClusterType(), NULL);
ForEachItemIn(k, clusters)
{
IEspTpLogicalCluster& cluster = clusters.item(k);
dfuclusters.append(cluster.getName());
}
#endif
resp.setClusterNames(dfuclusters);
}
catch(IException* e)
{
FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
}
}
return success;
}
bool CwssqlEx::onGetDBSystemInfo(IEspContext &context, IEspGetDBSystemInfoRequest &req, IEspGetDBSystemInfoResponse &resp)
{
bool success = false;
resp.setName("HPCC Systems");
context.ensureFeatureAccess(WSSQLACCESS, SecAccess_Access, -1, "WsSQL::GetDBSystemInfo: Permission denied.");
try
{
const char* build_ver = getBuildVersion();
if (build_ver && *build_ver)
{
StringBuffer project;
StringBuffer major;
StringBuffer minor;
StringBuffer point;
StringBuffer maturity;
//community_4.1.0-trunk1-Debug[heads/wssql-0-gb9e351-dirty
const char * tail = build_ver;
while (tail && *tail != '_')
project.append(*tail++);
tail++;
while (tail && *tail != '.')
major.append(*tail++);
resp.setMajor(major.str());
tail++;
while (tail && *tail != '.')
minor.append(*tail++);
resp.setMinor(minor.str());
tail++;
while (tail && *tail != '-')
point.append(*tail++);
resp.setPoint(point.str());
if (req.getIncludeAll())
{
resp.setFullVersion(build_ver);
resp.setProject(project.str());
tail++;
while (tail && *tail != '-' && *tail != '[')
maturity.append(*tail++);
resp.setMaturity(maturity.str());
}
}
const char* wssqlbuild_ver = getWsSqlBuildVersion();
if (wssqlbuild_ver && *wssqlbuild_ver)
{
StringBuffer major;
StringBuffer minor;
StringBuffer point;
StringBuffer maturity;
//5.4.0-trunk1-Debug[heads/wssql-0-gb9e351-dirty
const char * tail = wssqlbuild_ver;
while (tail && *tail != '.')
major.append(*tail++);
resp.setWsSQLMajor(major.str());
tail++;
while (tail && *tail != '.')
minor.append(*tail++);
resp.setWsSQLMinor(minor.str());
tail++;
while (tail && *tail != '-')
point.append(*tail++);
resp.setWsSQLPoint(point.str());
if (req.getIncludeAll())
{
resp.setWsSQLFullVersion(wssqlbuild_ver);
tail++;
while (tail && *tail != '-' && *tail != '[')
maturity.append(*tail++);
resp.setWsSQLMaturity(maturity.str());
}
success = true;
}
}
catch (...)
{
IERRLOG("Error Parsing HPCC and/or WsSQL Version string.");
}
return success;
}
void printTree(pANTLR3_BASE_TREE t, int indent)
{
pANTLR3_BASE_TREE child = NULL;
int children = 0;
char * tokenText = NULL;
string ind = "";
int i = 0;
if ( t != NULL )
{
children = t->getChildCount(t);
for ( i = 0; i < indent; i++ )
ind += " ";
for ( i = 0; i < children; i++ )
{
pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)(t->getChild(t, i));
ANTLR3_UINT32 tokenType = child->getType(child);
tokenText = (char *)child->toString(child)->chars;
fprintf(stderr, "%s%s\n", ind.c_str(), tokenText);
if (tokenType == ANTLR3_TOKEN_EOF)
break;
printTree(child, indent+1);
}
}
}
void myDisplayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer,pANTLR3_UINT8 * tokenNames)
{
StringBuffer errorMessage;
pANTLR3_PARSER parser = NULL;
pANTLR3_TREE_PARSER tparser = NULL;
pANTLR3_INT_STREAM is;
pANTLR3_STRING ttext;
pANTLR3_EXCEPTION ex;
pANTLR3_COMMON_TOKEN theToken;
pANTLR3_BASE_TREE theBaseTree;
pANTLR3_COMMON_TREE theCommonTree;
ex = recognizer->state->exception;
ttext = nullptr;
errorMessage.append("Error while parsing");
if (ex)
{
errorMessage.appendf(": ANTLR Error %d : %s", ex->type, (pANTLR3_UINT8)(ex->message));
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
{
parser = (pANTLR3_PARSER) (recognizer->super);
is = parser->tstream->istream;
theToken = (pANTLR3_COMMON_TOKEN)(ex->token);
if (theToken)
{
ttext = theToken->toString(theToken);
if (theToken->type == ANTLR3_TOKEN_EOF)
errorMessage.append(", at <EOF>");
else
errorMessage.appendf("\n Near %s\n ", ttext == nullptr ? (pANTLR3_UINT8)"<no text for the token>" : ttext->chars);
}
break;
}
case ANTLR3_TYPE_TREE_PARSER:
{
tparser = (pANTLR3_TREE_PARSER) (recognizer->super);
is = tparser->ctnstream->tnstream->istream;
theBaseTree = (pANTLR3_BASE_TREE)(ex->token);
if (theBaseTree)
{
ttext = theBaseTree->toStringTree(theBaseTree);
theCommonTree = (pANTLR3_COMMON_TREE) theBaseTree->super;
if (theCommonTree != nullptr)
theToken = (pANTLR3_COMMON_TOKEN) theBaseTree->getToken(theBaseTree);
errorMessage.appendf( ", at offset %d", theBaseTree->getCharPositionInLine(theBaseTree));
errorMessage.appendf( ", near %s", ttext->chars);
}
break;
}
default:
//errorMessage.appendf("Base recognizer function displayRecognitionError called by unknown parser type - provide override for this function\n");
return;
break;
}
switch (ex->type)
{
case ANTLR3_UNWANTED_TOKEN_EXCEPTION:
{
// Indicates that the recognizer was fed a token which seesm to be
// spurious input. We can detect this when the token that follows
// this unwanted token would normally be part of the syntactically
// correct stream. Then we can see that the token we are looking at
// is just something that should not be there and throw this exception.
//
if (tokenNames == nullptr)
{
errorMessage.appendf( " : Extraneous input...");
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
errorMessage.appendf(" : Extraneous input - expected <EOF>\n");
else
errorMessage.appendf(" : Extraneous input - expected %s ...\n", tokenNames[ex->expecting]);
}
break;
}
case ANTLR3_MISSING_TOKEN_EXCEPTION:
{
// Indicates that the recognizer detected that the token we just
// hit would be valid syntactically if preceeded by a particular
// token. Perhaps a missing ';' at line end or a missing ',' in an
// expression list, and such like.
//
if (tokenNames == nullptr)
{
errorMessage.appendf( " : Missing token (%d)...\n", ex->expecting);
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
errorMessage.appendf( " : Missing <EOF>\n");
else
errorMessage.appendf( " : Missing %s \n", tokenNames[ex->expecting]);
}
break;
}
case ANTLR3_RECOGNITION_EXCEPTION:
{
// Indicates that the recognizer received a token
// in the input that was not predicted. This is the basic exception type
// from which all others are derived. So we assume it was a syntax error.
// You may get this if there are not more tokens and more are needed
// to complete a parse for instance.
//
errorMessage.appendf( " : syntax error...\n");
break;
}
case ANTLR3_MISMATCHED_TOKEN_EXCEPTION:
{
// We were expecting to see one thing and got another. This is the
// most common error if we coudl not detect a missing or unwanted token.
// Here you can spend your efforts to
// derive more useful error messages based on the expected
// token set and the last token and so on. The error following
// bitmaps do a good job of reducing the set that we were looking
// for down to something small. Knowing what you are parsing may be
// able to allow you to be even more specific about an error.
//
if (tokenNames == NULL)
{
errorMessage.appendf(" : syntax error...\n");
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
errorMessage.appendf(" : expected <EOF>\n");
else
errorMessage.appendf(" : expected %s ...\n", tokenNames[ex->expecting]);
}
break;
}
case ANTLR3_NO_VIABLE_ALT_EXCEPTION:
{
// We could not pick any alt decision from the input given
// so god knows what happened - however when you examine your grammar,
// you should. It means that at the point where the current token occurred
// that the DFA indicates nowhere to go from here.
//
errorMessage.appendf(" : cannot match to any predicted input...\n");
break;
}
case ANTLR3_MISMATCHED_SET_EXCEPTION:
{
ANTLR3_UINT32 count;
ANTLR3_UINT32 bit;
ANTLR3_UINT32 size;
ANTLR3_UINT32 numbits;
pANTLR3_BITSET errBits;
// This means we were able to deal with one of a set of
// possible tokens at this point, but we did not see any
// member of that set.
errorMessage.appendf( " : unexpected input...\n expected one of : ");
// What tokens could we have accepted at this point in the parse?
count = 0;
errBits = antlr3BitsetLoad (ex->expectingSet);
numbits = errBits->numBits (errBits);
size = errBits->size (errBits);
if (size > 0)
{
// However many tokens we could have dealt with here, it is usually
// not useful to print ALL of the set here. I arbitrarily chose 8
// here, but you should do whatever makes sense for you of course.
// No token number 0, so look for bit 1 and on.
for (bit = 1; bit < numbits && count < 8 && count < size; bit++)
{
if (tokenNames[bit])
{
errorMessage.appendf( "%s%s", count > 0 ? ", " : "", tokenNames[bit]);
count++;
}
}
errorMessage.appendf( "\n");
}
else
{
errorMessage.appendf( "Unknown parsing error.\n");
}
break;
}
case ANTLR3_EARLY_EXIT_EXCEPTION:
{
// We entered a loop requiring a number of token sequences
// but found a token that ended that sequence earlier than
// we should have done.
errorMessage.appendf( " : missing elements...\n");
break;
}
default:
{
// We don't handle any other exceptions here, but you can
// if you wish. If we get an exception that hits this point
// then we are just going to report what we know about the
// token.
//
errorMessage.appendf( " : unrecognized syntax...\n");
break;
}
}
}
throw MakeStringException(-1, "%s", errorMessage.str());
}
HPCCSQLTreeWalker * CwssqlEx::parseSQL(IEspContext &context, StringBuffer & sqltext, bool attemptParameterization)
{
int limit = -1;
pHPCCSQLLexer hpccSqlLexer = NULL;
pANTLR3_COMMON_TOKEN_STREAM sqlTokens = NULL;
pHPCCSQLParser hpccSqlParser = NULL;
pANTLR3_BASE_TREE sqlAST = NULL;
pANTLR3_INPUT_STREAM sqlInputStream = NULL;
Owned<HPCCSQLTreeWalker> hpccSqlTreeWalker;
try
{
if (sqltext.length() <= 0)
throw MakeStringException(-1, "Empty SQL String detected.");
pANTLR3_UINT8 input_string = (pANTLR3_UINT8)sqltext.str();
pANTLR3_INPUT_STREAM sqlinputstream = antlr3StringStreamNew(input_string,
ANTLR3_ENC_8BIT,
sqltext.length(),
(pANTLR3_UINT8)"SQL INPUT");
pHPCCSQLLexer hpccsqllexer = HPCCSQLLexerNew(sqlinputstream);
//hpccSqlLexer->pLexer->rec->displayRecognitionError = myDisplayRecognitionError;
//ANTLR3_UINT32 lexerrors = hpccsqllexer->pLexer->rec->getNumberOfSyntaxErrors(hpccsqllexer->pLexer->rec);
//if (lexerrors > 0)
// throw MakeStringException(-1, "HPCCSQL Lexer reported %d error(s), request aborted.", lexerrors);
pANTLR3_COMMON_TOKEN_STREAM sqltokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(hpccsqllexer));
if (sqltokens == NULL)
{
throw MakeStringException(-1, "Out of memory trying to allocate ANTLR HPCCSQLParser token stream.");
}
pHPCCSQLParser hpccsqlparser = HPCCSQLParserNew(sqltokens);
//#if not defined(_DEBUG)
hpccsqlparser->pParser->rec->displayRecognitionError = myDisplayRecognitionError;
//#endif
pANTLR3_BASE_TREE sqlAST = (hpccsqlparser->root_statement(hpccsqlparser)).tree;
ANTLR3_UINT32 parserrors = hpccsqlparser->pParser->rec->getNumberOfSyntaxErrors(hpccsqlparser->pParser->rec);
if (parserrors > 0)
throw MakeStringException(-1, "HPCCSQL Parser reported %d error(s), request aborted.", parserrors);
#if defined(_DEBUG)
printTree(sqlAST, 0);
#endif
hpccSqlTreeWalker.setown(new HPCCSQLTreeWalker(sqlAST, context, attemptParameterization));
hpccsqlparser->free(hpccsqlparser);
sqltokens->free(sqltokens);
hpccsqllexer->free(hpccsqllexer);
sqlinputstream->free(sqlinputstream);
}
catch(IException* e)
{
try
{
if (hpccSqlParser)
hpccSqlParser->free(hpccSqlParser);
if (sqlTokens)
sqlTokens->free(sqlTokens);
if (hpccSqlLexer)
hpccSqlLexer->free(hpccSqlLexer);
if (sqlInputStream)
sqlInputStream->free(sqlInputStream);
hpccSqlTreeWalker.clear();
}
catch (...)
{
IERRLOG("!!! Unable to free HPCCSQL parser/lexer objects.");
}
//All IExceptions get bubbled up
throw e;
}
catch(...)
{
try
{
if (hpccSqlParser)
hpccSqlParser->free(hpccSqlParser);
if (sqlTokens)
sqlTokens->free(sqlTokens);
if (hpccSqlLexer)
hpccSqlLexer->free(hpccSqlLexer);
if (sqlInputStream)
sqlInputStream->free(sqlInputStream);
hpccSqlTreeWalker.clear();
}
catch (...)
{
IERRLOG("!!! Unable to free HPCCSQL parser/lexer objects.");
}
//All other unexpected exceptions are reported as generic ecl generation error.
throw MakeStringException(-1, "Error generating ECL code.");
}
return hpccSqlTreeWalker.getLink();
}
bool CwssqlEx::getWUResult(IEspContext &context, const char * wuid, StringBuffer &result, unsigned start, unsigned count, int sequence, const char * dsname, const char * schemaname)
{
OwnedActiveSpanScope resultSpanScope(queryThreadedActiveSpan()->createInternalSpan("get_wu_result"));
try
{
if (wuid && *wuid)
{
Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
if (!cw)
throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid);
SCMStringBuffer stateDesc;
switch (cw->getState())
{
case WUStateCompleted:
case WUStateFailed:
case WUStateUnknown:
case WUStateCompiled:
{
StringBufferAdaptor resultXML(result);
Owned<IResultSetFactory> factory = getResultSetFactory(context.queryUserId(), context.queryPassword());
Owned<INewResultSet> nr = factory->createNewResultSet(wuid, sequence, NULL);
if (nr.get())
{
OwnedActiveSpanScope xmlSpanScope(queryThreadedActiveSpan()->createInternalSpan("get_result_xml"));
try
{
getResultXml(resultXML, nr.get(), dsname, start, count, schemaname);
}
catch(IException* e)
{
xmlSpanScope->recordException(e);
throw;
}
}
else
return false;
break;
}
default:
break;
}
return true;
}
}
catch(IException* e)
{
resultSpanScope->recordException(e);
throw;
}
return false;
}
bool CwssqlEx::onSetRelatedIndexes(IEspContext &context, IEspSetRelatedIndexesRequest &req, IEspSetRelatedIndexesResponse &resp)
{
context.ensureFeatureAccess(WSSQLACCESS, SecAccess_Write, -1, "WsSQL::SetRelatedIndexes: Permission denied.");
StringBuffer username;
context.getUserID(username);
const char* passwd = context.queryPassword();
IArrayOf<IConstRelatedIndexSet>& relatedindexSets = req.getRelatedIndexSets();
if (relatedindexSets.length() == 0)
throw MakeStringException(-1, "WsSQL::SetRelatedIndexes empty request detected.");
ForEachItemIn(relatedindexsetindex, relatedindexSets)
{
IConstRelatedIndexSet &relatedIndexSet = relatedindexSets.item(relatedindexsetindex);
const char * fileName = relatedIndexSet.getFileName();
if (!fileName || !*fileName)
throw MakeStringException(-1, "WsSQL::SetRelatedIndexes error: Empty file name detected.");
StringArray& indexHints = relatedIndexSet.getIndexes();
int indexHintsCount = indexHints.length();
if (indexHintsCount > 0)
{
Owned<HPCCFile> file = HPCCFileCache::fetchHpccFileByName(fileName,username.str(), passwd, false, false);
if (!file)
throw MakeStringException(-1, "WsSQL::SetRelatedIndexes error: could not find file: %s.", fileName);
StringBuffer description;
StringBuffer currentIndexes;
description = file->getDescription();
HPCCFile::parseOutRelatedIndexes(description, currentIndexes);
description.append("\nXDBC:RelIndexes=[");
for(int indexHintIndex = 0; indexHintIndex < indexHintsCount; indexHintIndex++)
{
description.appendf("%s%c", indexHints.item(indexHintIndex), (indexHintIndex < indexHintsCount-1 ? ';' : ' '));
}
description.append("]\n");
HPCCFileCache::updateHpccFileDescription(fileName, username, passwd, description.str());
file->setDescription(description.str());
}
}
resp.setRelatedIndexSets(relatedindexSets);
return true;
}
bool CwssqlEx::onGetRelatedIndexes(IEspContext &context, IEspGetRelatedIndexesRequest &req, IEspGetRelatedIndexesResponse &resp)
{
try
{
context.ensureFeatureAccess(WSSQLACCESS, SecAccess_Read, -1, "WsSQL::GetRelatedIndexes: Permission denied.");
StringArray& filenames = req.getFileNames();
if (filenames.length() == 0)
throw MakeStringException(-1, "WsSQL::GetRelatedIndexes error: No filenames detected");
StringBuffer username;
context.getUserID(username);
const char* passwd = context.queryPassword();
IArrayOf<IEspRelatedIndexSet> relatedindexSets;
ForEachItemIn(filenameindex, filenames)
{
const char * fileName = filenames.item(filenameindex);
Owned<HPCCFile> file = HPCCFileCache::fetchHpccFileByName(fileName,username.str(), passwd, false, false);
if (file)
{
StringArray indexHints;
file->getRelatedIndexes(indexHints);
Owned<IEspRelatedIndexSet> relatedIndexSet = createRelatedIndexSet("", "");
relatedIndexSet->setFileName(fileName);
relatedIndexSet->setIndexes(indexHints);
relatedindexSets.append(*relatedIndexSet.getLink());
}
}
resp.setRelatedIndexSets(relatedindexSets);
}
catch(IException* e)
{
FORWARDEXCEPTION(context, e, -1);
}
return true;
}
void CwssqlEx::processMultipleClusterOption(StringArray & clusters, const char * targetcluster, StringBuffer & hashoptions)
{
int clusterscount = clusters.length();
if (clusterscount > 0)
{
hashoptions.appendf("\n#OPTION('AllowedClusters', '%s", targetcluster);
ForEachItemIn(i,clusters)
{
validateTargetName(clusters.item(i));
hashoptions.appendf(",%s", clusters.item(i));
}
hashoptions.append("');\n#OPTION('AllowAutoQueueSwitch', TRUE);\n\n");
}
}
bool CwssqlEx::onExecuteSQL(IEspContext &context, IEspExecuteSQLRequest &req, IEspExecuteSQLResponse &resp)
{
OwnedActiveSpanScope exSpanScope(queryThreadedActiveSpan()->createInternalSpan("on_execute_sql"));
try
{
context.ensureFeatureAccess(WSSQLACCESS, SecAccess_Write, -1, "WsSQL::ExecuteSQL: Permission denied.");
double version = context.getClientVersion();
StringBuffer sqltext;
StringBuffer ecltext;
StringBuffer username;
context.getUserID(username);
const char* passwd = context.queryPassword();
sqltext.set(req.getSqlText());
if (sqltext.length() <= 0)
throw MakeStringException(1,"Empty SQL request.");
const char * cluster = req.getTargetCluster();
StringBuffer hashoptions;
if (version > 3.03)
{
StringArray & alternates = req.getAlternateClusters();
if (alternates.length() > 0)
processMultipleClusterOption(alternates, cluster, hashoptions);
}
SCMStringBuffer compiledwuid;
int resultLimit = req.getResultLimit();
__int64 resultWindowStart = req.getResultWindowStart();
__int64 resultWindowCount = req.getResultWindowCount();
if (resultWindowStart < 0 || resultWindowCount <0 )
throw MakeStringException(-1,"Invalid result window value");
bool clonable = false;
bool cacheeligible = (version > 3.04 ) ? !req.getIgnoreCache() : true;
Owned<HPCCSQLTreeWalker> parsedSQL;
ESPLOG(LogNormal, "WsSQL: Parsing sql query...");
parsedSQL.setown(parseSQL(context, sqltext));
ESPLOG(LogNormal, "WsSQL: Finished parsing sql query...");
SQLQueryType querytype = parsedSQL->getSqlType();
if (querytype == SQLTypeCall)
{
if (strlen(parsedSQL->getQuerySetName())==0)
{
if (strlen(req.getTargetQuerySet())==0)
throw MakeStringException(-1,"Missing Target QuerySet.");
else
parsedSQL->setQuerySetName(req.getTargetQuerySet());
}
ESPLOG(LogMax, "WsSQL: Processing call query...");
WsEclWuInfo wsinfo("", parsedSQL->getQuerySetName(), parsedSQL->getStoredProcName(), username.str(), passwd);
compiledwuid.set(wsinfo.ensureWuid());
clonable = true;
}
else if (querytype == SQLTypeCreateAndLoad)
{
cacheeligible = false;
}
StringBuffer xmlparams;
StringBuffer normalizedSQL(parsedSQL->getNormalizedSQL());
normalizedSQL.append(" | --TC=").append(cluster);
if (username.length() > 0)
normalizedSQL.append("--USER=").append(username.str());
if (resultLimit > 0)
normalizedSQL.append("--HARDLIMIT=").append(resultLimit);
const char * wuusername = req.getUserName();
if (wuusername && *wuusername)
normalizedSQL.append("--WUOWN=").append(wuusername);
if (hashoptions.length()>0)
normalizedSQL.append("--HO=").append(hashoptions.str());
if (compiledwuid.length() != 0)
normalizedSQL.append("--PWUID=").append(compiledwuid.str());
ESPLOG(LogMax, "WsSQL: getWorkUnitFactory...");
Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
ESPLOG(LogMax, "WsSQL: checking query cache...");
if(cacheeligible && getCachedQuery(normalizedSQL.str(), compiledwuid.s))
{
ESPLOG(LogMax, "WsSQL: cache hit opening wuid %s...", compiledwuid.str());
Owned<IConstWorkUnit> cw = factory->openWorkUnit(compiledwuid.str(), false);
if (!cw)//cache hit but unavailable WU
{
ESPLOG(LogMax, "WsSQL: cache hit but unavailable WU...");
removeQueryFromCache(normalizedSQL.str());
compiledwuid.clear();
}
else
clonable = true;
}
if (compiledwuid.length()==0)
{
{
validateTargetName(cluster);
if (querytype == SQLTypeCreateAndLoad)
clonable = false;
{
OwnedActiveSpanScope eclGenSpanScope(queryThreadedActiveSpan()->createInternalSpan("generate_ecl"));
try
{
ECLEngine::generateECL(parsedSQL, ecltext);
if (hashoptions.length() > 0)
ecltext.insert(0, hashoptions.str());
}
catch(IException* e)
{
eclGenSpanScope->recordException(e);
throw;
}
}
if (isEmpty(ecltext))
throw MakeStringException(1,"Could not generate ECL from SQL.");
ecltext.appendf(EMBEDDEDSQLQUERYCOMMENT, sqltext.str(), normalizedSQL.str());
#if defined _DEBUG
fprintf(stderr, "GENERATED ECL:\n%s\n", ecltext.str());
#endif
ESPLOG(LogMax, "WsSQL: creating new WU...");
NewWsWorkunit wu(context);
compiledwuid.set(wu->queryWuid());
wu->setJobName("WsSQL Job");
wu.setQueryText(ecltext.str());
wu->setClusterName(cluster);
if (clonable)
wu->setCloneable(true);