This repository was archived by the owner on Jun 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathSqlCmd.cpp
More file actions
4101 lines (3470 loc) · 124 KB
/
SqlCmd.cpp
File metadata and controls
4101 lines (3470 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//
// @@@ END COPYRIGHT @@@
//
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: SqlCmd.C
* RCS: $Id: SqlCmd.cpp,v 1.1 2007/10/09 19:40:29 Exp $
* Description:
*
*
* Created: 4/15/95
* Modified: $ $Date: 2007/10/09 19:40:29 $ (GMT)
* Language: C++
* Status: $State: Exp $
*
*
*
*
*****************************************************************************
*/
#include "Platform.h"
#include <ctype.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <unistd.h>
#include "ComAnsiNamePart.h"
#include "ComGuardianFileNameParts.h"
#include "ComASSERT.h"
#include "Formatter.h"
#include "SqlciStats.h"
#include "NAString.h"
#include "ErrorMessage.h" // NAWriteConsole
#include "IntervalType.h" // NAType::convertTypeToText etc.
#include "SqlciError.h"
#include "SQLCLIdev.h"
#include "sqlcmd.h"
#include "sql_id.h"
#include "ComSqlId.h"
#include "ComRtUtils.h"
#define CAT_MAX_HEADING_LEN 132
#define CM_GUA_ENAME_LEN 36
#include "dfs2rec.h"
#include "ex_error.h"
#include "str.h"
#include "stringBuf.h"
#include "charinfo.h"
#include "NLSConversion.h"
#include "nawstring.h"
#include "SqlciList_templ.h"
#include "ComCextMisc.h"
#include "ComCextdecs.h"
#include "ComQueue.h"
#include "ExExeUtilCli.h"
extern SqlciEnv * global_sqlci_env; // global sqlci_env for break key handling purposes.
extern ComDiagsArea sqlci_DA;
extern NAHeap sqlci_Heap;
extern BOOL WINAPI CtrlHandler (DWORD signalType);
const Lng32 BREAK_ERROR = -999;
const Int32 MAX_MSGTEXT_LEN = 4096;
const Int32 MAX_OTHERBUF_LEN = ComAnsiNamePart::MAX_IDENTIFIER_EXT_LEN+1+1;
// These should come from a SQL Message Text (immudefs) file! ##
#define UNLOADED_MESSAGE "--- %ld row(s) unloaded."
#define LOADED_MESSAGE "--- %ld row(s) loaded."
#define SELECTED_MESSAGE "--- %d row(s) selected."
#define SELECTED_BUT_MESSAGE "--- %d row(s) selected (but none displayed)."
#define SELECTED_FIRST_ROW_DISPLAY_MESSAGE "--- %d row(s) selected (and first row displayed)."
#define INSERTED_MESSAGE "--- %ld row(s) inserted."
#define UPDATED_MESSAGE "--- %ld row(s) updated."
#define DELETED_MESSAGE "--- %ld row(s) deleted."
#define OP_COMPLETE_MESSAGE "--- SQL operation complete."
#define OP_COMPLETED_ERRORS "--- SQL operation failed with errors."
#define OP_COMPLETED_WARNINGS "--- SQL operation completed with warnings."
#define PREPARED_MESSAGE "--- SQL command prepared."
#define LISTCOUNT_MESSAGE " LIST_COUNT was reached."
#define CATAPI "CREATE TANDEM_CAT_REQUEST&"
// These static variables and global functions, in conjunction with their
// callers, have as one goal to nicely format blank lines for sqlci output
// (output to screen and to logfile -- which should be identical):
// We want single blank lines to enhance legibility; we never want two
// blank non-data lines in a row.
static Lng32 worstcode;
static NABoolean lastLineWasABlank;
// remember the number of rows affected by an SQL statement
// before resetting the diagnostics info
static Int64 rowsAffected;
#define Succ_or_Warn (retcode == SQL_Success || (retcode >= 0 && retcode != SQL_Eof))
void HandleCLIErrorInit()
{
ComASSERT(SQL_Error < SQL_Warning && SQL_Warning < SQL_Eof);
worstcode = SQL_Eof;
lastLineWasABlank = FALSE;
}
void SqlCmd::clearCLIDiagnostics()
{
SQLSTMT_ID dummy_stmt;
SQLMODULE_ID module;
init_SQLMODULE_ID(&module);
init_SQLSTMT_ID(&dummy_stmt,
SQLCLI_CURRENT_VERSION,
stmt_handle,
&module
);
SQL_EXEC_ClearDiagnostics(&dummy_stmt);
}
volatile Int32 breakReceived = 0;
void HandleCLIError(SQLSTMT_ID *stmt, Lng32 &error, SqlciEnv *sqlci_env,
NABoolean displayErr, NABoolean * isEOD,
Int32 prepcode)
{
Int32 diagsCondCount = 0;
if (error == 100)
diagsCondCount = getDiagsCondCount(stmt);
// Get Warnings only when there are 2 or more conditions.
// One condition is for the error code 100 and the others are the actual warnings
NABoolean getWarningsWithEOF = (diagsCondCount > 1);
HandleCLIError(error, sqlci_env, displayErr, isEOD, prepcode, getWarningsWithEOF);
}
void HandleCLIError(Lng32 &error, SqlciEnv *sqlci_env,
NABoolean displayErr, NABoolean * isEOD,
Int32 prepcode, NABoolean getWarningsWithEOF)
{
if (error == 100)
{
if (isEOD != NULL)
*isEOD = 1;
if (! getWarningsWithEOF) {
SqlCmd::clearCLIDiagnostics();
return;
}
}
if (isEOD)
*isEOD = 0;
if (error == BREAK_ERROR)
{
DWORD dwd = 0;
CtrlHandler(dwd);
}
else
#define MXCI_DONOTISSUE_ERRMSGS -1
if (error != 0)
{
Logfile *log = sqlci_env->get_logfile();
if (error != SQL_Eof)
worstcode = error;
SQLMODULE_ID module;
init_SQLMODULE_ID(&module);
SQLDESC_ID cond_desc;
init_SQLDESC_ID(&cond_desc, SQLCLI_CURRENT_VERSION, desc_handle,
&module);
// Get the total number of conditions and # of rows affected
Int32 total_conds = 0;
Int64 rows_affected = 0;
SQL_EXEC_AllocDesc(&cond_desc,2);
SQL_EXEC_SetDescItem(&cond_desc, 1, SQLDESC_TYPE_FS,
REC_BIN32_SIGNED, 0);
SQL_EXEC_SetDescItem(&cond_desc, 1, SQLDESC_VAR_PTR,
(Long) &total_conds, 0);
SQL_EXEC_SetDescItem(&cond_desc, 2, SQLDESC_TYPE_FS,
REC_BIN64_SIGNED, 0);
SQL_EXEC_SetDescItem(&cond_desc, 2, SQLDESC_VAR_PTR,
(Long) &rows_affected, 0);
Lng32 stmt_items[2];
stmt_items[0] = SQLDIAG_NUMBER;
stmt_items[1] = SQLDIAG_ROW_COUNT;
SQL_EXEC_GetDiagnosticsStmtInfo(stmt_items, &cond_desc);
// remember # of rows affected in a global variable
rowsAffected += rows_affected;
// Attach msgtext variable with the output descriptor
SQLMODULE_ID module2;
init_SQLMODULE_ID(&module2);
SQLDESC_ID msg_desc;
init_SQLDESC_ID(&msg_desc, SQLCLI_CURRENT_VERSION, desc_handle,
&module2);
SQLDIAG_COND_INFO_ITEM cond_info_item[4];
short SQLCode;
char msgtext[MAX_MSGTEXT_LEN];
char otherbuf[MAX_OTHERBUF_LEN];
NABoolean getCondInfo = log->isVerbose();
NABoolean showSQLSTATE = !!getenv("SHOW_SQLSTATE");
short num_output_entries = 2;
if (showSQLSTATE)
num_output_entries = 3;
// total_conds can be 1 (Executor error) or 2 (Compile error, the second
// sqlcode being 8822 "Unable to prepare the stmt").
Lng32 specialErr =
(ABS(error) == ABS(sqlci_env->specialError()) && total_conds <= 2) ?
ABS(error) : 0;
if (specialErr)
{
ComASSERT(total_conds > 0);
total_conds = 1;
getCondInfo = TRUE;
showSQLSTATE = FALSE;
num_output_entries = 3;
lastLineWasABlank = TRUE;
}
SQL_EXEC_AllocDesc(&msg_desc, num_output_entries);
// Set up to receive Message text.
SQL_EXEC_SetDescItem(&msg_desc, 1, SQLDESC_TYPE_FS,
REC_BYTE_F_ASCII, 0);
SQL_EXEC_SetDescItem(&msg_desc, 1, SQLDESC_LENGTH,
MAX_MSGTEXT_LEN, 0);
SQL_EXEC_SetDescItem(&msg_desc, 1, SQLDESC_VAR_PTR,
(Long) &msgtext, 0);
cond_info_item[0].item_id = SQLDIAG_MSG_TEXT;
cond_info_item[0].cond_number_desc_entry = 1;
// set up to receive sqlcode
SQL_EXEC_SetDescItem(&msg_desc, 2, SQLDESC_TYPE_FS,
REC_BIN16_SIGNED, 0);
SQL_EXEC_SetDescItem(&msg_desc, 2, SQLDESC_VAR_PTR,
(Long) &SQLCode, 0);
cond_info_item[1].item_id = SQLDIAG_SQLCODE;
cond_info_item[1].cond_number_desc_entry = 2;
//
if (showSQLSTATE || specialErr)
{
SQL_EXEC_SetDescItem(&msg_desc, 3, SQLDESC_TYPE_FS,
REC_BYTE_F_ASCII, 0);
SQL_EXEC_SetDescItem(&msg_desc, 3, SQLDESC_LENGTH,
MAX_OTHERBUF_LEN, 0);
SQL_EXEC_SetDescItem(&msg_desc, 3, SQLDESC_VAR_PTR,
(Long) &otherbuf, 0);
cond_info_item[2].item_id = SQLDIAG_RET_SQLSTATE;
cond_info_item[2].cond_number_desc_entry = 3;
if (specialErr)
{
// "msgtext" is really cat-name; "otherbuf" will contain schema-name.
cond_info_item[0].item_id = SQLDIAG_CATALOG_NAME;
cond_info_item[2].item_id = SQLDIAG_SCHEMA_NAME;
}
}
Int32 curr_cond = 1;
SQL_EXEC_SetDescEntryCount(&cond_desc, 1);
SQL_EXEC_SetDescItem(&cond_desc, 1, SQLDESC_VAR_PTR,
(Long) &curr_cond, 0);
if (!(error == SQL_Success))
{
if (total_conds)
{
// Start with a blank line -- cf. NADumpDiags(GetErrorMessage.C)
if (!lastLineWasABlank)
{
SQL_EXEC_GetDiagnosticsCondInfo(cond_info_item,
&cond_desc, &msg_desc);
if ((SQLCode != 100) &&
((SQLCode < 0) || (SQLCode > 0 && getCondInfo )))
{
if (displayErr) // || (SQLCode > 0))
{
log->WriteAll("");
// The error text(s) we are about to emit
// each have two lines,
// the second of which is a blank.
lastLineWasABlank = TRUE;
}
}
}
}
// Loop through total number of conditions, and print out
// the error message text. This loop should emulate
// NADumpDiags (GetErrorMessage.C) as much as possible.
for (; curr_cond <= total_conds; curr_cond++)
{
SQL_EXEC_GetDiagnosticsCondInfo(cond_info_item,
&cond_desc, &msg_desc);
// do not output no data warning 100.
// do not output warning message if it's printed during preparation
// on Linux.
if ((SQLCode == 100) || (SQLCode == prepcode))
{
if ((isEOD) && (SQLCode == 100)) // 100: SQL_Eof
*isEOD = 1;
continue;
}
//if 'set warnings off' set
if ((SQLCode < 0) || (SQLCode > 0 && getCondInfo ))
{
if (msgtext[0] == '\0') // an empty message
{
strcpy(msgtext, "*** ERROR[15000] Unexpected Error: Message text missing");
}
CharInfo::CharSet TCS = sqlci_env->getTerminalCharset();
CharInfo::CharSet ISOMAPCS = sqlci_env->getIsoMappingCharset();
if(
TCS != CharInfo::UTF8/*msgcharset*/
)
{
charBuf cbuf((unsigned char*)msgtext, strlen(msgtext));
NAWcharBuf* wcbuf = 0;
Int32 errorcode = 0;
wcbuf = csetToUnicode(cbuf, 0, wcbuf, CharInfo::UTF8/*msgcharset*/, errorcode);
NAString* tempstr;
if (errorcode == 0){
tempstr = unicodeToChar(wcbuf->data(),wcbuf->getStrLen(), TCS, NULL, TRUE);
TrimNAStringSpace(*tempstr, FALSE, TRUE); // trim trailing blanks
strcpy(msgtext, tempstr->data());
}
}
if (specialErr && sqlci_env->specialHandler())
{
sqlci_env->specialHandler()(sqlci_env, error, msgtext, otherbuf);
}
else
{
// ## Kludge for "error" 20109. Internationalization problem...!
const char *outtext = msgtext;
size_t pfxl = strlen("*** ERROR[20109] ");
#if defined(USE_WCHAR)
if (wcsncmp(msgtext, L"*** ERROR[20109] ", pfxl) == 0)
#else
if (strncmp(msgtext, "*** ERROR[20109] ", pfxl) == 0)
#endif
outtext += pfxl;
#ifdef USE_WCHAR
if (showSQLSTATE)
{
$$do something here$$
}
if (displayErr)// || (SQLCode > 0))
log->WriteAll((NAWchar*)outtext, NAWstrlen((NAWchar*)outtext));
#else // not wide, so don't use NAWxxx
//
// Rather than returning from the first executable statements in
// HandleCLIError, a couple of breakReceived conditional checks are
// performed to suppress the outputting of error messages after a
// break key was encountered. This allows MXCI to have more control
// of issuing (future break processing enhancements) warning and
// error messages during break key processing.
if (! breakReceived)
{
if (showSQLSTATE)
{
if (displayErr)// || (SQLCode > 0))
{
log->WriteAllWithoutEOL("*** SQLSTATE: ");
log->WriteAll(otherbuf);
}
}
if (displayErr)// || (SQLCode > 0))
log->WriteAll(outtext);
if (sqlci_env->specialError() ==
MXCI_DONOTISSUE_ERRMSGS)
{
sqlci_env->resetSpecialError();
curr_cond = curr_cond + total_conds;
}
} // breakReceived
#endif
// write out a blank line after error message
if (! breakReceived)
{
if (displayErr)// || (SQLCode > 0))
log->WriteAll("");
} // breakReceived
}
}
} // for
}
if (displayErr)// || (SQLCode > 0))
SqlCmd::clearCLIDiagnostics();
SQL_EXEC_DeallocDesc(&cond_desc);
SQL_EXEC_DeallocDesc(&msg_desc);
// delete (cond_desc);
// delete (msg_desc);
} // error != 0
// Check if Ctrl+break occured... nk
if ( sqlci_env->diagsArea().mainSQLCODE() == SQLCI_BREAK_RECEIVED)
error = SQL_Canceled;
} // HandleCLIError
void handleLocalError(ComDiagsArea *diags, SqlciEnv *sqlci_env)
{
Logfile *log = sqlci_env->get_logfile();
// Here the variable worstcode has to be set to SQL_Error in
// case of an error and SQL_Warning in case of a warning.
// which might have been caused due to a param processing error/warning.
// Usually this variable gets set in the HandleCLIError() function,
// when HandleCLIError() is called with a error after a CLI call.
// Soln :10-021203-3433
if (diags->getNumber(DgSqlCode::ERROR_)) {
worstcode = SQL_Error;
}
else if (diags->getNumber(DgSqlCode::WARNING_)) {
worstcode = SQL_Warning;
}
if (!lastLineWasABlank) log->WriteAllWithoutEOL("");
lastLineWasABlank = TRUE;
ostringstream errMsg;
NADumpDiags(errMsg, diags, TRUE/*newline*/, 0, NULL, log->isVerbose(),
sqlci_env->getTerminalCharset());
errMsg << ends;
log->WriteAllWithoutEOL(errMsg.str().c_str());
}
Int64 getRowsAffected(SQLSTMT_ID *stmt)
{
Int32 rc;
rc = SQL_EXEC_GetDiagnosticsStmtInfo2(stmt,
SQLDIAG_ROW_COUNT, &rowsAffected,
NULL, 0, NULL);
if (rc == 0)
return rowsAffected;
else
return -1;
}
Int32 getDiagsCondCount(SQLSTMT_ID *stmt)
{
Int32 rc;
Int32 diagsCondCount;
rc = SQL_EXEC_GetDiagnosticsStmtInfo2(stmt,
SQLDIAG_NUMBER, &diagsCondCount,
NULL, 0, NULL);
if (rc >= 0)
return diagsCondCount;
else
return 0;
}
static char * upshiftStr(char * inStr, char * outStr, UInt32 len)
{
for (UInt32 i = 0; i < len; i++)
{
outStr[i] = toupper(inStr[i]);
}
return outStr;
}
char * SqlCmd::replacePattern(SqlciEnv * sqlci_env, char * str)
{
if (str == NULL)
return NULL;
UInt32 len = strlen(str);
char upperStr[20];
// if SET PATTERN or RESET PATTERN, do not replace pattern.
UInt32 s = 0;
if (len >= strlen("SET PATTERN"))
{
if (strncmp(upshiftStr(str, upperStr, 3), "SET", 3) == 0)
s = 3;
}
else if (len >= strlen("RESET PATTERN"))
{
if (strncmp(upshiftStr(str, upperStr, 5), "RESET", 5) == 0)
s = 5;
}
if (s > 0) // SET or RESET found
{
// skip blanks
while ((s <= len) &&
(str[s] == ' '))
s++;
if (s < len)
{
if ((len - s) >= strlen("PATTERN"))
{
if (strncmp(upshiftStr(&str[s], upperStr, 7), "PATTERN", 7) == 0)
return str;
}
}
}
// preprocess the argument and replace the pattern: <definename >
// (< and > are included) with the value of define/env-var "definename".
enum State { CONSUME_CHAR, QUOTE_SEEN,
LPATTERN_SEEN, RPATTERN_SEEN };
UInt32 outstr_len = 500 + len;
char * outstr = new char[outstr_len];
char * patternText = new char[100];
UInt32 i = 0;
UInt32 j = 0;
UInt32 k = 0;
NABoolean skipChar = FALSE;
NABoolean inSingleQuote = FALSE;
State state = CONSUME_CHAR;
NABoolean patternSeen = FALSE;
while (i <= len)
{
skipChar = TRUE;
switch (state)
{
case CONSUME_CHAR:
if (str[i] == '\'')
{
state = QUOTE_SEEN;
inSingleQuote=TRUE;
}
if (str[i] == '"')
{
state = QUOTE_SEEN;
inSingleQuote = FALSE;
}
else if ((str[i] == '$') && ((i+1) < len) && (str[i+1] == '$'))
{
i+=2;
state = LPATTERN_SEEN;
skipChar = FALSE;
}
break;
case QUOTE_SEEN:
if (str[i] == '\'')
{
// If in a single quote, make sure this quote is the true end
if (inSingleQuote)
{
// If string contains two single quotes, can skip - not the end
if (((i+1) < len) && (str[i+1] == '\''))
{
outstr[k] = str[i]; // skip over quote
i++;
k++;
}
// The quote mark actually signifies the end of the quote
else
state = CONSUME_CHAR;
}
// else: Double quote found, so continue, not the end
}
if (str[i] == '"')
{
// If in a double quote, make sure this quote is the true end
if (!inSingleQuote)
{
//If string contains two double quotes, can skip - not the end
if (((i+1) < len) && (str[i+1] == '\''))
{
outstr[k] = str[i]; // skip over quote
i++;
k++;
}
// The double quote mark signifies the end of the quote
else
state = CONSUME_CHAR;
}
// else: single quote found, so continue - not the end
}
break;
case LPATTERN_SEEN:
patternSeen = TRUE;
if ((str[i] == '$') && ((i+1) < len) && (str[i+1] == '$'))
{
i+=2;
state = RPATTERN_SEEN;
}
else
{
patternText[j++] = str[i];
i++;
}
skipChar = FALSE;
break;
case RPATTERN_SEEN:
// find value of pattern and replace
patternText[j] = '\0';
Param * pattern
= sqlci_env->get_patternlist()->get(patternText);
char * patternValue = NULL;
if (pattern == NULL)
{
// if an env var is present with this name, use it
patternValue = getenv(patternText);
}
else
{
patternValue = pattern->getValue();
}
if (patternValue)
{
strncpy((char *)&outstr[k], patternValue, strlen(patternValue));
k += strlen(patternValue);
//special note: the total length of outstr should be smaller
//than outstr_len. if the condition below becomes false,
//increase outstr_len at the top of the function
ComASSERT(k <= outstr_len);
}
j = 0;
skipChar = FALSE;
state = CONSUME_CHAR;
break;
}
if (skipChar)
{
outstr[k] = str[i];
i++;
k++;
}
} // while
outstr[k] = '\0';
delete [] patternText;
if (NOT patternSeen)
{
delete [] outstr;
return str;
}
else
return outstr;
}
SqlCmd::SqlCmd(const sql_cmd_type cmd_type_, const char * argument_)
: SqlciNode(SqlciNode::SQL_CMD_TYPE),
cmd_type(cmd_type_)
{
if (argument_)
{
sql_stmt = new char[strlen(argument_)+1];
strcpy(sql_stmt, argument_);
}
else
sql_stmt = 0;
}
SqlCmd::~SqlCmd()
{
if (sql_stmt)
delete [] sql_stmt;
}
short SqlCmd::showShape(SqlciEnv *sqlci_env, const char *query)
{
if ((!query) ||
(strncmp(query, "SHOWSHAPE", 9) == 0))
return 0;
char * buf = new char[strlen("SHOWSHAPE ") + strlen(query) + 1];
strcpy(buf, "SHOWSHAPE ");
strcat(buf, query);
DML dml(buf, DML_SHOWSHAPE_TYPE, "__SQLCI_DML_SHOWSHAPE__");
short retcode = dml.process(sqlci_env);
delete buf;
if (retcode)
return retcode;
return 0;
}
short SqlCmd::updateRepos(SqlciEnv * sqlci_env, SQLSTMT_ID * stmt, char * queryId)
{
Lng32 retcode = 0;
// get explain fragment.
Lng32 explainDataLen = 50000; // start with 50K bytes
Int32 retExplainLen = 0;
char * explainData = new char[explainDataLen + 1];
retcode = SQL_EXEC_GetExplainData(stmt,
explainData, explainDataLen+1,
&retExplainLen
);
if (retcode == -CLI_GENCODE_BUFFER_TOO_SMALL)
{
delete explainData;
explainDataLen = retExplainLen;
explainData = new char[explainDataLen + 1];
SqlCmd::clearCLIDiagnostics();
retcode = SQL_EXEC_GetExplainData(stmt,
explainData, explainDataLen+1,
&retExplainLen
);
}
if (retcode < 0)
{
delete explainData;
HandleCLIError(retcode, sqlci_env);
return retcode;
}
explainDataLen = retExplainLen;
// update repository
ExeCliInterface cliInterface;
SQL_EXEC_SetParserFlagsForExSqlComp_Internal(0x20000);
char * queryBuf = new char[4000];
Int64 ts = NA_JulianTimestamp();
str_sprintf(queryBuf, "insert into %s.\"%s\".%s (instance_id, tenant_id, host_id, exec_start_utc_ts, query_id, explain_plan) values (0,0,0, CONVERTTIMESTAMP(%ld), '%s', '' ) ",
TRAFODION_SYSCAT_LIT, SEABASE_REPOS_SCHEMA, REPOS_METRIC_QUERY_TABLE,
ts, queryId);
retcode = cliInterface.executeImmediatePrepare(queryBuf);
if (retcode < 0)
{
HandleCLIError(retcode, sqlci_env);
goto label_return;
}
retcode = cliInterface.clearExecFetchClose(explainData, explainDataLen);
if (retcode < 0)
{
HandleCLIError(retcode, sqlci_env);
goto label_return;
}
retcode = SQL_EXEC_StoreExplainData(
&ts, queryId,
explainData, explainDataLen);
if (retcode < 0)
{
HandleCLIError(retcode, sqlci_env);
goto label_return;
}
label_return:
SQL_EXEC_ResetParserFlagsForExSqlComp_Internal(0x20000);
delete explainData;
delete queryBuf;
return retcode;
}
short SqlCmd::cleanupAfterError(Lng32 retcode,
SqlciEnv * sqlci_env,
SQLSTMT_ID * stmt,
SQLDESC_ID *sql_src,
SQLDESC_ID *output_desc,
SQLDESC_ID *input_desc,
NABoolean resetLastExecStmt)
{
// if retcode < 0, it is an error.
// Clean up and return.
if (retcode < 0)
{
SQL_EXEC_DeallocDesc(input_desc);
SQL_EXEC_DeallocDesc(output_desc);
SQL_EXEC_DeallocDesc(sql_src);
SQL_EXEC_DeallocStmt(stmt);
if (global_sqlci_env->getDeallocateStmt())
global_sqlci_env->resetDeallocateStmt();
delete (SQLMODULE_ID*)output_desc->module;
delete (SQLMODULE_ID*)input_desc->module;
delete (SQLMODULE_ID*)sql_src->module;
delete (SQLMODULE_ID*)stmt->module;
delete input_desc;
delete output_desc;
delete sql_src;
delete [] stmt->identifier;
delete stmt;
if (resetLastExecStmt)
sqlci_env->lastExecutedStmt() = NULL;
SqlCmd::clearCLIDiagnostics();
return (short)SQL_Error;
}
return 0;
}
short SqlCmd::do_prepare(SqlciEnv * sqlci_env,
PrepStmt * prep_stmt,
char * sqlStmt,
NABoolean resetLastExecStmt,
Lng32 rsIndex,
Int32 *prepcode,
Lng32 *statisticsType)
{
if (sqlci_env->showShape())
{
showShape(sqlci_env, sqlStmt);
}
SQLSTMT_ID *stmt = new SQLSTMT_ID;
SQLDESC_ID *sql_src = new SQLDESC_ID;
SQLDESC_ID *output_desc = new SQLDESC_ID;
SQLDESC_ID *input_desc = new SQLDESC_ID;
memset (stmt, 0, sizeof(SQLSTMT_ID));
memset (sql_src, 0, sizeof(SQLDESC_ID));
memset (output_desc, 0, sizeof(SQLDESC_ID));
memset (input_desc, 0, sizeof(SQLDESC_ID));
SQLMODULE_ID * module = new SQLMODULE_ID;
stmt->module = module;
init_SQLMODULE_ID(module);
module = new SQLMODULE_ID;
sql_src->module = module;
init_SQLMODULE_ID(module);
module = new SQLMODULE_ID;
input_desc->module = module;
init_SQLMODULE_ID(module);
module = new SQLMODULE_ID;
output_desc->module = module;
init_SQLMODULE_ID(module);
SqlCmd::clearCLIDiagnostics();
Lng32 retcode = 0;
// replace any user defined pattern in the sql query
// char * str = replacePattern(sqlci_env, sqlStmt);
char * str = sqlStmt;
prep_stmt->set(str, NULL, stmt, 0, NULL, 0, NULL);
char *stmtName = prep_stmt->getStmtName();
// Bookkeeping for stored procedure result sets
NABoolean isResultSet = (rsIndex > 0 ? TRUE : FALSE);
NABoolean skipPrepare = isResultSet;
if (!isResultSet)
HandleCLIErrorInit();
/* allocate a statement */
stmt->version = SQLCLI_CURRENT_VERSION;
stmt->name_mode = stmt_name;
char * identifier = new char[strlen(stmtName) + 1];
stmt->identifier_len = strlen(stmtName);
str_cpy_all(identifier,stmtName, stmt->identifier_len);
identifier[stmt->identifier_len] = 0;
stmt->identifier = identifier;
stmt->handle = 0;
if (!isResultSet)
{
retcode = SQL_EXEC_AllocStmt(stmt, 0);
HandleCLIError(retcode, sqlci_env);
}
else
{
SQLSTMT_ID callStmt;
SQLMODULE_ID module;
init_SQLMODULE_ID(&module);
init_SQLSTMT_ID(&callStmt, SQLCLI_CURRENT_VERSION, stmt_name, &module);
char *callStmtName = sqlci_env->lastExecutedStmt()->getStmtName();
callStmt.identifier_len = (Lng32) strlen(callStmtName);
callStmt.identifier = callStmtName;
retcode = SQL_EXEC_AllocStmtForRS(&callStmt, rsIndex, stmt);
// Statement allocation may have failed simply because the RS
// index is out of range or because the parent statement is not a
// CALL. That can be tolerated and in response we are going to
// return early.
if (retcode == -8909 || // Parent stmt is not a CALL
retcode == -8916) // RS index out of range
{
SqlCmd::clearCLIDiagnostics();
}
else
{
HandleCLIError(retcode, sqlci_env);
}
}
// Statement allocation failed. If errors needed to be reported to
// the console, that has already happened. We can cleanup and
// return.
if (retcode < 0)
{
return cleanupAfterError(retcode, sqlci_env, stmt, sql_src,
output_desc, input_desc, resetLastExecStmt);
}
if (!isResultSet)
{
global_sqlci_env->setDeallocateStmt();
global_sqlci_env->setLastAllcatedStmt(stmt);
}
/* allocate a descriptor which will hold the sql statement source */
sql_src->version = SQLCLI_CURRENT_VERSION;
sql_src->name_mode = desc_handle;
sql_src->identifier = 0;
sql_src->identifier_len = 0;
sql_src->handle = 0;
retcode = SQL_EXEC_AllocDesc(sql_src, 1);
HandleCLIError(retcode, sqlci_env);
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_TYPE_FS,
REC_BYTE_V_ANSI, 0);
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_CHAR_SET_NAM,
0, (char*)CharInfo::getCharSetName(sqlci_env->getTerminalCharset()));
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_VAR_PTR, (Long)str, 0);
HandleCLIError(retcode, sqlci_env);
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_LENGTH, strlen(str) + 1, 0);