/
pass1.cpp
2924 lines (2409 loc) · 87.8 KB
/
pass1.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
/*
* PROGRAM: Dynamic SQL runtime support
* MODULE: pass1.cpp
* DESCRIPTION: First-pass compiler for statement trees.
*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* 2001.5.26: Claudio Valderrama: field names should be skimmed from trailing
*
* 2001.5.26: Claudio Valderrama: COMPUTED fields will be skipped if a dummy
* "insert into tbl values(...)" sentence is issued.
*
* 2001.5.26: Claudio Valderrama: field names should be skimmed from trailing
* blanks to allow reliable comparisons in pass1_field. Same for table and
* and index names in plans.
*
* 2001.5.29: Claudio Valderrama: handle DROP VIEW case in pass1_statement().
*
* 2001.6.12: Claudio Valderrama: add basic BREAK capability to procedures.
*
* 2001.6.27: Claudio Valderrama: pass1_variable() now gives the name of the
* variable it can't find in the error message.
*
* 2001.6.30: Claudio Valderrama: Enhanced again to provide (line, col), see node.h.
*
* 2001.7.28: John Bellardo: added code to handle nod_limit and associated fields.
*
* 2001.08.14 Claudio Valderrama: fixed crash with trigger and CURRENT OF <cursor> syntax.
*
* 2001.09.10 John Bellardo: fixed gen_rse to attribute skip/first nodes to the parent_rse
* if present instead of the child rse. BUG #451798
*
* 2001.09.26 Claudio Valderrama: ambiguous field names are rejected from now.
*
* 2001.10.01 Claudio Valderrama: check constraints are allowed to have ambiguous field
* names because they use OLD and NEW as aliases of the same table. However, if the
* check constraint has an embedded ambiguous SELECT statement, it won't be detected.
* The code should be revisited if check constraints' before delete triggers are used
* for whatever reason. Currently they are never generated. The code can be improved
* to not report errors for fields between NEW and OLD contexts but complain otherwise.
*
* 2001.10.05 Neil McCalden: validate udf and parameters when comparing select list and
* group by list, to detect invalid SQL statements when grouping by UDFs.
*
* 2001.10.23 Ann Harrison: allow reasonable checking of ambiguous names in unions.
* Remembering, later, that LLS_PUSH expects an object, not an LLS block. Also
* stuck in the code for handling variables in pass1 - it apparently doesn't happen
* because the code returned an uninitialized pointer.
*
* 2001.11.17 Neil McCalden: Add aggregate_in_list procedure to handle cases
* where select statement has aggregate as a parameter to a udf which does
* not have to be in a group by clause.
*
* 2001.11.21 Claudio Valderrama: don't try to detect ambiguity in pass1_field()
* if the field or output procedure parameter has been fully qualified!!!
*
* 2001.11.27 Ann Harrison: Redo the amiguity checking so as to give better
* error messages, return warnings for dialect 1, and simplify.
*
* 2001.11.28 Claudio Valderrama: allow udf arguments to be query parameters.
* Honor the code in the parser that already accepts those parameters.
* This closes SF Bug# 409769.
*
* 2001.11.29 Claudio Valderrama: make the nice new ambiguity checking code do the
* right thing instead of crashing the engine and restore fix from 2001.11.21.
*
* 2001.12.21 Claudio Valderrama: Fix SF Bug #494832 - pass1_variable() should work
* with def_proc, mod_proc, redef_proc, def_trig and mod_trig node types.
*
* 2002.07.30 Arno Brinkman: Added pass1_coalesce, pass1_simple_case, pass1_searched_case
* and PASS1_put_args_on_stack
*
* 2002.08.04 Arno Brinkman: Added ignore_cast as parameter to PASS1_node_match,
* Changed invalid_reference procedure for allow EXTRACT, SUBSTRING, CASE,
* COALESCE and NULLIF functions in GROUP BY and as select_items.
* Removed aggregate_in_list procedure.
*
* 2002.08.07 Dmitry Yemanov: Disabled BREAK statement in triggers
*
* 2002.08.10 Dmitry Yemanov: ALTER VIEW
*
* 2002.09.28 Dmitry Yemanov: Reworked internal_info stuff, enhanced
* exception handling in SPs/triggers,
* implemented ROWS_AFFECTED system variable
*
* 2002.09.29 Arno Brinkman: Adding more checking for aggregate functions
* and adding support for 'linking' from sub-selects to aggregate functions
* which are in an lower level.
* Modified functions pass1_field, pass1_rse, copy_field, PASS1_sort.
* Functions pass1_found_aggregate and pass1_found_field added.
*
* 2002.10.21 Nickolay Samofatov: Added support for explicit pessimistic locks
*
* 2002.10.25 Dmitry Yemanov: Re-allowed plans in triggers
*
* 2002.10.29 Nickolay Samofatov: Added support for savepoints
*
* 2002.12.03 Dmitry Yemanov: Implemented ORDER BY clause in subqueries
*
* 2002.12.18 Dmitry Yemanov: Fixed bug with BREAK and partially implemented
* SQL-compliant labels and LEAVE statement
*
* 2003.01.11 Arno Brinkman: Reworked a lot of functions for bringing back backwards compatibilty
* with sub-selects and aggregates.
*
* 2003.01.14 Dmitry Yemanov: Fixed bug with cursors in triggers
*
* 2003.01.15 Dmitry Yemanov: Added support for parametrized events
*
* 2003.04.05 Dmitry Yemanov: Changed logic of ORDER BY with collations
* (because of the parser change)
*
* 2003.08.14 Arno Brinkman: Added derived table support.
*
* 2003.08.16 Arno Brinkman: Changed ambiguous column name checking.
*
* 2003.10.05 Dmitry Yemanov: Added support for explicit cursors in PSQL.
*
* 2004.01.16 Vlad Horsun: added support for default parameters and
* EXECUTE BLOCK statement
*
* Adriano dos Santos Fernandes
*
*/
#include "firebird.h"
#include <string.h>
#include <stdio.h>
#include "../jrd/ibase.h"
#include "../dsql/dsql.h"
#include "../dsql/Nodes.h"
#include "../dsql/BoolNodes.h"
#include "../dsql/ExprNodes.h"
#include "../jrd/intl.h"
#include "../jrd/blr.h"
#include "../jrd/jrd.h"
#include "../jrd/constants.h"
#include "../jrd/intl_classes.h"
#include "../jrd/RecordSourceNodes.h"
#include "../dsql/DdlNodes.h"
#include "../dsql/StmtNodes.h"
#include "../dsql/ddl_proto.h"
#include "../dsql/errd_proto.h"
#include "../dsql/gen_proto.h"
#include "../dsql/make_proto.h"
#include "../dsql/metd_proto.h"
#include "../dsql/pass1_proto.h"
#include "../dsql/utld_proto.h"
#include "../dsql/DSqlDataTypeUtil.h"
#include "../common/dsc_proto.h"
#include "../jrd/intl_proto.h"
#include "../jrd/jrd_proto.h"
#include "../jrd/thread_proto.h"
#include "../yvalve/why_proto.h"
#include "../jrd/SysFunction.h"
#include "../common/classes/array.h"
#include "../common/classes/auto.h"
#include "../common/utils_proto.h"
#include "../common/config/config.h"
#include "../common/StatusArg.h"
using namespace Jrd;
using namespace Firebird;
static string pass1_alias_concat(const string&, const string&);
static void pass1_expand_contexts(DsqlContextStack& contexts, dsql_ctx* context);
static ValueListNode* pass1_expand_select_list(DsqlCompilerScratch*, ValueListNode*, RecSourceListNode*);
static ValueListNode* pass1_group_by_list(DsqlCompilerScratch*, ValueListNode*, ValueListNode*);
static ValueExprNode* pass1_make_derived_field(thread_db*, DsqlCompilerScratch*, ValueExprNode*);
static RseNode* pass1_rse(DsqlCompilerScratch*, RecordSourceNode*, ValueListNode*, RowsClause*, bool, USHORT);
static RseNode* pass1_rse_impl(DsqlCompilerScratch*, RecordSourceNode*, ValueListNode*, RowsClause*, bool, USHORT);
static ValueListNode* pass1_sel_list(DsqlCompilerScratch*, ValueListNode*);
static RseNode* pass1_union(DsqlCompilerScratch*, UnionSourceNode*, ValueListNode*, RowsClause*, bool, USHORT);
static void pass1_union_auto_cast(DsqlCompilerScratch*, ExprNode*, const dsc&, size_t position);
static void remap_streams_to_parent_context(ExprNode*, dsql_ctx*);
AggregateFinder::AggregateFinder(DsqlCompilerScratch* aDsqlScratch, bool aWindow)
: dsqlScratch(aDsqlScratch),
window(aWindow),
currentLevel(dsqlScratch->scopeLevel),
deepestLevel(0),
ignoreSubSelects(false)
{
}
bool AggregateFinder::find(DsqlCompilerScratch* dsqlScratch, bool window, ExprNode* node)
{
AggregateFinder visitor(dsqlScratch, window);
return visitor.visit(node);
}
bool AggregateFinder::visit(ExprNode* node)
{
return node && node->dsqlAggregateFinder(*this);
}
Aggregate2Finder::Aggregate2Finder(USHORT aCheckScopeLevel, FieldMatchType aMatchType, bool aWindowOnly)
: checkScopeLevel(aCheckScopeLevel),
matchType(aMatchType),
windowOnly(aWindowOnly),
currentScopeLevelEqual(true)
{
}
bool Aggregate2Finder::find(USHORT checkScopeLevel, FieldMatchType matchType, bool windowOnly,
ExprNode* node)
{
Aggregate2Finder visitor(checkScopeLevel, matchType, windowOnly);
return visitor.visit(node);
}
bool Aggregate2Finder::visit(ExprNode* node)
{
return node && node->dsqlAggregate2Finder(*this);
}
FieldFinder::FieldFinder(USHORT aCheckScopeLevel, FieldMatchType aMatchType)
: checkScopeLevel(aCheckScopeLevel),
matchType(aMatchType),
field(false)
{
}
bool FieldFinder::find(USHORT checkScopeLevel, FieldMatchType matchType, ExprNode* node)
{
FieldFinder visitor(checkScopeLevel, matchType);
return visitor.visit(node);
}
bool FieldFinder::visit(ExprNode* node)
{
return node && node->dsqlFieldFinder(*this);
}
InvalidReferenceFinder::InvalidReferenceFinder(const dsql_ctx* aContext, const ValueListNode* aList)
: context(aContext),
list(aList),
insideOwnMap(false),
insideHigherMap(false)
{
DEV_BLKCHK(list, dsql_type_nod);
}
bool InvalidReferenceFinder::find(const dsql_ctx* context, const ValueListNode* list, ExprNode* node)
{
InvalidReferenceFinder visitor(context, list);
return visitor.visit(node);
}
bool InvalidReferenceFinder::visit(ExprNode* node)
{
DEV_BLKCHK(node, dsql_type_nod);
if (!node)
return false;
bool invalid = false;
// ASF: What we do in this function is the verification of all fields/dbkeys (or any parent
// expression involving them) are present in the passed node list.
// That makes valid:
// select n + 0 from table group by n => The n item is present in the list
// select n + 0 from table group by n + 0 => The n + 0 item is present in the list
// And makes invalid:
// select n + 1 from table group by n + 0 => The n + 1 item is not present in the list
if (list)
{
// Check if this node (with ignoring of CASTs) appears also
// in the list of group by. If yes then it's allowed
const NestConst<ValueExprNode>* ptr = list->items.begin();
for (const NestConst<ValueExprNode>* const end = list->items.end(); ptr != end; ++ptr)
{
if (PASS1_node_match(node, *ptr, true))
return false;
}
}
return node->dsqlInvalidReferenceFinder(*this);
}
FieldRemapper::FieldRemapper(DsqlCompilerScratch* aDsqlScratch, dsql_ctx* aContext, bool aWindow,
ValueListNode* aPartitionNode, ValueListNode* aOrderNode)
: dsqlScratch(aDsqlScratch),
context(aContext),
window(aWindow),
partitionNode(aPartitionNode),
orderNode(aOrderNode),
currentLevel(dsqlScratch->scopeLevel)
{
DEV_BLKCHK(dsqlScratch, dsql_type_req);
DEV_BLKCHK(context, dsql_type_ctx);
}
ExprNode* FieldRemapper::visit(ExprNode* node)
{
return node ? node->dsqlFieldRemapper(*this) : NULL;
}
bool SubSelectFinder::visit(ExprNode* node)
{
return node && node->dsqlSubSelectFinder(*this);
}
/**
PASS1_make_context
@brief Generate a context for a dsqlScratch.
@param dsqlScratch
@param relationNode
**/
dsql_ctx* PASS1_make_context(DsqlCompilerScratch* dsqlScratch, RecordSourceNode* relationNode)
{
DEV_BLKCHK(dsqlScratch, dsql_type_req);
thread_db* const tdbb = JRD_get_thread_data();
dsql_rel* relation = NULL;
dsql_prc* procedure = NULL;
// figure out whether this is a relation or a procedure
// and give an error if it is neither
MetaName relation_name;
ProcedureSourceNode* procNode = NULL;
RelationSourceNode* relNode = NULL;
SelectExprNode* selNode = NULL;
if ((procNode = relationNode->as<ProcedureSourceNode>()))
relation_name = procNode->dsqlName.identifier;
else if ((relNode = relationNode->as<RelationSourceNode>()))
relation_name = relNode->dsqlName;
else if ((selNode = relationNode->as<SelectExprNode>()))
relation_name = selNode->alias.c_str();
SelectExprNode* cte = NULL;
if (selNode)
{
// No processing needed here for derived tables.
}
else if (procNode && (procNode->dsqlName.package.hasData() || procNode->sourceList))
{
if (procNode->dsqlName.package.isEmpty())
procedure = dsqlScratch->getSubProcedure(procNode->dsqlName.identifier);
if (!procedure)
{
procedure = METD_get_procedure(dsqlScratch->getTransaction(), dsqlScratch,
procNode->dsqlName);
}
if (!procedure)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-204) <<
Arg::Gds(isc_dsql_procedure_err) <<
Arg::Gds(isc_random) <<
Arg::Str(procNode->dsqlName.toString()) <<
Arg::Gds(isc_dsql_line_col_error) << Arg::Num(relationNode->line) <<
Arg::Num(relationNode->column));
}
}
else if ((cte = dsqlScratch->findCTE(relation_name)))
relationNode = cte;
else
{
if (procNode && procNode->dsqlName.package.isEmpty())
procedure = dsqlScratch->getSubProcedure(procNode->dsqlName.identifier);
if (!procedure)
relation = METD_get_relation(dsqlScratch->getTransaction(), dsqlScratch, relation_name);
if (!relation && !procedure && procNode)
{
procedure = METD_get_procedure(dsqlScratch->getTransaction(),
dsqlScratch, procNode->dsqlName);
}
if (!relation && !procedure)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-204) <<
Arg::Gds(isc_dsql_relation_err) <<
Arg::Gds(isc_random) << Arg::Str(relation_name) <<
Arg::Gds(isc_dsql_line_col_error) << Arg::Num(relationNode->line) <<
Arg::Num(relationNode->column));
}
}
if (procedure && !procedure->prc_out_count)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-84) <<
Arg::Gds(isc_dsql_procedure_use_err) << Arg::Str(procedure->prc_name.toString()) <<
Arg::Gds(isc_dsql_line_col_error) << Arg::Num(relationNode->line) <<
Arg::Num(relationNode->column));
}
// Set up context block.
dsql_ctx* context = FB_NEW(*tdbb->getDefaultPool()) dsql_ctx(*tdbb->getDefaultPool());
context->ctx_relation = relation;
context->ctx_procedure = procedure;
if (selNode)
context->ctx_context = USHORT(MAX_UCHAR) + 1 + dsqlScratch->derivedContextNumber++;
else
context->ctx_context = dsqlScratch->contextNumber++;
context->ctx_scope_level = dsqlScratch->scopeLevel;
// When we're in a outer-join part mark context for it.
if (dsqlScratch->inOuterJoin)
context->ctx_flags |= CTX_outer_join;
context->ctx_in_outer_join = dsqlScratch->inOuterJoin;
// find the context alias name, if it exists.
string str;
if ((procNode = relationNode->as<ProcedureSourceNode>()))
str = procNode->alias;
else if ((relNode = relationNode->as<RelationSourceNode>()))
str = relNode->alias;
else if ((selNode = relationNode->as<SelectExprNode>()))
{
str = selNode->alias;
// ASF: In the case of a UNION contained in a CTE, selNode->querySpec will be a
// UnionSourceNode instead of a RseNode. Since ctx_rse is a RseNode and is always accessed
// as one, I'll leave this assignment here. It will be set in PASS1_derived_table anyway.
///context->ctx_rse = selNode->querySpec;
}
if (str.hasData())
context->ctx_internal_alias = str;
if (dsqlScratch->aliasRelationPrefix.hasData() && !selNode)
{
if (str.hasData())
str = pass1_alias_concat(dsqlScratch->aliasRelationPrefix, str);
else
str = pass1_alias_concat(dsqlScratch->aliasRelationPrefix, relation_name.c_str());
}
if (str.hasData())
{
context->ctx_alias = str;
// check to make sure the context is not already used at this same
// query level (if there are no subqueries, this checks that the
// alias is not used twice in the dsqlScratch).
for (DsqlContextStack::iterator stack(*dsqlScratch->context); stack.hasData(); ++stack)
{
const dsql_ctx* conflict = stack.object();
if (conflict->ctx_scope_level != context->ctx_scope_level)
continue;
const TEXT* conflict_name;
ISC_STATUS error_code;
if (conflict->ctx_alias.hasData())
{
conflict_name = conflict->ctx_alias.c_str();
error_code = isc_alias_conflict_err;
// alias %s conflicts with an alias in the same dsqlScratch.
}
else if (conflict->ctx_procedure)
{
conflict_name = conflict->ctx_procedure->prc_name.identifier.c_str();
error_code = isc_procedure_conflict_error;
// alias %s conflicts with a procedure in the same dsqlScratch.
}
else if (conflict->ctx_relation)
{
conflict_name = conflict->ctx_relation->rel_name.c_str();
error_code = isc_relation_conflict_err;
// alias %s conflicts with a relation in the same dsqlScratch.
}
else
continue;
if (context->ctx_alias == conflict_name)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-204) <<
Arg::Gds(error_code) << Arg::Str(conflict_name));
}
}
}
if (procedure)
{
USHORT count = 0;
if (procNode->sourceList)
{
context->ctx_proc_inputs = Node::doDsqlPass(dsqlScratch, procNode->sourceList, false);
count = context->ctx_proc_inputs->items.getCount();
}
if (count > procedure->prc_in_count ||
count < procedure->prc_in_count - procedure->prc_def_count)
{
ERRD_post(Arg::Gds(isc_prcmismat) << Arg::Str(procNode->dsqlName.toString()));
}
if (count)
{
// Initialize this stack variable, and make it look like a node
dsc desc_node;
ValueListNode* inputList = context->ctx_proc_inputs;
NestConst<ValueExprNode>* input = inputList->items.begin();
for (dsql_fld* field = procedure->prc_inputs;
input != inputList->items.end();
++input, field = field->fld_next)
{
DEV_BLKCHK(field, dsql_type_fld);
MAKE_desc_from_field(&desc_node, field);
PASS1_set_parameter_type(dsqlScratch, *input, &desc_node, false);
}
}
}
// push the context onto the dsqlScratch context stack
// for matching fields against
dsqlScratch->context->push(context);
return context;
}
// Compile a record selection expression, bumping up the statement scope level everytime an rse is
// seen. The scope level controls parsing of aliases.
RseNode* PASS1_rse(DsqlCompilerScratch* dsqlScratch, SelectExprNode* input, bool updateLock)
{
DEV_BLKCHK(dsqlScratch, dsql_type_req);
DEV_BLKCHK(input, dsql_type_nod);
dsqlScratch->scopeLevel++;
RseNode* node = pass1_rse(dsqlScratch, input, NULL, NULL, updateLock, 0);
dsqlScratch->scopeLevel--;
return node;
}
// Check for ambiguity in a field reference. The list with contexts where the field was found is
// checked and the necessary message is build from it.
void PASS1_ambiguity_check(DsqlCompilerScratch* dsqlScratch,
const MetaName& name, const DsqlContextStack& ambiguous_contexts)
{
// If there are no relations or only 1 there's no ambiguity, thus return.
if (ambiguous_contexts.getCount() < 2)
return;
TEXT buffer[1024];
USHORT loop = 0;
buffer[0] = 0;
TEXT* b = buffer;
TEXT* p = NULL;
for (DsqlContextStack::const_iterator stack(ambiguous_contexts); stack.hasData(); ++stack)
{
const dsql_ctx* context = stack.object();
const dsql_rel* relation = context->ctx_relation;
const dsql_prc* procedure = context->ctx_procedure;
if (strlen(b) > (sizeof(buffer) - 50))
{
// Buffer full
break;
}
// if this is the second loop add "and " before relation.
if (++loop > 2)
strcat(buffer, "and ");
// Process relation when present.
if (relation)
{
if (!(relation->rel_flags & REL_view))
strcat(buffer, "table ");
else
strcat(buffer, "view ");
strcat(buffer, relation->rel_name.c_str());
}
else if (procedure)
{
// Process procedure when present.
strcat(b, "procedure ");
strcat(b, procedure->prc_name.toString().c_str());
}
else
{
// When there's no relation and no procedure it's a derived table.
strcat(b, "derived table ");
if (context->ctx_alias.hasData())
strcat(b, context->ctx_alias.c_str());
}
strcat(buffer, " ");
if (!p)
p = b + strlen(b);
}
if (p)
*--p = 0;
if (dsqlScratch->clientDialect >= SQL_DIALECT_V6)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-204) <<
Arg::Gds(isc_dsql_ambiguous_field_name) << Arg::Str(buffer) << Arg::Str(++p) <<
Arg::Gds(isc_random) << name);
}
ERRD_post_warning(Arg::Warning(isc_sqlwarn) << Arg::Num(204) <<
Arg::Warning(isc_dsql_ambiguous_field_name) << Arg::Str(buffer) <<
Arg::Str(++p) <<
Arg::Warning(isc_random) << name);
}
/**
PASS1_check_unique_fields_names
check fields (params, variables, cursors etc) names against
sorted array
if success, add them into array
**/
void PASS1_check_unique_fields_names(StrArray& names, const CompoundStmtNode* fields)
{
if (!fields)
return;
const NestConst<StmtNode>* ptr = fields->statements.begin();
const NestConst<StmtNode>* const end = fields->statements.end();
for (; ptr != end; ++ptr)
{
const char* name = NULL;
const DeclareVariableNode* varNode;
const DeclareCursorNode* cursorNode;
if ((varNode = (*ptr)->as<DeclareVariableNode>()))
name = varNode->dsqlDef->name.c_str();
else if ((cursorNode = (*ptr)->as<DeclareCursorNode>()))
name = cursorNode->dsqlName.c_str();
else if ((*ptr)->as<DeclareSubProcNode>() || (*ptr)->as<DeclareSubFuncNode>())
continue;
fb_assert(name);
size_t pos;
if (!names.find(name, pos))
names.insert(pos, name);
else
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-637) <<
Arg::Gds(isc_dsql_duplicate_spec) << Arg::Str(name));
}
}
}
// Compose two booleans.
BoolExprNode* PASS1_compose(BoolExprNode* expr1, BoolExprNode* expr2, UCHAR blrOp)
{
thread_db* tdbb = JRD_get_thread_data();
fb_assert(blrOp == blr_and || blrOp == blr_or);
if (!expr1)
return expr2;
if (!expr2)
return expr1;
return FB_NEW(*tdbb->getDefaultPool()) BinaryBoolNode(
*tdbb->getDefaultPool(), blrOp, expr1, expr2);
}
// Report a field parsing recognition error.
void PASS1_field_unknown(const TEXT* qualifier_name, const TEXT* field_name,
const ExprNode* flawed_node)
{
TEXT field_buffer[MAX_SQL_IDENTIFIER_SIZE * 2];
if (qualifier_name)
{
sprintf(field_buffer, "%.*s.%.*s", (int) MAX_SQL_IDENTIFIER_LEN, qualifier_name,
(int) MAX_SQL_IDENTIFIER_LEN, field_name ? field_name : "*");
field_name = field_buffer;
}
if (flawed_node)
{
if (field_name)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-206) <<
Arg::Gds(isc_dsql_field_err) <<
Arg::Gds(isc_random) << Arg::Str(field_name) <<
Arg::Gds(isc_dsql_line_col_error) << Arg::Num(flawed_node->line) <<
Arg::Num(flawed_node->column));
}
else
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-206) <<
Arg::Gds(isc_dsql_field_err) <<
Arg::Gds(isc_dsql_line_col_error) << Arg::Num(flawed_node->line) <<
Arg::Num(flawed_node->column));
}
}
else
{
if (field_name)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-206) <<
Arg::Gds(isc_dsql_field_err) <<
Arg::Gds(isc_random) << Arg::Str(field_name) <<
Arg::Gds(isc_dsql_unknown_pos));
}
else
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-206) <<
Arg::Gds(isc_dsql_field_err) <<
Arg::Gds(isc_dsql_unknown_pos));
}
}
}
/**
PASS1_node_match
@brief Compare two nodes for equality of value.
[2002-08-04]--- Arno Brinkman
If ignoreMapCast is true and the node1 is
type nod_cast or nod_map then PASS1_node_match is
calling itselfs again with the node1
CASTs source or map->node.
This is for allow CAST to other datatypes
without complaining that it's an unknown
column reference. (Aggregate functions)
@param node1
@param node2
@param ignoreMapCast
**/
bool PASS1_node_match(const ExprNode* node1, const ExprNode* node2, bool ignoreMapCast)
{
DEV_BLKCHK(node1, dsql_type_nod);
DEV_BLKCHK(node2, dsql_type_nod);
if (!node1 && !node2)
return true;
if (!node1 || !node2)
return false;
const CastNode* castNode1 = node1->as<CastNode>();
if (ignoreMapCast && castNode1)
{
const CastNode* castNode2 = node2->as<CastNode>();
// If node2 is also cast and same type continue with both sources.
if (castNode2 &&
castNode1->castDesc.dsc_dtype == castNode2->castDesc.dsc_dtype &&
castNode1->castDesc.dsc_scale == castNode2->castDesc.dsc_scale &&
castNode1->castDesc.dsc_length == castNode2->castDesc.dsc_length &&
castNode1->castDesc.dsc_sub_type == castNode2->castDesc.dsc_sub_type)
{
return PASS1_node_match(castNode1->source, castNode2->source, ignoreMapCast);
}
return PASS1_node_match(castNode1->source, node2, ignoreMapCast);
}
const DsqlMapNode* mapNode1 = node1->as<DsqlMapNode>();
if (ignoreMapCast && mapNode1)
{
const DsqlMapNode* mapNode2 = node2->as<DsqlMapNode>();
if (mapNode2)
{
if (mapNode1->context != mapNode2->context)
return false;
return PASS1_node_match(mapNode1->map->map_node, mapNode2->map->map_node, ignoreMapCast);
}
return PASS1_node_match(mapNode1->map->map_node, node2, ignoreMapCast);
}
const DsqlAliasNode* aliasNode1 = node1->as<DsqlAliasNode>();
const DsqlAliasNode* aliasNode2 = node2->as<DsqlAliasNode>();
// We don't care about the alias itself but only about its field.
if (aliasNode1 || aliasNode2)
{
if (aliasNode1 && aliasNode2)
return PASS1_node_match(aliasNode1->value, aliasNode2->value, ignoreMapCast);
if (aliasNode1)
return PASS1_node_match(aliasNode1->value, node2, ignoreMapCast);
if (aliasNode2)
return PASS1_node_match(node1, aliasNode2->value, ignoreMapCast);
}
// Handle derived fields.
const DerivedFieldNode* derivedField1 = node1->as<DerivedFieldNode>();
const DerivedFieldNode* derivedField2 = node2->as<DerivedFieldNode>();
if (derivedField1 || derivedField2)
{
if (derivedField1 && derivedField2)
{
if (derivedField1->context->ctx_context != derivedField2->context->ctx_context ||
derivedField1->name != derivedField2->name)
{
return false;
}
return PASS1_node_match(derivedField1->value, derivedField2->value, ignoreMapCast);
}
if (derivedField1)
return PASS1_node_match(derivedField1->value, node2, ignoreMapCast);
if (derivedField2)
return PASS1_node_match(node1, derivedField2->value, ignoreMapCast);
}
return node1->type == node2->type && node1->dsqlMatch(node2, ignoreMapCast);
}
/**
PASS1_cursor_name
@brief Find a cursor.
@param dsqlScratch
@param name
@param mask
@param existence_flag
**/
DeclareCursorNode* PASS1_cursor_name(DsqlCompilerScratch* dsqlScratch, const MetaName& name,
USHORT mask, bool existence_flag)
{
DeclareCursorNode* cursor = NULL;
if (name.isEmpty())
{
if (existence_flag)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-504) <<
Arg::Gds(isc_dsql_cursor_err) <<
Arg::Gds(isc_dsql_cursor_invalid));
}
else
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-502) <<
Arg::Gds(isc_dsql_decl_err) <<
Arg::Gds(isc_dsql_cursor_invalid));
}
}
for (Array<DeclareCursorNode*>::iterator itr = dsqlScratch->cursors.begin();
itr != dsqlScratch->cursors.end();
++itr)
{
cursor = *itr;
if (cursor->dsqlName == name && (cursor->dsqlCursorType & mask))
break;
cursor = NULL;
}
if (!cursor && existence_flag)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-504) <<
Arg::Gds(isc_dsql_cursor_err) <<
Arg::Gds(isc_dsql_cursor_not_found) << name);
}
else if (cursor && !existence_flag)
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-502) <<
Arg::Gds(isc_dsql_decl_err) <<
Arg::Gds(isc_dsql_cursor_exists) << name);
}
return cursor;
}
// Extract relation and procedure context and expand derived child contexts.
static void pass1_expand_contexts(DsqlContextStack& contexts, dsql_ctx* context)
{
if (context->ctx_relation || context->ctx_procedure || context->ctx_map)
{
if (context->ctx_parent)
context = context->ctx_parent;
contexts.push(context);
}
else
{
for (DsqlContextStack::iterator i(context->ctx_childs_derived_table); i.hasData(); ++i)
pass1_expand_contexts(contexts, i.object());
}
}
// Process derived table which is part of a from clause.
RseNode* PASS1_derived_table(DsqlCompilerScratch* dsqlScratch, SelectExprNode* input,
const char* cte_alias)
{
DEV_BLKCHK(dsqlScratch, dsql_type_req);
thread_db* tdbb = JRD_get_thread_data();
MemoryPool& pool = *tdbb->getDefaultPool();
const string& alias = input->alias;
// Create the context now, because we need to know it for the tables inside.
dsql_ctx* const context = PASS1_make_context(dsqlScratch, input);
// Save some values to restore after rse process.
DsqlContextStack* const req_base = dsqlScratch->context;
const string aliasRelationPrefix = dsqlScratch->aliasRelationPrefix;
// Change context, because when we are processing the derived table rse
// it may not reference to other streams in the same scope_level.
DsqlContextStack temp;
// Put special contexts (NEW/OLD) also on the stack
for (DsqlContextStack::iterator stack(*dsqlScratch->context); stack.hasData(); ++stack)
{
dsql_ctx* local_context = stack.object();
if ((local_context->ctx_scope_level < dsqlScratch->scopeLevel) ||
(local_context->ctx_flags & CTX_system))
{
temp.push(local_context);
}
}
dsql_ctx* baseContext = NULL;
if (temp.hasData())
baseContext = temp.object();
dsqlScratch->context = &temp;
dsqlScratch->aliasRelationPrefix = pass1_alias_concat(aliasRelationPrefix, alias);
RecordSourceNode* query = input->querySpec;
UnionSourceNode* unionQuery = query->as<UnionSourceNode>();
RseNode* rse = NULL;
const bool isRecursive = unionQuery && unionQuery->recursive;
USHORT recursive_map_ctx = 0;
if (isRecursive)
{
// Create dummy, non-recursive select dsqlScratch by doing a union of
// one, non-recursive member. The dummy will be replaced at the end